Exemplo n.º 1
0
        public void EnsureBackwardsCompatibility()
        {
            if (this.RenameDnFlow != null)
            {
                Tracer.TraceWarning("'RenameDnFlow' is no longer supported. Use 'ConditionalRename' instead' or remove 'RenameDnFlow' element from rule definition (see documentation).");
            }
            switch (this.Action)
            {
            case RuleAction.provision:
                this.Action = RuleAction.Provision;
                Tracer.TraceWarning("Lowercase 'provision' action keyword is deprecated. Use 'Provision' instead' (see documentation).");
                break;

            case RuleAction.deprovision:
                this.Action = RuleAction.Deprovision;
                Tracer.TraceWarning("Lowercase 'deprovision' action keyword is deprecated. Use 'Deprovision' instead' (see documentation).");
                break;

            case RuleAction.rename:
                this.Action = RuleAction.Rename;
                Tracer.TraceWarning("Lowercase 'rename' action keyword is deprecated. Use 'Rename' instead' (see documentation).");
                break;

            case RuleAction.deprovisionall:
                this.Action = RuleAction.DeprovisionAll;
                Tracer.TraceWarning("Lowercase 'deprovisionall' action keyword is deprecated. Use 'DeprovisionAll' instead' (see documentation).");
                break;

            default:
                break;
            }
        }
Exemplo n.º 2
0
        object GetSafeValue(DataRow dataRow, string attributeName, AttributeType attributeType, bool DeltaDate = false)
        {
            object value = null;

            try
            {
                if (dataRow.IsNull(attributeName))
                {
                    return(null);
                }
                switch (attributeType)
                {
                case AttributeType.Binary:
                    value = dataRow.Field <object>(attributeName);
                    if (value.GetType().Equals(typeof(System.Guid)))
                    {
                        value = ((Guid)value).ToByteArray();
                    }
                    return(value);

                case AttributeType.Reference:     // reference is always string in FIM
                    value = dataRow.Field <object>(attributeName);
                    return(value.ToString());

                case AttributeType.String:
                    if (DeltaDate)
                    {
                        value = dataRow.Field <object>(attributeName);
                        return(value);
                    }
                    else
                    {
                        value = dataRow.Field <object>(attributeName);
                        if (IsDateTimeType(value.GetType()))
                        {
                            DateTime dt;
                            if (DateTime.TryParse(value.ToString(), out dt))
                            {
                                value = dt.ToString(Configuration.DateFormat);
                                return(value);
                            }
                            else
                            {
                                Tracer.TraceWarning("unable-to-parse-value-to-date: value: {0}", value);
                            }
                        }
                        return(value.ToString());
                    }

                default:
                    value = dataRow.Field <object>(attributeName);
                    return(value);
                }
            }
            catch (Exception e)
            {
                Tracer.TraceError($"{nameof(GetSafeValue)}, attribute: {attributeName}, target-type: {attributeType}, value: {value}, error: {e.Message}");
                throw;
            }
        }
Exemplo n.º 3
0
        public override bool Met(MVEntry mventry, CSEntry csentry)
        {
            if (!mventry[this.MVAttributeStartDate].IsPresent)
            {
                Tracer.TraceInformation("Condition failed (Reason: MVAttributeStartDate {0} attribute value is not present) / {0}", this.MVAttributeStartDate, this.Description);
                return(false);
            }
            if (!mventry[this.MVAttributeEndDate].IsPresent)
            {
                Tracer.TraceInformation("Condition failed (Reason: MVAttributeEndDate {0} attribute value is not present) / {0}", this.MVAttributeEndDate, this.Description);
                return(false);
            }

            DateTime startDate;
            DateTime endDate;

            if (!DateTime.TryParse(mventry[this.MVAttributeStartDate].StringValue, out startDate))
            {
                Tracer.TraceWarning("unable-to-parse-start-mvvalue-to-datetime {0}", mventry[this.MVAttributeStartDate].StringValue);
                return(false);
            }
            if (!DateTime.TryParse(mventry[this.MVAttributeEndDate].StringValue, out endDate))
            {
                Tracer.TraceWarning("unable-to-parse-end-mvvalue-to-datetime {0}", mventry[this.MVAttributeEndDate].StringValue);
                return(false);
            }

            DateTime now         = DateTime.Now;
            bool     returnValue = (startDate < now) && (now < endDate);

            Tracer.TraceInformation("compare-dates now: {0}, start: {1}, end: {2}, is-between: {3}", now, startDate, endDate, returnValue);
            return(returnValue);
        }
