Month: May 2016

How to avoid js files cache script bundle with razor

It happened to me, that I was working on an ASP.NET MVC Razor with AngularJs application, and every time that the team make a change in the AngularJs files and deploy to Production, the users start complaining about unresolved issues in the application. Those issues were because of the browser cache the JavaScript files in the client side. So in this article, I'll try to find an optimal solution to this problem, meaning that the javascript bundle should avoid cache when a new version of the application is deployed to production.
bundle cache

Avoiding browser cache:

We have to consider that one of the most popular techniques to avoid browsers cache with javascript files is to add a variable at the end of the file name, like this: src="/app/app.js?nocache=12365434576".

  <script type="text/javascript" src="/app/app.js?nocache=12365434576"></script>

Now this resolve the issue partially since 12365434576 it's going to be a random number that always going to avoid the cache, and we don't want that, we want to avoid cache only when a new version is deployed, for a better performance. So what we need to do is, instead of set the nocache var to a random number we are going to user the version of the application, like this:


Bundle Code:

We had a code like this to compose the bundle in App_Start/BoundleConfig.cs

 private static void AddAppBundles(BundleCollection bundles)
        {
            var path = "admin";
            var scriptBundle = new ScriptBundle("~/js/app");
            var FullPath = HttpContext.Current.Server.MapPath(string.Format("~/{0}", path));
            if (Directory.Exists(FullPath))
            {
                scriptBundle.Include(
                    // Order matters
                    string.Format("~/{0}/app.module.js", path),
                    string.Format("~/{0}/app.core.module.js", path)
                    )

                    .IncludeDirectory(string.Format("~/{0}", path), "*.module.js", true)
                    .IncludeDirectory(string.Format("~/{0}", path), "*.js", true);
            }
            bundles.Add(scriptBundle);
        }

With the code above we can include all the javascript files found in "path" variable in our _Layout.cshtml page, with this code:

@Scripts.Render("~/js/app")

The code is going to render something like this:

  <script type="text/javascript" src="/app/app.js"></script>
<script type="text/javascript" src="/app/config.js"></script>
<script type="text/javascript" src="/app/dashboard/dashboard.module.js"></script>
<script type="text/javascript" src="/app/layout/layout.module.js"></script>
<script type="text/javascript" src="/app/blocks/apiendpoint.config.js"></script>
<script type="text/javascript" src="/app/blocks/apiendpoint.provider.js"></script>

The question here is how we can render something like this src="/app/app.js?nocache=1.28.16145.10", when we render the bundle in razor.
We are going to use @Scripts.RenderFormat.

Solution:

@{  
    string version = typeof(yourProjectNamespace.WebApiApplication).Assembly.GetName().Version.ToString();
}
    <!--app scripts.-->
    @Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}?nocache="+ version +"\"></script>", "~/js/app")

This is an example of the result rendered:

  <script type="text/javascript" src="/app/app.js?nocache=1.28.16145.10"></script>
<script type="text/javascript" src="/app/config.js?nocache=1.28.16145.10"></script>
<script type="text/javascript" src="/app/dashboard/dashboard.module.js?nocache=1.28.16145.10"></script>
<script type="text/javascript" src="/app/layout/layout.module.js?nocache=1.28.16145.10"></script>
<script type="text/javascript" src="/app/blocks/apiendpoint.config.js?nocache=1.28.16145.10"></script>
<script type="text/javascript" src="/app/blocks/apiendpoint.provider.js?nocache=1.28.16145.10"></script>

Hope this was helpful. 🙂

State Management in ASP.Net

In this article I'll try to cover the different techniques session state management in ASP.Net applications. With this we are going to be able to determine the best approach for our solution when we manage the session states in ASP.Net applications.
session state management

These are the session state management options in Asp.net

  • Off
  • StateServer
  • InProc
  • SQLServer
  • Cookies
  • Query String
  • Custom

Fot Off|StateServer|InProc|SQLServer, we will need to specify the session state tag in the web.config. This is a template code:

<sessionState mode="Off|StateServer|InProc|SQLServer"
              cookieless="true|false"
              timeout="number of minutes"
              stateConnectionString="tcpip=server:port"
              sqlConnectionString="sql connection string"
              stateNetworkTimeout="number of seconds"/>

Off Mode

Off mode, which disables session state.


StateServer Session State mode

StateServer Session State mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. StateServer session runs as a Windows service and would help to minimize database traffic.
Example:

<configuration>
  <system.web>
    <sessionState mode="StateServer"
      stateConnectionString="tcpip=SampleStateServer:42424"
      cookieless="false"
      timeout="20"/>
  </system.web>
</configuration>

InProc Session State

InProc Session State, this mode stores session state with the ASP.NET worker process (in memory on the Web server). It is not valid in a web farm configuration.
Example

<configuration>
   <system.web>
      <sessionState mode="InProc"
                    cookieless="true"
                    timeout="20"/>
      </sessionState>
   </system.web>
</configuration>

SqlServer Session State

SqlServer Session State. stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. Although, It does support a web farm configuration, you should not use this if you want to minimize database traffic.
Example:

<configuration>
  <system.web>
    <sessionState mode="SQLServer"
      sqlConnectionString="Integrated Security=SSPI;data 
        source=SampleSqlServer;" />
  </system.web>
</configuration>

Cookie State mode

Cookie State mode. Cookies are stored on the client, so the application would not be able to keep the state if they switched to a different device or a different browser. Also the user needs to have the cookies enabled in their browser


Query String

Query String It can be used for passing limited state information across request boundaries, this solution would not be able to keep the state if they switched to a different device. This solution will work even if the user have disabled the cookies in the browser.


Custom mode

Custom mode, which enables you to specify a custom storage provider.
Example:

<configuration>
  <connectionStrings>
    <add name="OdbcSessionServices" 
      connectionString="DSN=SessionState;" />
  </connectionStrings>

  <system.web>
    <sessionState 
      mode="Custom"
      customProvider="OdbcSessionProvider">
      <providers>
        <add name="OdbcSessionProvider"
          type="Samples.AspNet.Session.OdbcSessionStateStore"
          connectionStringName="OdbcSessionServices" 
          writeExceptionsToEventLog="false" />
      </providers>
    </sessionState>
  </system.web>
</configuration>

These are the options we have in Asp.net to manage the session state in an application. Hope this was helpful.