T IKeyed <T> .this[IKey key]
 {
     get
     {
         return(_dict.GetOrAdd(key, k => IoC.Resolve <T>(new TypedParameter(key.GetType(), key))));
     }
 }
Exemplo n.º 2
0
        private async Task SendEmbedToBotOwner(ICommandContext context, IKey key)
        {
            SocketUser owner  = Client.GetUser(ConfigProperties.BotConfig.BotOwnerId);
            var        fields = new List <EmbedFieldBuilder>
            {
                new EmbedFieldBuilder
                {
                    IsInline = false,
                    Name     = "Key Properties",
                    Value    = $"Key: `{key.Key}`\nCreated by: `{owner}`\nExpires: " +
                               $"`{DateTime.Now.AddSeconds(key.LengthInSeconds).Humanize(false)}`"
                }
            };

            if (key.GetType() == typeof(PremiumKey))
            {
                var embed = new KaguyaEmbedBuilder
                {
                    Description = $"User `{context.User}` has just redeemed a " +
                                  $"Kaguya Premium key!",
                    Fields = fields
                };

                try
                {
                    await owner.SendMessageAsync(embed : embed.Build());
                }
                catch (HttpException)
                {
                    await ConsoleLogger.LogAsync("Attempted to DM an owner a notification about a " +
                                                 "Kaguya Premium key redemption, but a " +
                                                 "Discord.Net.HttpException was thrown.", LogLvl.WARN);
                }
            }
        }
Exemplo n.º 3
0
        protected bool GetHelper(IKey key)
        {
            bool isContained = false;

            if (!key.GetType().Equals(typeof(KeyType)))
            {
                throw new InvalidDataException("Invalid IKey Type");
            }

            /*
             * string keyHash = StreamFactory.GetString(
             *                  sha1.ComputeHash(StreamFactory.GetBytes(key)));
             */

            if (index.ContainsKey(key))
            // if (indexHeader.ContainsKey(key))
            {
                // TODO: this could just have been a simple collision
                //   -- make sure that this is the same key
                //   -- if different, use a secondary hash function

                isContained = true;
            }
            return(isContained);
        }
        protected static Collection<Dictionary<string, string>> ValidateDtoData(IKey dto, EntityBase entity)
        {
            var retVal = new Collection<Dictionary<string, string>>();
            var fieldName = string.Empty;
            foreach (var inputField in dto.GetType().GetProperties().Where(x => x.Name != "Key" && x.GetValue(dto) != null)) {
                if (inputField.Name.StartsWith("Start_")) {
                    fieldName = inputField.Name.Substring(6);
                } else if(inputField.Name.StartsWith("End_")){
                    fieldName = inputField.Name.Substring(4);
                } else if(inputField.Name.Contains("__")) {
                    //  using field from a different table
                    //      not currently handling this case
                } else {
                    fieldName = inputField.Name;
                }
                //  insure the entity contains the field represented by fieldName
                var entityFieldName = entity.GetType().GetProperty(fieldName);
                if (entityFieldName == null || entityFieldName.Name.Length == 0) {
                    //  entity does not contain this field
                    continue;
                }
                if (entity.GetDataType(fieldName) == typeof(string)) {
                    //  should be ok
                    continue;
                }
                if (entity.GetDataType(fieldName) == typeof(int) || entity.GetDataType(fieldName) == typeof(int?)) {
                    var nbr = 0;
                    if (!int.TryParse(inputField.GetValue(dto).ToString(), out nbr)) {

                        var dic = new Dictionary<string, string> {{inputField.Name, "Invalid data type cast"}};
                        retVal.Add(dic);
                    }
                    if (entity.GetDataType(fieldName) == typeof(bool) || entity.GetDataType(fieldName) == typeof(bool?)) {
                        if (inputField.GetValue(dto).ToString().ToLower() != "true" && inputField.GetValue(dto).ToString().ToLower() != "false") {
                            var dic = new Dictionary<string, string> { { inputField.Name, "Invalid data type cast" } };
                            retVal.Add(dic);
                        }
                    }
                    if (entity.GetDataType(fieldName) == typeof(DateTime) || entity.GetDataType(fieldName) == typeof(DateTime?)) {
                        DateTime dt;
                        if (!DateTime.TryParse(inputField.GetValue(dto).ToString(), out dt)) {
                            var dic = new Dictionary<string, string> { { inputField.Name, "Invalid data type cast" } };
                            retVal.Add(dic);
                        }
                    }
                    if (entity.GetDataType(fieldName) == typeof(decimal) || entity.GetDataType(fieldName) == typeof(decimal?)) {
                        decimal d;
                        if (!decimal.TryParse(inputField.GetValue(dto).ToString(), out d)) {
                            var dic = new Dictionary<string, string> { { inputField.Name, "Invalid data type cast" } };
                            retVal.Add(dic);
                        }
                    }
                }
            }
            return retVal;
        }
