Visual C# Built In Code Snippets For Fast Productivity


Code snippets are ready made, which means they are really useful reusable codes which need to be used and then again used at someother  part of work.

These snippets are not really of the type which are only used by just placing a cursor and inserting it to the place you want, but some are surrounded with code snippets also in which some line of code has been selected and then surrounded with required if statement, for loop and so on.

Code Snippets have following Advantages:

  • It saves a lot of your time by saving reusable code in code snippet manager and you can later use it anywhere.
  • It increases productivity by simply inserting code in you desired location.
  • It reduces the chances of less error by re typing your line of code.
  • It helps to stream line your work as per you assigned deadline.

Code Snippet Manager:

Firstly, you can check a whole list of code snippets in code snippets manager which you can open by pressing Combination of (Ctrl + K, Ctrl + B).

You can alternatively open code snippet manager from Visual Studio Menu from Tools è Code Snippets Manager…

There is another way to open as introduced in latest versions of visual studio which is very beneficial to open the menu items in less time; it is the Quick Launch Search Box Displayed in Top Right of your Visual Studio IDE.

As you type text it gives you suggestions and suggestions to do more actions also, like it displays the most Recently used items and Nuget Package Manager search for the searched keyword.

How to Use Code Snippets:

Basically there are two types of code snippets to be used; First one is by placing cursor at location and typing some code snippet code and secondly by using surround-with code snippets.

Note: At any time if you do not want to select the desired code snippets Press ESC Button it will dissolve and does not insert the code snippet.

Cursor Based Code Snippets:

Usage of code snippets is very simple. Just place cursor at the desired location where you want to insert code snippets, type snippet code and Press TAB Button Twice to insert in the place… we will discuss full list of code snippets in this article after following this but for reference I am quoting here an example of code snippet… for example you want to add for loop, just write for and press twice to check the magic of code snippet inserting and with full syntax and with default values. It Increases your productivity and time by also reducing the risk of human errors while creating complex syntax like for loop.

You can use it from Keyboard shortcut also by pressing key combination of (Ctrl + K, Ctrl + X) and select the Visual C# Category.

But if you have to remember the snippet code you can type it.

Surround-With Code Snippets:

You can use surround with code snippets by selecting the line of code and press keyboard short cut key combination (Ctrl + K, Ctrl + S) and type the desired code snippet to wrap in the line of code.

List of Available Code Snippets:

Now we will move into the using of code snippets inside IDE.

#region:

Region directive is used to define certain region in the code which specifies certain functionality or scope of certain work. It is collapsible portion and it is useful for pages which has lengthy code written so that you can collapse the region of code and focus on your work.

The start #region must be terminated with #endregion directive otherwise it will through the exception.

#region has a scope of anywhere means you can insert it anywhere you want.

(~):

This code snippet has scope only in class as class has destructors.


As already mentioned that has scope with in class so I checked it with creating outside the scope of class, although it created as it is snippet but it will generate compile error or a namespace cannot directly contain members such as fields or methods, while the other one inside the class scope did not through any exception.

ctor:

This code snippet is used to create constructor of a class. It has also scope within class otherwise it generate exception.

Type ctor and press TAB twice to insert.


class:

This snippet will create a declaration of class. It has a scope of namespace (global), class or struct.

enum:

This is used to declare enumeration. This is used to build a list of distinct enumerators. It has a scope of inside namespace, class or struct. The default value for initial first enumerator is 0 and the successive items will follow it like 0, 1 and so on. Enums cannot contain whitespaces while declaring their names.

The approved types of enum are int, long, byte,unit,ulong,ushort,short and sbyte.


cw:

Very helpful snippet cw means Console.WriteLine() which can show current line terminator to the output stream. Its scope lies inside method, indexer, property or event accessor.

It can take string as a parameter and return to output stream. You can align string to New Line also by using Console.Out.NewLine,

  1. Console.WriteLine();

equals:

The Equals as the name defined it has behavior to check equal of two objects either they are of same type or of different type and it returns Boolean value, if matched it return true otherwise false.

