Exemple #1
0
        public static void ExtractFromAudit()
        {
            IOrganizationService service = MSCRM.GetOrgService(true);

            // The GUID of the object you want to retirve in this case i am passing contactid
            var entityId = new Guid("B53045DC-8BF1-E411-80D0-005056A60603");

            Console.WriteLine("Retrieving the change history.\n");

            //
            //RetrieveAttributeChangeHistoryRequest req = new RetrieveAttributeChangeHistoryRequest();
            //req.Target = new Microsoft.Xrm.Sdk.EntityReference("quote", new Guid("592AF7E6-ADC1-E011-8D7C-1CC1DE79838E"));
            //req.AttributeLogicalName = "totallineitemamount";
            //RetrieveAttributeChangeHistoryResponse resp = (RetrieveAttributeChangeHistoryResponse)service.Execute(req);



            // Retrieve the audit history for the account and display it.
            RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();

            changeRequest.Target = new Microsoft.Xrm.Sdk.EntityReference("quote", entityId);



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

            AuditDetailCollection details = changeResponse.AuditDetailCollection;

            foreach (AttributeAuditDetail detail in details.AuditDetails)
            {
                DisplayAuditDetails(detail);
                // Display some of the detail information in each audit record.
            }
        }
Exemple #2
0
        /// <summary>
        /// Extract the audit history for the record and a specific Field
        /// </summary>
        /// <param name="entityID">ID of the Account</param>
        /// <param name="identificatorField">Identificator of the Row</param>
        /// <param name="attributeName">Name of the attribute to retrieve for Audit History</param>
        /// <param name="fileName">File to write</param>
        public List <AuditHistory> GetAuditHistoryForRecordAndField(Guid entityID, string entityLogicalName, string attributeName, string recordKeyValue)
        {
            List <AuditHistory> auditHistoryForRecord = new List <AuditHistory>();
            var attributeChangeHistoryRequest         = new RetrieveAttributeChangeHistoryRequest
            {
                Target = new EntityReference(entityLogicalName, entityID),
                AttributeLogicalName = attributeName,
            };

            RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();

            changeRequest.Target = new EntityReference(entityLogicalName, entityID);

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

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

            details = attributeChangeHistoryResponse.AuditDetailCollection;

            foreach (var detail in details.AuditDetails)
            {
                //AuditHistory change = GetRecordChanges(detail);

                auditHistoryForRecord.AddRange(GetRecordChanges(detail, recordKeyValue));
                //if (change != null)
                //{
                //    change.RecordKeyValue = recordKeyValue;
                //    auditHistoryForRecord.Add(change);
                //}
            }
            return(auditHistoryForRecord);
        }
        public List <AuditHistory> GetAuditHistoryForRecord(Guid entityID, string entityLogicalName, string recordKeyValue
                                                            //,ref List<Log> logs
                                                            )
        {
            List <AuditHistory> auditHistoryForRecord        = new List <AuditHistory>();
            RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();

            changeRequest.Target = new EntityReference(entityLogicalName, entityID);

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

            foreach (AuditDetail detail in details.AuditDetails)
            {
                List <AuditHistory> records = GetRecordChanges(detail, recordKeyValue);
                auditHistoryForRecord.AddRange(records);


                //if (logs.Contains(new Log() { recordId = entityID }))
                //{
                //    logs.Find(x => x.recordId.Equals(entityID)).AddNumberOfChanges(records.Count);
                //}
                //else
                //{
                //    Log logRecord = new Log() { recordId = entityID, RecordKeyValue = recordKeyValue, NumberOfChanges = records.Count };

                //    logs.Add(logRecord);
                //}
            }
            return(auditHistoryForRecord);
        }
        public void retrieveAuditData()
        {
            IOrganizationService service = CRMHelper.ConnectToMSCRM();
            // Retrieve the audit history for the account and display it.
            RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();

            changeRequest.Target = new EntityReference("account", new Guid("A9B96053-43B1-E111-A892-1CC1DEEAE7D7"));

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

            AuditDetailCollection details = changeResponse.AuditDetailCollection;
        }
        private void RetrieveRecordChangeHistory()
        {
            this.LogMessage(LogType.Info, "Retrieveing for {0}", this.EntityId);

            // Retrieve the audit history for the account and display it.
            RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();

            changeRequest.Target = new EntityReference(this.EntityName, this.EntityId);

            RetrieveRecordChangeHistoryResponse changeResponse =
                (RetrieveRecordChangeHistoryResponse)this.OrgService.Execute(changeRequest);

            this.auditCollection = changeResponse.AuditDetailCollection;
        }
        public List <AuditHistory> GetAuditHistoryForRecord(Guid entityID, string entityLogicalName, string recordKeyValue)
        {
            List <AuditHistory> auditHistoryForRecord        = new List <AuditHistory>();
            RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();

            changeRequest.Target = new EntityReference(entityLogicalName, entityID);

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

            foreach (AuditDetail detail in details.AuditDetails)
            {
                auditHistoryForRecord.AddRange(GetRecordChanges(detail, recordKeyValue));
            }
            return(auditHistoryForRecord);
        }
