/// <summary>
        /// Validates the state transition.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.isvalidstatetransitionrequest(v=crm.8).aspx
        /// </para>
        /// </summary>
        /// <param name="recordId">Record Id</param>
        /// <param name="entityLogicalName">Record's entity logical name</param>
        /// <param name="newStateCode"></param>
        /// <param name="newStatusCode"></param>
        /// <returns>
        /// Returns <c>true</c> if is valid. (<see cref="IsValidStateTransitionResponse.IsValid"/>)
        /// </returns>
        public bool Validate(Guid recordId, string entityLogicalName, string newStateCode, int newStatusCode)
        {
            ExceptionThrow.IfGuidEmpty(recordId, "id");
            ExceptionThrow.IfNullOrEmpty(entityLogicalName, "entityLogicalName");

            List <string> supportedEntityList = new List <string>()
            {
                "incident",
                "msdyn_postalbum",
                "msdyn_postconfig",
                "msdyn_postruleconfig",
                "msdyn_wallsavedquery",
                "msdyn_wallsavedqueryusersettings",
                "opportunity"
            };

            if (!supportedEntityList.Contains(entityLogicalName.ToLower().Trim()))
            {
                ExceptionThrow.IfNotExpectedValue(entityLogicalName, "entityLogicalName", "", string.Format("{0} is not supported for this operation. For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.isvalidstatetransitionrequest(v=crm.8).aspx", entityLogicalName));
            }

            IsValidStateTransitionRequest request = new IsValidStateTransitionRequest()
            {
                Entity    = new EntityReference(entityLogicalName, recordId),
                NewState  = newStateCode.Trim(),
                NewStatus = newStatusCode
            };

            IsValidStateTransitionResponse response = (IsValidStateTransitionResponse)this.OrganizationService.Execute(request);

            return(response.IsValid);
        }
Example #2
0
        /// <summary>
        /// <c>Cancel</c> the <c>SalesOrder</c>.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.cancelsalesorderrequest(v=crm.8).aspx
        /// </para>
        /// </summary>
        /// <param name="id"><c>SalesOrder</c> Id</param>
        /// <param name="status"><see cref="SalesOrderCanceledStatusCode"/> status code</param>
        /// <param name="customStatusCode">If you're using your custom statuscodes set this, otherwise you can set "0 (zero)" or null</param>
        /// <param name="ordercloseSubject"><c>OrderClose</c> subject</param>
        /// <param name="ordercloseDescription"><c>OrderClose</c> description</param>
        /// <param name="ordercloseActualEnd"><c>OrderClose</c> actual end date</param>
        /// <returns>
        /// <see cref="CancelSalesOrderResponse"/>
        /// </returns>
        public CancelSalesOrderResponse Cancel(Guid id, SalesOrderCanceledStatusCode status, int customStatusCode = 0, string ordercloseSubject = "", string ordercloseDescription = "", DateTime?ordercloseActualEnd = null)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");

            int statusCode = (int)status;

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

            if (string.IsNullOrEmpty(ordercloseSubject))
            {
                var salesorderEntity = this.Get(id, "ordernumber");
                ordercloseSubject = string.Format("Salesorder Close (Cancel) - {0}", salesorderEntity.GetAttributeValue <string>("ordernumber"));
            }

            CancelSalesOrderRequest request = new CancelSalesOrderRequest()
            {
                OrderClose = PrepareOrderCloseEntity(id, ordercloseSubject, ordercloseDescription, ordercloseActualEnd),
                Status     = new OptionSetValue(statusCode)
            };

            return((CancelSalesOrderResponse)this.OrganizationService.Execute(request));
        }
        /// <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));
        }
Example #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>
        /// Delete an existing record
        /// </summary>
        /// <param name="id">Record Id</param>
        /// <param name="entityLogicalName">Record logical name</param>
        public void Delete(Guid id, string entityLogicalName)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");
            ExceptionThrow.IfNullOrEmpty(entityLogicalName, "entityLogicalName");

            this.OrganizationService.Delete(entityLogicalName, id);
        }
