/// <summary>
        /// Add a existing <c>Privilege</c> with name (<c>prv</c> prefix) to a <c>Role</c>.
        /// </summary>
        /// <param name="roleName">Role name</param>
        /// <param name="privilegeName">Privilege name with <c>prv</c> prefix</param>
        /// <param name="depth"><see cref="PrivilegeDepth"/></param>
        /// <returns><see cref="AddPrivilegesRoleResponse"/></returns>
        public AddPrivilegesRoleResponse AddPrivilege(string roleName, string privilegeName, PrivilegeDepth depth)
        {
            ExceptionThrow.IfNullOrEmpty(privilegeName, "privilegeName");
            ExceptionThrow.IfNullOrEmpty(roleName, "roleName");

            Guid id = GetId(roleName);

            ExceptionThrow.IfGuidEmpty(id, "id", string.Format("'{0}' not found", roleName));

            PrivilegeHelper privilegeHelper = new PrivilegeHelper(this.OrganizationService);
            var             privilegeList   = privilegeHelper.GetPredefinedPrivileges();

            ExceptionThrow.IfNull(privilegeList, "privilegeList", "System pre-defined privileges not found (001)");
            ExceptionThrow.IfNullOrEmpty(privilegeList.Entities, "privilegeList.Entities", "System pre-defined privileges not found (002)");

            var existingRole = privilegeList.Entities.Where(d => d["name"].Equals(privilegeName)).SingleOrDefault();

            ExceptionThrow.IfNull(existingRole, "Privilege", string.Format("'{0}' privilege not found", privilegeName));

            RolePrivilege privilege = new RolePrivilege()
            {
                Depth = depth, PrivilegeId = existingRole.Id
            };

            return(AddPrivilege(id, privilege));
        }
        /// <summary>
        /// Create an email attachment from <see cref="AttachmentData"/> object
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/gg328344(v=crm.7).aspx
        /// </para>
        /// </summary>
        /// <param name="emailId">Existing <c>Email Activity</c> Id</param>
        /// <param name="attachmentFile"><see cref="AttachmentData"/> object</param>
        /// <returns>Created record Id (<see cref="System.Guid"/>)</returns>
        public Guid Attach(Guid emailId, AttachmentData attachmentFile)
        {
            ExceptionThrow.IfGuidEmpty(emailId, "emailId");
            ExceptionThrow.IfNull(attachmentFile, "attachmentFile");

            return(Attach(emailId, attachmentFile.Data.ByteArray, attachmentFile.Meta.Name));
        }
        /// <summary>
        /// Merge the information from two entity records of the same type.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.mergerequest(v=crm.8).aspx
        /// </para>
        /// </summary>
        /// <param name="mergeEntityType">Entity type that merged</param>
        /// <param name="masterRecordId">Target (merged to) of the merge operation</param>
        /// <param name="subordinateId">Id of the entity record from which to merge data</param>
        /// <param name="updatedContent">Additional entity attributes to be set during the merge operation for accounts, contacts, or leads. This property is not applied when merging incidents</param>
        /// <param name="performParentingChecks">Indicates whether to check if the parent information is different for the two entity records.</param>
        /// <returns>
        /// <see cref="MergeResponse"/>
        /// </returns>
        public MergeResponse Merge(MergeEntity mergeEntityType, Guid masterRecordId, Guid subordinateId, Entity updatedContent, bool performParentingChecks = false)
        {
            /*
             * MergeRequest CRM SDK notları
             * https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.mergerequest.aspx
             *
             * 2015-10-01 : Entities that support MERGE operation
             *   - Lead
             *   - Account
             *   - Contact
             *   - Incident
             *
             * Incident(Case) için kısıtlamalar
             *   - UpdateContent property kullanılamaz.
             *   https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.mergerequest.updatecontent.aspx
             *   https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.mergerequest_members.aspx adresinde "MergeRequest.UpdateContent" optional görünmesine rağmen ,
             *   boş gönderilince hata veriyor. Bu nedenle "Incident" için kullanımda new Entity("incident") ataması yapıyoruz
             */

            ExceptionThrow.IfGuidEmpty(subordinateId, "mergedRecordId");
            ExceptionThrow.IfGuidEmpty(masterRecordId, "mergeToRecordId");
            ExceptionThrow.IfNull(updatedContent, "updatedContent");
            ExceptionThrow.IfNotExpectedValue(updatedContent.LogicalName, mergeEntityType.Description(), "UpdatedContent.LogicalName");

            MergeRequest request = new MergeRequest()
            {
                Target                 = new EntityReference(mergeEntityType.Description(), masterRecordId),
                SubordinateId          = subordinateId,
                PerformParentingChecks = performParentingChecks,
                UpdateContent          = updatedContent
            };

            return((MergeResponse)this.OrganizationService.Execute(request));
        }
