Exemple #1
0
        /// <summary>
        /// Exports a batch of entries to the database
        /// </summary>
        /// <param name="csentries">A list of changes to export</param>
        /// <returns>The results of the batch export</returns>
        public PutExportEntriesResults PutExportEntries(IList <CSEntryChange> csentries)
        {
            try
            {
                this.client = new AcmaSyncServiceClient();

                PutExportEntriesResults exportEntriesResults = new PutExportEntriesResults();
                IList <AttributeChange> anchorchanges        = new List <AttributeChange>();
                ExportRequest           request = new ExportRequest();
                request.CSEntryChanges = csentries;

                Logger.WriteLine("Exporting page of {0} objects", csentries.Count);
                ExportResponse response = this.client.ExportPage(request);
                Logger.WriteLine("Got response of {0} objects", response.Results.Count);

                foreach (CSEntryChangeResult item in response.Results)
                {
                    exportEntriesResults.CSEntryChangeResults.Add(item);
                }

                return(exportEntriesResults);
            }
            catch (Exception ex)
            {
                Logger.WriteException(ex);
                throw;
            }
        }
        /// <summary>
        /// Exports a batch of entries to the database
        /// </summary>
        /// <param name="csentries">A list of changes to export</param>
        /// <returns>The results of the batch export</returns>
        PutExportEntriesResults IMAExtensible2CallExport.PutExportEntries(IList <CSEntryChange> csentries)
        {
            PutExportEntriesResults exportEntriesResults = new PutExportEntriesResults();

            foreach (CSEntryChange csentry in csentries)
            {
                try
                {
                    List <AttributeChange> anchorchanges = new List <AttributeChange>();
                    bool referenceRetryRequired;
                    anchorchanges.AddRange(CSEntryExport.PutExportEntry(csentry, out referenceRetryRequired));

                    if (referenceRetryRequired)
                    {
                        Logger.WriteLine(string.Format("Reference attribute not available for csentry {0}. Flagging for retry", csentry.DN));
                        exportEntriesResults.CSEntryChangeResults.Add(CSEntryChangeResult.Create(csentry.Identifier, anchorchanges, MAExportError.ExportActionRetryReferenceAttribute));
                    }
                    else
                    {
                        exportEntriesResults.CSEntryChangeResults.Add(CSEntryChangeResult.Create(csentry.Identifier, anchorchanges, MAExportError.Success));
                    }
                }
                catch (Exception ex)
                {
                    if (exportEntriesResults.CSEntryChangeResults.Contains(csentry.Identifier))
                    {
                        exportEntriesResults.CSEntryChangeResults.Remove(csentry.Identifier);
                    }

                    exportEntriesResults.CSEntryChangeResults.Add(this.GetExportChangeResultFromException(csentry, ex));
                }
            }

            return(exportEntriesResults);
        }
        public PutExportEntriesResults PutExportEntries(IList <CSEntryChange> csentries)
        {
            PutExportEntriesResults results = new PutExportEntriesResults();

            ParallelOptions po = new ParallelOptions
            {
                MaxDegreeOfParallelism = GlobalSettings.ExportThreadCount,
                CancellationToken      = this.exportContext.Token
            };

            Parallel.ForEach(csentries, po, (csentry) =>
            {
                Stopwatch timer = new Stopwatch();

                int number    = Interlocked.Increment(ref this.exportContext.ExportedItemCount);
                string record = $"{number}:{csentry.ObjectModificationType}:{csentry.ObjectType}:{csentry.DN}";
                CSEntryChangeResult result = null;

                logger.Info($"Exporting record {record}");

                try
                {
                    timer.Start();
                    result = this.PutCSEntryChange(csentry);
                }
                catch (Exception ex)
                {
                    logger.Error(ex.UnwrapIfSingleAggregateException(), $"An error occurred exporting record {record}");
                    result = CSEntryChangeResult.Create(csentry.Identifier, null, MAExportError.ExportErrorCustomContinueRun, ex.UnwrapIfSingleAggregateException().Message, ex.UnwrapIfSingleAggregateException().ToString());
                }
                finally
                {
                    timer.Stop();

                    if (result == null)
                    {
                        logger.Error($"CSEntryResult for object {record} was null");
                    }
                    else
                    {
                        lock (results)
                        {
                            results.CSEntryChangeResults.Add(result);
                        }
                    }

                    logger.Trace($"Export of record {record} returned '{result?.ErrorCode.ToString().ToLower() ?? "<null>"}' and took {timer.Elapsed}");
                }
            });

            logger.Info($"Page complete. Export count: {this.exportContext.ExportedItemCount}");
            return(results);
        }
        public PutExportEntriesResults PutExportEntries(IList <CSEntryChange> csentries)
        {
            PutExportEntriesResults exportEntriesResults = new PutExportEntriesResults();

            //int i = 0;

            foreach (CSEntryChange csentryChange in csentries)
            {
                userID = csentryChange.DN.ToString();

                if (csentryChange.ObjectType == "Person")
                {
                    // Code to Create RSA account
                    if (csentryChange.ObjectModificationType == ObjectModificationType.Add)
                    {
                        foreach (string attrib in csentryChange.ChangedAttributeNames)
                        {
                            switch (attrib)
                            {
                            case "First Name":
                                firstName = csentryChange.AttributeChanges["First Name"].ValueChanges[0].Value.ToString();
                                break;

                            case "Last Name":
                                lastName = csentryChange.AttributeChanges["Last Name"].ValueChanges[0].Value.ToString();
                                break;

                            case "Manager Email Address":
                                managerEmailAddress = csentryChange.AttributeChanges["Manager Email Address"].ValueChanges[0].Value.ToString();
                                break;

                            case "Middle Name":
                                middleName = csentryChange.AttributeChanges["Middle Name"].ValueChanges[0].Value.ToString();
                                break;
                            }
                        }


                        try
                        {
                            AssignNewTokenToExistingUser(userID, managerEmailAddress, firstName, lastName);
                        }
                        catch (UserNotFoundException)
                        {
                            CSEntryChangeResult error = CSEntryChangeResult.Create(csentryChange.Identifier, null, MAExportError.ExportErrorInvalidDN);
                            exportEntriesResults.CSEntryChangeResults.Add(error);

                            EmailError(new Exception("Unable to assign a token for user '" + userID + "'. User not found. The synchronization engine will try to assign a token on the next export."));
                        }
                    }


                    // Code to Delete from RSA store
                    if (csentryChange.ObjectModificationType == ObjectModificationType.Replace)
                    {
                        //this.DeleteUser(userID);
                    }
                } // End of type Person
            }     // End of ForEach

            // i++;



            return(exportEntriesResults);
        }
