Beispiel #1
0
        /// <summary>
        /// Provides an enhanced one-time, preprocessing functionality for the cmdlet.
        /// </summary>
        protected override void BeginProcessingEx()
        {
            if (ParameterSetName == ParameterSet.Default)
            {
                //Value is not required, but is required in that we need to explicitly say null
                if (!MyInvocation.BoundParameters.ContainsKey("Value"))
                {
                    throw new ParameterBindingException("Value parameter is mandatory, however a value was not specified. If Value should be empty, specify $null");
                }

                ParseValue();
            }
            else if (ParameterSetName == ParameterSet.Dynamic)
            {
                dynamicParameters = dynamicParams.GetBoundParameters(this, (p, v) => new PropertyParameter(p, PSObjectUtilities.CleanPSObject(v))).ToArray();
            }
            else if (ParameterSetName == ParameterSet.RawProperty)
            {
                RawValue = PSObjectUtilities.CleanPSObject(RawValue);
            }
            else if (ParameterSetName == ParameterSet.Raw)
            {
                parameters = RawParameters.Keys.Cast <object>()
                             .Select(k => new CustomParameter(k.ToString(), PSObjectUtilities.CleanPSObject(RawParameters[k]), ParameterType.MultiParameter))
                             .ToArray();
            }

            base.BeginProcessingEx();
        }
Beispiel #2
0
        /// <summary>
        /// Provides an enhanced one-time, preprocessing functionality for the cmdlet.
        /// </summary>
        protected override void BeginProcessingEx()
        {
            if (IsNormalParameterSet)
            {
                //Value is not required, but is required in that we need to explicitly say null
                if (!MyInvocation.BoundParameters.ContainsKey("Value"))
                {
                    throw new ParameterBindingException("Value parameter is mandatory, however a value was not specified. If Value should be empty, specify $null.");
                }

                ParseValue();
            }
            else if (IsDynamicParameterSet)
            {
                dynamicParameters = dynamicParams.GetBoundParameters(this, (p, v) => new PropertyParameter(p, PSObjectUtilities.CleanPSObject(v))).ToArray();

                if (dynamicParameters.Length == 0)
                {
                    throw new ParameterBindingException($"At least one dynamic property or -{nameof(Property)} and -{nameof(Value)} must be specified.");
                }
            }
            else if (IsRawPropertyParameterSet)
            {
                WarnSuspiciousPropertyName(RawProperty);
                RawValue = PSObjectUtilities.CleanPSObject(RawValue);
            }
            else if (IsRawParameterSet)
            {
                parameters = RawParameters.Keys.Cast <object>()
                             .Select(k => new CustomParameter(k.ToString(), PSObjectUtilities.CleanPSObject(RawParameters[k]), ParameterType.MultiParameter))
                             .ToArray();
            }

            base.BeginProcessingEx();
        }
Beispiel #3
0
        private NewSensorParameters CreateRawParameters()
        {
            if (!RawParameters.ContainsKey(NameParameter))
            {
                throw new InvalidOperationException($"Hashtable record '{NameParameter}' is mandatory, however a value was not specified");
            }

            if (!RawParameters.ContainsKey(SensorTypeParameter))
            {
                throw new InvalidOperationException($"Hashtable record '{SensorTypeParameter}' is mandatory, however a value was not specified'");
            }

            var parameters = new PSRawSensorParameters(RawParameters[NameParameter]?.ToString(), RawParameters[SensorTypeParameter]?.ToString());

            var toAdd = RawParameters.Keys.Cast <object>()
                        .Where(k => k.ToString() != SensorTypeParameter)
                        .Select(k => new CustomParameter(k.ToString(), PSObjectUtilities.CleanPSObject(RawParameters[k]), ParameterType.MultiParameter))
                        .ToList();

            foreach (var param in toAdd)
            {
                parameters[param.Name] = param.Value;
            }

            if (DynamicType)
            {
                parameters.DynamicType = true;
            }

            return(parameters);
        }
        public DynamicPropertyTypeParser(Enum property, PropertyCache cache, object value)
        {
            Property = property;
            Value    = PSObjectUtilities.CleanPSObject(value);
            Cache    = cache;

            //Get the PropertyType and ValueType values after unwrapping any nullable types

            PropertyType = Cache.Property.PropertyType;
            ValueType    = Value?.GetType();

            var propertyTypeUnderlying = Nullable.GetUnderlyingType(PropertyType);

            if (ValueType == null)
            {
                if (propertyTypeUnderlying != null)
                {
                    PropertyType = propertyTypeUnderlying;
                }
            }
            else
            {
                //If the property type is nullable, set it to its underlying type. Ideally, we would want to check
                //that both the property type and value type aren't both nullable, and then set whichever one
                //was nullable to its underlying type, however since ValueType will be boxed to its underlying
                //type T, it is never nullable and therefore we don't need to perform this check
                if (propertyTypeUnderlying != null)
                {
                    PropertyType = propertyTypeUnderlying;
                }
            }
        }
        /// <summary>
        /// Performs enhanced record-by-record processing functionality for the cmdlet.
        /// </summary>
        protected override void ProcessRecordEx()
        {
            Value = PSObjectUtilities.CleanPSObject(Value);

            switch (Trigger.Type)
            {
            case TriggerType.Change:
                SetProperty(new ChangeTriggerParameters(Trigger));
                break;

            case TriggerType.Speed:
                SetProperty(new SpeedTriggerParameters(Trigger));
                break;

            case TriggerType.State:
                SetProperty(new StateTriggerParameters(Trigger));
                break;

            case TriggerType.Threshold:
                SetProperty(new ThresholdTriggerParameters(Trigger));
                break;

            case TriggerType.Volume:
                SetProperty(new VolumeTriggerParameters(Trigger));
                break;

            default:
                throw new NotImplementedException($"Handler of trigger type '{Trigger.Type}' is not implemented.");
            }
        }
