August 20, 2010
ASP .NET MVC & Charting

At some point in our career as Web developers we’ve been asked to add a visual representation of data, commonly known as charts. Charting is an integral part of a line of business application. They represent data in a subtlety manner, making easier to interpret compiled data and make decisions from it. A chart can take a large variety of forms, however there are common features that provide the chart with its ability to extract meaning from data.

There are many options to render data on your Web application depending on your needs. We are going to discuss some of the options and see an example of how to do it on an ASP .NET MVC project. This might help us choose from the overwhelming offer of free components out there.

Doesn’t Microsoft provide free charting tools?

The answer is YES, but they are available as server-side controls for ASP .NET Webforms. After Microsoft acquiring Dundas Software, a couple of years ago, they where introduced on the previous .NET framework release (v3.5) and made formally part of the framework on the latest release (v4.0). Scott Guthrie describes the control in this blog post.

Certainly this charting control can be incorporated into ASP .NET MVC with ease. There’s been a lot of discussion about ways of achieving this. The solution boils down to just needing to reference the DataVisualization assembly and the handler for rendering the chart image on the web.config.

But doesn’t this feel a little out of place? Specially for the purpose of this framework? It’s like all of the sudden Mr. Postback is right around the corner of becoming a special needed feature of your ASP .NET MVC application. Ironic isn’t it? 

Other options in the charting world

Parting from this, many options exist, in order to fulfill this “must have” requirement. There are many flavors to choose from, when it comes to free charting libraries. Just to mention a few: Google Charting Tools, amCharts, Open Flash Charts, Flot, JSCharts…

Breaking them down!

Google Charting Tools are a good option. They’re pretty straight forward to use and understand. Google also provides a visualization playground where you can get more intimate with the API and all its features.

Flot is a jQuery plugin simple to use and renders awesome looking charts.  If you’re used to working with jQuery, this will be heaven for you. It displays a wide variety of charting options and programming utilities like feedback of the points clicked on the chart area. Go grab it now!

amCharts its a fancy looking solution. They have a huge palette of options for rendering data. Their charts also can have animations. If you want to use these you have to be willing to get your hands dirty in order to get this beast tamed. These charts are highly configurable, therefore you have to work with to separated XML files to get them working: one for the data and one for the chart configuration.

Open Flash Chart now this is the FULL package, it has it all. It renders the charts in flash but embraces the use of JSON as the data file, which makes them a perfect candidate for JavaScript tweaking. Also being completely open source, like Flot, encourages developers to create libraries and extend their functionality. There’s a library built for .NET already available for download on the linked site.

Isn’t this a technical blog?! Show me some code!!!!!

Just to be coherent, after praising Open Flash Charts, I’m choosing this package to feature on my example.

In order to start, let’s be clear on what we need:

  • Open Flash Chart swf object.
  • An Open Flash Chart library that outputs JSON formatted chart objects. (Open Flash Chart .NET library preferably, just to avoid the wheel reinvention) 

And that’s it!!!

So let’s start by getting the whole thing from the Open Flash Chart’s site download section. This will provide us with the charts swf object and different libraries for different languages and implementations.

After unpacking your download go straight to the “dot-net-library” directory and extract the DLL from the “OpenFlashChart” library project. There’s also a WebForms project that you can run and see implementations of all the library available options.

So following the tutorial we need to embed the OpenFlashChart.swf object to our webpage. To do so I chose the swfObject JavaScript library, which can be imported to the desired view or the site’s master page from Google’s CDN.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.1/swfobject.js"></script>

After importing the swfobject library we just need to embed our flash object like this:

<script type="text/javascript">
     swfobject.embedSWF("open-flash-chart.swf", "my_chart", "250", "200", "9.0.0");
</script>

This tutorial shows how data can be passed to the chart using a data file explicitly instead of using the query-string which is the default way of specifying the file.

Instead of using that code directly on our views I’d rather use another approach, which consists on creating a Html helper to render the chart. I’ve gone ahead and created a static extension class in order to extend the ASP .NET MVC’s Html Helper, here’s the code for my method.