Its scope lies only inside class or struct.

  1. // override object.Equals
  2. public override bool Equals(object obj)
  3. {
  4. //
  5. // See the full list of guidelines at
  6. // http://go.microsoft.com/fwlink/?LinkID=85237
  7. // and also the guidance for operator== at
  8. // http://go.microsoft.com/fwlink/?LinkId=85238
  9. //
  10. if (obj == null || GetType() != obj.GetType())
  11. {
  12. return false;
  13. }
  14. // TODO: write your implementation of Equals() here
  15. throw new NotImplementedException();
  16. return base.Equals(obj);
  17. }
  18. // override object.GetHashCode
  19. public override int GetHashCode()
  20. {
  21. // TODO: write your implementation of GetHashCode() here
  22. throw new NotImplementedException();
  23. return base.GetHashCode();
  24. }

exception:

Creates a declaration for class that derives from exception by default. Exceptions are errors which are generated by the application. Its scope is inside a namespace, class or struct.

  1. [Serializable]
  2. public class MyException : Exception
  3. {
  4. public MyException() { }
  5. public MyException(string message) : base(message) { }
  6. public MyException(string message, Exception inner) : base(message, inner) { }
  7. protected MyException(
  8. System.Runtime.Serialization.SerializationInfo info,
  9. System.Runtime.Serialization.StreamingContext context)
  10. base(info, context) { }
  11. }

for:

for statement is most probably used to run together block of statements in a repeated fashion until you statements return false. The best possible scenario for using for loop having you know number of iterations required to get possible operation.

  1. for (int i = 0; i < length; i++)
  2. {
  3. }
foreach:
foreach iterates through for each element in an array or object collection that implements IEnumerable or Generic IEnumerable Interface.
It just iterate to the collection of items but it does not for adding or removing items. you can use break and continue operation inside foreach loop as per your easness.

  1. foreach (var item in collection)
  2.         {
  3.         }

for:

this code snippet is for decrementing values  after each iteration using for loop. Its scope is as same as for loop.
  1. for (int i = length – 1; i >= 0; i–)
  2.        {
  3.        }

if:

it is the most important and too many used code snippet in daily work routine. due to its  simplicity its as important as you think you have to include for every block statement to check for. It has scope inside a method, indexer, property or event accessor. by default it has true value like we are checking for check box which is either checked or not so that we can evaluate the if … else condition on the base of it.

  1. if (true)
  2.         {
  3.         }

Interface:

by inserting this snippet it create the interface declaration. an interface only contain the signature of methods, indexer,events pr properties. a class which implements the interface must used the members which interface has defined.  An Interface can inherit from one or more base classes. it has scope inside a class, struct or namespace (global).

  1. interface IInterface
  2. {
  3. }

namespace:

it declare a scope / set of related objects. inside a namespace you can declare one or more namespace,c lass, struct, enum, interface and delegate.

it has scope only inside namespace which has global scope.

  1. namespace MyNamespace
  2. {
  3. }

prop: it created auto-implemented property inside a class or struct.you can initialize certain properties with some initial value.

  1. public int MyProperty { getset; }
propfull: it can create property declaration with get  and accessors and it has scope only inside a class or struct.
  1. private int myVar;
  2.     public int MyProperty
  3.     {
  4.         get { return myVar;}
  5.         set { myVar = value;}
  6.     }

switch:

It is a control statement which selects a switch section and break no succeeding section should be checked. each switch section contains one or more case labels followed by one or more statements depending on the scenario.

  1. switch (switch_on)
  2.         {
  3.             default:
  4.         }

try:

create a try….catch block. the most important purpose of try … catch is to catch unhandled exceptions by trying a block of code and it successful it moved to the next section or move out of the method block and if not successful it go to the catch section where customized as well as other exception are thrown to identify the type of breakage caused by the try code.

  1. try
  2.        {
  3.        }
  4.        catch (Exception)
  5.        {
  6.            throw;
  7.        }
tryf: the basic purpose of using finally with try block is to cleanup the resources which is occupied by try block,
  1. try
  2.         {
  3.         }
  4.         finally
  5.         {
  6.         }
