Exemplo n.º 1
0
        internal static void CreateCase(string complaint, string customerName, string phone, string email)
        {
            try
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;

                CrmServiceClient     crmConn = new CrmServiceClient("*****@*****.**", CrmServiceClient.MakeSecureString("Welcome@123"), "EMEA", "org61bce9a2", useUniqueInstance: false, useSsl: true, isOffice365: true);
                IOrganizationService service = crmConn.OrganizationServiceProxy;

                Microsoft.Xrm.Sdk.Entity Case = new Microsoft.Xrm.Sdk.Entity("incident");
                Case["title"] = complaint;

                Microsoft.Xrm.Sdk.Entity Account = new Microsoft.Xrm.Sdk.Entity("account");
                Account["customerName"]  = customerName;
                Account["telephone1"]    = phone;
                Account["emailaddress1"] = email;
                Guid AccountId = service.Create(Account);

                Case["customerid"] = new EntityReference("account", AccountId);
                Guid CaseId = service.Create(Case);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private void createCase(string complaint, string customerName, string phone, string email)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;

            ClientCredentials credentials = new ClientCredentials();

            credentials.UserName.UserName = "******";
            credentials.UserName.Password = "******";
            Uri OrganizationUri = new Uri("https://crm970111.api.crm4.dynamics.com/XRMServices/2011/Organization.svc");

            Uri  HomeRealUir = null;
            Guid CaseGuid    = new Guid();

            using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealUir, credentials, null))
            {
                IOrganizationService service = (IOrganizationService)serviceProxy;
                serviceProxy.EnableProxyTypes();

                Entity Case = new Entity("incident");
                Case["title"] = complaint;
                Entity Account = new Entity("account");
                Account["name"]          = customerName;
                Account["telephone1"]    = phone;
                Account["emailaddress1"] = email;
                Guid AccountGuid = service.Create(Account);
                Case["customerid"] = new EntityReference("account", AccountGuid);
                CaseGuid           = service.Create(Case);
            }
        }
        public static AdaptiveCard ExecuteViaLocalTemplate(Microsoft.Xrm.Sdk.Entity record, string orgUrl)
        {
            try
            {
                string templateName = "Templates.default.json";

                switch (record.LogicalName)
                {
                case ("task"):
                {
                    templateName = "Templates.task.json";
                    break;
                }

                case ("incident"):
                {
                    templateName = "Templates.incident.json";
                    break;
                }
                }

                string resourceData = GlobalHelper.GetEmbeddedResource("SS21.Examples.TeamBot", templateName);

                resourceData = MapAttributesToJsonTemplate(record, resourceData, orgUrl);

                AdaptiveCard ac = ExecuteViaJSON(resourceData);

                return(ac);
            }
            catch (Exception e)
            {
                throw new Exception("SS21.Examples.TeamBot.AdaptiveCardFactory.ExecuteViaLocalTemplate :: ERROR :: Unable to process JSON Template into Adaptive Card object due to the following reason/s " + Environment.NewLine + e.Message);
            }
        }
