Infragistics NetAdvantage for WPF!

CONNECT WITH US

Featured Post

ASP.NET web optimization framework with MVC 3 & ASP.NET 4.0 web form

Get article update by Email

Yesterday, I came across a forum post, where user was facing problem in integrating web optimization framework with MVC 3. So here in this post we will see how we can integrate asp.net web optimization framework with MVC 3 and ASP.NET 4.0 web form application.

Web optimization framework was introduced with MVC 4 and it is included in default MVC 4 template. But we can use it with MVC 3 and ASP.NET 4.0 web form application as well. This is because web optimization framework is built on top of framework 4.0. So here are the steps to use web optimization framework with ASP.NET 4.0 application.

  • Create new ASP.NET 4.0 web form or MVC 3 application
  • Add web optimization package by issuing following command in Visual studio package manager console
  • Now add following code in global.asax.cs
using System.Web.Optimization;
 
protected void Application_Start()
{
    Bundle commonBundle = new ScriptBundle("~/bundle/common")
        .Include("~/scripts/common.js");
    BundleTable.Bundles.Add(commonBundle);
}

Now build and browse ~/bundle/common and we can see minified version of JavaScript. So this is how we can see default bundle in action with ASP.NET 4.0 and MVC 3 application. You can refer my following post on advanced concept in web optimization framework.

Check out this index post on ASP.NET Web Optimization Framework (a.k.a Bundling & Minification) to read other post on same.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

ASP.NET MVC: Action filter series

Get article update by Email

Over the last few days, I was getting many requests from reader and friends, to start beginner level article series on ASP.NET and MVC. Generally I am sharing my learning experience here on this blog and mostly which fall in intermediate or advanced level. So I thought to write several beginners level article series on ASP.NET MVC. Towards to this step, this is the first article series on action filter in ASP.NET MVC. In this series we will see different available action filter in MVC including MVC 4. Do request other article series here with me; I will try my best to get it here.

Hope this would be helpful!

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

ASP.NET MVC Bundling: Auto sync JavaScript model with MVC model

Get article update by Email

In yesterdays post ASP.NET 4.5 & MVC 4 Bundling: Next Approach, we have seen how we can pass additional parameters to bundle transform so we can utilize it while generating bundle response. I suggest you to read that post first before starting with this post.

What was the original idea?

Recently in one application, I have to create one JavaScript object which represents C# enum in client side. Later on C# enum keep extending and at the same time I used to add entry in JavaScript object too. Everything was fine but sometime me or team member forget to sync JavaScript object with C# enum when adding or removing existing entry in C# enum and JavaScript starts breaking and further more each time syncing JavaScript object with C# enum was also tedious task specially when team member is new and do not know whole application architecture. So I though let me create one HTTP handler which generates dynamic JavaScript which represent C# enum.

Later when I started implementing HTTP handler, I realize that there are many other JavaScript that can be generated from other C# type and could save developer time & headache especially from task such as syncing JavaScript object/class with C# type. Let me elaborate whole scenario. The application was in MVC and for user friendliness & performance point of view we all are using lots of AJAX & JSON. For e.g.

  • MVC application return list of item in JSON format via JSON result, and we bind it with UI
  • Client post JSON object back to server and desterilize it back in MVC model or model binder take care of it
  • Some time we are using JavaScript MVVM library such as knockout.js or sometime we are using library like backbone.js
  • Microsoft also introduced Single Page Application (SPA) with set of JavaScript library
  • And many other approaches with AJAX, JSON

In short when you are creating rich application, model in client side (JavaScript) is also as important as server side MVC model, entity model or whatever approach you are using. And most of time JavaScript model is same as server side model. So now let back to main point… when I implemented HTTP handler, I thought let me generate JavaScript class for server side model too. So whenever any new property added or removed at that time it also syncs JavaScript class with it.

Later in this post, we will also see how we can use this auto generated JavaScript model with JavaScript library like knockout.js and backbone.js

Why & How I ended up with bundling in ASP.NET MVC application

I could implement it as HTTP handler and almost implemented but later I thought let me see if I could create custom bundle and transform for the same. There are few advantages of using bundling over HTTP handler while response are same application wide irrespective of user. It is

  • It stores generated response in server cache hence it is faster than processing each and every request to HTTP handler (read my full post on same here)
  • We can configure bundle url something pretty like ~/bundle/jsmodel over ~/jsmodel.ashx (yeah we can configure route for the same but still…)
  • We can clearly separate transformation logic in separate class/library etc.