#region OpenFlashChart
public static string RenderChart(this HtmlHelper helper, 
  string chartContainer, //This is the id of the html container where the chart is going to be rendered preferably a div.
  string chartData, //This is the route to the chart JSON formatted data
  int width, //This is the chart width
  int height, //This is the chart height
  string loadingText = "Loading data...") //This is chart's the loading text
{            
            var chart = new StringBuilder();

            //Creating the script tag
            var script = new TagBuilder("script");

            //Adding the type attribute
            script.Attributes.Add("type", "text/javascript");

            //Setting the swf object definition for the open flash chart
            string swfobject = "swfobject.embedSWF(" +
                        "\"/Content/swf/open-flash-chart.swf\"," + //This can be set from a config file or w/e
                        "\""+ chartContainer +"\"," + 
                        "\""+ width +"\"," + 
                        "\""+ height +"\"," +
                        "\"9.0.0\"," + 
                        "\"/Content/swf/expressInstall.swf\"," +
                        "{ \"data-file\": \""+ chartData +"\", \"loading\":\"" + loadingText + "\" }" +
                    ");";

            //Setting the inner text of the script tag without HTML encoding
            script.InnerHtml = swfobject;
            
            //Appending the script tag to the helper result
            chart.Append(script);

            //Returning the open flash chart client code implementation
            return chart.ToString();
}
#endregion

Now that we have our helper to render the chart it’s time to copy the corresponding files. First move the open-flash-chart.swf to the Content/swf directory as well as the flash expressInstall file. And then add a reference to the extracted OpenFlashChart library.

import dll

So now we are half way through, we just need to things: a controller method that returns the JSON formatted data and the implementation of our helper on the desired view.

I created a new controller called ExampleController which contains a method called Chart, which is responsible of generating the chart’s random data an returning the JSON formatted info in order to render the chart.

public string Chart()
{
            //Populating random chart data
            var chartData = new List();
            var rand = new Random(DateTime.Now.Millisecond);
            for (double i = 0; i < 12; i++)
            {
                chartData.Add(rand.Next(30));
            }


            //Creating the chart type definition
            Area area = new Area
                            {
                                Values = chartData,
                                HaloSize = 0,
                                Width = 2,
                                DotSize = 5,
                                FontSize = 12,
                                DotStyleType =
                                    {
                                        Tip = "#x_label#<br />#val#",
                                        Type = DotType.DOT,
                                        Colour = "#467533"
                                    },
                                Tooltip = "#val#",
                                Colour = "#CC3399",
                                FillColor = "#343399",
                                FillAlpha = .5
                            };

            //Creating the chart object
            var chart = new OpenFlashChart.OpenFlashChart { Title = new Title("line chart") };

            //Setting the Y axis properties
            chart.Y_Legend = new Legend("y axis");
            chart.Y_Axis.SetRange(0, 35, 5);
            chart.Y_Axis.Steps = 3;

            //Setting the X axis properties
            chart.X_Axis.Labels.Color = "#e43456";
            chart.X_Axis.Steps = 4;

            //Defining the chart's tooltip properties
            chart.Tooltip = new ToolTip("#val#")
                                {
                                    Shadow = true,
                                    Colour = "#e43456",
                                    MouseStyle = ToolTipStyle.CLOSEST
                                };
            
            //Adding the chart type to the elements collection of the chart
            chart.AddElement(area);

            //The library has a built in JSON serializer
            return chart.ToPrettyString();
}

Now we just need to call our Html helper extension method from the view to render the chart like this.

<%= Html.RenderChart("chartContainer", "example/chart", 960, 180) %>

Voila! We’ve got a nice looking chart!

chart

Try reading the tutorials listed on the Open Flash Chart web page where you can learn how to customize its elements.

Summary

All these charting tools are useful and get the job done. They provide us with a set of tools to achieve the data visualization need of our clients. It’s your job to choose the one that suits better your needs. 

Taking into account this drawback, having JavaScript disabled on the browser might be a killer for some of the animated charts. This is an inherited issue for all the Google charting tools siblings which rely on client-side rendering like Flot or JSCharts. This is where the ASP .NET chart control wins the fight.

I don’t know if there’s a successful web application that doesn’t embrace the power of JavaScript, but there are some IE6 users who work for corporations where the IT department don’t like JavaScript. I guess these poor people don’t know what they’re missing!

Download the source code.

July 20, 2010
TIP/Trick: Use DataPager control with ListView and Custom Data Source

Paging tabular data retrieved through a database query has been a long time need in transactional line of business applications. With time the ways of achieving this in ASP .NET have evolved into very easy solutions. On the previous version of the framework, .NET framework 3.5 (currently to the date they are now on 4.0) two server-side user controls where introduced, the ListView and the DataPager.