Exemplo n.º 4
0
        internal static void CreateCase(string complaint, string customerName, string phone, string email)
        {
            try
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
                ClientCredentials credentials = new ClientCredentials();
                credentials.UserName.UserName = "******";
                credentials.UserName.Password = "******";
                Uri OrganizationUri = new Uri("https://scasacrm.api.crm4.dynamics.com/XRMServices/2011/Organization.svc");
                Uri HomeRealUri     = null;
                using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealUri, credentials, null))
                {
                    IOrganizationService service = (IOrganizationService)serviceProxy;
                    //CrmServiceClient crmConn = new CrmServiceClient("*****@*****.**", CrmServiceClient.MakeSecureString("Welcome@123"), "EMEA", "orgdc02b016", useUniqueInstance: false, useSsl: true, isOffice365: true);
                    //IOrganizationService service = crmConn.OrganizationServiceProxy;

                    Microsoft.Xrm.Sdk.Entity Case = new Microsoft.Xrm.Sdk.Entity("incident");
                    Case["title"] = complaint;

                    Microsoft.Xrm.Sdk.Entity Account = new Microsoft.Xrm.Sdk.Entity("account");
                    Account["name"]          = customerName;
                    Account["telephone1"]    = phone;
                    Account["emailaddress1"] = email;
                    Guid AccountId = service.Create(Account);

                    Case["customerid"] = new EntityReference("account", AccountId);
                    Guid CaseId = service.Create(Case);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 5
0
        public static string GetAliasedValue(CRM.Entity entity, string fieldName)
        {
            if (entity == null || string.IsNullOrEmpty(fieldName))
            {
                return(string.Empty);
            }

            if (!entity.Contains(fieldName))
            {
                return(string.Empty);
            }

            CRM.AliasedValue alias = (CRM.AliasedValue)entity[fieldName];

            if (alias.Value.GetType().ToString() == "System.Guid" || alias.Value.GetType().ToString() == "System.String" || alias.Value.GetType().ToString() == "System.Boolean" || alias.Value.GetType().ToString() == "System.Int32")
            {
                return(alias.Value.ToString());
            }

            if (alias.Value.GetType().ToString() == "System.Double")
            {
                return(Convert.ToDouble(alias.Value, CultureInfo.GetCultureInfo("en-us")).ToString("###0.000000", CultureInfo.GetCultureInfo("en-us")).Replace(',', '.'));
            }

            CRM.EntityReference referencia = (CRM.EntityReference)alias.Value;

            return(referencia.Name);
        }
Exemplo n.º 6
0
        public void CreateNoteWithAttachmentRegardingCaseNoDocumentLocationWithBaseDocumentLocation()
        {
            var context = new XrmFakedContext();

            context.Initialize(new List <Entity>()
            {
                incidentEntity, sdlEntityBase
            });
            var target = new Microsoft.Xrm.Sdk.Entity("annotation")
            {
                Id = annotationId,
            };

            target.Attributes.Add("objectid", new EntityReference("incident", incidentId));
            target.Attributes.Add("filename", "spam.txt");
            var fakedPlugin       = context.ExecutePluginWithTarget <Crm.Plugins.CreateSharePointDocumentLocation>(target);
            var documentLocations = (from t in context.CreateQuery("sharepointdocumentlocation")
                                     where t.Id != sdlEntityBase.Id
                                     select t)
                                    .ToList();

            Assert.IsTrue(documentLocations.Count == 1);
            Assert.IsTrue(documentLocations[0].Attributes["relativeurl"].ToString() == "TC-XX-XXXX");
            Assert.IsTrue(documentLocations[0].Attributes["name"].ToString() == "TC-XX-XXXX");
            Assert.IsTrue((documentLocations[0].Attributes["parentsiteorlocation"] as EntityReference)
                          .Id == sdlEntityBase.Id);
            Assert.IsTrue((documentLocations[0].Attributes["regardingobjectid"] as EntityReference)
                          .Id == incidentId);
        }
Exemplo n.º 7
0
        public static Guid GetAliasedId(CRM.Entity entity, string fieldName)
        {
            if (entity == null || string.IsNullOrEmpty(fieldName))
            {
                return(Guid.Empty);
            }

            if (!entity.Contains(fieldName))
            {
                return(Guid.Empty);
            }

            CRM.AliasedValue alias = (CRM.AliasedValue)entity[fieldName];

            switch (alias.Value.GetType().ToString())
            {
            case "Microsoft.Xrm.Sdk.EntityReference":
                return(((CRM.EntityReference)alias.Value).Id);

            case "System.Guid":
                return(new Guid(alias.Value.ToString()));
            }

            return(Guid.Empty);
        }
Exemplo n.º 8
0
 private void CreateLeadinCRM()
 {
     Microsoft.Xrm.Sdk.Entity lead = new Microsoft.Xrm.Sdk.Entity("lead");
     lead.Attributes["subject"]     = "Interested in product " + interestOptions;
     lead.Attributes["lastname"]    = name;
     lead.Attributes["description"] = description;
     GetOrganizationService().Create(lead);
 }
Exemplo n.º 9
0
        public Guid?CreateTaskToCRMIncident(string ticketnumber, TimeItem timeItem)
        {
            try
            {
                Microsoft.Xrm.Sdk.Query.QueryExpression GetCasesByTicketNumber = new Microsoft.Xrm.Sdk.Query.QueryExpression {
                    EntityName = "incident", ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(true)
                };
                GetCasesByTicketNumber.Criteria.AddCondition("ticketnumber", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, ticketnumber);
                Microsoft.Xrm.Sdk.EntityCollection CaseResults = _service.RetrieveMultiple(GetCasesByTicketNumber);

                if (CaseResults.Entities.Count < 1)
                {
                    return(null);
                }

                Microsoft.Xrm.Sdk.Entity followup = new Microsoft.Xrm.Sdk.Entity("task");

                if (timeItem.title != null)
                {
                    followup["subject"] = timeItem.title.Replace(ticketnumber, "");
                }

                if (timeItem.description != null)
                {
                    followup["description"] = timeItem.description;
                }

                if (timeItem.isBillable == true && timeItem.isBillable != null)
                {
                    followup["actualdurationminutes"]    = (int)TimeSpan.Parse(timeItem.time).TotalMinutes;
                    followup["hsal_nonbillableduration"] = 0;
                }
                else
                {
                    followup["actualdurationminutes"]    = 0;
                    followup["hsal_nonbillableduration"] = (int)TimeSpan.Parse(timeItem.time).TotalMinutes;
                }

                followup["actualstart"] = DateTime.UtcNow;

                followup["regardingobjectid"] = CaseResults.Entities[0].ToEntityReference();

                Guid taskId = _service.Create(followup);

                Microsoft.Crm.Sdk.Messages.SetStateRequest req = new Microsoft.Crm.Sdk.Messages.SetStateRequest();
                req.EntityMoniker = new Microsoft.Xrm.Sdk.EntityReference("task", taskId);
                req.State         = new Microsoft.Xrm.Sdk.OptionSetValue(1);
                req.Status        = new Microsoft.Xrm.Sdk.OptionSetValue((5));
                _service.Execute(req);

                return(taskId);
            }
            catch (Exception ex)
            {
                //log error
                throw ex;
            }
        }
Exemplo n.º 10
0
        public static async Task <EntityReference> PromptInitialQuestion(Activity context, ConnectorClient connector, IOrganizationService service, Microsoft.Xrm.Sdk.Entity cxConversation, Microsoft.Xrm.Sdk.Entity cxCurrentStep)
        {
            Microsoft.Xrm.Sdk.Entity cxStep = cxCurrentStep;

            //update conversation to reflect the current step and initiate any workflow triggers
            Microsoft.Xrm.Sdk.Entity upsConversation1 = new Microsoft.Xrm.Sdk.Entity("aspect_cxconversation", "aspect_conversationid", context.Conversation.Id);
            upsConversation1["aspect_currentcxstepid"] = new EntityReference(cxCurrentStep.LogicalName, cxCurrentStep.Id);
            upsConversation1["aspect_nextcxstepid"]    = null;
            service.Execute(new UpsertRequest()
            {
                Target = upsConversation1
            });

            string responseText = ReplaceOutputText(service, new EntityReference(cxConversation.LogicalName, cxConversation.Id), (string)cxStep["aspect_message"]);


            //Create a conversation message with the text sent to the user
            Microsoft.Xrm.Sdk.Entity conversationClient = new Microsoft.Xrm.Sdk.Entity("aspect_cxconversationmessage");
            conversationClient["aspect_cxconversationid"] = new EntityReference("aspect_cxconversation", cxConversation.Id);
            conversationClient["aspect_cxstepid"]         = new EntityReference(cxCurrentStep.LogicalName, cxCurrentStep.Id);
            conversationClient["aspect_direction"]        = true;
            conversationClient["aspect_name"]             = cxConversation.Id.ToString();
            conversationClient["aspect_message"]          = responseText;
            service.Create(conversationClient);


            //send reply
            var responseMessage = context.CreateReply();

            responseMessage.Text      = responseText;
            responseMessage.Speak     = responseText;
            responseMessage.InputHint = Dynamics.CXGetAnswers(service, cxStep);
            responseMessage.Value     = JsonConvert.SerializeObject(new Dynamics.CXInformation()
            {
                //CXBotId = ((Guid)(((AliasedValue)["aspect_cxbot.aspect_cxbotid"]).Value)).ToString(),
                CXBotName          = (string)(((AliasedValue)cxCurrentStep["aspect_cxbot.aspect_name"]).Value),
                AudioDirectory     = cxCurrentStep.Contains("aspect_cxbot.aspect_audiodirectory") ? (string)(((AliasedValue)cxCurrentStep["aspect_cxbot.aspect_audiodirectory"]).Value) : string.Empty,
                RecordingDirectory = cxCurrentStep.Contains("aspect_cxbot.aspect_recordingdirectory") ? (string)(((AliasedValue)cxCurrentStep["aspect_cxbot.aspect_recordingdirectory"]).Value) : string.Empty,
                CXStepId           = cxStep.Id.ToString(),
                CXStepAudio        = cxStep.Contains("aspect_audio") ? (string)cxStep["aspect_audio"] : string.Empty,
                CXText             = responseText,
                CXAnswers          = CXGetAnswers(service, cxStep),
                CXType             = Dynamics.CXGetType((OptionSetValue)cxStep["aspect_type"])
            });
            ResourceResponse msgResponse = connector.Conversations.ReplyToActivity(responseMessage);

            //update conversation to reflect the current step and initiate any workflow triggers
            Microsoft.Xrm.Sdk.Entity upsConversation2 = new Microsoft.Xrm.Sdk.Entity("aspect_cxconversation", "aspect_conversationid", context.Conversation.Id);
            upsConversation2["aspect_currentcxstepid"] = new EntityReference(cxCurrentStep.LogicalName, cxCurrentStep.Id);
            upsConversation2["aspect_nextcxstepid"]    = cxStep.Contains("aspect_nextcxstepid") ? (EntityReference)cxStep["aspect_nextcxstepid"] : null;
            service.Execute(new UpsertRequest()
            {
                Target = upsConversation2
            });

            return(cxStep.Contains("aspect_nextcxstepid") ? (EntityReference)cxStep["aspect_nextcxstepid"] : null);
        }
Exemplo n.º 11
0
        public void RetrieveAccountsByNameTest()
        {
            //
            // Arrange
            //
            var entity1 = new Microsoft.Xrm.Sdk.Entity("account");

            entity1.Id      = Guid.NewGuid();
            entity1["name"] = "abcabcabc";

            var entity2 = new Microsoft.Xrm.Sdk.Entity("account");

            entity2.Id      = Guid.NewGuid();
            entity2["name"] = "123123123";

            var entity3 = new Microsoft.Xrm.Sdk.Entity("account");

            entity3.Id      = Guid.NewGuid();
            entity3["name"] = "a1b2c3a1b2c3";

            var service = new Microsoft.Xrm.Sdk.Fakes.StubIOrganizationService();

            service.ExecuteOrganizationRequest = r =>
            {
                List <Entity> entities = new List <Entity>
                {
                    entity1, entity2
                };

                var response = new RetrieveMultipleResponse
                {
                    Results = new ParameterCollection
                    {
                        { "EntityCollection", new EntityCollection(entities) }
                    }
                };

                return(response);
            };

            string accountName = "abcabcabc";
            IEnumerable <Microsoft.Xrm.Sdk.Entity> actual;
            LINQToCRM2 target = new LINQToCRM2(service);

            //
            // Act
            //
            actual = target.RetrieveAccountsByName(accountName);

            //
            // Assert
            //
            Assert.AreEqual(2, actual.Count());
            Assert.AreEqual(entity1, actual.ElementAt(0));
            Assert.AreEqual(entity2, actual.ElementAt(1));
        }
Exemplo n.º 12
0
        public static async Task <Microsoft.Xrm.Sdk.Entity> PromptNextQuestion(IDialogContext context, IOrganizationService service, Microsoft.Xrm.Sdk.Entity cxCurrentStep, Microsoft.Xrm.Sdk.Entity cxNextStep, IMessageActivity message)
        {
            Microsoft.Xrm.Sdk.Entity cxStep = service.Retrieve(cxNextStep.LogicalName, cxNextStep.Id, new ColumnSet(true));

            //update conversation to initiate any workflow triggers
            Microsoft.Xrm.Sdk.Entity upsConversation = new Microsoft.Xrm.Sdk.Entity("aspect_cxconversation", "aspect_conversationid", message.Conversation.Id);
            upsConversation["aspect_nextcxstepid"] = new EntityReference(cxNextStep.LogicalName, cxNextStep.Id);
            UpsertResponse upsResponse = (UpsertResponse)service.Execute(new UpsertRequest()
            {
                Target = upsConversation
            });

            string responseText = ReplaceOutputText(service, (EntityReference)upsResponse["Target"], (string)cxStep["aspect_message"]);

            //Create a conversation message with outbound message
            Microsoft.Xrm.Sdk.Entity conversationMessageOutbound = new Microsoft.Xrm.Sdk.Entity("aspect_cxconversationmessage");
            conversationMessageOutbound["aspect_cxconversationid"] = new EntityReference("aspect_cxconversation", "aspect_conversationid", message.Conversation.Id);
            conversationMessageOutbound["aspect_cxstepid"]         = new EntityReference(cxNextStep.LogicalName, cxNextStep.Id);
            conversationMessageOutbound["aspect_direction"]        = true;
            conversationMessageOutbound["aspect_name"]             = message.Id;
            conversationMessageOutbound["aspect_message"]          = responseText;
            service.Create(conversationMessageOutbound);

            //Update conversation to reflect the current step
            Microsoft.Xrm.Sdk.Entity upsConversation2 = new Microsoft.Xrm.Sdk.Entity("aspect_cxconversation", "aspect_conversationid", message.Conversation.Id);
            upsConversation2["aspect_currentcxstepid"] = new EntityReference(cxNextStep.LogicalName, cxNextStep.Id);
            upsConversation2["aspect_lastanswer"]      = message.Text;
            upsConversation2["aspect_nextcxstepid"]    = null;
            service.Execute(new UpsertRequest()
            {
                Target = upsConversation2
            });

            //send outbound message
            IMessageActivity responseMessage = context.MakeMessage();

            responseMessage.Text      = responseText;
            responseMessage.Speak     = responseText;
            responseMessage.InputHint = Dynamics.CXGetAnswers(service, cxStep);
            responseMessage.Value     = JsonConvert.SerializeObject(new Dynamics.CXInformation()
            {
                //CXBotId = ((Guid)(((AliasedValue)["aspect_cxbot.aspect_cxbotid"]).Value)).ToString(),
                CXBotName          = (string)(((AliasedValue)cxCurrentStep["aspect_cxbot.aspect_name"]).Value),
                AudioDirectory     = cxCurrentStep.Contains("aspect_cxbot.aspect_audiodirectory") ? (string)(((AliasedValue)cxCurrentStep["aspect_cxbot.aspect_audiodirectory"]).Value) : string.Empty,
                RecordingDirectory = cxCurrentStep.Contains("aspect_cxbot.aspect_recordingdirectory") ? (string)(((AliasedValue)cxCurrentStep["aspect_cxbot.aspect_recordingdirectory"]).Value) : string.Empty,
                CXStepId           = cxStep.Id.ToString(),
                CXStepAudio        = cxStep.Contains("aspect_audio") ? (string)cxStep["aspect_audio"] : string.Empty,
                CXText             = responseText,
                CXAnswers          = CXGetAnswers(service, cxStep),
                CXType             = Dynamics.CXGetType((OptionSetValue)cxStep["aspect_type"])
            });
            await context.PostAsync(responseMessage);

            return(cxNextStep);
        }
Exemplo n.º 13
0
 private void RemoveNullValues(Microsoft.Xrm.Sdk.Entity entity)
 {
     foreach (var k in entity.Attributes.Keys.ToArray())
     {
         var v = entity[k];
         if (v == null)
         {
             entity.Attributes.Remove(k);
         }
     }
 }
        public void QueryandAdd(ServerConnection.Configuration serverConfig, string wechatname, string CustomerOpenId, string PaOpenID)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    _service = (IOrganizationService)_serviceProxy;

                    //<snippetCRUDOperationsDE1>
                    // Instaniate an account object.
                    Microsoft.Xrm.Sdk.Entity account = new Microsoft.Xrm.Sdk.Entity("contact");

                    account["Nickname"] = wechatname;

                    // Create an account record named wechat name.
                    _accountId = _service.Create(account);

                    Debug.WriteLine("{0} {1} created, ", account.LogicalName, account.Attributes["Nickname"]);

                    // Create a column set to define which attributes should be retrieved.
                    ColumnSet attributes = new ColumnSet(new string[] { "name", "PC微信OpenId" });

                    // Retrieve the account and its name and ownerid attributes.
                    account = _service.Retrieve(account.LogicalName, _accountId, attributes);
                    Debug.WriteLine("retrieved, ");

                    // Update the postal code attribute.
                    account["PC微信OpenId"] = CustomerOpenId;

                    // Update the account.
                    _service.Update(account);
                    Debug.WriteLine("and updated.");

                    // Delete the account.
                    bool deleteRecords = false;

                    if (deleteRecords)
                    {
                        _service.Delete("account", _accountId);

                        Debug.WriteLine("Entity record(s) have been deleted.");
                    }
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Exemplo n.º 15
0
        private void GetInterestedUsers(Entity post, Entity comment, Entity entity, IOrganizationService org, HashSet <EntityReference> userIds, Dictionary <Guid, Link> entityRelationships)
        {
            var processedEntities = new HashSet <Guid>();

            // Get any users mentioned in the post
            var userRegex = new Regex(@"@\[(?<etc>[0-9]+),(?<id>[a-z0-9-]+),", RegexOptions.IgnoreCase);

            foreach (Match user in userRegex.Matches(comment.GetAttributeValue <string>("text")))
            {
                FollowMention(Int32.Parse(user.Groups["etc"].Value), new Guid(user.Groups["id"].Value), org, processedEntities, new Link {
                    From = comment.ToEntityReference(), Description = "Mentions"
                }, userIds, entityRelationships);
            }

            // Get the user who posted the comment
            var createdBy = comment.GetAttributeValue <EntityReference>("createdby");

            if (userIds.Add(createdBy))
            {
                entityRelationships.Add(createdBy.Id, new Link {
                    From = comment.ToEntityReference(), Description = "Posted By"
                });
            }

            // Get the user who posted the original post
            createdBy = post.GetAttributeValue <EntityReference>("createdby");
            if (userIds.Add(createdBy))
            {
                entityRelationships.Add(createdBy.Id, new Link {
                    From = post.ToEntityReference(), Description = "Posted By"
                });
            }

            // Add any user who has also replied to this same post
            var replyQry = new QueryByAttribute("postcomment");

            replyQry.AddAttributeValue("postid", post.Id);
            replyQry.ColumnSet = new ColumnSet("createdby");

            foreach (var reply in org.RetrieveMultiple(replyQry).Entities)
            {
                createdBy = reply.GetAttributeValue <EntityReference>("createdby");
                if (userIds.Add(createdBy))
                {
                    entityRelationships.Add(createdBy.Id, new Link {
                        From = entity.ToEntityReference(), Description = "Also Commented On By"
                    });
                }
            }

            // Get anyone otherwise interested in the record being posted on
            GetInterestedUsers(entity, org, processedEntities, userIds, entityRelationships);
        }
Exemplo n.º 16
0
        public void CreateNoteNoAttachment()
        {
            var context = new XrmFakedContext();
            var target  = new Microsoft.Xrm.Sdk.Entity("annotation")
            {
                Id = annotationId
            };
            var fakedPlugin       = context.ExecutePluginWithTarget <Crm.Plugins.CreateSharePointDocumentLocation>(target);
            var documentLocations = (from t in context.CreateQuery("sharepointdocumentlocation")
                                     select t).ToList();

            Assert.IsTrue(documentLocations.Count == 0);
        }
Exemplo n.º 17
0
        public static string GetStringValue(CRM.Entity entity, string fieldName)
        {
            if (entity == null || string.IsNullOrEmpty(fieldName))
            {
                return(string.Empty);
            }

            if (!entity.Contains(fieldName))
            {
                return(string.Empty);
            }

            return(entity[fieldName].ToString());
        }
Exemplo n.º 18
0
        public static Guid GetReferenceId(CRM.Entity entity, string fieldName)
        {
            if (entity == null || string.IsNullOrEmpty(fieldName))
            {
                return(Guid.Empty);
            }

            if (!entity.Contains(fieldName))
            {
                return(Guid.Empty);
            }

            return(((CRM.EntityReference)entity[fieldName]).Id);
        }
Exemplo n.º 19
0
        public static string GetReferenceValue(CRM.Entity entity, string fieldName)
        {
            if (entity == null || string.IsNullOrEmpty(fieldName))
            {
                return(string.Empty);
            }

            if (!entity.Contains(fieldName))
            {
                return(string.Empty);
            }

            return(((CRM.EntityReference)entity[fieldName]).Name);
        }
Exemplo n.º 20
0
        public bool?UpdateTaskInCRM(string ticketnumber, TimeItem timeItem)
        {
            try
            {
                Microsoft.Xrm.Sdk.Entity followup = _service.Retrieve("task", (Guid)timeItem.crmTaskId, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));

                Microsoft.Crm.Sdk.Messages.SetStateRequest req = new Microsoft.Crm.Sdk.Messages.SetStateRequest();
                req.EntityMoniker = new Microsoft.Xrm.Sdk.EntityReference("task", followup.Id);
                req.State         = new Microsoft.Xrm.Sdk.OptionSetValue(0);
                req.Status        = new Microsoft.Xrm.Sdk.OptionSetValue((-1));
                _service.Execute(req);

                if (timeItem.title != null)
                {
                    followup["subject"] = timeItem.title.Replace(ticketnumber, "");
                }

                if (timeItem.description != null)
                {
                    followup["description"] = timeItem.description;
                }

                if (timeItem.isBillable == true && timeItem.isBillable != null)
                {
                    followup["actualdurationminutes"]    = (int)TimeSpan.Parse(timeItem.time).TotalMinutes;
                    followup["hsal_nonbillableduration"] = 0;
                }
                else
                {
                    followup["actualdurationminutes"]    = 0;
                    followup["hsal_nonbillableduration"] = (int)TimeSpan.Parse(timeItem.time).TotalMinutes;
                }


                _service.Update(followup);

                req.EntityMoniker = new Microsoft.Xrm.Sdk.EntityReference("task", followup.Id);
                req.State         = new Microsoft.Xrm.Sdk.OptionSetValue(1);
                req.Status        = new Microsoft.Xrm.Sdk.OptionSetValue((5));
                _service.Execute(req);

                return(true);
            }
            catch (Exception ex)
            {
                //log error
                throw ex;
            }
        }
