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