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;
}
Related
I am using active directory for getting all the departsment and filtering distinct departments using linq query, below is my code
private static DomainController GetDomainController(string domainpath)
{
var domainContext = new DirectoryContext(DirectoryContextType.Domain, domainpath);
var domain = Domain.GetDomain(domainContext);
var controller = domain.FindDomainController();
return controller;
}
private static MyMethod()
{
var domainController = GetDomainController(ActiveDirectorySettings.DomainPath);
// Lookup the information in AD
var ldapEntry = new DirectoryEntry(string.Format("LDAP://{0}", domainController)) { AuthenticationType = AuthenticationTypes.Secure | AuthenticationTypes.FastBind };
DirectorySearcher ds;
ds = new DirectorySearcher(ldapEntry)
{
SearchScope = SearchScope.Subtree,
Filter = "(&" + "(objectClass=user)" + "(department=" + departmentname + "*))"
};
ds.PropertiesToLoad.Add("department");
if (ds.FindAll().Count >= 1)
{
//DataSet du = DataReader.CheckAdUserExist();
var results = ds.FindAll();
var uniqueSearchResults = results.Cast<SearchResult>().Select(x => GetProperty(x,"department")).Distinct();
addUsersList.AddRange(uniqueSearchResults.Select(departmentName => new UsersAndDepartments
{
UserDepartment = departmentName
}));
}
}
I want to check the linq query result with the database whether department already exist or not, I am not sure how to do that?
If what you want is to create a simple database connection using SqlConnection you just need to query your DB using the department parameter you received from your AD request.
try{
SqlConnection connection = new SqlConnection("YourConnectionstring");
connection.Open();
//Your connection string can be found through your Server DB
//Now you go through your SearchResultCollection populated by SearchResult objects
foreach(SearchResult res in uniqueSearchResult){
SqlCommand cmd = new SqlCommand("Select * from yourTable where department=" +res.Properties["department"][0].ToString() + "", connection);
SqlDataReader reader = cmd.ExecuteReader();
//Here you verify if there are corresponding rows in your table
//with the request you have executed
if(!reader.HasRows()){
//If you have not found corresponding rows, then you add the department to your
//list
addUsersList.Add(res.Properties["department"][0].ToString());
}
}
connection.close();
}catch(Exception e){
Console.WriteLine("Exception caught : \n\n" + e.ToString();
}
This should work.
There are plenty of tutorials for this, but if you are making alot of requests I do not recommend using this connection method you will just lose too much time / organization, maybe try using a persistence Framework like Entity Framework :
https://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C
Hope this answers your question!
Here is my solution, I have solved it myself
private static DomainController GetDomainController(string domainpath)
{
var domainContext = new DirectoryContext(DirectoryContextType.Domain, domainpath);
var domain = Domain.GetDomain(domainContext);
var controller = domain.FindDomainController();
return controller;
}
private static MyMethod()
{
var domainController = GetDomainController(ActiveDirectorySettings.DomainPath);
// Lookup the information in AD
var ldapEntry = new DirectoryEntry(string.Format("LDAP://{0}", domainController)) { AuthenticationType = AuthenticationTypes.Secure | AuthenticationTypes.FastBind };
DirectorySearcher ds;
ds = new DirectorySearcher(ldapEntry)
{
SearchScope = SearchScope.Subtree,
Filter = "(&" + "(objectClass=user)" + "(department=" + departmentname + "*))"
};
ds.PropertiesToLoad.Add("department");
if (ds.FindAll().Count >= 1)
{
// getting list of all departments from the database
var departmentsList = AllDepartments();
// getting list of all departments from active directory
var results = ds.FindAll();
// filtering distinct departments from the result
var uniqueSearchResults = results.Cast<SearchResult>().Select(x => GetProperty(x,"department")).Distinct();
// here firstly i am getting the department list from the database and checking it for null, then using linq query i am comparing the result with ad department results
if (departmentsList != null)
{
addUsersList.AddRange(from sResultSet in uniqueSearchResults
where !departmentsList.Exists(u => u.UserDepartment == sResultSet)
select new UsersAndDepartments
{
UserDepartment = sResultSet
});
}
else
{
addUsersList.AddRange(uniqueSearchResults.Select(departmentName => new UsersAndDepartments
{
UserDepartment = departmentName
}));
}
}
}
I am using following code snippet to set the Invoice ID of Invoices in plugin pre-operation. But I am unable to do so. I want to seek your kind suggestion to set the value.
Update
QueryExpression qe = new QueryExpression
{
EntityName = "invoice",
ColumnSet = new ColumnSet("salesorderid", "invoicenumber"),
Criteria = new FilterExpression
{
Conditions = {
new ConditionExpression("salesorderid",ConditionOperator.Equal,orderId)
}
}
};
EntityCollection ec = service.RetrieveMultiple(qe);
if (ec.Entities.Count == 0)
{
string orderName = generateInvoiceID(service, orderId);
foreach (Entity id in ec.Entities)
{
id.Attributes["invoicenumber"] = Convert.ToInt32(orderName) + 01;
}
}
Looking at the snippet looks like you have the plugin registered on "SalesOrder" entity and you are trying to update invoice entity, so it does not matter if it is a pre-op or a post-op, you would need to explicitly call IOrganizationService.Update
var qe = new QueryExpression
{
EntityName = "invoice",
ColumnSet = new ColumnSet("salesorderid", "invoicenumber"),
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression("salesorderid", ConditionOperator.Equal, orderId)
}
}
};
var ec = service.RetrieveMultiple(qe);
var orderName = generateInvoiceID(service, orderId);
foreach (var entity in ec.Entities)
{
var invoice = new Entity("invoice") { Id = entity.Id };
invoice.Attributes.Add("invoicenumber", Convert.ToInt32(orderName) + 01);
service.Update(invoice); //call the update method.
}
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");
}
Ive created a Directory Searcher to pull multiple properties from each user.
objSearchADAM = new DirectorySearcher(objADAM);
objSearchADAM.PropertiesToLoad.Add("givenname");
objSearchADAM.PropertiesToLoad.Add("lastlogontimestamp");
ect...
objSearchResults = objSearchADAM.FindAll();
I then enumerate them, and convert the interger8 timestamp to standard date/time, and save to csv file with
List<string> timeProps = new List<string>() { "lastlogontimestamp", "accountexpires", "pwdlastset", "lastlogoff", "lockouttime", "maxstorage", "usnchanged", "usncreated", "usndsalastobjremoved", "usnlastobjrem", "usnsource" };
foreach (SearchResult objResult in objSearchResults)
{
objEntry = objResult.GetDirectoryEntry();
ResultPropertyCollection myResultProp = objResult.Properties;
foreach (string myKey in myResultProp.PropertyNames)
{
foreach (Object myCollection in myResultProp[myKey])
{
Object sample = myCollection;
if (timeProps.Contains(myKey))
{
String times = sample.ToString();
long ft = Int64.Parse(times);
DateTime date;
try
{
date = DateTime.FromFileTime(ft);
}
catch (ArgumentOutOfRangeException ex)
{
date = DateTime.MinValue;
Console.WriteLine("Out of range: " + ft);
Console.WriteLine(ex.ToString());
}
sample = date;
Console.WriteLine("{0}{1}", myKey.PadRight(25), sample);
objWriter.WriteLine("{0}{1}", myKey.PadRight(25), sample);
}
else
{
Console.WriteLine("{0}{1}", myKey.PadRight(25), sample);
objWriter.WriteLine("{0}{1}", myKey.PadRight(25), sample);
}
}
now i need to create an object for each user with the strings from each result that i can put into an SQL command ive built. where the LDAP query to SQL would be givenname = FirstName and lastlogontimestamp = LastLogon and so on.
StringBuilder sb = new StringBuilder();
sb.Append("INSERT INTO activedirectory.dimUserST (FirstName, LastName) VALUES (#FirstName, #LastName)");
loadStagingCommand.Parameters.AddWithValue("#FirstName", FirstName).DbType = DbType.AnsiString;
ect...
loadStagingCommand.CommandText = sb.ToString();
loadStagingCommand.ExecuteNonQuery();
i tried to use IDictionary in my first foreach (similar to code found here http://ideone.com/vChWD ) but couldn't get it to work. I read about IList and reflection, but im not sure how i could incorporate these.
UPDATE
I researched and found ExpandoObjects and attempted to write in code based off of what i saw in here Creating Dynamic Objects
however i run this new code I return "employeenumber System.Collections.Generic.List`1[System.Dynamic.ExpandoObject]"
if(employeeNumber.Contains(myKey))
{
string[] columnNames = { "EmployeeNumber" };
List<string[]> listOfUsers = new List<string[]>();
for (int i = 0; i < 10; i++)
{
listOfUsers.Add(new[] { myKey});
}
var testData = new List<ExpandoObject>();
foreach (string[] columnValue in listOfUsers)
{
dynamic data = new ExpandoObject();
for (int j = 0; j < columnNames.Count(); j++)
{
((IDictionary<String, Object>)data).Add(columnNames[j], listOfUsers[j]);
}
testData.Add(data);
Console.WriteLine("{0}{1}", myKey.PadRight(25), testData);
objWriter.WriteLine("{0}{1}", myKey.PadRight(25), testData);
}
}
I am obviously missing something here and cant seem to wrap my head around what the problem is. I might even be going about this the wrong way. Basically all i need to do is pull users and their properties from Active Directory and put into SQL database tabels. And I've worked out how to do both separately, but I cant figure out how to put it all together.
If the CSV is just being used to cache the results, you could use a Dictionary to store the contents of the search results instead. Separating your code into functions could be helpful:
private static object GetFirstValue(ResultPropertyCollection properties,
string propertyName)
{
var propertyValues = properties[propertyName];
var result = propertyValues.Count == 0 ? null : propertyValues[0];
return result;
}
Then you could either use a dictionary to hold the property values, or you could create a type:
var results = new List<Dictionary<string, object>>();
foreach(SearchResult objResult in objSearchResults)
{
var properties = objResult.Properties;
var propertyDictionary = new Dictionary<string, object> {
{"FirstName", GetFirstValue(properties, "givenname")},
{"LastName", GetFirstValue(properties, "sn")},
{"UserName", GetFirstValue(properties, "samaccountname")},
};
results.Add(propertyDictionary);
}
Now you have a list of property bags.
This could also be a simple LINQ statement:
var results = objSearchResults.OfType<SearchResult>()
.Select(s => s.Properties)
.Select(p => new {
FirstName = (string)GetFirstValue(properties, "givenname"),
LastName = (string)GetFirstValue(properties, "sn"),
UserName = (string)GetValue(properties, "samaccountname"),
AccountExpires = GetDateTimeValue(properties, "accountexpires")
});
Use the dictionaries like this:
foreach(var item in results)
{
var command = new SqlCommand();
...
command.Parameters.AddWithValue("firstName", item["FirstName"]);
...
}
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}");
}
}