Exemple #5
0
        // PutExportEntries
        public PutExportEntriesResults PutExportEntries(IList <CSEntryChange> _csentries)
        {
            utils.Logger(TraceEventType.Information,
                         ConstDefinition.ID0800_START_PUTEXPORTENTRIES,
                         ConstDefinition.MSG0800_START_PUTEXPORTENTRIES);
            PutExportEntriesResults _exportEntriesResults = new PutExportEntriesResults();

            try
            {
                foreach (CSEntryChange _csentryChange in _csentries)
                {
#if DEBUG
                    utils.Logger(TraceEventType.Verbose, ConstDefinition.ID0850_VERBOSE_PUTEXPORTENTRIES, _csentryChange.DN.ToString());
#endif
                    // build json to POST
                    var _attr = new Dictionary <string, string>();
                    // anchor attribute
                    _attr.Add("Username", _csentryChange.DN.ToString());
                    switch (_csentryChange.ObjectModificationType)
                    {
                    case ObjectModificationType.Add:
                    case ObjectModificationType.Update:
#if DEBUG
                        utils.Logger(TraceEventType.Verbose, ConstDefinition.ID0850_VERBOSE_PUTEXPORTENTRIES, "ObjectModificationType : Add / Update");
#endif
                        foreach (string _attribName in _csentryChange.ChangedAttributeNames)
                        {
                            var _attributeChange = _csentryChange.AttributeChanges[_attribName];
                            var _valueChanges    = _attributeChange.ValueChanges;
                            if (_valueChanges != null)
                            {
                                foreach (var _valueChange in _valueChanges)
                                {
                                    if (_valueChange.ModificationType == ValueModificationType.Add)
                                    {
                                        // new value
#if DEBUG
                                        utils.Logger(TraceEventType.Verbose, ConstDefinition.ID0850_VERBOSE_PUTEXPORTENTRIES, _attribName + " : " + _valueChange.Value.ToString());
#endif
                                        _attr.Add(_attribName, _valueChange.Value.ToString());
                                        break;
                                    }
                                }
                            }
                        }
                        // build json
                        string _exportDataJSON = JsonConvert.SerializeObject(_attr);
#if DEBUG
                        utils.Logger(TraceEventType.Verbose, ConstDefinition.ID0850_VERBOSE_PUTEXPORTENTRIES, _exportDataJSON);
#endif
                        string _exportResult = utils.PostContentsWithAccessToken(resource_uri, auth_token, _exportDataJSON, null);

                        _exportEntriesResults.CSEntryChangeResults.Add(
                            CSEntryChangeResult.Create(_csentryChange.Identifier,
                                                       _csentryChange.AttributeChanges,
                                                       MAExportError.Success));
                        break;

                    case ObjectModificationType.Delete:
                        // NOT Implemented
                        break;

                    default:
                        // error
                        utils.Logger(TraceEventType.Error,
                                     ConstDefinition.ID0899_ERROR_PUTEXPORTENTRIES,
                                     ConstDefinition.MSG0899_ERROR_PUTEXPORTENTRIES + "Unknown Operation Type : " + _csentryChange.ObjectModificationType);
                        _exportEntriesResults.CSEntryChangeResults.Add(
                            CSEntryChangeResult.Create(_csentryChange.Identifier,
                                                       _csentryChange.AttributeChanges,
                                                       MAExportError.ExportErrorConnectedDirectoryError,
                                                       "Operation Error",
                                                       "Unknown Operation Type : " + _csentryChange.ObjectModificationType
                                                       ));
                        break;
                    }
                }
                return(_exportEntriesResults);
            }
            catch (Exception ex)
            {
                utils.Logger(TraceEventType.Error,
                             ConstDefinition.ID0899_ERROR_PUTEXPORTENTRIES,
                             ConstDefinition.MSG0899_ERROR_PUTEXPORTENTRIES + ex.Message);
                throw new ExtensibleExtensionException(ex.Message);
            }
        }
