RSS

Category Archives: ASP.NET MVC

Configuring Redis Session State Provider With Azure

Redis is an open source (BSD licensed), in-memory data structure store, used as database, cache and message broker. Even though it has been originally developed for POSIX systems it can be easily configured to store session data in .NET with the aid of couple of nugget packages and using windows port that can be downloaded from https://github.com/MSOpenTech/redis.

One particular need you might need to store session external to webserver itself is when you have a web farm/multiple webservers with an authenticated user where subsequent requests would be redirected to different servers for example via a load balancer. Traditionally this can be solved easily with session store providers but using Redis for this can be fast and easier if you have your host system in Azure which was in my case.

To test the implementation locally for development you could do following,

  1. Download Redis port for windows from https://github.com/MSOpenTech/redis. Note: it is not available in http://redis.io site.redis windows port extract
  2. 2. Starting local Redis server is very easier as indicated below.

redis server

It will start the Redis server and note the connection details. You can change these by changing redis.conf file which is documented in the site.

e.g. https://github.com/MSOpenTech/redis/blob/2.8/redis.conf

redis server start

3. You can use various commands specified in the project site’s documentation e.g. to view session keys use command below. (not to worry on hacking my servers these are my DEV ENV values )

redis keys

4. Then you have to do install redis session state provider nugget package from https://www.nuget.org/packages/Microsoft.Web.RedisSessionStateProvider/ to your project.

5. One caveat here is to support “sliding expiration” for session state you need to make sure you install package version >=1.5.0. Sliding expiration is typically a must in session state management. Current version at the time of writing is 1.6.5 so make sure you install the latest.

6. To install RedisSessionStateProvider, run the following command in theNuget Package Manager Console of Visual Studio.

PM> Install-Package Microsoft.Web.RedisSessionStateProvider -Version {latest version number here}

7. Then all you have to do is add following configuration section in your web.config and change values accordingly.

session state config

8. After you have successfully tested it in your development environment you might need to configure Redis in windows Azure. Creating Redis Cache in Azure is super easy as shown below. At the time of writing it will be only supported in new Azure portal found in http://portal.azure.com/. Old portals does not support Azure Redis Cache.

azure redis create

azure redis create 2

9. Choose appropriate pricing tear depending your data load.

azure redis pricing

10. It will take a while to create the Redis cache. It sometimes takes more than 10 minutes to up and gets running.

redis cache creating

11. After you create Redis cache you need to configure cryptographic key and connection details for the nuget package. Selecting created Redis cache will show the access keys as below.

redis session config cryptographic keys

12. Then all you need to do is enter Access key and host name of azure redis server to the web.config. Notice how the connection details being entered, its quite different than we used earlier for local Redis server. Also note that host name given by Microsoft is always ends suffixed with cache.windows.net. So your full host name should look like someuniquename.redis.cache.windows.net. This will essentially point your session store to Azure Redis cache.

redis session config values

Note: Redis desktop manager can be used to manage Redis DB if you prefer GUI interface which can be download at http://redisdesktop.com/

redis desktop manager

 
Leave a comment

Posted by on October 20, 2015 in .NET, ASP.NET, ASP.NET MVC, Azure, C#

 

Tags: , , , , ,

Pre-Bundling and Pre-Minification in ASP.NET

There are number of bundling and minification libraries available for asp.net/asp.net MVC applications. Following are few I have come across with.

• Microsoft ASP.NET Web Optimization Framework – Available as a nuget package
• WebGrease – Available as a nuget package.
• Request Reduce – Available as a nuget package, supports external resources, Also supports Less, SASS and Coffee Script.
• Packer
• Closure compiler
• JSMin
• SquishIt
• Combres
• Cassette – Also compile CoffeeScript & LESS

What is the one common limitation with these libraries?
However almost all above libraries require you to do initial bundling configuration in application before requests are being made. Then write directives in your views to render the configured bundles.
Following is what you would typically do in this instance it is ASP.NET MVC bundling… Similar kind of code needs to be put with other libraries.

public static void RegisterBundles(BundleCollection bundles)
{
     bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                 "~/Scripts/jquery-{version}.js"));
         // Code removed for clarity.
}

Then in your views you refer to these bundles.

 @Scripts.Render("~/bundles/jquery");

This is almost always ok but there are situations where this is not what the problem to be solved e.g. think about dynamically driven multi-site CMS handlers. These CMS handlers do host probably thousands of microsites inside their own one single abstract parent site handler. If we try to configure bundling with these it becomes impossible to use this approach or will become huge burden and will make things much slower.

I recently helped to one of my colleague to solve similar situation. Requirement was really simple in the admin panel you just select set of files for one of your micro-site and then it will generate bundled and minified output file.

Library I used for this was YUICompressor.NET which available as a nuget package. This is a .NET port of the Yahoo! UI Library’s YUI Compressor Java project. It can be installed as below to your project.

yui-compressor

You can write code similar to following to get compressed and minified output.

var cssFiles = Directory.GetFiles(Server.MapPath("~/CMSSitePath/1260/css-uploads"));

StringBuilder sb = new StringBuilder();			
foreach (var cssFile in cssFiles)
{
     sb.AppendLine(System.IO.File.ReadAllText(cssFile)); //make sure using AppendLine instead of Append of string builder
}
			
var compressedCss = new CssCompressor().Compress(sb.ToString());
System.IO.File.WriteAllText(Server.MapPath("~/WebSites/1260/css/main-css.min.css"), compressedCss);

As you can see above code is a very simple and naïve approach for solving the problem. Make sure to use AppnedLine of string builder instesad of Append this will be specially helpful for JavaScript otherwise you might end up with minification errors for some javsacript files. For demo purpose many additional error checks, configuration and streams has not been used. But you get the idea. Anyhow practically since the output is a bundled file that must be loadable in web browser without spending much time even the above code will be sufficient to handle production requirements no need for streams to read files (since input file contents are relatively less than 1mb most of the time).

 
Leave a comment

Posted by on June 26, 2015 in ASP.NET, ASP.NET MVC, C#

 

Tags: , , , ,

Remove unnecessary view engines if you don’t use them in ASP.NET MVC

Visual Studio 2012 MVC 4 internet project template by default supports Razor View engine out of the box where the views suffixed with cshtml extension created by default. If you further go through this route and use Razor view engine still ASP.NET MVC 4 default template uses web forms view engine by default before using Razor view engine when it comes to view resolution which has probably a little performance pay.
If you use Glimpse debugging plugin for ASP.NET MVC4 you can easily view this as shown below.
ASP.NET MVC View resolution in Glimpse

As you can see above web forms view engine by default used prior to Razor view engine. This might be a micro optimization but you should remove the web forms view engine if you are not using this as shown below or at least you should change the order if you are mostly using Razor views than web forms views.

protected void Application_Start()
		{
			AreaRegistration.RegisterAllAreas();

			WebApiConfig.Register(GlobalConfiguration.Configuration);
			FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
			RouteConfig.RegisterRoutes(RouteTable.Routes);
			BundleConfig.RegisterBundles(BundleTable.Bundles);
			AuthConfig.RegisterAuth();

			//Remove default view engines
			ViewEngines.Engines.Clear();
			// add the Razor view engine
			ViewEngines.Engines.Add(new RazorViewEngine());

		}

If you do this modification in Global.asax file you should see more efficient view resolution as shown below.
view engines in ASP.NET MVC

 
Leave a comment

Posted by on July 22, 2013 in ASP.NET, ASP.NET MVC

 

Tags: ,