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

Annotation of /trunk/TSAdminTool/Database.cs

Parent Directory Parent Directory | Revision Log Revision Log


Revision 74 - (hide annotations) (download)
Fri Jul 13 00:43:28 2012 UTC (9 years, 2 months ago) by william
File size: 30187 byte(s)
ATSGlobals.strDatabaseName

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

  ViewVC Help
Powered by ViewVC 1.1.22