private void AddOrUpdateThisRecordWithAzure(Entity queriedEntityRecord, Entity configurationRecord, LocalPluginContext localContext, IOrganizationService service, IPluginExecutionContext context)
        {
            localContext.TracingService.Trace("---------Send the Record to Azure---------");
            string messageName = context.MessageName;
            string text        = "Receipt";
            string text2       = Utilities.GetAzureWebAPIURL(service, context);

            localContext.TracingService.Trace("Got API URL: " + text2);
            if (text2 != string.Empty)
            {
                localContext.TracingService.Trace("Getting Latest Info for Record: " + queriedEntityRecord["msnfp_receiptid"].ToString());
                MSNFP_Receipt mSNFP_Receipt = new MSNFP_Receipt();
                mSNFP_Receipt.ReceiptId  = (Guid)queriedEntityRecord["msnfp_receiptid"];
                mSNFP_Receipt.Identifier = (queriedEntityRecord.Contains("msnfp_identifier") ? ((string)queriedEntityRecord["msnfp_identifier"]) : string.Empty);
                localContext.TracingService.Trace("Title: " + mSNFP_Receipt.Identifier);
                if (queriedEntityRecord.Contains("msnfp_customerid") && queriedEntityRecord["msnfp_customerid"] != null)
                {
                    mSNFP_Receipt.CustomerId = ((EntityReference)queriedEntityRecord["msnfp_customerid"]).Id;
                    if (((EntityReference)queriedEntityRecord["msnfp_customerid"]).LogicalName.ToLower() == "contact")
                    {
                        mSNFP_Receipt.CustomerIdType = 2;
                    }
                    else if (((EntityReference)queriedEntityRecord["msnfp_customerid"]).LogicalName.ToLower() == "account")
                    {
                        mSNFP_Receipt.CustomerIdType = 1;
                    }
                    localContext.TracingService.Trace("Got msnfp_customerid.");
                }
                else
                {
                    mSNFP_Receipt.CustomerId     = null;
                    mSNFP_Receipt.CustomerIdType = null;
                    localContext.TracingService.Trace("Did NOT find msnfp_customerid.");
                }
                if (queriedEntityRecord.Contains("msnfp_expectedtaxcredit") && queriedEntityRecord["msnfp_expectedtaxcredit"] != null)
                {
                    mSNFP_Receipt.ExpectedTaxCredit = ((Money)queriedEntityRecord["msnfp_expectedtaxcredit"]).Value;
                    localContext.TracingService.Trace("Got msnfp_expectedtaxcredit.");
                }
                else
                {
                    mSNFP_Receipt.ExpectedTaxCredit = null;
                    localContext.TracingService.Trace("Did NOT find msnfp_expectedtaxcredit.");
                }
                if (queriedEntityRecord.Contains("msnfp_generatedorprinted") && queriedEntityRecord["msnfp_generatedorprinted"] != null)
                {
                    mSNFP_Receipt.GeneratedorPrinted = (double)queriedEntityRecord["msnfp_generatedorprinted"];
                    localContext.TracingService.Trace("Got msnfp_generatedorprinted.");
                }
                else
                {
                    mSNFP_Receipt.GeneratedorPrinted = null;
                    localContext.TracingService.Trace("Did NOT find msnfp_generatedorprinted.");
                }
                if (queriedEntityRecord.Contains("msnfp_lastdonationdate") && queriedEntityRecord["msnfp_lastdonationdate"] != null)
                {
                    mSNFP_Receipt.LastDonationDate = (DateTime)queriedEntityRecord["msnfp_lastdonationdate"];
                    localContext.TracingService.Trace("Got msnfp_lastdonationdate.");
                }
                else
                {
                    mSNFP_Receipt.LastDonationDate = null;
                    localContext.TracingService.Trace("Did NOT find msnfp_lastdonationdate.");
                }
                if (queriedEntityRecord.Contains("msnfp_amount_nonreceiptable") && queriedEntityRecord["msnfp_amount_nonreceiptable"] != null)
                {
                    mSNFP_Receipt.AmountNonReceiptable = ((Money)queriedEntityRecord["msnfp_amount_nonreceiptable"]).Value;
                    localContext.TracingService.Trace("Got msnfp_amount_nonreceiptable.");
                }
                else
                {
                    mSNFP_Receipt.AmountNonReceiptable = null;
                    localContext.TracingService.Trace("Did NOT find msnfp_amount_nonreceiptable.");
                }
                if (queriedEntityRecord.Contains("msnfp_transactioncount") && queriedEntityRecord["msnfp_transactioncount"] != null)
                {
                    mSNFP_Receipt.TransactionCount = (int)queriedEntityRecord["msnfp_transactioncount"];
                    localContext.TracingService.Trace("Got msnfp_transactioncount.");
                }
                else
                {
                    mSNFP_Receipt.TransactionCount = null;
                    localContext.TracingService.Trace("Did NOT find msnfp_transactioncount.");
                }
                if (queriedEntityRecord.Contains("msnfp_preferredlanguagecode") && queriedEntityRecord["msnfp_preferredlanguagecode"] != null)
                {
                    mSNFP_Receipt.PreferredLanguageCode = ((OptionSetValue)queriedEntityRecord["msnfp_preferredlanguagecode"]).Value;
                    localContext.TracingService.Trace("Got msnfp_preferredlanguagecode.");
                }
                else
                {
                    mSNFP_Receipt.PreferredLanguageCode = null;
                    localContext.TracingService.Trace("Did NOT find msnfp_preferredlanguagecode.");
                }
                if (queriedEntityRecord.Contains("msnfp_receiptnumber") && queriedEntityRecord["msnfp_receiptnumber"] != null)
                {
                    mSNFP_Receipt.ReceiptNumber = (string)queriedEntityRecord["msnfp_receiptnumber"];
                    localContext.TracingService.Trace("Got msnfp_receiptnumber.");
                }
                else
                {
                    mSNFP_Receipt.ReceiptNumber = null;
                    localContext.TracingService.Trace("Did NOT find msnfp_receiptnumber.");
                }
                if (queriedEntityRecord.Contains("msnfp_receiptgeneration") && queriedEntityRecord["msnfp_receiptgeneration"] != null)
                {
                    mSNFP_Receipt.ReceiptGeneration = ((OptionSetValue)queriedEntityRecord["msnfp_receiptgeneration"]).Value;
                    localContext.TracingService.Trace("Got msnfp_receiptgeneration.");
                }
                else
                {
                    mSNFP_Receipt.ReceiptGeneration = null;
                    localContext.TracingService.Trace("Did NOT find msnfp_receiptgeneration.");
                }
                if (queriedEntityRecord.Contains("msnfp_receiptissuedate") && queriedEntityRecord["msnfp_receiptissuedate"] != null)
                {
                    mSNFP_Receipt.ReceiptIssueDate = (DateTime)queriedEntityRecord["msnfp_receiptissuedate"];
                    localContext.TracingService.Trace("Got msnfp_receiptissuedate.");
                }
                else
                {
                    mSNFP_Receipt.ReceiptIssueDate = null;
                    localContext.TracingService.Trace("Did NOT find msnfp_receiptissuedate.");
                }
                if (queriedEntityRecord.Contains("msnfp_receiptstackid") && queriedEntityRecord["msnfp_receiptstackid"] != null)
                {
                    mSNFP_Receipt.ReceiptStackId = ((EntityReference)queriedEntityRecord["msnfp_receiptstackid"]).Id;
                    localContext.TracingService.Trace("Got msnfp_receiptstackid.");
                }
                else
                {
                    mSNFP_Receipt.ReceiptStackId = null;
                    localContext.TracingService.Trace("Did NOT find msnfp_receiptstackid.");
                }
                if (queriedEntityRecord.Contains("msnfp_receiptstatus") && queriedEntityRecord["msnfp_receiptstatus"] != null)
                {
                    mSNFP_Receipt.ReceiptStatus = (string)queriedEntityRecord["msnfp_receiptstatus"];
                    localContext.TracingService.Trace("Got msnfp_receiptstatus.");
                }
                else
                {
                    mSNFP_Receipt.ReceiptStatus = null;
                    localContext.TracingService.Trace("Did NOT find msnfp_receiptstatus.");
                }
                if (queriedEntityRecord.Contains("msnfp_amount_receipted") && queriedEntityRecord["msnfp_amount_receipted"] != null)
                {
                    mSNFP_Receipt.AmountReceipted = ((Money)queriedEntityRecord["msnfp_amount_receipted"]).Value;
                    localContext.TracingService.Trace("Got msnfp_amount_receipted.");
                }
                else
                {
                    mSNFP_Receipt.AmountReceipted = null;
                    localContext.TracingService.Trace("Did NOT find msnfp_amount_receipted.");
                }
                if (queriedEntityRecord.Contains("msnfp_paymentscheduleid") && queriedEntityRecord["msnfp_paymentscheduleid"] != null)
                {
                    mSNFP_Receipt.PaymentScheduleId = ((EntityReference)queriedEntityRecord["msnfp_paymentscheduleid"]).Id;
                    localContext.TracingService.Trace("Got msnfp_paymentscheduleid.");
                }
                else
                {
                    mSNFP_Receipt.PaymentScheduleId = null;
                    localContext.TracingService.Trace("Did NOT find msnfp_paymentscheduleid.");
                }
                if (queriedEntityRecord.Contains("msnfp_replacesreceiptid") && queriedEntityRecord["msnfp_replacesreceiptid"] != null)
                {
                    mSNFP_Receipt.ReplacesReceiptId = ((EntityReference)queriedEntityRecord["msnfp_replacesreceiptid"]).Id;
                    localContext.TracingService.Trace("Got msnfp_replacesreceiptid.");
                }
                else
                {
                    mSNFP_Receipt.ReplacesReceiptId = null;
                    localContext.TracingService.Trace("Did NOT find msnfp_replacesreceiptid.");
                }
                if (queriedEntityRecord.Contains("msnfp_replacesreceiptid") && queriedEntityRecord["msnfp_replacesreceiptid"] != null)
                {
                    mSNFP_Receipt.ReplacesReceiptId = ((EntityReference)queriedEntityRecord["msnfp_replacesreceiptid"]).Id;
                    localContext.TracingService.Trace("Got msnfp_replacesreceiptid.");
                }
                else
                {
                    mSNFP_Receipt.ReplacesReceiptId = null;
                    localContext.TracingService.Trace("Did NOT find msnfp_replacesreceiptid.");
                }
                if (queriedEntityRecord.Contains("msnfp_amount") && queriedEntityRecord["msnfp_amount"] != null)
                {
                    mSNFP_Receipt.Amount = ((Money)queriedEntityRecord["msnfp_amount"]).Value;
                    localContext.TracingService.Trace("Got msnfp_amount.");
                }
                else
                {
                    mSNFP_Receipt.Amount = null;
                    localContext.TracingService.Trace("Did NOT find msnfp_amount.");
                }
                if (queriedEntityRecord.Contains("transactioncurrencyid") && queriedEntityRecord["transactioncurrencyid"] != null)
                {
                    mSNFP_Receipt.TransactionCurrencyId = ((EntityReference)queriedEntityRecord["transactioncurrencyid"]).Id;
                    localContext.TracingService.Trace("Got TransactionCurrencyId.");
                }
                else
                {
                    mSNFP_Receipt.TransactionCurrencyId = null;
                    localContext.TracingService.Trace("Did NOT find TransactionCurrencyId.");
                }
                if (queriedEntityRecord.Contains("msnfp_printed") && queriedEntityRecord["msnfp_printed"] != null)
                {
                    mSNFP_Receipt.Printed = (DateTime)queriedEntityRecord["msnfp_printed"];
                    localContext.TracingService.Trace("Got Printed.");
                }
                else
                {
                    mSNFP_Receipt.Printed = null;
                    localContext.TracingService.Trace("Did NOT find Printed.");
                }
                if (queriedEntityRecord.Contains("msnfp_deliverycode") && queriedEntityRecord["msnfp_deliverycode"] != null)
                {
                    mSNFP_Receipt.DeliveryCode = ((OptionSetValue)queriedEntityRecord["msnfp_deliverycode"]).Value;
                    localContext.TracingService.Trace("Got Delivery.");
                }
                else
                {
                    mSNFP_Receipt.DeliveryCode = null;
                    localContext.TracingService.Trace("Did NOT find Delivery.");
                }
                if (queriedEntityRecord.Contains("msnfp_emaildeliverystatuscode") && queriedEntityRecord["msnfp_emaildeliverystatuscode"] != null)
                {
                    mSNFP_Receipt.EmailDeliveryStatusCode = ((OptionSetValue)queriedEntityRecord["msnfp_emaildeliverystatuscode"]).Value;
                    localContext.TracingService.Trace("Got EmailDeliveryStatus.");
                }
                else
                {
                    mSNFP_Receipt.EmailDeliveryStatusCode = null;
                    localContext.TracingService.Trace("Did NOT find EmailDeliveryStatus.");
                }
                if (queriedEntityRecord.Contains("statecode") && queriedEntityRecord["statecode"] != null)
                {
                    mSNFP_Receipt.StateCode = ((OptionSetValue)queriedEntityRecord["statecode"]).Value;
                    localContext.TracingService.Trace("Got statecode.");
                }
                else
                {
                    mSNFP_Receipt.StateCode = null;
                    localContext.TracingService.Trace("Did NOT find statecode.");
                }
                if (queriedEntityRecord.Contains("statuscode") && queriedEntityRecord["statuscode"] != null)
                {
                    mSNFP_Receipt.StatusCode = ((OptionSetValue)queriedEntityRecord["statuscode"]).Value;
                    localContext.TracingService.Trace("Got statuscode.");
                }
                else
                {
                    mSNFP_Receipt.StatusCode = null;
                    localContext.TracingService.Trace("Did NOT find statuscode.");
                }
                if (messageName == "Create")
                {
                    mSNFP_Receipt.CreatedOn = DateTime.UtcNow;
                }
                else if (queriedEntityRecord.Contains("createdon") && queriedEntityRecord["createdon"] != null)
                {
                    mSNFP_Receipt.CreatedOn = (DateTime)queriedEntityRecord["createdon"];
                }
                else
                {
                    mSNFP_Receipt.CreatedOn = null;
                }
                mSNFP_Receipt.SyncDate = DateTime.UtcNow;
                if (messageName == "Delete")
                {
                    mSNFP_Receipt.Deleted     = true;
                    mSNFP_Receipt.DeletedDate = DateTime.UtcNow;
                }
                else
                {
                    mSNFP_Receipt.Deleted     = false;
                    mSNFP_Receipt.DeletedDate = null;
                }
                mSNFP_Receipt.PaymentSchedule        = null;
                mSNFP_Receipt.ReceiptStack           = null;
                mSNFP_Receipt.ReplacesReceipt        = null;
                mSNFP_Receipt.InverseReplacesReceipt = new HashSet <MSNFP_Receipt>();
                localContext.TracingService.Trace("JSON object created");
                if (messageName == "Create")
                {
                    text2 = text2 + text + "/Create" + text;
                }
                else if (messageName == "Update" || messageName == "Delete")
                {
                    text2 = text2 + text + "/Update" + text;
                }
                MemoryStream memoryStream = new MemoryStream();
                DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(MSNFP_Receipt));
                dataContractJsonSerializer.WriteObject(memoryStream, mSNFP_Receipt);
                byte[] array = memoryStream.ToArray();
                memoryStream.Close();
                string       @string      = Encoding.UTF8.GetString(array, 0, array.Length);
                WebAPIClient webAPIClient = new WebAPIClient();
                webAPIClient.Headers[HttpRequestHeader.ContentType] = "application/json";
                webAPIClient.Headers["Padlock"] = (string)configurationRecord["msnfp_apipadlocktoken"];
                webAPIClient.Encoding           = Encoding.UTF8;
                localContext.TracingService.Trace("---------Preparing JSON---------");
                localContext.TracingService.Trace("Converted to json API URL : " + text2);
                localContext.TracingService.Trace("JSON: " + @string);
                localContext.TracingService.Trace("---------End of Preparing JSON---------");
                localContext.TracingService.Trace("Sending data to Azure.");
                string str = webAPIClient.UploadString(text2, @string);
                localContext.TracingService.Trace("Got response.");
                localContext.TracingService.Trace("Response: " + str);
            }
            else
            {
                localContext.TracingService.Trace("No API URL or Enable Portal Pages. Exiting workflow.");
            }
        }
Example #2
0
        /// <summary>
        /// Replace all string place holders in Template data
        /// </summary>
        /// <param name="relatedEntity">related Entity object</param>
        /// <param name="primaryEntity">primary entity object</param>
        /// <param name="parameters">list of parameter attribute</param>
        /// <param name="recordBaseUrl">record base URL</param>
        /// <param name="dataToReplace">actual template data which need to be replaced</param>
        /// <returns>return replaced data</returns>
        internal static string ReplacePlaceHolders(Entity relatedEntity, Entity primaryEntity, Dictionary <string, dynamic> parameters, string recordBaseUrl, string dataToReplace)
        {
            // no data found to replace
            if (dataToReplace == null)
            {
                return(null);
            }

            // Regex Match format. specified format is {entityLogicalName!AttributeName}
            string          regexPattern     = "{[\\w*!.]+}";
            MatchCollection matchCollections = Regex.Matches(dataToReplace, regexPattern);
            string          entityName       = string.Empty;
            string          attributeName    = string.Empty;

            // dictionary object to store all match
            Dictionary <string, string> matchValueCollection = new Dictionary <string, string>();

            foreach (Match match in matchCollections)
            {
                // split match with entity logical name and attribute
                var splitter = match.Value.TrimStart('{').TrimEnd('}').Split('!');
                if (splitter.Length > 1)
                {
                    entityName    = splitter[0];
                    attributeName = splitter[1];

                    if (relatedEntity != null && relatedEntity.LogicalName == entityName && relatedEntity.Contains(attributeName))
                    {
                        // match with related entity
                        matchValueCollection.Add(match.Value, GetAttributeValue(attributeName, relatedEntity));
                    }
                    else if (primaryEntity != null && primaryEntity.LogicalName == entityName && primaryEntity.Contains(attributeName))
                    {
                        // match with primary entity
                        matchValueCollection.Add(match.Value, GetAttributeValue(attributeName, primaryEntity));
                    }
                    else if (parameters != null && entityName == "parameter" && parameters.ContainsKey(match.Value.TrimStart('{').TrimEnd('}')))
                    {
                        matchValueCollection.Add(match.Value, (string)parameters[match.Value.TrimStart('{').TrimEnd('}')]);
                    }
                    else if (relatedEntity != null && relatedEntity.LogicalName == entityName && attributeName.ToUpper(CultureInfo.InvariantCulture) == "URL")
                    {
                        // URL match for related entity
                        matchValueCollection.Add(match.Value, ReplaceURL(relatedEntity, recordBaseUrl));
                    }
                    else if (primaryEntity != null && primaryEntity.LogicalName == entityName && attributeName.ToUpper(CultureInfo.InvariantCulture) == "URL")
                    {
                        // URL match for primary entity
                        matchValueCollection.Add(match.Value, ReplaceURL(primaryEntity, recordBaseUrl));
                    }
                    else
                    {
                        // no match
                        matchValueCollection.Add(match.Value, string.Empty);
                    }
                }
                else
                {
                    throw new InvalidPluginExecutionException("Specified token is not in correct format. Please contact Administrator.");
                }
            }

            return(ReplaceTokens(dataToReplace, matchValueCollection, regexPattern));
        }