Esempio n. 4
0
        /// <summary>
        /// Send an <c>Email</c> message using a <c>Template</c>.
        /// If you do not know your template id, you can use this method with just template title.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.sendemailfromtemplaterequest(v=crm.8).aspx
        /// </para>
        /// </summary>
        /// <param name="email">CRM (XRM) email entity without body and subject. Email body and subject will be replaced by specified template's properties.</param>
        /// <param name="templateTitle"><c>Template</c> title</param>
        /// <param name="regarding">Regarding object that related by template</param>
        /// <returns>Created record Id (<see cref="Guid"/>)</returns>
        public Guid Send(Entity email, string templateTitle, EntityReference regarding)
        {
            ExceptionThrow.IfNullOrEmpty(templateTitle, "templateTitle");
            ExceptionThrow.IfNull(regarding, "regarding");
            ExceptionThrow.IfGuidEmpty(regarding.Id, "EntityReference.Id");
            ExceptionThrow.IfNullOrEmpty(regarding.LogicalName, "EntityReference.LogicalName");

            ValidateEmailEntity(email);

            QueryExpression query = new QueryExpression("template")
            {
                ColumnSet = new ColumnSet("templateid", "templatetypecode"),
                Criteria  = new FilterExpression()
            };

            query.Criteria.AddCondition("title", ConditionOperator.Equal, templateTitle);
            query.Criteria.AddCondition("templatetypecode", ConditionOperator.Equal, regarding.LogicalName.ToLower());

            EntityCollection templateCollection = this.OrganizationService.RetrieveMultiple(query);

            ExceptionThrow.IfNull(templateCollection, "template", string.Format("'{0}' template not exists or not related with '{1}' entity.", templateTitle, regarding.LogicalName));
            ExceptionThrow.IfGreaterThan(templateCollection.Entities.Count, "template", 1, "There are more than one template with same name");

            Guid templateId = templateCollection.Entities[0].Id;

            return(Send(email, templateId, regarding));
        }
        /// <summary>
        /// Add the specified <c>Principal</c> to the list of <c>Queue</c> members.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.addprincipaltoqueuerequest(v=crm.8).aspx
        /// </para>
        /// </summary>
        /// <param name="queueId"><c>Queue</c> Id</param>
        /// <param name="principalType"><c>System User</c> or <c>Team</c>. If the passed-in <c>PrincipalType.Team</c> , add each team member to the queue.</param>
        /// <param name="principalId"><c>Principal</c> Id</param>
        /// <returns>
        /// <see cref="AddPrincipalToQueueResponse"/>
        /// </returns>
        public AddPrincipalToQueueResponse AddPrincipalToQueue(Guid queueId, PrincipalType principalType, Guid principalId)
        {
            ExceptionThrow.IfGuidEmpty(queueId, "queueId");
            ExceptionThrow.IfGuidEmpty(principalId, "principalId");

            Entity principalEntity = null;

            switch (principalType)
            {
            case PrincipalType.SystemUser:
                SystemUserHelper systemuserHelper = new SystemUserHelper(this.OrganizationService);
                principalEntity = systemuserHelper.Get(principalId, "fullname");
                break;

            case PrincipalType.Team:
                TeamHelper teamHelper = new TeamHelper(this.OrganizationService);
                principalEntity = teamHelper.Get(principalId, "name");
                break;
            }

            ExceptionThrow.IfNull(principalEntity, "principal", string.Format("Principal not found with '{0}'", principalId.ToString()));

            AddPrincipalToQueueRequest request = new AddPrincipalToQueueRequest()
            {
                QueueId   = queueId,
                Principal = principalEntity
            };

            return((AddPrincipalToQueueResponse)this.OrganizationService.Execute(request));
        }
        /// <summary>
        /// Search for <c>Knowledge Article</c>.
        /// <para>
        /// For more information look at
        /// <c>By Fulltext</c> : https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.fulltextsearchknowledgearticlerequest.aspx
        /// </para>
        /// </summary>
        /// <param name="searchType"><see cref="SearchTypeCode"/></param>
        /// <param name="query">
        /// Query criteria to find <c>Knowledge Article</c> with specified keyword.
        /// This parameter supports <c>QueryExpression</c> and <c>FetchXml</c>.
        /// <para>
        /// Please note that <see cref="PagingInfo"/> data must be defined in this query.
        /// </para>
        /// </param>
        /// <param name="searchText">Text to search for in <c>Knowledge Article</c> data</param>
        /// <param name="useInflection">Indicates whether to use inflectional stem matching when searching for knowledge base articles with a specified body text</param>
        /// <param name="removeDuplicates">
        /// Indicates whether to remove multiple versions of the same knowledge article in search results.
        /// Default value is <c>true</c>.
        /// </param>
        /// <param name="stateCode">
        /// State of the knowledge articles to filter the search results.
        /// Default value is <c>-1</c> (for all data). For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.fulltextsearchknowledgearticlerequest.statecode.aspx
        /// </param>
        /// <returns>
        /// <see cref="EntityCollection"/> for <c>Article</c> data.
        /// </returns>
        public EntityCollection Search(SearchTypeCode searchType, QueryBase query, string searchText, bool useInflection, bool removeDuplicates = true, int stateCode = -1)
        {
            ExceptionThrow.IfNull(query, "query");
            ExceptionThrow.IfNullOrEmpty(searchText, "searchText");

            if (query is QueryExpression)
            {
                ExceptionThrow.IfNullOrEmpty(((QueryExpression)query).EntityName, "QueryExpression.EntityName");
                ExceptionThrow.IfNotExpectedValue(((QueryExpression)query).EntityName.ToLower(), "QueryExpression.EntityName", this.EntityName.ToLower());
            }

            EntityCollection result = new EntityCollection();

            OrganizationRequest  serviceRequest  = null;
            OrganizationResponse serviceResponse = null;

            switch (searchType)
            {
            case SearchTypeCode.FullText:
                serviceRequest = new FullTextSearchKnowledgeArticleRequest()
                {
                    QueryExpression  = query,
                    RemoveDuplicates = removeDuplicates,
                    SearchText       = searchText,
                    StateCode        = stateCode,
                    UseInflection    = useInflection
                };

                serviceResponse = this.OrganizationService.Execute(serviceRequest);
                result          = ((FullTextSearchKnowledgeArticleResponse)serviceResponse).EntityCollection;
                break;
            }

            return(result);
        }
