/// <summary>
        /// Gets the closest non-zero volatility strike to money.
        /// </summary>
        /// <param name="expiry">The expiry.</param>
        /// <returns></returns>
        ///
        public static Strike GetClosestStrikeToMoney(ForwardExpiry expiry)
        {
            decimal fwdPrice   = expiry.FwdPrice;
            var     expiryCopy = BinarySerializerHelper.Clone(expiry);

            /* Bin search bitwise complement returns first element larger than search key
             * Returns Array Length + 1 if search key greater than all elements */
            expiryCopy.RawStrikePrices.Sort();
            double[] strikes = expiryCopy.RawStrikePrices.ToArray();
            int      index   = Array.BinarySearch(strikes, Convert.ToDouble(fwdPrice));

            if (index < 0)
            {
                index = ~index;
            }
            if (expiryCopy.Strikes.Length == 0)
            {
                return(null);
            }
            if (index < expiryCopy.Strikes.Length)
            {
                double dist1 = Math.Abs(strikes[index] - Convert.ToDouble(fwdPrice));
                double dist2 = 0.0;
                if (index >= 1)
                {
                    dist2 = Math.Abs(strikes[index - 1] - Convert.ToDouble(fwdPrice));
                }
                if (dist1 <= dist2 || index == 0)
                {
                    return(expiryCopy.Strikes[index]);
                }
                return(expiryCopy.Strikes[index - 1]);
            }
            return(expiryCopy.Strikes[expiryCopy.RawStrikePrices.Count - 1]);
        }
        public List <DTOs.App> GetApps()
        {
            var        bytesAppIds = KeyValueStore.Get(KeyValueStore.DefaultType, KeyGenerator.AppsKey, null);
            List <int> appIds      = null;

            if (bytesAppIds == null)
            {
                return(new List <DTOs.App>());
            }

            appIds = (List <int>)BinarySerializerHelper.DeserializeObject(bytesAppIds);

            var res = new List <DTOs.App>();

            foreach (var appId in appIds)
            {
                var bytesApp = KeyValueStore.Get(KeyValueStore.DefaultType, KeyGenerator.GenerateAppKey(appId), null);
                if (bytesApp == null)
                {
                    continue;
                }

                var app = ProtoBufSerializerHelper.Deserialize <App>(bytesApp);

                res.Add(new DTOs.App
                {
                    Id          = app.Id,
                    Name        = app.Name,
                    Description = app.Description
                });
            }

            return(res);
        }
Exemple #3
0
        public void StackExchangeRedisKeyValueStore_Hash_Exceptions()
        {
            var store = new StackExchangeRedisKeyValueStore("localhost:6379");

            Assert.ThrowsException <ArgumentException>(() =>
            {
                store.Set(StackExchangeRedisDataTypesEnum.Hash, new List <Tuple <string, byte[], object> >
                {
                    Tuple.Create <string, byte[], object>("testKey2_1", BinarySerializerHelper.SerializeObject(1), new StackExchangeRedisHashParams {
                        HashField = "testKey2_1_1"
                    }),
                    Tuple.Create <string, byte[], object>("testKey2_2", BinarySerializerHelper.SerializeObject(2), new StackExchangeRedisHashParams {
                        HashField = "testKey2_1_2"
                    })
                });
            });

            Assert.ThrowsException <ArgumentException>(() =>
            {
                store.Get(StackExchangeRedisDataTypesEnum.Hash, new List <Tuple <string, object> >
                {
                    Tuple.Create <string, object>("testKey2_1", new StackExchangeRedisHashParams {
                        HashField = "testKey2_1_1"
                    }),
                    Tuple.Create <string, object>("testKey2_2", new StackExchangeRedisHashParams {
                        HashField = "testKey2_1_2"
                    })
                });
            });
        }
        public T Get <T>(TDataTypesEnum type, string key, object extraParams = null)
        {
            var currentFork = Fork;

            while (currentFork != null)
            {
                var byteValue = KeyValueStore.Get(type, KeyGenerator.GenerateForkValueKey(AppId, currentFork.Id, key), extraParams);

                if (byteValue != null)
                {
                    if (typeof(T) == typeof(byte[]))
                    {
                        return((T)Convert.ChangeType(byteValue, typeof(T)));
                    }

                    return((T)BinarySerializerHelper.DeserializeObject(byteValue));
                }

                if (KeyValueStore.Exists(type, KeyGenerator.GenerateForkNullKey(AppId, currentFork.Id, key), null))
                {
                    return(default(T));
                }

                currentFork = currentFork.Parent;
            }

            return(default(T));
        }
        public static BasicAssetValuation Add(BasicAssetValuation basicAssetValuation1, BasicAssetValuation basicAssetValuation2)
        {
            BasicAssetValuation result = BinarySerializerHelper.Clone(basicAssetValuation1);

            var proccessedMeasureTypes = new List <string>();

            foreach (BasicQuotation bq1 in result.quote)
            {
                proccessedMeasureTypes.Add(bq1.measureType.Value);

                BasicQuotation bq2 = GetQuotationByMeasureType(basicAssetValuation2, bq1.measureType.Value);

                if (null != bq2)
                {
                    bq1.value += bq2.value;
                }
            }

            var bqToAddToList = new List <BasicQuotation>();

            foreach (BasicQuotation bq2 in basicAssetValuation2.quote)
            {
                if (-1 == proccessedMeasureTypes.IndexOf(bq2.measureType.Value))//if hasn't been processed in the first pass
                {
                    bqToAddToList.Add(bq2);
                }
            }

            bqToAddToList.AddRange(result.quote);

            result.quote = bqToAddToList.ToArray();

            return(result);
        }
