/// <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");
        }
Exemple #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>
        /// Invokes the callback scriptblock as configured.
        /// </summary>
        /// <param name="Caller">The object containing the information pertaining to the calling command.</param>
        /// <param name="Invoker">The meta object representing the invoking command.</param>
        /// <param name="Data">Extra data that was passed to the event</param>
        public void Invoke(CallerInfo Caller, PSCmdlet Invoker, object Data)
        {
            Hashtable table = new Hashtable(StringComparer.InvariantCultureIgnoreCase);

            table["Command"]        = Invoker.MyInvocation.MyCommand.Name;
            table["ModuleName"]     = Invoker.MyInvocation.MyCommand.ModuleName;
            table["CallerFunction"] = Caller.CallerFunction;
            table["CallerModule"]   = Caller.CallerModule;
            table["Data"]           = Data;

            try
            {
                if (BreakAffinity)
                {
                    lock (_InvokeLock)
                    {
                        UtilityHost.ImportScriptBlock(ScriptBlock);
                        ScriptBlock.Invoke(table);
                    }
                }
                else
                {
                    ScriptBlock.Invoke(table);
                }
            }
            catch (Exception e)
            {
                throw new CallbackException(this, e);
            }
        }
        /// <summary>
        /// Clones the specified scriptblock maintaining its language mode.
        /// </summary>
        /// <param name="ScriptBlock">The Scriptblock to clone</param>
        /// <returns>A clone of the scriptblock with the languagemode intact</returns>
        public static ScriptBlock Clone(this ScriptBlock ScriptBlock)
        {
            ScriptBlock newBlock = (ScriptBlock)UtilityHost.InvokePrivateMethod("Clone", ScriptBlock, null);

            UtilityHost.SetPrivateProperty("LanguageMode", newBlock, UtilityHost.GetPrivateProperty("LanguageMode", ScriptBlock));
            return(newBlock);
        }
Exemple #5
0
        public static Script CreateScriptRuntime(LuaScriptHost host)
        {
            host.CoroutineManager = new LuaCoroutineManager(host);
            var script = new Script(CoreModules.Preset_Default | CoreModules.Debug);

            script.Options.UseLuaErrorLocations = false;

            script.Globals["_host"]     = host;
            script.Globals["console"]   = typeof(LuaRuntime.Console);
            script.Globals["scene"]     = new SceneHost();
            script.Globals["resources"] = new ResourcesHost();
            script.Globals["game"]      = new GameHost(host);
            script.Globals["vec2"]      = (Func <float, float, Vector2>)MathUtilities.vec2;
            script.Globals["vec3"]      = (Func <float, float, float, Vector3>)MathUtilities.vec3;
            var utility = new UtilityHost(host);

            script.Globals["timeout"]        = (Func <Closure, float, int>)utility.SetTimeout;
            script.Globals["interval"]       = (Func <Closure, float, int>)utility.Interval;
            script.Globals["removeTimeout"]  = (Action <int>)utility.RemoveTimeout;
            script.Globals["removeInterval"] = (Action <int>)utility.RemoveInterval;
            script.Globals["waitForSeconds"] = (Func <float, YieldInstruction>)utility.WaitForSeconds;
            script.Globals["Time"]           = typeof(Time);
            script.Globals["timer"]          = (Func <float, IEnumerable <float> >)Utility.Timer;
            script.Globals["entity"]         = host.GetComponent <GameEntity>();
            script.Globals["startCoroutine"] = (Func <Closure, UnityEngine.Coroutine>)host.CoroutineManager.StartCoroutine;
            script.Globals["stopCoroutine"]  = (Action <UnityEngine.Coroutine>)host.CoroutineManager.StopCoroutine;
            script.Globals["utility"]        = utility;
            script.Globals["camera"]         = SceneCamera.Instance;
            script.Globals["wait"]           = (Func <string, UnityEngine.Coroutine>)((t) => host.StartCoroutine(Wait(host, t)));
            script.Globals["sign"]           = (Func <float, int>)MathUtility.SignInt;
            GUIHost.InitHost(host, script);
            return(script);
        }
 /// <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);
 }
