private void FindContacts(Guid guid)
        {
            Guid                        selectedUser   = (Guid)ddlUsers.SelectedValue;
            List <AuditItem>            data           = new List <Model.AuditItem>();
            FetchExpression             query          = null;
            Tuple <int, string, string> selectedEntity = (Tuple <int, string, string>)ddlEntities.SelectedItem;
            string                      auditFetchXml;

            if (selectedUser == Guid.Empty)
            {
                auditFetchXml = string.Format(ConnectionDetail.OrganizationMajorVersion < 8 ?
                                              FetchXml.DeletedAuditLogs.Replace("regardingobject", "object") :
                                              FetchXml.DeletedAuditLogs,
                                              dateFrom.Value.ToString("yyyy-MM-dd"),
                                              dateTo.Value.AddDays(1).ToString("yyyy-MM-dd"),
                                              2);
            }
            else
            {
                auditFetchXml = string.Format(ConnectionDetail.OrganizationMajorVersion < 8 ?
                                              FetchXml.DeleteAuditLogsByUser.Replace("regardingobject", "object") :
                                              FetchXml.DeleteAuditLogsByUser,
                                              dateFrom.Value.ToString("yyyy-MM-dd"),
                                              dateTo.Value.AddDays(1).ToString("yyyy-MM-dd"),
                                              2,
                                              selectedUser);
            }
            query = new FetchExpression(auditFetchXml);
            var queryResult = Service.RetrieveMultiple(query);

            foreach (Entity item in queryResult.Entities)
            {
                RetrieveAuditDetailsRequest auditDetailRequest = new RetrieveAuditDetailsRequest();
                auditDetailRequest.AuditId = item.Id;
                RetrieveAuditDetailsResponse response        = (RetrieveAuditDetailsResponse)Service.Execute(auditDetailRequest);
                AttributeAuditDetail         attributeDetail = (AttributeAuditDetail)response.AuditDetail;
                EntityMetadata metadata = entityMetadataList.FirstOrDefault(x => (x.ObjectTypeCode == 2));

                AuditItem auditItem = new Model.AuditItem()
                {
                    AuditId      = item.Id,
                    DeletedBy    = ((EntityReference)item["userid"]).Name,
                    DeletionDate = (DateTime)item["createdon"],
                    Entity       = ((EntityReference)item["objectid"]).LogicalName,
                    RecordId     = ((EntityReference)item["objectid"]).Id,
                    AuditDetail  = attributeDetail,
                    Metadata     = metadata
                };

                if (selectedEntity.Item3 != null && attributeDetail.OldValue.Contains(selectedEntity.Item3))
                {
                    auditItem.Name = attributeDetail.OldValue[selectedEntity.Item3].ToString();
                }

                data.Add(auditItem);
            }
            var contact = data.First(x => x.AuditDetail.OldValue.Id == guid);

            Service.Create(contact.AuditDetail.OldValue);
        }
예제 #2
0
        public void GetAuditDetails(IOrganizationService service, EntityCollection entColl)
        {
            #region Execute Multiple with Results
            // Create an ExecuteMultipleRequest object.
            ExecuteMultipleRequest requestWithResults = new ExecuteMultipleRequest()
            {
                // Assign settings that define execution behavior: continue on error, return responses.
                Settings = new ExecuteMultipleSettings()
                {
                    ContinueOnError = false,
                    ReturnResponses = true
                },
                // Create an empty organization request collection.
                Requests = new OrganizationRequestCollection()
            };

            // Add a CreateRequest for each entity to the request collection.
            foreach (Entity ent in entColl.Entities)
            {
                var auditDetailsRequest = new RetrieveAuditDetailsRequest()
                {
                    AuditId = ent.Id
                };
                requestWithResults.Requests.Add(auditDetailsRequest);
            }

            // Execute all the requests in the request collection using a single web method call.
            ExecuteMultipleResponse AuditDetailResponses =
                (ExecuteMultipleResponse)service.Execute(requestWithResults);

            foreach (var AuditDetailResponse in AuditDetailResponses.Responses)
            {
                if (AuditDetailResponse.Response != null)
                {
                    if (((RetrieveAuditDetailsResponse)(AuditDetailResponse.Response)).Results != null)
                    {
                        if (((RetrieveAuditDetailsResponse)(AuditDetailResponse.Response)).AuditDetail != null)
                        {
                            AttributeAuditDetail AuditDetail_ = (AttributeAuditDetail)((RetrieveAuditDetailsResponse)(AuditDetailResponse.Response)).AuditDetail;
                            AuditDetailsColl.Add(AuditDetail_);
                        }
                    }
                }
                else if (AuditDetailResponse.Fault != null)
                {
                    MessageBox.Show("Exception: There was a problem in extacting the Audit History. " + AuditDetailResponse.Fault.ToString());
                }
            }
            #endregion
        }
