Tuesday, April 24, 2012

Code matrix in VS 2008


Code metrics is a tool which can show the developer how good is the code. Using set of measurements it will be easier to know how complex the coding is. By taking advantage of code metrics, developers can understand which types and/or methods should be reworked or more thoroughly tested. Development teams can identify potential risks, understand the current state of a project, and track progress during software development.

Below list shows the code metrics results that VS calculates:

Maintainability Index
Maintainability Index, which goes from 0 to 100 and indicates the overall maintainability of a class, member, namespace or project. If the value is higher than it show the code is better maintained. It also comes up with color code for quicker view.

Green - 20 and 100 (good).
Yellow - 10 and 19 (moderate)
Red - 0 and 9 (low)

Cyclomatic Complexity
Cyclomatic Complexity tells you two important things. First, it indicates the general complexity of a method. Lower is better; if the number is high, the method is probably trying to cover too many different situations and needs to be broken up into simpler, specialized methods that cater specifically to individual situations and are much easier to maintain. Second Cyclomatic Complexity tells you the total number of test cases you need to write, to ensure that all possible situations have been covered. So if the value is higher than you have to test the code with more test cases.

Depth of Inheritance
Lower is better; if Depth of Inheritance goes higher than three or four, your code will be difficult to maintain. The higher the number, the more subclasses you will have to modify and it might introduce new bugs when you do changes in base class.

Class Coupling
Lower is better; the higher the number, the more "tied-down" a class is, with more dependencies on the rest of its immediate environment and it will be difficult to reuse.

Lines of Code
Lines of Code (LOC) measure the size of a piece of software by counting the total number of executable lines of code in it. Lower is better. If you have higher value then you can go down to the function and try to break as much as possible. It will be easier to maintain and debug.

Best Practices in framework 2.0


Best Practices in framework 2.0

1)    The runtime optimizes the performance of 32-bit integer types (Int32 and UInt32), so use those types for counters and other frequently accessed integral variables.
2)    For floating-point operations, Double is the most efficient type because those operations are optimized by hardware.
3)    Garbage collection occurs only when needed or when triggered by a call to GC.Collect. Automatic garbage collection is optimized for applications where most instances are short-lived, except for those allocated at the beginning of the application. Following that design pattern will result in the best performance.
string s;
s = "wombat"; // "wombat"
s += " kangaroo"; // "wombat kangaroo"
s += " wallaby"; // "wombat kangaroo wallaby"
s += " koala"; // "wombat kangaroo wallaby koala"
Console.WriteLine(s);
Only the last string has a reference; the other three will be disposed of during garbage collection. Avoiding these types of temporary strings helps avoid unnecessary garbage collection, which improves performance. There are several ways to avoid temporary strings:

BEST PRACTICES Boxing and unboxing
Boxing and unboxing incur overhead, so you should avoid them when programming intensely repetitive tasks. Boxing also occurs when you call virtual methods that a structure inherits from System.Object, such as ToString.
Follow these tips to avoid unnecessary boxing:
4)    Implement type-specific versions (overloads) for procedures that accept various value types. It is better practice to create several overloaded procedures than one that accepts an Object argument.
5)    Use generics whenever possible instead of accepting Object arguments.
6)    Override the ToString, Equals, and GetHash virtual members when defining structures.

Regular Expression
7)    When validating input, always begin regular expressions with a “^” character and end them with “$”. This system ensures that input exactly matches the specified regular expression and does not merely contain matching input.

Wednesday, April 18, 2012

Performance tips for ASP.net

Performance Tips

1) Always use StringBuilder if you want to Concatenation two strings in a loop. Because if you Concatenation using the string object then both string object will be saved to memory first and then old string will be deleted and values will be read from new string object. It’s time consuming and hit the performance too.

2) Avoid Server Trip- It’s always smart to avoid unnecessary server trip. Some of the methods to avoid server side trips are 1) Do client side validation 2) Implement Ajax control for web application so only partial page will be loaded and not the full page.3) use Page.ISPostBack -Use Page.ISPostBack property to ensure that you only perform page initialization logic when a page is loaded the first time and not in response to client post backs.

