/// <summary>
        /// Accepts anything and tries to convert it to a live SMO Database object
        /// </summary>
        /// <param name="Item">The item to convert</param>
        public DbaDatabaseSmoParameter(object Item)
        {
            if (Item == null)
            {
                throw new ArgumentException("Input must not be null!");
            }

            InputObject = Item;
            PSObject tempInput = new PSObject(Item);

            if (tempInput.TypeNames.Contains("Microsoft.SqlServer.Management.Smo.Database"))
            {
                Database = Item;
                Name     = (string)tempInput.Properties["Name"].Value;
                return;
            }

            foreach (PSPropertyInfo prop in tempInput.Properties)
            {
                if (UtilityHost.IsLike(prop.Name, "Database") && (prop.Value != null))
                {
                    PSObject tempDB = new PSObject(prop.Value);

                    if (tempDB.TypeNames.Contains("Microsoft.SqlServer.Management.Smo.Database"))
                    {
                        Database = prop.Value;
                        Name     = (string)tempDB.Properties["Name"].Value;
                        return;
                    }
                }
            }

            throw new ArgumentException("Cannot interpret input as SMO Database object");
        }
Example #2
0
        /// <summary>
        /// Applies a transformation rule to the columns stored in this view
        /// </summary>
        /// <param name="Transform">The transformation rule to apply</param>
        public void TransformColumn(ColumnTransformation Transform)
        {
            if (!UtilityHost.IsLike(Name, Transform.FilterViewName))
            {
                return;
            }

            bool applied = false;

            foreach (Column column in Columns)
            {
                if ((!String.IsNullOrEmpty(Transform.FilterColumnName)) && (UtilityHost.IsLike(column.SortableName, Transform.FilterColumnName)))
                {
                    Transform.Apply(column);
                    applied = true;
                }
            }

            if (!applied && Transform.Append && (Transform.ScriptBlock != null))
            {
                Column tempColumn = new Column();
                Transform.Apply(tempColumn);
                Columns.Add(tempColumn);
            }
        }
 /// <summary>
 /// Tests, whether the completion set applies to the specified parameter / command combination
 /// </summary>
 /// <param name="Command">The command to test</param>
 /// <param name="Parameter">The parameter of the command to test</param>
 /// <returns>Whether this completion set applies to the specified combination of parameter / command</returns>
 public bool Applies(string Command, string Parameter)
 {
     if ((UtilityHost.IsLike(Command, this.Command)) && (UtilityHost.IsLike(Parameter, this.Parameter)))
     {
         return(true);
     }
     return(false);
 }
        /// <summary>
        /// Parses an input string as timespan
        /// </summary>
        /// <param name="Value">The string to interpret</param>
        /// <returns>The interpreted timespan value</returns>
        internal static TimeSpan ParseTimeSpan(string Value)
        {
            if (String.IsNullOrWhiteSpace(Value))
            {
                throw new ArgumentNullException("Cannot parse empty string!");
            }

            try { return(TimeSpan.Parse(Value, CultureInfo.CurrentCulture)); }
            catch { }
            try { return(TimeSpan.Parse(Value, CultureInfo.InvariantCulture)); }
            catch { }

            bool     positive   = !(Value.Contains('-'));
            TimeSpan timeResult = new TimeSpan();
            string   tempValue  = Value.Replace("-", "").Trim();

            foreach (string element in tempValue.Split(' '))
            {
                if (Regex.IsMatch(element, @"^\d+$"))
                {
                    timeResult = timeResult.Add(new TimeSpan(0, 0, Int32.Parse(element)));
                }
                else if (UtilityHost.IsLike(element, "*ms") && Regex.IsMatch(element, @"^\d+ms$", RegexOptions.IgnoreCase))
                {
                    timeResult = timeResult.Add(new TimeSpan(0, 0, 0, 0, Int32.Parse(Regex.Match(element, @"^(\d+)ms$", RegexOptions.IgnoreCase).Groups[1].Value)));
                }
                else if (UtilityHost.IsLike(element, "*s") && Regex.IsMatch(element, @"^\d+s$", RegexOptions.IgnoreCase))
                {
                    timeResult = timeResult.Add(new TimeSpan(0, 0, Int32.Parse(Regex.Match(element, @"^(\d+)s$", RegexOptions.IgnoreCase).Groups[1].Value)));
                }
                else if (UtilityHost.IsLike(element, "*m") && Regex.IsMatch(element, @"^\d+m$", RegexOptions.IgnoreCase))
                {
                    timeResult = timeResult.Add(new TimeSpan(0, Int32.Parse(Regex.Match(element, @"^(\d+)m$", RegexOptions.IgnoreCase).Groups[1].Value), 0));
                }
                else if (UtilityHost.IsLike(element, "*h") && Regex.IsMatch(element, @"^\d+h$", RegexOptions.IgnoreCase))
                {
                    timeResult = timeResult.Add(new TimeSpan(Int32.Parse(Regex.Match(element, @"^(\d+)h$", RegexOptions.IgnoreCase).Groups[1].Value), 0, 0));
                }
                else if (UtilityHost.IsLike(element, "*d") && Regex.IsMatch(element, @"^\d+d$", RegexOptions.IgnoreCase))
                {
                    timeResult = timeResult.Add(new TimeSpan(Int32.Parse(Regex.Match(element, @"^(\d+)d$", RegexOptions.IgnoreCase).Groups[1].Value), 0, 0, 0));
                }
                else
                {
                    throw new ArgumentException(String.Format("Failed to parse as timespan: {0} at {1}", Value, element));
                }
            }

            if (!positive)
            {
                return(timeResult.Negate());
            }
            return(timeResult);
        }