Exemple #6
0
        private void Serialise()
        {
            if (_text == null && _data != null)
            {
                var serialFormat = (SerialFormat)SysProps.GetValue(SysPropName.SAlg, 0);
                switch (serialFormat)
                {
                case SerialFormat.Binary:
                    // try Binary serialiser
                    _text = BinarySerializerHelper.SerializeToString(_data);
                    SysProps.Set(SysPropName.SAlg, (int)SerialFormat.Binary);
                    break;

                case SerialFormat.Soap:
                    // try Soap serialiser
                    _text = SoapSerializerHelper.SerializeToString(_data);
                    SysProps.Set(SysPropName.SAlg, (int)SerialFormat.Soap);
                    break;

                case SerialFormat.Json:
                    // try Json serialiser
                    _text = JsonSerializerHelper.SerializeToString(_data);
                    SysProps.Set(SysPropName.SAlg, (int)SerialFormat.Json);
                    break;

                case SerialFormat.Xml:
                    try
                    {
                        _text = XmlSerializerHelper.SerializeToString(_dataTypeType, _data);
                        SysProps.Set(SysPropName.SAlg, (int)SerialFormat.Xml);
                    }
                    catch (Exception excp)
                    {
                        throw new ApplicationException(
                                  "The XmlSerializer has thrown an exception: '" + excp.GetType().Name + "'. " +
                                  "If your intent was to use the BinaryFormatter or SoapFormatter for serialisation, " +
                                  "then you should set the SerialFormat property appropriately.",
                                  excp);
                    }
                    break;

                default:
                    // use default xml serialiser
                    try
                    {
                        _text = XmlSerializerHelper.SerializeToString(_dataTypeType, _data);
                        SysProps.Set(SysPropName.SAlg, (int)SerialFormat.Xml);
                    }
                    catch (Exception excp)
                    {
                        throw new ApplicationException(
                                  "The XmlSerializer has thrown an exception: '" + excp.GetType().Name + "'. " +
                                  "If your intent was to use the BinaryFormatter or SoapFormatter for serialisation, " +
                                  "then you should set the SerialFormat property appropriately.",
                                  excp);
                    }
                    break;
                }
            }
        }
        /// <summary>
        /// Sets the app Id
        /// </summary>
        /// <param name="appId"></param>
        public void SetApp(int appId)
        {
            if (appId == 0)
            {
                throw new ArgumentException(nameof(appId));
            }

            //Check if app exists
            var        bytesAppIds = KeyValueStore.Get(KeyValueStore.DefaultType, KeyGenerator.AppsKey, null);
            List <int> appIds      = null;

            if (bytesAppIds != null)
            {
                appIds = (List <int>)BinarySerializerHelper.DeserializeObject(bytesAppIds);
            }

            if (appIds == null || !appIds.Contains(appId))
            {
                throw new ArgumentException($"{nameof(appId)} - doesn't exist");
            }

            AppId = appId;

            ForkProvider = new ForkProvider <TDataTypesEnum>(KeyValueStore, AppId);
        }
        public void Test_Serializable()
        {
            //测试Serializable对序列化的影响,将对象序列化成字符串
            //BinarySerializer,json.net,XmlSerializer和LZ4
            //结论:特性[Serializable]只对使用BinaryFormatter序列化(序列化成流)的时候有影响,其它的序列化不影响。

            var input = new TestSerializableClass
            {
                Id          = 1,
                Name        = "aaa",
                CreatedTime = DateTime.Now
            };

            //BinarySerializer
            var result1 = string.Empty;

            try
            {
                result1 = BinarySerializerHelper.Serialize(input);
            }
            catch (Exception ex)
            {
            }

            //json.net
            var result2 = string.Empty;

            try
            {
                result2 = input.ToJson();
            }
            catch (Exception ex)
            {
            }

            //XmlSerializer
            var result3 = string.Empty;

            try
            {
                result3 = input.ToXml();
            }
            catch (Exception ex)
            {
            }

            //LZ4
            byte[] result4 = null;
            try
            {
                result4 = input.ToJson().LZ4Compress();
            }
            catch (Exception ex)
            {
            }
        }
Exemple #9
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="dataType"></param>
 /// <param name="binaryClone"></param>
 /// <returns></returns>
 public object GetData(Type dataType, bool binaryClone)
 {
     // deserialise if required
     Deserialise(dataType);
     if (binaryClone)
     {
         return(BinarySerializerHelper.Clone(_data));
     }
     return(_data);
 }
Exemple #10
0
        public static BasicQuotation Add(BasicQuotation basicQuotation1, BasicQuotation basicQuotation2)
        {
            if (basicQuotation1.measureType.Value != basicQuotation2.measureType.Value)
            {
                string errorMessage =
                    $"Error: can't add BasicQuotations with different 'measureTypes'. MeasureType for basicQuotation1 is {basicQuotation1.measureType.Value}, MeasureType for basicQuotation2 is {basicQuotation2.measureType.Value}";
                throw new System.Exception(errorMessage);
            }
            BasicQuotation result = BinarySerializerHelper.Clone(basicQuotation1);

            result.value += basicQuotation2.value;
            return(result);
        }
        public void AddQuotedAssetSet(QuotedAssetSet quotedAssetSet)
        {
            quotedAssetSet = BinarySerializerHelper.Clone(quotedAssetSet);

            //_lastQuotedAssetSet = quotedAssetSet;
            if (null == _lastQuotedAssetSet)
            {
                _lastQuotedAssetSet = quotedAssetSet;
            }
            else
            {
                MergeQuotedAssetSet(quotedAssetSet);
            }
        }
        public bool Set <T>(TDataTypesEnum type, string key, T value, object extraParams = null)
        {
            if (Fork.ReadOnly)
            {
                return(false);
            }

            KeyValueStore.Delete(type, KeyGenerator.GenerateForkNullKey(AppId, Fork.Id, key), extraParams);;

            var forkedKey = KeyGenerator.GenerateForkValueKey(AppId, Fork.Id, key);

            var byteValue = value as byte[] ?? BinarySerializerHelper.SerializeObject(value);

            return(KeyValueStore.Set(type, forkedKey, byteValue, extraParams));
        }