Esempio n. 7
0
        /// <summary>
        /// Add a <c>Contract Detail</c> to <c>Contract</c> with basic data.
        /// <c>Customer</c>, <c>Start Date</c> and <c>End Date</c> properties will be copied from <c>Contract</c> data.
        /// </summary>
        /// <param name="contractId"><c>Contract</c> Id</param>
        /// <param name="title">Title (description) of contract line</param>
        /// <param name="totalPrice">Total Price</param>
        /// <param name="totalAllotments">Total number of <c>minutes</c> or <c>case (incident)</c> allowed for the contract line.</param>
        /// <returns>Created record Id (<see cref="System.Guid"/>)</returns>
        public Guid Add(Guid contractId, string title, decimal totalPrice, int totalAllotments)
        {
            ExceptionThrow.IfGuidEmpty(contractId, "contractId");
            ExceptionThrow.IfNullOrEmpty(title, "title");

            ContractHelper contractHelper = new ContractHelper(this.OrganizationService);
            var            contract       = contractHelper.Get(contractId, "customerid", "activeon", "expireson");

            ExceptionThrow.IfNull(contract, "contract", string.Format("'{0}' not found", contractId));
            ExceptionThrow.IfNull(contract.GetAttributeValue <EntityReference>("customerid"), "contract.CustomerId");
            ExceptionThrow.IfGuidEmpty(contract.GetAttributeValue <EntityReference>("customerid").Id, "contract.CustomerId");
            ExceptionThrow.IfEquals(contract.GetAttributeValue <DateTime>("activeon"), "contract.StartDate", DateTime.MinValue);
            ExceptionThrow.IfEquals(contract.GetAttributeValue <DateTime>("expireson"), "contract.EndDate", DateTime.MinValue);

            Entity entity = new Entity(this.EntityName);

            entity["contractid"]      = new EntityReference("contract", contractId);
            entity["title"]           = title;
            entity["customerid"]      = contract.GetAttributeValue <EntityReference>("customerid");
            entity["activeon"]        = contract.GetAttributeValue <DateTime>("activeon");
            entity["expireson"]       = contract.GetAttributeValue <DateTime>("expireson");
            entity["price"]           = new Money(totalPrice);
            entity["totalallotments"] = totalAllotments;

            return(this.OrganizationService.Create(entity));
        }
        /// <summary>
        /// Create an attachment from <see cref="Stream"/>.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/gg328344(v=crm.7).aspx
        /// </para>
        /// </summary>
        /// <param name="emailId">Existing <c>Email Activity</c> Id</param>
        /// <param name="stream">File content</param>
        /// <param name="fileName">This will be attachment name</param>
        /// <returns>Created record Id (<see cref="System.Guid"/>)</returns>
        public Guid Attach(Guid emailId, Stream stream, string fileName)
        {
            ExceptionThrow.IfGuidEmpty(emailId, "emailId");
            ExceptionThrow.IfNull(stream, "stream");
            ExceptionThrow.IfNullOrEmpty(fileName, "fileName");

            return(Attach(emailId, stream.ToByteArray(), fileName));
        }