Example #6
0
        /// <summary>
        /// Successfuly <c>close (resolve)</c> an incident.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.closeincidentrequest(v=crm.8).aspx
        /// </para>
        /// </summary>
        /// <param name="id"><c>Incident</c> Id</param>
        /// <param name="status"><see cref="IncidentResolvedStatusCode"/> status code</param>
        /// <param name="customStatusCode">If you're using your custom statuscodes set this, otherwise you can set "0 (zero)" or null</param>
        /// <param name="subject"><c>Incident Resolution</c> subject</param>
        /// <param name="description"><c>Incident Resolution</c> description</param>
        /// <param name="resolveDate"><c>Incident Resolution</c> acual end date</param>
        /// <returns>
        /// <see cref="CloseIncidentResponse"/>
        /// </returns>
        public CloseIncidentResponse Resolve(Guid id, IncidentResolvedStatusCode status, int customStatusCode = 0, string subject = "Resolved Incident", string description = "", DateTime?resolveDate = null)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");

            int statusCode = (int)status;

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

            Entity incidentResolution = new Entity("incidentresolution");

            incidentResolution["incidentid"]  = new EntityReference(this.EntityName, id);
            incidentResolution["subject"]     = subject;
            incidentResolution["description"] = description;

            if (resolveDate.HasValue && resolveDate.Value != DateTime.MinValue)
            {
                incidentResolution["actualend"] = resolveDate.Value;
            }

            CloseIncidentRequest request = new CloseIncidentRequest()
            {
                IncidentResolution = incidentResolution,
                Status             = new OptionSetValue(statusCode)
            };

            return((CloseIncidentResponse)this.OrganizationService.Execute(request));
        }
        /// <summary>
        /// Create a <c>Campaign Activity</c>.
        /// </summary>
        /// <param name="campaignId"><c>Campaign</c> Id</param>
        /// <param name="subject">Subject</param>
        /// <param name="description">Description</param>
        /// <param name="typeCode"><see cref="CampaignActivityTypeCode"/> type code</param>
        /// <param name="channelCode"><see cref="CampaignActivityChannelTypeCode"/> channel code</param>
        /// <param name="customTypeCode">If you're using your custom typecode set this, otherwise you can set "0 (zero)" or null</param>
        /// <param name="customChannelCode">If you're using your custom channel code set this, otherwise you can set "0 (zero)" or null</param>
        /// <returns>
        /// Created record Id (<see cref="Guid"/>)
        /// </returns>
        public Guid Create(Guid campaignId, string subject, string description, CampaignActivityTypeCode typeCode, CampaignActivityChannelTypeCode channelCode, int customTypeCode = 0, int customChannelCode = 0)
        {
            ExceptionThrow.IfGuidEmpty(campaignId, "campaignId");
            ExceptionThrow.IfNullOrEmpty(subject, "subject");

            int activityTypeCode    = (int)typeCode;
            int activityChannelCode = (int)channelCode;

            if (typeCode == CampaignActivityTypeCode.CustomTypeCode)
            {
                ExceptionThrow.IfNegative(customTypeCode, "customTypeCode");
                activityTypeCode = customTypeCode;
            }

            if (channelCode == CampaignActivityChannelTypeCode.CustomChannelTypeCode)
            {
                ExceptionThrow.IfNegative(customChannelCode, "customChannelCode");
                activityChannelCode = customChannelCode;
            }

            Entity entity = new Entity(this.EntityName);

            entity["regardingobjectid"] = new EntityReference("campaign", campaignId);
            entity["subject"]           = subject;
            entity["typecode"]          = new OptionSetValue(activityTypeCode);
            entity["channeltypecode"]   = new OptionSetValue(activityChannelCode);
            entity["description"]       = description;

            return(this.OrganizationService.Create(entity));
        }
        /// <summary>
        /// <c>Win</c> an opportunity.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.winopportunityrequest(v=crm.7).aspx
        /// </para>
        /// </summary>
        /// <param name="id"><c>Opportunity</c> Id</param>
        /// <param name="status"><see cref="OpportunityWonStatusCode"/> status code</param>
        /// <param name="customStatusCode">If you're using your custom statuscodes set this, otherwise you can set "0 (zero)" or null</param>
        /// <param name="opportunitycloseSubject"><c>OpportunityClose</c> subjec</param>
        /// <param name="opportunitycloseDescription"><c>OpportunityClose</c> description</param>
        /// <param name="opportunitycloseActualEnd"><c>OpportunityClose</c> actual end date. Default value is <c>DateTime.UtcNow</c> or <c>DateTime.Now</c> depend on <c>useUtc</c> parameter on constructor</param>
        /// <param name="useOpportunityTotalAmountValue">Set <c>true</c>, if you want to use <c>Opportunity</c>'s current <c>Total Amount</c> value, otherwise if you want new value set <c>false</c> and set value of <c>opportunitycloseActualRevenue</c> parameter</param>
        /// <param name="opportunitycloseActualRevenue"><c>OpportunityClose</c> actual revenue.</param>
        /// <returns><see cref="WinOpportunityResponse"/></returns>
        public WinOpportunityResponse Win(Guid id, OpportunityWonStatusCode status, int customStatusCode = 0, string opportunitycloseSubject = "", string opportunitycloseDescription = "", DateTime?opportunitycloseActualEnd = null, bool useOpportunityTotalAmountValue = false, decimal opportunitycloseActualRevenue = 0)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");

            int statusCode = (int)status;

            opportunitycloseSubject = !string.IsNullOrEmpty(opportunitycloseSubject) ? opportunitycloseSubject.Trim() : "Opportunity Close - Won";

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

            if (useOpportunityTotalAmountValue)
            {
                opportunitycloseActualRevenue = GetTotalAmount(id);
            }

            WinOpportunityRequest request = new WinOpportunityRequest()
            {
                OpportunityClose = PrepareOpportunityCloseEntity(id, opportunitycloseSubject, opportunitycloseDescription, null, opportunitycloseActualEnd, opportunitycloseActualRevenue),
                Status           = new OptionSetValue(statusCode)
            };

            return((WinOpportunityResponse)this.OrganizationService.Execute(request));
        }
        /// <summary>
        /// Distribute <c>CampaignActivity</c> with <c>Email</c> activity.
        /// </summary>
        /// <param name="id"><c>CampaignActvity</c> Id</param>
        /// <param name="fromType">Email <c>From</c> (<see cref="FromEntityType"/>)</param>
        /// <param name="fromId">Email <c>From</c> Id</param>
        /// <param name="subject">Email Subject</param>
        /// <param name="body">Email Body</param>
        /// <param name="emailTemplateId">
        /// If you want to use existing <c>template</c> set this field.
        /// Method throws an exception (<see cref="ExceptionThrow.IfGuidEmpty(Guid, string, string)"/>) if you set this field to <see cref="Guid.Empty"/>
        /// </param>
        /// <param name="sendEmail">
        /// Set <c>true</c> if you want to send created activities.
        /// </param>
        /// <param name="propagationOwnershipOptions"></param>
        /// <param name="ownerTypeCode"></param>
        /// <param name="ownerId"></param>
        /// <param name="queueId"></param>
        /// <param name="doesPropagate">Set <c>true</c>, whether the activity is both created and executed. Otherwise set <c>false</c>.</param>
        /// <param name="useAsync">
        /// Set <c>true</c>, whether the activity is both created and executed. Otherwise set <c>false</c>.
        /// This field's default value is <c>true</c>, so activity will be created and executed (exp: email wil be send)
        /// </param>
        /// <param name="validateActivity"></param>
        /// <returns>
        /// Returns created <c>BulkOperation</c> Id in <see cref="DistributeCampaignActivityResponse.BulkOperationId"/> property.
        /// </returns>
        public DistributeCampaignActivityResponse DistributeByEmail(Guid id, FromEntityType fromType, Guid fromId, string subject, string body, Guid?emailTemplateId, bool sendEmail, PropagationOwnershipOptions propagationOwnershipOptions, PrincipalType ownerTypeCode, Guid ownerId, Guid?queueId, bool doesPropagate = true, bool useAsync = true, bool validateActivity = true)
        {
            ExceptionThrow.IfGuidEmpty(fromId, "fromId");

            Entity from = new Entity("activityparty");

            from["partyid"] = new EntityReference(fromType.Description(), fromId);

            Entity entity = new Entity("email");

            entity["from"] = new[] { from };

            if (emailTemplateId.HasValue)
            {
                ExceptionThrow.IfGuidEmpty(emailTemplateId.Value, "templateId");
            }
            else
            {
                ExceptionThrow.IfNullOrEmpty(subject, "subject");
                ExceptionThrow.IfNullOrEmpty(body, "body");

                entity["subject"]     = subject;
                entity["description"] = body;
            }

            return(Distribute(id, entity, propagationOwnershipOptions, ownerTypeCode, ownerId, queueId, emailTemplateId, doesPropagate, useAsync, sendEmail, validateActivity));
        }
