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

Contents of /trunk/TSAdminTool/Database.cs

Parent Directory Parent Directory | Revision Log Revision Log


Revision 123 - (show annotations) (download)
Sat Jul 14 11:14:09 2012 UTC (8 years ago) by william
File size: 34210 byte(s)
+ bulk commit
-- add SQLSerer SMO support for executing TSQL commands

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;
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 conn.CreateConnection(out ErrorInfo);
250 conn.OpenConnection(out ErrorInfo);
251
252 //Logging.ATSAdminLog.Debug(string.Format("Getting Coount of {0} databases", ATSGlobals.strDatabaseName));
253
254 SqlCommand cmd = conn.CreateCommandInstance(string.Format("select count(*) from master..sysdatabases where name='{0}'", ATSGlobals.strDatabaseName), new List<SqlParameter>(), out ErrorInfo);
255 db_count = Convert.ToInt32(cmd.ExecuteScalar());
256
257 Logging.ATSAdminLog.Info(string.Format("Found {0} databases named {1}", db_count, ATSGlobals.strDatabaseName));
258 }
259 catch (Exception ex)
260 {
261 if (ErrorInfo == null)
262 {
263 ErrorInfo = ex;
264 using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", ex.GetType().Name, ex.Message, System.Environment.NewLine, ex.ToString())))
265 {
266 Logging.ATSAdminLog.Error(string.Format("Failed to get count of databases named: {0}{1}", System.Environment.NewLine, ATSGlobals.strDatabaseName));
267 }
268 throw ErrorInfo;
269 }
270 else
271 {
272 ErrorInfo = ex.GetBaseException();
273 using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", ErrorInfo.GetType().Name, ErrorInfo.Message, System.Environment.NewLine, ErrorInfo.ToString())))
274 {
275 Logging.ATSAdminLog.Error(string.Format("Failed to get count of databases named: {0}{1}", System.Environment.NewLine, ATSGlobals.strDatabaseName));
276 }
277 throw ErrorInfo;
278 }
279
280 }
281 }
282 #endregion
283 if (db_count == -1)
284 {
285 return (int)VersionCheck.Failed;
286 }
287 else if (db_count == 0)
288 {
289 #region Database Creation support
290 using (MsSqlConnector conn = new MsSqlConnector(ProSupport.strDatabaseServer, ProSupport.strDatabaseInstance, ATSGlobals.strDatabaseName))
291 {
292 try
293 {
294 conn.CreateConnection(out ErrorInfo);
295 conn.OpenConnection(out ErrorInfo);
296 }
297 catch (Exception ex)
298 {
299 try
300 {
301 conn.Dispose();
302 using (MsSqlConnector conn1 = new MsSqlConnector(ProSupport.strDatabaseServer, ProSupport.strDatabaseInstance, "master"))
303 {
304 try
305 {
306 conn1.CreateConnection(out ErrorInfo);
307 conn1.OpenConnection(out ErrorInfo);
308
309 // create datagbase
310 using (log4net.NDC.Push("CheckVersion().CreateDatabase"))
311 {
312 Logging.ATSAdminLog.Info(string.Format("Creating Database {0}", ATSGlobals.strDatabaseName));
313 RunScript(SQLServerResources.CreateDatabase, conn1, out ErrorInfo);
314 Logging.ATSAdminLog.Info(string.Format("Created Database {0}", ATSGlobals.strDatabaseName));
315 }
316 using (log4net.NDC.Push("CheckVersion().CreateTables"))
317 {
318 // create tables
319 Logging.ATSAdminLog.Info(string.Format("Creating Tables in {0} Database", ATSGlobals.strDatabaseName));
320 RunScript(SQLServerResources.CreateTables, conn1, out ErrorInfo);
321 Logging.ATSAdminLog.Info(string.Format("Created Tables in {0} Database", ATSGlobals.strDatabaseName));
322 }
323 }
324 catch (Exception ex1)
325 {
326 if (ErrorInfo == null) { ErrorInfo = new Exception(ex1.Message, ex); }
327 throw ErrorInfo;
328 }
329 throw ErrorInfo;
330 }
331 }
332 catch (Exception ex1)
333 {
334 if (ErrorInfo == null) { ErrorInfo = new Exception(ex1.Message, ex); }
335 throw ErrorInfo;
336 }
337 }
338 }
339 if (ErrorInfo != null) { return (int)VersionCheck.Failed; }
340 #endregion
341 }
342
343
344 #region Get Database Version
345 using (MsSqlConnector conn = new MsSqlConnector(ProSupport.strDatabaseServer, ProSupport.strDatabaseInstance, ATSGlobals.strDatabaseName))
346 {
347 try
348 {
349 conn.CreateConnection(out ErrorInfo);
350 conn.OpenConnection(out ErrorInfo);
351
352 //Logging.ATSAdminLog.Debug(string.Format("Getting Coount of {0} databases", ATSGlobals.strDatabaseName));
353
354 SqlCommand cmd = conn.CreateCommandInstance(string.Format("SELECT value from {0}..AppInfo where property='version'", ATSGlobals.strDatabaseName), new List<SqlParameter>(), out ErrorInfo);
355 string version = (string)cmd.ExecuteScalar();
356 vDb = new Version(version);
357 Logging.ATSAdminLog.Info(string.Format("Database {0} is at Version: {1}", ATSGlobals.strDatabaseName, version));
358 }
359 catch (Exception ex)
360 {
361 if (ErrorInfo == null)
362 {
363 ErrorInfo = ex;
364 using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", ex.GetType().Name, ex.Message, System.Environment.NewLine, ex.ToString())))
365 {
366 Logging.ATSAdminLog.Error(string.Format("Failed to get count of databases named: {0}{1}", System.Environment.NewLine, ATSGlobals.strDatabaseName));
367 }
368 throw ErrorInfo;
369 }
370 else
371 {
372 ErrorInfo = ex.GetBaseException();
373 using (log4net.NDC.Push(string.Format("{0}: MESSAGE={1}{2}Diagnostics:{2}{3}", ErrorInfo.GetType().Name, ErrorInfo.Message, System.Environment.NewLine, ErrorInfo.ToString())))
374 {
375 Logging.ATSAdminLog.Error(string.Format("Failed to get count of databases named: {0}{1}", System.Environment.NewLine, ATSGlobals.strDatabaseName));
376 }
377 throw ErrorInfo;
378 }
379 }
380 }
381 #endregion
382
383 #region old-code might still need
384 //try
385 //{
386 // //using (log4net.NDC.Push(string.Format("SQL Statment={0}", "SELECT value from {0}..AppInfo where property='version'", ATSGlobals.strDatabaseName)))
387 // //{
388 // Logging.ATSAdminLog.Debug(string.Format("Getting {0} Database Version#1", ATSGlobals.strDatabaseName));
389 // sqlCon = new SqlConnection(Properties.Settings.Default.atsConnectionString.Replace(ATSGlobals.strDatabaseName, "master"));
390 // if (sqlCon.State != ConnectionState.Open) sqlCon.Open();
391 // sqlCmd = new SqlCommand(string.Format("SELECT value from {0}..AppInfo where property='version'",ATSGlobals.strDatabaseName), sqlCon);
392 // strResult = (string)sqlCmd.ExecuteScalar();
393 // sqlCon.Close();
394 // //}
395 // Logging.ATSAdminLog.DebugFormat("{0} database version={1}",ATSGlobals.strDatabaseName, strResult);
396 //}
397 //catch(SqlException ex)
398 //{
399 // // the database exists, but one or more tables are missing
400 // 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())))
401 // {
402 // Logging.ATSAdminLog.Error("Failed to get database version");
403 // }
404 // try
405 // {
406 // //using (log4net.NDC.Push(string.Format("SQL Statment={0}", SQLServerResources.CreateTables)))
407 // //{
408 // Logging.ATSAdminLog.Debug(string.Format("Creating Tables in {0} Database in CheckVersion()", ATSGlobals.strDatabaseName));
409 // sqlCon = new SqlConnection(Properties.Settings.Default.atsConnectionString.Replace(ATSGlobals.strDatabaseName, "master"));
410 // if (sqlCon.State != ConnectionState.Open) sqlCon.Open();
411 // RunScript(SQLServerResources.CreateTables);
412 // sqlCon.Close();
413 // //}
414 // Logging.ATSAdminLog.Debug(string.Format("Created Tables in {0} Database in CheckVersion()", ATSGlobals.strDatabaseName));
415 // using (log4net.NDC.Push(string.Format("SQL Statment={0}", string.Format("SELECT value from {0}..AppInfo where property='version'", ATSGlobals.strDatabaseName))))
416 // {
417 // Logging.ATSAdminLog.Debug(string.Format("Getting {0} Database Version#2", ATSGlobals.strDatabaseName));
418 // sqlCon = new SqlConnection(Properties.Settings.Default.atsConnectionString.Replace(ATSGlobals.strDatabaseName, "master"));
419 // if (sqlCon.State != ConnectionState.Open) sqlCon.Open();
420 // sqlCmd = new SqlCommand(string.Format("SELECT value from {0}..AppInfo where property='version'", ATSGlobals.strDatabaseName), sqlCon);
421 // strResult = (string)sqlCmd.ExecuteScalar();
422 // sqlCon.Close();
423 // }
424 // Logging.ATSAdminLog.DebugFormat("{0} database version={1}",ATSGlobals.strDatabaseName, strResult);
425 // }
426 // catch(SqlException ex1)
427 // {
428 // 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())))
429 // {
430 // Logging.ATSAdminLog.Error("Failed to get database version");
431 // }
432 // return (int)VersionCheck.Failed;
433 // }
434 //}
435 #endregion
436
437
438 //sqlCon.Close();
439
440 if (vDb == v)
441 return (int)VersionCheck.Equal;
442
443 if (vDb > v)
444 return (int)VersionCheck.DatabaseIsMoreNew;
445
446 else
447 return (int)VersionCheck.DatabaseIsOlder;
448
449 }
450 catch (SqlException sql_ex)
451 {
452 MessageBox.Show(sql_ex.Number.ToString() + " " + sql_ex.Message.ToString());
453 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())))
454 {
455 Logging.ATSAdminLog.Error("Failed to check database version");
456 }
457 return (int)VersionCheck.Failed;
458 }
459 catch (Exception system_ex)
460 {
461 MessageBox.Show(system_ex.Message.ToString());
462 using (log4net.NDC.Push(string.Format("SqlException: MESSAGE={0}{1}Diagnostics:{1}{2}", system_ex.Message, System.Environment.NewLine, system_ex.ToString())))
463 {
464 Logging.ATSAdminLog.Error("Failed to check database version");
465 }
466 return (int)VersionCheck.Failed;
467 }
468 }
469
470
471
472
473 //[Obsolete("SetDatabaseRights() has been deperecated - user rights are assigned via SQL Server", true)]
474 //public static void SetDatabaseRights()
475 //{
476 // try
477 // {
478 // // Add an access control entry to the database file.
479 // //ProSupport.GrantRWaccessForRemoteDesktopUsers(ProSupport.strDatabasePath + @"\" + ProSupport.strDatabaseFilename);
480 // //ProSupport.GrantRWaccessForRemoteDesktopUsers(ProSupport.strDatabasePath + @"\" + ProSupport.strDatabaseFilename2);
481 // }
482 // catch (Exception e)
483 // {
484 // MessageBox.Show("Cannot set access rights for users to the database. Do you have the sufficient rights? Application will abort. Error: " + e.Message);
485 // using (log4net.NDC.Push(string.Format("SqlException: MESSAGE={0}{1}Diagnostics:{1}{2}", e.Message, System.Environment.NewLine, e.ToString())))
486 // {
487 // Logging.ATSAdminLog.Fatal("Cannot set access rights for users to the database.");
488 // }
489 // Application.Exit();
490 // return;
491 // }
492 //}
493
494 public static void StartSQLbrowserService()
495 {
496 System.ServiceProcess.ServiceController srvController = new System.ServiceProcess.ServiceController(SQL_BROWSER_SERVICE_NAME);
497 try
498 {
499 // Check that the SQL browser service is not already running
500 if (srvController.Status != System.ServiceProcess.ServiceControllerStatus.Running)
501 { // Service not running, start it.
502 srvController.Start();
503 srvController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, TimeSpan.FromSeconds(50));
504 }
505 }
506
507 catch (Exception e)
508 {
509 MessageBox.Show("Could not start the SQL Browser service (13078). Error:" + e.Message);
510 using (log4net.NDC.Push(string.Format("SqlException: MESSAGE={0}{1}Diagnostics:{1}{2}", e.Message, System.Environment.NewLine, e.ToString())))
511 {
512 Logging.ATSAdminLog.Error("Could not start the SQL Browser service (13078).");
513 }
514 }
515 }
516
517 // Configure the SQL browser service to autostart
518 public static void AutostartSQLbrowserService()
519 {
520 try
521 {
522 //construct the management path
523 string path = "Win32_Service.Name='" + SQL_BROWSER_SERVICE_NAME + "'";
524 using (ManagementObject service = new ManagementObject(new ManagementPath(path)))
525 {
526 object[] parameters = new object[1];
527 parameters[0] = "Automatic";
528 service.InvokeMethod("ChangeStartMode", parameters);
529
530 }
531 }
532 catch(Exception e)
533 {
534 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.");
535 using (log4net.NDC.Push(string.Format("SqlException: MESSAGE={0}{1}Diagnostics:{1}{2}", e.Message, System.Environment.NewLine, e.ToString())))
536 {
537 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.");
538 }
539 }
540 }
541
542 // Enable named pipes on the SQL Express server
543 public static bool EnableNamedPipes()
544 {
545 ManagementScope manScope = new ManagementScope(@"\\.\root\Microsoft\SqlServer\ComputerManagement");
546 ManagementClass sqlServicesMan = new ManagementClass(manScope, new ManagementPath("SqlService"), null);
547 ManagementClass serverProtocolsMan = new ManagementClass(manScope, new ManagementPath("ServerNetworkProtocol"), null);
548 bool restarted = false; // Indicating if restart of SQL server was performed
549
550 sqlServicesMan.Get();
551 serverProtocolsMan.Get();
552
553 foreach (ManagementObject prot in serverProtocolsMan.GetInstances())
554 {
555 prot.Get();
556 if ((string)prot.GetPropertyValue("ProtocolName") == "Np" && //Named pipes
557 (string)prot.GetPropertyValue("InstanceName") == InstanceName)
558 { // We found the named pipes protocol
559 if (!(bool)prot.GetPropertyValue("Enabled"))
560 { // Named pipes not activated
561 prot.InvokeMethod("SetEnable", null); // Activate named pipes
562
563 // Check if user wants to restart SQL server
564 DialogResult resultRights;
565 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);
566 if (resultRights == DialogResult.Yes)
567 {
568 // Restart the SQL server
569 const uint sqlServerService = 1;
570 const uint sqlServiceStopped = 1;
571 foreach (ManagementObject svc in sqlServicesMan.GetInstances())
572 {
573 if ((uint)svc.GetPropertyValue("SqlServiceType") == sqlServerService &&
574 (string)svc.GetPropertyValue("ServiceName") == string.Format("MSSQL${0}", InstanceName))
575 {
576 svc.Get();
577 if ((uint)svc.GetPropertyValue("State") != sqlServiceStopped)
578 {
579 svc.InvokeMethod("StopService", null);
580 }
581 svc.InvokeMethod("StartService", null);
582 restarted = true;
583 } // end if
584 }
585 }
586 } // end if 'named pipes protool'
587 }
588 } // foreach
589
590 return restarted;
591 }
592 }
593 }

  ViewVC Help
Powered by ViewVC 1.1.22