Exemplo n.º 5
0
        /// <summary>
        /// Tries to convert/cast <paramref name="key"/> to the type <typeparamref name="TKey"/>.
        /// </summary>
        /// <typeparam name="TKey">The requested type of key.</typeparam>
        /// <param name="key">The key to convert/cast.</param>
        /// <returns>The converted/casted key.</returns>
        /// <exception cref="RequiredKeyOfClassException">When the <paramref name="key"/> is not of the <typeparamref name="TKey"/>.</exception>
        public static TKey As <TKey>(this IKey key)
            where TKey : class, IKey
        {
            if (key is TKey target)
            {
                return(target);
            }

            throw new RequiredKeyOfClassException(key.GetType(), typeof(TKey));
        }
Exemplo n.º 6
0
        /// <summary>
        /// Tries to convert/cast <paramref name="key"/> to the type <typeparamref name="TKey"/>.
        /// </summary>
        /// <typeparam name="TKey">The requested type of key.</typeparam>
        /// <param name="key">The key to convert/cast.</param>
        /// <returns>The converted/casted key.</returns>
        /// <exception cref="RequiredKeyOfClassException">When the <paramref name="key"/> is not of the <typeparamref name="TKey"/>.</exception>
        public static TKey As <TKey>(this IKey key)
            where TKey : class, IKey
        {
            TKey target = key as TKey;

            if (target == null)
            {
                throw new RequiredKeyOfClassException(key.GetType(), typeof(TKey));
            }

            return(target);
        }
Exemplo n.º 7
0
 public virtual Boolean sameAs(IKey key)
 {
     if (typeof(TypeKey).IsAssignableFrom(key.GetType()))
     {
         var typeKey = (TypeKey)key;
         return(typeKey.type.IsAssignableFrom(type));
     }
     else
     {
         return(false);
     }
 }
Exemplo n.º 8
0
        public IEnumerable <EventModel> Get(IKey aggregateKey, int version)
        {
            Ensure.Condition.NotEmptyKey(aggregateKey, "aggregateKey");

            GuidKey key = aggregateKey as GuidKey;

            if (key == null)
            {
                throw Ensure.Exception.NotGuidKey(aggregateKey.GetType(), "aggregateKey");
            }

            IEnumerable <EventEntity> entities = contextFactory().Events
                                                 .Where(e => e.AggregateType == key.Type && e.AggregateID == key.Guid && e.Version > version)
                                                 .OrderBy(e => e.Version);

            return(entities.Select(e => e.ToModel()));
        }
Exemplo n.º 9
0
        private string GetMovieId(IKey key)
        {
            string id = null;

            if (key is GuidKey guidKey)
            {
                id = guidKey.Guid.ToString();
            }
            else if (key is StringKey stringKey)
            {
                id = stringKey.Identifier;
            }
            else
            {
                throw Ensure.Exception.NotSupported($"Not supported key of class '{key.GetType()}'.");
            }

            return(id);
        }