3) Save View state- Save the view state only when it is must otherwise skip it. When we can avoid to having view state true. 1) Your page does not post back. It just show the data and there is no need to reload it again. 2) you do not handle server control events in your page. 3) If you ignore old data, and if you repopulate the server control each time the page is refreshed

4) Use of Session Variables- When storing the data in session variable make sure you use efficiently. Even though you close the browser but the session variable remain on server for a long time.

5) Use Server.Transfer – whenever you need to redirect to an page within the website you use Server.Transfer and not Response.Redirect. If you need authentication and authorization checks during redirection, use Response.Redirect instead of Server.Transfer

6) Choose the data viewing control- DataGrid control can be a quick and easy way to display data, but it is frequently the most expensive in terms of performance. Rendering the data yourself by generating the appropriate HTML may work in some simple cases, but customization and browser targeting can quickly offset the extra work involved. A Repeater Web server control is a compromise between convenience and performance. It is efficient, customizable, and programmable.

7) Optimize code and Exception handling- Use for loop instead of for each loop. It’s better to write a code which check the condition and make sure you don’t have exception in your programme flow. Because handling the exception and writing it on server will hit the performance.

8) Use DataReader- Use datareader for fast retrieval. If you want to show just read-only data then better to use datareader instated of dataset.

9) Use Paging- It is general idea that people don’t want to see thousands of data. So it is always better to use paging so that it will increase the performance.

10) Explicitly close resource- Always use try /finally and make sure you close and dispose all the connection and any other objects which is not required any more.

11) Disable Tracking and debugging. Always disable tracking and debugging when you deploy the application on production server. Set debug=false in web.config

12) Use store procedures- In most cases you can get an additional performance boost by using compiled stored procedures instead of ad hoc queries.

13) Always make sure you check Page.IsValid before processing your forms when using Validator Controls.

14) When you can, use toString () instead of format (). In most cases, it will provide you with the functionality you need, with much less overhead.

15) Place StyleSheets into the Header

16) Put Scripts to the end of Document

17) Make JavaScript and CSS External -Using external files generally produces faster pages because the JavaScript and CSS files are cached by the browser. Inline JavaScript and CSS increases the HTML document size but reduces the number of HTTP requests.

Wednesday, June 29, 2011

HTML5

Hi friends
i am back with a new thing:) might be the old one for code guru. Today i was looking into the new HTML version HTML5.

This is the latest version on HTML which is launched to make sure that HTML is not legging behind with the world. In today's net savvy world we have different type of videoes, audioes,pictures showing on the websites. These all items need different plug in to run with like flash player, but now no plugin is required:)

below are some of the tags which make your life so much easy in the world of html.
1) audio- For playing sounds, music or other audio streams
2) video- For showing video content, such as a movie clip or other video streams
3) source- For media resources for media elements, defined inside video or audio elements
4) embed- For embedded content, such as a plug-in
5) Canvas - The HTML5 canvas element uses JavaScript to draw graphics on a web page. using this you can create images on the webpage itself file filled rectangle
6) localStorage - stores data with no time limit, this will be the replacement for cookies so that you can keep the big data on client side also without hammpering the performance of the application
7)SessionStorage - stores data for one session and when you close the browser all the data will be lost.

Here are some of the new input types which is supported in HTML5. These type will life of developer much simpler as developer don't have to write javascript for validation of these types.

1) email= if you put the input type as email then this type will make sure that user enter the email address only. another words it will do validation for email address format and if your browser don't support it it will show as simple input type.
2) url= It will validate the text box for URL format
3) number= It will validate the number format. it also support the max and min number user can enter in input box. there is one more feature call step so it will show the number as the step value you have defined.
4) range= this will make the range for the number like min to max value.
5) Date pickers (date, month, week, time, datetime, datetime-local)- it will set date time value in text box and user can select the appropriate date time values
6)search-The search type is used for search fields, like a site search, or Google search.
7) color- validation for color number values (Chrome support hexadecimal values and safari will show the color picker it self for user to select any of the colors)
8) placeholder- this will show the message in text box and when user click on the text box the value goes off. this will be like information for the content of the input text box.

