Пример #1
0
        private void CommandEvents_BeforeExecute(string Guid, int ID, object CustomIn, object CustomOut, ref bool CancelDefault)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            //Microsoft.SqlServer.Management.SqlStudio.
            //var objectExplorerService = (ObjectExplorerService)_package.GetServiceAsync(typeof(IObjectExplorerService)).Result;

            //// var oesTreeProperty = objectExplorerService.GetType().GetProperty("Tree", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase);
            ////// if (oesTreeProperty != null)

            ////     var x = (TreeView)oesTreeProperty.GetValue(objectExplorerService, null);

            //int arraySize;
            //INodeInformation[] array;
            //objectExplorerService.GetSelectedNodes(out arraySize, out array);


            //if (arraySize == 0)
            //    return;

            //var node = array[0];

            //var table = (HierarchyObject)node.GetService(typeof(IMenuHandler));
            //table.AddChild("abc", new tableMenuItem());

            //Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.FilterOperator

            try
            {
                string queryText = GetQueryText();

                if (string.IsNullOrWhiteSpace(queryText))
                {
                    return;
                }

                // Get Current Connection Information
                UIConnectionInfo connInfo = ServiceCache.ScriptFactory.CurrentlyActiveWndConnectionInfo.UIConnectionInfo;

                var queryItem = new QueryItem()
                {
                    Query            = queryText,
                    Server           = connInfo.ServerName,
                    Username         = connInfo.UserName,
                    Database         = connInfo.AdvancedOptions["DATABASE"],
                    ExecutionDateUtc = DateTime.UtcNow
                };

                _logger.LogInformation("Enqueued {@quetyItem}", queryItem.Query);

                itemsQueue.Enqueue(queryItem);

                Task.Delay(1000).ContinueWith((t) => this.SavePendingItems());
            }
            catch (Exception ex)
            {
                _logger.LogError("Error on BeforeExecute tracking", ex);
            }
        }
Пример #2
0
 private static void Postfix(UIConnectionInfo __instance)
 {
     if (((Profile)UICActivate._profile.GetValue(__instance)).localPlayer)
     {
         __instance.controlString += " @MENU2@Upload@SAVEICONTINY@";
     }
     __instance.controlString += " @STRAFE@Stats@RANDOMICON@";
     __instance.controlString += " @RAGDOLL@@PLANET@-@MOON@";
 }
Пример #3
0
        public static SqlConnectionInfo GetConnectionInfo(UIConnectionInfo uiConnectionInfo)
        {
            SqlConnectionInfo connectionInfo = new SqlConnectionInfo();

            connectionInfo.ApplicationName       = "SSMS Plugin Bits and Pieces";
            connectionInfo.ServerName            = uiConnectionInfo.ServerName;
            connectionInfo.UserName              = uiConnectionInfo.UserName;
            connectionInfo.Password              = uiConnectionInfo.Password;
            connectionInfo.UseIntegratedSecurity = String.IsNullOrEmpty(uiConnectionInfo.Password);
            return(connectionInfo);
        }
Пример #4
0
        public DbConnectionString GetFromActiveConnection()
        {
            UIConnectionInfo connInfo = ServiceCache.ScriptFactory.CurrentlyActiveWndConnectionInfo?.UIConnectionInfo;

            if (connInfo == null || connInfo.AdvancedOptions["DATABASE"] == null || DbHelper.IsSystemDb(connInfo.AdvancedOptions["DATABASE"]))
            {
                return(null);
            }

            return(new DbConnectionString(GetConnectionString(connInfo), connInfo.AdvancedOptions["DATABASE"]));
        }