Exemplo n.º 10
0
 public override Boolean sameAs(IKey key)
 {
     if (base.sameAs(key))
     {
         if (key.GetType() == typeof(NamedTypeKey))
         {
             var typeKeyWithName = (NamedTypeKey)key;
             return(typeKeyWithName.name == name);
         }
         else
         {
             return(false);
         }
     }
     else
     {
         return(false);
     }
 }
        public IKeyToParametersConverter Add(IKeyValueCollection parameters, IKey key)
        {
            Ensure.NotNull(parameters, "parameters");
            Ensure.NotNull(key, "key");

            if (!key.IsEmpty)
            {
                Type keyType = key.GetType();
                Action <IKeyValueCollection, IKey> handler;
                if (!Definitions.keyToParameters.TryGetValue(keyType, out handler))
                {
                    throw new MissingKeyClassToParametersMappingException(keyType);
                }

                handler(parameters, key);
            }

            return(this);
        }
Exemplo n.º 12
0
        /// <summary>
        /// conversion function to transform string values from parameter 
        /// object received by a Web API into an object that can be
        /// saved or updated in the database
        /// </summary>        
        public void ProcessRecord(IKey dto)
        {
            foreach (var inputField in dto.GetType().GetProperties().Where(x => x.Name != "Key" && x.GetValue(dto) != null)) {
                var fieldName = string.Empty;
                Type type;
                if (inputField.Name.StartsWith("Start_")) {
                    fieldName = inputField.Name.Substring(6);
                } else if (inputField.Name.StartsWith("End_")) {
                    fieldName = inputField.Name.Substring(4);
                } else if (inputField.Name.Contains("__")) {
                    //  this represents a field in another table, we aren't going
                    //      to attempt handling recursive searching at this time
                    continue;
                } else {
                    fieldName = inputField.Name;
                }

                if (fieldName != this.KeyName()) {
                    var matchingField = this.GetType().GetProperty(fieldName);
                    if (matchingField == null) {
                        //  represents a field in another object used in searching
                        continue;
                    }
                    type = GetDataType(fieldName);
                    if (type == typeof(string)) {
                        var value = inputField.GetValue(dto).ToString();
                        matchingField.SetValue(this, value);
                        continue;
                    }
                    if (type == typeof(int) || type == typeof(int?)) {
                        var value = int.Parse(inputField.GetValue(dto).ToString());
                        matchingField.SetValue(this, value);
                        continue;
                    }

                    if (type == typeof(bool) || type == typeof(bool?)) {
                        var value = bool.Parse(inputField.GetValue(dto).ToString());
                        matchingField.SetValue(this, value);
                        continue;
                    }

                    if (type == typeof(DateTime) || type == typeof(DateTime?)) {
                        var value = DateTime.Parse(inputField.GetValue(dto).ToString());
                        matchingField.SetValue(this, value);
                        continue;
                    }

                    if (type == typeof(decimal) || type == typeof(decimal?)) {
                        var value = decimal.Parse(inputField.GetValue(dto).ToString());
                        matchingField.SetValue(this, value);
                    }

                    if (type == typeof(byte[]))
                    {
                        var value = System.Text.Encoding.UTF8.GetBytes(inputField.GetValue(dto).ToString());
                        matchingField.SetValue(this, value);
                    }

                }
            }
        }
