Ejemplo n.º 1
0
        public object GetElementAt(int index)
        {
            if (InputObject == null)
            {
                SetExceptionAndThrow(new Exception("no input data"));
            }

            Type objectType = InputObject.GetType();

            if (TypeHelper.IsEnumerable(objectType))
            {
                IEnumerable enumerable = (IEnumerable)InputObject;
                IEnumerator enumerator = enumerable.GetEnumerator();
                int         c          = 0;
                while (enumerator.MoveNext())
                {
                    if (c >= index)
                    {
                        return(enumerator.Current);
                    }
                    c++;
                }
                SetExceptionAndThrow(new Exception("index out of range"));
            }
            SetExceptionAndThrow(new Exception("data is not a set of elements"));
            return(null);
        }
Ejemplo n.º 2
0
 protected override void ProcessRecord()
 {
     if (this.MyInvocation.BoundParameters.ContainsKey("InputObject"))
     {
         if (InputObject is Type inputType)
         {
             list.Add(inputType);
         }
         else if (InputObject is PSObject psObj)
         {
             if (this.MyInvocation.BoundParameters.ContainsKey("Enumerate") && psObj.ImmediateBaseObject is IEnumerable ienum)
             {
                 list.AddRange(base.GetTypesFromArray(ienum));
             }
             else if (psObj.ImmediateBaseObject is Type type)
             {
                 list.Add(type);
             }
             else
             {
                 list.Add(psObj.ImmediateBaseObject.GetType());
             }
         }
         else
         {
             list.Add(InputObject.GetType());
         }
     }
     else
     {
         list.AddRange(base.ResolveTypeThroughPowerShell(TypeName));
     }
 }
Ejemplo n.º 3
0
        protected override void ProcessRecord()
        {
            if (this.MyInvocation.BoundParameters.ContainsKey("InputObject"))
            {
                BaseType = InputObject is Type type
                    ? type.FullName
                    : InputObject.GetType().FullName;
            }

            IEnumerable <Type> derivedTypes = DerivedType.GetDerivedTypes(BaseType, asses, Recurse.ToBool());

            WriteObject(derivedTypes, true);
        }
Ejemplo n.º 4
0
        public override void ExecuteCmdlet()
        {
            PSSecuritySetting setting;

            switch (ParameterSetName)
            {
            case ParameterSetNames.DataExportSettingsScope:
                break;

            case ParameterSetNames.InputObject:
                if (InputObject.GetType().Name == nameof(PSSecurityDataExportSetting))
                {
                    SettingKind = "DataExportSettings";
                    Enabled     = !this.IsParameterBound(c => c.Enabled) ? ((PSSecurityDataExportSetting)InputObject).Enabled : Enabled;
                }
                SettingName = InputObject.Name;
                break;

            default:
                throw new PSInvalidOperationException();
            }

            if (SettingKind == "DataExportSettings")
            {
                setting = new PSSecurityDataExportSetting()
                {
                    Enabled = Enabled,
                    Name    = SettingName
                };
            }
            else
            {
                throw new PSInvalidOperationException("Invalid setting kind");
            }


            if (ShouldProcess(SettingName, VerbsCommon.Set))
            {
                var updatedSetting = SecurityCenterClient.Settings.UpdateWithHttpMessagesAsync(SettingName, setting.ConvertToCSType()).GetAwaiter().GetResult().Body;

                WriteObject(updatedSetting.ConvertToPSType(), enumerateCollection: false);
            }
        }
Ejemplo n.º 5
0
        protected override void ProcessRecord()
        {
            StringBuilder line = new StringBuilder();

            if ((!NoTypeInformation.ToBool()) && (!typeWritten))
            {
                file.WriteLine("#TYPE " + InputObject.GetType().ToString());
                typeWritten = true;
            }

            foreach (PSPropertyInfo _prop in InputObject.Properties)
            {
                line.Append(_prop.Value.ToString());
                line.Append(',');
            }

            // Remove the trailing comma
            line.Remove((line.Length - 1), 1);

            file.WriteLine(line.ToString());
        }
