Combining query filters with CRM FilterExpression - c#

I am trying to write the following a (pseudo)query in C# for CRM 4:
Status = active
AND
(
mail = somemail
OR
(
firstName like firstNameSearchTerm
AND
lastName like LastNameSearchTerm
)
)
The problem is, that middle names might be part of firstName or LastName. I am having a hard time putting this into ConditionExpressions / FilterExpressions.
#region mail conditions
// Create the ConditionExpression.
ConditionExpression mail1Condition = new ConditionExpression();
mail1Condition.AttributeName = "emailaddress1";
mail1Condition.Operator = ConditionOperator.Like;
mail1Condition.Values = new object[] { Registration.Email };
ConditionExpression mail2Condition = new ConditionExpression();
mail2Condition.AttributeName = "emailaddress2";
mail2Condition.Operator = ConditionOperator.Like;
mail2Condition.Values = new object[] { Registration.Email };
ConditionExpression mail3Condition = new ConditionExpression();
mail3Condition.AttributeName = "emailaddress3";
mail3Condition.Operator = ConditionOperator.Like;
mail3Condition.Values = new object[] { Registration.Email };
ConditionExpression statusCondition = new ConditionExpression();
statusCondition.AttributeName = "statuscode";
statusCondition.Operator = ConditionOperator.Equal;
statusCondition.Values = new object[] { "1" };
FilterExpression mailFilter = new FilterExpression();
mailFilter.FilterOperator = LogicalOperator.Or;
mailFilter.Conditions = new ConditionExpression[] { mail1Condition, mail2Condition, mail3Condition };
#endregion mail conditions
#region name conditions
/* FIRST NAME */
FilterExpression firstNameFilter = new FilterExpression();
firstNameFilter.FilterOperator = LogicalOperator.Or;
List<ConditionExpression> firstNameConditions = new List<ConditionExpression>();
var firstAndMiddleNames = Registration.FirstName.Trim().Split(' ');
firstAndMiddleNames = firstAndMiddleNames.Select(s => s.Replace(s, "%"+s+"%")).ToArray(); // Add wildcard search
foreach (var item in firstAndMiddleNames)
{
ConditionExpression firstNameCondition = new ConditionExpression();
firstNameCondition.AttributeName = "firstname";
firstNameCondition.Operator = ConditionOperator.Like;
firstNameCondition.Values = new object[] { item };
firstNameConditions.Add(firstNameCondition);
}
firstNameFilter.Conditions = firstNameConditions.ToArray();
/* LAST NAME */
FilterExpression lastNameFilter = new FilterExpression();
lastNameFilter.FilterOperator = LogicalOperator.Or;
List<ConditionExpression> lastNameConditions = new List<ConditionExpression>();
var lastAndMiddleNames = Registration.LastName.Trim().Split(' ');
lastAndMiddleNames = lastAndMiddleNames.Select(s => s.Replace(s, "%" + s + "%")).ToArray(); // Add wildcard search
foreach (var item in lastAndMiddleNames)
{
ConditionExpression lastNameCondition = new ConditionExpression();
lastNameCondition.AttributeName = "lastname";
lastNameCondition.Operator = ConditionOperator.Like;
lastNameCondition.Values = new object[] { item };
lastNameConditions.Add(lastNameCondition);
}
lastNameFilter.Conditions = firstNameConditions.ToArray();
#endregion name conditions
FilterExpression nameFilter = new FilterExpression();
nameFilter.FilterOperator = LogicalOperator.And;
nameFilter.Filters = new FilterExpression[] { firstNameFilter, lastNameFilter };
// Create the outer most filter to AND the state condition with the other filters
FilterExpression stateFilter = new FilterExpression();
stateFilter.FilterOperator = LogicalOperator.And;
stateFilter.Conditions = new ConditionExpression[] { statusCondition };
stateFilter.Filters = new FilterExpression[] { nameFilter };
query.EntityName = EntityName.contact.ToString();
query.Criteria = stateFilter;
query.ColumnSet = columns;
BusinessEntityCollection contacts = Service.RetrieveMultiple(query);
I
The query currently bypasses the mail filter for debugging purposes.
The result is that it finds all contacts matching the firstname or lastname (should be AND). Why???

