ViewVC Help
View File | Revision Log | Show Annotations | Download File | View Changeset | Root Listing
root/AnywhereTS-MSSQL/trunk/TSAdminTool/Database.cs
Revision: 132
Committed: Sun Jul 15 03:09:38 2012 UTC (11 years, 7 months ago) by william
File size: 34462 byte(s)
Log Message:

File Contents

# User Rev Content
1 william 4 using System;
2     using System.Collections.Generic;
3     using System.Text;
4     using System.Data;
5     using System.Data.SqlClient;
6     using System.Windows.Forms;
7     using System.Text.RegularExpressions;
8     using System.Management;
9 william 33 using log4net;
10 william 74 using System.Security.Principal;
11 william 87 using AnywhereTS.DBSupport;
12 william 4
13     namespace AnywhereTS
14     {
15     class DatabaseSupport
16     {
17 william 131
18 william 4 enum VersionCheck
19     {
20 william 131 Failed = 0,
21     Equal,
22 william 21 DatabaseIsMoreNew,
23 william 131 DatabaseIsOlder,
24 william 21 //DatabaseNotFound,
25     DatabaseCreated,
26 william 4 };
27    
28 william 99 //private SqlConnection sqlCon = new SqlConnection();
29     //private SqlCommand sqlCmd = new SqlCommand();
30 william 4
31     const string SQL_BROWSER_SERVICE_NAME = "SQLBrowser";
32 william 99 public static string InstanceName { get { return AnywhereTS.DBSupport.Properties.Settings.Default.DBInstance; } }
33 william 4 public bool SetupDatabase()
34     {
35 william 87 Exception ErrorInfo = null;
36 william 107 try
37 william 131 {
38 william 107 bool bContinue = false;
39     // Create a connection to SQL Server
40 william 131 Logging.DatabaseLog.Debug("SetupDatabase() called ");
41 william 107 #region comment-code
42     #region Database Creation support
43     using (MsSqlConnector conn = new MsSqlConnector(ProSupport.strDatabaseServer, ProSupport.strDatabaseInstance, ATSGlobals.strDatabaseName))
44     {
45     try
46     {
47 william 119
48 william 107 conn.CreateConnection(out ErrorInfo);
49     conn.OpenConnection(out ErrorInfo);
50     }
51     catch (Exception ex)
52     {
53 william 132 Exception e = ex;
54 william 107 try
55 william 132 {
56 william 131 conn.CloseConnection(out ErrorInfo);
57 william 107 using (MsSqlConnector conn1 = new MsSqlConnector(ProSupport.strDatabaseServer, ProSupport.strDatabaseInstance, "master"))
58     {
59     try
60     {
61 william 131 conn1.CreateConnection(out ErrorInfo);
62     conn1.OpenConnection(out ErrorInfo);
63 william 39
64 william 131 // create datagbase
65     using (log4net.NDC.Push("SetupDatabase().CreateDatabase"))
66     {
67     Logging.DatabaseLog.Info(string.Format("Creating Database {0}", ATSGlobals.strDatabaseName));
68     RunScript(SQLServerResources.CreateDatabase, conn1, out ErrorInfo);
69     Logging.DatabaseLog.Info(string.Format("Created Database {0}", ATSGlobals.strDatabaseName));
70     }
71     using (log4net.NDC.Push("SetupDatabase().CreateTables"))
72     {
73     // create tables
74     Logging.DatabaseLog.Info(string.Format("Creating Tables in {0} Database", ATSGlobals.strDatabaseName));
75     RunScript(SQLServerResources.CreateTables, conn1, out ErrorInfo);
76     Logging.DatabaseLog.Info(string.Format("Created Tables in {0} Database", ATSGlobals.strDatabaseName));
77     }
78 william 107 }
79     catch (Exception ex1)
80     {
81 william 132 e = ex1.GetBaseException();
82     if (ErrorInfo == null) { ErrorInfo = e;}
83     throw ErrorInfo;
84 william 107 }
85     }
86     }
87     catch (Exception ex1)
88     {
89 william 132 e = ex1.GetBaseException();
90     if (ErrorInfo == null) { ErrorInfo = e; }
91     throw ErrorInfo;
92     }
93     e = ex.GetBaseException();
94     if (!e.Message.ToLower().Contains(string.Format("Cannot open database \"{0}\" requested by the login",ATSGlobals.strDatabaseName).ToLower()))
95     {
96     if (ErrorInfo == null) { ErrorInfo = e; }
97 william 107 throw ErrorInfo;
98     }
99     }
100     }
101     #endregion
102 william 4
103 william 107 #region Database version check
104     // Now that you are connected to Express, check the database versions
105     Version databaseVersion; // The current version of the database
106     int chkVer = CheckVersion(out databaseVersion);
107     VersionCheck verChk = (VersionCheck)chkVer;
108     //MessageBox.Show(string.Format("Version Check: {0} Version: {1}", verChk.ToString(), databaseVersion.ToString()));
109 william 131 Logging.DatabaseLog.InfoFormat("Database Version Check: {0} .... Database Version: {1}", verChk.ToString(), databaseVersion.ToString());
110 william 107 switch (chkVer)
111     {
112     case (int)VersionCheck.Equal:
113     {
114     bContinue = true;
115     break;
116     }
117     case (int)VersionCheck.Failed:
118     {
119     bContinue = false;
120     break;
121     }
122     case (int)VersionCheck.DatabaseIsOlder:
123     {
124     using (MsSqlConnector conn = new MsSqlConnector(ProSupport.strDatabaseServer, ProSupport.strDatabaseInstance, ATSGlobals.strDatabaseName))
125     {
126     try
127     {
128     conn.CreateConnection(out ErrorInfo);
129     conn.OpenConnection(out ErrorInfo);
130     #region database upggrade scripts
131     switch (databaseVersion.ToString())
132     {
133     // Run the apropriate upgdrade script(s)
134     case "1.0.0.0":
135     { // Current database is version 1.0.0.0, update to 1.0.0.1
136 william 131 Logging.DatabaseLog.InfoFormat("Upgrading Database from version: {0} to version: {1}", "1.0.0.0", "1.0.0.1");
137 william 107 bContinue = RunScript(SQLServerResources.UpdateDatabase1, conn, out ErrorInfo);
138 william 131 Logging.DatabaseLog.InfoFormat("Upgraded Database from version: {0} to version: {1}", "1.0.0.0", "1.0.0.1");
139 william 107 goto case "1.0.0.1"; // Continue and upgrade one more step
140     }
141     case "1.0.0.1":
142     { // Current database is version 1.0.0.1, update to 1.0.0.2
143 william 131 Logging.DatabaseLog.InfoFormat("Upgrading Database from version: {0} to version: {1}", "1.0.0.1", "1.0.0.2");
144 william 107 bContinue = RunScript(SQLServerResources.UpdateDatabase2, conn, out ErrorInfo);
145 william 131 Logging.DatabaseLog.InfoFormat("Upgraded Database from version: {0} to version: {1}", "1.0.0.2", "1.0.0.2");
146 william 107 goto case "1.0.0.2"; // Continue and upgrade one more step
147     }
148     case "1.0.0.2":
149     { // Current database is version 1.0.0.2, update to 1.0.0.3
150 william 131 Logging.DatabaseLog.InfoFormat("Upgrading Database from version: {0} to version: {1}", "1.0.0.2", "1.0.0.3");
151 william 107 bContinue = RunScript(SQLServerResources.UpdateDatabase3, conn, out ErrorInfo);
152 william 131 Logging.DatabaseLog.InfoFormat("Upgraded Database from version: {0} to version: {1}", "1.0.0.2", "1.0.0.3");
153 william 107 goto case "1.0.0.3"; // Continue and upgrade one more step
154     }
155     case "1.0.0.3":
156     { // Current database is version 1.0.0.3, update to 1.0.0.4
157 william 131 Logging.DatabaseLog.InfoFormat("Upgrading Database from version: {0} to version: {1}", "1.0.0.3", "1.0.0.4");
158 william 107 bContinue = RunScript(SQLServerResources.UpdateDatabase4, conn, out ErrorInfo);
159 william 131 Logging.DatabaseLog.InfoFormat("Upgraded Database from version: {0} to version: {1}", "1.0.0.4", "1.0.0.4");
160 william 107 break;
161     }
162     default:
163     {
164     //MessageBox.Show("Error: Not able to upgrade database (51188)");
165     if (databaseVersion == new Version(0, 0, 0, 0))
166     {
167     string format = string.Format("Database version is {0}, this should have been auto upgraded to {1}", databaseVersion.ToString(), ATSGlobals.strDatabaseVersion);
168 william 131 Logging.DatabaseLog.Fatal(format);
169 william 107 MessageBox.Show(format);
170     }
171     else
172     {
173     string format = string.Format("Failed to upgrade Database from version: {0} to version: {1}", databaseVersion.ToString(), ATSGlobals.strDatabaseVersion);
174 william 131 Logging.DatabaseLog.Fatal(format);
175 william 107 MessageBox.Show(format);
176     }
177     break;
178     }
179     }
180     #endregion
181     }
182     catch (Exception ex)
183     {
184     if (ErrorInfo == null) { ErrorInfo = ex; }
185     throw ErrorInfo;
186     }
187     }
188     break;
189     }
190     case (int)VersionCheck.DatabaseIsMoreNew:
191     {
192     bContinue = false;
193     break;
194     }
195     default:
196     {
197     bContinue = false;
198     break;
199     }
200    
201     }
202     #endregion
203     #endregion
204     return bContinue;
205     }
206 william 128
207 william 107 catch (Exception ex)
208     {
209 william 121 if (ErrorInfo == null)
210     {
211 william 128 ErrorInfo = ex.GetBaseException();
212 william 121 using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", ex.GetType().Name, ex.Message, System.Environment.NewLine, ex.ToString())))
213     {
214 william 131 Logging.DatabaseLog.Error(string.Format("SetupDatabase() failed"));
215 william 121 }
216     throw ErrorInfo;
217     }
218     else
219     {
220 william 128 ErrorInfo = ErrorInfo.GetBaseException();
221 william 121 using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", ErrorInfo.GetType().Name, ErrorInfo.Message, System.Environment.NewLine, ErrorInfo.ToString())))
222     {
223 william 131 Logging.DatabaseLog.Error(string.Format("SetupDatabase() failed"));
224 william 121 }
225     throw ErrorInfo;
226     }
227 william 107 }
228 william 4 }
229 william 87
230 william 131
231 william 87 public bool RunScript(string strFile, MsSqlConnector con, out Exception ErrorInfo)
232 william 74 {
233 william 87 ErrorInfo = null;
234 william 123 string cmd = strFile;
235     //cmd = cmd.Replace("[DataDir]", ProSupport.strDatabasePath);
236 william 87 con.RunScript(cmd, out ErrorInfo);
237     return false;
238 william 74 }
239 william 4 // Check the version of the datbase
240     public int CheckVersion(out Version vDb)
241     {
242 william 87 Exception ErrorInfo = null;
243 william 4 //Get Version information from application
244 william 131 Version v = new Version(ATSGlobals.strDatabaseVersion);
245 william 4 vDb = new Version("0.0.0.0"); // Assign a default value for version
246     try
247     {
248    
249 william 87 //string strResult;
250 william 4
251 william 87 int db_count = -1;
252 william 4 //Verify that the AnywhereTS database exists
253 william 87 #region Get Database Count
254 william 99 using (MsSqlConnector conn = new MsSqlConnector(ProSupport.strDatabaseServer, ProSupport.strDatabaseInstance, ATSGlobals.strDatabaseName))
255 william 87 {
256     try
257     {
258 william 131 SqlConnection sqlCon = conn.CreateConnection(out ErrorInfo);
259 william 87 conn.OpenConnection(out ErrorInfo);
260 william 131 //Logging.DatabaseLog.Debug(string.Format("Getting Coount of {0} databases", ATSGlobals.strDatabaseName));
261     SqlCommand sqlCmd = new SqlCommand(string.Format("select count(*) from master..sysdatabases where name='{0}'", ATSGlobals.strDatabaseName), sqlCon);
262     db_count = Convert.ToInt32(sqlCmd.ExecuteScalar());
263 william 21
264 william 131 Logging.DatabaseLog.Info(string.Format("Found {0} databases named {1}", db_count, ATSGlobals.strDatabaseName));
265 william 87 }
266     catch (Exception ex)
267     {
268     if (ErrorInfo == null)
269     {
270     ErrorInfo = ex;
271     using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", ex.GetType().Name, ex.Message, System.Environment.NewLine, ex.ToString())))
272     {
273 william 131 Logging.DatabaseLog.Error(string.Format("Failed to get count of databases named: {0}{1}", System.Environment.NewLine, ATSGlobals.strDatabaseName));
274 william 87 }
275 william 107 throw ErrorInfo;
276 william 87 }
277     else
278     {
279     ErrorInfo = ex.GetBaseException();
280     using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", ErrorInfo.GetType().Name, ErrorInfo.Message, System.Environment.NewLine, ErrorInfo.ToString())))
281     {
282 william 131 Logging.DatabaseLog.Error(string.Format("Failed to get count of databases named: {0}{1}", System.Environment.NewLine, ATSGlobals.strDatabaseName));
283 william 87 }
284 william 107 throw ErrorInfo;
285 william 87 }
286 william 107
287 william 87 }
288     }
289     #endregion
290     if (db_count == -1)
291 william 4 {
292 william 87 return (int)VersionCheck.Failed;
293 william 21 }
294 william 87 else if (db_count == 0)
295 william 4 {
296 william 88 #region Database Creation support
297 william 99 using (MsSqlConnector conn = new MsSqlConnector(ProSupport.strDatabaseServer, ProSupport.strDatabaseInstance, ATSGlobals.strDatabaseName))
298 william 88 {
299     try
300     {
301     conn.CreateConnection(out ErrorInfo);
302     conn.OpenConnection(out ErrorInfo);
303     }
304     catch (Exception ex)
305     {
306     try
307     {
308     conn.Dispose();
309 william 99 using (MsSqlConnector conn1 = new MsSqlConnector(ProSupport.strDatabaseServer, ProSupport.strDatabaseInstance, "master"))
310 william 88 {
311     try
312     {
313     conn1.CreateConnection(out ErrorInfo);
314     conn1.OpenConnection(out ErrorInfo);
315 william 41
316 william 88 // create datagbase
317 william 121 using (log4net.NDC.Push("CheckVersion().CreateDatabase"))
318     {
319 william 131 Logging.DatabaseLog.Info(string.Format("Creating Database {0}", ATSGlobals.strDatabaseName));
320 william 121 RunScript(SQLServerResources.CreateDatabase, conn1, out ErrorInfo);
321 william 131 Logging.DatabaseLog.Info(string.Format("Created Database {0}", ATSGlobals.strDatabaseName));
322 william 121 }
323     using (log4net.NDC.Push("CheckVersion().CreateTables"))
324     {
325     // create tables
326 william 131 Logging.DatabaseLog.Info(string.Format("Creating Tables in {0} Database", ATSGlobals.strDatabaseName));
327 william 121 RunScript(SQLServerResources.CreateTables, conn1, out ErrorInfo);
328 william 131 Logging.DatabaseLog.Info(string.Format("Created Tables in {0} Database", ATSGlobals.strDatabaseName));
329 william 121 }
330 william 88 }
331     catch (Exception ex1)
332     {
333     if (ErrorInfo == null) { ErrorInfo = new Exception(ex1.Message, ex); }
334 william 107 throw ErrorInfo;
335 william 88 }
336 william 107 throw ErrorInfo;
337 william 88 }
338     }
339     catch (Exception ex1)
340     {
341     if (ErrorInfo == null) { ErrorInfo = new Exception(ex1.Message, ex); }
342 william 107 throw ErrorInfo;
343 william 88 }
344     }
345     }
346 william 90 if (ErrorInfo != null) { return (int)VersionCheck.Failed; }
347 william 87 #endregion
348 william 41 }
349 william 87
350 william 131
351 william 87 #region Get Database Version
352 william 99 using (MsSqlConnector conn = new MsSqlConnector(ProSupport.strDatabaseServer, ProSupport.strDatabaseInstance, ATSGlobals.strDatabaseName))
353 william 41 {
354     try
355     {
356 william 131 SqlConnection sqlCon = conn.CreateConnection(out ErrorInfo);
357 william 87 conn.OpenConnection(out ErrorInfo);
358 william 41
359 william 131 //Logging.DatabaseLog.Debug(string.Format("Getting Coount of {0} databases", ATSGlobals.strDatabaseName));
360 william 41
361 william 131 SqlCommand sqlCmd = new SqlCommand(string.Format("SELECT value from {0}..AppInfo where property='version'", ATSGlobals.strDatabaseName), sqlCon);
362     string version = (string)sqlCmd.ExecuteScalar();
363 william 87 vDb = new Version(version);
364 william 131 Logging.DatabaseLog.Info(string.Format("Database {0} is at Version: {1}", ATSGlobals.strDatabaseName, version));
365 william 41 }
366 william 87 catch (Exception ex)
367 william 41 {
368 william 87 if (ErrorInfo == null)
369 william 41 {
370 william 87 ErrorInfo = ex;
371     using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", ex.GetType().Name, ex.Message, System.Environment.NewLine, ex.ToString())))
372     {
373 william 131 Logging.DatabaseLog.Error(string.Format("Failed to get count of databases named: {0}{1}", System.Environment.NewLine, ATSGlobals.strDatabaseName));
374 william 87 }
375 william 107 throw ErrorInfo;
376 william 41 }
377 william 87 else
378     {
379     ErrorInfo = ex.GetBaseException();
380     using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", ErrorInfo.GetType().Name, ErrorInfo.Message, System.Environment.NewLine, ErrorInfo.ToString())))
381     {
382 william 131 Logging.DatabaseLog.Error(string.Format("Failed to get count of databases named: {0}{1}", System.Environment.NewLine, ATSGlobals.strDatabaseName));
383 william 87 }
384 william 107 throw ErrorInfo;
385 william 87 }
386 william 22 }
387 william 4 }
388 william 87 #endregion
389    
390     #region old-code might still need
391     //try
392     //{
393     // //using (log4net.NDC.Push(string.Format("SQL Statment={0}", "SELECT value from {0}..AppInfo where property='version'", ATSGlobals.strDatabaseName)))
394     // //{
395 william 131 // Logging.DatabaseLog.Debug(string.Format("Getting {0} Database Version#1", ATSGlobals.strDatabaseName));
396 william 87 // sqlCon = new SqlConnection(Properties.Settings.Default.atsConnectionString.Replace(ATSGlobals.strDatabaseName, "master"));
397     // if (sqlCon.State != ConnectionState.Open) sqlCon.Open();
398     // sqlCmd = new SqlCommand(string.Format("SELECT value from {0}..AppInfo where property='version'",ATSGlobals.strDatabaseName), sqlCon);
399     // strResult = (string)sqlCmd.ExecuteScalar();
400     // sqlCon.Close();
401     // //}
402 william 131 // Logging.DatabaseLog.DebugFormat("{0} database version={1}",ATSGlobals.strDatabaseName, strResult);
403 william 87 //}
404     //catch(SqlException ex)
405     //{
406     // // the database exists, but one or more tables are missing
407     // using (log4net.NDC.Push(string.Format("SqlException: ID={0} MESSAGE={1}{2}Diagnostics:{2}{3}", ex.Number.ToString(), ex.Message, System.Environment.NewLine, ex.ToString())))
408     // {
409 william 131 // Logging.DatabaseLog.Error("Failed to get database version");
410 william 87 // }
411     // try
412     // {
413     // //using (log4net.NDC.Push(string.Format("SQL Statment={0}", SQLServerResources.CreateTables)))
414     // //{
415 william 131 // Logging.DatabaseLog.Debug(string.Format("Creating Tables in {0} Database in CheckVersion()", ATSGlobals.strDatabaseName));
416 william 87 // sqlCon = new SqlConnection(Properties.Settings.Default.atsConnectionString.Replace(ATSGlobals.strDatabaseName, "master"));
417     // if (sqlCon.State != ConnectionState.Open) sqlCon.Open();
418     // RunScript(SQLServerResources.CreateTables);
419     // sqlCon.Close();
420     // //}
421 william 131 // Logging.DatabaseLog.Debug(string.Format("Created Tables in {0} Database in CheckVersion()", ATSGlobals.strDatabaseName));
422 william 87 // using (log4net.NDC.Push(string.Format("SQL Statment={0}", string.Format("SELECT value from {0}..AppInfo where property='version'", ATSGlobals.strDatabaseName))))
423     // {
424 william 131 // Logging.DatabaseLog.Debug(string.Format("Getting {0} Database Version#2", ATSGlobals.strDatabaseName));
425 william 87 // sqlCon = new SqlConnection(Properties.Settings.Default.atsConnectionString.Replace(ATSGlobals.strDatabaseName, "master"));
426     // if (sqlCon.State != ConnectionState.Open) sqlCon.Open();
427     // sqlCmd = new SqlCommand(string.Format("SELECT value from {0}..AppInfo where property='version'", ATSGlobals.strDatabaseName), sqlCon);
428     // strResult = (string)sqlCmd.ExecuteScalar();
429     // sqlCon.Close();
430     // }
431 william 131 // Logging.DatabaseLog.DebugFormat("{0} database version={1}",ATSGlobals.strDatabaseName, strResult);
432 william 87 // }
433     // catch(SqlException ex1)
434     // {
435     // using (log4net.NDC.Push(string.Format("SqlException: ID={0} MESSAGE={1}{2}Diagnostics:{2}{3}", ex1.Number.ToString(), ex1.Message, System.Environment.NewLine, ex1.ToString())))
436     // {
437 william 131 // Logging.DatabaseLog.Error("Failed to get database version");
438 william 87 // }
439     // return (int)VersionCheck.Failed;
440     // }
441     //}
442     #endregion
443 william 131
444    
445 william 99 //sqlCon.Close();
446 william 4
447     if (vDb == v)
448     return (int)VersionCheck.Equal;
449    
450     if (vDb > v)
451     return (int)VersionCheck.DatabaseIsMoreNew;
452    
453 william 131 else
454 william 4 return (int)VersionCheck.DatabaseIsOlder;
455 william 131
456 william 4 }
457     catch (SqlException sql_ex)
458     {
459     MessageBox.Show(sql_ex.Number.ToString() + " " + sql_ex.Message.ToString());
460 william 41 using (log4net.NDC.Push(string.Format("SqlException: ID={0} MESSAGE={1}{2}Diagnostics:{2}{3}", sql_ex.Number.ToString(), sql_ex.Message, System.Environment.NewLine, sql_ex.ToString())))
461     {
462 william 131 Logging.DatabaseLog.Error("Failed to check database version");
463 william 41 }
464 william 4 return (int)VersionCheck.Failed;
465     }
466     catch (Exception system_ex)
467     {
468     MessageBox.Show(system_ex.Message.ToString());
469 william 41 using (log4net.NDC.Push(string.Format("SqlException: MESSAGE={0}{1}Diagnostics:{1}{2}", system_ex.Message, System.Environment.NewLine, system_ex.ToString())))
470     {
471 william 131 Logging.DatabaseLog.Error("Failed to check database version");
472 william 41 }
473 william 4 return (int)VersionCheck.Failed;
474     }
475     }
476    
477    
478 william 21
479 william 131
480 william 123 //[Obsolete("SetDatabaseRights() has been deperecated - user rights are assigned via SQL Server", true)]
481     //public static void SetDatabaseRights()
482     //{
483     // try
484     // {
485     // // Add an access control entry to the database file.
486     // //ProSupport.GrantRWaccessForRemoteDesktopUsers(ProSupport.strDatabasePath + @"\" + ProSupport.strDatabaseFilename);
487     // //ProSupport.GrantRWaccessForRemoteDesktopUsers(ProSupport.strDatabasePath + @"\" + ProSupport.strDatabaseFilename2);
488     // }
489     // catch (Exception e)
490     // {
491     // MessageBox.Show("Cannot set access rights for users to the database. Do you have the sufficient rights? Application will abort. Error: " + e.Message);
492     // using (log4net.NDC.Push(string.Format("SqlException: MESSAGE={0}{1}Diagnostics:{1}{2}", e.Message, System.Environment.NewLine, e.ToString())))
493     // {
494 william 131 // Logging.DatabaseLog.Fatal("Cannot set access rights for users to the database.");
495 william 123 // }
496     // Application.Exit();
497     // return;
498     // }
499     //}
500 william 4
501     public static void StartSQLbrowserService()
502     {
503     System.ServiceProcess.ServiceController srvController = new System.ServiceProcess.ServiceController(SQL_BROWSER_SERVICE_NAME);
504     try
505     {
506     // Check that the SQL browser service is not already running
507     if (srvController.Status != System.ServiceProcess.ServiceControllerStatus.Running)
508     { // Service not running, start it.
509     srvController.Start();
510     srvController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, TimeSpan.FromSeconds(50));
511     }
512     }
513    
514     catch (Exception e)
515     {
516     MessageBox.Show("Could not start the SQL Browser service (13078). Error:" + e.Message);
517 william 46 using (log4net.NDC.Push(string.Format("SqlException: MESSAGE={0}{1}Diagnostics:{1}{2}", e.Message, System.Environment.NewLine, e.ToString())))
518     {
519 william 131 Logging.DatabaseLog.Error("Could not start the SQL Browser service (13078).");
520 william 46 }
521 william 4 }
522     }
523    
524     // Configure the SQL browser service to autostart
525     public static void AutostartSQLbrowserService()
526     {
527     try
528     {
529     //construct the management path
530     string path = "Win32_Service.Name='" + SQL_BROWSER_SERVICE_NAME + "'";
531     using (ManagementObject service = new ManagementObject(new ManagementPath(path)))
532     {
533     object[] parameters = new object[1];
534     parameters[0] = "Automatic";
535     service.InvokeMethod("ChangeStartMode", parameters);
536    
537     }
538     }
539 william 131 catch (Exception e)
540 william 4 {
541 william 17 MessageBox.Show("Error, could not configure SQL Browser service (24888). Please check that SQL Server is intalled and that you are logged in with sufficient rights to configure services. Then retry the operation.");
542 william 46 using (log4net.NDC.Push(string.Format("SqlException: MESSAGE={0}{1}Diagnostics:{1}{2}", e.Message, System.Environment.NewLine, e.ToString())))
543     {
544 william 131 Logging.DatabaseLog.Fatal("Could not configure SQL Browser service (24888). Please check that SQL Server is intalled and that you are logged in with sufficient rights to configure services. Then retry the operation.");
545 william 46 }
546 william 4 }
547     }
548    
549     // Enable named pipes on the SQL Express server
550     public static bool EnableNamedPipes()
551 william 131 {
552 william 4 ManagementScope manScope = new ManagementScope(@"\\.\root\Microsoft\SqlServer\ComputerManagement");
553     ManagementClass sqlServicesMan = new ManagementClass(manScope, new ManagementPath("SqlService"), null);
554     ManagementClass serverProtocolsMan = new ManagementClass(manScope, new ManagementPath("ServerNetworkProtocol"), null);
555     bool restarted = false; // Indicating if restart of SQL server was performed
556    
557     sqlServicesMan.Get();
558     serverProtocolsMan.Get();
559    
560     foreach (ManagementObject prot in serverProtocolsMan.GetInstances())
561     {
562     prot.Get();
563     if ((string)prot.GetPropertyValue("ProtocolName") == "Np" && //Named pipes
564 william 17 (string)prot.GetPropertyValue("InstanceName") == InstanceName)
565 william 4 { // We found the named pipes protocol
566     if (!(bool)prot.GetPropertyValue("Enabled"))
567     { // Named pipes not activated
568     prot.InvokeMethod("SetEnable", null); // Activate named pipes
569 william 131
570 william 4 // Check if user wants to restart SQL server
571     DialogResult resultRights;
572 william 17 resultRights = MessageBox.Show(string.Format("In order for users to use the AnywhereTS control panel, the {0} service on this computer need to be restarted. This operation might take up to 60 seconds. Do you want restart the {0} service now?", InstanceName), string.Format("AnywhereTS - Restart {0} (This operation might take up to 60 seconds!)", InstanceName), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
573 william 4 if (resultRights == DialogResult.Yes)
574     {
575     // Restart the SQL server
576     const uint sqlServerService = 1;
577     const uint sqlServiceStopped = 1;
578     foreach (ManagementObject svc in sqlServicesMan.GetInstances())
579     {
580     if ((uint)svc.GetPropertyValue("SqlServiceType") == sqlServerService &&
581 william 17 (string)svc.GetPropertyValue("ServiceName") == string.Format("MSSQL${0}", InstanceName))
582 william 4 {
583     svc.Get();
584     if ((uint)svc.GetPropertyValue("State") != sqlServiceStopped)
585     {
586     svc.InvokeMethod("StopService", null);
587     }
588     svc.InvokeMethod("StartService", null);
589     restarted = true;
590     } // end if
591     }
592     }
593     } // end if 'named pipes protool'
594     }
595     } // foreach
596    
597     return restarted;
598     }
599     }
600     }