Ejemplo n.º 6
0
        public int GetSetCount()
        {
            if (InputObject == null)
            {
                SetExceptionAndThrow(new Exception("no input data"));
            }
            Type objectType = InputObject.GetType();

            if (TypeHelper.IsEnumerable(objectType))
            {
                IEnumerable enumerable = (IEnumerable)InputObject;
                IEnumerator enumerator = enumerable.GetEnumerator();
                int         c          = 0;
                while (enumerator.MoveNext())
                {
                    c++;
                }
                return(c);
            }
            SetExceptionAndThrow(new Exception("data is not a set of elements"));
            return(0);
        }
Ejemplo n.º 7
0
        public MeasureResult MeasureList(string property)
        {
            if (InputObject == null)
            {
                SetExceptionAndThrow(new Exception("no input data"));
            }

            Type objectType  = InputObject.GetType();
            Type elementType = TypeHelper.GetEnumerableElementType(objectType);

            if (elementType == null)
            {
                SetExceptionAndThrow(new Exception("input data should be generic list"));
            }
            object      sum = null;
            object      min = null;
            object      max = null;
            object      current;
            bool        inited     = false;
            int         count      = 1;
            IEnumerable enumerable = (IEnumerable)InputObject;
            IEnumerator enumerator = enumerable.GetEnumerator();

            if (property == null)
            {
                dynamic value = null;
                while (enumerator.MoveNext())
                {
                    current = enumerator.Current;
                    value   = ObjectHelper.TryGetValue(current);
                    if (value != null)
                    {
                        inited = true;
                        break;
                    }
                }
                if (!inited)
                {
                    SetExceptionAndThrow(new Exception($"no valid element inside list"));
                }
                if (value is string str)
                {
                    value = TryConvertFromString(str);
                }
                sum = value;
                min = value;
                max = value;
                while (enumerator.MoveNext())
                {
                    current = enumerator.Current;
                    value   = ObjectHelper.TryGetValue(current);
                    if (value == null)
                    {
                        continue;
                    }
                    if (value is string istr)
                    {
                        value = TryConvertFromString(istr);
                    }
                    sum = (dynamic)sum + value;
                    if ((dynamic)min > value)
                    {
                        min = value;
                    }
                    if ((dynamic)max < value)
                    {
                        max = value;
                    }
                    count++;
                }
            }
            else
            {
                dynamic value = null;
                while (enumerator.MoveNext())
                {
                    current = enumerator.Current;
                    current = ObjectHelper.TryGetValue(current);
                    value   = ObjectHelper.GetPropertyByName(current, property, true);
                    if (value != null)
                    {
                        inited = true;
                        break;
                    }
                }
                if (!inited)
                {
                    SetExceptionAndThrow(new Exception($"property {property} does not exist"));
                }
                if (value is string str)
                {
                    value = TryConvertFromString(str);
                }
                sum = value;
                min = value;
                max = value;
                while (enumerator.MoveNext())
                {
                    current = enumerator.Current;
                    current = ObjectHelper.TryGetValue(current);
                    value   = ObjectHelper.GetPropertyByName(current, property, true);
                    if (value == null)
                    {
                        continue;
                    }
                    if (value is string istr)
                    {
                        value = TryConvertFromString(istr);
                    }
                    sum = (dynamic)sum + value;
                    if ((dynamic)min > value)
                    {
                        min = value;
                    }
                    if ((dynamic)max < value)
                    {
                        max = value;
                    }
                    count++;
                }
            }

            return(new MeasureResult(sum, max, min, count));
        }
