EditorConfig: A simple way to manage consistent coding style

As per Robert Martin, Code should be elegant, efficient, readable like well-written prose . I’m also a strong believer of that. There are two key observations that I often see in code when multiple people work in a team. These are

  1. Everybody has different coding style so they write the code in their own way unless a common coding guideline is followed by team. It’s always advisable to make it part of an automated process.
  2. New members join the team and if they are not properly guided, chances are more to have spaghetti code. It becomes more problematic if the new members are junior developers/interns.

These issues can be solved at certain extent with the help of editorconfig file. In this file, we can define a set of rules (we will discuss few) which can be extremely useful to maintain the code consistency. This file can be made a part of solution so it is available to every team member.

Editor Config has it’s own format and guidelines to define the rules which can be seamlessly used by multiple editors like VS Code, Sublime, Vim, Netbeans, Eclipse, notepad++ and many more.

Follwing are the common set of rules which can be used

  • indent_style
  • indent_size
  • end_of_line
  • charset
  • trim_trailing_whitespace
  • insert_final_newline
  • tab_width

Let’s see an example. I have specified the editorconfig as

Here, I provided the indent style, indent size as tab and tab size. The last item trim_trailing_whitespace is set as true. One more thing, these rules will be applied to csharp (.cs) file but we can more file types as [.{cs,vb,js}] or even [*].

Note: The default values of these settings are available in Visual Studio IDE but once we add the editorconfig is added in project, it overrides the IDE setting. A notification also appears as

Let’s first discuss the first three as they are related. The default value for tab size is 4, but here I made it 3. As indent size is marked as tab, it has the power to resolve the whitespace vs tab issue :). Now when a developer uses whitespace for identation, it will turn to tab. In the below example, we can see, for few lines tab is used and for other spaces.

 

If the code is written with the above settings it will be as

Note – I have used ctrl+r, ctrl+w to see the tabs and spaces in the VS IDE.

Also the last settings helped in removing unnecessary white spaces after at the end of the line.

.NET related code conventions can be divided in three categories as

  1. Language Conventions
  2. Formatting Conventions
  3. Naming Conventions

Language Conventions: As the name suggests, these are related to the C#/VB language like using braces, using var instead of explicit type etc. The format looks as

options_name = false|true : none|suggestion|warning|error

Here we need to provide two values true/false and severity. true means prefer this style and false is opposite. Severity has four options as below

  1. none/silent : This will be used by code generation features only. No indication to user if it is not followed.
  2. suggestion : In case of violation, show a suggestion to user which appears as eclipses under the first two characters.
  3. warning : Shows an warning by underlining the variable with green squiggly.
  4. error: Shows an error by underlining the variable with red squiggly.

Let’s see an example. Here first we will see the editorconfig

Now let’s see the code

Here in first part of the image, we can see the gray squiggly and when we select, it displays a suggestion to change it var as per the editorconfig. Also we see the quick action icon which allows us to change with a preview (depicted in second part of the screen). Similarly, let’s see other options

 

In first part of the image, we can see a green squiggly as we configured to have braces and set is as warning. While second part of the pic, we see red squiggly which denotes an error as we configured to use predefined type. So based on our project needs, we can have a specific config file so we every member in the team follows the same rule.

Formatting Conventions : We have a set of rules which can help us in defining formatting guidelines of our code files. These formatting rules can be defined as

rule_name = false|true 

The rules could be as

Here first rule says system directive should be written first while other suggests not to have single line blocks, instead have it in multiple lines. There are many other rules which can be extremely helpful in maintaining the consistency. You can find all the list here. Similarly, Let’s have quick look on naming conventions.

Naming Conventions : Naming of the variable is also one of the key items while writing the code and .NET supports a list of rules which can be used in the editorconfig file. These rules are fully customizable. Let’s say we want a rule where we want public members as captilazied. It can look as