Exemple #7
0
 /// <summary>
 /// This will import the events into the current execution context, breaking runspace affinity
 /// </summary>
 public void LocalizeEvents()
 {
     UtilityHost.ImportScriptBlock(BeginEvent, true);
     UtilityHost.ImportScriptBlock(StartEvent, true);
     UtilityHost.ImportScriptBlock(MessageEvent, true);
     UtilityHost.ImportScriptBlock(ErrorEvent, true);
     UtilityHost.ImportScriptBlock(EndEvent, true);
     UtilityHost.ImportScriptBlock(FinalEvent, true);
 }
        /// <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);
        }
Exemple #9
0
        public void ShouldExecute_Dispose_Correctly()
        {
            var host = new UtilityHost();

            CreateApplication();
            eventFired = false;
            host.Init(application);
            WebCoreEvents.Instance.HostStop += Instance_Fired;
            host.Dispose();
            WebCoreEvents.Instance.HostStop -= Instance_Fired;

            Assert.IsTrue(eventFired);
        }
Exemple #10
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);
        }
Exemple #11
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);
        }
 /// <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);
 }
Exemple #13
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);
        }
Exemple #14
0
        public void ShouldExecute_Init_Correctly()
        {
            eventFired = false;
            var routesRegistered = false;

            using (var fakeProvider = new ContextScopeProviderHelper())
            {
                var registration = new Mock <IWebModulesRegistration>();
                registration
                .Setup(r => r.RegisterKnownModuleRoutes(It.IsAny <RouteCollection>()))
                .Callback <RouteCollection>(rc => routesRegistered = true);
                fakeProvider.RegisterFakeServiceInstance(registration.Object, typeof(IWebModulesRegistration));

                var host = new UtilityHost();
                CreateApplication();

                WebCoreEvents.Instance.HostStart += Instance_Fired;
                host.Init(application);
                WebCoreEvents.Instance.HostStart -= Instance_Fired;
            }
            Assert.IsTrue(eventFired);
            Assert.IsTrue(routesRegistered);
        }
Exemple #15
0
        /// <summary>
        /// Validates that the parameter argument is not untrusted
        /// </summary>
        /// <param name="arguments">Object to validate</param>
        /// <param name="engineIntrinsics">
        /// The engine APIs for the context under which the validation is being
        /// evaluated.
        /// </param>
        /// <exception cref="ValidationMetadataException">
        /// if the argument is untrusted.
        /// </exception>
        protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics)
        {
            bool       everConstrained = false;
            bool       isFullLanguage  = false;
            MethodInfo marked          = null;

            try
            {
                object executionContextTLS = UtilityHost.GetExecutionContextFromTLS();
                everConstrained = (bool)UtilityHost.GetPrivateStaticProperty(executionContextTLS.GetType(), "HasEverUsedConstrainedLanguage");
                isFullLanguage  = (PSLanguageMode)UtilityHost.GetPrivateProperty("LanguageMode", executionContextTLS) == PSLanguageMode.FullLanguage;
                marked          = UtilityHost.GetPrivateStaticMethod(executionContextTLS.GetType(), "IsMarkedAsUntrusted");
            }
            catch { }

            if (everConstrained && isFullLanguage)
            {
                if ((bool)marked.Invoke(null, BindingFlags.NonPublic | BindingFlags.Static, null, new object[] { arguments }, System.Globalization.CultureInfo.CurrentCulture))
                {
                    throw new ValidationMetadataException(String.Format(Localization.LocalizationHost.Read("PSFramework.Assembly.Validation.UntrustedData"), arguments));
                }
            }
        }
Exemple #16
0
        private IWebApplicationHost CreateHost()
        {
            var host = new UtilityHost();

            return(host);
        }
Exemple #17
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);
        }
 /// <summary>
 /// Resets the current scriptblock's sessionstate to either the current runspace's current sessionstate or its global sessionstate.
 /// </summary>
 /// <param name="ScriptBlock">The scriptblock to import</param>
 /// <param name="Global">Whether to import into the global sessionstate</param>
 /// <returns>The imported ScriptBlock</returns>
 public static ScriptBlock Import(this ScriptBlock ScriptBlock, bool Global = false)
 {
     UtilityHost.ImportScriptBlock(ScriptBlock, Global);
     return(ScriptBlock);
 }
 /// <summary>
 /// Resets the current scriptblock's sessionstate to the current runspace's current sessionstate.
 /// </summary>
 /// <param name="ScriptBlock">The scriptblock to import</param>
 /// <returns>The imported scriptblock</returns>
 public static ScriptBlock ToLocal(this ScriptBlock ScriptBlock)
 {
     UtilityHost.ImportScriptBlock(ScriptBlock);
     return(ScriptBlock);
 }
 /// <summary>
 /// Resets the current scriptblock's sessionstate to the current runspace's global sessionstate.
 /// </summary>
 /// <param name="ScriptBlock">The scriptblock to globalize</param>
 /// <returns>The globalized scriptblock</returns>
 public static ScriptBlock ToGlobal(this ScriptBlock ScriptBlock)
 {
     UtilityHost.ImportScriptBlock(ScriptBlock, true);
     return(ScriptBlock);
 }