예제 #3
0
        public AuditModel ConvertToAuditModel(Guid auditId)
        {
            var service = _d365Access.GetCrmService();

            var request = new RetrieveAuditDetailsRequest()
            {
                AuditId = auditId
            };

            var result = service.Execute(request);

            var model = _auditManagement.ConvertAuditResponseToAuditModel((RetrieveAuditDetailsResponse)result);

            return(model);
        }
        /// <summary>
        /// This is to get the audit details from CRM
        /// </summary>
        /// <param name="objectId">the object id</param>
        /// <returns>The List of Audit details</returns>
        private List <AuditDetails> GetAuditDetailsFromCRM(Guid?objectId, string entityName)
        {
            QueryExpression query = new QueryExpression("audit");

            query.ColumnSet = new ColumnSet(true);
            ConditionExpression objectTypeCheck = new ConditionExpression("objectid", ConditionOperator.Equal, objectId);
            ConditionExpression entityNameCheck = new ConditionExpression("objecttypecode", ConditionOperator.Equal, entityName);

            FilterExpression queryFilterExp = new FilterExpression(LogicalOperator.And);

            queryFilterExp.Conditions.AddRange(objectTypeCheck);
            queryFilterExp.Conditions.AddRange(entityNameCheck);
            if (searchString != null)
            {
                ConditionExpression fieldNameCheck = new ConditionExpression("objecttypecode", ConditionOperator.Equal, entityName);
                queryFilterExp.Conditions.AddRange(fieldNameCheck);
            }
            query.Criteria.AddFilter(queryFilterExp);
            query.AddOrder("createdon", OrderType.Descending);
            EntityCollection    auditDetails = this.organizationService.RetrieveMultiple(query);
            List <AuditDetails> lstDetails   = new List <AuditDetails>();

            if (auditDetails != null && auditDetails.Entities.Count > 0)
            {
                foreach (var ent in auditDetails.Entities)
                {
                    var auditDetailsRequest = new RetrieveAuditDetailsRequest
                    {
                        AuditId = ent.Id
                    };
                    var auditDetailsResponse = (RetrieveAuditDetailsResponse)this.organizationService.Execute(auditDetailsRequest);
                    //GET TABLE LABLE
                    EntityLogicalName  = auditDetailsResponse.AuditDetail.AuditRecord.GetAttributeValue <string>("objecttypecode");
                    EntityMetaResponse = getRetrieveEntityResponse(EntityLogicalName);
                    EntiryDisplayName  = EntityMetaResponse.EntityMetadata.DisplayName.LocalizedLabels[0].Label;
                    this.FetchAuditDetails(auditDetailsResponse.AuditDetail);
                }

                DataTable dtCom = this.dtcombined;
                lstDetails = ConvertDataTableToList <AuditDetails>(dtCom);
            }

            return(lstDetails);
        }