Exemplo n.º 13
0
        public string GetPredicate(IKey dto, EntityBase entity, string companyId)
        {
            var sb  = new StringBuilder();
            var fld = dto.GetType().GetProperty("CompanyID");

            if (fld != null)
            {
                var type = entity.GetDataType("CompanyID");
                if (type == typeof(string))
                {
                    sb.Append(string.Format("{0}{1}{2}", "CompanyID", "==", companyId));
                }
                if (type == typeof(int?))
                {
                    sb.Append(string.Format("{0}{1}{2}{3}", "CompanyID", ".Value", "==", companyId));
                }
            }
            foreach (var field in dto.GetType().GetProperties().Where(x => x.Name != "Key" && x.GetValue(dto) != null))
            {
                var value = field.GetValue(dto).ToString();
                if (!string.IsNullOrEmpty(value))
                {
                    if (sb.Length > 0)
                    {
                        sb.Append(" && ");
                    }
                    if (field.Name.Contains("__"))
                    {
                        //  embedded table.field reference
                        sb.Append(FormatEmbeddedReference(field, field.GetValue(dto).ToString()));
                    }
                    else
                    {
                        var fieldName = string.Empty;
                        if (field.Name.StartsWith("Start_"))
                        {
                            fieldName = field.Name.Substring(6);
                        }
                        else if (field.Name.StartsWith("End_"))
                        {
                            fieldName = field.Name.Substring(4);
                        }
                        else
                        {
                            fieldName = field.Name;
                        }
                        var type = entity.GetDataType(fieldName);
                        if (type == typeof(string))
                        {
                            sb.Append(fieldName + ".Contains('");
                            sb.Append(String.Format("{0}{1}", field.GetValue(dto), "')"));
                            //sb.Append(field.GetValue(dto) + ")");
                            continue;
                        }
                        if (type == typeof(int))
                        {
                            sb.Append(string.Format("{0}{1}{2}", fieldName, "==", int.Parse(field.GetValue(dto).ToString())));
                            continue;
                        }
                        if (type == typeof(int?))
                        {
                            sb.Append(string.Format("{0}{1}{2}{3}", fieldName, ".Value", "==", int.Parse(field.GetValue(dto).ToString())));
                            continue;
                        }
                        if (type == typeof(bool))
                        {
                            sb.Append(string.Format("{0}{1}{2}", fieldName, "==", bool.Parse(field.GetValue(dto).ToString())));
                            continue;
                        }
                        if (type == typeof(bool?))
                        {
                            sb.Append(string.Format("{0}{1}{2}{3}", fieldName, ".Value", "==", bool.Parse(field.GetValue(dto).ToString())));
                            continue;
                        }
                        if (type == typeof(DateTime?))
                        {
                            var comparer = string.Empty;
                            var date     = string.Empty;
                            if (field.Name.StartsWith("Start_"))
                            {
                                comparer = ">";
                                date     = DateTime.Parse(field.GetValue(dto).ToString()).AddDays(-1).ToShortDateString();
                            }
                            else
                            {
                                comparer = "<";
                                date     = DateTime.Parse(field.GetValue(dto).ToString()).AddDays(1).ToShortDateString();
                            }
                            fieldName = fieldName + ".Value";
                            sb.Append(String.Format("{0}{1}{2}{3}{2}", fieldName, comparer, "'", date));
                            continue;
                        }
                        if (type == typeof(DateTime))
                        {
                            var comparer = string.Empty;
                            var date     = string.Empty;
                            if (field.Name.StartsWith("Start_"))
                            {
                                comparer = ">";
                                date     = DateTime.Parse(field.GetValue(dto).ToString()).AddDays(-1).ToShortDateString();
                            }
                            else
                            {
                                comparer = "<";
                                date     = DateTime.Parse(field.GetValue(dto).ToString()).AddDays(1).ToShortDateString();
                            }
                            sb.Append(String.Format("{0}{1}{2}{3}{2}", fieldName, comparer, "'", date));
                            continue;
                        }
                        if (type == typeof(decimal))
                        {
                            sb.Append(string.Format("{0}{1}{2}", fieldName, "==", decimal.Parse(field.GetValue(dto).ToString())));
                        }
                        if (type == typeof(decimal?))
                        {
                            sb.Append(string.Format("{0}{1}{2}{3}", fieldName, ".Value", "==", decimal.Parse(field.GetValue(dto).ToString())));
                        }
                    }
                }
            }
            return(sb.ToString());
        }