Exemple #13
0
        public void Dispose()
        {
            if (_orgServiceCreate)
            {
                var orgService          = ContextContainer.GetValue <IOrganizationService>(ContextTypes.OrgService);
                var orgServiceDiposable = orgService as IDisposable;

                if (orgServiceDiposable != null)
                {
                    using (orgServiceDiposable)
                    {
                    }
                }

                ContextContainer.SetValue <IOrganizationService>(ContextTypes.OrgService, null);
            }

            if (_dictionaryCreate)
            {
                var dict    = ContextContainer.GetValue <Dictionary <string, object> >(ContextTypes.Dictionary);
                var strDict = BinarySerializerHelper.Serializer <Dictionary <string, object> >(dict);
                _context.SharedVariables["dictionary"] = strDict;

                ContextContainer.SetValue <Dictionary <string, object> >(ContextTypes.Dictionary, null);
            }

            if (_currentUserCreate)
            {
                ContextContainer.SetValue <ICurrentUserInfoContext>(ContextTypes.CurrentUser, null);
            }

            if (_currentOrganizationCreate)
            {
                ContextContainer.SetValue <Guid>(ContextTypes.CurrentOrganization, Guid.Empty);
            }

            if (_orgServiceFactoryCreate)
            {
                ContextContainer.SetValue <IOrganizationServiceFactory>(ContextTypes.OrgServiceFactory, null);
            }

            if (_tracingServiceCreate)
            {
                ContextContainer.SetValue <IConfigurationService>(ContextTypes.TracingService, null);
            }
        }
        ///// <summary>
        ///// Creates the surface from expiry node list.
        ///// </summary>
        ///// <param name="assetId">The asset id.</param>
        ///// <param name="expiryNodes">The expiry nodes.</param>
        ///// <returns></returns>
        //public static IVolatilitySurface CreateSurfaceFromNodalExpiryNodeList(string assetId, XmlNodeList expiryNodes)
        //{
        //    IVolatilitySurface surface = new VolatilitySurface(assetId);
        //    List<ForwardExpiry> expiries = ForwardExpiryHelper.CreateExpiriesFromExpiryNodeList(expiryNodes);

        //    if (expiries != null)
        //    {
        //        foreach (ForwardExpiry expiry in expiries)
        //        {
        //            surface.AddExpiry(expiry);
        //        }
        //    }
        //    else
        //    {
        //        throw new IncompleteInputDataException("Surface has no expiries");
        //    }
        //    return surface;

        //}



        /// <summary>
        /// Gets the closest non-zero volatility strike to money.
        /// </summary>
        /// <param name="expiry">The expiry.</param>
        /// <returns></returns>
        ///
        public static double GetClosestNonZeroVolStrikeToMoney(ForwardExpiry expiry)
        {
            decimal fwdPrice   = expiry.FwdPrice;
            var     expiryCopy = BinarySerializerHelper.Clone(expiry);

            //Remove strikes with zero vol in the search object
            //Want to return the location of the nearest *non-zero* strike
            foreach (Strike strike in expiryCopy.Strikes)
            {
                if (strike.Volatility.Value == 0)
                {
                    expiryCopy.RemoveStrike(strike.StrikePrice);
                }
            }

            /* Bin search bitwise complement returns first element larger than search key
             * Returns Array Length + 1 if search key greater than all elements */

            expiryCopy.RawStrikePrices.Sort();
            double[] strikes = expiryCopy.RawStrikePrices.ToArray();
            int      index   = Array.BinarySearch(strikes, Convert.ToDouble(fwdPrice));

            if (index < 0)
            {
                index = ~index;
            }
            if (expiryCopy.RawStrikePrices.Count == 0)
            {
                return(0.0);
            }
            if (index < expiryCopy.RawStrikePrices.Count)
            {
                double dist1 = Math.Abs(strikes[index] - Convert.ToDouble(fwdPrice));
                double dist2 = 0.0;
                if (index >= 1)
                {
                    dist2 = Math.Abs(strikes[index - 1] - Convert.ToDouble(fwdPrice));
                }
                if (dist1 <= dist2 || index == 0)
                {
                    return(expiryCopy.RawStrikePrices[index]);
                }
                return(expiryCopy.RawStrikePrices[index - 1]);
            }
            return(expiryCopy.RawStrikePrices[expiryCopy.RawStrikePrices.Count - 1]);
        }
        private void InitForksDict()
        {
            var rawForks = new Dictionary <int, ForkRawData>();
            var forkIds  = (List <int>)BinarySerializerHelper.DeserializeObject(Store.Get(Store.DefaultType, KeyGenerator.GenerateForksKey(AppId), null));

            foreach (var forkId in forkIds)
            {
                rawForks[forkId]         = ProtoBufSerializerHelper.Deserialize <ForkRawData>(Store.Get(Store.DefaultType, KeyGenerator.GenerateForkKey(AppId, forkId), null));
                _forksTimeStamps[forkId] = (DateTime)BinarySerializerHelper.DeserializeObject(Store.Get(Store.DefaultType, KeyGenerator.GenerateForkTimeStampKey(AppId, forkId), null));
            }

            var masterForks = rawForks.Where(x => x.Value.ParentId == 0).Select(x => x.Key).ToArray();

            foreach (var masterFork in masterForks)
            {
                CreateFork(rawForks, masterFork);
            }
        }
Exemple #16
0
 public static void ResolveBusinessCenters(object objectGraph)
 {
     foreach (BusinessDayAdjustments businessDayAdjustment in GetBusinessDayAdjustments(objectGraph))
     {
         // "NONE" adjustments have neither businessCenters nor businessCentersReference.
         //
         if ((null != businessDayAdjustment) &&
             (null == businessDayAdjustment.businessCenters) &&
             (null != businessDayAdjustment.businessCentersReference) &&
             (!String.IsNullOrEmpty(businessDayAdjustment.businessCentersReference.href)))
         {
             var businessCenters = ObjectLookupHelper.GetById <BusinessCenters>(objectGraph, businessDayAdjustment.businessCentersReference.href);
             var businessCentersCloneWithNoId = BinarySerializerHelper.Clone(businessCenters);
             businessCentersCloneWithNoId.id       = null;
             businessDayAdjustment.businessCenters = businessCentersCloneWithNoId;
         }
     }
 }