예제 #5
0
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

                    Console.WriteLine("Enabling auditing on the organization and account entities.");

                    // Enable auditing on the organization.
                    // First, get the organization's ID from the system user record.
                    Guid orgId = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).OrganizationId;

                    // Next, retrieve the organization's record.
                    var org = service.Retrieve(Organization.EntityLogicalName, orgId,
                                               new ColumnSet(new string[] { "organizationid", "isauditenabled" })) as Organization;

                    // Finally, enable auditing on the organization.
                    bool organizationAuditingFlag = org.IsAuditEnabled.Value;
                    org.IsAuditEnabled = true;
                    service.Update(org);

                    // Enable auditing on account entities.
                    bool accountAuditingFlag = EnableEntityAuditing(service, Account.EntityLogicalName, true);
                    #endregion Enable Auditing for an Account
                    #region Retrieve the Record Change History
                    Console.WriteLine("Retrieving the account change history.\n");

                    // Retrieve the audit history for the account and display it.
                    var changeRequest = new RetrieveRecordChangeHistoryRequest();
                    changeRequest.Target = new EntityReference(Account.EntityLogicalName, _newAccountId);

                    var changeResponse =
                        (RetrieveRecordChangeHistoryResponse)service.Execute(changeRequest);

                    AuditDetailCollection details = changeResponse.AuditDetailCollection;

                    foreach (AttributeAuditDetail detail in details.AuditDetails)
                    {
                        // Display some of the detail information in each audit record.
                        DisplayAuditDetails(service, detail);
                    }
                    #endregion Retrieve the Record Change History

                    #region Retrieve the Attribute Change History

                    // Update the Telephone1 attribute in the Account entity record.
                    var accountToUpdate = new Account();
                    accountToUpdate.AccountId  = _newAccountId;
                    accountToUpdate.Telephone1 = "123-555-5555";
                    service.Update(accountToUpdate);
                    Console.WriteLine("Updated the Telephone1 field in the Account entity.");

                    // Retrieve the attribute change history.
                    Console.WriteLine("Retrieving the attribute change history for Telephone1.");
                    var attributeChangeHistoryRequest = new RetrieveAttributeChangeHistoryRequest
                    {
                        Target = new EntityReference(
                            Account.EntityLogicalName, _newAccountId),
                        AttributeLogicalName = "telephone1"
                    };

                    var attributeChangeHistoryResponse =
                        (RetrieveAttributeChangeHistoryResponse)service.Execute(attributeChangeHistoryRequest);

                    // Display the attribute change history.
                    details = attributeChangeHistoryResponse.AuditDetailCollection;

                    foreach (var detail in details.AuditDetails)
                    {
                        DisplayAuditDetails(service, detail);
                    }

                    // Save an Audit record ID for later use.
                    Guid auditSampleId = details.AuditDetails.First().AuditRecord.Id;
                    #endregion Retrieve the Attribute Change History

                    #region Retrieve the Audit Details
                    Console.WriteLine("Retrieving audit details for an audit record.");

                    // Retrieve the audit details and display them.
                    var auditDetailsRequest = new RetrieveAuditDetailsRequest
                    {
                        AuditId = auditSampleId
                    };

                    var auditDetailsResponse =
                        (RetrieveAuditDetailsResponse)service.Execute(auditDetailsRequest);
                    DisplayAuditDetails(service, auditDetailsResponse.AuditDetail);

                    #endregion Retrieve the Audit Details

                    #region Revert Auditing
                    // Set the organization and account auditing flags back to the old values
                    org.IsAuditEnabled = organizationAuditingFlag;
                    service.Update(org);

                    EnableEntityAuditing(service, Account.EntityLogicalName, accountAuditingFlag);

                    #endregion Revert Auditing

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #endregion Demonstrate

                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Dynamics CRM";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