Following is the full source code for the same staring with Bundle which accepts .NET type as an extra parameter.

public class JSModelBundle : Bundle
{
    private List<Type> _modelList = new List&lt;Type&gt;();
 
    public JSModelBundle(string virtualPath)
        : base(virtualPath, new JSModelTransform())
    {
    }
 
    public List<Type> ModelList
    {
        get { return _modelList; }
        set { _modelList = value; }
    }
}

Transform type which transforms .NET type in JavaScript object/class.

public class JSModelTransform : IBundleTransform
{
    public void Process(BundleContext context, BundleResponse response)
    {
        string strResponse = string.Empty;
        response.ContentType = "text/javascript";
 
        JSModelBundle bundle = (context.BundleCollection
            .Where(b => b.Path == context.BundleVirtualPath)
            .FirstOrDefault()) as JSModelBundle;
 
        foreach (Type type in bundle.ModelList)
        {
            if (type.IsClass)
            {
                strResponse += GetFunctionBodyForClass(type);
            }
            else if (type.IsEnum)
            {
                strResponse += GetObjectBodyForEnum(type);
            }
        }
 
        response.Content = strResponse;
    }
 
    string GetFunctionBodyForClass(Type type)
    {
        StringBuilder sbFunctionBody = new StringBuilder();
        sbFunctionBody.AppendLine("function " + type.Name + "() {");
 
        foreach (PropertyInfo p in type.GetProperties())
        {
            sbFunctionBody.AppendLine("this." + p.Name + " = '';");
        }
 
        sbFunctionBody.Append("}");
        sbFunctionBody.Append("\n\n");
        return sbFunctionBody.ToString();
    }
 
    string GetObjectBodyForEnum(Type type)
    {
        StringBuilder sbFunctionBody = new StringBuilder();
        sbFunctionBody.AppendLine(type.Name + " = {");
 
        int enumLength = type.GetEnumValues().Length;
        int index = 1;
 
        foreach (var v in type.GetEnumValues())
        {
            string strEnumField = v.ToString() + " : " + (int)v;
            if (index &lt; enumLength)
                strEnumField += ",";
            sbFunctionBody.AppendLine(strEnumField);
            index++;
        }
 
        sbFunctionBody.Append("}");
        sbFunctionBody.Append("\n\n");
        return sbFunctionBody.ToString();
    }
}

Sample .NET types

public class Product
{
    public int ProductId { get; set; }
    public string ProductCode { get; set; }
    public string ProductName { get; set; }
}
 
public enum Event
{
    Add,
    Update,
    Delete,
}

and code snippet for how to include it in bundle

JSModelBundle bundle = new JSModelBundle("~/bundles/JsModel");
bundle.ModelList.Add(typeof(Product));
bundle.ModelList.Add(typeof(Event));
bundles.Add(bundle);

Now we can use generated JavaScript model with backbone.js as displayed below.

var product = new Backbone.Model(new Product());

Following is the code snippet of using it with knockout.js

var product = new Product();
ko.applyBindings(product);

Hope this would be helpful!

Check out this index post on ASP.NET Web Optimization Framework (a.k.a Bundling & Minification) to read other post on same.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

ASP.NET 4.5 & MVC 4 Bundling: Next Approach

Get article update by Email

In the earlier post, we have seen how we can access bundle context while processing bundle through custom transform. Taking it further, in this post we will see how we can utilize bundle context to pass extra parameters to transform and later how we can utilize those parameters to transform bundle.

What are the needs of extra parameter?

Since ASP.NET 4.5 & MVC 4 developer preview version, bundling was introduced with two transforms JsMinify and CssMinify which minify JavaScript & CSS respectively. Then after community came with few more transforms for Sass, LESS, CoffeeScript, (TypeScript might be in pipeline) etc. But if you have noticed, one thing is common in all these transforms is that all transforms are applying on files. We include some files in bundle with Bundle.Include and those files are transformed. In other word, we could pass only file (or VirtualFile) to bundle transform and bundle transform read those file content and process it. But what if I want to pass other information to bundle transform? Let say I want to pass Dictionary collection to bundle transform. At first glance, we don’t have any mechanism for the same! Is it really so? Nop we can pass such extra parameter to bundle transform and can utilize it while generating bundle response. Following is the steps for the same.

Create one class which is derived from Bundle class and add properties for the any extra parameter in it as displayed below.