Esempio n. 9
0
        /// <summary>
        /// Remove attribute if exists
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="node"></param>
        void RemoveAttribute(ref Entity entity, string node)
        {
            ExceptionThrow.IfNull(entity, "entity");
            ExceptionThrow.IfNullOrEmpty(node, "node");

            if (entity.Contains(node))
            {
                entity.Attributes.Remove(node);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Merge two different <c>Contact</c> record
        /// </summary>
        /// <param name="mergeToRecordId"></param>
        /// <param name="mergedRecordId"></param>
        /// <param name="performParentingChecks"></param>
        /// <param name="updatedContent"></param>
        /// <returns>
        /// <see cref="MergeResponse"/>
        /// </returns>
        public MergeResponse Merge(Guid mergeToRecordId, Guid mergedRecordId, bool performParentingChecks = false, Entity updatedContent = null)
        {
            ExceptionThrow.IfGuidEmpty(mergeToRecordId, "mergeToRecordId");
            ExceptionThrow.IfGuidEmpty(mergedRecordId, "mergedRecordId");
            ExceptionThrow.IfNull(updatedContent, "updatedContent");

            CommonHelper commonHelper = new CommonHelper(this.OrganizationService);

            return(commonHelper.Merge(CommonHelper.MergeEntity.Contact, mergeToRecordId, mergedRecordId, updatedContent, performParentingChecks));
        }
Esempio n. 11
0
        /// <summary>
        /// Add <c>BCC</c> with bulk email address list.
        /// </summary>
        /// <param name="emailAddressList"></param>
        /// <returns><see cref="XrmEmail"/></returns>
        public XrmEmail Bcc(List <string> emailAddressList)
        {
            ExceptionThrow.IfNull(emailAddressList, "BCC Email Address List");

            foreach (string item in emailAddressList)
            {
                _bcc.Add(new Tuple <ToEntityType, Guid, string>(ToEntityType.Undefined, Guid.Empty, item));
            }

            return(this);
        }
Esempio n. 12
0
        /// <summary>
        /// Add <c>BCC</c> with bulk Id list.
        /// </summary>
        /// <param name="entityType"></param>
        /// <param name="idList"></param>
        /// <returns><see cref="XrmEmail"/></returns>
        public XrmEmail Bcc(ToEntityType entityType, List <Guid> idList)
        {
            ExceptionThrow.IfNull(idList, "Bcc.Id List");

            foreach (var item in idList)
            {
                _bcc.Add(new Tuple <ToEntityType, Guid, string>(entityType, item, string.Empty));
            }

            return(this);
        }
        /// <summary>
        /// Schedule or “book” an appointment.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.bookrequest(v=crm.7).aspx
        /// </para>
        /// </summary>
        /// <param name="appointment"></param>
        /// <returns>
        /// Returns <c>Validation Result</c> (<see cref="ValidationResult"/>) in <see cref="ValidateResponse"/>.
        /// You can reach created <c>Appointment</c> Id in <see cref="ValidationResult.ActivityId"/> property.
        /// </returns>
        public BookResponse Book(XrmAppointment appointment)
        {
            ExceptionThrow.IfNull(appointment, "appointment");

            BookRequest request = new BookRequest()
            {
                Target = appointment.ToEntity()
            };

            return((BookResponse)this.OrganizationService.Execute(request));
        }
        /// <summary>
        /// Create an <c>Annotation</c>.
        /// </summary>
        /// <param name="relatedObject">Related object that attach note</param>
        /// <param name="subject">Subject</param>
        /// <param name="text">Note text</param>
        /// <returns>Created record Id (<see cref="Guid"/>)</returns>
        public Guid Create(EntityReference relatedObject, string subject, string text)
        {
            ExceptionThrow.IfNull(relatedObject, "relatedObject");
            ExceptionThrow.IfGuidEmpty(relatedObject.Id, "relatedObject.Id");
            ExceptionThrow.IfNullOrEmpty(relatedObject.LogicalName, "relatedObject.LogicalName");
            ExceptionThrow.IfNullOrEmpty(text, "text");

            Entity entity = PrepareBasicAnnotation(relatedObject, subject, text);

            return(this.OrganizationService.Create(entity));
        }
        /// <summary>
        /// Retrieve <c>Article</c> 's <c>Subject</c>.
        /// </summary>
        /// <param name="id"></param>
        /// <returns>
        /// <c>Subject</c> Id (<see cref="System.Guid"/>)
        /// </returns>
        public Guid RetrieveSubjectId(Guid id)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");

            var data = this.Get(id, "subjectid");

            ExceptionThrow.IfNull(data, "KbArticle");
            ExceptionThrow.IfNull(data.GetAttributeValue <EntityReference>("subjectid"), "KbArticle.SubjectId");

            return(data.GetAttributeValue <EntityReference>("subjectid").Id);
        }
        /// <summary>
        /// Create an attachment from byte array.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/gg328344(v=crm.7).aspx
        /// </para>
        /// </summary>
        /// <param name="emailId"><c>Email Activity</c> Id</param>
        /// <param name="content">File content</param>
        /// <param name="fileName">This will be attachment name</param>
        /// <returns>
        /// Created record Id (<see cref="System.Guid"/>)
        /// </returns>
        public Guid Attach(Guid emailId, byte[] content, string fileName)
        {
            ExceptionThrow.IfGuidEmpty(emailId, "emailId");
            ExceptionThrow.IfNull(content, "content");
            ExceptionThrow.IfNegative(content.Length, "content");
            ExceptionThrow.IfNullOrEmpty(fileName, "fileName");

            var entity = PrepareAttachmentData(emailId, content, fileName);

            return(this.OrganizationService.Create(entity));
        }
Esempio n. 17
0
        /// <summary>
        /// <c>Qualify</c> a <c>Lead</c> and create an account, contact, or opportunity records that are linked to the originating lead.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.qualifyleadrequest(v=crm.8).aspx
        /// </para>
        /// </summary>
        /// <param name="id"><c>Lead</c> Id</param>
        /// <param name="qualifyTo">Lead qualified to entity type</param>
        /// <param name="existingRecordType">Existing record entity type</param>
        /// <param name="existingRecordId">If you qualify with existing record (account or contact) set record Id</param>
        /// <param name="currencyId">
        /// If you want create an <c>Opportunity</c> set <c>TransactionCurrency Id</c>, otherwise leave NULL.
        /// <para>
        /// If you want create an <c>Opportunity</c> and do not know / sure <c>TransactionCurrency Id</c> leave NULL, this method will find <c>TransactionCurrency Id</c>
        /// </para>
        /// </param>
        /// <param name="campaignId"></param>
        /// <param name="status"><see cref="LeadQualifiedStatusCode"/> status code</param>
        /// <param name="customStatusCode">If you're using your custom statuscodes set this, otherwise you can set "0 (zero)" or null</param>
        /// <returns>Resturns created entities after qualification in <see cref="QualifyLeadResponse.CreatedEntities"/> property.</returns>
        public QualifyLeadResponse Qualify(Guid id, QualifyLeadTo qualifyTo, ExistingEntityType?existingRecordType, Guid?existingRecordId, Guid?currencyId, Guid?campaignId, LeadQualifiedStatusCode status = LeadQualifiedStatusCode.Qualified, int customStatusCode = 0)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");
            ExceptionThrow.IfNegative((int)qualifyTo, "qualifyTo");

            int statusCode = (int)status;

            if (status == LeadQualifiedStatusCode.CustomStatusCode)
            {
                ExceptionThrow.IfNegative(customStatusCode, "customStatusCode");
                statusCode = customStatusCode;
            }

            bool isAccount     = (qualifyTo.HasFlag(QualifyLeadTo.Account) || qualifyTo.HasFlag(QualifyLeadTo.AccountAndContact) || qualifyTo.HasFlag(QualifyLeadTo.OpportunityWithAccountAndContact)) && !qualifyTo.HasFlag(QualifyLeadTo.None);
            bool isContact     = (qualifyTo.HasFlag(QualifyLeadTo.Contact) || qualifyTo.HasFlag(QualifyLeadTo.AccountAndContact) || qualifyTo.HasFlag(QualifyLeadTo.OpportunityWithContact) || qualifyTo.HasFlag(QualifyLeadTo.OpportunityWithAccountAndContact)) && !qualifyTo.HasFlag(QualifyLeadTo.None);
            bool isOpportunity = (qualifyTo.HasFlag(QualifyLeadTo.OpportunityWithContact) || qualifyTo.HasFlag(QualifyLeadTo.OpportunityWithAccountAndContact) || qualifyTo.HasFlag(QualifyLeadTo.OpportunityWithExistingRecord)) && !qualifyTo.HasFlag(QualifyLeadTo.None);

            QualifyLeadRequest request = new QualifyLeadRequest()
            {
                LeadId            = new EntityReference(this.EntityName.ToLower(), id),
                CreateAccount     = isAccount,
                CreateContact     = isContact,
                CreateOpportunity = isOpportunity,
                Status            = new OptionSetValue(statusCode)
            };

            if (campaignId.HasValue)
            {
                ExceptionThrow.IfGuid(campaignId.Value, "campaignId");

                request.SourceCampaignId = new EntityReference("campaign", campaignId.Value);
            }

            if (isOpportunity)
            {
                var currencyEntityReference = currencyId.HasValue && !currencyId.Value.IsGuidEmpty() ? new EntityReference("transactioncurrency", currencyId.Value) : GetTransactionCurrency("lead", id);

                ExceptionThrow.IfNull(currencyEntityReference, "OpportunityCurrency");
                ExceptionThrow.IfGuidEmpty(currencyEntityReference.Id, "OpportunityCurrency.Id");

                request.OpportunityCurrencyId = currencyEntityReference;

                if (qualifyTo.HasFlag(QualifyLeadTo.OpportunityWithExistingRecord))
                {
                    ExceptionThrow.IfNull(existingRecordType, "existingRecordType");
                    ExceptionThrow.IfGuidEmpty(existingRecordId.Value, "existingRecordId");

                    request.OpportunityCustomerId = new EntityReference(existingRecordType.Description(), existingRecordId.Value);
                }
            }

            return((QualifyLeadResponse)this.OrganizationService.Execute(request));
        }