Exemple #17
0
 private void Deserialise(Type userDataType)
 {
     if (_data == null)
     {
         // decompress 1st if required
         Decompress();
         // now deserialise
         Type dataTypeType = userDataType ?? _dataTypeType;
         if ((dataTypeType == null) && !String.IsNullOrEmpty(DataTypeName))
         {
             dataTypeType = Type.GetType(DataTypeName);
         }
         var serialFormat = (SerialFormat)SysProps.GetValue(SysPropName.SAlg, (int)SerialFormat.Undefined);
         if (String.IsNullOrEmpty(_text))
         {
             // null data object
             _data = null;
         }
         else if (serialFormat == SerialFormat.Binary)
         {
             // use Binary deserialiser
             _data = BinarySerializerHelper.DeserializeFromString(_text);
         }
         else if (serialFormat == SerialFormat.Soap)
         {
             // use Soap deserialiser
             _data = SoapSerializerHelper.DeserializeFromString(_text);
         }
         else if (serialFormat == SerialFormat.Json)
         {
             // use Json deserialiser
             _data = JsonSerializerHelper.DeserializeFromString(dataTypeType, _text);
         }
         else if (dataTypeType != null)
         {
             // try default xml serialiser
             _data = XmlSerializerHelper.DeserializeFromString(dataTypeType, _text);
         }
         else
         {
             throw new ApplicationException("Cannot deserialise!");
         }
     }
 }
Exemple #18
0
        public void StackExchangeRedisKeyValueStore_String()
        {
            var store = new StackExchangeRedisKeyValueStore("localhost:6379");

            store.Set(StackExchangeRedisDataTypesEnum.String, "testKey1", BinarySerializerHelper.SerializeObject(123));
            var res = (int)BinarySerializerHelper.DeserializeObject(store.Get(StackExchangeRedisDataTypesEnum.String, "testKey1"));

            Assert.AreEqual(123, res);

            store.Set(StackExchangeRedisDataTypesEnum.String, new List <Tuple <string, byte[], object> >
            {
                Tuple.Create <string, byte[], object>("testKey1_1", BinarySerializerHelper.SerializeObject(1), null),
                Tuple.Create <string, byte[], object>("testKey1_2", BinarySerializerHelper.SerializeObject(2), null),
                Tuple.Create <string, byte[], object>("testKey1_3", BinarySerializerHelper.SerializeObject(3), null)
            });

            var multipleRes = store.Get(StackExchangeRedisDataTypesEnum.String, new List <Tuple <string, object> >
            {
                Tuple.Create <string, object>("testKey1_1", null),
                Tuple.Create <string, object>("testKey1_2", null),
                Tuple.Create <string, object>("testKey1_3", null)
            });

            Assert.AreEqual(1, (int)BinarySerializerHelper.DeserializeObject(multipleRes["testKey1_1"]));
            Assert.AreEqual(2, (int)BinarySerializerHelper.DeserializeObject(multipleRes["testKey1_2"]));
            Assert.AreEqual(3, (int)BinarySerializerHelper.DeserializeObject(multipleRes["testKey1_3"]));


            store.Delete(StackExchangeRedisDataTypesEnum.String, new List <Tuple <string, object> >
            {
                Tuple.Create <string, object>("testKey1_1", null),
                Tuple.Create <string, object>("testKey1_2", null)
            });

            multipleRes = store.Get(StackExchangeRedisDataTypesEnum.String, new List <Tuple <string, object> >
            {
                Tuple.Create <string, object>("testKey1_1", null),
                Tuple.Create <string, object>("testKey1_2", null),
                Tuple.Create <string, object>("testKey1_3", null)
            });

            Assert.AreEqual(3, (int)BinarySerializerHelper.DeserializeObject(multipleRes["testKey1_3"]));
            Assert.AreEqual(1, multipleRes.Count);
        }
Exemple #19
0
        public bool SaveSurveyMain(string string_0, string string_1, SurveyMain surveyMain_0 = null)
        {
            if (surveyMain_0 == null)
            {
                surveyMain_0 = this.oSurveyMainDal.GetBySurveyId(string_0);
            }
            bool result;

            try
            {
                string text  = string_1 + this.OutputPath;
                string text2 = "S" + string_0 + GClass0.smethod_0("HĪɧͣѵ");
                string path  = text + GClass0.smethod_0("]") + text2;
                if (!Directory.Exists(text))
                {
                    Directory.CreateDirectory(text);
                }
                int outPutType = this.OutPutType;
                if (outPutType != 2)
                {
                    if (outPutType != 3)
                    {
                        XmlSerializer xmlSerializer = new XmlSerializer(typeof(SurveyMain));
                        FileStream    stream        = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
                        xmlSerializer.Serialize(stream, surveyMain_0);
                    }
                    else
                    {
                        BinarySerializerHelper.Serialize <SurveyMain>(surveyMain_0, text, text2);
                    }
                }
                else
                {
                    XmlSerializerHelper.Serialize <SurveyMain>(surveyMain_0, text, text2);
                }
                result = true;
            }
            catch (Exception ex)
            {
                Logging.Error.WriteLog(GClass0.smethod_0("QŅɋ̦іեٵݧ࠻"), ex.Message);
                result = false;
            }
            return(result);
        }