Ejemplo n.º 8
0
 protected override void ProcessRecord()
 {
     if (!this.MyInvocation.BoundParameters.ContainsKey("Properties") && !this.MyInvocation.BoundParameters.ContainsKey("Methods"))
     {
         if (this.ParameterSetName.Contains("Pipeline"))
         {
             if (InputObject is ScriptBlock sb)
             {
                 Collection <PSObject> sbResult = sb.Invoke();
                 for (int i1 = 0; i1 < sbResult.Count; i1++)
                 {
                     PSObject one = sbResult[i1];
                     if (one.ImmediateBaseObject is Type t)
                     {
                         ResolvedTypes.Add(t);
                     }
                     else if (one.ImmediateBaseObject is IEnumerable <Type> types)
                     {
                         ResolvedTypes.AddRange(types);
                     }
                     else if (one.ImmediateBaseObject is string str)
                     {
                         ResolvedTypes.AddRange(base.ResolveTypeThroughPowerShell(str));
                     }
                     else if (one.ImmediateBaseObject is IEnumerable <string> strs)
                     {
                         ResolvedTypes.AddRange(base.ResolveTypeThroughPowerShell(strs.ToArray()));
                     }
                 }
             }
             else if (InputObject is PSObject psObj)
             {
                 if (psObj.ImmediateBaseObject.GetType().IsArray)
                 {
                     foreach (object obj in (IEnumerable)psObj.ImmediateBaseObject)
                     {
                         ResolvedTypes.Add(obj.GetType());
                     }
                 }
                 else
                 {
                     ResolvedTypes.Add(psObj.ImmediateBaseObject.GetType());
                 }
             }
             else if (InputObject is object[])
             {
                 ResolvedTypes.Add(typeof(object[]));
             }
             else
             {
                 ResolvedTypes.Add(InputObject.GetType());
             }
         }
         else if (this.MyInvocation.BoundParameters.ContainsKey("TypeName"))
         {
             ResolvedTypes.AddRange(base.ResolveTypeThroughPowerShell(TypeName));
         }
     }
     else if (this.MyInvocation.BoundParameters.ContainsKey("Properties"))
     {
         WriteObject(this.GetMemberCommand(InputObject, "Properties", Force.ToBool()), true);
     }
     else if (this.MyInvocation.BoundParameters.ContainsKey("Methods"))
     {
         WriteObject(this.GetMemberCommand(InputObject, "Methods", Force.ToBool()), true);
     }
 }
Ejemplo n.º 9
0
        public override void ExecuteCmdlet()
        {
            PSSecuritySetting setting;

            switch (ParameterSetName)
            {
            case ParameterSetNames.SettingsScope:
                break;

            case ParameterSetNames.InputObject:
                if (InputObject.GetType().Name == nameof(PSSecurityDataExportSetting))
                {
                    SettingKind = DataExportSettingsSettingKind;
                    Enabled     = !this.IsParameterBound(c => c.Enabled) ? ((PSSecurityDataExportSetting)InputObject).Enabled : Enabled;
                }
                if (InputObject.GetType().Name == nameof(PSSecurityAlertSyncSettings))
                {
                    SettingKind = AlertSyncSettingsSettingKind;
                    Enabled     = !this.IsParameterBound(c => c.Enabled) ? ((PSSecurityAlertSyncSettings)InputObject).Enabled : Enabled;
                }
                SettingName = InputObject.Name;
                break;

            default:
                throw new PSInvalidOperationException();
            }

            if ((SettingName == SentinelSettingName && SettingKind != AlertSyncSettingsSettingKind) ||
                ((SettingName == McasSettingName || SettingName == WdatpSettingName) && SettingKind != DataExportSettingsSettingKind))
            {
                throw new PSInvalidOperationException("Setting kind doesn't match the setting name");
            }

            switch (SettingKind)
            {
            case DataExportSettingsSettingKind:
            {
                setting = new PSSecurityDataExportSetting()
                {
                    Enabled = Enabled,
                    Name    = SettingName
                };
                break;
            };

            case AlertSyncSettingsSettingKind:
            {
                setting = new PSSecurityAlertSyncSettings()
                {
                    Enabled = Enabled,
                    Name    = SettingName
                };
                break;
            };

            default:
                throw new PSInvalidOperationException("Invalid setting kind");
            }

            if (ShouldProcess(SettingName, VerbsCommon.Set))
            {
                var updatedSetting = SecurityCenterClient.Settings.UpdateWithHttpMessagesAsync(SettingName, setting.ConvertToCSType()).GetAwaiter().GetResult().Body;

                WriteObject(updatedSetting.ConvertToPSType(), enumerateCollection: false);
            }
        }