Esempio n. 18
0
        public static Entity Create(string entityName, string relatedEntityName, Guid relatedEntityId, Guid?productId, Guid?uomId, string productName, decimal quantity, decimal?price, decimal?discountAmount, decimal?tax)
        {
            ExceptionThrow.IfNullOrEmpty(entityName, "entityName");
            ExceptionThrow.IfNullOrEmpty(relatedEntityName, "relatedEntityName");
            ExceptionThrow.IfGuidEmpty(relatedEntityId, "relatedEntityId");
            ExceptionThrow.IfNegative(quantity, "quantity");

            Entity entity = new Entity(entityName.ToLower().Trim());

            entity[string.Format("{0}id", relatedEntityName.Trim())] = new EntityReference(relatedEntityName.Trim(), relatedEntityId);
            entity["quantity"] = quantity;

            if (string.IsNullOrEmpty(productName))
            {
                ExceptionThrow.IfNull(productId, "productId");
                ExceptionThrow.IfNull(uomId, "uomId");
                ExceptionThrow.IfGuidEmpty(productId.Value, "productId");
                ExceptionThrow.IfGuidEmpty(uomId.Value, "uomId");

                entity["productid"] = new EntityReference("product", productId.Value);
                entity["uomid"]     = new EntityReference("uom", uomId.Value);
            }
            else
            {
                entity["isproductoverridden"] = true;
                entity["productdescription"]  = productName;
            }

            if (price.HasValue)
            {
                ExceptionThrow.IfNegative(price.Value, "price");

                entity["priceperunit"]      = new Money(price.Value);
                entity["ispriceoverridden"] = true;
            }

            if (discountAmount.HasValue)
            {
                ExceptionThrow.IfNegative(discountAmount.Value, "discountAmount");

                entity["manualdiscountamount"] = new Money(discountAmount.Value);
            }

            if (tax.HasValue)
            {
                ExceptionThrow.IfNegative(tax.Value, "tax");

                entity["tax"] = new Money(tax.Value);
            }

            return(entity);
        }
Esempio n. 19
0
        /// <summary>
        /// Add a existing <c>Privilege</c> to a <c>Role</c>.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.addprivilegesrolerequest(v=crm.8).aspx
        /// </para>
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="privilege"></param>
        /// <returns><see cref="AddPrivilegesRoleResponse"/></returns>
        public AddPrivilegesRoleResponse AddPrivilege(Guid roleId, RolePrivilege privilege)
        {
            ExceptionThrow.IfGuidEmpty(roleId, "roleId");
            ExceptionThrow.IfNull(privilege, "privilege");

            AddPrivilegesRoleRequest request = new AddPrivilegesRoleRequest()
            {
                RoleId     = roleId,
                Privileges = new RolePrivilege[] { privilege }
            };

            return((AddPrivilegesRoleResponse)this.OrganizationService.Execute(request));
        }
        /// <summary>
        /// Retrieve <c>Article</c> 's content by <c>Html</c>.
        /// </summary>
        /// <param name="id"><c>Article</c> Id</param>
        /// <returns>
        /// <c>Html</c> data for <c>Article</c> content.
        /// </returns>
        public string RetrieveContent(Guid id)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");

            string result = string.Empty;

            var data = this.Get(id, "content");

            ExceptionThrow.IfNull(data, "KbArticle");

            result = data.GetAttributeValue <string>("content");
            return(result);
        }
Esempio n. 21
0
        /// <summary>
        /// Validate <c>Email</c> entity with required attributes.
        /// </summary>
        /// <param name="entity"></param>
        void ValidateEmailEntity(Entity entity)
        {
            ExceptionThrow.IfNull(entity, "entity");
            ExceptionThrow.IfNullOrEmpty(entity.LogicalName, "Entity.LogicalName");
            ExceptionThrow.IfNotExpectedValue(entity.LogicalName.Trim().ToLower(), "Entity.LogicalName", "email", "Entity.LogicalName must be 'email'");

            var sender = GetFrom(entity);

            ExceptionThrow.IfNull(sender, "email.from");
            ExceptionThrow.IfGuidEmpty(sender.Id, "email.from.id");
            ExceptionThrow.IfNullOrEmpty(sender.LogicalName, "email.from.LogicalName");

            ExceptionThrow.IfNullOrEmpty(((EntityCollection)entity["to"]).Entities, "email.to");
        }
        /// <summary>
        /// Add <c>recurrence</c> information to an existing <c>appointment</c>.
        /// Please note that when you convert an existing appointment to a recurring appointment, the data from the existing appointment is copied to a new recurring appointment master instance and the existing appointment record is deleted.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.addrecurrencerequest(v=crm.7).aspx
        /// </para>
        /// </summary>
        /// <param name="appointmentId"><c>Appointment</c> Id</param>
        /// <param name="recurringAppointment">
        /// Recurring Appointment entity (<see cref="Entity"/>)
        /// </param>
        /// <returns>
        /// Newly created <c>Recurring Appointment</c> Id (<see cref="Guid"/>)
        /// </returns>
        public Guid AddRecurrence(Guid appointmentId, Entity recurringAppointment)
        {
            ExceptionThrow.IfGuidEmpty(appointmentId, "appointmentId");
            ExceptionThrow.IfNull(recurringAppointment, "recurringAppointment");
            ExceptionThrow.IfNullOrEmpty(recurringAppointment.LogicalName, "Entity.LogicalName");
            ExceptionThrow.IfNotExpectedValue(recurringAppointment.LogicalName, "Entity.LogicalName", "recurringappointmentmaster");

            AddRecurrenceRequest request = new AddRecurrenceRequest()
            {
                AppointmentId = appointmentId,
                Target        = recurringAppointment
            };

            return(((AddRecurrenceResponse)this.OrganizationService.Execute(request)).id);
        }
