コード例 #1
0
        private decimal ConvertPriceToBaseCurrency(decimal price)
        {
            try
            {
                if (TransactionCurrency.Equals(BaseCurrencyCode, StringComparison.CurrentCultureIgnoreCase))
                {
                    return(price);
                }

                var baseCurrency  = BasePage.CurrencyService.GetCurrencyByCode(BaseCurrencyCode);
                var orderCurrency = Order.Currency;

                var baseRate  = Convert.ToDecimal(baseCurrency.ConversionRate);
                var orderRate = Convert.ToDecimal(orderCurrency.ConversionRate);

                var convertedPrice = (baseRate * price) / orderRate;

                return(Math.Round(convertedPrice, 2));
            }
            catch (Exception ex)
            {
                BasePage.Log("ConvertPriceToBaseCurrency() breaks for price: " + price);
                return(price);
            }
        }
コード例 #2
0
        public void TestPrecisionSource()
        {
            using (var context = new Xrm(orgAdminUIService))
            {
                var currency = new TransactionCurrency()
                {
                    ExchangeRate      = 1m,
                    CurrencyPrecision = 3
                };
                currency.Id = orgAdminUIService.Create(currency);

                var bus = new dg_bus()
                {
                    dg_name               = "Woop",
                    dg_Ticketprice        = 10.1234m,
                    TransactionCurrencyId = currency.ToEntityReference()
                };
                bus.Id = orgAdminUIService.Create(bus);

                var retrieved = orgAdminUIService.Retrieve(dg_bus.EntityLogicalName, bus.Id, new ColumnSet(true)) as dg_bus;
                Assert.AreEqual(Math.Round(bus.dg_Ticketprice.Value, currency.CurrencyPrecision.Value), retrieved.dg_Ticketprice.Value);
                Assert.AreEqual(Math.Round(Math.Round(bus.dg_Ticketprice.Value, currency.CurrencyPrecision.Value) * 20, 2), retrieved.dg_Udregnet.Value);
                Assert.AreEqual(Math.Round(Math.Round(bus.dg_Ticketprice.Value, currency.CurrencyPrecision.Value) * 20, 1), retrieved.dg_EndnuUdregnet.Value);
            }
        }
コード例 #3
0
        public void TestUserCurrencyIsChosen()
        {
            using (var context = new Xrm(orgAdminUIService))
            {
                var currentUser = orgAdminUIService.Retrieve(SystemUser.EntityLogicalName, crm.AdminUser.Id, new ColumnSet(true)).ToEntity <SystemUser>();
                var currency    = new TransactionCurrency
                {
                    ExchangeRate      = 0.5m,
                    CurrencyPrecision = 3
                };
                currency.Id = orgAdminUIService.Create(currency);
                currentUser.TransactionCurrencyId = currency.ToEntityReference();
                orgAdminUIService.Update(currentUser);

                var bus = new dg_bus
                {
                    dg_Ticketprice = 10m
                };
                bus.Id = orgAdminUIService.Create(bus);

                var retrieved = orgAdminUIService.Retrieve(dg_bus.EntityLogicalName, bus.Id, new ColumnSet(true)) as dg_bus;
                Assert.Equal(currency.ToEntityReference(), retrieved.TransactionCurrencyId);

                bus.dg_Ticketprice = 20m;
                orgAdminUIService.Update(bus);
                retrieved = orgAdminUIService.Retrieve(dg_bus.EntityLogicalName, bus.Id, new ColumnSet(true)) as dg_bus;
                Assert.Equal(currency.ToEntityReference(), retrieved.TransactionCurrencyId);
            }
        }
コード例 #4
0
        /// <summary>
        /// Formats a transaction value for pretty printing (i.e. 470000 satoshis -> "0.00470000 BTC")
        /// </summary>
        /// <param name="currency">The currency in which the transaction is conducted.</param>
        /// <param name="value">The transaction value.</param>
        /// <returns>A pretty-printed string in the format of "[transaction value] [currency code]"</returns>
        public static string PrettyPrintedValue(this TransactionCurrency currency, long value)
        {
            long decimalPlaces = 0;

            switch (currency)
            {
            case TransactionCurrency.Bitcoin:
                decimalPlaces = 8;
                break;

            case TransactionCurrency.Monero:
                decimalPlaces = 12;
                break;

            default:
                throw new ArgumentException("No pretty printing information for unknown currency", nameof(currency));
            }

            long divisor = 1;

            for (int i = 0; i < decimalPlaces; ++i)
            {
                divisor *= 10;
            }

            return($"{value / divisor}.{(value % divisor).ToString($"D{decimalPlaces}")} {currency.GetCurrencyCode()}");
        }
コード例 #5
0
        private async Task UpdateExchangeRates(LocalPluginContext localcontext)
        {
            var currencyList = (from c in new XrmSvc(localcontext.OrganizationService)
                                .CreateQuery <TransactionCurrency>()
                                select new TransactionCurrency
            {
                CurrencySymbol = c.CurrencySymbol,
                TransactionCurrencyId = c.TransactionCurrencyId
            }).ToArray();

            var baseCurrency    = "EUR";
            var currentISOCodes = string.Join(",", currencyList
                                              .Select(x => x.CurrencySymbol)
                                              .Where(x => x != baseCurrency)
                                              .ToArray());

            using (HttpClient client = new HttpClient())
            {
                var webApiUrl = "http://data.fixer.io/api/latest?access_key=";
                var accessKey = "43eb1b0960d03281d3b0da30693df254&symbols=";
                var suffix    = "&format=1";

                var requestUri = new Uri(webApiUrl + accessKey + currentISOCodes + suffix);
                var request    = new HttpRequestMessage(HttpMethod.Get, requestUri);
                var response   = await client.SendAsync(request);

                if (!response.IsSuccessStatusCode)
                {
                    throw new InvalidPluginExecutionException("Exchangerate service returned: " + response);
                }

                var json    = response.Content.ReadAsStringAsync().Result;
                var setting = new DataContractJsonSerializerSettings()
                {
                    UseSimpleDictionaryFormat = true
                };
                ExchangeRateResult result = new ExchangeRateResult();

                using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
                {
                    var serializer = new DataContractJsonSerializer(typeof(ExchangeRateResult), setting);

                    result = (ExchangeRateResult)serializer.ReadObject(ms);
                }

                foreach (var currency in currencyList.Where(x => x.CurrencySymbol != baseCurrency))
                {
                    if (result.rates.Keys.Contains(currency.CurrencySymbol))
                    {
                        var update = new TransactionCurrency
                        {
                            TransactionCurrencyId = currency.TransactionCurrencyId,
                            ExchangeRate          = (decimal?)result.rates[currency.CurrencySymbol]
                        };

                        localcontext.OrganizationService.Update(update);
                    }
                }
            }
        }
