예제 #1
0
        public static string SerializeToXml(listxml xmlModel)
        {
            IXmlSerializerHelper xmlSerializerHelper = new XmlSerializerHelper();

            return(xmlSerializerHelper.SerializeToXml(xmlModel, encoding: Encoding.ASCII));
        }
예제 #2
0
        private void AllImagesProcessedHandler(object sender, AllImgProcessedEventArgs args)
        {
            XmlSerializerHelper.Serialize(args.ClickInputs, GetClickInputsFilePath(_folderPath));

            SetClickInputs(args.ClickInputs);
        }
예제 #3
0
        private void ValueStripMenuItemClick(object sender, EventArgs e)
        {
            var itemToValue = treeNavigation.SelectedNode?.Tag as ICoreItem;

            if (itemToValue == null)
            {
                return;
            }
            var   schema = itemToValue.AppProps.GetValue <string>(TradeProp.Schema, true);
            Trade trade;

            if (schema == FpML5R3NameSpaces.ConfirmationSchema)
            {
                var xml    = itemToValue.Text; //XmlSerializerHelper.SerializeToString(itemToValue.Data);
                var newxml = xml.Replace("FpML-5/confirmation", "FpML-5/reporting");
                trade = XmlSerializerHelper.DeserializeFromString <Trade>(newxml);
            }
            else
            {
                trade = XmlSerializerHelper.DeserializeFromString <Trade>(itemToValue.Text);
            }
            if (trade != null)
            {
                // the item
                var properties        = itemToValue.AppProps;
                var party1            = properties.GetValue <string>(TradeProp.Party1, true);
                var baseParty         = comboBoxParty.Text == party1 ? "Party1" : "Party2";
                var nameSpace         = properties.GetValue <string>(EnvironmentProp.NameSpace, true);
                var valuationDate     = dateTimePickerValuation.Value;
                var market            = comboBoxMarket.Items[comboBoxMarket.SelectedIndex].ToString();
                var reportingCurrency = comboBoxCurrency.Items[comboBoxCurrency.SelectedIndex].ToString();
                //Predefined metrics
                var metrics = new List <string> {
                    "NPV", "Delta0", "Delta1", "LocalCurrencyNPV", "NFV"
                };
                var requestedMetrics = listBoxMetrics.SelectedItems;
                foreach (var metric in requestedMetrics)
                {
                    if (!metrics.Contains(metric.ToString()))
                    {
                        metrics.Add(metric.ToString());
                    }
                }
                var uniqueTradeId = itemToValue.Name;
                var product       = trade.Item;
                try
                {
                    _loggerRef.Target.LogDebug("Valuing the trade: ." + uniqueTradeId);
                    var pricer = new TradePricer(_loggerRef.Target, _client, nameSpace, null, trade, itemToValue.AppProps);
                    //Get the market
                    var marketEnviroment     = CurveEngine.GetMarket(_loggerRef.Target, _client, nameSpace, product, market, reportingCurrency, false);
                    var controller           = TradePricer.CreateInstrumentModelData(metrics, valuationDate, marketEnviroment, reportingCurrency, baseParty);
                    var assetValuationReport = pricer.Price(controller, ValuationReportType.Full);
                    _loggerRef.Target.LogDebug("Valued the trade: ." + uniqueTradeId);
                    var id = uniqueTradeId.Split('.')[uniqueTradeId.Split('.').Length - 1];
                    //Build the val report properties
                    var valProperties = properties.Clone();
                    //Trade type
                    var tradeType = ProductTypeHelper.TradeTypeHelper(product);
                    valProperties.Set(ValueProp.PortfolioId, tradeType + "." + id);
                    valProperties.Set(ValueProp.BaseParty, baseParty);
                    valProperties.Set(ValueProp.MarketName, market);
                    valProperties.Set(ValueProp.CalculationDateTime, valuationDate);
                    valProperties.Set(TradeProp.UniqueIdentifier, null);
                    //The unique identifier for the valuation report
                    var valuationIdentifier = new ValuationReportIdentifier(valProperties);
                    _client.SaveObject(assetValuationReport, nameSpace + "." + valuationIdentifier.UniqueIdentifier, valProperties);
                    _loggerRef.Target.LogDebug("Valued and saved results for the trade: {0}", uniqueTradeId);
                }
                catch (Exception excp)
                {
                    MessageBox.Show(excp.ToString(), Resources.CoreViewerForm_ValueStripMenuItemClick_Value_failed, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
예제 #4
0
        public FutureTransactionPricer(ILogger logger, ICoreCache cache, string nameSpace, DateTime tradeDate, ExchangeContractTypeEnum futuresType,
                                       IBusinessCalendar settlementCalendar, FutureTransaction futureFpML, string basePartyReference, Boolean forecastRateInterpolation)
        {
            logger.LogInfo("FuturesType set. Commence to build a future transaction.");
            if (futureFpML == null)
            {
                return;
            }
            Multiplier        = 1.0m;
            BuyerReference    = futureFpML.buyerPartyReference.href;
            PaymentCurrencies = new List <string> {
                futureFpML.unitPrice.currency.Value
            };
            SellerReference = futureFpML.sellerPartyReference.href;
            BasePartyBuyer  = basePartyReference == futureFpML.buyerPartyReference.href;
            if (!BasePartyBuyer)
            {
                Multiplier = -1.0m;
            }
            ForecastRateInterpolation = forecastRateInterpolation;
            SettlementCalendar        = settlementCalendar;
            FuturesType       = futuresType;
            ReferenceContract = futureFpML.future.id;
            var futuresCode = ReferenceContract.Split('-')[2];

            NumberOfContracts = Convert.ToInt16(futureFpML.numberOfUnits);
            PurchasePrice     = MoneyHelper.GetAmount(futureFpML.unitPrice.amount, futureFpML.unitPrice.currency.Value);
            var exchangeMIC = futureFpML.future.exchangeId;

            FuturesCurveName  = CurveNameHelpers.GetExchangeTradedCurveName(futureFpML.unitPrice.currency.Value, exchangeMIC.Value, futuresCode);
            DiscountCurveName = CurveNameHelpers.GetDiscountCurveName(futureFpML.unitPrice.currency, true);
            FuturesTypeInfo   = new FutureNodeStruct();
            var exchangeMICData = InstrumentDataHelper.CreateEquityExchangeKey(nameSpace, exchangeMIC.Value);
            var exchangeData    = cache.LoadItem <ExchangeConfigData>(exchangeMICData);

            if (exchangeData?.Data is ExchangeConfigData)
            {
                Exchange = (ExchangeConfigData)exchangeData.Data;
                FuturesTypeInfo.SpotDate = Exchange.SettlementDate;
            }
            if (futureFpML.future != null)
            {
                if (SettlementCalendar == null)
                {
                    SettlementCalendar = BusinessCenterHelper.ToBusinessCalendar(cache,
                                                                                 FuturesTypeInfo.SpotDate
                                                                                 .businessCenters,
                                                                                 nameSpace);
                }
                var future = XmlSerializerHelper.Clone(futureFpML.future);
                FuturesTypeInfo.Future = future;
                if (FuturesTypeInfo.SpotDate != null)
                {
                    SettlementDate = GetSettlementDate(tradeDate, SettlementCalendar,
                                                       FuturesTypeInfo.SpotDate);
                }
                //Instantiate the priceable future.
                NamedValueSet namedValueSet = PriceableAssetFactory.BuildPropertiesForAssets(nameSpace, FuturesTypeInfo.Future.id, tradeDate);
                var           asset         = AssetHelper.Parse(FuturesTypeInfo.Future.id, 0.0m, 0.0m);
                UnderlyingFuture = PriceableAssetFactory.Create(logger, cache, nameSpace, asset.Second, namedValueSet, null, null) as IPriceableFuturesAssetController;
                if (UnderlyingFuture != null)
                {
                    RiskMaturityDate = UnderlyingFuture.GetRiskMaturityDate();
                    MaturityDate     = RiskMaturityDate;
                    LastTradeDate    = UnderlyingFuture.LastTradeDate;
                }
                if (!PaymentCurrencies.Contains(futureFpML.future.currency.Value))
                {
                    PaymentCurrencies.Add(futureFpML.future.currency.Value);
                }
                logger.LogInfo("Futures transaction has been successfully created.");
            }
            else
            {
                logger.LogInfo("Futures type data not available.");
            }
            //Add payments like the settlement price
            if (!PurchasePrice.amountSpecified)
            {
                return;
            }
            var amount            = PurchasePrice.amount * NumberOfContracts / 100;
            var settlementPayment = PaymentHelper.Create("FuturesSettlemetAmount", BuyerReference, SellerReference, amount, SettlementDate);

            AdditionalPayments = PriceableInstrumentsFactory.CreatePriceablePayments(basePartyReference, new[] { settlementPayment }, SettlementCalendar);
            if (!PaymentCurrencies.Contains(settlementPayment.paymentAmount.currency.Value))
            {
                PaymentCurrencies.Add(settlementPayment.paymentAmount.currency.Value);
            }
        }
예제 #5
0
        public static void Save(string fileName, Pipeline pipeline)
        {
            var serializer = new XmlSerializerHelper <Pipeline>();

            serializer.Save(fileName, pipeline);
        }
예제 #6
0
        /// <summary>
        /// Reads the incident magnitude from configuration.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns>The incident wave magnitude direction.</returns>
        public static CartesianCoordinate ReadIncidentMagnitudeFromConfiguration(string fileName)
        {
            var aaa = XmlSerializerHelper.DeserializeObject <DDAParameters>(fileName);

            return(aaa.IncidentMagnitude.ConvertToCartesian());
        }
예제 #7
0
        public static void LoadFpMLCodes(ILogger logger, ICoreCache targetClient, string nameSpace)
        {
            Assembly     assembly = Assembly.GetExecutingAssembly();
            const string prefix   = "FpML.V5r10.ConfigData.Config.FpMLCodes";
            Dictionary <string, string> chosenFiles = ResourceHelper.GetResources(assembly, prefix, "xml");

            if (chosenFiles.Count == 0)
            {
                throw new InvalidOperationException("Missing FpML Code Lists");
            }

            foreach (var file in chosenFiles)
            {
                var    data         = XmlSerializerHelper.DeserializeFromString <CodeListDocument>(file.Value);
                string classDefName = GetClassDefName(data.Identification.ShortName);

                // determine primary key
                string primaryKey = null;
                foreach (Key key in data.ColumnSet.Key)
                {
                    if (key.Id == "PrimaryKey")
                    {
                        if (primaryKey != null)
                        {
                            throw new ApplicationException("PrimaryKey defined more than once!");
                        }
                        primaryKey = key.ColumnRef[0].Ref;
                    }
                }
                if (primaryKey == null)
                {
                    throw new ApplicationException("PrimaryKey is not defined!");
                }

                // load rows
                IFpMLCodeScheme scheme = FpMLCodeSchemeFactory.CreateCodeScheme(classDefName);
                foreach (Row row in data.SimpleCodeList.Row)
                {
                    IFpMLCodeValue codeValue = scheme.CreateCodeValue(row);
                    if (scheme is DayCountFractionScheme)
                    {
                        var dcfValue = (DayCountFractionValue)codeValue;
                        if (dcfValue.HLClassName == null)
                        {
                            dcfValue.HLClassName = "DefaultClassName";
                        }
                    }
                    scheme.AddCodeValue(codeValue);
                }
                var type = scheme.GetItemProps().Get("FpMLCodeScheme");
                scheme.GetItemProps().Set(EnvironmentProp.DataGroup, "Orion.V5r10.Reporting.Configuration." + type);
                scheme.GetItemProps().Set(EnvironmentProp.SourceSystem, "Orion");
                scheme.GetItemProps().Set(EnvironmentProp.Function, FunctionProp.Configuration.ToString());
                scheme.GetItemProps().Set(EnvironmentProp.Type, "FpMLCodeScheme");
                scheme.GetItemProps().Set(EnvironmentProp.Schema, "V5r10.Reporting");
                scheme.GetItemProps().Set(EnvironmentProp.NameSpace, nameSpace);
                string identifier = "Configuration.FpMLCodeScheme." + type;
                string itemName   = nameSpace + "." + identifier;
                scheme.GetItemProps().Set(CurveProp.UniqueIdentifier, identifier);
                targetClient.SaveTypedObject(scheme.GetType(), scheme, itemName, scheme.GetItemProps());
            } // foreach file
            logger.LogDebug("Loaded FpML code lists.");
        }
예제 #8
0
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            int i = 0;

            foreach (var line in File.ReadLines(excelPath))
            {
                if (i >= int.Parse(FromLineInput.Text) && i <= int.Parse(ToLineInput.Text))
                {
                    string[] cases = line.Split('\t');

                    Law tmpLaw = new Law();
                    tmpLaw.Id          = int.Parse(cases[0]);
                    tmpLaw.Title       = cases[1];
                    tmpLaw.Description = cases[3];
                    // Yes Stuff
                    if (cases[6] != "")
                    {
                        if (int.Parse(cases[6]) != -1)
                        {
                            tmpLaw.YesLawsToAdd.Add(int.Parse(cases[6]));
                        }
                    }
                    if (cases[7] != "")
                    {
                        tmpLaw.YesPropertyModifiers.Add(new PropertyModifier(GameProperty.GameProperty_GOVERNMENTOPINION, int.Parse(cases[7])));
                    }
                    if (cases[8] != "")
                    {
                        tmpLaw.YesPropertyModifiers.Add(new PropertyModifier(GameProperty.GameProperty_POPULACEOPINION, int.Parse(cases[8])));
                    }
                    if (cases[9] != "")
                    {
                        tmpLaw.YesPropertyModifiers.Add(new PropertyModifier(GameProperty.GameProperty_ECONOMY, int.Parse(cases[9])));
                    }
                    if (cases[10] != "")
                    {
                        tmpLaw.YesPropertyModifiers.Add(new PropertyModifier(GameProperty.GameProperty_EMPLOYMENT, int.Parse(cases[10])));
                    }
                    if (cases[11] != "")
                    {
                        tmpLaw.YesPropertyModifiers.Add(new PropertyModifier(GameProperty.GameProperty_RELIGION, int.Parse(cases[11])));
                    }
                    if (cases[12] != "")
                    {
                        tmpLaw.YesPropertyModifiers.Add(new PropertyModifier(GameProperty.GameProperty_PERSONALMONEY, int.Parse(cases[12])));
                    }

                    // No Stuff
                    if (cases[13] != "")
                    {
                        if (int.Parse(cases[13]) != -1)
                        {
                            tmpLaw.NoLawsToAdd.Add(int.Parse(cases[13]));
                        }
                    }
                    if (cases[14] != "")
                    {
                        tmpLaw.NoPropertyModifiers.Add(new PropertyModifier(GameProperty.GameProperty_GOVERNMENTOPINION, int.Parse(cases[14])));
                    }
                    if (cases[15] != "")
                    {
                        tmpLaw.NoPropertyModifiers.Add(new PropertyModifier(GameProperty.GameProperty_POPULACEOPINION, int.Parse(cases[15])));
                    }
                    if (cases[16] != "")
                    {
                        tmpLaw.NoPropertyModifiers.Add(new PropertyModifier(GameProperty.GameProperty_ECONOMY, int.Parse(cases[16])));
                    }
                    if (cases[17] != "")
                    {
                        tmpLaw.NoPropertyModifiers.Add(new PropertyModifier(GameProperty.GameProperty_EMPLOYMENT, int.Parse(cases[17])));
                    }
                    if (cases[18] != "")
                    {
                        tmpLaw.NoPropertyModifiers.Add(new PropertyModifier(GameProperty.GameProperty_RELIGION, int.Parse(cases[18])));
                    }
                    if (cases[19] != "")
                    {
                        tmpLaw.NoPropertyModifiers.Add(new PropertyModifier(GameProperty.GameProperty_PERSONALMONEY, int.Parse(cases[19])));
                    }

                    // SoftenCond
                    if (cases[20] != "")
                    {
                        tmpLaw.MinimizeLawsToAdd.Add(int.Parse(cases[20]));
                    }

                    // HardenCond

                    if (cases[21] != "")
                    {
                        tmpLaw.MaximizeLawsToAdd.Add(int.Parse(cases[21]));
                    }

                    XmlSerializerHelper <Law> .SerializeXmlFile(outputPath + "/Law" + tmpLaw.Id + ".xml", tmpLaw);
                }

                i++;
            }
            doneLabel.Content = "Done !!!";
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="cache"></param>
        /// <param name="nameSpace"></param>
        /// <param name="tradeDate"></param>
        /// <param name="settlementDate">The payment settlement date.</param>
        /// <param name="settlementCalendar"></param>
        /// <param name="paymentCalendar"></param>
        /// <param name="bondFpML"></param>
        /// <param name="basePartyReference"></param>
        /// <param name="bondType"></param>
        /// <param name="forecastRateInterpolation"></param>
        public BondTransactionPricer(ILogger logger, ICoreCache cache, string nameSpace, DateTime tradeDate,
                                     DateTime settlementDate, IBusinessCalendar settlementCalendar, IBusinessCalendar paymentCalendar,
                                     BondTransaction bondFpML, string basePartyReference, string bondType, Boolean forecastRateInterpolation)
        {
            Multiplier = 1.0m;
            TradeDate  = tradeDate;
            BondType   = EnumHelper.Parse <BondTypesEnum>(bondType);
            logger.LogInfo("BondType set. Commence to build a bond transaction.");
            if (bondFpML == null)
            {
                return;
            }
            BuyerReference    = bondFpML.buyerPartyReference.href;
            PaymentCurrencies = new List <string> {
                bondFpML.notionalAmount.currency.Value
            };
            SellerReference = bondFpML.sellerPartyReference.href;
            BasePartyBuyer  = basePartyReference == bondFpML.buyerPartyReference.href;
            if (!BasePartyBuyer)
            {
                Multiplier = -1.0m;
            }
            ForecastRateInterpolation = forecastRateInterpolation;
            SettlementCalendar        = settlementCalendar;
            PaymentCalendar           = paymentCalendar;
            //Set the bond price information
            BondPrice = new BondPrice();
            if (bondFpML.price.accrualsSpecified)
            {
                BondPrice.accrualsSpecified = true;
                BondPrice.accruals          = bondFpML.price.accruals;
            }
            if (bondFpML.price.dirtyPriceSpecified)
            {
                BondPrice.dirtyPriceSpecified = true;
                BondPrice.dirtyPrice          = bondFpML.price.dirtyPrice;
            }
            BondPrice.cleanOfAccruedInterest = bondFpML.price.cleanOfAccruedInterest;
            BondPrice.cleanPrice             = bondFpML.price.cleanPrice;
            //Set the notional information
            NotionalAmount = MoneyHelper.GetAmount(bondFpML.notionalAmount.amount, bondFpML.notionalAmount.currency.Value);
            //Determines the quotation and units
            QuoteType = BondPriceEnum.YieldToMaturity;
            //We need to get the ytm in until there is a bond market price/spread.
            if (BondPrice.dirtyPriceSpecified)
            {
                QuoteType = BondPriceEnum.DirtyPrice;
                Quote     = BasicQuotationHelper.Create(BondPrice.dirtyPrice, RateQuotationType);
            }
            //Get the insturment configuration information.
            var            assetIdentifier = bondFpML.bond.currency.Value + "-Bond-" + BondType;
            BondNodeStruct bondTypeInfo    = null;
            var            instrument      = InstrumentDataHelper.GetInstrumentConfigurationData(cache, nameSpace, assetIdentifier);

            if (instrument != null)
            {
                bondTypeInfo = instrument.InstrumentNodeItem as BondNodeStruct;
            }
            if (bondFpML.bond != null && bondTypeInfo != null)
            {
                if (SettlementCalendar == null)
                {
                    SettlementCalendar = BusinessCenterHelper.ToBusinessCalendar(cache, bondTypeInfo.SettlementDate.businessCenters, nameSpace);
                }
                if (PaymentCalendar == null)
                {
                    PaymentCalendar = BusinessCenterHelper.ToBusinessCalendar(cache, bondTypeInfo.BusinessDayAdjustments.businessCenters, nameSpace);
                }
                //Preprocesses the data for the priceableasset.
                var bond = XmlSerializerHelper.Clone(bondFpML.bond);
                BondTypeInfo      = XmlSerializerHelper.Clone(bondTypeInfo);
                BondTypeInfo.Bond = bond;
                //This is done because the config data is not stored in the ciorrect way. Need to add a price quote units.
                if (bond.couponRateSpecified)
                {
                    var coupon = bond.couponRate;
                    BondTypeInfo.Bond.couponRate = coupon;
                }
                BondTypeInfo.Bond.faceAmount = NotionalAmount.amount;
                if (BondTypeInfo.Bond.maturitySpecified)
                {
                    RiskMaturityDate = BondTypeInfo.Bond.maturity;
                }
                SettlementDate = settlementDate;
                if (!PaymentCurrencies.Contains(bondFpML.bond.currency.Value))
                {
                    PaymentCurrencies.Add(bondFpML.bond.currency.Value);
                }
                logger.LogInfo("Bond transaction has been successfully created.");
            }
            else
            {
                logger.LogInfo("Bond type data not available.");
            }
            //Add payments like the settlement price
            if (!BondPrice.dirtyPriceSpecified)
            {
                return;
            }
            var amount            = BondPrice.dirtyPrice * NotionalAmount.amount / 100;
            var settlementPayment = PaymentHelper.Create("BondSettlemetAmount", BuyerReference, SellerReference, amount, SettlementDate);

            AdditionalPayments = PriceableInstrumentsFactory.CreatePriceablePayments(basePartyReference, new[] { settlementPayment }, SettlementCalendar);
            if (!PaymentCurrencies.Contains(settlementPayment.paymentAmount.currency.Value))
            {
                PaymentCurrencies.Add(settlementPayment.paymentAmount.currency.Value);
            }
        }
예제 #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="cache"></param>
        /// <param name="nameSpace"></param>
        /// <param name="tradeDate"></param>
        /// <param name="settlementDate">The payment settlement date.</param>
        /// <param name="settlementCalendar"></param>
        /// <param name="paymentCalendar"></param>
        /// <param name="bondFpML"></param>
        /// <param name="basePartyReference"></param>
        /// <param name="bondType"></param>
        /// <param name="forecastRateInterpolation"></param>
        public BondTransactionPricer(ILogger logger, ICoreCache cache, string nameSpace, DateTime tradeDate,
                                     DateTime settlementDate, IBusinessCalendar settlementCalendar, IBusinessCalendar paymentCalendar,
                                     BondTransaction bondFpML, string basePartyReference, string bondType, bool forecastRateInterpolation)
        {
            Multiplier = 1.0m;
            TradeDate  = tradeDate;
            BondType   = EnumHelper.Parse <BondTypesEnum>(bondType);
            logger.LogInfo("BondType set. Commence to build a bond transaction.");
            if (bondFpML == null)
            {
                return;
            }
            BuyerReference    = bondFpML.buyerPartyReference.href;
            PaymentCurrencies = new List <string> {
                bondFpML.notionalAmount.currency.Value
            };
            SellerReference = bondFpML.sellerPartyReference.href;
            BasePartyBuyer  = basePartyReference == bondFpML.buyerPartyReference.href;
            if (!BasePartyBuyer)
            {
                Multiplier = -1.0m;
            }
            ForecastRateInterpolation = forecastRateInterpolation;
            SettlementCalendar        = settlementCalendar;
            PaymentCalendar           = paymentCalendar;
            //Set the bond price information
            BondPrice = new BondPrice();
            if (bondFpML.price.accrualsSpecified)
            {
                BondPrice.accrualsSpecified = true;
                BondPrice.accruals          = bondFpML.price.accruals;
            }
            if (bondFpML.price.dirtyPriceSpecified)
            {
                BondPrice.dirtyPriceSpecified = true;
                BondPrice.dirtyPrice          = bondFpML.price.dirtyPrice;
            }
            BondPrice.cleanOfAccruedInterest = bondFpML.price.cleanOfAccruedInterest;
            BondPrice.cleanPrice             = bondFpML.price.cleanPrice;
            //Set the currencies
            CouponCurrency  = bondFpML.notionalAmount.currency;
            PaymentCurrency = bondFpML.notionalAmount.currency;//This could be another currency!
            //Set the notional information
            NotionalAmount = MoneyHelper.GetAmount(bondFpML.notionalAmount.amount, bondFpML.notionalAmount.currency.Value);
            //Determines the quotation and units
            QuoteType = BondPriceEnum.YieldToMaturity;
            //We need to get the ytm in until there is a bond market price/spread.
            if (BondPrice.dirtyPriceSpecified)
            {
                QuoteType = BondPriceEnum.DirtyPrice;
                Quote     = BasicQuotationHelper.Create(BondPrice.dirtyPrice, RateQuotationType);
            }
            //Get the instrument configuration information.
            var            assetIdentifier = bondFpML.bond.currency.Value + "-Bond-" + BondType;
            BondNodeStruct bondTypeInfo    = null;
            //TODO Set the swap curves for asset swap valuation.
            //
            //Gets the template bond type
            var instrument = InstrumentDataHelper.GetInstrumentConfigurationData(cache, nameSpace, assetIdentifier);

            if (instrument != null)
            {
                bondTypeInfo = instrument.InstrumentNodeItem as BondNodeStruct;
            }
            if (bondFpML.bond != null && bondTypeInfo != null)
            {
                if (SettlementCalendar == null)
                {
                    SettlementCalendar = BusinessCenterHelper.ToBusinessCalendar(cache, bondTypeInfo.SettlementDate.businessCenters, nameSpace);
                }
                if (PaymentCalendar == null)
                {
                    PaymentCalendar = BusinessCenterHelper.ToBusinessCalendar(cache, bondTypeInfo.BusinessDayAdjustments.businessCenters, nameSpace);
                }
                //Pre-processes the data for the priceable asset.
                var bond = XmlSerializerHelper.Clone(bondFpML.bond);
                Bond = bond;
                bondTypeInfo.Bond = Bond;
                //Set the curves to use for valuations.
                BondCurveName = CurveNameHelpers.GetBondCurveName(Bond.currency.Value, Bond.id);
                //THe discount curve is only for credit calculations.
                DiscountCurveName = CurveNameHelpers.GetDiscountCurveName(Bond.currency.Value, true);
                if (bond.maturitySpecified)
                {
                    MaturityDate = bond.maturity;
                }
                SettlementDateConvention = bondTypeInfo.SettlementDate;
                BusinessDayAdjustments   = bondTypeInfo.BusinessDayAdjustments;
                ExDivDateConvention      = bondTypeInfo.ExDivDate;
                //This is done because the config data is not stored in the correct way. Need to add a price quote units.
                if (bond.couponRateSpecified)
                {
                    var coupon = bond.couponRate;
                    Bond.couponRate = coupon;
                }
                bondTypeInfo.Bond.faceAmount          = NotionalAmount.amount;
                bondTypeInfo.Bond.faceAmountSpecified = true;
                Bond.faceAmount = NotionalAmount.amount;
                if (Bond.maturitySpecified)
                {
                    RiskMaturityDate = Bond.maturity;
                }
                SettlementDate = settlementDate;
                if (!PaymentCurrencies.Contains(bondFpML.bond.currency.Value))
                {
                    PaymentCurrencies.Add(bondFpML.bond.currency.Value);
                }
                logger.LogInfo("Bond transaction has been successfully created.");
            }
            else
            {
                logger.LogInfo("Bond type data not available.");
            }
            //Set the underlying bond
            UnderlyingBond = new PriceableSimpleBond(tradeDate, bondTypeInfo, SettlementCalendar, PaymentCalendar, Quote, QuoteType);
            BondIssuer     = UnderlyingBond.Issuer;
            if (BondPrice.dirtyPriceSpecified)
            {
                UnderlyingBond.PurchasePrice = BondPrice.dirtyPrice / 100; //PriceQuoteUnits
            }
            //Set the coupons
            var bondId = Bond.id;//Could use one of the instrumentIds

            //bondStream is an interest Rate Stream but needs to be converted to a bond stream.
            //It automatically contains the coupon currency.
            Coupons = new PriceableBondCouponRateStream(logger, cache, nameSpace, bondId, tradeDate,
                                                        bondFpML.notionalAmount.amount, CouponStreamType.GenericFixedRate, Bond,
                                                        BusinessDayAdjustments, ForecastRateInterpolation, null, PaymentCalendar);
            //Add payments like the settlement price
            if (!BondPrice.dirtyPriceSpecified)
            {
                return;
            }
            var amount            = BondPrice.dirtyPrice * NotionalAmount.amount / 100;
            var settlementPayment = PaymentHelper.Create(BuyerReference, SellerReference, PaymentCurrency.Value, amount, SettlementDate);

            AdditionalPayments = PriceableInstrumentsFactory.CreatePriceablePayments(basePartyReference, new[] { settlementPayment }, SettlementCalendar);
            //
            var finalPayment = PaymentHelper.Create(BondIssuer, BuyerReference, CouponCurrency.Value, NotionalAmount.amount, RiskMaturityDate);

            FinalRedemption =
                PriceableInstrumentsFactory.CreatePriceablePayment(basePartyReference, finalPayment, PaymentCalendar);
            AdditionalPayments.Add(FinalRedemption);
            if (!PaymentCurrencies.Contains(settlementPayment.paymentAmount.currency.Value))
            {
                PaymentCurrencies.Add(settlementPayment.paymentAmount.currency.Value);
            }
        }
    private void getSceneryList()
    {
        int iCount     = 6;
        int iPageIndex = yeyRequest.Params("pageindex") == null ? 1 : Convert.ToInt32(yeyRequest.Params("pageindex"));
        int iPageCount = yeyRequest.Params("hPageNum") == null ? 0 : Convert.ToInt32(yeyRequest.Params("hPageNum"));

        ccWhere.Clear();
        ccWhere.AddComponent("OrderNumber", Request["OrderNumber"], SearchComponent.Equals, SearchPad.NULL);
        ccWhere.AddComponent("BelongFactory", LoginUser.BelongFactory, SearchComponent.Equals, SearchPad.And);
        servComm.strOrderString = " ModifyDate desc ";
        DataTable dtTalk = servComm.GetListTop(0, "OrderMessage", ccWhere);



        List <string> talkList     = new List <string>();
        List <string> talkListTemp = new List <string>();
        List <string> pageTalkList = new List <string>();

        if (CacheHelper.GetInfoByIdentify(LoginUser.BelongFactory + "|" + Request["OrderNumber"]) != null)
        {
            talkListTemp = CacheHelper.GetInfoByIdentify(LoginUser.BelongFactory + "|" + Request["OrderNumber"]);
            //talkListTemp.Reverse();
            talkList.AddRange(talkListTemp.AsEnumerable <string>());
            talkList.Reverse();
        }
        for (int i = 0; i < dtTalk.Rows.Count; i++)
        {
            talkListTemp = XmlSerializerHelper.DeserializeObject(dtTalk.Rows[i]["TalkContent"].ToString());
            talkListTemp.Reverse();
            talkList.AddRange(talkListTemp.AsEnumerable <string>());
        }


        pageTalkList = talkList.GetRange((iPageIndex - 1) * iPageCount, (talkList.Count - (iPageIndex - 1) * iPageCount) > 10 ? 10 : talkList.Count - (iPageIndex - 1) * iPageCount);
        pageTalkList.Reverse();

        if (iPageCount <= 1)
        {
            iPageCount = servComm.PageCount;
            iPageIndex = 1;
        }

        int    PageCount = (talkList.Count - 1) / iPageCount + 1;
        string talkJson  = "";

        //string backstr = Json.ListToJson("replyJson", talkList, string.Format("\"PageCount\":\"{0}\",", iPageCount)).Replace("\n", "<br/>").Replace("\r", "<br/>");
        for (int i = 0; i < pageTalkList.Count; i++)
        {
            string talkTime = pageTalkList[i].Split('|')[0];
            string talkUser = pageTalkList[i].Split('|')[1];

            string talkMessage = pageTalkList[i].Replace(talkTime + "|" + talkUser + "|", "").Replace("\"", "\\\"").Replace("\n", "").Replace("\r", "");
            talkJson = talkJson + ",{" + "\"TalkMessage\":" + "\"" + talkMessage + "\"" + ",\"TalkTime\":" + "\"" + talkTime + "\"" + ",\"TalkUser\":" + "\"" + talkUser + "\"" + "}";
        }
        if (talkJson == "")
        {
            Response.Write("{\"PageCount\":0}");
            Response.End();
        }
        else
        {
            talkJson = talkJson.Substring(1);
            talkJson = "{" + "\"PageCount\":" + PageCount + ",\"replyJson\"" + ":[" + talkJson + "]}";
            //if (talkJson.IndexOf("\\") >= 0)
            //{
            //    talkJson = talkJson.Replace("\\", "\\\\");
            //}

            Response.Write(talkJson);
            Response.End();
        }
    }
예제 #12
0
        static void Main(string[] args)
        {
            Console.WriteLine("FpMLCodeListTool: Starting...");
            var outerIterator = new TemplateIterator(1);

            outerIterator.Iterations[0].Tokens.Set("NameSpace", "FpML.V5r3.Codes");
            outerIterator.Iterations[0].Tokens.Set("ToolTitle", "TemplateProcessor");
            outerIterator.Iterations[0].Tokens.Set("ToolVersion", "1.1.0.0");
            Console.WriteLine("FpMLCodeListTool: Parsing code lists...");
            string[] xmlFiles      = Directory.GetFiles(@"..\..\..\..\FpML.V5r3\fpml.org\download\codelist", "*.xml", SearchOption.AllDirectories);
            var      classIterator = new TemplateIterator(xmlFiles.Length);

            outerIterator.Iterations[0].SubIterators["ClassDef"] = classIterator;
            int fileNum = 0;

            foreach (string xmlFile in xmlFiles)
            {
                try
                {
                    //Console.WriteLine("FpMLCodeListTool:   Parsing '{0}' ...", xmlFile);
                    var    data         = XmlSerializerHelper.DeserializeFromFile <CodeListDocument>(xmlFile);
                    string classDefName = GetClassDefName(data.Identification.ShortName);
                    // determine primary key
                    string primaryKey = null;
                    foreach (Key key in data.ColumnSet.Key)
                    {
                        if (key.Id == "PrimaryKey")
                        {
                            if (primaryKey != null)
                            {
                                throw new ApplicationException("PrimaryKey defined more than once!");
                            }
                            primaryKey = key.ColumnRef[0].Ref;
                        }
                    }
                    if (primaryKey == null)
                    {
                        throw new ApplicationException("PrimaryKey is not defined!");
                    }

                    classIterator.Iterations[fileNum].Tokens.Set("ClassDef", classDefName);
                    classIterator.Iterations[fileNum].Tokens.Set("PrimaryKey", primaryKey);
                    classIterator.Iterations[fileNum].Tokens.Set("ClassDefDataFile", Path.GetFileNameWithoutExtension(xmlFile));
                    // subiterator - column (field) definitions
                    var fieldIterator = new TemplateIterator(data.ColumnSet.Column.Length);
                    classIterator.Iterations[fileNum].SubIterators["FieldDef"] = fieldIterator;
                    int colNum = 0;
                    foreach (Column col in data.ColumnSet.Column)
                    {
                        fieldIterator.Iterations[colNum].Tokens.Set("ColumnNum", colNum);
                        fieldIterator.Iterations[colNum].Tokens.Set("ColumnName", col.ShortName);
                        fieldIterator.Iterations[colNum].Tokens.Set("XSDataType", col.Data.Type);
                        // next column
                        colNum++;
                    }
                    // subiterator - row (primary key/enum) definitions
                    var valueIterator = new TemplateIterator(data.SimpleCodeList.Row.Length);
                    classIterator.Iterations[fileNum].SubIterators["ValueDef"] = valueIterator;
                    int rowNum = 0;
                    foreach (Row row in data.SimpleCodeList.Row)
                    {
                        valueIterator.Iterations[rowNum].Tokens.Set("RowNum", rowNum + 1); // note: 0 = Undefined
                        string value = row.Value[0].SimpleValue.Value;
                        valueIterator.Iterations[rowNum].Tokens.Set("RowName", value);
                        string enumName = EnumHelper.ToEnumId(value);
                        valueIterator.Iterations[rowNum].Tokens.Set("RowEnum", enumName);
                        //valueIterator.Iterations[rowNum].Tokens.Set("XSDataType", row.Data.Type);
                        // next row
                        rowNum++;
                    }
                }
                catch (Exception excp)
                {
                    Console.Error.WriteLine("FpMLCodeListTool:   Parse '{0}' failed: {1}", xmlFile, excp);
                }
                // next file
                fileNum++;
            }
            // write XML schema definitions
            Console.WriteLine("FpMLCodeListTool: Writing schema definition...");
            {
                const string templateFileName = @"TemplateCodeList.txt";
                outerIterator.Iterations[0].Tokens.Set("TemplateFile", templateFileName);
                string   text  = ResourceHelper.GetResourceWithPartialName(Assembly.GetExecutingAssembly(), templateFileName);
                string[] input = text.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                var tp = new TemplateProcessor {
                    CommentPrefix = "<!--", CommentSuffix = "-->"
                };
                string[] output = tp.ProcessTemplate(input, outerIterator);
                using (StreamWriter f = File.CreateText("FpMLCodes.xsd"))
                {
                    foreach (string line in output)
                    {
                        f.WriteLine(line);
                    }
                    f.Flush();
                }
            }
            // write class extensions
            Console.WriteLine("FpMLCodeListTool: Writing class extensions...");
            {
                const string templateFileName = @"TemplateExtensions.txt";
                outerIterator.Iterations[0].Tokens.Set("TemplateFile", templateFileName);
                string   text  = ResourceHelper.GetResourceWithPartialName(Assembly.GetExecutingAssembly(), templateFileName);
                string[] input = text.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                var      tp    = new TemplateProcessor {
                    CommentPrefix = "//", CommentSuffix = null
                };
                string[] output = tp.ProcessTemplate(input, outerIterator);
                using (StreamWriter f = File.CreateText("FpMLCodesExt.cs"))
                {
                    foreach (string line in output)
                    {
                        f.WriteLine(line);
                    }
                    f.Flush();
                }
            }
            Console.WriteLine("FpMLCodeListTool: Complete.");
        }
예제 #13
0
 private string ConvertObjectToXml(Object objToXml, bool includeNamespace, bool includeStartDocument)
 {
     return(XmlSerializerHelper.ConvertObjectToXml(objToXml, _ns, includeNamespace, includeStartDocument));
 }
예제 #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="cache"></param>
        /// <param name="nameSpace"></param>
        /// <param name="tradeDate"></param>
        /// <param name="effectiveDate"></param>
        /// <param name="referenceEquity"></param>
        /// <param name="settlementCalendar"></param>
        /// <param name="equityFpML"></param>
        /// <param name="basePartyReference"></param>
        /// <param name="forecastRateInterpolation"></param>
        public EquityTransactionPricer(ILogger logger, ICoreCache cache, string nameSpace, DateTime tradeDate, DateTime effectiveDate,
                                       String referenceEquity, IBusinessCalendar settlementCalendar, EquityTransaction equityFpML, string basePartyReference, Boolean forecastRateInterpolation)
        {
            logger.LogInfo("EquityType set. Commence to build a equity transaction.");
            if (equityFpML == null)
            {
                return;
            }
            SettlementDate    = effectiveDate;
            TradeDate         = tradeDate;
            Multiplier        = 1.0m;
            BuyerReference    = equityFpML.buyerPartyReference.href;
            PaymentCurrencies = new List <string> {
                equityFpML.unitPrice.currency.Value
            };
            SellerReference           = equityFpML.sellerPartyReference.href;
            BasePartyBuyer            = basePartyReference == equityFpML.buyerPartyReference.href;
            ForecastRateInterpolation = forecastRateInterpolation;
            SettlementCalendar        = settlementCalendar;
            ReferenceEquity           = referenceEquity;
            NumberOfShares            = Convert.ToInt16(equityFpML.numberOfUnits);
            PurchasePrice             = MoneyHelper.GetAmount(equityFpML.unitPrice.amount, equityFpML.unitPrice.currency.Value);
            PaymentCurrencies         = new List <string> {
                equityFpML.unitPrice.currency.Value
            };
            var exchangeMIC     = equityFpML.equity.exchangeId;
            var exchangeMICData = InstrumentDataHelper.CreateEquityExchangeKey(nameSpace, exchangeMIC.Value);
            var exchangeData    = cache.LoadItem <ExchangeConfigData>(exchangeMICData);

            if (exchangeData?.Data is ExchangeConfigData exchange)
            {
                var equityTypeInfo = new EquityNodeStruct {
                    SettlementDate = exchange.SettlementDate
                };
                if (equityFpML.equity != null)
                {
                    if (SettlementCalendar == null)
                    {
                        SettlementCalendar = BusinessCenterHelper.ToBusinessCalendar(cache,
                                                                                     equityTypeInfo.SettlementDate
                                                                                     .businessCenters,
                                                                                     nameSpace);
                    }
                    if (PaymentCalendar == null)
                    {
                        PaymentCalendar = SettlementCalendar;
                    }
                    var equity = XmlSerializerHelper.Clone(equityFpML.equity);
                    EquityTypeInfo        = XmlSerializerHelper.Clone(equityTypeInfo);
                    EquityTypeInfo.Equity = equity;
                    RiskMaturityDate      = SettlementDate;
                    MaturityDate          = SettlementDate;
                    if (!PaymentCurrencies.Contains(equityFpML.equity.currency.Value))
                    {
                        PaymentCurrencies.Add(equityFpML.equity.currency.Value);
                    }
                    logger.LogInfo("Equity transaction has been successfully created.");
                }
            }
            else
            {
                logger.LogInfo("Equity type data not available.");
            }
            //Add payments like the settlement price
            if (PurchasePrice == null || !PurchasePrice.amountSpecified)
            {
                return;
            }
            var amount            = PurchasePrice.amount * NumberOfShares;
            var settlementPayment = PaymentHelper.Create("EquitySettlementAmount", BuyerReference, SellerReference, amount, SettlementDate);

            AdditionalPayments = PriceableInstrumentsFactory.CreatePriceablePayments(basePartyReference, new[] { settlementPayment }, PaymentCalendar);
            if (!PaymentCurrencies.Contains(settlementPayment.paymentAmount.currency.Value))
            {
                PaymentCurrencies.Add(settlementPayment.paymentAmount.currency.Value);
            }
        }
예제 #15
0
 public void SaveSettings()
 {
     var sett = new XmlSerializerHelper<ApplicationSettings>();
     using (var writer = new StreamWriter(SettingsFileFilename))
     {
         writer.Write(sett.Save(this));
     }
 }
예제 #16
0
            public static void Load(Microsoft.Xna.Framework.Content.ContentManager p_loader)
            {
                // everything else
                JKContentManager.Audio.WaterSplashEnter = new JKSound(p_loader.Load <SoundEffect>("audio/water_splash_enter"), SoundType.SFX);
                JKContentManager.Audio.WaterSplashExit  = new JKSound(p_loader.Load <SoundEffect>("audio/water_splash_exit"), SoundType.SFX);
                JKContentManager.Audio.Plink            = new JKSound(p_loader.Load <SoundEffect>("audio/plink"), SoundType.SFX);
                JKContentManager.Audio.PressStart       = new JKSound(p_loader.Load <SoundEffect>("audio/press_start"), SoundType.SFX);
                JKContentManager.Audio.NewLocation      = new JKSound(p_loader.Load <SoundEffect>("audio/new_location"), SoundType.SFX);
                JKContentManager.Audio.Talking          = new JKSound(p_loader.Load <SoundEffect>("audio/talking"), SoundType.SFX);
                JKContentManager.Audio.RaymanSFX        = new JKSound(p_loader.Load <SoundEffect>("audio/illusion"), SoundType.SFX);
                JKContentManager.Audio.Player.Load(p_loader);
                JKContentManager.Audio.Menu.Load(p_loader);
                JKContentManager.Audio.Babe.Load(p_loader);

                // music only
                string text = "mods/audio/music/";

                if (File.Exists(Game1.instance.Content.RootDirectory + "/mods/audio/music/menu loop/menu_intro.xnb"))
                {
                    JKContentManager.Audio.Music.TitleScreen = new JKSound(p_loader.Load <SoundEffect>(text + "menu loop/menu_intro"), SoundType.Music);
                }
                else
                {
                    JKContentManager.Audio.Music.TitleScreen = new JKSound(p_loader.Load <SoundEffect>("audio/music/menu loop/menu_intro"), SoundType.Music);
                }
                JKContentManager.Audio.Music.TitleScreen.IsLooped = true;
                JKContentManager.Audio.Music.Opening = new JKSound(p_loader.Load <SoundEffect>("audio/music/opening theme"), SoundType.Music);
                if (File.Exists(Game1.instance.Content.RootDirectory + "/mods/audio/music/ending.xnb"))
                {
                    JKContentManager.Audio.Music.Ending = new JKSound(p_loader.Load <SoundEffect>(text + "ending"), SoundType.Music);
                }
                else
                {
                    JKContentManager.Audio.Music.Ending = new JKSound(p_loader.Load <SoundEffect>("audio/music/ending"), SoundType.Music);
                }
                if (File.Exists(Game1.instance.Content.RootDirectory + "/mods/audio/music/ending2.xnb"))
                {
                    JKContentManager.Audio.Music.Ending2 = new JKSound(p_loader.Load <SoundEffect>(text + "ending2"), SoundType.Music);
                }
                else
                {
                    JKContentManager.Audio.Music.Ending2 = new JKSound(p_loader.Load <SoundEffect>("audio/music/ending2"), SoundType.Music);
                }
                if (File.Exists(Game1.instance.Content.RootDirectory + "/mods/audio/music/ending3.xnb"))
                {
                    JKContentManager.Audio.Music.Ending3 = new JKSound(p_loader.Load <SoundEffect>(text + "ending3"), SoundType.Music);
                }
                else
                {
                    JKContentManager.Audio.Music.Ending3 = new JKSound(p_loader.Load <SoundEffect>("audio/music/ending3"), SoundType.Music);
                }
                JKContentManager.Audio.Music.event_music = new Dictionary <string, JKSound>();
                Dictionary <string, SoundEffect> dictionary = JKExtensions.UltraContent.LoadCunt <SoundEffect>(p_loader, text + "event_music", ".xnb");

                foreach (string key in dictionary.Keys)
                {
                    JKContentManager.Audio.Music.event_music.Add(key, new JKSound(dictionary[key], SoundType.Music));
                }
                Dictionary <string, SoundEffect> dictionary2 = JKExtensions.UltraContent.LoadCunt <SoundEffect>(p_loader, "audio/event_sfx", ".xnb");

                foreach (string key2 in dictionary2.Keys)
                {
                    JKContentManager.Audio.Music.event_music.Add(key2, new JKSound(dictionary2[key2], SoundType.SFX));
                }
                JKContentManager.Audio.Music.JINGLE_SETTINGS = XmlSerializerHelper.Deserialize <JumpKing.MiscSystems.ScreenEvents.JingleEventSettings>("Content/" + text + "event_music/events.xml");

                // ambient
                JKContentManager.Audio.AmbienceSaveValues = XmlSerializerHelper.Deserialize <AmbienceManager.AmbienceSaveValues>(Game1.instance.Content.RootDirectory + "/mods/audio/background/data/values.xml");
                if (JKContentManager.Audio.AmbienceSaveValues.special_info == null)
                {
                    JKContentManager.Audio.AmbienceSaveValues.special_info = new AmbienceManager.AmbienceInfo[0];
                }
                text = "mods/audio/background";
                FileInfo[] filesInFolder = p_loader.GetFilesInFolder(text);
                for (int i = 0; i < filesInFolder.Length; i++)
                {
                    string text2 = filesInFolder[i].Name;
                    if (text2.Contains("."))
                    {
                        text2 = text2.Substring(0, text2.IndexOf('.'));
                    }
                    SoundType p_type          = SoundType.Ambience;
                    float     p_fade_out_time = 0f;
                    float     p_fade_in_time  = 0f;
                    foreach (AmbienceManager.AmbienceInfo ambienceInfo in JKContentManager.Audio.AmbienceSaveValues.special_info)
                    {
                        if (ambienceInfo.name == text2)
                        {
                            p_type          = ambienceInfo.type;
                            p_fade_out_time = ambienceInfo.fade_out_length;
                            p_fade_in_time  = ambienceInfo.fade_in_length;
                        }
                    }
                    LubedSound lubedSound = Program.contentThread.CreateSound(new ManagedSound(text + "/" + text2, p_type));
                    JKContentManager.Audio.AmbienceSound value = new JKContentManager.Audio.AmbienceSound
                    {
                        lube        = lubedSound,
                        volume_fade = new JumpKing.MiscSystems.FadeAmbience(lubedSound, p_fade_out_time, p_fade_in_time)
                    };
                    JKContentManager.Audio.Ambience.Add(text2, value);
                }
            }
예제 #17
0
 /// <summary>
 /// Reads the wave propagation from configuration.
 /// </summary>
 /// <param name="fileName">Name of the file.</param>
 /// <returns>The wave propagation direction.</returns>
 public static SphericalCoordinate ReadWavePropagationFromConfiguration(string fileName)
 {
     return(XmlSerializerHelper.DeserializeObject <DDAParameters>(fileName).WavePropagation);
 }
예제 #18
0
            public static void Load(ContentManager p_loader)
            {
                Wardrobe.wardrobeItems   = new List <WardrobeItem>();
                Wardrobe.collectionItems = new List <WardrobeItem>();

                if (File.Exists(p_loader.RootDirectory + "/mods/king/base.xnb"))
                {
                    JKContentManager.PlayerTexture = p_loader.Load <Texture2D>("mods/king/base");
                }
                else
                {
                    JKContentManager.PlayerTexture = p_loader.Load <Texture2D>("king/base");
                }
                JKContentManager.PlayerSprites._CurrentSprites = new LayeredKingSprites(JKContentManager.PlayerTexture);

                string[] files = Directory.GetFiles("Content/wardrobe", "*.xml");
                for (int i = 0; i < files.Length; i++)
                {
                    WardrobeItem wardrobeItem = new WardrobeItem(files[i]);
                    WardrobeItem.WardrobeSettings wItemSettings = wardrobeItem._wItemSettings;
                    bool isCollection = wItemSettings.isCollection;
                    if (isCollection)
                    {
                        Wardrobe.collectionItems.Add(wardrobeItem);
                    }
                    else
                    {
                        Wardrobe.wardrobeItems.Add(wardrobeItem);
                    }
                }

                SkinSettings skinSettings = XmlSerializerHelper.Deserialize <SkinSettings>("Content/mods/king/skin_settings.xml");

                SkinManager.SetSettings(skinSettings);

                Skin[] skins = skinSettings.skins;
                for (int j = 0; j < skins.Length; j++)
                {
                    Skin         skin          = skins[j];
                    WardrobeItem wardrobeItem2 = Wardrobe.collectionItems.Find((WardrobeItem c) => Wardrobe.HasSkin(c._wItemSettings.collection.Value.Reskins, skin.item) && c._wItemSettings.collection.Value.enabled);
                    bool         flag          = wardrobeItem2 == null;
                    if (flag)
                    {
                        WardrobeItem wardrobeItem3 = Wardrobe.wardrobeItems.Find((WardrobeItem x) => x._wItemSettings.skin.Equals(skin.item) && x._wItemSettings.enabled.Value);
                        bool         flag2         = wardrobeItem3 != null;
                        if (flag2)
                        {
                            Texture2D p_tex = p_loader.Load <Texture2D>("wardrobe/" + wardrobeItem3._wItemSettings.name);
                            SkinManager.AddSkinSprite(skin.item, new KingSprites(p_tex));
                        }
                        else
                        {
                            bool flag3 = !File.Exists(p_loader.RootDirectory + "/mods/king/" + skin.texture + ".xnb");
                            if (flag3)
                            {
                                Texture2D p_tex2 = p_loader.Load <Texture2D>("king/" + skin.texture);
                                SkinManager.AddSkinSprite(skin.item, new KingSprites(p_tex2));
                            }
                            else
                            {
                                Texture2D p_tex3 = p_loader.Load <Texture2D>("mods/king/" + skin.texture);
                                SkinManager.AddSkinSprite(skin.item, new KingSprites(p_tex3));
                            }
                        }
                    }
                    else
                    {
                        WardrobeItem.Reskin skinsEnabled = Wardrobe.GetSkinsEnabled(wardrobeItem2._wItemSettings.collection.Value, skin.item);
                        Texture2D           p_tex4       = p_loader.Load <Texture2D>("wardrobe/" + skinsEnabled.name);
                        SkinManager.AddSkinSprite(skinsEnabled.skin, new KingSprites(p_tex4));
                    }
                }
            }
예제 #19
0
 public static void EncryptStringToFile(string fileName, string content, DataProtectionScope protectionScope)
 {
     fileName = ResolveFilename(fileName);
     content  = Encrypt(content, protectionScope);
     XmlSerializerHelper.Save(content, fileName);
 }
 public bool Equals(TimeDimension x, TimeDimension y)
 {
     return(XmlSerializerHelper.AreEqual(x, y));
 }
예제 #21
0
        /// <summary>
        /// Gets the instrument config data.
        /// </summary>
        /// <param name="cache">The cache.</param>
        /// <param name="nameSpace">The client namespace</param>
        /// <param name="parts">The AssetId or the parts of the AssetId.</param>
        /// <returns></returns>
        public static Instrument GetInstrumentConfigurationData(ICoreCache cache, string nameSpace, params string[] parts)
        {
            bool simplifiable = true;

            if (parts.Length == 1)
            {
                parts = parts[0].Split('-');
            }
            string     uniqueName;
            var        assetType            = (AssetTypesEnum)Enum.Parse(typeof(AssetTypesEnum), parts[1], true);
            var        swapTypes            = new[] { AssetTypesEnum.IRSwap, AssetTypesEnum.BasisSwap, AssetTypesEnum.XccyBasisSwap, AssetTypesEnum.XccySwap };
            var        fxTypes              = new[] { AssetTypesEnum.FxSpot, AssetTypesEnum.FxForward };
            var        bondTypes            = new[] { AssetTypesEnum.Bond };
            var        commodityTypes       = new[] { AssetTypesEnum.CommoditySpread, AssetTypesEnum.CommodityForward };
            var        equityTypes          = new[] { AssetTypesEnum.Equity, AssetTypesEnum.EquityForward, AssetTypesEnum.EquitySpread };
            var        irfuturesOptionTypes = new[] { AssetTypesEnum.IRFutureOption, AssetTypesEnum.IRCallFutureOption, AssetTypesEnum.IRPutFutureOption };
            var        otherTypes           = new[] { AssetTypesEnum.BondForward, AssetTypesEnum.BondSpot };
            ICoreItem  loadedItem;
            Instrument instrument;
            string     exchangeMIC = null;

            if (swapTypes.Contains(assetType) && parts.Length > 3)
            {
                uniqueName = CreateKey(nameSpace, parts[1], parts[0], parts[2], parts[3]);
            }
            else if (irfuturesOptionTypes.Contains(assetType) && parts.Length > 2)
            {
                uniqueName = CreateKey(nameSpace, AssetTypesEnum.IRFutureOption.ToString(), parts[0], parts[2]);
            }
            else if (commodityTypes.Contains(assetType) && parts.Length > 3)
            {
                uniqueName = CreateKey(nameSpace, parts[1], parts[0], parts[2], parts[3]);
            }
            else if (fxTypes.Contains(assetType))
            {
                return(GetFxInstrumentConfigurationData(cache, nameSpace, parts));
            }
            else if (bondTypes.Contains(assetType) && parts[2].Split('.').Length > 4)
            {
                uniqueName = CreateBondKey(nameSpace, parts[2]);
                var extraData = cache.LoadItem <Bond>(uniqueName);
                var bondType  = extraData.AppProps.GetValue <string>(BondProp.BondType, true);
                uniqueName = CreateKey(nameSpace, parts[1], parts[0], bondType);
                loadedItem = cache.LoadItem <Instrument>(uniqueName);
                instrument = loadedItem.Data as Instrument;
                if (instrument != null)
                {
                    var newInstrument = XmlSerializerHelper.Clone(instrument);
                    ((BondNodeStruct)newInstrument.InstrumentNodeItem).Bond = extraData.Data as Bond;
                    return(newInstrument);
                }
            }
            else if (equityTypes.Contains(assetType))
            {
                var         assetCode   = parts[2].Split('.');
                EquityAsset equityAsset = null;
                if (assetCode.Length == 2)
                {
                    uniqueName = CreateEquityAssetKey(nameSpace, parts[2]);
                    var equity = cache.LoadItem <EquityAsset>(uniqueName);
                    exchangeMIC = equity.AppProps.GetValue <string>(EquityProp.ExchangeMIC, true);
                    equityAsset = equity.Data as EquityAsset;
                }
                if (assetCode.Length == 1)
                {
                    exchangeMIC = assetCode[0];
                }
                uniqueName = CreateEquityExchangeKey(nameSpace, exchangeMIC);
                loadedItem = cache.LoadItem <ExchangeConfigData>(uniqueName);
                if (assetType == AssetTypesEnum.Equity && loadedItem.Data is ExchangeConfigData exchange)
                {
                    instrument = new Instrument();
                    var equityNode = new EquityNodeStruct
                    {
                        Equity         = equityAsset,
                        Exchange       = exchange.ExchangeData,
                        SettlementDate = exchange.SettlementDate
                    };
                    instrument.AssetType          = parts[1];
                    instrument.InstrumentNodeItem = equityNode;
                    instrument.Currency           = CurrencyHelper.Parse(parts[0]);
                    instrument.ExtraItem          = equityNode.Exchange.MIC;
                    return(instrument);
                }
                if (parts.Length > 3)
                {
                    uniqueName = CreateKey(nameSpace, parts[1], parts[0], exchangeMIC, parts[3]);
                }
                else
                {
                    uniqueName   = CreateKey(nameSpace, parts[1], parts[0], exchangeMIC);
                    simplifiable = false;
                }
            }
            else if (otherTypes.Contains(assetType) && parts.Length > 3)
            {
                //This is to simplify the configuration data and no bond forward is required
                uniqueName = CreateKey(nameSpace, parts[1], parts[0], parts[2], parts[3]);
            }
            //Default Area that sweeps all the standard keys structures.
            else if (parts.Length > 2)
            {
                uniqueName = CreateKey(nameSpace, parts[1], parts[0], parts[2]);
            }
            else
            {
                uniqueName   = CreateKey(nameSpace, parts[1], parts[0]);
                simplifiable = false;
            }
            loadedItem = cache.LoadItem <Instrument>(uniqueName);
            if (loadedItem == null && simplifiable)
            {
                if (swapTypes.Contains(assetType) && parts.Length > 3)
                {
                    //This handles the special case of IRSwaps, where the underlying maturity should use the default.
                    uniqueName = CreateKey(nameSpace, parts[1], parts[0], "Default", parts[3]);
                }
                else if (commodityTypes.Contains(assetType) && parts.Length > 3)
                {
                    uniqueName = CreateKey(nameSpace, parts[1], parts[0], parts[2]);
                }
                else if (equityTypes.Contains(assetType) && parts.Length > 3)
                {
                    //Orion.V5r3.Configuration.Instrument.EquityForward.AUD-EquityForward.AU.0D
                    uniqueName = CreateKey(nameSpace, parts[1], parts[0], exchangeMIC);
                }
                else if (otherTypes.Contains(assetType))
                {
                    //This is to simplify the configuration data and no bond forward is required
                    uniqueName = CreateKey(nameSpace, AssetTypesEnum.Bond.ToString(), parts[0], parts[2]);
                }
                else
                {
                    uniqueName = CreateKey(nameSpace, parts[1], parts[0]);
                }
                loadedItem = cache.LoadItem <Instrument>(uniqueName);
            }
            instrument = loadedItem?.Data as Instrument;
            return(instrument);
        }
 public int GetHashCode(TimeDimension obj)
 {
     return(XmlSerializerHelper.SerializeToString(obj).GetHashCode());
 }
예제 #23
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            var dte = Host.Instance.Dte2;

            _project = dte.GetActiveProejct();
            Common.CheckTfs(_project);

            _dir        = _project.GetDirectory();
            _nuspecFile = Path.Combine(_dir, NuGetDomain.NuSpecFileName);
            if (!File.Exists(_nuspecFile))
            {
                var dr = VsShellUtilities.ShowMessageBox(this.ServiceProvider, $"Miss {NuGetDomain.NuSpecFileName} file,would you add it now?", "Warning",
                                                         OLEMSGICON.OLEMSGICON_WARNING, OLEMSGBUTTON.OLEMSGBUTTON_YESNO, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                if (dr != 6)
                {
                    return;
                }
                new AddNuSpecCommand().Execute();
            }

            _assemblyInfo = _project.GetProjectAssemblyInfo();
            _xmlDoc       = new XmlDocument();
            _xmlDoc.Load(_nuspecFile);
            var xml = _xmlDoc.InnerXml;

            _nupack = XmlSerializerHelper.LoadObjectFromXmlString <NuGet.Package>(xml);

            var packageFields  = new List <string>();
            var assemblyFields = new List <string>();

            if (_nupack.Metadata.Id.IsEmptyOrPlaceHolder() && string.IsNullOrWhiteSpace(_assemblyInfo.Title))
            {
                packageFields.Add("id");
                assemblyFields.Add("AssemblyTitle");
            }
            if (_nupack.Metadata.Authors.IsEmptyOrPlaceHolder() && string.IsNullOrWhiteSpace(_assemblyInfo.Company))
            {
                packageFields.Add("authors");
                assemblyFields.Add("AssemblyCompany");
            }
            if (_nupack.Metadata.Description.IsEmptyOrPlaceHolder() && string.IsNullOrWhiteSpace(_assemblyInfo.Description))
            {
                packageFields.Add("description");
                assemblyFields.Add("AssemblyDescription");
            }


            if (assemblyFields.Count > 0)
            {
                var assemblyInfoFile = _project.GetAssemblyInfoFileName();

                if (File.Exists(assemblyInfoFile))
                {
                    VsShellUtilities.ShowMessageBox(this.ServiceProvider,
                                                    $"{string.Join("/", assemblyFields)} required,please edit {Path.GetFileName(assemblyInfoFile)} at first.", "Warning",
                                                    OLEMSGICON.OLEMSGICON_WARNING, OLEMSGBUTTON.OLEMSGBUTTON_OK,
                                                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);

                    dte.ItemOperations.OpenFile(assemblyInfoFile);
                }
                else
                {
                    VsShellUtilities.ShowMessageBox(this.ServiceProvider,
                                                    $"{string.Join("/", packageFields)} required,please edit package.nuspec at first.", "Warning",
                                                    OLEMSGICON.OLEMSGICON_WARNING, OLEMSGBUTTON.OLEMSGBUTTON_OK,
                                                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);

                    dte.ItemOperations.OpenFile(_nuspecFile);
                }
                return;
            }

            MergePackagesConfig();

            var form = new DeployWizard(_assemblyInfo, _nupack, _xmlDoc);

            if (form.ShowDialog() == DialogResult.OK)
            {
                form.SaveAndBuild();
            }
        }
        private void PricingStructureFormDisplayLoad(object sender, EventArgs e)
        {
            textBox1.Text = _item.Name;
            //Instantiate the datagrid
            //
            //dataGridView1.Columns.Add("PropertyName", "Name");
            //dataGridView1.Columns.Add("PropertyValue", "Value");
            var properties = _item.AppProps.ToDictionary();

            foreach (var property in properties)
            {
                object[] row = { property.Key, property.Value.ToString() };
                dataGridView1.Rows.Add(row);
            }
            //Populate the market data
            //dataGridView2.Columns.Add("assetName", "Name");
            //dataGridView2.Columns.Add("assetValue", "Value");
            var marketData     = XmlSerializerHelper.DeserializeFromString <Market>(_item.Text);
            var quotedAssetSet = marketData.GetQuotedAssetSet();

            if (quotedAssetSet != null)
            {
                //Populate the asset data grid
                var index = 0;
                foreach (var asset in quotedAssetSet.instrumentSet.Items)
                {
                    object[] row = { asset.id, quotedAssetSet.assetQuote[index].quote[0].value };
                    dataGridView2.Rows.Add(row);
                    index++;
                }
            }
            chart1.Name = "termCurveChart";
            chart1.Titles.Add("Zero Curve");
            //chart1.ChartAreas.Add("termCurveArea");
            //chart1.ChartAreas["termCurveArea"].AxisX.Minimum = 0;
            //chart1.ChartAreas["termCurveArea"].AxisX.Maximum = 10000;
            //chart1.ChartAreas["termCurveArea"].AxisX.Interval = 1;
            //chart1.ChartAreas["termCurveArea"].AxisY.Minimum = 0;
            //chart1.ChartAreas["termCurveArea"].AxisY.Maximum = .1;
            //chart1.ChartAreas["termCurveArea"].AxisY.Interval = .01;
            chart1.Series["Curve"].Color     = Color.Blue;
            chart1.Series["Curve"].ChartType = SeriesChartType.Line;
            var zeroCurve = marketData.GetTermCurve();
            var baseDate  = marketData.Items1[0].baseDate.Value;

            if (zeroCurve != null)
            {
                //Populate the curve graph
                var rates = zeroCurve.GetListMidValues();
                var dates = zeroCurve.GetListTermDates();
                if (rates != null && dates != null)
                {
                    var index = 0;
                    foreach (var rate in rates)
                    {
                        var currentDate = dates[index];
                        var numDays     = currentDate.Subtract(baseDate);
                        chart1.Series["Curve"].Points.AddXY(numDays.TotalDays, Convert.ToDouble(rate));
                        index++;
                    }
                }
            }
        }
예제 #25
0
        private void StripBackgroundHandler(object sender, StripBackgroundEventArgs args)
        {
            XmlSerializerHelper.Serialize(args.BackgroundStrippingParams, GetBackgroundStrippingParamsFilePath(_folderPath));

            SetStripBackgroundParams(args.BackgroundStrippingParams);
        }
예제 #26
0
        //public static void LoadTrades(ILogger logger, ICoreCache targetClient)
        //{
        //    LoadIRTrades(logger, targetClient);
        //}

        public static void LoadTrades(ILogger logger, ICoreCache targetClient)
        {
            logger.LogDebug("Loading trades...");

            Assembly     assembly = Assembly.GetExecutingAssembly();
            const string prefix   = "Orion.Configuration.TradeData.FpML47";
            Dictionary <string, string> chosenFiles = ResourceHelper.GetResources(assembly, prefix, "xml");

            if (chosenFiles.Count == 0)
            {
                throw new InvalidOperationException("Missing Trades");
            }

            foreach (KeyValuePair <string, string> file in chosenFiles)
            {
                var     document = XmlSerializerHelper.DeserializeFromString <Document>(file.Value);//This does not work!
                Trade   tradeVersion;
                Party[] party;
                if (document as DataDocument != null)
                {
                    var tradeData = (DataDocument)document;
                    tradeVersion = tradeData.Items[0] as Trade;
                    if (tradeVersion != null)
                    {
                        party = tradeData.party;
                        BuildTrade(logger, targetClient, tradeVersion, party);
                    }
                }
                else if (document as TradeConfirmed != null)
                {
                    var tradeData = (TradeConfirmed)document;
                    tradeVersion = tradeData.trade;
                    party        = tradeData.party;
                    BuildTrade(logger, targetClient, tradeVersion, party);
                }
                else if (document as RequestTradeConfirmation != null)
                {
                    var tradeData = (RequestTradeConfirmation)document;
                    tradeVersion = tradeData.trade;
                    party        = tradeData.party;
                    BuildTrade(logger, targetClient, tradeVersion, party);
                }
                else if (document as TradeCreated != null)
                {
                    var tradeData = (TradeCreated)document;
                    tradeVersion = tradeData.trade;
                    party        = tradeData.party;
                    BuildTrade(logger, targetClient, tradeVersion, party);//TradeCancelled
                }
                else if (document as TradeCancelled != null)
                {
                    var tradeData = (TradeCancelled)document;
                    tradeVersion = tradeData.Items[0] as Trade;
                    party        = tradeData.party;
                    BuildTrade(logger, targetClient, tradeVersion, party);//
                }
                //else if (document as LoanContractNotice != null)
                //{
                //    var tradeData = (LoanContractNotice)document;
                //    tradeVersion = tradeData.Items[0] as Trade;
                //    party = tradeData.party;
                //    BuildTrade(logger, targetClient, tradeVersion, party);
                //}
            } // foreach file
            //as TradeConfirmed
            logger.LogDebug("Loaded {0} trades.", chosenFiles.Count());
        }
예제 #27
0
 private void button3_Click(object sender, EventArgs e)
 {
     var connectionsXml = File.ReadAllText("connections.xml");
     var crmConnections = (CrmConnections)XmlSerializerHelper.Deserialize(connectionsXml, typeof(CrmConnections));
     var connection     = crmConnections.Connections.First();
 }
        public void CreateSwaptionValuation()
        {
            DateTime valuationDate = DateTime.Today;

            SwaptionPricer irSwaptionPricer = new InterestRateSwaptionPricer();

            string discountCurveID   = BuildAndCacheRateCurve(valuationDate); //RateCurveExcelInterfaceTests.ExcelInterface_CreateAUDCurveFromDepostSwapsFuturesFras_WithDates(valuationDate, valuationDate);
            string projectionCurveID = discountCurveID;

            SwapLegParametersRange_Old payFixed       = CreateFixedAUD_6MSwapLegParametersRange(_NAB, CounterParty, valuationDate, 0.065m, "ACT/365.FIXED", "AUSY", "FOLLOWING", "AUSY", "NONE", discountCurveID);
            SwapLegParametersRange_Old receiveFloat   = CreateFloatingAUD_6MSwapLegParametersRange(CounterParty, _NAB, valuationDate, 0, "ACT/365.FIXED", "AUSY", "FOLLOWING", "AUSY", "NONE", discountCurveID, projectionCurveID);
            ValuationRange             valuationRange = CreateValuationRangeForNAB(valuationDate);
            var payCFRangeItemList = InterestRateSwapPricer.GetDetailedCashflowsTestOnly(Engine.Logger, Engine.Cache, Engine.NameSpace, payFixed, valuationRange);

            payCFRangeItemList[0].CouponType = "fixed"; // that should test case insensitive nature of coupons
            payCFRangeItemList[1].CouponType = "Fixed"; //
            var receiveCFRangeItemList = InterestRateSwapPricer.GetDetailedCashflowsTestOnly(Engine.Logger, Engine.Cache, Engine.NameSpace, receiveFloat, valuationRange);

            receiveCFRangeItemList[0].CouponType = "float"; // that should test case insensitive nature of coupons
            receiveCFRangeItemList[1].CouponType = "Float"; //
            var tradeRange = new TradeRange {
                Id = "TradeId_12345", TradeDate = valuationDate
            };
            var leg1PrincipalExchangeCashflowList = new List <InputPrincipalExchangeCashflowRangeItem>();
            var leg2PrincipalExchangeCashflowList = new List <InputPrincipalExchangeCashflowRangeItem>();
            var leg1BulletPaymentList             = new List <AdditionalPaymentRangeItem>();
            var leg2BulletPaymentList             = new List <AdditionalPaymentRangeItem>();
            var swaptionParametersRange           = new SwaptionParametersRange
            {
                Premium                = 456789.12m,
                PremiumCurrency        = "AUD",
                PremiumPayer           = CounterParty,
                PremiumReceiver        = _NAB,
                ExpirationDate         = valuationDate.AddDays(10),
                ExpirationDateCalendar = "AUSY-GBLO",
                ExpirationDateBusinessDayAdjustments = "FOLLOWING",
                PaymentDate         = valuationDate.AddDays(20),
                PaymentDateCalendar = "USNY-GBLO",
                PaymentDateBusinessDayAdjustments = "MODFOLLOWING",
                EarliestExerciseTime = new TimeSpan(10, 0, 0).TotalDays,
                ExpirationTime       = new TimeSpan(11, 0, 0).TotalDays,
                AutomaticExcercise   = false
            };
            List <PartyIdRangeItem>           partyList = GetPartyList("NAB", "book", "MCHammer", "counterparty");
            List <OtherPartyPaymentRangeItem> otherPartyPaymentRangeItems = GetOtherPartyPaymentList("counterparty", "cost center");
            List <FeePaymentRangeItem>        feePaymentRangeItems        = GetFeeList("counterparty", "book");
            //  Get price and swap representation using non-vanilla PRICE function.
            //
            string valuatonId = irSwaptionPricer.CreateValuation(Engine.Logger, Engine.Cache, Engine.NameSpace, null, null,
                                                                 swaptionParametersRange,
                                                                 CreateValuationSetList2(12345.67, -0.321), valuationRange, tradeRange,
                                                                 payFixed, receiveFloat,
                                                                 payCFRangeItemList, receiveCFRangeItemList,
                                                                 leg1PrincipalExchangeCashflowList, leg2PrincipalExchangeCashflowList,
                                                                 leg1BulletPaymentList, leg2BulletPaymentList,
                                                                 partyList, otherPartyPaymentRangeItems,
                                                                 feePaymentRangeItems);
            var valuationReport = Engine.Cache.LoadObject <ValuationReport>(Engine.NameSpace + "." + valuatonId);

            Debug.Print(XmlSerializerHelper.SerializeToString(valuationReport));
        }
예제 #29
0
 public void FromXmlString(string xmlString)
 {
     ImportParameters(XmlSerializerHelper.DeserializeXML <AesParameters>(xmlString));
 }
예제 #30
0
        /// <summary>
        /// Reads the wavelength from configuration.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns>The optical spectrum.</returns>
        public static OpticalSpectrum ReadWavelengthFromConfiguration(string fileName)
        {
            var config = XmlSerializerHelper.DeserializeObject <DDAParameters>(fileName);

            return(ReadWavelengthFromConfiguration(config));
        }
예제 #31
0
        private void tsbInstall_Click(object sender, EventArgs e)
        {
            if (lvPlugins.CheckedItems.Count == 0)
            {
                return;
            }

            ((MainForm)Owner).EnableNewPluginsWatching(false);

            var pus = new PluginUpdates {
                PreviousProcessId = Process.GetCurrentProcess().Id
            };

            foreach (ListViewItem item in lvPlugins.CheckedItems.Cast <ListViewItem>().Where(l => l.Tag is XtbNuGetPackage))
            {
                var xtbPackage = (XtbNuGetPackage)item.Tag;

                if (xtbPackage.Action == PackageInstallAction.Unavailable)
                {
                    if (xtbPackage.Package.ProjectUrl != null && !string.IsNullOrEmpty(xtbPackage.Package.ProjectUrl.ToString()))
                    {
                        if (DialogResult.Yes == MessageBox.Show($"{xtbPackage.Package.Title}\nis incompatible with this version of XrmToolBox.\nOpen project URL?", "Incompatible plugin", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation))
                        {
                            Process.Start(xtbPackage.Package.ProjectUrl.ToString());
                        }
                    }
                    else
                    {
                        MessageBox.Show($"{xtbPackage.Package.Title}\nis incompatible with this version of XrmToolBox.", "Incompatible plugin", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                    continue;
                }
                manager.InstallPackage(xtbPackage.Package, true, false);

                var packageFolder = Path.Combine(nugetPluginsFolder, xtbPackage.Package.Id + "." + xtbPackage.Package.Version);

                foreach (var fi in xtbPackage.Package.GetFiles())
                {
                    var destinationFile = Path.Combine(applicationFolder, fi.EffectivePath);

                    // XrmToolBox restart is required when a plugin has to be
                    // updated or when a new plugin shares files with other
                    // plugin(s) already installed
                    if (xtbPackage.RequiresXtbRestart)
                    {
                        pus.Plugins.Add(new PluginUpdate
                        {
                            Source      = Path.Combine(packageFolder, fi.Path),
                            Destination = destinationFile
                        });
                    }
                    else if (xtbPackage.Action == PackageInstallAction.Install)
                    {
                        try
                        {
                            // Can install plugin directly
                            var destinationDirectory = Path.GetDirectoryName(destinationFile);
                            if (!Directory.Exists(destinationDirectory))
                            {
                                Directory.CreateDirectory(destinationDirectory);
                            }
                            File.Copy(Path.Combine(packageFolder, fi.Path), destinationFile, true);
                        }
                        catch (Exception error)
                        {
                            MessageBox.Show(this,
                                            "An error occured while copying files: " + error.Message +
                                            "\r\n\r\nCopy has been aborted", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                }
            }

            if (pus.Plugins.Count > 0)
            {
                XmlSerializerHelper.SerializeToFile(pus, Path.Combine(applicationFolder, "Update.xml"));

                if (DialogResult.Yes == MessageBox.Show(
                        "This application needs to restart to install updated plugins (or new plugins that share some files with already installed plugins). Click Yes to restart this application now",
                        "Information", MessageBoxButtons.YesNo, MessageBoxIcon.Information))
                {
                    Application.Restart();
                }
            }
            else
            {
                // Refresh plugins list when installation is done
                ((MainForm)Owner).ReloadPluginsList();
                RefreshPluginsList();
                MessageBox.Show("Installation done!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            ((MainForm)Owner).EnableNewPluginsWatching(true);
        }
예제 #32
0
 public static ApplicationSettings LoadSettingsFromFile()
 {
     try
     {
         using (var reader = new FileStream(SettingsFileFilename,FileMode.Open))
         {
             var sett=new XmlSerializerHelper<ApplicationSettings>();
             return sett.Read(reader);
         }
     }
     catch (Exception exception)
     {
         MessageBox.Show("No settings present. Please visit \"Settings\" page to configure bot.");
         return new ApplicationSettings();
     }
 }