There was a simple typo in the following line
lastNameFilter.Conditions = firstNameConditions.ToArray();
should be
lastNameFilter.Conditions = lastNameConditions.ToArray();

Related

add two group into one group in c#

I have two groups like below, theyh have different data. Based on both I need to create an xml file .
How can I write a for-loop for both groups and generate a single xml file?
var groups = checkFile.AsEnumerable().GroupBy(x => new { DocNum = x.Field<int>("orderid"), Type = x.Field<string>("Type"), ProdName = x.Field<string>("ProdName"), Status = x.Field<string>("Status"), productno = x.Field<string>("productno"), uom = x.Field<string>("uom"), customer = x.Field<string>("customer"), remark = x.Field<string>("remark"), U_JobNumber = x.Field<string>("U_JobNumber"), U_SalesPerson = x.Field<string>("U_SalesPerson"), U_POnum = x.Field<string>("U_POnum"), U_JobType = x.Field<string>("U_JobType"), PlannedQty = x.Field<decimal>("PlannedQty"), OriginNum = x.Field<int?>("OriginNum"), orderdate = x.Field<DateTime>("orderdate"), duedate = x.Field<DateTime>("duedate"), DocTotal = x.Field<decimal>("DocTotal") });
var groups2 = checkFile2.AsEnumerable().GroupBy(x => new { DocNum = x.Field<int>("DocNum") });
//now i need to take both group data inside this loop to print the file
foreach (var group in groups)
{
var stringwriter = new StringWriter();
using (var xmlWriter = XmlWriter.Create(stringwriter, new XmlWriterSettings { Indent = true }))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("Root");
xmlWriter.WriteEndElement();
}
var xml = stringwriter.ToString();
XmlDocument docSave = new XmlDocument();
docSave.LoadXml(stringwriter.ToString());
docSave.Save(System.IO.Path.Combine(#SystemSettings.ImportBankStatementPendingFolderPath, "DocNum -" + group.Key.DocNum + ".xml"));
count++;
}
Try following :
DataTable checkFile = new DataTable();
var groups = checkFile.AsEnumerable().GroupBy(x => new
{
DocNum = x.Field<int>("orderid"),
Type = x.Field<string>("Type"),
ProdName = x.Field<string>("ProdName"),
Status = x.Field<string>("Status"),
productno = x.Field<string>("productno"),
uom = x.Field<string>("uom"),
customer = x.Field<string>("customer"),
remark = x.Field<string>("remark"),
U_JobNumber = x.Field<string>("U_JobNumber"),
U_SalesPerson = x.Field<string>("U_SalesPerson"),
U_POnum = x.Field<string>("U_POnum"),
U_JobType = x.Field<string>("U_JobType"),
PlannedQty = x.Field<decimal>("PlannedQty"),
OriginNum = x.Field<int?>("OriginNum"),
orderdate = x.Field<DateTime>("orderdate"),
duedate = x.Field<DateTime>("duedate"),
DocTotal = x.Field<decimal>("DocTotal")
});
DataTable checkFile2 = new DataTable();
//now i need to take both group data inside this loop to print the file
foreach (var group in groups)
{
List<DataRow> groups2 = checkFile2.AsEnumerable().Where(x => group.Key.DocNum == x.Field<int>("DocNum")).ToList();
}

Need dynamic variable names in C# for ebay feeds

I need these varaible names to be dynamic.
To give you an example of what I'm looking at > https://ebaydts.com/eBayKBDetails?KBid=1742
Now in the above link, it has some code for variaitons.
//Specify Variations
VariationTypeCollection VarCol = new VariationTypeCollection();
//Variation 1 - Black S
VariationType var1 = new VariationType();
var1.SKU = "VAR1";
var1.Quantity = 10;
var1.StartPrice = new AmountType();
var1.StartPrice.currencyID = CurrencyCodeType.AUD;
var1.StartPrice.Value = 35;
var1.VariationSpecifics = new NameValueListTypeCollection();
NameValueListType Var1Spec1 = new NameValueListType();
StringCollection Var1Spec1Valuecoll = new StringCollection();
Var1Spec1.Name = "Colour";
Var1Spec1Valuecoll.Add("Black");
Var1Spec1.Value = Var1Spec1Valuecoll;
var1.VariationSpecifics.Add(Var1Spec1);
NameValueListType Var1Spec2 = new NameValueListType();
StringCollection Var1Spec2Valuecoll = new StringCollection();
Var1Spec2.Name = "Size";
Var1Spec2Valuecoll.Add("S");
Var1Spec2.Value = Var1Spec2Valuecoll;
var1.VariationSpecifics.Add(Var1Spec2);
VarCol.Add(var1);
//Variation 2 - Black L
VariationType var2 = new VariationType();
var2.SKU = "VAR2";
var2.Quantity = 10;
var2.StartPrice = new AmountType();
var2.StartPrice.currencyID = CurrencyCodeType.AUD;
var2.StartPrice.Value = 45;
var2.VariationSpecifics = new NameValueListTypeCollection();
NameValueListType Var2Spec1 = new NameValueListType();
StringCollection Var2Spec1Valuecoll = new StringCollection();
Var2Spec1.Name = "Colour";
Var2Spec1Valuecoll.Add("Black");
Var2Spec1.Value = Var2Spec1Valuecoll;
var2.VariationSpecifics.Add(Var2Spec1);
NameValueListType Var2Spec2 = new NameValueListType();
StringCollection Var2Spec2Valuecoll = new StringCollection();
Var2Spec2.Name = "Size";
Var2Spec2Valuecoll.Add("L");
Var2Spec2.Value = Var2Spec2Valuecoll;
var2.VariationSpecifics.Add(Var2Spec2);
VarCol.Add(var2);
So the code I'm working with I would Like dynamically create the varaible names, because as you can imagine there is no way for me to know how many variations each product has.
Sure i could count the amount of variations, and set up an if else structure
if (count == 1) {
//some code
}
else if (count == 2) {
//some code
}
But that doesn't seem like a good solution.
At the moment variables are required to be output inside a for each loop
Here is the code I'm working with:
string UPC = "";
string Brand = "";
string MPN = "";
if (!String.IsNullOrEmpty(product.Gtin))
UPC = product.Gtin;
if (!String.IsNullOrEmpty(ebayProduct.EbayProductBrandName))
Brand = ebayProduct.EbayProductBrandName;
if (!String.IsNullOrEmpty(product.ManufacturerPartNumber))
MPN = product.ManufacturerPartNumber;
//create the call object
AddFixedPriceItemCall AddFPItemCall = new AddFixedPriceItemCall(context);
AddFPItemCall.AutoSetItemUUID = true;
//create an item object and set the properties
ItemType item = new ItemType();
//set the item condition depending on the value from GetCategoryFeatures
item.ConditionID = 1000; //new
//Basic properties of a listing
item.Country = CountryCodeType.AU;
item.Currency = CurrencyCodeType.AUD;
//Track item by SKU
item.InventoryTrackingMethod = InventoryTrackingMethodCodeType.SKU;
item.SKU = ebayProduct.EbayProductSKU;
if (!String.IsNullOrEmpty(ebayProduct.EbayProductDescription))
item.Description = ebayProduct.EbayProductDescription;
else
item.Description = "This product is brand new.";
if (!String.IsNullOrEmpty(ebayProduct.EbayProductTitle))
item.Title = ebayProduct.EbayProductTitle;
item.SubTitle = ebayProduct.EbayProductItemSubtitle;
item.ListingDuration = "GTC";
item.ItemSpecifics = new NameValueListTypeCollection();
NameValueListTypeCollection ItemSpecs = new NameValueListTypeCollection();
var productSpecAttributes = product.ProductSpecificationAttributes.ToList();
foreach (var val in productSpecAttributes)
{
StringCollection valueCol1 = new StringCollection();
NameValueListType nv1 = new NameValueListType();
nv1.Name = val.SpecificationAttributeOption.SpecificationAttribute.Name.Replace(":", "");
valueCol1.Add(val.CustomValue);
nv1.Value = valueCol1;
ItemSpecs.Add(nv1);
}
item.ItemSpecifics = ItemSpecs;
item.PaymentMethods = new BuyerPaymentMethodCodeTypeCollection();
item.PaymentMethods.Add(BuyerPaymentMethodCodeType.PayPal);
item.PayPalEmailAddress = "test#test.com";
item.PostalCode = "5000";
//Specify Shipping Services
item.DispatchTimeMax = 3;
item.ShippingDetails = new ShippingDetailsType();
item.ShippingDetails.ShippingServiceOptions = new ShippingServiceOptionsTypeCollection();
ShippingServiceOptionsType shipservice1 = new ShippingServiceOptionsType();
shipservice1.ShippingService = "AU_Regular";
shipservice1.ShippingServicePriority = 1;
shipservice1.ShippingServiceCost = new AmountType();
shipservice1.ShippingServiceCost.currencyID = CurrencyCodeType.AUD;
shipservice1.ShippingServiceCost.Value = 1.0;
shipservice1.ShippingServiceAdditionalCost = new AmountType();
shipservice1.ShippingServiceAdditionalCost.currencyID = CurrencyCodeType.AUD;
shipservice1.ShippingServiceAdditionalCost.Value = 1.0;
item.ShippingDetails.ShippingServiceOptions.Add(shipservice1);
ShippingServiceOptionsType shipservice2 = new ShippingServiceOptionsType();
shipservice2.ShippingService = "AU_Express";
shipservice2.ShippingServicePriority = 2;
shipservice2.ShippingServiceCost = new AmountType();
shipservice2.ShippingServiceCost.currencyID = CurrencyCodeType.AUD;
shipservice2.ShippingServiceCost.Value = 4.0;
shipservice2.ShippingServiceAdditionalCost = new AmountType();
shipservice2.ShippingServiceAdditionalCost.currencyID = CurrencyCodeType.AUD;
shipservice2.ShippingServiceAdditionalCost.Value = 1.0;
item.ShippingDetails.ShippingServiceOptions.Add(shipservice2);
//Specify Return Policy
item.ReturnPolicy = new ReturnPolicyType();
item.ReturnPolicy.ReturnsAcceptedOption = "ReturnsAccepted";
item.StartPrice = new AmountType();
item.StartPrice.currencyID = CurrencyCodeType.AUD;
item.StartPrice.Value = Double.Parse(ebayProduct.EbayProductPrice.ToString());
item.PrimaryCategory = new CategoryType();
item.PrimaryCategory.CategoryID = ebayProduct.EbayCategoryID;
item.ProductListingDetails = new ProductListingDetailsType();
//Specifying UPC as the product identifier. Other applicable product identifiers
//include ISBN, EAN, Brand-MPN.
item.ProductListingDetails.UPC = UPC;
//If multiple product identifiers are specified, eBay uses the first one that
//matches a product in eBay's catalog system.
item.ProductListingDetails.BrandMPN = new BrandMPNType();
item.ProductListingDetails.BrandMPN.Brand = ebayProduct.EbayProductBrandName;
item.ProductListingDetails.BrandMPN.MPN = product.ManufacturerPartNumber;
//If multiple prod matches found, list the item with the 1st product's information
item.ProductListingDetails.UseFirstProduct = true;
//Add pictures
item.PictureDetails = new PictureDetailsType();
item.PictureDetails.PictureURL = new StringCollection();
//Specify GalleryType
item.PictureDetails.GalleryType = GalleryTypeCodeType.None;
item.PictureDetails.GalleryTypeSpecified = true;
/*
* Handle Variations
*/
var childProducts = _productService.GetAssociatedProducts(product.Id);
if (childProducts != null)
{
//Specify VariationsSpecificsSet
item.Variations = new VariationsType();
item.Variations.VariationSpecificsSet = new NameValueListTypeCollection();
var colourSpec = productSpecAttributes.FirstOrDefault(
x => x.SpecificationAttributeOption.SpecificationAttribute.Name == "Colour");
var sizeSpec = productSpecAttributes.FirstOrDefault(
x => x.SpecificationAttributeOption.SpecificationAttribute.Name == "Size");
if (colourSpec != null && sizeSpec == null)
{
List<string> colourSpecsList = new List<string>();
foreach (var cp in childProducts)
{
var colourSpecs = cp.ProductSpecificationAttributes.FirstOrDefault(
x => x.SpecificationAttributeOption.SpecificationAttribute.Name == "Colour");
colourSpecsList.Add(colourSpecs.SpecificationAttributeOption.Name);
}
//sizes
NameValueListType NVListVS2 = new NameValueListType();
NVListVS2.Name = "Colour";
StringCollection VSvaluecollection2 = new StringCollection();
String[] Colour = colourSpecsList.ToArray();
VSvaluecollection2.AddRange(Colour);
NVListVS2.Value = VSvaluecollection2;
item.Variations.VariationSpecificsSet.Add(NVListVS2);
}
//Add Variation Specific Pictures
item.Variations.Pictures = new PicturesTypeCollection();
foreach (var cp in childProducts)
{
//Specify Variations
VariationTypeCollection VarCol = new VariationTypeCollection();
PicturesType pic = new PicturesType();
var specs = cp.ProductSpecificationAttributes.FirstOrDefault(x => x.SpecificationAttributeOption.SpecificationAttribute.Name == "Colour");
var childEbayProduct = _ebayProductService.GetEbayProductById(cp.Id);
if (!String.IsNullOrEmpty(specs.SpecificationAttributeOption.Name))
{
VariationType var1 = new VariationType();
var1.SKU = cp.RexProductId.ToString();
Debug.WriteLine(cp.RexProductId.ToString());
var1.Quantity = cp.StockQuantity;
var1.StartPrice = new AmountType();
var1.StartPrice.currencyID = CurrencyCodeType.AUD;
var1.StartPrice.Value = Double.Parse(cp.Price.ToString());
var1.VariationSpecifics = new NameValueListTypeCollection();
NameValueListType Var1Spec1 = new NameValueListType();
StringCollection Var1Spec1Valuecoll = new StringCollection();
Var1Spec1.Name = "Colour";
Var1Spec1Valuecoll.Add(specs.SpecificationAttributeOption.Name);
Var1Spec1.Value = Var1Spec1Valuecoll;
var1.VariationSpecifics.Add(Var1Spec1);
//pics
pic.VariationSpecificName = "Colour";
pic.VariationSpecificPictureSet = new VariationSpecificPictureSetTypeCollection();
VariationSpecificPictureSetType VarPicSet1 = new VariationSpecificPictureSetType();
VarPicSet1.VariationSpecificValue = specs.SpecificationAttributeOption.Name;
StringCollection PicURLVarPicSet1 = new StringCollection();
PicURLVarPicSet1.Add(childEbayProduct.EbayProductMainImgUrl);
VarPicSet1.PictureURL = PicURLVarPicSet1;
pic.VariationSpecificPictureSet.Add(VarPicSet1);
item.Variations.Pictures.Add(pic);
VarCol.Add(var1);
item.Variations.Variation = VarCol;
}
}
}
Anyone know what I might be able to do here.
Cheers
The closest thing to "dynamic variable names" is a Dictionary.
Dictionary<string, string> variables = new Dictionary<string, string>();
variables.Add("var1", "test1");
variables.Add("var2", "test2");
MessageBox.Show(variables["var1"]); // will display test1
If you have a set of needed data for each "variable", make a class or struct (maybe call it "TheData")
Dictionary<string, TheData> variables = new Dictionary<string, TheData>();
variables.Add("var1", new TheData() { price = 25.28, upc = "01121...", manufacturer = "ACME" });

Error in QueryExpression with PartyList

I'm trying to retrieve appointments whose "requiredattendees" contains on one of entities from account list. requiredattendees have a type of PartyList.
My query looks like:
var query = new QueryExpression("appointment")
{
ColumnSet = columnSet,
Criteria = new FilterExpression(LogicalOperator.Or)
};
And adding conditions :
GetAccounts()
.Select(a => new ConditionExpression("requiredattendees", ConditionOperator.Contains, a.Id))
.ForEach(c => query.Criteria.AddCondition(c));
a.Id is the account guid.
I'm getting following error:
Cannot add attribute requiredattendees of type partylist in a condition
System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral]]
This code is for serviceappointment, but if i remember right, it's just the same for appointment. Hope this helps
QueryExpression qe = new QueryExpression
{
EntityName = "serviceappointment",
Criteria = new FilterExpression
{
FilterOperator = LogicalOperator.And,
Conditions =
{
new ConditionExpression
{
AttributeName = "scheduledstart",
Operator = ConditionOperator.LessThan,
Values =
{
endTime
}
},
new ConditionExpression
{
AttributeName = "scheduledend",
Operator = ConditionOperator.GreaterThan,
Values =
{
startTime
}
}
}
},
LinkEntities =
{
new LinkEntity
{
LinkFromEntityName = "activitypointer",
LinkFromAttributeName = "activityid",
LinkToEntityName = "activityparty",
LinkToAttributeName = "activityid",
LinkCriteria = new FilterExpression
{
FilterOperator = LogicalOperator.And,
Conditions =
{
new ConditionExpression
{
AttributeName = "partyid",
Operator = ConditionOperator.Equal,
Values =
{
someEntity.id
}
}
}
}
}
}
};
QueryExpression query = new QueryExpression(LetterEntityAttributeNames.EntityName)
{
ColumnSet = new ColumnSet(new string[]
{
LetterEntityAttributeNames.SubjectFieldName,
LetterEntityAttributeNames.RegardingObjectId,
LetterEntityAttributeNames.ToFieldName
}),
Criteria = new FilterExpression
{
FilterOperator = LogicalOperator.And,
Conditions =
{
new ConditionExpression
{
AttributeName = LetterEntityAttributeNames.DirectChannelTypeFieldName,
Operator = ConditionOperator.Equal,
Values =
{
DirectChannelType
}
},
new ConditionExpression
{
AttributeName = LetterEntityAttributeNames.RegardingObjectId,
Operator = ConditionOperator.Equal,
Values =
{
RegardingId
}
}
}
},
LinkEntities =
{
new LinkEntity
{
LinkFromEntityName = ActivityPointerEntityAttributeNames.EntityName,
LinkFromAttributeName = ActivityPartyAttributeNames.ActivityId,
LinkToEntityName = ActivityPartyAttributeNames.EntityName,
LinkToAttributeName = CampaignActivityAttributeNames.Id,
LinkCriteria = new FilterExpression
{
FilterOperator = LogicalOperator.And,
Conditions =
{
new ConditionExpression
{
AttributeName = ActivityPointerAttributeNames.PartyIdField,
Operator = ConditionOperator.Equal,
Values =
{
ToEntityGuid
}
}
}
}
}
}
};

