locked
Web setup project : sql connectionstring problem RRS feed

  • Question

  • User-269404413 posted

    hullo to all,

               I create a new web setup project within this i add Contents using Add Output project option. Now i install it, its working fine but, i have two probelms

    1. During login page the system meet Connection String problem. In my project i wrote connection string within Web.Config file. After installation the system meet this connectionstring problem.

    How to solve the sql connection string problem 

     

    2. I see the installed Virtual directory folder all of my pages is there and can open & view all source code. But, i want to protect my source code, i have DotFuscCator but it obfuscate only the dll or exe files. How to project my code during installation.

     

    Monday, April 21, 2008 1:19 AM

Answers

  • User372121194 posted

    Hi,

    1. During login page the system meet Connection String problem. In my project i wrote connection string within Web.Config file. After installation the system meet this connectionstring problem.

     

    If you want to change the Database connection string using Web Setup project while installing, you can try to add the custom action to your Web Setup project to configure the Database connection string.

     For example, see http://weblogs.asp.net/scottgu/archive/2007/06/15/tip-trick-creating-packaged-asp-net-setup-programs-with-vs-2005.aspx (Section 7: Useful Custom Action Example: Configuring Database Connection String).

    2. I see the installed Virtual directory folder all of my pages is there and can open & view all source code. But, i want to protect my source code, i have DotFuscCator but it obfuscate only the dll or exe files. How to project my code during installation.

     

    In your case, I guess your project is Asp.net website project instead of Asp.net web application project. If so, you can add the Visual Studio 2005 Web Deployment Projects to pre-compilation your website to protect the source code. If you do so, you can configure the Web Setup project to use the output from your Website Deployment project.

     

    I hope this helps.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 24, 2008 2:01 AM
  • User-269404413 posted

    Dear Thomas,

     

                     Thanks for your nice reply. I understand your answer. May i know what is Web site project and what is web application project. Is any advantages over web application

    compared to web site project ?

                   Any guide for how to use web deployment projects ?
     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 24, 2008 2:35 AM
  • User-269404413 posted

    Ahhh...what a great article, now i understand. Me to not installed service pack1 by that asp.net web application is not display in my machine.

    Thanks for your nice reply 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 24, 2008 5:31 AM

