private void AuditExportDetails_Load(object sender, EventArgs e)
        {
            Control[] ComboBoxes = au.Controls.Find("comboBoxConnectionSource", true);
            if (ComboBoxes.Length != 1)
            {
                return;
            }
            ComboBox              sourceCB = (ComboBox)ComboBoxes[0];
            EnvAuditStructure     es       = au.man.ReadEnvStructure(sourceCB.SelectedItem.ToString());
            List <EnvAuditEntity> eeList   = es.Entities;
            EnvAuditEntity        ee       = eeList.Find(eP => eP.LogicalName == this.entity);
            SelectedAuditEntity   se       = null;

            if (au.currentProfile != null)
            {
                se = au.currentProfile.SelectedEntities.Find(eP => eP.LogicalName == this.entity);
            }

            foreach (string Attribute in ee.Attributes)
            {
                checkedListBoxAttributes.Items.AddRange(new object[] { Attribute });
                checkedListBoxAttributes.SetItemChecked(checkedListBoxAttributes.Items.Count - 1, au.AuditType != "Attribute Change History");
                //Enable all Attributes selection for Audit Summary Export type
                //if (au.AuditType != "Attribute Change History")
                //    continue;
                if (se == null)
                {
                    continue;
                }
                if (se.SelectedAttributes == null)
                {
                    continue;
                }
                string selectedAttribute = se.SelectedAttributes.Find(a => a == Attribute);
                if (selectedAttribute == null)
                {
                    checkedListBoxAttributes.SetItemChecked(checkedListBoxAttributes.Items.Count - 1, false);
                }
                else
                {
                    checkedListBoxAttributes.SetItemChecked(checkedListBoxAttributes.Items.Count - 1, true);
                }
            }

            //Disable Attributes selection for Audit Summary Export type
            if (au.AuditType != "Attribute Change History")
            {
                checkedListBoxAttributes.Enabled = false;
            }

            //Display Export Filter
            if (se != null && se.Filter != null && se.Filter != "")
            {
                xmlEditor1.Text = se.Filter;
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Populates the checked list boxes.
        /// </summary>
        private void populateCheckedListBoxes()
        {
            checkedListBoxActions.Items.Clear();
            checkedListBoxOperations.Items.Clear();
            checkedListBoxUsers.Items.Clear();
            checkedListBoxEntities.Items.Clear();

            //If Structure already downloaded display entities list
            if (comboBoxConnectionSource.SelectedItem == null)
                return;

            try
            {
                es = man.ReadEnvStructure(comboBoxConnectionSource.SelectedItem.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error while reading the struction of connection " + comboBoxConnectionSource.SelectedItem.ToString() + ". The structure file may be corrupted.\r\n\r\n" + ex.Message);
                return;
            }
            labelStructureLastLoadedDate.Text = "never";
            if (es != null)
            {
                string structureFileName = man.Folder + "\\" + comboBoxConnectionSource.SelectedItem + ".xml";
                DateTime structureRefreshedOn = File.GetLastWriteTime(structureFileName);
                labelStructureLastLoadedDate.Text = structureRefreshedOn.ToString();

                //Fill Actions checkedListBox
                foreach (KeyValuePair<int, string> aa in es.Actions)
                {
                    checkedListBoxActions.Items.Add(new ActionListBoxItem { Key = aa.Key, Value = aa.Value });
                    if (currentProfile == null || (currentProfile != null && currentProfile.AllActionsSelected))
                    {
                        checkedListBoxActions.SetItemChecked(checkedListBoxActions.Items.Count - 1, true);
                        continue;
                    }

                    if (currentProfile.SelectedActions == null)
                        continue;

                    foreach (int a in currentProfile.SelectedActions)
                    {
                        if (aa.Key == a)
                            checkedListBoxActions.SetItemChecked(checkedListBoxActions.Items.Count - 1, true);
                    }
                }

                //Fill Operations checkedListBox
                foreach (KeyValuePair<int, string> oo in es.Operations)
                {
                    checkedListBoxOperations.Items.Add(new ActionListBoxItem { Key = oo.Key, Value = oo.Value });
                    if (currentProfile == null || (currentProfile != null && currentProfile.AllOperationsSelected))
                    {
                        checkedListBoxOperations.SetItemChecked(checkedListBoxOperations.Items.Count - 1, true);
                        continue;
                    }

                    if (currentProfile.SelectedOperations == null)
                        continue;

                    foreach (int o in currentProfile.SelectedOperations)
                    {
                        if (oo.Key == o)
                            checkedListBoxOperations.SetItemChecked(checkedListBoxOperations.Items.Count - 1, true);
                    }
                }

                //Fill Users checkedListBox
                foreach (AuditUser u in es.Users)
                {
                    checkedListBoxUsers.Items.Add(new CheckListBoxItem { Id = u.Id, Text = u.FullName });
                    if (currentProfile == null || (currentProfile != null && currentProfile.AllUsersSelected))
                    {
                        checkedListBoxUsers.SetItemChecked(checkedListBoxUsers.Items.Count - 1, true);
                        continue;
                    }

                    if (currentProfile.SelectedUsers == null)
                        continue;

                    foreach (AuditUser ee1 in currentProfile.SelectedUsers)
                    {
                        if (u.Id == ee1.Id)
                            checkedListBoxUsers.SetItemChecked(checkedListBoxUsers.Items.Count - 1, true);
                    }
                }

                //Fill Entities checkedListBox
                foreach (EnvAuditEntity ee in es.Entities)
                {
                    checkedListBoxEntities.Items.AddRange(new object[] { new EntityListBoxItem { Value = ee.LogicalName, ObjectTypeCode = ee.ObjectTypeCode } });

                    if (currentProfile == null)
                        continue;
                    if (currentProfile != null && currentProfile.AllEntitiesSelected)
                    {
                        checkedListBoxEntities.SetItemChecked(checkedListBoxEntities.Items.Count - 1, true);
                        continue;
                    }
                    if (currentProfile.SelectedEntities == null)
                        continue;

                    foreach (SelectedAuditEntity ee1 in currentProfile.SelectedEntities)
                    {
                        if (ee.LogicalName == ee1.LogicalName)
                            checkedListBoxEntities.SetItemChecked(checkedListBoxEntities.Items.Count - 1, true);
                    }
                }

                if (currentProfile == null)
                {
                    comboBoxActionsSelector.SelectedIndex = 0;
                    comboBoxOperationsSelector.SelectedIndex = 0;
                    comboBoxUsersSelector.SelectedIndex = 0;
                    comboBoxEntitiesSelector.SelectedIndex = 1;
                }
                else
                {
                    if (checkedListBoxActions.CheckedItems.Count == checkedListBoxActions.Items.Count)
                        comboBoxActionsSelector.SelectedItem = "All";
                    else if (checkedListBoxActions.CheckedItems.Count == 0)
                        comboBoxActionsSelector.SelectedItem = "None";
                    else
                        comboBoxActionsSelector.SelectedItem = "Custom";

                    if (checkedListBoxOperations.CheckedItems.Count == checkedListBoxOperations.Items.Count)
                        comboBoxOperationsSelector.SelectedItem = "All";
                    else if (checkedListBoxOperations.CheckedItems.Count == 0)
                        comboBoxOperationsSelector.SelectedItem = "None";
                    else
                        comboBoxOperationsSelector.SelectedItem = "Custom";

                    if (checkedListBoxUsers.CheckedItems.Count == checkedListBoxUsers.Items.Count)
                        comboBoxUsersSelector.SelectedItem = "All";
                    else if (checkedListBoxUsers.CheckedItems.Count == 0)
                        comboBoxUsersSelector.SelectedItem = "None";
                    else
                        comboBoxUsersSelector.SelectedItem = "Custom";

                    if (checkedListBoxEntities.CheckedItems.Count == checkedListBoxEntities.Items.Count)
                        comboBoxEntitiesSelector.SelectedItem = "All";
                    else if (checkedListBoxEntities.CheckedItems.Count == 0)
                        comboBoxEntitiesSelector.SelectedItem = "None";
                    else
                        comboBoxEntitiesSelector.SelectedItem = "Custom";
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Handles the Click event of the buttonLoadEntities 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 buttonLoadEntities_Click(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = "";
            DialogResult dResTest = MessageBox.Show("Loading the structure may take some time. The application will become unresponsive during this time.\n\nAre you sure you want to load the structure from the Source?", "Confirm Structure Load", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dResTest == DialogResult.No)
            {
                return;
            }

            toolStripStatusLabel1.Text = "Loading structure. Please wait...";
            Application.DoEvents();

            try
            {
                es = man.downloadEnvAuditStructure(comboBoxConnectionSource.SelectedItem.ToString());
            }
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                MessageBox.Show("Error:" + ex.Detail.Message + "\n" + ex.Detail.TraceText);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                    MessageBox.Show("Error:" + ex.Message + "\n" + ex.InnerException.Message);
                else
                {
                    MessageBox.Show("Error:" + ex.Message);
                }
            }

            if (es == null)
                return;

            string structureFileName = man.Folder + "\\" + comboBoxConnectionSource.SelectedItem.ToString() + ".xml";
            DateTime structureRefreshedOn = File.GetLastWriteTime(structureFileName);
            labelStructureLastLoadedDate.Text = structureRefreshedOn.ToString();

            populateCheckedListBoxes();

            toolStripStatusLabel1.Text = "Structure successfully loaded";
        }
        /// <summary>
        /// Exports the specified profile.
        /// </summary>
        /// <param name="profile">The profile.</param>
        private void Export(MSCRMAuditExportProfile profile)
        {
            MSCRMConnection connection = profile.getSourceConneciton();
            _serviceProxy = cm.connect(connection);

            IOrganizationService service = (IOrganizationService)_serviceProxy;
            es = ReadEnvStructure(profile.SourceConnectionName);

            List<string> columns = new List<string> { "transactionid", "createdon", "userid", "objecttypecode", "objectid", "action", "operation" };
            List<string> DisplayedColumns = new List<string> { "TransactionId", "Date", "User", "Entity", "Record", "Action", "Operation" };

            if (!(profile.AuditType == "User Acces Audit") && !(profile.AuditType == "Audit Summary View"))
            {
                columns.Add("key");
                columns.Add("oldValue");
                columns.Add("newValue");
                DisplayedColumns.Add("Attribute");
                DisplayedColumns.Add("Old_Value");
                DisplayedColumns.Add("New_Value");
            }

            if (profile.AuditType == "User Acces Audit" || profile.AuditType == "Audit Summary View")
            {
                LogManager.WriteLog("Exporting " + profile.AuditType);
                string fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";
                fetchXml += "<entity name='audit'>";
                fetchXml += "<attribute name='transactionid' />";
                fetchXml += "<attribute name='attributemask' />";
                fetchXml += "<attribute name='action' />";
                fetchXml += "<attribute name='createdon' />";
                fetchXml += "<attribute name='auditid' />";
                fetchXml += "<attribute name='userid' />";
                fetchXml += "<attribute name='operation' />";
                fetchXml += "<attribute name='objectid' />";
                fetchXml += "<order attribute='createdon' descending='true' />";
                fetchXml += "<filter type='and'>";
                if (!profile.AllUsersSelected && profile.SelectedUsers.Count > 0)
                {
                    //When a User Access Audit type is selected the User is in the Object
                    if (profile.AuditType == "User Acces Audit")
                        fetchXml += "<condition attribute='objectid' operator='in'>";
                    else
                        fetchXml += "<condition attribute='userid' operator='in'>";

                    foreach (AuditUser u in profile.SelectedUsers)
                    {
                        fetchXml += "<value uitype='systemuser'>" + u.Id.ToString() + "</value>";
                    }
                    fetchXml += "</condition>";
                }
                if (!profile.AllActionsSelected && profile.SelectedActions.Count > 0)
                {
                    fetchXml += "<condition attribute='action' operator='in'>";
                    foreach (int i in profile.SelectedActions)
                    {
                        fetchXml += "<value>" + i + "</value>";
                    }
                    fetchXml += "</condition>";
                }
                if (!profile.AllOperationsSelected && profile.SelectedOperations.Count > 0)
                {
                    fetchXml += "<condition attribute='operation' operator='in'>";
                    foreach (int i in profile.SelectedOperations)
                    {
                        fetchXml += "<value>" + i + "</value>";
                    }
                    fetchXml += "</condition>";
                }
                if (profile.AuditType != "User Acces Audit" && !profile.AllEntitiesSelected && profile.SelectedEntities.Count > 0)
                {
                    fetchXml += "<condition attribute='objecttypecode' operator='in'>";
                    foreach (SelectedAuditEntity i in profile.SelectedEntities)
                    {
                        fetchXml += "<value>" + i.ObjectTypeCode + "</value>";
                    }
                    fetchXml += "</condition>";
                }

                if (profile.AuditRecordCreatedOnFilter == "Last X Days")
                    fetchXml += "<condition attribute='createdon' operator='last-x-days' value='" + profile.AuditRecordCreatedOnFilterLastX + "' />";
                else if (profile.AuditRecordCreatedOnFilter == "Last X Months")
                    fetchXml += "<condition attribute='createdon' operator='last-x-months' value='" + profile.AuditRecordCreatedOnFilterLastX + "' />";
                else if (profile.AuditRecordCreatedOnFilter == "Last X Years")
                    fetchXml += "<condition attribute='createdon' operator='last-x-years' value='" + profile.AuditRecordCreatedOnFilterLastX + "' />";
                else if (profile.AuditRecordCreatedOnFilter == "Between Dates")
                {
                    fetchXml += "<condition attribute='createdon' operator='on-or-after' value='" + String.Format("{0:yyyy-MM-dd}", profile.AuditRecordCreatedOnFilterFrom) + "' />";
                    fetchXml += "<condition attribute='createdon' operator='on-or-before' value='" + String.Format("{0:yyyy-MM-dd}", profile.AuditRecordCreatedOnFilterTo) + "' />";
                }

                fetchXml += "</filter>";
                fetchXml += "</entity></fetch>";
                int recordCountPerEntity = ExportEntity(profile, fetchXml, "", columns, DisplayedColumns, null);
            }
            else
            {
                foreach (SelectedAuditEntity sae in profile.SelectedEntities)
                {
                    //Get entity PrimaryNameAttribute
                    String PrimaryNameAttribute = es.Entities.Find(e => e.LogicalName == sae.LogicalName).PrimaryNameAttribute;
                    LogManager.WriteLog("Exporting audit data for entity " + sae.LogicalName);
                    string fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";
                    fetchXml += "<entity name='" + sae.LogicalName + "'>";
                    fetchXml += "<attribute name='" + PrimaryNameAttribute + "' />";
                    fetchXml += sae.Filter;
                    fetchXml += "</entity></fetch>";
                    int recordCountPerEntity = ExportEntity(profile, fetchXml, PrimaryNameAttribute, columns, DisplayedColumns, sae);
                }
            }
        }
        /// <summary>
        /// Downloads the env audit structure.
        /// </summary>
        /// <param name="connectionName">Name of the connection.</param>
        /// <returns>The Environment Audit Structure.</returns>
        public EnvAuditStructure downloadEnvAuditStructure(string connectionName)
        {
            try
            {
                MSCRMConnection connection = cm.getConnection(connectionName);
                _serviceProxy = cm.connect(connection);
                IOrganizationService service = (IOrganizationService)_serviceProxy;
                EnvAuditStructure es = new EnvAuditStructure();
                es.Entities = new List<EnvAuditEntity>();
                es.Users = new List<AuditUser>();

                RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
                {
                    EntityFilters = EntityFilters.Attributes,
                    RetrieveAsIfPublished = true
                };

                // Retrieve the MetaData.
                RetrieveAllEntitiesResponse AllEntitiesResponse = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);
                IOrderedEnumerable<EntityMetadata> EMD = AllEntitiesResponse.EntityMetadata.OrderBy(ee => ee.LogicalName);

                List<string> AdditionalEntities = new List<string> {"duplicaterule",
                                                                    "duplicaterulecondition",
                                                                    "incidentresolution",
                                                                    "kbarticlecomment",
                                                                    "opportunityclose",
                                                                    "orderclose",
                                                                    "postcomment",
                                                                    "postlike",
                                                                    "quoteclose",
                                                                    "subject",
                                                                    "uom"};

                List<string> IgnoredEntities = new List<string> { "activitypointer",
                    "asyncoperation",
                    "fieldsecurityprofile",
                    "importjob",
                    "pluginassembly",
                    "plugintype",
                    "processsession",
                    "recurringappointmentmaster",
                    "sdkmessage",
                    "sdkmessagefilter",
                    "sdkmessageprocessingstep",
                    "sdkmessageprocessingstepimage",
                    "sdkmessageprocessingstepsecureconfig",
                    "workflow"
                };

                List<string> IgnoredAttributes = new List<string> { "importsequencenumber",
                                                                    "statuscode",
                                                                    "timezoneruleversionnumber",
                                                                    "utcconversiontimezonecode",
                                                                    "overriddencreatedon",
                                                                    "ownerid"
                };

                foreach (EntityMetadata currentEntity in EMD)
                {
                    if (!currentEntity.IsAuditEnabled.Value && currentEntity.LogicalName != "audit")
                        continue;

                    EnvAuditEntity ee = new EnvAuditEntity();
                    ee.LogicalName = currentEntity.LogicalName;
                    ee.ObjectTypeCode = currentEntity.ObjectTypeCode.Value;
                    ee.PrimaryNameAttribute = currentEntity.PrimaryNameAttribute;
                    ee.Attributes = new List<string>();
                    IOrderedEnumerable<AttributeMetadata> AMD = currentEntity.Attributes.OrderBy(a => a.LogicalName);

                    if (currentEntity.LogicalName == "audit")
                    {
                        es.Operations = new List<KeyValuePair<int, string>>();
                    }
                    foreach (AttributeMetadata currentAttribute in AMD)
                    {
                        if (!currentAttribute.IsAuditEnabled.Value && currentEntity.LogicalName != "audit")
                            continue;

                        // Only write out main attributes enabled for reading and creation.
                        if ((currentAttribute.AttributeOf == null) &&
                            currentAttribute.IsValidForRead.Value &&
                            currentAttribute.IsValidForCreate.Value &&
                            IgnoredAttributes.IndexOf(currentAttribute.LogicalName) < 0)
                        {
                            ee.Attributes.Add(currentAttribute.LogicalName);
                        }

                        if (currentEntity.LogicalName == "audit")
                        {
                            if (currentAttribute.LogicalName == "operation")
                            {
                                var typedAttribute = (PicklistAttributeMetadata)currentAttribute;
                                foreach (var option in typedAttribute.OptionSet.Options)
                                {
                                    es.Operations.Add(new KeyValuePair<int, string>(option.Value.Value, option.Label.UserLocalizedLabel.Label));
                                }
                            }
                            else if (currentAttribute.LogicalName == "action")
                            {
                                var typedAttribute = (PicklistAttributeMetadata)currentAttribute;
                                foreach (var option in typedAttribute.OptionSet.Options)
                                {
                                    es.Actions.Add(new KeyValuePair<int, string>(option.Value.Value, option.Label.UserLocalizedLabel.Label));
                                }
                            }
                        }
                    }
                    //Dont export entitites for which only the ID is retrieved
                    if (ee.Attributes.Count > 1)
                        es.Entities.Add(ee);
                }

                //Get users
                string usersQuery = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='systemuser'>";
                usersQuery += "<attribute name='fullname' /><attribute name='systemuserid' /><order attribute='fullname' descending='false' />";
                usersQuery += "</entity></fetch>";

                RetrieveMultipleRequest UsersRequest = new RetrieveMultipleRequest()
                {
                    Query = new FetchExpression(usersQuery)
                };

                EntityCollection Users = ((RetrieveMultipleResponse)_serviceProxy.Execute(UsersRequest)).EntityCollection;

                foreach (Entity User in Users.Entities)
                {
                    es.Users.Add(new AuditUser { Id = User.Id, FullName = (string)User["fullname"] });
                }

                es.connectionName = connectionName;
                WriteEnvStructure(es);
                return es;
            }
            catch (Exception)
            {
                throw;
            }
        }
 /// <summary>
 /// Writes the env structure.
 /// </summary>
 /// <param name="str">The Environment Audit Structure.</param>
 private void WriteEnvStructure(EnvAuditStructure str)
 {
     string filename = Folder + "\\" + str.connectionName + ".xml";
     FileStream writer = new FileStream(filename, FileMode.Create);
     DataContractSerializer ser = new DataContractSerializer(typeof(EnvAuditStructure));
     ser.WriteObject(writer, str);
     writer.Close();
 }
 /// <summary>
 /// Gets the operation label.
 /// </summary>
 /// <param name="str">The string.</param>
 /// <param name="Value">The value.</param>
 /// <returns>The operation label.</returns>
 private string getOperationLabel(EnvAuditStructure str, int Value)
 {
     return str.Operations.Find(o => o.Key == Value).Value;
 }