Example #5
0
        /// <summary>
        /// Returns a list of callbacks
        /// </summary>
        /// <param name="Name">The name to filter by</param>
        /// <param name="All">Whether also callbacks from other runspaces should be included</param>
        /// <returns>The list of matching callbacks</returns>
        public static List <Callback> Get(string Name, bool All = false)
        {
            List <Callback> callbacks = new List <Callback>();

            foreach (Callback callback in Callbacks.Values)
            {
                if (UtilityHost.IsLike(callback.Name, Name) && (All || callback.Runspace == null || callback.Runspace == System.Management.Automation.Runspaces.Runspace.DefaultRunspace.InstanceId))
                {
                    callbacks.Add(callback);
                }
            }
            return(callbacks);
        }
Example #6
0
        /// <summary>
        /// Checks, whether a given entry matches the filter defined in this subscription
        /// </summary>
        /// <param name="Entry">The entry to validate</param>
        /// <returns>Whether the subscription should react to this entry</returns>
        public bool Applies(LogEntry Entry)
        {
            if (MessageFilterSet && !UtilityHost.IsLike(Entry.Message, MessageFilter))
            {
                return(false);
            }
            if (ModuleNameFilterSet && !UtilityHost.IsLike(Entry.ModuleName, ModuleNameFilter))
            {
                return(false);
            }
            if (FunctionNameFilterSet && !UtilityHost.IsLike(Entry.FunctionName, FunctionNameFilter))
            {
                return(false);
            }
            if (TargetFilterSet && (Entry.TargetObject != TargetFilter))
            {
                return(false);
            }
            if (LevelFilterSet && !LevelFilter.Contains(Entry.Level))
            {
                return(false);
            }
            if (TagFilterSet)
            {
                bool test = false;

                foreach (string tag in TagFilter)
                {
                    foreach (string tag2 in Entry.Tags)
                    {
                        if (tag == tag2)
                        {
                            test = true;
                        }
                    }
                }

                if (!test)
                {
                    return(false);
                }
            }
            if (RunspaceFilterSet && RunspaceFilter != Entry.Runspace)
            {
                return(false);
            }

            return(true);
        }
