Development Rules
BEST PRACTICES FOR GOOD PROGRAMMING
Tuesday, August 6, 2013
MicroSoft DotNet Help: Windows Phone Application Development Event Life C...
Windows Phone Application Development Event Life Cycle
Windows Phone Application Development Event Life Cycle
It is important for development to know Application life Cycle so that they can understand well
Easy to understand using below image:
Step 1:
Step 2:
I believe now you are understanding well, we can discuss briefly about application life cycle below
Event and States together make up for an application life cycle .In windows phone application life cycle events (4 type of event)
Windows Application life cycle Events:
1. Launching
2. Deactivated
3. Activated
4. Closing
Windows mobile have 3 type of application state
1. Running
2. Dormant
3. Tombstoned
Events lead to change the application state
1. Launch Event:
1. This event is raised when user launch the application
รจ Mostly avoid this event for Application will get load quickly
Application Launching Event coding:( App.xaml.cs)
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
1.1Running State:
1. Once the application is launched its goes into Running state
When Running State will appear?
1. This state is on till the user doesn't navigate away from application
2. The Phone is in Lock mode
2. Deactivated Event:
The user goes away from your application this event is raised
In this application context and page should be saved
When this application reactivated, that time save state should be restore
Coding( App.xaml.cs)
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}
2.1 Dormant State:
- Deactivated event goes into dormant state
- In Dormant State the application is stopped ,but application in phone memory
- Again application activate state that time phone need more memory,
(While activate application, that time state convert into Tombstoned state)
2.2 Tombstoned State:
-Once an application is terminated its goes into tombstoned state
-In this state the data and application state information preserved for maximum 5 application
Activated Event
When user switch back to a dormant or tombstoned application, this event is fired.
Developer should check the IsApplicationInstancePreserved property to know if the application is returning from being dormant or tombstoned state.
If it's value true, then the application was in dormant state else tombstoned state.
Coding: App.xaml.cs
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
if (e.IsApplicationInstancePreserved == true)
{
//Dormant state
}
else
{
//tombstoned state
}
}
Close Event
When the user navigates backwards from the first page of application, this event is fired.
Application gets terminated in this event and you get only 10 seconds to save any data if required.
For your Info : User does not have API for close application
Coding: App.xaml.cs
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
}
Thursday, February 24, 2011
NAMING CONVENTIONS AND STANDARDS
NAMING CONVENTIONS AND STANDARDS
Naming Conventions
Consistency is the key to maintainable code. This statement is most true for naming your projects, source files, and identifiers including Fields, Variables, Properties, Methods, Parameters, Classes, Interfaces, and Namespaces.
General Guidelines
- Always use Camel Case or Pascal Case names.
- Avoid ALL CAPS and all lowercase names. Single lowercase words or letters are acceptable.
- Do not create declarations of the same type (namespace, class, method, property, field, or parameter) and access modifier (protected, public, private, internal) that vary only by capitalization.
- Do not use names that begin with a numeric character.
- Do add numeric suffixes to identifier names.
- Always choose meaningful and specific names.
- Always err on the side of verbosity not terseness.
- Variables and Properties should describe an entity not the type or size.
- Do not use Hungarian Notation!
Example: strName or iCount
- Avoid using abbreviations unless the full name is excessive.
- Avoid abbreviations longer than 5 characters.
- Any Abbreviations must be widely known and accepted.
- Use uppercase for two-letter abbreviations, and Pascal Case for longer abbreviations.
- Do not use C# reserved words as names.
- Avoid naming conflicts with existing .NET Framework namespaces, or types.
- Avoid adding redundant or meaningless prefixes and suffixes to identifiers
Example:
// Bad!
public enum ColorsEnum {…} public class CVehicle {…}
public struct RectangleStruct {…}
- Do not include the parent class name within a property name.
Example: Customer.Name NOT Customer.CustomerName
- Try to prefix Boolean variables and properties with "Can", " Is" or " Has".
- Append computational qualifiers to variable names like Average, Count, Sum, Min, and Max where appropriate.
- When defining a root namespace, use a Product, Company, or Developer Name as the root.
Example:
LanceHunt.StringUtilities
NAME USAGE & SYNTAX
1. Identifier: Project File
Naming Convention: Pascal Case. Always match Assembly Name & Root Namespace.
Example: LanceHunt.Web.csproj -> LanceHunt.Web.dll ->
namespace LanceHunt.Web
2. Identifier: Source File
Naming Convention: Pascal Case. Always match Class name and file name. Avoid including more than one Class, Enum (global), or Delegate (global) per file. Use a descriptive file name when containing multiple Class, Enum, or Delegates.
Example: MyClass.cs=> public class MyClass{…}
3. Identifier: Resource or Embedded File
Naming Convention: Try to use Pascal Case. Use a name describing the file contents.
4. Identifier: Namespace
Naming Convention: Pascal Case. Try to partially match Project/Assembly Name.
Example: namespace LanceHunt.Web {…}
5. Identifier: Class or Struct
Naming Convention: Pascal Case. Use a noun or noun phrase for class name. Add an appropriate class-suffix when sub-classing another type when possible.
Examples:
private class MyClass {…}
internal class SpecializedAttribute : Attribute {…}
public class CustomerCollection : CollectionBase {…}
public class CustomEventArgs : EventArgs {…}
private struct ApplicationSettings {…}
6. Identifier: Interface
Naming Convention: Pascal Case. Always prefix interface name with capital "I".
Example: interface ICustomer{…}
7. Identifier: Generic Class & Generic Parameter Type [C#v2+]
Naming Convention:Always use a single capital letter, such as T or K.
Example:
public class FifoStack<T>
{
public void Push(<T> obj) {…}
public <T> Pop(){…}
}
8. Identifier: Method
Naming Convention: Pascal Case. Try to use a Verb or Verb-Object pair.
Example: public void Execute(){…}private string GetAssemblyVersion(Assembly target) {…}
9. Identifier: Property
Naming Convention
Pascal Case. Property name should represent the entity it returns. Never prefix property names with
"Get" or " Set".
Example:
public string Name
{
get{…} set{…} }
10. Identifier: Field(Public, Protected, or Internal)
Naming Convention: Pascal Case. Avoid using non-private Fields! Use Properties instead.
Example: public string Name;
protected IList InnerList;
11. Identifier: Field (Private)
Naming Convention: Camel Case and prefix with a single underscore (_) character.
Example: private string _name;
12. Identifier: Constant or Static Field
Naming Convention: Treat like a Field. Choose appropriate Field access-modifier above.
13. Identifier: Enum
Naming Convention:Pascal Case (both the Type and the Options). Add the FlagsAttribute to bit-mask multiple options.
Example:
public enum CustomerTypes
{ Consumer, Commercial}
14. Identifier: Delegate or Event
Naming Convention: Treat as a Field. Choose appropriate Field access-modifier above.
Example: public event EventHandler LoadPlugin;
15. Identifier: Variable (inline)
Naming Convention: Camel Case. Avoid enumerating variable names like text1, text2, text3 etc.
16. Identifier: Parameter
Naming Convention: Camel Case.
Example: public void Execute(string commandText, int iterations) {…}
Note : The terms Pascal Casing and Camel Casing are used throughout this Book. Pascal Casing - First character of all words are Upper Case and other characters are lower case. Example: BackColor Camel Casing - First character of all words, except the first word are Upper Case and other characters are lower case. Example: backColor |
1.Use Pascal casing for Class names
public class HelloWorld
{
...
}
2. Use Pascal casing for Method names
void SayHello(string name)
{
...
}
3. Use Camel casing for variables and method parameters
int totalCount = 0;
void SayHello(string name)
{
string fullMessage = "Hello " + name;
...
}
4. Use the prefix "I" with Camel Casing for interfaces ( Example: IEntity )
5. Do not use Hungarian notation to name variables.
In earlier days most of the programmers liked it - having the data type as a prefix for the variable name and using m_ as prefix for member variables. Eg:
string m_sName;
int nAge;
However, in .NET coding standards, this is not recommended. Usage of data type and m_ to represent member variables should not be used. All variables should use camel casing.
Some programmers still prefer to use the prefix m_ to represent member variables, since there is no other easy way to identify a member variable. |
6. Use Meaningful, descriptive words to name variables. Do not use abbreviations.
Good:
string address
int salary
Not Good:
string nam
string addr
int sal
7. Do not use single character variable names like i, n, s etc. Use names like index, temp
One exception in this case would be variables used for iterations in loops:
for ( int i = 0; i < count; i++ )
{
...
}
If the variable is used only as a counter for iteration and is not used anywhere else in the loop, many people still like to use a single char variable (i) instead of inventing a different suitable name.
8. Do not use underscores (_) for local variable names.
9. All member variables must be prefixed with underscore (_) so that they can be identified from other local variables.
10. Do not use variable names that resemble keywords.
11. Prefix boolean variables, properties and methods with "is" or similar prefixes.
Ex: private bool _isFinished
12. Namespace names should follow the standard pattern
<company name>.<product name>.<top level module>.<bottom level module>
13. Use appropriate prefix for the UI elements so that you can identify them from the rest of the variables.
There are 2 different approaches recommended here.
1. Use a common prefix ( ui_ ) for all UI elements. This will help you group all of the UI elements together and easy to access all of them from the intellisense.
2. Use appropriate prefix for each of the ui element. A brief list is given below. Since .NET has given several controls, you may have to arrive at a complete list of standard prefixes for each of the controls (including third party controls) you are using.
Control | Prefix |
Label | Lbl |
TextBox | Txt |
DataGrid | Dtg |
Button | Btn |
ImageButton | imb |
Hyperlink | Hlk |
DropDownList | ddl |
ListBox | lst |
DataList | Dtl |
Repeater | rep |
Checkbox | Chk |
CheckBoxList | cbl |
RadioButton | rdo |
RadioButtonList | rbl |
Image | Img |
Panel | pnl |
PlaceHolder | phd |
Table | tbl |
Validators | val |
14. File name should match with class name.
For example, for the class HelloWorld, the file name should be helloworld.cs (or, helloworld.vb)
15. Use Pascal Case for file names.
1. Use TAB for indentation. Do not use SPACES. Define the Tab size as 4.
2. Comments should be in the same level as the code (use the same level of indentation).
Good:
// Format a message and display
string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
MessageBox.Show ( message );
Not Good:
// Format a message and display
string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
MessageBox.Show ( message );
3. Curly braces ({}) should be in the same level as the code outside the braces.
4. Use one blank line to separate logical groups of code.
Good:
bool SayHello ( string name )
{
string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
MessageBox.Show ( message );
if ( ... )
{
// Do something // ...
return false;
}
return true;
}
Not Good:
bool SayHello (string name)
{
string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
MessageBox.Show ( message );
if ( ... )
{
// Do something // ...
return false;
}
return true;
}
5. There should be one and only one single blank line between each method inside the class.
6. The curly braces should be on a separate line and not in the same line as if, for etc.
Good:
if ( ... )
{
// Do something
}
Not Good:
if ( ... ) {
// Do something }
7. Use a single space before and after each operator and brackets.
Good: if ( showResult == true )
{
for ( int i = 0; i < 10; i++ )
{ // }
}
Not Good:
if(showResult==true)
{
for(int i= 0;i<10;i++)
{
//
}
}
8. Use #region to group related pieces of code together. If you use proper grouping using #region, the page should like this when all definitions are collapsed.
9. Keep private member variables, properties and methods in the top of the file and public members in the bottom.
THE FOLLOWING TABLE SUMMARIZES THE CAPITALIZATION RULES AND PROVIDES EXAMPLES FOR THE DIFFERENT TYPES OF IDENTIFIERS:
IDENTIFIER |
CASE |
EXAMPLE |
Class | Pascal | AppDomain |
Enum type | Pascal | ErrorLevel |
Enum values | Pascal | FatalError |
Event | Pascal | ValueChange |
Exception class | Pascal | WebException Note Always ends with the suffix Exception. |
Read-only Static field | Pascal | RedValue |
Interface | Pascal | IDisposable Note Always begins with the prefix I. |
Method | Pascal | ToString |
Namespace | Pascal | System.Drawing |
Parameter | Camel | typeName |
Property | Pascal | BackColor
|
Protected instance field | Camel | redValue Note Rarely used. A property is preferable to using a protected instance field. |
Public instance field | Pascal | RedValue Note Rarely used. A property is preferable to using a public instance field. |