Here we created a new rule (public_members_must_be_capitalized) and provided the definition for that. For details, refer the documentation here.

Now we can see that this file is extremely useful. It may take some time to create but once done, pretty usefull. We can have files at solution and/or project level. At soultion we need to mention root = true as in the first image.

Editor Config has native support in Visual Studio 2017 but for earlier version of Visual Studio you can install the extension from here.

So hope you have enjoyed the post and would be able to use in your projects.

Cheers,
Brij

Advertisements

Remove ViewEngines that are not used : An ASP.NET MVC performance tip

Today, I am writing a small post on ASP.NET MVC that will help in performance of ASP.NET MVC application. So lets discuss it in detail.

Whenever we create an ASP.NET MVC application it allows us to select a View Engine Razor for the application as.

select View engine

Here we selected Razor and this is selected by default as well.

But when applications run, it loads multiple view engines and we use only one view engine normally that is selected while application creation. We can prove it many ways

1) Let’s see the collection ViewEngines in Global.asax. It shows as while debugging.

firstallThe above clearly shows that it contains two View Engines while we selected Razor View Engine while creating application.

2) To prove it another way, As we know when we use Razor View Engine then views extension is .cshtml and for WebForms view engine, it is .aspx. So lets say we created a controller and it has a method like

public ActionResult Index()
{
    return View();
}

And we did not created any view accordingly. Now when we run the applications it throws the following error

serachedviews

It tries to find the View but could not find. It also shows what file names and where does it try to find. If we see the above screenshot then we find that it tries to look files with extension .cshtml/.vbhtml and .aspx/.ascx as well, where .aspx/.ascx is used in case of web-forms view engine. And we selected razor View engine while application creation. It simply shows that it loads two view  engines which is not required.

Solution : Add the following code in the method Application_Start in Global.asax

// Removes all the view engine
ViewEngines.Engines.Clear();

// Add View Engine that we are ging to use. Here I am using Razor View Engine
ViewEngines.Engines.Add(new RazorViewEngine());

Now after making the above changes, it loads only the added ( here Razor) view engine.

Now we can check the scenario discussed in point 2 and now see the page

afterremovinNow it tries to find only .cshtml/.vbhtml files.

We should use the above logic and because there is no use loading all the view engines in memory if we are not using .

Hope you all find it useful and use it in your projects.

Cheers,
Brij

The requested content appears to be script and will not be served by the static file handler. : A Solution

Today, I faced one issue while working on one sample . And could not find solution in one go and error shown was not intuitive enough.

First let me share my environment. Windows 8 (64 bit), Visual Studio 2012, IIS8

I created an ASP.NET 2.0 web service using Visual Studio 2012 directly at IIS8. But as soon as, I tried to access my web service via browser I found the following error

ErrorAs you can see from the error, it does not point to any cause.

For this error there could be one issue that IIS is not registered with ASP.NET. So to register it, I opened the command prompt with run as administrator and navigated to the folder C:\Windows\Microsoft.NET\Framework\v2.0.50727. I navigated to framework version 2.0 because I was accessing the ASP.NET 2.0 webservice. Now I required to run the following command

aspnet_regiis -i

But as soon as I run the above command, I faced another error

errorcmd

Later, I found that my Operating System (Windows 8) that I am running is of 64 bit version. So again navigated 64bit version executable and it ran successfully

successfullyRanSo you can see above the message “Finished installing ASP.NET <2.0.50727>”.  Here in the above pic, if you see the red encircled area, I have ran here 64 bit version executable.

Also note, this issue arises only if you installed the IIS after installing Visual Studio.

Hope this would save lot of time of yours.

Thanks,
Brij

How to access the input control’s data at Server side during Client Callback : A useful trick

Client callback is one way to update the webpage without performing the full page postback. It maintains the Client state while updating the Webpage. During Client callback the webpage runs through modifies version of Page Life Cycle.

The LifeCycle of a page in Client Call Back is  as

Page Lifecycle iin Callback