Exemplo n.º 21
0
        public void CreateNoteWithAttachmentRegardingNull()
        {
            var context = new XrmFakedContext();
            var target  = new Microsoft.Xrm.Sdk.Entity("annotation")
            {
                Id = annotationId,
            };

            target.Attributes.Add("filename", "spam.txt");
            var fakedPlugin       = context.ExecutePluginWithTarget <Crm.Plugins.CreateSharePointDocumentLocation>(target);
            var documentLocations = (from t in context.CreateQuery("sharepointdocumentlocation")
                                     select t).ToList();

            Assert.IsTrue(documentLocations.Count == 0);
        }
        public void EmailWithNoGuid()
        {
            var context = new XrmFakedContext();
            var target  = new Microsoft.Xrm.Sdk.Entity("email")
            {
                Id = Guid.Empty
            };
            var pluginContext = new XrmFakedPluginExecutionContext();

            pluginContext.Stage           = 20;
            pluginContext.MessageName     = "create";
            pluginContext.InputParameters = new ParameterCollection();
            pluginContext.InputParameters.Add("Target", target);
            Assert.ThrowsException <InvalidPluginExecutionException>(() => context.ExecutePluginWith <Crm.Plugins.Email.PreoperationUpdateEmailBody>(pluginContext));
        }