コード例 #6
0
        public void LocalCrmDatabaseOrganizationServiceExecuteTests_InitializeFromRequest()
        {
            var service  = GetService();
            var currency = new TransactionCurrency();

            currency.Id = service.Create(currency);

            var lead = new LeadBuilder
            {
                Lead = new Lead
                {
                    Address1_Line2                 = "Test Address1_Line2",
                    Address1_Line3                 = "Test Address1_Line3",
                    Description                    = "Test Description",
                    Fax                            = "555-555-1234",
                    JobTitle                       = "Sales Agent",
                    LeadSourceCodeEnum             = Lead_LeadSourceCode.Advertisement,
                    PreferredContactMethodCodeEnum = Lead_PreferredContactMethodCode.Phone,
                    WebSiteUrl                     = "https://github.com/daryllabar/XrmUnitTest",
                    TransactionCurrencyId          = currency.ToEntityReference()
                }
            }
            .WithAddress1()
            .WithAddress2()
            .WithDoNotContact(false)
            .WithEmail()
            .WithName()
            .WithPhone()
            .Build();

            lead.Id = service.Create(lead);
            lead    = service.GetEntity <Lead>(lead.Id);

            var contact = service.InitializeFrom <Contact>(lead.ToEntityReference(), TargetFieldType.ValidForCreate);

            foreach (var attribute in lead.Attributes)
            {
                var key   = attribute.Key;
                var value = attribute.Value;
                switch (key)
                {
                case Lead.Fields.LeadId:
                    key   = Contact.Fields.OriginatingLeadId;
                    value = lead.ToEntityReference();
                    break;

                case Lead.Fields.CreatedOn:
                case Lead.Fields.CreatedBy:
                case Lead.Fields.ModifiedOn:
                case Lead.Fields.ModifiedBy:
                    Assert.IsFalse(contact.Contains(key));
                    continue;
                }

                Assert.IsTrue(
                    contact.Contains(key) && contact[key].Equals(value),
                    $"Field {attribute.Key} was not mapped correctly.");
            }
            service.Create(contact);
        }
コード例 #7
0
        internal static Transaction CreateFromDatabaseEntry(SQLiteDataReader reader)
        {
            TransactionCurrency currency = (TransactionCurrency)reader.GetInt32(2);
            Transaction         t        = new Transaction(currency);

            t.Id               = (ulong)reader.GetInt64(0);
            t.Status           = (TransactionStatus)reader.GetInt32(1);
            t.PaymentAmount    = reader.GetInt64(3);
            t.MinConfirmations = reader.GetInt32(4);

            if (!reader.IsDBNull(5))
            {
                t.Note = reader.GetString(5);
            }

            if (!reader.IsDBNull(6))
            {
                t.SuccessUrl = reader.GetString(6);
            }

            if (!reader.IsDBNull(7))
            {
                t.FailureUrl = reader.GetString(7);
            }

            return(t);
        }
コード例 #8
0
        public HttpResponseMessage UpdateTransactionCurrency(TransactionCurrency updatedRecord)
        {
            try
            {
                if (updatedRecord == null)
                {
                    return(new HttpResponseMessage(HttpStatusCode.BadRequest));
                }

                // Create the entity record in the Azure SQL DB:
                int updateResult = _transactionCurrencyWorker.UpdateCreate(updatedRecord);
                if (updateResult > 0)
                {
                    return(new HttpResponseMessage(HttpStatusCode.OK));
                }
                // Existed already:
                else if (updateResult == 0)
                {
                    return(new HttpResponseMessage(HttpStatusCode.OK));
                }

                return(new HttpResponseMessage(HttpStatusCode.OK));
            }
            catch (Exception e)
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }
        }
コード例 #9
0
ファイル: CurrencyHelper.cs プロジェクト: volkanytu/NEF
        public static TransactionCurrency GetBaseCurrency(string currencyName, SqlDataAccess sda)
        {
            TransactionCurrency returnValue = new TransactionCurrency();

            try
            {
                #region | SQL QUERY |
                string query = @"SELECT
		                            o.BaseCurrencyId AS Id
		                            ,o.BaseCurrencyIdName Name
	                            FROM
		                            Organization AS o"        ;
                #endregion

                DataTable dt = sda.getDataTable(query);

                if (dt != null && dt.Rows.Count > 0)
                {
                    #region | GET CURRENCY |

                    returnValue.TransactionCurrencyId = (Guid)dt.Rows[0]["Id"];
                    returnValue.Name = dt.Rows[0]["CurrencyName"] != DBNull.Value ? dt.Rows[0]["Name"].ToString() : string.Empty;

                    #endregion
                }
            }
            catch (Exception ex)
            {
            }

            return(returnValue);
        }
コード例 #10
0
        private EntityReference ToTransactionCurrency(string p, decimal?value)
        {
            using (var orgContext = new OrganizationServiceContext(this.service))
            {
                if (p == "USD")
                {
                    return((from i in orgContext.CreateQuery <TransactionCurrency>()
                            where i.ISOCurrencyCode == p
                            select i).FirstOrDefault().ToEntityReference());
                }
                var TransactionCurrencyId = (from i in orgContext.CreateQuery <TransactionCurrency>()
                                             where i.ISOCurrencyCode == p
                                             select i.Id).FirstOrDefault();

                TransactionCurrency entityForUpdate = new TransactionCurrency()
                {
                    Id           = TransactionCurrencyId,
                    LogicalName  = TransactionCurrency.EntityLogicalName,
                    ExchangeRate = value
                };

                service.Update(entityForUpdate);
                return(entityForUpdate.ToEntityReference());
            }
        }
コード例 #11
0
        public void TestExchangeRate()
        {
            using (var context = new Xrm(orgAdminUIService))
            {
                var dollar = new TransactionCurrency
                {
                    ExchangeRate      = 0.6m,
                    CurrencyPrecision = 3
                };
                var dollarId = orgAdminUIService.Create(dollar);
                dollar.Id = dollarId;


                var bus = new dg_bus
                {
                    dg_Ticketprice        = 10m,
                    TransactionCurrencyId = dollar.ToEntityReference()
                };
                var busId = orgAdminUIService.Create(bus);

                var retrieved = orgAdminUIService.Retrieve(dg_bus.EntityLogicalName, busId, new ColumnSet(true)) as dg_bus;
                Assert.IsTrue(retrieved.dg_ticketprice_Base.HasValue);
                Assert.AreEqual(Math.Round(bus.dg_Ticketprice.Value / dollar.ExchangeRate.Value, dollar.CurrencyPrecision.Value), retrieved.dg_ticketprice_Base.Value);
            }
        }