예제 #6
0
        /// <summary>
        /// This method first connects to the organization service. Next, auditing
        /// is enabled on the organization and an account entity. The account record
        /// is updated and the audit history printed out.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
            {
                // Enable early-bound type support.
                _serviceProxy.EnableProxyTypes();

                // You can access the service through the proxy, but this sample uses the interface instead.
                _service = _serviceProxy;

                #region Enable Auditing for an Account
                //<snippetAuditing1>
                Console.WriteLine("Enabling auditing on the organization and account entities.");

                // Enable auditing on the organization.
                // First, get the organization's ID from the system user record.
                Guid orgId = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).OrganizationId;

                // Next, retrieve the organization's record.
                Organization org = _service.Retrieve(Organization.EntityLogicalName, orgId,
                                                     new ColumnSet(new string[] { "organizationid", "isauditenabled" })) as Organization;

                // Finally, enable auditing on the organization.
                bool organizationAuditingFlag = org.IsAuditEnabled.Value;
                org.IsAuditEnabled = true;
                _service.Update(org);

                // Enable auditing on account entities.
                bool accountAuditingFlag = EnableEntityAuditing(Account.EntityLogicalName, true);
                //</snippetAuditing1>
                #endregion Enable Auditing for an Account

                CreateRequiredRecords();

                #region Retrieve the Record Change History
                Console.WriteLine("Retrieving the account change history.\n");
                //<snippetAuditing5>
                // Retrieve the audit history for the account and display it.
                RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();
                changeRequest.Target = new EntityReference(Account.EntityLogicalName, _newAccountId);

                RetrieveRecordChangeHistoryResponse changeResponse =
                    (RetrieveRecordChangeHistoryResponse)_service.Execute(changeRequest);

                AuditDetailCollection details = changeResponse.AuditDetailCollection;
                //</snippetAuditing5>

                foreach (AttributeAuditDetail detail in details.AuditDetails)
                {
                    // Display some of the detail information in each audit record.
                    DisplayAuditDetails(detail);
                }
                #endregion Retrieve the Record Change History

                #region Retrieve the Attribute Change History

                //<snippetAuditing7>
                // Update the Telephone1 attribute in the Account entity record.
                Account accountToUpdate = new Account();
                accountToUpdate.AccountId  = _newAccountId;
                accountToUpdate.Telephone1 = "123-555-5555";
                _serviceProxy.Update(accountToUpdate);
                Console.WriteLine("Updated the Telephone1 field in the Account entity.");

                // Retrieve the attribute change history.
                Console.WriteLine("Retrieving the attribute change history for Telephone1.");

                var attributeChangeHistoryRequest = new RetrieveAttributeChangeHistoryRequest
                {
                    Target = new EntityReference(
                        Account.EntityLogicalName, _newAccountId),
                    AttributeLogicalName = "telephone1"
                };

                var attributeChangeHistoryResponse =
                    (RetrieveAttributeChangeHistoryResponse)_service.Execute(attributeChangeHistoryRequest);

                // Display the attribute change history.
                details = attributeChangeHistoryResponse.AuditDetailCollection;
                //</snippetAuditing7>

                foreach (var detail in details.AuditDetails)
                {
                    DisplayAuditDetails(detail);
                }

                // Save an Audit record ID for later use.
                Guid auditSampleId = details.AuditDetails.First().AuditRecord.Id;
                #endregion Retrieve the Attribute Change History

                #region Retrieve the Audit Details
                //<snippetAuditing8>
                Console.WriteLine("Retrieving audit details for an audit record.");

                // Retrieve the audit details and display them.
                var auditDetailsRequest = new RetrieveAuditDetailsRequest
                {
                    AuditId = auditSampleId
                };

                var auditDetailsResponse =
                    (RetrieveAuditDetailsResponse)_service.Execute(auditDetailsRequest);
                //</snippetAuditing8>
                DisplayAuditDetails(auditDetailsResponse.AuditDetail);

                #endregion Retrieve the Audit Details

                #region Revert Auditing
                // Set the organization and account auditing flags back to the old values
                org.IsAuditEnabled = organizationAuditingFlag;
                _service.Update(org);

                EnableEntityAuditing(Account.EntityLogicalName, accountAuditingFlag);

                #endregion Revert Auditing

                DeleteRequiredRecords(promptforDelete);
            }
        }