Exemplo n.º 23
0
        public static decimal GetMoneyValue(CRM.Entity entity, string fieldName)
        {
            if (entity == null || string.IsNullOrEmpty(fieldName))
            {
                return(0);
            }

            if (!entity.Contains(fieldName))
            {
                return(0);
            }

            CRM.Money data = (CRM.Money)entity[fieldName];
            return(Convert.ToDecimal(data.Value));
        }
Exemplo n.º 24
0
        public static void UpdateIfCRMValueIsDifferent_EntityReference(Microsoft.Xrm.Sdk.Entity oSourceCIFEntity,
                                                       Microsoft.Xrm.Sdk.Entity oTargetCIFEntity,
                                                       string attributeName, object objSourceVal,
                                                       string logicalName, bool allowNull = true) {
            bool isEmpty = (objSourceVal == null) || (objSourceVal == DBNull.Value);
            bool isDifferent = true;

            // get the CRM current value - if one is available to compare - if none assume different
            if (oSourceCIFEntity != null) {
                EntityReference existingValue = null;

                // get the existing value
                if (oSourceCIFEntity.Attributes.Contains(attributeName))
                    existingValue = (EntityReference)oSourceCIFEntity[attributeName];

                // check if the values are different
                if (((existingValue == null) && !isEmpty) || ((existingValue != null) && isEmpty)) {
                    isDifferent = true;
                } else {
                    if ((existingValue == null) && isEmpty)
                        isDifferent = false;
                    else
                        if (!existingValue.Id.Equals((Guid)objSourceVal))
                        isDifferent = true;
                    else
                        isDifferent = false;
                }
            }

            // get the new string value if the objects are different
            if (isDifferent) {
                if (isEmpty) {
                    if (allowNull) {
                        if (oTargetCIFEntity.Contains(attributeName)) {
                            oTargetCIFEntity[attributeName] = null;
                        } else {
                            oTargetCIFEntity.Attributes.Add(attributeName, null);
                        }
                    }
                } else {
                    if (oTargetCIFEntity.Contains(attributeName)) {
                        oTargetCIFEntity[attributeName] = new EntityReference(logicalName, (Guid)objSourceVal);
                    } else {
                        oTargetCIFEntity.Attributes.Add(attributeName, new EntityReference(logicalName, (Guid)objSourceVal));
                    }
                }
            }
        }
