. NET Development Specification

Source: Internet
Author: User
Tags md5 encryption message queue modifiers

First, naming rules

1.1 Naming Law description

(1) Pascal nomenclature: Capitalize the first letter of the identifier and the first letter of each word that is connected behind it.

Example: BackColor

(2) Camel nomenclature: The first letter of the identifier is lowercase, and the first letter of each subsequent concatenated word is capitalized.

Example: BackColor

(3) The names of variables, class names, member variables, methods, etc., are forbidden: English and pinyin combination, pinyin naming, non-standard English shorthand naming, Chinese character naming (except for special cases, such as partial enumeration using Chinese characters);

Description: The name definition is not afraid of long, strive for accuracy, and readability friendly;

Counter example: decimal jiage = 0m;//Price

1.2 Common naming conventions

(1) C # method parameters, internal variables named: Camel should be named, that is, the first letter lowercase;

Positive example: int userId = 0;

(2) C # class member properties: The Pascal name should be used, that is, the first letter capitalized;

Positive example: public int UserId {get; set;}

(3) C # enumeration (enum) naming: The Pascal name should be used, that is, the first letter capitalized;

Description: Should be a noun singular form of English words, should not increase the enum prefix or suffix, according to the actual business definition can be;

Positive example: usertype

Inverse example: usertypeenum| Usertypes

(4) C # Interface (interface) naming: The Pascal name should be used, that is, the first letter capitalized;

Note: Should be unified to start with the letter I, the implementation of the class is to remove the corresponding I letter;

(5) C # entity object (Model) naming: Using Pascal nomenclature, that is, the first letter capitalized;

Description

The database table entity should be named Modelinfo,model as the database table name;

The data Model (Datamodel) should be defined as dmodelinfo,d prefix, info as suffix, model for related business name;

The view model (ViewModel) should be defined as vmodelinfo,v prefix, info as suffix, model as page or related business name;

Positive example: tuserinfo| duserloginfo| Vuserlistinfo

(6) C # Data Layer (DAL) class naming: The Pascal name should be used, that is, the first letter capitalized;

Note: The Dal suffix should be used uniformly, Modeldal,model is the entity name (minus the info suffix);

Positive example: Tuserdal

(7) C # persistence layer (persistence,ibatisnet) naming: The map file name is generally consistent with the namespace in the file, and the database entity table name consistent, the method name and the DAL layer call method is consistent, easy to read;

(8) C # Business Layer (BLL) class naming: The Pascal nomenclature should be used, that is, the first letter capitalized;

Note: The BLL suffix should be used uniformly, Modelbll,model is the entity name (remove the info suffix);

Positive example: tuserbll| Duserlogbll

(9) Naming rules for object type members: rules that satisfy the attributes of members in a class;

Note: The entity name after the prefix and suffix should be removed from the full class name as the attribute name;

Positive example: public statictuserinfo TUser {get; set;}

Counter example: public Statictuserinfo tuserinfo{get; set;}

(10) Constant naming specification: All letters capitalized, each word is divided by an underscore;

Positive example:///<summary> Channel ID (value:175) </summary>

Private Const int channel_id= 175;

(one) JS variable and method name rule: All should use the Camel name method, the first letter lowercase;

(12) The names of database objects and fields should be named by Pascal as far as possible, that is, the first letter capitalized;

Description: The naming of common database objects, in addition to naming conventions, should be used to differentiate the types of objects by using prefixes.

Example: Table: tuser| view: vuserlevel| Custom Function: GetMaxID () | stored procedure: procsetuserstate

WCF references the service naming specification, which is recommended to add the Wcfservice prefix to the referenced namespace;

1.3 code file naming

(1) file names follow the Pascal Nomenclature, no special case, extension lowercase;

(2) Use a unified and universal file extension: C # class. cs;

Positive example: TUserInfo.cs

Second, the code formatting the appearance of 2.1 Code column display

In order to facilitate reading, single-line code should be as far as possible to control in one screen, otherwise you should adjust the line display according to the actual situation:

(1) After the code or the expression of the comma after the line;

(2) Wrap the line before the operator of the code or expression;

(3) The above situation, can be discretionary, as far as possible to ensure convenient reading can;

2.2 code file layout

(1) Visual Studio can use the default shortcut key Ctrl +k,ctrl +d format cs file or cshtml and other file code, before committing the code should be formatted;

(2) Too long code block, according to business logic, using the external code #region ... #endregion将代码分块折叠;

Positive example:

#region test methods

#endregion End test method

Third, the program code annotation specification 3.1 In-line comments