while:

It executes block of statements until the expression is not set to false. The executing statement can also be terminated by adding break, go to like statements. It has scope inside a  method, indexer, property or event accessor.
  1. while (true)
  2.        {
  3.        }
That’s all about some of the useful code snippets but there are some others; you can check full code snippets  manager for full list.

Introduction to HTTP Status Response Codes


Before going into the detailed description of each status codes we need to understand some definitions which are necessary to fully understand the terms used in this context.

What is Hypertext Transfer Protocol (HTTP)?

HTTP is a stateless protocol means  (the request which client generated must have some response from server and no data reside on server while processing both). Http Follow client-server approach as client send request from browser and in return server response. For every request you send to server you have to wait for response that browser shows in the form or HTML.

HTTP consist of Headers, Cookies, DNS Prefetching, Response Codes, Request Methods and Access Authentication.

We Will discuss in detail about the main backbones of HTTP Request-Response Model.

There are several versions of HTTP, but currently HTTP 1.1 is in use.

Hope you understand the basics of HTTP, Now Let’s start with the key area of HTTP Request – Response Model which is Http Response Codes.

HTTP Response Codes

These provide information about certain HTTP Requests either they are completed or not.

These are 3 digit codes.

These are grouped in to five major categories enlisted below:

Status Code Group Status Info Status Description
1xx Informational Continue and processing.
2xx Success Response Successful, no action required, Ok Status
3xx Redirection Need more action to fulfill the request.
4xx Client Error The Request contains unknown syntax and server did not fulfill the request.
5xx Server Error The Server failed to fulfill the valid request.

List of Common HTTP Status Response Codes

  • 200 OK
  • 300 Multiple Choices
  • 301 Moved Permanently
  • 302 Found
  • 304 Not Modified
  • 307 Temporary Redirect
  • 400 Bad Request
  • 401 Unauthorized
  • 403 Forbidden
  • 404 Not Found
  • 410 Gone
  • 500 Internal Server Error
  • 501 Not Implemented
  • 503 Service Unavailable
  • 550 Permission denied

Code and Description of Other Response Codes

1xx Informational Responses

HTTP status codes in the 1xx are typically informational.

  • 100 Continue
  • 101 Switching Protocols
  • 102 Processing
  • 103 Checkpoint
  • 122 Request-URI too long
2xx Successful Responses

Status codes in the 2xx range indicate that the transaction was received, understood, accepted and processed successfully.

  • 200 OK
  • 201 Created
  • 202 Accepted
  • 203 Non-Authoritative Information (since HTTP/1.1)
  • 204 No Content
  • 205 Reset Content
  • 206 Partial Content
  • 207 Multi-Status (WebDAV) (RFC 4918)
  • 226 IM Used (RFC 3229)
3xx Redirection Responses

HTTP status codes in the 3xx range pertain to redirection. The client must take additional action to complete the request.

  • 300 Multiple Choices
  • 301 Moved Permanently
  • 302 Found
  • 303 See Other (since HTTP/1.1)
  • 304 Not Modified
  • 305 Use Proxy (since HTTP/1.1)
  • 306 Switch Proxy
  • 307 Temporary Redirect (since HTTP/1.1)
  • 308 Resume Incomplete
4xx Client Error

HTTP status codes in the 4xx range indicate that a problem occurred with the request.

  • 400 Bad Request
  • 401 Unauthorized
  • 402 Payment Required
  • 403 Forbidden
  • 404 Not Found
  • 405 Method Not Allowed
  • 406 Not Acceptable
  • 407 Proxy Authentication Required
  • 408 Request Timeout
  • 409 Conflict
  • 410 Gone
  • 411 Length Required
  • 412 Precondition Failed
  • 413 Request Entity Too Large
  • 414 Request-URI Too Long
  • 415 Unsupported Media Type
  • 416 Requested Range Not Satisfiable
  • 417 Expectation Failed
  • 418 I’m a teapot (RFC 2324)
  • 422 Unprocessable Entity (WebDAV) (RFC 4918)
  • 423 Locked (WebDAV) (RFC 4918)
  • 424 Failed Dependency (WebDAV) (RFC 4918)
  • 425 Unordered Collection (RFC 3648)
  • 426 Upgrade Required (RFC 2817)
  • 428 Precondition Required
  • 429 Too Many Requests
  • 431 Request Header Fields Too Large
  • 444 No Response
  • 449 Retry With
  • 450 Blocked by Windows Parental Controls
  • 499 Client Closed Request
