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

Annotation of /trunk/TSAdminTool/Database.cs

Parent Directory Parent Directory | Revision Log Revision Log


Revision 87 - (hide annotations) (download)
Fri Jul 13 22:37:40 2012 UTC (9 years, 2 months ago) by william
File size: 31269 byte(s)
+ start implementation of AnywhereTS.DBSupport

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

  ViewVC Help
Powered by ViewVC 1.1.22