CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Dec 2007
    Location
    South Africa
    Posts
    263

    [RESOLVED] [2005]Update Connection String

    Good Afternoon

    My Application is Structured in a Way that before you login you must First Select a Database. Now i have one page that i want to change the Connection String Database name.

    I have this function that get called on page load


    Code:
        /*This Function will change the Connection string in the web.congif file based on the Database that exists on the 
         * session Variable. If there is nulll then set odirect3 as a current Database name.
         */
        public void UpdateConfig()
        {
            CommonFunctions obj = new CommonFunctions();
    
            
    
            String strKey = "NEWDT";
     
            String StrDatabase;
    
            if (Session["ActiveDatabase"] != null)
            {
                StrDatabase = Convert.ToString(Session["ActiveDatabase"]);
            }
            else
            {
                StrDatabase = "oDirectv3";
            }
     
            String strValue = @"User id=sa;Password=wow;Server=drddd;Database="+StrDatabase;
    
            Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");
    
            AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
    
            if (objAppsettings != null)
            {
                objAppsettings.Settings[strKey].Value = strValue;
    
                objConfig.Save();
            }
        }
    On the Development site it works well. But while still debugging the code, checking if its doing what i want, There is a point where it has to save the changes
    Code:
        objConfig.Save();
    The Part will execute and message box will appear asking me if i really want to save the changes made, i will save yes and everything will be fine. But if i don debug it , it gives an Error that says
    Code:
    A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
    How can i do this and Suppress this dialogs


    Thank you
    Last edited by vuyiswam; March 2nd, 2009 at 08:19 AM.
    Few companies that installed computers to reduce the employment of clerks have realized their expectations.... They now need more and more expensive clerks even though they call them "Developers" or "Programmers."

  2. #2
    Join Date
    Jan 2009
    Location
    Cochin, India
    Posts
    40

    Smile Re: [2005]Update Connection String

    Hi,

    The message box appears only if you try to execute the code from Visual Studio. It will work fine and the message box will not appear at runtime. You will have to add the web.config file before hand and include the element "NEWDT" in the appSettings section. This is difficult to explain but I can demonstrate this to you with some sample code. Open a default web site in VS 2005 and here I give below the code for both Default.aspx and Default.aspx.cs.

    Code For Default.aspx

    Code:
    <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        
        </div>
        </form>
    </body>
    </html>

    Code for Default.aspx.cs

    Code:
    using System;
    using System.Data;
    using System.Configuration;
    using System.Web.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    
    public partial class _Default : System.Web.UI.Page 
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            UpdateConfig();
        }
    
        public void UpdateConfig()
        {
            String strKey = "NEWDT";
            String StrDatabase;
            if (Session["ActiveDatabase"] != null)
            {
                StrDatabase = Convert.ToString(Session["ActiveDatabase"]);
            }
            else
            {
                StrDatabase = "oDirectv3";
            }
            String strValue = @"User id=sa;Password=wow;Server=drddd;Database=" + StrDatabase;
            Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");
            AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
            if (objAppsettings != null)
            {
                objAppsettings.Settings[strKey].Value = strValue;
                objConfig.Save();
            }
        }
    }
    Now here is the third thing you will have to do. Add a web.config file. To do that go to the solution explorer and right click on the top heading and choose "add new item". In the window that opens up choose "web configuration file" and click okay. This will add a web.config file to your application. Now change the appSettings section to look like

    Code:
      <appSettings>
        <add key="NEWDT" value="ABCD" />
      </appSettings>

    After making this change here is what your Web.Config looks like. I am giving below the full code for the web.config.

    Code:
    <?xml version="1.0"?>
    <!-- 
        Note: As an alternative to hand editing this file you can use the 
        web admin tool to configure settings for your application. Use
        the Website->Asp.Net Configuration option in Visual Studio.
        A full list of settings and comments can be found in 
        machine.config.comments usually located in 
        \Windows\Microsoft.Net\Framework\v2.x\Config 
    -->
    <configuration>
      <appSettings>
        <add key="NEWDT" value="ABCD" />
      </appSettings>
        <connectionStrings/>
        <system.web>
            <!-- 
                Set compilation debug="true" to insert debugging 
                symbols into the compiled page. Because this 
                affects performance, set this value to true only 
                during development.
            -->
            <compilation debug="false" />
            <!--
                The <authentication> section enables configuration 
                of the security authentication mode used by 
                ASP.NET to identify an incoming user. 
            -->
            <authentication mode="Windows" />
            <!--
                The <customErrors> section enables configuration 
                of what to do if/when an unhandled error occurs 
                during the execution of a request. Specifically, 
                it enables developers to configure html error pages 
                to be displayed in place of a error stack trace.
    
            <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
                <error statusCode="403" redirect="NoAccess.htm" />
                <error statusCode="404" redirect="FileNotFound.htm" />
            </customErrors>
            -->
        </system.web>
    </configuration>
    You can see the key "NEWDT" has a value of "ABCD"

    Do not execute the application now from VS2005. Because if you do it will execute fine but at the end it will ask you a question. It will say that the web.config file has been modified externally and ask you whether you want to reload it? But this will happen only if you run the application from VS 2005 by clicking on the F5 key.

    It will not ocur at runtime. So do not run it now. First just build the application. And close VS 2005. Now your application might have had any name. Let us assume it is called WebSite1. Now copy the directory WebSite1 from wherever it was, to your IIS root. Mostly the IIS root is the directory c:\inetpub\wwwroot. Copy the directory WebSite1 into this directory.

    Now you will have to do a few more things. Open up IIS and set the Home directory of "Default Web Site" to c:\inetpub\wwwroot\WebSite1. Give the required permissions and make c:\inetpub\wwwroot\WebSite1 a shared directory and also allow the group "everyone" access to it. Close IIS. If you have done everything correctly, open your browser and type in localhost in the address bar. The page will get executed and you will get the done message in the status bar of the browser.

    But you will not see anything in the page. And no messages will pop up either.

    Now here is how you can check if the code has been executed.

    Now open VS 2005 and open the website at c:\inetpub\wwwroot\WebSite1 and check your Web.Config file and look at the appSettings section. You will find the value of the key "NEWDT" has changed from "ABCD" to "User id=sa;Password=wow;Server=drddd;Database=oDirectv3"

    This is what it will look like in your Web.Config file.

    Code:
    <appSettings>
        <add key="NEWDT" value="User id=sa;Password=wow;Server=drddd;Database=oDirectv3" />
      </appSettings>
    So the code has worked and changed the value of the key "NEWDT". This is a very elaborate explanation. But it was required for demonstration. Hope this helps.

    Warm Regards.

    Quote Originally Posted by vuyiswam View Post
    Good Afternoon

    My Application is Structured in a Way that before you login you must First Select a Database. Now i have one page that i want to change the Connection String Database name.

    I have this function that get called on page load


    Code:
        /*This Function will change the Connection string in the web.congif file based on the Database that exists on the 
         * session Variable. If there is nulll then set odirect3 as a current Database name.
         */
        public void UpdateConfig()
        {
            CommonFunctions obj = new CommonFunctions();
    
            
    
            String strKey = "NEWDT";
     
            String StrDatabase;
    
            if (Session["ActiveDatabase"] != null)
            {
                StrDatabase = Convert.ToString(Session["ActiveDatabase"]);
            }
            else
            {
                StrDatabase = "oDirectv3";
            }
     
            String strValue = @"User id=sa;Password=wow;Server=drddd;Database="+StrDatabase;
    
            Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");
    
            AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
    
            if (objAppsettings != null)
            {
                objAppsettings.Settings[strKey].Value = strValue;
    
                objConfig.Save();
            }
        }
    On the Development site it works well. But while still debugging the code, checking if its doing what i want, There is a point where it has to save the changes
    Code:
        objConfig.Save();
    The Part will execute and message box will appear asking me if i really want to save the changes made, i will save yes and everything will be fine. But if i don debug it , it gives an Error that says
    Code:
    A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
    How can i do this and Suppress this dialogs


    Thank you
    Jay
    Support Resort
    http://www.supportresort.com
    Bringing offshore expertise to the world

  3. #3
    Join Date
    Dec 2007
    Location
    South Africa
    Posts
    263

    Re: [2005]Update Connection String

    I would like to take a Chance to Thank you for what you have done for me. The Code looks good. The Code looks like this

    Code:
    protected void setupGrid()
        {
            if (((int)Session["numCycles"]) > 0)
            {
                UltraWebGrid cycleGrid = ultraGridCycles;
                int numCols = 0; //Number of Colums             
                int numRows = 0; //Number of Rows
    
                //If the Sessions are Greater than 13 , Make 
                //the Columns to be 13 else keep the supplied value for the Columns
                if (((int)Session["numCycles"]) >= 13)
                {
                    numCols = 13;
                }
                else
                {  //Keep the Columns as they are 
                    numCols = ((int)Session["numCycles"]);
                }
    
    
                /*This one is used for the Row not the Column like the above one*/
                //Divide the Session variable Value by 13, the Returned 
                //number is Checked if its 0 if that is true the First Statement get executed 
                //else the second -->
                //I suppose this was meant to check the zero, because you cant divide by zero
                if ((((int)Session["numCycles"]) % 13) == 0)
                {
                    //Assign the value of a Session Varable that is Devided by 13
                    numRows = (int)(((int)Session["numCycles"]) / 13);
                }
                else
                {
                    //Assign the value of a session variable and Divide it by 13 
                    //add a on top of it. 
                    numRows = (int)((((int)Session["numCycles"]) / 13) + 1);
                }
    
                //Change the Height of the Grid
                cycleGrid.Height = Unit.Pixel(20 * numRows + 6);
    
                /*'''''''''''''''''''''''''''''''''''''''''''
                 * For the Column
                 * ''''''''''''''''''''''''''''''''''''''''''*/
    
                /*This is a For Loop. We First declare 
                 * the integer and initialize it to 0 and the second one is
                 * the expression, we say, as long as the number of [i] variable are less than the number of columns
                 * then increase the value of i
                 */
                for (int i = 0; i < numCols; i++)
                {   //Create an object of a class Ultracolumn that represents the Column
                    UltraGridColumn col = new UltraGridColumn(true);
                    //adjust the Width of the Column
                    col.Width = Unit.Pixel(10);
                    //Its a Unique String in a Gridview
                    col.Key = i.ToString();
                    //Now we are adding Columns in the Gridview by passing the Column object.
                    cycleGrid.Columns.Add(col);
                }
    
                /*'''''''''''''''''''''''''''''''''''''''''''
                 * For the Rows
                 * ''''''''''''''''''''''''''''''''''''''''''*/
                /*Here we are using the For loop,
                 * First declare and initializing the variable i 
                 * and while the variable i is less than the number of rows then increase 
                 * the value of i */
                for (int i = 1; i <= numRows; i++)
                {
                    //Create an object of a Class UltragridRow and initialize it
                    UltraGridRow row = new UltraGridRow(true);
                    //Assign a unique key of a row
                    row.Key = i.ToString();
    
                    /*'''''''''''''''''''''''''''''''''''''''''''
                    * For the Cell
                    * ''''''''''''''''''''''''''''''''''''''''''*/
                    /*Declare a Variable of integer "j" and assign it a value of "1"
                     * and as long as the value of J is less that and equal to number of Columns
                     * then increament the value of a variable J
                     */
                    for (int j = 1; j <= numCols; j++)
                    {
                        //Create an object of a class UltraGridCell and initialize it.
                        UltraGridCell cell = new UltraGridCell(true);
                        //adjust the gridproperties
                        cell.Style.HorizontalAlign = HorizontalAlign.Center;
                        //adjust the gridproperties
                        cell.Style.Padding.Left = 0;
                        //adjust the gridproperties
                        cell.Style.Padding.Top = 0;
                        //adjust the gridproperties
                        cell.Style.Padding.Bottom = 0;
                        //adjust the gridproperties
                        cell.Style.Padding.Right = 0;
                        //adjust the gridproperties
    
                        //Adjust the Cell Value to Integer 13 mutiply by number of rows -1 ajd pluss number of Columns
                        cell.Value = (int)((13 * (i - 1)) + j);
    
                        /*If 13 multiply by number of rows -1 one plus number of Columns
                         * is greateer than the session variable then set the value of that cell to null */
                        if (((13 * (i - 1)) + j) > ((int)Session["numCycles"]))
                        {
                            cell.Value = null;
                            cell.Style.BackColor = System.Drawing.Color.Gray;
                            cell.AllowEditing = AllowEditing.No;
                        }
    
                        //add the cells to the Grid                                       
                        row.Cells.Add(cell);
    
    
    
                    }
                    cycleGrid.Rows.Add(row);
    
                }
                /*After the Grid has been Populated, let us remove some of the cells 
                        * using the Following code
                        */
                ArrayList array = (ArrayList)Disable_Grid();
    
    
    
                //Count the Number of rows in a gridview and initialize the integer with those values
                int u = cycleGrid.Rows.Count;
    
                /*Another For Loop,First we declare an Interger variable "i" and 
            * initialize it with "0" and as long as the variable i is less than the number of
            * rows in a gridview increament the variable i
            */
                for (int i = 0; i < cycleGrid.Rows.Count; i++)
                {
                    /*Creating an object of a Class GridViewRow "g" and 
                 * passing the Value a Variable i that has 
                 * been checked as less than the Value of the Rows 
                 */
    
                    UltraGridRow g = cycleGrid.Rows[i];
                    /*Another For Loop. Initialization of a newly declared variable 
                 *  j to "0" and as long as the number of Cells are less than the variable J then increase the Value of a 
                 * variable J
                 */
                    for (int j = 0; j < g.Cells.Count; j++)
                    {
                        /*for Loop in a For loop. Declare an Integer "p" and Assign 
                         * 0 to it and as long as the number of p variable  are 
                         * less than the number of indexes in the array list variable
                          if its true the value of P is incremented by 1*/
                        for (int p = 0; p < array.Count; p++)
                        {
                            /*A String is Declared and is Assigned a value of 
                             * of a cell indexed by the variable J that is not supposed greater than
                             * the number of cells in a grid
                             */
                            string txt = g.Cells[j].Text;
                            /*if then value in the text is equal to the value of the array 
                             * make the cell invisible*/
    
                            //int m = array.Count;
    
                            if (txt != array[p].ToString())
                            {
                                /*The I is representing the Rows and the J is representing the Cells
                                 */
                                 
                                cycleGrid.Rows[i].Cells[j].Style.ForeColor = System.Drawing.Color.DarkGray;
    
                                cycleGrid.Rows[i].Cells[j].Style.ForeColor = System.Drawing.Color.DarkGray;
    
                                cycleGrid.Rows[i].Cells[j].AllowEditing = AllowEditing.No;
    
                                //this.cycleGrid.Rows[0].Cells[0].Activation = Activation.Disabled;
    
                                cycleGrid.Rows[i].Cells[j].Activated = false; 
    
                            }
                            else
                            {
    
                                cycleGrid.Rows[i].Cells[j].Style.ForeColor = System.Drawing.Color.Black;
                                cycleGrid.Rows[i].Cells[j].Style.BackColor = System.Drawing.Color.White;
                                cycleGrid.Rows[i].Cells[j].Style.Font.Bold = true;
    
                            }
                        }
                    }
                }
            }
        }
    The grey Part make it look as if its disabled. Am using Infragistic Control Ultragridweb, so i could not Disable the cells there. Do you have any suggestions there?

    Thank you for your help
    Few companies that installed computers to reduce the employment of clerks have realized their expectations.... They now need more and more expensive clerks even though they call them "Developers" or "Programmers."

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured