public void CreateWorkOrderIfNecessary(Guid alertId) { // create account, case, work order type, price list, and work order Entity newAccount = new Entity("account"); string uniqueAccountName = Guid.NewGuid().ToString(); newAccount["name"] = uniqueAccountName; Guid createdAccountId = cdsServiceClient.Create(newAccount); entitiesToDelete.Add(new KeyValuePair <Guid, string>(createdAccountId, "account")); output.WriteLine($"Created Account with id {createdAccountId}"); Entity newCase = new Entity("incident"); newCase["title"] = uniqueFaultName; newCase["customerid"] = new EntityReference("account", createdAccountId); Guid createdCaseId = cdsServiceClient.Create(newCase); output.WriteLine($"Created Incident with id {createdCaseId}"); string uniqueWorkOrderTypeName = Guid.NewGuid().ToString(); Entity newWorkOrderType = new Entity("msdyn_workordertype"); newWorkOrderType["msdyn_name"] = uniqueWorkOrderTypeName; newWorkOrderType["msdyn_incidentrequired"] = false; newWorkOrderType["msdyn_taxable"] = false; Guid createdWorkOrderTypeId = cdsServiceClient.Create(newWorkOrderType); entitiesToDelete.Add(new KeyValuePair <Guid, string>(createdWorkOrderTypeId, "msdyn_workordertype")); output.WriteLine($"Created WorkOrderType with id {createdWorkOrderTypeId}"); QueryExpression usDollarQueryExpression = FindEntityWithPropertyValue("transactioncurrency", "isocurrencycode", "USD"); EntityCollection usDollarQueryExpressionResult = cdsServiceClient.RetrieveMultiple(usDollarQueryExpression); Guid currencyId = usDollarQueryExpressionResult.Entities[0].Id; string uniquePriceListName = Guid.NewGuid().ToString(); Entity newPriceList = new Entity("pricelevel"); newPriceList["name"] = uniquePriceListName; newPriceList["transactioncurrencyid"] = new EntityReference("transactioncurrency", currencyId); Guid createdPriceListId = cdsServiceClient.Create(newPriceList); entitiesToDelete.Add(new KeyValuePair <Guid, string>(createdPriceListId, "pricelevel")); output.WriteLine($"Created PriceLevel with id {createdPriceListId}"); Entity newWorkOrder = new Entity("msdyn_workorder"); newWorkOrder["msdyn_systemstatus"] = 690970000; newWorkOrder["msdyn_taxable"] = false; newWorkOrder["msdyn_workordersummary"] = uniqueFaultName; newWorkOrder["msdyn_serviceaccount"] = new EntityReference("account", createdAccountId); newWorkOrder["msdyn_pricelist"] = new EntityReference("pricelevel", createdPriceListId); newWorkOrder["msdyn_workordertype"] = new EntityReference("msdyn_workordertype", createdWorkOrderTypeId); newWorkOrder["msdyn_iotalert"] = new EntityReference(DynamicsEntities.IoTAlert, alertId); Guid createdWorkOrderId = cdsServiceClient.Create(newWorkOrder); output.WriteLine($"Created WorkOrder with id {createdWorkOrderId}"); }
private static void PolyLookup(CdsServiceClient svc) { var account = new Account { Name = "Super Awesome" }; var accountId = svc.Create(account); var contact = new Contact { FirstName = "Super", LastName = "Awesome", ParentCustomerId = new EntityReference(Account.EntityLogicalName, accountId) }; svc.Create(contact); }
public void CreateRequestTests() { Mock <IOrganizationService> orgSvc = null; Mock <MoqHttpMessagehander> fakHttpMethodHander = null; CdsServiceClient cli = null; testSupport.SetupMockAndSupport(out orgSvc, out fakHttpMethodHander, out cli); // Set up Responses CreateResponse testCreate = new CreateResponse(); testCreate.Results.AddOrUpdateIfNotNull("accountid", testSupport._DefaultId); testCreate.Results.AddOrUpdateIfNotNull("id", testSupport._DefaultId); HttpResponseMessage createRespMsg = new HttpResponseMessage(System.Net.HttpStatusCode.OK); createRespMsg.Headers.Add("Location", $"https://deploymenttarget02.crm.dynamics.com/api/data/v9.1/accounts({testSupport._DefaultId})"); createRespMsg.Headers.Add("OData-EntityId", $"https://deploymenttarget02.crm.dynamics.com/api/data/v9.1/accounts({testSupport._DefaultId})"); // Setup handlers to deal with both orgRequest and WebAPI request. fakHttpMethodHander.Setup(s => s.Send(It.Is <HttpRequestMessage>(f => f.Method.ToString().Equals("post", StringComparison.OrdinalIgnoreCase)))).Returns(createRespMsg); orgSvc.Setup(f => f.Execute(It.Is <CreateRequest>(p => p.Target.LogicalName.Equals("account")))).Returns(testCreate); // Setup request // use create operation to setup request Dictionary <string, CdsDataTypeWrapper> newFields = new Dictionary <string, CdsDataTypeWrapper>(); newFields.Add("name", new CdsDataTypeWrapper("CrudTestAccount", CdsFieldType.String)); Entity acctEntity = new Entity("account"); acctEntity.Attributes.Add("name", "CrudTestAccount"); Guid respId = Guid.Empty; // Test entity create var response = cli.ExecuteCdsOrganizationRequest(new CreateRequest() { Target = acctEntity }, useWebAPI: false); Assert.NotNull(response); respId = ((CreateResponse)response).id; Assert.Equal(testSupport._DefaultId, respId); // Test low level create respId = cli.Create(acctEntity); Assert.Equal(testSupport._DefaultId, respId); // Test Helper create respId = cli.CreateNewRecord("account", newFields); Assert.Equal(testSupport._DefaultId, respId); }
private static void CreateContactRecord(Contact contact, CdsServiceClient svc) { Console.WriteLine("\n======================================\n"); try { var id = svc.Create(contact); Console.WriteLine($"Created Contact {contact.LastName} with ID: {id}"); } catch (Exception e) { Console.WriteLine($"Failed to create contact {contact.LastName}"); Console.WriteLine(e); } }
protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken) { try { var member = await TeamsInfo.GetMemberAsync(turnContext, turnContext.Activity.From.Id, cancellationToken); var username = member.UserPrincipalName; string message; Guid postId; string domainName; if (!String.IsNullOrEmpty(turnContext.Activity.Text)) { var connectionString = _config.GetConnectionString("Storage"); var storageAccount = CloudStorageAccount.Parse(connectionString); var tableClient = storageAccount.CreateCloudTableClient(); var table = tableClient.GetTableReference("users"); var user = (User)table.Execute(TableOperation.Retrieve <User>(username, "")).Result; if (user == null) { await turnContext.SendActivityAsync(MessageFactory.Text("Sorry, I couldn't find your user details. Please remove and re-add the D365 Posts Bot app in Teams and try again")); return; } if (user.LastPostId == null) { await turnContext.SendActivityAsync(MessageFactory.Text("Sorry, I couldn't find a message to reply to. Please use the Reply button on the post you want to reply to.")); return; } message = turnContext.Activity.Text; postId = user.LastPostId.Value; domainName = user.LastDomainName; } else { dynamic val = turnContext.Activity.Value; message = val.comment; postId = val.PostId; domainName = val.DomainName; } await turnContext.SendActivityAsync(new Activity { Type = ActivityTypes.Typing }); try { using (var org = new CdsServiceClient(new Uri("https://" + domainName), _config.GetValue <string>("MicrosoftAppId"), _config.GetValue <string>("MicrosoftAppPassword"), true, null)) { // Find the CDS user details var userQry = new QueryByAttribute("systemuser") { ColumnSet = new ColumnSet("systemuserid") }; userQry.AddAttributeValue("domainname", username); var users = org.RetrieveMultiple(userQry); if (users.Entities.Count == 0) { throw new ApplicationException("Could not find your user account in D365"); } org.CallerId = users.Entities[0].Id; var postComment = new Entity("postcomment") { ["postid"] = new EntityReference("post", postId), ["text"] = message }; org.Create(postComment); } await turnContext.SendActivityAsync(MessageFactory.Text("Your reply has been sent")); } catch (Exception ex) { await turnContext.SendActivityAsync(MessageFactory.Text("There was an error sending your reply back to D365: " + ex.Message)); } } catch (Exception ex) { await turnContext.SendActivityAsync(MessageFactory.Text(ex.ToString())); } }
public void DataTypeParsingTest() { Mock <IOrganizationService> orgSvc = null; Mock <MoqHttpMessagehander> fakHttpMethodHander = null; CdsServiceClient cli = null; testSupport.SetupMockAndSupport(out orgSvc, out fakHttpMethodHander, out cli); // Set up Responses CreateResponse testCreate = new CreateResponse(); testCreate.Results.AddOrUpdateIfNotNull("accountid", testSupport._DefaultId); testCreate.Results.AddOrUpdateIfNotNull("id", testSupport._DefaultId); HttpResponseMessage createRespMsg = new HttpResponseMessage(System.Net.HttpStatusCode.OK); createRespMsg.Headers.Add("Location", $"https://deploymenttarget02.crm.dynamics.com/api/data/v9.1/accounts({testSupport._DefaultId})"); createRespMsg.Headers.Add("OData-EntityId", $"https://deploymenttarget02.crm.dynamics.com/api/data/v9.1/accounts({testSupport._DefaultId})"); // Setup handlers to deal with both orgRequest and WebAPI request. fakHttpMethodHander.Setup(s => s.Send(It.Is <HttpRequestMessage>(f => f.Method.ToString().Equals("post", StringComparison.OrdinalIgnoreCase)))).Returns(createRespMsg); orgSvc.Setup(f => f.Execute(It.Is <CreateRequest>(p => p.Target.LogicalName.Equals("account")))).Returns(testCreate); // Setup request for all datatypes // use create operation to setup request Dictionary <string, CdsDataTypeWrapper> newFields = new Dictionary <string, CdsDataTypeWrapper>(); newFields.Add("name", new CdsDataTypeWrapper("CrudTestAccount", CdsFieldType.String)); newFields.Add("Field01", new CdsDataTypeWrapper(false, CdsFieldType.Boolean)); newFields.Add("Field02", new CdsDataTypeWrapper(testSupport._DefaultId, CdsFieldType.Customer, "parentaccount")); newFields.Add("Field03", new CdsDataTypeWrapper(DateTime.UtcNow, CdsFieldType.DateTime)); newFields.Add("Field04", new CdsDataTypeWrapper(64, CdsFieldType.Decimal)); newFields.Add("Field05", new CdsDataTypeWrapper(1.001, CdsFieldType.Float)); newFields.Add("Field06", new CdsDataTypeWrapper(testSupport._DefaultId, CdsFieldType.Key)); newFields.Add("Field07", new CdsDataTypeWrapper(testSupport._DefaultId, CdsFieldType.Lookup, "parentaccount")); newFields.Add("Field08", new CdsDataTypeWrapper(50, CdsFieldType.Money)); newFields.Add("Field09", new CdsDataTypeWrapper(100, CdsFieldType.Number)); newFields.Add("Field010", new CdsDataTypeWrapper(20, CdsFieldType.Picklist)); newFields.Add("Field011", new CdsDataTypeWrapper("RawValue", CdsFieldType.Raw)); newFields.Add("Field012", new CdsDataTypeWrapper(testSupport._DefaultId, CdsFieldType.UniqueIdentifier)); Entity acctEntity = new Entity("account"); acctEntity.Attributes.Add("name", "CrudTestAccount"); acctEntity.Attributes.Add("Field01", false); acctEntity.Attributes.Add("Field02", new EntityReference("parentaccount", testSupport._DefaultId)); acctEntity.Attributes.Add("Field03", DateTime.UtcNow); acctEntity.Attributes.Add("Field04", 64); acctEntity.Attributes.Add("Field05", 1.001); acctEntity.Attributes.Add("Field08", 50); acctEntity.Attributes.Add("Field09", 100); acctEntity.Attributes.Add("Field010", new OptionSetValue(20)); // Test Helper create var respId = cli.CreateNewRecord("account", newFields); Assert.Equal(testSupport._DefaultId, respId); // Test entity create var response = cli.ExecuteCdsOrganizationRequest(new CreateRequest() { Target = acctEntity }, useWebAPI: false); Assert.NotNull(response); respId = ((CreateResponse)response).id; Assert.Equal(testSupport._DefaultId, respId); // Test low level create respId = cli.Create(acctEntity); Assert.Equal(testSupport._DefaultId, respId); }
private static void CustomLookup(CdsServiceClient svc) { var cdsServiceContext = new CdsServiceContext(svc); var vicId = (from s in cdsServiceContext.CreateQuery <new_state>() where s.new_name == "Victoria" select s.Id).FirstOrDefault(); if (vicId == Guid.Empty) { var stateVic = new new_state { new_name = "Victoria" }; vicId = svc.Create(stateVic); } var contact = new Contact { FirstName = "Test", LastName = "Address 1 State Entity Ref", new_Address1StateId = new EntityReference(new_state.EntityLogicalName, vicId) //Standard case on Schema Name when Creating }; CreateContactRecord(contact, svc); contact = new Contact { FirstName = "Test", LastName = "Address 2 State Entity Ref", new_address2stateid = new EntityReference(new_state.EntityLogicalName, vicId) //Forced Lowercase on Schema Name when Creating }; CreateContactRecord(contact, svc); //Works contact = new Contact { FirstName = "Test", LastName = "Address 1 Crafted Name without bind, with case", }; contact["new_Address1StateId"] = new EntityReference(new_state.EntityLogicalName, vicId); CreateContactRecord(contact, svc); //Doesn't WOrk contact = new Contact { FirstName = "Test", LastName = "Address 1 Crafted Name with case & Bind", }; contact["*****@*****.**"] = new EntityReference(new_state.EntityLogicalName, vicId); CreateContactRecord(contact, svc); //Works contact = new Contact { FirstName = "Test", LastName = "Address 1 Crafted Name without case & Bind", }; contact["new_address1stateid"] = new EntityReference(new_state.EntityLogicalName, vicId); CreateContactRecord(contact, svc); //Doesn't Work contact = new Contact { FirstName = "Test", LastName = "Address 1 Crafted Name with bind, without case", }; contact["*****@*****.**"] = new EntityReference(new_state.EntityLogicalName, vicId); CreateContactRecord(contact, svc); //Doesn't Work }