Ejemplo n.º 10
0
        private void CreateTable()
        {
            string stmt;

            // Try to select from a table given by TableName in order to find whether such a table exists.

            bool tableExists = false;

            try
            {
                stmt = "select * from " + _qualifiedTableName;
                WriteVerbose(stmt);

                using (var cmd = _connection.CreateCommand())
                    using (var adaptor = _factory.CreateDataAdapter())
                    {
                        cmd.CommandText       = stmt;
                        adaptor.SelectCommand = cmd;

                        using (var dataSet = new DataSet())
                        {
                            adaptor.FillSchema(dataSet, SchemaType.Mapped);

                            var table = dataSet.Tables[0];

                            _fieldSet = new HashSet <string>();
                            foreach (DataColumn c in table.Columns)
                            {
                                _fieldSet.Add(c.ColumnName);
                            }
                        }

                        tableExists = true;
                    }
            }
            catch (DbException)
            {
                // Ignore an exception
            }

            if (tableExists)
            {
                return;
            }

            // Collect field names from the input object

            var fields = new List <string>();

            if (InputObject is PSObject)
            {
                var obj = (PSObject)InputObject;
                foreach (var p in obj.Properties)
                {
                    fields.Add(p.Name);
                }
            }
            else
            {
                foreach (var p in InputObject.GetType().GetProperties())
                {
                    if (!p.CanRead)
                    {
                        continue;
                    }
                    fields.Add(p.Name);
                }
            }

            if (AdditionalColumns != null)
            {
                foreach (var c in AdditionalColumns)
                {
                    fields.Add(c);
                }
            }

            _fieldSet = new HashSet <string>(fields);

            // Create a table

            string stringType = "varchar(4000)"; // ANSI SQL standard

            if (TypeName != null)
            {
                // User-specified type name
                stringType = TypeName;
            }
            else if (_connection is System.Data.SQLite.SQLiteConnection)
            {
                // SQLite can omit a type
                stringType = "";
            }
            else if (_connection is System.Data.SqlClient.SqlConnection)
            {
                // SQL Server supports nvarchar that represents a UTF-16 string.
                // It is safe for any database encoding.
                stringType = "nvarchar(4000)";
            }
            else if (_connection.GetType().FullName.Contains("Oracle"))
            {
                // Conventional type name of string for Oracle
                stringType = "nvarchar2(4000)";
            }
            else
            {
                long length = 4000;
                try
                {
                    using (var schema = _connection.GetSchema("DataTypes"))
                    {
                        foreach (DataRow row in schema.Rows)
                        {
                            var columnName = (string)row["TypeName"];
                            if (columnName == "varchar" || columnName == "VARCHAR" || columnName == "Varchar")
                            {
                                long l = (long)row["ColumnSize"];
                                length = Math.Min(4000, l);
                                break;
                            }
                        }
                    }
                    stringType = String.Format("varchar({0})", length);
                }
                catch (Exception)
                {
                    // Because schema information varies from provider to provider,
                    // when an error occurs, just ignore it and apply standard type definition.
                }
            }

            var templ = new StringBuilder();

            templ.Append("create table ");
            templ.Append(_qualifiedTableName);
            templ.Append(" (\r\n");
            bool first = true;

            foreach (var f in fields)
            {
                if (!first)
                {
                    templ.AppendLine(",");
                }

                first = false;
                templ.Append("    ");
                templ.Append(_builder.QuoteIdentifier(f));
                templ.Append(" {0}");
            }
            templ.AppendLine("\r\n)");

            stmt = String.Format(templ.ToString(), stringType);
            WriteVerbose(stmt);

            using (var cmd = _connection.CreateCommand())
            {
                cmd.CommandText = stmt;
                cmd.ExecuteNonQuery();
            }
        }