Example #3
0
        public void Execute(IServiceProvider serviceProvider)
        {
            SqlDataAccess sda = null;

            try
            {
                sda = new SqlDataAccess();
                sda.openConnection(Globals.ConnectionString);

                #region | SERVICE |
                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

                #region | Validate Request |
                //Target yoksa veya Entity tipinde değilse, devam etme.
                if (!context.InputParameters.Contains("Target") || !(context.InputParameters["Target"] is Entity))
                {
                    return;
                }
                #endregion

                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                #endregion

                Entity entity = (Entity)context.InputParameters["Target"];

                #region | VARIABLES |
                List <ScoreLimit> lstLimits = new List <ScoreLimit>();

                EntityReference portal = null;
                EntityReference user   = null;

                if (entity.Contains("new_portalid") && entity["new_portalid"] != null)
                {
                    portal = (EntityReference)entity["new_portalid"];
                }

                if (entity.Contains("new_userid") && entity["new_userid"] != null)
                {
                    user = (EntityReference)entity["new_userid"];
                }
                #endregion

                MsCrmResultObject limitRes = ScoreHelper.GetScoreLimitsByType(ScoreType.Survey, sda);

                if (limitRes.Success)
                {
                    lstLimits = (List <ScoreLimit>)limitRes.ReturnObject;

                    for (int i = 0; i < lstLimits.Count; i++)
                    {
                        int      recCount = 0;
                        DateTime start    = GeneralHelper.GetStartDateByScorePeriod(lstLimits[i].Period);
                        DateTime end      = GeneralHelper.GetEndDateByScorePeriod(lstLimits[i].Period);

                        recCount = SurveyHelper.GetUserSurveyAnswerCount(portal.Id, user.Id, start, end, sda);

                        if (lstLimits[i].Frequency >= recCount)
                        {
                            Score sc = new Score()
                            {
                                Point     = lstLimits[i].Point,
                                Portal    = portal,
                                User      = user,
                                ScoreType = ScoreType.Survey
                            };

                            MsCrmResult scoreRes = ScoreHelper.CreateScore(sc, service);

                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //LOG
                throw new InvalidPluginExecutionException(ex.Message);
            }
            finally
            {
                if (sda != null)
                {
                    sda.closeConnection();
                }
            }
        }
Example #4
0
        public string ExecuteContractCover(Guid bankCreditId, string Path)
        {
            string  parsel                  = string.Empty;
            string  ada                     = string.Empty;
            string  pafta                   = string.Empty;
            string  discrict                = string.Empty;
            string  deliveryDate            = string.Empty;
            string  bankName                = string.Empty;
            string  SalesAccountName        = string.Empty;
            string  SalesAccountAddress     = string.Empty;
            string  SalesAccountEmail       = string.Empty;
            string  SalesAccountMersisno    = string.Empty;
            string  SalesAccountTel         = string.Empty;
            string  secondCustomerFirstName = string.Empty;
            string  secondCustomerLastName  = string.Empty;
            string  secondCustomerTc        = string.Empty;
            string  secondCustomerNumber    = string.Empty;
            string  projectName             = string.Empty;
            string  blok                    = string.Empty;
            string  floor                   = string.Empty;
            string  apartmentNo             = string.Empty;
            string  apartmentCity           = string.Empty;
            decimal m2                  = 0;
            decimal grossm2             = 0;
            string  currencySymbol      = string.Empty;
            string  city                = string.Empty;
            string  county              = string.Empty;
            string  adaPaftaParsel      = string.Empty;
            string  unitType            = string.Empty;
            string  apartmentType       = string.Empty;
            string  location            = string.Empty;
            string  freeSectionIdNumber = string.Empty;
            string  address             = string.Empty;
            string  passportNumber      = string.Empty;
            string  foreignAddress      = string.Empty;
            string  Nationality         = string.Empty;
            string  CustomerNumber      = string.Empty;
            string  bbnetalan           = string.Empty;
            string  bbbrutalan          = string.Empty;
            string  satisesasalan       = string.Empty;
            string  bahce               = string.Empty;
            string  teras               = string.Empty;
            string  balkon              = string.Empty;
            string  satisesasalanm2     = string.Empty;
            string  bbgenelbrutalan     = string.Empty;
            Guid    projectId           = Guid.Empty;
            Guid    QuoteId             = Guid.Empty;
            Guid    bankId              = Guid.Empty;
            Entity  contact             = null;
            Entity  account             = null;
            Entity  SalesAccount        = null;

            service = MSCRM.AdminOrgService;
            Entity bankCreditRecord = service.Retrieve("new_bankcreditstatus", bankCreditId, new ColumnSet(true));

            if (bankCreditRecord != null)
            {
                QuoteId = bankCreditRecord.GetAttributeValue <EntityReference>("new_quoteid").Id;
                bankId  = bankCreditRecord.GetAttributeValue <EntityReference>("new_bankid").Id;
            }
            else
            {
                return(string.Empty);
            }

            Entity bank = service.Retrieve("new_bank", bankId, new ColumnSet(true));

            if (bank == null)
            {
                return(string.Empty);
            }
            Entity quote = service.Retrieve("quote", QuoteId, new ColumnSet(true));

            if (quote == null)
            {
                return(string.Empty);
            }

            bankName       = bank.GetAttributeValue <string>("new_name");
            bankNameGlobal = bankName;

            Entity currencyDetail = this.GetCurrencyDetail(((EntityReference)quote["transactioncurrencyid"]).Id, new string[1] {
                "currencysymbol"
            });

            if (currencyDetail != null && currencyDetail.Attributes.Contains("currencysymbol"))
            {
                currencySymbol = currencyDetail["currencysymbol"].ToString();
            }

            if (((EntityReference)quote.Attributes["customerid"]).LogicalName.ToLower() == "contact")
            {
                if (quote.Contains("new_secondcontactid"))
                {
                    Entity secondContact = service.Retrieve("contact", ((EntityReference)quote.Attributes["new_secondcontactid"]).Id, new ColumnSet(true));
                    secondCustomerFirstName = secondContact.Contains("firstname") ? (string)secondContact.Attributes["firstname"] : string.Empty;
                    secondCustomerLastName  = secondContact.Contains("lastname") ? (string)secondContact.Attributes["lastname"] : string.Empty;
                    secondCustomerTc        = secondContact.Contains("new_tcidentitynumber") ? (string)secondContact.Attributes["new_tcidentitynumber"] : string.Empty;
                    if (secondContact.Contains("new_passportnumber"))
                    {
                        secondCustomerTc = secondCustomerTc + " / " + (string)secondContact.Attributes["new_passportnumber"];
                    }
                    secondCustomerNumber = secondContact.Contains("new_number") ? (string)secondContact.Attributes["new_number"] : string.Empty;
                }

                contact = service.Retrieve("contact", ((EntityReference)quote.Attributes["customerid"]).Id, new ColumnSet(true));
                city    = contact.Contains("new_addresscityid") ? ((EntityReference)contact.Attributes["new_addresscityid"]).Name + "/" : string.Empty + "/";
                city   += contact.Contains("new_addresstownid") ? ((EntityReference)contact.Attributes["new_addresstownid"]).Name + "/" : string.Empty + "/";
                city   += contact.Contains("new_addressdistrictid") ? ((EntityReference)contact.Attributes["new_addressdistrictid"]).Name : string.Empty;

                address = contact.Contains("new_addressdetail") ? contact.Attributes["new_addressdetail"].ToString() : string.Empty;
                address = address + " " + city;

                passportNumber = contact.Contains("new_passportnumber") ? (string)contact.Attributes["new_passportnumber"] : string.Empty;
                if (contact.Contains("new_address3countryid"))
                {
                    foreignAddress  = contact.Contains("new_nontcidentityaddress") ? contact.Attributes["new_nontcidentityaddress"].ToString() : string.Empty;
                    foreignAddress += " " + ((EntityReference)contact.Attributes["new_address3cityid"]).Name + "/" + ((EntityReference)contact.Attributes["new_address3countryid"]).Name;
                }
                if (contact.Contains("new_nationalityid"))
                {
                    Nationality = ((EntityReference)contact.Attributes["new_nationalityid"]).Name;
                }
                CustomerNumber  = contact.Contains("new_number") ? contact.Attributes["new_number"].ToString() : string.Empty;
                CustomerNumber += secondCustomerNumber != string.Empty ? " - " + secondCustomerNumber : string.Empty;
            }
            else if (((EntityReference)quote.Attributes["customerid"]).LogicalName.ToLower() == "account")
            {
                account = service.Retrieve("account", ((EntityReference)quote.Attributes["customerid"]).Id, new ColumnSet(true));
                city    = account.Contains("new_addresscityid") ? ((EntityReference)account.Attributes["new_addresscityid"]).Name + "/" : string.Empty + "/";
                city   += account.Contains("new_addresstownid") ? ((EntityReference)account.Attributes["new_addresstownid"]).Name + "/" : string.Empty + "/";
                city   += account.Contains("new_addressdistrictid") ? ((EntityReference)account.Attributes["new_addressdistrictid"]).Name : string.Empty;
                address = account.Contains("new_addressdetail") ? account.Attributes["new_addressdetail"].ToString() : string.Empty;
                address = address + " " + city;
            }

            ConditionExpression con1 = new ConditionExpression();

            con1.AttributeName = "quoteid";
            con1.Operator      = ConditionOperator.Equal;
            con1.Values.Add(QuoteId);

            FilterExpression filter = new FilterExpression();

            filter.FilterOperator = LogicalOperator.And;
            filter.Conditions.Add(con1);

            QueryExpression Query = new QueryExpression("quotedetail");

            Query.ColumnSet = new ColumnSet("productid");
            Query.Criteria.FilterOperator = LogicalOperator.And;
            Query.Criteria.Filters.Add(filter);

            EntityCollection Result = service.RetrieveMultiple(Query);

            if (Result.Entities.Count > 0)
            {
                Entity product = service.Retrieve("product", ((EntityReference)Result.Entities[0].Attributes["productid"]).Id, new ColumnSet(true));
                projectId         = product.Contains("new_projectid") ? ((EntityReference)product.Attributes["new_projectid"]).Id : Guid.Empty;
                projectName       = product.Contains("new_projectid") ? ((EntityReference)product.Attributes["new_projectid"]).Name : string.Empty;
                projectNameGlobal = projectName;

                parsel              = product.Contains("new_parcelid") ? ((EntityReference)product.Attributes["new_parcelid"]).Name : string.Empty;
                ada                 = product.Contains("new_blockofbuildingid") ? ((EntityReference)product.Attributes["new_blockofbuildingid"]).Name : string.Empty;
                pafta               = product.Contains("new_threaderid") ? ((EntityReference)product.Attributes["new_threaderid"]).Name : string.Empty;
                discrict            = product.Contains("new_district") ? (string)product.Attributes["new_district"] : string.Empty;
                blok                = product.Contains("new_blockid") ? ((EntityReference)product.Attributes["new_blockid"]).Name : string.Empty;
                floor               = product.Contains("new_floornumber") ? product.Attributes["new_floornumber"].ToString() : string.Empty;
                apartmentNo         = product.Contains("new_homenumber") ? (string)product.Attributes["new_homenumber"] : string.Empty;
                m2                  = product.Contains("new_netm2") ? (decimal)product.Attributes["new_netm2"] : 0;
                grossm2             = product.Contains("new_grossm2") ? (decimal)product.Attributes["new_grossm2"] : 0;
                adaPaftaParsel      = product.Contains("new_blockofbuildingid") ? ((EntityReference)product.Attributes["new_blockofbuildingid"]).Name + "/" : string.Empty + "/";
                adaPaftaParsel     += product.Contains("new_threaderid") ? ((EntityReference)product.Attributes["new_threaderid"]).Name + "/" : string.Empty + "/";
                adaPaftaParsel     += product.Contains("new_parcelid") ? ((EntityReference)product.Attributes["new_parcelid"]).Name : string.Empty;
                apartmentCity       = product.Contains("new_city") ? (string)product.Attributes["new_city"] + "/" : string.Empty + "/";
                apartmentCity      += product.Contains("new_district") ? (string)product.Attributes["new_district"] + "/" : string.Empty + "/";
                apartmentCity      += product.Contains("new_quarter") ? (string)product.Attributes["new_quarter"] : string.Empty;
                unitType            = product.Contains("new_unittypeid") ? ((EntityReference)product.Attributes["new_unittypeid"]).Name : string.Empty;
                apartmentType       = product.Contains("new_generaltypeofhomeid") ? ((EntityReference)product.Attributes["new_generaltypeofhomeid"]).Name : string.Empty;
                location            = product.Contains("new_locationid") ? ((EntityReference)product.Attributes["new_locationid"]).Name : string.Empty;
                freeSectionIdNumber = product.Contains("new_freesectionidnumber") ? (string)product.Attributes["new_freesectionidnumber"] : string.Empty;
                bbnetalan           = product.Contains("new_bbnetarea") ? ((decimal)product.Attributes["new_bbnetarea"]).ToString("N2") : string.Empty;
                bbbrutalan          = product.Contains("new_netm2") ? ((decimal)product.Attributes["new_netm2"]).ToString("N2") : string.Empty;
                satisesasalan       = product.Contains("new_satisaesasalan") ? ((decimal)product.Attributes["new_satisaesasalan"]).ToString("N2") : string.Empty;
                bahce               = product.Contains("new_garden") ? ((decimal)product.Attributes["new_garden"]).ToString("N2") : " - ";
                teras               = product.Contains("new_terracegross") ? ((decimal)product.Attributes["new_terracegross"]).ToString("N2") : " - ";
                balkon              = product.Contains("new_balconym2") ? ((decimal)product.Attributes["new_balconym2"]).ToString("N2") : " - ";
                satisesasalanm2     = product.Contains("new_grossm2") ? ((decimal)product.Attributes["new_grossm2"]).ToString("N2") : " - ";
                bbgenelbrutalan     = product.Contains("new_bbgeneralgrossarea") ? ((decimal)product.Attributes["new_bbgeneralgrossarea"]).ToString("N2") : string.Empty;
                deliveryDate        = product.Contains("new_deliverydate") ? ((DateTime)product.Attributes["new_deliverydate"]).ToLocalTime().ToString("dd/MM/yyyy") : string.Empty;
            }
            Entity project = service.Retrieve("new_project", projectId, new ColumnSet(true));
            Dictionary <string, string> dictionary1 = new Dictionary <string, string>();

            dictionary1.Add("TeslimTarihi", string.Empty);
            dictionary1.Add("SatışBrüt", grossm2.ToString("N2"));

            decimal sumOfPrePaymentAndVoucher = 0;

            if (contact != null)
            {
                if (!string.IsNullOrEmpty(contact.Attributes["fullname"].ToString()))
                {
                    dictionary1.Add("İlgiliKişi", contact.Attributes["fullname"].ToString());
                }
                else
                {
                    dictionary1.Add("İlgiliKişi", string.Empty);
                }
            }
            else if (account != null)
            {
                if (!string.IsNullOrEmpty(account.Attributes["name"].ToString()))
                {
                    dictionary1.Add("İlgiliKişi", account.Attributes["name"].ToString());
                }
                else
                {
                    dictionary1.Add("İlgiliKişi", string.Empty);
                }
            }

            if (bankCreditRecord.Contains("new_bankofficeid"))
            {
                dictionary1.Add("BankaŞubesi", bankCreditRecord.GetAttributeValue <EntityReference>("new_bankofficeid").Name);
            }
            else
            {
                dictionary1.Add("BankaŞubesi", string.Empty);
            }

            if (bankCreditRecord.Contains("new_appcreditamount"))
            {
                dictionary1.Add("BaşvurulanKrediTutarı", ((Money)bankCreditRecord.Attributes["new_appcreditamount"]).Value.ToString("N2"));
            }
            else
            {
                dictionary1.Add("BaşvurulanKrediTutarı", string.Empty);
            }

            if (!string.IsNullOrEmpty(bankName))
            {
                dictionary1.Add("Banka", bankName);
            }
            else
            {
                dictionary1.Add("Banka", string.Empty);
            }


            if (quote.Contains("new_prepaymentamount"))
            {
                dictionary1.Add("ÖnÖdemeTutarı", ((Money)quote.Attributes["new_prepaymentamount"]).Value.ToString("N2"));

                Entity kusuratEtiketi = this.GetKusuratEtiketi(((EntityReference)quote["transactioncurrencyid"]).Id, new string[1] {
                    "new_name"
                });
                string yaziylaTutar = YaziyaCevir(((Money)quote.Attributes["new_prepaymentamount"]).Value,
                                                  currencyDetail["currencysymbol"].ToString(), kusuratEtiketi["new_name"].ToString());
                dictionary1.Add("YazıylaÖnÖdemeTutarı", yaziylaTutar);
                sumOfPrePaymentAndVoucher += ((Money)quote.Attributes["new_prepaymentamount"]).Value;
            }

            if (quote.Contains("new_totalvoucheramount"))
            {
                dictionary1.Add("PeşinÖdemeTutarı", ((Money)quote.Attributes["new_totalvoucheramount"]).Value.ToString("N2") + " " + currencySymbol);
                sumOfPrePaymentAndVoucher += ((Money)quote.Attributes["new_totalvoucheramount"]).Value;
            }

            if (!string.IsNullOrEmpty(sumOfPrePaymentAndVoucher.ToString("N2")))
            {
                Entity kusuratEtiketi = this.GetKusuratEtiketi(((EntityReference)quote["transactioncurrencyid"]).Id, new string[1] {
                    "new_name"
                });
                string yaziylaTutar = YaziyaCevir(sumOfPrePaymentAndVoucher, currencyDetail["currencysymbol"].ToString(), kusuratEtiketi["new_name"].ToString());
                dictionary1.Add("ÖnÖdemeTutarıPeşinÖdemeTutarı", sumOfPrePaymentAndVoucher.ToString("N2"));
                dictionary1.Add("YazıylaÖnÖdemeTutarıPeşinÖdemeTutarı", yaziylaTutar);
            }
            else
            {
                dictionary1.Add("ÖnÖdemeTutarıPeşinÖdemeTutarı", string.Empty);
            }

            if (!string.IsNullOrEmpty(projectName))
            {
                dictionary1.Add("Proje", projectName);
            }
            else
            {
                dictionary1.Add("Proje", string.Empty);
            }

            if (!string.IsNullOrEmpty(pafta))
            {
                dictionary1.Add("Pafta", pafta);
            }
            else
            {
                dictionary1.Add("Pafta", string.Empty);
            }

            if (!string.IsNullOrEmpty(ada))
            {
                dictionary1.Add("Ada", ada);
            }
            else
            {
                dictionary1.Add("Ada", string.Empty);
            }

            if (!string.IsNullOrEmpty(parsel))
            {
                dictionary1.Add("Parsel", parsel);
            }
            else
            {
                dictionary1.Add("Parsel", string.Empty);
            }

            if (!string.IsNullOrEmpty(apartmentNo))
            {
                dictionary1.Add("DaireNo", apartmentNo);
            }
            else
            {
                dictionary1.Add("DaireNo", string.Empty);
            }

            if (!string.IsNullOrEmpty(blok))
            {
                dictionary1.Add("Blok", blok);
            }
            else
            {
                dictionary1.Add("Blok", string.Empty);
            }

            if (quote.Contains("new_contractdate"))
            {
                dictionary1.Add("SözleşmeTarihi", ((DateTime)quote.Attributes["new_contractdate"]).ToLocalTime().ToString("dd/MM/yyyy"));
            }
            else
            {
                dictionary1.Add("SözleşmeTarihi", string.Empty);
            }



            if (bankCreditRecord.Contains("new_approvedcreditamount"))
            {
                dictionary1.Add("OnaylananKrediTutarı", ((Money)bankCreditRecord.Attributes["new_approvedcreditamount"]).Value.ToString("N2"));
            }
            else
            {
                dictionary1.Add("OnaylananKrediTutarı", string.Empty);
            }

            if (!string.IsNullOrEmpty(address))
            {
                dictionary1.Add("AdresDetayı", address);
            }
            else
            {
                dictionary1.Add("AdresDetayı", string.Empty);
            }

            if (!string.IsNullOrEmpty(discrict))
            {
                dictionary1.Add("İlçe", discrict);
            }
            else
            {
                dictionary1.Add("İlçe", string.Empty);
            }

            if (!string.IsNullOrEmpty(floor))
            {
                dictionary1.Add("Kat", floor);
            }
            else
            {
                dictionary1.Add("Kat", string.Empty);
            }

            if (!string.IsNullOrEmpty(apartmentCity))
            {
                dictionary1.Add("İl", apartmentCity);
            }
            else
            {
                dictionary1.Add("İl", string.Empty);
            }

            decimal totalAmountlessFreight = 0;
            decimal creditAmount           = 0;

            if (quote.Contains("totalamountlessfreight"))
            {
                totalAmountlessFreight = ((Money)quote.Attributes["totalamountlessfreight"]).Value;
                dictionary1.Add("İndirimliKonutFiyatı", totalAmountlessFreight.ToString("N2") + " " + currencySymbol);
            }
            else
            {
                dictionary1.Add("İndirimliKonutFiyatı", string.Empty);
            }

            if (quote.Contains("new_creditamount"))
            {
                creditAmount = ((Money)quote.Attributes["new_creditamount"]).Value;

                dictionary1.Add("KrediTutarınınYarısı", (creditAmount / 2).ToString("N2"));


                decimal diff           = totalAmountlessFreight - creditAmount;
                Entity  kusuratEtiketi = this.GetKusuratEtiketi(((EntityReference)quote["transactioncurrencyid"]).Id, new string[1] {
                    "new_name"
                });
                string yaziylaTutar = YaziyaCevir(diff,
                                                  currencyDetail["currencysymbol"].ToString(), kusuratEtiketi["new_name"].ToString());

                dictionary1.Add("PeşinÖdemelerToplamı", diff.ToString("N2"));
                dictionary1.Add("PeşinÖdemelerToplamıYarısı", (diff / 2).ToString());
                dictionary1.Add("YazıylaPeşinÖdemelerToplamı", yaziylaTutar);
            }
            else
            {
                dictionary1.Add("YazıylaPeşinÖdemelerToplamı", string.Empty);
            }

            dictionary1.Add("today", DateTime.Now.ToShortDateString());
            dictionary1.Add("day", DateTime.Now.Day.ToString());
            dictionary1.Add("month", DateTime.Now.Month.ToString());
            dictionary1.Add("year", DateTime.Now.Year.ToString());
            dictionary1.Add("ParaBirimi", currencySymbol);
            dictionary1.Add("Köy", "..............");
            dictionary1.Add("Sokak", "..............");
            dictionary1.Add("Cadde", "..............");
            dictionary1.Add("Mahalle", "..............");
            dictionary1.Add("Mevki", "..............");
            DataSet dataSetSorted = null;

            if (projectName.Equals("853 NEF 03 Kağıthane") ||
                projectName.Equals("857 NEF 12 Merter") ||
                projectName.Equals("855 NEF 13 Merter"))
            {
                // akbank işbank garanti
                if (bankName.Equals("Akbank T.A.Ş."))
                {
                    string folder = BankCreditHelper.CreateFolder(bankCreditId, Path);
                    byte[] bytes  = DocumentMerge.WordDokumanOlustur(Path + "DocumentMerge\\BankTemplates\\NEF_03_12_13\\AKBANK\\AKBANK.docx", dataSetSorted, dictionary1);
                    string path1  = Path + "DocumentMerge\\Document\\" + folder + "\\AKBANK.docx";
                    if (path1 != string.Empty)
                    {
                        System.IO.File.WriteAllBytes(path1, bytes);
                    }
                    return(path1);
                }
                else if (bankName.Equals("Türkiye İş Bankası A.Ş."))
                {
                    string folder = BankCreditHelper.CreateFolder(bankCreditId, Path);
                    byte[] bytes  = DocumentMerge.WordDokumanOlustur(Path + "DocumentMerge\\BankTemplates\\NEF_03_12_13\\ISBANK\\ISBANK.docx", dataSetSorted, dictionary1);
                    string path1  = Path + "DocumentMerge\\Document\\" + folder + "\\ISBANK.docx";
                    if (path1 != string.Empty)
                    {
                        System.IO.File.WriteAllBytes(path1, bytes);
                    }
                    return(path1);
                }
                else if (bankName.Equals("Türkiye Garanti Bankası A.Ş."))
                {
                    string folder = BankCreditHelper.CreateFolder(bankCreditId, Path);
                    byte[] bytes  = DocumentMerge.WordDokumanOlustur(Path + "DocumentMerge\\BankTemplates\\NEF_03_12_13\\GARANTI\\GARANTI.docx", dataSetSorted, dictionary1);
                    string path1  = Path + "DocumentMerge\\Document\\" + folder + "\\GARANTI.docx";
                    if (path1 != string.Empty)
                    {
                        System.IO.File.WriteAllBytes(path1, bytes);
                    }
                    return(path1);
                }
            }
            else if (projectName.Equals("827 Inistanbul Topkapı"))
            {
                if (bankName.Equals("Türkiye İş Bankası A.Ş."))
                {
                    string folder = BankCreditHelper.CreateFolder(bankCreditId, Path);
                    byte[] bytes  = DocumentMerge.WordDokumanOlustur(Path + "DocumentMerge\\BankTemplates\\TOPKAPI\\ISBANK\\ISBANK.docx", dataSetSorted, dictionary1);
                    string path1  = Path + "DocumentMerge\\Document\\" + folder + "\\ISBANK.docx";
                    if (path1 != string.Empty)
                    {
                        System.IO.File.WriteAllBytes(path1, bytes);
                    }
                    return(path1);
                }
                else if (bankName.Equals("Yapı ve Kredi Bankası A.Ş."))
                {
                    string folder = BankCreditHelper.CreateFolder(bankCreditId, Path);
                    byte[] bytes  = DocumentMerge.WordDokumanOlustur(Path + "DocumentMerge\\BankTemplates\\TOPKAPI\\YAPIKREDI\\YAPIKREDI.docx", dataSetSorted, dictionary1);
                    string path1  = Path + "DocumentMerge\\Document\\" + folder + "\\YAPIKREDI.docx";
                    if (path1 != string.Empty)
                    {
                        System.IO.File.WriteAllBytes(path1, bytes);
                    }
                    return(path1);
                }
                else if (bankName.Equals("Türkiye Garanti Bankası A.Ş."))
                {
                    string folder = BankCreditHelper.CreateFolder(bankCreditId, Path);
                    byte[] bytes  = DocumentMerge.WordDokumanOlustur(Path + "DocumentMerge\\BankTemplates\\TOPKAPI\\GARANTI\\GARANTI.docx", dataSetSorted, dictionary1);
                    string path1  = Path + "DocumentMerge\\Document\\" + folder + "\\GARANTI.docx";
                    if (path1 != string.Empty)
                    {
                        System.IO.File.WriteAllBytes(path1, bytes);
                    }
                    return(path1);
                }
                else if (bankName.Equals("Türkiye Vakıflar Bankası T.A.O."))
                {
                    string folder = BankCreditHelper.CreateFolder(bankCreditId, Path);
                    byte[] bytes  = DocumentMerge.WordDokumanOlustur(Path + "DocumentMerge\\BankTemplates\\TOPKAPI\\VAKIFBANK\\VAKIFBANK.docx", dataSetSorted, dictionary1);
                    string path1  = Path + "DocumentMerge\\Document\\" + folder + "\\VAKIFBANK.docx";
                    if (path1 != string.Empty)
                    {
                        System.IO.File.WriteAllBytes(path1, bytes);
                    }
                    return(path1);
                }
            }
            else if (projectName.Equals("847 NEF 08 Kağıthane") ||
                     projectName.Equals("837 NEF 06 Points") ||
                     projectName.Equals("843 NEF 04 Points") ||
                     projectName.Equals("841 NEF 25 Şişli") ||
                     projectName.Equals("831 NEF 14 Kağıthane"))
            {
                if (bankName.Equals("Denizbank A.Ş."))
                {
                    string folder = BankCreditHelper.CreateFolder(bankCreditId, Path);
                    byte[] bytes  = DocumentMerge.WordDokumanOlustur(Path + "DocumentMerge\\BankTemplates\\NEF_08_06_04_25_14\\DENIZBANK\\DENIZBANK.docx", dataSetSorted, dictionary1);
                    string path1  = Path + "DocumentMerge\\Document\\" + folder + "\\DENIZBANK.docx";
                    if (path1 != string.Empty)
                    {
                        System.IO.File.WriteAllBytes(path1, bytes);
                    }
                    return(path1);
                }
            }
            else if (projectName.Equals("833 NEF 22 Ataköy"))
            {
                if (bankName.Equals("Türkiye İş Bankası A.Ş."))
                {
                    string folder = BankCreditHelper.CreateFolder(bankCreditId, Path);
                    byte[] bytes  = DocumentMerge.WordDokumanOlustur(Path + "DocumentMerge\\BankTemplates\\NEF_22\\ISBANK\\ISBANK.docx", dataSetSorted, dictionary1);
                    string path1  = Path + "DocumentMerge\\Document\\" + folder + "\\ISBANK.docx";
                    if (path1 != string.Empty)
                    {
                        System.IO.File.WriteAllBytes(path1, bytes);
                    }
                    return(path1);
                }
                else if (bankName.Equals("Odea Bank A.Ş."))
                {
                    string folder = BankCreditHelper.CreateFolder(bankCreditId, Path);
                    byte[] bytes  = DocumentMerge.WordDokumanOlustur(Path + "DocumentMerge\\BankTemplates\\NEF_22\\ODEABANK\\ODEABANK.docx", dataSetSorted, dictionary1);
                    string path1  = Path + "DocumentMerge\\Document\\" + folder + "\\ODEABANK.docx";
                    if (path1 != string.Empty)
                    {
                        System.IO.File.WriteAllBytes(path1, bytes);
                    }
                    return(path1);
                }
            }
            else
            {
                return(string.Empty);
            }
            return(string.Empty);
        }
        private List <MeteringPoint> GetMeteringPointsFromEntityCollection(OrganizationServiceContext serviceContext, IQueryable <Entity> zahplunkts)
        {
            List <MeteringPoint> meteringPoints = new List <MeteringPoint>();

            foreach (Entity zahplunkt in zahplunkts)
            {
                MeteringPoint meteringPoint = new MeteringPoint();

                if (zahplunkt.Contains(MetadataDZählpunkt.METERING_POINT_ID))
                {
                    meteringPoint.Id = zahplunkt.GetAttributeValue <Guid>(MetadataDZählpunkt.METERING_POINT_ID);
                }
                if (zahplunkt.Contains(MetadataDZählpunkt.NAME))
                {
                    meteringPoint.Name = zahplunkt.GetAttributeValue <string>(MetadataDZählpunkt.NAME);
                }
                if (zahplunkt.Contains(MetadataDZählpunkt.ACCOUNT))
                {
                    EntityReference linkedAccount = zahplunkt.GetAttributeValue <EntityReference>(MetadataDZählpunkt.ACCOUNT);
                    meteringPoint.CrmAccountId   = linkedAccount.Id;
                    meteringPoint.CrmAccountName = linkedAccount.Name;

                    //GetBeitreibersByAccountId(linkedAccount.Id);
                }
                if (zahplunkt.Contains(MetadataDZählpunkt.ZAHLPUNKTBEZEICHNER))
                {
                    meteringPoint.Zählpunktbezeichner = zahplunkt.GetAttributeValue <string>(MetadataDZählpunkt.ZAHLPUNKTBEZEICHNER);
                }
                if (zahplunkt.Contains(MetadataDZählpunkt.KURZEEZEICHNUNG))
                {
                    meteringPoint.Kurzbezeichnung = zahplunkt.GetAttributeValue <string>(MetadataDZählpunkt.KURZEEZEICHNUNG);
                }
                if (zahplunkt.Contains(MetadataDZählpunkt.ANLAGENTYP))
                {
                    meteringPoint.Anlagentyp = zahplunkt.GetAttributeValue <string>(MetadataDZählpunkt.ANLAGENTYP);
                }
                if (zahplunkt.Contains(MetadataDZählpunkt.PLZ))
                {
                    meteringPoint.PLZ = zahplunkt.GetAttributeValue <string>(MetadataDZählpunkt.PLZ);
                }
                if (zahplunkt.Contains(MetadataDZählpunkt.STRASSE))
                {
                    meteringPoint.Strasse = zahplunkt.GetAttributeValue <string>(MetadataDZählpunkt.STRASSE);
                }
                if (zahplunkt.Contains(MetadataDZählpunkt.ORT))
                {
                    meteringPoint.Ort = zahplunkt.GetAttributeValue <string>(MetadataDZählpunkt.ORT);
                }
                if (zahplunkt.Contains(MetadataDZählpunkt.DATENVERSANDAKTIV))
                {
                    meteringPoint.DatenversandAktiv = zahplunkt.GetAttributeValue <bool>(MetadataDZählpunkt.DATENVERSANDAKTIV) ? "Yes" : "No";
                }
                if (zahplunkt.Contains(MetadataDZählpunkt.ZAHLVERFAHREN))
                {
                    string value = String.Empty;
                    int    code  = -1;
                    switch (zahplunkt.GetAttributeValue <OptionSetValue>(MetadataDZählpunkt.ZAHLVERFAHREN).Value)
                    {
                    case (int)MetadataDZählpunkt.OpSetZählverfahren.RLM:
                        code  = (int)MetadataDZählpunkt.OpSetZählverfahren.RLM;
                        value = MetadataDZählpunkt.OpSetZählverfahren.RLM.ToString();
                        break;

                    case (int)MetadataDZählpunkt.OpSetZählverfahren.SLP:
                        code  = (int)MetadataDZählpunkt.OpSetZählverfahren.SLP;
                        value = MetadataDZählpunkt.OpSetZählverfahren.SLP.ToString();
                        break;
                    }
                    meteringPoint.ZählverfahrenCode  = code;
                    meteringPoint.ZählverfahrenValue = value;
                }
                if (zahplunkt.Contains(MetadataDZählpunkt.UMESSUNG))
                {
                    int code; string value;
                    this.SetSetSpannungsebene(zahplunkt.GetAttributeValue <OptionSetValue>(MetadataDZählpunkt.UMESSUNG).Value,
                                              out code, out value);

                    meteringPoint.UMessungCode  = code;
                    meteringPoint.UMessungValue = value;
                }
                if (zahplunkt.Contains(MetadataDZählpunkt.UENTNAHME))
                {
                    int code; string value;
                    this.SetSetSpannungsebene(zahplunkt.GetAttributeValue <OptionSetValue>(MetadataDZählpunkt.UENTNAHME).Value,
                                              out code, out value);

                    meteringPoint.UEntnahmeCode  = code;
                    meteringPoint.UEntnahmeValue = value;
                }
                if (zahplunkt.Contains(MetadataDZählpunkt.KUNDENRUCKMELDUNG))
                {
                    meteringPoint.Kundenrückmeldung = zahplunkt.GetAttributeValue <string>(MetadataDZählpunkt.KUNDENRUCKMELDUNG);
                }
                if (zahplunkt.Contains(MetadataDZählpunkt.VNB))
                {
                    EntityReference linkedVnb = zahplunkt.GetAttributeValue <EntityReference>(MetadataDZählpunkt.VNB);
                    meteringPoint.VNBId   = linkedVnb.Id;
                    meteringPoint.VNBName = linkedVnb.Name;
                }
                if (zahplunkt.Contains(MetadataDZählpunkt.CODE))
                {
                    meteringPoint.Code = zahplunkt.GetAttributeValue <string>(MetadataDZählpunkt.CODE);
                }

                #region "Threshold Values"
                //Get the threshold for this metering point
                IQueryable <Entity>           grenzwerts = serviceContext.CreateQuery(EntityNames.Grenzwert).Where(g => g.GetAttributeValue <EntityReference>(MetadataGrenzwert.GrenzwerteZPID).Id == zahplunkt.Id);
                List <MeteringPointThreshold> meteringPointThresholds = new List <MeteringPointThreshold>();
                meteringPoint.MeteringCodeThresholds = new List <MeteringPointThreshold>();
                if (grenzwerts != null)
                {
                    Entity grenzwert = grenzwerts.ToList().FirstOrDefault();
                    if (grenzwert != null)
                    {
                        #region "System Threshold Values"
                        MeteringPointThreshold meteringPointThreshlodSystem = new MeteringPointThreshold {
                            Type = MeteringPointThresholdType.System
                        };

                        if (grenzwert.Contains(MetadataGrenzwert.Grenze))
                        {
                            meteringPointThreshlodSystem.GrenzwertBezeichner = String.Format("{0:F2}", grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.Grenze));
                        }
                        if (grenzwert.Contains(MetadataGrenzwert.GrenzwerteId))
                        {
                            meteringPointThreshlodSystem.Id = grenzwert.GetAttributeValue <Guid>(MetadataGrenzwert.GrenzwerteId);
                        }
                        if (grenzwert.Contains(MetadataGrenzwert.GültigAb))
                        {
                            meteringPointThreshlodSystem.GultingAb = grenzwert.GetAttributeValue <DateTime>(MetadataGrenzwert.GültigAb);
                        }
                        if (grenzwert.Contains(MetadataGrenzwert.GrenzwertMaxSystem))
                        {
                            meteringPointThreshlodSystem.MaximaGlobal = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertMaxSystem)).ToString();
                        }
                        if (grenzwert.Contains(MetadataGrenzwert.GrenzwertMinSystem))
                        {
                            meteringPointThreshlodSystem.MinimaGlobal = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertMinSystem)).ToString();
                        }
                        if (grenzwert.Contains(MetadataGrenzwert.GrenzwertSommerMaxSystem))
                        {
                            meteringPointThreshlodSystem.MaximaSommer = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertSommerMaxSystem)).ToString();
                        }
                        if (grenzwert.Contains(MetadataGrenzwert.GrenzwertSommerMinSystem))
                        {
                            meteringPointThreshlodSystem.MinimaSommer = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertSommerMinSystem)).ToString();
                        }
                        if (grenzwert.Contains(MetadataGrenzwert.GrenzwertWinterMaxSystem))
                        {
                            meteringPointThreshlodSystem.MaximaWinter = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertWinterMaxSystem)).ToString();
                        }
                        if (grenzwert.Contains(MetadataGrenzwert.GrenzwertWinterMinSystem))
                        {
                            meteringPointThreshlodSystem.MinimaWinter = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertWinterMinSystem)).ToString();
                        }
                        meteringPointThresholds.Add(meteringPointThreshlodSystem);
                        #endregion "System Threshold Values"

                        #region "User Threshold Values"
                        MeteringPointThreshold meteringPointThreshlodUser = new MeteringPointThreshold {
                            Type = MeteringPointThresholdType.User
                        };
                        if (grenzwert.Contains(MetadataGrenzwert.GrenzwerteId))
                        {
                            meteringPointThreshlodUser.Id = grenzwert.GetAttributeValue <Guid>(MetadataGrenzwert.GrenzwerteId);
                        }
                        if (grenzwert.Contains(MetadataGrenzwert.Grenze))
                        {
                            meteringPointThreshlodUser.GrenzwertBezeichner = String.Format("{0:F2}", grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.Grenze));
                        }
                        if (grenzwert.Contains(MetadataGrenzwert.GültigAb))
                        {
                            meteringPointThreshlodUser.GultingAb = grenzwert.GetAttributeValue <DateTime>(MetadataGrenzwert.GültigAb);
                        }
                        if (grenzwert.Contains(MetadataGrenzwert.GrenzwertMaxUser))
                        {
                            meteringPointThreshlodUser.MaximaGlobal = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertMaxUser)).ToString();
                        }
                        if (grenzwert.Contains(MetadataGrenzwert.GrenzwertMinUser))
                        {
                            meteringPointThreshlodUser.MinimaGlobal = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertMinUser)).ToString();
                        }
                        if (grenzwert.Contains(MetadataGrenzwert.GrenzwertSommerMaxUser))
                        {
                            meteringPointThreshlodUser.MaximaSommer = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertSommerMaxUser)).ToString();
                        }
                        if (grenzwert.Contains(MetadataGrenzwert.GrenzwertSommerMinUser))
                        {
                            meteringPointThreshlodUser.MinimaSommer = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertSommerMinUser)).ToString();
                        }
                        if (grenzwert.Contains(MetadataGrenzwert.GrenzwertWinterMaxUser))
                        {
                            meteringPointThreshlodUser.MaximaWinter = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertWinterMaxUser)).ToString();
                        }
                        if (grenzwert.Contains(MetadataGrenzwert.GrenzwertWinterMinUser))
                        {
                            meteringPointThreshlodUser.MinimaWinter = (grenzwert.GetAttributeValue <decimal>(MetadataGrenzwert.GrenzwertWinterMinUser)).ToString();
                        }
                        meteringPointThresholds.Add(meteringPointThreshlodUser);
                        #endregion "User Threshold Values"

                        meteringPoint.MeteringCodeThresholds = meteringPointThresholds;
                    }
                    #endregion "Threshold Values"
                }
                meteringPoints.Add(meteringPoint);
            }

            return(meteringPoints);
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            try
            {
                //Extract the tracing service
                var tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
                if (tracingService == null)
                {
                    throw new InvalidPluginExecutionException("Failed to retrieve the tracing service.");
                }

                // Obtain the execution context from the service provider.
                var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

                // Only process Create and Update messages
                if (context.MessageName != "Create" && context.MessageName != "Update")
                {
                    return;
                }
                tracingService.Trace("SoundsLikePlugin: Create or Update");


                // Only process if there is a target entity
                Entity pre = null;
                if (context.PreEntityImages.ContainsKey("pre"))
                {
                    pre = context.PreEntityImages["pre"];
                }

                if (!context.InputParameters.Contains("Target") ||
                    (!(context.InputParameters["Target"] is Entity)))
                {
                    tracingService.Trace("SoundsLikePlugin: No Target");
                    return;
                }
                else
                {
                    tracingService.Trace("SoundsLikePlugin: Target Found");
                }

                Entity entity = (Entity)context.InputParameters["Target"];



                // Codify for each setting
                foreach (var setting in Configuration.Settings)
                {
                    // Continue if the Target does not contain the field to encode, no need to re-encode
                    // something that wasn't changed
                    if (entity.Contains(setting.Target))
                    {
                        // If DisableUpdate is specified, then don't allow someone to manually
                        // update the coded text
                        if (setting.DisableUpdate && entity.Contains(setting.Target))
                        {
                            entity.Attributes.Remove(setting.Target);
                        }
                    }

                    // Get the text to encode
                    tracingService.Trace("SoundsLikePlugin: Getting Text for Sources");
                    string text = String.Format("{0}{1}{2}",
                                                GetString(tracingService, entity, pre, setting.Source),
                                                GetString(tracingService, entity, pre, setting.Source2, " "),
                                                GetString(tracingService, entity, pre, setting.Source3, " "));
                    tracingService.Trace("SoundsLikePlugin: Source Text: {0}", text);

                    // Codify the string using the method specified
                    string codifiedText;

                    tracingService.Trace("SoundsLikePlugin: Codifying Text: {0}", text);
                    switch (setting.Method)
                    {
                    case CodificationMethod.Soundex:
                        codifiedText = Soundex.Codify(text, setting.MinLength, setting.MaxLength, false);
                        break;

                    case CodificationMethod.SoundexOriginal:
                        codifiedText = Soundex.Codify(text, setting.MinLength, setting.MaxLength, true);
                        break;

                    case CodificationMethod.Metaphone:
                        codifiedText = Metaphone.Codify(text, setting.MinLength, setting.MaxLength);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                    tracingService.Trace("SoundsLikePlugin: Codified To: {0}", codifiedText);

                    // Add or update the codified attribute);
                    if (entity.Attributes.ContainsKey(setting.Target))
                    {
                        tracingService.Trace("SoundsLikePlugin: Setting Target Field: {0}", setting.Target);
                        entity.Attributes[setting.Target] = codifiedText;
                    }
                    else
                    {
                        tracingService.Trace("SoundsLikePlugin: Adding Target Field: {0}", setting.Target);
                        entity.Attributes.Add(setting.Target, codifiedText);
                    }

                    //throw new Exception("doh");
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException("SoundsLikePlugin Failed", ex);
            }
        }
 /// <summary>
 /// Checks if the state of an entity is already properly set and removes it if it is, otherwise it is set.
 /// </summary>
 /// <param name="dictionary">The <c>Dictionary</c> that contains the state to be set on the entity.</param>
 /// <param name="entity">The CRM <c>Entity</c> to set the state on.</param>
 /// <param name="propertyName">The state code property name.</param>
 /// <param name="adapter">The <see cref="DynamicCrmAdapter"/> to be used for state name to value conversions.</param>
 private static void CheckStateAndStatus(Dictionary<string, object> dictionary, Entity entity, string propertyName, DynamicCrmAdapter adapter)
 {
     int stateToSet = (int)dictionary[propertyName];
     if (!entity.Contains(propertyName) || CRM2011AdapterUtilities.ConvertStateNameToValue(entity[propertyName].ToString(), entity.LogicalName, adapter) != stateToSet)
     {
         entity[propertyName] = new OptionSetValue(stateToSet);
     }
     else
     {
         entity.Attributes.Remove(propertyName);
         if (entity.Contains("statuscode"))
         {
             entity.Attributes.Remove("statuscode");
         }
     }
 }
        /// <summary>
        /// Validates that a product is not new when retrieving from the product catalog
        /// </summary>
        /// <param name="product">The <c>Entity</c> that contains the <c>product</c> that was retrieved</param>
        /// <param name="productKey">The value of the product's dynamics_integrationkey</param>
        public static void ValidateInventoriedProduct(Entity product, string productKey)
        {
            if (product == null)
            {
                throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.ArgumentNullExceptionMessage), new ArgumentNullException("product")) { ExceptionId = AdapterException.SystemExceptionGuid };
            }

            if (product.Contains(CRM2011AdapterUtilities.IsNew) && (bool)product[CRM2011AdapterUtilities.IsNew] == true)
            {
                throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.NonIntegratedProductSuppliedExceptionMessage, productKey)) { ExceptionId = ErrorCodes.ProductNotFound };
            }
        }
        /// <summary>
        /// Determines if the supplied CRM <c>Entity</c> is address 1 or 2.
        /// </summary>
        /// <param name="childEntity">The CRM <c>customeraddress</c> to be checked.</param>
        /// <returns>True if the <c>customeraddress</c> that was supplied is address 1 or 2.</returns>
        internal static bool IsAddressOneOrTwo(Entity childEntity)
        {
            if (childEntity.Contains("addressnumber"))
            {
                int addressNumber = (int)childEntity["addressnumber"];
                return addressNumber == 1 || addressNumber == 2;
            }

            return false;
        }
        /// <summary>
        /// Assigns an object to be the value for a property on a <c>Entity</c>.
        /// </summary>
        /// <param name="reference">The <c>object</c> be assigned as the value</param>
        /// <param name="entity">The <c>Entity</c> to be assigned to</param>
        /// <param name="propertyToBeAssignedValue">The name of the property on the <c>Entity</c> to assign the supplied object to</param>
        /// <remarks>If the <c>object</c> is null, nothing is assigned to the property</remarks>
        protected static void AssignReferencePropertyValue(EntityReference reference, Entity entity, string propertyToBeAssignedValue)
        {
            if (entity == null)
            {
                throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.ArgumentNullExceptionMessage), new ArgumentNullException("entity")) { ExceptionId = AdapterException.SystemExceptionGuid };
            }

            // These checks are only for updates
            if (entity.Contains(CRM2011AdapterUtilities.IsNew) && !(bool)entity[CRM2011AdapterUtilities.IsNew])
            {
                if (entity.Contains(propertyToBeAssignedValue))
                {
                    if (reference == null)
                    {
                        // Since the reference entity supplied is null, remove the property from the retrieved entity to avoid a potential update storm
                        entity.Attributes.Remove(propertyToBeAssignedValue);
                    }
                    else if (((EntityReference)entity[propertyToBeAssignedValue]).Id == reference.Id)
                    {
                        // Since this property has the same value we are trying to assign it, remove it to avoid a potential update storm
                        entity.Attributes.Remove(propertyToBeAssignedValue);
                    }
                    else
                    {
                        entity[propertyToBeAssignedValue] = reference;
                    }

                    return;
                }
            }

            // This is a new instance or the existing instance did not contain this property when it was retrieved
            if (reference != null)
            {
                entity[propertyToBeAssignedValue] = reference;
            }
        }
        /// <summary>
        /// Used to actually create instances of the child entities in an inherited class.
        /// </summary>
        /// <param name="parentKey">The <c>Key</c> of the parent entity.</param>
        /// <param name="childEntity">The child entity to be created in the form of a <c>Entity</c>.</param>
        /// <param name="collectionFieldName">The name of the field in the <c>ObjectProvider</c>'s configuration file that is being mapped currently.</param>
        protected virtual void CreateUpdateChildInstanceForField(Guid parentKey, Entity childEntity, string collectionFieldName)
        {
            if (parentKey == null || childEntity == null)
            {
                throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.ArgumentNullExceptionMessage)) { ExceptionId = AdapterException.SystemExceptionGuid };
            }

            if (!childEntity.Contains(childEntity.LogicalName + "id"))
            {
                // Set a default value of parnet entity name + id
                string parentAttribName = this.ProvidedEntityName + "id";

                // Select the child entity's type def
                TypeDefinition childType = this.ObjectDefinition.Types.SingleOrDefault(td => td.Name == childEntity.LogicalName);
                if (childType != null)
                {
                    // Query to limit the number of fields on the child type we iterate over when looking for the parent field
                    var childFields = from childField in childType.Children
                                      where childField.AdditionalAttributes != null
                                      select childField;
                    foreach (FieldDefinition fieldDef in childFields)
                    {
                        XmlAttribute attrib = fieldDef.AdditionalAttributes.FirstOrDefault(at => at.Name == CRM2011AdapterUtilities.IsParentField);
                        if (attrib != null && attrib.Value.ToUpperInvariant() == true.ToString().ToUpperInvariant())
                        {
                            // Set the parent field's name and break out of the foreach loop
                            parentAttribName = fieldDef.Name;
                            break;
                        }
                    }
                }

                childEntity[parentAttribName] = new EntityReference(this.ProvidedEntityName, parentKey);
                this.CreateNewEntity(childEntity);
            }
            else
            {
                this.UpdateEntity(childEntity);
            }
        }
        /// <summary>
        /// Removes properties and sets state for an entity
        /// </summary>
        /// <param name="entity">A <c>Entity</c> to prep for an update operation.</param>
        private void PrepEntityForUpdate(Entity entity)
        {
            entity.Attributes.Remove(CRM2011AdapterUtilities.IsNew);
            this.SetState(entity);
            if (entity.Contains("owninguser") && entity["owninguser"].GetType().Equals(typeof(EntityReference)))
            {
                this.SetOwner(entity);
            }

            RemoveStateCode(entity);
            RemoveStatusCode(entity);
        }
        /// <summary>
        /// Removes the status code from a <c>Entity</c>
        /// </summary>
        /// <param name="entity">The <c>Entity</c> to remove the status code from</param>
        /// <returns>The value of the status code that was removed</returns>
        private static OptionSetValue RemoveStatusCode(Entity entity)
        {
            OptionSetValue status = null;
            if (entity.Contains("statuscode") && entity["statuscode"] != null)
            {
                status = (OptionSetValue)entity["statuscode"];
                entity.Attributes.Remove("statuscode");
            }

            return status;
        }
 /// <summary>
 /// Removes properties from the <c>Entity</c> that are not needed.
 /// </summary>
 /// <param name="entity">The <c>Entity</c> that is being created / updated.</param>
 /// <param name="dictionary">The <c>Dictionary</c> that contains the data to placed into the supplied <c>DynmicEntity</c></param>
 private static void RemoveProperties(Entity entity, Dictionary<string, object> dictionary)
 {
     // Only loop if this is an update
     if (entity.Contains(CRM2011AdapterUtilities.IsNew) && !(bool)entity[CRM2011AdapterUtilities.IsNew])
     {
         var updateProperties = from property in entity.Attributes where dictionary.Keys.Contains(property.Key) || property.Key == CRM2011AdapterUtilities.IsNew || property.Key == entity.LogicalName + "id" || property.Key == "addressnumber" || CRM2011AdapterUtilities.GetSpecialAddressPicklistFields().Contains(property.Key) select property;
         entity.Attributes = new AttributeCollection();
         updateProperties.ToList().ForEach(prop => entity.Attributes.Add(prop));
     }
 }
        protected override void Execute(CodeActivityContext executionContext)
        {
            EntityReference Template        = DocumentTemplateId.Get(executionContext);
            Boolean         Logging         = EnableLogging.Get(executionContext);
            string          LicenseFilePath = LicenseFile.Get(executionContext);
            string          LogFilePath     = LogFile.Get(executionContext);

            OutputAttachmentId.Set(executionContext, new EntityReference("annotation", Guid.Empty));
            try
            {
                if (Logging)
                {
                    Log("Workflow Executed", LogFilePath);
                }
                IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
                string PrimaryEntityName = context.PrimaryEntityName;
                Guid   PrimaryEntityId   = context.PrimaryEntityId;
                try
                {
                    if (Logging)
                    {
                        Log("Enable Licensing", LogFilePath);
                    }
                    if (LicenseFilePath != "" && File.Exists(LicenseFilePath))
                    {
                        License Lic = new License();
                        Lic.SetLicense(LicenseFilePath);
                        if (Logging)
                        {
                            Log("License Set", LogFilePath);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log("Error while applying license: " + ex.Message, LogFilePath);
                }
                QueryExpression RetrieveNoteQuery = new QueryExpression("annotation");
                RetrieveNoteQuery.ColumnSet = new ColumnSet(new string[] { "subject", "documentbody" });
                RetrieveNoteQuery.Criteria.AddCondition(new ConditionExpression("objectid", ConditionOperator.Equal, Template.Id));
                if (Logging)
                {
                    Log("Executing Query to retrieve Template Attachment", LogFilePath);
                }
                EntityCollection Notes = service.RetrieveMultiple(RetrieveNoteQuery);
                if (Logging)
                {
                    Log("Attachment Retrieved Successfully", LogFilePath);
                }
                if (Notes.Entities.Count > 0)
                {
                    Entity Note     = Notes[0];
                    string FileName = "";
                    if (Note.Contains("subject"))
                    {
                        FileName = Note["subject"].ToString();
                    }
                    if (Note.Contains("documentbody"))
                    {
                        if (Logging)
                        {
                            Log("Attachment Read Successfully", LogFilePath);
                        }
                        byte[]       DocumentBody = Convert.FromBase64String(Note["documentbody"].ToString());
                        MemoryStream fileStream   = new MemoryStream(DocumentBody);
                        if (Logging)
                        {
                            Log("Reading Document in Aspose.Words", LogFilePath);
                        }
                        Document doc = new Document(fileStream);
                        if (Logging)
                        {
                            Log("Getting Fields list", LogFilePath);
                        }

                        string[] fields = doc.MailMerge.GetFieldNames();
                        if (Logging)
                        {
                            Log("Getting list of fields for entity", LogFilePath);
                        }
                        Entity PrimaryEntity = service.Retrieve(PrimaryEntityName, PrimaryEntityId, new ColumnSet(fields));
                        if (Logging)
                        {
                            Log("Retrieved Contact entity", LogFilePath);
                        }
                        if (PrimaryEntity != null)
                        {
                            string[] values = new string[fields.Length];
                            for (int i = 0; i < fields.Length; i++)
                            {
                                if (PrimaryEntity.Contains(fields[i]))
                                {
                                    if (PrimaryEntity[fields[i]].GetType() == typeof(OptionSetValue))
                                    {
                                        values[i] = PrimaryEntity.FormattedValues[fields[i]].ToString();
                                    }
                                    else if (PrimaryEntity[fields[i]].GetType() == typeof(EntityReference))
                                    {
                                        values[i] = ((EntityReference)PrimaryEntity[fields[i]]).Name;
                                    }
                                    else
                                    {
                                        values[i] = PrimaryEntity[fields[i]].ToString();
                                    }
                                }
                                else
                                {
                                    values[i] = "";
                                }
                            }
                            if (Logging)
                            {
                                Log("Executing Mail Merge", LogFilePath);
                            }
                            doc.MailMerge.Execute(fields, values);
                            MemoryStream UpdateDoc = new MemoryStream();
                            if (Logging)
                            {
                                Log("Saving Document", LogFilePath);
                            }
                            doc.Save(UpdateDoc, SaveFormat.Docx);
                            byte[] byteData = UpdateDoc.ToArray();
                            // Encode the data using base64.
                            string encodedData = System.Convert.ToBase64String(byteData);

                            if (Logging)
                            {
                                Log("Creating Attachment", LogFilePath);
                            }
                            Entity NewNote = new Entity("annotation");
                            // Im going to add Note to entity
                            NewNote.Attributes.Add("objectid", new EntityReference(PrimaryEntityName, PrimaryEntityId));
                            NewNote.Attributes.Add("subject", FileName);

                            // Set EncodedData to Document Body
                            NewNote.Attributes.Add("documentbody", encodedData);

                            // Set the type of attachment
                            NewNote.Attributes.Add("mimetype", @"application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                            NewNote.Attributes.Add("notetext", "Document Created using template");

                            // Set the File Name
                            NewNote.Attributes.Add("filename", FileName);
                            Guid NewNoteId = service.Create(NewNote);
                            OutputAttachmentId.Set(executionContext, new EntityReference("annotation", NewNoteId));
                            if (Logging)
                            {
                                Log("Successfull", LogFilePath);
                            }
                        }
                    }
                }

                if (Logging)
                {
                    Log("Workflow Executed Successfully", LogFilePath);
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message, LogFilePath);
            }
        }
 /// <summary>
 /// Determines if an option set is one of the customer address 1 or 2 option sets.
 /// </summary>
 /// <param name="entity">The CRM <c>Entity</c> currently being integrated.</param>
 /// <param name="field">The <see cref="FieldDefinition"/> for the CRM attribute currently being integrated.</param>
 /// <returns>True if the field is one of the customer address 1 or 2 fields, false otherwise.</returns>
 internal static bool IsSpecialAddressPicklist(Entity entity, FieldDefinition field)
 {
     return entity.LogicalName == "customeraddress" && GetSpecialAddressPicklistFields().Contains(field.Name) && entity.Contains("addressnumber") && IsAddressOneOrTwo(entity);
 }
        //Created By : Jerome Anthony Gerero, Created On : 7/11/2017

        /*Purpose: Validate import records
         * Registration Details:
         * Event/Message:
         *      Pre-Operation/Create: gsc_sls_adjustmentvariancedetailid
         * Primary Entity: Vehicle Adjustment/Variance Entry Detail
         */
        public Entity ValidateImportRecord(Entity vehicleAdjustmentVarianceEntryDetailEntity)
        {
            _tracingService.Trace("Started ValidateImportRecord Method...");

            //Return if record does not come from file import
            if (vehicleAdjustmentVarianceEntryDetailEntity.GetAttributeValue <EntityReference>("gsc_productid") != null)
            {
                return(null);
            }

            String modelCode = vehicleAdjustmentVarianceEntryDetailEntity.Contains("gsc_modelcode")
                ? vehicleAdjustmentVarianceEntryDetailEntity.GetAttributeValue <String>("gsc_modelcode")
                : String.Empty;
            String optionCode = vehicleAdjustmentVarianceEntryDetailEntity.Contains("gsc_optioncode")
                ? vehicleAdjustmentVarianceEntryDetailEntity.GetAttributeValue <String>("gsc_optioncode")
                : String.Empty;
            String colorCode = vehicleAdjustmentVarianceEntryDetailEntity.Contains("gsc_colorcode")
                ? vehicleAdjustmentVarianceEntryDetailEntity.GetAttributeValue <String>("gsc_colorcode")
                : String.Empty;

            //Create filter for product
            var productConditionList = new List <ConditionExpression>
            {
                new ConditionExpression("gsc_modelcode", ConditionOperator.Equal, modelCode),
                new ConditionExpression("gsc_optioncode", ConditionOperator.Equal, optionCode)
            };

            EntityCollection productRecords = CommonHandler.RetrieveRecordsByConditions("product", productConditionList, _organizationService, null, OrderType.Ascending,
                                                                                        new[] { "productid", "gsc_vehiclemodelid" });

            if (productRecords != null && productRecords.Entities.Count > 0)
            {
                Entity product = productRecords.Entities[0];
                vehicleAdjustmentVarianceEntryDetailEntity["gsc_productid"]          = new EntityReference(product.LogicalName, product.Id);
                vehicleAdjustmentVarianceEntryDetailEntity["gsc_vehiclebasemodelid"] = product.GetAttributeValue <EntityReference>("gsc_vehiclemodelid") != null
                    ? product.GetAttributeValue <EntityReference>("gsc_vehiclemodelid")
                    : null;

                //Create filter for vehicle color
                var vehicleColorConditionList = new List <ConditionExpression>
                {
                    new ConditionExpression("gsc_colorcode", ConditionOperator.Equal, colorCode),
                    new ConditionExpression("gsc_productid", ConditionOperator.Equal, product.Id)
                };

                EntityCollection vehicleColorRecords = CommonHandler.RetrieveRecordsByConditions("gsc_cmn_vehiclecolor", vehicleColorConditionList, _organizationService, null, OrderType.Ascending,
                                                                                                 new[] { "gsc_vehiclecolorpn" });

                if (vehicleColorRecords != null && vehicleColorRecords.Entities.Count > 0)
                {
                    Entity vehicleColor = vehicleColorRecords.Entities[0];
                    vehicleAdjustmentVarianceEntryDetailEntity["gsc_vehiclecolorid"] = new EntityReference(vehicleColor.LogicalName, vehicleColor.Id);
                }
                else
                {
                    throw new InvalidPluginExecutionException("Vehicle color does not exist.");
                }
            }
            else
            {
                throw new InvalidPluginExecutionException("Product does not exist.");
            }

            _tracingService.Trace("Ended ValidateImportRecord Method...");
            return(vehicleAdjustmentVarianceEntryDetailEntity);
        }
        protected string ExecuteSqlDatabaseIntegration(Guid pointId, string inputStart, Entity targetEntity)
        {
            try
            {
                Entity integrationPoint = service.Retrieve("new_integrationpoint", pointId, new ColumnSet(databaseAttrs));

                string entityfields      = integrationPoint.Contains("new_entityfields") ? integrationPoint["new_entityfields"].ToString() : null;
                string datasourcefields  = integrationPoint.Contains("new_datasourcefields") ? integrationPoint["new_datasourcefields"].ToString() : null;
                string connectionstring  = integrationPoint.Contains("new_connectionstring") ? integrationPoint["new_connectionstring"].ToString() : null;
                string entity_record_id  = integrationPoint.Contains("new_entity_record_id") ? integrationPoint["new_entity_record_id"].ToString() : null;
                string databasetablename = integrationPoint.Contains("new_databasetablename") ? integrationPoint["new_databasetablename"].ToString() : null;

                //get entityAttrNames
                List <string> entityAttrNames = (entityfields.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))[0].Split('.').ToList();
                entityAttrNames.RemoveAt(0);

                for (int i = 0; i < entityAttrNames.Count; i++)
                {
                    string noGapAttr = entityAttrNames[i].Replace(" ", "");
                    entityAttrNames[i] = noGapAttr.Substring(0, noGapAttr.IndexOf('('));
                }

                //add guid to entityAttrNames
                entityAttrNames.Add(entityLogicalName + "id");

                //get datasourceAttrNames
                List <string> datasourceAttrNames = (datasourcefields.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))[0].Split('.').ToList();
                datasourceAttrNames.RemoveAt(0);

                for (int i = 0; i < datasourceAttrNames.Count; i++)
                {
                    string s = datasourceAttrNames[i].TrimStart();
                    s = s.Replace("\n", " ");

                    if (s.Contains(' '))
                    {
                        string[] helpArray = s.Split(' ');
                        datasourceAttrNames[i] = helpArray[0];
                    }
                    else
                    {
                        datasourceAttrNames[i] = s;
                    }
                }

                //add guid to datasourceAttrNames
                datasourceAttrNames.Add(entity_record_id);

                //create input string
                string input = inputStart + ":"
                               + "connectionstring:" + connectionstring
                               + ":databasetablename:" + databasetablename + ":attributes:";

                for (int i = 0; i < entityAttrNames.Count; i++)
                {
                    if (targetEntity.Contains(entityAttrNames[i]))
                    {
                        if (targetEntity[entityAttrNames[i]] != null)
                        {
                            string attrType = targetEntity[entityAttrNames[i]].GetType().ToString();

                            if (attrType == "System.String")
                            {
                                input += datasourceAttrNames[i] + "&" + targetEntity[entityAttrNames[i]].ToString() + ";";
                            }
                            else if (attrType == "System.DateTime")
                            {
                                input += datasourceAttrNames[i] + "&" + ((DateTime)targetEntity[entityAttrNames[i]]).ToString("MM-dd-yyyy HH:mm:ss") + ";";
                            }
                            else if (attrType == "System.Int32")
                            {
                                input += datasourceAttrNames[i] + "&" + targetEntity[entityAttrNames[i]].ToString() + ";";
                            }
                            else if (attrType == "System.Boolean")
                            {
                                input += datasourceAttrNames[i] + "&" + targetEntity[entityAttrNames[i]].ToString() + ";";
                            }
                            else if (attrType == "Microsoft.Xrm.Sdk.OptionSetValue")
                            {
                                int optionSetValue = ((OptionSetValue)targetEntity[entityAttrNames[i]]).Value;

                                var attReq = new RetrieveAttributeRequest();
                                attReq.EntityLogicalName     = targetEntity.LogicalName;
                                attReq.LogicalName           = entityAttrNames[i];
                                attReq.RetrieveAsIfPublished = true;

                                var attResponse = (RetrieveAttributeResponse)service.Execute(attReq);
                                var attMetadata = (EnumAttributeMetadata)attResponse.AttributeMetadata;

                                string optionText = attMetadata.OptionSet.Options.Where(x => x.Value == optionSetValue).FirstOrDefault().Label.UserLocalizedLabel.Label;
                                input += datasourceAttrNames[i] + "&" + optionText + ";";
                            }
                            else if (attrType == "Microsoft.Xrm.Sdk.EntityReference")
                            {
                                input += datasourceAttrNames[i] + "&" + ((EntityReference)targetEntity[entityAttrNames[i]]).Id.ToString() + ";";
                            }
                            else if (attrType == "System.Guid")
                            {
                                input += datasourceAttrNames[i] + "&" + targetEntity[entityAttrNames[i]].ToString() + ";";
                            }
                        }
                        else
                        {
                            input += datasourceAttrNames[i] + "&;";
                        }
                    }
                }

                input = input.Substring(0, input.Length - 1);
                return(input);
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException("ExecuteSqlDatabaseIntegration: " + ex.Message, ex);
            }
        }
Example #19
0
 public override string ToString()
 {
     return(view.Contains("name") ? view["name"].ToString() : view.Contains("listname") ? view["listname"].ToString() : "?");
 }
            public IComparable Process(Entity entity)
            {
                var attr = entity.Contains(Attribute) ? entity[Attribute] : null;

                return(FindGroupValue(attr));
            }
Example #21
0
        public static XrmLeadResult CreateLead(Dictionary <string, string> properties, IDictionary <string, string> settings, IDictionary <string, string> actions, CrmConnection connection = null)
        {
            XrmLeadResult result    = new XrmLeadResult();
            bool          match     = Convert.ToBoolean(settings.GetValueOrDefault <string>("match", bool.FalseString));
            Entity        lead      = new Entity("lead", Guid.NewGuid());
            string        email     = properties.GetValueOrDefault <string>("emailaddress1", "");
            string        accountId = properties.GetValueOrDefault <string>("accountid", properties.GetValueOrDefault <string>("companyname", ""));
            Entity        contact   = null;
            Entity        account   = null;

            if (match && !string.IsNullOrEmpty(email))
            {
                if (!string.IsNullOrEmpty(accountId))
                {
                    Guid g;
                    if (Guid.TryParse(accountId, out g))
                    {
                        account = XrmCore.Retrieve("account", g);
                    }
                    else
                    {
                        account = XrmCore.RetrieveByAttribute("account", "name", accountId).Entities.OrderByDescending(x => x.GetAttributeValue <DateTime>("createdon")).FirstOrDefault();
                    }
                }

                contact = XrmCore.RetrieveByAttribute("contact", "emailaddress1", email).Entities.OrderByDescending(x => x.GetAttributeValue <DateTime>("createdon")).FirstOrDefault();
                if (contact != null)
                {
                    lead["parentcontactid"] = contact.ToEntityReference();
                    result.ContactId        = contact.Id.ToString();
                    if (accountId == null && contact.Contains("parentcustomerid"))
                    {
                        account = XrmCore.Retrieve("account", contact.GetAttributeValue <EntityReference>("parentcustomerid").Id);
                    }
                    //if (string.IsNullOrEmpty(accountId))
                    //{
                    //    accountId = contact.GetAttributeValue<string>("parentcustomerid_name");
                    //}
                }

                if (account != null)
                {
                    lead["parentaccountid"] = account.ToEntityReference();
                    result.AccountId        = account.Id.ToString();
                }
            }

            result.CompanyName = properties.GetValueOrDefault <string>("companyname", account != null && account.Contains("name") ? account.GetAttributeValue <string>("name") : "");
            result.Email       = email;
            result.FullName    = properties.GetValueOrDefault <string>("fullname", contact != null && contact.Contains("fullname") ? contact.GetAttributeValue <string>("fullname") : "");

            // Apply properties
            EntityMetadata meta = XrmCore.RetrieveMetadata("lead", EntityFilters.All, connection);

            foreach (KeyValuePair <string, string> kv in properties)
            {
                lead.SetAttributeMetaValue(kv, settings, meta);
            }

            Guid Id = XrmCore.CreateEntity(lead);

            result.LeadId = Id.ToString();

            // Apply actions
            foreach (KeyValuePair <string, string> kv in actions)
            {
                lead.ApplyAction(kv);
            }


            return(result);
        }
Example #22
0
        internal static CrmPlusPlusEntity ToCrmPlusPlusEntity(this Entity entity, Type crmPlusPlusEntityType, string alias = "")
        {
            var crmPlusPlusEntity = (CrmPlusPlusEntity)Activator.CreateInstance(crmPlusPlusEntityType);

            crmPlusPlusEntity.Id = entity.Id;

            if (!string.IsNullOrEmpty(alias) && !alias.EndsWith("."))
            {
                alias = alias + ".";
            }

            if (alias == string.Empty)
            {
                crmPlusPlusEntity.CreatedOn  = entity.Contains("createdon") ? DateTime.Parse(entity["createdon"].ToString()) : DateTime.MinValue;
                crmPlusPlusEntity.ModifiedOn = entity.Contains("modifiedon") ? DateTime.Parse(entity["modifiedon"].ToString()) : DateTime.MinValue;
            }
            else
            {
                crmPlusPlusEntity.Id = entity.Contains(alias + "id") ? (Guid)((AliasedValue)entity[alias + "id"]).Value : crmPlusPlusEntity.Id;

                crmPlusPlusEntity.CreatedOn  = entity.Contains(alias + "createdon") ? DateTime.Parse(((AliasedValue)entity[alias + "createdon"]).Value.ToString()) : DateTime.MinValue;
                crmPlusPlusEntity.ModifiedOn = entity.Contains(alias + "modifiedon") ? DateTime.Parse(((AliasedValue)entity[alias + "modifiedon"]).Value.ToString()) : DateTime.MinValue;
            }

            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(crmPlusPlusEntityType))
            {
                if (property.Name == "ModifedOn" || property.Name == "CreatedOn")
                {
                    continue;
                }

                var attributes = property.Attributes.AsEnumerable();

                var propertyNameAttr = attributes.SingleOrDefault(attr => attr.GetType() == typeof(PropertyNameAttribute));
                var propertyInfoAttr = attributes.SingleOrDefault(attr => attr.GetType() == typeof(PropertyInfoAttribute));
                var typeInfoAttr     = attributes
                                       .SingleOrDefault(attr => (attr.GetType() == typeof(BooleanAttribute) && property.PropertyType == typeof(bool)) ||
                                                        (attr.GetType() == typeof(DateTimeAttribute) && property.PropertyType == typeof(DateTime)) ||
                                                        (attr.GetType() == typeof(DecimalAttribute) && property.PropertyType == typeof(decimal)) ||
                                                        (attr.GetType() == typeof(DoubleAttribute) && property.PropertyType == typeof(double)) ||
                                                        (attr.GetType() == typeof(IntegerAttribute) && property.PropertyType == typeof(int)) ||
                                                        (attr.GetType() == typeof(StringAttribute) && property.PropertyType == typeof(string)) ||
                                                        (attr.GetType() == typeof(OptionSetAttribute) && property.PropertyType.IsEnum) ||
                                                        (attr.GetType() == typeof(LookupAttribute) && property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(EntityReference <>)));

                if (propertyNameAttr != null && propertyInfoAttr != null && typeInfoAttr != null)
                {
                    var propertyName = ((PropertyNameAttribute)propertyNameAttr).PropertyName;

                    if (entity.Contains(alias + propertyName))
                    {
                        object value = null;

                        if (alias == string.Empty)
                        {
                            value = entity[propertyName];
                        }
                        else
                        {
                            value = ((AliasedValue)entity[alias + propertyName]).Value;
                        }

                        if (value.GetType() == typeof(EntityReference))
                        {
                            var referenceEntityName = property.PropertyType.GetGenericArguments().Single();
                            var entityReferenceType = typeof(EntityReference <>).MakeGenericType(referenceEntityName);

                            value = Activator.CreateInstance(entityReferenceType, new object[] { ((Microsoft.Xrm.Sdk.EntityReference)value).Id });
                        }
                        else if (value.GetType() == typeof(OptionSetValue))
                        {
                            var integerOptionValue = ((OptionSetValue)value).Value;
                            value = integerOptionValue;
                        }

                        property.SetValue(crmPlusPlusEntity, value);
                    }
                }
            }

            return(crmPlusPlusEntity);
        }
        /// <summary>
        /// Executes the plug-in.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        /// </remarks>
        protected void ExecutePostVehicleSalesReturnUpdate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService    service = localContext.OrganizationService;
            ITracingService         trace   = localContext.TracingService;

            Entity preImageEntity  = (context.PreEntityImages != null && context.PreEntityImages.Contains(this.preImageAlias)) ? context.PreEntityImages[this.preImageAlias] : null;
            Entity postImageEntity = (context.PostEntityImages != null && context.PostEntityImages.Contains(this.postImageAlias)) ? context.PostEntityImages[this.postImageAlias] : null;

            if (!(context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity))
            {
                return;
            }

            if (postImageEntity.LogicalName != "gsc_sls_vehiclesalesreturn")
            {
                return;
            }

            string message = context.MessageName;

            try
            {
                VehicleSalesReturnHandler vehicleSalesReturnHandler = new VehicleSalesReturnHandler(service, trace);

                var preImageInvoiceId = preImageEntity.Contains("gsc_invoiceid")
                         ? preImageEntity.GetAttributeValue <EntityReference>("gsc_invoiceid").Id
                         : Guid.Empty;

                var postImageInvoiceId = postImageEntity.Contains("gsc_invoiceid")
                        ? postImageEntity.GetAttributeValue <EntityReference>("gsc_invoiceid").Id
                        : Guid.Empty;

                var preImagePostTransaction = preImageEntity.Contains("gsc_posttransaction")
                       ? preImageEntity.GetAttributeValue <bool>("gsc_posttransaction")
                       : false;

                var postImagePostTransaction = postImageEntity.Contains("gsc_posttransaction")
                        ? postImageEntity.GetAttributeValue <bool>("gsc_posttransaction")
                        : false;


                //execute when Invoice id was changed
                if (preImageInvoiceId != postImageInvoiceId)
                {
                    vehicleSalesReturnHandler.ReplicateInvoicedVehicle(postImageEntity, message);
                }


                //execute when PostTransaction was changed
                if (preImagePostTransaction != postImagePostTransaction && postImagePostTransaction != false)
                {
                    trace.Trace("Post Transaction COndition");
                    EntityCollection salesReturnDetailCollection = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_salesreturndetail", "gsc_vehiclesalesreturnid", postImageEntity.Id, service, null, OrderType.Ascending,
                                                                                                           new[] { "gsc_inventoryid", "gsc_branchsiteid" });
                    trace.Trace("Condition if not null");
                    if (salesReturnDetailCollection.Entities.Count > 1)
                    {
                        trace.Trace("More than 1 SalesReturnDetail record retrieved... " + salesReturnDetailCollection.Entities.Count);
                    }
                    trace.Trace("Sales ReturnDetail");
                    SalesReturnDetailHandler salesReturnDetailHandler = new SalesReturnDetailHandler(service, trace);

                    //Update Quantity Cout
                    trace.Trace("Update Quantity Cout");
                    if (salesReturnDetailCollection.Entities.Count > 0)
                    {
                        salesReturnDetailHandler.PostTransaction(salesReturnDetailCollection.Entities[0]);
                    }

                    //Update VSR Status
                    trace.Trace("Update VSR Status");
                    vehicleSalesReturnHandler.PostTransaction(postImageEntity);
                    trace.Trace("DeleteTransactedVehicle");
                    vehicleSalesReturnHandler.DeleteTransactedVehicle(postImageEntity);
                    trace.Trace("CreateReturnedInventoryHistory");
                    vehicleSalesReturnHandler.CreateReturnedInventoryHistory(postImageEntity);
                }
            }

            catch (Exception ex)
            {
                if (ex.Message.Contains("Sales invoice selected already returned."))
                {
                    throw new InvalidPluginExecutionException(ex.Message);
                }
                else
                {
                    throw new InvalidPluginExecutionException(String.Concat("(Exception)\n", ex.Message, Environment.NewLine, ex.StackTrace));
                }
            }
        }
