Sunday, November 18, 2012

How to update web.config in Web Setup Project

The Web Setup Project is the window installer that allow user to run the setup file and steps through a wizard to install the web application or web site so that the files for a Web Setup Projects are installed into a Virtual Root directory on Web servers.
To deploy a Web application to a Web server, it is easy to create a Web Setup project, build it, copy it to the Web server , and run the installer to install the application on the server using the settings defined in your Web Setup project. Let's start here step by step.

I assume that you have one solution project and one web application already.Let's say, web.config for Web Application look like as below:
<connectionStrings>
    -----
    <add name="NorthwindEntities"
         connectionString="metadata=res://*/NorthwindModel.csdl|res://*/NorthwindModel.ssdl|res://*/NorthwindModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=[ServerName];Initial Catalog=[DBName];Persist Security Info=True;User ID=[UserName];Password=[Password];MultipleActiveResultSets=True&quot;"
         providerName="System.Data.EntityClient" />
</connectionStrings>
<system.serviceModel>
    -----
    <client>
      <endpoint address="http://localhost:3961/Service1.svc" binding="basicHttpBinding"
       bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference.IService1"
       name="BasicHttpBinding_IService1" />
      <endpoint address="http://localhost:3961/Service1.svc" binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IService11" contract="ServiceReference2.IService1"
        name="BasicHttpBinding_IService11" />
    </client>
</system.serviceModel>
Web Setup Installer will update the above configuration section during installation.

First, create a new web setup project
  1. On the File menu, point to Add Project, and then click New Project.
  2. In the resulting Add New Project dialog box, select the Setup and Deployment Projects folder.
  3. Choose Web Setup Project and type WebAppSetup in the Name box as below:

Second, create an installer class for custom action
  1. On the File menu, click New Project.
  2. In the New Project dialog box, select Visual C# Projects in the Project Type pane, and then choose Class Library in the Templates pane. In the Name box, type UpdateWebconfig.
  3. On the Project menu, click Add New Item.
  4. In the Add New Item dialog box, choose Installer Class. In the Name box, type Installer1.cs.
In Installer1.cs, it needs the following namespace for web configuration and virtual directory.


Develop the "Installer1.cs" as show below:
using System;
using System.Configuration;
using System.Configuration.Install;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.DirectoryServices;
using System.Web.Configuration;
using System.Windows.Forms;
using System.Collections;
using System.ServiceModel.Configuration;
namespace UpdatingWebconfig
{
    [RunInstaller(true)]
    public partial class Installer1 : System.Configuration.Install.Installer
    {
        public Installer1()
        {
            InitializeComponent();
        }
        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);
            try
            {
                // Retrieve configuration settings           
                string targetSite = Context.Parameters["targetsite"];
                string targetVDir = Context.Parameters["targetvdir"];
                string targetDirectory = Context.Parameters["targetdir"];
                string serverName = Context.Parameters["serverName"];
                string dbName = Context.Parameters["databaseName"];
                string userName = Context.Parameters["userName"];
                string password = Context.Parameters["password"];
                string serviceUrl1 = Context.Parameters["serviceUrl1"];
                string serviceUrl2 = Context.Parameters["serviceUrl2"];
                if (serverName.Length < 1)
                    throw new InstallException("Please provide server name!");
                if (targetSite == null)
                    throw new InstallException("IIS Site Name Not Specified!");
                if (targetSite.StartsWith("/LM/"))
                    targetSite = targetSite.Substring(4);
              
                // Retrieve "Friendly Site Name" from IIS for TargetSite
                DirectoryEntry entry = new DirectoryEntry("IIS://LocalHost/" + targetSite);
                string friendlySiteName = entry.Properties["ServerComment"].Value.ToString();
                // Open Application's Web.Config           
                Configuration config = WebConfigurationManager.OpenWebConfiguration("/" + targetVDir, friendlySiteName);
                UpdateConnectionString(serverName, dbName, userName, password, config);
                UpdateEndPoint(serviceUrl1, serviceUrl2, config);
                // Persist web.config settings           
                config.Save();
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
                if (ex.InnerException != null)
                    msg = ex.InnerException.ToString();
                MessageBox.Show(msg);
            }

        }
        //Method to update the connectionstring to your web.config:
        private static void UpdateConnectionString(string serverName, string dbName,
            string userName, string password, Configuration config)
        {
            ConnectionStringSettingsCollection settings = config.ConnectionStrings.ConnectionStrings;
            ConnectionStringSettings connSetting = settings["NorthwindEntities"];
            if (connSetting != null)
            {
                string strConn = connSetting.ConnectionString;
                strConn = strConn.Replace("[ServerName]", serverName);
                strConn = strConn.Replace("[DBName]", dbName);
                strConn = strConn.Replace("[UserName]", userName);
                strConn = strConn.Replace("[Password]", password);
                connSetting.ConnectionString = strConn;
            } 
        }
        //Method to update the endpoints to your web.config:
        private static void UpdateEndPoint(string serviceUrl1, string serviceUrl2, Configuration config)
        {
            ClientSection clientSection = config.GetSection("system.serviceModel/client") as ClientSection;
            Uri uriOutput;
            foreach (ChannelEndpointElement endpoint in clientSection.Endpoints)
            {
                switch (endpoint.Name)
                {
                    case "BasicHttpBinding_IService1":
                        {
                            if (Uri.TryCreate(serviceUrl1, UriKind.RelativeOrAbsolute, out uriOutput))
                                endpoint.Address = uriOutput;

                        }
                        break;
                    case "BasicHttpBinding_IService11":
                        {
                            if (Uri.TryCreate(serviceUrl2, UriKind.RelativeOrAbsolute, out uriOutput))
                                endpoint.Address = uriOutput;

                        }
                        break;
                }
            }
        }
    }
}
That's it for class library.
Go WebAppSetup project and add Project Output by right click on project > Add > Project Output.