Example #7
0
 /// <summary>
 /// Whether the callback applies to the current command.
 /// </summary>
 /// <param name="ModuleName">Module the current command is part of</param>
 /// <param name="CommandName">Command that is currently executing</param>
 /// <returns>True if it applies, otherwise False</returns>
 public bool Applies(string ModuleName, string CommandName)
 {
     if (!ModuleName.Equals(ModuleName, StringComparison.InvariantCultureIgnoreCase))
     {
         return(false);
     }
     if ((Runspace != null) & (Runspace != System.Management.Automation.Runspaces.Runspace.DefaultRunspace.InstanceId))
     {
         return(false);
     }
     if (!UtilityHost.IsLike(CommandName, this.CommandName))
     {
         return(false);
     }
     return(true);
 }
Example #8
0
        /// <summary>
        /// Returns the first transform whose filter is similar enough to work out.
        /// </summary>
        /// <param name="TypeName">The name of the type to check for a transform</param>
        /// <param name="ModuleName">The module of the command that wrote the message with the transformable object</param>
        /// <param name="Functionname">The command that wrote the message with the transformable object</param>
        /// <returns>Either a transform or null, if no fitting transform was found</returns>
        public TransformCondition Get(string TypeName, string ModuleName, string Functionname)
        {
            foreach (TransformCondition con in list)
            {
                if (!UtilityHost.IsLike(TypeName, con.TypeName))
                {
                    continue;
                }
                if (!UtilityHost.IsLike(ModuleName, con.ModuleName))
                {
                    continue;
                }
                if (!UtilityHost.IsLike(Functionname, con.FunctionName))
                {
                    continue;
                }

                return(con);
            }

            return(null);
        }