Example #24
0
        protected override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            Entity crmPluginStep = _repository.Get("sdkmessageprocessingstep", Id);

            Mode       = Mode ?? (CrmPluginStepMode)crmPluginStep.GetAttributeValue <OptionSetValue>("mode").Value;
            Stage      = Stage ?? (CrmPluginStepStage)crmPluginStep.GetAttributeValue <OptionSetValue>("stage").Value;
            Deployment = Deployment ?? (CrmPluginStepDeployment)crmPluginStep.GetAttributeValue <OptionSetValue>("supporteddeployment").Value;

            if (Mode == CrmPluginStepMode.Asynchronous && Stage != CrmPluginStepStage.PostOperation)
            {
                throw new Exception("Asynchronous Execution Mode requires registration in one of the Post Stages. Please change the Mode or the Stage.");
            }
            if (!string.IsNullOrWhiteSpace(SecureConfig) && (Deployment == CrmPluginStepDeployment.OfflineOnly || Deployment == CrmPluginStepDeployment.Both))
            {
                throw new Exception("Secure Configuration is not supported for Steps deployed Offline.");
            }

            EntityReference crmMessageFilterReference = crmPluginStep.GetAttributeValue <EntityReference>("sdkmessagefilterid");
            Entity          crmMessageFilter          = _repository.Get(crmMessageFilterReference.LogicalName, crmMessageFilterReference.Id);

            int filterAvailability = crmMessageFilter.GetAttributeValue <int>("availability");

            if (!IsDeploymentSupported(filterAvailability, Deployment.Value))
            {
                throw new Exception(string.Format("The Step must be deployed '{0}'.", Enum.GetName(typeof(CrmPluginStepDeployment), filterAvailability)));
            }

            EntityReference crmEventHandlerReference = crmPluginStep.GetAttributeValue <EntityReference>("eventhandler");

            if (crmEventHandlerReference.LogicalName.Equals("serviceendpoint", StringComparison.InvariantCultureIgnoreCase) && Mode == CrmPluginStepMode.Synchronous)
            {
                throw new Exception("Only asynchronous Steps are supported for Service Endpoint plug-ins.");
            }

            if (!string.IsNullOrWhiteSpace(Name))
            {
                if (crmPluginStep.Contains("name"))
                {
                    crmPluginStep.Attributes["name"] = Name;
                }
                else
                {
                    crmPluginStep.Attributes.Add("name", Name);
                }
            }
            if (Description != null)
            {
                string description = string.IsNullOrWhiteSpace(Description) ? null : Description;
                if (crmPluginStep.Contains("description"))
                {
                    crmPluginStep.Attributes["description"] = description;
                }
                else
                {
                    crmPluginStep.Attributes.Add("description", description);
                }
            }
            if (UnsecureConfig != null)
            {
                string unsecureConfig = string.IsNullOrWhiteSpace(UnsecureConfig) ? null : UnsecureConfig;
                if (crmPluginStep.Contains("configuration"))
                {
                    crmPluginStep.Attributes["configuration"] = unsecureConfig;
                }
                else
                {
                    crmPluginStep.Attributes.Add("configuration", unsecureConfig);
                }
            }
            if (ExecutionOrder.HasValue)
            {
                if (crmPluginStep.Contains("rank"))
                {
                    crmPluginStep.Attributes["rank"] = ExecutionOrder.Value;
                }
                else
                {
                    crmPluginStep.Attributes.Add("rank", ExecutionOrder.Value);
                }
            }
            if (DeleteAsyncOperation.IsPresent)
            {
                if (crmPluginStep.Contains("asyncautodelete"))
                {
                    crmPluginStep.Attributes["asyncautodelete"] = DeleteAsyncOperation.ToBool();
                }
                else
                {
                    crmPluginStep.Attributes.Add("asyncautodelete", DeleteAsyncOperation.ToBool());
                }
            }
            if (User != null)
            {
                if (User.Value != Guid.Empty)
                {
                    if (crmPluginStep.Contains("impersonatinguserid"))
                    {
                        crmPluginStep.Attributes["impersonatinguserid"] = new EntityReference("systemuser", User.Value);
                    }
                    else
                    {
                        crmPluginStep.Attributes.Add("impersonatinguserid", new EntityReference("systemuser", User.Value));
                    }
                }
                else
                {
                    if (crmPluginStep.Contains("impersonatinguserid"))
                    {
                        crmPluginStep.Attributes["impersonatinguserid"] = null;
                    }
                    else
                    {
                        crmPluginStep.Attributes.Add("impersonatinguserid", null);
                    }
                }
            }
            if (Attributes != null)
            {
                EntityReference crmMessageReference = crmPluginStep.GetAttributeValue <EntityReference>("sdkmessageid");
                if (crmMessageReference.Name.Equals("update", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (Attributes.Length != 0)
                    {
                        string filteringAttributes = string.Join(",", Attributes);
                        if (crmPluginStep.Contains("filteringattributes"))
                        {
                            crmPluginStep.Attributes["filteringattributes"] = filteringAttributes;
                        }
                        else
                        {
                            crmPluginStep.Attributes.Add("filteringattributes", filteringAttributes);
                        }
                    }
                    else
                    {
                        if (crmPluginStep.Contains("filteringattributes"))
                        {
                            crmPluginStep.Attributes["filteringattributes"] = null;
                        }
                        else
                        {
                            crmPluginStep.Attributes.Add("filteringattributes", null);
                        }
                    }
                }
            }
            crmPluginStep.Attributes["mode"]  = new OptionSetValue((int)Mode);
            crmPluginStep.Attributes["stage"] = new OptionSetValue((int)Stage);
            crmPluginStep.Attributes["supporteddeployment"] = new OptionSetValue((int)Deployment);

            EntityReference crmSecureConfigReference = crmPluginStep.GetAttributeValue <EntityReference>("sdkmessageprocessingstepsecureconfigid");

            if (SecureConfig != null)
            {
                if (!string.IsNullOrWhiteSpace(SecureConfig))
                {
                    if (crmSecureConfigReference != null)
                    {
                        _repository.Update(crmSecureConfigReference.LogicalName, crmSecureConfigReference.Id, new System.Collections.Hashtable()
                        {
                            { "secureconfig", SecureConfig }
                        });
                    }
                    else
                    {
                        Guid secureConfigId = _repository.Add("sdkmessageprocessingstepsecureconfig", Guid.Empty, new System.Collections.Hashtable()
                        {
                            { "secureconfig", SecureConfig }
                        });
                        crmPluginStep.Attributes.Add("sdkmessageprocessingstepsecureconfigid", new EntityReference("sdkmessageprocessingstepsecureconfig", secureConfigId));
                    }
                }
                else
                {
                    if (crmSecureConfigReference != null)
                    {
                        crmPluginStep.Attributes["sdkmessageprocessingstepsecureconfigid"] = null;
                    }
                }
            }

            _repository.Update(crmPluginStep);
            if (SecureConfig != null && string.IsNullOrWhiteSpace(SecureConfig) && crmSecureConfigReference != null)
            {
                _repository.Delete(crmSecureConfigReference.LogicalName, crmSecureConfigReference.Id);
            }

            if (PassThru)
            {
                WriteObject(_repository.Get("sdkmessageprocessingstep", Id));
            }
        }
        private static string Replace(this Entity entity, IBag bag, string text, string scope, Dictionary <string, string> replacepatterns, bool supressinvalidattributepaths, string token)
        {
            bag.Logger.StartSection("Replace " + token);

            var attributepath = token;

            if (ComparePositions(token, ":", "<") < 0 &&    // Det finns kolon och det är inte en del av iif, expand etc (som börjar med < )
                ComparePositions(token, ":", "|") < 0)      // Det finns kolon och det är inte en del av formatsträng (som börjar med | )
            {
                // Separate namespace and attribute-path from token name
                attributepath = token.Substring(token.IndexOf(':') + 1);             // "businessunitid.createdon|yyyy-MM-dd"
            }
            // Extract format string
            string format = null;

            if (!attributepath.Contains("<expand|") && attributepath.Contains("|"))
            {
                format        = attributepath.Substring(attributepath.IndexOf('|') + 1);            // "yyyy-MM-dd"
                attributepath = attributepath.Substring(0, attributepath.IndexOf('|'));             // "businessunitid.createdon"
            }

            // Extract "next" attribute in the path
            var attribute = attributepath.Split('.')[0];

            var value = string.Empty;

            if (entity.Contains(attribute))                                                // Attribute exists
            {
                if ((entity.Attributes[attribute] is EntityReference ||                    // Attribute is a reference
                     entity.Attributes[attribute] is Guid) && attributepath.Contains(".")) // References from intersect tables are only guids
                {
                    // Traverse down through the reference list
                    var attributepos   = 2;
                    var finalattribute = attributepath;
                    var tmp            = GetSeparatedPart(attributepath, ".", attributepos);
                    while (!string.IsNullOrWhiteSpace(tmp))
                    {
                        finalattribute = tmp; // "createdon"
                        attributepos++;
                        tmp = GetSeparatedPart(attributepath, ".", attributepos);
                    }
                    Entity deRef = null;
                    try
                    {
                        if (format == "<value>" && attributepath.IndexOf('.') < 0)
                        {
                            deRef = entity;
                            bag.Logger.Log($"Get attribute off current entity (token = {token})");
                        }
                        else
                        {
                            var cols = new ColumnSet();
                            if (!finalattribute.StartsWith("<") && !finalattribute.StartsWith("&lt;"))
                            {
                                cols.AddColumn(finalattribute);
                            }

                            var strAttributeRelated = attributepath.Replace("." + finalattribute, "");
                            deRef = entity.GetRelated(bag, strAttributeRelated, cols);
                        }
                    }
                    catch (FaultException <OrganizationServiceFault> ex)
                    {
                        if (!supressinvalidattributepaths)
                        {
                            throw;
                        }
                        bag.Logger.Log($"Invalid path '{token}' is supressed: {ex.Message}");
                    }
                    if (deRef != null)
                    {
                        // Reference found, get the requested attribute from it
                        bag.Logger.Log($"Retrieved related {deRef.LogicalName}");
                        if (format == "<value>")
                        {
                            value = deRef.PropertyAsBaseType(finalattribute, "", true).ToString();// "2010-05-14T..."
                        }
                        else if (finalattribute.StartsWith("<expand|"))
                        {
                            value = deRef.Substitute(bag, finalattribute, 0, scope);
                        }
                        else
                        {
                            value = deRef.PropertyAsString(bag, finalattribute, "", true, format);     // "2010-05-14"
                        }
                    }
                }
                else
                {
                    // Get attribute text
                    value = entity.PropertyAsString(bag, attribute, "", true, format);
                }
            }
            if (replacepatterns != null && replacepatterns.Count > 0)
            {
                value = MultiReplace(value, replacepatterns);
            }

            if (!string.IsNullOrEmpty(value))
            {
                if (value.Contains(string.Concat("{", token, "}")))
                {   // Prevents recursion within this token, if its value contains the token
                    value = value.Replace(
                        string.Concat("{", token, "}"),
                        string.Concat("%STARTKRULL_%", token, "%SLUTKRULL_%"));
                }
            }

            // Only replace first (current) occurrence of ph, that is why we don't use string.Replace.
            token = string.Concat("{", token, "}");
            var phstart  = text.IndexOf(token, StringComparison.InvariantCulture);
            var phlength = token.Length;

            bag.Logger.Log($"Replacing {token} with {value}");
            text = text.Substring(0, phstart) + value + text.Substring(phstart + phlength);
            bag.Logger.Log($"Result: {text}");
            bag.Logger.EndSection();

            return(text);
        }