check the below site for more and better understanding.

Monday, July 26, 2010

Warning 1 Use command line option '/keyfile'

This is the common Warning message we usuall get when we build a 1.1 framework project in newer version like 2.0 or 3.5. I got the warning as below.
Warning 1 Use command line option '/keyfile' or appropriate project settings instead of 'AssemblyKeyFile'

I had never noticed the warning before, but looked into some of the past builds and noticed that it had always been there. After doing some research, I found out that Visual Studio 2005 now considers the use of setting the AssemblyKeyFile in the AssemblyInfo.cs file a security issue. This is due to the AssemblyKeyFile attribute being embedded within your assembly and possibly containing sensitive path information. The warning also recommended setting this information via the project settings. I use an external strong name key file for all of my assemblies. It resides outside all of my projects/solutions. When I referenced this strong name key file, VS2005 copied it into the project. This wasn't a good thing at all.


If you are using Visual Studio 2005, you can use Project Settings (right click project name in solution explorer) to sign the assembly.

Sunday, April 26, 2009

Upload files on Secure FTP

hi friends
i am having trouble with the Secure ftp site. i was not able to upload the files on the secure ftp site using my code. the code works good if the ftp site don't have the Secure SSI connection. then i have written a code which uses FtpWebRequest for uploading the data on secure ftp site. In this code i have one problem about the Certificates which should be issued in order to make it secure sit. i don't have that certificates so i have written a static method which will make the certification value as valid in any case. here is the code. hope it will help you guys
public bool SecureConnection(string UrlPath, string UserName, string Password,string command,string filePath,string fileName) { try { //String serverUri = "ftp://ftpsite.com/folder1/Test"; if (command.Equals("UF")) UrlPath = UrlPath + "//" + fileName; //String serverUri =UrlPath; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(UrlPath); request.Credentials = new NetworkCredential(UserName, Password); request.UsePassive = true; request.EnableSsl = true; switch (command) { case "MD": if(SecureConnectionRemoveDirectory(UrlPath,UserName,Password)) request.Method = WebRequestMethods.Ftp.MakeDirectory; break; case "UF": request.Method = WebRequestMethods.Ftp.UploadFile; StreamReader sourceStream = new StreamReader(filePath); byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); sourceStream.Close(); request.ContentLength = fileContents.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); requestStream.Close(); break; } ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); } catch (Exception _exp) { return false; } return true; } public static bool ValidateServerCertificate(object sender,X509Certificate certificate, X509Chain chain,SslPolicyErrors sslPolicyErrors) { return true; }

Tuesday, April 21, 2009

Finding Number of Rows in UltraGrid

Hi friends
Today i was working on Ultra Grid provided by
Infragistics. I found out a typical problem. There is a scenario where i have to find the number of rows selected in the grid. These number of rows are not by selecting the check boxes in the grid cell but by CTR-Click combination. i can check the activated row by the active index properties but now i have to select all the rows which i have previously selected with the holding the control button. Below is the code which might be helpful for you.


public ArrayList GetSelectedAccount(Infragistics.Win.UltraWinGrid.UltraGrid dgAccount)
{
ArrayList AccountArray = new ArrayList();
CurrencyManager cmAccount = (CurrencyManager)this.BindingContext [dgAccount.DataSource, dgAccount.DataMember];
DataView dvAccount = (DataView)cmAccount .List;
for (int i = 0; i < dvAccount .Count; ++i)
{
if (dgAccount.Rows[i].Selected)
{
AccountArray.Add(dgAccount.Rows[i].Cells["AccountID"]);
}
}
messagebox.show(AccountArray.length.tostring());
}
[/CODE]