In the Add Project Output Group dialog box, select Primary output and Content Files for the WebApp project as below:

Go File System Editor by right click on msi project > View > File System.
In the File System Editor, select the Web Application Folder. On the Action menu, click Add, and then click Project Output as follow:
  

In the Add Project Output Group dialog box, select Primary output for the UpdateWebconfig project as below:

Now, we create custom UI dialog for accepting user input such as db connection info and WCF url. Go User Interface Editor by right click on msi project > View > User Interface.

In the User Interface Editor, select Start node under Install. On the Action menu, choose Add Dialog.
In the Add Dialog dialog box, select the Textboxes (A) dialog, then click OK.
On the Action menu, choose Move Up. Repeat until the Textboxes (A) dialog is above the Installation Folder node and changes its Properties as below:
See Database Connection Dialog in wizard step
For Textboxes (B), do the same way like above setps.
See WCF Information Dialog in wizard step

Go Custom Actions Editor by right click on msi project > View > Custom Actions.
There are four folders named Install, Commit, Rollback, Uninstall. We need to add custom action for Install folder. Right click on Install folder, select Add Custom Action as below:

In Select Item in Project dialog, Click Web Application Folder to get in. Select Primary output from UpdateWebconfig (Active) and click OK.

You will see Primary output from UpdateWebconfig (Active) section under the Install folder and change CustomActionData property to the following string:
/targetdir="[TARGETDIR]\" /targetvdir="[TARGETVDIR]" /targetsite="[TARGETSITE]" /serverName="[SERVERNAME]" /databaseName="[DBNAME]" /userName="[USERNAME]" /password="[PASSWORD]" /serviceUrl1="[WCF1]" /serviceUrl2="[WCF2]" 

Now, you have finished Web Setup Project and build it. To test it, we can right-click on the web setup project within the solution explorer and select the “Install” menu and follow by wizard as below:


Database Connection Dialog

WCF Information Dialog



Note : If your project is Web Site, this Web Setup Project install the web application on target server including source files (.cs files). If you may want to just deploy your pre-compiled application to the server, you need to create Web Deployment Project for MSI installer package. I hope this article is useful for this case.

26 comments:

  1. Hi,
    thanks for this tuto.
    I have question about URL,
    I work with "webHttpBinding" => service WCF

    ReplyDelete
  2. Nice article. It is very useful..

    ReplyDelete
  3. That's amazing, completely fulfil my requirement

    ReplyDelete
  4. The server using the settings defined in your Web Setup project. Let's start here step by step.learn web deisgn

    ReplyDelete
  5. Reading something so beautiful has a healing power for the soul.
    responsive wordpress website

    ReplyDelete
  6. This is an awesome post. Really very informative and creative contents. This concept is a good way to enhance knowledge. I like it and help me to development very well. Thank you for this brief explanation and very nice information. Well, got good knowledge.
    WordPress development company in Chennai

    ReplyDelete
  7. This is exciting, nevertheless it is vital for you to visit this specific url:
    mason soiza

    ReplyDelete
  8. Fascinatingly composed,Totally in wonder of the article.
    mason soiza

    ReplyDelete
  9. Indeed, even the words like engaging and dazzling can't do full value concerning depicting this blog.
    Mason Soiza

    ReplyDelete
  10. Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place..
    Mason Soiza

    ReplyDelete
  11. A web site is your internet address which aids you reach customers in every corner of earth, no matter which corner you're sitting in. In different cases you may employ your website for a lead generation tool where you don't conduct financial transactions online. maketavimo paslaugos

    ReplyDelete
  12. In this article I will reveal 10 tips to choose the right development company and how it will better your project's success.
    https://medijo.lt/skrajutes/

    ReplyDelete
  13. I wanted to thanks for this notable proper to apply!! I really loved all tiny little bit of it. I have you bookmarked your web site to test out the introduced belongings you pronounce. Web Design Company

    ReplyDelete
  14. HI, Have some problem with custom action, I need create another TARGETSITE, not using the combo Box, I using a Text Box, in my installer class a create new Web Site, but when install in completed, I have installed the Web Page in Default Web Page and the new that I create, how can solve that?? please help!!!

    ReplyDelete
  15. Web templates are semi completed as in they are not prepared to transfer as they seem to be. You have to add certain components to make them look total. A portion of the fundamental components that you have to include incorporate
    Jekyllup

    ReplyDelete
  16. You make so many great points here that I read your article a couple of times. Your views are in accordance with my own for the most part. This is great content for your readers. Visit website

    ReplyDelete
  17. Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. Webdesign

    ReplyDelete
  18. Love to read it,Waiting For More new Update and I Already Read your Recent Post its Great Thanks. Webdesign

    ReplyDelete
  19. Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place.. Webdesign

    ReplyDelete
  20. Webdesigner waar u een professionele en betaalbare website kan laten maken? De nr. 1 webdesigner in Limburg, Antwerpen en Vlaams-Brabant voor SEO websites. Webdesigner

    ReplyDelete
  21. Notwithstanding, the troubles of achieving your objective can be misdirecting. Webdesign

    ReplyDelete
  22. I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people. Webdesign bureau

    ReplyDelete
  23. Your blogs are easily accessible and quite enlightening so keep doing the amazing work guys. Best Web Design Toronto

    ReplyDelete
  24. I would state, you do the genuinely amazing.This substance is made to a wonderful degree well. weebly uk

    ReplyDelete
  25. One of the principle focal points of these courses is that they are composed by masters and along these lines are for the most part destined to be successful for everybody needing to learn through online website composition preparing.
    Web Design Curriculum

    ReplyDelete
  26. This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. peter web designer

    ReplyDelete