Exemplo n.º 14
0
        /// <summary>
        /// conversion function to transform string values from parameter
        /// object received by a Web API into an object that can be
        /// saved or updated in the database
        /// </summary>
        public void ProcessRecord(IKey dto)
        {
            foreach (var inputField in dto.GetType().GetProperties().Where(x => x.Name != "Key" && x.GetValue(dto) != null))
            {
                var  fieldName = string.Empty;
                Type type;
                if (inputField.Name.StartsWith("Start_"))
                {
                    fieldName = inputField.Name.Substring(6);
                }
                else if (inputField.Name.StartsWith("End_"))
                {
                    fieldName = inputField.Name.Substring(4);
                }
                else if (inputField.Name.Contains("__"))
                {
                    //  this represents a field in another table, we aren't going
                    //      to attempt handling recursive searching at this time
                    continue;
                }
                else
                {
                    fieldName = inputField.Name;
                }

                if (fieldName != this.KeyName())
                {
                    var matchingField = this.GetType().GetProperty(fieldName);
                    if (matchingField == null)
                    {
                        //  represents a field in another object used in searching
                        continue;
                    }
                    type = GetDataType(fieldName);
                    if (type == typeof(string))
                    {
                        var value = inputField.GetValue(dto).ToString();
                        matchingField.SetValue(this, value);
                        continue;
                    }
                    if (type == typeof(int) || type == typeof(int?))
                    {
                        var value = int.Parse(inputField.GetValue(dto).ToString());
                        matchingField.SetValue(this, value);
                        continue;
                    }

                    if (type == typeof(bool) || type == typeof(bool?))
                    {
                        var value = bool.Parse(inputField.GetValue(dto).ToString());
                        matchingField.SetValue(this, value);
                        continue;
                    }

                    if (type == typeof(DateTime) || type == typeof(DateTime?))
                    {
                        var value = DateTime.Parse(inputField.GetValue(dto).ToString());
                        matchingField.SetValue(this, value);
                        continue;
                    }

                    if (type == typeof(decimal) || type == typeof(decimal?))
                    {
                        var value = decimal.Parse(inputField.GetValue(dto).ToString());
                        matchingField.SetValue(this, value);
                    }

                    if (type == typeof(byte[]))
                    {
                        var value = System.Text.Encoding.UTF8.GetBytes(inputField.GetValue(dto).ToString());
                        matchingField.SetValue(this, value);
                    }
                }
            }
        }
Exemplo n.º 15
0
        //protected static int ValidateUser(string oldKey, out string newKey, ref string companyId) {
        //    var ur = new AppUserRepository();
        //    return ur.ValidateUser(oldKey, out newKey, ref companyId);
        //}

        protected static Collection <Dictionary <string, string> > ValidateDtoData(IKey dto, EntityBase entity)
        {
            var retVal    = new Collection <Dictionary <string, string> >();
            var fieldName = string.Empty;

            foreach (var inputField in dto.GetType().GetProperties().Where(x => x.Name != "Key" && x.GetValue(dto) != null))
            {
                if (inputField.Name.StartsWith("Start_"))
                {
                    fieldName = inputField.Name.Substring(6);
                }
                else if (inputField.Name.StartsWith("End_"))
                {
                    fieldName = inputField.Name.Substring(4);
                }
                else if (inputField.Name.Contains("__"))
                {
                    //  using field from a different table
                    //      not currently handling this case
                }
                else
                {
                    fieldName = inputField.Name;
                }
                //  insure the entity contains the field represented by fieldName
                var entityFieldName = entity.GetType().GetProperty(fieldName);
                if (entityFieldName == null || entityFieldName.Name.Length == 0)
                {
                    //  entity does not contain this field
                    continue;
                }
                if (entity.GetDataType(fieldName) == typeof(string))
                {
                    //  should be ok
                    continue;
                }
                if (entity.GetDataType(fieldName) == typeof(int) || entity.GetDataType(fieldName) == typeof(int?))
                {
                    var nbr = 0;
                    if (!int.TryParse(inputField.GetValue(dto).ToString(), out nbr))
                    {
                        var dic = new Dictionary <string, string> {
                            { inputField.Name, "Invalid data type cast" }
                        };
                        retVal.Add(dic);
                    }
                    if (entity.GetDataType(fieldName) == typeof(bool) || entity.GetDataType(fieldName) == typeof(bool?))
                    {
                        if (inputField.GetValue(dto).ToString().ToLower() != "true" && inputField.GetValue(dto).ToString().ToLower() != "false")
                        {
                            var dic = new Dictionary <string, string> {
                                { inputField.Name, "Invalid data type cast" }
                            };
                            retVal.Add(dic);
                        }
                    }
                    if (entity.GetDataType(fieldName) == typeof(DateTime) || entity.GetDataType(fieldName) == typeof(DateTime?))
                    {
                        DateTime dt;
                        if (!DateTime.TryParse(inputField.GetValue(dto).ToString(), out dt))
                        {
                            var dic = new Dictionary <string, string> {
                                { inputField.Name, "Invalid data type cast" }
                            };
                            retVal.Add(dic);
                        }
                    }
                    if (entity.GetDataType(fieldName) == typeof(decimal) || entity.GetDataType(fieldName) == typeof(decimal?))
                    {
                        decimal d;
                        if (!decimal.TryParse(inputField.GetValue(dto).ToString(), out d))
                        {
                            var dic = new Dictionary <string, string> {
                                { inputField.Name, "Invalid data type cast" }
                            };
                            retVal.Add(dic);
                        }
                    }
                }
            }
            return(retVal);
        }