Esempio n. 23
0
        /// <summary>
        /// Convert <see cref="XrmEmail"/> to <see cref="Entity"/> for <c>Email Activity</c>.
        /// </summary>
        /// <returns><see cref="Entity"/></returns>
        public Entity ToEntity()
        {
            Entity result = null;

            if (!_isInit)
            {
                throw new InvalidOperationException("Please INIT (call constructor of XrmEmail) before call ToEntity method.");
            }

            ExceptionThrow.IfNullOrEmpty(_from.Key, "From.EntityType");
            ExceptionThrow.IfGuidEmpty(_from.Value, "From.Id");
            ExceptionThrow.IfNull(_to, "To");
            ExceptionThrow.IfNullOrEmpty(_to.ToArray(), "To");
            ExceptionThrow.IfNullOrEmpty(_subject, "Subject");
            ExceptionThrow.IfNullOrEmpty(_body, "Body");

            result = new Entity("email");

            Entity from = new Entity("activityparty");

            from["partyid"] = new EntityReference(_from.Key, _from.Value);

            result["subject"]       = _subject;
            result["description"]   = _body;
            result["from"]          = new[] { from };
            result["to"]            = CreateActivityParty(_to);
            result["cc"]            = CreateActivityParty(_cc);
            result["bcc"]           = CreateActivityParty(_bcc);
            result["directioncode"] = _directionCode;
            result["prioritycode"]  = new OptionSetValue(_priority);
            result["statuscode"]    = new OptionSetValue(1);
            //INFO : In Microsoft Dynamics CRM 2015 and Microsoft Dynamics CRM Online 2015 Update, the Email.StatusCode attribute cannot be null. https://msdn.microsoft.com/en-us/library/gg334229.aspx

            if (!string.IsNullOrEmpty(_regardingObject.Key) && !_regardingObject.Value.IsGuidEmpty())
            {
                result["regardingobjectid"] = new EntityReference(_regardingObject.Key, _regardingObject.Value);
            }

            if (_customAttributeList != null && _customAttributeList.Keys.Count > 0)
            {
                foreach (KeyValuePair <string, object> item in _customAttributeList)
                {
                    result[item.Key] = item.Value;
                }
            }

            return(result);
        }
        /// <summary>
        /// Remove link (association) between records.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.xrm.sdk.messages.disassociaterequest(v=crm.8).aspx
        /// </para>
        /// </summary>
        /// <param name="mainRecordId"></param>
        /// <param name="mainRecordLogicalName"></param>
        /// <param name="relatedEntities"></param>
        /// <param name="relationName"></param>
        /// <returns>
        /// <see cref="DisassociateResponse"/>
        /// </returns>
        public DisassociateResponse Disassociate(Guid mainRecordId, string mainRecordLogicalName, EntityReferenceCollection relatedEntities, string relationName)
        {
            ExceptionThrow.IfGuidEmpty(mainRecordId, "mainRecordId");
            ExceptionThrow.IfNullOrEmpty(mainRecordLogicalName, "mainRecordLogicalName");
            ExceptionThrow.IfNull(relatedEntities, "relatedEntities");
            ExceptionThrow.IfNullOrEmpty(relationName, "relationName");

            DisassociateRequest request = new DisassociateRequest()
            {
                Target          = new EntityReference(mainRecordLogicalName, mainRecordId),
                RelatedEntities = relatedEntities,
                Relationship    = new Relationship(relationName)
            };

            return((DisassociateResponse)this.OrganizationService.Execute(request));
        }
        void ValidateEntity(Entity entity)
        {
            ExceptionThrow.IfNull(entity, "Entity");
            ExceptionThrow.IfNullOrEmpty(entity.LogicalName, "Entity.LogicalName");

            var n = entity.LogicalName.ToLower().Trim();

            if (n.Equals("phonecall") || n.Equals("appointment") || n.Equals("letter") || n.Equals("fax") || n.Equals("email"))
            {
                //Valid
            }
            else
            {
                ExceptionThrow.IfNotExpectedValue(entity.LogicalName, "Entity.LogicalName", "phonecall - appointment - letter - fax - email");
            }
        }
        /// <summary>
        /// Convert <see cref="XrmAppointment"/> to <see cref="Entity"/>
        /// </summary>
        /// <returns><see cref="Entity"/></returns>
        public Entity ToEntity()
        {
            Entity result = null;

            if (!_isInit)
            {
                throw new InvalidOperationException("Please INIT (call constructor of XrmAppointment) before call ToEntity method.");
            }

            ExceptionThrow.IfGuidEmpty(_organizer.Value, "Organizer.Id");
            ExceptionThrow.IfNullOrEmpty(_attendeeList, "AttendeeList");
            ExceptionThrow.IfNullOrEmpty(_subject, "Subject");
            ExceptionThrow.IfNull(_start, "StartDate");
            ExceptionThrow.IfNull(_end, "EndDate");

            result = new Entity("appointment");

            Entity organizer = new Entity("activityparty");

            organizer["partyid"] = new EntityReference(_organizer.Key.Description(), _organizer.Value);

            result["subject"]           = _subject;
            result["description"]       = _description;
            result["organizer"]         = new[] { organizer };
            result["requiredattendees"] = CreateActivityParty(AttendeeTypeCode.Required, _attendeeList);
            result["optionalattendees"] = CreateActivityParty(AttendeeTypeCode.Optional, _attendeeList);
            result["prioritycode"]      = new OptionSetValue(_priority);
            result["scheduledstart"]    = _start.Value;
            result["scheduledend"]      = _end.Value;
            result["isalldayevent"]     = _isAllDayEvent;
            result["location"]          = _location;

            if (!string.IsNullOrEmpty(_regardingObject.Key) && !_regardingObject.Value.IsGuidEmpty())
            {
                result["regardingobjectid"] = new EntityReference(_regardingObject.Key, _regardingObject.Value);
            }

            if (_customAttributeList != null && _customAttributeList.Keys.Count > 0)
            {
                foreach (KeyValuePair <string, object> item in _customAttributeList)
                {
                    result[item.Key] = item.Value;
                }
            }

            return(result);
        }
        /// <summary>
        /// Attach an existing attachment to email
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/gg328344(v=crm.7).aspx
        /// </para>
        /// </summary>
        /// <param name="emailId">Existing <c>Email Activity</c> Id</param>
        /// <param name="attachmentId">Existing <c>Attachment</c> Id</param>
        /// <returns>Created record Id (<see cref="System.Guid"/>)</returns>
        public Guid Attach(Guid emailId, Guid attachmentId)
        {
            ExceptionThrow.IfGuidEmpty(emailId, "EmailId");
            ExceptionThrow.IfGuidEmpty(attachmentId, "attachmentId");

            Entity existing = this.OrganizationService.Retrieve(this.EntityName, attachmentId, new ColumnSet(true));

            ExceptionThrow.IfNull(existing, "Attachment");

            Entity entity = new Entity(this.EntityName);

            entity["objectid"]       = new EntityReference("email", emailId);
            entity["objecttypecode"] = "email";
            entity["attachmentid"]   = existing["attachmentid"];

            return(this.OrganizationService.Create(entity));
        }