5xx Server Error

Error codes in the 5xx range indicate that server is aware that it has encountered an error or is otherwise incapable of performing the request.

  • 500 Internal Server Error
  • 501 Not Implemented
  • 502 Bad Gateway
  • 503 Service Unavailable
  • 504 Gateway Timeout
  • 505 HTTP Version Not Supported
  • 506 Variant Also Negotiates (RFC 2295)
  • 507 Insufficient Storage (WebDAV) (RFC 4918)
  • 509 Bandwidth Limit Exceeded (Apache bw/limited extension)
  • 510 Not Extended (RFC 2774)
  • 511 Network Authentication Required
  • 598 (Informal convention) network read timeout error
  • 599 (Informal convention) network connect timeout error

Reference:

Introduction Of Visual Studio Code Lens


What is Code Lens

Code lens tells us the code changes in a fantastic way and the best thing of this feature is there in editor history which you get before code lens in a lot of time.

With code lens you have a deep focus on your code, since you know what last changes were made to the file with reference history and who changed it. Code lens is a combination of References, changes in your code, code reviews, bugs associated with item, unit tests and their detail of what number of unit test passed or failed in a unique fashion.

All of the above options you can check while leaving your editor and in page references make life easier, since all of these are associated directly with your code.But wait are you too much excited after readings its indicators, just read the note.

Note: CodeLens is available only in Visual Studio Enterprise and Visual Studio Professional editions. It is not available in Visual Studio Community edition.

So let’s start in detail about indicators of code lens. You can customize the indicators on / off from Tools, Options, Text Editor, then All Languages and Code Lens.

As you can see in the image above the code lens option is enabled by default in the editor. If you are connected to Team Foundation Server or any other version control system you have all the options available and you can customize other specific options.

If you want to disable all the options you can uncheck the Enable CodeLens Option and if you want to enable CodeLens, then check the Enable CodeLens and then customize the indicators what do you want to see in the editor.

There are number of options available as elaborated below:

Show Test Status

By turning this option on you can see the indicator defining the last test run status and it will show left to the references. By clicking the status icon you can take the test result information.

Show References

If your code does not have reference, it show 0 References. you can view the code references by pressing (Alt + 2). if your code has references, then you can view them by moving mouse on the top of reference and by pressing double click you can view the reference definition.

After the references are opened you can see the information displayed in the form of Parent element contains the File location, followed by definition of method with line number as the child of each page.

Show Tested By

 

The Show Tested By option will show the tests associated with your code and the overall status of how many tests associated with number and status of tests run or not. If you have unit test project then this can show the unit test status by giving you value of how much passed, failed with ratio of 1/2 means out of 2, 1 passed and 1 failed and it give you detailed information of unit test with methods and duration in ms (milliseconds).

You can directly run all the tests or specific test and can review the test code by pressing (Alt + 3).

The tests shown with indicator marks of wrong and correct icon which show who failed or passed. If you see the warning icon then it means you have not run any tests and that way you can run through code lens unit test indicator.

To review the test definition double click on the test item.

Show Authors

 

Show author option will able to show you the last author who has changed the file or work in file and check in the latest changes. If there are more than one author associated with your code it shows the last author name like MUHAMMAD AQIB + 2, the count next to the author tells that there are two more authors associated with file. To show this option you can press (Alt + 4) key.

Show Changes

 

This option can give you overview of the changes / history that are associated with the code. The code changes indicator shown on VS Editor is like

