Export to Excel in asp.net MVC

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

Detail
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
                             {
                                e.firstname,
                                e.lastname,
                                e.emailid,
                                e.addresss
                             };

            System.Web.UI.WebControls.GridView gridvw = new System.Web.UI.WebControls.GridView();
            gridvw.DataSource = employeeDetail.ToList().Take(7); //bind the datatable to the gridview
            gridvw.DataBind();
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment;filename=employeeDetail.xls");
            Response.ContentType = "application/excel";
            StringWriter swr = new StringWriter();
            HtmlTextWriter tw = new HtmlTextWriter(swr);
            gridvw.RenderControl(tw);
            Response.Write(swr.ToString());

            Response.End();
            return View("About", employeeDetail);
        }

Please post a comment if you have any more questions.

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

    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”

    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

    Convert PowerPoint to HTML

    Hello friends,

    This post is explain about how to convert ppt file in html pages by asp.net application. A requirement comes like when user will provide ppt with attached set of images and asp.net application needs to convert it in html pages where images needs to find from ppt and save in one folder and attached with html pages, so html page desing looks like same as ppt.

    To implement this I have used MS office atomization tool (DCOM). I have added below dll from .net references.
    Microsfot.Office.Core
    Microsfot.Office.Interop.PowerPoint

    In MS Power Point has inbuild functionality available to : File> Save as Web Pages. So I have used the same functionality by .net code from Powerpoint compenent.

    Below are the code I have implemented to achieve this.

    string strSourceFile = @"D:\PPT_Presentation.pptx";
                //Give the name and path of the HTML file to be generated
                string strDestinationFile = @"D:\HTML_Presentation.htm";
                //Create a PowerPoint Application Object
    
                Microsoft.Office.Interop.PowerPoint.Application oApplication = new Microsoft.Office.Interop.PowerPoint.Application();
    
                //Create a PowerPoint Presentation object
    
                Microsoft.Office.Interop.PowerPoint.Presentation oPresentation = oApplication.Presentations.Open(strSourceFile);
                //Call the SaveAs method of Presentaion object and specify the format as HTML
                oPresentation.SaveAs(strDestinationFile, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsHTML);
    
                //Close the Presentation object
                oPresentation.Close();
                //Close the Application object
                oApplication.Quit();
    
    

    So once you will run the application there will be one html file created which you provided as destination file and one folder created with same name at same location with all required supported files.

    Requirement to run this code:
    Microsoft office should be installed on the system
    Microsoft office Power Point DCOM configured with application user with proper access.

    Note: Use direct component is not suggested by Microsoft, due to performance and reliability issue.
    http://support.microsoft.com/kb/257757/en-us
    So to achieve this scenario Microsoft suggests Office open xml format.
    http://msdn.microsoft.com/en-us/library/bb332059(v=office.12).aspx

    Please contact me at amitpatel.it@gmail.com for more any other information.

    Thanks,
    Amit Patel
    “Enjoy Programming”

    Embed images in email by dynamic template

    In general .net mail sending we are using image as url but this is not good if image is delete from server and path as been changed then our email comes with image not found.
    So to avoid this we can embed image with email and then create cid and that cid we can use anywhere in email by image tag.

    But if we have used email template and used images on that template then how can we handle, by generic class.
    So for solution of this is that we can create add predefine image tags in email template and that will be passed by image class as below.

    public class EmbedImages
        {
            public EmbedImages(string _ImagePlaceHolde, string _ImagePath, string _width, string _height)
            {
                this.ImagePlaceHolde = _ImagePlaceHolde;
                this.ImagePath = _ImagePath;
                this.width = _width;
                this.height = _height;
            }
            public string ImagePlaceHolde { get; set; }
            public string ImagePath { get; set; }
            public string width { get; set; }
            public string height { get; set; }
        }
    

    This List of object of “EmbedImages” will be used in email send mail class where we are fetching the value and preparing image tag and replacing.

    Actually we need to put any of the placeholder in email template and that will be replace by image tag.
    As per below logic by embedding images.

     if (this.ImageParamers != null && this.ImageParamers.Count > 0)
     {
                        AlternateView View;
                        LinkedResource resource;
                        View = AlternateView.CreateAlternateViewFromString(message.Body, null, "text/html");
                        foreach (EmbedImages item in this.ImageParamers)
                        {
                            resource = new LinkedResource(item.ImagePath);
                            resource.ContentId = item.ImagePlaceHolde;
                            View.LinkedResources.Add(resource);
                            string ImageTag = "<img src=cid:" + item.ImagePlaceHolde + "width='" + item.width + "' and height='" + item.height + "px'/></p>";
                            message.Body = message.Body.Replace(item.ImagePlaceHolde, ImageTag);
                        }                    
                        message.AlternateViews.Add(View);
      }
    

    We can actually fit this login in our common class for send an email with all other facilities.

    public class SentMail
        {
            public SentMail()
            {
    
            }
            private string _SMTPAddress;
            public string SMTPAddress 
            {
                get
                {
                    if(string.IsNullOrEmpty(_SMTPAddress))
                        return ConfigurationManager.AppSettings["SMTPSERVER"].ToString();
                    else
                        return _SMTPAddress;
                }
                set
                {
                    _SMTPAddress = value;
                }
            }
            public bool isMailSent {get;set;}
            private string _FromDisplayName;
            public string FromDisplayName
            {
                get
                {
                    if (string.IsNullOrEmpty(_FromDisplayName))
                        return ConfigurationManager.AppSettings["FROMDISPLAY"].ToString();
                    else
                        return _FromDisplayName;
                }
                set
                {
                    _FromDisplayName = value;
                }
            }
            private string _FromAddress;
            public string FromAddress
            {
                get
                {
                    if (string.IsNullOrEmpty(_FromAddress))
                        return ConfigurationManager.AppSettings["FROMADDRESS"].ToString();
                    else
                        return _FromAddress;
                }
                set
                {
                    _FromAddress = value;
                }
            }
            /// <summary>
            /// To Address if multiple then add ; in between each address
            /// </summary>
            public string ToDisplayName { get; set; }
            public string ToAddress { get; set; }
            /// <summary>
            /// CC Address if multiple then add ; in between each address
            /// </summary>
            public string CCAddress { get; set; }
            /// <summary>
            /// BCC Address if multiple then add ; in between each address
            /// </summary>
            public string BCCAddress { get; set; }
            public string Body { get; set; }
            public string Subject { get; set; }
            public List<string> SubjectParameter { get; set; }
            public List<string> Attachment { get; set; }
            public bool HighPriority { get; set; }
            public List<string> DynamicParameter { get; set; }
            public string TemplateFile { get; set; }
            public List ImageParamers { get; set; }
    
            public bool Sent()
            {
                bool bReturn = true;
                try
                {
                    string user = System.Configuration.ConfigurationManager.AppSettings["SMTP_USERNAME"];
                    string pass = System.Configuration.ConfigurationManager.AppSettings["SMTP_PASSWORD"];
    
                    SmtpClient oSMTLClient = new SmtpClient();
                    oSMTLClient.Host = this.SMTPAddress;
                    
                    oSMTLClient.Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SMTP_PORT"]);
                    oSMTLClient.UseDefaultCredentials = false;
                    oSMTLClient.Credentials = new System.Net.NetworkCredential(user, pass);
                    oSMTLClient.DeliveryMethod = SmtpDeliveryMethod.Network;
    
    
                    MailMessage message = new MailMessage();
                    message.From = new MailAddress(this.FromAddress, this.FromDisplayName);
                    if (!string.IsNullOrEmpty(this.ToAddress))
                    {
                        string[] ToAddress = this.ToAddress.Trim().Split(";".ToCharArray());
                        foreach (string itemTo in ToAddress)
                        {
                            message.To.Add(itemTo);
                        }
                    }
                    // CC address
                    if (!string.IsNullOrEmpty(this.CCAddress))
                    {
                        string[] CCAddress = this.CCAddress.Trim().Split(";".ToCharArray());
                        foreach (string itemCC in CCAddress)
                        {
                            message.CC.Add(itemCC);
                        }
                    }
                    
                    // BCC address
                    if (!string.IsNullOrEmpty(this.BCCAddress))
                    {
                        string[] BCCAddress = this.BCCAddress.Trim().Split(";".ToCharArray());
                        foreach (string itemBCC in BCCAddress)
                        {
                            message.Bcc.Add(itemBCC);
                        }
                    }
    
                    if (this.DynamicParameter != null && DynamicParameter.Count > 0)
                        message.Body = string.Format(this.MailBodystring(), this.DynamicParameter.ToArray());
                    else
                        message.Body = this.MailBodystring();
                    
                    
                    message.IsBodyHtml=true;
                    if (this.HighPriority)
                    {
                        message.Priority = MailPriority.High;
                    }
    
                    if (this.Attachment != null && this.Attachment.Count > 0)
                    {
                        
                        foreach (string itemAttachFile in this.Attachment)
    	                {
                            System.Net.Mail.Attachment oAttachment = new Attachment(itemAttachFile);
                            message.Attachments.Add(oAttachment);
    	                }
    
                        
                    }
                    if (this.SubjectParameter != null && SubjectParameter.Count > 0)
                        message.Subject = string.Format(this.Subject, this.SubjectParameter.ToArray());
                    else
                        message.Subject = this.Subject;
                    //oSMTLClient.SendCompleted += SendCompletedCallback;
                    if (this.ImageParamers != null && this.ImageParamers.Count > 0)
                    {
                        AlternateView View;
                        LinkedResource resource;
                        View = AlternateView.CreateAlternateViewFromString(message.Body, null, "text/html");
                        foreach (EmbedImages item in this.ImageParamers)
                        {
                            resource = new LinkedResource(item.ImagePath);
                            resource.ContentId = item.ImagePlaceHolde;
                            View.LinkedResources.Add(resource);
                            string ImageTag = "<img src=cid:" + item.ImagePlaceHolde + "width='" + item.width + "' and height='" + item.height + "px'/></p>";
                            message.Body = message.Body.Replace(item.ImagePlaceHolde, ImageTag);
                        }                    
                        message.AlternateViews.Add(View);
                    }
    
    
                    
                    var userState = message;
                    oSMTLClient.Send(message);
    
                    bReturn = true;
                }
                catch (Exception ex)
                {
                    bReturn = false;
                }
    
                return bReturn;
               
                //message.CC = this.CCAddress
    
            }
            private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
            {
                this.isMailSent=true;
            }
            private string MailBodystring()
            {
                string MailBody = "";
                if (File.Exists(this.TemplateFile))
                {
                    StreamReader SR = new StreamReader(this.TemplateFile);
                    MailBody = SR.ReadToEnd();
                    SR.Close();
                    SR.Dispose();
                }
                return MailBody;
            }
        }
    

    So now when we want to use this class we use by below way.

    
     SentMail oMail = new SentMail();
                oMail.DynamicParameter = new List<string> { "Amit", "Password" };
    
                oMail.HighPriority = false;
                oMail.ToAddress = "amitpatel.it@gmail.com";
                oMail.Subject = "Password change";
    
                oMail.TemplateFile = System.Web.HttpContext.Current.Server.MapPath("~/EmailTemplate/ChangePassord.htm");
    	    List lstImage = new List()
    	    lstImage.add("ComapnyLogo","<path>","100","50") // for dynamic apporach we can fetch this details from database and ser can attach each placeholder in email template by any WYSWYG editor.
    	    oMail.ImageParamers = lstImage
                
                oMail.Sent();
    

    So in this way we can send an email with dynamically embed images.

    Please feel free to contact me for any other assistance at amitpatel.it@gmail.com

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

    Follow

    Get every new post delivered to your Inbox.

    Join 239 other followers