Example #26
0
        //Create By: Leslie Baliguat, Created On: 3/4/2016 /*Purpose: Replicate Prospect Information to Prospect Inquiry

        /* Purpose: Once a monthly amortization record was tagged "selected",
         * it's monthly amortization will be replicated to it's quotes's net monthly amortization field
         * and other monthly amortization with the same quote id, selected field will be unchecked
         * Registration Details:
         * Event/Message:
         *      Post/Update: Selected
         * Primary Entity: Monthly Amortization
         */
        public void ReplicateMonthlyAmortization(Entity monthlyAmortizationEntity)
        {
            _tracingService.Trace("Started ReplicateMonthlyAmortization method ...");

            if (monthlyAmortizationEntity.Contains("gsc_quoteid") || monthlyAmortizationEntity.GetAttributeValue <EntityReference>("gsc_quoteid") != null)
            {
                var quoteid    = monthlyAmortizationEntity.GetAttributeValue <EntityReference>("gsc_quoteid").Id;
                var isSelected = monthlyAmortizationEntity.GetAttributeValue <Boolean>("gsc_isselected");

                if (isSelected == true)
                {
                    _tracingService.Trace("isSelected is true ...");

                    //update net monthly amortization  in quote
                    _tracingService.Trace("Retrieve Quote Record...");

                    EntityCollection quoteRecords = CommonHandler.RetrieveRecordsByOneValue("quote", "quoteid", quoteid, _organizationService, null, OrderType.Ascending,
                                                                                            new[] { "gsc_netmonthlyamortization" });

                    if (quoteRecords != null && quoteRecords.Entities.Count > 0)
                    {
                        _tracingService.Trace("Update Net Monthly Amortization in Quote ...");

                        Entity quoteEntity = quoteRecords.Entities[0];

                        var monthlyDecimal = monthlyAmortizationEntity["gsc_quotemonthlyamortizationpn"].ToString().Trim(',');
                        quoteEntity["gsc_netmonthlyamortization"] = new Money(Decimal.Parse(monthlyDecimal));

                        _organizationService.Update(quoteEntity);
                    }

                    //check if there is other monthly amortization record which gsc_isselected is checked
                    _tracingService.Trace("Retrieve Monthly Amortization Records associated with the same Quote...");

                    var monthlyAmotizationConditionList = new List <ConditionExpression>
                    {
                        new ConditionExpression("gsc_quoteid", ConditionOperator.Equal, quoteid),
                        new ConditionExpression("gsc_sls_quotemonthlyamortizationid", ConditionOperator.NotEqual, monthlyAmortizationEntity.Id)
                    };

                    EntityCollection monthlyAmortizationRecords = CommonHandler.RetrieveRecordsByConditions("gsc_sls_quotemonthlyamortization", monthlyAmotizationConditionList, _organizationService, null, OrderType.Ascending,
                                                                                                            new[] { "gsc_isselected" });

                    if (monthlyAmortizationRecords != null || monthlyAmortizationRecords.Entities.Count > 0)
                    {
                        foreach (Entity monthlyAmortization in monthlyAmortizationRecords.Entities)
                        {
                            var monthlyAmortization_isSelected = monthlyAmortization.GetAttributeValue <Boolean>("gsc_isselected");

                            if (monthlyAmortization_isSelected == true)
                            {
                                _tracingService.Trace("Update isSelected field which value is true");

                                monthlyAmortization["gsc_isselected"] = false;

                                _organizationService.Update(monthlyAmortization);

                                break;
                            }
                        }
                    }
                }
                else
                {
                    CheckMonthlyAmortizationRecords(monthlyAmortizationEntity);
                }
            }

            _tracingService.Trace("Ended ReplicateMonthlyAmortization method ...");
        }
        internal static object ToJSONComplexObject(Entity entity)
        {
            var entityDictionary = new Dictionary <string, object>();

            entityDictionary["entity"] = entity.LogicalName;
            entityDictionary["id"]     = entity.Id.ToString("B");

            var attributesList = new List <Dictionary <string, object> >();

            entityDictionary["attributes"] = attributesList;

            foreach (var attribute in entity.Attributes)
            {
                var name  = attribute.Key;
                var value = attribute.Value;

                if (name == entity.LogicalName + "id")
                {
                    continue;
                }

                if (name.EndsWith("_base") && entity.Contains(name.Substring(0, name.Length - 5)))
                {
                    continue;
                }

                var attributeDictionary = new Dictionary <string, object>();
                attributesList.Add(attributeDictionary);

                if (value is AliasedValue av)
                {
                    if (!String.IsNullOrEmpty(av.AttributeLogicalName))
                    {
                        attributeDictionary["attributelogicalname"] = av.AttributeLogicalName;
                    }

                    if (!String.IsNullOrEmpty(av.EntityLogicalName))
                    {
                        attributeDictionary["entitylogicalname"] = av.EntityLogicalName;
                    }
                }

                attributeDictionary["name"] = name;
                attributeDictionary["type"] = LastClassName(value);

                if (value is EntityReference er)
                {
                    attributeDictionary["entity"] = er.LogicalName;

                    if (!String.IsNullOrEmpty(er.Name))
                    {
                        attributeDictionary["namevalue"] = er.Name;
                    }
                }

                if (value != null)
                {
                    attributeDictionary["value"] = AttributeToBaseType(value);
                }
            }

            return(entityDictionary);
        }