Search user by profile property

How i can search by profile property? MSDN say use ProfileSearchManager, but it not working.
I want search users by MobilePhone property.
SPServiceContext serviceContext = SPServiceContext.GetContext(site);
UserProfileManager upm = new UserProfileManager(serviceContext);
ProfileSearchManager sp = ProfileSearchManager.GetProfileSearchManager(serviceContext);
string[] searchPattern = { "123" };
ProfileBase[] searchResults = sp.Search(searchPattern, ProfileSearchFlags.User);
foreach (ProfileBase profile in searchResults)
{
Console.WriteLine(profile.DisplayName);
}
using (SPSite site = new SPSite(siteUrl))
{
using (var qRequest = new KeywordQuery(site)
{
QueryText = "MobilePhone:*" +"123" ,
EnableQueryRules = true,
EnableSorting = false,
SourceId = new Guid("Enter here Result Source Guid"),
TrimDuplicates = false
})
{
//Get properties you want here
qRequest.SelectProperties.Add("FirstName");
qRequest.SelectProperties.Add("LastName");
SearchExecutor e = new SearchExecutor();
ResultTableCollection rt = e.ExecuteQuery(qRequest);
var tab = rt.Filter("TableType", KnownTableTypes.RelevantResults);
var result = tab.FirstOrDefault();
DataTable resultTable = result.Table;
}
}