3 Changes. To show this option you can press (Alt + 5) key, by opening the changes window you can see the detail of changes with change set ID, Change set Description, Author Name and Date of Changes.

In the changes window, by right clicking on any item it will give you the following three more options:

  1. View Diff of Changeset with [Number] – show difference between selected changeset number with earlier changeset number.
  2. Changeset Details –  by selecting this will show the detail of changeset in team explorer window.
  3. Send Email to [Author Name] –  this will open you default email program and fill the specific change details in the To, Subject and Body section of Email.

Show Bugs

 

If there are some bugs reported with your work items, it will show like 2 Bugs and by opening the bugs detail window it will show you Bug ID, Type, Description, Author and date reported.

Show Work Items

 

It will show the related work items with the piece of code just before the code review indicators. 3 work items,  it means there are 3 work items associated with the the checked in changes and all are associated work items are related with it.

Show Code Reviews

 

It will give you information about the associated code review with specific method and it will show in the last of code lens indicators as 4 reviews.
After opening the review window it will show the Review ID, Type, Title, Author and Date of Review.

Code Lens Formatting

 

With this option you can perform formatting with the code lens like fonts, color and other things in Tools, Options, Environment, then Font and Colors
option and select the show settings for: code lens and after the selection from drop down list it will display Items in other window with options such as indicator text, indicator text (Hovered), indicator text (Selected), indicator text (Disabled) and Indicator separator and then if you require formatting changes, hit OK button and enjoy with formatting colors and applied fonts.

Code Lens Accessibility

 

You can easily access code lens indicators by mouse and with the keyboard keys.

Just point the mouse to the specified indicator and click on it to show indicator options.

From keyboard move the cursor to the desired method and press and hold Alt key for 2 seconds and then it give you number option to select your desired option by pressing numbers.

Code Lens Options From Visual Studio Editor

You can also open code lens option from the Visual studio editor. To do so just right click on any one of the code lens indicator and you can see two options.

Refresh CodeLens Team Indicators.

CodeLens Options

CodeLens options opens the same window which was elaborated at the starting of this article.Hope you enjoyed this article and happy coding with Visual Studio IDE.

Best Ever Performance And Debugging Tools In Visual Studio 2015


The performance of the application is of utmost importance and this going to be very important from the perspective of client which they are facing if you have performance leaks in your application. To identify the performance leak prior to the Production environment is not an easy task but the new emerging power of VS 2015 Diagnostic Tools windows made it easier for us to have a deep performance analysis before it go live.

Instead of running a full profiling tool, you might take one or more of the following steps.

Insert code into an app (such as System.Diagnostics.Stop­watch) to measure how long it takes to run between various points, iteratively adding stopwatches as needed to narrow down the hot path.

Step through the code to see if any particular step “feels slow.”

These practices are typically not accurate, not a good use of time or both. That’s why there are now performance tools in the debugger. They will help you understand your apps performance during normal debugging.

Why not try this new and improved way to diagnose.

Diagnostic Tools Window

The primary difference you’ll notice when debugging code in Visual Studio 2015 is the new Diagnostic Tools window that will appear, firstly go to Debug and Click on Menu Item Show Diagnostic Tools, as in the following Figure 1.

Figure 1: How to open Diagnostic tools Window in Visual Studio 2015

These Diagnostic Tools present information in two complementary ways. They add graphs to the timeline in the upper-half of the window, and provide detailed information in the tabs on the bottom as in the following Figure 2.


Figure 2: the New Diagnostic Tools Window in Visual Studio 2015

  • Debugger Events (with IntelliTrace) gives you access to all Break, Output, and IntelliTrace events collected during your debugging session. The data is presented both as a timeline and as a tabular view. The two views are synchronized and can interact with each other.
  • The Memory Usage tool allows you to monitor the memory usage of your app while you are debugging. You can also take and compare detailed snapshots of native and managed memory to analyze the cause of memory growth and memory leaks.
  • The CPU Usage tool allows you to monitor the CPU usage of your application while you are debugging.

New IntelliTrace UI and experience:

  • Record specific events.
  • Examine related code, data that appears in the Locals window during debugger events, and function call information.
  • Debug errors that are hard to reproduce or that happen in deployment.