(1) When modifying a single line of code for any reason, it should be commented to explain the reason, time and author of the modification, and if relevant requirements or bugs should be marked with the requirement or bug number;

(2) If necessary, add a note to the top of the document in the following format, and add a detailed description of the change record after each important change;

3.2 Document-type annotations

(1) All classes, methods, member properties, enumerations, etc. for external invocation should be added this type of comment (summary), the caller can directly through the ToolTip to consult the relevant instructions, no need to go into the definition of reading code and comments;

(2) Document comments generally on the purpose of the annotated object, usage, parameter list and return value, etc. to make a detailed description, convenient for callers to consult;

(3) The general JS method of the package can also use the document annotation specification, the syntax should be based on JS annotation specification;

Note: In Visual Studio, JS's document annotations also have the effect of ToolTips; Add summary comments to the JS method in the VS editor Quick steps: Right-click in the first line of the method, select "Insert Snippet"-select "Xmlcomments" You can then add param or summary nodes;

four, commonly used. NET Programming Specification 4.1 Classes and the use of member modifiers within a class

(1) Class and class members notice the modifier, do not misuse the public keyword, according to the actual situation of the definition;

(2) Permanent memory constants, it is recommended to use the const modification;

Positive example:

<summary> Channel ID (value:175) </summary>

Private Const int channel_id = 175;

(3) The implementation of a singleton mode, in addition to using static modification, should consider whether the need for volatile modification;

(4) Partial (partial) use: when there are too many blocks of code within a class, or if the business module is too complex, consider splitting the class into multiple files, and the naming of the file should consider indicating the name of the business module under the current class.

Example: When TUSERBLL used partial decoration, split into login-related, background management related 2 partial class files, should be named: tuserbll.login.cs| TUserBLL.Management.cs

(5) Description of common modifiers:

Public, class and member access modifiers, no access restrictions;

Internal internal, class, and member access modifiers, limited to access within the Assembly;

Protected protected, member access modifier, restricted to class or derived class access;

protected internal protected or internal, member access modifier, limited to: accessible within an assembly, derived classes within other assemblies are accessible;

Private, member access modifier, restricted to intra-class access;

Description: Any class, method, parameter, variable, strict access scope, too broad scope of access, not conducive to module decoupling;

(6) Other C # keyword usage specifications and instructions, referring to Microsoft official documentation:

C # Keywords | Microsoft Docs

Https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/index

4.2 Use of loop code blocks

(1) Circulation body must master the cycle times, especially user-level applications, to avoid timeouts;

(2) The loop body does not allow the direct declaration of any type of variable (including value types, objects and collection types);

Note: Variables should be defined outside the loop body, assigned within the loop, and other methods of the loop body invocation should also consider the case of the internal variable Declaration;

(3) JS loop body should also consider the performance problem;

4.3 Use of the entity model

(1) in the entity model of the database, the added non-database field attribute should be marked "[Virtual field]" in the document type comment, which is convenient for callers to check;

(2) Try to avoid the use of anonymous classes (including but not limited to action Jsonresult);

Description: You can use the model, ViewModel, Datamodel and other common objects of the data table as the returned value object of the serialization;

(3) An enumeration type field in an entity, not defined as an int with other value types, is recommended to define the enumeration type directly;

Positive example: public static usertype Type {get; set;}

(4) When the value of a configuration parameter is JSON or a field in a table, you should also consider defining a separate data model for each application.

4.4 Reasonable assignment of variables

(1) string concatenation try to avoid the use of "+" or "+ =", a small number of splicing or formatting using string. The Format () method, looping or a large number of stitching must use the StringBuilder object;

Description: StringBuilder in the format of information, you can directly use the AppendFormat method;

(2) The assignment of a constant number, the case of a non-int value, shall be identified by the type letter at the end of the value, reducing the implicit type conversion;

Positive example:

Decimal decvalue = 108.21m;//m denotes decimal type numeric declaration

float Fltvalue = 108.21f;//f denotes float type numeric declaration

Long Lgvalue = 108l;//l denotes long type numeric declaration

(3) The use of Hashtable, in accordance with different business conditions to add different keys, it is recommended to use the key index form assignment, do not use the Add () method;

Description

An exception is thrown when a duplicate Key,add method is added because of business judgment;

Assigning a value directly using the key index will overwrite the duplicate key and value;

Positive example:

int userid=1;

Hashtable param =new Hashtable ();

param["UserId"] =userid;

4.5 use of collections (IList and list)

(1) Minimize the ToList () method invocation of the IList object (especially when the collection element is large);

(2) Data collection from the data source (cache or database) should not be taken out too much data at a time, user-level application is recommended to get no more than 100 elements at a time, Windows services can be increased in moderation but not recommended more than 1000, business needs, should consider paging processing;

