PageRenderTime 4ms CodeModel.GetById 22ms app.highlight 85ms RepoModel.GetById 1ms app.codeStats 1ms

/Tools/LinqPad/LINQPad/Repository.cs

https://github.com/vishalsh-spec/TestProject
C# | 1798 lines | 1777 code | 21 blank | 0 comment | 62 complexity | 9d02a699777d8c167a2c15693d12f1b0 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1namespace LINQPad
   2{
   3    using LINQPad.Extensibility.DataContext;
   4    using LINQPad.UI;
   5    using System;
   6    using System.Collections.Generic;
   7    using System.ComponentModel;
   8    using System.Data;
   9    using System.Data.Common;
  10    using System.Data.SqlClient;
  11    using System.IO;
  12    using System.Linq;
  13    using System.Reflection;
  14    using System.Runtime.CompilerServices;
  15    using System.Runtime.Serialization;
  16    using System.Security.Cryptography;
  17    using System.Text;
  18    using System.Threading;
  19    using System.Windows.Forms;
  20    using System.Xml.Linq;
  21
  22    [Serializable]
  23    internal class Repository : ISerializable, IConnectionInfo, IDatabaseInfo, ICustomTypeInfo, IDynamicSchemaOptions, INotifyPropertyChanged, ICustomMemberProvider
  24    {
  25        private DCDriverLoader _driverLoader;
  26        private List<LinkedDatabase> _linkedDbs;
  27        private static AutoResetEvent _openThrottler = new AutoResetEvent(true);
  28        private string _password;
  29        private static object _passwordChangeLocker = new object();
  30        private static int _serialCount;
  31        private static Dictionary<string, object> _servers = new Dictionary<string, object>();
  32        private IDictionary<string, object> _sessionData;
  33        private XElement _store;
  34        private static Timer _tmr;
  35        internal static string[] AssembliesNeedingPathQualification = new string[0];
  36        internal bool AutoGenAssemblyFailed;
  37        internal string AutoGenNamespace;
  38        internal string AutoGenTypeName;
  39        internal bool DoNotSave;
  40        private const string ElementName = "Connection";
  41        internal TempFileRef IntellicachePath;
  42        internal bool IsAutoGenAssemblyAvailable;
  43        internal static Dictionary<string, bool> TypesNeedingAssemblyQualification = new Dictionary<string, bool>();
  44
  45        public event PropertyChangedEventHandler PropertyChanged;
  46
  47        public Repository() : this(new XElement("Connection"))
  48        {
  49        }
  50
  51        public Repository(XElement store)
  52        {
  53            this.AutoGenNamespace = "LINQPad.User";
  54            this.AutoGenTypeName = "TypedDataContext";
  55            this._linkedDbs = new List<LinkedDatabase>();
  56            this._driverLoader = DCDriverLoader.DefaultLoader;
  57            this.LoadFromStore(store);
  58        }
  59
  60        private Repository(SerializationInfo info, StreamingContext context)
  61        {
  62            this.AutoGenNamespace = "LINQPad.User";
  63            this.AutoGenTypeName = "TypedDataContext";
  64            this._linkedDbs = new List<LinkedDatabase>();
  65            this._driverLoader = DCDriverLoader.DefaultLoader;
  66            this.LoadFromStore(XElement.Parse(info.GetString("data")));
  67            this._sessionData = (Dictionary<string, object>) info.GetValue("sessionData", typeof(Dictionary<string, object>));
  68        }
  69
  70        public static bool AreEquivalent(Repository r1, Repository r2)
  71        {
  72            if ((r1 == null) && (r2 == null))
  73            {
  74                return true;
  75            }
  76            if ((r1 == null) || (r2 == null))
  77            {
  78                return false;
  79            }
  80            return ((r1 == r2) || r1.IsEquivalent(r2));
  81        }
  82
  83        private bool ChangeSqlPassword()
  84        {
  85            using (UpdatePasswordForm form = new UpdatePasswordForm(this.Server, this.UserName))
  86            {
  87                if (form.ShowDialog() == DialogResult.OK)
  88                {
  89                    Repository repository = this.Clone();
  90                    repository.Password = form.OldPassword;
  91                    try
  92                    {
  93                        SqlConnection.ChangePassword(repository.GetCxString(), form.NewPassword);
  94                    }
  95                    catch (Exception exception)
  96                    {
  97                        MessageBox.Show(exception.Message, "LINQPad", MessageBoxButtons.OK, MessageBoxIcon.Hand);
  98                        return false;
  99                    }
 100                    this.Password = form.NewPassword;
 101                    if (this.Parent == null)
 102                    {
 103                        this.SaveToDisk();
 104                    }
 105                }
 106            }
 107            return true;
 108        }
 109
 110        public void ClearDatabaseProperties()
 111        {
 112            string str;
 113            this.UserName = str = "";
 114            this.Server = str = str;
 115            this.Provider = str = str;
 116            this.Password = str = str;
 117            this.AttachFileName = this.Database = str;
 118            this.MaxDatabaseSize = 0;
 119            this.UserInstance = false;
 120            this.ShowServer = false;
 121            this.NoPluralization = false;
 122            this.NoCapitalization = false;
 123            this.ExcludeRoutines = false;
 124            this.AttachFile = false;
 125        }
 126
 127        public Repository Clone()
 128        {
 129            return new Repository(new XElement(this.GetStore())) { _driverLoader = this._driverLoader };
 130        }
 131
 132        public Repository CreateChild(string databaseName)
 133        {
 134            Repository repository = this.Clone();
 135            repository.Database = databaseName;
 136            repository.Parent = this;
 137            repository.ShowServer = true;
 138            return repository;
 139        }
 140
 141        public Repository CreateParent()
 142        {
 143            Repository repository = this.Clone();
 144            repository.Database = "";
 145            this.Parent = repository;
 146            return repository;
 147        }
 148
 149        public AppDomain CreateSchemaAndRunnerDomain(string name, bool shadowingActive, bool queryExecutionContext)
 150        {
 151            string configPath = this.DriverLoader.IsValid ? this.DriverLoader.Driver.GetAppConfigPath(this) : this.AppConfigPath;
 152            string data = null;
 153            if (((this.DriverLoader.InternalID == null) && this.DriverLoader.IsValid) && (this.DriverLoader.Driver is StaticDataContextDriver))
 154            {
 155                try
 156                {
 157                    data = Path.GetDirectoryName(this.CustomAssemblyPath);
 158                }
 159                catch (ArgumentException)
 160                {
 161                }
 162                if (data == "")
 163                {
 164                    data = null;
 165                }
 166            }
 167            string baseFolderOverride = ((data == null) || shadowingActive) ? (((data == null) || !shadowingActive) ? null : AppDomain.CurrentDomain.BaseDirectory) : data;
 168            AppDomain domain = this.DriverLoader.CreateNewDriverDomain(name, baseFolderOverride, configPath);
 169            if (data != null)
 170            {
 171                domain.SetData("LINQPad.UseLoadFileForDCDriver", true);
 172                domain.SetData("LINQPad.DCDriverFolder", this.DriverLoader.GetAssemblyFolder());
 173                domain.SetData("LINQPad.StaticDCFolder", data);
 174                if (!queryExecutionContext)
 175                {
 176                    domain.DoCallBack(new CrossAppDomainDelegate(Repository.ResolveCustomAssemblies));
 177                }
 178            }
 179            return domain;
 180        }
 181
 182        public string Decrypt(string s)
 183        {
 184            if (string.IsNullOrEmpty(s))
 185            {
 186                return "";
 187            }
 188            try
 189            {
 190                return Encoding.UTF8.GetString(ProtectedData.Unprotect(Convert.FromBase64String(s), base.GetType().Assembly.GetName().GetPublicKey(), DataProtectionScope.CurrentUser));
 191            }
 192            catch
 193            {
 194                return "";
 195            }
 196        }
 197
 198        public string Encrypt(string s)
 199        {
 200            if (string.IsNullOrEmpty(s))
 201            {
 202                return "";
 203            }
 204            try
 205            {
 206                return Convert.ToBase64String(ProtectedData.Protect(Encoding.UTF8.GetBytes(s), base.GetType().Assembly.GetName().GetPublicKey(), DataProtectionScope.CurrentUser));
 207            }
 208            catch
 209            {
 210                return "";
 211            }
 212        }
 213
 214        private static string FormatCustomCxString(string s)
 215        {
 216            try
 217            {
 218                DbConnectionStringBuilder builder = new DbConnectionStringBuilder {
 219                    ConnectionString = s
 220                };
 221                if (builder.ContainsKey("password"))
 222                {
 223                    builder.Remove("password");
 224                }
 225                if (builder.ContainsKey("pwd"))
 226                {
 227                    builder.Remove("pwd");
 228                }
 229                string[] toRemove = new string[] { "true", "false", "enabled" };
 230                s = string.Join(";", (from v in builder.Values.OfType<string>()
 231                    where !toRemove.Contains<string>(v.ToLowerInvariant()) && (v.Length > 2)
 232                    select v).ToArray<string>());
 233            }
 234            catch
 235            {
 236            }
 237            if (s.Length > 0x55)
 238            {
 239                s = s.Substring(0, 80) + "...";
 240            }
 241            return s;
 242        }
 243
 244        public static List<Repository> FromDisk()
 245        {
 246            List<Repository> list = new List<Repository>();
 247            using (Mutex mutex = GetMutex())
 248            {
 249                if (!mutex.WaitOne(TimeSpan.FromSeconds(3.0), false))
 250                {
 251                    return list;
 252                }
 253                try
 254                {
 255                    XElement xmlFromDisk = GetXmlFromDisk();
 256                    if (xmlFromDisk == null)
 257                    {
 258                        return list;
 259                    }
 260                    foreach (XElement element2 in xmlFromDisk.Elements("Connection"))
 261                    {
 262                        try
 263                        {
 264                            list.Add(new Repository(element2));
 265                        }
 266                        catch
 267                        {
 268                        }
 269                    }
 270                }
 271                finally
 272                {
 273                    mutex.ReleaseMutex();
 274                }
 275            }
 276            return list;
 277        }
 278
 279        private bool GetBool(string key)
 280        {
 281            bool? nullable = (bool?) this._store.Element(key);
 282            return (nullable.HasValue ? nullable.GetValueOrDefault() : false);
 283        }
 284
 285        public IDbConnection GetConnection()
 286        {
 287            IDbConnection iDbConnection = this.DriverLoader.Driver.GetIDbConnection(this);
 288            if (iDbConnection == null)
 289            {
 290                throw new DisplayToUserException("The driver for this connection does not support SQL queries.");
 291            }
 292            return iDbConnection;
 293        }
 294
 295        public string[] GetCustomTypesInAssembly()
 296        {
 297            return this.GetCustomTypesInAssembly(null);
 298        }
 299
 300        public string[] GetCustomTypesInAssembly(string baseTypeName)
 301        {
 302            return AssemblyProber.GetTypeNames(this.CustomAssemblyPath, baseTypeName);
 303        }
 304
 305        public string GetCxString()
 306        {
 307            string password;
 308            if (this.CustomCxString.Length > 0)
 309            {
 310                return this.CustomCxString;
 311            }
 312            if ((((this.DriverLoader != null) && (this.DriverLoader != null)) && (this.DriverLoader.SimpleAssemblyName != null)) && (this.DriverLoader.SimpleAssemblyName.ToLowerInvariant() == "iqdriver"))
 313            {
 314                throw new DisplayToUserException("Connection is missing a password or other information: right-click the connection and click 'Properties'");
 315            }
 316            if (this.IsSqlCE)
 317            {
 318                if (this.AttachFileName.Length == 0)
 319                {
 320                    return "";
 321                }
 322                string str2 = "Data Source=" + this.AttachFileName;
 323                if (this.Password.Length > 0)
 324                {
 325                    password = this.Password;
 326                    if (password.Contains<char>(';'))
 327                    {
 328                        password = "'" + password + "'";
 329                    }
 330                    str2 = str2 + ";Password=" + password;
 331                }
 332                if (this.MaxDatabaseSize > 0)
 333                {
 334                    str2 = str2 + ";Max Database Size=" + this.MaxDatabaseSize;
 335                }
 336                return str2;
 337            }
 338            if (this.Server.Length == 0)
 339            {
 340                return "";
 341            }
 342            string str4 = "Data Source=" + this.Server;
 343            if (this.SqlSecurity)
 344            {
 345                password = this.Password;
 346                if (password.Contains<char>('\''))
 347                {
 348                    password = '"' + password + '"';
 349                }
 350                else if (password.Contains<char>(';') || password.Contains<char>('"'))
 351                {
 352                    password = "'" + password + "'";
 353                }
 354                string str5 = str4;
 355                str4 = str5 + ";User ID=" + this.UserName + ";Password=" + password;
 356            }
 357            else
 358            {
 359                str4 = str4 + ";Integrated Security=SSPI";
 360            }
 361            if (!((!this.AttachFile || (this.AttachFileName.Length <= 0)) || this.IsAzure))
 362            {
 363                str4 = str4 + ";AttachDbFilename=" + this.AttachFileName;
 364            }
 365            if (!((!this.UserInstance || this.SqlSecurity) || this.IsAzure))
 366            {
 367                str4 = str4 + ";User Instance=True";
 368            }
 369            if (!((!this.AttachFile || this.IsAzure) ? (this.Database.Length <= 0) : true))
 370            {
 371                str4 = str4 + ";Initial Catalog=" + this.Database;
 372            }
 373            str4 = str4 + ";app=LINQPad";
 374            if (!string.IsNullOrEmpty(Util.CurrentQueryName))
 375            {
 376                str4 = str4 + " [" + Util.CurrentQueryName.Replace(";", "") + "]";
 377            }
 378            if (!this.IsAzure && !((!this.DriverLoader.IsValid || !(this.DriverLoader.Driver is EntityFrameworkDriver)) ? !Program.EnableMARS : false))
 379            {
 380                str4 = str4 + ";MultipleActiveResultSets=True";
 381            }
 382            if (this.IsAzure || this.EncryptTraffic)
 383            {
 384                str4 = str4 + ";Encrypt=true";
 385            }
 386            return str4;
 387        }
 388
 389        public List<string> GetDatabaseList()
 390        {
 391            if (!this.IsSqlServer)
 392            {
 393                throw new NotSupportedException("This operation is supported only for SQL Server.");
 394            }
 395            List<string> list = new List<string>();
 396            string cmdText = this.IsAzure ? "select name from sys.databases" : "dbo.sp_MShasdbaccess";
 397            using (SqlConnection connection = new SqlConnection(this.GetCxString()))
 398            {
 399                connection.Open();
 400                using (SqlDataReader reader = new SqlCommand(cmdText, connection).ExecuteReader())
 401                {
 402                    while (reader.Read())
 403                    {
 404                        list.Add(reader[0].ToString());
 405                    }
 406                }
 407            }
 408            return list;
 409        }
 410
 411        public string[] GetDriverAssemblies()
 412        {
 413            if (!this.DriverLoader.IsValid)
 414            {
 415                return new string[0];
 416            }
 417            string staticDataContextFolder = null;
 418            if ((this.DriverLoader.Driver is StaticDataContextDriver) && !string.IsNullOrEmpty(this.CustomAssemblyPath))
 419            {
 420                try
 421                {
 422                    staticDataContextFolder = Path.GetDirectoryName(this.CustomAssemblyPath);
 423                }
 424                catch (ArgumentException)
 425                {
 426                }
 427            }
 428            return (this.DriverLoader.Driver.TryGetFullAssembliesToAdd(staticDataContextFolder, this) ?? new string[0]);
 429        }
 430
 431        public string GetFriendlyName()
 432        {
 433            return this.GetFriendlyName(FriendlyNameMode.Normal);
 434        }
 435
 436        public string GetFriendlyName(FriendlyNameMode mode)
 437        {
 438            string connectionDescription;
 439            if (this.DriverLoader.InternalID == null)
 440            {
 441                if (!this.DriverLoader.IsValid)
 442                {
 443                    return ("(Unknown driver '" + this.DriverLoader.SimpleAssemblyName + "')");
 444                }
 445                if (!string.IsNullOrEmpty(this.DisplayName))
 446                {
 447                    return this.DisplayName;
 448                }
 449                try
 450                {
 451                    return this.DriverLoader.Driver.GetConnectionDescription(this);
 452                }
 453                catch (Exception exception)
 454                {
 455                    Log.Write(exception);
 456                    string message = exception.Message;
 457                    if (((exception is TargetInvocationException) || (exception is TypeInitializationException)) && (exception.InnerException != null))
 458                    {
 459                        message = exception.InnerException.Message;
 460                    }
 461                    return ("(Error loading driver: " + message + ")");
 462                }
 463            }
 464            if (string.IsNullOrEmpty(this.DisplayName))
 465            {
 466                connectionDescription = this.DriverLoader.Driver.GetConnectionDescription(this);
 467                if (!string.IsNullOrEmpty(connectionDescription))
 468                {
 469                    return connectionDescription;
 470                }
 471            }
 472            string customTypeName = "";
 473            string str5 = "";
 474            if (!this.DynamicSchema)
 475            {
 476                if (!string.IsNullOrEmpty(this.DisplayName))
 477                {
 478                    return this.DisplayName;
 479                }
 480                string key = this.CustomTypeName.Split(new char[] { '.' }).Last<string>();
 481                if (mode == FriendlyNameMode.Short)
 482                {
 483                    return key;
 484                }
 485                bool flag = true;
 486                bool flag2 = true;
 487                bool flag3 = false;
 488                if ((mode != FriendlyNameMode.FullTooltip) && (flag2 = TypesNeedingAssemblyQualification.TryGetValue(key, out flag)))
 489                {
 490                    try
 491                    {
 492                        flag3 = !AssembliesNeedingPathQualification.Contains<string>(Path.GetFileName(this.CustomAssemblyPath));
 493                    }
 494                    catch (ArgumentException)
 495                    {
 496                    }
 497                }
 498                customTypeName = this.CustomTypeName;
 499                if (!flag)
 500                {
 501                    customTypeName = customTypeName.Split(new char[] { '.' }).Last<string>();
 502                }
 503                if (flag2)
 504                {
 505                    string customAssemblyPath = this.CustomAssemblyPath;
 506                    if (flag3)
 507                    {
 508                        try
 509                        {
 510                            customAssemblyPath = Path.GetFileName(customAssemblyPath);
 511                        }
 512                        catch (ArgumentException)
 513                        {
 514                        }
 515                    }
 516                    customTypeName = customTypeName + " in " + customAssemblyPath;
 517                }
 518                if (mode == FriendlyNameMode.FullTooltip)
 519                {
 520                    customTypeName = customTypeName + "\r\nDatabase = ";
 521                }
 522                else
 523                {
 524                    customTypeName = customTypeName + " (";
 525                    str5 = ")";
 526                }
 527            }
 528            if (this.CustomCxString.Length > 0)
 529            {
 530                if (!string.IsNullOrEmpty(this.DisplayName))
 531                {
 532                    return this.DisplayName;
 533                }
 534                return FormatCustomCxString(this.CustomCxString);
 535            }
 536            if (this.AttachFile || this.IsSqlCE)
 537            {
 538                if (!string.IsNullOrEmpty(this.DisplayName))
 539                {
 540                    return this.DisplayName;
 541                }
 542                bool flag4 = true;
 543                try
 544                {
 545                    flag4 = Path.IsPathRooted(this.AttachFileName);
 546                }
 547                catch
 548                {
 549                }
 550                if (!(flag4 && (this.DynamicSchema || (mode == FriendlyNameMode.Short))))
 551                {
 552                    return (customTypeName + this.AttachFileName + str5);
 553                }
 554                string attachFileName = this.AttachFileName;
 555                string str9 = "";
 556                try
 557                {
 558                    attachFileName = Path.GetFileName(attachFileName);
 559                    if (mode != FriendlyNameMode.Short)
 560                    {
 561                        str9 = " in " + PathHelper.EncodeFolder(Path.GetDirectoryName(this.AttachFileName));
 562                    }
 563                }
 564                catch (ArgumentException)
 565                {
 566                }
 567                return (customTypeName + attachFileName + str9 + str5);
 568            }
 569            string str10 = string.Join(" + ", (from l in this._linkedDbs.Take<LinkedDatabase>(3) select l.ToString()).ToArray<string>());
 570            if (this._linkedDbs.Count > 3)
 571            {
 572                str10 = str10 + "...";
 573            }
 574            if (str10.Length > 0)
 575            {
 576                str10 = " + " + str10;
 577            }
 578            if (((mode == FriendlyNameMode.Normal) || (mode == FriendlyNameMode.Short)) && ((this.Database.Length > 0) && ((this.Parent != null) || (mode == FriendlyNameMode.Short))))
 579            {
 580                if (!string.IsNullOrEmpty(this.DisplayName))
 581                {
 582                    return ((this.Parent == null) ? this.DisplayName : (this.Database + str10));
 583                }
 584                return (customTypeName + this.Database + str5);
 585            }
 586            if (!string.IsNullOrEmpty(this.DisplayName))
 587            {
 588                connectionDescription = this.DisplayName;
 589                if ((this.Parent != null) && (this.Database.Length > 0))
 590                {
 591                    connectionDescription = connectionDescription + "." + this.Database;
 592                }
 593                return connectionDescription;
 594            }
 595            string server = this.Server;
 596            if (this.IsAzure && (mode != FriendlyNameMode.FullTooltip))
 597            {
 598                if (server.EndsWith(".database.windows.net", StringComparison.InvariantCultureIgnoreCase))
 599                {
 600                    server = server.Substring(0, server.Length - ".database.windows.net".Length);
 601                }
 602                if (server.StartsWith("tcp:", StringComparison.InvariantCultureIgnoreCase))
 603                {
 604                    server = server.Substring("tcp:".Length);
 605                }
 606            }
 607            string str12 = server + (this.SqlSecurity ? ("." + this.UserName) : "");
 608            if (this.Database.Length > 0)
 609            {
 610                str12 = str12 + "." + this.Database + str10;
 611            }
 612            return (customTypeName + str12 + str5);
 613        }
 614
 615        private Guid GetGuid(string key)
 616        {
 617            return (Guid) this._store.Element(key);
 618        }
 619
 620        private int GetInt(string key)
 621        {
 622            int? nullable = (int?) this._store.Element(key);
 623            return (nullable.HasValue ? nullable.GetValueOrDefault() : 0);
 624        }
 625
 626        public List<LinkedDatabase> GetLinkedDatabaseList()
 627        {
 628            if (!this.IsSqlServer)
 629            {
 630                throw new NotSupportedException("This operation is supported only for SQL Server.");
 631            }
 632            StringBuilder builder = new StringBuilder();
 633            List<string> list = new List<string>();
 634            List<LinkedDatabase> list2 = new List<LinkedDatabase>();
 635            string cmdText = "select data_source from sys.servers where provider = 'SQLNCLI' and is_linked = 1";
 636            using (SqlConnection connection = new SqlConnection(this.GetCxString()))
 637            {
 638                SqlDataReader reader;
 639                connection.Open();
 640                using (reader = new SqlCommand(cmdText, connection).ExecuteReader())
 641                {
 642                    while (reader.Read())
 643                    {
 644                        string item = reader[0].ToString();
 645                        list.Add(item);
 646                        builder.AppendLine("select name from [" + item + "].[master].[sys].[databases]");
 647                    }
 648                }
 649                int num = 0;
 650                using (reader = new SqlCommand(builder.ToString(), connection).ExecuteReader())
 651                {
 652                    while (reader.Read())
 653                    {
 654                        list2.Add(new LinkedDatabase(list[num], reader[0].ToString()));
 655                        continue;
 656                    Label_00D6:
 657                        if (!reader.NextResult())
 658                        {
 659                            return list2;
 660                        }
 661                        num++;
 662                    }
 663                    goto Label_00D6;
 664                }
 665            }
 666        }
 667
 668        private static Mutex GetMutex()
 669        {
 670            return new Mutex(true, "LINQPad.DefaultConnection");
 671        }
 672
 673        public IEnumerable<string> GetNames()
 674        {
 675            List<string> list = new List<string>();
 676            Type[] typeArray2 = new Type[] { typeof(IDatabaseInfo), typeof(ICustomTypeInfo), typeof(IDynamicSchemaOptions) };
 677            foreach (Type t in typeArray2)
 678            {
 679                list.AddRange(from p in t.GetProperties() select t.Name.Substring(1) + "." + p.Name);
 680            }
 681            list.Add("AppConfigPath");
 682            list.Add("Persist");
 683            return list;
 684        }
 685
 686        public IEnumerable<LinkedDatabase> GetOtherServerLinkedDatabases()
 687        {
 688            return (from l in this._linkedDbs
 689                where l.Server != null
 690                select l);
 691        }
 692
 693        public DbProviderFactory GetProviderFactory()
 694        {
 695            return this.DriverLoader.Driver.GetProviderFactory(this);
 696        }
 697
 698        public DbProviderFactory GetProviderFactory(DbConnection cx)
 699        {
 700            if (cx == null)
 701            {
 702                return this.GetProviderFactory();
 703            }
 704            PropertyInfo property = cx.GetType().GetProperty("DbProviderFactory", BindingFlags.NonPublic | BindingFlags.Instance);
 705            if (property == null)
 706            {
 707                return this.GetProviderFactory();
 708            }
 709            try
 710            {
 711                return (((DbProviderFactory) property.GetValue(cx, null)) ?? this.GetProviderFactory());
 712            }
 713            catch
 714            {
 715                return this.GetProviderFactory();
 716            }
 717        }
 718
 719        private static Repository GetRepository(XElement e)
 720        {
 721            try
 722            {
 723                return new Repository(e);
 724            }
 725            catch
 726            {
 727                return null;
 728            }
 729        }
 730
 731        public IEnumerable<Repository> GetSameServerLinkedRepositories()
 732        {
 733            XElement xe = this.GetStore();
 734            return (from db in this._linkedDbs
 735                where db.Server == null
 736                select new Repository(xe) { _linkedDbs = new List<LinkedDatabase>(), Database = db.Database, IncludeSystemObjects = false, AttachFile = false, AttachFileName = "" });
 737        }
 738
 739        public string GetSortOrder()
 740        {
 741            if (this.DriverLoader.IsValid && (this.DriverLoader.Driver is LinqToSqlDynamicDriver))
 742            {
 743                return ((this.IsSqlCE ? "3" : (this.IsAzure ? "2" : "1")) + this.GetFriendlyName());
 744            }
 745            return this.GetFriendlyName();
 746        }
 747
 748        public XElement GetStore()
 749        {
 750            this._store.Elements("LinkedDb").Remove<XElement>();
 751            this._store.Add(from db in this._linkedDbs select new XElement("LinkedDb", new object[] { db.Database, (db.Server == null) ? null : new XAttribute("Server", db.Server) }));
 752            if (this._store.Element("DriverData") != null)
 753            {
 754                this._store.Element("DriverData").Remove();
 755            }
 756            if ((this.DriverData != null) && (!this.DriverData.IsEmpty || this.DriverData.Attributes().Any<XAttribute>()))
 757            {
 758                this._store.Add(new XElement("DriverData", new object[] { this.DriverData.Elements(), this.DriverData.Attributes() }));
 759            }
 760            return this._store;
 761        }
 762
 763        private string GetString(string key)
 764        {
 765            string str = (string) this._store.Element(key);
 766            return ((str == null) ? "" : str.Trim());
 767        }
 768
 769        public IEnumerable<Type> GetTypes()
 770        {
 771            List<Type> list = new List<Type>();
 772            Type[] typeArray2 = new Type[] { typeof(IDatabaseInfo), typeof(ICustomTypeInfo), typeof(IDynamicSchemaOptions) };
 773            foreach (Type type in typeArray2)
 774            {
 775                list.AddRange(from p in type.GetProperties() select p.PropertyType);
 776            }
 777            list.Add(typeof(string));
 778            list.Add(typeof(bool));
 779            return list;
 780        }
 781
 782        public IEnumerable<object> GetValues()
 783        {
 784            Func<PropertyInfo, object> selector = null;
 785            List<object> list = new List<object>();
 786            Type[] typeArray2 = new Type[] { typeof(IDatabaseInfo), typeof(ICustomTypeInfo), typeof(IDynamicSchemaOptions) };
 787            foreach (Type type in typeArray2)
 788            {
 789                if (selector == null)
 790                {
 791                    selector = p => p.GetValue(this, null);
 792                }
 793                list.AddRange(type.GetProperties().Select<PropertyInfo, object>(selector));
 794            }
 795            list.Add(this.AppConfigPath);
 796            list.Add(this.Persist);
 797            return list;
 798        }
 799
 800        private static XElement GetXmlFromDisk()
 801        {
 802            XElement element = new XElement("Connections");
 803            if (File.Exists(FilePath) || File.Exists(OldFilePath))
 804            {
 805                try
 806                {
 807                    element = XElement.Load(File.Exists(FilePath) ? FilePath : OldFilePath);
 808                }
 809                catch
 810                {
 811                    Thread.Sleep(200);
 812                    try
 813                    {
 814                        element = XElement.Load(File.Exists(FilePath) ? FilePath : OldFilePath);
 815                    }
 816                    catch
 817                    {
 818                        return null;
 819                    }
 820                }
 821            }
 822            return element;
 823        }
 824
 825        public bool IsEquivalent(Repository other)
 826        {
 827            if (other == null)
 828            {
 829                return false;
 830            }
 831            if (!(this.DriverLoader.IsValid && other.DriverLoader.IsValid))
 832            {
 833                return (this.GetStore().ToString() == other.GetStore().ToString());
 834            }
 835            if (!this.DriverLoader.Equals(other.DriverLoader))
 836            {
 837                return false;
 838            }
 839            return this.DriverLoader.Driver.AreRepositoriesEquivalent(this, other);
 840        }
 841
 842        string ICustomTypeInfo.GetCustomTypeDescription()
 843        {
 844            bool flag = true;
 845            bool flag2 = true;
 846            bool flag3 = false;
 847            string key = this.CustomTypeName.Split(new char[] { '.' }).Last<string>();
 848            if (flag2 = TypesNeedingAssemblyQualification.TryGetValue(key, out flag))
 849            {
 850                try
 851                {
 852                    flag3 = !AssembliesNeedingPathQualification.Contains<string>(Path.GetFileName(this.CustomAssemblyPath));
 853                }
 854                catch (ArgumentException)
 855                {
 856                }
 857            }
 858            string customTypeName = this.CustomTypeName;
 859            if (!flag)
 860            {
 861                customTypeName = customTypeName.Split(new char[] { '.' }).Last<string>();
 862            }
 863            if (!flag2)
 864            {
 865                return customTypeName;
 866            }
 867            string customAssemblyPath = this.CustomAssemblyPath;
 868            if (flag3)
 869            {
 870                try
 871                {
 872                    customAssemblyPath = Path.GetFileName(customAssemblyPath);
 873                }
 874                catch (ArgumentException)
 875                {
 876                }
 877            }
 878            return (customTypeName + " in " + customAssemblyPath);
 879        }
 880
 881        bool ICustomTypeInfo.IsEquivalent(ICustomTypeInfo other)
 882        {
 883            if (other == null)
 884            {
 885                return false;
 886            }
 887            if (!string.Equals(this.CustomAssemblyPath, other.CustomAssemblyPath, StringComparison.OrdinalIgnoreCase))
 888            {
 889                return false;
 890            }
 891            if (!string.Equals(this.CustomMetadataPath, other.CustomMetadataPath, StringComparison.OrdinalIgnoreCase))
 892            {
 893                return false;
 894            }
 895            return (this.CustomTypeName == other.CustomTypeName);
 896        }
 897
 898        string IDatabaseInfo.GetDatabaseDescription()
 899        {
 900            if (this.CustomCxString.Length > 0)
 901            {
 902                return FormatCustomCxString(this.CustomCxString);
 903            }
 904            if (this.AttachFile || this.IsSqlCE)
 905            {
 906                return this.AttachFileName;
 907            }
 908            string str2 = this.Server + (this.SqlSecurity ? ("." + this.UserName) : "");
 909            if (this.Database.Length > 0)
 910            {
 911                str2 = str2 + "." + this.Database;
 912            }
 913            return str2;
 914        }
 915
 916        bool IDatabaseInfo.IsEquivalent(IDatabaseInfo other)
 917        {
 918            if (other == null)
 919            {
 920                return false;
 921            }
 922            if ((this.CustomCxString.Length > 0) != (other.CustomCxString.Length > 0))
 923            {
 924                return false;
 925            }
 926            if (this.CustomCxString.Length > 0)
 927            {
 928                return (this.CustomCxString.ToLowerInvariant() == other.CustomCxString.ToLowerInvariant());
 929            }
 930            if (this.IsSqlCE != other.IsSqlCE)
 931            {
 932                return false;
 933            }
 934            if (this.IsSqlCE)
 935            {
 936                return (string.Equals(this.Provider, other.Provider, StringComparison.OrdinalIgnoreCase) && string.Equals(this.AttachFileName, other.AttachFileName, StringComparison.OrdinalIgnoreCase));
 937            }
 938            if (!string.Equals(this.Server, other.Server, StringComparison.OrdinalIgnoreCase))
 939            {
 940                return false;
 941            }
 942            if (this.SqlSecurity != other.SqlSecurity)
 943            {
 944                return false;
 945            }
 946            if (!(!this.SqlSecurity || string.Equals(this.UserName, other.UserName, StringComparison.OrdinalIgnoreCase)))
 947            {
 948                return false;
 949            }
 950            if (this.AttachFile != other.AttachFile)
 951            {
 952                return false;
 953            }
 954            if (!(!this.AttachFile || string.Equals(this.AttachFileName, other.AttachFileName, StringComparison.OrdinalIgnoreCase)))
 955            {
 956                return false;
 957            }
 958            if (!(this.AttachFile || string.Equals(this.Database, other.Database, StringComparison.OrdinalIgnoreCase)))
 959            {
 960                return false;
 961            }
 962            Repository repository = other as Repository;
 963            if (!(from d in this._linkedDbs
 964                orderby d
 965                select d).SequenceEqual<LinkedDatabase>((from d in repository._linkedDbs
 966                orderby d
 967                select d)))
 968            {
 969                return false;
 970            }
 971            return true;
 972        }
 973
 974        public void LoadFromStore(XElement store)
 975        {
 976            this._store = store;
 977            Guid? nullable = (Guid?) this._store.Element("ID");
 978            if (!nullable.HasValue)
 979            {
 980                this.ID = Guid.NewGuid();
 981            }
 982            string str = (string) this._store.Element("Password");
 983            if (!string.IsNullOrEmpty(str))
 984            {
 985                this._password = this.Decrypt(str);
 986            }
 987            this.AttachFileName = this.AttachFileName;
 988            XElement other = store.Element("DriverData");
 989            this.DriverData = (other == null) ? new XElement("DriverData") : new XElement(other);
 990            this._driverLoader = DCDriverLoader.FromXElement(store.Element("Driver"));
 991            this._linkedDbs = (from e in store.Elements("LinkedDb")
 992                select new LinkedDatabase((string) e.Attribute("Server"), e.Value) into e
 993                orderby e
 994                select e).ToList<LinkedDatabase>();
 995        }
 996
 997        private void OnPropertyChanged(PropertyChangedEventArgs args)
 998        {
 999            if (this.PropertyChanged != null)
1000            {
1001                this.PropertyChanged(this, args);
1002            }
1003        }
1004
1005        public IDbConnection Open()
1006        {
1007            return this.Open(false);
1008        }
1009
1010        public IDbConnection Open(bool noThrottle)
1011        {
1012            object obj2;
1013            IDbConnection cx = this.GetConnection();
1014            if (!((!noThrottle && (this.CustomCxString.Length <= 0)) && this.Server.ToUpperInvariant().Contains("SQLEXPRESS")))
1015            {
1016                this.OpenCx(cx, noThrottle);
1017                return cx;
1018            }
1019            lock (_servers)
1020            {
1021                string server = this.Server;
1022                if (!_servers.ContainsKey(server))
1023                {
1024                    _servers.Add(server, new object());
1025                }
1026                obj2 = _servers[server];
1027            }
1028            lock (obj2)
1029            {
1030                this.OpenCx(cx, noThrottle);
1031            }
1032            return cx;
1033        }
1034
1035        private void OpenCx(IDbConnection cx, bool noThrottle)
1036        {
1037            if (!noThrottle && (Environment.Version.Major < 4))
1038            {
1039                lock (_openThrottler)
1040                {
1041                    if (_tmr == null)
1042                    {
1043                        _tmr = new Timer(state => _openThrottler.Set(), null, 0x5dc, 500);
1044                    }
1045                }
1046                _openThrottler.WaitOne();
1047            }
1048            string password = this.Password;
1049        Label_008D:
1050            try
1051            {
1052                try
1053                {
1054                    cx.Open();
1055                }
1056                catch (IndexOutOfRangeException exception)
1057                {
1058                    throw new DisplayToUserException("SqlConnection has reported an internal error in the connection pool.\r\nYou may need to restart LINQPad.", exception);
1059                }
1060                catch (SqlException exception2)
1061                {
1062                    if (!UserOptions.Instance.NoSqlPasswordExpiryPrompts && ((exception2.Number == 0x4837) || (exception2.Number == 0x4838)))
1063                    {
1064                        lock (_passwordChangeLocker)
1065                        {
1066                            if (password != this.Password)
1067                            {
1068                                cx = this.GetConnection();
1069                                goto Label_008D;
1070                            }
1071                            if (!this.ChangeSqlPassword())
1072                            {
1073                                goto Label_008D;
1074                            }
1075                            cx = this.GetConnection();
1076                            cx.Open();
1077                            return;
1078                        }
1079                    }
1080                    throw;
1081                }
1082                return;
1083            }
1084            finally
1085            {
1086                _openThrottler.Set();
1087            }
1088            goto Label_008D;
1089        }
1090
1091        private static void ResolveCustomAssemblies()
1092        {
1093            AppDomain.CurrentDomain.AssemblyResolve += delegate (object sender, ResolveEventArgs args) {
1094                string str = new AssemblyName(args.Name).Name + ".dll";
1095                string path = Path.Combine((string) AppDomain.CurrentDomain.GetData("LINQPad.DCDriverFolder"), str);
1096                if (File.Exists(path))
1097                {
1098                    return Assembly.LoadFrom(path);
1099                }
1100                return null;
1101            };
1102        }
1103
1104        public bool SaveToDisk()
1105        {
1106            Func<XElement, bool> predicate = null;
1107            if (this.DoNotSave)
1108            {
1109                return false;
1110            }
1111            using (Mutex mutex = GetMutex())
1112            {
1113                if (!mutex.WaitOne(TimeSpan.FromSeconds(3.0), false))
1114                {
1115                    return false;
1116                }
1117                try
1118                {
1119                    if (!Directory.Exists(Program.UserDataFolder))
1120                    {
1121                        Directory.CreateDirectory(Program.UserDataFolder);
1122                    }
1123                    if (this.ID == Guid.Empty)
1124                    {
1125                        this.ID = Guid.NewGuid();
1126                    }
1127                    XElement xmlFromDisk = GetXmlFromDisk();
1128                    if (xmlFromDisk == null)
1129                    {
1130                        return false;
1131                    }
1132                    bool flag2 = false;
1133                    try
1134                    {
1135                        if (predicate == null)
1136                        {
1137                            predicate = delegate (XElement e) {
1138                                Guid? nullable = (Guid?) e.Element("ID");
1139                                return (nullable.HasValue ? nullable.GetValueOrDefault() : Guid.Empty) == this.ID;
1140                            };
1141                        }
1142                        XElement element2 = xmlFromDisk.Elements("Connection").FirstOrDefault<XElement>(predicate);
1143                        if (element2 != null)
1144                        {
1145                            element2.Remove();
1146                            flag2 = true;
1147                        }
1148                    }
1149                    catch
1150                    {
1151                        return false;
1152                    }
1153                    if (!(flag2 || this.Persist))
1154                    {
1155                        return true;
1156                    }
1157                    if (this.Persist)
1158                    {
1159                        xmlFromDisk.Add(this.GetStore());
1160                    }
1161                    try
1162                    {
1163                        xmlFromDisk.Save(FilePath);
1164                    }
1165                    catch
1166                    {
1167                        Thread.Sleep(200);
1168                        try
1169                        {
1170                            xmlFromDisk.Save(FilePath);
1171                        }
1172                        catch
1173                        {
1174                            return false;
1175                        }
1176                    }
1177                }
1178                finally
1179                {
1180                    mutex.ReleaseMutex();
1181                }
1182            }
1183            return true;
1184        }
1185
1186        private void Set(string key, bool value)
1187        {
1188            if (!value)
1189            {
1190                this._store.Elements(key).Remove<XElement>();
1191            }
1192            else
1193            {
1194                this._store.SetElementValue(key, value);
1195            }
1196            this.OnPropertyChanged(new PropertyChangedEventArgs(key));
1197        }
1198
1199        private void Set(string key, Guid value)
1200        {
1201            this._store.SetElementValue(key, value);
1202            this.OnPropertyChanged(new PropertyChangedEventArgs(key));
1203        }
1204
1205        private void Set(string key, int value)
1206        {
1207            if (value == 0)
1208            {
1209                this._store.Elements(key).Remove<XElement>();
1210            }
1211            else
1212            {
1213                this._store.SetElementValue(key, value);
1214            }
1215            this.OnPropertyChanged(new PropertyChangedEventArgs(key));
1216        }
1217
1218        private void Set(string key, string value)
1219        {
1220            if ((value == null) || (value.Trim().Length == 0))
1221            {
1222                this._store.Elements(key).Remove<XElement>();
1223            }
1224            else
1225            {
1226                this._store.SetElementValue(key, value);
1227            }
1228            this.OnPropertyChanged(new PropertyChangedEventArgs(key));
1229        }
1230
1231        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
1232        {
1233            _serialCount++;
1234            info.AddValue("data", this.GetStore().ToString());
1235            IDictionary<string, object> dictionary = this._sessionData;
1236            if ((dictionary != null) && (dictionary.Count == 0))
1237            {
1238                dictionary = null;
1239            }
1240            info.AddValue("sessionData", dictionary);
1241        }
1242
1243        public override string ToString()
1244        {
1245            return this.GetFriendlyName(FriendlyNameMode.Standalone);
1246        }
1247
1248        public void UpdateFromParent()
1249        {
1250            if (this.Parent != null)
1251            {
1252                this.Provider = this.Parent.Provider;
1253                this.Server = this.Parent.Server;
1254                this.AttachFile = this.Parent.AttachFile;
1255                this.UserInstance = this.Parent.UserInstance;
1256                this.AttachFileName = this.Parent.AttachFileName;
1257                this.SqlSecurity = this.Parent.SqlSecurity;
1258                this.UserName = this.Parent.UserName;
1259                this.Password = this.Parent.Password;
1260                this.NoPluralization = this.Parent.NoPluralization;
1261                this.NoCapitalization = this.Parent.NoCapitalization;
1262                this.ExcludeRoutines = this.Parent.ExcludeRoutines;
1263                this.CustomCxString = this.Parent.CustomCxString;
1264                this.MaxDatabaseSize = this.Parent.MaxDatabaseSize;
1265                this.DisplayName = this.Parent.DisplayName;
1266                this.IncludeSystemObjects = this.Parent.IncludeSystemObjects;
1267                this.EncryptTraffic = this.Parent.EncryptTraffic;
1268            }
1269        }
1270
1271        public string AppConfigPath
1272        {
1273            get
1274            {
1275                return this.GetString("AppConfigPath");
1276            }
1277            set
1278            {
1279                this.Set("AppConfigPath", value);
1280            }
1281        }
1282
1283        public bool AttachFile
1284        {
1285            get
1286            {
1287                return this.GetBool("AttachFile");
1288            }
1289            set
1290            {
1291                this.Set("AttachFile", value);
1292            }
1293        }
1294
1295        public string AttachFileName
1296        {
1297            get
1298            {
1299                return PathHelper.DecodeFolder(this.GetString("AttachFileName"));
1300            }
1301            set
1302            {
1303                this.Set("AttachFileName", PathHelper.EncodeFolder(value));
1304            }
1305        }
1306
1307        public string CustomAssemblyPath
1308        {
1309            get
1310            {
1311                string str = PathHelper.DecodeFolder(this.GetString("CustomAssemblyPathEncoded"));
1312                if (!string.IsNullOrEmpty(str))
1313                {
1314                    return str;
1315                }
1316                return this.GetString("CustomAssemblyPath");
1317            }
1318            set
1319            {
1320                string str = PathHelper.EncodeFolder(value);
1321                this.Set("CustomAssemblyPathEncoded", (str == value) ? null : str);
1322                this.Set("CustomAssemblyPath", value);
1323            }
1324        }
1325
1326        public string CustomCxString
1327        {
1328            get
1329            {
1330                string s = this.GetString("CustomCxString");
1331                if (this.EncryptCustomCxString)
1332                {
1333                    s = this.Decrypt(s);
1334                }
1335                return s;
1336            }
1337            set
1338            {
1339                string s = value;
1340                if (this.EncryptCustomCxString)
1341                {
1342                    s = this.Encrypt(s);
1343                }
1344                this.Set("CustomCxString", s);
1345            }
1346        }
1347
1348        public string CustomMetadataPath
1349        {
1350            get
1351            {
1352                string str = PathHelper.DecodeFolder(this.GetString("CustomMetadataPathEncoded"));
1353                if (!string.IsNullOrEmpty(str))
1354                {
1355                    return str;
1356                }
1357                return this.GetString("CustomMetadataPath");
1358            }
1359            set
1360            {
1361                string str = PathHelper.EncodeFolder(value);
1362                this.Set("CustomMetadataPathEncoded", (str == value) ? null : str);
1363                this.Set("CustomMetadataPath", value);
1364            }
1365        }
1366
1367        public ICustomTypeInfo CustomTypeInfo
1368        {
1369            get
1370            {
1371                return this;
1372            }
1373        }
1374
1375        public string CustomTypeName
1376        {
1377            get
1378            {
1379                return this.GetString("CustomTypeName");
1380            }
1381            set
1382            {
1383                this.Set("CustomTypeName", value);
1384            }
1385        }
1386
1387        public string Database
1388        {
1389            get
1390            {
1391                return this.GetString("Database");
1392            }
1393            set
1394            {
1395                this.Set("Database", value);
1396            }
1397        }
1398
1399        public IDatabaseInfo DatabaseInfo
1400        {
1401            get
1402            {
1403                return this;
1404            }
1405        }
1406
1407        public string DbVersion
1408        {
1409            get
1410            {
1411                return this.GetString("DbVersion");
1412            }
1413            set
1414            {
1415                this.Set("DbVersion", value);
1416            }
1417        }
1418
1419        public string DisplayName
1420    

Large files files are truncated, but you can click here to view the full file