Example #9
0
        /// <summary>
        /// Creates a DBA Instance Parameter from string
        /// </summary>
        /// <param name="Name">The name of the instance</param>
        public DbaInstanceParameter(string Name)
        {
            InputObject = Name;

            if (string.IsNullOrWhiteSpace(Name))
            {
                throw new BloodyHellGiveMeSomethingToWorkWithException("Please provide an instance name", "DbaInstanceParameter");
            }

            if (Name == ".")
            {
                _ComputerName    = Name;
                _NetworkProtocol = SqlConnectionProtocol.NP;
                return;
            }

            string tempString = Name.Trim();

            tempString = Regex.Replace(tempString, @"^\[(.*)\]$", "$1");

            if (UtilityHost.IsLike(tempString, @".\*"))
            {
                _ComputerName    = Name;
                _NetworkProtocol = SqlConnectionProtocol.NP;

                string instanceName = tempString.Substring(2);

                if (!Utility.Validation.IsValidInstanceName(instanceName))
                {
                    throw new ArgumentException(String.Format("Failed to interpret instance name: '{0}' is not a legal name!", instanceName));
                }

                _InstanceName = instanceName;

                return;
            }

            if (UtilityHost.IsLike(tempString, "*.WORKGROUP"))
            {
                tempString = Regex.Replace(tempString, @"\.WORKGROUP$", "", RegexOptions.IgnoreCase);
            }

            // Named Pipe path notation interpretation
            if (Regex.IsMatch(tempString, @"^\\\\[^\\]+\\pipe\\([^\\]+\\){0,1}sql\\query$", RegexOptions.IgnoreCase))
            {
                try
                {
                    _NetworkProtocol = SqlConnectionProtocol.NP;

                    _ComputerName = Regex.Match(tempString, @"^\\\\([^\\]+)\\").Groups[1].Value;

                    if (Regex.IsMatch(tempString, @"\\MSSQL\$[^\\]+\\", RegexOptions.IgnoreCase))
                    {
                        _InstanceName = Regex.Match(tempString, @"\\MSSQL\$([^\\]+)\\", RegexOptions.IgnoreCase).Groups[1].Value;
                    }
                }
                catch (Exception e)
                {
                    throw new ArgumentException(String.Format("Failed to interpret named pipe path notation: {0} | {1}", InputObject, e.Message), e);
                }

                return;
            }

            // Connection String interpretation
            try
            {
                System.Data.SqlClient.SqlConnectionStringBuilder connectionString =
                    new System.Data.SqlClient.SqlConnectionStringBuilder(tempString);
                DbaInstanceParameter tempParam = new DbaInstanceParameter(connectionString.DataSource);
                _ComputerName = tempParam.ComputerName;
                if (tempParam.InstanceName != "MSSQLSERVER")
                {
                    _InstanceName = tempParam.InstanceName;
                }
                if (tempParam.Port != 1433)
                {
                    _Port = tempParam.Port;
                }
                _NetworkProtocol = tempParam.NetworkProtocol;

                if (UtilityHost.IsLike(tempString, @"(localdb)\*"))
                {
                    _NetworkProtocol = SqlConnectionProtocol.NP;
                }

                IsConnectionString = true;

                return;
            }
            catch (ArgumentException ex)
            {
                string name = "unknown";
                try
                {
                    name = ex.TargetSite.GetParameters()[0].Name;
                }
                catch
                {
                }
                if (name == "keyword")
                {
                    throw;
                }
            }
            catch (FormatException)
            {
                throw;
            }
            catch { }

            // Handle and clear protocols. Otherwise it'd make port detection unneccessarily messy
            if (Regex.IsMatch(tempString, "^TCP:", RegexOptions.IgnoreCase)) //TODO: Use case insinsitive String.BeginsWith()
            {
                _NetworkProtocol = SqlConnectionProtocol.TCP;
                tempString       = tempString.Substring(4);
            }
            if (Regex.IsMatch(tempString, "^NP:", RegexOptions.IgnoreCase)) // TODO: Use case insinsitive String.BeginsWith()
            {
                _NetworkProtocol = SqlConnectionProtocol.NP;
                tempString       = tempString.Substring(3);
            }

            // Case: Default instance | Instance by port
            if (tempString.Split('\\').Length == 1)
            {
                if (Regex.IsMatch(tempString, @"[:,]\d{1,5}$") && !Regex.IsMatch(tempString, RegexHelper.IPv6) && ((tempString.Split(':').Length == 2) || (tempString.Split(',').Length == 2)))
                {
                    char delimiter;
                    if (Regex.IsMatch(tempString, @"[:]\d{1,5}$"))
                    {
                        delimiter = ':';
                    }
                    else
                    {
                        delimiter = ',';
                    }

                    try
                    {
                        Int32.TryParse(tempString.Split(delimiter)[1], out _Port);
                        if (_Port > 65535)
                        {
                            throw new PSArgumentException("Failed to parse instance name: " + tempString);
                        }
                        tempString = tempString.Split(delimiter)[0];
                    }
                    catch
                    {
                        throw new PSArgumentException("Failed to parse instance name: " + Name);
                    }
                }

                if (Utility.Validation.IsValidComputerTarget(tempString))
                {
                    _ComputerName = tempString;
                }

                else
                {
                    throw new PSArgumentException("Failed to parse instance name: " + Name);
                }
            }

            // Case: Named instance
            else if (tempString.Split('\\').Length == 2)
            {
                string tempComputerName = tempString.Split('\\')[0];
                string tempInstanceName = tempString.Split('\\')[1];

                if (Regex.IsMatch(tempComputerName, @"[:,]\d{1,5}$") && !Regex.IsMatch(tempComputerName, RegexHelper.IPv6))
                {
                    char delimiter;
                    if (Regex.IsMatch(tempComputerName, @"[:]\d{1,5}$"))
                    {
                        delimiter = ':';
                    }
                    else
                    {
                        delimiter = ',';
                    }

                    try
                    {
                        Int32.TryParse(tempComputerName.Split(delimiter)[1], out _Port);
                        if (_Port > 65535)
                        {
                            throw new PSArgumentException("Failed to parse instance name: " + Name);
                        }
                        tempComputerName = tempComputerName.Split(delimiter)[0];
                    }
                    catch
                    {
                        throw new PSArgumentException("Failed to parse instance name: " + Name);
                    }
                }
                else if (Regex.IsMatch(tempInstanceName, @"[:,]\d{1,5}$") && !Regex.IsMatch(tempInstanceName, RegexHelper.IPv6))
                {
                    char delimiter;
                    if (Regex.IsMatch(tempString, @"[:]\d{1,5}$"))
                    {
                        delimiter = ':';
                    }
                    else
                    {
                        delimiter = ',';
                    }

                    try
                    {
                        Int32.TryParse(tempInstanceName.Split(delimiter)[1], out _Port);
                        if (_Port > 65535)
                        {
                            throw new PSArgumentException("Failed to parse instance name: " + Name);
                        }
                        tempInstanceName = tempInstanceName.Split(delimiter)[0];
                    }
                    catch
                    {
                        throw new PSArgumentException("Failed to parse instance name: " + Name);
                    }
                }

                // LocalDBs mostly ignore regular Instance Name rules, so that validation is only relevant for regular connections
                if (UtilityHost.IsLike(tempComputerName, "(localdb)") || (Utility.Validation.IsValidComputerTarget(tempComputerName) && Utility.Validation.IsValidInstanceName(tempInstanceName, true)))
                {
                    if (UtilityHost.IsLike(tempComputerName, "(localdb)"))
                    {
                        _ComputerName = "(localdb)";
                    }
                    else
                    {
                        _ComputerName = tempComputerName;
                    }
                    if ((tempInstanceName.ToLower() != "default") && (tempInstanceName.ToLower() != "mssqlserver"))
                    {
                        _InstanceName = tempInstanceName;
                    }
                }

                else
                {
                    throw new PSArgumentException(string.Format("Failed to parse instance name: {0}. Computer Name: {1}, Instance {2}", Name, tempComputerName, tempInstanceName));
                }
            }

            // Case: Bad input
            else
            {
                throw new PSArgumentException("Failed to parse instance name: " + Name);
            }
        }