Exemplo n.º 4
0
        public PowerShellManagementAgent()
        {
            Tracer.IndentLevel = 0;
            Tracer.Enter("initialize");
            Tracer.Indent();
            try
            {
                Tracer.TraceInformation("memory-usage {0:n} Mb", GC.GetTotalMemory(true) / 102400);
                System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                FileVersionInfo            fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);
                string version = fvi.FileVersion;
                Tracer.TraceInformation("psma-version {0}", version);
                Tracer.TraceInformation("reading-registry-settings");
                RegistryKey machineRegistry = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
                RegistryKey mreRootKey      = machineRegistry.OpenSubKey(@"SOFTWARE\Granfeldt\FIM\ManagementAgents\PowerShell", false);

                if (mreRootKey != null)
                {
                    Tracer.TraceInformation("adding-eventlog-listener-for name: {0}, source: {1}", EventLogName, EventLogSource);
                    EventLog evl = new EventLog(EventLogName);
                    evl.Log    = EventLogName;
                    evl.Source = EventLogSource;

                    EventLogTraceListener eventLog = new EventLogTraceListener(EventLogSource);
                    eventLog.EventLog = evl;
                    EventTypeFilter filter = new EventTypeFilter(SourceLevels.Warning | SourceLevels.Error | SourceLevels.Critical);
                    eventLog.TraceOutputOptions = TraceOptions.Callstack;
                    eventLog.Filter             = filter;
                    Tracer.Trace.Listeners.Add(eventLog);
                    if (!EventLog.SourceExists(EventLogSource))
                    {
                        Tracer.TraceInformation("creating-eventlog-source '{0}'", EventLogSource);
                        EventLog.CreateEventSource(EventLogSource, EventLogName);
                    }

                    string logFileValue = mreRootKey.GetValue("DebugLogFileName", null) as string;
                    if (logFileValue != null)
                    {
                        Tracer.TraceWarning("Logging to file is no longer supported. Please remove registrykey DebugLogFileName and use DebugView or similar instead to catch traces from this Management Agent");
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.TraceError("could-not-initialize", ex);
                throw;
            }
            finally
            {
                Tracer.Unindent();
                Tracer.Exit("initialize");
            }
        }
 public override bool Met(MVEntry mventry, CSEntry csentry)
 {
     Tracer.TraceWarning("Condition type 'ConditionAttributeIsNotPresent' is obsolete. Please see documentation.");
     if (!mventry[this.MVAttribute].IsPresent)
     {
         return(true);
     }
     else
     {
         Tracer.TraceInformation("Condition failed (Reason: Metaverse attribute value is present) {0}", this.Description);
         return(false);
     }
 }
Exemplo n.º 6
0
 void InvokeExternalMethod(string ExternalReferenceId, ExternalType Type, MVEntry mventry, CSEntry csentry)
 {
     if (!string.IsNullOrEmpty(ExternalReferenceId) && Externals.ContainsKey(ExternalReferenceId))
     {
         External external = Externals[ExternalReferenceId];
         if (external != null)
         {
             if (Type == ExternalType.Provision)
             {
                 external.Provision(mventry);
             }
             else if (Type == ExternalType.ShouldDeleteFromMV)
             {
                 external.ShouldDeleteFromMV(csentry, mventry);
             }
         }
         else
         {
             Tracer.TraceWarning("no-external-reference-found-for-referenceid {0}", ExternalReferenceId);
         }
     }
 }
Exemplo n.º 7
0
 public override bool Met(MVEntry mventry, CSEntry csentry)
 {
     if (mventry[this.MVAttribute].IsPresent)
     {
         DateTime value;
         if (DateTime.TryParse(mventry[this.MVAttribute].StringValue, out value))
         {
             DateTime now         = DateTime.Now;
             bool     returnValue = now > value;
             Tracer.TraceInformation("compare-dates now: {0}, mvvalue: {1}, is-after: {2}", now, value, returnValue);
             return(returnValue);
         }
         else
         {
             Tracer.TraceWarning("unable-to-parse-mvvalue-to-datetime {0}", mventry[this.MVAttribute].StringValue);
             return(false);
         }
     }
     else
     {
         Tracer.TraceInformation("Condition failed (Reason: Metaverse attribute value is not present) {0}", this.Description);
         return(false);
     }
 }
Exemplo n.º 8
0
        public GetImportEntriesResults GetImportEntries(GetImportEntriesRunStep importRunStep)
        {
            Tracer.Enter("getimportentries");
            try
            {
                #region call import script

                // if results is null, then this is the first time that we're called,
                // so call script and get pipeline object and custom data
                Tracer.TraceInformation("more-to-import '{0}'", MoreToImport);

                if (MoreToImport)
                {
                    MoreToImport = false; // make sure we set more-to-import to false; could be overwritten further down if pagedimports is true, though

                    // on first call, we set customdata to value from last successful run
                    returnedCustomData = importRunStep.CustomData;

                    Command cmd = new Command(Path.GetFullPath(ImportScript));
                    cmd.Parameters.Add(new CommandParameter("Username", Username));
                    cmd.Parameters.Add(new CommandParameter("Password", Password));
                    cmd.Parameters.Add(new CommandParameter("Credentials", GetSecureCredentials(Username, SecureStringPassword)));

                    cmd.Parameters.Add(new CommandParameter("AuxUsername", UsernameAux));
                    cmd.Parameters.Add(new CommandParameter("AuxPassword", PasswordAux));
                    cmd.Parameters.Add(new CommandParameter("AuxCredentials", GetSecureCredentials(UsernameAux, SecureStringPasswordAux)));

                    cmd.Parameters.Add(new CommandParameter("ConfigurationParameter", ConfigurationParameter));

                    cmd.Parameters.Add(new CommandParameter("OperationType", importOperationType.ToString()));
                    cmd.Parameters.Add(new CommandParameter("UsePagedImport", UsePagedImport));
                    cmd.Parameters.Add(new CommandParameter("PageSize", ImportRunStepPageSize));
                    cmd.Parameters.Add(new CommandParameter("Schema", schemaPSObject));

                    Tracer.TraceInformation("setting-custom-data '{0}'", importRunStep.CustomData);
                    powershell.Runspace.SessionStateProxy.SetVariable("RunStepCustomData", importRunStep.CustomData);
                    Tracer.TraceInformation("setting-page-token '{0}'", pageToken);
                    powershell.Runspace.SessionStateProxy.SetVariable("PageToken", pageToken);

                    importResults = InvokePowerShellScript(cmd, null).ToList <PSObject>();

                    returnedCustomData = powershell.Runspace.SessionStateProxy.GetVariable("RunStepCustomData");
                    pageToken          = powershell.Runspace.SessionStateProxy.GetVariable("PageToken");

                    Tracer.TraceInformation("page-token-returned '{0}'", pageToken == null ? "(null)" : pageToken);
                    Tracer.TraceInformation("custom-data returned '{0}'", returnedCustomData);
                    Tracer.TraceInformation("number-of-object(s)-in-pipeline {0:n0}", importResults.Count);

                    if (UsePagedImport)
                    {
                        // Tracer.TraceError("paged-import-not-supported-currently");
                        object moreToImportObject = powershell.Runspace.SessionStateProxy.GetVariable("MoreToImport");
                        if (moreToImportObject == null)
                        {
                            Tracer.TraceError("For paged imports, the global variable 'MoreToImport' must be set to 'true' or 'false'");
                        }
                        else
                        {
                            Tracer.TraceInformation("MoreToImport-value-returned '{0}'", moreToImportObject);
                            if (bool.TryParse(moreToImportObject == null ? bool.FalseString : moreToImportObject.ToString(), out MoreToImport))
                            {
                                Tracer.TraceInformation("paged-import-setting-MoreToImport-to '{0}'", MoreToImport);
                            }
                            else
                            {
                                Tracer.TraceError("Value returned in MoreToImport must be a boolean with value of 'true' or 'false'");
                            }
                        }
                    }
                    else
                    {
                        MoreToImport = false;
                        Tracer.TraceInformation("non-paged-import-setting-MoreToImport-to '{0}'", MoreToImport);
                    }
                }
                #endregion

                #region parse returned objects
                if (importResults != null && importResults.Count > 0)
                {
                    List <PSObject> importResultsBatch = importResults.Take(ImportRunStepPageSize).ToList();
                    if (importResults.Count > ImportRunStepPageSize)
                    {
                        importResults.RemoveRange(0, importResultsBatch.Count);
                    }
                    else
                    {
                        importResults.Clear();
                    }
                    Tracer.TraceInformation("converting-objects-to-csentrychange {0:n0}", importResultsBatch.Count);
                    foreach (PSObject obj in importResultsBatch)
                    {
                        HashSet <AttributeDefinition> attrs = new HashSet <AttributeDefinition>();

                        Tracer.TraceInformation("start-connector-space-object");
                        try
                        {
                            CSEntryChange csobject = CSEntryChange.Create();

                            if (obj.BaseObject.GetType() != typeof(System.Collections.Hashtable))
                            {
                                Tracer.TraceWarning("invalid-object-in-pipeline '{0}'", 1, obj.BaseObject.GetType());
                                continue;
                            }

                            object        AnchorValue         = null;
                            string        AnchorAttributeName = null;
                            string        objectDN            = null;
                            string        objectClass         = ""; // should be string to prevent null exceptions
                            string        changeType          = null;
                            string        ErrorName           = null;
                            string        ErrorDetail         = null;
                            MAImportError ImportErrorType     = MAImportError.Success; // assume no error
                            Hashtable     hashTable           = (Hashtable)obj.BaseObject;

                            #region get control values
                            Tracer.TraceInformation("start-getting-control-values");
                            foreach (string key in hashTable.Keys)
                            {
                                if (key.Equals(Constants.ControlValues.ObjectClass, StringComparison.OrdinalIgnoreCase) || key.Equals(Constants.ControlValues.ObjectClassEx, StringComparison.OrdinalIgnoreCase))
                                {
                                    objectClass = (string)hashTable[key];
                                    Tracer.TraceInformation("got-objectclass {0}, {1}", objectClass, key);
                                    continue;
                                }
                                if (key.Equals(Constants.ControlValues.DN, StringComparison.OrdinalIgnoreCase))
                                {
                                    objectDN = (string)hashTable[key];
                                    Tracer.TraceInformation("got-dn {0}, {1}", objectDN, key);
                                    continue;
                                }
                                if (key.Equals(Constants.ControlValues.ChangeType, StringComparison.OrdinalIgnoreCase) || key.Equals(Constants.ControlValues.ChangeTypeEx, StringComparison.OrdinalIgnoreCase))
                                {
                                    changeType = (string)hashTable[key];
                                    Tracer.TraceInformation("got-changetype {0}, {1}", changeType, key);
                                    continue;
                                }
                                if (key.Equals(Constants.ControlValues.ErrorName, StringComparison.OrdinalIgnoreCase))
                                {
                                    ErrorName = (string)hashTable[key];
                                    Tracer.TraceInformation("got-errorname {0}, {1}", ErrorName, key);
                                    continue;
                                }
                                if (key.Equals(Constants.ControlValues.ErrorDetail, StringComparison.OrdinalIgnoreCase))
                                {
                                    ErrorDetail = (string)hashTable[key];
                                    Tracer.TraceInformation("got-errordetail {0}, {1}", ErrorDetail, key);
                                    continue;
                                }
                            }

                            if (string.IsNullOrEmpty(objectClass))
                            {
                                Tracer.TraceError("missing-objectclass");
                                ImportErrorType = MAImportError.ImportErrorCustomContinueRun;
                                ErrorName       = "missing-objectclass-value";
                                ErrorDetail     = "No value provided for objectclass attribute";
                            }
                            else
                            {
                                AnchorAttributeName = objectTypeAnchorAttributeNames[objectClass] == null ? "" : (string)objectTypeAnchorAttributeNames[objectClass];
                                if (string.IsNullOrEmpty(AnchorAttributeName))
                                {
                                    ImportErrorType = MAImportError.ImportErrorInvalidAttributeValue;
                                    ErrorName       = "invalid-objecttype";
                                    ErrorDetail     = "Objecttype not defined in schema";
                                }

                                foreach (string key in hashTable.Keys)
                                {
                                    if (key.Equals(AnchorAttributeName, StringComparison.OrdinalIgnoreCase))
                                    {
                                        AnchorValue = hashTable[key];
                                        Tracer.TraceInformation("got-anchor {0}, {1}", AnchorValue, key);
                                        break;
                                    }
                                }
                            }
                            Tracer.TraceInformation("end-getting-control-values");

                            if (AnchorValue == null)
                            {
                                Tracer.TraceError("missing-anchor");
                                ImportErrorType = MAImportError.ImportErrorCustomContinueRun;
                                ErrorName       = "missing-anchor-value";
                                ErrorDetail     = "No value provided for anchor attribute";
                            }

                            if (AnchorValue != null && string.IsNullOrEmpty(objectDN))
                            {
                                Tracer.TraceInformation("setting-anchor-as-dn {0}", AnchorValue);
                                objectDN = AnchorValue.ToString();
                            }

                            if (!string.IsNullOrEmpty(ErrorName))
                            {
                                ImportErrorType = MAImportError.ImportErrorCustomContinueRun;
                                if (string.IsNullOrEmpty(ErrorDetail))
                                {
                                    ErrorDetail = "No error details provided";
                                }
                            }
                            #endregion control values

                            #region return invalid object
                            if (ImportErrorType != MAImportError.Success)
                            {
                                Tracer.TraceInformation("returning-invalid-object");
                                if (AnchorValue != null)
                                {
                                    csobject.AnchorAttributes.Add(AnchorAttribute.Create(AnchorAttributeName, AnchorValue));
                                }
                                csobject.ObjectModificationType = ObjectModificationType.Add;
                                if (!string.IsNullOrEmpty(objectClass))
                                {
                                    try
                                    {
                                        csobject.ObjectType = objectClass;
                                    }
                                    catch (NoSuchObjectTypeException otEx)
                                    {
                                        Tracer.TraceError("no-such-object '{0}'", otEx);
                                    }
                                }
                                if (!string.IsNullOrEmpty(objectClass))
                                {
                                    csobject.DN = objectDN;
                                }
                                Tracer.TraceError("invalid-object dn: {0}, type: {1}, name: {2}, details: {3} ", objectDN, ImportErrorType, ErrorName, ErrorDetail);
                                csobject.ErrorCodeImport = ImportErrorType;
                                csobject.ErrorName       = ErrorName;
                                csobject.ErrorDetail     = ErrorDetail;
                                csentryqueue.Add(csobject);
                                continue;
                            }
                            #endregion

                            #region return deleted object
                            // we must set ObjectModificationType before any other attributes; otherwise it will default to 'Add'
                            if (!string.IsNullOrEmpty(changeType) && changeType.Equals("delete", StringComparison.OrdinalIgnoreCase))
                            {
                                Tracer.TraceInformation("returning-deleted-object");
                                Tracer.TraceInformation("change-type {0}", changeType);
                                csobject.ObjectModificationType = ObjectModificationType.Delete;
                                csobject.ObjectType             = objectClass;
                                csobject.DN = objectDN;

                                // we need to get the object anchor value for the deletion
                                csobject.AnchorAttributes.Add(AnchorAttribute.Create(AnchorAttributeName, AnchorValue));
                                csentryqueue.Add(csobject);
                                continue;
                            }
                            #endregion

                            #region returned live object
                            Tracer.TraceInformation("returning-valid-object");
                            csobject.ObjectModificationType = ObjectModificationType.Add;
                            csobject.ObjectType             = objectClass;
                            csobject.DN = objectDN;
                            csobject.AnchorAttributes.Add(AnchorAttribute.Create(AnchorAttributeName, AnchorValue));
                            foreach (string key in hashTable.Keys)
                            {
                                try
                                {
                                    if (Regex.IsMatch(key, string.Format(@"^(objectClass|\[objectclass\]|changeType|\[changetype\]|\[DN\]|\[ErrorName\]|\[ErrorDetail\]|{0})$", AnchorAttributeName), RegexOptions.Compiled | RegexOptions.IgnoreCase))
                                    {
                                        Tracer.TraceInformation("skip-control-value {0}", key);
                                        continue;
                                    }
                                    if (hashTable[key] == null)
                                    {
                                        Tracer.TraceInformation("skip-null-value-for '{0}'", key);
                                        continue;
                                    }
                                    SchemaAttribute sa = schema.Types[objectClass].Attributes[key];
                                    Tracer.TraceInformation("attribute: {0} (type {1}, {2}): '{3}'", key, sa.DataType, sa.IsMultiValued ? "multi-value" : "single-value", hashTable[key]);
                                    if (sa.IsMultiValued)
                                    {
                                        //Tracer.TraceInformation("add-multivalue '{0}' [{1}]", key, hashTable[key].GetType());
                                        List <object> mvs = new List <object>();
                                        if (hashTable[key].ToString().EndsWith("[]"))
                                        {
                                            mvs.AddRange((object[])hashTable[key]);
                                        }
                                        else
                                        {
                                            mvs.Add(hashTable[key]);
                                        }
                                        csobject.AttributeChanges.Add(AttributeChange.CreateAttributeAdd(key, mvs));
                                    }
                                    else
                                    {
                                        csobject.AttributeChanges.Add(AttributeChange.CreateAttributeAdd(key, hashTable[key]));
                                    }
                                }
                                catch (KeyNotFoundException keyexception)
                                {
                                    Tracer.TraceError("attribute-is-not-defined-for '{0}' / '{1}' ({2})", key, objectClass, keyexception.ToString());
                                }
                            }
                            #endregion

                            if (csobject.ErrorCodeImport != MAImportError.Success)
                            {
                                Tracer.TraceError("defective-csentrychange id: {0}, dn: {1}, errorcode: {2}, error: {3}, details: {4}", csobject.Identifier, csobject.DN, csobject.ErrorCodeImport, csobject.ErrorName, csobject.ErrorDetail);
                            }
                            Tracer.TraceInformation("returning-csentry dn: {0}, id: {1}", csobject.DN, csobject.Identifier);
                            csentryqueue.Add(csobject);
                        }
                        catch (Exception ex)
                        {
                            Tracer.TraceError("creating-csentrychange", ex);
                        }
                        finally
                        {
                            Tracer.TraceInformation("end-connector-space-object");
                        }
                    }
                    // clearing results for next loop
                    importResultsBatch.Clear();
                }
                #endregion

                #region dequeue csentries

                GetImportEntriesResults importReturnInfo = null;

                Tracer.TraceInformation("total-import-object(s)-left {0:n0}", importResults.Count);
                Tracer.TraceInformation("total-connector-space-object(s)-left {0:n0}", csentryqueue.Count);

                List <CSEntryChange> batch = csentryqueue.Take(ImportRunStepPageSize).ToList();
                if (csentryqueue.Count > ImportRunStepPageSize)
                {
                    csentryqueue.RemoveRange(0, batch.Count);
                }
                else
                {
                    csentryqueue.Clear();
                }
                importReturnInfo = new GetImportEntriesResults();
                importReturnInfo.MoreToImport = MoreToImport || importResults.Count > 0 || (csentryqueue.Count > 0);
                importReturnInfo.CustomData   = returnedCustomData == null ? "" : returnedCustomData.ToString();
                importReturnInfo.CSEntries    = batch;

                Tracer.TraceInformation("should-return-for-more {0}", importReturnInfo.MoreToImport);
                Tracer.TraceInformation("custom-data '{0}'", importReturnInfo.CustomData);
                Tracer.TraceInformation("connector-space-object(s)-returned {0:n0}", importReturnInfo.CSEntries.Count);

                return(importReturnInfo);

                #endregion
            }
            catch (Exception ex)
            {
                Tracer.TraceError("getimportentries", ex);
                throw;
            }
            finally
            {
                Tracer.Exit("getimportentries");
            }
        }
Exemplo n.º 9
0
        public void Initialize()
        {
            Tracer.TraceInformation("enter-initialize");
            try
            {
                System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                FileVersionInfo            fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);
                Tracer.TraceInformation("fim-mre-version {0}", fvi.FileVersion);

                RegistryKey machineRegistry = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
                RegistryKey mreRootKey      = machineRegistry.OpenSubKey(@"SOFTWARE\Granfeldt\FIM\MRE", false);

                if (mreRootKey != null)
                {
                    string logFileValue = mreRootKey.GetValue("DebugLogFileName", null) as string;
                    if (logFileValue != null)
                    {
                        Tracer.TraceWarning("DebugLogFileName registry key is deprecated. Use trace logging instead.");
                    }

                    string ruleFilesAlternativePath = mreRootKey.GetValue("RuleFilesAlternativePath", null) as string;
                    if (!string.IsNullOrEmpty(ruleFilesAlternativePath))
                    {
                        ruleFilesPath = ruleFilesAlternativePath;
                        Tracer.TraceInformation("registry-alternative-rulefiles-path '{0}'", ruleFilesPath);
                    }
                }

                if (!EventLog.SourceExists(EventLogSource))
                {
                    Tracer.TraceInformation("creating-eventlog-source source: {0}, logname: ", EventLogSource, EventLogName);
                    EventLog.CreateEventSource(EventLogSource, EventLogName);
                }
                EventLog evl = new EventLog(EventLogName);
                evl.Log    = EventLogName;
                evl.Source = EventLogSource;

                EventLogTraceListener eventLog = new EventLogTraceListener(EventLogSource);
                eventLog.EventLog = evl;
                EventTypeFilter filter = new EventTypeFilter(SourceLevels.Warning | SourceLevels.Error | SourceLevels.Critical);
                eventLog.TraceOutputOptions = TraceOptions.Callstack;
                eventLog.Filter             = filter;
                Tracer.Trace.Listeners.Add(eventLog);

#if DEBUG
                // for debugging, we use current path
                if (ruleFilesPath == Utils.ExtensionsDirectory)
                {
                    ruleFilesPath = Directory.GetCurrentDirectory();
                }
#endif
                Tracer.TraceInformation("loading-rule-files-from '{0}'", ruleFilesPath);
                this.EngineRules = new Dictionary <string, List <Rule> >();
                this.Externals   = new Dictionary <string, External>();

                string[] ruleFiles = Directory.GetFiles(ruleFilesPath, "*.mre.xml", SearchOption.AllDirectories);
                foreach (string ruleFile in ruleFiles)
                {
                    RulesFile rules = new RulesFile();
                    Tracer.TraceInformation("loading-rule-file '{0}'", ruleFile);
                    MVRules.LoadSettingsFromFile(ruleFile, ref rules);

                    foreach (Rule rule in rules.Rules)
                    {
                        if (rule.Enabled)
                        {
                            Tracer.TraceInformation("found-active-rule {0}", rule.Name);
                        }
                        else
                        {
                            Tracer.TraceInformation("found-inactive-rule {0}", rule.Name);
                            continue;
                        }

                        rule.EnsureBackwardsCompatibility();

                        if (rule.Enabled && rule.RenameDnFlow != null)
                        {
                            Tracer.TraceWarning("RenameDnFlow XML element is obsolete and will not be supported in coming versions. Please see documentation for more information.");
                        }

                        if (!this.EngineRules.ContainsKey(rule.SourceObject))
                        {
                            this.EngineRules.Add(rule.SourceObject, new List <Rule>());
                        }

                        this.EngineRules[rule.SourceObject].Add(rule);
                    }

                    // handle loading externals
                    foreach (External e in rules.Externals)
                    {
                        if (string.IsNullOrEmpty(e.ReferenceId))
                        {
                            Tracer.TraceWarning("skipping-external-without-referenceid-value");
                            continue;
                        }
                        if (!this.Externals.ContainsKey(e.ReferenceId))
                        {
                            Tracer.TraceInformation("external referenceid: {0}, type: {1}, filename: {2}", e.ReferenceId, e.Type, e.Filename);
                            e.EnsureFullFilename(ruleFilesPath);
                            e.LoadExternalAssembly();
                            this.Externals.Add(e.ReferenceId, e);
                            foreach (External i in Externals?.Values)
                            {
                                i.Initialize();
                            }
                        }
                        else
                        {
                            Tracer.TraceError("cannot-add-duplicate-external-referenceid-value {0}", e.ReferenceId);
                        }
                    }
                }

                if (this.EngineRules.Count == 0)
                {
                    Tracer.TraceWarning("no-rules-loaded");
                }
            }
            catch (Exception ex)
            {
                Tracer.TraceError("error {0}", ex.GetBaseException());
                throw;
            }
            finally
            {
                Tracer.TraceInformation("exit-initialize");
            }
        }