If you want to learn  more about Client Callback, click here.

But the main drawback of  Client Callback, The input data is not posted from Client to Server. Also,  It does not maintain the view state during partial postback as you can see the Page life cycle of Client callbak it is not saved or SaveViewState event is not fired.

Lets see it with an example.

I have created a simple form to collect some information of an person data. And it has a submit button, which initiates a Callback. As

 <table>
 <tr><td><asp:Label id="lblFName" runat="server" Text="First Name" /> </td>
 <td><asp:TextBox ID="tbFName" runat="server"></asp:TextBox></td></tr><tr>
 <td><asp:Label id="lblMName" runat="server" Text="Middile Name" /> </td>
 <td><asp:TextBox ID="tbMName" runat="server"></asp:TextBox></td></tr><tr>
 <td><asp:Label id="lblLName" runat="server" Text="Last Name" /></td><td><asp:TextBox ID="tbLName" runat="server"></asp:TextBox></td></tr><tr>
 <td><asp:Label id="lblAge" runat="server" Text="Age" /></td><td><asp:TextBox ID="tbAge" runat="server"></asp:TextBox></td></tr><tr>
 <td><asp:Label id="lblMailId" runat="server" Text="Email" /></td><td><asp:TextBox ID="tbEMail" runat="server"></asp:TextBox></td></tr><tr>
 <td><asp:Label id="lblSex" runat="server" Text="Sex" /></td><td><asp:TextBox ID="tbSex" runat="server"></asp:TextBox></td></tr><tr>
 <td colspan="2"><input id="btnCallBack" type="button" value="Submit" onclick="InitiateCallBack();"/></td></tr>
</table>

Server side code is as

public partial class Callback : System.Web.UI.Page,ICallbackEventHandler
{
    string result;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsCallback)
            return;
        //Creating a reference of Client side Method, that is called after callback on server
        String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg",
            "ReceiveServerData", "");

        //Putting the reference in the method that will initiate Callback
        String callbackScript = "function CallServer(arg, context) {" +
            cbReference + "; }";

        //Registering the method
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
            "CallServer", callbackScript, true);
    }
    public void RaiseCallbackEvent(String eventArgument)
    {
        string firstName = tbFName.Text;
        //Read other data as well

    }
    public string GetCallbackResult()
    {
        return result;
    }
}

And the client side method is

function InitiateCallBack() {
     //Intiate the callback
     CallServer("",'');
}

// Called after the server side processing is done
function ReceiveServerData(arg, context) {
    //arg: hold the result
    //Updating the UI
    document.getElementById('divCallbacl').innerHTML = arg;
}

After filling this form, I submitted it. Now if you try to access the entered using control’s property, you would not get it.

Let’s dig it more and check the form collection, whether the data is passed from Client to server or not

So as you can see that the data is not passed in form collection

But let’s put the following lines of code in java-script, just before initiating the call for Callback as

 function InitiateCallBack() {
	__theFormPostCollection.length = 0;
        __theFormPostData = "";
        WebForm_InitCallback();

        //Intiate the callback
        CallServer("",'');
}

Now let’s run the code and submit the form as earlier.

Now let’s check the form collection.

What a surprise, we got all the input data in form collection. That’s nice.

Now access the data using control’s property.

and you got it.

Now let’s try to see, what does the extra lines of code does

//This Clear the earlier the old data in form collection.
__theFormPostCollection.length = 0;
//It sets the forms data to empty
__theFormPostData = "";
//This method builds the body of the POST request when the page loads. The body of the page is a string 
//(that is __theFormPostData) filled with the contents 
of the view state and all of the input fields in the form.
WebForm_InitCallback();

But I would suggest to use these line at caution. Use only when you need to collect the update from Page during Callback. If you don’t need to get some data or it is in readonly page, don’t use it it introduce extra overhead to your page and costs at performance point of view.

Hope you  all have enjoyed the post.