/src/sqltools/SqlWebAdminCS/App_Code/CS/SmoHelper.cs

# · C# · 324 lines · 247 code · 40 blank · 37 comment · 43 complexity · dd8bed27e12ec3ea23f2563e4135ca41 MD5 · raw file

  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Web;
  5. using System.Web.Security;
  6. using System.Web.UI;
  7. using System.Web.UI.WebControls;
  8. using System.Web.UI.WebControls.WebParts;
  9. using System.Web.UI.HtmlControls;
  10. using System.Data.SqlClient;
  11. using Microsoft.SqlServer.Management;
  12. using Microsoft.SqlServer.Management.Common;
  13. using Smo = Microsoft.SqlServer.Management.Smo;
  14. using System.Collections.Generic;
  15. /// <summary>
  16. /// Helper class to make it easier to request objects or collections from the
  17. /// SQL Server
  18. /// </summary>
  19. namespace SqlWebAdmin.CSharp
  20. {
  21. public sealed class SmoHelper
  22. {
  23. // make constructor private to keep the class from being instantiated
  24. private SmoHelper()
  25. {
  26. }
  27. public static Microsoft.SqlServer.Management.Smo.Server CurrentServer
  28. {
  29. get
  30. {
  31. HttpContext context = HttpContext.Current;
  32. return context.Cache[String.Format("{0}:CurrentServer", context.Session.SessionID)] as Smo.Server;
  33. }
  34. set
  35. {
  36. HttpContext context = HttpContext.Current;
  37. //context.Cache[String.Format("{0}:CurrentServer", context.Session.SessionID)] = value;
  38. context.Cache.Insert(String.Format("{0}:CurrentServer", context.Session.SessionID), value);
  39. }
  40. }
  41. public static void ResetServer(ref Smo.Server smoServer)
  42. {
  43. HttpContext.Current.Trace.Write("SmoHelper", "Resetting SMO Server");
  44. ServerConnection currentConnection = smoServer.ConnectionContext;
  45. smoServer = new Microsoft.SqlServer.Management.Smo.Server(currentConnection);
  46. }
  47. public static string GetConnectionString()
  48. {
  49. string returnValue = null;
  50. HttpContext context = HttpContext.Current;
  51. context.Trace.Write("SmoHelper", "End GetConnectionString");
  52. if (context != null)
  53. {
  54. string cryptConnString = (string)context.Profile["ConnectionString"];
  55. if (cryptConnString == null || cryptConnString.Length < 1)
  56. context.Response.Redirect(SiteUrls.Credentials());
  57. string clearConnString = string.Empty;
  58. try
  59. {
  60. Encryption crypt = Encryption.Current();
  61. returnValue = crypt.Decrypt(cryptConnString);
  62. }
  63. catch (Exception ex)
  64. {
  65. HttpContext.Current.Response.Redirect(String.Format("~/credentials.aspx?Error={0}&RU={1}", context.Server.UrlEncode(ex.Message), context.Request["SCRIPT_NAME"]));
  66. }
  67. }
  68. context.Trace.Write("SmoHelper", "End GetConnectionString");
  69. return returnValue;
  70. }
  71. /// <summary>
  72. /// Method to return an Smo.Server instance based on information in the Session. If the expected
  73. /// session key is not in the session this will cause an exception to be thrown. Use the <see>GetServer</see>
  74. /// method that allows you to pass in the server name as a parameter to the method.
  75. /// </summary>
  76. /// <returns></returns>
  77. public static Microsoft.SqlServer.Management.Smo.Server GetServer()
  78. {
  79. Smo.Server server = null;
  80. HttpContext context = HttpContext.Current;
  81. if (context != null)
  82. {
  83. context.Trace.Write("SmoHelper", "Begin GetServer");
  84. if (CurrentServer == null)
  85. {
  86. string clearConnString = GetConnectionString();
  87. server = new Microsoft.SqlServer.Management.Smo.Server(new ServerConnection(new SqlConnection(clearConnString)));
  88. try
  89. {
  90. // get a build number from ther server, this will ensure that we have connected with the server.
  91. int buildNumber = server.ConnectionContext.ServerVersion.BuildNumber;
  92. }
  93. catch (ConnectionFailureException sqlex)
  94. {
  95. //HttpContext context = HttpContext.Current;
  96. context.Response.Redirect(String.Format("~/credentials.aspx?Error={0}&RU={1}", context.Server.UrlEncode(sqlex.Message), context.Request["SCRIPT_NAME"]));
  97. // context.Response.End();
  98. }
  99. CurrentServer = server;
  100. }
  101. else
  102. {
  103. context.Trace.Write("Cache Hit", "Extracting Connection from user Cache");
  104. server = CurrentServer;
  105. if (server.ConnectionContext.IsOpen == false)
  106. server.ConnectionContext.Connect();
  107. // The cache here is really a connection cache. We won't have to pay the price of retrieving and decrypting
  108. // the connection string from the profile data store.
  109. ResetServer(ref server);
  110. }
  111. context.Trace.Write("SmoHelper", "Begin GetServer");
  112. return server;
  113. }
  114. else
  115. throw new System.InvalidOperationException("Trying to access an unspecified server");
  116. }
  117. /// <summary>
  118. ///
  119. /// </summary>
  120. /// <param name="serverName"></param>
  121. /// <returns></returns>
  122. public static Microsoft.SqlServer.Management.Smo.Server GetServer(string serverName, bool useIntegratedSecurity, string username, string password)
  123. {
  124. Smo.Server smoServer = new Microsoft.SqlServer.Management.Smo.Server(serverName);
  125. if (useIntegratedSecurity)
  126. {
  127. smoServer.ConnectionContext.LoginSecure = false;
  128. smoServer.ConnectionContext.Login = username;
  129. smoServer.ConnectionContext.Password = password;
  130. }
  131. return smoServer;
  132. }
  133. public static Smo.DatabaseCollection GetDatabases()
  134. {
  135. Smo.Server server = GetServer();
  136. if (server != null)
  137. return server.Databases;
  138. else
  139. return null;
  140. }
  141. public static Smo.Database GetDatabase()
  142. {
  143. HttpContext context = HttpContext.Current;
  144. if (context != null)
  145. {
  146. string databaseName = context.Request.QueryString[QueryStringKeys.Database];
  147. if (databaseName != null)
  148. {
  149. Smo.DatabaseCollection databases = GetDatabases();
  150. if (databases != null)
  151. {
  152. if (databases.Contains(databaseName))
  153. return databases[databaseName];
  154. else
  155. throw new Exception(String.Format("Database ({0}) not found.", databaseName));
  156. }
  157. else
  158. throw new InvalidOperationException("No databases found for the server");
  159. }
  160. else
  161. throw new InvalidOperationException("Could not retrieve a database object without be instructed as to which specific database to access");
  162. }
  163. else
  164. throw new InvalidOperationException("Could not retrieve a database object without be instructed as to which specific database to access");
  165. }
  166. public static Smo.TableCollection GetTables()
  167. {
  168. HttpContext context = HttpContext.Current;
  169. Smo.Database db = GetDatabase();
  170. if (db != null)
  171. {
  172. return db.Tables;
  173. }
  174. return null;
  175. }
  176. public static Smo.Table GetTable()
  177. {
  178. HttpContext context = HttpContext.Current;
  179. context.Trace.Write("SmoHelper", "Begin GetTable");
  180. Smo.Database db = GetDatabase();
  181. Smo.Table returnValue = null;
  182. if (db != null)
  183. {
  184. string tableName = context.Request.QueryString[QueryStringKeys.Table];
  185. string schemaName = context.Request.QueryString[QueryStringKeys.Schema];
  186. if (String.IsNullOrEmpty(tableName))
  187. throw new ArgumentNullException(QueryStringKeys.Table, "Table name was not specified");
  188. if (db.Tables.Contains(tableName, schemaName))
  189. {
  190. returnValue = db.Tables[tableName, schemaName];
  191. }
  192. }
  193. context.Trace.Write("SmoHelper", "End GetTable");
  194. // fall through
  195. return null;
  196. }
  197. public static Smo.StoredProcedureCollection GetStoredProcedures()
  198. {
  199. HttpContext context = HttpContext.Current;
  200. Smo.Database db = GetDatabase();
  201. if (db != null)
  202. {
  203. return db.StoredProcedures;
  204. }
  205. return null;
  206. }
  207. public static Smo.StoredProcedure GetStoredProcedure()
  208. {
  209. HttpContext context = HttpContext.Current;
  210. Smo.Database db = GetDatabase();
  211. if (db != null)
  212. {
  213. string procedureName = context.Request.QueryString[QueryStringKeys.StoredProcedure];
  214. string schemaName = context.Request.QueryString[QueryStringKeys.Schema];
  215. if (String.IsNullOrEmpty(procedureName))
  216. throw new ArgumentNullException(QueryStringKeys.StoredProcedure, "Stored Procedure name was not specified");
  217. if (db.StoredProcedures.Contains(procedureName, schemaName))
  218. {
  219. return db.StoredProcedures[procedureName, schemaName];
  220. }
  221. }
  222. // fall through
  223. return null;
  224. }
  225. public static List<Smo.Database> FilterSystemObjects(Smo.DatabaseCollection dbc, bool hideUserObjects)
  226. {
  227. List<Smo.Database> dbCollection = new List<Microsoft.SqlServer.Management.Smo.Database>();
  228. for (int i = 0; i < dbc.Count; i++)
  229. {
  230. if (dbc[i].IsSystemObject == hideUserObjects)
  231. dbCollection.Add(dbc[i]);
  232. }
  233. return dbCollection;
  234. }
  235. public static List<Smo.Table> FilterSystemObjects(Smo.TableCollection tbc, bool hideUserObjects)
  236. {
  237. List<Smo.Table> tbCollection = new List<Microsoft.SqlServer.Management.Smo.Table>();
  238. for (int i = 0; i < tbc.Count; i++)
  239. {
  240. if (tbc[i].IsSystemObject == hideUserObjects)
  241. tbCollection.Add(tbc[i]);
  242. }
  243. return tbCollection;
  244. }
  245. public static List<Smo.StoredProcedure> FilterSystemObjects(Smo.StoredProcedureCollection spc, bool hideUserObjects)
  246. {
  247. List<Smo.StoredProcedure> spCollection = new List<Microsoft.SqlServer.Management.Smo.StoredProcedure>();
  248. for (int i = 0; i < spc.Count; i++)
  249. {
  250. if (spc[i].IsSystemObject == hideUserObjects)
  251. spCollection.Add(spc[i]);
  252. }
  253. return spCollection;
  254. }
  255. public static List<Smo.Database> ListUserDatabases(Smo.DatabaseCollection dbc, bool hideUserObjects)
  256. {
  257. HttpContext context = HttpContext.Current;
  258. context.Trace.Write("SmoHelper", "Start ListUserDatabases");
  259. List<Smo.Database> dbCollection = new List<Microsoft.SqlServer.Management.Smo.Database>();
  260. DateTime start = DateTime.Now;
  261. foreach (Smo.Database db in dbc)
  262. {
  263. if (db.IsAccessible)
  264. dbCollection.Add(db);
  265. }
  266. //for (int i = 0; i < dbc.Count; i++)
  267. //{
  268. // try
  269. // {
  270. // int cnt = dbc[i].Tables.Count; // force it to check to see if we have access to table.
  271. // if(dbc[i].IsSystemObject == hideUserObjects)
  272. // dbCollection.Add(dbc[i]);
  273. // }
  274. // catch(Exception ex)
  275. // {
  276. // HttpContext.Current.Trace.Warn("Database Access Exception",String.Format("Exception: {0}", ex.Message));
  277. // }
  278. //}
  279. DateTime end = DateTime.Now;
  280. context.Trace.Write("SmoHelper", "End ListUserDatabases");
  281. return dbCollection;
  282. }
  283. }
  284. }