Exemplo n.º 25
0
        public static void CreateTestDrive(TestDriveDetail testDrive, IOrganizationService crmService)
        {
            var lead = new Microsoft.Xrm.Sdk.Entity(EntityName);

            //lead.Attributes
            lead.Attributes.Add(Field_Subject, $"Test Drive Request by {testDrive.CustomerName}");
            lead.Attributes.Add(Field_FirstName, testDrive.CustomerName);
            lead.Attributes.Add(Field_Description, $@"Test drive request summary:
                                    {Environment.NewLine}Car Make: {testDrive.CarMake},
                                    {Environment.NewLine}Car Model: {testDrive.CarModel},
                                    {Environment.NewLine}Requested Time: {testDrive.RequestedTime},
                                    {Environment.NewLine}Customer Name: {testDrive.CustomerName},
                                    {Environment.NewLine}Phone Number: {testDrive.PhoneNumber}");

            crmService.Create(lead);
        }
Exemplo n.º 26
0
        public static string GetOptionValue(CRM.Entity entity, string fieldName)
        {
            if (entity == null || string.IsNullOrEmpty(fieldName))
            {
                return(string.Empty);
            }

            if (!entity.Contains(fieldName))
            {
                return(string.Empty);
            }

            CRM.OptionSetValue option = (CRM.OptionSetValue)entity[fieldName];

            return(option.Value.ToString(CultureInfo.InvariantCulture));
        }
Exemplo n.º 27
0
        public Guid?CreateExternalComment(string ticketnumber, TimeItem timeItem)
        {
            try
            {
                Microsoft.Xrm.Sdk.Query.QueryExpression GetCasesByTicketNumber = new Microsoft.Xrm.Sdk.Query.QueryExpression {
                    EntityName = "incident", ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(true)
                };
                GetCasesByTicketNumber.Criteria.AddCondition("ticketnumber", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, ticketnumber);
                Microsoft.Xrm.Sdk.EntityCollection CaseResults = _service.RetrieveMultiple(GetCasesByTicketNumber);

                if (CaseResults.Entities.Count < 1)
                {
                    return(null);
                }

                Microsoft.Xrm.Sdk.Entity comment = new Microsoft.Xrm.Sdk.Entity("hsal_externalcomments");

                if (timeItem.title != null)
                {
                    comment["subject"] = timeItem.title.Replace(ticketnumber, "");
                }

                if (timeItem.description != null)
                {
                    comment["description"] = timeItem.description;
                }

                comment["regardingobjectid"] = CaseResults.Entities[0].ToEntityReference();

                Guid externalCommentId = _service.Create(comment);

                Microsoft.Crm.Sdk.Messages.SetStateRequest req = new Microsoft.Crm.Sdk.Messages.SetStateRequest();
                req.EntityMoniker = new Microsoft.Xrm.Sdk.EntityReference("hsal_externalcomments", externalCommentId);
                req.State         = new Microsoft.Xrm.Sdk.OptionSetValue(1);
                req.Status        = new Microsoft.Xrm.Sdk.OptionSetValue((2));
                _service.Execute(req);

                return(externalCommentId);
            }
            catch (Exception ex)
            {
                //log error
                throw ex;
            }
        }
        public Entity Retrieve(string entityName, Guid id, ColumnSet columnSet)
        {
            var result = this.shadow.Get(entityName, id);

            if (columnSet.AllColumns)
            {
                return(result);
            }
            var nextResult = new Microsoft.Xrm.Sdk.Entity {
                LogicalName = entityName, Id = id
            };

            foreach (var col in columnSet.Columns)
            {
                nextResult[col] = result[col];
            }
            return(this.ToEarlyBoundEntity(nextResult));
        }
        public void EmailWithDescription()
        {
            var context = new XrmFakedContext();
            var target  = new Microsoft.Xrm.Sdk.Entity("email")
            {
                Id = Guid.NewGuid()
            };
            var pluginContext = new XrmFakedPluginExecutionContext();

            pluginContext.Stage           = 20;
            pluginContext.MessageName     = "create";
            pluginContext.InputParameters = new ParameterCollection();
            pluginContext.InputParameters.Add("Target", target);
            target["description"]   = "{!EmailHeaderFooter:Test Footer1}";
            target["directioncode"] = true;
            var emailDescription = string.Empty;
            var fakedPlugin      = context.ExecutePluginWith <Crm.Plugins.Email.PreoperationUpdateEmailBody>(pluginContext);
        }
Exemplo n.º 30
0
        public void RetrieveAccountsByIdTest()
        {
            //
            // Arrange
            //
            Guid id = Guid.NewGuid();

            Microsoft.Xrm.Sdk.Entity expected = new Microsoft.Xrm.Sdk.Entity {
                Id = id
            };

            var service = new Microsoft.Xrm.Sdk.Fakes.StubIOrganizationService();

            service.ExecuteOrganizationRequest = r =>
            {
                List <Entity> entities = new List <Entity>
                {
                    expected
                };

                var response = new RetrieveMultipleResponse
                {
                    Results = new ParameterCollection
                    {
                        { "EntityCollection", new EntityCollection(entities) }
                    }
                };

                return(response);
            };

            Microsoft.Xrm.Sdk.Entity actual;
            LINQToCRM2 target = new LINQToCRM2(service);

            //
            // Act
            //
            actual = target.RetrieveAccountsById(id);

            //
            // Assert
            //
            Assert.AreEqual(expected, actual);
        }
Exemplo n.º 31
0
        public IList<Entity> GenerateFakeEntities(string entityName, int howMany)
        {
            var metadataProvider = _MetadataProvider;
            var metadata = metadataProvider.GetEntityMetadata(entityName);
            Random rand = new Random();

            List<Entity> results = new List<Entity>();

            // Used for generating random dates.
            DateTime minCrmDate = new DateTime(1900, 1, 1);
            int crmDayRange = (DateTime.Today - minCrmDate).Days;

            for (int i = 0; i < howMany; i++)
            {
                var ent = new Microsoft.Xrm.Sdk.Entity(entityName);
                ent.Id = Guid.NewGuid();

                int stateCode = rand.Next(0, 1);
                int statusCode = stateCode + 1;

                foreach (var a in metadata.Attributes)
                {
                    switch (a.AttributeType.Value)
                    {
                        case AttributeTypeCode.BigInt:
                            var randomBigInt = (long)rand.NextLong(0, Int64.MaxValue);
                            ent[a.LogicalName] = randomBigInt;
                            break;
                        case AttributeTypeCode.Boolean:
                            int randomBoolInt = rand.Next(0, 1);
                            ent[a.LogicalName] = randomBoolInt == 1;
                            break;
                        case AttributeTypeCode.CalendarRules:
                            break;
                        case AttributeTypeCode.Customer:
                            int randomCustomerInt = rand.Next(0, 1);
                            string customerentity = "contact";
                            Guid customerId = Guid.NewGuid();
                            if (randomCustomerInt == 1)
                            {
                                customerentity = "account";
                            }
                            EntityReference customerRef = new EntityReference(customerentity, customerId);
                            ent[a.LogicalName] = customerRef;
                            break;
                        case AttributeTypeCode.DateTime:
                            DateTime randomDate = rand.NextCrmDate(minCrmDate, crmDayRange);
                            ent[a.LogicalName] = randomDate;
                            break;
                        case AttributeTypeCode.Decimal:
                            var decAtt = (DecimalAttributeInfo)a;
                            var scale = decAtt.NumericScale;
                            byte byteScale = (byte)scale;
                            var randomDecimal = rand.NextDecimal(byteScale);
                            ent[a.LogicalName] = randomDecimal;
                            break;
                        case AttributeTypeCode.Double:
                            var doubleAtt = (DoubleAttributeInfo)a;
                            var doubleScale = doubleAtt.NumericScale;
                            byte byteDoubleScale = (byte)doubleScale;
                            // todo apply precision / scale
                            var randomDouble = rand.NextDouble();
                            ent[a.LogicalName] = randomDouble;
                            break;
                        case AttributeTypeCode.EntityName:
                            break;
                        case AttributeTypeCode.Integer:
                            ent[a.LogicalName] = rand.Next();
                            break;
                        case AttributeTypeCode.Lookup:
                            break;
                        case AttributeTypeCode.ManagedProperty:
                            break;
                        case AttributeTypeCode.Memo:
                            var randomMemoString = string.Format("Test Memo String {0}", DateTime.UtcNow.Ticks.ToString());
                            ent[a.LogicalName] = randomMemoString;
                            break;
                        case AttributeTypeCode.Money:
                            var moneyAtt = (MoneyAttributeInfo)a;
                            var mscale = moneyAtt.NumericScale;
                            byte bytemScale = (byte)mscale;
                            var randomMoneyDecimal = rand.NextDecimal(bytemScale);
                            var randMoney = new Money(randomMoneyDecimal);
                            ent[a.LogicalName] = randMoney;
                            break;
                        case AttributeTypeCode.Owner:
                            EntityReference ownerRef = new EntityReference("systemuser", Guid.NewGuid());
                            ent[a.LogicalName] = ownerRef;
                            break;
                        case AttributeTypeCode.PartyList:
                            break;
                        case AttributeTypeCode.Picklist:
                            OptionSetValue optValue = new OptionSetValue(rand.Next());
                            ent[a.LogicalName] = optValue;
                            break;
                        case AttributeTypeCode.State:
                            // todo randomise active and inactive.
                            var stateCodeOpt = new OptionSetValue(stateCode);
                            ent[a.LogicalName] = stateCodeOpt;
                            break;
                        case AttributeTypeCode.Status:
                            var statusCodeOpt = new OptionSetValue(statusCode);
                            // todo randomise active and inactive.
                            ent[a.LogicalName] = statusCodeOpt;
                            break;
                        case AttributeTypeCode.String:
                            var randomString = string.Format("TestString{0}", DateTime.UtcNow.Ticks.ToString());
                            ent[a.LogicalName] = randomString;
                            break;
                        case AttributeTypeCode.Uniqueidentifier:
                            ent[a.LogicalName] = Guid.NewGuid();
                            break;
                        case AttributeTypeCode.Virtual:
                            break;
                        default:
                            break;
                    }

                }

                results.Add(ent);
            }

            return results;
        }