Example #10
0
        /// <summary>
        /// Change <c>Quote</c> status to <c>Won</c>.
        /// Please note that this action is required in order to convert a <c>Quote</c> into a <c>SalesOrder</c> with <see cref="ConvertToSalesOrder(Guid, string[])"/> method.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.winquoterequest(v=crm.7).aspx
        /// </para>
        /// </summary>
        /// <param name="id"><c>Quote</c> Id</param>
        /// <param name="status"><see cref="QuoteWonStatusCode"/> status code</param>
        /// <param name="customStatusCode">If you're using your custom statuscodes set this, otherwise you can set "0 (zero)" or null</param>
        /// <param name="quotecloseSubject"><c>QuoteClose</c> subject</param>
        /// <param name="quotecloseDescription"><c>QuoteClose</c> description</param>
        /// <param name="quotecloseActualEnd"><c>QuoteClose</c> actual end date</param>
        /// <returns><see cref="WinQuoteResponse"/></returns>
        public WinQuoteResponse Win(Guid id, QuoteWonStatusCode status, int customStatusCode = 0, string quotecloseSubject = "", string quotecloseDescription = "", DateTime?quotecloseActualEnd = null)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");

            int statusCode = (int)status;

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

            if (string.IsNullOrEmpty(quotecloseSubject))
            {
                var quoteEntity = this.Get(id, "quotenumber");
                quotecloseSubject = string.Format("Quote Close (Won) - {0}", quoteEntity.GetAttributeValue <string>("quotenumber"));
            }

            WinQuoteRequest request = new WinQuoteRequest()
            {
                QuoteClose = PrepareQuoteCloseEntity(id, quotecloseSubject, quotecloseDescription, quotecloseActualEnd),
                Status     = new OptionSetValue(statusCode)
            };

            return((WinQuoteResponse)this.OrganizationService.Execute(request));
        }
        /// <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));
        }