All replies

  • User-1125720926 posted

    1) it's possible to have a second (or more) web.configs and swap (& rename) the correct one into a setup package. (But only have one properly named web.config at a time!) eg: in your solution you could have web.configDEV, web.configTEST etc. You can put the correct connection strings in for each deployment and configure the installer to install and rename the correct file. This can be done by excluding the web.config from the normal output and adding the alternative web.config as a single 'add file' in the setup project, then change it's 'target' filename.

    2) have you thought of 'publishing' the site: http://msdn.microsoft.com/en-us/library/aa983453(VS.80).aspx this way the source code can be pre-compiled - hiding the source code (although as you say without obsfucation people can still reverse-engineer the compiled assemblies if they really wanted to and know how.. In practice unless there is really sensitive information hidden in your source code there's little to worry about from people stealing your code! If you have real 'business secrets' in your source code that you're concerned about then you should consider buying professional obsfucation tools.

    hth

     

    Monday, April 21, 2008 8:22 AM
  • User-269404413 posted

    Hai DiscernIT,

                     Thanks for your interest. But i want to know how to set the connection string during installation by coding.
     

    Tuesday, April 22, 2008 7:09 AM
  • User-1125720926 posted

    the best way of writing code for run during install is by writing an installer: http://msdn.microsoft.com/en-us/library/system.configuration.install.installer.aspx

    not sure how you access the target web.config file at install time though. sounds a little tricky!

    Tuesday, April 22, 2008 7:24 AM
  • User372121194 posted

    Hi,

    1. During login page the system meet Connection String problem. In my project i wrote connection string within Web.Config file. After installation the system meet this connectionstring problem.

     

    If you want to change the Database connection string using Web Setup project while installing, you can try to add the custom action to your Web Setup project to configure the Database connection string.

     For example, see http://weblogs.asp.net/scottgu/archive/2007/06/15/tip-trick-creating-packaged-asp-net-setup-programs-with-vs-2005.aspx (Section 7: Useful Custom Action Example: Configuring Database Connection String).

    2. I see the installed Virtual directory folder all of my pages is there and can open & view all source code. But, i want to protect my source code, i have DotFuscCator but it obfuscate only the dll or exe files. How to project my code during installation.

     

    In your case, I guess your project is Asp.net website project instead of Asp.net web application project. If so, you can add the Visual Studio 2005 Web Deployment Projects to pre-compilation your website to protect the source code. If you do so, you can configure the Web Setup project to use the output from your Website Deployment project.

     

    I hope this helps.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 24, 2008 2:01 AM
  • User-269404413 posted

    Dear Thomas,

     

                     Thanks for your nice reply. I understand your answer. May i know what is Web site project and what is web application project. Is any advantages over web application

    compared to web site project ?

                   Any guide for how to use web deployment projects ?
     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 24, 2008 2:35 AM
  • User372121194 posted

    Hi,

    Thanks for your response and I am glad to help you.

    In your case (for deployment),  you can get some information from http://msdn.microsoft.com/en-us/magazine/cc163448.aspx.

    For differences between them, you can refer to http://forums.asp.net/p/1150861/1876473.aspx.

     

    I hope this helps.

    Thursday, April 24, 2008 5:05 AM
  • User-269404413 posted

    Ahhh...what a great article, now i understand. Me to not installed service pack1 by that asp.net web application is not display in my machine.

    Thanks for your nice reply 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 24, 2008 5:31 AM
  • User1354447825 posted

     Hi  Sir Thomas,

    I am reading artical on link http://weblogs.asp.net/scottgu/archive/2007/06/15/tip-trick-creating-packaged-asp-net-setup-programs-with-vs-2005.aspx which you mensioned on your above post and crating a custom action to my websetup project to change connectionstring at installation time.

    I am using the function

    private void ConfigureDatabase(string targetSite, string targetVDir, string connectionString)
            {
                // 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);

                // Add new connection string setting for web.config
                ConnectionStringSettings appDatabase = new ConnectionStringSettings();
                appDatabase.Name = DATABASE_CONNECTION_KEY;
                appDatabase.ConnectionString = connectionString;
               
               
                config.ConnectionStrings.ConnectionStrings.Clear();
                config.ConnectionStrings.ConnectionStrings.Add(appDatabase);

                // Persist web.config settings
                config.Save();
            } 

    but i am getting error an compilation time, which is given below.

     1. The type or namespace could not be found.

     2. The name space WebConfigurationManager does not exists.

    while i am already added 

    using System.Collections;
    using System.ComponentModel;
    using System.Configuration.Install;
    using System.Data;
    using System.Data.SqlClient;
    using System.IO;
    using System.Reflection;
    using System.Text.RegularExpressions;
    using System.DirectoryServices;
    using System.Diagnostics;
    using System.Configuration;

    name spaces.

    is DATABASE_CONNECTION_KEY represents the key name of connection string of web config file?

    One another thing, i want to know, do i need to add additional dialog to supply 

    /targetdir="[TARGETDIR]\" /targetvdir="[TARGETVDIR]" /targetsite="[TARGETSITE]"

    parameters or it will not required to supply bu using additional dialog.

    Please help me. 

    Tuesday, March 10, 2009 7:34 AM
  • User1354447825 posted

    Hello Sir,

    I have passed the three parameters in ConfigureDatabase() function..

     

     string targetSite = Context.Parameters["targetsite"];
                    string targetVDir = Context.Parameters["targetvdir"];
                    string connectionString = GetLogin(
                            Context.Parameters["databaseServer"],
                            Context.Parameters["userName"],
                            Context.Parameters["userPass"],
                            "TrainTrack");
                    ConfigureDatabase(targetSite, targetVDir, connectionString);

     public void ConfigureDatabase(string targetSite, string targetVDir, string connectionString)
            {
                // 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);

                // Add new connection string setting for web.config
                ConnectionStringSettings appDatabase = new ConnectionStringSettings();
                appDatabase.Name = "TrainTrack";
               
                appDatabase.ConnectionString = connectionString;


                config.ConnectionStrings.ConnectionStrings.Clear();
                config.ConnectionStrings.ConnectionStrings.Add(appDatabase);

                // Persist web.config settings
                config.Save();
            } 

     

     

    Thursday, March 12, 2009 7:12 AM
  • User1354447825 posted

     Hello Sir,

    I resolve the above error by adding required assemblies. But now, i am getting anoter error at installation. Error generates when i am calling ConfigureDatabase() function, otherwise every thing is ok.

    My error is...

    The installer has encountered and unexpected error installing this package. This may indicate a problem with this package. The error code id 2869.

    Here i attach my hole source code...


    using System.Collections;
    using System.ComponentModel;
    using System.Configuration.Install;
    using System.Data;
    using System.Data.SqlClient;
    using System.IO;
    using System.Reflection;
    using System.Text.RegularExpressions;
    using System.DirectoryServices;
    using System.Diagnostics;
    using System.Web.Configuration;
    using System.Configuration;

    namespace aleph.framework.SqlInstall
    {
        /// <summary>
        /// SQL DataBase installer
        /// </summary>
        [RunInstaller(true)]
        public class ScriptInstall : Installer
        {
            //default value, it will be overwrite by the installer
            string conStr="packet size=4096;integrated security=SSPI;"+
                        "data source=\"(local)\";persist security info=False;"+
                        "initial catalog=master";
            private Container components=null;
           
            public ScriptInstall()
            {
                // This call is required by the Designer.
                InitializeComponent();
            }

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                if( disposing )
                {
                    if(components != null)
                    {
                        components.Dispose();
                    }
                }
                base.Dispose( disposing );
            }

            #region Component Designer generated code
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {

            }
            #endregion

            private static string GetScript(string name)
            {
                Assembly asm = Assembly.GetExecutingAssembly();
                Stream str = asm.GetManifestResourceStream(asm.GetName().Name+ "." + name);
                StreamReader reader = new StreamReader(str);
                return reader.ReadToEnd();
            }
            private static string GetLogin(string databaseServer,string userName,string userPass,string database)
            {
                return "server=" + databaseServer + ";database="+database+";User ID=" + userName + ";Password=" + userPass;
            }

            private static void ExecuteSql(SqlConnection sqlCon)
            {
                string[] SqlLine;
                Regex regex = new Regex("^GO",RegexOptions.IgnoreCase | RegexOptions.Multiline);
               
                string txtSQL = GetScript("install.txt");
                SqlLine = regex.Split(txtSQL);

                SqlCommand cmd = sqlCon.CreateCommand();
                cmd.Connection = sqlCon;

                foreach(string line in SqlLine)
                {
                    if(line.Length>0)
                    {
                        cmd.CommandText = line;
                        cmd.CommandType = CommandType.Text;
                        try
                        {
                            cmd.ExecuteNonQuery();
                        }
                        catch(SqlException)
                        {
                            //rollback
                            ExecuteDrop(sqlCon);
                            break;
                        }
                    }
                }
            }
            private static void ExecuteDrop(SqlConnection sqlCon)
            {   
                if(sqlCon.State!=ConnectionState.Closed)sqlCon.Close();
                sqlCon.Open();
                SqlCommand cmd = sqlCon.CreateCommand();
                cmd.Connection = sqlCon;
                cmd.CommandText = GetScript("uninstall.txt");
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();
                sqlCon.Close();
            }

            public override void Install(IDictionary stateSaver)
            {
                base.Install (stateSaver);

                if(Context.Parameters["databaseServer"].Length>0 &&
                    Context.Parameters["userName"].Length>0 &&
                    Context.Parameters["userPass"].Length>0)
                {
                    conStr = GetLogin(
                        Context.Parameters["databaseServer"],
                        Context.Parameters["userName"],
                        Context.Parameters["userPass"],
                        "master");

                    RijndaelCryptography rijndael = new RijndaelCryptography();
                    rijndael.GenKey();
                    rijndael.Encrypt(conStr);
                    //save information in the state-saver IDictionary
                    //to be used in the Uninstall method
                    stateSaver.Add("key",rijndael.Key);
                    stateSaver.Add("IV",rijndael.IV);
                    stateSaver.Add("conStr",rijndael.Encrypted);
                }

                SqlConnection sqlCon = new SqlConnection(conStr);

                sqlCon.Open();
                ExecuteSql(sqlCon);
                if(sqlCon.State!=ConnectionState.Closed)sqlCon.Close();

              
                    string targetSite = Context.Parameters["targetsite"];
                    string targetVDir = Context.Parameters["targetvdir"];
                    string connectionString = GetLogin(
                            Context.Parameters["databaseServer"],
                            Context.Parameters["userName"],
                            Context.Parameters["userPass"],
                            "TrainTrack");
                    ConfigureDatabase(targetSite, targetVDir, connectionString);
               
               

            }

            public override void Uninstall(IDictionary savedState)
            {
                base.Uninstall (savedState);

                if(savedState.Contains("conStr"))
                {
                    RijndaelCryptography rijndael = new RijndaelCryptography();
                    rijndael.Key = (byte[])savedState["key"];
                    rijndael.IV = (byte[])savedState["IV"];
                    conStr = rijndael.Decrypt((byte[])savedState["conStr"]);           
                }
       
                SqlConnection sqlCon = new SqlConnection(conStr);
       
                ExecuteDrop(sqlCon);
            }
            public override void Rollback(IDictionary savedState)
            {
                base.Rollback(savedState);
                if (savedState.Contains("conStr"))
                {
                    RijndaelCryptography rijndael = new RijndaelCryptography();
                    rijndael.Key = (byte[])savedState["key"];
                    rijndael.IV = (byte[])savedState["IV"];
                    conStr = rijndael.Decrypt((byte[])savedState["conStr"]);
                }

                SqlConnection sqlCon = new SqlConnection(conStr);

                ExecuteDrop(sqlCon);
            }
           

            public void ConfigureDatabase(string targetSite, string targetVDir, string connectionString)
            {
                // 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);

                // Add new connection string setting for web.config
                ConnectionStringSettings appDatabase = new ConnectionStringSettings();
                appDatabase.Name = "TrainTrack";
               
                appDatabase.ConnectionString = connectionString;


                config.ConnectionStrings.ConnectionStrings.Clear();
                config.ConnectionStrings.ConnectionStrings.Add(appDatabase);

                // Persist web.config settings
                config.Save();
            }

        }
    }
     

    Actually, What is the problem with my code. Am i missing some steps in my code? 

    Please help me.

    Thursday, March 12, 2009 7:14 AM
  • User-1638851029 posted

     Hi Prabha

    I am also got problem in ConfigureDatabase()

     

    here is my code

    using

    System;

    using

    System.Collections.Generic;

    using

    System.Text;

    using

    System.Web.Configuration;

    using

    System.Configuration;

    using

    System.Configuration.Install;

    using

    System.ComponentModel;

    using

    System.Diagnostics;

    using

    System.IO;

    using

    System.DirectoryServices;

    using

    System.Data.SqlClient;

    namespace

    {

    [

     

    DbconnectionClassRunInstaller(true)]public class Class1:Installer

    {

     

    {

     

     

    public override void Install(System.Collections.IDictionary stateSaver)base.Install(stateSaver);// Retrieve configuration settings

     

     

     

     

    Context.Parameters[

    Context.Parameters[

    Context.Parameters[

     

    ConfigureDatabase(targetSite, targetVDir, connectionString);

     

     

     

    targetSite = targetSite.Substring(4);

    RegisterScriptMaps(targetSite, targetVDir);

    }

     

    {

     

    string targetSite = Context.Parameters["targetsite"];string targetVDir = Context.Parameters["targetvdir"];string targetDirectory = Context.Parameters["targetdir"];string connectionString = GetLogin("databaseServer"],"userName"],"userPass"],"TrainTrack");if (targetSite == null)throw new InstallException("IIS Site Name Not Specified!");if (targetSite.StartsWith("/LM/"))void RegisterScriptMaps(string targetSite, string targetVDir)// Calculate Windows path

     

     

    string sysRoot = System.Environment.GetEnvironmentVariable("SystemRoot");// Launch aspnet_regiis.exe utility to configure mappings

     

    info.FileName =

    info.Arguments =

    info.CreateNoWindow =

    info.UseShellExecute =

     

    }

     

    {

     

    ProcessStartInfo info = new ProcessStartInfo();Path.Combine(sysRoot, @"Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe");string.Format("-s {0}/ROOT/{1}", targetSite, targetVDir);true;false;Process.Start(info);void ConfigureDatabase(string targetSite, string targetVDir, string connectionString)// 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);// Add new connection string setting for web.config

     

    appDatabase.Name =

    appDatabase.ConnectionString = connectionString;

    config.ConnectionStrings.ConnectionStrings.Clear();

    config.ConnectionStrings.ConnectionStrings.Add(appDatabase);

     

    ConnectionStringSettings appDatabase = new ConnectionStringSettings();"TrainTrack";// Persist web.config settings

    config.Save();

    }

     

    {

     

    }

    }

    }

    private static string GetLogin(string databaseServer, string userName, string userPass, string database)return "server=" + databaseServer + ";database=" + database + ";User ID=" + userName + ";Password=" + userPass;

     

     

    here am got unknown error during installation

    do u have any solution regards this issue

    how can u got user database name and  user id , password

    i am using only one textbox in connection string that textbox value is

    'Data Source=local;User ID=sa;Password=sa' it is correct

    pls give if you find any solution

     

     

     

    Friday, August 7, 2009 3:49 AM
  • User-1638851029 posted

    HI

    WE GOT ERROR

    FROM  GetScript(string p) FUNCTION
      
            Assembly asm = Assembly.GetExecutingAssembly();
            Stream str = asm.GetManifestResourceStream(p);

    str values return null


    pls solve this problem


    Saturday, August 8, 2009 5:20 AM