Esempio n. 28
0
        /// <summary>
        /// Creates an <see cref="AttachmentData"/> from <c>Byte Array</c> content.
        /// </summary>
        /// <param name="content"></param>
        /// <param name="fileName"></param>
        /// <returns>
        /// <see cref="AttachmentData"/>
        /// </returns>
        public static AttachmentData CreateFromByte(byte[] content, string fileName)
        {
            ExceptionThrow.IfNull(content, "content");
            ExceptionThrow.IfNullOrEmpty(fileName, "fileName");

            string tempFileName = Path.GetTempFileName();

            File.WriteAllBytes(tempFileName, content);

            FileInfo fileInfo = new FileInfo(tempFileName);

            var result = CreateFromPath(tempFileName, fileName);

            File.Delete(tempFileName);

            return(result);
        }
        /// <summary>
        /// Retrieve <c>Privilege</c> Id
        /// </summary>
        /// <param name="name">Privilege name with <c>prv</c> prefix
        /// </param>
        /// <returns>Record Id</returns>
        public Guid GetId(string name)
        {
            ExceptionThrow.IfNullOrEmpty("name", name);

            Guid result = Guid.Empty;

            var privilegeList = GetPredefinedPrivileges();

            ExceptionThrow.IfNull(privilegeList, "privilegeList", "System pre-defined privileges not found (001)");
            ExceptionThrow.IfNullOrEmpty(privilegeList.Entities, "privilegeList.Entities", "System pre-defined privileges not found (002)");

            var existingRole = privilegeList.Entities.Where(d => d["name"].Equals(name)).SingleOrDefault();

            ExceptionThrow.IfNull(existingRole, "Privilege", string.Format("'{0}' privilege not found", name));

            result = existingRole.Id;

            return(result);
        }
        void ValidateActivity(Guid id, string activityName)
        {
            var entity      = this.Get(id);
            var channelcode = entity.GetAttributeValue <OptionSetValue>("channeltypecode");

            ExceptionThrow.IfNull(channelcode, "channeltypecode", "CampaignActivity must has 'channeltypecode' (optionset) field.");

            if (!Enum.IsDefined(typeof(CampaignActivityChannelTypeCode), channelcode.Value))
            {
                ExceptionThrow.IfNotExpectedValue(channelcode.Value, "channelcode", 0, "'channeltypecode' value is not defined in 'CampaignActivityHelper.CampaignActivityChannelTypeCode' enum");
            }

            CampaignActivityChannelTypeCode channelEnum = (CampaignActivityChannelTypeCode)channelcode.Value;

            if (!activityName.ToLower().Trim().Equals(channelEnum.Description()))
            {
                ExceptionThrow.IfNotExpectedValue(activityName.ToLower().Trim(), "Entity.LogicalName", channelEnum.Description(), string.Format("Entity.LogicalName ('{0}') and CampaignActivity ChannelCode ('{1}') must be same value.", activityName.ToLower().Trim(), channelEnum.Description()));
            }
        }