Example #12
0
        /// <summary>
        /// Retrieve <c>members</c> from <c>List (marketing list)</c>.
        /// <para>
        /// Please note that if your <c>list</c> is <c>dynamic</c> it must has "Fullname" (for <c>Contact</c>, <c>Lead</c>) or "Name" (for <c>Account</c>) attribute in its query.
        /// Otherwise <see cref="ListMemberItemDetail.Name"/> will be <see cref="string.Empty"/>.
        /// </para>
        /// </summary>
        /// <param name="listId">Marketing List Id</param>
        /// <param name="itemPerPage">
        /// Record count per page. If marketling list has more than value, method works in loop.
        /// It's default value <c>5000</c> and recommended range is between <c>500</c> - <c>5000</c> for better performance.
        /// </param>
        /// <returns>
        /// <see cref="ListMemberResult"/> for data.
        /// </returns>
        public ListMemberResult GetMemberList(Guid listId, int itemPerPage = 5000)
        {
            ExceptionThrow.IfGuidEmpty(listId, "listId");

            ListMemberResult result = new ListMemberResult();

            var list = this.OrganizationService.Retrieve(this.EntityName, listId, new ColumnSet("type", "membertype", "query"));

            if (list != null)
            {
                ListTypeCode       listType   = (ListTypeCode)Convert.ToInt32(list.GetAttributeValue <bool>("type"));
                ListMemberTypeCode membertype = (ListMemberTypeCode)list.GetAttributeValue <int>("membertype");
                string             query      = list.GetAttributeValue <string>("query");

                switch (listType)
                {
                case ListTypeCode.Static:
                    result = PopulateStaticList(listId, membertype, itemPerPage);
                    break;

                case ListTypeCode.Dynamic:
                    result = PopulateDynamicList(query, membertype, itemPerPage);
                    break;
                }
            }

            return(result);
        }
        /// <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));
        }
Example #14
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>
        /// 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));
        }
        /// <summary>
        /// Add <c>organizer</c>
        /// </summary>
        /// <param name="entityTypeCode"><see cref="AttendeeEntityTypeCode"/></param>
        /// <param name="id"></param>
        /// <returns><see cref="XrmAppointment"/></returns>
        public XrmAppointment AddOrganizer(AttendeeEntityTypeCode entityTypeCode, Guid id)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");

            _organizer = new KeyValuePair <AttendeeEntityTypeCode, Guid>(entityTypeCode, id);
            return(this);
        }