public class CustomBundle : Bundle
{
    private Dictionary<string, string> _metaInfo = null;
 
    public CustomBundle(string virtualPath)
        : base(virtualPath, new CustomTransform())
    {
    }
 
    public Dictionary<string, string> MetaInfo
    {
        get { return _metaInfo; }
        set { _metaInfo = value; }
    }
}

For demonstration purpose, I have created one property of type dictionary but it could be of any type. With the help of this property, we will pass additional info to bundle transform.

With custom bundle class we have defined list of additional parameters. Now following is the code of custom transform type and how we can read those extra parameters with the help of bundle context while generating response. For more info on custom transform type read my previous post here.

public class CustomTransform : IBundleTransform
{
    public void Process(BundleContext context, BundleResponse response)
    {
        CustomBundle bundle = (context.BundleCollection
            .Where(b => b.Path == context.BundleVirtualPath)
            .FirstOrDefault()) as CustomBundle;
 
        response.Content = JsonConvert.SerializeObject(bundle.MetaInfo);
    }
}

As we know that we can have access of bundle collection while transforming bundle. So we are extracting current bundle from bundle collection and hence type of current bundle is CustomBundle we can access extra parameters through it. Here for simplicity we are serializing it into JSON but possibilities are lot more stay tuned for tomorrow’s post to know how I wanted to use it.

Now we are ready with custom bundle and transform type so following is the code which shows how to add this custom bundle to bundle collection.

CustomBundle bundle = new CustomBundle("~/bundles/metainfo");
 
bundle.MetaInfo = new Dictionary<string, string>();
bundle.MetaInfo.Add("Blog", "dotnetExpertGuide.com");
bundle.MetaInfo.Add("Author", "Nandip Makwana");
 
bundles.Add(bundle);

What leads me to find the way of passing extra parameters and how I wanted to use it?

For simplicity and clear separation of topic I have written another post which shows how I wanted to use this bundling approach with ASP.NET MVC application.

Check out this index post on ASP.NET Web Optimization Framework (a.k.a Bundling & Minification) to read other post on same.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

ASP.NET MVC: ChildActionOnly action filter

Get article update by Email
ASP.NET MVC: ChildActionOnly

ChildActionOnly action filter confirms that specified action method should be only accessible by child request. Unlike NonAction filter, such methods are still treated as action method but it can’t be invoke as a parent request. More specific user can’t invoke it direct by requesting action name but we developer can invoke it through code.

Attribute Usage: Controller & method

Sample Code:

[ChildActionOnly]
public ActionResult About()
{
    return View();
}

We can also apply this action filter at controller level so all action method of specified controller will be accessible by only child request.

What is child request in ASP.NET MVC?

So now next question arise is what is child request? So child request means we can’t access it by direct url in other word we can’t use it to begin new request/response pipeline but we can use it as action method from within code where request/response pipeline are already initiated by some other request or action method. We can use such child action method as follow.

@Html.Action("ChildActionMethod")
 
@{
    Html.RenderAction("ChildActionMethod");
}

If we try to access such method with direct url then it will throw an System.InvalidOperationException.

Check out ASP.NET MVC: Action filter series post to read about other available action filters.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More

ASP.NET MVC: AcceptVerbs action filter

Get article update by Email
ASP.NET MVC: AcceptVerbs

So far we have seen various action filter in ASP.NET MVC which allow us to restrict action method usage based on HTTP verb or method. But with the usage of HttpGet, HttpPost, HttpPut or other such action filter, we are limited to only respective HTTP verb. But sometime we require that action method should be accessible by more than one HTTP verb but not all. This is the case where AcceptVerbs comes in picture.

In this case, we can use AcceptVerbs action filter. Here we can specify list of HTTP verbs and action method would be accessible by only those verbs.

Attribute Usage: Only method

Sample Code:

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult About()
{
    return View();
}

In above example, action method will be accessible by only HTTP GET & POST verbs. Following is the full list of possible value for AcceptVerbs

  • HttpVerbs.Get
  • HttpVerbs.Post
  • HttpVerbs.Put
  • HttpVerbs.Delete
  • HttpVerbs.Head
  • HttpVerbs.Patch
  • HttpVerbs.Options

We can use any combination from above list with AcceptVerbs filter.

Check out ASP.NET MVC: Action filter series post to read about other available action filters.

You can follow me on twitter for latest link and update on ASP.NET & MVC.

Read More