-1

i created a software,which worked fine in Visual Studio. but when i deploy it on any computer it gives the following error while trying to make connection to the database:-

************** Exception Text **************
System.InvalidOperationException: The ConnectionString property has not been initialized.
   at System.Data.SqlClient.SqlConnection.PermissionDemand()
   at System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection)
   at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
   at System.Data.SqlClient.SqlConnection.Open()
   at System.Data.Common.DbDataAdapter.QuietOpen(IDbConnection connection, ConnectionState& originalState)
   at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
   at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
   at DentalGood.frmLogin.startLogin() in E:\PRGS\DentalGood\DentalGood\frmLogin.cs:line 28
   at KryptonForm.frmMain.btnLogin_Click(Object sender, EventArgs e) in E:\PRGS\DentalGood\DentalGood\frmMain.cs:line 216
   at ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton.OnClick(EventHandler finishDelegate)
   at ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton.PerformClick(EventHandler finishDelegate)
   at a5.d(Object A_0, EventArgs A_1)
   at eq.b(Object A_0, EventArgs A_1)
   at ek.b(EventArgs A_0)
   at ek.a(Control A_0, Point A_1, MouseButtons A_2)
   at ComponentFactory.Krypton.Toolkit.ToolTipController.MouseUp(Control c, Point pt, MouseButtons button)
   at ComponentFactory.Krypton.Toolkit.ViewBase.MouseUp(Point pt, MouseButtons button)
   at ComponentFactory.Krypton.Toolkit.ViewBase.MouseUp(Point pt, MouseButtons button)
   at ComponentFactory.Krypton.Toolkit.ViewBase.MouseUp(Point pt, MouseButtons button)
   at ComponentFactory.Krypton.Toolkit.ViewBase.MouseUp(Point pt, MouseButtons button)
   at ComponentFactory.Krypton.Toolkit.ViewManager.MouseUp(MouseEventArgs e, Point rawPt)
   at ComponentFactory.Krypton.Toolkit.ViewControl.OnMouseUp(MouseEventArgs e)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at ComponentFactory.Krypton.Toolkit.ViewControl.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)


************** Loaded Assemblies **************
mscorlib
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.6400 (Win8RTMGDR.050727-6400)
    CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v2.0.50727/mscorlib.dll

have initialised the ConnectionString in the program.cs file. it stores the connection string in a file and loads it whenever connection is needed. any help?

user2257581
  • 87
  • 1
  • 1
  • 9
  • your connection string is incorrect – KF2 Apr 11 '13 at 14:20
  • I think it's not good idea to store ConnectionString in Program.cs. If you wish to get it from other files, you can make a `public static` method of creation of that ConnectionString. Also, could you show please the text of that string? – Mr Zak Apr 11 '13 at 14:22
  • Is your connection string stored in a file? What does the path to it look like? I suspect you've referenced a specific location on your machine rather than a more general location which is why it can't be found on other machines – DGibbs Apr 11 '13 at 14:22
  • but the same string works well with Visual Studio – user2257581 Apr 11 '13 at 14:23
  • @DGibbs yes the connection string is stored in a file.heres the code in program.cs file:- `public static SqlConnection con = new SqlConnection(); public static bool Connected; [STAThread] static void Main() { string filename = Application.StartupPath + "\\DBConfig.CFG"; bool b = File.Exists(filename);` – user2257581 Apr 11 '13 at 14:29
  • `if (b == true) { FileStream FS = new FileStream(filename, FileMode.Open); StreamReader sr = new StreamReader(FS); try { con.ConnectionString = sr.ReadLine(); sr.Close(); FS.Close(); con.Open(); Connected = true; } catch (Exception) { ` this much is enuf? rest code contains exeption handling and error message. – user2257581 Apr 11 '13 at 14:30
  • Yeah, i'd guess the path to your connection string is wrong when deploying to other machines. Check and confirm that the app startuppath is the same on both machines – DGibbs Apr 11 '13 at 14:31
  • `Application.StartupPath` isn't used for just the path? does changing the path would really affect its working? i installed the application on my own computer which was used for development.Still it gives the error – user2257581 Apr 11 '13 at 14:35
  • Does the file "DBConfig.CFG" exhist in the startup path of application you are trying to deploy? Do you have OS permission to open file from the directory you put it in? And why you don't use ConfigurationManager like it is done here - http://stackoverflow.com/questions/7139440/sqlconnection-in-c-sharp?rq=1 . Also, possible way - SqlConnectionStringBuilder, so you'll be able to dinamically construct your connection string. – Mr Zak Apr 11 '13 at 14:58
  • @MrZak yes the DBconfig.cfg exists in the startup path and is accesible. in some folder where it is not accessible the application gives an error.but in this case it is accessible. and i am new to C# this is the only way i know to store the connection string. here it goes:- have a form for user to enter the servername and authentication type.and that info along with the connection string is stored in that DBconfig.cfg file. i cant figure out where the error is. current string in DBconfig.cfg file is **Server=VARIJ\SQLEXPRESS;database=Dental;trusted_connection=yes** – user2257581 Apr 11 '13 at 15:22