They idea behind the ListView control is to provide the developer with more control over the markup output while providing the data-bound experience of previous controls. The ListView control displays data based on user defined templates, which is extremely convenient for styling purposes. It also reduces to zero the garbage markup automatically generated by older controls like the GridView.

The DataPager, in the other hand, is product of the decoupling of the paging feature from the data-bound controls that implement the IPageableItemContainer interface. Providing more freedom when it comes to paging customization on regards of functionality and appearance.

Both controls complement each other in a marvelous way. The DataPager provides paging practically out of the box when using a data source control, which is what the documentation found almost everywhere encourages to use. BUT! The truth is that sometimes we use custom data sources because of a special scenario that dictates their use to get the data. In this scenario is were the use of the DataPager becomes a little bit more challenging, since the paging is once more a developer’s responsibility rather than a delegated feature for the framework.

So how do we tackle this?

One approach is raising and handling the PagerCommand event found on the DataPager TemplatePagerField template and evaluating each command sent from the server-side controls placed there. This is extremely convenient if you want to implement a custom way of paging the data and navigating through it. You’ll also have the responsibility of rendering the current page you’re at, as well as all the other available navigation pages.

Another approach, and the one we’ll describe with more depth, is a little bit more simple and similar to the default behavior of the DataPager when used with data source controls. For this we just need to raise the ListView’s PagePropertiesChanging event and invoke the DataPager’s SetPageProperties method. This is an obvious combination since the PagePropertiesChangingEventArgs provide us the arguments of the SetPageProperties method overload.

The code

I think we’ve done enough to describe what we are trying to achieve here, so let’s see the code for this. Let’s asume we have a ListView called lvProducts.

protected void lvProducts_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
    var pager = (DataPager)lvProducts.FindControl("pager"); //pager is the name of our DataPager control

    pager.SetPageProperties(

      e.StartRowIndex, 

      e.MaximumRows, 

      false); //Set false because we are using a custom data source

    BindDataToListView(); //Here we just bind the data to our list view again and the new data page will be displayed
}

And that’s it! Paging should work like a charm. Happy coding!

February 28, 2010
How to use Membership/Role Provider and when to use custom implementations

Authentication is a must have feature for every system. Every system administrator needs to give an identity to the ones using their system. Which leads us, developers, to make this repetitive process something easier to implement and reuse every now and then on any application that may need user login.

I’ve seen many “authentication frameworks” which encapsulate simple verification routines into assemblies, that can be implemented as easy as just creating a reference and running a sql script against the DB. What the heck! Even I made one of those and felt 1337 because of my glorious creation. But! That was until I meet the provider model, which reduced the greatness of my crappy “framework” or I may say, reinvention of the wheel.

The provider model involves many other things that go a lot further than just user authentication, resource permissions, etc. For now I’ll address the ones related to user management and their default implementation.

What? More sh*!t about Membership/Role/Profile Provider?!! Why should I care?

Let’s start by saying that this is not something new. The provider model has been around since ASP .NET 2.0, therefore 5 years ago you could’ve done this without any problem the same way I’m gonna do it now. The deal is that people rather read or download an example from a blog, than actually spend some time reading about how the thing works and what’s the most suitable way of implementing it depending t heir given situation.

Instead of trying to write a manual of how to do it, I’ll try to explain why use the default or simplest form of the provider model for user management rather than opting for a custom membership provider. Of course if you are able to choose how to handle your users and you don’t stick an existing form of user authentication into your app. Either way I encourage you to drop your 1337 implementation, and use this since the Login controls work out of the box.

My intention is to eradicate the taboo surrounding t his, and really show how simple it is to make this work along with our application without any effort at all.

To Customize the provider or not to customize the provider

So, in order to make the provider a viable solution they had to make it flexible. And it is. By simply extending the membership, role or provider base classes you can implement your own customization of these providers. The thing is that people tend to opt for this without hesitating falling again into the loop of reinventing something that it’s already done for you.

Everything resumes to this: Unless you have to use a pre-defined structure for the users database your option will be a custom implementation of the membership/role/profile providers. But if you are using ASP .NET 2.0 or higher (obviously), MSSQL, and do not have to use an existing user base you shouldn’t create your custom provider. There are also ports of the ASP .NET Application Services DB for Oracle, MySQL and Postgre, so there are not excuses for this.

The usual excuse for resistance of using the default implementation of the provider is the assumption of “having to rely on the username field and having alphanumeric fields as FK’s among the whole system might affect performance”. This, even though it sounds technically convincing it’s a lie. All the relationships on the default DB schema are made using GUID’s which definitely knock off this vague excuse. Obtaining the user’s unique identifier takes as little as two lines of code, so don’t let that stop you.

Avoiding the implementation of a custom membership/role/profile provider WILL save you time and let you focus on other tasks more important than user administration and resource permissions.

OK, so where’s the code?

Since I’m not addressing a custom implementation of any of the providers being discussed. It’s only going to be necessary to configure the providers using the web.config or the ASP .NET Configuration panel. There are a couple of ways of implementing the membership and role provider on its simplest form. One way is to use the ASP .NET Configuration in order to achieve it. Let’s see how.

Step 1

First, select the ASP .NET Configuration option from your Website menu in Visual Studio.

ASP .NET Configuration

Note that this will open a website which contains the website configuration settings grouped in three categories: Security, Application Configuration & Provider Configuration.These presented options on the ASP .NET Configuration website will allow us to configurate everything, from authentication methods, users and all that other stuff to smtp mail servers (of course this is useful if our application sends emails, for instance a user password reset). Here’s what you can do on each tab:

Security.- Here you’ll be able to find the user/role configuration stuff, you’ll be able to do CRUD operations on your users and roles, and also define the access rules per user/role for your application resources.

Application Configuration.- Here, you can define application settings which are just application are keys that are going to be accessible from the <appSettings/> dictionary. Also you’ll be able to set the stmp settings, take the application offline and set the debugging and tracing options.

Provider Configuration.- Here, you can select the providers you’ll on the application, these is very useful since you can define various providers on your web.config (if you’d like) and switch through them. For instance the settings for your application on the development environment are different from your production environment.

ASP .NET Configuration

Also, this action will automatically create a new Database file and place it on your App_Data folder of your website/webapp. This database named aspnetdb will contain the Application Services DB schema definition.

ASP .NET Application Services DB

Step 2

You just need to access the Security tab and start creating your users, roles and access rules.

ASP .NET Application Services DB

By default we have in our hands a simple yet robust implementation of user management. We are able to select the forms of authentication for our application from the provided configuration options, Windows or Forms, these options are described on the msdn documentation. When using forms authentication, the passwords of our users are going to stored on our database, by default these are going to be hashed. Also our users need to have a secret question/answer in order to reset/retrieve their passwords.

From our application will be able to access all of these user management CRUD actions by using the System.Security.Membership class. All of the Login Toolbox controls located on the visual studio Toolboox palette, will work without writting a single line of code.

Great! But what if I want to use my own Database

So you already have designed your application database and you want include the Application Services Schema definition in it. This is a very common scenario, and you’ll need to do very little to get this working.

First, you need to run the aspnet_regsql command from the visual studio command prompt and go through the, fairly simple, wizard until you select and register your database. This will copy all the Application Services tables and store procedures that you’ll need to use the Provider Model into your existing DB.

After that, you’ll need to define a connection string that points to that database on your web.config. This connection string will be specified on our membership provider definition.

<remove name="LocalSqlServer"/>
<add name="LocalSqlServer" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=MyAppDB;Persist Security Info=True;
User=sa;Password=P@$$w0rd" providerName="System.Data.SqlClient"/>

Now we just need to define the provider and then change the membership provider for the application to use our new one on the Provider Configuration.

<system.web>  
   <membership userIsOnlineTimeWindow="20" hashAlgorithmType="SHA1">
      <providers>
        <add connectionStringName="LocalSqlServer" enablePasswordRetrieval="false"
          enablePasswordReset="true" requiresQuestionAndAnswer="false"
          passwordFormat="Hashed" applicationName="MyApplication" name="MyAppMembershipProvider"
          type="System.Web.Security.SqlMembershipProvider" />
      </providers>
   </membership>
</system.web>

Retrieving the User Unique Identifier

If you need to create a relationship between a user and any other entity by using it’s unique identifier (GUID) instead of its username, you just need to retrieve it by using the read-only property ProviderUserKey from the MembershipUser class.

System.Web.Security.MembershipUser mu = System.Web.Security.Membership.GetUser();
string usrID = mu.ProviderUserKey.ToString();

Conclusion

On this blog post, I discussed ASP .NET Membership & Role provider implementations on it’s simplest form, which in my opinion should be your first option when implementing this feature, of course if the scenario allows it. Custom implementation of the providers aren’t bad and I’m not against them but you should use them when its necessary, that’s all. This topic was very debated when this feature first came out, and 4 Guys from Rolla have a very good series of articles that go in depth on the subject, I encourage you to read it if you are interested on learning how this thing works.

December 1, 2009
TIP/Trick: Enable/Disable ASP .NET Ajax TabContainer Tabs

Space and content distribution is a very important part when designing a web site. That’s why breaking content into multiple sections using a tabbed widget in order to save space is a commonly used technique in web design these days.

Today I’m going to address a common issue that arises when using a tab widget, which is enabling/disabling specific tabs. But first let’s talk a little bit about the Ajax Control Toolkit. The Ajax Control Toolkit provides a palette of AJAX enabled controls, with the purpose of creating an “interactive web experience”. If you work with ASP .NET, you MUST have heard about ASP .NET AJAX, previously known as ATLAS. You must also have seen and feel familiar with update panels and Microsoft’s ASP .NET AJAX paradigm. Certainly the ASP .NET AJAX framework makes AJAX implementation trivial to anyone.

The tendency of throwing update panels everywhere in order to achieve partial post backs in your page it’s a widely used approach among ASP .NET AJAX enabled sites. It’s also a common practice to see how every server/client side control on a web page, get replaced with any equivalent found on the AJAX Toolkit provided by Microsoft. If you are using one of these “cutting edge” techniques my friend, let me tell you that you are killing your application performance. And that also, I’m NOT the first one to point this out. The ASP .NET AJAX framework and the AJAX Toolkit have been widely criticized over thousands of technical web blogs. Mainly because by providing a mechanism for “easy” AJAX implementation performance of your web application gets compromised.

Basically, performance get s affected because a lot of web resources get imported when using both the framework and the toolkit. Also the fact that in every “partial post back” you actually send the whole page making HTTP GET/POST actions more bloated when loading your page. You could use Mozilla Firefox’s Firebug plugin to analyze your HTTP requests and the amount of data that gets sent back and forth to the server, or just google about the topic in order to extend your knowledge about this particular subject.

I encourage you guys to use other lightweight javascript frameworks that help you achieve DOM manipulation and asynchronous calls to the server in order to retrieve and send data like jQuery or Prototype.

Show me the code!

So I decided to do two examples instead of one. Besides doing it using the AJAX Control Toolkit. I also did it using jQuery, just to have two options. So here’s the code.

AJAX Control Toolkit Tab Container

Here’s the HTML:

<div style="width: 500px">
  <cc1:TabContainer ID="TabContainer1" runat="server">
      <cc1:TabPanel HeaderText=”Tab 1” runat=”server” ID=”tpTab1”>
          <ContentTemplate>
                Tab 1 Content!
          </ContentTemplate>
      </cc1:TabPanel>
      <cc1:TabPanel HeaderText=”Tab 2” runat=”server” ID=”tpTab2”>
          <ContentTemplate>
                Tab 2 Content!
          </ContentTemplate>
      </cc1:TabPanel>
  </cc1:TabContainer>
  <p>
      <input type=”button” onclick=”javascript:DisableEnableTab(false,0);” value=”Disable Tab 1” />
  </p>         
</div>

And here’s the javascript:

function DisableEnableTab(boolVal, tabIndex) {
      var tab = $find('<%=TabContainer1.ClientID%>');
      tab.get_tabs()[tabIndex].set_enabled(boolVal);
}

jQuery

Here’s the HTML:

<div id="tabs" style="width: 500px">
      <ul>
          <li><a href="#tab-1"><span>One</span></a></li>
          <li><a href="#tab-2"><span>Two</span></a></li>
      </ul>
      <div id="tab-1">
          Tab 1 Content!
      </div>
      <div id="tab-2">
          Tab 2 Content!
     </div>
</div>
<p>
   <input type="button" onclick="javascript:DisableTab();" value="Disable Tab 1" />
</p>

And here’s the javascript:

$(document).ready(function() {
      $("#tabs").tabs();
 });
            
 function DisableTab() {
       //Selecting another tab
      $("#tabs").tabs('select', 1);
                
      //Disabling first tab
      $("#tabs").tabs('option', 'disabled', [0]);
 }

So there it is, happy coding!

October 28, 2009
Can URI and URL be used interchangeably ?!