Exemplo n.º 16
0
        protected void UpdateHelper(IKey key, IValue value, bool IsAppend)
        {
            if (!key.GetType().Equals(typeof(KeyType)))
            {
                throw new InvalidDataException("Invalid IKey Type");
            }
            if (!value.GetType().Equals(typeof(ValType)))
            {
                throw new InvalidDataException("Invalid IValue Type");
            }

            /*
             * string keyHash = StreamFactory.GetString(
             *                  sha1.ComputeHash(StreamFactory.GetBytes(key)));
             */

            List <TS_Offset> offsets;

            // check if the entry is present (and record offset)
            if (index.ContainsKey(key))
            {
                // TODO: this could just have been a simple collision
                //   -- make sure that this is the same key
                //   -- if different, use a secondary hash function

                offsets = index[key];
            }
            else
            {
                offsets    = new List <TS_Offset>();
                index[key] = offsets;
            }

            // get file offset; add <key_hash, offset> to index
            fs_bw.BaseStream.Seek(0, SeekOrigin.End);
            long offset = fs_bw.BaseStream.Position;

            // write <op (1B), ts, key, val_len, val>
            byte op;

            if (IsAppend)
            {
                op = (byte)WriteOp.AppendOp;
            }
            else
            {
                op = (byte)WriteOp.UpdateOp;
            }
            long ts = StreamFactory.NowUtc();
            DataBlock <KeyType, ValType> db = new DataBlock <KeyType, ValType>();

            db.op        = op;
            db.timestamp = ts;
            db.key       = key;
            db.value     = value;
            fs_bw.Write(db.SerializeToJsonStream());
            fs_bw.Flush();

            latest_tso = new TS_Offset(ts, offset);
            // apply to index
            if (IsAppend)
            {
                offsets.Add(latest_tso);
            }
            else
            {
                if (offsets.Count == 0)
                {
                    offsets.Add(latest_tso);
                }
                else
                {
                    offsets[offsets.Count - 1] = latest_tso;
                }
            }
            /* ts_index.Add(new TS_Offset(ts, offset)); */
        }