Exemple #20
0
        public static BasicQuotation Sum(List <BasicQuotation> basicQuotationList)
        {
            if (0 == basicQuotationList.Count)
            {
                throw new ArgumentException("basicQuotationList is empty");
            }
            if (1 == basicQuotationList.Count)
            {
                return(BinarySerializerHelper.Clone(basicQuotationList[0]));
            }
            // clone collection internally - just to keep invariant of the method.
            //
            List <BasicQuotation> clonedCollection = BinarySerializerHelper.Clone(basicQuotationList);
            BasicQuotation        firstElement     = clonedCollection[0];

            clonedCollection.RemoveAt(0);
            BasicQuotation sumOfTheTail = Sum(clonedCollection);

            return(Add(firstElement, sumOfTheTail));
        }
        /// <summary>
        /// Gets the  i-th closest non-zero volatility strike to money.
        /// </summary>
        /// <param name="expiry">The expiry.</param>
        /// <param name="i"></param>
        /// <returns></returns>
        public static double GetClosestNonZeroVolStrikeToMoney(ForwardExpiry expiry, int i)
        {
            decimal fwdPrice   = expiry.FwdPrice;
            var     expiryCopy = BinarySerializerHelper.Clone(expiry);

            //Remove strikes with zero vol in the search object
            //Want to return the location of the nearest *non-zero* strike
            foreach (Strike strike in expiryCopy.Strikes)
            {
                if (strike.Volatility.Value == 0)
                {
                    expiryCopy.RemoveStrike(strike.StrikePrice);
                }
            }
            var newStrikes = new double[expiryCopy.RawStrikePrices.Count];

            expiryCopy.RawStrikePrices.Sort();
            double[] strikes = expiryCopy.RawStrikePrices.ToArray();

            if (strikes.Length < i)
            {
                return(0);
            }
            var keys = new int[strikes.Length];

            for (int idx = 0; idx < strikes.Length; idx++)
            {
                newStrikes[idx] = strikes[idx] - (double)fwdPrice;
                keys[idx]       = idx;
            }
            //Get min distance to forward
            Array.Sort(newStrikes, keys, new DistanceComparer());
            if (i > 0)
            {
                return(expiryCopy.Strikes[keys[i - 1]].StrikePrice);
            }
            return(0);

            /* Bin search bitwise complement returns first element larger than search key
             * Returns Array Length + 1 if search key greater than all elements */
        }
        /// <summary>
        /// Creates a new app and a master fork
        /// On success sets the app id
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="name"></param>
        /// <param name="description"></param>
        public void CreateApp(int appId, string name, string description)
        {
            var        bytesAppIds = KeyValueStore.Get(KeyValueStore.DefaultType, KeyGenerator.AppsKey, null);
            List <int> appIds      = null;

            if (bytesAppIds != null)
            {
                appIds = (List <int>)BinarySerializerHelper.DeserializeObject(bytesAppIds);
            }
            else
            {
                appIds = new List <int>();
                KeyValueStore.Set(KeyValueStore.DefaultType, KeyGenerator.AppsKey, BinarySerializerHelper.SerializeObject(appIds), null);
            }

            if (appIds.Contains(appId))
            {
                throw new ArgumentException(nameof(appId));
            }

            appIds.Add(appId);

            KeyValueStore.Set(KeyValueStore.DefaultType, KeyGenerator.AppsKey, BinarySerializerHelper.SerializeObject(appIds), null);

            var res = new App
            {
                Id          = appId,
                Name        = name,
                Description = description
            };

            KeyValueStore.Set(KeyValueStore.DefaultType, KeyGenerator.GenerateAppKey(appId), ProtoBufSerializerHelper.Serialize(res), null);
            KeyValueStore.Set(KeyValueStore.DefaultType, KeyGenerator.GenerateForksKey(appId), BinarySerializerHelper.SerializeObject(new List <int>()), null);

            SetApp(appId);

            CreateMasterFork();
        }
Exemple #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PriceableFxOptionPremium"/> class.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="receiverPartyReference">The receiver.</param>
        /// <param name="payerIsBase">The flag determining if the payer is the base party.</param>
        /// <param name="amount">The amount.</param>
        /// <param name="settlementDate">The adjusted payment date.</param>
        /// <param name="payerPartyReference">The payer.</param>
        /// <param name="premiumQuote">The premium quote </param>
        /// <param name="settlementInformation">The settlement information. </param>
        /// <param name="paymentCalendar">Type paymentCalendar.</param>
        public PriceableFxOptionPremium
        (
            string id
            , string payerPartyReference
            , string receiverPartyReference
            , bool payerIsBase
            , Money amount
            , DateTime settlementDate
            , PremiumQuote premiumQuote
            , SettlementInformation settlementInformation
            , IBusinessCalendar paymentCalendar) :
            base(id, "DiscountedCashflow", payerIsBase, amount,
                 AdjustableOrAdjustedDateHelper.CreateAdjustedDate(settlementDate),
                 PaymentTypeHelper.Create("Certain"), CashflowTypeHelper.Create(CashflowTypeEnum.Premium.ToString()), false, paymentCalendar)
        {
            PayerPartyReference    = PartyReferenceFactory.Create(payerPartyReference);
            ReceiverPartyReference = PartyReferenceFactory.Create(receiverPartyReference);
            OrderedPartyNames.Add(PayerPartyReference.href);
            OrderedPartyNames.Add(ReceiverPartyReference.href);
            if (premiumQuote != null)
            {
                PremiumQuote = new PremiumQuote
                {
                    quoteBasis          = premiumQuote.quoteBasis,
                    quoteBasisSpecified = true,
                    value          = premiumQuote.value,
                    valueSpecified = true
                };
            }
            if (settlementInformation == null)
            {
                return;
            }
            SettlementInformation = new SettlementInformation();
            var item = BinarySerializerHelper.Clone(settlementInformation.Item);

            SettlementInformation.Item = item;
        }
