In Dynamics CRM 2011, on the Incident entity, the "Status Reason" optionset (aka statuscode) is related to the "Status" optionset (aka statecode)
e.g. see this screenshot
When I use the API to retrieve the Status Reason optionset, like so:
RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
{
EntityLogicalName = "incident",
LogicalName = "statuscode",
RetrieveAsIfPublished = true
};
RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)serv.Execute(attributeRequest);
AttributeMetadata attrMetadata = (AttributeMetadata)attributeResponse.AttributeMetadata;
StatusAttributeMetadata statusMetadata = (StatusAttributeMetadata)attrMetadata;
var dict = new Dictionary<int?, string>();
foreach (OptionMetadata optionMeta in statusMetadata.OptionSet.Options)
{
dict.Add(optionMeta.Value, optionMeta.Label.UserLocalizedLabel.Label);
}
It works in that I get the whole list of "Status Reason" (statuscode) options. However, I dont get any info about which "Status Reason" (statuscode) options relate to which "Status" (statecode) options.
How do I get that information?
You already have everything try insert this code inside of foreach:
int stateOptionValue = (int)((StatusOptionMetadata)optionMeta).State;
See StatusAttributeMetaData.OptionSet.Options hierarchy can return a type called StatusOptionMetadata if you use the State property of the StatusOptionMetadata, it will return the statecode this statuscode belongs to.
Here is how you can get it by querying the database
SELECT distinct e.LogicalName as entity,
smState.Value AS stateCode,
smstate.AttributeValue,
smStatus.Value AS [statuscode/statusreason],
smStatus.AttributeValue
FROM StatusMap sm
JOIN Entity e ON sm.ObjectTypeCode = e.ObjectTypeCode
JOIN StringMap smState ON smState.AttributeValue = sm.State
AND smState.ObjectTypeCode = e.ObjectTypeCode
AND smState.AttributeName = 'StateCode'
JOIN StringMap smStatus ON smStatus.AttributeValue = sm.Status
AND smStatus.ObjectTypeCode = e.ObjectTypeCode
AND smStatus.AttributeName = 'StatusCode'
WHERE e.LogicalName in ('lead')
ORDER BY e.LogicalName,
smState.AttributeValue,
smStatus.AttributeValue;
Here is working code that will output State/Status mapping for a given entity (you just need to provide the orgServiceProxy):
var dictState = new Dictionary<int, OptionMetadata>();
var dictStatus = new Dictionary<int, List<OptionMetadata>>();
string entityName = "lead";
int count=0;
using (var orgServiceProxy = GetOrgServiceProxy(orgServiceUriOnLine))
{
RetrieveAttributeResponse attributeResponse = GetAttributeData(orgServiceProxy, entityName, "statecode");
AttributeMetadata attrMetadata = (AttributeMetadata)attributeResponse.AttributeMetadata;
StateAttributeMetadata stateMetadata = (StateAttributeMetadata)attrMetadata;
foreach (OptionMetadata optionMeta in stateMetadata.OptionSet.Options)
{
dictState.Add(optionMeta.Value.Value,optionMeta);
dictStatus.Add(optionMeta.Value.Value,new List<OptionMetadata>());
}
attributeResponse = GetAttributeData(orgServiceProxy, entityName, "statuscode");
attrMetadata = (AttributeMetadata)attributeResponse.AttributeMetadata;
StatusAttributeMetadata statusMetadata = (StatusAttributeMetadata)attrMetadata;
foreach (OptionMetadata optionMeta in statusMetadata.OptionSet.Options)
{
int stateOptionValue = ((StatusOptionMetadata)optionMeta).State.Value;
var statusList = dictStatus[stateOptionValue];
statusList.Add(optionMeta);
count++;
}
}
Console.WriteLine($"Number of mappings: {count}");
foreach (var stateKvp in dictState.OrderBy(x=> x.Key))
{
Console.WriteLine($"State: {stateKvp.Value.Value}: {stateKvp.Value.Label.UserLocalizedLabel.Label}");
var statusList = dictStatus[stateKvp.Key];
Console.WriteLine($"\tStatuses");
foreach (var status in statusList.OrderBy(s => s.Value))
{
Console.WriteLine($"\t\t{stateKvp.Value.Value}: {status.Label.UserLocalizedLabel.Label}");
}
}
Related
var orderJson = JsonConvert.DeserializeObject<dynamic>(httpResultStr);
var orderidCount = orderJson.data.orderUuids.Count;
for (int i = 0; i <= orderidCount; i++)
{
var orderId = orderJson.data.orderUuids[i]; // my fail attempt. Didnt work
var map = orderJson.data.ordersMap;
foreach (var d in map)
{
var receipt = d.fareInfo.totalPrice;
Console.WriteLine(receipt);
}
}
Im trying to access the ordersMap members with the given values in orderUuids object. Inside the ordersMap Ids contain the fareInfo.totalPrice property that I'm trying to access. How would I go about achieving this?
[![json tree with ordersMap. Trying to access its members with the given values in orderUuids object.][1]][1]
You can make a partial/full map using the JSON file and use JsonConvert.DeserializeObject<>(json).
Other solution could be create a partial map using an anonymous type. Here is a code snip.
var anonymousTypeObject = new
{
status = "",
data = new
{
ordersMap = new Dictionary<string, JToken>(),
orderUuids = new string[0]
}
};
var obj = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
foreach (var kvp in obj.data.ordersMap)
{
var totalPrice = kvp.Value["fareInfo"]?["totalPrice"]?.ToString();
Debug.WriteLine($"{kvp.Key} -> {totalPrice}");
}
EDIT If you don't want any map use this solution.
var jObj = JsonConvert.DeserializeObject<JObject>(json);
var orderUuids = jObj.SelectToken("data.orderUuids")?.Values<string>();
foreach (var orderUuid in orderUuids)
{
var totalPrice = jObj.SelectToken($"data.ordersMap.{orderUuid}.fareInfo.totalPrice")?.Value<double>();
Debug.WriteLine($"{orderUuid} -> {totalPrice}");
}
I have a problem with LINQ query (see comment) there is a First method and it only shows me the first element.
When I write in the console "Sales Representative" it shows me only the first element of it as in
I would like to get all of data about Sales Representative. How can I do it?
public PracownikDane GetPracownik(string imie)
{
PracownikDane pracownikDane = null;
using (NORTHWNDEntities database = new NORTHWNDEntities())
{
//Employee matchingProduct = database.Employees.First(p => p.Title == imie);
var query = from pros in database.Employees
where pros.Title == imie
select pros;
// Here
Employee pp = query.First();
pracownikDane = new PracownikDane();
pracownikDane.Tytul = pp.Title;
pracownikDane.Imie = pp.FirstName;
pracownikDane.Nazwisko = pp.LastName;
pracownikDane.Kraj = pp.Country;
pracownikDane.Miasto = pp.City;
pracownikDane.Adres = pp.Address;
pracownikDane.Telefon = pp.HomePhone;
pracownikDane.WWW = pp.PhotoPath;
}
return pracownikDane;
}
Right now you are just getting the .First() result from the Query collection:
Employee pp = query.First();
If you want to list all employees you need to iterate through the entire collection.
Now, if you want to return all the employee's you should then store each new "pracownikDane" you create in some sort of IEnumerable
public IEnumerable<PracownikDane> GetPracownik(string imie) {
using (NORTHWNDEntities database = new NORTHWNDEntities())
{
var query = from pros in database.Employees
where pros.Title == imie
select pros;
var EmployeeList = new IEnumerable<PracownikDane>();
foreach(var pp in query)
{
EmployeeList.Add(new PracownikDane()
{
Tytul = pp.Title,
Imie = pp.FirstName,
Nazwisko = pp.LastName,
Kraj = pp.Country,
Miasto = pp.City,
Adres = pp.Address,
Telefon = pp.HomePhone,
WWW = pp.PhotoPath
});
}
return EmployeeList;
}
Then, with this returned List you can then do what ever you wanted with them.
I am not able to add or update milestones field for the Features in the Rally. If anyone having the code available using C# to update the same, please share with me. I am searching and doing from last one week with no luck.
When I am trying to add/Update milestones in the Features. I am getting the error as "Could not read: Could not read referenced object null". My code is as follows:-
public DynamicJsonObject UpdateFeaturesbyName(string fea, string bFun)
{
//getting list of Feature.
Request feat = new Request("PortfolioItem/Feature");
feat.Query = new Query("Name", Query.Operator.Equals, fea);
QueryResult TCSResults = restApi.Query(feat);
foreach (var res in TCSResults.Results)
{
var steps = res["Milestones"];
Request tsteps = new Request(steps);
QueryResult tstepsResults = restApi.Query(tsteps);
foreach (var item in tstepsResults.Results)
{
}
if (res.Name == fea)
{
var targetFeature = TCSResults.Results.FirstOrDefault();
DynamicJsonObject toUpdate = new DynamicJsonObject();
//toUpdate["Milestones"] = "";
// CreateResult createResult = restApi.Create(steps._ref, toUpdate);
// String contentRef = steps._ref;
//String contentRef = createResult._ref;
string[] value = null;
string AccCri = string.Empty;
if (!string.IsNullOrWhiteSpace(bFun))
{
value = bFun.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
foreach (string item in value)
{
//if (string.IsNullOrWhiteSpace(AccCri))
// AccCri = item;
//else
// AccCri = AccCri + "<br/>" + item;
if (!string.IsNullOrWhiteSpace(item))
{
//Query for Milestone.
Request ms = new Request("Milestone");
ms.Fetch = new List<string>() { "Name", "ObjectID" };
ms.Query = new Query("Name", Query.Operator.Equals, item);
QueryResult msResults = restApi.Query(ms);
var targetMLResult = msResults.Results.FirstOrDefault();
long MLOID = targetMLResult["ObjectID"];
DynamicJsonObject tarML = restApi.GetByReference("Milestone", MLOID, "Name", "_ref", "DisplayColor");
DynamicJsonObject targetML = new DynamicJsonObject();
targetML["Name"] = tarML["Name"];
//targetML["_ref"] = tarML["_ref"];
targetML["_ref"] = "/milestone/" + Convert.ToString(MLOID);
targetML["DisplayColor"] = tarML["DisplayColor"];
// Grab collection of existing Milestones.
var existingMilestones = targetFeature["Milestones"];
long targetOID = targetFeature["ObjectID"];
// Milestones collection on object is expected to be a System.Collections.ArrayList.
var targetMLArray = existingMilestones;
var tagList2 = targetMLArray["_tagsNameArray"];
tagList2.Add(targetML);//
//targetMLArray.Add(targetML);
targetMLArray["_tagsNameArray"] = tagList2;
toUpdate["Milestones"] = targetMLArray;
OperationResult updateResult = restApi.Update(res._ref, toUpdate);
bool resp = updateResult.Success;
}
}
}
//toUpdate["c_AcceptanceCriteria"] = AccCri;
//OperationResult updateResult = restApi.Update(res._ref, toUpdate);
}
}
var features = TCSResults.Results.Where(p => p.Name == fea).FirstOrDefault();
var featuresref = features._ref;
return features;
}
Now that v3.1.1 of the toolkit has been released you can use the AddToCollection method to do this.
Otherwise, you can still always just update the full collection. The value should be an arraylist of objects with _ref properties.
Check out this example (which adds tasks to defects, but should be very similar to what you're doing): https://github.com/RallyCommunity/rally-dot-net-rest-apps/blob/master/UpdateTaskCollectionOnDefect/addTaskOnDefect.cs
I am using this code to retrieve global optionsets
var request = new RetrieveOptionSetRequest {Name = "OptionsetNameGoesHere"};
var retrieveOptionSetResponse =(RetrieveOptionSetResponse) DynamicsHandler._serviceProxy.Execute(request);
var retrievedOptionSetMetadata =(OptionSetMetadata) retrieveOptionSetResponse.OptionSetMetadata;
var optionList = retrievedOptionSetMetadata.Options.ToArray();
foreach (var optionMetadata in optionList)
{
Printout(optionMetadata.Label.LocalizedLabels[0].Label + "\n");
}
But how do I retrieve optionsets like AccountCategory (AccountCategoryCode) so that I can bind them to a Combobox?
You should get it with a RetrieveAttributeRequest. It will return an RetrieveAttributeResponse which contains the Property AttributeMetadata.
In your case it should be of type OptionSetMetadata, which is what you are looking for.
This is how I have solved this problem.
CRMBase is my base class with connection to the CRM instance. Codelanguage: C#
public static Dictionary<int, string> GetAll(CRMBase conn, string entityName, string attributeName)
{
OptionMetadataCollection result = RetrieveOptionSetMetaDataCollection(conn, entityName, attributeName);
return result.Where(r => r.Value.HasValue).ToDictionary(r => r.Value.Value, r => r.Label.UserLocalizedLabel.Label);
}
// Method to retrieve OptionSet Options Metadadata collection.
private static OptionMetadataCollection RetrieveOptionSetMetaDataCollection(CRMBase conn, string prmEntityName, string prmAttributeName)
{
RetrieveEntityRequest retrieveEntityRequest = new RetrieveEntityRequest();
retrieveEntityRequest.LogicalName = prmEntityName;
retrieveEntityRequest.EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes;
RetrieveEntityResponse retrieveEntityResponse = (RetrieveEntityResponse)conn._orgContext.Execute(retrieveEntityRequest);
return (from AttributeMetadata in retrieveEntityResponse.EntityMetadata.Attributes where
(AttributeMetadata.AttributeType == AttributeTypeCode.Picklist & AttributeMetadata.LogicalName == prmAttributeName)
select ((PicklistAttributeMetadata)AttributeMetadata).OptionSet.Options).FirstOrDefault();
}
I'm trying to pull information from a CRM installation and so far this is fine for using the default fields. However I'm having difficulty retrieving custom fields, for example Contacts have a custom field called web_username.
My code at present is
QueryExpression query = new QueryExpression();
query.EntityName = "contact";
ColumnSet cols = new ColumnSet();
cols.Attributes = new string[] { "firstname", "lastname" };
query.ColumnSet = cols;
BusinessEntityCollection beReturned = tomService.RetrieveMultiple(query);
foreach (contact _contact in beReturned.BusinessEntities)
{
DataRow dr = dt.NewRow();
dr["firstname"] = _contact.firstname;
dr["lastname"] = _contact.lastname;
dt.Rows.Add(dr);
}
How do I include custom fields in my query? I've tried searching around but with no luck yet but I could be searching incorrectly as I'm not used to CRM terms.
Cheers in advance!
I've since been able to solve this. In case it is of use to anyone else this is what I did. The query is set up as before except I've added my custom field to the ColumnSet.
cols.Attributes = new string[] { "firstname", "lastname", "new_web_username" };
And then used RetrieveMultipleResponse and Request with ReturnDynamicEntities set to true
RetrieveMultipleResponse retrived = new RetrieveMultipleResponse();
RetrieveMultipleRequest retrive = new RetrieveMultipleRequest();
retrive.Query = query;
retrive.ReturnDynamicEntities = true;
retrived = (RetrieveMultipleResponse)tomService.Execute(retrive);
Please still comment if there is a better way for me to do this.
EDIT
Using the example in my original question if you cast to a contact
contact myContact = (contact)myService.Retrieve(EntityName.contact.ToString(), userID, cols);
You can then access properties of the object
phone = myContact.telephone1;
password = myContact.new_password;
If you update your CRM webreference custom fields you've added in CRM are available.
public List<Entity> GetEntitiesCollection(IOrganizationService service, string entityName, ColumnSet col)
{
try
{
QueryExpression query = new QueryExpression
{
EntityName = entityName,
ColumnSet = col
};
var testResult = service.RetrieveMultiple(query);
var testResultSorted = testResult.Entities.OrderBy(x => x.LogicalName).ToList();
foreach (Entity res in testResultSorted)
{
var keySorted = res.Attributes.OrderBy(x => x.Key).ToList();
DataRow dr = null;
dr = dt.NewRow();
foreach (var attribute in keySorted)
{
try
{
if (attribute.Value.ToString() == "Microsoft.Xrm.Sdk.OptionSetValue")
{
var valueofattribute = GetoptionsetText(entityName, attribute.Key, ((Microsoft.Xrm.Sdk.OptionSetValue)attribute.Value).Value, _service);
dr[attribute.Key] = valueofattribute;
}
else if (attribute.Value.ToString() == "Microsoft.Xrm.Sdk.EntityReference")
{
dr[attribute.Key] = ((Microsoft.Xrm.Sdk.EntityReference)attribute.Value).Name;
}
else
{
dr[attribute.Key] = attribute.Value;
}
}
catch (Exception ex)
{
Response.Write("<br/>optionset Error is :" + ex.Message);
}
}
dt.Rows.Add(dr);
}
return testResultSorted;
}
catch (Exception ex)
{
Response.Write("<br/> Error Message : " + ex.Message);
return null;
}
}
//here i have mentioned one another function:
var valueofattribute = GetoptionsetText(entityName, attribute.Key, ((Microsoft.Xrm.Sdk.OptionSetValue)attribute.Value).Value, _service);
//definition of this function is as below:
public static string GetoptionsetText(string entityName, string attributeName, int optionSetValue, IOrganizationService service)
{
string AttributeName = attributeName;
string EntityLogicalName = entityName;
RetrieveEntityRequest retrieveDetails = new RetrieveEntityRequest
{
EntityFilters = EntityFilters.All,
LogicalName = entityName
};
RetrieveEntityResponse retrieveEntityResponseObj = (RetrieveEntityResponse)service.Execute(retrieveDetails);
Microsoft.Xrm.Sdk.Metadata.EntityMetadata metadata = retrieveEntityResponseObj.EntityMetadata;
Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => String.Equals(attribute.LogicalName, attributeName, StringComparison.OrdinalIgnoreCase)) as Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata;
Microsoft.Xrm.Sdk.Metadata.OptionSetMetadata options = picklistMetadata.OptionSet;
IList<OptionMetadata> OptionsList = (from o in options.Options
where o.Value.Value == optionSetValue
select o).ToList();
string optionsetLabel = (OptionsList.First()).Label.UserLocalizedLabel.Label;
return optionsetLabel;
}