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

Contents of /trunk/TSAdminTool/Database.cs

Parent Directory Parent Directory | Revision Log Revision Log


Revision 128 - (show annotations) (download)
Sat Jul 14 13:01:52 2012 UTC (8 years ago) by william
File size: 34294 byte(s)
+ fix RunScript ==> CommandType must be set to Text

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

  ViewVC Help
Powered by ViewVC 1.1.22