Example #10
0
        /// <summary>
        /// Generates a Computer Parameter object from string
        /// </summary>
        /// <param name="ComputerName">The name to use as input</param>
        public ComputerParameter(string ComputerName)
        {
            InputObject = ComputerName;

            if (string.IsNullOrWhiteSpace(ComputerName))
            {
                throw new ArgumentException("Computername cannot be empty!");
            }

            string tempString = ComputerName.Trim();

            if (ComputerName == ".")
            {
                this.ComputerName = "localhost";
                return;
            }

            if (UtilityHost.IsLike(tempString, "*.WORKGROUP"))
            {
                tempString = Regex.Replace(tempString, @"\.WORKGROUP$", "", RegexOptions.IgnoreCase);
            }

            if (UtilityHost.IsValidComputerTarget(tempString))
            {
                this.ComputerName = tempString;
                return;
            }

            // Named Pipe path notation interpretation
            if (Regex.IsMatch(tempString, @"^\\\\[^\\]+\\pipe\\([^\\]+\\){0,1}sql\\query$", RegexOptions.IgnoreCase))
            {
                try
                {
                    this.ComputerName = Regex.Match(tempString, @"^\\\\([^\\]+)\\").Groups[1].Value;
                    return;
                }
                catch (Exception e)
                {
                    throw new ArgumentException(String.Format("Failed to interpret named pipe path notation: {0} | {1}", InputObject, e.Message), e);
                }
            }

            // Connection String interpretation
            try
            {
                System.Data.SqlClient.SqlConnectionStringBuilder connectionString = new System.Data.SqlClient.SqlConnectionStringBuilder(tempString);
                ComputerParameter tempParam = new ComputerParameter(connectionString.DataSource);
                this.ComputerName = tempParam.ComputerName;

                return;
            }
            catch (ArgumentException ex)
            {
                string name = "unknown";
                try
                {
                    name = ex.TargetSite.GetParameters()[0].Name;
                }
                catch
                {
                }
                if (name == "keyword")
                {
                    throw;
                }
            }
            catch (FormatException)
            {
                throw;
            }
            catch { }

            throw new ArgumentException(String.Format("Could not resolve computer name: {0}", ComputerName));
        }
