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

Contents of /trunk/TSAdminTool/Database.cs

Parent Directory Parent Directory | Revision Log Revision Log


Revision 121 - (show annotations) (download)
Sat Jul 14 09:40:33 2012 UTC (9 years, 2 months ago) by william
File size: 34134 byte(s)
+ log context

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

  ViewVC Help
Powered by ViewVC 1.1.22