PageRenderTime 49ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/Tools/LinqPad/LINQPad/Extensibility/DataContext/AstoriaHelper.cs

https://github.com/vishalsh-spec/TestProject
C# | 315 lines | 301 code | 14 blank | 0 comment | 40 complexity | caf45e912a51335c99592a639f20d983 MD5 | raw file
Possible License(s): CC-BY-SA-3.0, LGPL-2.0, Apache-2.0
  1. namespace LINQPad.Extensibility.DataContext
  2. {
  3. using LINQPad;
  4. using Microsoft.CSharp;
  5. using System;
  6. using System.CodeDom.Compiler;
  7. using System.Collections.Generic;
  8. using System.Data;
  9. using System.Data.Services.Client;
  10. using System.Data.Services.Design;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Net;
  14. using System.Reflection;
  15. using System.Runtime.InteropServices;
  16. using System.Text.RegularExpressions;
  17. using System.Xml;
  18. using System.Xml.Linq;
  19. using System.Xml.Schema;
  20. internal static class AstoriaHelper
  21. {
  22. private const string DesignDllErrorMessage = "Cannot load System.Data.Services.Design.dll. (A possible cause is installing the .NET Framework Client Profile instead of the full .NET Framework.)";
  23. private static void BuildAssembly(string code, AssemblyName name)
  24. {
  25. CompilerResults results;
  26. string str = "v4.0";
  27. string str2 = "";
  28. Dictionary<string, string> providerOptions = new Dictionary<string, string>();
  29. providerOptions.Add("CompilerVersion", str);
  30. using (CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions))
  31. {
  32. CompilerParameters options = new CompilerParameters(("System.dll System.Core.dll System.Xml.dll " + str2 + "System.Data.Services.Client.dll").Split(new char[0]), name.CodeBase, true);
  33. results = provider.CompileAssemblyFromSource(options, new string[] { code });
  34. }
  35. if (results.Errors.Count > 0)
  36. {
  37. string msg = string.Concat(new object[] { "Cannot compile typed context: ", results.Errors[0].ErrorText, " (line ", results.Errors[0].Line, ")" });
  38. if (results.Errors[0].ErrorNumber == "CS0513")
  39. {
  40. msg = msg + "\r\nHave you forgotten to call SetEntitySetAccessRule(...) and SetServiceOperationAccessRule(...) in your Data Service?";
  41. }
  42. throw new DisplayToUserException(msg);
  43. }
  44. }
  45. private static string GenerateCode(XmlReader reader, string nameSpace)
  46. {
  47. EntityClassGenerator generator = new EntityClassGenerator(LanguageOption.GenerateCSharpCode) {
  48. Version = DataServiceCodeVersion.V2
  49. };
  50. StringWriter targetWriter = new StringWriter();
  51. try
  52. {
  53. IList<EdmSchemaError> list = generator.GenerateCode(reader, targetWriter, nameSpace);
  54. if (list.Count > 0)
  55. {
  56. throw new DisplayToUserException(string.Concat(new object[] { "Bad schema: ", list[0].Message, " (line ", list[0].Line, ")" }));
  57. }
  58. }
  59. catch (MetadataException exception)
  60. {
  61. throw new DisplayToUserException("MetadataException: " + exception.Message);
  62. }
  63. catch (XmlSchemaValidationException exception2)
  64. {
  65. throw new DisplayToUserException("This schema is unsupported.\r\n\r\nEntityClassGenerator returned the following error: " + exception2.Message);
  66. }
  67. catch (FileNotFoundException exception3)
  68. {
  69. if (exception3.Message.Contains("System.Data.Services.Design"))
  70. {
  71. throw new DisplayToUserException("Cannot load System.Data.Services.Design.dll. (A possible cause is installing only the .NET Framework Client Profile instead of the full .NET Framework.)");
  72. }
  73. throw;
  74. }
  75. return targetWriter.ToString();
  76. }
  77. private static List<ExplorerItem> GetSchema(XDocument data, out string typeName, out string nameSpace)
  78. {
  79. return new AstoriaSchemaReader(data).GetSchema(out typeName, out nameSpace);
  80. }
  81. internal static List<ExplorerItem> GetSchemaAndBuildAssembly(IConnectionInfo r, AssemblyName name, ref string nameSpace, ref string typeName)
  82. {
  83. XmlReader reader;
  84. XDocument document;
  85. string str;
  86. string str2;
  87. try
  88. {
  89. using (new PushDefaultWebProxy())
  90. {
  91. using (reader = GetSchemaReader(r))
  92. {
  93. document = XDocument.Load(reader);
  94. }
  95. }
  96. }
  97. catch (Exception exception)
  98. {
  99. Log.Write(exception, "Astoria GetSchema");
  100. throw new DisplayToUserException(exception.Message);
  101. }
  102. try
  103. {
  104. using (reader = document.CreateReader())
  105. {
  106. str = GenerateCode(reader, nameSpace);
  107. }
  108. }
  109. catch (FileNotFoundException exception2)
  110. {
  111. if (exception2.Message.Contains("System.Data.Services.Design"))
  112. {
  113. throw new DisplayToUserException("Cannot load System.Data.Services.Design.dll. (A possible cause is installing the .NET Framework Client Profile instead of the full .NET Framework.)");
  114. }
  115. throw;
  116. }
  117. BuildAssembly(str, name);
  118. List<ExplorerItem> list = GetSchema(document, out typeName, out str2);
  119. if (!(!Regex.IsMatch(str, @"^\s*namespace\s+" + nameSpace + "." + str2 + @"\b", RegexOptions.Multiline) || Regex.IsMatch(str, @"^\s*namespace\s+" + nameSpace + @"\b", RegexOptions.Multiline)))
  120. {
  121. nameSpace = nameSpace + "." + str2;
  122. }
  123. return list;
  124. }
  125. private static XmlReader GetSchemaReader(IConnectionInfo r)
  126. {
  127. Uri metadataUri = new DataServiceContext(new Uri(r.DatabaseInfo.Server)).GetMetadataUri();
  128. XmlReaderSettings settings = new XmlReaderSettings();
  129. XmlResolver resolver = new XmlUrlResolver();
  130. if (r.DatabaseInfo.UserName.Length > 0)
  131. {
  132. resolver.Credentials = new NetworkCredential(r.DatabaseInfo.UserName, r.DatabaseInfo.Password);
  133. }
  134. else
  135. {
  136. resolver.Credentials = CredentialCache.DefaultNetworkCredentials;
  137. }
  138. settings.XmlResolver = resolver;
  139. return XmlReader.Create(metadataUri.ToString(), settings);
  140. }
  141. internal static void InitializeContext(IConnectionInfo r, object context, bool dallas)
  142. {
  143. DataServiceContext context2 = (DataServiceContext) context;
  144. context2.ResolveType = name => Type.GetType("LINQPad.User." + name.Split(new char[] { '.' }).Last<string>());
  145. if (dallas)
  146. {
  147. string str = (string) r.DriverData.Element("AccountKey");
  148. if (!string.IsNullOrEmpty(str))
  149. {
  150. str = r.Decrypt(str);
  151. }
  152. if (!string.IsNullOrEmpty(str))
  153. {
  154. context2.Credentials = new NetworkCredential("accountkey", str);
  155. }
  156. }
  157. else if (r.DatabaseInfo.UserName.Length > 0)
  158. {
  159. context2.Credentials = new NetworkCredential(r.DatabaseInfo.UserName, r.DatabaseInfo.Password);
  160. }
  161. else
  162. {
  163. context2.Credentials = CredentialCache.DefaultNetworkCredentials;
  164. }
  165. context2.SendingRequest += delegate (object sender, SendingRequestEventArgs e) {
  166. WebProxy webProxy = Util.GetWebProxy();
  167. if (webProxy != null)
  168. {
  169. e.Request.Proxy = webProxy;
  170. }
  171. DataContextBase.SqlLog.WriteLine(e.Request.RequestUri);
  172. };
  173. }
  174. internal static void PreprocessObjectToWrite(ref object objectToWrite, ObjectGraphInfo info)
  175. {
  176. if (objectToWrite is DataServiceQuery)
  177. {
  178. objectToWrite = ((DataServiceQuery) objectToWrite).Execute();
  179. }
  180. if (objectToWrite is QueryOperationResponse)
  181. {
  182. QueryOperationResponse qor = (QueryOperationResponse) objectToWrite;
  183. if (qor.GetType().IsGenericType && (qor.GetType().GetGenericTypeDefinition() == typeof(QueryOperationResponse<>)))
  184. {
  185. objectToWrite = Util.VerticalRun(new object[] { new QueryOperationResponseWrapper(true, qor), new QueryOperationResponseWrapper(false, qor) });
  186. }
  187. }
  188. else if (objectToWrite is QueryOperationResponseWrapper)
  189. {
  190. QueryOperationResponseWrapper wrapper = (QueryOperationResponseWrapper) objectToWrite;
  191. if (wrapper.Enumerate)
  192. {
  193. objectToWrite = wrapper.Qor;
  194. }
  195. else
  196. {
  197. DataServiceQueryContinuation continuation = wrapper.Qor.GetContinuation();
  198. if (!((continuation == null) || wrapper.ElementType.Name.Contains<char>('<')))
  199. {
  200. Uri nextLinkUri = continuation.NextLinkUri;
  201. objectToWrite = new Hyperlinq(QueryLanguage.Expression, "Execute<" + wrapper.ElementType.Name + "> (new Uri (\"" + nextLinkUri.ToString() + "\"))", "Next Page");
  202. }
  203. else
  204. {
  205. objectToWrite = info.DisplayNothingToken;
  206. }
  207. }
  208. }
  209. else
  210. {
  211. DataServiceQueryException exception = objectToWrite as DataServiceQueryException;
  212. if ((exception != null) && (exception.InnerException is DataServiceClientException))
  213. {
  214. DataServiceClientException innerException = (DataServiceClientException) exception.InnerException;
  215. try
  216. {
  217. XElement element = XElement.Parse(innerException.Message);
  218. if (element.Name.LocalName == "error")
  219. {
  220. XNamespace namespace2 = element.Name.Namespace;
  221. string str = (string) element.Element((XName) (namespace2 + "message"));
  222. if (!string.IsNullOrEmpty(str))
  223. {
  224. str = str.Trim();
  225. if (str.EndsWith("cannot be used in a query"))
  226. {
  227. str = str + " predicate";
  228. }
  229. if (!str.EndsWith("."))
  230. {
  231. str = str + ".";
  232. }
  233. Util.Highlight(str + " See exception below for more details.").Dump<object>();
  234. }
  235. }
  236. }
  237. catch
  238. {
  239. }
  240. }
  241. }
  242. }
  243. internal static string TestConnection(IConnectionInfo r)
  244. {
  245. try
  246. {
  247. return TestConnectionInternal(r);
  248. }
  249. catch (Exception exception)
  250. {
  251. string str2 = exception.GetType().Name + ": " + exception.Message;
  252. if (exception is XmlSchemaValidationException)
  253. {
  254. str2 = "This schema is unsupported - EntityClassGenerator returned the following error: " + str2;
  255. }
  256. if ((exception is FileNotFoundException) && exception.Message.Contains("System.Data.Services.Design"))
  257. {
  258. str2 = "Cannot load System.Data.Services.Design.dll. (A possible cause is installing the .NET Framework Client Profile instead of the full .NET Framework.)";
  259. }
  260. return str2;
  261. }
  262. }
  263. internal static string TestConnectionInternal(IConnectionInfo r)
  264. {
  265. IList<EdmSchemaError> list;
  266. EntityClassGenerator generator = new EntityClassGenerator(LanguageOption.GenerateCSharpCode) {
  267. Version = DataServiceCodeVersion.V2
  268. };
  269. StringWriter targetWriter = new StringWriter();
  270. using (new PushDefaultWebProxy())
  271. {
  272. using (XmlReader reader = GetSchemaReader(r))
  273. {
  274. list = generator.GenerateCode(reader, targetWriter, null);
  275. }
  276. }
  277. if (list.Count == 0)
  278. {
  279. return null;
  280. }
  281. return list.First<EdmSchemaError>().Message;
  282. }
  283. private class QueryOperationResponseWrapper
  284. {
  285. public readonly bool Enumerate;
  286. public readonly QueryOperationResponse Qor;
  287. public QueryOperationResponseWrapper(bool enumerate, QueryOperationResponse qor)
  288. {
  289. this.Enumerate = enumerate;
  290. this.Qor = qor;
  291. }
  292. public Type ElementType
  293. {
  294. get
  295. {
  296. return this.Qor.GetType().GetGenericArguments()[0];
  297. }
  298. }
  299. }
  300. }
  301. }