Exemple #7
0
        public List <AuditHistory> RetrieveRecordChangeHistory(EntityReference target)
        {
            AuditHistoryManager manager = new AuditHistoryManager(crmseviceClient);
            List <AuditHistory> auditHistoryForRecord        = new List <AuditHistory>();
            RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();

            changeRequest.Target = target;
            //new EntityReference("account", new Guid("b1f68180-4c5a-eb11-bb23-000d3a0a74cb"));
            RetrieveRecordChangeHistoryResponse changeResponse = (RetrieveRecordChangeHistoryResponse)crmseviceClient.Execute(changeRequest);
            AuditDetailCollection details = changeResponse.AuditDetailCollection;

            foreach (AuditDetail detail in details.AuditDetails)
            {
                List <AuditHistory> records = manager.GetRecordChanges(detail);
                auditHistoryForRecord.AddRange(records);
            }
            return(auditHistoryForRecord);
        }
        public DateTime CheckLastLoginDate(IOrganizationService service, Guid systemUserId)
        {
            try
            {
                // Retrieve the audit history for the account and display it.
                RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();
                changeRequest.Target = new EntityReference("systemuser", systemUserId);

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

                AuditDetailCollection details = changeResponse.AuditDetailCollection;

                var auditRecords = details.AuditDetails;

                for (int i = 0; i < auditRecords.Count; i++)
                {
                    // READ: https://docs.microsoft.com/en-us/dynamics365/customer-engagement/web-api/audit?view=dynamics-ce-odata-9#see-also
                    // 64 = "User Access via Web"
                    // 65 = "User Access via Web Services"

                    var auditActionType = auditRecords[i].AuditRecord.GetAttributeValue <OptionSetValue>("action").Value;
                    var auditCreatedOn  = auditRecords[i].AuditRecord.GetAttributeValue <DateTime>("createdon").ToLocalTime();

                    if ((auditActionType == 64 || auditActionType == 65) && auditCreatedOn > DateTime.Today.AddMonths(-6))
                    {
                        return(auditCreatedOn);
                    }
                }
                return(new DateTime(1900, 01, 01));
                // EVT: https://docs.microsoft.com/en-us/dynamics365/customerengagement/on-premises/developer/sample-disable-user
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #9
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);
            }
        }
        /// <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);
            }
        }
        protected DataTable BuildDataTable(CodeActivityContext context, IWorkflowContext workflowContext, IOrganizationService service)
        {
            TimeZoneSummary timeZone = StaticMethods.CalculateTimeZoneToUse(this.TimeZoneOption.Get(context), workflowContext, service);

            DataTable table = new DataTable()
            {
                TableName = workflowContext.PrimaryEntityName
            };

            table.Columns.AddRange(new DataColumn[] { new DataColumn("Date"), new DataColumn("User"), new DataColumn("Attribute"), new DataColumn("Old Value"), new DataColumn("New Value") });
            DateTime oldestUpdate = DateTime.MinValue;

            if (this.Units != null && this.Number != null && this.Number.Get <int>(context) != 0)
            {
                OptionSetValue value = this.Units.Get <OptionSetValue>(context);
                if (value != null)
                {
                    switch (value.Value)
                    {
                    case 222540000:
                        oldestUpdate = DateTime.Now.AddYears(this.Number.Get <int>(context) * -1);
                        break;

                    case 222540001:
                        oldestUpdate = DateTime.Now.AddMonths(this.Number.Get <int>(context) * -1);
                        break;

                    case 222540002:
                        oldestUpdate = DateTime.Now.AddDays(this.Number.Get <int>(context) * -7);
                        break;

                    case 222540003:
                        oldestUpdate = DateTime.Now.AddDays(this.Number.Get <int>(context) * -1);
                        break;

                    case 222540004:
                        oldestUpdate = DateTime.Now.AddHours(this.Number.Get <int>(context) * -1);
                        break;

                    default:
                        oldestUpdate = DateTime.Now.AddMinutes(this.Number.Get <int>(context) * -1);
                        break;
                    }
                }
            }

            RetrieveRecordChangeHistoryRequest request = new RetrieveRecordChangeHistoryRequest()
            {
                Target     = new EntityReference(workflowContext.PrimaryEntityName, workflowContext.PrimaryEntityId),
                PagingInfo = new PagingInfo()
                {
                    Count = 100, PageNumber = 1
                }
            };
            RetrieveRecordChangeHistoryResponse response = service.Execute(request) as RetrieveRecordChangeHistoryResponse;
            var detailsToInclude = response.AuditDetailCollection.AuditDetails
                                   .Where(ad => ad is AttributeAuditDetail && ad.AuditRecord.Contains("createdon") && ((DateTime)ad.AuditRecord["createdon"]) > oldestUpdate)
                                   .OrderByDescending(ad => ((DateTime)ad.AuditRecord["createdon"]))
                                   .ToList();

            if (detailsToInclude.Any())
            {
                Microsoft.Xrm.Sdk.Messages.RetrieveEntityRequest retrieveEntityRequest = new Microsoft.Xrm.Sdk.Messages.RetrieveEntityRequest()
                {
                    EntityFilters = EntityFilters.Attributes,
                    LogicalName   = workflowContext.PrimaryEntityName
                };
                Microsoft.Xrm.Sdk.Messages.RetrieveEntityResponse retrieveEntityResponse = service.Execute(retrieveEntityRequest) as Microsoft.Xrm.Sdk.Messages.RetrieveEntityResponse;
                EntityMetadata metadata = retrieveEntityResponse.EntityMetadata;

                foreach (var detail in detailsToInclude.Select(d => d as AttributeAuditDetail).Where(d => d.NewValue != null && d.OldValue != null))
                {
                    DateTime dateToModify = (DateTime)detail.AuditRecord["createdon"];
                    if (dateToModify.Kind != DateTimeKind.Utc)
                    {
                        dateToModify = dateToModify.ToUniversalTime();
                    }


                    LocalTimeFromUtcTimeRequest timeZoneChangeRequest = new LocalTimeFromUtcTimeRequest()
                    {
                        UtcTime = dateToModify, TimeZoneCode = timeZone.MicrosoftIndex
                    };
                    LocalTimeFromUtcTimeResponse timeZoneResponse = service.Execute(timeZoneChangeRequest) as LocalTimeFromUtcTimeResponse;
                    DateTime timeZoneSpecificDateTime             = timeZoneResponse.LocalTime;

                    var details = detail.NewValue.Attributes.Keys.Union(detail.OldValue.Attributes.Keys)
                                  .Distinct()
                                  .Select(a =>
                                          new {
                        AttributeName = a,
                        DisplayName   = GetDisplayLabel(metadata, a)
                    })
                                  .OrderBy(a => a.DisplayName);

                    foreach (var item in details)
                    {
                        DataRow newRow = table.NewRow();
                        newRow["User"]      = GetDisplayValue(detail.AuditRecord, "userid");
                        newRow["Date"]      = timeZoneSpecificDateTime.ToString("MM/dd/yyyy h:mm tt");
                        newRow["Attribute"] = item.DisplayName;
                        newRow["Old Value"] = GetDisplayValue(detail.OldValue, item.AttributeName);
                        newRow["New Value"] = GetDisplayValue(detail.NewValue, item.AttributeName);
                        table.Rows.Add(newRow);
                    }
                }
            }
            return(table);
        }