Exemple #21
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);
            }
        }
        /// <summary>
        /// Removes all value entries whose corresponding Runspace has been destroyed
        /// </summary>
        public void PurgeExpired()
        {
            // Store IDs first, so parallel access is not an issue and a new value gets accidentally discarded
            Guid[] IDs = Values.Keys.ToArray();
            ICollection <System.Management.Automation.Runspaces.Runspace> runspaces = UtilityHost.GetRunspaces();
            ICollection <Guid> runspaceIDs = (ICollection <Guid>)runspaces.Select(o => o.InstanceId);

            foreach (Guid ID in IDs)
            {
                if (!runspaceIDs.Contains(ID))
                {
                    Values.Remove(ID);
                }
            }
        }
Exemple #23
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);
        }
Exemple #24
0
        /// <summary>
        /// Returns the correct results, either by executing the scriptblock or consulting the cache
        /// </summary>
        /// <returns></returns>
        public string[] Invoke()
        {
            if (!ShouldExecute)
            {
                return(LastResult);
            }

            List <string> results = new List <string>();

            CallStackFrame callerFrame = null;
            InvocationInfo info        = null;

            try
            {
                object CurrentCommandProcessor = UtilityHost.GetPrivateProperty("CurrentCommandProcessor", UtilityHost.GetExecutionContextFromTLS());
                object CommandObject           = UtilityHost.GetPrivateProperty("Command", CurrentCommandProcessor);
                info = UtilityHost.GetPublicProperty("MyInvocation", CommandObject) as InvocationInfo;
            }
            catch (Exception e)
            {
                if (PSFCore.PSFCoreHost.DebugMode)
                {
                    PSFCore.PSFCoreHost.WriteDebug(String.Format("Script Container {0} | Error accessing Current Command Processor", Name), e);
                }
            }

            if (info == null)
            {
                IEnumerable <CallStackFrame> _callStack = Utility.UtilityHost.Callstack;

                object errorItem = null;
                try
                {
                    if (_callStack.Count() > 0)
                    {
                        callerFrame = _callStack.Where(frame => frame.InvocationInfo != null && frame.InvocationInfo.MyCommand != null).First();
                    }
                }
                catch (Exception e) { errorItem = e; }
                if (PSFCore.PSFCoreHost.DebugMode)
                {
                    PSFCore.PSFCoreHost.WriteDebug(String.Format("Script Container {0} | Callframe selected", Name), callerFrame);
                    PSFCore.PSFCoreHost.WriteDebug(String.Format("Script Container {0} | Script Callstack", Name), new Message.CallStack(Utility.UtilityHost.Callstack));
                    if (errorItem != null)
                    {
                        PSFCore.PSFCoreHost.WriteDebug(String.Format("Script Container {0} | Error when selecting Callframe", Name), errorItem);
                    }
                }
            }
            if (info == null && callerFrame != null)
            {
                info = callerFrame.InvocationInfo;
            }

            // ScriptBlock scriptBlock = ScriptBlock.Create(ScriptBlock.ToString());
            if (info != null)
            {
                foreach (PSObject item in ScriptBlock.Invoke(info.MyCommand.Name, "", "", null, info.BoundParameters))
                {
                    results.Add((string)item.Properties["CompletionText"].Value);
                }
            }
            else
            {
                foreach (PSObject item in ScriptBlock.Invoke("<ScriptBlock>", "", "", null, new Dictionary <string, object>(StringComparer.InvariantCultureIgnoreCase)))
                {
                    results.Add((string)item.Properties["CompletionText"].Value);
                }
            }

            return(results.ToArray());
        }
Exemple #25
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));
        }