/[AnywhereTS-MSSQL]/trunk/TSAdminTool/Database.cs
ViewVC logotype

Contents of /trunk/TSAdminTool/Database.cs

Parent Directory Parent Directory | Revision Log Revision Log


Revision 134 - (show annotations) (download)
Sun Jul 15 05:13:20 2012 UTC (9 years, 4 months ago) by william
File size: 35260 byte(s)
+ fix errors in database
+ logon to 'master' database and refer to our database is sql statments
+ remove empty GO statements from end of .sql files

1 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 using log4net;
10 using System.Security.Principal;
11 using AnywhereTS.DBSupport;
12
13 namespace AnywhereTS
14 {
15 class DatabaseSupport
16 {
17
18 enum VersionCheck
19 {
20 Failed = 0,
21 Equal,
22 DatabaseIsMoreNew,
23 DatabaseIsOlder,
24 //DatabaseNotFound,
25 DatabaseCreated,
26 };
27
28 //private SqlConnection sqlCon = new SqlConnection();
29 //private SqlCommand sqlCmd = new SqlCommand();
30
31 const string SQL_BROWSER_SERVICE_NAME = "SQLBrowser";
32 public static string InstanceName { get { return AnywhereTS.DBSupport.Properties.Settings.Default.DBInstance; } }
33 public bool SetupDatabase()
34 {
35 Exception ErrorInfo = null;
36 try
37 {
38 bool bContinue = false;
39 // Create a connection to SQL Server
40 Logging.DatabaseLog.Debug("SetupDatabase() called ");
41 #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
48 conn.CreateConnection(out ErrorInfo);
49 conn.OpenConnection(out ErrorInfo);
50 }
51 catch (Exception ex)
52 {
53 Exception e = ex;
54 try
55 {
56 conn.CloseConnection(out ErrorInfo);
57 using (MsSqlConnector conn1 = new MsSqlConnector(ProSupport.strDatabaseServer, ProSupport.strDatabaseInstance, "master"))
58 {
59 try
60 {
61 conn1.CreateConnection(out ErrorInfo);
62 conn1.OpenConnection(out ErrorInfo);
63
64 // 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 }
79 catch (Exception ex1)
80 {
81 e = ex1.GetBaseException();
82 if (ErrorInfo == null) { ErrorInfo = e;}
83 throw ErrorInfo;
84 }
85 }
86 }
87 catch (Exception ex1)
88 {
89 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 throw ErrorInfo;
98 }
99 }
100 }
101 #endregion
102
103 #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 Logging.DatabaseLog.InfoFormat("Database Version Check: {0} .... Database Version: {1}", verChk.ToString(), databaseVersion.ToString());
110 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, "master"))
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 Logging.DatabaseLog.InfoFormat("Upgrading Database from version: {0} to version: {1}", "1.0.0.0", "1.0.0.1");
137 bContinue = RunScript(SQLServerResources.UpdateDatabase1, conn, out ErrorInfo);
138 Logging.DatabaseLog.InfoFormat("Upgraded Database from version: {0} to version: {1}", "1.0.0.0", "1.0.0.1");
139 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 Logging.DatabaseLog.InfoFormat("Upgrading Database from version: {0} to version: {1}", "1.0.0.1", "1.0.0.2");
144 bContinue = RunScript(SQLServerResources.UpdateDatabase2, conn, out ErrorInfo);
145 Logging.DatabaseLog.InfoFormat("Upgraded Database from version: {0} to version: {1}", "1.0.0.2", "1.0.0.2");
146 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 Logging.DatabaseLog.InfoFormat("Upgrading Database from version: {0} to version: {1}", "1.0.0.2", "1.0.0.3");
151 bContinue = RunScript(SQLServerResources.UpdateDatabase3, conn, out ErrorInfo);
152 Logging.DatabaseLog.InfoFormat("Upgraded Database from version: {0} to version: {1}", "1.0.0.2", "1.0.0.3");
153 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 Logging.DatabaseLog.InfoFormat("Upgrading Database from version: {0} to version: {1}", "1.0.0.3", "1.0.0.4");
158 bContinue = RunScript(SQLServerResources.UpdateDatabase4, conn, out ErrorInfo);
159 Logging.DatabaseLog.InfoFormat("Upgraded Database from version: {0} to version: {1}", "1.0.0.3", "1.0.0.4");
160 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 Logging.DatabaseLog.Fatal(format);
169 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 Logging.DatabaseLog.Fatal(format);
175 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
207 catch (Exception ex)
208 {
209 if (ErrorInfo == null)
210 {
211 ErrorInfo = ex.GetBaseException();
212 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 Logging.DatabaseLog.Error(string.Format("SetupDatabase() failed"));
215 }
216 throw ErrorInfo;
217 }
218 else
219 {
220 ErrorInfo = ErrorInfo.GetBaseException();
221 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 Logging.DatabaseLog.Error(string.Format("SetupDatabase() failed"));
224 }
225 throw ErrorInfo;
226 }
227 }
228 }
229
230
231 public bool RunScript(string strFile, MsSqlConnector con, out Exception ErrorInfo)
232 {
233 ErrorInfo = null;
234 string cmd = strFile;
235 //cmd = cmd.Replace("[DataDir]", ProSupport.strDatabasePath);
236 con.RunScript(cmd, out ErrorInfo);
237 return false;
238 }
239 // Check the version of the datbase
240 public int CheckVersion(out Version vDb)
241 {
242 Exception ErrorInfo = null;
243 //Get Version information from application
244 Version v = new Version(ATSGlobals.strDatabaseVersion);
245 vDb = new Version("0.0.0.0"); // Assign a default value for version
246 try
247 {
248
249 //string strResult;
250
251 int db_count = -1;
252 //Verify that the AnywhereTS database exists
253 #region Get Database Count
254 using (MsSqlConnector conn = new MsSqlConnector(ProSupport.strDatabaseServer, ProSupport.strDatabaseInstance, "master"))
255 {
256 try
257 {
258 conn.CreateConnection(out ErrorInfo);
259 conn.OpenConnection(out ErrorInfo);
260 SqlConnection sqlCon;
261 conn.GetConnectionClone(out sqlCon, out ErrorInfo);
262 SqlCommand sqlCmd = new SqlCommand();
263 sqlCmd.CommandText = string.Format("select count(*) from master..sysdatabases where name='{0}'", ATSGlobals.strDatabaseName);
264 sqlCmd.CommandType = CommandType.Text;
265 sqlCmd.Connection = sqlCon;
266 try
267 {
268 db_count = Convert.ToInt32(sqlCmd.ExecuteScalar());
269 }
270 catch (Exception ex)
271 {
272 Exception e = ex.GetBaseException();
273 using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", e.GetType().Name, e.Message, System.Environment.NewLine, e.ToString())))
274 {
275 Logging.DatabaseLog.Error(string.Format("sqlCmd.ExecuteScalar() failed"));
276 }
277 }
278
279 Logging.DatabaseLog.Info(string.Format("Found {0} databases named {1}", db_count, ATSGlobals.strDatabaseName));
280 }
281 catch (Exception ex)
282 {
283 if (ErrorInfo == null)
284 {
285 ErrorInfo = ex;
286 using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", ex.GetType().Name, ex.Message, System.Environment.NewLine, ex.ToString())))
287 {
288 Logging.DatabaseLog.Error(string.Format("Failed to get count of databases named: {0}{1}", System.Environment.NewLine, ATSGlobals.strDatabaseName));
289 }
290 throw ErrorInfo;
291 }
292 else
293 {
294 ErrorInfo = ex.GetBaseException();
295 using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", ErrorInfo.GetType().Name, ErrorInfo.Message, System.Environment.NewLine, ErrorInfo.ToString())))
296 {
297 Logging.DatabaseLog.Error(string.Format("Failed to get count of databases named: {0}{1}", System.Environment.NewLine, ATSGlobals.strDatabaseName));
298 }
299 throw ErrorInfo;
300 }
301
302 }
303 }
304 #endregion
305 if (db_count == -1)
306 {
307 return (int)VersionCheck.Failed;
308 }
309 else if (db_count == 0)
310 {
311 #region Database Creation support
312 using (MsSqlConnector conn = new MsSqlConnector(ProSupport.strDatabaseServer, ProSupport.strDatabaseInstance, ATSGlobals.strDatabaseName))
313 {
314 try
315 {
316 conn.CreateConnection(out ErrorInfo);
317 conn.OpenConnection(out ErrorInfo);
318 }
319 catch (Exception ex)
320 {
321 try
322 {
323 conn.Dispose();
324 using (MsSqlConnector conn1 = new MsSqlConnector(ProSupport.strDatabaseServer, ProSupport.strDatabaseInstance, "master"))
325 {
326 try
327 {
328 conn1.CreateConnection(out ErrorInfo);
329 conn1.OpenConnection(out ErrorInfo);
330
331 // create datagbase
332 using (log4net.NDC.Push("CheckVersion().CreateDatabase"))
333 {
334 Logging.DatabaseLog.Info(string.Format("Creating Database {0}", ATSGlobals.strDatabaseName));
335 RunScript(SQLServerResources.CreateDatabase, conn1, out ErrorInfo);
336 Logging.DatabaseLog.Info(string.Format("Created Database {0}", ATSGlobals.strDatabaseName));
337 }
338 using (log4net.NDC.Push("CheckVersion().CreateTables"))
339 {
340 // create tables
341 Logging.DatabaseLog.Info(string.Format("Creating Tables in {0} Database", ATSGlobals.strDatabaseName));
342 RunScript(SQLServerResources.CreateTables, conn1, out ErrorInfo);
343 Logging.DatabaseLog.Info(string.Format("Created Tables in {0} Database", ATSGlobals.strDatabaseName));
344 }
345 }
346 catch (Exception ex1)
347 {
348 if (ErrorInfo == null) { ErrorInfo = new Exception(ex1.Message, ex); }
349 throw ErrorInfo;
350 }
351 throw ErrorInfo;
352 }
353 }
354 catch (Exception ex1)
355 {
356 if (ErrorInfo == null) { ErrorInfo = new Exception(ex1.Message, ex); }
357 throw ErrorInfo;
358 }
359 }
360 }
361 if (ErrorInfo != null) { return (int)VersionCheck.Failed; }
362 #endregion
363 }
364
365
366 #region Get Database Version
367 using (MsSqlConnector conn = new MsSqlConnector(ProSupport.strDatabaseServer, ProSupport.strDatabaseInstance, "master"))
368 {
369 try
370 {
371 conn.CreateConnection(out ErrorInfo);
372 conn.OpenConnection(out ErrorInfo);
373 SqlConnection sqlCon;
374 conn.GetConnectionClone(out sqlCon, out ErrorInfo);
375 SqlCommand sqlCmd = new SqlCommand();
376 sqlCmd.CommandText = string.Format("SELECT value from {0}..AppInfo where property='version'", ATSGlobals.strDatabaseName);
377 sqlCmd.CommandType = CommandType.Text;
378 sqlCmd.Connection = sqlCon;
379 string version = (string)sqlCmd.ExecuteScalar();
380 vDb = new Version(version);
381 Logging.DatabaseLog.Info(string.Format("Database {0} is at Version: {1}", ATSGlobals.strDatabaseName, version));
382 }
383 catch (Exception ex)
384 {
385 if (ErrorInfo == null)
386 {
387 ErrorInfo = ex;
388 using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", ex.GetType().Name, ex.Message, System.Environment.NewLine, ex.ToString())))
389 {
390 Logging.DatabaseLog.Error(string.Format("Failed to get count of databases named: {0}{1}", System.Environment.NewLine, ATSGlobals.strDatabaseName));
391 }
392 throw ErrorInfo;
393 }
394 else
395 {
396 ErrorInfo = ex.GetBaseException();
397 using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", ErrorInfo.GetType().Name, ErrorInfo.Message, System.Environment.NewLine, ErrorInfo.ToString())))
398 {
399 Logging.DatabaseLog.Error(string.Format("Failed to get count of databases named: {0}{1}", System.Environment.NewLine, ATSGlobals.strDatabaseName));
400 }
401 throw ErrorInfo;
402 }
403 }
404 }
405 #endregion
406
407 #region old-code might still need
408 //try
409 //{
410 // //using (log4net.NDC.Push(string.Format("SQL Statment={0}", "SELECT value from {0}..AppInfo where property='version'", ATSGlobals.strDatabaseName)))
411 // //{
412 // Logging.DatabaseLog.Debug(string.Format("Getting {0} Database Version#1", ATSGlobals.strDatabaseName));
413 // sqlCon = new SqlConnection(Properties.Settings.Default.atsConnectionString.Replace(ATSGlobals.strDatabaseName, "master"));
414 // if (sqlCon.State != ConnectionState.Open) sqlCon.Open();
415 // sqlCmd = new SqlCommand(string.Format("SELECT value from {0}..AppInfo where property='version'",ATSGlobals.strDatabaseName), sqlCon);
416 // strResult = (string)sqlCmd.ExecuteScalar();
417 // sqlCon.Close();
418 // //}
419 // Logging.DatabaseLog.DebugFormat("{0} database version={1}",ATSGlobals.strDatabaseName, strResult);
420 //}
421 //catch(SqlException ex)
422 //{
423 // // the database exists, but one or more tables are missing
424 // 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())))
425 // {
426 // Logging.DatabaseLog.Error("Failed to get database version");
427 // }
428 // try
429 // {
430 // //using (log4net.NDC.Push(string.Format("SQL Statment={0}", SQLServerResources.CreateTables)))
431 // //{
432 // Logging.DatabaseLog.Debug(string.Format("Creating Tables in {0} Database in CheckVersion()", ATSGlobals.strDatabaseName));
433 // sqlCon = new SqlConnection(Properties.Settings.Default.atsConnectionString.Replace(ATSGlobals.strDatabaseName, "master"));
434 // if (sqlCon.State != ConnectionState.Open) sqlCon.Open();
435 // RunScript(SQLServerResources.CreateTables);
436 // sqlCon.Close();
437 // //}
438 // Logging.DatabaseLog.Debug(string.Format("Created Tables in {0} Database in CheckVersion()", ATSGlobals.strDatabaseName));
439 // using (log4net.NDC.Push(string.Format("SQL Statment={0}", string.Format("SELECT value from {0}..AppInfo where property='version'", ATSGlobals.strDatabaseName))))
440 // {
441 // Logging.DatabaseLog.Debug(string.Format("Getting {0} Database Version#2", ATSGlobals.strDatabaseName));
442 // sqlCon = new SqlConnection(Properties.Settings.Default.atsConnectionString.Replace(ATSGlobals.strDatabaseName, "master"));
443 // if (sqlCon.State != ConnectionState.Open) sqlCon.Open();
444 // sqlCmd = new SqlCommand(string.Format("SELECT value from {0}..AppInfo where property='version'", ATSGlobals.strDatabaseName), sqlCon);
445 // strResult = (string)sqlCmd.ExecuteScalar();
446 // sqlCon.Close();
447 // }
448 // Logging.DatabaseLog.DebugFormat("{0} database version={1}",ATSGlobals.strDatabaseName, strResult);
449 // }
450 // catch(SqlException ex1)
451 // {
452 // 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())))
453 // {
454 // Logging.DatabaseLog.Error("Failed to get database version");
455 // }
456 // return (int)VersionCheck.Failed;
457 // }
458 //}
459 #endregion
460
461
462 //sqlCon.Close();
463
464 if (vDb == v)
465 return (int)VersionCheck.Equal;
466
467 if (vDb > v)
468 return (int)VersionCheck.DatabaseIsMoreNew;
469
470 else
471 return (int)VersionCheck.DatabaseIsOlder;
472
473 }
474 catch (SqlException sql_ex)
475 {
476 MessageBox.Show(sql_ex.Number.ToString() + " " + sql_ex.Message.ToString());
477 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())))
478 {
479 Logging.DatabaseLog.Error("Failed to check database version");
480 }
481 return (int)VersionCheck.Failed;
482 }
483 catch (Exception system_ex)
484 {
485 MessageBox.Show(system_ex.Message.ToString());
486 using (log4net.NDC.Push(string.Format("SqlException: MESSAGE={0}{1}Diagnostics:{1}{2}", system_ex.Message, System.Environment.NewLine, system_ex.ToString())))
487 {
488 Logging.DatabaseLog.Error("Failed to check database version");
489 }
490 return (int)VersionCheck.Failed;
491 }
492 }
493
494
495
496
497 //[Obsolete("SetDatabaseRights() has been deperecated - user rights are assigned via SQL Server", true)]
498 //public static void SetDatabaseRights()
499 //{
500 // try
501 // {
502 // // Add an access control entry to the database file.
503 // //ProSupport.GrantRWaccessForRemoteDesktopUsers(ProSupport.strDatabasePath + @"\" + ProSupport.strDatabaseFilename);
504 // //ProSupport.GrantRWaccessForRemoteDesktopUsers(ProSupport.strDatabasePath + @"\" + ProSupport.strDatabaseFilename2);
505 // }
506 // catch (Exception e)
507 // {
508 // MessageBox.Show("Cannot set access rights for users to the database. Do you have the sufficient rights? Application will abort. Error: " + e.Message);
509 // using (log4net.NDC.Push(string.Format("SqlException: MESSAGE={0}{1}Diagnostics:{1}{2}", e.Message, System.Environment.NewLine, e.ToString())))
510 // {
511 // Logging.DatabaseLog.Fatal("Cannot set access rights for users to the database.");
512 // }
513 // Application.Exit();
514 // return;
515 // }
516 //}
517
518 public static void StartSQLbrowserService()
519 {
520 System.ServiceProcess.ServiceController srvController = new System.ServiceProcess.ServiceController(SQL_BROWSER_SERVICE_NAME);
521 try
522 {
523 // Check that the SQL browser service is not already running
524 if (srvController.Status != System.ServiceProcess.ServiceControllerStatus.Running)
525 { // Service not running, start it.
526 srvController.Start();
527 srvController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, TimeSpan.FromSeconds(50));
528 }
529 }
530
531 catch (Exception e)
532 {
533 MessageBox.Show("Could not start the SQL Browser service (13078). Error:" + e.Message);
534 using (log4net.NDC.Push(string.Format("SqlException: MESSAGE={0}{1}Diagnostics:{1}{2}", e.Message, System.Environment.NewLine, e.ToString())))
535 {
536 Logging.DatabaseLog.Error("Could not start the SQL Browser service (13078).");
537 }
538 }
539 }
540
541 // Configure the SQL browser service to autostart
542 public static void AutostartSQLbrowserService()
543 {
544 try
545 {
546 //construct the management path
547 string path = "Win32_Service.Name='" + SQL_BROWSER_SERVICE_NAME + "'";
548 using (ManagementObject service = new ManagementObject(new ManagementPath(path)))
549 {
550 object[] parameters = new object[1];
551 parameters[0] = "Automatic";
552 service.InvokeMethod("ChangeStartMode", parameters);
553
554 }
555 }
556 catch (Exception e)
557 {
558 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.");
559 using (log4net.NDC.Push(string.Format("SqlException: MESSAGE={0}{1}Diagnostics:{1}{2}", e.Message, System.Environment.NewLine, e.ToString())))
560 {
561 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.");
562 }
563 }
564 }
565
566 // Enable named pipes on the SQL Express server
567 public static bool EnableNamedPipes()
568 {
569 ManagementScope manScope = new ManagementScope(@"\\.\root\Microsoft\SqlServer\ComputerManagement");
570 ManagementClass sqlServicesMan = new ManagementClass(manScope, new ManagementPath("SqlService"), null);
571 ManagementClass serverProtocolsMan = new ManagementClass(manScope, new ManagementPath("ServerNetworkProtocol"), null);
572 bool restarted = false; // Indicating if restart of SQL server was performed
573
574 sqlServicesMan.Get();
575 serverProtocolsMan.Get();
576
577 foreach (ManagementObject prot in serverProtocolsMan.GetInstances())
578 {
579 prot.Get();
580 if ((string)prot.GetPropertyValue("ProtocolName") == "Np" && //Named pipes
581 (string)prot.GetPropertyValue("InstanceName") == InstanceName)
582 { // We found the named pipes protocol
583 if (!(bool)prot.GetPropertyValue("Enabled"))
584 { // Named pipes not activated
585 prot.InvokeMethod("SetEnable", null); // Activate named pipes
586
587 // Check if user wants to restart SQL server
588 DialogResult resultRights;
589 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);
590 if (resultRights == DialogResult.Yes)
591 {
592 // Restart the SQL server
593 const uint sqlServerService = 1;
594 const uint sqlServiceStopped = 1;
595 foreach (ManagementObject svc in sqlServicesMan.GetInstances())
596 {
597 if ((uint)svc.GetPropertyValue("SqlServiceType") == sqlServerService &&
598 (string)svc.GetPropertyValue("ServiceName") == string.Format("MSSQL${0}", InstanceName))
599 {
600 svc.Get();
601 if ((uint)svc.GetPropertyValue("State") != sqlServiceStopped)
602 {
603 svc.InvokeMethod("StopService", null);
604 }
605 svc.InvokeMethod("StartService", null);
606 restarted = true;
607 } // end if
608 }
609 }
610 } // end if 'named pipes protool'
611 }
612 } // foreach
613
614 return restarted;
615 }
616 }
617 }

  ViewVC Help
Powered by ViewVC 1.1.22