Exemplo n.º 10
0
 static void Warning_DataAdded(object sender, DataAddedEventArgs e)
 {
     Tracer.TraceWarning("warning {0}", ((PSDataCollection <WarningRecord>)sender)[e.Index].ToString());
 }
Exemplo n.º 11
0
        public void InitializeConfigParameters(System.Collections.ObjectModel.KeyedCollection <string, ConfigParameter> configParameters)
        {
            Tracer.Enter("initializeconfigparameters");
            try
            {
                if (configParameters != null)
                {
                    foreach (ConfigParameter cp in configParameters)
                    {
                        Tracer.TraceInformation("{0}: '{1}'", cp.Name, cp.IsEncrypted ? "*** secret ***" : cp.Value);
                        if (cp.Name.Equals(Constants.Parameters.Username))
                        {
                            Username = configParameters[cp.Name].Value;
                        }
                        if (cp.Name.Equals(Constants.Parameters.Password))
                        {
                            Password             = configParameters[cp.Name].SecureValue.ConvertToUnsecureString();
                            SecureStringPassword = configParameters[cp.Name].SecureValue;
                        }

                        if (cp.Name.Equals(Constants.Parameters.UsernameAux))
                        {
                            UsernameAux = configParameters[cp.Name].Value;
                        }
                        if (cp.Name.Equals(Constants.Parameters.PasswordAux))
                        {
                            PasswordAux             = configParameters[cp.Name].SecureValue.ConvertToUnsecureString();
                            SecureStringPasswordAux = configParameters[cp.Name].SecureValue;
                        }
                        if (cp.Name.Equals(Constants.Parameters.ConfigurationParameters))
                        {
                            string[] result = Regex.Split(configParameters[cp.Name].Value, "\r\n|\r|\n");
                            if (result != null)
                            {
                                foreach (string s in result)
                                {
                                    string key   = null;
                                    string value = null;
                                    if (getConfigurationParameter(s, out key, out value))
                                    {
                                        Tracer.TraceInformation($"configuration-parameter key: '{key}', value: '{value}'");
                                        if (ConfigurationParameter.ContainsKey(key))
                                        {
                                            Tracer.TraceWarning($"duplicate-configuration key: {key}");
                                        }
                                        else
                                        {
                                            ConfigurationParameter.Add(key, value);
                                        }
                                    }
                                }
                            }
                        }

                        if (cp.Name.Equals(Constants.Parameters.ImpersonationDomain))
                        {
                            impersonationUserDomain = configParameters[cp.Name].Value;
                        }
                        if (cp.Name.Equals(Constants.Parameters.ImpersonationUsername))
                        {
                            impersonationUsername = configParameters[cp.Name].Value;
                        }
                        if (cp.Name.Equals(Constants.Parameters.ImpersonationPassword))
                        {
                            impersonationUserPassword = configParameters[cp.Name].SecureValue.ConvertToUnsecureString();
                        }

                        if (cp.Name.Equals(Constants.Parameters.SchemaScript))
                        {
                            SchemaScript = configParameters[cp.Name].Value;
                        }
                        if (cp.Name.Equals(Constants.Parameters.ImportScript))
                        {
                            ImportScript = configParameters[cp.Name].Value;
                        }
                        if (cp.Name.Equals(Constants.Parameters.ExportScript))
                        {
                            ExportScript = configParameters[cp.Name].Value;
                        }
                        if (cp.Name.Equals(Constants.Parameters.PasswordManagementScript))
                        {
                            PasswordManagementScript = configParameters[cp.Name].Value;
                        }
                        if (cp.Name.Equals(Constants.Parameters.ExportSimpleObjects))
                        {
                            ExportSimpleObjects = configParameters[cp.Name].Value == "0" ? false : true;
                        }
                        if (cp.Name.Equals(Constants.Parameters.UsePagedImport))
                        {
                            UsePagedImport = configParameters[cp.Name].Value == "0" ? false : true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.TraceError("initializeconfigparameters", ex);
                throw;
            }
            finally
            {
                Tracer.Exit("initializeconfigparameters");
            }
        }
Exemplo n.º 12
0
        public AttributeDefinition(string Name, string DataTypeName)
        {
            this.Name          = Name;
            AttributeOperation = AttributeOperation.ImportExport;
            switch (DataTypeName)
            {
            case "int": this.AttributeType = AttributeType.Integer; break;

            case "bigint": this.AttributeType = AttributeType.Integer; break;

            case "tinyint": this.AttributeType = AttributeType.Integer; break;

            case "smallint": this.AttributeType = AttributeType.Integer; break;

            case "bit": this.AttributeType = AttributeType.Boolean; break;

            case "binary": this.AttributeType = AttributeType.Binary; break;

            case "varbinary": this.AttributeType = AttributeType.Binary; break;

            case "image": this.AttributeType = AttributeType.Binary; break;

            case "uniqueidentifier": this.AttributeType = AttributeType.Binary; break;

            case "date": this.AttributeType = AttributeType.String; break;

            case "datetime": this.AttributeType = AttributeType.String; break;

            case "smalldatetime": this.AttributeType = AttributeType.String; break;

            case "datetime2": this.AttributeType = AttributeType.String;; break;

            case "datetimeoffset": this.AttributeType = AttributeType.String; break;

            case "time": this.AttributeType = AttributeType.String; break;

            case "timestamp": this.AttributeType = AttributeType.String; AttributeOperation = AttributeOperation.ImportOnly; break;

            case "nvarchar": this.AttributeType = AttributeType.String; break;

            case "char": this.AttributeType = AttributeType.String; break;

            case "varchar": this.AttributeType = AttributeType.String; break;

            case "text": this.AttributeType = AttributeType.String; break;

            case "nchar": this.AttributeType = AttributeType.String; break;

            case "ntext": this.AttributeType = AttributeType.String; break;

            case "decimal": this.AttributeType = AttributeType.String; break;

            case "float": this.AttributeType = AttributeType.String; break;

            case "money": this.AttributeType = AttributeType.String; break;

            case "smallmoney": this.AttributeType = AttributeType.String; break;

            case "real": this.AttributeType = AttributeType.String; break;

            case "xml": this.AttributeType = AttributeType.String; break;

            default:
                Tracer.TraceWarning("non-supported-type name: {0}, sql-type: {1}", Name, DataTypeName);
                this.AttributeType = AttributeType.String;
                break;
            }
            Tracer.TraceInformation("name: {0}, sql-type: {1}, selected-schematype: {2}", Name, DataTypeName, AttributeType);
        }