Ejemplo n.º 11
0
        protected override void ProcessRecord()
        {
            try
            {
                if (InputObject == null)
                {
                    return;
                }

                if (_fieldSet == null)
                {
                    _qualifiedTableName = GetQualifiedTableName();

                    CreateTable();

                    _useNamedParameters = TestNamedParameterSupport();

                    _insertStmt = "insert into " + _qualifiedTableName + " (";

                    _transaction = _connection.BeginTransaction();
                }

                using (var cmd = _connection.CreateCommand())
                {
                    cmd.CommandText = _insertStmt;
                    cmd.Transaction = _transaction;

                    var buffer       = new StringBuilder(_insertStmt);
                    var placeholders = new StringBuilder();

                    string pa    = "?";
                    var    count = 0;
                    if (InputObject is PSObject)
                    {
                        var obj = (PSObject)InputObject;
                        foreach (var p in obj.Properties)
                        {
                            if (!p.IsGettable || !p.IsInstance)
                            {
                                continue;
                            }

                            if (_fieldSet.Contains(p.Name))
                            {
                                if (count > 0)
                                {
                                    buffer.Append(',');
                                    placeholders.Append(',');
                                }
                                ++count;

                                var qualified = _builder.QuoteIdentifier(p.Name);
                                buffer.Append(qualified);

                                var param = cmd.CreateParameter();
                                if (_useNamedParameters)
                                {
                                    pa = "@" + count.ToString();
                                    param.ParameterName = pa;
                                }

                                var value = p.Value;
                                if (value != null)
                                {
                                    if (value is PSObject)
                                    {
                                        value = (value as PSObject).BaseObject;
                                    }
                                    param.Value = value;
                                }

                                cmd.Parameters.Add(param);

                                placeholders.Append(pa);
                            }
                        }
                    }
                    else
                    {
                        foreach (var p in InputObject.GetType().GetProperties())
                        {
                            if (!p.CanRead)
                            {
                                continue;
                            }

                            if (_fieldSet.Contains(p.Name))
                            {
                                if (count > 0)
                                {
                                    buffer.Append(',');
                                    placeholders.Append(',');
                                }
                                ++count;

                                var qualified = _builder.QuoteIdentifier(p.Name);
                                buffer.Append(qualified);

                                var param = cmd.CreateParameter();
                                if (_useNamedParameters)
                                {
                                    pa = "@" + count.ToString();
                                    param.ParameterName = pa;
                                }

                                var value = p.GetValue(InputObject);
                                if (value != null)
                                {
                                    if (value is PSObject)
                                    {
                                        value = (value as PSObject).BaseObject;
                                    }
                                    param.Value = value;
                                }

                                cmd.Parameters.Add(param);

                                placeholders.Append(pa);
                            }
                        }
                    }

                    // If there are no columns to be inserted, just skip.
                    if (placeholders.Length == 0)
                    {
                        return;
                    }

                    buffer.Append(") values (");
                    buffer.Append(placeholders);
                    buffer.Append(')');
                    var stmt = buffer.ToString();
                    WriteVerbose(stmt);

                    cmd.CommandText = stmt;

                    var rowsAffected = cmd.ExecuteNonQuery();
                    if (rowsAffected != 1)
                    {
                        throw new RuntimeException("Insertion failed");
                    }
                }
            }
            catch (Exception e)
            {
                if (_transaction != null)
                {
                    _transaction.Rollback();
                }

                DisposeResources();

                WriteError(new ErrorRecord(e, "", ErrorCategory.NotSpecified, null));
                throw new PipelineStoppedException();
            }
        }