コード例 #12
0
        /// <summary>
        /// If it is a new expense, set by default:
        /// 1. Today as Transaction date.
        /// 2. Draft as status
        /// 3. First available category
        /// 4. First available currency
        /// </summary>
        public void SetDefaultsValues()
        {
            if (Expense.Id == Guid.Empty && Expense.CanEdit())
            {
                // Default transaction date to today
                Expense.msdyn_TransactionDate_utc = Expense.msdyn_TransactionDate_utc ?? DateTime.Today;

                // Default status to Draft
                Expense.msdyn_ExpenseStatus = Expense.msdyn_ExpenseStatus ?? new OptionSetValue((int)msdyn_expense_msdyn_expensestatus.Draft);

                // Default category to the first available one
                if (Expense.msdyn_ExpenseCategory == null)
                {
                    msdyn_expensecategory expenseCategory = this.GetDefaultData <msdyn_expensecategory>();
                    if (expenseCategory != null)
                    {
                        EntityReference newReference = new EntityReference(expenseCategory.LogicalName, expenseCategory.Id);
                        newReference.Name             = expenseCategory.Preview;
                        Expense.msdyn_ExpenseCategory = newReference;
                    }
                }

                // Default transaction currency to the first available one.
                if (Expense.TransactionCurrency == null || Expense.TransactionCurrency.Id == Guid.Empty)
                {
                    TransactionCurrency transactionCurrency = this.GetDefaultData <TransactionCurrency>();
                    if (transactionCurrency != null)
                    {
                        Expense.TransactionCurrency = transactionCurrency;
                    }
                }
            }
        }
コード例 #13
0
        private Transaction(TransactionCurrency currency)
        {
            TransactionLock  = new object();
            Currency         = currency;
            AssociatedDaemon = MainApplication.Instance.GetDaemonForCurrency(currency);

            if (AssociatedDaemon == null)
            {
                throw new InvalidOperationException("Cannot create a transaction for a cryptocurrency which daemon is not running.");
            }
        }
コード例 #14
0
        /// <summary>
        /// Retrieves a three- or four-letter currency code (ex. "BTC", "XMR") for a given cryptocurrency.
        /// </summary>
        public static string GetCurrencyCode(this TransactionCurrency currency)
        {
            switch (currency)
            {
            case TransactionCurrency.Bitcoin:
                return("BTC");

            case TransactionCurrency.Monero:
                return("XMR");
            }

            throw new ArgumentException("No currency code for unknown currency", nameof(currency));
        }
コード例 #15
0
        /// <summary>
        /// Retrieves the number of confirmations a transaction should have to be deemed confirmed.
        /// </summary>
        public static int GetDefaultConfirmationCount(this TransactionCurrency currency)
        {
            switch (currency)
            {
            case TransactionCurrency.Bitcoin:
                return(1);

            case TransactionCurrency.Monero:
                return(5);
            }

            throw new ArgumentException("No data for default confirmation threshold for unknown currency", nameof(currency));
        }
コード例 #16
0
        private async Task UpdateExchangRates(LocalPluginContext localcontext)
        {
            var currencyList = (from c in new XrmSvc(localcontext.OrganizationService).CreateQuery <TransactionCurrency>()
                                select new TransactionCurrency
            {
                CurrencySymbol = c.CurrencySymbol,
                TransactionCurrencyId = c.TransactionCurrencyId
            }).ToArray();

            var baseCurrency     = "EUR";
            var currencyISOCodes = string.Join(",", currencyList.Select(c => c.CurrencySymbol).Where(c => c != baseCurrency).ToArray());

            using (HttpClient client = new HttpClient())
            {
                //Try this API https://free.currconv.com/api/v7/convert?q=USD_PHP&compact=ultra&apiKey=705271941c489685a770
                var requestUri = new Uri("https://api.fixer.io/latest?symbols=" + String.Join(",", currencyISOCodes));
                var request    = new HttpRequestMessage(HttpMethod.Get, requestUri);
                var response   = await client.SendAsync(request);

                if (!response.IsSuccessStatusCode)
                {
                    throw new InvalidPluginExecutionException("Exchangerate service returned " + response);
                }

                var json    = response.Content.ReadAsStringAsync().Result;
                var setting = new DataContractJsonSerializerSettings()
                {
                    UseSimpleDictionaryFormat = true
                };

                ExchangeRateResult result = null;
                using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
                {
                    var serializer = new DataContractJsonSerializer(typeof(ExchangeRateResult), setting);
                    result = (ExchangeRateResult)serializer.ReadObject(ms);
                }

                foreach (var currency in currencyList.Where(c => c.CurrencySymbol != baseCurrency))
                {
                    if (result.Rates.Keys.Contains(currency.CurrencySymbol))
                    {
                        var update = new TransactionCurrency
                        {
                            TransactionCurrencyId = currency.TransactionCurrencyId,
                            ExchangeRate          = (decimal?)result.Rates[currency.CurrencySymbol]
                        };
                        localcontext.OrganizationService.Update(update);
                    }
                }
            }
        }
コード例 #17
0
        //private static string GetOrganizations(string DiscoverServiceURL, string UserName, string Password)
        //{
        //    ClientCredentials credentials = new ClientCredentials();
        //    credentials.UserName.UserName = UserName;
        //    credentials.UserName.Password = Password;

        //    using (var discoveryProxy = new DiscoveryServiceProxy(new Uri(DiscoverServiceURL), null, credentials, null))
        //    {
        //        discoveryProxy.Authenticate();

        //        // Get all Organizations using Discovery Service

        //        RetrieveOrganizationsRequest retrieveOrganizationsRequest = new RetrieveOrganizationsRequest()
        //        {
        //            AccessType = EndpointAccessType.Default,
        //            Release = OrganizationRelease.Current
        //        };

        //        RetrieveOrganizationsResponse retrieveOrganizationsResponse =
        //        (RetrieveOrganizationsResponse)discoveryProxy.Execute(retrieveOrganizationsRequest);

        //        if (retrieveOrganizationsResponse.Details.Count > 0)
        //        {
        //            //var orgs = new List<String>();
        //            foreach (OrganizationDetail orgInfo in retrieveOrganizationsResponse.Details)
        //                //orgs.Add(orgInfo.FriendlyName);
        //                return orgInfo.FriendlyName;

        //            //return orgs;
        //        }
        //        else
        //            return null;
        //    }
        //}
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            Console.WriteLine("  Creating currency 'Canadian Dollar'");
            // Create another currency
            _currency = new TransactionCurrency()
            {
                CurrencyName      = "Canadian Dollar",
                CurrencyPrecision = 2,
                ExchangeRate      = (decimal)0.9755,
                ISOCurrencyCode   = "CAD", // Canadian Dollar currency code
                CurrencySymbol    = "$"
            };
            _currency.Id = service.Create(_currency);
        }
コード例 #18
0
        public async Task <bool> OnCurrencySelected(string selectedItemKey, int selectedItemIndex)
        {
            TransactionCurrency selectedCurrency = this.GetObjectByName <TransactionCurrency>(selectedItemKey);

            if (selectedCurrency != null)
            {
                if (Expense.TransactionCurrency == null || selectedCurrency.Id != Expense.TransactionCurrency.Id)
                {
                    Expense.TransactionCurrency = selectedCurrency;
                }
                return(true);
            }
            return(false);
        }
コード例 #19
0
        public void TestRetrieveExchangeRate()
        {
            using (var context = new Xrm(orgAdminUIService))
            {
                var dollar = new TransactionCurrency
                {
                    ExchangeRate = 0.6m
                };
                dollar.Id = orgAdminUIService.Create(dollar);

                var request = new RetrieveExchangeRateRequest
                {
                    TransactionCurrencyId = dollar.Id
                };
                var response = orgAdminUIService.Execute(request) as RetrieveExchangeRateResponse;
                Assert.Equal(dollar.ExchangeRate, response.ExchangeRate);
            }
        }
コード例 #20
0
        public void TestExchangeIsSet()
        {
            using (var context = new Xrm(orgAdminUIService)) {
                var dollar = new TransactionCurrency();
                dollar.ExchangeRate      = 0.6m;
                dollar.CurrencyPrecision = 3;
                var dollarId = orgAdminUIService.Create(dollar);
                dollar.Id = dollarId;


                var bus = new dg_bus();
                bus.dg_Ticketprice        = 10m;
                bus.TransactionCurrencyId = dollar.ToEntityReference();
                var busId = orgAdminUIService.Create(bus);

                var retrieved = orgAdminUIService.Retrieve(dg_bus.EntityLogicalName, busId, new ColumnSet(true)) as dg_bus;
                Assert.IsTrue(retrieved.ExchangeRate.HasValue);
                Assert.AreEqual(dollar.ExchangeRate, retrieved.ExchangeRate);
            }
        }
コード例 #21
0
        public static Transaction CreateNewTransaction(TransactionCurrency currency, long paymentAmount, int minConfirmations = int.MaxValue, string note = null, string successUrl = null, string failureUrl = null)
        {
            DBConnection db = MainApplication.Instance.DBConnection;
            Transaction  t  = new Transaction(currency);

            lock (IdLock)
            {
                do
                {
                    t.Id = GetNewTransactionId();
                } while (t.Id == 0 || pendingIDs.Contains(t.Id) || db.IsIDUsed(t.Id));

                pendingIDs.Add(t.Id);
            }

            t.PaymentAmount = paymentAmount;
            t.Status        = TransactionStatus.Pending;

            if (minConfirmations == int.MaxValue)
            {
                t.MinConfirmations = currency.GetDefaultConfirmationCount();
            }
            else
            {
                t.MinConfirmations = minConfirmations;
            }

            t.Note       = note;
            t.SuccessUrl = successUrl;
            t.FailureUrl = failureUrl;

            db.CreateNewTransaction(t);

            lock (IdLock)
            {
                pendingIDs.Remove(t.Id);
            }

            Logger.Log("Transactions", $"Created a new transaction for {currency.PrettyPrintedValue(t.PaymentAmount)} with ID {t.Id}");
            return(t);
        }
コード例 #22
0
ファイル: CurrencyHelper.cs プロジェクト: volkanytu/NEF
        public static TransactionCurrency GetCurrencyByName(string currencyName, SqlDataAccess sda)
        {
            TransactionCurrency returnValue = new TransactionCurrency();

            try
            {
                #region | SQL QUERY |
                string query = @"SELECT
	                                TC.TransactionCurrencyId
	                                ,TC.CurrencyName
                                FROM
	                                TransactionCurrency TC
                                WHERE
	                                TC.CurrencyName = '{0}'
                                ORDER BY
	                                TC.CurrencyName ASC"    ;
                #endregion

                DataTable dt = sda.getDataTable(string.Format(query, currencyName));

                if (dt != null && dt.Rows.Count > 0)
                {
                    #region | GET CURRENCY |

                    returnValue.TransactionCurrencyId = (Guid)dt.Rows[0]["TransactionCurrencyId"];
                    returnValue.Name = dt.Rows[0]["CurrencyName"] != DBNull.Value ? dt.Rows[0]["CurrencyName"].ToString() : string.Empty;

                    #endregion
                }
            }
            catch (Exception ex)
            {
            }

            return(returnValue);
        }
コード例 #23
0
        private EntityReference ToTransactionCurrency(string p, decimal? value)
        {
            using (var orgContext = new OrganizationServiceContext(this.service))
            {
                if (p == "USD")
                {
                    return (from i in orgContext.CreateQuery<TransactionCurrency>()
                            where i.ISOCurrencyCode == p
                            select i).FirstOrDefault().ToEntityReference();
                }
                var TransactionCurrencyId = (from i in orgContext.CreateQuery<TransactionCurrency>()
                                             where i.ISOCurrencyCode == p
                                             select i.Id).FirstOrDefault();

                TransactionCurrency entityForUpdate = new TransactionCurrency()
                {
                    Id = TransactionCurrencyId,
                    LogicalName = TransactionCurrency.EntityLogicalName,
                    ExchangeRate = value
                };

                service.Update(entityForUpdate);
                return entityForUpdate.ToEntityReference();
            }
        }
コード例 #24
0
 public void CreateRequiredRecords()
 {
     Console.WriteLine("  Creating currency 'Canadian Dollar'");
     // Create another currency
     _currency = new TransactionCurrency()
     {
         CurrencyName = "Canadian Dollar",
         CurrencyPrecision = 2,
         ExchangeRate = (decimal)0.9755,
         ISOCurrencyCode = "CAD", // Canadian Dollar currency code
         CurrencySymbol = "$"
     };
     _currency.Id = _serviceProxy.Create(_currency);
 }
コード例 #25
0
        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
            }

            tracingService.Trace("Entered UpdateFXs.Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                                 executionContext.ActivityInstanceId,
                                 executionContext.WorkflowInstanceId);

            // Create the context
            IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>();

            if (context == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
            }

            tracingService.Trace("UpdateFXs.Execute(), Correlation Id: {0}, Initiating User: {1}",
                                 context.CorrelationId,
                                 context.InitiatingUserId);

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            string serviceBaseCurrency = "RUB";

            using (var ctx = new OrganizationServiceContext(service))
            {
                try
                {
                    // Get exchange rates

                    DailyInfo client = new DailyInfo();
                    tracingService.Trace("Getting Most recent date available");
                    DateTime lastestDate = client.GetLatestDateTime();
                    tracingService.Trace("Getting FX Rates");
                    var exchangeRates = client.GetCursOnDateXML(lastestDate);



                    string baseCurrencyISO = string.Empty;
                    Guid   empty           = Guid.Empty;

                    var baseCurrency = (from c in ctx.CreateQuery <TransactionCurrency>()
                                        join o in ctx.CreateQuery <Organization>()
                                        on c.TransactionCurrencyId equals o.BaseCurrencyId.Id
                                        select new TransactionCurrency
                    {
                        TransactionCurrencyId = c.TransactionCurrencyId,
                        ISOCurrencyCode = c.ISOCurrencyCode,
                    }).FirstOrDefault();



                    if (baseCurrency != null)
                    {
                        baseCurrencyISO = baseCurrency.ISOCurrencyCode.ToUpper();

                        // Get the rate from service base rate to crm base currency
                        var serviceRateToCrmBase = GetExchangeRate(baseCurrencyISO, exchangeRates);
                        if (serviceRateToCrmBase == null)
                        {
                            throw new Exception(String.Format("Cannot find rate for base rate '{0}'", baseCurrencyISO));
                        }

                        // Get the currencies that are not the base currency
                        // Only update active currencies
                        var currencies = (from c in ctx.CreateQuery <TransactionCurrency>()
                                          where c.TransactionCurrencyId != baseCurrency.TransactionCurrencyId &&
                                          c.StateCode == TransactionCurrencyState.Active
                                          select new TransactionCurrency
                        {
                            TransactionCurrencyId = c.TransactionCurrencyId,
                            ISOCurrencyCode = c.ISOCurrencyCode,
                        });



                        foreach (TransactionCurrency currency in currencies)
                        {
                            string  isoCode    = currency.ISOCurrencyCode.ToUpper();
                            decimal?latestRate = null;

                            // Get rate from service base currency to this currency
                            decimal?serviceRate = 1;
                            if (isoCode != serviceBaseCurrency)
                            {
                                serviceRate = GetExchangeRate(isoCode, exchangeRates);
                            }


                            if (serviceRate != null)
                            {
                                // Get the rate from crm base rate
                                latestRate = serviceRateToCrmBase / serviceRate;
                            }
                            else
                            {
                                // The webserviceX currency service is no longer working - investigating alternatives
                                // latestRate = GetStandardRate(baseCurrencyISO, isoCode);
                            }


                            if (latestRate != null)
                            {
                                // We have a new rate so update it (even if it is the same!)
                                TransactionCurrency update = new TransactionCurrency();
                                update.TransactionCurrencyId = currency.TransactionCurrencyId;
                                update.ExchangeRate          = latestRate;
                                service.Update(update);
                            }
                        }
                    }
                }
                catch (FaultException <OrganizationServiceFault> e)
                {
                    tracingService.Trace("Exception: {0}", e.ToString());

                    // Handle the exception.
                    throw;
                }
                catch (Exception ex)
                {
                    tracingService.Trace("Exception (will retry): {0}", ex.ToString());
                    // All exceptions must be retried since this workflow must call it's self to run on a daily basis
                    OrganizationServiceFault fault = new OrganizationServiceFault();
                    fault.ErrorCode = -2147204346; // This will cause the Async Server to retry up to 10 times before failing
                    fault.Message   = ex.ToString();
                    var networkException = new FaultException <OrganizationServiceFault>(fault);
                    throw networkException;
                }
            }
            tracingService.Trace("Exiting UpdateFXs.Execute(), Correlation Id: {0}", context.CorrelationId);
        }
コード例 #26
0
        public static MsCrmResult Process()
        {
            MsCrmResult returnValue = new MsCrmResult();

            try
            {
                service = MSCRM.GetOrgService(true);

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

                XElement   CurrencyRate = XElement.Load("http://www.tcmb.gov.tr/kurlar/today.xml");
                string     currentDate  = DateTime.Now.ToShortDateString();
                XAttribute dateRate     = (from p in CurrencyRate.Attributes()
                                           where p.Name.LocalName == "Tarih"
                                           select p).Single();

                if (string.Format("dd/MM/yyyy", dateRate.Value) == string.Format("dd/MM/yyyy", currentDate))
                {
                    #region | USD |
                    XElement dollar = (from p in CurrencyRate.Elements()
                                       where p.Attribute("CurrencyCode").Value == "USD"
                                       select p).Single();

                    ExchangeRate erDollar = new ExchangeRate();
                    erDollar.BuyRate  = Convert.ToDecimal(dollar.Element("BanknoteBuying").Value.Replace('.', ','));
                    erDollar.SaleRate = Convert.ToDecimal(dollar.Element("BanknoteSelling").Value.Replace('.', ','));
                    erDollar.RateDate = DateTime.Now.Date;

                    TransactionCurrency currUsd = CurrencyHelper.GetCurrencyByName("USD", sda);

                    erDollar.Currency = new EntityReference()
                    {
                        Id          = currUsd.TransactionCurrencyId,
                        Name        = "US Dollar",
                        LogicalName = "transactioncurrency"
                    };

                    MsCrmResultObject resultDollar = CurrencyHelper.GetExchangeRateByCurrency(DateTime.Now, erDollar.Currency.Id, sda);

                    if (resultDollar.Success)
                    {
                        #region | TOMORROW |
                        erDollar.RateDate = erDollar.RateDate.AddDays(1);
                        CurrencyHelper.CreateOrUpdateExchangeRate(erDollar, service);

                        #endregion

                        #region | UPDATE TODAY |
                        ExchangeRate eRateDollar = (ExchangeRate)resultDollar.ReturnObject;
                        erDollar.Id = eRateDollar.Id;

                        erDollar.RateDate = erDollar.RateDate.AddDays(-1);
                        CurrencyHelper.CreateOrUpdateExchangeRate(erDollar, service);

                        #endregion
                    }
                    else
                    {
                        #region | CREATE TODAY |
                        CurrencyHelper.CreateOrUpdateExchangeRate(erDollar, service);

                        #endregion

                        #region | TOMORROW |
                        erDollar.RateDate = erDollar.RateDate.AddDays(1);
                        CurrencyHelper.CreateOrUpdateExchangeRate(erDollar, service);

                        #endregion
                    }

                    #endregion

                    #region | EUR |
                    XElement euro = (from p in CurrencyRate.Elements()
                                     where p.Attribute("CurrencyCode").Value == "EUR"
                                     select p).Single();

                    ExchangeRate erEuro = new ExchangeRate();
                    erEuro.BuyRate  = Convert.ToDecimal(euro.Element("BanknoteBuying").Value.Replace('.', ','));
                    erEuro.SaleRate = Convert.ToDecimal(euro.Element("BanknoteSelling").Value.Replace('.', ','));
                    erEuro.RateDate = DateTime.Now.Date;

                    TransactionCurrency currEur = CurrencyHelper.GetCurrencyByName("Euro", sda);

                    erEuro.Currency = new EntityReference()
                    {
                        Id          = currEur.TransactionCurrencyId,
                        Name        = "Euro",
                        LogicalName = "transactioncurrency"
                    };

                    MsCrmResultObject resultEuro = CurrencyHelper.GetExchangeRateByCurrency(DateTime.Now, erEuro.Currency.Id, sda);

                    if (resultEuro.Success)
                    {
                        #region | TOMORROW |
                        erEuro.RateDate = erEuro.RateDate.AddDays(1);
                        CurrencyHelper.CreateOrUpdateExchangeRate(erEuro, service);

                        #endregion

                        #region | UPDATE TODAY |
                        ExchangeRate eRateEuro = (ExchangeRate)resultEuro.ReturnObject;
                        erEuro.Id = eRateEuro.Id;

                        erEuro.RateDate = erEuro.RateDate.AddDays(-1);
                        CurrencyHelper.CreateOrUpdateExchangeRate(erEuro, service);

                        #endregion
                    }
                    else
                    {
                        #region | CREATE TODAY |
                        CurrencyHelper.CreateOrUpdateExchangeRate(erEuro, service);

                        #endregion

                        #region | TOMORROW |
                        erEuro.RateDate = erEuro.RateDate.AddDays(1);
                        CurrencyHelper.CreateOrUpdateExchangeRate(erEuro, service);

                        #endregion
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                returnValue.Result = ex.Message;
            }
            finally
            {
                if (sda != null)
                {
                    sda.closeConnection();
                }
            }

            return(returnValue);
        }
コード例 #27
0
        public void TestRollUp()
        {
            using (var context = new Xrm(orgAdminUIService))
            {
                var childlessBus = new dg_bus()
                {
                    dg_name = "Buu"
                };
                childlessBus.Id = orgAdminUIService.Create(childlessBus);

                var retrieved = orgAdminUIService.Retrieve(dg_bus.EntityLogicalName, childlessBus.Id, new ColumnSet(true)) as dg_bus;
                Assert.IsNull(retrieved.dg_Totalallowance);

                childlessBus.dg_name = "Woop";
                orgAdminUIService.Update(childlessBus);

                retrieved = orgAdminUIService.Retrieve(dg_bus.EntityLogicalName, childlessBus.Id, new ColumnSet(true)) as dg_bus;
                Assert.IsNull(retrieved.dg_Totalallowance);

                var bus = new dg_bus {
                    dg_name = "Woop"
                };
                bus.Id = orgAdminUIService.Create(bus);

                orgAdminUIService.Create(
                    new dg_child()
                {
                    dg_name      = "Hans Jørgen",
                    dg_Allowance = 20,
                    dg_Skolebus  = new EntityReference
                    {
                        Id          = bus.Id,
                        LogicalName = dg_bus.EntityLogicalName
                    }
                });

                orgAdminUIService.Create(
                    new dg_child()
                {
                    dg_name      = "Hans Gert",
                    dg_Allowance = 50,
                    dg_Skolebus  = new EntityReference
                    {
                        Id          = bus.Id,
                        LogicalName = dg_bus.EntityLogicalName
                    }
                });

                var anotherCurrency = new TransactionCurrency()
                {
                    ExchangeRate      = 0.5m,
                    CurrencyPrecision = 2
                };
                anotherCurrency.Id = orgAdminUIService.Create(anotherCurrency);

                orgAdminUIService.Create(
                    new dg_child()
                {
                    dg_name      = "Børge Hansen",
                    dg_Allowance = 30,
                    dg_Skolebus  = new EntityReference
                    {
                        Id          = bus.Id,
                        LogicalName = dg_bus.EntityLogicalName
                    },
                    TransactionCurrencyId = anotherCurrency.ToEntityReference()
                });

                retrieved = orgAdminUIService.Retrieve(dg_bus.EntityLogicalName, bus.Id, new ColumnSet(true)) as dg_bus;
                Assert.IsNull(retrieved.dg_Totalallowance);
                Assert.IsNull(retrieved.dg_MaxAllowance);
                Assert.IsNull(retrieved.dg_MinAllowance);
                Assert.IsNull(retrieved.dg_AvgAllowance);

                var req = new CalculateRollupFieldRequest()
                {
                    FieldName = "dg_totalallowance",
                    Target    = bus.ToEntityReference()
                };
                orgAdminUIService.Execute(req);

                retrieved = orgAdminUIService.Retrieve(dg_bus.EntityLogicalName, bus.Id, new ColumnSet(true)) as dg_bus;
                Assert.AreEqual(130, retrieved.dg_Totalallowance);
                Assert.IsNull(retrieved.dg_MaxAllowance);
                Assert.IsNull(retrieved.dg_MinAllowance);
                Assert.IsNull(retrieved.dg_AvgAllowance);

                req.FieldName = "dg_maxallowance";
                orgAdminUIService.Execute(req);

                retrieved = orgAdminUIService.Retrieve(dg_bus.EntityLogicalName, bus.Id, new ColumnSet(true)) as dg_bus;
                Assert.AreEqual(130, retrieved.dg_Totalallowance);
                Assert.AreEqual(60, retrieved.dg_MaxAllowance);
                Assert.IsNull(retrieved.dg_MinAllowance);
                Assert.IsNull(retrieved.dg_AvgAllowance);

                req.FieldName = "dg_minallowance";
                orgAdminUIService.Execute(req);

                retrieved = orgAdminUIService.Retrieve(dg_bus.EntityLogicalName, bus.Id, new ColumnSet(true)) as dg_bus;
                Assert.AreEqual(130, retrieved.dg_Totalallowance);
                Assert.AreEqual(60, retrieved.dg_MaxAllowance);
                Assert.AreEqual(20, retrieved.dg_MinAllowance);
                Assert.IsNull(retrieved.dg_AvgAllowance);

                req.FieldName = "dg_avgallowance";
                orgAdminUIService.Execute(req);

                retrieved = orgAdminUIService.Retrieve(dg_bus.EntityLogicalName, bus.Id, new ColumnSet(true)) as dg_bus;
                Assert.AreEqual(130, retrieved.dg_Totalallowance.Value);
                Assert.AreEqual(60, retrieved.dg_MaxAllowance.Value);
                Assert.AreEqual(20, retrieved.dg_MinAllowance.Value);
                Assert.AreEqual(43.33m, retrieved.dg_AvgAllowance.Value);
            }
        }
コード例 #28
0
 public ICryptoDaemon GetDaemonForCurrency(TransactionCurrency currency)
 {
     return(CryptoDaemons.GetValueOrDefault(currency));
 }
コード例 #29
0
        public void TestBasesGetUpdated()
        {
            using (var context = new Xrm(orgAdminUIService))
            {
                var currency = new TransactionCurrency()
                {
                    ExchangeRate      = 0.5m,
                    CurrencyPrecision = 2
                };
                currency.Id = orgAdminUIService.Create(currency);

                // test currency gets set
                var bus = new dg_bus
                {
                    TransactionCurrencyId = currency.ToEntityReference()
                };
                bus.Id = orgAdminUIService.Create(bus);

                var retrieved = orgAdminUIService.Retrieve(dg_bus.EntityLogicalName, bus.Id, new ColumnSet(true)) as dg_bus;
                Assert.Equal(bus.TransactionCurrencyId, retrieved.TransactionCurrencyId);

                // test base value gets updated
                bus.dg_Ticketprice = 100m;
                orgAdminUIService.Update(bus);

                retrieved = orgAdminUIService.Retrieve(dg_bus.EntityLogicalName, bus.Id, new ColumnSet(true)) as dg_bus;
                Assert.Equal(Math.Round(bus.dg_Ticketprice.Value / currency.ExchangeRate.Value, currency.CurrencyPrecision.Value), retrieved.dg_ticketprice_Base);

                // test currency doesn't update before record gets updated
                var oldExchangeRate = currency.ExchangeRate;
                currency.ExchangeRate = 0.7m;
                orgAdminUIService.Update(currency);

                retrieved = orgAdminUIService.Retrieve(dg_bus.EntityLogicalName, bus.Id, new ColumnSet(true)) as dg_bus;
                Assert.Equal(Math.Round(bus.dg_Ticketprice.Value / oldExchangeRate.Value, currency.CurrencyPrecision.Value), retrieved.dg_ticketprice_Base);

                // test base value gets updated when record field value changes
                bus.dg_Ticketprice = 120m;
                orgAdminUIService.Update(bus);

                retrieved = orgAdminUIService.Retrieve(dg_bus.EntityLogicalName, bus.Id, new ColumnSet(true)) as dg_bus;
                Assert.Equal(Math.Round(bus.dg_Ticketprice.Value / currency.ExchangeRate.Value, currency.CurrencyPrecision.Value), retrieved.dg_ticketprice_Base);

                // test base value gets updated when transactioncurrencyid changes
                var newCurrency = new TransactionCurrency
                {
                    ExchangeRate      = 1m,
                    CurrencyPrecision = 3
                };
                newCurrency.Id = orgAdminUIService.Create(newCurrency);

                retrieved = orgAdminUIService.Retrieve(dg_bus.EntityLogicalName, bus.Id, new ColumnSet(true)) as dg_bus;
                Assert.Equal(Math.Round(bus.dg_Ticketprice.Value / currency.ExchangeRate.Value, currency.CurrencyPrecision.Value), retrieved.dg_ticketprice_Base);

                bus.TransactionCurrencyId = newCurrency.ToEntityReference();
                orgAdminUIService.Update(bus);

                retrieved = orgAdminUIService.Retrieve(dg_bus.EntityLogicalName, bus.Id, new ColumnSet(true)) as dg_bus;
                Assert.Equal(Math.Round(bus.dg_Ticketprice.Value / newCurrency.ExchangeRate.Value, newCurrency.CurrencyPrecision.Value), retrieved.dg_ticketprice_Base);

                // test base value gets updated when state of record changes
                oldExchangeRate          = newCurrency.ExchangeRate;
                newCurrency.ExchangeRate = 0.3m;
                orgAdminUIService.Update(newCurrency);

                retrieved = orgAdminUIService.Retrieve(dg_bus.EntityLogicalName, bus.Id, new ColumnSet(true)) as dg_bus;
                Assert.Equal(Math.Round(bus.dg_Ticketprice.Value / oldExchangeRate.Value, newCurrency.CurrencyPrecision.Value), retrieved.dg_ticketprice_Base);

                bus.SetState(orgAdminUIService, dg_busState.Inactive);

                retrieved = orgAdminUIService.Retrieve(dg_bus.EntityLogicalName, bus.Id, new ColumnSet(true)) as dg_bus;
                Assert.Equal(Math.Round(bus.dg_Ticketprice.Value / newCurrency.ExchangeRate.Value, newCurrency.CurrencyPrecision.Value), retrieved.dg_ticketprice_Base);
            }
        }
コード例 #30
0
ファイル: ProcessRecords.cs プロジェクト: volkanytu/NEF
        private static void SetPayment(DataRow dr, Guid quoteId, int customerIdType, Guid customerId, Guid financialAccount, IOrganizationService service)
        {
            string        paymentType  = Convert.ToString(dr["Ödeme Tipi"]);
            string        currencyType = Convert.ToString(dr["ParaBirimi"]);
            SqlDataAccess sda          = new SqlDataAccess();

            sda.openConnection(Globals.ConnectionString);
            Payment payment = new Payment();

            payment.PaymentAmount = Convert.ToDecimal(dr["Tutar"]);
            switch (paymentType)
            {
            case "Banka Kredisi":    //Banka Ödemesi
                payment.PaymentType            = PaymentTypes.BankaOdemesi;
                payment.PaymentAccountingTypes = PaymentAccountingTypes.MusteriPesinat_BankaKredisi;
                break;

            case "Peşinat":    //Pesin Odeme
                payment.PaymentType            = PaymentTypes.PesinOdeme;
                payment.PaymentAccountingTypes = PaymentAccountingTypes.MusteriPesinat_Nakit;
                break;

            case "Taksit":    //Düzenli taksit
                payment.PaymentType            = PaymentTypes.DuzenliTaksit;
                payment.PaymentAccountingTypes = PaymentAccountingTypes.MusteriTaksit;
                break;

            case "Ara Ödeme":
                payment.PaymentType            = PaymentTypes.AraOdeme;
                payment.PaymentAccountingTypes = PaymentAccountingTypes.MusteriTaksit;
                break;

            default:
                break;
            }
            if (customerIdType == 1)// account
            {
                payment.Account = new EntityReference("account", customerId);
            }
            else if (customerIdType == 2)//contact
            {
                payment.Contact = new EntityReference("contact", customerId);
            }

            payment.PaymentDate      = Convert.ToDateTime(dr["Vade Gün"]);
            payment.FinancialAccount = new EntityReference("new_financialaccount", financialAccount);
            TransactionCurrency tcurrency = CurrencyHelper.GetCurrencyByName(currencyType, sda);

            payment.Currency = new EntityReference("transactioncurrency", tcurrency.TransactionCurrencyId);
            payment.Quote    = new EntityReference("quote", quoteId);
            switch (payment.PaymentType)
            {
            case PaymentTypes.BankaOdemesi: payment.Name = "Banka Ödemesi - " + DateTime.Now.ToShortDateString(); break;

            case PaymentTypes.DuzenliTaksit: payment.Name = "Düzenli Taksit - " + DateTime.Now.ToShortDateString(); break;

            case PaymentTypes.PesinOdeme: payment.Name = "Pesin Ödeme - " + DateTime.Now.ToShortDateString(); break;

            case PaymentTypes.AraOdeme: payment.Name = "Ara Ödeme - " + DateTime.Now.ToShortDateString(); break;

            default:
                break;
            }
            PaymentHelper.CreateOrUpdatePayment(payment, service);
            sda.closeConnection();
        }
コード例 #31
0
ファイル: Program.cs プロジェクト: pro100ham/SoftLine
        static void Main(string[] args)
        {
            CustomService = new CrmService();

            Console.WriteLine("Connection esteblished...");

            List <TransactionCurrency> currencies =
                CustomService
                .XrmContext
                .TransactionCurrencySet
                .ToList();

            List <ExchangeRateDTO> eRateDtos = DownloadRatesFile();

            DateTime relevanceDate = GetRelevanceDate(eRateDtos.First());

            DeactivateAllExchangeRates(CustomService, relevanceDate);

            decimal usdRate = findUsdToAznRate(eRateDtos);

            foreach (var rate in eRateDtos)
            {
                if (rate.IsoCode.ToUpper() == "USD")
                {
                    rate.IsoCode = "AZN";
                }

                TransactionCurrency currentCurrency =
                    currencies
                    .SingleOrDefault(x =>
                                     x.ISOCurrencyCode.ToUpper() == rate.IsoCode.ToUpper());

                if (currentCurrency == null)
                {
                    continue;
                }

                sl_ExchangeRate newRate = new sl_ExchangeRate();

                if (rate.IsoCode != "AZN")
                {
                    newRate = new sl_ExchangeRate()
                    {
                        sl_RelevanceDate         = relevanceDate,
                        sl_TransactionCurrencyId = currentCurrency.ToEntityReference(),
                        sl_ExchangeRate1         = 1 / decimal.Parse(rate.ExchangeValue.Replace('.', ',')) * usdRate, // eur/azn / usd/azn
                    };
                }
                else
                {
                    newRate = new sl_ExchangeRate()
                    {
                        sl_RelevanceDate         = relevanceDate,
                        sl_TransactionCurrencyId = new EntityReference(TransactionCurrency.EntityLogicalName, currentCurrency.TransactionCurrencyId.Value),
                        sl_ExchangeRate1         = decimal.Parse(rate.ExchangeValue.Replace('.', ','))
                    };
                }

                CustomService.Create(newRate);

                Console.WriteLine("Created exchange rate of {0} = {1}", currentCurrency.ISOCurrencyCode, newRate.sl_ExchangeRate1);
            }

            Console.WriteLine("Update complete!");
        }
コード例 #32
0
        private async Task UpdateExchangRates(LocalPluginContext localcontext)
        {
            ITracingService tracer       = localcontext.TracingService;
            var             currencyList = (from c in new XrmSvc(localcontext.OrganizationService).CreateQuery <TransactionCurrency>()
                                            select new TransactionCurrency
            {
                ISOCurrencyCode = c.ISOCurrencyCode,
                TransactionCurrencyId = c.TransactionCurrencyId
            }).ToArray();

            var baseCurrency     = "CAD";
            var currencyISOCodes = string.Join(",", currencyList.Select(c => c.ISOCurrencyCode).Where(c => c != baseCurrency).ToArray());

            tracer.Trace(currencyISOCodes.ToString());


            //WebProxy oWebProxy = new System.Net.WebProxy("net-inspect-1.dhltd.corp:8080",true);
            //oWebProxy.Credentials = System.Net.CredentialCache.DefaultCredentials;

            //var httpClientHandler = new HttpClientHandler()
            //{
            //    Proxy = oWebProxy,
            //};

            //if (true)
            //{
            //    httpClientHandler.PreAuthenticate = true;
            //    httpClientHandler.UseDefaultCredentials = false;

            //    // *** These creds are given to the web server, not the proxy server ***
            //    //httpClientHandler.Credentials = new NetworkCredential(
            //    //    userName: serverUserName,
            //    //    password: serverPassword);
            //}


            using (HttpClient client = new HttpClient(/*handler:httpClientHandler, disposeHandler: true*/))
            {
                //var requestUri = new Uri("https://api.fixer.io/latest?symbols=" + String.Join(",", currencyISOCodes));

                var requestUri = new Uri("https://exchangeratesapi.io/api/latest?base=CAD&symbols=" + String.Join(",", currencyISOCodes));
                //var requestUri = new Uri("http://free.currencyconverterapi.com/api/v5/convert?q=" + String.Join("_", currencyISOCodes)+ "&compact=y");
                tracer.Trace(requestUri.ToString());

                var request = new HttpRequestMessage(HttpMethod.Get, requestUri);


                var response = await client.SendAsync(request);

                if (!response.IsSuccessStatusCode)
                {
                    throw new InvalidPluginExecutionException("Exchangerate service returned " + response);
                }


                var json    = response.Content.ReadAsStringAsync().Result;
                var setting = new DataContractJsonSerializerSettings()
                {
                    UseSimpleDictionaryFormat = true
                };

                ExchangeRateResult result = null;
                using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
                {
                    var serializer = new DataContractJsonSerializer(typeof(ExchangeRateResult), setting);
                    result = (ExchangeRateResult)serializer.ReadObject(ms);
                }

                foreach (var currency in currencyList.Where(c => c.ISOCurrencyCode != baseCurrency))
                {
                    if (result.rates.Keys.Contains(currency.ISOCurrencyCode))
                    {
                        var update = new TransactionCurrency
                        {
                            TransactionCurrencyId = currency.TransactionCurrencyId,
                            ExchangeRate          = (decimal?)result.rates[currency.ISOCurrencyCode]
                        };
                        localcontext.OrganizationService.Update(update);
                    }
                }
            }
        }