Imran Baloch's Blog

  • Possible ASP.NET 5 (vNext) Deployed Folder Structure(With and Without Source)

     

            Introduction:

     

                       When you work with ASP.NET VNext application then one thing that may come into your mind is how your folder structure will be look like if you deploy your application with or without source. In this article, I will tell you how your folder structure may look like if you deploy your application with packages or with source. Note that ASP.NET VNext still is in pre-release, so things might change when ASP.NET VNext will become RTM.  

     

            Description:

     

                        If you deploy your application then your application might be depend or not depend upon 3rd party packages and/or class libraries(Note ASP.NET VNext will be package dependent instead of assembly dependent). You might also want to deploy your web application as package instead of deploying the source. In any case you always have a root folder(let's say wwwroot). You will keep your bin, scripts, contents, fonts, etc. folders/files inside the wwwroot folder. Your wwwroot/bin folder should also include Microsoft.AspNet.Loader.IIS.dll(Helios) if you are deploying your app in IIS. In addition to wwwroot root folder, there will be always another root folder(let's say approot) which include packages and src folders. You need to keep the packages inside approot/packages folder and code inside approot/src. Let say you have YourSite.Web project (a web application), YourSite.Data and YourSite.Bussiness projects (class libraries) and Elmah(a third party package). Then the deployed application folder structure with source will look like,

      

            
    	wwwroot/bin/Microsoft.AspNet.Loader.IIS.dll
    	wwwroot/Contents/site.css
    	wwwroot/Contents/.......................................
    	........................................................
    	wwwroot/Scripts/jquery.js
    	wwwroot/Scripts/........................................
    	........................................................
    	........................................................
    
    	approot/src/YourSite.Web/project.json
    	approot/src/YourSite.Web/...............................
    	approot/src/YourSite.Data/project.json
    	approot/src/YourSite.Data/..............................
    	approot/src/YourSite.Bussiness/project.json
    	approot/src/YourSite.Bussiness/.........................
    	approot/packages/Elmah/{version}/.......................
    	........................................................
    

     

                        If you deploy/pack without source then the deployed folder structure will look like,

     

            
    	wwwroot/bin/Microsoft.AspNet.Loader.IIS.dll
    	wwwroot/Contents/site.css
    	wwwroot/Contents/.......................................
    	........................................................
    	wwwroot/Scripts/jquery.js
    	wwwroot/Scripts/........................................
    	........................................................
    	........................................................
    
    	approot/packages/YourSite.Web/{version}/................
    	approot/packages/YourSite.Data/{version}/...............
    	approot/packages/YourSite.Bussiness/{version}/..........
    	approot/packages/Elmah/{version}/.......................
    

                        

                                           

            Summary:

     

                        In this article I showed you how to deploy the ASP.NET VNext application using source and packages. You can check this link if you need more information.

    Read more...

  • ValidateAntiForgeryTokenAttribute and Ajax Requests

            Introduction:

                       Cross-Site Request Forgery (CSRF or XSRF) is still in the top ten list of The Open Web Application Security Project (OWASP). Fortunately, ASP.NET MVC has built-in support to mitigate this attack since its earlier versions. The default ASP.NET MVC template include code to mitigate this attack. But if you are using ajax requests then you need to keep some points in your mind. In this article, I will tell you some tips that will help you when you are doing CSRF protection in your ajax requests.

            Description:

     

     

                        First tip is that when you send an ajax request to server then you need to explicitly attach anti-forgery token with your request. Let say you have this form in your ASP.NET MVC view,

            
        @using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { }))
        {
             @Html.AntiForgeryToken()
             .......................
             .......................
    

                        Then you can easily include/attach the request anti-forgery token with your ajax request using these lines of javascript(assuming that you are using jQuery),

            
        function appendAntiXsrfToken(data) {
            if (data instanceof Array) {
                data.push({ name: "__RequestVerificationToken", value: $('input[name=__RequestVerificationToken]').val() });
            } else {
                data.__RequestVerificationToken = $('input[name=__RequestVerificationToken]').val();
            }
        };
        .................................................
        appendAntiXsrfToken(data);
        $.ajax({
            type: 'POST',
            url: uri,
            data: data,
        })
    

                        Note that I am appending anti-forgery token to data before sending ajax request. The data can be object or array. The function will automatically handle this. 

                        On the server side, if you are using ajax then most of the time you need to send the anti-fogery exception type response in JSON format. You can handle this situation in a custom exception filter or in your BaseController.OnException method. Here is an example(you can change the JSON if you need different response), 

        
            protected override void OnException(ExceptionContext filterContext)
            {
                if (filterContext.ExceptionHandled || !Request.IsAjaxRequest() || !(filterContext.exception is HttpAntiForgeryException))
                {
                    base.OnException(filterContext);
                    return;
                }
                filterContext.ExceptionHandled = true;
                filterContext.Result = new JsonResult
                {
                    Data = new { code = 400, message = "Invalid Token" },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
    	}
    

                       You can also put your controller action in try/catch block and invoke AntiForgery.Validate explicitly.

                        On the server side, if you are using ajax then most of the time you need to send the anti-fogery exception type response in JSON format. You can handle this situation in a custom exception filter or in your BaseController.OnException method. Here is an example(you can change the JSON if you need different response), 

                       

            Summary:

                        Using ValidateAntiForgeryTokenAttribute with ajax requests, you might find some problems. In this article, I showed you some tips about using ASP.NET MVC ValidateAntiForgeryTokenAttribute with ajax requests.

    Read more...

  • A simple Bootstrap Pager Html Helper

            Introduction:


                       In ASP.NET MVC 5, MVC project templates uses Bootstrap 3.0 user interface framework. It makes the user interface sleek and responsive look. Bootstrap 3.0 also have nice pagination support. In this article, I will show you how to create a simple html helper which will generate Bootstrap 3.0 pagination specific markup.


            Description:

     

     

                        So, what do we need in this pager html helper? currentPageIndex(the current page number), action(the url pointing to an action), totalItems(total number(count) of items),  pageSize(items per page) and numberOfLinks(number of links in a page, for example if numberOfLinks = 5 then it will generate 1 2 3 4 5)


            
        namespace Shopex.Web.HtmlHelpers
        {
            public static class HtmlHelperExtensions
            {
                public static MvcHtmlString BootstrapPager(this HtmlHelper helper, int currentPageIndex, Func<int, string> action, int totalItems, int pageSize = 10, int numberOfLinks = 5)
                {
                    if (totalItems <= 0)
                    {
                        return MvcHtmlString.Empty;
                    }
                    var totalPages = (int)Math.Ceiling(totalItems / (double)pageSize);
                    var lastPageNumber = (int)Math.Ceiling((double)currentPageIndex / numberOfLinks) * numberOfLinks;
                    var firstPageNumber = lastPageNumber - (numberOfLinks - 1);
                    var hasPreviousPage = currentPageIndex > 1;
                    var hasNextPage = currentPageIndex < totalPages;
                    if (lastPageNumber > totalPages)
                    {
                        lastPageNumber = totalPages;
                    }
                    var ul = new TagBuilder("ul");
                    ul.AddCssClass("pagination");
                    ul.InnerHtml += AddLink(1, action,  currentPageIndex == 1, "disabled", "<<", "First Page");
                    ul.InnerHtml += AddLink(currentPageIndex - 1, action, !hasPreviousPage, "disabled", "<", "Previous Page");
                    for (int i = firstPageNumber; i <= lastPageNumber; i++)
                    {
                        ul.InnerHtml += AddLink(i, action, i == currentPageIndex, "active", i.ToString(), i.ToString());
                    }
                    ul.InnerHtml += AddLink(currentPageIndex + 1, action, !hasNextPage, "disabled", ">", "Next Page");
                    ul.InnerHtml += AddLink(totalPages, action, currentPageIndex == totalPages, "disabled", ">>", "Last Page");
                    return MvcHtmlString.Create(ul.ToString());
                }
    
                private static TagBuilder AddLink(int index, Func<int, string> action, bool condition, string classToAdd, string linkText, string tooltip)
                {
                    var li = new TagBuilder("li");
                    li.MergeAttribute("title", tooltip);
                    if (condition)
                    {
                        li.AddCssClass(classToAdd);
                    }
                    var a = new TagBuilder("a");
                    a.MergeAttribute("href", !condition ? action(index) : "javascript:");
                    a.SetInnerText(linkText);
                    li.InnerHtml = a.ToString();
                    return li;
                }
            }
        }
    

                        Now you can use this html helper in your view,


        
        @using HtmlHelpers
    
        @Html.BootstrapPager(pageIndex, index => Url.Action("Index", "Product", new { pageIndex = index }), Model.TotalCount, numberOfLinks: 10)
    


                       

            Summary:


                        Most applications requires some sort of nice and clean pagination. Bootstrap 3.0 have nice pagination support. In this article, I showed you how to create a simple html helper which generate Bootstrap 3.0 pagination specific markup.



    Read more...

  • Forcing Visual Studio 2013 to use ASP.NET MVC 5.1, ASP.NET Web API 2.1 and ASP.NET Web Pages 3.1

            Introduction:



                       DISCLAIMER: This was done completely for my own benefit, but I thought this might be useful to others, so I am sharing my work with you. But please backup your files before replacing.

                        A few days ago, Microsoft announced the release of ASP.NET MVC 5.1, ASP.NET Web API 2.1 and ASP.NET Web Pages 3.1 and Visual Studio 2013 Update 1. We can now create ASP.NET MVC 5.1, ASP.NET Web API 2.1 and ASP.NET Web Pages 3.1 application by creating a new web application and update the released NuGet packages(means running Install-Package Microsoft.AspNet.Mvc -Version 5.1.0, Install-Package Microsoft.AspNet.WebApi -Version 5.1.0 and Install-Package Microsoft.AspNet.WebPages -Version 3.1.0). But doing this every time when you create a new web application takes some time and easily forgettable. In this article, I will tell you some quick tips to force Visual Studio 2013 to use the new versions automatically when you create a new web application.  


            Description:

     

     

                        First of all download VS2013TemplatesForMVC5.1WebAPI2.1WebPages3.1. These templates will force Visual Studio 2013 to use MVC 5.1, Web API 2.1, Web Pages 3.1 and Katana(Owin) 2.1. The download zip file includes 3 folders. First, copy/paste the contents of 'C Program Files (x86) Microsoft ASP.NET ASP.NET Web Stack 5 Packages' to C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Stack 5\Packages. Next, copy/paste the contents of 'C Program Files (x86) Microsoft Visual Studio 12.0 Common7 IDE WebTemplates' to C://Program Files (x86)/Microsoft Visual Studio 12.0/Common7/IDE/WebTemplates and finally copy/paste the contents of 'C Program Files (x86) Microsoft Web Tools Packages' to C:\Program Files (x86)\Microsoft Web Tools\Packages. That's it. Now whenever you create a new web application, Visual Studio will use MVC 5.1, Web API 2.1, Web Pages 3.1 and Katana(Owin) 2.1. So, no need to update the NuGet packages.

     

            Summary:


                        Creating a new ASP.NET MVC 5.1, ASP.NET Web API 2.1 and ASP.NET Web Pages 3.1 application might be painful because you need to update the NuGet packages every time you create a new web application. In this article, I showed you how to force Visual Studio 2013 to use the new versions automatically when you create new web application. Hopefully you enjoyed my this article too.



    Read more...