Have you encountered yourselves hesitating when trying to use the terms URI or URL? I have. Apparently the difference between a URI and a URL is a very debated topic on the web. And it’s also a source of confusion for many people, including myself.  

Almost every comparison that I find seem to be a tongue-twister, which vaguely describes that they are related but they’re not the same (aha! you see? I did it too, I said something but actually said nothing. PLOP!). The truth is that there’s a different RFC describing the scheme of each, URI’s and URL’s. If you go through the W3C documentation you’ll find that they have a documentation page trying to clarify the confusion around URI’s.

In the end? What’s are URI’s and what are URL’s?

The RFC2396 describes a Uniform Resource Identifier (URI) as a set of characters used to identify a resource name, location or both on the internet. This means that an URI can be classified as a locator (URL), a name (URN), or both. The RFC2717 describes a “Uniform Resource Locator” (URL) as a compact string representation of the location for a resource that is available via the Internet. Parting from these definitions we can conclude that every time we refer to a URL we are talking about an URI, but not the other way.

So? Can we use them interchangeably?

The short answer is, NO. Even though its a tendency among experts, this World Wide Web Consortium memo states that there shouldn’t be any confusion, since they all have different schemes (URI’s, URL’s and URN’s) describing the differences among them. BUT!!! If we are talking about “how to identify the resource and provide the means of locating the resource by describing it’s primary access mechanism” then we are talking about an URL, which is also an URI; therefore we can use them interchangeably in that specific case.

Conclusion

When talking about Internet resources we tend to use these terms to refer to them, specially when talking about HTTP actions in order to get a document. So, there’s always the safe way of doing things: if you don’t know if you are talking an URL or an URI, just refer to it as an URI and you wont be wrong.

12:00am  |   URL: http://tumblr.com/ZPs6Cx7D_xpM
(View comments
Filed under: URN URL URI WWW W3C 
September 21, 2009
How to: Write your own Visual Studio Code Snippets

Just to go with the formality flow, let’s first define a snippet. According to wikipedia, a Code Snippet is a programming term for a small region of re-usable source code or text. Ordinarily, these are formally-defined operative units to incorporate into larger programming modules. Snippets are often used to clarify the meaning of an otherwise “cluttered” function, or to minimize the use of repeated code that is common to other functions.

Visual studio allows us to add our own code snippets for reuse of common block codes in current or further projects. Custom code snippets can be adhered to the ones bundled with the IDE. These can be created and edited with the text editor of your preference. Snippets are handled as XML files, which follow a XML Schema from Microsoft. This schema contains the definition of mandatory elements and attributes for the snippet to work.

Since the 2005 release, code snippets were introduced as part of Visual Studio. Visual Studio 2005/2008 itself has pre-bundled snippets for surrounding or inserting code blocks. Visual Studio also allows code snippets to be added to the toolbar by simply pasting the code block into it. You could create different tabs to classify them.

How to create your own custom code snippet in Visual Studio 2005/2008

1. To start, let’s create an XML file with a *.snippet extension. This file will contain our snippet attributes, as well as the desired code block.

2. Ironically, let’s use the “snippet” snippet which comes pre-bundled with Visual Studio. This will inject into our file the snippet XML structure.

3. Edit the snippet template by filling in the necessary values.The type for the snippets may vary depending on what we want to achieve, we may only want to insert a block code, or surround one with the desired snippet as well. The declarations correspond to de variables that may be edited from the code edit or (Visual Studio) and they must be referred between $ on the code element. We must specify for what language is the snippet as well.

4. After editing the file, the next step is to open the Code Snippets Manager from the tools menu. On the Code Snippets Manager by selecting add, we are going to be able to add a complete folder containing our code snippets. If we want to import one specific snippet into a selected folder we just have to click on Import.

Using our custom code snippet

So let’s use our code snippet. We can select it from the insert code snippet in the Visual Studio context menu (right click on the class file), or we can use our defined shortcut and press tab twice to import the block of code.

The Result!

So here it is ladies and gentlemen, our custom code snippet!

Summary

The purpose of this article is to highlight a very useful feature from Microsoft’s IDE. A cool feature we should exploit in order to gain the most of it, and that not many people gets to take advantage of. Grabbing a code block that is constantly reused and insert it from with the help of the IDE whenever we need it, boosts our productivity significantly. Also, this feature encourages the developer to embrace re-usability when designing a piece of code.

Liked posts on Tumblr: More liked posts »