1 Answers1

0

First, exclude the name of server from the string. Type the dot (.) instead. It'll mean you connect to sql server installed on localhost. It'll provide you with opportunity to test application connection string.

Second, you can not to store connection string in file, but generate it in code of program instead. You can type something like that (not in Program.cs):

 public Form2()
    {
        InitializeComponent();
        conn = "";
    }

  private void btnOK_Click(object sender, EventArgs e)
    {
         conn = CreateConn(conn, comboBox1.Text);
         SqlConnection connect = new SqlConnection(conn);
         MessageBox.Show(connect.ConnectionString.ToString());
    }
    public static string CreateConn(string connectString, string param)
    {
        connectString = String.Format("Data Source={0};Initial Catalog=db_Raspisanie;Integrated Security=True", 
            param);
        return connectString;
    }

UPD2.In the ComboBox1 property SelectedText, you can write (local), that will provide user opportunity not to type server Name every time, if he works on local server where the database is stored.

This is very simple method, by the MessabeBox.Show it displays you the connection String you get.

UPD.

If you need it to be stored in the file (I use .txt for this purpose), you can use this code:

     /*Code of Form2, which is Login like*/
  public static string conn;
    private void Form2_Load(object sender, EventArgs e)
    {

    }

    private void btnOK_Click(object sender, EventArgs e)
    {
         conn = CreateConn(conn);
         SqlConnection connect = new SqlConnection(conn);

         //MessageBox.Show(connect.ConnectionString.ToString());

         Form1 fr = new Form1();
         fr.ShowDialog();
    }
      public static string CreateConn(string connectString)
    {
        string fileName = Application.StartupPath + "\\string.txt";
        FileStream fs = new FileStream(fileName, FileMode.Open);
        StreamReader strem = new StreamReader(fs);
        conn = strem.ReadLine();
        connectString = conn;
        strem.Close(); fs.Close();

        return connectString;
    }


       /*Code of Form1 which is main form*/

 public Form1()
    {
        InitializeComponent();
        string param = "";
        param = Form2.conn;
         con = new SqlConnection(param);
    }
    SqlConnection con;
    SqlDataAdapter da;
    DataSet ds;
    private void Form1_Load(object sender, EventArgs e)
    {
        da = new SqlDataAdapter("Select * from Table1", con);
        ds = new DataSet();
        da.Fill(ds, "Table1");
        dataGridView1.DataSource = ds.Tables["Table1"];

    }

Contents of .txt file are the same as you wrote:

    Server=.;database=db_Raspisanie;trusted_connection=true

Seems to be I included everything as needed. Please write if it give exceptions, I tested it, but may be.

Mr Zak
  • 361
  • 2
  • 10
  • but this way user have to enter the connection string every time he logs into the database – user2257581 Apr 11 '13 at 16:17
  • but how do you want it to be? Ye, every time user opens the program, he have to enter Server Name (not connection string!) into the field. – Mr Zak Apr 11 '13 at 17:05
  • yeah sorry,i meant servername only. but that would be annoying for a user.(in this case it is). i want that the user enter the string once for the first time he starts the application and then application would use that string. (more user friendly) – user2257581 Apr 11 '13 at 17:13
  • Please see the update for my answer. To this way one can also add method that in the first execution time will ask user to type server name, and it'll be writen in the .txt file – Mr Zak Apr 11 '13 at 17:30
  • i am using the same approach as u told in your update.diff is i declared that code to access file in the program.cs file so as the application makes database connection on startup itself. and the ".CFG" extention is used to protect the file from user editing.in actual it is a text file readable in notepad. – user2257581 Apr 11 '13 at 17:42
  • when i debug the program the database works well and so do the connection string. but after installation it causes such error – user2257581 Apr 11 '13 at 17:44
  • As I told, it's not good way to create connection in Program.cs. Unfortunately, I don't have opportunity to test setup creation, but it seems to me you get error because of wrong setup creation or because of lack OS opportunity to open that file. Still, I think it's better to use dynamical creation of connection String, because it'll save you from problem of wrong access to the file where it is stored in. – Mr Zak Apr 11 '13 at 17:51
  • error solved.the problem was solved when i added the database files along with the software – user2257581 Apr 12 '13 at 16:25