Why debug with IntelliTrace

  • An exception happens.

PerfTips:
 
Figure 3: PerfTips

There is also a new option to show the CPU consumption time with PerfTips by clicking on that checkbox.

References

In Visual Studio 2015, you’ll see three tools in the Diagnostics Tools window: Debugger (includes IntelliTrace), Memory Usage and CPU Usage.

You can enable or disable the CPU Usage and Memory Usage tools by clicking on the Select Tools dropdown as in the following image:

The Debugger tool has three tracks that show Break Events, Output Events and IntelliTrace Events.

Figure 4: Digonostic Tools

This feature is used to trace the root cause of Bug/Error fastly and reliably by using events like clicking, post click changes and lots of trace information. This rich tool has lot of information about your running events.

You can spend less time debugging your application when you use IntelliTrace to record and trace your code’s execution history. You can find bugs easily because IntelliTrace lets you.

Note: You can use IntelliTrace in Visual Studio Enterprise edition (but not the Professional or Community editions).

IntelliTrace enhances the debugging experience and saves you valuable debugging time! It does that by capturing additional events with useful information about your programs execution, allowing you to identify potential root causes with fewer debugging iterations. The data it collects appear as events in the IntelliTrace track and in the table in the Events details tab.

In the Enterprise edition of Visual Studio 2015, you will see that we have completely revamped the user interface of IntelliTrace by bringing it into the Diagnostic Tools window. IntelliTrace vastly enhances the debugger by automatically capturing interesting events in your application and surfacing them in the Events graph and the Events tab as in the following image:

Figure 5: Event

UIcon in the graph area of events are the interesting events that are captured while debugging.

By mouse hovering it give detail information in the tooltip and by double clicking to the event it points to the event in Events Tab.

Traditional or live debugging shows only your application’s current state, with limited data about past events. You either have to infer these events based on the applications current state, or you have to recreate these events by rerunning your application.

IntelliTrace expands this traditional debugging experience by recording specific events and data at these points of time. This lets you see what happened in your application without restarting it, especially if you step past where the bug is. IntelliTrace is turned on by default during traditional debugging and collects data automatically and invisibly. This lets you switch easily between traditional debugging and IntelliTrace debugging to see the recorded information. See IntelliTrace Features and what data does IntelliTrace collect?

IntelliTrace can also help you debug errors that are hard to reproduce or that happen in deployment. You can collect IntelliTrace data and save it to an IntelliTrace log file (.iTrace file). An .iTrace file contains details about exceptions, performance events, web requests, test data, threads, modules, and other system information. You can open this file in Visual Studio Enterprise, select an item, and start debugging with IntelliTrace. This lets you go to any event in the file and see specific details about your application at that point in time.

These events made easier to capture where the bug happens as it give full stack tracing in historical debugging section as in the following:

Example

Without IntelliTrace, you get a message about an exception but you don’t have much information about the events that led to the exception. You can examine the call stack to see the chain of calls that led to the exception, but you can’t see the sequence of events that happened during those calls. With IntelliTrace, you can examine the events that happened before the exception.

Videos Link

https://channel9.msdn.com/Shows/Visual-Studio-Toolbox/Historical-Debugging-with-IntelliTrace-in-Visual-Studio-2015/player

PerfTips (performance information in tooltips) is a new feature introduced in Visual Studio 2015 through which you can calculate time between the breakpoint hit points to the last point or while you step into the code.

It give you tips while you debug through code of the elapsed time as in the following image and on hovering over the mouse it gives detailed analysis and the value it estimate also contain debug overhead.

By clicking the elapsed time it can open the diagnostic tools window and show the current event with process memory and CPU utilization if selected.

Beside the elapsed time information if you want to show the CPU utilization this can be set through right clicking the elapsed time link.

When we right-click on that time it’ll show the PerfTips options to configure that.

The default value of showing elapsed time are in milliseconds.

Figure 6: Performance Tools

VideoLink

PerfTips Video