specification for 4.6 MVC and razor View Syntax

(1) All Controller and action should take into account the filter and user login status, permission limits;

(2) business code as far back as possible, the main purpose of the view is to display and return data, as far as possible do not appear business code modules; The controller is responsible for interacting with the business layer data, complex business processing as far as possible to the business layer (BLL);

(3) View data display, as far as possible to convert viewbag and other data into a strong type of entities, easy to develop and read; Dynamic types such as dynamics, unable to identify and display the specific properties under the entity and the ToolTip for document-type annotations;

(4) A common view should be encapsulated as a generic component by some pages or other means;

Positive example: the user submits the order, the user address management and so on many places will use the provincial and municipal administrative divisions linkage Choice code block, should encapsulate an administrative division's drop box linkage component;

(5) Some JS code in the view, or the control of the dynamic loading of HTML code, should try to use razor to implement, discard the control mode of using JS, reduce the amount of page rendering code;

(6) It is not recommended to stitch HTML content on the output view of HTML string within action, which is less maintainable and extensible;

v. Persistence layer (based on ibatisnet) and database specification

(1) All database access must be performed at the data layer (DAL), which prohibits access to the database at other levels;

(2) All scripts can only exist in the map file of the stored procedure and persistence layer, and it is forbidden to appear on the Dal or other layer;

(3) In order to facilitate reading, please try to standardize the script to write:

SQL Server keyword all uppercase;

database objects, such as table name, field name, view, custom function, and so on, are written in the same case as the definition;

(4) All queries prohibit the "SELECT * from" notation, even if all fields need to be listed separately, if the database field appears inconsistent with model, "SELECT * from" causes an ORM map to throw an exception;

Description: Minimize the number of fields in the query, especially the fields of large text data, do not query back when necessary;

(5) query as far as possible using lock-free query with (NOLOCK);

Description: Strong real-time (such as account balance, or immediately after the update query, etc.) should consider abandoning the use of lock-free query;

(6) The SQL script of the map file can be dynamically assembled according to the actual parameters, and has the effect of caching, but it is not recommended to share the same map method with a script that is not strong in business correlation;

Note: If a query script is written with complex queries, join cascading queries, etc., such scripts can only be used for method calls that do require joins or complex queries, and if the caller does not require complex queries, a new query scripting method should be created;

A positive example: a script that already exists uses a LEFT join to concatenate multiple tables, and when the caller does not need to correlate the tables, consider choosing a different map method or a new creation method that cannot be shared.

(7) Count (1) or count (Id) is recommended when Count counts, it is not recommended to use COUNT (*) directly;

(8) It is recommended to use syntax exists to determine if a record satisfies the specified condition through SQL script;

Description: Use the keyword exists and if combination, by judging the return value is 1 or the limit of the determination of the data to be queried for existence;

In the wording should also use exists substitution;

Positive example:

IF (EXISTS (SELECT 1 from dbo. TUser with (NOLOCK) WHERE UserId = 1))

SELECT 1

ELSE SELECT 0

Counter-Example: Prohibit direct use of the following wording:

SELECT * FROM dbo. TUser WHERE UserId = 1

SELECT TOP 1 * FROM dbo. TUser WHERE UserId =1

SELECT COUNT (1) from dbo. TUser WHERE UserId = 1

(9) Using the Ibatisnet Update method, do not easily update all the fields of the entire model, wasting resources, and may cause bugs; Try to update only the modified fields;

Description: As far as possible only the fields that need to be modified, if necessary, can be defined as Hashtable dictionary type parameters;

(+) from SQL SERVER 2012, we recommend that you use the new paging method (OFFSET ... FETCH);

Description: From the execution plan point of view, fetch syntax, than row_number () paging performance is much better, the syntax is as follows,

OFFSET {integer_constant | offset_row_count_expression} {ROW | ROWS}

FETCH {First | NEXT} {integer_constant |fetch_row_count_expression} {row | ROWS} only

(11) Delete data using Delete, it must be considered carefully;

Description: Data priceless, carefully deleted! If necessary, consider using a tombstone (identified by the field as the deletion state);

(12) The use of transactions: if you need to use transactions, make sure that the transaction has an end point, the transaction is responsible for the data update operation, should not put unnecessary queries into the transaction;

Note: You must ensure that all paths have commit or rollback, the use of transactions, you must use the Try...catch module to catch the exception, and in the case of an exception rollback;

(13) All database scripts prohibit cross-library access;

Description: All T-SQL statements, do not add database name prefixes as direct cross-library access, such as the exact need to cross-library, should use linked server (linkedserver) mode, or consider other solutions;

(14) Complex data processing business, should consider creating stored procedures;

(15) Production environment is generally not recommended to manually modify the data, if necessary, please be careful to check the correctness of the script and send the script and related requirements to the DBA to execute

vi. Distributed Cache Usage Specification

(1) It is recommended to use Redis or memcached cache;

(2) The cache is only allowed to be referenced directly in the BLL (business layer) and not directly in other layers;

(3) All the use of the cache, to ensure that the cache data refresh timely, otherwise it will cause inconsistent data of the bug;

(4) The key name of the cache must be defined according to the established rules; It is recommended to define the key node using a tree structure;

(5) Before using the cache to read data, it is important to ensure that the correct cache key is configured, otherwise the read data will fail;

(6) The data model cannot be replaced privately with the data in the configured cache, which causes other applications to resolve to the correct data, and an unhandled exception occurs;

(7) When the data is updated, when it involves displaying the data and judging the data, it is not necessary to take the cached data directly as the pre-modified presentation data to prevent overwriting the old data to the database;

(8) Reasonable use of the cache: relatively static data, high frequency of access to data should be used as appropriate to read the cache, reduce the database access pressure, and should be based on the actual cache hit rate situation to consider setting the length of the cache;

(9) Use of Redis Message Queuing: The data inserted into the message queue should be accurate and concise; the queue is read and manipulated by the service, has a certain time delay, and the result of operation is not feedback to the application, so the actual application scenario should be considered.

vii. WCF and WEBAPI usage specifications 7.1 Encapsulation of WCF and WEBAPI principles

(1) General business methods, modules should be considered encapsulated as WCF or WEBAPI;

7.2 Configuration and references for WCF

(1) The production environment WCF, should adopt the TCP protocol deployment and the reference (must have the external network reference of WCF except);

(2) The WCF deployment domain name of the test environment, it is recommended to use the same settings as the production environment (can be accessed through the hosts), to ensure the consistency of debugging and production environment;

(3) Prohibit the introduction and return of ultra-large amounts of data via WCF;

(4) A reference to WCF should be added to the BLL (business layer) and not referenced to other layers;

Description: Although WCF references to the BLL layer, the configuration node should be manually added to the Web. config or app. config for each application;

7.3 Development specifications for WCF and Webapi

(1) Incoming parameters and return values, as far as possible in JSON format, and use the data model to define, avoid directly using value types or object types;

Description: The value type and the object type parameter extensibility is not good, such as encountered the increment return value field or the parameter fields, does not favor the extension;

(2) If the returned data is a collection, and the volume is too large, you should consider using paging to return the data, each page of data suggestions not more than 100;

(3) The open WCF interface or WEBAPI must consider the security control;

Description: The security can be controlled by the signature verification method of the private key and time stamp, the signature can be realized by MD5 encryption algorithm, and the special interface can not increase the signature verification without increasing the limit; the development ability should realize the perfect OAuth2.0 authorization mechanism;

(4) Call the method of WCF, after use, must explicitly call the WCF Close method directly;

Note: Opening a WCF connection consumes a lot of server resources, be sure to shut down in a timely manner, and do not cycle through multiple connections;

(5) WCF service layer, WEBAPI action layer to minimize the coupling of business code, the business logic is placed behind the BLL business layer;

(6) Common WCF or WEBAPI interface, proposed to form a development manual (development specification document);

viii. Visual Studio Solutions use

(1) All solutions must not be introduced into the front-end components, service-side components, not to change the existing components or framework;

(2) The General Tools layer shall not introduce third party components without permission, or change, delete or add a common method;

(3) All resource files (CSS files, JS files, image files) shall not be modified without permission, and the documents provided by the UI must prevail;

(4) Debugging the solution, if you set up local IIS debugging or other special vs settings, do not submit the configuration to SVN (or other source control tools), recommend setting to the user file, and add the user file to the SVN ignore list, because other developers certainly do not have a consistent IIS site, can cause debugging exceptions;

(5) Do not upgrade any project under any of the solutions without authorization. NETFramework version;

(6) The version of all third-party components and DLL files introduced may not be upgraded without authorization;

(7) The third-party DLL files introduced under all the projects should be placed under the specified folder of the corresponding solution and classified and submitted to SVN, preventing other developers from obtaining the introduced files, resulting in compilation failure;

(8) The development of complex projects, it is recommended to draw the corresponding business flow chart, more rigorous process path, more clear development ideas, maintenance more convenient;

(9) In the project development process, it is recommended to record the list of files that need to be released at the time of publication to prevent omission;

. NET Development Specification

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.