Beispiel #6
0
        public DynamicPropertyTypeParser(Enum property, PropertyCache cache, object value)
        {
            Property = property;
            Value    = PSObjectUtilities.CleanPSObject(value);
            Cache    = cache;

            GetParameterTypes();
        }
Beispiel #7
0
        /// <summary>
        /// Stores the value of a property in the underlying set, using its raw serialized name.
        /// </summary>
        /// <param name="name">The raw name of the parameter.</param>
        /// <param name="value">The value to store.</param>
        protected void SetCustomParameterInternal(string name, object value)
        {
            value = PSObjectUtilities.CleanPSObject(value);

            var parameter = new CustomParameter(name, value);

            ((ICustomParameterContainer)this).AddParameter(parameter);
        }
Beispiel #8
0
        private string FormatSingleParameterInternal(string name, object val, bool encodeValue, bool isEnum = false)
        {
            string str = string.Empty;

            val = PSObjectUtilities.CleanPSObject(val);

            if (val is string)
            {
                str = val.ToString();
            }
            else
            {
                if (val is IMultipleSerializable)
                {
                    var ps = ((IMultipleSerializable)val).GetSerializedFormats().Select(f =>
                                                                                        FormatSingleParameterInternal(name, f, encodeValue, isEnum)
                                                                                        ).ToList();

                    if (ps.Count > 0)
                    {
                        return(string.Join("&", ps));
                    }
                }
                else if (val is ISerializable)
                {
                    str = ((ISerializable)val).GetSerializedFormat();
                }
                else if (val is bool)
                {
                    str = (bool)val ? "1" : "0";
                }
                else
                {
                    str = Convert.ToString(val);
                }
            }

            if (isEnum && name != Parameter.Password.GetDescription())
            {
                str = str.ToLower();

                if (encodeValue)
                {
                    str = WebUtility.UrlEncode(str);
                }

                return($"{name.ToLower()}={str}");
            }

            if (encodeValue)
            {
                str = WebUtility.UrlEncode(str);
            }

            return($"{name.ToLower()}={str}");
        }