Exemplo n.º 17
0
        protected long UpdateHelper(IKey key, IValue value, bool IsAppend, Byte[] valHash = null, long timestamp = -1, long offsetInStream = -1)
        {
            long offset;

            if (!key.GetType().Equals(typeof(KeyType)))
            {
                throw new InvalidDataException("Invalid IKey Type");
            }
            if (!value.GetType().Equals(typeof(ValType)))
            {
                throw new InvalidDataException("Invalid IValue Type");
            }

            if (logger != null)
            {
                logger.Log("Start ValueDataStream Tag Lookup");
            }
            List <DataBlockInfo> offsets;

            // check if the entry is present (and record offset)
            if (index.ContainsKey(key))
            {
                // TODO: this could just have been a simple collision
                //   -- make sure that this is the same key
                //   -- if different, use a secondary hash function

                offsets = index[key];
            }
            else
            {
                offsets    = new List <DataBlockInfo>();
                index[key] = offsets;
                // IncrementIndexSize(offsets.Count);
                IncrementIndexSize(1);
            }
            if (logger != null)
            {
                logger.Log("End ValueDataStream Tag Lookup");
            }

            if (logger != null)
            {
                logger.Log("Start ValueDataStream Construct DataBlock");
            }
            // write <op (1B), ts, key, val_len, val>
            byte op;

            if (IsAppend)
            {
                op = (byte)WriteOp.AppendOp;
            }
            else
            {
                op = (byte)WriteOp.UpdateOp;
            }


            long ts;

            // Construct datablock
            if (timestamp == -1)
            {
                ts = StreamFactory.NowUtc();
            }
            else
            {
                ts = timestamp;
            }

            DataBlock <KeyType, ValType> db = new DataBlock <KeyType, ValType>();

            db.op = op;
            //db.timestamp = ts;
            //db.setKey(key);

            /*
             * Commenting out because the synchronizer will do this now at the chunk level
             * if (streamtype == StreamFactory.StreamSecurityType.Secure)
             * {
             *  //if (logger != null) logger.Log("Start encrypting value");
             *  db.value = new ByteValue(Crypto.EncryptBytesSimple(value.GetBytes(), Crypto.KeyDer(acl_md.encKey), acl_md.IV));
             *  //if (logger != null) logger.Log("End encrypting value");
             * }
             * else*/
            {
                //db.value = new ByteValue(value.GetBytes());
                db.setValue(value);
            }
            if (logger != null)
            {
                logger.Log("End ValueDataStream Construct DataBlock");
            }

            if (offsetInStream == -1)
            {
                if (logger != null)
                {
                    logger.Log("Start ValueDataStream Serialize DataBlock");
                }
                //Byte[] buffer = db.SerializeToByteStream().ToArray();
                Byte[] buffer = SerializerHelper <DataBlock <KeyType, ValType> > .SerializeToProtoStream(db).ToArray();

                if (logger != null)
                {
                    logger.Log("End ValueDataStream Serialize DataBlock");
                }

                if (logger != null)
                {
                    logger.Log("Start ValueDataStream WriteToDisc DataBlock");
                }
                // fs_bw.Write(db.SerializeToJsonStream());
                // get file offset; add <key_hash, offset> to index
                fs_bw.BaseStream.Seek(0, SeekOrigin.End);
                offset = fs_bw.BaseStream.Position;
                fs_bw.Write(buffer.Length);
                fs_bw.Write(buffer);
                fs_bw.Flush();
                if (logger != null)
                {
                    logger.Log("End ValueDataStream WriteToDisc DataBlock");
                }
            }
            else
            {
                offset = offsetInStream;
            }
            // Construct dbinfo in index
            if (logger != null)
            {
                logger.Log("Start ValueDataStream Construct and Add DataBlockInfo");
            }
            DataBlockInfo latest_tso = new DataBlockInfo(ts, offset);

            if (streamtype == StreamFactory.StreamSecurityType.Secure)
            {
                if (valHash != null) // passed from the dir stream and written into datablockinfo. not written for file stream
                {
                    latest_tso.hashValue = valHash;
                }

                /*
                 *  else
                 *  {
                 *      if (logger != null) logger.Log("Start taking hash of encrypted value");
                 *      latest_tso.hashValue = hasher.ComputeHash(db.value.GetBytes());
                 *      if (logger != null) logger.Log("End taking hash of encrypted value");
                 *
                 *  }
                 *   latest_tso.key_version = acl_md.keyVersion;
                 */
            }

            // apply to index
            if (IsAppend)
            {
                offsets.Add(latest_tso);
                // IncrementIndexSize();
            }
            else
            {
                if (offsets.Count == 0)
                {
                    offsets.Add(latest_tso);
                    // IncrementIndexSize();
                }
                else
                {
                    offsets[offsets.Count - 1] = latest_tso;
                }
            }
            if (logger != null)
            {
                logger.Log("End ValueDataStream Construct and Add DataBlockInfo");
            }
            return(offset);
        }