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
        {
            get
            {
                if(string.IsNullOrEmpty(_virtualdirectory))
                    return System.Configuration.ConfigurationManager.AppSettings["virtualDirectory"].ToString();
                else
                    return _virtualdirectory;
            }
            set
            {
                _virtualdirectory = value;
            }
        }
        public string bindingvalue { get; set; }
        
        public void AddBinding()
        {
            if(string.IsNullOrEmpty(bindingvalue))
                return;
            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;
                    bindingsCollection.Add(bindingElement);

                    ////ConfigurationElement bindingElement1 = bindingsCollection.CreateElement("binding");
                    ////bindingElement1["protocol"] = @"https";
                    ////bindingElement1["bindingInformation"] = @"*:443:";
                    ////bindingsCollection.Add(bindingElement1);

                    serverManager.CommitChanges();
                }
               
            }

        }
        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;
                    break;
                }
            }
            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;
                            break;
                        }
                    }
                    if (matches)
                    {
                        return element;
                    }
                }
            }
            return null;
        }
    }
}

To use this class we have to add below reference in the project.
Microsoft.Web.Administration;

Below are the code you can use for add binding.

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

Also make sure your application running user have proper access about the process, because this is generally update below sensitive file, and generally normal asp.net 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 asp.net process mean either console or window services.

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

    Thanks,
    Amit Patel
    “Happy Programming”

    About these ads

    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.

    Thanks,
    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

    Upload photo in flickr by asp.net code

    In my applications are providing to facility to share their customer’s images but for that key issue is where those images need to store because generally every host environment have very limited access to update photos.

    Flickr is providing a facility to upload any number of images and providing a link so we can share this link in any where.

    Below are the steps for that.

      Need to create a app in flicker and generate app key from below link

    http://www.flickr.com/services/apps/create/

    Once you will create app that will returns you below key

      Api key
      Api secrete key
      Then you can use that key in below code
    Flickr flickr = new Flickr(ConfigurationManager.AppSettings["apiKey"],
                   ConfigurationManager.AppSettings["shardSecret"]);
             
    flickr.OAuthAccessTokenSecret = "b149b2e96eb8072a";
    flickr.OAuthAccessToken = "72157631518163710-91816d732ba5f46c";
    string FileuploadedID = flickr.UploadPicture(@"E:\Documents\TweetingRoom\Logo\Main-screen.jpg", "TwittingRoom", "TwittingRoom Image", "ClientName", true, false, false);
    PhotoInfo oPhotoInfo = flickr.PhotosGetInfo(FileuploadedID);
    string FileULR = oPhotoInfo.LargeUrl;
    Response.Write(FileULR);
    

    In this code I have stored api key and api secrete key in web.config file.
    Also for upload file user first need to get access token key and access token secrete key so for that you need to

    Flickr f = new Flickr(ConfigurationManager.AppSettings["apiKey"],
                   ConfigurationManager.AppSettings["shardSecret"]);
                OAuthRequestToken requestToken = f.OAuthGetRequestToken("oob");
                string url = f.OAuthCalculateAuthorizationUrl(requestToken.Token, AuthLevel.Write);
    

    So it will show on request token and use that token in below code:

    OAuthRequestToken requestToken = f.OAuthGetRequestToken("oob");
    var accessToken = f.OAuthGetAccessToken(requestToken, VerifierTextBox.Text);
    

    In accessToken this object user can get access token and access token secrete key.

    So now you can use this access token and token screate key to upload file on above provided code and that will returns you url, thumbnail url and flickr page as to show image.

    Thanks,
    Amit Patel
    “Enjoy Programming”

    Bind cascading dropdown by ajax/json in MVC application

    An Asp.net MVC developer can use this code to bind cascading drop down by ajax/json . Let’s say we have country drop down. When user selects country, states of selected country will be filled by json. (See below image)

    Dropdown fill by json

    First dropdown bind by retaining view bag by controller and for second drop down we can use JavaScript/Jquery to fill value based on selected country.

    Below code used on cshtml page:

    <div class="editor-label">
                    @Html.LabelFor(m => m.Country)
                </div>
                <div class="editor-field">
                  @Html.DropDownListFor(model => model.Country, new SelectList(Model.Country, "Value", "Text"), "Select Contry", new { onchange = "CountryChange()" })                                                                                                                   
                </div>
    
                <div class="editor-label">
                    @Html.LabelFor(m => m.State)
                </div>
                <div class="editor-field">
                    @Html.DropDownList("state","Select State")
                </div>
    

    We have used “CountryChange()” javascript function to fetch and fill data in state dropdown based on country change. Below is the JavaScript function implementation.

    <script language="JavaScript" type="text/JavaScript">
        function CountryChange () {
            var url = '@Url.Content("~/Account/GetState")';
    
            var ddlsource = "#Country";
            var ddltarget = "#State";
    
            if ($(ddlsource).val() != "") {
                $.ajaxSetup({ cache: false });
                $.getJSON(url, { Sel_Country: $(ddlsource).val() }, function (data) {
    
                    $(ddltarget).empty();
    
                    $("#State").append("<option  value=''>Select State</option>");
    
                    $.each(data, function (index, optionData) {
                        $("#State").append("<option value='" + optionData.Value + "'>" + optionData.Text + "</option>");
                    });
                });
            }
            else {
                $("#State").empty();
                $("#State").append("<option value=''>Select State</option>");
            }
        }
    </script>
    

    Here json url specified “~/Account/GetState” is method “GetState” available in “Account” controller to retrieve data and pass data in json format.

    public JsonResult GetState (string Sel_Country)
            {
    
                CountryService db = new CountryService ();
                JsonResult result = new JsonResult();
                var vStateList = db.GetStateList(Convert.ToInt64(Sel_Country));
                result.Data = vStateList.ToList();
                result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                return result;
            }
    

    Based on this approach developer can fill dropdown or fetch any kind of server side data and fill in the page by Jquery without postback.

    Feel free to write your questions in comments.

    Enjoy Programming!!
    Amit Patel

    In MVC controller returns rendered html

    In MVC development sometime developers need to get rendered html code from controller’s action method. In my one of the requirement I am updating page’s specific portion by java script by json method, so I am updating returned html in related tag by jquery.

    Below are the code and description of the solution.

    In Below action method is about for refresh page’s section and return new updated HTML.

    public JsonResult RefreshPage(string SectionID)
    {
       JsonResult result = new JsonResult();
       // My bussiness logic to get data
       string StrReturn = RenderViewToString("HomePage", oTS.Data, this.ControllerContext);
       result.Data = StrReturn.ToString();
       result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
       return result;
    }
    

    In this method We have used RenderViewToString method to get rendered html, here “HomePage” is my partial view for this which is actual bind oTS.Data data and generate html.

    Below is the method for RenderViewToString

    public string RenderViewToString(string viewPath, object model, ControllerContext context)
    {
           var viewEngineResult = ViewEngines.Engines.FindPartialView(context, viewPath);
           var view = viewEngineResult.View;
           context.Controller.ViewData.Model = model;
           string result = String.Empty;
           using (var sw = new StringWriter())
           {
               var ctx = new ViewContext(context, view,
                                         context.Controller.ViewData,
                                         context.Controller.TempData,
                                         sw);
               view.Render(ctx, sw);
               result = sw.ToString();
           }
           return result;
    }
    

    So in this way we can return html. and that html will be used by below jquery method by json.

     function RefreshPage() {
            var hiddenID = $('#hdTDetailsID').val();
            var url = '@Url.Content("~/page/RefreshPage")';
            $.ajaxSetup
            (
                {
                    cache: false
                }
            );
            $.getJSON(url,
             {
                 Sel_TDetailID: hiddenID
             },
            function (data) {
                $(divname).html(data);
            });
        }
    

    In this way we can refresh page’s any of the portion’s data by jquery in MVC. There are other various ways to do it but when you append some data in current data then this approach is useful.

    Feel free to write me in case of any question or need more details on this.

    Thanks,
    Amit Patel
    “Enjoy Programming”

    Fetch list of property name and value from any object

    In any of the scenario where we have to wrote a common function where we can use any of the object type but all have set of common property so we need to fetch those properties.

    In one of the my scenario where I am creating common data log function where what ever object I pass to this function and that function is saving all properties value in database log table with property and value.
    This kind of logic we can say as reflation. Below is the sample code for this.

    public void GetPropertiesFromObject(object oObject)
            {
                foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(oObject))
                {
                    string name = descriptor.Name;
                    string value = "";
                    if (descriptor.GetValue(oObject) != null)
                    {
                        value = descriptor.GetValue(oObject).ToString();
                    }
                    //use this name and value
                    if (descriptor.Attributes[4].GetType().Name == "DataMemberAttribute")
                    {
                        this.InsertRequesObjectParameter(this.ID, name, value, false, 1);
                    }
                }
            }
    

    To run this code need to use below namespace
    System.ComponentModel;

    We can get all other attributes and function name as well as by this also we can able to call function as well.

    Thanks,
    Amit Patel
    “Enjoy Programming”
    amitpatel.it@gmail.com

    Follow

    Get every new post delivered to your Inbox.

    Join 214 other followers