How to find Customer Entities logical name from Guid in Microsoft CRM

In CRM I am trying to automate the process of creating a new email from a previous email in the chain. This email has to go to the customer of the case, who could be either an account or a contact.
I can retrieve the Guid of the contact/account but I dont know how to retrieve the logical name.
This is what I have so far:
OrganizationServiceProxy service = CRMCentralCRMServiceInstance;
Guid customerId = GetCustomerIdFromCase(caseId);
Entity email = new Entity("email");
Entity activityPartyTo = new Entity("activityparty");
//"account" is a guess, it could be "contact"
EntityReference customerReferenceTo = new EntityReference("account", customerId);
activityPartyTo["partyid"] = customerReferenceTo;
EntityCollection toEntityCollection = new EntityCollection();
toEntityCollection.Entities.Add(activityPartyTo);
email["to"] = toEntityCollection;
.
.
.
newEmailId = service.Create(email);
public Guid GetCustomerIdFromCase(Guid caseId) {
Guid customerId = Guid.Empty;
List<CRMCase> caseList = GetCRMCasesById(caseId);
if (caseList.Count > 0)
{
CRMCase cmcCase = caseList.First();
customerId = cmcCase.CustomerId;
}
return (customerId);
}
public List<CRMCase> GetCRMCasesById(Guid caseId)
{
List<CRMCase> crmCases = new List<CRMCase>();
try
{
OrganizationServiceProxy service = CRMCentralCRMServiceInstance;
ConditionExpression condition1 = new ConditionExpression();
ConditionExpression condition2 = new ConditionExpression();
condition1.AttributeName = "incidentid";
condition1.Operator = ConditionOperator.Equal;
condition1.Values.Add(caseId.ToString("N"));
condition2.AttributeName = "statecode";
condition2.Operator = ConditionOperator.In;
condition2.Values.Add("Active");
condition2.Values.Add("Resolved");
FilterExpression filter = new FilterExpression();
filter.FilterOperator = LogicalOperator.And;
filter.Conditions.Add(condition1);
filter.Conditions.Add(condition2);
QueryExpression query = new QueryExpression();
query.EntityName = "incident";
query.ColumnSet = new ColumnSet(true);
query.Criteria = filter;
RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest();
retrieveAttributeRequest.EntityLogicalName = "incident";
retrieveAttributeRequest.LogicalName = "statuscode";
retrieveAttributeRequest.RetrieveAsIfPublished = true;
RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
StatusAttributeMetadata statusCodeAttribute = (StatusAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
retrieveAttributeRequest = new RetrieveAttributeRequest();
retrieveAttributeRequest.EntityLogicalName = "incident";
retrieveAttributeRequest.LogicalName = "prioritycode";
retrieveAttributeRequest.RetrieveAsIfPublished = true;
retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
PicklistAttributeMetadata priorityCodeAttribute = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
retrieveAttributeRequest = new RetrieveAttributeRequest();
retrieveAttributeRequest.EntityLogicalName = "incident";
retrieveAttributeRequest.LogicalName = "statecode";
retrieveAttributeRequest.RetrieveAsIfPublished = true;
retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
StateAttributeMetadata stateCodeAttribute = (StateAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;
EntityCollection casesColl = service.RetrieveMultiple(query);
foreach (Entity entity in casesColl.Entities)
{
Entity incidentCRMCase = entity;
CRMCase cRMCase = GetCRMCaseFromIncidentCase(incidentCRMCase, statusCodeAttribute.OptionSet.Options, stateCodeAttribute.OptionSet.Options, priorityCodeAttribute.OptionSet.Options);
crmCases.Add(cRMCase);
}
}
catch (SoapException se)
{
string action = MethodBase.GetCurrentMethod().DeclaringType.Name + " :: " + MethodBase.GetCurrentMethod().Name;
string message = "Unexpected error in action: " + action
+ Environment.NewLine + se.Message
+ Environment.NewLine + se.Detail.InnerText;
throw new Exception(message);
}
return (crmCases);
}
I found this brute force method but I would rather find a cleaner way if there is.
Ok. Really complicated code. Try to use something like following:
private EntityReference GetCustomerFromCase(Guid caseId)
{
Entity Case = CRMCentralCRMServiceInstance.Retrieve("incident", caseId, new ColumnSet("customerid"));
return Case.GetAttributeValue<EntityReference>("customerid");
}

Categories