Example #11
0
        /// <summary>
        /// Tests whether an error record applies to the provider instance
        /// </summary>
        /// <param name="Record">The error record to test</param>
        /// <returns>Whether it applies to the provider instance</returns>
        public bool MessageApplies(Message.PsfExceptionRecord Record)
        {
            // Modules
            if (IncludeModules.Count > 0)
            {
                bool test = false;
                foreach (string module in IncludeModules)
                {
                    if (string.Equals(Record.ModuleName, module, StringComparison.InvariantCultureIgnoreCase))
                    {
                        test = true;
                    }
                }

                if (!test)
                {
                    return(false);
                }
            }

            foreach (string module in ExcludeModules)
            {
                if (string.Equals(Record.ModuleName, module, StringComparison.InvariantCultureIgnoreCase))
                {
                    return(false);
                }
            }

            // Functions
            if (IncludeFunctions.Count > 0)
            {
                bool test = false;
                foreach (string function in IncludeFunctions)
                {
                    if (UtilityHost.IsLike(Record.FunctionName, function))
                    {
                        test = true;
                    }
                }

                if (!test)
                {
                    return(false);
                }
            }

            foreach (string function in ExcludeFunctions)
            {
                if (UtilityHost.IsLike(Record.FunctionName, function))
                {
                    return(false);
                }
            }

            // Tags
            if (IncludeTags.Count > 0)
            {
                if (IncludeTags.Except(Record.Tags).ToList().Count == IncludeTags.Count)
                {
                    return(false);
                }
            }

            if (ExcludeTags.Except(Record.Tags).ToList().Count < ExcludeTags.Count)
            {
                return(false);
            }

            return(true);
        }
Example #12
0
        /// <summary>
        /// Tests whether a log entry applies to the provider instance
        /// </summary>
        /// <param name="Entry">The Entry to validate</param>
        /// <returns>Whether it applies</returns>
        public bool MessageApplies(Message.LogEntry Entry)
        {
            // Level
            if (!IncludeWarning && (Entry.Level == Message.MessageLevel.Warning))
            {
                return(false);
            }
            if (((_MinLevel != 1) || (_MaxLevel != 9)) && (Entry.Level != Message.MessageLevel.Warning))
            {
                if (Entry.Level < (Message.MessageLevel)_MinLevel)
                {
                    return(false);
                }
                if (Entry.Level > (Message.MessageLevel)_MaxLevel)
                {
                    return(false);
                }
            }

            // Modules
            if (IncludeModules.Count > 0)
            {
                bool test = false;
                foreach (string module in IncludeModules)
                {
                    if (string.Equals(Entry.ModuleName, module, StringComparison.InvariantCultureIgnoreCase))
                    {
                        test = true;
                    }
                }

                if (!test)
                {
                    return(false);
                }
            }

            foreach (string module in ExcludeModules)
            {
                if (string.Equals(Entry.ModuleName, module, StringComparison.InvariantCultureIgnoreCase))
                {
                    return(false);
                }
            }

            // Functions
            if (IncludeFunctions.Count > 0)
            {
                bool test = false;
                foreach (string function in IncludeFunctions)
                {
                    if (UtilityHost.IsLike(Entry.FunctionName, function))
                    {
                        test = true;
                    }
                }

                if (!test)
                {
                    return(false);
                }
            }

            foreach (string function in ExcludeFunctions)
            {
                if (UtilityHost.IsLike(Entry.FunctionName, function))
                {
                    return(false);
                }
            }

            // Tags
            if (IncludeTags.Count > 0)
            {
                if (IncludeTags.Except(Entry.Tags, StringComparer.InvariantCultureIgnoreCase).ToList().Count == IncludeTags.Count)
                {
                    return(false);
                }
            }

            if (ExcludeTags.Except(Entry.Tags, StringComparer.InvariantCultureIgnoreCase).ToList().Count < ExcludeTags.Count)
            {
                return(false);
            }

            return(true);
        }