Example #17
0
        /// <summary>
        /// Retrieve <c>Transaction Currency</c> information for specified entity.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="entityLogicalName"></param>
        /// <returns></returns>
        public EntityReference GetTransactionCurrencyInfo(Guid id, string entityLogicalName)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");
            ExceptionThrow.IfNullOrEmpty(entityLogicalName, "entityLogicalName");

            EntityReference result = null;

            var transactionCurrency = this.OrganizationService.Retrieve(entityLogicalName, id, new ColumnSet("transactioncurrencyid"));

            if (transactionCurrency != null && transactionCurrency.Contains("transactioncurrencyid"))
            {
                result = (EntityReference)transactionCurrency["transactioncurrencyid"];
            }
            else
            {
                QueryExpression organizationQuery = new QueryExpression("organization")
                {
                    ColumnSet = new ColumnSet("basecurrencyid")
                };

                var response = this.OrganizationService.RetrieveMultiple(organizationQuery);

                if (response != null && response.Entities != null && response.Entities.Count > 0)
                {
                    result = (EntityReference)response.Entities[0]["basecurrencyid"];
                }
            }

            return(result);
        }
Example #18
0
        /// <summary>
        /// Validate specified marketing lists with <c>Targeted At</c> field (<c>CreatedFromCode</c> attribute).
        /// </summary>
        /// <param name="sourceListId">Source Marketing List Id</param>
        /// <param name="targetListId">Target Marketing List Id</param>
        /// <returns>
        /// <c>true</c> if marketing lists are same type
        /// </returns>
        public bool IsSameType(Guid sourceListId, Guid targetListId)
        {
            ExceptionThrow.IfGuidEmpty(sourceListId, "sourceListId");
            ExceptionThrow.IfGuidEmpty(targetListId, "targetListId");

            bool result = false;

            var sourceList = this.Get(sourceListId, "createdfromcode");
            var targetList = this.Get(targetListId, "createdfromcode");

            int sourceCode = 0;
            int targetcode = 0;

            if (sourceList != null && sourceList.GetAttributeValue <OptionSetValue>("createdfromcode") != null)
            {
                sourceCode = sourceList.GetAttributeValue <OptionSetValue>("createdfromcode").Value;
            }

            if (targetList != null && targetList.GetAttributeValue <OptionSetValue>("createdfromcode") != null)
            {
                targetcode = targetList.GetAttributeValue <OptionSetValue>("createdfromcode").Value;
            }

            if (sourceCode != 0 && targetcode != 0 && sourceCode.Equals(targetcode))
            {
                result = true;
            }

            return(result);
        }
Example #19
0
        /// <summary>
        /// Release Hold.
        /// </summary>
        /// <param name="id"></param>
        public void ReleaseHold(Guid id)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");

            CommonHelper commonHelper = new CommonHelper(this.OrganizationService);

            commonHelper.UpdateState(id, this.EntityName, (int)ContractStateCode.Invoiced, (int)ContractInvoicedStatusCode.Invoiced);
        }
        /// <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));
        }
