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

Contents of /trunk/TSAdminTool/Database.cs

Parent Directory Parent Directory | Revision Log Revision Log


Revision 131 - (show annotations) (download)
Sun Jul 15 02:55:20 2012 UTC (8 years, 10 months ago) by william
File size: 33942 byte(s)
+ move all database options to DatabaseLog (even if it comes from ATSAdmin.exe)

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

  ViewVC Help
Powered by ViewVC 1.1.22