I have an appointment entity which has an association with contact entity. I am trying to remove all association from this appointment entity without explicitly providing contact_id. Here is my code snippet with create appointment entity and then associate with an existing contact.
Entity activity = new Entity("appointment");
activity["scheduledstart"] = DateTime.Now;
activity["scheduledend"] = DateTime.Now.AddMinutes(30);
activity["subject"] = "Test Meeting";
activity["description"] = "Test Description";
activity["owneridname"] = "test_user";
activity["location"] = "Dallas";
EntityCollection attendees = new EntityCollection();
Entity attendee1 = new Entity("activityparty");
attendee1["addressused"] = "test.test#acmegroup.com";
attendees.Entities.Add(attendee1);
activity["requiredattendees"] = attendees;
Guid id = _service.Create(activity);
Console.WriteLine("id: " + id);
AssociateRequest associateRequest = new AssociateRequest();
associateRequest.Relationship = new Relationship("new_appointment_contact");
associateRequest.Target = new Microsoft.Xrm.Sdk.EntityReference("appointment", id);
EntityReferenceCollection referenceCollection = new EntityReferenceCollection();
Microsoft.Xrm.Sdk.EntityReference entityReference = new Microsoft.Xrm.Sdk.EntityReference("contact", new Guid("e6e71e53-b44b-e211-a81e-0050568b36bf"));
referenceCollection.Add(entityReference);
associateRequest.RelatedEntities = referenceCollection;
// Execute the request.
_service.Execute(associateRequest);
I am aware of using DisassociateRequest to remove this association but I don't want to explicitly provide contact_id. I just need something like .Clear() which can
remove all contact association.
DisassociateRequest disassociateRequest = new DisassociateRequest();
disassociateRequest.Relationship = new Relationship("new_appointment_contact");
disassociateRequest.Target = new Microsoft.Xrm.Sdk.EntityReference("appointment", id);
EntityReferenceCollection referenceCollection2 = new EntityReferenceCollection();
Microsoft.Xrm.Sdk.EntityReference entityReference2 = new Microsoft.Xrm.Sdk.EntityReference("contact", new Guid("e6e71e53-b44b-e211-a81e-0050568b36bf"));
referenceCollection2.Add(entityReference2);
disassociateRequest.RelatedEntities = referenceCollection2;
// Execute the request.
_service.Execute(disassociateRequest);
I used GetRelatedEntities method to pull all related entities into collection and then use this collection to disassociate all related entities:
DisassociateRequest disassociateRequest = new DisassociateRequest();
disassociateRequest.Relationship = new Relationship("new_appointment_contact");
disassociateRequest.Target = new Microsoft.Xrm.Sdk.EntityReference("appointment", id);
EntityReferenceCollection referenceCollection2 = new EntityReferenceCollection();
Entity existingAppointment = _service.Retrieve("appointment", id, new ColumnSet(true));
foreach (Entity item in existingAppointment.GetRelatedEntities(orgContext, "new_appointment_contact"))
{
Guid contactId = new Guid(item["contactid"].ToString());
Microsoft.Xrm.Sdk.EntityReference entityReference2 = new Microsoft.Xrm.Sdk.EntityReference("contact", contactId);
referenceCollection2.Add(entityReference2);
}
disassociateRequest.RelatedEntities = referenceCollection2;
_service.Execute(disassociateRequest);
Related
Using Microsoft.Sharepoint.CLient & .Runtime.dll ver.16.0.0.0
I have a Item list (Lost packages) with Tracking number(title),Description(currier),MailTo(Type: Person, Show Field: E-Mail)
I also have another list (buyers) of available User to pick up from
So from my C# client program I want to add or update an item from Lost packages and with the MailTo -Email- of an user. Right now I can only get the Name as String of the Author of a ListItem. How do I get the user information from a ListItem so I can change the MailTo to a specific user
public Package(ListItem _package) {
this.item = _package;
if (this.item != null) {
this.exist = true;
this.id = this.item["ID"].ToString();
this.trackNo = (String)this.item["Title"];
this.currier = (String)this.item["Description"];
this.status = (String)this.item["Status"];
FieldUserValue userAuthor = (FieldUserValue)this.item["Author"];
this.Owner = userAuthor.LookupValue.ToString();
Here is a sample code for your reference, just need to set the User Id to FieldUserValue class, then set to MailTo field:
ClientContext clientContext = new ClientContext("http://sp/sites/dev");
Web web = clientContext.Web;
Microsoft.SharePoint.Client.List spList = clientContext.Web.Lists.GetByTitle("JerryList4");
clientContext.Load(spList);
clientContext.ExecuteQuery();
ListItem item = spList.GetItemById(3);
clientContext.Load(item);
clientContext.ExecuteQuery();
FieldUserValue userValue = new FieldUserValue();
userValue.LookupId = 19; //set user Id here
item["MailTo"] = userValue;
item.Update();
clientContext.ExecuteQuery();
For the user id, you can get it from this Rest EndPoint:
http://siteurl/_api/web/siteusers?$select=Id,LoginName
I am trying to allocate a resource to a task in Dynamics 365 programmatically. The code is:
private static void AssignResourceToTask(XrmServiceContext xrm)
{
Guid TaskId = new Guid("e0bdf7c7-6a14-e711-8114-e0071b6ac161");
Guid ResourceId = new Guid("cd01ae07-b9cd-e611-80e7-c4346bac0910");
Guid ProjectId = new Guid("7982feea-a0f2-e611-8130-e0071b6a92f1");
var AssignResource = new msdyn_resourceassignment
{
msdyn_resourceassignmentId = Guid.NewGuid(),
msdyn_bookableresourceid = new Microsoft.Xrm.Client.CrmEntityReference("bookableresource", ResourceId),
msdyn_taskid = new Microsoft.Xrm.Client.CrmEntityReference("msdyn_projecttask", TaskId),
msdyn_projectid = new Microsoft.Xrm.Client.CrmEntityReference("msdyn_project", ProjectId),
};
AssignResource.msdyn_bookableresourceid.Name = "Amy Alberts";
xrm.AddObject(AssignResource);
xrm.SaveChanges();
}
But I am unable to assign a resource to a task using the above code.
Have you tried Microsoft.Crm.Sdk.AssignRequest? Your code would look like:
_serviceProxy.EnableProxyTypes();
_service = (IOrganizationService)_serviceProxy;
var assignRequest = new AssignRequest
{
Assignee = new EntityReference("contact", ResourceId),
Target = new EntityReference("task", TaskId)
};
_service.Execute(assignRequest);
Microsoft have an example here.
Given entities:
Team, User. Relation between those is N:N.
Question:
How do I find users which belong to specified teams (with given list of ids).
PS.
I found how to do with single team, but have no clue how to deal with the list of teams?
var team_id = ...
QueryExpression query = new QueryExpression("user");
// setting up relation between teams and users
Relationship rel = new Relationship();
rel.SchemaName = "new_teams_users";
RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();
relatedEntity.Add(rel, query);
RetrieveRequest request = new RetrieveRequest();
request.RelatedEntitiesQuery = relatedEntity;
request.ColumnSet = new ColumnSet(new string[] {"id"});
request.Target = new EntityReference { Id = team_id, LogicalName = "new_team" };
// Results: List of users by team id.
RetrieveResponse response = (RetrieveResponse)CrmService.Execute(request);
QueryExpression build on intersect entity will help you. As example i used product and competitor N:N relationship
QueryExpression qe = new QueryExpression()
{
EntityName = "competitorproduct", //this name can be get from N:N rel properties (Relationship form, Relationship Entity Name field)
ColumnSet = new ColumnSet(true),
};
qe.Criteria.AddCondition(
"competitorid",
ConditionOperator.In,
new object[] { "GUID1", "GUID2"});
//Below is optional - if you need some details of entity, add LinkEntity object. This example adds all fields from product entity
LinkEntity lePorduct = new LinkEntity("competitorproduct", "product", "productid", "productid", JoinOperator.Inner);
lePorduct.Columns = new ColumnSet(true);
qe.LinkEntities.Add(lePorduct);
You would make your primary entity the intersection entity so in your example it would be "TeamMembership" the criteria would then be set against the attribute "SystemUserId".
To get more information on the team you need to add the team entity as a linked entity to your query like this
LinkEntity TeamLink = new LinkEntity();
TeamLink .EntityAlias = "TeamLink ";
TeamLink .JoinOperator = JoinOperator.Inner;
TeamLink .LinkFromEntityName = "teammembership";
TeamLink .LinkFromAttributeName = "teamid";
TeamLink .LinkToEntityName = "team";
TeamLink .LinkToAttributeName = "teamid";
You can then bring back what ever columns you want and get the data out.
I have multiple entities to be stored in the same physical Azure table. I'm trying to Insert/Merge the table entries from a file. I'm trying to find a way to do this w/o really serializing each property or for that matter creating a custom entities.
While trying the following code, I thought maybe I could use generic DynamicTableEntity. However, I'm not sure if it helps in an insert operation (most documentation is for replace/merge operations).
The error I get is
HResult=-2146233088
Message=Unexpected response code for operation : 0
Source=Microsoft.WindowsAzure.Storage
Any help is appreciated.
Here's an excerpt of my code
_tableClient = storageAccount.CreateCloudTableClient();
_table = _tableClient.GetTableReference("CloudlyPilot");
_table.CreateIfNotExists();
TableBatchOperation batch = new TableBatchOperation();
....
foreach (var pkGroup in result.Elements("PartitionGroup"))
{
foreach (var entity in pkGroup.Elements())
{
DynamicTableEntity tableEntity = new DynamicTableEntity();
string partitionKey = entity.Elements("PartitionKey").FirstOrDefault().Value;
string rowKey = entity.Elements("RowKey").FirstOrDefault().Value;
Dictionary<string, EntityProperty> props = new Dictionary<string, EntityProperty>();
//if (pkGroup.Attribute("name").Value == "CloudServices Page")
//{
// tableEntity = new CloudServicesGroupEntity (partitionKey, rowKey);
//}
//else
//{
// tableEntity = new CloudServiceDetailsEntity(partitionKey,rowKey);
//}
foreach (var element in entity.Elements())
{
tableEntity.Properties[element.Name.ToString()] = new EntityProperty(element.Value.ToString());
}
tableEntity.ETag = Guid.NewGuid().ToString();
tableEntity.Timestamp = new DateTimeOffset(DateTime.Now.ToUniversalTime());
//tableEntity.WriteEntity(/*WHERE TO GET AN OPERATION CONTEXT FROM?*/)
batch.InsertOrMerge(tableEntity);
}
_table.ExecuteBatch(batch);
batch.Clear();
}
Have you tried using DictionaryTableEntity? This class allows you to dynamically fill the entity as if it were a dictionary (similar to DynamicTableEntity). I tried something like your code and it works:
var batch = new TableBatchOperation();
var entity1 = new DictionaryTableEntity();
entity1.PartitionKey = "abc";
entity1.RowKey = Guid.NewGuid().ToString();
entity1.Add("name", "Steve");
batch.InsertOrMerge(entity1);
var entity2 = new DictionaryTableEntity();
entity2.PartitionKey = "abc";
entity2.RowKey = Guid.NewGuid().ToString();
entity2.Add("name", "Scott");
batch.InsertOrMerge(entity2);
table.ExecuteBatch(batch);
var entities = table.ExecuteQuery<DictionaryTableEntity>(new TableQuery<DictionaryTableEntity>());
One last thing, I see that you're setting the Timestamp and ETag yourself. Remove these two lines and try again.
I am using managed client side object model in sharepoint 2010. And I want to get loginaName of the AssignedTo user in Task list.
In server side object model I use SPFieldUserValue.User.LoginName to get this property but in client side object model FieldUserValue.User does not exists.
How can I resolve this situation ?
Thanks
Here is the code for that. I've taken an example of AssignedTo field from Task list. I hope that helps.
public static User GetUserFromAssignedToField(string siteUrl)
{
// create site context
ClientContext ctx = new ClientContext(siteUrl);
// create web object
Web web = ctx.Web;
ctx.Load(web);
// get Tasks list
List list = ctx.Web.Lists.GetByTitle("Tasks");
ctx.Load(list);
// get list item using Id e.g. updating first item in the list
ListItem targetListItem = list.GetItemById(1);
// Load only the assigned to field from the list item
ctx.Load(targetListItem,
item => item["AssignedTo"]);
ctx.ExecuteQuery();
// create and cast the FieldUserValue from the value
FieldUserValue fuv = (FieldUserValue)targetListItem["AssignedTo"];
Console.WriteLine("Request succeeded. \n\n");
Console.WriteLine("Retrieved user Id is: {0}", fuv.LookupId);
Console.WriteLine("Retrieved login name is: {0}", fuv.LookupValue);
User user = ctx.Web.EnsureUser(fuv.LookupValue);
ctx.Load(user);
ctx.ExecuteQuery();
// display the user's email address.
Consol.writeLine("User Email: " + user.Email);
return user;
}
The fuv.LookupValue may contain the display name, not the login name, so my suggestion is (assuming you have the FieldUserValue - fuv in code (as descibed by #ekhanna):
var userId = fuv.LookupId;
var user = ctx.Web.GetUserById(userId);
ctx.Load(user);
ctx.ExecuteQuery();
You get the column which as the FieldUserValue from the list, once you have that you use the lookup id value and then query against the Sites User Info List. In the example below I cache the results to prevent looking up the same id more than once since the query can be expensive.
private readonly Dictionary<int, string> userNameCache = new Dictionary<int, string>();
public string GetUserName(object user)
{
if (user == null)
{
return string.Empty;
}
var username = string.Empty;
var spUser = user as FieldUserValue;
if (spUser != null)
{
if (!userNameCache.TryGetValue(spUser.LookupId, out username))
{
var userInfoList = context.Web.SiteUserInfoList;
context.Load(userInfoList);
var query = new CamlQuery { ViewXml = "<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='ID' /><Value Type='int'>" + spUser.LookupId + "</Value></Eq></Where></Query></View>" };
var users = userInfoList.GetItems(query);
context.Load(users, items => items.Include(
item => item.Id,
item => item["Name"]));
if (context.TryExecuteQuery())
{
var principal = users.GetById(spUser.LookupId);
context.Load(principal);
context.ExecuteQuery()
username = principal["Name"] as string;
userNameCache.Add(spUser.LookupId, username);
}
}
}
return username;
}
Everything above worked for me, but instead of:
FieldUserValue fuv = (FieldUserValue)targetListItem["AssignedTo"];
I used:
FieldUserValue[] fuv = targetListItem["AssignedTo"] as FieldUserValue[];