Visual studio 2012 provides a features of the MVC with web api with web services to rest service call.

So when need to create web services we can use this one rather than creating a traditional web services or WCF services.

Below are the process for this to create MVC web api.

  • Select Project with MVC
  • Select Web API Template
  • Web API Template

    Web API Template

  • Then project created with web api template and one default values controller created.
  • In this control you have web method available so we can use this method as web services as rest services.
  • Below are the code.

            // GET api/values
            public IEnumerable<string> GetData()
                return new string[] { "value1", "value2" };

    So once call below url


    It execute GetData and if post request via Post method then it execute Post method. Here we don’t need to set action method.
    If need to use different action method then make below changes in WebApiConfig

                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }

    Change below with action method so we can use different action methods

                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{action}/{{id}",
                    defaults: new { id = RouteParameter.Optional }

    Amit Patel
    “Enjoy Programming”

    Export to Excel in MVC

    In a scenario comes on MVC application comes where user need to export in excel , csv, xml file by MVC application as tabular data.

    So on export button form will be submitted and execute controller’s POST Method.

    So in POST method load all data and export in excel with below code, Also if any filter applied then that filter parameter need pass as parameter in post method and execute data based on that filter to before export in excel.

    public ActionResult ExportData()
                var employeeDetail = from e in DB.employees.AsEnumerable()
                             select new
                System.Web.UI.WebControls.GridView gridvw = new System.Web.UI.WebControls.GridView();
                gridvw.DataSource = employeeDetail.ToList().Take(7); //bind the datatable to the gridview
                Response.AddHeader("content-disposition", "attachment;filename=employeeDetail.xls");
                Response.ContentType = "application/excel";
                StringWriter swr = new StringWriter();
                HtmlTextWriter tw = new HtmlTextWriter(swr);
                return View("About", employeeDetail);

    Please post a comment if you have any more questions.

    Amit Patel
    “Enjoy Programming”

    Use variable in CSS by using SASS

    In General requirement developer needs some changes on every time when they run project in local and publish in server. So each time developer go to the css file and find all the required place and need to change it.

    So SASS is providing very good features for this. So developer need to define variable and that can convert by actuall value in css by ruby compass tool.

    for convert scss to css need to use ruby compass tool so that is convert and create new css with get path from related variable.

    Below are the few example of writing scss.

    Let’s give one real time example for usage of this approach.

    In local server images are load from local path but on live server all static images needs to be load from any different path, hence developer need to change every time when they deploy so here is the problem comes for developer to change lot of place when deploy on server.

    So this problem can be solved by SASS concept. So here developer need to create on scss file based on above link and define variable in sass file and that file automatically convert it in css by ruby compass. So in converted css file path will get from defined variable in SASS file. Below are the some sample code for this.


    $server-path: "";
    body {
      background: #d3d0d1 url($server -path + "/Images/bg.jpg?format=png");


    $server-path: "";
    body {
      background: #d3d0d1 url(" /Images/bg.jpg?format=png");

    So this example can be use full to any web developer who need to define css from any variable.

    As SASS has many more features like below.

    • Nesting
    • Parent References
    • Variables
    • Operations and Functions
    • Interpolation
    • Mixins
    • Arguments
    • Further Reading

    Please post comments if need any more details.

    Amit Patel
    “Enjoy Programming”

    Enter IIS binding entry by C# code

    In many situation required to multiple domain in one web application. A specially for web based content management system.
    So in this kind of application this is very much important to bind each url with IIS binding, so below are the code is help for the IIS binding by c# code by dynamically, so when new sub domain or domain add then code automatically add binding entry in IIS.

    Below are the class for the same…

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Text;
    using Microsoft.Web.Administration;
    namespace HostEntry
        /// <summary>
        /// Summary description for Class1
        /// </summary>
        public class Biding
            public Biding()
            public Biding(string binding)
                this.bindingvalue = binding;
            public Biding(string binding, string virtualdirectory)
                this.bindingvalue = binding;
                this.virtualdirectory = virtualdirectory;
            private string _virtualdirectory;
            public string virtualdirectory
                        return System.Configuration.ConfigurationManager.AppSettings["virtualDirectory"].ToString();
                        return _virtualdirectory;
                    _virtualdirectory = value;
            public string bindingvalue { get; set; }
            public void AddBinding()
                using (ServerManager serverManager = new ServerManager())
                    Configuration config = serverManager.GetApplicationHostConfiguration();
                    ConfigurationSection sitesSection = config.GetSection("system.applicationHost/sites");
                    ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();
                    ConfigurationElement siteElement = FindElement(sitesCollection, "site", "name", this.virtualdirectory);
                    if (siteElement == null) throw new InvalidOperationException("Element not found!");
                    ConfigurationElementCollection bindingsCollection = siteElement.GetCollection("bindings");
                    if (bindingsCollection.Where(q => q.Attributes["bindingInformation"].Value.ToString() == "*:80:" + this.bindingvalue).Count() == 0)
                        ConfigurationElement bindingElement = bindingsCollection.CreateElement("binding");
                        bindingElement["protocol"] = @"http";
                        bindingElement["bindingInformation"] = @"*:80:" + this.bindingvalue;
                        ////ConfigurationElement bindingElement1 = bindingsCollection.CreateElement("binding");
                        ////bindingElement1["protocol"] = @"https";
                        ////bindingElement1["bindingInformation"] = @"*:443:";
            public bool BidningExist(ConfigurationElementCollection bindingsCollection)
                bool isExist = false;
                foreach (ConfigurationElement item in bindingsCollection)
                    if (item != null && item.Attributes["bindingInformation"] != null && item.Attributes["bindingInformation"].Value.ToString() == "*:80:" + this.bindingvalue)
                        isExist = true;
                return isExist;
            private static ConfigurationElement FindElement(ConfigurationElementCollection collection, string elementTagName, params string[] keyValues)
                foreach (ConfigurationElement element in collection)
                    if (String.Equals(element.ElementTagName, elementTagName, StringComparison.OrdinalIgnoreCase))
                        bool matches = true;
                        for (int i = 0; i < keyValues.Length; i += 2)
                            object o = element.GetAttributeValue(keyValues[i]);
                            string value = null;
                            if (o != null)
                                value = o.ToString();
                            if (!String.Equals(value, keyValues[i + 1], StringComparison.OrdinalIgnoreCase))
                                matches = false;
                        if (matches)
                            return element;
                return null;

    To use this class we have to add below reference in the project.

    Below are the code you can use for add binding.

     Biding oBiding = new Biding("<<Site Name>>","<<Virtual directory name>>");

    Also make sure your application running user have proper access about the process, because this is generally update below sensitive file, and generally normal or iss user dont have permission to update this file so either you have to give perimission with this file or run the app with administrator account,

  • C:\Windows\System32\inetsrv\config\administration.config
  • C:\Windows\System32\inetsrv\config\applicationHost.config
  • C:\Windows\System32\inetsrv\config\redirection.config
  • I suggest this kind of application we should run on out the process mean either console or window services.

    Let me know if you need any more details about this.

    Amit Patel
    “Happy Programming”

    Benefits of HTML5 and CSS 3.0

    Most of the web programmer is familiar with hypertext markup language and css. These two language are use full to run layout in browser and easy for search and indexing. But the problem is html is not providing video streaming and rich interface like flash and flex. So HTML 5 has been launched to resolve this problem in html without using any flash or Silverlight component. By using of CSS3 web developer /designer can control web designing process and create attractive user interface.

    Most of the web programmer is familiar with hypertext markup language and css. These two language are use full to run layout in browser and easy for search and indexing. But the problem is html is not providing video streaming and rich interface like flash and flex. So HTML 5 has been launched to resolve this problem in html without using any flash or Silverlight component. By using of CSS3 web developer /designer can control web designing process and create attractive user interface.

    Below are the benefits of HTML5.

    • Video streaming
      • Newer days in a web application to show rich interface, animation, stream video, play musing are needed to use. So that can be possible via flash, Silverlight flex or any JavaScript plugin. But now with the help of HTML5 it is possible to embed video and audio, high quality drawings, charts and animation and many other rich content without using any plugins and third party programming as the functionality is built into the browser.
    • Cleaner markup / Improved Code
      • Web developer/designer can make html code to more clean by replacing general div tag with schematic html5 element.
      • By HTML5, developer can easily distingue html content as header, footer and menus etc by sing of below specific element.
      • <article>, <footer>, <header>, <nav>, <section>
    • Form Validation
      • HTML5 enables designer to use fancier forms. Even it makes form validation native to HTML, User interface enhancements and reduced need for JavaScript (only needed in browsers that don’t support form types). There will be different type of text inputs, search and different fields for different purpose.
    • Offline cache application
      • This is really great feature of html5 cache mechanism, where developer can specify whether this page would be set as cache or not, if developer will set page in cache then that page would be stored in cache. So as results when visitor open that page and then internet disconnected then also that page content would be loaded after refresh the page.
    • Client side database
      • While cookies have been used to track unique user data for years, they have serious disadvantages. The largest flaw is that all of your cookie data is added to every HTTP request header. This can end up having a measurable impact on response time. So a best practice is to reduce cookie size. With HTML5 we can do better by using  sessionStorage and localStorage(two different storage in HTML5) in place of cookies. It is not a permanent database, but enables you to store structured data, temporarily.
    • Provide drag and drop features.
      • Drag and drop is a very common feature. It is when you “grab” an object and drag it to a different location. In HTML5, drag and drop is part of the standard, and any element can be drag gable.
    • Canvas and SVG
      • This is very emphasized feature of HTML 5 to provide rich user interface. Web developer can draw 2d graphic in canvas on the fly. SVG is language for describing 2D graphics in XML. SVG is used for vector based graphics in web. SVG images are scalable, zoom able and can be printed in any of the high quality resolution.
    • Responsive design
      • This very good features by html5 as compare to current market’s demand. In newer day’s visitor is open web site from any of the device, i.e. mobile, notebook or laptop. So that is required to web site should be open in any of the browser by readable content.
    • Locate the User’s Position
      • The HTML5 Geo location API is used to get the geographical position of a user.
      • Since this can compromise user privacy, the position is not available unless the user approves it.

    Below are the benefits of CSS 3.0

    • Border radios
      • Developer can set border radios so set any radios border no need to create round corner image.
    • Border Images
      • This feature will allow developers and designers to take their site to the next level. Developer can be as creative as you want and be able to apply it as a border without extra elements. Quite simple code really:
    • Box Shadow
      • CSS3 allows developer and designer to set shadow in web pages without creating any image.
    • Multiple background
      • CSS3 allows developer to set multiple backgrounds in one web page.
    • Embed font
      • This is really good features, where developer can use any of the font in a web page and embed that font so if font not available on client’s machine then automatically loaded from server.
    • Pages load faster:
      • In HTML design css3 will perform many things so minimize the usage of images in UI layout so it will increase the page load performance.

    Amit Patel
    Enjoy Programming

    Responsive Web Design for all Devices

    In current days visitors are accessing web site by multiple devices, so it is necessary to support web site for multiple device with different screen resolution. Let say web site should be accessible by normal desktop, mobile devices, and tabulates. All this have different screens resolution. Web site should be available with supported to all this devices with proper readable layout format.

    HTML5 and CSS 3.0 are come up with resolution of this problem, where we can create one common web site and that will be loaded in different browser (Devices) with different format.

    Below are the screens which we have opened in different devices with different format

    • Screen for general  desktop

    Large screen

    •  Screen for tablets
    Tablates Screen

    Tablates Screen


    • Mobile Screen
    Mobile Web site screen

    Mobile Web site screen


    We have created same web site which is loading with different style based on selected device’s screen.

    To achieve this solution I have used media query listeners of CSS 3.0.

    Actually there is one Viewport metadata tag controls the logical dimensions and scaling of the mobile browser’s (chrome-less) window. Setting the width equal to the device-width works around the problem:

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    And also in CSS style we have added media object with all screen resolution with font and width allocation based on specified screens.


    Below are the styles for this example.

    @media screen and (max-width: 478px) &nbsp;&nbsp;&nbsp; {
    h1 { font-size: 30px; padding: 1px; }
    h2 { font-size: 1xpx; padding: 1px; }
    body { font-size: 13px; }
    @media screen and (max-width: 740px) &nbsp;&nbsp;&nbsp; 
    .left-col { width: 100%; }
    .sidebar { width: 100%; }
    @media screen and (max-width: 480px) {

    In above code set different font size and padding based for screen 480px width and more than 740px as well as set sidebar width based on screen.
    Other option about responsive design is define two separate css and load css based on screen size selection.

    <link rel="stylesheet" type="text/css" media="screen and (max-device-width: 480px)" href=" media-queries_480.css" />

    Now technology is moving ahead and users are increasing the use of mobile device to accessing internet thus mobile device are necessary to support for each webs site hence responsive design is very important and required for each new upcoming site.
    Add as Comment your questions or feedbacks.

    “Happy Programming”
    Amit Patel


    Get every new post delivered to your Inbox.

    Join 244 other followers