Exemple #6
0
        PutExportEntriesResults IMAExtensible2CallExport.PutExportEntries(IList <CSEntryChange> csentries)
        {
            Tracer.Enter("putexportentries");
            Tracer.Indent();
            PutExportEntriesResults     exportEntries  = new PutExportEntriesResults();
            PSDataCollection <PSObject> exportPipeline = new PSDataCollection <PSObject>();

            try
            {
                Command cmd = new Command(Path.GetFullPath(ExportScript));
                cmd.Parameters.Add(new CommandParameter("User", Username));
                cmd.Parameters.Add(new CommandParameter("Password", Password));
                cmd.Parameters.Add(new CommandParameter("Credentials", GetSecureCredentials()));
                cmd.Parameters.Add(new CommandParameter("ExportType", exportType));

                foreach (CSEntryChange csentryChange in csentries)
                {
                    Tracer.TraceInformation("adding-object id: {0}, dn: '{1}' [{2}]", csentryChange.Identifier, csentryChange.DN, csentryChange.ObjectModificationType);
                    if (ExportSimpleObjects)
                    {
                        // http://karlprosser.com/coder/2008/06/12/generating-a-propertybag-aka-pscustomobject-in-c/
                        // creating a PSobject without any parameters in the constructor creates a PSCustomObject
                        PSObject obj = new PSObject();
                        // PSNoteProperties are not strongly typed but do contain an explicit type.
                        obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.Identifier, csentryChange.Identifier.ToString()));
                        obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.Anchor, csentryChange.AnchorAttributes.Count > 0 ? csentryChange.AnchorAttributes.FirstOrDefault().Value : ""));
                        obj.Properties.Add(new PSAliasProperty(Constants.ControlValues.IdentifierAsGuid, csentryChange.Identifier.ToString(), typeof(Guid)));
                        obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.ObjectModificationType, csentryChange.ObjectModificationType.ToString()));
                        obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.ObjectType, csentryChange.ObjectType));

                        List <string> attrs = schema.Types[csentryChange.ObjectType].Attributes.Select(a => a.Name).ToList <string>();
                        obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.AttributeNames, attrs));

                        obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.ChangedAttributeNames, csentryChange.ChangedAttributeNames == null ? new List <string>() : csentryChange.ChangedAttributeNames));
                        obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.DN, csentryChange.DN));
                        obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.RDN, csentryChange.RDN));
                        foreach (AttributeChange ac in csentryChange.AttributeChanges)
                        {
                            if (!ac.IsMultiValued)
                            {
                                foreach (ValueChange vc in ac.ValueChanges)
                                {
                                    obj.Properties.Add(new PSNoteProperty(string.Format("{0}", ac.Name), vc.Value));
                                }
                            }
                            else
                            {
                                List <object> values = new List <object>();
                                foreach (ValueChange vc in ac.ValueChanges)
                                {
                                    values.Add(vc.Value);
                                }
                                obj.Properties.Add(new PSNoteProperty(string.Format("{0}", ac.Name), values.ToArray()));
                            }
                        }
                        exportPipeline.Add(obj);
                    }
                    else
                    {
                        exportPipeline.Add(new PSObject(csentryChange));
                    }
                }

                exportResults = InvokePowerShellScript(cmd, exportPipeline);

                if (exportResults != null)
                {
                    foreach (PSObject result in exportResults)
                    {
                        if (result.BaseObject.GetType() != typeof(System.Collections.Hashtable))
                        {
                            continue;
                        }
                        Hashtable hashTable   = (Hashtable)result.BaseObject;
                        string    ErrorName   = "unspecified-error";
                        string    ErrorDetail = "No details specified";
                        Guid      identifier  = new Guid();

                        // get anchor attribute changes
                        List <AttributeChange> attrchanges = new List <AttributeChange>();
                        foreach (string key in hashTable.Keys)
                        {
                            if (key.Equals(Constants.ControlValues.Identifier, StringComparison.OrdinalIgnoreCase))
                            {
                                try
                                {
                                    identifier = new Guid(hashTable[key].ToString());
                                    Tracer.TraceInformation("got-identifier {0}, {1}", identifier, key);
                                }
                                catch (FormatException fex)
                                {
                                    Tracer.TraceError("identifier-format-error '{0}'", fex.ToString());
                                }
                                continue;
                            }
                            if (key.Equals(Constants.ControlValues.ErrorName, StringComparison.OrdinalIgnoreCase))
                            {
                                ErrorName = hashTable[key].ToString();
                                Tracer.TraceInformation("got-errorname {0}, {1}", ErrorName, key);
                                continue;
                            }
                            if (key.Equals(Constants.ControlValues.ErrorDetail, StringComparison.OrdinalIgnoreCase))
                            {
                                ErrorDetail = hashTable[key].ToString();
                                Tracer.TraceInformation("got-errordetail {0}, {1}", ErrorDetail, key);
                                continue;
                            }
                            if (!(Regex.IsMatch(key, @"^\[.+\]$", RegexOptions.IgnoreCase)))
                            {
                                Tracer.TraceInformation("got-attribute-change {0}: '{1}'", key, hashTable[key]);
                                attrchanges.Add(AttributeChange.CreateAttributeAdd(key, hashTable[key]));
                                continue;
                            }
                        }

                        if (string.IsNullOrEmpty(ErrorName) || ErrorName.Equals("success", StringComparison.OrdinalIgnoreCase))
                        {
                            Tracer.TraceInformation("returning-success id: {0}", identifier);
                            CSEntryChangeResult cschangeresult = CSEntryChangeResult.Create(identifier, attrchanges, MAExportError.Success);
                            exportEntries.CSEntryChangeResults.Add(cschangeresult);
                        }
                        else
                        {
                            Tracer.TraceInformation("returning-error id: {0}, name: {1}, details: {2}", identifier, ErrorName, ErrorDetail);
                            CSEntryChangeResult cschangeresult = CSEntryChangeResult.Create(identifier, attrchanges, MAExportError.ExportErrorCustomContinueRun, ErrorName, ErrorDetail);
                            exportEntries.CSEntryChangeResults.Add(cschangeresult);
                        }
                    }
                }
                exportPipeline.Clear();
                exportResults.Clear();
                exportResults = null;
                return(exportEntries);
            }
            catch (Exception ex)
            {
                Tracer.TraceError("putexportentries", ex);
                throw;
            }
            finally
            {
                Tracer.Unindent();
                Tracer.Exit("putexportentries");
            }
        }
        public PutExportEntriesResults PutExportEntries(IList <CSEntryChange> csentries)
        {
            ParallelOptions po = new ParallelOptions
            {
                MaxDegreeOfParallelism = MAConfigurationSection.Configuration.ExportThreads,
                CancellationToken      = this.cancellationToken.Token
            };

            PutExportEntriesResults results = new PutExportEntriesResults();

            try
            {
                Parallel.ForEach(csentries, po, (csentry) =>
                {
                    try
                    {
                        Interlocked.Increment(ref this.opCount);
                        Logger.StartThreadLog();
                        Logger.WriteSeparatorLine('-');
                        Logger.WriteLine("Starting export {0} for {1} with {2} attribute changes", csentry.ObjectModificationType, csentry.DN, csentry.AttributeChanges.Count);
                        SchemaType type = this.operationSchemaTypes.Types[csentry.ObjectType];

                        CSEntryChangeResult result = ExportProcessor.PutCSEntryChange(csentry, type, this.Configuration);
                        lock (results)
                        {
                            results.CSEntryChangeResults.Add(result);
                        }
                    }
                    catch (AggregateException ex)
                    {
                        Logger.WriteLine("An unexpected error occurred while processing {0}", csentry.DN);
                        Logger.WriteException(ex);
                        CSEntryChangeResult result = CSEntryChangeResult.Create(csentry.Identifier, null, MAExportError.ExportErrorCustomContinueRun, ex.InnerException?.Message ?? ex.Message, ex.InnerException?.StackTrace ?? ex.StackTrace);
                        lock (results)
                        {
                            results.CSEntryChangeResults.Add(result);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteLine("An unexpected error occurred while processing {0}", csentry.DN);
                        Logger.WriteException(ex);
                        CSEntryChangeResult result = CSEntryChangeResult.Create(csentry.Identifier, null, MAExportError.ExportErrorCustomContinueRun, ex.Message, ex.StackTrace);
                        lock (results)
                        {
                            results.CSEntryChangeResults.Add(result);
                        }
                    }
                    finally
                    {
                        Logger.WriteSeparatorLine('-');
                        Logger.EndThreadLog();
                    }
                });
            }
            catch (OperationCanceledException)
            {
            }

            return(results);
        }
Exemple #8
0
        //TODO: Remember to return identity from SQL if possible
        public PutExportEntriesResults PutExportEntriesDetached(IList <CSEntryChange> csentries)
        {
            Tracer.Enter(nameof(PutExportEntriesDetached));
            PutExportEntriesResults results = new PutExportEntriesResults();

            try
            {
                bool handleSoftDeletion = Configuration.HasDeletedColumn;
                bool handleMultivalues  = Configuration.HasMultivalueTable;

                foreach (CSEntryChange exportChange in csentries)
                {
                    List <string>          exportSqlCommands = new List <string>();
                    List <AttributeChange> attrchanges       = new List <AttributeChange>();

                    string anchor = null;
                    if (exportChange.AnchorAttributes.Count == 0)
                    {
                        Tracer.TraceInformation("no-anchor-present");
                    }
                    else
                    {
                        anchor = CSValueAsString(exportChange.AnchorAttributes[0].Value, exportChange.AnchorAttributes[0].DataType);
                    }
                    string objectClass = exportChange.ObjectType;

                    if (Configuration.RunBeforeObjectExport)
                    {
                        List <SqlParameter> parameters = new List <SqlParameter>();
                        parameters.Add(new SqlParameter("anchor", anchor));
                        parameters.Add(new SqlParameter("action", exportChange.ObjectModificationType.ToString()));
                        methods.RunStoredProcedure(Configuration.ExportObjectCommandBefore, parameters);
                    }

                    Tracer.TraceInformation("export-object {0}, cs-id: {1}, anchor: {2}, dn: {3} [{4}]", objectClass, exportChange.Identifier, anchor, exportChange.DN, exportChange.ObjectModificationType);
                    try
                    {
                        // first try to handle a delete
                        if (exportChange.ObjectModificationType == ObjectModificationType.Delete)
                        {
                            if (anchor == null)
                            {
                                throw new InvalidOperationException("cannot-delete-without-anchor");
                            }

                            Tracer.TraceInformation("deleting-record type: {1}, anchor: {0}", objectClass, anchor);
                            methods.DeleteRecord(anchor, Configuration.HasMultivalueTable, handleSoftDeletion);
                            results.CSEntryChangeResults.Add(CSEntryChangeResult.Create(exportChange.Identifier, attrchanges, MAExportError.Success));
                            continue;
                        }

                        // if we get here its either an update or and add
                        if (exportChange.ObjectModificationType == ObjectModificationType.Add)
                        {
                            Tracer.TraceInformation("adding-record type: {1}, anchor: {0}", objectClass, anchor);
                            object newAnchor = anchor;                             // set it to incoming anchor
                            if (anchor != null && methods.ExistRecord(anchor))
                            {
                                methods.Undelete(anchor);
                            }
                            else
                            {
                                methods.AddRecord(anchor, out newAnchor, objectClass);
                            }
                            attrchanges.Add(AttributeChange.CreateAttributeAdd(anchor, newAnchor));
                        }

                        // updating attributes is common for add and update
                        foreach (string attributeChange in exportChange.ChangedAttributeNames)
                        {
                            AttributeChange ac = exportChange.AttributeChanges[attributeChange];
                            Tracer.TraceInformation("attribute-change {0}, {1}", ac.Name, ac.ModificationType);
                            if (ac.IsMultiValued)
                            {
                                if (ac.ModificationType == AttributeModificationType.Delete)
                                {
                                    methods.RemoveAllMultiValues(anchor, attributeChange, handleSoftDeletion);
                                    continue;
                                }
                                foreach (ValueChange vc in ac.ValueChanges)
                                {
                                    switch (vc.ModificationType)
                                    {
                                    case ValueModificationType.Add:
                                        methods.AddMultiValue(anchor, attributeChange, vc.Value);
                                        break;

                                    case ValueModificationType.Delete:
                                        methods.DeleteMultiValue(anchor, attributeChange, vc.Value, handleSoftDeletion);
                                        break;
                                    }
                                }
                                continue;
                            }
                            if (ac.ModificationType == AttributeModificationType.Delete)
                            {
                                methods.DeleteSingleValue(anchor, attributeChange);
                                continue;
                            }
                            foreach (ValueChange vc in ac.ValueChanges.Where(x => x.ModificationType == ValueModificationType.Add))
                            {
                                Tracer.TraceInformation("singlevalue-change {0}, {1}", vc.ModificationType, vc.Value);
                                methods.AddSingleValue(anchor, attributeChange, vc.Value);
                            }
                        }
                        results.CSEntryChangeResults.Add(CSEntryChangeResult.Create(exportChange.Identifier, attrchanges, MAExportError.Success));

                        if (Configuration.RunAfterObjectExport)
                        {
                            List <SqlParameter> parameters = new List <SqlParameter>();
                            parameters.Add(new SqlParameter("anchor", anchor));
                            parameters.Add(new SqlParameter("action", exportChange.ObjectModificationType.ToString()));
                            methods.RunStoredProcedure(Configuration.ExportObjectCommandAfter, parameters);
                        }
                    }
                    catch (Exception exportEx)
                    {
                        Tracer.TraceError(nameof(PutExportEntriesDetached), exportEx);
                        results.CSEntryChangeResults.Add(CSEntryChangeResult.Create(exportChange.Identifier, attrchanges, MAExportError.ExportErrorCustomContinueRun, "export-exception", exportEx.Message));
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.TraceError(nameof(PutExportEntriesDetached), ex);
                throw;
            }
            finally
            {
                Tracer.Exit(nameof(PutExportEntriesDetached));
            }
            return(results);
        }
        public PutExportEntriesResults PutExportEntries(IList <CSEntryChange> csentries)
        {
            string exportwebservicepath;
            int    i = 0;

            foreach (CSEntryChange csentryChange in csentries)
            {
                EMPLOYEE_ID = csentries[i].DN.ToString();
                if (csentryChange.ObjectType == "Person")
                {
                    #region Add
                    if (csentryChange.ObjectModificationType == ObjectModificationType.Add)
                    {
                        #region a
                        foreach (string attrib in csentryChange.ChangedAttributeNames)
                        {
                            switch (attrib)
                            {
                            case "USERNAME":
                                USERNAME = csentryChange.AttributeChanges["USERNAME"].ValueChanges[0].Value.ToString();
                                break;

                            case "PASSWORD":
                                PASSWORD = csentryChange.AttributeChanges["PASSWORD"].ValueChanges[0].Value.ToString();
                                break;

                            case "LAST_NAME":
                                LAST_NAME = csentryChange.AttributeChanges["LAST_NAME"].ValueChanges[0].Value.ToString();
                                break;

                            case "FIRST_NAME":
                                FIRST_NAME = csentryChange.AttributeChanges["FIRST_NAME"].ValueChanges[0].Value.ToString();
                                break;

                            case "EMAIL":
                                EMAIL = csentryChange.AttributeChanges["EMAIL"].ValueChanges[0].Value.ToString();
                                break;

                            case "EMPLOYEE_STATUS":
                                EMPLOYEE_STATUS = csentryChange.AttributeChanges["EMPLOYEE_STATUS"].ValueChanges[0].Value.ToString();
                                break;

                            case "ROLE_ASSIGNMENT":
                                ROLE_ASSIGNMENT = csentryChange.AttributeChanges["ROLE_ASSIGNMENT"].ValueChanges[0].Value.ToString();
                                break;

                            case "WORKPHONE":
                                WORKPHONE = csentryChange.AttributeChanges["WORKPHONE"].ValueChanges[0].Value.ToString();
                                break;
                            }
                        }
                        #endregion

                        //call the webservice to update
                        exportwebservicepath = this.exUrl; //+ "?employeeid=" + myEmpID + "&email=" + attribValue + "&accountName=" + attribValue2;
                        HttpWebRequest  request  = WebRequest.Create(exportwebservicepath) as HttpWebRequest;
                        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                    }

                    #endregion
                    #region Delete
                    if (csentryChange.ObjectModificationType == ObjectModificationType.Delete)
                    {
                        //call the webservice to update
                        exportwebservicepath = this.exUrl; //+ "?employeeid=" + myEmpID + "&email=" + attribValue + "&accountName=" + attribValue2;
                        HttpWebRequest  request  = WebRequest.Create(exportwebservicepath) as HttpWebRequest;
                        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                    }
                    #endregion

                    #region Update
                    if (csentryChange.ObjectModificationType == ObjectModificationType.Update)
                    {
                        foreach (string attribName in csentryChange.ChangedAttributeNames)
                        {
                            if (csentryChange.AttributeChanges[attribName].ModificationType == AttributeModificationType.Add)
                            {
                                EMPLOYEE_ID = csentryChange.AnchorAttributes[0].Value.ToString();
                                string attribValue = csentryChange.AttributeChanges[attribName].ValueChanges[0].Value.ToString();
                                //string cmdText = "Update" + myTable + "SET" + attribName + " = '" + attribValue + "' Where EmployeeID = '" + myEmpID + "'";
                                //cmd.CommandText = cmdText;
                                //cmd.Connection = conn;
                                //cmd.ExecuteNonQuery();


                                //call the webservice to update
                                exportwebservicepath = this.exUrl; //+ "?employeeid=" + myEmpID + "&email=" + attribValue + "&accountName=" + attribValue2;
                                HttpWebRequest  request  = WebRequest.Create(exportwebservicepath) as HttpWebRequest;
                                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                            }
                            else if (csentryChange.AttributeChanges[attribName].ModificationType == AttributeModificationType.Delete)
                            {
                                EMPLOYEE_ID = csentryChange.AnchorAttributes[0].Value.ToString();
                                //string cmdText = "Update " + myTable + " SET " + attribName + " = 'NULL' Where EmployeeID = '" + myEmpID + "'";
                                //cmd.CommandText = cmdText;
                                //cmd.Connection = conn;
                                //cmd.ExecuteNonQuery();

                                //call the webservice to update
                                exportwebservicepath = this.exUrl; //+ "?employeeid=" + myEmpID + "&email=" + attribValue + "&accountName=" + attribValue2;
                                HttpWebRequest  request  = WebRequest.Create(exportwebservicepath) as HttpWebRequest;
                                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                            }
                            else if (csentryChange.AttributeChanges[attribName].ModificationType == AttributeModificationType.Replace)
                            {
                                //EMPLOYEE_ID = csentryChange.AnchorAttributes[0].Value.ToString();
                                //string attribValue = csentryChange.AttributeChanges[attribName].ValueChanges[0].Value.ToString();
                                //string cmdText = "Update " + myTable + " SET " + attribName + " = '" + attribValue + "' Where EmployeeID = '" + myEmpID + "'";
                                //cmd.CommandText = cmdText;
                                //cmd.Connection = conn;
                                //cmd.ExecuteNonQuery();

                                //call the webservice to update
                                exportwebservicepath = this.exUrl; //+ "?employeeid=" + myEmpID + "&email=" + attribValue + "&accountName=" + attribValue2;
                                HttpWebRequest  request  = WebRequest.Create(exportwebservicepath) as HttpWebRequest;
                                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                            }
                            else if (csentryChange.AttributeChanges[attribName].ModificationType == AttributeModificationType.Update)
                            {
                                //EMPLOYEE_ID = csentryChange.AnchorAttributes[0].Value.ToString();
                                //string attribValue = csentryChange.AttributeChanges[attribName].ValueChanges[0].Value.ToString();
                                //string cmdText = "Update " + myTable + " SET " + attribName + " = '" + attribValue + "' Where EmployeeID = '" + myEmpID + "'";
                                //cmd.CommandText = cmdText;
                                //cmd.Connection = conn;
                                //cmd.ExecuteNonQuery();

                                //call the webservice to update
                                exportwebservicepath = this.exUrl; //+ "?employeeid=" + myEmpID + "&email=" + attribValue + "&accountName=" + attribValue2;
                                HttpWebRequest  request  = WebRequest.Create(exportwebservicepath) as HttpWebRequest;
                                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                            }
                        }
                    }

                    #endregion
                }

                i++;
            }



            PutExportEntriesResults exportEntriesResults = new PutExportEntriesResults();

            return(exportEntriesResults);
        }
Exemple #10
0
        public PutExportEntriesResults PutExportEntries(IList <CSEntryChange> csentries)
        {
            var results = new PutExportEntriesResults();

            foreach (var csentry in csentries)
            {
                try
                {
                    //Logger.Log.DebugFormat("Exporting csentry {0} with modificationType {1}", csentry.DN,
                    //          csentry.ObjectModificationType);

                    //Generic type will always be named the same as the csentry objecttype
                    string typeName = csentry.ObjectType;
                    IObjectSource <IExternalObject> repoContainer = _objectSources.FirstOrDefault(source => source.ObjectTypeName == typeName);

                    if (repoContainer == null)
                    {
                        throw new Exception("Couldnt find RepoContainer for type " + typeName);
                    }

                    //object entity = typeof(CsentryConverter)
                    //    .GetMethod("ConvertFromCsentry")
                    //    .MakeGenericMethod(new Type[] { repoContainer.Type })
                    //    .Invoke(null, new[] { csentry });
                    IExternalObject entity = repoContainer.CSentryConverter.ConvertFromCSentry(csentry);

                    if (entity == null)
                    {
                        string errorMsg = String.Format("Was not able to convert CSEntry to {0}",
                                                        repoContainer.ObjectTypeName);

                        throw new Exception(errorMsg);
                    }

                    switch (csentry.ObjectModificationType)
                    {
                    case ObjectModificationType.Add:
                        repoContainer.Add(entity);
                        break;

                    case ObjectModificationType.Delete:
                        repoContainer.Delete(entity);
                        break;

                    case ObjectModificationType.Replace:
                    case ObjectModificationType.Update:
                        repoContainer.Update(entity);
                        break;

                    case ObjectModificationType.Unconfigured:
                        break;

                    case ObjectModificationType.None:
                        break;
                    }
                }
                catch (Exception ex)
                {
                    var changeResult = CSEntryChangeResult.Create(csentry.Identifier, null,
                                                                  MAExportError.ExportErrorCustomContinueRun
                                                                  , "script-error", ex.ToString());
                    results.CSEntryChangeResults.Add(changeResult);
                }
            }

            return(results);
        }
Exemple #11
0
        public PutExportEntriesResults PutExportEntries(IList <CSEntryChange> csentries)
        {
            string exportwebservicepath;
            int    i = 0;

            foreach (CSEntryChange csentryChange in csentries)
            {
                email = csentries[i].DN.ToString();
                if (csentryChange.ObjectType == "Person")
                {
                    #region Add
                    if (csentryChange.ObjectModificationType == ObjectModificationType.Add)
                    {
                        #region a
                        foreach (string attrib in csentryChange.ChangedAttributeNames)
                        {
                            switch (attrib)
                            {
                            case "title":
                                title = csentryChange.AttributeChanges["title"].ValueChanges[0].Value.ToString();
                                break;

                            case "username":
                                username = csentryChange.AttributeChanges["username"].ValueChanges[0].Value.ToString();
                                break;

                            case "email":
                                email = csentryChange.AttributeChanges["email"].ValueChanges[0].Value.ToString();
                                break;

                            case "firstName":
                                firstName = csentryChange.AttributeChanges["firstName"].ValueChanges[0].Value.ToString();
                                break;

                            case "lastName":
                                lastName = csentryChange.AttributeChanges["lastName"].ValueChanges[0].Value.ToString();
                                break;

                            case "mobileNo":
                                mobileNo = csentryChange.AttributeChanges["mobileNo"].ValueChanges[0].Value.ToString();
                                break;

                            case "verifiedMobileNo":
                                verifiedMobileNo = csentryChange.AttributeChanges["verifiedMobileNo"].ValueChanges[0].Value.ToString();
                                break;

                            case "passportId":
                                passportId = csentryChange.AttributeChanges["passportId"].ValueChanges[0].Value.ToString();
                                break;

                            case "emailVerified":
                                emailVerified = csentryChange.AttributeChanges["emailVerified"].ValueChanges[0].Value.ToString();
                                break;

                            case "mobileNoVerified":
                                mobileNoVerified = csentryChange.AttributeChanges["mobileNoVerified"].ValueChanges[0].Value.ToString();
                                break;

                            case "userStore":
                                userStore = csentryChange.AttributeChanges["userStore"].ValueChanges[0].Value.ToString();
                                break;

                            case "password":
                                password = csentryChange.AttributeChanges["password"].ValueChanges[0].Value.ToString();
                                break;

                            case "ConfirmPassword":
                                password = csentryChange.AttributeChanges["confirmPassword"].ValueChanges[0].Value.ToString();
                                break;

                            case "oldPassword":
                                password = csentryChange.AttributeChanges["oldPassword"].ValueChanges[0].Value.ToString();
                                break;
                            }
                        }
                        #endregion

                        //call the webservice to update
                        exportwebservicepath = this.exUrl;

                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(exportwebservicepath);
                        request.ContentType = "application/json";
                        request.Method      = "POST";
                        // request.Headers["Authorization"] = "Bearer" +;

                        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                        {
                            string json = "{ \"email\":" + email + ", \"firstName\": " + firstName + ", \"lastName\": " + lastName + ", \"password\": " + password + "}";
                            streamWriter.Write(json);
                            streamWriter.Flush();
                            streamWriter.Close();
                        }
                        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                        using (var streamReader = new StreamReader(response.GetResponseStream()))
                        {
                            var result = streamReader.ReadToEnd();
                        }
                    }

                    #endregion
                    #region Delete
                    //if (csentryChange.ObjectModificationType == ObjectModificationType.Delete)
                    //{

                    //    //call the webservice to update
                    //    exportwebservicepath = this.exUrl; //+ "?employeeid=" + myEmpID + "&email=" + attribValue + "&accountName=" + attribValue2;
                    //    HttpWebRequest request = WebRequest.Create(exportwebservicepath) as HttpWebRequest;
                    //    HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                    //}
                    #endregion
                    #region Update
                    if (csentryChange.ObjectModificationType == ObjectModificationType.Update)
                    {
                        foreach (string attribName in csentryChange.ChangedAttributeNames)
                        {
                            if (csentryChange.AttributeChanges[attribName].ModificationType == AttributeModificationType.Update)
                            {
                                email = csentryChange.AnchorAttributes[0].Value.ToString();
                                exportwebservicepath = this.exUrl + "change-passsword";
                                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(exportwebservicepath);
                                request.ContentType = "application/json";
                                request.Method      = "POST";

                                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                                {
                                    string json = "{ \"oldPassword\":" + oldPassword + ", \"password\": " + firstName + ", \"confirmPassword\": " + confirmPassword + "}";
                                    streamWriter.Write(json);
                                    streamWriter.Flush();
                                    streamWriter.Close();
                                }
                                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                                using (var streamReader = new StreamReader(response.GetResponseStream()))
                                {
                                    var result = streamReader.ReadToEnd();
                                }
                            }
                        }
                    }

                    #endregion
                }

                i++;
            }

            PutExportEntriesResults exportEntriesResults = new PutExportEntriesResults();

            return(exportEntriesResults);
        }