public void When_ordering_by_money_fields_descending_expected_result_is_returned() { List<Entity> contactList = new List<Entity>(); Entity contact1 = new Entity("contact"); contact1.Id = Guid.NewGuid(); contact1.Attributes["firstname"] = "Fred"; contact1.Attributes["lastname"] = "Bloggs"; contact1.Attributes["new_somefield"] = new Money(12345); // (decimal)678910 Entity contact2 = new Entity("contact"); contact2.Id = Guid.NewGuid(); contact2.Attributes["firstname"] = "Jo"; contact2.Attributes["lastname"] = "Bloggs"; contact2.Attributes["new_somefield"] = new Money(678910); // (decimal)678910 contactList.Add(contact2); contactList.Add(contact1); var context = new XrmFakedContext(); context.Initialize(contactList); var service = context.GetFakedOrganizationService(); QueryExpression qry = new QueryExpression("contact"); qry.ColumnSet = new ColumnSet(true); qry.AddOrder("new_somefield", OrderType.Descending); var results = service.RetrieveMultiple(qry); var firstResultValue = results.Entities[0]["new_somefield"] as Money; Assert.Equal(678910M, firstResultValue.Value); }
public void When_ordering_by_datetime_fields_expected_result_is_returned() { List<Entity> contactList = new List<Entity>(); var now = DateTime.UtcNow; Entity contact1 = new Entity("contact"); contact1.Id = Guid.NewGuid(); contact1.Attributes["firstname"] = "Fred"; contact1.Attributes["new_orderbyfield"] = now; Entity contact2 = new Entity("contact"); contact2.Id = Guid.NewGuid(); contact2.Attributes["firstname"] = "Jo"; contact2.Attributes["new_orderbyfield"] = now.AddDays(1); contactList.Add(contact2); contactList.Add(contact1); var context = new XrmFakedContext(); context.Initialize(contactList); var service = context.GetFakedOrganizationService(); QueryExpression qry = new QueryExpression("contact"); qry.ColumnSet = new ColumnSet(true); qry.AddOrder("new_orderbyfield", OrderType.Ascending); var results = service.RetrieveMultiple(qry); var firstResultValue = (DateTime)results.Entities[0]["new_orderbyfield"]; Assert.Equal(now, firstResultValue); }
/// <summary> /// Obtains all users corresponding to the search filter /// </summary> /// <param name="value">Search filter</param> /// <returns>List of users matching the search filter</returns> public List<Entity> GetUsers(string value) { var users = new List<Entity>(); var ceStatus = new ConditionExpression("isdisabled", ConditionOperator.Equal, false); var feStatus = new FilterExpression(); feStatus.AddCondition(ceStatus); var qe = new QueryExpression("systemuser"); qe.ColumnSet = new ColumnSet("systemuserid", "fullname", "lastname", "firstname", "domainname", "businessunitid"); qe.AddOrder("lastname", OrderType.Ascending); qe.Criteria = new FilterExpression(); qe.Criteria.Filters.Add(new FilterExpression()); qe.Criteria.Filters[0].FilterOperator = LogicalOperator.And; qe.Criteria.Filters[0].Filters.Add(feStatus); qe.Criteria.Filters[0].Filters.Add(new FilterExpression()); qe.Criteria.Filters[0].Filters[1].FilterOperator = LogicalOperator.Or; if (value.Length > 0) { bool isGuid = false; try { Guid g = new Guid(value); isGuid = true; } catch { } if (isGuid) { var ce = new ConditionExpression("systemuserid", ConditionOperator.Equal, value); qe.Criteria.Filters[0].Filters[1].AddCondition(ce); } else { var ce = new ConditionExpression("fullname", ConditionOperator.Like, value.Replace("*", "%")); var ce2 = new ConditionExpression("firstname", ConditionOperator.Like, value.Replace("*", "%")); var ce3 = new ConditionExpression("lastname", ConditionOperator.Like, value.Replace("*", "%")); var ce4 = new ConditionExpression("domainname", ConditionOperator.Like, value.Replace("*", "%")); qe.Criteria.Filters[0].Filters[1].AddCondition(ce); qe.Criteria.Filters[0].Filters[1].AddCondition(ce2); qe.Criteria.Filters[0].Filters[1].AddCondition(ce3); qe.Criteria.Filters[0].Filters[1].AddCondition(ce4); } } foreach (var record in service.RetrieveMultiple(qe).Entities) { users.Add(record); } return users; }
internal void LoadViews(Action action) { this.host.WorkAsync("Loading views...", (a) => { this.views = new Dictionary<string, List<Entity>>(); if (views.Count == 0) { var combinedResult = new Dictionary<string, DataCollection<Entity>>(); DataCollection<Entity> singleResult; var qex = new QueryExpression(); qex.ColumnSet = new ColumnSet("name", "returnedtypecode", "fetchxml", "layoutxml"); qex.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0); qex.Criteria.AddCondition("querytype", ConditionOperator.In, 0, 32); qex.AddOrder("name", OrderType.Ascending); foreach (var entity in new string[] { "savedquery", "userquery" }) { qex.EntityName = entity; singleResult = this.host.Service.RetrieveMultiple(qex).Entities; if (singleResult.Count > 0) { combinedResult.Add(qex.EntityName, singleResult); } } a.Result = combinedResult; } }, (a) => { var allViews = (Dictionary<string, DataCollection<Entity>>)a.Result; foreach (var key in allViews.Keys) { this.ExtractViews(allViews[key]); } this.entities = this.views.Keys.Select(x => x.Split('|')[0]).Distinct().ToList(); action(); }); }
public void Execute(IServiceProvider serviceProvider) { int step = 1; ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); try { if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { step = 2; Entity phoneCall = (Entity)context.InputParameters["Target"]; //Check if the Entity on which plugin is executing is Phone Call if (phoneCall.LogicalName != "phonecall") { return; } //Check if the Phone Call record is Completed either with Contacted or Demo Set status //if (phoneCall.Attributes.Contains("statuscode") && (((OptionSetValue)phoneCall.Attributes["statuscode"]).Value == 2 || ((OptionSetValue)phoneCall.Attributes["statuscode"]).Value == 756480004 || ((OptionSetValue)phoneCall.Attributes["statuscode"]).Value == 756480005)) if (phoneCall.Attributes.Contains("category") && (phoneCall.Attributes["category"].ToString() == "Contacted" || phoneCall.Attributes["category"].ToString() == "Demo Set" || phoneCall.Attributes["category"].ToString() == "Transferred")) { step = 3; //Get the phone call details ( All Attributes ) QueryExpression phoneCallQuery = new QueryExpression(); phoneCallQuery.EntityName = phoneCall.LogicalName; phoneCallQuery.ColumnSet = new ColumnSet(true); phoneCallQuery.Criteria.AddCondition("activityid", ConditionOperator.Equal, (Guid)phoneCall.Id); Entity phoneCallRecord = service.RetrieveMultiple(phoneCallQuery).Entities[0]; //Go into the loop only if phone call is of type Incoming (false) if (phoneCallRecord.Attributes.Contains("directioncode") && (bool)phoneCallRecord.Attributes["directioncode"] == false) { //Go into the loop only if phonecall contains dnis if (phoneCallRecord.Attributes.Contains("fdx_dnis") && phoneCallRecord.Attributes["fdx_dnis"] != null) { step = 4; //Query to pick recent campaign with the DNIS mentioned in phonecall QueryExpression campaignQuery = new QueryExpression(); campaignQuery.EntityName = "campaign"; campaignQuery.ColumnSet = new ColumnSet("campaignid", "codename", "name"); campaignQuery.Criteria.AddFilter(LogicalOperator.And); campaignQuery.Criteria.AddCondition("fdx_dnis", ConditionOperator.Equal, phoneCallRecord.Attributes["fdx_dnis"].ToString()); campaignQuery.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0); campaignQuery.AddOrder("createdon", OrderType.Descending); EntityCollection campaignRecordSet = service.RetrieveMultiple(campaignQuery); //Check if there exist a campaign with the dnis mentioned in Phonecall if (campaignRecordSet.Entities.Count > 0) { Entity campaignRecord = campaignRecordSet[0]; //Check if phone call is tagged with a Record Type (any entity Type will be tagged in the same field. But current requirement is lead/opp/contact) if (phoneCallRecord.Attributes.Contains("regardingobjectid")) { step = 5; //Create a Campaign Response object, which needs to be created as part of Incoming Phone Call against a DNIS Entity campaignResponse = new Entity("campaignresponse"); campaignResponse.Attributes["channeltypecode"] = new OptionSetValue(3);//Type of Campaign Response : Phone Call(3) campaignResponse.Attributes["regardingobjectid"] = new EntityReference(campaignRecord.LogicalName, campaignRecord.Id); campaignResponse.Attributes["fdx_parentcampaigncode"] = campaignRecord.Attributes["codename"].ToString(); campaignResponse.Attributes["receivedon"] = DateTime.UtcNow; string switchEntity = ((EntityReference)phoneCallRecord.Attributes["regardingobjectid"]).LogicalName; step = 6; //Set attribute values in Campaign Response object based on the regardignobject type in Phone Call switch (switchEntity) { case "lead": #region Create a CR by querying and copying details from a Lead step = 7; //Query the Lead and get the required attributes to set into Campaign Response object QueryExpression queryLead = new QueryExpression(); queryLead.EntityName = switchEntity; queryLead.ColumnSet = new ColumnSet("firstname", "lastname", "fdx_credential", "telephone1", "telephone2", "fdx_jobtitlerole", "emailaddress1", "address1_line1", "address1_line2", "address1_city", "fdx_stateprovince", "fdx_zippostalcode", "address1_country", "telephone3", "companyname", "websiteurl", "campaignid", "leadsourcecode"); queryLead.Criteria.AddCondition("leadid", ConditionOperator.Equal, ((EntityReference)phoneCallRecord.Attributes["regardingobjectid"]).Id); step = 8; Entity lead = new Entity(); lead = service.RetrieveMultiple(queryLead).Entities[0]; step = 9; string firstname = ""; string lastname = ""; if (lead.Attributes.Contains("firstname")) { firstname = lead.Attributes["firstname"].ToString(); campaignResponse.Attributes["firstname"] = lead.Attributes["firstname"].ToString(); } if (lead.Attributes.Contains("lastname")) { lastname = lead.Attributes["lastname"].ToString(); campaignResponse.Attributes["lastname"] = lead.Attributes["lastname"].ToString(); } campaignResponse.Attributes["subject"] = firstname + " " + lastname; step = 10; campaignResponse.Attributes["fdx_reconversionlead"] = new EntityReference(lead.LogicalName, lead.Id); if (lead.Attributes.Contains("fdx_credential")) { campaignResponse.Attributes["fdx_credential"] = lead.Attributes["fdx_credential"].ToString(); } if (lead.Attributes.Contains("telephone1")) { campaignResponse.Attributes["fdx_telephone1"] = lead.Attributes["telephone1"].ToString(); } step = 11; if (lead.Attributes.Contains("fdx_jobtitlerole")) { campaignResponse.Attributes["fdx_jobtitlerole"] = new OptionSetValue(((OptionSetValue)(lead.Attributes["fdx_jobtitlerole"])).Value); } if (lead.Attributes.Contains("telephone2")) { campaignResponse.Attributes["telephone"] = lead.Attributes["telephone2"].ToString(); } if (lead.Attributes.Contains("emailaddress1")) { campaignResponse.Attributes["emailaddress"] = lead.Attributes["emailaddress1"].ToString(); } if (lead.Attributes.Contains("companyname")) { campaignResponse.Attributes["companyname"] = lead.Attributes["companyname"].ToString(); } step = 12; if (lead.Attributes.Contains("fdx_zippostalcode")) { campaignResponse.Attributes["fdx_zippostalcode"] = new EntityReference("fdx_zipcode", ((EntityReference)lead.Attributes["fdx_zippostalcode"]).Id); } step = 13; if (lead.Attributes.Contains("websiteurl")) { campaignResponse.Attributes["fdx_websiteurl"] = lead.Attributes["websiteurl"].ToString(); } if (lead.Attributes.Contains("telephone3")) { campaignResponse.Attributes["fdx_telephone3"] = lead.Attributes["telephone3"].ToString(); } if (lead.Attributes.Contains("address1_line1")) { campaignResponse.Attributes["fdx_address1_line1"] = lead.Attributes["address1_line1"].ToString(); } if (lead.Attributes.Contains("address1_line2")) { campaignResponse.Attributes["fdx_address1_line2"] = lead.Attributes["address1_line2"].ToString(); } if (lead.Attributes.Contains("address1_city")) { campaignResponse.Attributes["fdx_address1_city"] = lead.Attributes["address1_city"].ToString(); } step = 14; if (lead.Attributes.Contains("fdx_stateprovince")) { campaignResponse.Attributes["fdx_stateprovince"] = new EntityReference("fdx_state", ((EntityReference)lead.Attributes["fdx_stateprovince"]).Id); } step = 15; if (lead.Attributes.Contains("address1_country")) { campaignResponse.Attributes["fdx_address1_country"] = lead.Attributes["address1_country"].ToString(); } //Smart-905 if (!lead.Attributes.Contains("campaignid") && ((OptionSetValue)lead.Attributes["leadsourcecode"]).Value == 3) { campaignResponse.Attributes["fdx_sourcecampaignresponse"] = true; } step = 16; Guid crGuid = Guid.Empty; crGuid = service.Create(campaignResponse); step = 17; #endregion #region Update Lead's source campaign for first campaign response if (!lead.Attributes.Contains("campaignid") && ((OptionSetValue)lead.Attributes["leadsourcecode"]).Value == 3) { step = 171; Entity LeadUpdate = new Entity("lead"); LeadUpdate.Id = ((EntityReference)phoneCallRecord.Attributes["regardingobjectid"]).Id; LeadUpdate.Attributes["campaignid"] = new EntityReference("campaign", ((EntityReference)campaignResponse.Attributes["regardingobjectid"]).Id); //Smart-905 LeadUpdate.Attributes["relatedobjectid"] = new EntityReference("campaignresponse", crGuid); step = 172; service.Update(LeadUpdate); } #endregion break; case "contact": #region Create a CR by querying and copying details from a Contact step = 18; //Query the Contact and get the required attributes to set into Campaign Response object QueryExpression queryContact = new QueryExpression(); queryContact.EntityName = switchEntity; queryContact.ColumnSet = new ColumnSet("firstname", "lastname", "fdx_credential", "telephone1", "telephone2", "fdx_jobtitlerole", "emailaddress1", "address1_line1", "address1_line2", "address1_city", "fdx_stateprovinceid", "fdx_zippostalcodeid", "address1_country", "websiteurl"); queryContact.Criteria.AddCondition("contactid", ConditionOperator.Equal, ((EntityReference)phoneCallRecord.Attributes["regardingobjectid"]).Id); step = 19; Entity contact = new Entity(); contact = service.RetrieveMultiple(queryContact).Entities[0]; step = 20; firstname = ""; lastname = ""; if (contact.Attributes.Contains("firstname")) { firstname = contact.Attributes["firstname"].ToString(); campaignResponse.Attributes["firstname"] = contact.Attributes["firstname"].ToString(); } if (contact.Attributes.Contains("lastname")) { lastname = contact.Attributes["lastname"].ToString(); campaignResponse.Attributes["lastname"] = contact.Attributes["lastname"].ToString(); } campaignResponse.Attributes["subject"] = firstname + " " + lastname; step = 21; campaignResponse.Attributes["fdx_reconversioncontact"] = new EntityReference(contact.LogicalName, contact.Id); if (contact.Attributes.Contains("fdx_credential")) { campaignResponse.Attributes["fdx_credential"] = contact.Attributes["fdx_credential"].ToString(); } if (contact.Attributes.Contains("telephone1")) { campaignResponse.Attributes["fdx_telephone1"] = contact.Attributes["telephone1"].ToString(); } step = 22; if (contact.Attributes.Contains("fdx_jobtitlerole")) { campaignResponse.Attributes["fdx_jobtitlerole"] = new OptionSetValue(((OptionSetValue)(contact.Attributes["fdx_jobtitlerole"])).Value); } if (contact.Attributes.Contains("telephone2")) { campaignResponse.Attributes["telephone"] = contact.Attributes["telephone2"].ToString(); } if (contact.Attributes.Contains("emailaddress1")) { campaignResponse.Attributes["emailaddress"] = contact.Attributes["emailaddress1"].ToString(); } step = 23; if (contact.Attributes.Contains("fdx_zippostalcode")) { campaignResponse.Attributes["fdx_zippostalcode"] = new EntityReference("fdx_zipcode", ((EntityReference)contact.Attributes["fdx_zippostalcodeid"]).Id); } step = 24; if (contact.Attributes.Contains("websiteurl")) { campaignResponse.Attributes["fdx_websiteurl"] = contact.Attributes["websiteurl"].ToString(); } if (contact.Attributes.Contains("address1_line1")) { campaignResponse.Attributes["fdx_address1_line1"] = contact.Attributes["address1_line1"].ToString(); } if (contact.Attributes.Contains("address1_line2")) { campaignResponse.Attributes["fdx_address1_line2"] = contact.Attributes["address1_line2"].ToString(); } if (contact.Attributes.Contains("address1_city")) { campaignResponse.Attributes["fdx_address1_city"] = contact.Attributes["address1_city"].ToString(); } step = 25; if (contact.Attributes.Contains("fdx_stateprovinceid")) { campaignResponse.Attributes["fdx_stateprovince"] = new EntityReference("fdx_state", ((EntityReference)contact.Attributes["fdx_stateprovinceid"]).Id); } step = 26; if (contact.Attributes.Contains("address1_country")) { campaignResponse.Attributes["fdx_address1_country"] = contact.Attributes["address1_country"].ToString(); } step = 27; service.Create(campaignResponse); #endregion step = 28; break; case "opportunity": #region Create a CR by querying and copying details from an Opportunity step = 29; //Query the Opportunity and get the Account and Contact of Opportunity to set into Campaign Response object QueryExpression queryOpportunity = new QueryExpression(); queryOpportunity.EntityName = switchEntity; queryOpportunity.ColumnSet = new ColumnSet("parentaccountid", "parentcontactid"); queryOpportunity.Criteria.AddCondition("opportunityid", ConditionOperator.Equal, ((EntityReference)phoneCallRecord.Attributes["regardingobjectid"]).Id); step = 30; Entity opportunity = new Entity(); opportunity = service.RetrieveMultiple(queryOpportunity).Entities[0]; step = 31; Entity opportunityContact = new Entity(); Entity opportunityAccount = new Entity(); //Query the Account related to Opportunity to get the Address related attributes if (opportunity.Attributes.Contains("parentaccountid")) { step = 32; QueryExpression queryOpportunityAccount = new QueryExpression(); queryOpportunityAccount.EntityName = "account"; queryOpportunityAccount.ColumnSet = new ColumnSet("address1_line1", "address1_line2", "address1_city", "fdx_stateprovinceid", "fdx_zippostalcodeid", "address1_country", "websiteurl"); queryOpportunityAccount.Criteria.AddCondition("accountid", ConditionOperator.Equal, ((EntityReference)opportunity.Attributes["parentaccountid"]).Id); step = 33; opportunityAccount = service.RetrieveMultiple(queryOpportunityAccount).Entities[0]; step = 34; } //Query the Contact related to Opportunity to get the Phone or other attributes if (opportunity.Attributes.Contains("parentcontactid")) { step = 35; QueryExpression queryOpportunityContact = new QueryExpression(); queryOpportunityContact.EntityName = "contact"; queryOpportunityContact.ColumnSet = new ColumnSet("firstname", "lastname", "fdx_credential", "telephone1", "telephone2", "fdx_jobtitlerole", "emailaddress1"); queryOpportunityContact.Criteria.AddCondition("contactid", ConditionOperator.Equal, ((EntityReference)opportunity.Attributes["parentcontactid"]).Id); step = 36; opportunityContact = service.RetrieveMultiple(queryOpportunityContact).Entities[0]; step = 37; } firstname = ""; lastname = ""; if (opportunityContact.Attributes.Contains("firstname")) { firstname = opportunityContact.Attributes["firstname"].ToString(); campaignResponse.Attributes["firstname"] = opportunityContact.Attributes["firstname"].ToString(); step = 38; } if (opportunityContact.Attributes.Contains("lastname")) { lastname = opportunityContact.Attributes["lastname"].ToString(); campaignResponse.Attributes["lastname"] = opportunityContact.Attributes["lastname"].ToString(); step = 39; } campaignResponse.Attributes["subject"] = firstname + " " + lastname; step = 40; campaignResponse.Attributes["fdx_reconversionopportunity"] = new EntityReference(opportunity.LogicalName, opportunity.Id); if (opportunityContact.Attributes.Contains("fdx_credential")) { campaignResponse.Attributes["fdx_credential"] = opportunityContact.Attributes["fdx_credential"].ToString(); } if (opportunityContact.Attributes.Contains("telephone1")) { campaignResponse.Attributes["fdx_telephone1"] = opportunityContact.Attributes["telephone1"].ToString(); } step = 41; if (opportunityContact.Attributes.Contains("fdx_jobtitlerole")) { campaignResponse.Attributes["fdx_jobtitlerole"] = new OptionSetValue(((OptionSetValue)(opportunityContact.Attributes["fdx_jobtitlerole"])).Value); } if (opportunityContact.Attributes.Contains("telephone2")) { campaignResponse.Attributes["telephone"] = opportunityContact.Attributes["telephone2"].ToString(); } if (opportunityContact.Attributes.Contains("emailaddress1")) { campaignResponse.Attributes["emailaddress"] = opportunityContact.Attributes["emailaddress1"].ToString(); } step = 42; if (opportunityAccount.Attributes.Contains("fdx_zippostalcode")) { campaignResponse.Attributes["fdx_zippostalcode"] = new EntityReference("fdx_zipcode", ((EntityReference)opportunityAccount.Attributes["fdx_zippostalcodeid"]).Id); } step = 43; if (opportunityAccount.Attributes.Contains("websiteurl")) { campaignResponse.Attributes["fdx_websiteurl"] = opportunityAccount.Attributes["websiteurl"].ToString(); } if (opportunityAccount.Attributes.Contains("address1_line1")) { campaignResponse.Attributes["fdx_address1_line1"] = opportunityAccount.Attributes["address1_line1"].ToString(); } if (opportunityAccount.Attributes.Contains("address1_line2")) { campaignResponse.Attributes["fdx_address1_line2"] = opportunityAccount.Attributes["address1_line2"].ToString(); } if (opportunityAccount.Attributes.Contains("address1_city")) { campaignResponse.Attributes["fdx_address1_city"] = opportunityAccount.Attributes["address1_city"].ToString(); } step = 44; if (opportunityAccount.Attributes.Contains("fdx_stateprovinceid")) { campaignResponse.Attributes["fdx_stateprovince"] = new EntityReference("fdx_state", ((EntityReference)opportunityAccount.Attributes["fdx_stateprovinceid"]).Id); } step = 45; if (opportunityAccount.Attributes.Contains("address1_country")) { campaignResponse.Attributes["fdx_address1_country"] = opportunityAccount.Attributes["address1_country"].ToString(); } step = 46; service.Create(campaignResponse); #endregion //#region Update Opportunity's source campaign for first campaign response //if (!opportunity.Attributes.Contains("campaignid")) //{ // step = 47; // Entity OpportunityUpdate = new Entity("opportunity"); // OpportunityUpdate.Id = ((EntityReference)phoneCallRecord.Attributes["regardingobjectid"]).Id; // OpportunityUpdate.Attributes["campaignid"] = new EntityReference("campaign", ((EntityReference)campaignResponse.Attributes["regardingobjectid"]).Id); // step = 48; // service.Update(OpportunityUpdate); //} //#endregion break; default: break; } } } } } } } } catch (FaultException <OrganizationServiceFault> ex) { throw new InvalidPluginExecutionException(string.Format("An error occurred in the IncomingPhoneCampaignResponseCreate plug-in at Step {0}.", step), ex); } catch (Exception ex) { tracingService.Trace("IncomingPhoneCampaignResponseCreate: step {0}, {1}", step, ex.ToString()); throw; } }
private void getWorkflows() { #region Reset Variables ExecutionRecordSet.Entities.Clear(); _workflows.Entities.Clear(); _selectedWorkflow = null; _views.Entities.Clear(); _selectedView = null; this.Invoke((MethodInvoker)delegate() { cmbWorkflows.Items.Clear(); cmbViews.Items.Clear(); txtRecordCount.Clear(); rtxtFetchXML.Clear(); radFetchXML.Checked = false; radViews.Checked = true; //progressBar1.Style = ProgressBarStyle.Marquee; txtBatch.Text = "200"; emrBatchSize = 200; }); #endregion Reset Variables #region Get Workflows Query QueryExpression query = new QueryExpression("workflow"); query.ColumnSet.AddColumns("workflowid", "name", "primaryentity"); query.Distinct = true; query.AddOrder("name", OrderType.Ascending); query.Criteria = new FilterExpression(); //query.Criteria.AddCondition("category", ConditionOperator.Equal, 0); FilterExpression childFilter = query.Criteria.AddFilter(LogicalOperator.And); childFilter.AddCondition("category", ConditionOperator.Equal, 0); childFilter.AddCondition("activeworkflowid", ConditionOperator.NotNull); childFilter.AddCondition("ondemand", ConditionOperator.Equal, true); _workflows = service.RetrieveMultiple(query); if (_workflows.Entities.Count > 0) { foreach (var item in _workflows.Entities) { this.Invoke((MethodInvoker)delegate() { cmbWorkflows.Items.Add(item["name"]); }); } } this.Invoke((MethodInvoker)delegate() { cmbWorkflows.Text = "Select a Workflow to run"; cmbViews.Text = "Select a Workflow to populate this list"; //progressBar1.Style = ProgressBarStyle.Continuous; }); infoPanel.Dispose(); infoPanel.Dispose(); Controls.Remove(infoPanel); #endregion Get Workflows Query }
public void Execute(IServiceProvider serviceProvider) { IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); ITracingService tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity) { try { Entity entity = (Entity)context.InputParameters["Target"];//create the Entity where it call Entity postEntity = (Entity)context.PostEntityImages["PostImage"]; string businessSegment = ""; string subSegment = ""; string leadChannel = ""; if (postEntity.Contains("alletech_businesssegmentglb")) { businessSegment = ((EntityReference)postEntity.Attributes["alletech_businesssegmentglb"]).Name; } tracing.Trace("businessSegment: " + businessSegment); if (postEntity.Contains("alletech_subbusinesssegment")) { subSegment = ((EntityReference)postEntity.Attributes["alletech_subbusinesssegment"]).Name; } tracing.Trace("subSegment: " + subSegment); if (postEntity.Contains("alletech_leadchannellookup")) { leadChannel = ((EntityReference)postEntity.Attributes["alletech_leadchannellookup"]).Name; } tracing.Trace("leadChannel: " + leadChannel); if (businessSegment != null && subSegment != null && leadChannel != null) { tracing.Trace("segment : " + businessSegment + subSegment + leadChannel); if (businessSegment == "Business" && subSegment == "SDWAN" && leadChannel != "Self Lead")//lead chanel and sub seg should come from config. { string vertical = ((EntityReference)postEntity.Attributes["onl_vertical"]).Name; tracing.Trace("vertical: " + vertical); QueryExpression objquery = new QueryExpression("onl_vertical"); //creating the new Expression to relate the next entity objquery.ColumnSet = new ColumnSet("onl_name"); //get all attribute of this entity objquery.Criteria.AddCondition(new ConditionExpression("onl_name", ConditionOperator.Equal, vertical)); //check the opp id on saf is same as opp idin customer site EntityCollection objCol = service.RetrieveMultiple(objquery); // tracing.Trace("vertical Retrive Sucessfuly"); if (objCol != null) { if (objCol.Entities.Count > 0) { Guid city = ((EntityReference)postEntity.Attributes["alletech_completecity"]).Id; tracing.Trace("city ID: " + city); QueryExpression objquery1 = new QueryExpression("onl_verticalconfiguration"); //creating the new Expression to relate the next entity objquery1.ColumnSet = new ColumnSet("onl_verticalowneruser"); //get all attribute of this entity objquery1.Criteria.AddCondition(new ConditionExpression("onl_city", ConditionOperator.Equal, city)); //check the opp id on saf is same as opp idin customer site EntityCollection objCol1 = service.RetrieveMultiple(objquery1); // tracing.Trace("verticalconfiguraation retrive secussfuly."); if (objCol1 != null) { if (objCol1.Entities.Count == 1) { Guid verticalUser = ((EntityReference)objCol1[0].Attributes["onl_verticalowneruser"]).Id; tracing.Trace("vertical User: "******"systemuser", verticalUser), Target = new EntityReference("lead", entity.Id) }; service.Execute(assign); tracing.Trace("Executed Sucessfully. "); Entity verticalConfig = new Entity("onl_verticalconfiguration"); tracing.Trace("vertical Config: " + verticalConfig); verticalConfig.Id = objCol1[0].Id; tracing.Trace("vertical Config id: " + verticalConfig.Id); verticalConfig["onl_assigneddate"] = DateTime.Now; service.Update(verticalConfig); tracing.Trace("vertical Config updated sucessfuly: "); } if (objCol1.Entities.Count > 1) { QueryExpression objquery2 = new QueryExpression("onl_verticalconfiguration"); //creating the new Expression to relate the next entity objquery2.ColumnSet = new ColumnSet("onl_verticalowneruser"); //get all attribute of this entity objquery2.Criteria.AddCondition(new ConditionExpression("onl_city", ConditionOperator.Equal, city)); //check the opp id on saf is same as opp idin customer site objquery2.Criteria.AddCondition(new ConditionExpression("onl_assigneddate", ConditionOperator.Null)); //check the opp id on saf is same as opp idin customer site objquery2.AddOrder("createdon", OrderType.Ascending); EntityCollection objCol2 = service.RetrieveMultiple(objquery2); // tracing.Trace("vertical Config retrive secussfuly: "); if (objCol2 != null) { Guid verticalUser = ((EntityReference)objCol2[0].Attributes["onl_verticalowneruser"]).Id; tracing.Trace("vertical user: "******"systemuser", verticalUser), Target = new EntityReference("lead", entity.Id) }; service.Execute(assign); tracing.Trace("service Executed Sucessfuly: "); Entity verticalConfig = new Entity("onl_verticalconfiguration"); tracing.Trace("vertical entity: "); verticalConfig.Id = objCol2[0].Id; tracing.Trace("vertical config ID: " + verticalConfig.Id); verticalConfig["onl_assigneddate"] = DateTime.Now; service.Update(verticalConfig); tracing.Trace("vertcal config updated Sucessfuly: "); } else { QueryExpression objquery3 = new QueryExpression("onl_verticalconfiguration"); //creating the new Expression to relate the next entity objquery3.ColumnSet = new ColumnSet("onl_verticalowneruser"); //get all attribute of this entity objquery3.Criteria.AddCondition(new ConditionExpression("onl_city", ConditionOperator.Equal, city)); //check the opp id on saf is same as opp idin customer site objquery3.AddOrder("onl_assigneddate", OrderType.Ascending); EntityCollection objCol3 = service.RetrieveMultiple(objquery3); // if (objCol3 != null) { Guid verticalUser = ((EntityReference)objCol3[0].Attributes["onl_verticalowneruser"]).Id; tracing.Trace("Vertical User GUID: " + verticalUser); AssignRequest assign = new AssignRequest { Assignee = new EntityReference("systemuser", verticalUser), Target = new EntityReference("lead", entity.Id) }; service.Execute(assign); tracing.Trace("service Executed Sucessfuly: "); Entity verticalConfig = new Entity("onl_verticalconfiguration"); verticalConfig.Id = objCol3[0].Id; verticalConfig["onl_assigneddate"] = DateTime.Now; tracing.Trace("verticalConfig['onl_assigneddate'] " + verticalConfig["onl_assigneddate"]); service.Update(verticalConfig); tracing.Trace("vertical updated Sucessfuly: "); } } } } } } } } } catch (Exception ex) { throw new InvalidPluginExecutionException("Error: " + ex.Message); } } }
private Task<List<Role>> LoadRoles() { return Task.Run(() => { var query = new QueryExpression("role"); query.NoLock = true; query.ColumnSet = new ColumnSet("name", "roleid"); query.AddOrder("name", OrderType.Ascending); var bu = query.AddLink("businessunit", "businessunitid", "businessunitid"); bu.LinkCriteria.AddCondition("parentbusinessunitid", ConditionOperator.Null); var result = _service.RetrieveMultiple(query); var roles = result.Entities.Select(e => new Role { RoleId = e.Id, Name = e["name"] as string }); roles = roles.Concat(new Role[] { new Role { RoleId = Guid.Empty, Name = " -- Users without an assigned role -- " } }); return roles.OrderBy(r => r.Name).ToList(); }); }
internal void LoadViews(Action viewsLoaded) { WorkAsync(new WorkAsyncInfo("Loading views...", (eventargs) => { EnableControls(false); if (views == null || views.Count == 0) { if (Service == null) { throw new Exception("Need a connection to load views."); } var qexs = new QueryExpression("savedquery"); qexs.ColumnSet = new ColumnSet("name", "returnedtypecode", "fetchxml", "layoutxml", "iscustomizable"); qexs.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0); qexs.Criteria.AddCondition("fetchxml", ConditionOperator.NotNull); if (!settings.OpenUncustomizableViews) { qexs.Criteria.AddCondition("iscustomizable", ConditionOperator.Equal, true); } qexs.AddOrder("name", OrderType.Ascending); var sysviews = RetrieveMultiple(qexs); foreach (var view in sysviews.Entities) { var entityname = view["returnedtypecode"].ToString(); if (!string.IsNullOrWhiteSpace(entityname) && GetEntity(entityname) != null) { if (views == null) { views = new Dictionary <string, List <Entity> >(); } if (!views.ContainsKey(entityname + "|S")) { views.Add(entityname + "|S", new List <Entity>()); } views[entityname + "|S"].Add(view); } } var qexu = new QueryExpression("userquery"); qexu.ColumnSet = new ColumnSet("name", "returnedtypecode", "fetchxml", "layoutxml"); qexu.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0); qexu.AddOrder("name", OrderType.Ascending); var userviews = RetrieveMultiple(qexu); foreach (var view in userviews.Entities) { var entityname = view["returnedtypecode"].ToString(); if (!string.IsNullOrWhiteSpace(entityname) && GetEntity(entityname) != null) { if (views == null) { views = new Dictionary <string, List <Entity> >(); } if (!views.ContainsKey(entityname + "|U")) { views.Add(entityname + "|U", new List <Entity>()); } views[entityname + "|U"].Add(view); } } } }) { PostWorkCallBack = (completedargs) => { EnableControls(true); if (completedargs.Error != null) { ShowErrorDialog(completedargs.Error, "Loading Views"); } else { viewsLoaded(); } } }); }
private static void AddOrderExpressions(QueryExpression query, IEnumerable<OrderExpression> orders) { if (orders != null) { foreach (var order in orders) query.AddOrder(order.AttributeName, order.OrderType); } }
public static QueryExpression BuildQueryActive(string entityType, IEnumerable<string> fields, IEnumerable<ConditionExpression> filters, string[] sortFields) { var query = new QueryExpression(entityType); query.Criteria.AddCondition("statecode", ConditionOperator.Equal, XrmPicklists.State.Active); if (filters != null) { foreach (var condition in filters) query.Criteria.AddCondition(condition); } if (sortFields != null) { foreach (var sortField in sortFields) query.AddOrder(sortField, OrderType.Ascending); } if (fields != null) query.ColumnSet = new ColumnSet(fields.ToArray()); else query.ColumnSet = new ColumnSet(true); return query; }
/// <summary> /// Gets the Accounts associated with a Team and/or DSM2 /// </summary> /// <param name="TeamID">Team or DSM2 ID</param> /// <param name="DSM2">Not Used</param> /// <returns>List of Account Model class</returns> public static List <CRMAccountModel> GetCRMAccountsForTeamService(string TeamID, string DSM2) { List <CRMAccountModel> theAccounts = new List <CRMAccountModel>(); try { CrmServiceClient conn = new CrmServiceClient(DatabaseServices.GetCRMDBConnectionString()); IOrganizationService _orgService; _orgService = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy; Guid objGuid = Guid.Empty; if (Guid.TryParse(TeamID, out objGuid)) { // string can be converted to GUID // no additional processing needed } else { // can not parse into a guid throw new Exception("Can not convert TeamID into GUID"); } QueryExpression query = new QueryExpression { EntityName = "account", ColumnSet = new ColumnSet("accountid", "name", "csi_facilityname", "ownerid", "new_dsm2"), Criteria = { Filters = { new FilterExpression { FilterOperator = LogicalOperator.Or, Conditions = { //new ConditionExpression("ownerid", ConditionOperator.Equal, TeamID.Trim()), new ConditionExpression("ownerid", ConditionOperator.Equal, objGuid), //new ConditionExpression("new_dsm2", ConditionOperator.Equal, TeamID.Trim()) new ConditionExpression("new_dsm2", ConditionOperator.Equal, objGuid) } } } } }; // return records sorted by name //query.AddOrder("csi_facilityname", OrderType.Ascending); query.AddOrder("name", OrderType.Ascending); EntityCollection entityRecords = _orgService.RetrieveMultiple(query); // see if data returned if (entityRecords != null && entityRecords.Entities.Count > 0) { CRMAccountModel entityModel; for (int i = 0; i < entityRecords.Entities.Count; i++) { // new blank copy of the C# model entityModel = new CRMAccountModel(); if (entityRecords[i].Contains("accountid") && entityRecords[i]["accountid"] != null) { entityModel.Id = entityRecords[i]["accountid"].ToString(); } if (entityRecords[i].Contains("csi_facilityname") && entityRecords[i]["csi_facilityname"] != null) { entityModel.CSI_FacilityName = entityRecords[i]["csi_facilityname"].ToString(); } if (entityRecords[i].Contains("name") && entityRecords[i]["name"] != null) { entityModel.Name = CRMUtilityServices.GetTitleCaseService(entityRecords[i]["name"].ToString()); } if (entityRecords[i].Contains("ownerid") && entityRecords[i]["ownerid"] != null) { EntityReference ownerRef = entityRecords[i].GetAttributeValue <EntityReference>("ownerid"); entityModel.OwnerID = ownerRef.Id.ToString(); //entityModel.OwnerID = entityRecords[i]["ownerid"].ToString(); } if (entityRecords[i].Contains("new_dsm2") && entityRecords[i]["new_dsm2"] != null) { EntityReference ownerRef = entityRecords[i].GetAttributeValue <EntityReference>("new_dsm2"); entityModel.OwnerID = ownerRef.Id.ToString(); //entityModel.New_DSM2 = entityRecords[i]["new_dsm2"].ToString(); } // add row to collection theAccounts.Add(entityModel); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } return(theAccounts); }
private Task<IEnumerable<Role>> LoadRoles() { return Task.Run(() => { var query = new QueryExpression("role"); query.NoLock = true; query.ColumnSet = new ColumnSet("name", "roleid"); query.AddOrder("name", OrderType.Ascending); var bu = query.AddLink("businessunit", "businessunitid", "businessunitid"); bu.LinkCriteria.AddCondition("parentbusinessunitid", ConditionOperator.Null); var result = _service.RetrieveMultiple(query); var roles = result.Entities.Select(e => new Role { RoleId = e.Id, Name = e["name"] as string }); return roles; }); }
public DataTable Execute(SelectStatement statement) { var metadata = new MetadataManager(CRMInstance); ValidateStatement(statement); var entityName = ((SelectFrom)statement.From.First()).Name; var query = new QueryExpression(entityName); if (statement.Columns.Any()) { query.ColumnSet = new ColumnSet(false); // Until caching layer is ready we will retrieve fields every time var entityFields = metadata.GetEntityFields(entityName); if (entityFields == null) { throw new Exception($"Unable to read entity '{entityName}' fields."); } if (statement.Columns.Any(x => x.Type.In(SelectColumnTypeEnum.All, SelectColumnTypeEnum.System))) { for (int i = 0; i < statement.Columns.Count; i++) { var column = statement.Columns[i]; if (column.Type == SelectColumnTypeEnum.All) { foreach (var entityField in entityFields) { var fieldSelectColumn = new FieldSelectColumn(entityField.SchemaName); statement.Columns.Insert(i++, fieldSelectColumn); } } else if (column.Type == SelectColumnTypeEnum.System) { foreach (var fieldName in Configuration.Settings.SystemSelectFields) { if (fieldName.IsEmpty()) { throw new Exception($"'{fieldName}' not set."); } if (string.Equals(fieldName, "$id", StringComparison.OrdinalIgnoreCase)) { var idEntityField = entityFields.Single(x => x.IsPrimaryId); var fieldSelectColumn = new FieldSelectColumn(idEntityField.SchemaName); statement.Columns.Insert(i++, fieldSelectColumn); } else if (string.Equals(fieldName, "$name", StringComparison.OrdinalIgnoreCase)) { var nameEntityField = entityFields.Single(x => x.IsPrimaryName); var fieldSelectColumn = new FieldSelectColumn(nameEntityField.SchemaName); statement.Columns.Insert(i++, fieldSelectColumn); } else if (fieldName.StartsWith("$")) { throw new Exception($"System field '{fieldName}' not supported."); } else { var fieldSelectColumn = new FieldSelectColumn(fieldName); statement.Columns.Insert(i++, fieldSelectColumn); } } } } } for (int i = 0; i < statement.Columns.Count; i++) { var column = statement.Columns[i]; if (column.Type == SelectColumnTypeEnum.Field) { var fieldColumn = (FieldSelectColumn)column; query.ColumnSet.AddColumn(fieldColumn.Name); } else if (column.Type == SelectColumnTypeEnum.InnerSelect) { throw new Exception("Inner selects are currently unsupported."); } else if (column.Type == SelectColumnTypeEnum.Function) { throw new Exception("Columns with functions are currently unsupported."); } } } else { query.ColumnSet = new ColumnSet(true); } if (statement.Top.HasValue) { query.TopCount = statement.Top.Value; } if (statement.Where.Any()) { for (var i = 0; i < statement.Where.Count; i++) { var whereClause = statement.Where[i]; if (whereClause.Type == SelectWhereTypeEnum.Comparison) { var comparisonClause = (SelectWhereComparison)whereClause; var conditionName = GetWhereClauseAttributeName(comparisonClause.LeftExpression); var conditionValue = GetWhereClauseAttributeName(comparisonClause.RightExpression); var conditionOperator = ConditionOperator.Equal; switch (comparisonClause.Operator) { case SelectWhereComparisonOperatorEnum.Equal: conditionOperator = comparisonClause.Negate ? ConditionOperator.NotEqual : ConditionOperator.Equal; break; case SelectWhereComparisonOperatorEnum.NotEqual: conditionOperator = comparisonClause.Negate ? ConditionOperator.Equal : ConditionOperator.NotEqual; break; case SelectWhereComparisonOperatorEnum.LessThan: conditionOperator = comparisonClause.Negate ? ConditionOperator.GreaterEqual : ConditionOperator.LessThan; break; case SelectWhereComparisonOperatorEnum.LessEqualThan: conditionOperator = comparisonClause.Negate ? ConditionOperator.GreaterThan : ConditionOperator.LessEqual; break; case SelectWhereComparisonOperatorEnum.GreaterThan: conditionOperator = comparisonClause.Negate ? ConditionOperator.LessEqual : ConditionOperator.GreaterThan; break; case SelectWhereComparisonOperatorEnum.GreaterEqualThan: conditionOperator = comparisonClause.Negate ? ConditionOperator.LessThan : ConditionOperator.GreaterEqual; break; default: throw new Exception($"Found unexpected comparison operator '{comparisonClause.Operator}'"); } query.Criteria.AddCondition(conditionName, conditionOperator, conditionValue); } else if (whereClause.Type == SelectWhereTypeEnum.Null) { var nullClause = (SelectWhereNull)whereClause; var conditionName = GetWhereClauseAttributeName(nullClause.Expression); query.Criteria.AddCondition(conditionName, nullClause.Negate ? ConditionOperator.NotNull : ConditionOperator.Null); } else if (whereClause.Type == SelectWhereTypeEnum.Like) { var likeClause = (SelectWhereLike)whereClause; var conditionName = GetWhereClauseAttributeName(likeClause.LeftExpression); var conditionValue = GetWhereClauseAttributeName(likeClause.RightExpression); query.Criteria.AddCondition(conditionName, likeClause.Negate ? ConditionOperator.NotLike : ConditionOperator.Like, conditionValue); } else if (whereClause.Type != SelectWhereTypeEnum.Operator) { throw new Exception($"Found unexpected where clause {whereClause.Type}"); } } } if (statement.Order.Any()) { foreach (var orderItem in statement.Order) { if (orderItem.Type == SelectOrderTypeEnum.Column) { var columnOrder = (SelectOrderColumn)orderItem; var direction = orderItem.Direction == OrderDirection.Asc ? OrderType.Ascending : OrderType.Descending; query.AddOrder(columnOrder.Name, direction); } else if (orderItem.Type == SelectOrderTypeEnum.Position) { var columnPosition = (SelectOrderPosition)orderItem; var direction = orderItem.Direction == OrderDirection.Asc ? OrderType.Ascending : OrderType.Descending; var fieldColumn = statement.Columns[columnPosition.Position - 1] as FieldSelectColumn; if (fieldColumn == null) { throw new Exception($"Position '{columnPosition.Position}' must point to a CRM field"); } query.AddOrder(fieldColumn.Name, direction); } else { throw new Exception($"Unsupported order type '{orderItem.Type}'"); } } } var entities = CRMInstance.Service.RetrieveMultiple(query).Entities.ToList(); var list = new List <List <KeyValuePair <string, object> > >(); foreach (var entity in entities) { var values = new List <KeyValuePair <string, object> >(); foreach (var attribute in entity.Attributes) { object value = null; var type = attribute.Value.GetType(); if (type != typeof(string)) { if (entity.FormattedValues.ContainsKey(attribute.Key)) { value = entity.FormattedValues[attribute.Key]; } } if (value == null) { value = Convert.ToString(attribute.Value); } values.Add(new KeyValuePair <string, object>(attribute.Key, value)); } list.Add(values); } return(ConvertToDataTable(list, statement.Columns)); }
internal void LoadViews(Action viewsLoaded) { if (working) { return; } if (entities == null || entities.Count == 0) { LoadEntities(viewsLoaded); return; } working = true; WorkAsync(new WorkAsyncInfo("Loading views...", (bgworker, workargs) => { EnableControls(false); if (views == null || views.Count == 0) { if (Service == null) { throw new Exception("Need a connection to load views."); } var qex = new QueryExpression("savedquery"); qex.ColumnSet = new ColumnSet("name", "returnedtypecode", "fetchxml"); qex.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0); qex.Criteria.AddCondition("querytype", ConditionOperator.In, 0, 32); qex.AddOrder("name", OrderType.Ascending); bgworker.ReportProgress(33, "Loading system views..."); var sysviews = Service.RetrieveMultiple(qex); foreach (var view in sysviews.Entities) { var entityname = view["returnedtypecode"].ToString(); if (!string.IsNullOrWhiteSpace(entityname) && entities.ContainsKey(entityname)) { if (views == null) { views = new Dictionary <string, List <Entity> >(); } if (!views.ContainsKey(entityname + "|S")) { views.Add(entityname + "|S", new List <Entity>()); } views[entityname + "|S"].Add(view); } } qex.EntityName = "userquery"; bgworker.ReportProgress(66, "Loading user views..."); var userviews = Service.RetrieveMultiple(qex); foreach (var view in userviews.Entities) { var entityname = view["returnedtypecode"].ToString(); if (!string.IsNullOrWhiteSpace(entityname) && entities.ContainsKey(entityname)) { if (views == null) { views = new Dictionary <string, List <Entity> >(); } if (!views.ContainsKey(entityname + "|U")) { views.Add(entityname + "|U", new List <Entity>()); } views[entityname + "|U"].Add(view); } } bgworker.ReportProgress(100, "Finalizing..."); } }) { PostWorkCallBack = (completedargs) => { working = false; EnableControls(true); if (completedargs.Error != null) { MessageBox.Show(completedargs.Error.Message); } else { viewsLoaded(); } }, ProgressChanged = (changeargs) => { SetWorkingMessage(changeargs.UserState.ToString()); } }); }
static void Main(string[] args) { // Extract the command line args CommandLineArgs options = new CommandLineArgs(); if (!CommandLine.Parser.Default.ParseArguments(args, options)) { Environment.Exit(1); } // Log into CRM Console.WriteLine("Logging in"); CrmServiceClient service = new CrmServiceClient(options.ConnectionString); if (!string.IsNullOrEmpty(service.LastCrmError)) { Console.WriteLine($"Unable to connect to crm {service.LastCrmError}"); Environment.Exit(2); } // Get all of the system users QueryExpression systemUserQuery = new QueryExpression("systemuser"); systemUserQuery.ColumnSet = new ColumnSet("fullname", "isdisabled"); if (options.IgnoreDeactivated) { systemUserQuery.Criteria.AddCondition("isdisabled", ConditionOperator.Equal, false); } var systemUsers = service.RetrieveMultiple(systemUserQuery).Entities; // Build a filter for the api access that we care about FilterExpression filter = new FilterExpression(LogicalOperator.Or); filter.AddCondition("action", ConditionOperator.Equal, 64); filter.AddCondition("action", ConditionOperator.Equal, 65); // Create the header for the CSV List <string> dump = new List <string>() { @"""User"",""Date"",""Status""" }; foreach (Entity e in systemUsers) { // Get the last time a user accessed the system QueryExpression query = new QueryExpression("audit"); query.ColumnSet = new ColumnSet("createdon"); query.Criteria.AddCondition("objectid", ConditionOperator.Equal, e.Id); query.Criteria.AddFilter(filter); query.AddOrder("createdon", OrderType.Descending); query.TopCount = 1; string lastAccess = ""; var result = service.RetrieveMultiple(query).Entities; if (result.Count != 0) { lastAccess = ((DateTime)result[0]["createdon"]).ToShortDateString(); } Console.WriteLine($"{e["fullname"]}: {lastAccess}"); string status = (bool)e["isdisabled"] ? "Disabled" : "Enabled"; // Add that to the CSV we are building dump.Add($@"""{(string)e["fullname"]}"", ""{lastAccess}"",""{status}"""); } // Attempt to write the resulting file try { File.WriteAllLines("result.csv", dump); } catch (Exception ex) { Console.WriteLine("Error writing output file"); Console.WriteLine(ex.Message); Environment.Exit(3); } Console.WriteLine("All done"); Console.ReadLine(); }
private EntityCollection GetSharedEntityScope(Fetch fetch) { var typeField = ""; if (_configuration.EntityName == "account" || _configuration.EntityName == "contact") { typeField = "gsc_recordtype"; } else if (_configuration.EntityName == "product") { typeField = "gsc_producttype"; } else { return(null); } int recordType = 0; Guid webRoleId = Guid.Empty; var context = HttpContext.Current; var request = context.Request.RequestContext; var cookies = request.HttpContext.Request.Cookies; if (cookies != null) { if (cookies["Branch"] != null) { webRoleId = new Guid(cookies["Branch"]["webRoleId"]); } } EntityCollection recordTypeCollection = _service.ServiceContext.RetrieveMultiple(new FetchExpression(fetch.ToXml().ToString())); /* QueryExpression queryRecordType = new QueryExpression(configuration.EntityName); * queryRecordType.ColumnSet = new ColumnSet(typeField); * queryRecordType.Criteria.AddCondition(result.First().LogicalName.ToString() + "id", ConditionOperator.Equal, result.First().Id); * EntityCollection recordTypeCollection = _service.ServiceContext.RetrieveMultiple(queryRecordType);*/ if (recordTypeCollection != null && recordTypeCollection.Entities.Count > 0) { if (recordTypeCollection.Entities[0].Contains(typeField)) { recordType = GetOptionSetId("adx_entitypermission", "gsc_recordtype", recordTypeCollection.Entities[0].FormattedValues[typeField]); } else { return(null); } } QueryExpression queryEntityPermission = new QueryExpression("adx_entitypermission"); queryEntityPermission.ColumnSet = new ColumnSet(true); queryEntityPermission.Criteria.AddCondition("gsc_recordtype", ConditionOperator.Equal, recordType); queryEntityPermission.AddOrder("adx_scope", OrderType.Descending); queryEntityPermission.LinkEntities.Add(new LinkEntity("adx_entitypermission", "adx_entitypermission_webrole", "adx_entitypermissionid", "adx_entitypermissionid", JoinOperator.Inner)); queryEntityPermission.LinkEntities[0].LinkCriteria.AddCondition("adx_webroleid", ConditionOperator.Equal, webRoleId); EntityCollection entityPermissionCollection = _service.ServiceContext.RetrieveMultiple(queryEntityPermission); if (entityPermissionCollection != null && entityPermissionCollection.Entities.Count > 0) { return(entityPermissionCollection); } return(null); }
private void UpdateMLs() { cmbML.Items.Clear(); cmbML.Text = ""; txtFetch.Text = ""; btnOk.Enabled = false; // Instantiate QueryExpression QElist var QElist = new QueryExpression("list"); // Add columns to QElist.ColumnSet QElist.ColumnSet.AddColumns("listname", "query"); QElist.AddOrder("listname", OrderType.Ascending); //// Define filter QElist.Criteria QElist.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0); QElist.Criteria.AddCondition("type", ConditionOperator.Equal, true); QElist.Criteria.AddCondition("query", ConditionOperator.NotNull); var lists = Caller.Service.RetrieveMultiple(QElist); foreach (var list in lists.Entities) { cmbML.Items.Add(new ViewItem(list)); } Enabled = true; }
private List<Entity> BeginShowExistingWebResources() { QueryExpression qe = new QueryExpression("webresource"); qe.ColumnSet = new ColumnSet("webresourceid", "webresourcetype", "name", "displayname"); qe.Criteria.AddCondition("ismanaged", ConditionOperator.Equal, false); qe.Criteria.AddCondition("iscustomizable", ConditionOperator.Equal, true); qe.AddOrder("name", OrderType.Ascending); return this.Sdk.RetrieveMultiple(qe).Entities.ToList(); }
public OrganizationResponse Execute(OrganizationRequest req, XrmFakedContext ctx) { var request = req as RetrieveMultipleRequest; List <Entity> list = null; PagingInfo pageInfo = null; QueryExpression qe; string entityName = null; if (request.Query is QueryExpression) { qe = (request.Query as QueryExpression).Clone(); entityName = qe.EntityName; var linqQuery = XrmFakedContext.TranslateQueryExpressionToLinq(ctx, qe); list = linqQuery.ToList(); } else if (request.Query is FetchExpression) { var fetchXml = (request.Query as FetchExpression).Query; var xmlDoc = XrmFakedContext.ParseFetchXml(fetchXml); qe = XrmFakedContext.TranslateFetchXmlDocumentToQueryExpression(ctx, xmlDoc); entityName = qe.EntityName; var linqQuery = XrmFakedContext.TranslateQueryExpressionToLinq(ctx, qe); list = linqQuery.ToList(); if (xmlDoc.IsAggregateFetchXml()) { list = XrmFakedContext.ProcessAggregateFetchXml(ctx, xmlDoc, list); } } else if (request.Query is QueryByAttribute) { // We instantiate a QueryExpression to be executed as we have the implementation done already var query = request.Query as QueryByAttribute; qe = new QueryExpression(query.EntityName); entityName = qe.EntityName; qe.ColumnSet = query.ColumnSet; qe.Criteria = new FilterExpression(); for (var i = 0; i < query.Attributes.Count; i++) { qe.Criteria.AddCondition(new ConditionExpression(query.Attributes[i], ConditionOperator.Equal, query.Values[i])); } foreach (var order in query.Orders) { qe.AddOrder(order.AttributeName, order.OrderType); } qe.PageInfo = query.PageInfo; // QueryExpression now done... execute it! var linqQuery = XrmFakedContext.TranslateQueryExpressionToLinq(ctx, qe); list = linqQuery.ToList(); } else { throw PullRequestException.NotImplementedOrganizationRequest(request.Query.GetType()); } if (qe.Distinct) { list = GetDistinctEntities(list); } // Handle the top count before taking paging into account if (qe.TopCount != null && qe.TopCount.Value < list.Count) { list = list.Take(qe.TopCount.Value).ToList(); } // Handle TotalRecordCount here? int totalRecordCount = -1; if (qe?.PageInfo?.ReturnTotalRecordCount == true) { totalRecordCount = list.Count; } // Handle paging var pageSize = ctx.MaxRetrieveCount; pageInfo = qe.PageInfo; int pageNumber = 1; if (pageInfo != null && pageInfo.PageNumber > 0) { pageNumber = pageInfo.PageNumber; pageSize = pageInfo.Count == 0 ? ctx.MaxRetrieveCount : pageInfo.Count; } // Figure out where in the list we need to start and how many items we need to grab int numberToGet = pageSize; int startPosition = 0; if (pageNumber != 1) { startPosition = (pageNumber - 1) * pageSize; } if (list.Count < pageSize) { numberToGet = list.Count; } else if (list.Count - pageSize * (pageNumber - 1) < pageSize) { numberToGet = list.Count - (pageSize * (pageNumber - 1)); } var recordsToReturn = startPosition + numberToGet > list.Count ? new List <Entity>() : list.GetRange(startPosition, numberToGet); recordsToReturn.ForEach(e => e.ApplyDateBehaviour(ctx)); recordsToReturn.ForEach(e => PopulateFormattedValues(e)); var response = new RetrieveMultipleResponse { Results = new ParameterCollection { { "EntityCollection", new EntityCollection(recordsToReturn) } } }; response.EntityCollection.EntityName = entityName; response.EntityCollection.MoreRecords = (list.Count - pageSize * pageNumber) > 0; response.EntityCollection.TotalRecordCount = totalRecordCount; if (response.EntityCollection.MoreRecords) { var first = response.EntityCollection.Entities.First(); var last = response.EntityCollection.Entities.Last(); response.EntityCollection.PagingCookie = $"<cookie page=\"{pageNumber}\"><{first.LogicalName}id last=\"{last.Id.ToString("B").ToUpper()}\" first=\"{first.Id.ToString("B").ToUpper()}\" /></cookie>"; } return(response); }
private Task<List<Privilege>> LoadPrivileges(Guid roleId) { return Task.Run(() => { var query = new QueryExpression("privilege"); query.NoLock = true; query.ColumnSet = new ColumnSet("name", "accessright"); query.AddOrder("name", OrderType.Ascending); var typecode = query.AddLink("privilegeobjecttypecodes", "privilegeid", "privilegeid", JoinOperator.LeftOuter); typecode.EntityAlias = "privilegeobjecttypecode"; typecode.Columns = new ColumnSet("objecttypecode"); var intersect = query.AddLink("roleprivileges", "privilegeid", "privilegeid"); intersect.EntityAlias = "roleprivilege"; intersect.Columns = new ColumnSet("privilegedepthmask"); var role = intersect.AddLink("role", "roleid", "roleid"); role.LinkCriteria.AddCondition("roleid", ConditionOperator.Equal, roleId); var result = _service.RetrieveMultiple(query); return result.Entities.Select(e => new Privilege { PrivilegeId = e.Id, Name = e["name"] as string, AccessRight = GetAccessRight(e), LogicalName = GetEntityName(e), Depth = GetDepth(e) }).ToList(); }); }
protected DateTime lastActivity(string username, string subject) { using (OrganizationService service = new OrganizationService(OurConnect())) { ConditionExpression toCondition = new ConditionExpression(); ConditionExpression fromCondition = new ConditionExpression(); ConditionExpression subjectCondition = new ConditionExpression(); toCondition.AttributeName = consts.to; toCondition.Operator = ConditionOperator.Equal; toCondition.Values.Add(username); fromCondition.AttributeName = consts.from; fromCondition.Operator = ConditionOperator.Equal; fromCondition.Values.Add(_ApplicationName); FilterExpression filter = new FilterExpression(); filter.Conditions.Add(toCondition); filter.Conditions.Add(fromCondition); if (subject != String.Empty) { subjectCondition.AttributeName = consts.subject; subjectCondition.Operator = ConditionOperator.Equal; subjectCondition.Values.Add(subject); } QueryExpression query = new QueryExpression(consts.activities); query.ColumnSet.AddColumn(consts.activitytime); query.AddOrder(consts.activitytime, OrderType.Descending); query.Criteria.AddFilter(filter); EntityCollection collection = service.RetrieveMultiple(query); return (DateTime)collection.Entities[0][consts.activitytime]; } }
public static QueryExpression BuildQuery(string entityType, IEnumerable<string> fields, IEnumerable<ConditionExpression> filters, IEnumerable<string> sortFields) { var query = new QueryExpression(entityType); if (filters != null) { foreach (var condition in filters) query.Criteria.AddCondition(condition); } if (sortFields != null) { foreach (var sortField in sortFields) query.AddOrder(sortField, OrderType.Ascending); } if (fields != null) query.ColumnSet = new ColumnSet(fields.ToArray()); else query.ColumnSet = new ColumnSet(true); return query; }
public void LocalCrmTests_OrderBy() { var service = GetService(); service.Create(new Contact() {FirstName = "Chuck", LastName = "Adams"}); service.Create(new Contact() {FirstName = "Anna", LastName = "Adams"}); service.Create(new Contact() {FirstName = "Bill", LastName = "Adams"}); var qe = new QueryExpression(Contact.EntityLogicalName); qe.ColumnSet = new ColumnSet(true); // Ascending Order Test qe.AddOrder("firstname", OrderType.Ascending); var results = service.GetEntities<Contact>(qe); Assert.AreEqual("Anna", results[0].FirstName, "Ascending Ordering failed. \"Anna\" should have been returned first"); Assert.AreEqual("Bill", results[1].FirstName, "Ascending Ordering failed. \"Bill\" should have been returned second"); Assert.AreEqual("Chuck", results[2].FirstName, "Ascending Ordering failed. \"Chuck\" should have been returned third"); // Descending Order Test qe.Orders[0].OrderType = OrderType.Descending; results = service.GetEntities<Contact>(qe); Assert.AreEqual("Chuck", results[0].FirstName, "Descending Ordering failed. \"Chuck\" should have been returned first"); Assert.AreEqual("Bill", results[1].FirstName, "Descending Ordering failed. \"Bill\" should have been returned second"); Assert.AreEqual("Anna", results[2].FirstName, "Descending Ordering failed. \"Anna\" should have been returned third"); // Add Dups service.Create(new Contact() {FirstName = "Chuck", LastName = "Bell"}); service.Create(new Contact() {FirstName = "Anna", LastName = "Bell"}); service.Create(new Contact() {FirstName = "Anna", LastName = "Carter"}); service.Create(new Contact() {FirstName = "Bill", LastName = "Bell"}); service.Create(new Contact() {FirstName = "Bill", LastName = "Carter"}); service.Create(new Contact() {FirstName = "Chuck", LastName = "Carter"}); // Order By Descending First Then By Ascending Last Test qe.AddOrder("lastname", OrderType.Ascending); results = service.GetEntities<Contact>(qe); Assert.AreEqual("Chuck Adams", results[0].FullName, "Descending then Ascending Ordering failed. \"Chuck Adams\" should have been returned first"); Assert.AreEqual("Chuck Bell", results[1].FullName, "Descending then Ascending Ordering failed. \"Chuck Bell\" should have been returned second"); Assert.AreEqual("Chuck Carter", results[2].FullName, "Descending then Ascending Ordering failed. \"Chuck Carter\" should have been returned third"); Assert.AreEqual("Bill Adams", results[3].FullName, "Descending then Ascending Ordering failed. \"Bill Adams\" should have been returned forth"); Assert.AreEqual("Bill Bell", results[4].FullName, "Descending then Ascending Ordering failed. \"Bill Bell\" should have been returned fifth"); Assert.AreEqual("Bill Carter", results[5].FullName, "Descending then Ascending Ordering failed. \"Bill Carter\" should have been returned sixth"); Assert.AreEqual("Anna Adams", results[6].FullName, "Descending then Ascending Ordering failed. \"Anna Adams\" should have been returned seventh"); Assert.AreEqual("Anna Bell", results[7].FullName, "Descending then Ascending Ordering failed. \"Anna Bell\" should have been returned eighth"); Assert.AreEqual("Anna Carter", results[8].FullName, "Descending then Ascending Ordering failed. \"Anna Carter\" should have been returned nineth"); // Order By Ascending First Then By Descending Last Test qe.Orders.Clear(); qe.AddOrder("firstname", OrderType.Ascending); qe.AddOrder("lastname", OrderType.Descending); results = service.GetEntities<Contact>(qe); Assert.AreEqual("Anna Carter", results[0].FullName, "Ascending then Descending Ordering failed. \"Anna Carter\" should have been returned first"); Assert.AreEqual("Anna Bell", results[1].FullName, "Ascending then Descending Ordering failed. \"Anna Bell\" should have been returned second"); Assert.AreEqual("Anna Adams", results[2].FullName, "Ascending then Descending Ordering failed. \"Anna Adams\" should have been returned thrid"); Assert.AreEqual("Bill Carter", results[3].FullName, "Ascending then Descending Ordering failed. \"Bill Carter\" should have been returned forth"); Assert.AreEqual("Bill Bell", results[4].FullName, "Ascending then Descending Ordering failed. \"Bill Bell\" should have been returned fifth"); Assert.AreEqual("Bill Adams", results[5].FullName, "Ascending then Descending Ordering failed. \"Bill Adams\" should have been returned sixth"); Assert.AreEqual("Chuck Carter", results[6].FullName, "Ascending then Descending Ordering failed. \"Chuck Carter\" should have been returned seventh"); Assert.AreEqual("Chuck Bell", results[7].FullName, "Ascending then Descending Ordering failed. \"Chuck Bell\" should have been returned eighth"); Assert.AreEqual("Chuck Adams", results[8].FullName, "Ascending then Descending Ordering failed. \"Chuck Adams\" should have been returned nineth"); // Order by Date Ascending qe.Orders.Clear(); qe.AddOrder("createdon", OrderType.Ascending); results = service.GetEntities<Contact>(qe); Assert.AreEqual("Adams", results[0].LastName, "Ascending Date Ordering failed. \"Adams\" should have been returned first"); Assert.AreEqual("Adams", results[1].LastName, "Ascending Date Ordering failed. \"Adams\" should have been returned first"); Assert.AreEqual("Adams", results[2].LastName, "Ascending Date Ordering failed. \"Adams\" should have been returned first"); // Order by Date Descending qe.Orders.Clear(); qe.AddOrder("createdon", OrderType.Descending); results = service.GetEntities<Contact>(qe); Assert.AreEqual("Adams", results[8].LastName, "Ascending Date Ordering failed. \"Adams\" should have been returned last"); Assert.AreEqual("Adams", results[7].LastName, "Ascending Date Ordering failed. \"Adams\" should have been returned last"); Assert.AreEqual("Adams", results[6].LastName, "Ascending Date Ordering failed. \"Adams\" should have been returned last"); }
internal void LoadViews(Action viewsLoaded) { if (working) { return; } if (entities == null || entities.Count == 0) { LoadEntities(viewsLoaded); return; } working = true; WorkAsync("Loading views...", (bgworker, workargs) => { EnableControls(false); if (views == null || views.Count == 0) { if (Service == null) { throw new Exception("Need a connection to load views."); } var qex = new QueryExpression("savedquery"); qex.ColumnSet = new ColumnSet("name", "returnedtypecode", "fetchxml"); qex.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0); qex.Criteria.AddCondition("querytype", ConditionOperator.In, 0, 32); qex.AddOrder("name", OrderType.Ascending); bgworker.ReportProgress(33, "Loading system views..."); var sysviews = Service.RetrieveMultiple(qex); foreach (var view in sysviews.Entities) { var entityname = view["returnedtypecode"].ToString(); if (!string.IsNullOrWhiteSpace(entityname) && entities.ContainsKey(entityname)) { if (views == null) { views = new Dictionary<string, List<Entity>>(); } if (!views.ContainsKey(entityname + "|S")) { views.Add(entityname + "|S", new List<Entity>()); } views[entityname + "|S"].Add(view); } } qex.EntityName = "userquery"; bgworker.ReportProgress(66, "Loading user views..."); var userviews = Service.RetrieveMultiple(qex); foreach (var view in userviews.Entities) { var entityname = view["returnedtypecode"].ToString(); if (!string.IsNullOrWhiteSpace(entityname) && entities.ContainsKey(entityname)) { if (views == null) { views = new Dictionary<string, List<Entity>>(); } if (!views.ContainsKey(entityname + "|U")) { views.Add(entityname + "|U", new List<Entity>()); } views[entityname + "|U"].Add(view); } } bgworker.ReportProgress(100, "Finalizing..."); } }, (completedargs) => { working = false; EnableControls(true); if (completedargs.Error != null) { MessageBox.Show(completedargs.Error.Message); } else { viewsLoaded(); } }, (changeargs) => { SetWorkingMessage(changeargs.UserState.ToString()); }); }
public void When_ordering_by_guid_fields_expected_result_is_returned() { List<Entity> contactList = new List<Entity>(); var g1 = new Guid(12, 0, 0, new byte[] { new byte(), new byte(), new byte(), new byte(), new byte(), new byte(), new byte(), new byte() }); var g2 = new Guid(24, 0, 0, new byte[] { new byte(), new byte(), new byte(), new byte(), new byte(), new byte(), new byte(), new byte() }); Entity contact1 = new Entity("contact"); contact1.Id = Guid.NewGuid(); contact1.Attributes["firstname"] = "Fred"; contact1.Attributes["new_orderbyfield"] = g1; Entity contact2 = new Entity("contact"); contact2.Id = Guid.NewGuid(); contact2.Attributes["firstname"] = "Jo"; contact2.Attributes["new_orderbyfield"] = g2; contactList.Add(contact2); contactList.Add(contact1); var context = new XrmFakedContext(); context.Initialize(contactList); var service = context.GetFakedOrganizationService(); QueryExpression qry = new QueryExpression("contact"); qry.ColumnSet = new ColumnSet(true); qry.AddOrder("new_orderbyfield", OrderType.Ascending); var results = service.RetrieveMultiple(qry); var firstResultValue = (Guid)results.Entities[0]["new_orderbyfield"]; Assert.Equal(g1, firstResultValue); }
private Task<IEnumerable<User>> RetrieveUsers() { return Task.Run(() => { var query = new QueryExpression("systemuser"); query.NoLock = true; query.ColumnSet = new ColumnSet("domainname", "fullname", "systemuserid"); query.AddOrder("fullname", OrderType.Ascending); if (SelectedRole.RoleId == Guid.Empty) { var userroles = query.AddLink("systemuserroles", "systemuserid", "systemuserid", JoinOperator.LeftOuter); userroles.EntityAlias = "roles"; query.Criteria.AddCondition("roles", "roleid", ConditionOperator.Null); } else { var userroles = query.AddLink("systemuserroles", "systemuserid", "systemuserid"); userroles.LinkCriteria.AddCondition("roleid", ConditionOperator.Equal, SelectedRole.RoleId); } var result = _service.RetrieveMultiple(query); var users = result.Entities.Select(e => new User { UserId = e.Id, DomainName = e.Contains("domainname") ? e["domainname"] as string : null, FullName = e.Contains("fullname") ? e["fullname"] as string : null }); return users; }); }
public static IEnumerable<Entity> Get( this IOrganizationService service, out int totalItemsCount, string entityname, bool allattributes = false, IEnumerable<OrderBy> orders = null, IEnumerable<ConditionExpression> conditions = null, IEnumerable<string> attrs = null, int? page = null, int? count = null) { ObjectCacheManager.GetInstance().Clear(); if (string.IsNullOrEmpty(entityname)) throw new ArgumentNullException("entityname"); var query = new QueryExpression(entityname); if (attrs != null) { var a = attrs.ToArray(); if (allattributes) { query.ColumnSet = new ColumnSet(true); } else { query.ColumnSet = a.Count() == 0 ? new ColumnSet(false) : new ColumnSet(a); } } if (conditions != null) { conditions.ToList().ForEach(x => { query.Criteria.AddCondition(x); }); } if (orders != null) { orders.ToList().ForEach(x => { query.AddOrder(x.AttributeName, x.OrderType); }); } List<Entity> ents; totalItemsCount = 0; if (page != null && count != null) { query.PageInfo = new PagingInfo { Count = count.Value, PageNumber = page.Value, PagingCookie = null, ReturnTotalRecordCount = true }; ents = service.GetPage(query, out totalItemsCount); } else { ents = service.GetAllEntities(query); } return ents; }
public void When_ordering_by_entity_reference_fields_expected_result_is_returned() { List<Entity> contactList = new List<Entity>(); Entity contact1 = new Entity("contact"); contact1.Id = Guid.NewGuid(); contact1.Attributes["firstname"] = "Fred"; contact1.Attributes["lastname"] = "Bloggs"; contact1.Attributes["new_somefield"] = new EntityReference() { Id = Guid.NewGuid(), Name = "Jordi" }; Entity contact2 = new Entity("contact"); contact2.Id = Guid.NewGuid(); contact2.Attributes["firstname"] = "Jo"; contact2.Attributes["lastname"] = "Bloggs"; contact2.Attributes["new_somefield"] = new EntityReference() { Id = Guid.NewGuid(), Name = "Skuba" }; contactList.Add(contact2); contactList.Add(contact1); var context = new XrmFakedContext(); context.Initialize(contactList); var service = context.GetFakedOrganizationService(); QueryExpression qry = new QueryExpression("contact"); qry.ColumnSet = new ColumnSet(true); qry.AddOrder("new_somefield", OrderType.Ascending); var results = service.RetrieveMultiple(qry); var firstResultValue = results.Entities[0]["new_somefield"] as EntityReference; Assert.Equal("Jordi", firstResultValue.Name); }
private Task<List<Assembly>> LoadAssemblies() { return Task.Run(() => { var query = new QueryExpression("pluginassembly"); query.Distinct = true; query.NoLock = true; query.ColumnSet = new ColumnSet("name", "pluginassemblyid"); query.AddOrder("name", OrderType.Ascending); var type = query.AddLink("plugintype", "pluginassemblyid", "pluginassemblyid", JoinOperator.Inner); type.LinkCriteria.AddCondition("typename", ConditionOperator.NotLike, "Microsoft.Crm.%"); type.LinkCriteria.AddCondition("typename", ConditionOperator.NotLike, "ActivityFeeds.%"); var result = _service.RetrieveMultiple(query); var assemblies = result.Entities.Select(e => new Assembly { AssemblyId = e.Id, Export = false, Name = e["name"] as string, RegisteredStepCount = 0 }).ToList(); foreach (var assembly in assemblies) { query = new QueryExpression("sdkmessageprocessingstep"); query.Distinct = true; query.NoLock = true; query.ColumnSet = new ColumnSet("sdkmessageprocessingstepid"); type = query.AddLink("plugintype", "plugintypeid", "plugintypeid"); type.LinkCriteria.AddCondition("pluginassemblyid", ConditionOperator.Equal, assembly.AssemblyId); result = _service.RetrieveMultiple(query); assembly.RegisteredStepCount = result.Entities.Count; } return assemblies; }); }
private void getViews() { #region Reset View Stuff int selectedWorkflowIndex = 0; ExecutionRecordSet.Entities.Clear(); Guid WorkflowId = Guid.Empty; _views.Entities.Clear(); _selectedView = null; this.Invoke((MethodInvoker)delegate() { cmbViews.Items.Clear(); rtxtFetchXML.Clear(); radViews.Checked = true; radFetchXML.Checked = false; txtRecordCount.Clear(); //progressBar1.Style = ProgressBarStyle.Marquee; selectedWorkflowIndex = cmbWorkflows.SelectedIndex; }); #endregion Reset View Stuff _selectedWorkflow = _workflows[selectedWorkflowIndex]; #region System Views Loop QueryExpression query = new QueryExpression("savedquery"); query.ColumnSet.AllColumns = true; query.AddOrder("name", OrderType.Ascending); query.Criteria = new FilterExpression(); //query.Criteria.AddCondition("returnedtypecode", ConditionOperator.Equal, workflowEntity); FilterExpression childFilter = query.Criteria.AddFilter(LogicalOperator.And); childFilter.AddCondition("querytype", ConditionOperator.Equal, 0); childFilter.AddCondition("returnedtypecode", ConditionOperator.Equal, _selectedWorkflow["primaryentity"]); childFilter.AddCondition("statecode", ConditionOperator.Equal, 0); childFilter.AddCondition("fetchxml", ConditionOperator.NotNull); EntityCollection _ManagedViews = service.RetrieveMultiple(query); _views.Entities.AddRange(_ManagedViews.Entities); foreach (var item in _ManagedViews.Entities) { this.Invoke((MethodInvoker)delegate() { cmbViews.Items.Add(item["name"]); }); } #endregion System Views Loop #region Personal View Divider ////////////////////////////////////////////////////////////////////////////// this.Invoke((MethodInvoker)delegate() { cmbViews.Items.Add("---------------------Personal Views-----------------------"); }); Entity _dummyView = new Entity("userquery"); _dummyView.Id = _defaultGuid; _dummyView["name"] = "Dummy View"; _views.Entities.Add(_dummyView); ; //viewGuidList.Add(_viewCounter, _defaultGuid); //viewFetchList.Add(_defaultGuid, "Personal Views"); //_viewCounter++; ////////////////////////////////////////////////////////////////////////////// #endregion Personal View Divider #region Personal Views Loop QueryExpression query2 = new QueryExpression("userquery"); query2.ColumnSet.AllColumns = true; query.AddOrder("name", OrderType.Ascending); query2.Criteria = new FilterExpression(); //query.Criteria.AddCondition("ismanaged", ConditionOperator.Equal, true); FilterExpression childFilter2 = query2.Criteria.AddFilter(LogicalOperator.And); childFilter2.AddCondition("querytype", ConditionOperator.Equal, 0); childFilter2.AddCondition("returnedtypecode", ConditionOperator.Equal, _selectedWorkflow["primaryentity"]); childFilter2.AddCondition("statecode", ConditionOperator.Equal, 0); childFilter2.AddCondition("fetchxml", ConditionOperator.NotNull); EntityCollection _UserViews = service.RetrieveMultiple(query2); _views.Entities.AddRange(_UserViews.Entities); foreach (var item in _UserViews.Entities) { //if (item.Attributes.Contains("fetchxml")) //{ //viewGuidList.Add(_viewCounter, item.Id); //viewFetchList.Add(item.Id, item["fetchxml"].ToString()); this.Invoke((MethodInvoker)delegate() { cmbViews.Items.Add(item["name"]); }); //_viewCounter++; //} } #endregion Personal Views Loop this.Invoke((MethodInvoker)delegate() { cmbViews.Text = "Select a View to run the workflow against"; //progressBar1.Style = ProgressBarStyle.Continuous; }); }
private void RefreshTraces() { if (Service != null) { var QEplugintracelog = new QueryExpression("plugintracelog"); QEplugintracelog.ColumnSet.AddColumns( "performanceexecutionstarttime", "operationtype", "messagename", "plugintracelogid", "primaryentity", "exceptiondetails", "messageblock", "performanceexecutionduration", "createdon", "typename", "depth", "mode"); if (chkRecords.Checked) { QEplugintracelog.TopCount = (int)numRecords.Value; } if (checkDateFrom.Checked) { QEplugintracelog.Criteria.AddCondition("createdon", ConditionOperator.GreaterEqual, GetDateTimeAsUTC(dateFrom.Value)); } if (checkDateTo.Checked) { QEplugintracelog.Criteria.AddCondition("createdon", ConditionOperator.LessEqual, GetDateTimeAsUTC(dateTo.Value)); } if (chkPlugin.Checked && !string.IsNullOrWhiteSpace(comboPlugin.Text)) { var pluginFilter = QEplugintracelog.Criteria.AddFilter(LogicalOperator.Or); foreach (var plugin in comboPlugin.Text.Split(',')) { if (string.IsNullOrWhiteSpace(plugin)) { continue; } pluginFilter.AddCondition("typename", plugin.Contains("*") ? ConditionOperator.Like : ConditionOperator.Equal, plugin.Replace("*", "%").Trim()); } } if (chkMessage.Checked && !string.IsNullOrWhiteSpace(comboMessage.Text)) { QEplugintracelog.Criteria.AddCondition("messagename", ConditionOperator.Equal, comboMessage.Text); } if (chkEntity.Checked && !string.IsNullOrWhiteSpace(comboEntity.Text)) { var entityFilter = QEplugintracelog.Criteria.AddFilter(LogicalOperator.Or); foreach (var entity in comboEntity.Text.Split(',')) { if (string.IsNullOrWhiteSpace(entity)) { continue; } entityFilter.AddCondition("primaryentity", entity.Contains("*") ? ConditionOperator.Like : ConditionOperator.Equal, entity.Replace("*", "%").Trim()); } } if (chkExceptions.Checked) { QEplugintracelog.Criteria.AddCondition("exceptiondetails", ConditionOperator.NotNull); QEplugintracelog.Criteria.AddCondition("exceptiondetails", ConditionOperator.NotEqual, ""); } if (rbModeSync.Checked) { QEplugintracelog.Criteria.AddCondition("mode", ConditionOperator.Equal, 0); } else if (rbModeAsync.Checked) { QEplugintracelog.Criteria.AddCondition("mode", ConditionOperator.Equal, 1); } if (chkDurationMin.Checked) { QEplugintracelog.Criteria.AddCondition("performanceexecutionduration", ConditionOperator.GreaterEqual, (int)numDurationMin.Value); } if (chkDurationMax.Checked) { QEplugintracelog.Criteria.AddCondition("performanceexecutionduration", ConditionOperator.LessEqual, (int)numDurationMax.Value); } QEplugintracelog.AddOrder("performanceexecutionstarttime", OrderType.Descending); var asyncinfo = new WorkAsyncInfo() { Message = "Loading trace log records", Work = (a, args) => { args.Result = Service.RetrieveMultiple(QEplugintracelog); }, PostWorkCallBack = (args) => { if (args.Error != null) { MessageBox.Show($"Failed to load trace logs:\n{args.Error.Message}", "Load", MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (args.Result is EntityCollection) { PopulateGrid(args.Result as EntityCollection); } } }; WorkAsync(asyncinfo); } }