Example #28
0
        internal string ExecuteDocumentWritenRecordForm(Guid productId, string Path)
        {
            string folder      = DeliveryNoticeHelper.CreateFolder(productId, Path);
            string projectName = string.Empty;
            string referans    = string.Empty;
            string blok        = string.Empty;
            string floor       = string.Empty;
            string apartmentNo = string.Empty;
            string banka       = string.Empty;



            Guid   projectId           = Guid.Empty;
            string city                = string.Empty;
            string address             = string.Empty;
            string passportNumber      = string.Empty;
            string freeSectionIdNumber = string.Empty;

            string salesAccountName      = string.Empty;
            string salesAccountAddress   = string.Empty;
            string salesAccountShortName = string.Empty;
            string name                = string.Empty;
            string deliveryDate        = string.Empty;
            string ada                 = string.Empty;
            string productCity         = string.Empty;
            string secondryContactName = string.Empty;
            string productDistrict     = string.Empty;
            string quarter             = string.Empty;
            string threader            = string.Empty;
            string licenceNumber       = string.Empty;
            string parcel              = string.Empty;
            Entity quote               = null;
            Entity contact             = null;
            Entity account             = null;
            Entity SalesAccount        = null;
            string contractDate        = string.Empty;


            service = MSCRM.AdminOrgService;



            Entity product = service.Retrieve("product", productId, new ColumnSet(true));

            projectId       = product.Contains("new_projectid") ? ((EntityReference)product.Attributes["new_projectid"]).Id : Guid.Empty;
            projectName     = product.Contains("new_projectid") ? ((EntityReference)product.Attributes["new_projectid"]).Name : string.Empty;
            blok            = product.Contains("new_blockid") ? ((EntityReference)product.Attributes["new_blockid"]).Name : string.Empty;
            ada             = product.Contains("new_blockofbuildingid") ? ((EntityReference)product.Attributes["new_blockofbuildingid"]).Name : string.Empty;
            floor           = product.Contains("new_floornumber") ? product.Attributes["new_floornumber"].ToString() : string.Empty;
            apartmentNo     = product.Contains("new_homenumber") ? (string)product.Attributes["new_homenumber"] : string.Empty;
            quarter         = product.Contains("new_quarter") ? (string)product.Attributes["new_quarter"] : string.Empty;
            threader        = product.Contains("new_threaderid") ? ((EntityReference)product.Attributes["new_threaderid"]).Name : string.Empty;
            parcel          = product.Contains("new_parcelid") ? ((EntityReference)product.Attributes["new_parcelid"]).Name : string.Empty;
            productDistrict = product.Contains("new_district") ? (string)product.Attributes["new_district"] : string.Empty;
            productCity     = product.Contains("new_city") ? (string)product.Attributes["new_city"] : string.Empty;
            deliveryDate    = product.Contains("new_deliverydate") ? ((DateTime)product.Attributes["new_deliverydate"]).ToShortDateString() : string.Empty;
            licenceNumber   = product.Contains("new_licencenumber") ? (string)product.Attributes["new_licencenumber"] : string.Empty;

            freeSectionIdNumber = product.Contains("new_freesectionidnumber") ? (string)product.Attributes["new_freesectionidnumber"] : string.Empty;


            ConditionExpression con1 = new ConditionExpression();

            con1.AttributeName = "productid";
            con1.Operator      = ConditionOperator.Equal;
            con1.Values.Add(productId);

            ConditionExpression con2 = new ConditionExpression();

            con2.AttributeName = "quotestatecode";
            con2.Operator      = ConditionOperator.Equal;
            con2.Values.Add(1);

            FilterExpression filter = new FilterExpression();

            filter.FilterOperator = LogicalOperator.And;
            filter.Conditions.Add(con1);
            filter.Conditions.Add(con2);


            QueryExpression Query = new QueryExpression("quotedetail");

            Query.ColumnSet = new ColumnSet("quoteid");
            Query.Criteria.FilterOperator = LogicalOperator.And;
            Query.Criteria.Filters.Add(filter);

            EntityCollection Result = service.RetrieveMultiple(Query);

            if (Result.Entities.Count > 0)
            {
                quote        = service.Retrieve("quote", ((EntityReference)Result.Entities[0].Attributes["quoteid"]).Id, new ColumnSet(true));
                contractDate = quote.Contains("new_contractdate") ? ((DateTime)quote.Attributes["new_contractdate"]).ToLocalTime().ToShortDateString() : string.Empty;
                banka        = quote.Contains("new_bankid") ? ((EntityReference)quote.Attributes["new_bankid"]).Name : string.Empty;
                if (quote.Contains("new_salesshareaccountid"))
                {
                    SalesAccount          = service.Retrieve("new_share", ((EntityReference)quote.Attributes["new_salesshareaccountid"]).Id, new ColumnSet(true));
                    salesAccountName      = SalesAccount.Contains("new_name") ? SalesAccount.Attributes["new_name"].ToString() : string.Empty;
                    salesAccountAddress   = SalesAccount.Contains("new_adressdetail") ? SalesAccount.Attributes["new_adressdetail"].ToString() : string.Empty;
                    salesAccountShortName = SalesAccount.Contains("new_shortname") ? SalesAccount.Attributes["new_shortname"].ToString() : string.Empty;
                }
                if (((EntityReference)quote.Attributes["customerid"]).LogicalName.ToLower() == "contact")
                {
                    contact        = service.Retrieve("contact", ((EntityReference)quote.Attributes["customerid"]).Id, new ColumnSet(true));
                    name           = contact.Contains("fullname") ? (string)contact.Attributes["fullname"] : string.Empty;
                    city           = contact.Contains("new_addresscityid") ? ((EntityReference)contact.Attributes["new_addresscityid"]).Name + "/" : string.Empty + "/";
                    city          += contact.Contains("new_addresstownid") ? ((EntityReference)contact.Attributes["new_addresstownid"]).Name + "/" : string.Empty + "/";
                    city          += contact.Contains("new_addressdistrictid") ? ((EntityReference)contact.Attributes["new_addressdistrictid"]).Name : string.Empty;
                    address        = contact.Contains("new_addressdetail") ? contact.Attributes["new_addressdetail"].ToString() : string.Empty;
                    address       += " " + city;
                    passportNumber = contact.Contains("new_passportnumber") ? (string)contact.Attributes["new_passportnumber"] : string.Empty;
                }
                else if (((EntityReference)quote.Attributes["customerid"]).LogicalName.ToLower() == "account")
                {
                    account  = service.Retrieve("account", ((EntityReference)quote.Attributes["customerid"]).Id, new ColumnSet(true));
                    city     = account.Contains("new_addresscityid") ? ((EntityReference)account.Attributes["new_addresscityid"]).Name + "/" : string.Empty + "/";
                    city    += account.Contains("new_addresstownid") ? ((EntityReference)account.Attributes["new_addresstownid"]).Name + "/" : string.Empty + "/";
                    city    += account.Contains("new_addressdistrictid") ? ((EntityReference)account.Attributes["new_addressdistrictid"]).Name : string.Empty;
                    address  = account.Contains("new_addressdetail") ? account.Attributes["new_addressdetail"].ToString() : string.Empty;
                    address += " " + city;
                }


                if (quote.Contains("new_secondcontactid"))
                {
                    secondryContactName = ((EntityReference)quote.Attributes["new_secondcontactid"]).Name;
                }
            }

            Dictionary <string, string> dictionary1 = new Dictionary <string, string>();

            dictionary1.Add("İlçe", productDistrict);
            if (!string.IsNullOrEmpty(secondryContactName))
            {
                dictionary1.Add("personal", name + " - " + secondryContactName);
            }
            else
            {
                dictionary1.Add("personal", name);
            }


            dictionary1.Add("Mahalle", quarter);
            dictionary1.Add("Ada", ada);
            dictionary1.Add("Pafta", threader);
            dictionary1.Add("Parsel", parcel);
            dictionary1.Add("Blok", blok);
            dictionary1.Add("Kat", floor);
            dictionary1.Add("BagimsizNo", freeSectionIdNumber);
            dictionary1.Add("TeslimTarihi", deliveryDate);
            dictionary1.Add("ruhsatno", licenceNumber);
            dictionary1.Add("sozlesmetarihi", contractDate);

            if (projectName == "853 NEF 03 Kağıthane")
            {
                dictionary1.Add("Proje", "NEF KAĞITHANE 03");
            }
            else
            {
                dictionary1.Add("Proje", projectName.Substring(7, projectName.Length - 7).Trim());
            }

            byte[] bytes = DocumentMerge.WordDokumanOlustur(Path + "DocumentMerge\\Templates\\DeliveryNotice.docx", (DataSet)null, dictionary1);
            string path1 = Path + "DocumentMerge\\Document\\" + folder + "\\DeliveryNotice.docx";

            if (path1 != string.Empty)
            {
                System.IO.File.WriteAllBytes(path1, bytes);
            }
            return(path1);
        }
        private void SetReceiptIdentifier(Guid receiptID, LocalPluginContext localContext, IOrganizationService service, string messageName)
        {
            localContext.TracingService.Trace("Entering SetReceiptIdentifier().");
            Entity    entity    = null;
            Guid?     guid      = null;
            string    text      = string.Empty;
            string    empty     = string.Empty;
            double    num       = 0.0;
            int       num2      = 0;
            ColumnSet columnSet = new ColumnSet("msnfp_receiptid", "msnfp_identifier", "msnfp_receiptstackid", "msnfp_receiptstatus");
            Entity    entity2   = service.Retrieve("msnfp_receipt", receiptID, columnSet);

            localContext.TracingService.Trace("Found receipt with id: " + receiptID.ToString());
            if (entity2.Contains("msnfp_identifier") && messageName != "Create")
            {
                localContext.TracingService.Trace("Found receipt identifier: " + (string)entity2["msnfp_identifier"]);
                if (entity2["msnfp_identifier"] != null || ((string)entity2["msnfp_identifier"]).Length > 0)
                {
                    localContext.TracingService.Trace("Receipt already has identfier. Exiting SetReceiptIdentifier().");
                    return;
                }
            }
            if (entity2.Contains("msnfp_receiptstackid"))
            {
                guid = entity2.GetAttributeValue <EntityReference>("msnfp_receiptstackid").Id;
                localContext.TracingService.Trace("Found receipt stack.");
            }
            else
            {
                localContext.TracingService.Trace("No receipt stack found.");
            }
            if (guid.HasValue)
            {
                ITracingService tracingService = localContext.TracingService;
                Guid?           guid2          = guid;
                tracingService.Trace("Locking Receipt Stack record Id:" + guid2.ToString());
                Entity entity3 = new Entity("msnfp_receiptstack", guid.Value);
                entity3["msnfp_locked"] = true;
                service.Update(entity3);
                localContext.TracingService.Trace("Receipt Stack record locked");
                entity = service.Retrieve("msnfp_receiptstack", ((EntityReference)entity2["msnfp_receiptstackid"]).Id, new ColumnSet("msnfp_receiptstackid", "msnfp_prefix", "msnfp_currentrange", "msnfp_numberrange"));
                localContext.TracingService.Trace("Obtaining prefix, current range and number range.");
                empty = (entity.Contains("msnfp_prefix") ? ((string)entity["msnfp_prefix"]) : string.Empty);
                num   = (entity.Contains("msnfp_currentrange") ? ((double)entity["msnfp_currentrange"]) : 0.0);
                num2  = (entity.Contains("msnfp_numberrange") ? ((OptionSetValue)entity["msnfp_numberrange"]).Value : 0);
                switch (num2)
                {
                case 844060000:
                    localContext.TracingService.Trace("Number range : 6 digit");
                    text = empty + (num + 1.0).ToString().PadLeft(6, '0');
                    break;

                case 844060001:
                    localContext.TracingService.Trace("Number range : 8 digit");
                    text = empty + (num + 1.0).ToString().PadLeft(8, '0');
                    break;

                case 844060002:
                    localContext.TracingService.Trace("Number range : 10 digit");
                    text = empty + (num + 1.0).ToString().PadLeft(10, '0');
                    break;

                default:
                    localContext.TracingService.Trace("Receipt number range unknown. msnfp_numberrange: " + num2);
                    break;
                }
                localContext.TracingService.Trace("Receipt Number: " + text);
                Entity entity4 = new Entity(entity2.LogicalName, entity2.Id);
                entity4["msnfp_receiptnumber"] = text;
                entity4["msnfp_identifier"]    = text;
                if (messageName == "Create" && !entity2.Contains("msnfp_receiptstatus"))
                {
                    entity4["msnfp_receiptstatus"] = "Issued";
                }
                localContext.TracingService.Trace("Updating Receipt.");
                service.Update(entity4);
                localContext.TracingService.Trace("Receipt Updated");
                localContext.TracingService.Trace("Now update the receipt stacks current number by 1.");
                Entity entity5 = new Entity("msnfp_receiptstack", guid.Value);
                entity5["msnfp_currentrange"] = num + 1.0;
                entity5["msnfp_locked"]       = false;
                service.Update(entity5);
                localContext.TracingService.Trace("Updated Receipt Stack current range to: " + (num + 1.0));
            }
            else
            {
                localContext.TracingService.Trace("No receipt stack found.");
            }
            localContext.TracingService.Trace("Exiting SetReceiptIdentifier().");
        }