Exemple #24
0
        public void StackExchangeRedisKeyValueStore_Hash()
        {
            var store = new StackExchangeRedisKeyValueStore("localhost:6379");

            store.Set(StackExchangeRedisDataTypesEnum.Hash, "testKey2", BinarySerializerHelper.SerializeObject(123), new StackExchangeRedisHashParams {
                HashField = "testKey2Hash"
            });
            var res = (int)BinarySerializerHelper.DeserializeObject(store.Get(StackExchangeRedisDataTypesEnum.Hash, "testKey2", new StackExchangeRedisHashParams {
                HashField = "testKey2Hash"
            }));

            Assert.AreEqual(123, res);

            store.Set(StackExchangeRedisDataTypesEnum.Hash, new List <Tuple <string, byte[], object> >
            {
                Tuple.Create <string, byte[], object>("testKey2_1", BinarySerializerHelper.SerializeObject(4), new StackExchangeRedisHashParams {
                    HashField = "testKey2_1_1"
                }),
                Tuple.Create <string, byte[], object>("testKey2_1", BinarySerializerHelper.SerializeObject(5), new StackExchangeRedisHashParams {
                    HashField = "testKey2_1_2"
                }),
                Tuple.Create <string, byte[], object>("testKey2_1", BinarySerializerHelper.SerializeObject(6), new StackExchangeRedisHashParams {
                    HashField = "testKey2_1_3"
                })
            });

            var multipleRes = store.Get(StackExchangeRedisDataTypesEnum.Hash, new List <Tuple <string, object> >
            {
                Tuple.Create <string, object>("testKey2_1", new StackExchangeRedisHashParams {
                    HashField = "testKey2_1_1"
                }),
                Tuple.Create <string, object>("testKey2_1", new StackExchangeRedisHashParams {
                    HashField = "testKey2_1_2"
                }),
                Tuple.Create <string, object>("testKey2_1", new StackExchangeRedisHashParams {
                    HashField = "testKey2_1_3"
                })
            });

            Assert.AreEqual(4, (int)BinarySerializerHelper.DeserializeObject(multipleRes["testKey2_1_1"]));
            Assert.AreEqual(5, (int)BinarySerializerHelper.DeserializeObject(multipleRes["testKey2_1_2"]));
            Assert.AreEqual(6, (int)BinarySerializerHelper.DeserializeObject(multipleRes["testKey2_1_3"]));


            store.Delete(StackExchangeRedisDataTypesEnum.Hash, new List <Tuple <string, object> >
            {
                Tuple.Create <string, object>("testKey2_1", new StackExchangeRedisHashParams {
                    HashField = "testKey2_1_2"
                }),
                Tuple.Create <string, object>("testKey2_1", new StackExchangeRedisHashParams {
                    HashField = "testKey2_1_3"
                })
            });
            multipleRes = store.Get(StackExchangeRedisDataTypesEnum.Hash, new List <Tuple <string, object> >
            {
                Tuple.Create <string, object>("testKey2_1", new StackExchangeRedisHashParams {
                    HashField = "testKey2_1_1"
                }),
                Tuple.Create <string, object>("testKey2_1", new StackExchangeRedisHashParams {
                    HashField = "testKey2_1_2"
                }),
                Tuple.Create <string, object>("testKey2_1", new StackExchangeRedisHashParams {
                    HashField = "testKey2_1_3"
                })
            });

            Assert.AreEqual(4, (int)BinarySerializerHelper.DeserializeObject(multipleRes["testKey2_1_1"]));
            Assert.AreEqual(1, multipleRes.Count);

            store.Delete(StackExchangeRedisDataTypesEnum.Hash, "testKey2_1", null);
            multipleRes = store.Get(StackExchangeRedisDataTypesEnum.Hash, new List <Tuple <string, object> >
            {
                Tuple.Create <string, object>("testKey2_1", new StackExchangeRedisHashParams {
                    HashField = "testKey2_1_1"
                }),
                Tuple.Create <string, object>("testKey2_1", new StackExchangeRedisHashParams {
                    HashField = "testKey2_1_2"
                }),
                Tuple.Create <string, object>("testKey2_1", new StackExchangeRedisHashParams {
                    HashField = "testKey2_1_3"
                })
            });
            Assert.AreEqual(0, multipleRes.Count);
        }
Exemple #25
0
        public IWorkflowContextController Init(CodeActivityContext codeActivityContext)
        {
            bool dictionaryCreate          = false;
            bool orgServiceCreate          = false;
            bool tracingServiceCreate      = false;
            bool currentUserCreate         = false;
            bool currentOrganizationCreate = false;
            bool orgServiceFactoryCreate   = false;

            IWorkflowContext            wfContext = codeActivityContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory sFactory  = codeActivityContext.GetExtension <IOrganizationServiceFactory>();
            IWorkflowContext            workContext;

            workContext = wfContext;

            while (workContext.ParentContext != null)
            {
                workContext = workContext.ParentContext;
            }


            //获取当前用户
            var currentUser = ContextContainer.GetValue <ICurrentUserInfoContext>(ContextTypes.CurrentUser);
            //获取当前组织编号
            var currentOrganization = ContextContainer.GetValue <Guid>(ContextTypes.CurrentOrganization);
            //获取dictorany
            var dict = ContextContainer.GetValue <Dictionary <string, object> >(ContextTypes.Dictionary);
            //获取orgService
            var orgService       = ContextContainer.GetValue <IOrganizationService>(ContextTypes.OrgService);
            var isAutoOrgService = ContextContainer.IsAuto <IOrganizationService>(ContextTypes.OrgService.ToString());
            //获取orgServiceFactory
            var orgServiceFactory = ContextContainer.GetValue <IOrganizationServiceFactory>(ContextTypes.OrgServiceFactory);
            //获取tracingService
            var tracingService = ContextContainer.GetValue <ITracingService>(ContextTypes.TracingService);



            //新建所有上下文
            if (currentUser == null || ContextContainer.IsAuto <ICurrentUserInfoContext>(ContextTypes.CurrentUser))
            {
                currentUserCreate = true;
                ContextContainer.SetValue <ICurrentUserInfoContext>(ContextTypes.CurrentUser, CurrentUserInfoContextFactory.Get().Create(workContext.InitiatingUserId));
            }


            if (currentOrganization == Guid.Empty || ContextContainer.IsAuto <Guid>(ContextTypes.CurrentOrganization))
            {
                currentOrganizationCreate = true;
                ContextContainer.SetValue <Guid>(ContextTypes.CurrentOrganization, workContext.OrganizationId);
            }

            if (tracingService == null || ContextContainer.IsAuto <ITracingService>(ContextTypes.TracingService))
            {
                tracingServiceCreate = true;
                ContextContainer.SetValue <ITracingService>(ContextTypes.TracingService, codeActivityContext.GetExtension <ITracingService>());
            }


            if (dict == null || ContextContainer.IsAuto <Dictionary <string, object> >(ContextTypes.Dictionary))
            {
                dictionaryCreate = true;
                if (workContext.SharedVariables.Contains("dictionary"))
                {
                    var dictionary = BinarySerializerHelper.Deserialize <Dictionary <string, object> >(workContext.SharedVariables["dictionary"].ToString());

                    ContextContainer.SetValue <Dictionary <string, object> >(ContextTypes.Dictionary, dictionary);

                    dict = dictionary;
                }
                else
                {
                    dict = new Dictionary <string, object>();
                    ContextContainer.SetValue <Dictionary <string, object> >(ContextTypes.Dictionary, dict);
                }
            }


            lock (dict)
            {
                dict[ContextDictionaryKeys.OrgName] = workContext.OrganizationName;
            }

            if (orgService == null || isAutoOrgService)
            {
                orgServiceCreate = true;
                //获取临时OrgService
                var tempOrgService          = sFactory.CreateOrganizationService(workContext.InitiatingUserId);
                var tempOrgServiceDiposable = tempOrgService as IDisposable;

                if (tempOrgServiceDiposable != null)
                {
                    using (tempOrgServiceDiposable)
                    {
                        ContextContainer.SetValue <IOrganizationService>(ContextTypes.OrgService, tempOrgService);
                        EntityReference administratorId = _configurationService.GetAdministratorID();
                        orgService = sFactory.CreateOrganizationService(administratorId.Id);

                        ContextContainer.SetValue <IOrganizationService>(ContextTypes.OrgService, orgService);
                    }
                }
                else
                {
                    ContextContainer.SetValue <IOrganizationService>(ContextTypes.OrgService, tempOrgService);
                    EntityReference administratorId = _configurationService.GetAdministratorID();
                    orgService = sFactory.CreateOrganizationService(administratorId.Id);

                    ContextContainer.SetValue <IOrganizationService>(ContextTypes.OrgService, orgService);
                }
            }



            if (orgServiceFactory == null || ContextContainer.IsAuto <IOrganizationServiceFactory>(ContextTypes.OrgServiceFactory))
            {
                orgServiceFactoryCreate = true;
                ContextContainer.SetValue <IOrganizationServiceFactory>(ContextTypes.OrgServiceFactory, sFactory);
            }


            return(new WorkflowContextController(workContext, dictionaryCreate, orgServiceCreate, tracingServiceCreate, currentUserCreate, currentOrganizationCreate, orgServiceFactoryCreate));
        }