Example #21
0
        /// <summary>
        /// Add <c>BCC</c>.
        /// </summary>
        /// <param name="entityType"></param>
        /// <param name="id"></param>
        /// <returns><see cref="XrmEmail"/></returns>
        public XrmEmail Bcc(ToEntityType entityType, Guid id)
        {
            ExceptionThrow.IfGuidEmpty(id, "Bcc.Id");

            _bcc.Add(new Tuple <ToEntityType, Guid, string>(entityType, id, string.Empty));

            return(this);
        }
        /// <summary>
        /// Archive <c>Knowledge Article</c> record.
        /// </summary>
        /// <param name="id"><c>Article</c> Id</param>
        public void Archive(Guid id)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");

            CommonHelper commonHelper = new CommonHelper(this.OrganizationService);

            commonHelper.UpdateState(id, this.EntityName, (int)KnowledgeArticleStateCode.Archived, (int)KnowledgeArticleArchivedStatusCode.Archived);
        }
        /// <summary>
        /// Revert to draft <c>Knowledge Article</c> record.
        /// </summary>
        /// <param name="id"><c>Article</c> Id</param>
        public void Draft(Guid id)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");

            CommonHelper commonHelper = new CommonHelper(this.OrganizationService);

            commonHelper.UpdateState(id, this.EntityName, (int)KnowledgeArticleStateCode.Draft, (int)KnowledgeArticleDraftStatusCode.Proposed);
        }
        /// <summary>
        /// Add <c>attendee</c>
        /// </summary>
        /// <param name="typecode"><see cref="AttendeeTypeCode"/></param>
        /// <param name="entityTypeCode"><see cref="AttendeeEntityTypeCode"/></param>
        /// <param name="id"></param>
        /// <returns><see cref="XrmAppointment"/></returns>
        public XrmAppointment AddAttendee(AttendeeTypeCode typecode, AttendeeEntityTypeCode entityTypeCode, Guid id)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");

            _attendeeList.Add(new Tuple <AttendeeTypeCode, AttendeeEntityTypeCode, Guid>(typecode, entityTypeCode, id));

            return(this);
        }
        /// <summary>
        /// Unpublish <c>Article</c>.
        /// </summary>
        /// <param name="id"><c>Article</c> Id</param>
        public void UnPublish(Guid id)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");

            CommonHelper commonHelper = new CommonHelper(this.OrganizationService);

            commonHelper.UpdateState(id, this.EntityName, (int)KbArticleStateCode.Unapproved, (int)KbArticleUnapprovedStatusCode.Unapproved);
        }
Example #26
0
        /// <summary>
        /// Enable a <c>System User</c> by Id.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/jj602914(v=crm.8).aspx
        /// </para>
        /// </summary>
        /// <param name="id"><c>System User</c> Id</param>
        public void Enable(Guid id)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");

            CommonHelper commonHelper = new CommonHelper(this.OrganizationService);

            commonHelper.UpdateState(id, this.EntityName, 0, -1);
        }
Example #27
0
        /// <summary>
        /// Enable a <c>System User</c> by domainname.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/jj602914(v=crm.8).aspx
        /// </para>
        /// </summary>
        /// <param name="domainname"><c>Active Directory name</c>(with domain)</param>
        public void Enable(string domainname)
        {
            ExceptionThrow.IfNullOrEmpty(domainname, "domainname");

            Guid id = GetId(domainname.Trim());

            ExceptionThrow.IfGuidEmpty(id, "id", string.Format("{0} user not found", domainname));
            Enable(id);
        }
        /// <summary>
        /// Create an attachment from drive path.
        /// <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="path">File path</param>
        /// <returns>
        /// Created record Id (<see cref="System.Guid"/>)
        /// </returns>
        public Guid Attach(Guid emailId, string path)
        {
            ExceptionThrow.IfGuidEmpty(emailId, "emailId");
            ExceptionThrow.IfNullOrEmpty(path, "path");

            var attachment = AttachmentHelper.CreateFromPath(path, string.Empty);

            return(Attach(emailId, attachment.Data.ByteArray, attachment.Meta.Name));
        }
        /// <summary>
        /// Delete an existing record
        /// </summary>
        /// <param name="id">Record Id</param>
        public void Delete(Guid id)
        {
            ExceptionThrow.IfNullOrEmpty(this.EntityName, "BaseEntityHelper.EntityName");
            ExceptionThrow.IfGuidEmpty(id, "id");

            CommonHelper commonHelper = new CommonHelper(this.OrganizationService);

            commonHelper.Delete(id, this.EntityName);
        }
        /// <summary>
        /// Retrieve record by Id
        /// </summary>
        /// <param name="id">Record (Entity) Id</param>
        /// <param name="retrievedColumns">Set columns (attributes) that you need. If you don't set, default value is <see cref="ColumnSet(true)"/></param>
        /// <returns>
        /// <see cref="Entity"/> for record data
        /// </returns>
        public Entity Get(Guid id, params string[] retrievedColumns)
        {
            ExceptionThrow.IfNullOrEmpty(this.EntityName, "BaseEntityHelper.EntityName");
            ExceptionThrow.IfGuidEmpty(id, "id");

            var columnSet = !retrievedColumns.IsNullOrEmpty() ? new ColumnSet(retrievedColumns) : new ColumnSet(true);

            return(this.OrganizationService.Retrieve(this.EntityName.ToLower().Trim(), id, columnSet));
        }