Example #30
0
        /// <summary>
        /// Main entry point for he business logic that the plug-in is to execute.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics 365 caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        /// </remarks>
        protected override void ExecuteCrmPlugin(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new InvalidPluginExecutionException("localContext");
            }

            // TODO: Implement your custom Plug-in business logic.


            //flag update

            try
            {
                IPluginExecutionContext context = localContext.PluginExecutionContext;
                IOrganizationService    service = localContext.OrganizationService;

                if (context.IsInTransaction)
                {
                    lock (SyncLock)
                    {
                        if (context.InputParameters["Target"] is Entity)
                        {
                            Entity target = (Entity)context.InputParameters["Target"];


                            #region Update Flag
                            if (target.Contains("new_projectdetail_update_flag"))
                            {
                                if ((bool)target["new_projectdetail_update_flag"] == true)
                                {
                                    Entity report = service.Retrieve("new_weekly_report", target.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(
                                                                         "new_d_expected_monday_sum",
                                                                         "new_d_expected_tuesday_sum",
                                                                         "new_d_expected_wednesday_sum",
                                                                         "new_d_expected_thursday_sum",
                                                                         "new_d_expected_friday_sum",
                                                                         "new_p_division",
                                                                         "new_l_related_project_detail",
                                                                         "new_l_related_account",
                                                                         "new_l_related_appservice",
                                                                         "new_l_related_it_support",
                                                                         "new_p_year",
                                                                         "new_p_month",
                                                                         "new_p_week"
                                                                         ));

                                    Entity reportdetail = new Entity("new_weekly_report_detail");

                                    if (target.Contains("new_d_input_expected_monday"))
                                    {
                                        reportdetail["new_d_input_expected_monday"] = Convert.ToDecimal(target["new_d_input_expected_monday"]);
                                    }
                                    else if (report.Contains("new_d_input_expected_monday"))
                                    {
                                        reportdetail["new_d_input_expected_monday"] = Convert.ToDecimal(report["new_d_input_expected_monday"]);
                                    }
                                    else
                                    {
                                        reportdetail["new_d_input_expected_monday"] = Convert.ToDecimal(0);
                                    }
                                    if (target.Contains("new_d_input_expected_tuesday"))
                                    {
                                        reportdetail["new_d_input_expected_tuesday"] = Convert.ToDecimal(target["new_d_input_expected_tuesday"]);
                                    }
                                    else if (report.Contains("new_d_input_expected_tuesday"))
                                    {
                                        reportdetail["new_d_input_expected_tuesday"] = Convert.ToDecimal(report["new_d_input_expected_tuesday"]);
                                    }
                                    else
                                    {
                                        reportdetail["new_d_input_expected_tuesday"] = Convert.ToDecimal(0);
                                    }
                                    if (target.Contains("new_d_input_expected_wednesday"))
                                    {
                                        reportdetail["new_d_input_expected_wednesday"] = Convert.ToDecimal(target["new_d_input_expected_wednesday"]);
                                    }
                                    else if (report.Contains("new_d_input_expected_wednesday"))
                                    {
                                        reportdetail["new_d_input_expected_wednesday"] = Convert.ToDecimal(report["new_d_input_expected_wednesday"]);
                                    }
                                    else
                                    {
                                        reportdetail["new_d_input_expected_wednesday"] = Convert.ToDecimal(0);
                                    }
                                    if (target.Contains("new_d_input_expected_thursday"))
                                    {
                                        reportdetail["new_d_input_expected_thursday"] = Convert.ToDecimal(target["new_d_input_expected_thursday"]);
                                    }
                                    else if (report.Contains("new_d_input_expected_thursday"))
                                    {
                                        reportdetail["new_d_input_expected_thursday"] = Convert.ToDecimal(report["new_d_input_expected_thursday"]);
                                    }
                                    else
                                    {
                                        reportdetail["new_d_input_expected_thursday"] = Convert.ToDecimal(0);
                                    }
                                    if (target.Contains("new_d_input_expected_friday"))
                                    {
                                        reportdetail["new_d_input_expected_friday"] = Convert.ToDecimal(target["new_d_input_expected_friday"]);
                                    }
                                    else if (report.Contains("new_d_input_expected_friday"))
                                    {
                                        reportdetail["new_d_input_expected_friday"] = Convert.ToDecimal(report["new_d_input_expected_friday"]);
                                    }
                                    else
                                    {
                                        reportdetail["new_d_input_expected_friday"] = Convert.ToDecimal(0);
                                    }
                                    if (target.Contains("new_txt_subject"))
                                    {
                                        reportdetail["new_txt_subject"] = target["new_txt_subject"];
                                    }
                                    else if (report.Contains("new_txt_subject"))
                                    {
                                        reportdetail["new_txt_subject"] = report["new_txt_subject"];
                                    }
                                    else
                                    {
                                        reportdetail["new_txt_subject"] = "제목없음";
                                    }


                                    //add guid in detail entity
                                    reportdetail["new_l_weekly_report"] = new EntityReference("new_weekly_report", new Guid(target.Id.ToString()));

                                    var defaultValue = 100000000;

                                    reportdetail["new_i_year"]  = ((OptionSetValue)report["new_p_year"]).Value - defaultValue;
                                    reportdetail["new_i_month"] = (((OptionSetValue)report["new_p_month"]).Value);
                                    reportdetail["new_i_week"]  = ((OptionSetValue)report["new_p_week"]).Value - defaultValue + 1;

                                    //if have null in report value, make 0
                                    if (!report.Contains("new_d_expected_monday_sum"))
                                    {
                                        report["new_d_expected_monday_sum"] = new Decimal(0);
                                    }
                                    if (!report.Contains("new_d_expected_tuesday_sum"))
                                    {
                                        report["new_d_expected_tuesday_sum"] = new Decimal(0);
                                    }
                                    if (!report.Contains("new_d_expected_wednesday_sum"))
                                    {
                                        report["new_d_expected_wednesday_sum"] = new Decimal(0);
                                    }
                                    {
                                        report["new_d_expected_thursday_sum"] = new Decimal(0);
                                    }
                                    if (!report.Contains("new_d_expected_friday_sum"))
                                    {
                                        report["new_d_expected_friday_sum"] = new Decimal(0);
                                    }


                                    target["new_d_expected_monday_sum"]    = (Decimal)report["new_d_expected_monday_sum"] + (Decimal)reportdetail["new_d_input_expected_monday"];
                                    target["new_d_expected_tuesday_sum"]   = (Decimal)report["new_d_expected_tuesday_sum"] + (Decimal)reportdetail["new_d_input_expected_tuesday"];
                                    target["new_d_expected_wednesday_sum"] = (Decimal)report["new_d_expected_wednesday_sum"] + (Decimal)reportdetail["new_d_input_expected_wednesday"];
                                    target["new_d_expected_thursday_sum"]  = (Decimal)report["new_d_expected_thursday_sum"] + (Decimal)reportdetail["new_d_input_expected_thursday"];
                                    target["new_d_expected_friday_sum"]    = (Decimal)report["new_d_expected_friday_sum"] + (Decimal)reportdetail["new_d_input_expected_friday"];

                                    target["new_d_input_expected_monday"]    = null;
                                    target["new_d_input_expected_tuesday"]   = null;
                                    target["new_d_input_expected_wednesday"] = null;
                                    target["new_d_input_expected_thursday"]  = null;
                                    target["new_d_input_expected_friday"]    = null;
                                    target["new_projectdetail_update_flag"]  = false;
                                    context.InputParameters["Target"]        = target;


                                    service.Create(reportdetail);

                                    report["new_d_input_expected_monday"]    = null;
                                    report["new_d_input_expected_tuesday"]   = null;
                                    report["new_d_input_expected_wednesday"] = null;
                                    report["new_d_input_expected_thursday"]  = null;
                                    report["new_d_input_expected_friday"]    = null;
                                    report["new_projectdetail_update_flag"]  = false;
                                }
                            }

                            #endregion
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
Example #31
0
        /// <summary>
        /// Main entry point for he business logic that the plug-in is to execute.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics 365 caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        /// </remarks>
        protected override void ExecuteCrmPlugin(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new InvalidPluginExecutionException("localContext");
            }

            try
            {
                IPluginExecutionContext context = localContext.PluginExecutionContext;
                IOrganizationService    service = localContext.OrganizationService;

                if (context.IsInTransaction)
                {
                    lock (SyncLock)
                    {
                        if (context.InputParameters["Target"] is Entity)
                        {
                            Entity target = (Entity)context.InputParameters["Target"];

                            //retreive (target.id)
                            Entity reportDetail = service.Retrieve("new_weekly_report_detail", target.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(true
                                                                                                                                                //"new_l_task",
                                                                                                                                                //"new_i_week",
                                                                                                                                                ));


                            if (reportDetail.Contains("new_l_task"))
                            {
                                // Function 화
                                EntityReference     task = new EntityReference("task", (((EntityReference)reportDetail["new_l_task"]).Id));
                                ConditionExpression ce   = new ConditionExpression(); //  task 이름이랑 같은 값이 주간업무보고에 포함되어 있는지
                                ce.AttributeName = "new_l_task";
                                ce.Operator      = ConditionOperator.Equal;
                                ce.Values.Add(task);

                                FilterExpression fe = new FilterExpression();
                                fe.Conditions.Add(ce);

                                QueryExpression qe = new QueryExpression("new_weekly_report_detail");
                                qe.ColumnSet.AddColumns("new_l_task");
                                qe.Criteria.AddFilter(fe);

                                EntityCollection ec = service.RetrieveMultiple(qe);

                                if (ec.Entities.Count == 1)
                                {
                                    // just update
                                    //    task["scheduledend"]
                                    //    task["scheduledstart"]
                                    //    task["actualdurationminutes"]
                                    //    task["regardingobjectid"]
                                }
                                else
                                {
                                    int min = Convert.ToInt32(reportDetail["new_i_week"]);
                                    int max = Convert.ToInt32(reportDetail["new_i_week"]);
                                    int my  = Convert.ToInt32(reportDetail["new_i_week"]);
                                    foreach (var anotherDetail in ec.Entities)
                                    {
                                        Entity anoterRpoertDetail = service.Retrieve("new_weekly_report_detail", anotherDetail.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(true
                                                                                                                                                                         // 필요한 INDEX 만 뽑기
                                                                                                                                                                         ));
                                        // 1안 index 숫자 가져와서
                                        // for문 두번 돌면서 min인지 max인지 측정 .

                                        if (max < Convert.ToInt32(anoterRpoertDetail["new_i_week"]))
                                        {
                                            max = Convert.ToInt32(anoterRpoertDetail["new_i_week"]);
                                        }

                                        if (min < Convert.ToInt32(anoterRpoertDetail["new_i_week"]))
                                        {
                                            min = Convert.ToInt32(anoterRpoertDetail["new_i_week"]);
                                        }
                                    }
                                    if (my == max)
                                    {
                                        //task update with d
                                    }
                                    else if (my == max)
                                    {
                                        //tash update with s
                                    }
                                    else
                                    {
                                        //task update only int
                                    }
                                }
                            }

                            //자신과 같은 작업을 가진, 다른 상세들 가져오기, (Entity)로 -> * Function 화 필요 * (F1)

                            //해당 Enttiy의 부모들을 가져오기

                            //개수가 1개이면 그냥 업데이트


                            //개수가 2개 이상이면 아래 로직 -> 이것도 Function화 필요

                            //자기 자신이 가장 늦은주 ( 전주가 없다 ) -> S
                            //자기 자신이 가장 늦은주 X(전주가 있다)
                            //자기 자신이 가장 빠른주 O (후주가 없다) -> D
                            //자기 자신이 가장 빠른주 X ( 중간이다 ) -> 기간만 반환


                            // TODO: Implement your custom Plug-in business logic.
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
        protected override void ExecuteCrmPlugin(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }
            localContext.TracingService.Trace("---------Triggered PaymentMethodUpdate.cs---------");
            IPluginExecutionContext    pluginExecutionContext     = localContext.PluginExecutionContext;
            IOrganizationService       organizationService        = localContext.OrganizationService;
            OrganizationServiceContext organizationServiceContext = new OrganizationServiceContext(organizationService);
            string empty  = string.Empty;
            Guid   empty2 = Guid.Empty;

            if (!pluginExecutionContext.InputParameters.Contains("Target") || !(pluginExecutionContext.InputParameters["Target"] is Entity))
            {
                return;
            }
            localContext.TracingService.Trace("---------Entering PaymentMethodUpdate.cs Main Function---------");
            Entity entity           = (Entity)pluginExecutionContext.InputParameters["Target"];
            Guid   initiatingUserId = pluginExecutionContext.InitiatingUserId;
            Entity entity2          = organizationService.Retrieve("systemuser", initiatingUserId, new ColumnSet("msnfp_configurationid"));
            Entity entity3          = organizationService.Retrieve("msnfp_paymentmethod", entity.Id, GetColumnSet());

            if (entity3 == null)
            {
                throw new ArgumentNullException("msnfp_paymentmethodid");
            }
            if (entity2 == null)
            {
                throw new Exception("No user id found. Please ensure the user is valid. Exiting plugin.");
            }
            if (entity3.Contains("msnfp_isreusable") && entity3.Contains("msnfp_type") && entity3.Contains("msnfp_billing_line1") && entity3.Contains("msnfp_paymentprocessorid") && entity3.Contains("msnfp_customerid") && entity3.Contains("msnfp_authtoken") && entity3.Contains("msnfp_cclast4"))
            {
                if (!(bool)entity3["msnfp_isreusable"] || ((OptionSetValue)entity3["msnfp_type"]).Value != 844060000 || (string)entity3["msnfp_billing_line1"] == null)
                {
                    localContext.TracingService.Trace("Payment Method is not reusable, has no street 1 or is not a credit card. Exiting plugin.");
                    return;
                }
                Entity paymentProcessorForPaymentMethod = getPaymentProcessorForPaymentMethod(entity3, localContext, organizationService);
                if (paymentProcessorForPaymentMethod != null)
                {
                    localContext.TracingService.Trace("Payment Processor retrieved.");
                    if (paymentProcessorForPaymentMethod.Contains("msnfp_paymentgatewaytype"))
                    {
                        if (((OptionSetValue)paymentProcessorForPaymentMethod["msnfp_paymentgatewaytype"]).Value == 844060000)
                        {
                        }
                        if (((OptionSetValue)paymentProcessorForPaymentMethod["msnfp_paymentgatewaytype"]).Value == 844060001)
                        {
                        }
                        if (((OptionSetValue)paymentProcessorForPaymentMethod["msnfp_paymentgatewaytype"]).Value != 844060002)
                        {
                        }
                    }
                }
                localContext.TracingService.Trace("---------Exiting PaymentMethodUpdate.cs---------");
            }
            else
            {
                localContext.TracingService.Trace("Payment Method is not reusable, has no street 1, is not a credit card or has no payment processor. Exiting plugin.");
            }
        }
        //Created By : Jerome Anthony Gerero, Created On : 8/31/2016

        /*Purpose: Update Inventory record fields on Vehicle Adjustment/Variance Entry Detail record delete
         * Registration Details:
         * Event/Message:
         *      Pre-Validate/Delete: gsc_sls_adjustmentvariancedetailid
         *      Post/Update:
         *      Post/Create:
         * Primary Entity: Vehicle Adjustment/Variance Entry Detail
         */
        public Entity AdjustInventoryRecordOnDelete(Entity vehicleAdjustmentVarianceEntryDetailEntity)
        {
            _tracingService.Trace("Started AdjustInventoryRecordOnDelete Method...");

            Guid vehicleAdjustmentVarianceEntryId = vehicleAdjustmentVarianceEntryDetailEntity.GetAttributeValue <EntityReference>("gsc_vehicleadjustmentvarianceentryid") != null
                ? vehicleAdjustmentVarianceEntryDetailEntity.GetAttributeValue <EntityReference>("gsc_vehicleadjustmentvarianceentryid").Id
                : Guid.Empty;

            //Retrieve Vehicle Adjustment/Variance Entry record
            EntityCollection vehicleAdjustmentVarianceEntryRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_sls_vehicleadjustmentvarianceentry", "gsc_sls_vehicleadjustmentvarianceentryid", vehicleAdjustmentVarianceEntryId, _organizationService, null, OrderType.Ascending,
                                                                                                             new[] { "gsc_adjustmentvariancestatus" });

            if (vehicleAdjustmentVarianceEntryRecords != null && vehicleAdjustmentVarianceEntryRecords.Entities.Count > 0)
            {
                Entity vehicleAdjustmentVarianceEntry = vehicleAdjustmentVarianceEntryRecords.Entities[0];

                if (vehicleAdjustmentVarianceEntry.FormattedValues["gsc_adjustmentvariancestatus"].Equals("Posted"))
                {
                    throw new InvalidPluginExecutionException("Unable to delete already posted Vehicle Adjustment/Variance Entry");
                }
            }

            Guid inventoryId = vehicleAdjustmentVarianceEntryDetailEntity.GetAttributeValue <EntityReference>("gsc_inventoryid") != null
                ? vehicleAdjustmentVarianceEntryDetailEntity.GetAttributeValue <EntityReference>("gsc_inventoryid").Id
                : Guid.Empty;

            //Retrieve Inventory records
            EntityCollection inventoryRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_inventory", "gsc_iv_inventoryid", inventoryId, _organizationService, null, OrderType.Ascending,
                                                                                        new[] { "gsc_status", "gsc_productquantityid" });

            if (inventoryRecords != null && inventoryRecords.Entities.Count > 0)
            {
                Entity inventory = inventoryRecords.Entities[0];

                inventory["gsc_status"] = new OptionSetValue(100000000);

                _organizationService.Update(inventory);

                Guid productQuantityId = inventory.GetAttributeValue <EntityReference>("gsc_productquantityid") != null
                    ? inventory.GetAttributeValue <EntityReference>("gsc_productquantityid").Id
                    : Guid.Empty;

                //Retrieve Product Quantity records
                EntityCollection productQuantityRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_iv_productquantity", "gsc_iv_productquantityid", productQuantityId, _organizationService, null, OrderType.Ascending,
                                                                                                  new[] { "gsc_allocated", "gsc_available" });

                if (productQuantityRecords != null && productQuantityRecords.Entities.Count > 0)
                {
                    Entity productQuantity = productQuantityRecords.Entities[0];

                    Int32 allocatedCount = productQuantity.Contains("gsc_allocated")
                        ? productQuantity.GetAttributeValue <Int32>("gsc_allocated")
                        : 1;
                    Int32 availableCount = productQuantity.Contains("gsc_available")
                        ? productQuantity.GetAttributeValue <Int32>("gsc_available")
                        : 0;

                    if (allocatedCount != 0)
                    {
                        productQuantity["gsc_allocated"] = allocatedCount - 1;
                    }
                    productQuantity["gsc_available"] = availableCount + 1;

                    _organizationService.Update(productQuantity);
                }
            }

            _tracingService.Trace("Ended AdjustInventoryRecordOnDelete Method...");
            return(vehicleAdjustmentVarianceEntryDetailEntity);
        }
        private void AddOrUpdateThisRecordWithAzure(Entity queriedEntityRecord, Entity configurationRecord, LocalPluginContext localContext, IOrganizationService service, IPluginExecutionContext context)
        {
            localContext.TracingService.Trace("---------Send the Record to Azure---------");
            string messageName = context.MessageName;
            string text        = "Designation";
            string text2       = Utilities.GetAzureWebAPIURL(service, context);

            localContext.TracingService.Trace("Got API URL: " + text2);
            if (text2 != string.Empty)
            {
                localContext.TracingService.Trace("Getting Latest Info for Record: " + queriedEntityRecord["msnfp_designationid"].ToString());
                MSNFP_Designation mSNFP_Designation = new MSNFP_Designation();
                mSNFP_Designation.DesignationId = (Guid)queriedEntityRecord["msnfp_designationid"];
                mSNFP_Designation.Name          = (queriedEntityRecord.Contains("msnfp_name") ? ((string)queriedEntityRecord["msnfp_name"]) : string.Empty);
                localContext.TracingService.Trace("Title: " + mSNFP_Designation.Name);
                if (messageName == "Create")
                {
                    mSNFP_Designation.CreatedOn = DateTime.UtcNow;
                }
                else if (queriedEntityRecord.Contains("createdon") && queriedEntityRecord["createdon"] != null)
                {
                    mSNFP_Designation.CreatedOn = (DateTime)queriedEntityRecord["createdon"];
                }
                else
                {
                    mSNFP_Designation.CreatedOn = null;
                }
                mSNFP_Designation.SyncDate = DateTime.UtcNow;
                if (messageName == "Delete")
                {
                    mSNFP_Designation.Deleted     = true;
                    mSNFP_Designation.DeletedDate = DateTime.UtcNow;
                }
                else
                {
                    mSNFP_Designation.Deleted     = false;
                    mSNFP_Designation.DeletedDate = null;
                }
                mSNFP_Designation.StatusCode = ((OptionSetValue)queriedEntityRecord["statuscode"]).Value;
                mSNFP_Designation.StateCode  = ((OptionSetValue)queriedEntityRecord["statecode"]).Value;
                localContext.TracingService.Trace("JSON object created");
                if (messageName == "Create")
                {
                    text2 = text2 + text + "/Create" + text;
                }
                else if (messageName == "Update" || messageName == "Delete")
                {
                    text2 = text2 + text + "/Update" + text;
                }
                MemoryStream memoryStream = new MemoryStream();
                DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(MSNFP_Designation));
                dataContractJsonSerializer.WriteObject(memoryStream, mSNFP_Designation);
                byte[] array = memoryStream.ToArray();
                memoryStream.Close();
                string       @string      = Encoding.UTF8.GetString(array, 0, array.Length);
                WebAPIClient webAPIClient = new WebAPIClient();
                webAPIClient.Headers[HttpRequestHeader.ContentType] = "application/json";
                webAPIClient.Headers["Padlock"] = (string)configurationRecord["msnfp_apipadlocktoken"];
                webAPIClient.Encoding           = Encoding.UTF8;
                localContext.TracingService.Trace("---------Preparing JSON---------");
                localContext.TracingService.Trace("Converted to json API URL : " + text2);
                localContext.TracingService.Trace("JSON: " + @string);
                localContext.TracingService.Trace("---------End of Preparing JSON---------");
                localContext.TracingService.Trace("Sending data to Azure.");
                string text3 = webAPIClient.UploadString(text2, @string);
                localContext.TracingService.Trace("Got response.");
                localContext.TracingService.Trace("Response: " + text3);
                Utilities utilities = new Utilities();
                utilities.CheckAPIReturnJSONForErrors(text3, configurationRecord.GetAttributeValue <OptionSetValue>("msnfp_showapierrorresponses"), localContext.TracingService);
            }
            else
            {
                localContext.TracingService.Trace("No API URL or Enable Portal Pages. Exiting workflow.");
            }
        }
        //Created By : Jerome Anthony Gerero, Created On : 8/30/2016

        /*Purpose: Validate if new record exists in Inventory entity
         * Registration Details:
         * Event/Message:
         *      Pre/Create: All input fields
         *      Post/Update:
         *      Post/Create:
         * Primary Entity: Vehicle Adjustment/Variance Entry Detail
         */
        public Entity CheckExistingInventoryRecord(Entity vehicleAdjustmentVarianceEntryDetailEntity, String message)
        {
            _tracingService.Trace("Started CheckExistingInventoryRecord Method...");

            //Return if record is made through plugin by checking if Inventory field contains data
            if (vehicleAdjustmentVarianceEntryDetailEntity.GetAttributeValue <EntityReference>("gsc_inventoryid") != null)
            {
                return(null);
            }

            //Retrieve Vehicle Adjustment/Variance Entry record
            Entity vehicleAdjustmentVarianceEntry = _organizationService.Retrieve("gsc_sls_vehicleadjustmentvarianceentry", vehicleAdjustmentVarianceEntryDetailEntity.GetAttributeValue <EntityReference>("gsc_vehicleadjustmentvarianceentryid").Id, new ColumnSet("gsc_adjustmentvariancestatus"));

            //Return error message if record is already posted
            if (vehicleAdjustmentVarianceEntry.FormattedValues["gsc_adjustmentvariancestatus"].Equals("Posted"))
            {
                throw new InvalidPluginExecutionException("Record is already posted. Cannot allocate new vehicle.");
            }

            Guid productId = vehicleAdjustmentVarianceEntryDetailEntity.GetAttributeValue <EntityReference>("gsc_productid") != null
                ? vehicleAdjustmentVarianceEntryDetailEntity.GetAttributeValue <EntityReference>("gsc_productid").Id
                : Guid.Empty;

            String modelCode = vehicleAdjustmentVarianceEntryDetailEntity.Contains("gsc_modelcode")
                ? vehicleAdjustmentVarianceEntryDetailEntity.GetAttributeValue <String>("gsc_modelcode")
                : String.Empty;
            String optionCode = vehicleAdjustmentVarianceEntryDetailEntity.Contains("gsc_optioncode")
                ? vehicleAdjustmentVarianceEntryDetailEntity.GetAttributeValue <String>("gsc_optioncode")
                : String.Empty;
            Guid colorId = vehicleAdjustmentVarianceEntryDetailEntity.GetAttributeValue <EntityReference>("gsc_vehiclecolorid") != null
                ? vehicleAdjustmentVarianceEntryDetailEntity.GetAttributeValue <EntityReference>("gsc_vehiclecolorid").Id
                : Guid.Empty;

            String colorName    = String.Empty;
            String productionNo = vehicleAdjustmentVarianceEntryDetailEntity.Contains("gsc_productionno")
                ? vehicleAdjustmentVarianceEntryDetailEntity.GetAttributeValue <String>("gsc_productionno")
                : String.Empty;
            String csNo = vehicleAdjustmentVarianceEntryDetailEntity.Contains("gsc_csno")
                ? vehicleAdjustmentVarianceEntryDetailEntity.GetAttributeValue <String>("gsc_csno")
                : String.Empty;
            String engineNo = vehicleAdjustmentVarianceEntryDetailEntity.Contains("gsc_engineno")
                ? vehicleAdjustmentVarianceEntryDetailEntity.GetAttributeValue <String>("gsc_engineno")
                : String.Empty;
            String vin = vehicleAdjustmentVarianceEntryDetailEntity.Contains("gsc_vin")
                ? vehicleAdjustmentVarianceEntryDetailEntity.GetAttributeValue <String>("gsc_vin")
                : String.Empty;

            //Retrieve Vehicle Color record for filtering
            EntityCollection vehicleColorRecords = CommonHandler.RetrieveRecordsByOneValue("gsc_cmn_vehiclecolor", "gsc_cmn_vehiclecolorid", colorId, _organizationService, null, OrderType.Ascending,
                                                                                           new[] { "gsc_vehiclecolorpn" });

            _tracingService.Trace(vehicleColorRecords.Entities.Count.ToString() + " Vehicle Color record/records retrieved.");

            if (vehicleColorRecords != null && vehicleColorRecords.Entities.Count > 0)
            {
                Entity vehicleColor = vehicleColorRecords.Entities[0];

                colorName = vehicleColor.Contains("gsc_vehiclecolorpn")
                    ? vehicleColor.GetAttributeValue <String>("gsc_vehiclecolorpn")
                    : String.Empty;
            }

            //Create filter for Product in Product entity
            var productConditionList = new List <ConditionExpression>
            {
                new ConditionExpression("productid", ConditionOperator.Equal, productId),
                new ConditionExpression("gsc_modelcode", ConditionOperator.Equal, modelCode),
                new ConditionExpression("gsc_optioncode", ConditionOperator.Equal, optionCode)
            };

            //Retrieve Product record
            EntityCollection productRecords = CommonHandler.RetrieveRecordsByConditions("product", productConditionList, _organizationService, null, OrderType.Ascending,
                                                                                        new[] { "productid", "gsc_modelyear", "gsc_vehiclemodelid" });

            _tracingService.Trace("Product Records Retrieved: " + productRecords.Entities.Count);
            if (productRecords != null && productRecords.Entities.Count > 0)
            {
                Entity product = productRecords.Entities[0];

                vehicleAdjustmentVarianceEntryDetailEntity["gsc_modelyear"] = product.Contains("gsc_modelyear")
                    ? product.GetAttributeValue <String>("gsc_modelyear")
                    : String.Empty;
                vehicleAdjustmentVarianceEntryDetailEntity["gsc_vehiclebasemodelid"] = product.GetAttributeValue <EntityReference>("gsc_vehiclemodelid") != null
                    ? new EntityReference("gsc_iv_vehiclebasemodel", product.GetAttributeValue <EntityReference>("gsc_vehiclemodelid").Id)
                    : null;
                vehicleAdjustmentVarianceEntryDetailEntity["gsc_productid"] = new EntityReference(product.LogicalName, product.Id);
            }
            else
            {
                throw new InvalidPluginExecutionException("Product with Model Code: " + modelCode + " and Option Code: " + optionCode + " does not exist yet. Please insert product information in Vehicle and Item Catalog.");
            }

            //Create filter for Product in Adjustment/Variance Entry and Inventory entities
            FilterExpression productFilter = new FilterExpression(LogicalOperator.And);

            FilterExpression productInfoFilter = new FilterExpression(LogicalOperator.Or);

            productInfoFilter.Conditions.Add(new ConditionExpression("gsc_productionno", ConditionOperator.Equal, productionNo));
            productInfoFilter.Conditions.Add(new ConditionExpression("gsc_csno", ConditionOperator.Equal, csNo));
            productInfoFilter.Conditions.Add(new ConditionExpression("gsc_engineno", ConditionOperator.Equal, engineNo));
            productInfoFilter.Conditions.Add(new ConditionExpression("gsc_vin", ConditionOperator.Equal, vin));

            FilterExpression statusFilter = new FilterExpression(LogicalOperator.And);

            statusFilter.Conditions.Add(new ConditionExpression("statecode", ConditionOperator.Equal, 0));

            productFilter.AddFilter(productInfoFilter);
            productFilter.AddFilter(statusFilter);

            //Verify if vehicle exists in Adjustment/Variance Detail entity with Open Status
            QueryExpression vehicleAdjustmentVarianceEntryDetailQuery = new QueryExpression("gsc_sls_adjustmentvariancedetail");

            vehicleAdjustmentVarianceEntryDetailQuery.ColumnSet = new ColumnSet("gsc_vehicleadjustmentvarianceentryid");
            vehicleAdjustmentVarianceEntryDetailQuery.Criteria.AddFilter(productInfoFilter);
            EntityCollection vehicleAdjustmentVarianceEntryDetailRecords = _organizationService.RetrieveMultiple(vehicleAdjustmentVarianceEntryDetailQuery);

            _tracingService.Trace(vehicleAdjustmentVarianceEntryDetailRecords.Entities.Count.ToString() + " Vehicle Adjustment/Variance Entry Detail record/records retrieved.");

            if (vehicleAdjustmentVarianceEntryDetailRecords != null && vehicleAdjustmentVarianceEntryDetailRecords.Entities.Count > 0)
            {
                foreach (Entity vehicleAdjustmentVarianceEntryDetail in vehicleAdjustmentVarianceEntryDetailRecords.Entities)
                {
                    var vehicleAdjustmentId = CommonHandler.GetEntityReferenceIdSafe(vehicleAdjustmentVarianceEntryDetail, "gsc_vehicleadjustmentvarianceentryid");

                    if (message.Equals("Create"))
                    {
                        Entity vehicleAdjustment = _organizationService.Retrieve("gsc_sls_vehicleadjustmentvarianceentry", vehicleAdjustmentId, new ColumnSet("gsc_adjustmentvariancestatus"));

                        if (vehicleAdjustment != null)
                        {
                            if (vehicleAdjustment.GetAttributeValue <OptionSetValue>("gsc_adjustmentvariancestatus").Value == 100000000)
                            {
                                throw new InvalidPluginExecutionException("Vehicle already exists in Adjustment/Variance Entry.");
                            }
                        }
                    }
                    else if (message.Equals("Update"))
                    {
                        if (vehicleAdjustmentVarianceEntryDetail.Id != vehicleAdjustmentVarianceEntryDetailEntity.Id)
                        {
                            Entity vehicleAdjustment = _organizationService.Retrieve("gsc_sls_vehicleadjustmentvarianceentry", vehicleAdjustmentId, new ColumnSet("gsc_adjustmentvariancestatus"));

                            if (vehicleAdjustment != null)
                            {
                                if (vehicleAdjustment.GetAttributeValue <OptionSetValue>("gsc_adjustmentvariancestatus").Value == 100000000)
                                {
                                    throw new InvalidPluginExecutionException("Vehicle already exists in Adjustment/Variance Entry.");
                                }
                            }
                        }
                    }
                }
            }

            //Retrieve Inventory records using ConditionList
            QueryExpression inventoryQuery = new QueryExpression("gsc_iv_inventory");

            inventoryQuery.ColumnSet = new ColumnSet("gsc_status", "gsc_productquantityid");
            inventoryQuery.Criteria.AddFilter(productFilter);
            EntityCollection inventoryRecords = _organizationService.RetrieveMultiple(inventoryQuery);

            _tracingService.Trace(inventoryRecords.Entities.Count.ToString() + " Inventory record/records retrieved.");

            if (inventoryRecords != null && inventoryRecords.Entities.Count > 0)
            {
                throw new InvalidPluginExecutionException("Vehicle already exists in inventory.");
            }

            if (message.Equals("Create"))
            {
                _tracingService.Trace("Create...");
                //Set Vehicle Adjustment/Variance Entry Detail Operation field to 'Add'
                vehicleAdjustmentVarianceEntryDetailEntity["gsc_operation"] = new OptionSetValue(100000000);
                vehicleAdjustmentVarianceEntryDetailEntity["gsc_quantity"]  = 1;
            }
            else if (message.Equals("Update"))
            {
                _tracingService.Trace("Update...");
                _organizationService.Update(vehicleAdjustmentVarianceEntryDetailEntity);
            }

            _tracingService.Trace("Ended CheckExistingInventoryRecord Method...");
            return(vehicleAdjustmentVarianceEntryDetailEntity);
        }
Example #36
0
        /// <summary>
        /// Copy view layout form source view to all specified target views
        /// </summary>
        /// <param name="sourceView">Source view</param>
        /// <param name="targetViews">List of target views</param>
        /// <param name="service">Crm organization service</param>
        /// <returns>Indicates if all views have been updated</returns>
        public static List <Tuple <string, string> > PropagateLayout(Entity sourceView, List <Entity> targetViews, IOrganizationService service)
        {
            var    errors = new List <Tuple <string, string> >();
            string multiObjectAttribute = string.Empty;

            try
            {
                foreach (Entity targetView in targetViews)
                {
                    if (targetView.Id != sourceView.Id)
                    {
                        bool canUpdateLinkedAttributes = true;

                        if (sourceView["layoutxml"].ToString().Contains(".") && (int)targetView["querytype"] == VIEW_ASSOCIATED)
                        {
                            errors.Add(new Tuple <string, string>(targetView["name"].ToString(), "The associated view has not been updated because of related attributes"));
                            //canUpdateLinkedAttributes = false;
                            continue;
                        }

                        // Update grid cells
                        XmlDocument targetLayout = new XmlDocument();
                        targetLayout.LoadXml(targetView["layoutxml"].ToString());

                        XmlAttribute multiAttr = targetLayout.SelectSingleNode("grid/row").Attributes["multiobjectidfield"];
                        if (multiAttr != null)
                        {
                            multiObjectAttribute = multiAttr.Value;
                        }

                        // We empty the existing cells
                        for (int i = targetLayout.SelectSingleNode("grid/row").ChildNodes.Count; i > 0; i--)
                        {
                            XmlNode toDelete = targetLayout.SelectSingleNode("grid/row").ChildNodes[i - 1];
                            targetLayout.SelectSingleNode("grid/row").RemoveChild(toDelete);
                        }

                        XmlDocument sourceLayout = new XmlDocument();
                        sourceLayout.LoadXml(sourceView["layoutxml"].ToString());

                        XmlNodeList sourceCellNodes = sourceLayout.SelectNodes("grid/row/cell");

                        var cells = new List <string>();

                        foreach (XmlNode cellNode in sourceCellNodes)
                        {
                            if (!cellNode.Attributes["name"].Value.Contains(".") || (int)targetView["querytype"] != VIEW_ASSOCIATED)
                            {
                                cells.Add(cellNode.Attributes["name"].Value);

                                XmlNode nodeDest = targetLayout.ImportNode(cellNode.Clone(), true);
                                targetLayout.SelectSingleNode("grid/row").AppendChild(nodeDest);
                            }
                        }

                        targetView["layoutxml"] = targetLayout.OuterXml;

                        // Retrieve target fetch data
                        if (targetView.Contains("fetchxml"))
                        {
                            XmlDocument targetFetchDoc = new XmlDocument();
                            targetFetchDoc.LoadXml(targetView["fetchxml"].ToString());

                            // Apply same sorting
                            XmlNodeList targetSortNodes = targetFetchDoc.SelectNodes("fetch/entity/order");

                            // Removes existing sorting
                            for (int i = targetSortNodes.Count; i > 0; i--)
                            {
                                XmlNode toDelete = targetSortNodes[i - 1];
                                targetSortNodes[i - 1].ParentNode.RemoveChild(toDelete);
                            }

                            XmlDocument sourceFetchDoc = new XmlDocument();
                            sourceFetchDoc.LoadXml(sourceView["fetchxml"].ToString());

                            XmlNodeList sourceAttrNodes = sourceFetchDoc.SelectNodes("fetch/entity/attribute");

                            foreach (XmlNode attrNode in sourceAttrNodes)
                            {
                                if (targetFetchDoc.SelectSingleNode("fetch/entity/attribute[@name='" + attrNode.Attributes["name"].Value + "']") == null)
                                {
                                    XmlNode attrNodeToAdd = targetFetchDoc.ImportNode(attrNode, true);
                                    targetFetchDoc.SelectSingleNode("fetch/entity").AppendChild(attrNodeToAdd);
                                }
                            }

                            foreach (XmlNode cellNode in sourceCellNodes)
                            {
                                string name = cellNode.Attributes["name"].Value;
                                if (!name.Contains(".") && targetFetchDoc.SelectSingleNode("fetch/entity/attribute[@name='" + name + "']") == null)
                                {
                                    XmlElement attrNodeToAdd = targetFetchDoc.CreateElement("attribute");
                                    attrNodeToAdd.SetAttribute("name", name);
                                    targetFetchDoc.SelectSingleNode("fetch/entity").AppendChild(attrNodeToAdd);
                                }
                            }

                            XmlNodeList sourceSortNodes = sourceFetchDoc.SelectNodes("fetch/entity/order");

                            // Removes existing sorting
                            foreach (XmlNode orderNode in sourceSortNodes)
                            {
                                XmlNode orderNodeToAdd = targetFetchDoc.ImportNode(orderNode, true);
                                targetFetchDoc.SelectSingleNode("fetch/entity").AppendChild(orderNodeToAdd);
                            }

                            if (canUpdateLinkedAttributes)
                            {
                                // Retrieve source fetch data
                                if (sourceView.Contains("fetchxml"))
                                {
                                    //XmlDocument sourceFetchDoc = new XmlDocument();
                                    //sourceFetchDoc.LoadXml(sourceView["fetchxml"].ToString());

                                    XmlNodeList linkNodes = sourceFetchDoc.SelectNodes("fetch/entity/link-entity");

                                    foreach (XmlNode sourceLinkNode in linkNodes)
                                    {
                                        var alias = sourceLinkNode.Attributes["alias"].Value;

                                        if (cells.FirstOrDefault(c => c.StartsWith(alias + ".")) == null)
                                        {
                                            continue;
                                        }

                                        XmlNode targetLinkNode = targetFetchDoc.SelectSingleNode("fetch/entity/link-entity[@alias=\"" + alias + "\"]");

                                        // Adds the missing link-entity node
                                        if (targetLinkNode == null)
                                        {
                                            XmlNode      nodeDest = targetFetchDoc.ImportNode(sourceLinkNode.Clone(), true);
                                            XmlAttribute typeAttr = nodeDest.Attributes["link-type"];
                                            if (typeAttr == null)
                                            {
                                                typeAttr       = targetFetchDoc.CreateAttribute("link-type");
                                                typeAttr.Value = "outer";
                                                nodeDest.Attributes.Append(typeAttr);
                                            }
                                            else
                                            {
                                                typeAttr.Value = "outer";
                                            }

                                            targetFetchDoc.SelectSingleNode("fetch/entity").AppendChild(nodeDest);
                                        }

                                        // Retrieves node again (if it was added)
                                        targetLinkNode = targetFetchDoc.SelectSingleNode("fetch/entity/link-entity[@alias=\"" + alias + "\"]");

                                        // Removes existing attributes
                                        for (int i = targetLinkNode.ChildNodes.Count; i > 0; i--)
                                        {
                                            if (targetLinkNode.ChildNodes[i - 1].Name == "attribute")
                                            {
                                                XmlNode toDelete = targetLinkNode.ChildNodes[i - 1];
                                                targetLinkNode.RemoveChild(toDelete);
                                            }
                                        }

                                        // Adds the attribute nodes from the source node
                                        foreach (XmlNode node in sourceLinkNode.ChildNodes)
                                        {
                                            if (node.Name == "attribute")
                                            {
                                                XmlNode attributeNode = targetLinkNode.SelectSingleNode("attribute[@name='" + node.Attributes["name"].Value + "']");

                                                if (attributeNode == null)
                                                {
                                                    XmlNode nodeDest = targetFetchDoc.ImportNode(node.Clone(), true);
                                                    targetLinkNode.AppendChild(nodeDest);
                                                }
                                            }
                                        }
                                    }
                                }

                                // Suppression des éléments Attribute inutiles dans la requête
                                List <string> attributesToRemove = new List <string>();

                                foreach (XmlNode attributeNode in targetFetchDoc.SelectNodes("//attribute"))
                                {
                                    if (attributeNode.Attributes["name"].Value == multiObjectAttribute)
                                    {
                                        break;
                                    }

                                    bool isFoundInCell = false;

                                    foreach (XmlNode cellNode in sourceLayout.SelectNodes("grid/row/cell"))
                                    {
                                        if (attributeNode.ParentNode.Name == "link-entity")
                                        {
                                            if (cellNode.Attributes["name"].Value == attributeNode.ParentNode.Attributes["alias"].Value + "." + attributeNode.Attributes["name"].Value)
                                            {
                                                isFoundInCell = true;
                                                break;
                                            }
                                        }
                                        else
                                        {
                                            if (attributeNode.Attributes["name"].Value == (attributeNode.ParentNode.Attributes["name"].Value + "id") || cellNode.Attributes["name"].Value == attributeNode.Attributes["name"].Value)
                                            {
                                                isFoundInCell = true;
                                                break;
                                            }
                                        }
                                    }

                                    if (!isFoundInCell)
                                    {
                                        if (attributeNode.ParentNode.Name == "link-entity")
                                        {
                                            attributesToRemove.Add(attributeNode.ParentNode.Attributes["alias"].Value + "." + attributeNode.Attributes["name"].Value);
                                        }
                                        else
                                        {
                                            attributesToRemove.Add(attributeNode.Attributes["name"].Value);
                                        }
                                    }
                                }

                                foreach (string attributeName in attributesToRemove)
                                {
                                    XmlNode node = null;

                                    if (attributeName.Contains("."))
                                    {
                                        node = targetFetchDoc.SelectSingleNode("fetch/entity/link-entity[@alias='" + attributeName.Split('.')[0] + "']/attribute[@name='" + attributeName.Split('.')[1] + "']");
                                        targetFetchDoc.SelectSingleNode("fetch/entity/link-entity[@alias='" + node.ParentNode.Attributes["alias"].Value + "']").RemoveChild(node);
                                    }
                                    else
                                    {
                                        node = targetFetchDoc.SelectSingleNode("fetch/entity/attribute[@name='" + attributeName + "']");
                                        targetFetchDoc.SelectSingleNode("fetch/entity").RemoveChild(node);
                                    }
                                }

                                foreach (XmlNode linkentityNode in targetFetchDoc.SelectNodes("fetch/entity/link-entity"))
                                {
                                    if (linkentityNode != null && linkentityNode.ChildNodes.Count == 0)
                                    {
                                        targetFetchDoc.SelectSingleNode("fetch/entity").RemoveChild(linkentityNode);
                                    }
                                }

                                targetView["fetchxml"] = targetFetchDoc.OuterXml;
                            }
                        }

                        try
                        {
                            service.Update(targetView);
                        }
                        catch (Exception error)
                        {
                            errors.Add(new Tuple <string, string>(targetView["name"].ToString(), error.Message));
                        }
                    }
                }

                return(errors);
            }
            catch (Exception error)
            {
                string errorMessage = CrmExceptionHelper.GetErrorMessage(error, false);

                throw new Exception("Error while copying layout to target views: " + errorMessage);
            }
        }
        public void SetCCAddOnAmount(Entity orderCabChassis, String message)
        {
            _tracingService.Trace("Started SetCCAddOnAmount Method...");
            var orderId = orderCabChassis.Contains("gsc_orderid") ? orderCabChassis.GetAttributeValue <EntityReference>("gsc_orderid").Id
                : Guid.Empty;
            Decimal ccAddOns = 0;

            EntityCollection orderCollection = CommonHandler.RetrieveRecordsByOneValue("salesorder", "salesorderid", orderId, _organizationService, null, OrderType.Ascending,
                                                                                       new[] { "gsc_discount", "gsc_ccaddons", "gsc_netprice", "gsc_unitprice", "gsc_colorprice", "gsc_freightandhandling", "gsc_paymentmode", "gsc_branchid",
                                                                                               "gsc_vatablesales", "gsc_vatexemptsales", "gsc_zeroratedsales", "gsc_totalsales", "gsc_vatamount", "gsc_totalamountdue", "gsc_insurance", "gsc_othercharges", "customerid"
                                                                                               , "gsc_accessories", "gsc_productid", "gsc_downpaymentamount", "gsc_discountamountfinanced" });

            if (orderCollection.Entities.Count > 0)
            {
                Entity orderEntity = orderCollection.Entities[0];

                Decimal paymentMode = orderEntity.Contains("gsc_paymentmode") ? orderEntity.GetAttributeValue <OptionSetValue>("gsc_paymentmode").Value
                    : 0;

                //Retrieve all order cab chassis related to quote
                EntityCollection orderCabChassisCollection = CommonHandler.RetrieveRecordsByOneValue("gsc_sls_ordercabchassis", "gsc_orderid", orderId, _organizationService,
                                                                                                     null, OrderType.Ascending, new[] { "gsc_amount", "gsc_financing" });

                if (orderCabChassisCollection.Entities.Count > 0)
                {
                    //Get total cc add on price that are for financing...
                    foreach (Entity quoteCabChassisEntity in orderCabChassisCollection.Entities)
                    {
                        if (quoteCabChassisEntity.Contains("gsc_amount"))
                        {
                            ccAddOns += quoteCabChassisEntity.GetAttributeValue <Money>("gsc_amount").Value;
                            _tracingService.Trace("CC Add Ons Amount: " + ccAddOns);
                        }
                    }

                    //Subtract sellprice of deleted.
                    if (orderCabChassis.Contains("gsc_amount") && message.Equals("Delete"))
                    {
                        _tracingService.Trace("Message is Delete...");
                        ccAddOns = ccAddOns - (Decimal)orderCabChassis.GetAttributeValue <Money>("gsc_amount").Value;
                    }

                    orderEntity["gsc_ccaddons"] = new Money(ccAddOns);

                    #region Recalculate net price

                    SalesOrderHandler orderHandler = new SalesOrderHandler(_organizationService, _tracingService);
                    orderEntity["gsc_netprice"] = new Money(orderHandler.ComputeNetPrice(orderEntity));
                    orderEntity = orderHandler.ComputeVAT(orderEntity);

                    var paymentmode = orderEntity.Contains("gsc_paymentmode")
                        ? orderEntity.GetAttributeValue <OptionSetValue>("gsc_paymentmode").Value
                        : Decimal.Zero;
                    var amountfinanced = Decimal.Zero;

                    //Financing
                    if (paymentmode == 100000001 || (paymentmode == 100000002 && orderHandler.CheckifOrderHasDownPayment(orderEntity) == true))
                    {
                        amountfinanced = orderHandler.ComputeAmountFinanced(orderEntity);
                        orderEntity["gsc_amountfinanced"]      = new Money(amountfinanced);
                        orderEntity["gsc_totalamountfinanced"] = new Money(amountfinanced);
                    }

                    #endregion

                    if (ccAddOns >= 0)
                    {
                        _organizationService.Update(orderEntity);
                    }
                    else
                    {
                        _tracingService.Trace("CC add on is negative...");
                    }
                }
            }
            _tracingService.Trace("ending SetCCAddOnAmount Entity");
        }
Example #38
0
        public static XrmLeadResult CaptureLead(Dictionary <string, string> properties, IDictionary <string, string> settings, IDictionary <string, string> actions, CrmConnection connection = null)
        {
            XrmLeadResult result = new XrmLeadResult();
            bool          match  = Convert.ToBoolean(settings.GetValueOrDefault <string>("match", bool.FalseString));
            Entity        lead   = new Entity("lead", Guid.NewGuid());
            string        email  = properties.GetValueOrDefault <string>("emailaddress1", "");

            result.Email = email;

            string accountId = properties.GetValueOrDefault <string>("accountid", properties.GetValueOrDefault <string>("companyname", ""));
            Entity contact   = null;
            Entity account   = null;

            contact = XrmCore.RetrieveByAttribute("contact", "emailaddress1", email, CacheResults: false).Entities.OrderByDescending(x => x.GetAttributeValue <DateTime>("createdon")).FirstOrDefault();
            if (contact != null)
            {
                result.ContactId = contact.Id.ToString();
                result.FullName  = contact.GetAttributeValue <string>("fullname");
                if (contact.Contains("parentcustomerid"))
                {
                    EntityReference accountReference = contact.GetAttributeValue <EntityReference>("parentcustomerid");
                    result.AccountId        = accountReference.Id.ToString();
                    result.CompanyName      = accountReference.Name;
                    lead["parentaccountid"] = accountReference;
                }

                // return matched contact result
                return(result);
            }
            else
            {
                // No contact match. Match against an existing lead
                EntityCollection leadCollection = XrmCore.RetrieveByAttribute("lead", "emailaddress1", email, new Microsoft.Xrm.Sdk.Query.ColumnSet("createdon", "fullname", "parentcontactid", "parentaccountid", "companyname"), CacheResults: false);
                if (leadCollection.Entities.Count > 0)
                {
                    lead          = leadCollection.Entities.OrderByDescending(x => x.GetAttributeValue <DateTime>("createdon")).First();
                    result.LeadId = lead.Id.ToString();
                    if (lead.Contains("fullname"))
                    {
                        result.FullName = lead.GetAttributeValue <string>("fullname");
                    }
                    EntityReference er = null;
                    if (lead.Contains("parentaccountid"))
                    {
                        er = lead.GetAttributeValue <EntityReference>("parentaccountid");
                        Entity parentAccount = XrmCore.Retrieve("account", er.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet("statecode"));
                        if (parentAccount != null && parentAccount.GetAttributeValue <OptionSetValue>("statecode").Value == 0)
                        {
                            result.AccountId   = er.Id.ToString();
                            result.CompanyName = er.Name;
                        }
                    }
                    else if (lead.Contains("companyname"))
                    {
                        result.CompanyName = lead.GetAttributeValue <string>("companyname");
                    }
                    if (lead.Contains("parentcontactid"))
                    {
                        er = lead.GetAttributeValue <EntityReference>("parentcontactid");
                        Entity parentContact = XrmCore.Retrieve("contact", er.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet("statecode"));
                        if (parentContact != null && parentContact.GetAttributeValue <OptionSetValue>("statecode").Value == 0)
                        {
                            result.ContactId = er.Id.ToString();
                        }
                    }

                    // result matched lead result
                    return(result);
                }
            }

            //
            // No contact or lead match. Create a new lead in the system
            //
            if (!string.IsNullOrEmpty(accountId))
            {
                Guid g;
                if (Guid.TryParse(accountId, out g))
                {
                    account = XrmCore.Retrieve("account", g);
                }
                else
                {
                    account = XrmCore.RetrieveByAttribute("account", "name", accountId).Entities.OrderByDescending(x => x.GetAttributeValue <DateTime>("createdon")).FirstOrDefault();
                }

                if (account != null)
                {
                    lead["parentaccountid"] = account.ToEntityReference();
                    properties.Remove("accountid");
                    result.AccountId   = account.Id.ToString();
                    result.CompanyName = account.GetAttributeValue <string>("name");
                }
            }

            if (account == null)
            {
                result.CompanyName = properties.GetValueOrDefault <string>("companyname", "");
            }

            result.FullName = properties.GetValueOrDefault <string>("fullname", "");
            if (string.IsNullOrEmpty(result.FullName))
            {
                if (properties.ContainsKey("firstname") && properties.ContainsKey("lastname"))
                {
                    result.FullName = string.Concat(properties.GetValueOrDefault <string>("firstname", ""), " ", properties.GetValueOrDefault <string>("lastname", ""));
                }
            }

            // Apply properties
            EntityMetadata meta = XrmCore.RetrieveMetadata("lead", EntityFilters.All, connection);

            foreach (KeyValuePair <string, string> kv in properties)
            {
                lead.SetAttributeMetaValue(kv, settings, meta);
            }

            Guid Id = XrmCore.CreateEntity(lead);

            result.LeadId = Id.ToString();

            // Apply actions
            foreach (KeyValuePair <string, string> kv in actions)
            {
                lead.ApplyAction(kv);
            }

            return(result);
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));


            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));



            tracingService.Trace("Entered in R");

            if (context != null)
            {
                //tracingService.Trace(context)
            }
            if (context.Depth > 1)
            {
                tracingService.Trace("depth");
                return;
            }
            //Entity entity = context.PostEntityImages["PostImage"];
            if (context.PostEntityImages.Contains("PostImage") &&
                context.PostEntityImages["PostImage"] is Entity)
            {
                Entity entity = (Entity)context.PostEntityImages["PostImage"];
                if (entity.LogicalName != "poad_customaddress")
                {
                    return;
                }
                IOrganizationServiceFactory serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                try
                {
                    CrmDataHelper objHelper              = new CrmDataHelper();
                    Guid          accountId              = Guid.Empty;
                    Guid          contactid              = Guid.Empty;
                    Guid          addressId              = Guid.Empty;
                    int           addressNumber          = 0;
                    int           objectTypeCode         = 0;
                    bool          blnupdateaddressnumber = false;
                    Entity        customAddressObject;

                    if (entity.Contains(CustomAddressAttributes.poad_addressnumber) && entity[CustomAddressAttributes.poad_addressnumber] != null)
                    {
                        addressNumber = (int)entity[CustomAddressAttributes.poad_addressnumber];
                    }

                    if (entity.Contains(CustomAddressAttributes.poad_customerid) && entity[CustomAddressAttributes.poad_customerid] != null)
                    {
                        EntityReference customer = ((EntityReference)entity[CustomAddressAttributes.poad_customerid]);
                        if (customer.LogicalName == "contact")
                        {
                            objectTypeCode = 2;
                        }
                        else if (customer.LogicalName == "account")
                        {
                            objectTypeCode = 1;
                        }
                        addressId = objHelper.GetAddressId(service, addressNumber, customer.Id);
                        if (addressNumber == 0)
                        {
                            addressNumber          = objHelper.GetMaxAddressNumber(service, tracingService, customer.Id, objectTypeCode);
                            blnupdateaddressnumber = true;
                        }
                    }
                    //else if(entity.Contains(CustomAddressAttributes.poad_contactid) && entity[CustomAddressAttributes.poad_contactid] != null)
                    //{
                    //    objectTypeCode = 2;
                    //    contactid = ((EntityReference)entity[CustomAddressAttributes.poad_contactid]).Id;
                    //    addressId = objHelper.GetAddressId(service, addressNumber, contactid);
                    //    if (addressNumber == 0)
                    //    {
                    //        addressNumber = objHelper.GetMaxAddressNumber(service, tracingService, contactid, objectTypeCode);
                    //        blnupdateaddressnumber = true;
                    //    }
                    //}

                    tracingService.Trace("Object Type code" + objectTypeCode);
                    tracingService.Trace("ADdress number::" + addressNumber);
                    if (objectTypeCode != 1 && objectTypeCode != 2)
                    {
                        return;
                    }
                    if (addressNumber == 0)
                    {
                        return;
                    }
                    tracingService.Trace("message" + context.MessageName);


                    if (context.MessageName == "Create" || context.MessageName == "Update")
                    {
                        if (addressId == Guid.Empty)
                        {
                            customAddressObject = CreateAddressObject(entity, objectTypeCode, addressNumber);
                            service.Create(customAddressObject);
                        }
                        else
                        {
                            customAddressObject    = CreateAddressObject(entity, objectTypeCode, addressNumber);
                            customAddressObject.Id = addressId;
                            service.Update(customAddressObject);
                        }
                    }
                    if (context.MessageName == "Create" && blnupdateaddressnumber == true)
                    {
                        entity[CustomAddressAttributes.poad_addressnumber] = addressNumber;
                        service.Update(entity);
                    }
                }
                catch (Exception ex)
                {
                    tracingService.Trace("HandleCustom OOB Address: {0}", ex.ToString());
                    throw;
                }
                //catch (FaultException<OrganizationServiceFault> ex)
                //{
                //    throw new InvalidPluginExecutionException("An error occurred in HandleCustomAddress.", ex);
                //}
            }
        }
        /// <summary>
        /// Sets the state code for this instance.
        /// </summary>
        /// <param name="entity">The <c>Entity</c> to set the state code for.</param>
        protected void SetState(Entity entity)
        {
            if (entity != null && entity.Contains("statecode"))
            {
                if (!entity.Contains("statuscode"))
                {
                    entity["statuscode"] = new OptionSetValue(-1);
                }

                OrganizationRequest request = this.GetSetStateRequest(((OptionSetValue)entity["statecode"]).Value, ((OptionSetValue)entity["statuscode"]).Value, entity.Id);
                if (request != null)
                {
                    try
                    {
                        this.CallCrmExecuteWebMethod(request);
                    }
                    catch (AdapterException ae)
                    {
                        if (ae.ExceptionId == ErrorCodes.CrmPlatformException)
                        {
                            ae.ExceptionId = ErrorCodes.StateSettingError;
                        }

                        throw;
                    }
                }
            }
        }