Showing posts with label installer. Show all posts
Showing posts with label installer. Show all posts

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.

Sunday, October 21, 2012

Creating and Restoring SQL Server 2008 Database in Setup project

Windows Installer deployment allows you to create installer packages to be distributed to users; the user runs the setup file and steps through a wizard to install the application. This is done by adding a Setup project to your solution; when built, it creates a setup file that you distribute to users; the user runs the setup file and steps through a wizard to install the application.
There are five types of deployment projects: Merge Module Project, Setup Project, Web Setup Project, and Cab Project. The Setup Wizard is provided to step you through the process of creating deployment projects.This step-by-step article explains how to create a setup package in the Visual Studio .NET development environment for creating database on target server.

I assume that you have one solution project and "Northwind" database backup file already.

First, create a new 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 Setup Project for a standard setup 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 CreatingDB.
  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 Microsoft.SqlServer.Management.Smo namespace contains classes that represent the core SQL Server Database Engine objects that include instances, databases, tables, stored procedures, and views. You will have to import the following four files to access all of the classes in the Microsoft.SqlServer.Management.Smo namespace.
  •     Microsoft.SqlServer.ConnectionInfo
  •     Microsoft.SqlServer.Management.Sdk.Sfc
  •     Microsoft.SqlServer.Smo
  •     Microsoft.SqlServer.SmoExtended
You can find these .dll files at C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies location.
Create one folder "DLL" in "CreatingDB" class library and copy the above four dll files. Then add these assemblies to your project as reference as well as System.Windows.Forms as shown below:

Develop the "Installer1.cs" as show below:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Data.SqlClient;
using System.IO;
using System.Security.AccessControl;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System.Collections.Specialized;

[RunInstaller(true)]
public partial class Installer1 : System.Configuration.Install.Installer
{
    public Installer1()
    {
        InitializeComponent();
    }

    public void RestoreDatabase(String databaseName, String backupFilePath, String serverName,
        String userName, String password, String dataFilePath, String dbLogicalName)
    {
        // Create Restore instance
        Restore sqlRestore = new Restore();
        // Point to database
        BackupDeviceItem deviceItem = new BackupDeviceItem(backupFilePath, DeviceType.File);
        sqlRestore.Devices.Add(deviceItem);
        sqlRestore.Database = databaseName;
        // Connect to DB Server
        ServerConnection connection;
        if (userName == "") // for Windows Authentication
        {
            SqlConnection sqlCon = new SqlConnection(@"Data Source=" + serverName + @"; Integrated Security=True;");
            connection = new ServerConnection(sqlCon);
        }
        else // for Server Authentication
            connection = new ServerConnection(serverName, userName, password);
        // Restoring
        Server sqlServer = new Server(connection);
        sqlRestore.Action = RestoreActionType.Database;
        String dataFileLocation = dataFilePath + databaseName + ".mdf";
        String logFileLocation = dataFilePath + databaseName + "_Log.ldf";
        sqlRestore.RelocateFiles.Add(new RelocateFile(dbLogicalName, dataFileLocation));
        sqlRestore.RelocateFiles.Add(new RelocateFile(dbLogicalName + "_log", logFileLocation));
        sqlRestore.ReplaceDatabase = true;
        sqlRestore.PercentCompleteNotification = 10;
        try
        {
            sqlRestore.SqlRestore(sqlServer);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.InnerException.ToString());
        }
        //it dont need to attach when logical name and file name is the same ,and file location is MS SQL Server Data filepath.
        AttachDatabase(databaseName, connection, dataFileLocation, logFileLocation);
        Database db = sqlServer.Databases[databaseName];
        db.SetOnline();
        sqlServer.Refresh();
    }

    public void AttachDatabase(String databaseName, ServerConnection connection, 
        String dataFileLocation, string logFileLocation)
    {
        Server SqlServer = new Server(connection);
        StringCollection DatabaseFilesCollection = new StringCollection();
        DatabaseFilesCollection.Add(dataFileLocation);
        DatabaseFilesCollection.Add(logFileLocation);
        try
        {
            SqlServer.AttachDatabase(databaseName, DatabaseFilesCollection);
        }
        catch (Microsoft.SqlServer.Management.Smo.SmoException ex)
        {
            //it throw error when logical name and physical file name is the same,
            //and they are in default MS SQL Server Data file path.
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.InnerException.ToString());
        }
    }

    public override void Commit(System.Collections.IDictionary savedState)
    {
        // Required permission
        try
        {
            DirectorySecurity dirSec = Directory.GetAccessControl(Context.Parameters["TargetDir"]);
            FileSystemAccessRule fsar = new FileSystemAccessRule
            (@"NT AUTHORITY\NETWORK SERVICE"
            , FileSystemRights.FullControl
            , InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit
            , PropagationFlags.None
            , AccessControlType.Allow);
            dirSec.AddAccessRule(fsar);
            Directory.SetAccessControl(Context.Parameters["TargetDir"], dirSec);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        // Parameters that comes from setup project (CreatingDBSetup) 
        RestoreDatabase(Context.Parameters["databaseName"].ToString(), Context.Parameters["backupFilePath"].ToString(), 
            Context.Parameters["serverName"].ToString(), Context.Parameters["userName"].ToString(), Context.Parameters["password"].ToString(), Context.Parameters
        ["dataFilePath"].ToString(), Context.Parameters["dbLogicalName"].ToString());
        
        base.Commit(savedState);
    }
}
That's it for class library. Build it. Now, it need to use above created class library in "CreatingDBSetup" msi.
Go File System Editor by right click on msi project > View > File System.
In the File System Editor, select the 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 CreatingDB project as below:

Required dependencies are loaded automatically as you see in the below picture. Now, we should add database backup file. Right click on empty area in panel, select Add - File.

In Add Files dialog, select backup file "Northwind" and click Open.

Now, we create custom installation dialog for accepting user input such as server name and db connection info. 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 Server Information Dialog for ouput
For Textboxes (B), do the same way like above setps.

See Database Connection Dialog for output

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 each folder. Right click on Install folder, select Add Custom Action as below:

In Select Item in Project dialog, Click Application Folder to get in. Select Primary output from CreatingDB (Active) and click OK. Do the same steps for other folder.

You will see Primary output from CreatingDB (Active) section under the Install and other folders as shown below image. Click each section and change CustomActionData property to the following string:
/TargetDir="[TARGETDIR]\" /databaseName="[DBNAME]" /backupFilePath="[TARGETDIR]Northwind.bak" /serverName="[SERVERNAME]" /userName="[USERNAME]" /password="[PASSWORD]" /dataFilePath="[DBLOC]\\" /dbLogicalName="Northwind"

Now, you finished developing Setup Project and Build and Install it. You will see the following wizards step by step.

Server Information Dialog
Database Connecton Dialog




Reference Article is here.