Exemple #26
0
        public static void TransferObjects(DataTransferJob job, ref long cancelFlag)
        {
            int sourceSizeInBytes = 0;
            int sourceSizeInChars = 0;
            int targetSizeInBytes = 0;
            int targetSizeInChars = 0;
            var sourceItems       = new List <RawItem>();

            if ((job.SourceClient != null) || (job.SourceStream != null))
            {
                //logger.LogDebug("Loading ...");
                if (job.SourceStream != null)
                {
                    // source is a file
                    int loadCount = 0;
                    while (!job.SourceStream.EndOfStream)
                    {
                        string itemAsString = job.SourceStream.ReadLine();
                        var    item         = (RawItem)BinarySerializerHelper.DeserializeFromString(itemAsString);
                        if (item.ItemKind == (int)ItemKind.Object)
                        {
                            sourceSizeInBytes += item.YData?.Length ?? 0;
                            if (itemAsString != null)
                            {
                                sourceSizeInChars += itemAsString.Length;
                            }
                            sourceItems.Add(item);
                            loadCount++;
                            //if (loadCount % 2500 == 0)
                            //    logger.LogDebug("Loaded {0} objects ...", loadCount);
                        }
                        if (Interlocked.Add(ref cancelFlag, 0) > 0)
                        {
                            //logger.LogDebug("Transfer cancelled! ({0} objects loaded)", loadCount);
                            return;
                        }
                    }
                }
                else
                {
                    // source is a server
                    if (job.SourceClient != null)
                    {
                        List <ICoreItem> list = job.SourceClient.LoadUntypedItems(job.DataTypeName, ItemKind.Object, job.Filter, false);
                        foreach (ICoreItem item in list)
                        {
                            sourceSizeInBytes += item.SysProps.GetValue(SysPropName.ZLen, 0);
                            sourceSizeInChars += item.SysProps.GetValue(SysPropName.TLen, 0);
                            sourceItems.Add(new RawItem(item));
                        }
                    }
                }
            }
            if ((job.TargetClient != null) || (job.TargetStream != null))
            {
                int saveCount = 0;
                if (job.TargetStream != null)
                {
                    // to stream
                    foreach (RawItem item in sourceItems)
                    {
                        string itemAsString = BinarySerializerHelper.SerializeToString(item);
                        job.TargetStream.WriteLine(itemAsString);
                        targetSizeInBytes  = sourceSizeInBytes;
                        targetSizeInChars += itemAsString.Length;
                        saveCount++;
                        //if (saveCount % 2500 == 0)
                        //    logger.LogDebug("Saved {0} objects ...", saveCount);
                        if (Interlocked.Add(ref cancelFlag, 0) > 0)
                        {
                            //logger.LogDebug("Transfer cancelled! ({0} objects saved)", saveCount);
                            return;
                        }
                    }
                }
                else
                {
                    // to server
                    targetSizeInBytes = sourceSizeInBytes;
                    targetSizeInChars = sourceSizeInChars;
                    //
                    //This is where we can replace the appScope
                    //
                    //foreach(var item in sourceItems)
                    //{
                    //    item.AppScope = AppScopeNames.Current;
                    //}
                    job.TargetClient?.SaveRawItems(sourceItems);
                    saveCount += sourceItems.Count;
                }
                job.TargetStream?.Flush();
                //logger.LogDebug("Saved {0} objects ({1} chars, {2} bytes)", saveCount, targetSizeInChars, targetSizeInBytes);
            }
            else
            {
                //if(!job.ReadOnly)
                //    logger.LogError("No target specified!");
            }
        }
        public bool Set <T>(TDataTypesEnum type, IEnumerable <Tuple <string, T, object> > values)
        {
            if (Fork.ReadOnly)
            {
                return(false);
            }

            KeyValueStore.Delete(type, values.Select(x => Tuple.Create(KeyGenerator.GenerateForkNullKey(AppId, Fork.Id, x.Item1), x.Item3)));

            var forkedValues = values.Select(x => Tuple.Create(KeyGenerator.GenerateForkValueKey(AppId, Fork.Id, x.Item1), x.Item2 as byte[] ?? BinarySerializerHelper.SerializeObject(x.Item2), x.Item3));

            return(KeyValueStore.Set(type, forkedValues));
        }
        public bool Delete(TDataTypesEnum type, string key, object extraParams = null)
        {
            if (Fork.ReadOnly)
            {
                return(false);
            }

            var res = KeyValueStore.Delete(type, KeyGenerator.GenerateForkValueKey(AppId, Fork.Id, key), extraParams);

            if (Fork.GetAllParents().Any(x => KeyValueStore.Exists(type, KeyGenerator.GenerateForkValueKey(AppId, x.Id, key), extraParams)))
            {
                return(KeyValueStore.Set(type, KeyGenerator.GenerateForkNullKey(AppId, Fork.Id, key), BinarySerializerHelper.SerializeObject(type), extraParams));
            }

            return(res);
        }
        public IDictionary <string, T> Get <T>(TDataTypesEnum type, IEnumerable <Tuple <string, object> > keys)
        {
            var currentFork = Fork;
            var missingKeys = keys.Select(x => x.Item1).ToList();

            // Easy access to tuple data
            var keysDict = keys.ToDictionary(x => x.Item1, x => x.Item2);

            var res = new Dictionary <string, T>();

            while (currentFork != null)
            {
                var keysForGet = new List <Tuple <string, object> >();
                var generatedKeyToOriginalKey = new Dictionary <string, string>();

                foreach (var key in missingKeys)
                {
                    var generatedKey = KeyGenerator.GenerateForkValueKey(AppId, currentFork.Id, key);
                    keysForGet.Add(Tuple.Create(generatedKey, keysDict[key]));
                    generatedKeyToOriginalKey[generatedKey] = key;
                }

                var byteValues = KeyValueStore.Get(type, keysForGet);

                if (typeof(T) == typeof(byte[]))
                {
                    foreach (var key in byteValues.Keys)
                    {
                        res[generatedKeyToOriginalKey[key]] = (T)Convert.ChangeType(byteValues[key], typeof(T));
                    }
                }
                else
                {
                    foreach (var key in byteValues.Keys)
                    {
                        res[generatedKeyToOriginalKey[key]] = (T)BinarySerializerHelper.DeserializeObject(byteValues[key]);
                    }
                }

                missingKeys = missingKeys.Except(byteValues.Keys.Select(x => generatedKeyToOriginalKey[x])).ToList();

                var nullMissingKeys = new List <string>();
                foreach (var missingKey in missingKeys.ToList())
                {
                    if (KeyValueStore.Exists(type, KeyGenerator.GenerateForkNullKey(AppId, currentFork.Id, missingKey), keysDict[missingKey]))
                    {
                        nullMissingKeys.Add(missingKey);
                    }
                }

                missingKeys = missingKeys.Except(nullMissingKeys).ToList();

                if (missingKeys.Count == 0)
                {
                    break;
                }

                currentFork = currentFork.Parent;
            }

            return(res);
        }
        private void UpdateForks()
        {
            var changedForkIds = new HashSet <int>();

            var updatedForkIds = (List <int>)BinarySerializerHelper.DeserializeObject(Store.Get(Store.DefaultType, KeyGenerator.GenerateForksKey(AppId), null));
            var newForkIds     = updatedForkIds.Except(_forks.Keys);

            foreach (var newForkId in newForkIds)
            {
                var bytesNewRawFork = Store.Get(Store.DefaultType, KeyGenerator.GenerateForkKey(AppId, newForkId), null);
                if (bytesNewRawFork == null)
                {
                    continue;
                }

                var newRawFork = ProtoBufSerializerHelper.Deserialize <ForkRawData>(bytesNewRawFork);

                var bytesNewForkTimeStamp = Store.Get(Store.DefaultType, KeyGenerator.GenerateForkTimeStampKey(AppId, newForkId), null);
                if (bytesNewForkTimeStamp == null)
                {
                    continue;
                }

                var newForkTimeStamp = (DateTime)BinarySerializerHelper.DeserializeObject(bytesNewForkTimeStamp);

                var parentFork = newRawFork.ParentId == 0 ? null : _forks[newRawFork.ParentId];
                var newFork    = new Fork
                {
                    Id              = newForkId,
                    Name            = newRawFork.Name,
                    Description     = newRawFork.Description,
                    IsInGracePeriod = newRawFork.IsInGracePeriod,
                    Parent          = parentFork
                };

                if (parentFork != null)
                {
                    parentFork.Children.Add(newFork);
                    changedForkIds.Add(parentFork.Id);
                }

                _forks[newForkId]           = newFork;
                _forksTimeStamps[newForkId] = newForkTimeStamp;
            }
            var toDel = _forks.Keys.Except(updatedForkIds).ToList();

            foreach (var toDelFork in toDel)
            {
                _forks.Remove(toDelFork);
                _forksTimeStamps.Remove(toDelFork);
            }

            foreach (var forkId in _forks.Keys.ToList())
            {
                var newTimeStamp          = (DateTime)BinarySerializerHelper.DeserializeObject(Store.Get(Store.DefaultType, KeyGenerator.GenerateForkTimeStampKey(AppId, forkId), null));
                var _currentForkTimeStamp = _forksTimeStamps[forkId];
                if (newTimeStamp > _currentForkTimeStamp)
                {
                    var rawFork = ProtoBufSerializerHelper.Deserialize <ForkRawData>(Store.Get(Store.DefaultType, KeyGenerator.GenerateForkKey(AppId, forkId), null));
                    _forksTimeStamps[forkId] = newTimeStamp;

                    UpdateFork(_forks[forkId], rawFork);
                    changedForkIds.Add(forkId);
                }
            }

            RaiseForkChanged(changedForkIds.ToList());
        }