Exemple #12
0
        static void Main(string[] args)
        {
            //OrganizationServiceProxy serviceProxy = ConnectHelper.CrmService;
            //var service = (IOrganizationService)serviceProxy;
            //serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

            IOrganizationService organizationService = null;

            try
            {
                ClientCredentials clientCredentials = new ClientCredentials();
                clientCredentials.UserName.UserName = "******";
                clientCredentials.UserName.Password = "******";

                organizationService = (IOrganizationService) new OrganizationServiceProxy(new Uri("https://udstrialsdemo40.api.crm4.dynamics.com/XRMServices/2011/Organization.svc"),
                                                                                          null, clientCredentials, null);

                RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();
                changeRequest.Target = new EntityReference("account", new Guid("{B0B2DD8A-F30D-EB11-A813-000D3A666701}"));

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

                AuditDetailCollection details = changeResponse.AuditDetailCollection;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }



            #region Task14Testing

            //            TempRepository tempRepository = new TempRepository(service);
            //            var vo = tempRepository.GetVoMainScriptRecors().Entities;
            //            foreach (var item in vo)
            //            {
            //                Console.WriteLine(item.Id+" "+item.Attributes["new_name"]);
            //            }
            //            var entity = vo[0];
            //            var name = entity.LogicalName;
            //            var id = entity.Id;

            //            string path = @"D:\C# Junior собеседование\UDS Consulting (стажировка)\Developer Education\ЛК1.docx";
            //            string fileAsString = GetBase64StringFromFile(path);
            //            string fileName = Path.GetFileName(path);
            //            string mimeType = MimeMapping.GetMimeMapping(fileName);

            //            Entity Note = new Entity("annotation");
            //            Note["objectid"] = new EntityReference(name, id);
            //            Note["objecttypecode"] = name;
            //            Note["subject"] = "Test Subject";
            //            Note["notetext"] = "Test note text";

            //            Note["documentbody"] = fileAsString;
            //            Note["mimetype"] = mimeType;
            //            Note["filename"] = fileName;

            //            service.Create(Note);
            #endregion

            Console.ReadLine();
        }
        protected DataTable BuildDataTable(CodeActivityContext context, IWorkflowContext workflowContext, IOrganizationService service)
        {
            DataTable table = new DataTable()
            {
                TableName = workflowContext.PrimaryEntityName
            };

            table.Columns.AddRange(new DataColumn[] { new DataColumn("Attribute"), new DataColumn("Old Value"), new DataColumn("New Value") });

            RetrieveRecordChangeHistoryRequest request = new RetrieveRecordChangeHistoryRequest()
            {
                Target     = new EntityReference(workflowContext.PrimaryEntityName, workflowContext.PrimaryEntityId),
                PagingInfo = new PagingInfo()
                {
                    Count = 100, PageNumber = 1
                }
            };
            RetrieveRecordChangeHistoryResponse response = service.Execute(request) as RetrieveRecordChangeHistoryResponse;

            if (response != null && response.AuditDetailCollection.Count > 0)
            {
                string onlyIfField          = LastUpdateWithThisField.Get(context);
                AttributeAuditDetail detail = null;
                for (int i = 0; i < response.AuditDetailCollection.Count; i++)
                {
                    AttributeAuditDetail thisDetail = response.AuditDetailCollection[i] as AttributeAuditDetail;
                    if (thisDetail != null && (String.IsNullOrEmpty(onlyIfField) ||
                                               (thisDetail.OldValue.Attributes.Keys.Contains(onlyIfField) ||
                                                thisDetail.NewValue.Attributes.Keys.Contains(onlyIfField))))
                    {
                        detail = thisDetail;
                        break;
                    }
                }

                if (detail != null && detail.NewValue != null && detail.OldValue != null)
                {
                    Microsoft.Xrm.Sdk.Messages.RetrieveEntityRequest retrieveEntityRequest = new Microsoft.Xrm.Sdk.Messages.RetrieveEntityRequest()
                    {
                        EntityFilters = EntityFilters.Attributes,
                        LogicalName   = workflowContext.PrimaryEntityName
                    };
                    Microsoft.Xrm.Sdk.Messages.RetrieveEntityResponse retrieveEntityResponse = service.Execute(retrieveEntityRequest) as Microsoft.Xrm.Sdk.Messages.RetrieveEntityResponse;
                    EntityMetadata metadata = retrieveEntityResponse.EntityMetadata;

                    var details = detail.NewValue.Attributes.Keys.Union(detail.OldValue.Attributes.Keys)
                                  .Distinct()
                                  .Select(a => new
                    {
                        AttributeName = a,
                        DisplayName   = this.GetDisplayLabel(metadata, a),
                        OldValue      = String.Empty,
                        NewValue      = String.Empty
                    })
                                  .OrderBy(a => a.DisplayName);

                    foreach (var item in details)
                    {
                        DataRow newRow = table.NewRow();
                        newRow["Attribute"] = item.DisplayName;
                        newRow["Old Value"] = GetDisplayValue(detail.OldValue, item.AttributeName);
                        newRow["New Value"] = GetDisplayValue(detail.NewValue, item.AttributeName);
                        table.Rows.Add(newRow);
                    }
                }
            }
            return(table);
        }