Beispiel #9
0
        /// <summary>
        /// Gets or sets the value associated with the specified parameter.
        /// </summary>
        /// <param name="name">The name of the parameter to get or set.</param>
        /// <returns>When getting, if the specified parameter exiasts, the value of that parameter.
        /// If the parameter does not exist, an <see cref="InvalidOperationException"/> will be thrown.</returns>
        public object this[string name]
        {
            get { return(GetIndex(name)); }
            set
            {
                value = PSObjectUtilities.CleanPSObject(value);

                SetIndex(name, value);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Provides a one-time, preprocessing functionality for the cmdlet.
        /// </summary>
        protected override void BeginProcessing()
        {
            First  = PSObjectUtilities.CleanPSObject(First);
            Second = PSObjectUtilities.CleanPSObject(Second);

            if (ParameterSetName == ParameterSet.Dynamic)
            {
                base.BeginProcessing();
            }
        }
Beispiel #11
0
        /// <summary>
        /// Provides an enhanced one-time, preprocessing functionality for the cmdlet.
        /// </summary>
        protected override void BeginProcessingEx()
        {
            Value = PSObjectUtilities.CleanPSObject(Value);

            if (DynamicSet())
            {
                dynamicParameters = dynamicParams.GetBoundParameters(this, (p, v) => new ChannelParameter(p, PSObjectUtilities.CleanPSObject(v)));
            }

            base.BeginProcessingEx();
        }
Beispiel #12
0
        private static SensorQueryTargetParameters GetQueryParameters(Hashtable queryParametersRaw)
        {
            if (queryParametersRaw == null)
            {
                return(null);
            }

            var queryParameters = new SensorQueryTargetParameters();

            foreach (var key in queryParametersRaw.Keys.Cast <object>())
            {
                queryParameters[key.ToString()] = PSObjectUtilities.CleanPSObject(queryParametersRaw[key]);
            }

            return(queryParameters);
        }
Beispiel #13
0
        /// <summary>
        /// Parse a value into its expected type. Requires the target <paramref name="property"/> contain a Parse method.
        /// </summary>
        /// <param name="property">The property the value applies to.</param>
        /// <param name="value">The value to apply to the property.</param>
        /// <returns>If the target property type contains a Parse method which did not throw upon being called, the parsed value. Otherwise, the original value.</returns>
        protected object ParseValueIfRequired(PropertyInfo property, object value)
        {
            value = PSObjectUtilities.CleanPSObject(value);

            //Types that can have possible enum values (such as TriggerChannel) possess a static Parse method for type conversion by the PowerShell runtime.
            //Only parse types that are defined in the PrtgAPI assembly.
            if (IsPrtgAPIProperty(property) && !property.PropertyType.IsEnum)
            {
                var method = property.PropertyType.GetMethod("Parse", BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static);

                if (method != null)
                {
                    try
                    {
                        var newValue = method.Invoke(null, new[] { value });
                        value = newValue;
                    }
                    catch (Exception)
                    {
                        //Don't care if our value wasn't parsable
                    }
                }
            }
            else
            {
                //Try and parse the value if the property type is an Enum or Nullable Enum
                var type = property.PropertyType;

                if (!type.IsEnum)
                {
                    type = Nullable.GetUnderlyingType(property.PropertyType);
                }

                if (type?.IsEnum == true)
                {
                    if (Enum.GetNames(type).Any(e => e.ToLower() == value?.ToString().ToLower()))
                    {
                        return(Enum.Parse(type, value.ToString(), true));
                    }
                }
            }

            return(value);
        }
Beispiel #14
0
        /// <summary>
        /// Provides an enhanced one-time, preprocessing functionality for the cmdlet.
        /// </summary>
        protected override void BeginProcessingEx()
        {
            if (this is IDynamicParameters && dynamicParameterSet != null)
            {
                dynamicParameters = dynamicParameterSet.GetBoundParameters(this, (p, v) =>
                {
                    var cleaned = PSObjectUtilities.CleanPSObject(v);

                    if (cleaned == null)
                    {
                        return(new List <SearchFilter>());
                    }

                    var underlying = cleaned.GetType().GetElementType() ?? cleaned.GetType();

                    if (underlying == typeof(object))
                    {
                        if (cleaned.IsIEnumerable())
                        {
                            var first = cleaned.ToIEnumerable().FirstOrDefault();

                            if (first != null)
                            {
                                underlying = first.GetType();
                            }
                        }
                    }

                    if (underlying == typeof(string))
                    {
                        return(GetWildcardFilters(p, cleaned, val => val.ToString()));
                    }
                    if (typeof(IStringEnum).IsAssignableFrom(underlying))
                    {
                        return(GetWildcardFilters(p, cleaned, val => ((IStringEnum)val).StringValue));
                    }

                    return(new[] { GetPipelineFilter(p, cleaned) });
                });
            }

            base.BeginProcessingEx();
        }
Beispiel #15
0
        /// <summary>
        /// Formats a <see cref="ParameterType.MultiParameter"/>. Result is in the form name=val1&amp;name=val2&amp;name=val3
        /// </summary>
        /// <param name="enumerable">The values to assign to the parameter</param>
        /// <param name="description">The serialized name of the parameter</param>
        /// <returns></returns>
        private string FormatMultiParameter(IEnumerable enumerable, string description)
        {
            var builder = new StringBuilder();

            foreach (var e in enumerable)
            {
                if (e != null)
                {
                    var val = PSObjectUtilities.CleanPSObject(e);

                    string query;

                    if (description == Parameter.FilterXyz.GetDescription())
                    {
                        var filter = (SearchFilter)val;

                        query = FormatMultiParameterFilter(filter, filter.Value);
                    }
                    else if (val != null && val.GetType().IsEnum) //If it's an enum other than FilterXyz
                    {
                        var result = FormatFlagEnum((Enum)val, v => SearchFilter.ToString(description, FilterOperator.Equals, v, null, FilterMode.Normal));

                        query = result ?? SearchFilter.ToString(description, FilterOperator.Equals, val, null, FilterMode.Normal);
                    }
                    else
                    {
                        query = FormatSingleParameterWithValEncode(description, val);
                    }

                    if (!string.IsNullOrWhiteSpace(query))
                    {
                        builder.Append(query + "&");
                    }
                }
            }

            if (builder.Length > 0)
            {
                builder.Length--;
            }

            return(builder.ToString());
        }
Beispiel #16
0
        internal void BeginProcessing()
        {
            Value = PSObjectUtilities.CleanPSObject(Value);

            if (DynamicSet())
            {
                dynamicParameters = new Lazy <List <TParameter> >(() =>
                {
                    var ret = dynamicParams.GetBoundParameters(cmdlet,
                                                               (p, v) => createParameter(p, PSObjectUtilities.CleanPSObject(v)));

                    if (ret.Count == 0)
                    {
                        throw new ParameterBindingException($"At least one dynamic property or -{nameof(Property)} and -{nameof(Value)} must be specified.");
                    }

                    return(ret);
                });
            }
        }
Beispiel #17
0
        /// <summary>
        /// Retrieves the value of a <see cref="ParameterType.MultiValue"/> parameter. Result is in the form val1,val2,val3
        /// </summary>
        /// <param name="enumerable">The values to assign to the parameter</param>
        /// <returns></returns>
        private string GetMultiValueStr(IEnumerable enumerable)
        {
            var builder = new StringBuilder();

            foreach (var o in enumerable)
            {
                if (o != null)
                {
                    var obj = PSObjectUtilities.CleanPSObject(o);

                    string toEncode;

                    if (obj != null && obj.GetType().IsEnum)
                    {
                        toEncode = ((Enum)obj).GetDescription();
                    }
                    else
                    {
                        if (obj is ISerializable)
                        {
                            toEncode = ((ISerializable)obj).GetSerializedFormat();
                        }
                        else
                        {
                            toEncode = Convert.ToString(obj);
                        }
                    }

                    builder.Append(WebUtility.UrlEncode(toEncode) + ",");
                }
            }

            if (builder.Length > 0)
            {
                builder.Length--;
            }

            return(builder.ToString().ToLower());
        }
Beispiel #18
0
        /// <summary>
        /// Performs record-by-record processing functionality for the cmdlet.
        /// </summary>
        protected override void ProcessRecord()
        {
            if (Value is PSObject)
            {
                Value = PSObjectUtilities.CleanPSObject(Value);
            }

            FilterMode filterMode = FilterMode.Normal;

            if (Raw)
            {
                filterMode = FilterMode.Raw;
            }
            else
            {
                if (Illegal)
                {
                    filterMode = FilterMode.Illegal;
                }
            }

            WriteObject(new SearchFilter(Property, Operator, Value, filterMode));
        }
Beispiel #19
0
        /// <summary>
        /// Creates nodes for all specified values and <see cref="ScriptBlock"/> results and emits them to the pipeline.
        /// </summary>
        /// <param name="values">The values to process.</param>
        protected void ProcessValues(params TValue[] values)
        {
            List <PrtgNode> children = null;

            if (ScriptBlock != null)
            {
                var result = PSObjectUtilities.CleanPSObject(ScriptBlock.Invoke())?.ToIEnumerable().ToArray();

                if (result != null)
                {
                    var invalid = result.Where(v => !(v is PrtgNode)).ToArray();

                    if (invalid.Length > 0)
                    {
                        throw new InvalidOperationException($"Expected -{nameof(ScriptBlock)} to return one or more values of type '{nameof(PrtgNode)}', however response contained an invalid value of type '{invalid[0].GetType().FullName}'.");
                    }

                    children = result.Cast <PrtgNode>().ToList();
                }
            }

            ProcessValues(values, children);
        }
Beispiel #20
0
        /// <summary>
        /// Provides an enhanced one-time, preprocessing functionality for the cmdlet.
        /// </summary>
        protected override void BeginProcessingEx()
        {
            dynamicParameters = dynamicParams.GetBoundParameters(this, (p, v) => new TriggerParameter(p, PSObjectUtilities.CleanPSObject(v))).ToArray();

            base.BeginProcessingEx();
        }