예제 #7
0
파일: Program.cs 프로젝트: cesugden/Scripts
        /// <summary>
        /// This method first connects to the organization service. Next, auditing 
        /// is enabled on the organization and an account entity. The account record
        /// is updated and the audit history printed out.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
            {
                // Enable early-bound type support.
                _serviceProxy.EnableProxyTypes();

                // You can access the service through the proxy, but this sample uses the interface instead.
                _service = _serviceProxy;

                #region Enable Auditing for an Account
                //<snippetAuditing1>
                Console.WriteLine("Enabling auditing on the organization and account entities.");

                // Enable auditing on the organization.
                // First, get the organization's ID from the system user record.
                Guid orgId = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).OrganizationId;

                // Next, retrieve the organization's record.
                Organization org = _service.Retrieve(Organization.EntityLogicalName, orgId,
                    new ColumnSet(new string[] { "organizationid", "isauditenabled" })) as Organization;

                // Finally, enable auditing on the organization.
                bool organizationAuditingFlag = org.IsAuditEnabled.Value;
                org.IsAuditEnabled = true;
                _service.Update(org);

                // Enable auditing on account entities.
                bool accountAuditingFlag = EnableEntityAuditing(Account.EntityLogicalName, true);
                //</snippetAuditing1>
                #endregion Enable Auditing for an Account

                CreateRequiredRecords();

                #region Retrieve the Record Change History
                Console.WriteLine("Retrieving the account change history.\n");
                //<snippetAuditing5>
                // Retrieve the audit history for the account and display it.
                RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();
                changeRequest.Target = new EntityReference(Account.EntityLogicalName, _newAccountId);

                RetrieveRecordChangeHistoryResponse changeResponse =
                    (RetrieveRecordChangeHistoryResponse)_service.Execute(changeRequest);

                AuditDetailCollection details = changeResponse.AuditDetailCollection;
                //</snippetAuditing5>

                foreach (AttributeAuditDetail detail in details.AuditDetails)
                {
                    // Display some of the detail information in each audit record. 
                    DisplayAuditDetails(detail);
                }
                #endregion Retrieve the Record Change History

                #region Retrieve the Attribute Change History

                //<snippetAuditing7>
                // Update the Telephone1 attribute in the Account entity record.
                Account accountToUpdate = new Account();
                accountToUpdate.AccountId = _newAccountId;
                accountToUpdate.Telephone1 = "123-555-5555";
                _serviceProxy.Update(accountToUpdate);
                Console.WriteLine("Updated the Telephone1 field in the Account entity.");

                // Retrieve the attribute change history.
                Console.WriteLine("Retrieving the attribute change history for Telephone1.");

                var attributeChangeHistoryRequest = new RetrieveAttributeChangeHistoryRequest
                {
                    Target = new EntityReference(
                        Account.EntityLogicalName, _newAccountId),
                    AttributeLogicalName = "telephone1"
                };

                var attributeChangeHistoryResponse =
                    (RetrieveAttributeChangeHistoryResponse)_service.Execute(attributeChangeHistoryRequest);

                // Display the attribute change history.
                details = attributeChangeHistoryResponse.AuditDetailCollection;
                //</snippetAuditing7>

                foreach (var detail in details.AuditDetails)
                {
                    DisplayAuditDetails(detail);
                }

                // Save an Audit record ID for later use.
                Guid auditSampleId = details.AuditDetails.First().AuditRecord.Id;
                #endregion Retrieve the Attribute Change History

                #region Retrieve the Audit Details
                //<snippetAuditing8>
                Console.WriteLine("Retrieving audit details for an audit record.");

                // Retrieve the audit details and display them.
                var auditDetailsRequest = new RetrieveAuditDetailsRequest
                {
                    AuditId = auditSampleId
                };

                var auditDetailsResponse =
                    (RetrieveAuditDetailsResponse)_service.Execute(auditDetailsRequest);
                //</snippetAuditing8>
                DisplayAuditDetails(auditDetailsResponse.AuditDetail);

                #endregion Retrieve the Audit Details

                #region Revert Auditing
                // Set the organization and account auditing flags back to the old values
                org.IsAuditEnabled = organizationAuditingFlag;
                _service.Update(org);

                EnableEntityAuditing(Account.EntityLogicalName, accountAuditingFlag);

                #endregion Revert Auditing

                DeleteRequiredRecords(promptforDelete);
            }
        }
        /// <summary>
        /// This method first connects to the organization service. Afterwards,
        /// auditing is enabled on the organization, account entity, and a couple
        /// of attributes. Finally, display that information in Console, and creates
        /// an XML file.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            _sampleStartTime = DateTime.Now;
            using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
            {
                // This statement is required to enable early-bound type support.
                _serviceProxy.EnableProxyTypes();

                // You can access the service through the proxy, but this sample uses the interface instead.
                _service = _serviceProxy;

                #region Enable Auditing for an Account

                Console.WriteLine("Enabling auditing on the organization and account entities.");

                // Enable auditing on the organization.
                // First, get the organization's ID from the system user record.
                Guid orgId = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).OrganizationId;

                // Next, retrieve the organization's record.
                Organization org = _service.Retrieve(Organization.EntityLogicalName, orgId,
                                                     new ColumnSet(new string[] { "organizationid", "isauditenabled" })) as Organization;

                // Finally, enable auditing on the organization.
                bool organizationAuditingFlag = org.IsAuditEnabled.Value;
                bool usersAccessAuditingFlag  = org.IsUserAccessAuditEnabled.HasValue ?
                                                org.IsUserAccessAuditEnabled.Value : false;

                org.IsAuditEnabled           = true;
                org.IsUserAccessAuditEnabled = true;
                _service.Update(org);

                // Enable auditing on account entities.
                bool accountAuditingFlag = EnableEntityAuditing(Account.EntityLogicalName, true);

                #endregion Enable Auditing for an Account

                CreateRequiredRecords();

                #region Create and start XML file

                // Create the XML file
                String fileName = "auditReport.xml";
                textWriter = new XmlTextWriter(fileName, null);
                textWriter.WriteStartDocument();

                // Start Audit Node
                textWriter.WriteStartElement("auditReport", "");

                #endregion

                #region Retrive user access audit records

                var query = new QueryExpression(Audit.EntityLogicalName)
                {
                    ColumnSet = new ColumnSet("createdon", "action", "operation", "objectid"),
                    Criteria  = new FilterExpression(LogicalOperator.And)
                };

                // Only retrieve audit records that track user access.
                query.Criteria.AddCondition("action", ConditionOperator.In,
                                            (int)AuditAction.UserAccessAuditStarted,
                                            (int)AuditAction.UserAccessAuditStopped,
                                            (int)AuditAction.UserAccessviaWebServices,
                                            (int)AuditAction.UserAccessviaWeb);

                // Change this to false in order to retrieve audit records for all users
                // when running the sample.
                var filterAuditsRetrievedByUser = true;
                if (filterAuditsRetrievedByUser)
                {
                    // Only retrieve audit records for the current user.
                    var userFilter = new FilterExpression(LogicalOperator.Or);
                    userFilter.AddCondition(
                        "userid", ConditionOperator.Equal, _serviceProxy.CallerId);
                }
                // Only retrieve records for this sample run, so that we don't get too
                // many results if auditing was enabled previously.
                query.Criteria.AddCondition(
                    "createdon", ConditionOperator.GreaterEqual, _sampleStartTime);

                var results = _serviceProxy.RetrieveMultiple(query);
                foreach (Audit audit in results.Entities)
                {
                    // Display results
                    DisplayAndAddToXMLFileUserAccessDetails(audit);
                }

                #endregion

                #region Retrieve the Audit History
                Console.WriteLine("Retrieving the account change history.\n");

                DateTime startTime = DateTime.Now;

                // Retrieve the audit records for accounts.
                RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();
                changeRequest.Target = new EntityReference(Account.EntityLogicalName, _newAccountId);

                RetrieveRecordChangeHistoryResponse changeResponse =
                    (RetrieveRecordChangeHistoryResponse)_service.Execute(changeRequest);

                AuditDetailCollection details = changeResponse.AuditDetailCollection;

                foreach (AttributeAuditDetail detail in details.AuditDetails)
                {
                    // Write out some of the information in each audit record.
                    DisplayAndAddToXMLFileAuditDetails(detail);
                }
                #endregion Retrieve the Audit History

                #region RetrieveAttributeChangeHistoryRequest
                // How to use message: RetrieveAttributeChangeHistoryRequest

                // Update Telephone1 in account entity
                Account accountToUpdate = new Account();
                accountToUpdate.AccountId  = _newAccountId;
                accountToUpdate.Telephone1 = "123-555-5555";
                _serviceProxy.Update(accountToUpdate);
                Console.WriteLine("Updated Telephone1 field in Account entity.");

                Console.WriteLine("Retrieving attribute change history for Telephone1.");
                // Create RetrieveAttributeChangeHistoryRequest
                var attributeChangeHistoryRequest = new RetrieveAttributeChangeHistoryRequest
                {
                    Target = new EntityReference(
                        Account.EntityLogicalName, _newAccountId),
                    AttributeLogicalName = "telephone1"
                };

                // Execute RetrieveAttributeChangeHistoryRequest
                var attributeChangeHistoryResponse =
                    (RetrieveAttributeChangeHistoryResponse)_service.Execute(attributeChangeHistoryRequest);

                // Set AuditDetailCollection and output to console
                details = attributeChangeHistoryResponse.AuditDetailCollection;

                foreach (var detail in details.AuditDetails)
                {
                    DisplayAndAddToXMLFileAuditDetails(detail);
                }

                // Create an Audit record
                // to store a sample for use with RetrieveAuditDetailsRequest
                Guid auditSampleId = details.AuditDetails.First().AuditRecord.Id;
                #endregion RetrieveAttributeChangeHistoryRequest

                #region RetrieveAuditDetailsRequest
                // How to use message: RetrieveAuditDetailsRequest

                Console.WriteLine("Retrieving audit details for an audit record.");
                // Create RetrieveAuditDetailsRequest
                var auditDetailsRequest = new RetrieveAuditDetailsRequest
                {
                    AuditId = auditSampleId
                };

                // Execute RetrieveAuditDetailsRequest
                var auditDetailsResponse =
                    (RetrieveAuditDetailsResponse)_service.Execute(auditDetailsRequest);

                // Display results
                DisplayAndAddToXMLFileAuditDetails(auditDetailsResponse.AuditDetail);

                #endregion RetrieveAuditDetailsRequest

                #region Retrieve AuditExtension details

                Console.WriteLine("Simulating a user reading records");
                _service.Retrieve(Account.EntityLogicalName, _newAccountId, new ColumnSet("accountid"));

                // creating read records is an async process - wait until the records have been created
                // wait a max of 30 seconds
                Console.WriteLine("Fetching read audit records for accounts");
                for (int i = 0; i < 30; i++)
                {
                    query = new QueryExpression
                    {
                        EntityName = "sample_auditextension",
                        ColumnSet  = new ColumnSet("createdon", "sample_objectlogicalname",
                                                   "sample_objectid", "sample_userid", "sample_action", "sample_operation"),
                        Criteria = new FilterExpression
                        {
                            Conditions =
                            {
                                new ConditionExpression("sample_objectlogicalname", ConditionOperator.Equal, Account.EntityLogicalName),
                                new ConditionExpression("sample_objectid",          ConditionOperator.Equal,
                                                        _newAccountId.ToString().TrimStart('{').TrimEnd('}'))
                            }
                        }
                    };
                    results = _service.RetrieveMultiple(query);
                    if (results.Entities.Count > 0)
                    {
                        break;
                    }
                    else if (i == 29)
                    {
                        throw new Exception("Exceeded maximum wait time");
                    }
                    System.Threading.Thread.Sleep(1000);
                }

                foreach (var record in results.Entities)
                {
                    _auditExtensionRecordIds.Add(record.Id);
                    DisplayAndAddToXmlFileAuditExtension(record);
                }

                #endregion

                #region Finish and close XML file

                // End auditReport Xml Node
                textWriter.WriteEndElement();
                textWriter.WriteEndDocument();

                // Close xml writer.
                textWriter.Close();

                Console.WriteLine("File name: " + fileName);

                #endregion

                #region Revert auditing
                // Set the organization and account auditing flags back to the old values
                org.IsAuditEnabled           = organizationAuditingFlag;
                org.IsUserAccessAuditEnabled = usersAccessAuditingFlag;
                _service.Update(org);

                EnableEntityAuditing(Account.EntityLogicalName, accountAuditingFlag);

                #endregion Revert auditing

                DeleteRequiredRecords(promptforDelete);
            }
        }
        /// <summary>
        /// Handles the Click event of the btnShowRecords control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void btnShowRecords_Click(object sender, EventArgs e)
        {
            if (IsValid())
            {
                WorkAsync(new WorkAsyncInfo
                {
                    Message = "Loading deleted records...",
                    Work    = (w, ev) =>
                    {
                        Guid selectedUser     = (Guid)ddlUsers.SelectedValue;
                        List <AuditItem> data = new List <Model.AuditItem>();
                        FetchExpression query = null;
                        Tuple <int, string, string> selectedEntity = (Tuple <int, string, string>)ddlEntities.SelectedItem;
                        string auditFetchXml;
                        if (selectedUser == Guid.Empty)
                        {
                            auditFetchXml = string.Format(ConnectionDetail.OrganizationMajorVersion < 8 ?
                                                          FetchXml.DeletedAuditLogs.Replace("regardingobject", "object") :
                                                          FetchXml.DeletedAuditLogs,
                                                          dateFrom.Value.ToString("yyyy-MM-dd"),
                                                          dateTo.Value.AddDays(1).ToString("yyyy-MM-dd"),
                                                          ddlEntities.SelectedValue);
                        }
                        else
                        {
                            auditFetchXml = string.Format(ConnectionDetail.OrganizationMajorVersion < 8 ?
                                                          FetchXml.DeleteAuditLogsByUser.Replace("regardingobject", "object") :
                                                          FetchXml.DeleteAuditLogsByUser,
                                                          dateFrom.Value.ToString("yyyy-MM-dd"),
                                                          dateTo.Value.AddDays(1).ToString("yyyy-MM-dd"),
                                                          ddlEntities.SelectedValue,
                                                          selectedUser);
                        }
                        query           = new FetchExpression(auditFetchXml);
                        var queryResult = Service.RetrieveMultiple(query);
                        foreach (Entity item in queryResult.Entities)
                        {
                            RetrieveAuditDetailsRequest auditDetailRequest = new RetrieveAuditDetailsRequest();
                            auditDetailRequest.AuditId            = item.Id;
                            RetrieveAuditDetailsResponse response = (RetrieveAuditDetailsResponse)Service.Execute(auditDetailRequest);
                            AttributeAuditDetail attributeDetail  = (AttributeAuditDetail)response.AuditDetail;
                            EntityMetadata metadata = entityMetadataList.FirstOrDefault(x => (x.ObjectTypeCode == selectedEntity.Item1));
                            AuditItem auditItem     = new Model.AuditItem()
                            {
                                AuditId      = item.Id,
                                DeletedBy    = ((EntityReference)item["userid"]).Name,
                                DeletionDate = (DateTime)item["createdon"],
                                Entity       = ((EntityReference)item["objectid"]).LogicalName,
                                RecordId     = ((EntityReference)item["objectid"]).Id,
                                AuditDetail  = attributeDetail,
                                Metadata     = metadata
                            };

                            if (selectedEntity.Item3 != null && attributeDetail.OldValue.Contains(selectedEntity.Item3))
                            {
                                auditItem.Name = attributeDetail.OldValue[selectedEntity.Item3].ToString();
                            }

                            data.Add(auditItem);
                        }

                        ev.Result = data.OrderByDescending(x => x.DeletionDate).ToList();
                    },
                    ProgressChanged = ev =>
                    {
                        // If progress has to be notified to user, use the following method:
                        SetWorkingMessage("Loading entities with auditing enabled...");
                    },
                    PostWorkCallBack = ev =>
                    {
                        GridDeletedRecords.DataSource = ev.Result;
                    },
                    AsyncArgument = null,
                    IsCancelable  = true,
                    MessageWidth  = 340,
                    MessageHeight = 150
                });
            }
        }
        public void RetreiveAndSet(IConfiguration config, IJobTime job, Imapping mapping, IDwService dw)
        {
            int?duplicates            = null;
            var maxRecordsPerExcution = int.Parse(config.Get("MaxRecordsPerExcution").ToString());
            var languageCode          = int.Parse(config.Get("LanguageCode").ToString());
            var untilDate             = config.Get("UntilDate").ToString();
            var isRemoveDuplicate     = config.Get("IsRemoveDuplicate").ToString();

            var last  = DateTime.UtcNow;
            var first = job.RetrieveLastDateJob(config);

            if (!String.IsNullOrWhiteSpace(untilDate))
            {
                last = DateTime.ParseExact(untilDate, "yyyy-MM-dd", null);
            }

            int pageNumber = 1; int crmLogsItemsCount = 0; int fieldsChangeCount = 0;

            List <AuditLogModel> audtLogs;
            bool moreRecords = true;

            do
            {
                audtLogs = new List <AuditLogModel>();
                audtLogs.Clear();
                var rmr  = new RetrieveMultipleRequest();
                var resp = new RetrieveMultipleResponse();

                QueryExpression query = new QueryExpression()
                {
                    EntityName = "audit",
                    ColumnSet  = new ColumnSet(true),
                    Criteria   = new FilterExpression
                    {
                        FilterOperator = LogicalOperator.And,
                        Conditions     = { new ConditionExpression
                                           {
                                               AttributeName = "createdon",
                                               Operator      = ConditionOperator.Between,
                                               Values        = { first, last } //access
                                           } },
                    },
                    Orders = { new OrderExpression
                               {
                                   AttributeName = "createdon",
                                   OrderType     = OrderType.Ascending
                               } }
                };

                query.PageInfo = new PagingInfo
                {
                    PageNumber = pageNumber,
                    Count      = maxRecordsPerExcution
                };
                rmr.Query = query;
                resp      = (RetrieveMultipleResponse)_service.Execute(rmr);
                foreach (Entity entiyAuditLog in resp.EntityCollection.Entities)
                {
                    crmLogsItemsCount++;
                    Console.WriteLine(entiyAuditLog.Id);
                    // Retrieve the audit details and display them.
                    var auditDetailsRequest = new RetrieveAuditDetailsRequest {
                        AuditId = entiyAuditLog.Id
                    };

                    var auditDetailsResponse = (RetrieveAuditDetailsResponse)_service.Execute(auditDetailsRequest);

                    var changes = mapping.ToDwItems(_service, auditDetailsResponse.AuditDetail, languageCode, job);
                    if (changes.Any())
                    {
                        audtLogs.AddRange(changes);
                        fieldsChangeCount += changes.Count();
                    }
                }
                moreRecords = resp.EntityCollection.MoreRecords;
                if (moreRecords)
                {
                    pageNumber++;
                }
                dw.BulkAdd(audtLogs);
            }while (moreRecords);
            if (isRemoveDuplicate == "1")
            {
                try
                {
                    duplicates = dw.RemoveDuplicate();
                }
                catch (Exception e)
                {
                    _log("WARNING:can not remove duplicate see log");
                    _log(e.ToString());
                }
            }
            job.UpdateEndDateOnComplete(fieldsChangeCount, crmLogsItemsCount, duplicates, last);
        }