Exemple #14
0
        private void LoadAuditHistoryLogic()
        {
            if (Service != null)
            {
                RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();
                try
                {
                    Guid guid = TrimGuid(recordGuid.Text);

                    changeRequest.Target = new EntityReference(entitiesList.SelectedItem.ToString(), guid);
                    RetrieveRecordChangeHistoryResponse changeResponse =
                        (RetrieveRecordChangeHistoryResponse)Service.Execute(changeRequest);

                    AuditDetailCollection auditDetailCollection = changeResponse.AuditDetailCollection;

                    Entity entity = Service.Retrieve(entitiesList.SelectedItem.ToString(), guid, new ColumnSet(true));
                    TargetEntity = new Entity(entity.LogicalName, entity.Id);

                    foreach (var attrAuditDetail in auditDetailCollection.AuditDetails)
                    {
                        var detailType = attrAuditDetail.GetType();
                        if (detailType == typeof(AttributeAuditDetail))
                        {
                            var auditRecord     = attrAuditDetail.AuditRecord;
                            var attributeDetail = (AttributeAuditDetail)attrAuditDetail;

                            var newValueEntity = attributeDetail.NewValue;
                            var oldValueEntity = attributeDetail.OldValue;

                            var action = auditRecord.FormattedValues["action"];
                            if (Array.Exists(ValidActions, x => x == action))
                            {
                                foreach (KeyValuePair <String, object> attribute in attributeDetail.NewValue.Attributes)
                                {
                                    string fieldmetadata = "";
                                    string lookupId      = "";
                                    string oldValue      = "";
                                    string newValue      = "";

                                    if (attributeDetail.OldValue.Contains(attribute.Key))
                                    {
                                        lookupId      = GetLookupId(attribute.Key, attribute.Value, oldValueEntity, attribute.Key);
                                        fieldmetadata = GetFieldMetaData(attribute.Key, attribute.Value, oldValueEntity, attribute.Key);
                                        oldValue      = GetFieldValue(attribute.Key, attribute.Value, oldValueEntity, oldValueEntity[attribute.Key].ToString());
                                    }
                                    newValue = GetFieldValue(attribute.Key, attribute.Value, newValueEntity, newValueEntity[attribute.Key].ToString());

                                    CreateAuditRecord(auditRecord.Attributes["auditid"], auditRecord.Attributes["createdon"], ((EntityReference)auditRecord.Attributes["userid"]).Name,
                                                      auditRecord.FormattedValues["action"], attribute.Key, oldValue, newValue, attribute.Value, fieldmetadata, lookupId);
                                }

                                foreach (KeyValuePair <String, object> attribute in attributeDetail.OldValue.Attributes)
                                {
                                    if (!attributeDetail.NewValue.Contains(attribute.Key))
                                    {
                                        string fieldmetadata = "";
                                        string loookupId     = "";
                                        string newValue      = "";

                                        loookupId     = GetLookupId(attribute.Key, attribute.Value, oldValueEntity, attribute.Key);
                                        fieldmetadata = GetFieldMetaData(attribute.Key, attribute.Value, oldValueEntity, attribute.Key);
                                        string oldValue = GetFieldValue(attribute.Key, attribute.Value, oldValueEntity, oldValueEntity[attribute.Key].ToString());

                                        CreateAuditRecord(auditRecord.Attributes["auditid"], auditRecord.Attributes["createdon"], ((EntityReference)auditRecord.Attributes["userid"]).Name,
                                                          auditRecord.FormattedValues["action"], attribute.Key, oldValue, newValue, attribute.Value, fieldmetadata, loookupId);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (InvalidPluginExecutionException ex)
                {
                    MessageBox.Show($"An error occurred: {ex.Message}");
                }
                catch (FaultException <OrganizationServiceFault> ex)
                {
                    MessageBox.Show($"An error occurred: {ex.Message}");
                }
                catch (TimeoutException ex)
                {
                    MessageBox.Show($"An error occurred: {ex.Message}");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"An error occurred: {ex.Message}");
                }
            }
        }