Пример #5
0
        /// <summary>
        /// Writes TSQL query history to an XML file
        /// </summary>
        /// <param name="Guid"></param>
        /// <param name="ID"></param>
        /// <param name="customIn"></param>
        /// <param name="customOut"></param>
        public void CommandEvents_AfterExecute(string Guid, int ID, object customIn, object customOut)
        {
            EnvDTE.TextDocument doc = (EnvDTE.TextDocument)ServiceCache.ExtensibilityModel.ActiveDocument.Object(null);
            if (doc != null)
            {
                string Sql = GetSQLString(doc);

                if (String.IsNullOrWhiteSpace(Sql))
                {
                    return;
                }

                // Get Current Connection Information
                UIConnectionInfo connInfo = ServiceCache.ScriptFactory.CurrentlyActiveWndConnectionInfo.UIConnectionInfo;

                // Set the path to the history file
                string path = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                    "SSMS Query History",
                    DateTime.Now.ToString("yyyy-MMM-dd"));

                // Create the history file path if it doesn't exist
                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }

                // Set the filename of the history file
                string filename = Path.Combine(path, "QueryHistory.xml");

                // Attempt to load the history file and create an empty file if it doesn't exist
                XDocument history;
                try
                {
                    history = XDocument.Load(filename);
                }
                catch (FileNotFoundException)
                {
                    history = XDocument.Parse("<SSMSQueryHistory/>");
                }

                // Add the newly executed TSQL query
                history.Root.Add(
                    new XElement("HistoryEntry",
                                 new XElement("Server", new XCData(connInfo.ServerName ?? String.Empty)),
                                 new XElement("Database", new XCData(connInfo.AdvancedOptions["DATABASE"])),
                                 new XElement("DateTime", DateTime.Now),
                                 new XElement("Query", new XCData(Sql))));

                // Save the history file
                history.Save(filename);
            }
        }
        public ServerConnectionInfo GetCurrentConnection()
        {
            ServerConnectionInfo currentConnection = null;

            try
            {
                UIConnectionInfo connectionInfo = null;

                if (_scriptFactory.CurrentlyActiveWndConnectionInfo != null)
                {
                    connectionInfo = _scriptFactory.CurrentlyActiveWndConnectionInfo.UIConnectionInfo;
                }

                if (connectionInfo != null)
                {
                    currentConnection = new ServerConnectionInfo
                    {
                        ServerName            = connectionInfo.ServerName,
                        UseIntegratedSecurity = string.IsNullOrEmpty(connectionInfo.Password),
                        UserName = connectionInfo.UserName,
                        Password = connectionInfo.Password
                    };
                }
                else
                {
                    int nodeCount;
                    INodeInformation[] nodes;

                    _objectExplorerService.GetSelectedNodes(out nodeCount, out nodes);

                    if (nodes.Length > 0)
                    {
                        var info = nodes[0].Connection as SqlConnectionInfo;
                        if (info != null)
                        {
                            currentConnection = new ServerConnectionInfo
                            {
                                ServerName            = info.ServerName,
                                UseIntegratedSecurity = info.UseIntegratedSecurity,
                                UserName = info.UserName,
                                Password = info.Password
                            };
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Error getting current connection: {0}", ex);
            }
            return(currentConnection);
        }
Пример #7
0
        /// <summary>
        /// Gets the connection string from a UIConnectionInfo object
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <returns></returns>
        internal static string GetConnectionString(UIConnectionInfo connection)
        {
            var builder = new SqlConnectionStringBuilder();

            builder.DataSource         = connection.ServerName;
            builder.IntegratedSecurity = string.IsNullOrEmpty(connection.Password);
            builder.Password           = connection.Password;
            builder.UserID             = connection.UserName;
            builder.InitialCatalog     = connection.AdvancedOptions["DATABASE"] ?? "master";
            builder.ApplicationName    = "Internals Viewer";

            return(builder.ToString());
        }
Пример #8
0
        internal static string GetConnectionString(UIConnectionInfo connection, string defaultDatabase = "master")
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();

            builder.DataSource         = connection.ServerName;
            builder.IntegratedSecurity = string.IsNullOrEmpty(connection.Password);

            builder.Password        = connection.Password;
            builder.UserID          = connection.UserName;
            builder.InitialCatalog  = connection.AdvancedOptions["DATABASE"] ?? defaultDatabase;
            builder.ApplicationName = "Peter Henell Plugins";

            return(builder.ToString());
        }
        private static UIConnectionInfo CreateFrom(SqlConnectionInfo connInfo)
        {
            var ci = new UIConnectionInfo();

            ci.ServerName      = connInfo.ServerName;
            ci.ServerType      = new Guid("8c91a03d-f9b4-46c0-a305-b5dcc79ff907");
            ci.UserName        = connInfo.UserName;
            ci.Password        = connInfo.Password;
            ci.PersistPassword = true;
            ci.ApplicationName = "Microsoft SQL Server Management Studio - Query";

            ci.AuthenticationType = !connInfo.UseIntegratedSecurity
                                ? 1
                                : 0;

            return(ci);
        }
Пример #10
0
        /// <summary>
        /// Gets the active window connection.
        /// </summary>
        /// <returns></returns>
        internal SqlConnectionInfo GetActiveWindowConnection()
        {
            SqlConnectionInfo info = null;

            try
            {
                UIConnectionInfo connInfo = null;

                if (ServiceCache.ScriptFactory.CurrentlyActiveWndConnectionInfo != null)
                {
                    connInfo = ServiceCache.ScriptFactory.CurrentlyActiveWndConnectionInfo.UIConnectionInfo;
                }

                if (connInfo != null)
                {
                    if (connInfo == currentUiConnection)
                    {
                        return(currentConnection);
                    }
                    else
                    {
                        info = CreateSqlConnectionInfo(connInfo);

                        currentConnection   = info;
                        currentUiConnection = connInfo;
                    }
                }

                if (info == null)
                {
                    var nodes = GetObjectExplorerSelectedNodes();

                    if (nodes.Length > 0)
                    {
                        info = nodes[0].Connection as SqlConnectionInfo;
                    }
                }

                return(info);
            }
            catch (NullReferenceException)
            {
                return(null);
            }
        }
        /// <summary>
        /// Creates a SqlConnectionInfo object from a UIConnectionInfo object
        /// </summary>
        /// <param name="connectionInfo">The connection info.</param>
        /// <returns></returns>
        public static SqlConnectionInfo CreateSqlConnectionInfo(UIConnectionInfo connectionInfo)
        {
            var sqlConnInfo = new SqlConnectionInfo();

            sqlConnInfo.ServerName = connectionInfo.ServerName;
            sqlConnInfo.UserName   = connectionInfo.UserName;

            if (string.IsNullOrEmpty(connectionInfo.Password))
            {
                sqlConnInfo.UseIntegratedSecurity = true;
            }
            else
            {
                sqlConnInfo.Password = connectionInfo.Password;
            }

            return(sqlConnInfo);
        }
Пример #12
0
        private static string GetConnectionString(UIConnectionInfo connection)
        {
            var integratedSecurity = string.IsNullOrEmpty(connection.Password);
            var builder            = new SqlConnectionStringBuilder
            {
                DataSource         = connection.ServerName,
                IntegratedSecurity = integratedSecurity,
                InitialCatalog     = connection.AdvancedOptions["DATABASE"] ?? "master",
                ApplicationName    = "Q2C"
            };

            if (!integratedSecurity)
            {
                builder.Password = connection.Password;
                builder.UserID   = connection.UserName;
            }
            return(builder.ConnectionString);
        }
Пример #13
0
        public void Connect()
        {
            using (ShellConnectionDialog dialog = new ShellConnectionDialog())
            {
                IServerType serverType = new SqlServerType();

                dialog.AddServer(serverType);

                UIConnectionInfo connectionInfo = new UIConnectionInfo();

                if (dialog.ShowDialogCollectValues(ServiceCache.MainShellWindow, ref connectionInfo) == DialogResult.OK)
                {
                    ConnectionManager.ConnectInternalsViewer(connectionInfo);

                    this.allocationWindowControl.RefreshDatabases();
                }
            }
        }
Пример #14
0
        private static UIConnectionInfo CreateFrom(SqlConnectionInfo connInfo)
        {
            //System.Diagnostics.Debugger.Launch();
            //System.Diagnostics.Debugger.Break();

            var authMethod = SqlConnectionInfo.AuthenticationMethod.NotSpecified;

            if (!connInfo.UseIntegratedSecurity)
            {
                if (connInfo.Authentication != SqlConnectionInfo.AuthenticationMethod.NotSpecified)
                {
                    authMethod = connInfo.Authentication;
                }
                else if (!string.IsNullOrEmpty(connInfo.UserName) && !string.IsNullOrEmpty(connInfo.Password))
                {
                    // Note: For some reason, auth type is set as not specified for SqlPassword.
                    authMethod = SqlConnectionInfo.AuthenticationMethod.SqlPassword;
                }
            }

            var ci = new UIConnectionInfo
            {
                ServerName         = connInfo.ServerName,
                ServerType         = new Guid("8c91a03d-f9b4-46c0-a305-b5dcc79ff907"),
                UserName           = connInfo.UserName,
                Password           = connInfo.Password,
                PersistPassword    = true,
                ApplicationName    = "Microsoft SQL Server Management Studio - Query",
                AuthenticationType = (int)authMethod,
                ServerVersion      = connInfo.ServerVersion,
                OtherParams        = connInfo.AdditionalParameters,
                RenewableToken     = connInfo.AccessToken,
                InMemoryPassword   = connInfo.SecurePassword,
            };

            return(ci);
        }
Пример #15
0
        private void CommandEvents_BeforeExecute(string Guid, int ID, object CustomIn, object CustomOut, ref bool CancelDefault)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            try
            {
                string queryText = GetQueryText();

                if (string.IsNullOrWhiteSpace(queryText))
                {
                    return;
                }

                // Get Current Connection Information
                UIConnectionInfo connInfo = ServiceCache.ScriptFactory.CurrentlyActiveWndConnectionInfo.UIConnectionInfo;

                var queryItem = new QueryItem()
                {
                    Query            = queryText,
                    Server           = connInfo.ServerName,
                    Username         = connInfo.UserName,
                    Database         = connInfo.AdvancedOptions["DATABASE"],
                    ExecutionDateUtc = DateTime.UtcNow
                };

                _logger.LogInformation("Enqueued {@quetyItem}", queryItem.Query);

                itemsQueue.Enqueue(queryItem);

                Task.Delay(1000).ContinueWith((t) => this.SavePendingItems());
            }
            catch (Exception ex)
            {
                _logger.LogError("Error on BeforeExecute tracking", ex);
            }
        }
Пример #16
0
        private static void Postfix(UIConnectionInfo __instance, string trigger)
        {
            Profile p = (Profile)_profile.GetValue(__instance);

            if (trigger == "STRAFE")//view stats
            {
                StatsMenu.OpenStatsViewer(p, __instance.rootMenu);
            }
            else if (trigger == "MENU2" && p.localPlayer) //auth/ update
            {
                if (Keyboard.Down(Keys.LeftShift))        //reset auth; dont update
                {
                    statsWork.ValidateMeAsync();
                }
                else                                      //auth&auth
                {
                    statsWork.UpdateStatsAsync(p);
                }
            }
            else if (trigger == "RAGDOLL")                //view in browser
            {
                System.Diagnostics.Process.Start(statsWork.wepAppAdress + "/stats?search=" + p.steamID);
            }
        }
Пример #17
0
        public static SqlConnectionInfo GetActiveConnectionInfo()
        {
            UIConnectionInfo uiConnectionInfo = ServiceCache.ScriptFactory.CurrentlyActiveWndConnectionInfo.UIConnectionInfo;

            return(GetConnectionInfo(uiConnectionInfo));
        }
Пример #18
0
        public SqlConnectionInfo GetActiveWindowConnectionInfo()
        {
            SqlConnectionInfo info = null;
            try
            {
                UIConnectionInfo uiConnInfo = GetActiveUIConnectionInfo();
                //Dim uiConnInfo As UIConnectionInfo = Nothing
                //If ServiceCache.ScriptFactory.CurrentlyActiveWndConnectionInfo IsNot Nothing Then
                //	uiConnInfo = ServiceCache.ScriptFactory.CurrentlyActiveWndConnectionInfo.UIConnectionInfo
                //End If
                if (uiConnInfo != null)
                {
                    if (uiConnInfo == currentUIConnection)
                    {
                        return currentConnection;
                    }
                    else
                    {
                        info = CreateSqlConnectionInfo(uiConnInfo);
                        currentConnection = info;
                        currentUIConnection = uiConnInfo;
                    }
                }

                if (info == null)
                {	//desiti ce se ako GetActiveUIConnectionInfo() vrati nothing
                    INodeInformation[] nodes = GetObjectExplorerSelectedNodes();
                    if (nodes.Length > 0)
                    {
                        info = nodes[0].Connection as SqlConnectionInfo;
                    }
                }
                return info;
            }
            //catch (NullReferenceException e)
            catch (Exception e)
            {
                throw; // rethrows exception
                throw (new ApplicationException("GetActiveWindowConnectionInfo: unable to find connection info", e));
                //return null;
            }
        }
Пример #19
0
 /// <summary>
 /// Iz UIConnectionInfo builda SqlConnectionInfo kopirajući server, username, password, odabranu bazu.
 /// SqlConnectionInfo zna na temelju toga vratiti connectionstring i mozes ga koristiti za kreiranje sql konekcija.
 /// </summary>
 /// <param name="uiConnInfo"></param>
 /// <returns></returns>
 /// <remarks></remarks>
 private SqlConnectionInfo CreateSqlConnectionInfo(UIConnectionInfo uiConnInfo)
 {
     SqlConnectionInfo sqlConnInfo = new SqlConnectionInfo();
     sqlConnInfo.ServerName = uiConnInfo.ServerName;
     sqlConnInfo.UserName = uiConnInfo.UserName;
     if (string.IsNullOrEmpty(uiConnInfo.Password))
     {
         sqlConnInfo.UseIntegratedSecurity = true;
     }
     else
     {
         sqlConnInfo.Password = uiConnInfo.Password;
     }
     sqlConnInfo.DatabaseName = uiConnInfo.AdvancedOptions["DATABASE"];
     sqlConnInfo.ConnectionTimeout = 3; // default je 15, jedinice su sekunde
     sqlConnInfo.QueryTimeout = 5; // max trajanje upita
     sqlConnInfo.ApplicationName = "XDetails"; // da se vidi u sesijama baze tko se spaja
     return sqlConnInfo;
 }
Пример #20
0
        ServerInfo GetServerInfo(UIConnectionInfo uiConnectionInfo)
        {
            var databases = Properties.Settings.Default.GetDatabases();

            if (databases.Length == 0)
            {
                return(null);
            }

            if (_cache.ContainsKey(uiConnectionInfo.ServerName))
            {
                ServerInfoCache serverInfoCache = _cache[uiConnectionInfo.ServerName];
                if (Enumerable.SequenceEqual(serverInfoCache.databases, databases) &&
                    DateTime.Now.Subtract(serverInfoCache.timestamp).TotalMinutes < 30)
                {
                    return(serverInfoCache.info);
                }
            }

            ServerInfo        res            = new ServerInfo();
            SqlConnectionInfo connectionInfo = Common.Connection.GetConnectionInfo(uiConnectionInfo);
            ServerConnection  connection     = new ServerConnection(connectionInfo);
            Server            server         = new Server(connection);

            foreach (Database database in server.Databases)
            {
                if (databases.Contains(database.Name))
                {
                    DatabaseInfo databaseInfo = new DatabaseInfo();
                    foreach (Table table in database.Tables)
                    {
                        databaseInfo.tables[table.Name] = table.Schema;
                        databaseInfo.tablesLower[table.Name.ToLower()] = table.Name;
                    }
                    foreach (View view in database.Views)
                    {
                        // views are indistinguishable from tables in preloader's context
                        databaseInfo.tables[view.Name] = view.Schema;
                        databaseInfo.tablesLower[view.Name.ToLower()] = view.Name;
                    }
                    foreach (UserDefinedFunction function in database.UserDefinedFunctions)
                    {
                        databaseInfo.functions[function.Name] = function.Schema;
                        databaseInfo.functionsLower[function.Name.ToLower()] = function.Name;
                    }
                    foreach (StoredProcedure proc in database.StoredProcedures)
                    {
                        databaseInfo.procedures[proc.Name] = proc.Schema;
                        databaseInfo.proceduresLower[proc.Name.ToLower()] = proc.Name;
                    }
                    res.databases[database.Name] = databaseInfo;
                }
            }

            {
                ServerInfoCache serverInfoCache = new ServerInfoCache();
                serverInfoCache.info                = res;
                serverInfoCache.databases           = databases;
                serverInfoCache.timestamp           = DateTime.Now;
                _cache[uiConnectionInfo.ServerName] = serverInfoCache;
            }

            return(res);
        }
Пример #21
0
        public void Apply(TextDocument textDoc, TextPoint startPoint, TextPoint endPoint)
        {
            string delta = startPoint.CreateEditPoint().GetText(endPoint);

            if (!(delta == " " || delta == "\t" || delta == "\r\n" || delta == "("))
            {
                return;
            }

            UIConnectionInfo uiConnectionInfo = ServiceCache.ScriptFactory.CurrentlyActiveWndConnectionInfo.UIConnectionInfo;
            ServerInfo       serverInfo       = GetServerInfo(uiConnectionInfo);

            if (serverInfo == null)
            {
                return;
            }

            string text = textDoc.StartPoint.CreateEditPoint().GetText(endPoint);

            text = text.Replace(Environment.NewLine, "\n");
            int    cursorPos      = textDoc.Selection.ActivePoint.AbsoluteCharOffset - 1;
            string activeDatabase = Common.Connection.GetActiveDatabase(text, cursorPos);

            var wordMatch = wordRegex.Match(text);

            if (!wordMatch.Success)
            {
                return;
            }
            string wordSchema  = wordMatch.Groups[1].Value;
            string matchedWord = wordMatch.Groups[2].Value;
            string word        = matchedWord;
            var    group       = wordMatch.Groups[1].Success ? wordMatch.Groups[1] : wordMatch.Groups[2];

            string prependDb           = null;
            string prependSchema       = null;
            bool   prependSchemaIgnore = false;

            if (fromJoinRegex.Match(text).Success)
            {
                foreach (var db in serverInfo.databases)
                {
                    word = DictGet(db.Value.tablesLower, word, word);
                    if (db.Key != activeDatabase)
                    {
                        string cword = DictGet(db.Value.tablesLower, word, word);
                        if (db.Value.tables.ContainsKey(cword))
                        {
                            prependDb           = db.Key;
                            prependSchema       = db.Value.tables[word];
                            prependSchemaIgnore = prependSchema == "dbo";
                            break;
                        }
                    }
                }
            }
            else if (execRegex.Match(text).Success)
            {
                foreach (var db in serverInfo.databases)
                {
                    word = DictGet(db.Value.proceduresLower, word, word);
                    if (db.Key != activeDatabase)
                    {
                        if (db.Value.procedures.ContainsKey(word))
                        {
                            prependDb           = db.Key;
                            prependSchema       = db.Value.procedures[word];
                            prependSchemaIgnore = prependSchema == "dbo";
                            break;
                        }
                    }
                }
            }
            else if (delta == "(")
            {
                foreach (var db in serverInfo.databases)
                {
                    word = DictGet(db.Value.functionsLower, word, word);
                    if (db.Value.functions.ContainsKey(word))
                    {
                        prependDb     = db.Key;
                        prependSchema = db.Value.functions[word];
                        break;
                    }
                }
            }
            if (word != matchedWord)
            {
                var editPoint = textDoc.CreateEditPoint();
                editPoint.MoveToAbsoluteOffset(wordMatch.Groups[2].Index + 1);
                editPoint.Delete(wordMatch.Groups[2].Length);
                editPoint.Insert(word);
            }
            string prependText = "";

            if (prependDb != null)
            {
                prependText += prependDb + ".";
            }
            if (prependSchema != null)
            {
                if (!String.IsNullOrEmpty(wordSchema))
                {
                    if ((prependSchema + '.') != wordSchema)
                    {
                        return;
                    }
                }
                else
                {
                    if (!prependSchemaIgnore)
                    {
                        prependText += prependSchema;
                    }
                    prependText += ".";
                }
            }
            if (prependText != "")
            {
                var editPoint = textDoc.CreateEditPoint();
                editPoint.MoveToAbsoluteOffset(group.Index + 1);
                editPoint.Insert(prependText);
            }
        }
Пример #22
0
        public static void SetSqlEditorConnection(IVsTextLines ppBuffer, ISqlContextDeterminator contextDeterminator, OleMenuCommandService commandService, CommandID sqlEditorConnectCmdId)
        {
            if (ppBuffer != null && contextDeterminator != null && _sqlExtractionFile != null)
            {
#if DEV15_OR_LATER
                Assembly dll = Assembly.Load(@"Microsoft.VisualStudio.Data.Tools.SqlEditor, Version=15.0.0.0");
#elif DEV14_OR_LATER
                Assembly dll = Assembly.Load(@"Microsoft.VisualStudio.Data.Tools.SqlEditor, Version=14.0.0.0");
#else
                Assembly dll = Assembly.Load(@"Microsoft.VisualStudio.Data.Tools.SqlEditor, Version=12.0.0.0");
#endif
                if (dll != null)
                {
                    Type sqlEditorPackageType = dll.GetType("Microsoft.VisualStudio.Data.Tools.SqlEditor.VSIntegration.SqlEditorPackage");
                    if (sqlEditorPackageType != null)
                    {
                        // get the GetAuxiliaryDocData method
                        var instanceProp = sqlEditorPackageType.GetProperty("Instance", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
                        if (instanceProp != null)
                        {
                            var instanceVal = instanceProp.GetValue(null, null);
                            if (instanceVal != null)
                            {
                                var getAuxMethod = sqlEditorPackageType.GetMethod("GetAuxillaryDocData", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                                if (getAuxMethod != null)
                                {
                                    var auxiliaryDocDataVal = getAuxMethod.Invoke(instanceVal, new object[] { ppBuffer });
                                    if (auxiliaryDocDataVal != null)
                                    {
                                        // set the sql connection (IDbConnection) on the QueryExecutor.ConnectionStrategy
                                        var queryExecutorType = auxiliaryDocDataVal.GetType().GetProperty("QueryExecutor", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                                        if (queryExecutorType != null)
                                        {
                                            var queryExecutorVal = queryExecutorType.GetValue(auxiliaryDocDataVal, null);
                                            if (queryExecutorVal != null)
                                            {
                                                var connectionStrategyType = queryExecutorVal.GetType().GetProperty("ConnectionStrategy", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                                                if (connectionStrategyType != null)
                                                {
                                                    var connectionStrategyVal = connectionStrategyType.GetValue(queryExecutorVal, null);
                                                    if (connectionStrategyVal != null)
                                                    {
                                                        // set the _connection field

                                                        var connectionField   = connectionStrategyVal.GetType().GetAllFields().Where(x => x.Name == "_connection").FirstOrDefault();
                                                        var uiConnectionField = connectionStrategyVal.GetType().GetAllFields().Where(x => x.Name == "_connectionInfo").FirstOrDefault();
                                                        if (connectionField != null && uiConnectionField != null)
                                                        {
                                                            string server, database;
                                                            if (contextDeterminator.DetermineSqlContext(_sqlExtractionFile, out server, out database))
                                                            {
                                                                SqlConnection sqlCon = new SqlConnection(string.Format(@"Data Source={0};Integrated Security=true;", server));
                                                                sqlCon.Open();
                                                                sqlCon.ChangeDatabase(database);
                                                                connectionField.SetValue(connectionStrategyVal, sqlCon);

                                                                try
                                                                {
                                                                    UIConnectionInfo connInfo = new UIConnectionInfo()
                                                                    {
                                                                        ServerName = server, UserName = string.Format("{0}\\{1}", Environment.UserDomainName, Environment.UserName)
                                                                    };
                                                                    uiConnectionField.SetValue(connectionStrategyVal, connInfo);
                                                                }
                                                                catch (ArgumentException ae)
                                                                {
                                                                    // In VS2015 this exception gets thrown, but everything works correctly.
                                                                    // So for the time being, we'll just keep going
                                                                }

                                                                if (commandService != null)
                                                                {
                                                                    commandService.GlobalInvoke(sqlEditorConnectCmdId);
                                                                }

                                                                // attempt to set the QueryExecutor's IsConnected value
                                                                var isConnProp = queryExecutorVal.GetType().GetProperty("IsConnected", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                                                                if (isConnProp != null)
                                                                {
                                                                    isConnProp.SetValue(queryExecutorVal, true, null);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #23
0
 /// <summary>
 /// Connects the internals viewer singleton
 /// </summary>
 /// <param name="connectionInfo">The connection info.</param>
 internal static void ConnectInternalsViewer(UIConnectionInfo connectionInfo)
 {
     ConnectInternalsViewer(ConnectionManager.CreateSqlConnectionInfo(connectionInfo));
 }