public static HashEntry[] ToHashEntryArray(this Dictionary<string, string> Items)
 {
     var Entries = new HashEntry[Items.Count];
     int i = 0;
     foreach (var Item in Items)
     {
         Entries[i++] = new HashEntry(Item.Key, Item.Value);
     }
     return Entries;
 }
 public LngFile(Stream fileStream)
 {
     using (LngBinaryReader b = new LngBinaryReader(EndianBitConverter.Big, fileStream))
     {
         byte[] keys, values;
         hasChanges = false;
         magic = b.ReadInt32();
         // SIZE - Skip
         b.ReadInt32();
         // Hash Section (HSHS)
         hshs = new Hshs(b);
         // Hash Table (HSHT)
         hsht = new Hsht(b);
         // Offsets (SIDA)
         sida = new SidA(b);
         // Keys (SIDB)
         sidb = new SidB(b);
         keys = b.ReadBytes(sidb.Size);
         // Values (LNGB)
         lngb = new LngB(b);
         values = b.ReadBytes(lngb.Size);
         count = sida.Entry.Length;
         for (int i = 0; i < sida.Entry.Length; i++)
         {
             HashEntry hEntry = new HashEntry();
             hEntry.Key = ReadTerminatedString(keys, sida.Entry[i].KeyOffset, 0x00);
             hEntry.Value = ReadTerminatedString(values, sida.Entry[i].ValueOffset, 0x00);
             hsht.Table[GetHash(hEntry.Key)].Add(hEntry);
         }
     }
 }
 public static HashEntry[] ToHashEntryArray(this IEnumerable<KeyValuePair<string, string>> Items)
 {
     var Entries = new HashEntry[Items.Count()];
     int i = 0;
     foreach (var Item in Items)
     {
         Entries[i++] = new HashEntry(Item.Key, Item.Value);
     }
     return Entries;
 }
Beispiel #4
0
 public EmbeddingScan(HashEntry[] hashEntries)
 {
     this.m_AliquotOrderId = hashEntries[0].Value;
     this.m_ProcessorStartTime = Business.Helper.DateTimeExtensions.NullableDateTimeFromString(hashEntries[1].Value);
     this.m_ProcessorFixationDuration = Business.Helper.DateTimeExtensions.NullableTimeSpanFromString(hashEntries[2].Value);
     this.m_DateScanned = DateTime.Parse(hashEntries[3].Value);
     this.m_ScannedById = Convert.ToInt32(hashEntries[4].Value);
     this.m_ScannedBy = hashEntries[5].Value;
     this.m_Updated = Convert.ToBoolean(hashEntries[6].Value);
 }
		public static HashEntry[] ToHashEntries(this IEnumerable<KeyValuePair<string, string>> keyValuePairs)
		{
			var hashEntry = new HashEntry[keyValuePairs.Count()];
			int i = 0;
			foreach (var kvp in keyValuePairs)
			{
				hashEntry[i] = new HashEntry(kvp.Key, kvp.Value);
				i++;
			}
			return hashEntry;
		}
        /// <summary>
        /// Initializes a new instance of the
        /// Sentinel.OAuth.TokenManagers.RedisTokenRepository.Models.RedisRefreshToken class.
        /// </summary>
        /// <param name="hashEntries">The hash entries.</param>
        public RedisRefreshToken(HashEntry[] hashEntries)
        {
            var clientId = hashEntries.FirstOrDefault(x => x.Name == "ClientId");
            var redirectUri = hashEntries.FirstOrDefault(x => x.Name == "RedirectUri");
            var subject = hashEntries.FirstOrDefault(x => x.Name == "Subject");
            var token = hashEntries.FirstOrDefault(x => x.Name == "Token");
            var validTo = hashEntries.FirstOrDefault(x => x.Name == "ValidTo");
            var created = hashEntries.FirstOrDefault(x => x.Name == "Created");

            this.ClientId = clientId.Value.HasValue ? clientId.Value.ToString() : string.Empty;
            this.RedirectUri = redirectUri.Value.HasValue ? redirectUri.Value.ToString() : string.Empty;
            this.Subject = subject.Value.HasValue ? subject.Value.ToString() : string.Empty;
            this.Token = token.Value.HasValue ? token.Value.ToString() : string.Empty;
            this.ValidTo = validTo.Value.HasValue ? JsonConvert.DeserializeObject<DateTime>(validTo.Value.ToString()) : DateTime.MinValue;
            this.Created = created.Value.HasValue ? JsonConvert.DeserializeObject<DateTime>(created.Value.ToString()) : DateTime.MinValue;
        }
        /// <summary>
        /// Initializes a new instance of the
        /// Sentinel.OAuth.TokenManagers.RedisTokenRepository.Models.RedisAuthorizationCode class.
        /// </summary>
        /// <param name="hashEntries">The hash entries.</param>
        public RedisAuthorizationCode(HashEntry[] hashEntries)
        {
            var clientId = hashEntries.FirstOrDefault(x => x.Name == "ClientId");
            var redirectUri = hashEntries.FirstOrDefault(x => x.Name == "RedirectUri");
            var subject = hashEntries.FirstOrDefault(x => x.Name == "Subject");
            var code = hashEntries.FirstOrDefault(x => x.Name == "Code");
            var ticket = hashEntries.FirstOrDefault(x => x.Name == "Ticket");
            var validTo = hashEntries.FirstOrDefault(x => x.Name == "ValidTo");
            var created = hashEntries.FirstOrDefault(x => x.Name == "Created");

            this.ClientId = clientId.Value.HasValue ? clientId.Value.ToString() : string.Empty;
            this.RedirectUri = redirectUri.Value.HasValue ? redirectUri.Value.ToString() : string.Empty;
            this.Subject = subject.Value.HasValue ? subject.Value.ToString() : string.Empty;
            this.Code = code.Value.HasValue ? code.Value.ToString() : string.Empty;
            this.Ticket = ticket.Value.HasValue ? ticket.Value.ToString() : string.Empty;
            this.ValidTo = validTo.Value.HasValue ? JsonConvert.DeserializeObject<DateTime>(validTo.Value.ToString()) : DateTime.MinValue;
            this.Created = created.Value.HasValue ? JsonConvert.DeserializeObject<DateTime>(created.Value.ToString()) : DateTime.MinValue;
        }
 public void Load(X360IO io)
 {
     IO = io;
     IO.Stream.Position = 0x0;
     Magic = IO.Reader.ReadInt64();
     if (Magic != 0x5343455546000000)
         return;
     Version = IO.Reader.ReadInt64();
     ImageVersion = IO.Reader.ReadInt64();
     FileCount = IO.Reader.ReadInt64();
     HeaderSize = IO.Reader.ReadInt64();
     DataSize = IO.Reader.ReadInt64();
     Files = new List<FileEntry>();
     for(int i = 0; i < FileCount; i++)
     {
         FileEntry entry = new FileEntry
                               {
                                   ID = IO.Reader.ReadInt64(),
                                   Offset = IO.Reader.ReadInt64(),
                                   Size = IO.Reader.ReadInt64(),
                                   Padding = IO.Reader.ReadInt64()
                               };
         Files.Add(entry);
     }
     Hashes = new List<HashEntry>();
     for(int i = 0; i < FileCount; i++)
     {
         HashEntry entry = new HashEntry();
         entry.FileID = IO.Reader.ReadInt64();
         entry.HMACSHA1 = IO.Reader.ReadBytes(0x14);
         entry.Padding = IO.Reader.ReadInt32();
         Hashes.Add(entry);
         Files[(int) entry.FileID].Hash = entry;
     }
     HeaderHash = IO.Reader.ReadBytes(0x14);
     Padding = IO.Reader.ReadBytes(0xC);
 }
 public TranspositionTable(Field field)
 {
     Field_       = field;
     HashEntries_ = new HashEntry[AiSettings.HashTableSize];
 }
 public void HashSet_1()
 {
     HashEntry[] hashFields = new HashEntry[0];
     wrapper.HashSet("key", hashFields, CommandFlags.None);
     mock.Verify(_ => _.HashSet("prefix:key", hashFields, CommandFlags.None));
 }
 public DBCache(Type type, IDatabase database) : base(type, database)
 {
     this.targetObj = Activator.CreateInstance(type);
     this.nullEntry = new HashEntry();
 }
Beispiel #12
0
        public static HashEntry[] GetEntrys <T>(T t)
        {
            Type type = t.GetType();

            PropertyInfo[] pInfos   = type.GetProperties();
            var            entryArr = new HashEntry[pInfos.Length];

            for (int i = 0; i < pInfos.Length; i++)
            {
                var val = pInfos[i].GetValue(t);
                //枚举
                if (pInfos[i].PropertyType.IsEnum)
                {
                    entryArr[i] = new HashEntry(pInfos[i].Name, (int)val);
                }
                //int
                else if (pInfos[i].PropertyType.FullName == typeof(int).FullName)
                {
                    entryArr[i] = new HashEntry(pInfos[i].Name, val != null ? (int)val : 0);
                }
                //int||null
                else if (pInfos[i].PropertyType.FullName == typeof(Nullable <int>).FullName)
                {
                    entryArr[i] = new HashEntry(pInfos[i].Name, val != null ? ((int?)val) : 0);
                }
                //byte
                else if (pInfos[i].PropertyType.FullName == typeof(byte).FullName)
                {
                    entryArr[i] = new HashEntry(pInfos[i].Name, val != null ? (byte)val : 0);
                }
                //byte||null
                else if (pInfos[i].PropertyType.FullName == typeof(Nullable <byte>).FullName)
                {
                    entryArr[i] = new HashEntry(pInfos[i].Name, val != null ? ((byte?)val) : 0);
                }
                //string
                else if (pInfos[i].PropertyType.FullName == typeof(string).FullName)
                {
                    entryArr[i] = new HashEntry(pInfos[i].Name, val != null ? (string)val : string.Empty);
                }
                //date
                else if (pInfos[i].PropertyType.FullName == typeof(DateTime).FullName)
                {
                    entryArr[i] = new HashEntry(pInfos[i].Name, val != null ? val.ToString() : string.Empty);
                }
                //date||null
                else if (pInfos[i].PropertyType.FullName == typeof(Nullable <DateTime>).FullName)
                {
                    entryArr[i] = new HashEntry(pInfos[i].Name, val != null ? ((Nullable <DateTime>)val).ToString() : string.Empty);
                }
                //bool
                else if (pInfos[i].PropertyType.FullName == typeof(bool).FullName)
                {
                    entryArr[i] = new HashEntry(pInfos[i].Name, val != null ? (bool)val : false);
                }
                //bool||null
                else if (pInfos[i].PropertyType.FullName == typeof(Nullable <bool>).FullName)
                {
                    entryArr[i] = new HashEntry(pInfos[i].Name, val != null ? (bool?)val : false);
                }
                //long
                else if (pInfos[i].PropertyType.FullName == typeof(long).FullName)
                {
                    entryArr[i] = new HashEntry(pInfos[i].Name, val != null ? Convert.ToInt32(val) : 0);
                }
                //long||null
                else if (pInfos[i].PropertyType.FullName == typeof(Nullable <long>).FullName)
                {
                    entryArr[i] = new HashEntry(pInfos[i].Name, val != null ? (long?)val : 0);
                }
                //decimal
                else if (pInfos[i].PropertyType.FullName == typeof(decimal).FullName)
                {
                    entryArr[i] = new HashEntry(pInfos[i].Name, val != null ? Convert.ToDouble(val) : 0);
                }
                //decimal||null
                else if (pInfos[i].PropertyType.FullName == typeof(Nullable <decimal>).FullName)
                {
                    entryArr[i] = new HashEntry(pInfos[i].Name, val != null ? Convert.ToDouble((decimal?)val) : 0);
                }
                //guid
                else if (pInfos[i].PropertyType.FullName == typeof(Guid).FullName)
                {
                    entryArr[i] = new HashEntry(pInfos[i].Name, val != null ? ((Guid)val).ToString() : string.Empty);
                }
                //guid||null
                else if (pInfos[i].PropertyType.FullName == typeof(Nullable <Guid>).FullName)
                {
                    entryArr[i] = new HashEntry(pInfos[i].Name, val != null ? ((Guid?)val).ToString() : string.Empty);
                }
                //float
                else if (pInfos[i].PropertyType.FullName == typeof(float).FullName)
                {
                    entryArr[i] = new HashEntry(pInfos[i].Name, val != null ? Convert.ToSingle(val) : 0);
                }
                //float||null
                else if (pInfos[i].PropertyType.FullName == typeof(Nullable <float>).FullName)
                {
                    entryArr[i] = new HashEntry(pInfos[i].Name, val != null ? Convert.ToSingle(val) : 0);
                }
                //double
                else if (pInfos[i].PropertyType.FullName == typeof(double).FullName)
                {
                    entryArr[i] = new HashEntry(pInfos[i].Name, val != null ? Convert.ToDouble(val) : 0);
                }
                //double||null
                else if (pInfos[i].PropertyType.FullName == typeof(Nullable <double>).FullName)
                {
                    entryArr[i] = new HashEntry(pInfos[i].Name, val != null ? Convert.ToDouble(val) : 0);
                }
            }
            return(entryArr);
        }
Beispiel #13
0
        public static void RunProcess(Object stateInfo)
        {
            List <Log> logs = new List <Log>();

            StreamEntry[] entries = db.StreamRead("Stream:Customer", position);
            foreach (var entry in entries)
            {
                string entityKey = ((NameValueEntry)entry.Values.GetValue(0)).Value.ToString();
                string logKey    = ((NameValueEntry)entry.Values.GetValue(1)).Value.ToString();



                Log logItem = new Log();
                logs.Add(logItem);
                logItem.Current = db.HashGetAll(entityKey);

                //search for the key and get the most up to date one
                var    keys = server.Keys(pattern: $"log:{entityKey}*", pageSize: 10000);
                string previousSnapshotKey = "";


                List <string> keyList = keys.Select(k => k.ToString()).OrderByDescending(o => o.ToString()).ToList();

                foreach (var k in keyList)
                {
                    if (String.Compare(logKey, k) > 0)
                    {
                        //logKey the most up to date record.
                        //we will take the one below
                        previousSnapshotKey = k;
                        break;
                    }
                }



                #region New Record
                if (previousSnapshotKey == String.Empty)
                {
                    //it is a new record.
                    foreach (var item in logItem.Current)
                    {
                        logItem.Added.Add(item.Name);
                    }

                    Console.WriteLine("== Added Items ==");
                    foreach (var d in logItem.Added)
                    {
                        Console.WriteLine($"{d}={logItem.Current.ToDictionary()[d]}");
                    }

                    position = entry.Id;
                    continue;
                }

                #endregion

                logItem.Snapshot = db.HashGetAll(previousSnapshotKey);

                #region Added/Updated Action
                foreach (var item in logItem.Current)
                {
                    HashEntry snapshotItem = Array.Find(logItem.Snapshot, s => s.Name == item.Name);

                    if (snapshotItem != null)
                    {
                        //key exists
                        if (snapshotItem.Value != item.Value)
                        {
                            logItem.Updated.Add(item.Name);                                   //value has been updated
                        }
                    }
                    else
                    {
                        //key not exists. It must be new field
                        logItem.Added.Add(item.Name); //new value
                    }
                }

                Console.WriteLine("== Updated Items ==");
                foreach (var d in logItem.Updated)
                {
                    Console.WriteLine($"{d}={logItem.Current.ToDictionary()[d]}");
                }

                #endregion

                #region Deleted Action
                foreach (var item in logItem.Snapshot)
                {
                    if (!Array.Exists(logItem.Current, a => a.Name == item.Name))
                    {
                        //new set has no such key
                        logItem.Removed.Add(item.Name);
                    }
                }
                #endregion

                position = entry.Id;
            }
        }
        public void Update()
        {
            UpdateVoxelDistances(Camera.main.transform.position);
            if (!m_ActiveReconstruction)
            {
                return;
            }

            // Fill in the data to draw the point cloud.
            if (Frame.PointCloud.IsUpdatedThisFrame)
            {
                // Copy the point cloud points for mesh verticies.
                NumberOfPoints += Frame.PointCloud.PointCount;

                for (int i = 0; i < Frame.PointCloud.PointCount; i++)
                {
                    UnityEngine.Profiling.Profiler.BeginSample("PointCloud");
                    m_Points[i]    = Frame.PointCloud.GetPoint(i);
                    detected_point = Frame.PointCloud.GetPoint(i);

                    int hash = m_Reconstructor.GetSpatialHashing().GetHash(detected_point, m_Reconstructor.GetSpatialHashing().GetScale(), m_Reconstructor.GetSpatialHashing().GetHashTableSize());

                    if (detected_point.w < Constants.CONFIDENCE_THRESHOLD)
                    {
                        continue;
                    }
                    if (Vector3.Distance(Camera.main.transform.position, detected_point) > m_Reconstructor.GetSpatialHashing().GetMaxReconstructionDistance())
                    {
                        continue;
                    }
                    if (!m_Reconstructor.GetSpatialHashing().Contains(hash))
                    {
                        //Debug.Log("Reconstructor" + ": " + "Point > " + m_Points[i].ToString("G4") + ", NEW Hash: " + hash + ", Size: " + reconstructor.spatialHashing.Size());
                        Vector3 point = Optimization.ScalePoint(detected_point, m_Reconstructor.GetSpatialHashing().GetScale());
                        pose.position = point;
                        pose.rotation = zeroQuaternion;
                        Anchor     anchor      = Session.CreateAnchor(pose);
                        GameObject voxelObject = Instantiate(m_VoxelPrefab, pose.position, pose.rotation);
                        float      voxelSize   = 1.00f / m_Reconstructor.GetSpatialHashing().GetScale();
                        voxelObject.GetComponent <Renderer>().enabled = m_ActiveRenderer;
                        voxelObject.transform.localScale = new Vector3(voxelSize, voxelSize, voxelSize);

                        GameObject parentVoxelGameObject = new GameObject("_voxel_" + hash);
                        GameObject lodContainer          = new GameObject("_levelOfDetail_0");
                        voxelObject.transform.SetParent(lodContainer.transform);
                        lodContainer.transform.SetParent(anchor.transform);
                        anchor.transform.SetParent(parentVoxelGameObject.transform);
                        parentVoxelGameObject.transform.SetParent(m_AllVoxels.transform);

                        m_TempHashEntry = m_Reconstructor.GetSpatialHashing().CreateHash(detected_point, new Voxel(voxelObject), lodContainer);
                        m_Reconstructor.GetSpatialHashing().AddToTable(m_TempHashEntry);
                    }
                    else
                    {
                        m_TempHashEntry = (HashEntry)m_Reconstructor.GetSpatialHashing().GetFromTable(hash);
                        m_Reconstructor.GetSpatialHashing().AddPointToEntry(detected_point);
                    }
                    UnityEngine.Profiling.Profiler.EndSample();

                    if (DebugText.Instance.UpdateDistances)
                    {
                        m_Reconstructor.GetSpatialHashing().UpdateDistanceResolution(m_TempHashEntry);
                    }
                    if (!m_ActiveRenderer)
                    {
                        GameObject gameObject = GameObject.Find("_voxel_" + hash);
                        foreach (Renderer r in gameObject.GetComponentsInChildren <Renderer>())
                        {
                            r.enabled = false;
                        }
                    }
                    CheckPointCloseToPlanes(m_TempHashEntry);
                }
                if (m_ActiveRenderer)
                {
                    DrawPointCloud();
                }
                else
                {
                    m_Mesh.Clear();
                }
            }

            GetCubeInfoOnTouch();
        }
Beispiel #15
0
 /// <summary>
 /// Gets the locale of the file. The actual values of the enum are Windows LANGID values, but
 /// files are most commonly set to 0 (default or neutral locale).
 /// </summary>
 /// <returns>The locale.</returns>
 public LocaleID GetLocale()
 {
     return(HashEntry.GetLocalizationID());
 }
Beispiel #16
0
        public bool setHashs(string hash, List <KeyValuePair <string, object> > par, IDBTableDesc desc)
        {
            if (_conn == null)
            {
                // error: without _conn
                // important: don't log par, or may expose sensitive data!!!
                Debug.logger.log(LogType.LOG_ERR, "DBRedisDB name[" + this.name + "] setHashs hash[" + hash + "] without connection!");
                return(false);
            }

            IDatabase db  = _conn.GetDatabase();
            bool      ret = true;

            HashEntry[] hashs = new HashEntry[par.Count];
            for (int i = 0; i < par.Count; ++i)
            {
                AEDBDataType dt = desc.getDataType(par[i].Key);
                switch (dt)
                {
                case AEDBDataType.ADDT_INT:
                    hashs[i] = new HashEntry(par[i].Key, (int)par[i].Value);
                    break;

                case AEDBDataType.ADDT_UINT:
                    hashs[i] = new HashEntry(par[i].Key, (uint)par[i].Value);
                    break;

                case AEDBDataType.ADDT_FLOAT:
                    hashs[i] = new HashEntry(par[i].Key, (float)par[i].Value);
                    break;

                case AEDBDataType.ADDT_LONG:
                    hashs[i] = new HashEntry(par[i].Key, (long)par[i].Value);
                    break;

                case AEDBDataType.ADDT_ULONG:
                    hashs[i] = new HashEntry(par[i].Key, (ulong)par[i].Value);
                    break;

                case AEDBDataType.ADDT_DOUBLE:
                    hashs[i] = new HashEntry(par[i].Key, (double)par[i].Value);
                    break;

                case AEDBDataType.ADDT_BINARY:
                {
                    byte[] objBytes = AEDBHelper.serializeObject(par[i].Value);
                    hashs[i] = new HashEntry(par[i].Key, objBytes);
                }
                break;

                //case AEDBDataType.ADDT_STRING: // deault is string
                default:
                    hashs[i] = new HashEntry(par[i].Key, (string)par[i].Value);
                    break;
                }
            }

            if (_expireTime > 0)
            {
                db.HashSet(hash, hashs);
                db.KeyExpire(hash, TimeSpan.FromSeconds(_expireTime));
            }
            else
            {
                db.HashSet(hash, hashs);
            }

            return(ret);
        }
Beispiel #17
0
        private async Task SetCacheEntities(IReadOnlyList <Entity> entities)
        {
            IRedisDatabase db    = GetCache();
            ITransaction   trans = db.Database.CreateTransaction();
            {
                string      key        = CacheUtils.BuildEntities(Nuid.New(Identity, Identity));
                HashEntry[] hashFields = new HashEntry[entities.Count];
                for (int i = 0; i < entities.Count; i++)
                {
                    hashFields[i] = new HashEntry(entities[i].Id.Unique, entities[i].Type);
                }

                Task _ = trans.HashSetAsync(key, hashFields);
            }

            {
                foreach (Entity entity in entities)
                {
                    EntityPrefab entity_prefab = Prefabs.GetEntity(entity.Type);
                    if (entity_prefab == null)
                    {
                        continue;
                    }

                    string           fields_key   = CacheUtils.BuildFields(entity.Id);
                    Field[]          fields       = entity.GetFields();
                    List <HashEntry> cache_fields = new List <HashEntry>();
                    for (int i = 0; i < fields.Length; i++)
                    {
                        FieldPrefab field_prefab = entity_prefab.fields[fields[i].Name];
                        if (field_prefab == null)
                        {
                            continue;
                        }

                        string field_value = "";
                        switch (field_prefab.type)
                        {
                        case VarType.Bool:
                            field_value = JsonUtils.ToJson(fields[i].Get <bool>());
                            break;

                        case VarType.Int:
                            field_value = JsonUtils.ToJson(fields[i].Get <int>());
                            break;

                        case VarType.Long:
                            field_value = JsonUtils.ToJson(fields[i].Get <long>());
                            break;

                        case VarType.Float:
                            field_value = JsonUtils.ToJson(fields[i].Get <float>());
                            break;

                        case VarType.String:
                            field_value = JsonUtils.ToJson(fields[i].Get <string>());
                            break;

                        case VarType.Nuid:
                            field_value = JsonUtils.ToJson(fields[i].Get <Nuid>());
                            break;

                        case VarType.List:
                            field_value = JsonUtils.ToJson(fields[i].Get <NList>());
                            break;

                        default:
                            break;
                        }

                        cache_fields.Add(new HashEntry(fields[i].Name, field_value));
                    }

                    Task _ = trans.HashSetAsync(fields_key, cache_fields.ToArray());

                    Table[] tables = entity.GetTables();
                    foreach (Table table in tables)
                    {
                        string table_key = CacheUtils.BuildTable(entity.Id, table.GetName());

                        TablePrefab table_prefab = entity_prefab.tables[table.GetName()];
                        if (table_prefab == null)
                        {
                            continue;
                        }

                        List <HashEntry> cache_key_values = new List <HashEntry>();

                        void SetCacheKeyValue <TPrimaryKey>()
                        {
                            Table <TPrimaryKey>         t    = table as Table <TPrimaryKey>;
                            IReadOnlyList <TPrimaryKey> keys = t.GetPrimaryKeys();

                            foreach (TPrimaryKey key in keys)
                            {
                                string json = JsonUtils.ToJson(t.GetKeyValue(key));
                                cache_key_values.Add(new HashEntry(key.ToString(), json));
                            }
                        }

                        switch (table_prefab.primary_key.type)
                        {
                        case VarType.Bool:
                            SetCacheKeyValue <bool>();
                            break;

                        case VarType.Int:
                            SetCacheKeyValue <int>();
                            break;

                        case VarType.Long:
                            SetCacheKeyValue <long>();
                            break;

                        case VarType.Float:
                            SetCacheKeyValue <float>();
                            break;

                        case VarType.String:
                            SetCacheKeyValue <string>();
                            break;

                        case VarType.Nuid:
                            SetCacheKeyValue <Nuid>();
                            break;

                        default:
                            break;
                        }

                        Task __ = trans.HashSetAsync(table_key, cache_key_values.ToArray());
                    }
                }

                bool redis_execute = await trans.ExecuteAsync();

                if (!redis_execute)
                {
                    throw new Exception("trans ExecuteAsync ERROR!!");
                }
            }
        }
Beispiel #18
0
        public async Task <T> Save(T instance, bool saveChangedOnly = true)
        {
            var serialKey       = _storageKeyGenerator.GetSerialKey(_typeDefinition);
            var clusterIndexKey = _storageKeyGenerator.GetClusteredIndexKey(_typeDefinition);

            var        _val     = _valueConverter.ResolveId(_typeDefinition, instance);
            RedisValue id       = _val.Item1;
            bool       wasIdSet = _val.Item2;

            RedisKey key;
            var      existingIndexes = new RedisKey[0];
            var      existingRecord  = new HashEntry[0];
            long     serial          = -1;

            if (!wasIdSet)
            {
                // this is a new object so we need to add it to the clustered index...
                serial = await _database.StringIncrementAsync(serialKey).ConfigureAwait(false);

                // guid ids are auto generated and not null
                if (id.IsNull)
                {
                    id = serial;
                }

                // and set the id on the object
                _typeDefinition.Accessor[instance, _typeDefinition.PrimaryKey.Name] = _valueConverter.ToObject(id, _typeDefinition.PrimaryKey.Type);
                key = _storageKeyGenerator.GetKey(_typeDefinition, id);
            }
            else
            {
                string rawIndexes = null;
                key = _storageKeyGenerator.GetKey(_typeDefinition, id);

                if (saveChangedOnly)
                {
                    existingRecord = await _database.HashGetAllAsync(key).ConfigureAwait(false);

                    rawIndexes = existingRecord.FirstOrDefault(h => h.Name == Constants.RoidHashFieldIndexes).Value;
                }
                else
                {
                    rawIndexes = await _database.HashGetAsync(key, Constants.RoidHashFieldIndexes).ConfigureAwait(false);
                }

                // if rawIndexes is null, that means we have not yet saved the object
                // id is user provided in this case hence we need to add it to the clustered index
                if (string.IsNullOrWhiteSpace(rawIndexes))
                {
                    serial = await _database.StringIncrementAsync(serialKey).ConfigureAwait(false);
                }
                else
                {
                    existingIndexes = rawIndexes.Split(new[] { Constants.Separator }, StringSplitOptions.RemoveEmptyEntries)
                                      .Select(i => (RedisKey)i)
                                      .ToArray();
                }
            }

            bool isNew = serial != -1;
            var  hash  = _mapper.HashFor(_typeDefinition, instance, isNew, existingRecord);

            var indexes         = _indexer.GetIndexes(_typeDefinition, hash);
            var indexesToRemove = existingIndexes.Where(i => !indexes.Contains(i)).ToArray();
            var indexesToAdd    = indexes.Where(i => !existingIndexes.Contains(i)).ToArray();

            #region save to redis

            var keyString = (string)key;
            var txn       = _database.CreateTransaction();

#pragma warning disable CS4014

            txn.HashSetAsync(key, hash.ToArray());

            if (isNew)
            {
                txn.SortedSetAddAsync(clusterIndexKey, new[] { new SortedSetEntry(keyString, serial) });
            }

            foreach (var index in indexesToAdd)
            {
                txn.SetAddAsync(index, keyString);
            }
            foreach (var index in indexesToRemove)
            {
                txn.SetRemoveAsync(index, keyString);
            }

#pragma warning restore CS4014

            if (!await txn.ExecuteAsync().ConfigureAwait(false))
            {
                throw new RoidException("Failed to commit the transaction");
            }

            #endregion save to redis

            return(instance);
        }
Beispiel #19
0
        private static HashEntry GetHashEntry(Type enumType)
        {
            HashEntry hashEntry = (HashEntry)fieldInfoHash[enumType];

            if (hashEntry == null)
            {
                // To reduce the workingset we clear the hashtable when a threshold number of elements are inserted.
                if (fieldInfoHash.Count > maxHashElements)
                    fieldInfoHash.Clear();

                ulong[] values = null;
                String[] names = null;

                BCLDebug.Assert(enumType.BaseType == typeof(Enum), "Base type must of type Enum");
                if (enumType.BaseType == typeof(Enum))
                    InternalGetEnumValues(enumType, ref values, ref names);
                    // If we switch over to EnumBuilder, this code path will be required.
                    else
                {
                    // fall back on reflection for odd cases
                    FieldInfo[] flds = enumType.GetFields(BindingFlags.Static | BindingFlags.Public);

                    values = new ulong[flds.Length];
                    names = new String[flds.Length];
                    for (int i = 0; i < flds.Length; i++)
                    {
                        names[i] = flds[i].Name;
                        values[i] = ToUInt64(flds[i].GetValue(null));
                    }

                    // Insertion Sort these values in ascending order.
                    // We use this O(n^2) algorithm, but it turns out that most of the time the elements are already in sorted order and
                    // the common case performance will be faster than quick sorting this.
                    for (int i = 1; i < values.Length; i++)
                    {
                        int j = i;
                        String tempStr = names[i];
                        ulong val = values[i];
                        bool exchanged = false;

                        // Since the elements are sorted we only need to do one comparision, we keep the check for j inside the loop.
                        while (values[j - 1] > val)
                        {
                            names[j] = names[j - 1];
                            values[j] = values[j - 1];
                            j--;
                            exchanged = true;
                            if (j == 0)
                                break;
                        }

                        if (exchanged)
                        {
                            names[j] = tempStr;
                            values[j] = val;
                        }
                    }
                }

                hashEntry = new HashEntry(names, values);
                fieldInfoHash[enumType] = hashEntry;
            }

            return hashEntry;
        }
Beispiel #20
0
 /**
  * Creates a ReferenceEntry instead of a HashEntry.
  *
  * @param next  the next entry in sequence
  * @param hashCode  the hash code to use
  * @param key  the key to store
  * @param value  the value to store
  * @return the newly created entry
  */
 protected override HashEntry createEntry(HashEntry next, int hashCode, Object key, Object value)
 {
     return(new ReferenceEntry(this, next, hashCode, key, value));
 }
        public void NeighborhoodSearch(Vector3d[] particles, Vector3d[] boundary)
        {
            if (particles.Length > NumParticles)
            {
                throw new ArgumentException("Particle array length larger than expected");
            }

            //double invCellSize = 1.0 / CellSize;
            double r2 = CellSize * CellSize;

            for (int i = 0; i < NumParticles; i++)
            {
                AddToGrid(i, particles[i]);
            }

            for (int i = 0; i < boundary.Length; i++)
            {
                AddToGrid(NumParticles + i, boundary[i]);
            }

            for (int i = 0; i < NumParticles; i++)
            {
                Vector3d p0 = particles[i];
                NumNeighbors[i] = 0;

                int cellPos1, cellPos2, cellPos3;
                Floor(particles[i], out cellPos1, out cellPos2, out cellPos3);

                for (int j = 0; j < 27; j++)
                {
                    int cellPos = Hash(cellPos1 + Indexes[j, 0], cellPos2 + Indexes[j, 1], cellPos3 + Indexes[j, 2]);

                    HashEntry entry = null;
                    GridMap.TryGetValue(cellPos, out entry);

                    if (entry != null && entry.TimeStamp == CurrentTimeStamp)
                    {
                        int count = entry.Indices.Count;
                        for (int m = 0; m < count; m++)
                        {
                            int pi = entry.Indices[m];
                            if (pi == i)
                            {
                                continue;
                            }

                            double dist2 = 0.0;

                            if (pi < NumParticles)
                            {
                                Vector3d p;
                                p.x = p0.x - particles[pi].x;
                                p.y = p0.y - particles[pi].y;
                                p.z = p0.z - particles[pi].z;

                                dist2 = p.x * p.x + p.y * p.y + p.z * p.z;
                            }
                            else
                            {
                                int bi = pi - NumParticles;

                                Vector3d p;
                                p.x = p0.x - boundary[bi].x;
                                p.y = p0.y - boundary[bi].y;
                                p.z = p0.z - boundary[bi].z;

                                dist2 = p.x * p.x + p.y * p.y + p.z * p.z;
                            }

                            if (dist2 < r2)
                            {
                                if (NumNeighbors[i] < MaxNeighbors)
                                {
                                    Neighbors[i, NumNeighbors[i]++] = pi;
                                }
                                else
                                {
                                    throw new InvalidOperationException("too many neighbors detected");
                                }
                            }
                        }
                    }
                }
            }

            //End of function
        }
Beispiel #22
0
 /// <summary>
 /// Gets the platform that the file is meant for. A 0 indicates default or platform-neutral.
 /// </summary>
 /// <returns>The platform.</returns>
 public ushort GetPlatform()
 {
     return(HashEntry.GetPlatformID());
 }
Beispiel #23
0
        /// <summary>
        /// Gets the user data.
        /// </summary>
        /// <returns>The user data.</returns>
        /// <param name="email">Email.</param>

        public User getUserHashData(string email)
        {
            //check if email is verifyed in Redis
            int emailVerifyResponse = emailVerify(email);

            switch (emailVerifyResponse)
            {
            case 1:                     //no email exists
                return(null);

            case -1:                     //empty field email
                return(null);

            case -2:                     //incorrect email format
                return(null);

            case -3:                     //YAY email exists

                //create key for Redis call
                var key = "user:"******"name")
                    {
                        getUser.Name = userKey.Value.ToString();
                    }
                    else if (userKey.Name.ToString() == "email")
                    {
                        getUser.Email = userKey.Value.ToString();
                    }
                    else if (userKey.Name.ToString() == "age")
                    {
                        getUser.Age = Int16.Parse(userKey.Value.ToString());
                    }
                    else if (userKey.Name.ToString() == "weight")
                    {
                        getUser.Weight = Int16.Parse(userKey.Value.ToString());
                    }
                    else if (userKey.Name.ToString() == "bench")
                    {
                        getUser.Bench = Int16.Parse(userKey.Value.ToString());
                    }
                    else if (userKey.Name.ToString() == "squat")
                    {
                        getUser.Squat = Int16.Parse(userKey.Value.ToString());
                    }
                    else if (userKey.Name.ToString() == "snatch")
                    {
                        getUser.Snatch = Int16.Parse(userKey.Value.ToString());
                    }
                    else if (userKey.Name.ToString() == "deadlift")
                    {
                        getUser.Deadlift = Int16.Parse(userKey.Value.ToString());
                    }
                    else if (userKey.Name.ToString() == "cleanjerk")
                    {
                        getUser.CleanAndJerk = Int16.Parse(userKey.Value.ToString());
                    }
                    else if (userKey.Name.ToString() == "workoutsCompleted")
                    {
                        getUser.WorkoutsCompleted = Int16.Parse(userKey.Value.ToString());
                    }
                    else if (userKey.Name.ToString() == "password")
                    {
                        getUser.Password = userKey.Value.ToString();
                    }
                }


                string getResponse = string.Empty;

                for (int i = 0; i < data.Length; i++)
                {
                    if (i == data.Length - 1)
                    {
                        getResponse = getResponse + data[i];
                    }
                    else
                    {
                        getResponse = getResponse + data[i] + ",";
                    }
                }

                return(getUser);

            case -4:
            default:
                return(null);
            }
        }
        public void OnExecuted(RedisCommand command, ref object result, RedisKey[] involvedKeys = null)
        {
            if (CanBeExecuted(involvedKeys))
            {
                if (result != null && result.GetType() != typeof(bool) && result.GetType() != typeof(int) && result.GetType() != typeof(long))
                {
                    bool isScanResult = command == RedisCommand.SCAN || command == RedisCommand.HSCAN || command == RedisCommand.SSCAN || command == RedisCommand.ZSCAN;
                    object scanValues = null;

                    if (isScanResult)
                        scanValues = result.GetType()
                                            .GetField("Values", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)
                                            .GetValue(result);

                    if (result.GetType() == typeof(RedisValue))
                    {
                        byte[] valueBlob = (RedisValue)result;

                        RedisValueCompressor.Compressor.Decompress(ref valueBlob);

                        if (valueBlob != null && valueBlob.Length > 0)
                            result = (RedisValue)Encoding.UTF8.GetString(valueBlob);
                    }
                    else if (result.GetType() == typeof(RedisValue[]) || (command == RedisCommand.SCAN || command == RedisCommand.SSCAN))
                    {
                        RedisValue[] values;

                        if (!isScanResult)
                            values = (RedisValue[])result;
                        else
                            values = (RedisValue[])scanValues;

                        for (int i = 0; i < values.Length; i++)
                        {
                            byte[] valueBlob = values[i];
                            RedisValueCompressor.Compressor.Decompress(ref valueBlob);
                            values[i] = (RedisValue)valueBlob;
                        }
                    }
                    else if (result.GetType() == typeof(SortedSetEntry))
                    {
                        SortedSetEntry source = (SortedSetEntry)result;
                        byte[] valueBlob = source.Element;
                        RedisValueCompressor.Compressor.Decompress(ref valueBlob);
                        result = new SortedSetEntry((RedisValue)valueBlob, source.Score);
                    }
                    else if (result.GetType() == typeof(SortedSetEntry[]) || command == RedisCommand.ZSCAN)
                    {
                        SortedSetEntry[] entries;

                        if (!isScanResult)
                            entries = (SortedSetEntry[])result;
                        else
                            entries = (SortedSetEntry[])scanValues;

                        for (int i = 0; i < entries.Length; i += 2)
                        {
                            SortedSetEntry source = (SortedSetEntry)entries[i];
                            byte[] valueBlob = source.Element;
                            RedisValueCompressor.Compressor.Decompress(ref valueBlob);
                            entries[i] = new SortedSetEntry((RedisValue)valueBlob, source.Score);
                        }
                    }
                    else if (result.GetType() == typeof(HashEntry))
                    {
                        HashEntry source = (HashEntry)result;

                        byte[] valueBlob = source.Value;
                        RedisValueCompressor.Compressor.Decompress(ref valueBlob);
                        result = new HashEntry(source.Name, (RedisValue)valueBlob);
                    }
                    else if (result.GetType() == typeof(HashEntry[]) || command == RedisCommand.HSCAN)
                    {
                        HashEntry[] entries;

                        if (!isScanResult)
                            entries = (HashEntry[])result;
                        else
                            // TODO: Not the best solution... But I need to investigate further how to improve StackExchange.Redis
                            // to get these values directly...
                            entries = (HashEntry[])scanValues;

                        for (int i = 0; i < entries.Length; i++)
                        {
                            HashEntry source = entries[i];
                            byte[] valueBlob = source.Value;
                            RedisValueCompressor.Compressor.Decompress(ref valueBlob);
                            entries[i] = new HashEntry(source.Name, (RedisValue)valueBlob);
                        }
                    }
                }
            }
        }
    public async Task CheckTheUserForMessage(ApplicationUser user, int ChannelId, string channelName)
    {
        if (user.UserName == "haha" || user.UserName == "haha2")
        {
            return;
        }

        //Console.WriteLine(user.UserId);
        var sent_message_count        = 0;
        var sent_email_body           = "";
        var last_seen_time            = DateTime.Now;
        List <TextModel> message_list = new List <TextModel>();

        // last seen is updated ondisconnectedasync
        RedisValue test_data;

        try
        {
            test_data = _redis_db.HashGet("LastSeen" + ChannelId, user.Id);
        }
        catch
        {
            return;
        }
        // Console.WriteLine("Plz: " + test_data);
        System.Diagnostics.Debug.WriteLine(test_data);

        last_seen_time = Convert.ToDateTime(test_data);
        System.Diagnostics.Debug.WriteLine(last_seen_time);
        // Get all the messages in that channel
        // Compare them with last seen, and append them to list
        var messages = _redis_db.ListRange(ChannelId.ToString(), 0, -1);

        foreach (var message in messages)
        {
            TextModel text      = JsonConvert.DeserializeObject <TextModel>(message);
            var       sent_time = Convert.ToDateTime(text.SentTime);
            if (sent_time > last_seen_time)
            {
                // Add message to bulk email content
                sent_email_body += text.Content;
                // Add message to list
                message_list.Add(text);
                // Increment the counter
                sent_message_count++;
            }
        }
        // If no message is fetched no need to send a mail
        if (sent_message_count == 0)
        {
            System.Diagnostics.Debug.WriteLine("No need to send a mail.");
        }
        else
        {
            var finalized_mail_body = GetFormattedMessage(message_list, user, channelName);
            // Send the email to user
            await _emailSender.SendEmailAsync(user.Email, "Channel Bulk Mail Feed : " + channelName, finalized_mail_body);

            // Set last seen for this person in this channel to this message
            HashEntry   entry = new HashEntry(user.Id.ToString(), DateTime.Now.ToString());
            HashEntry[] arr   = new HashEntry[1];
            arr[0] = entry;
            _redis_db.HashSet("LastSeen" + ChannelId.ToString(), arr);
        }
    }
 public void HashSet_1()
 {
     HashEntry[] hashFields = new HashEntry[0];
     wrapper.HashSet("key", hashFields, CommandFlags.HighPriority);
     mock.Verify(_ => _.HashSet("prefix:key", hashFields, CommandFlags.HighPriority));
 }
Beispiel #27
0
        public void TransferLock(string address)
        {
            IDatabase db = Business.RedisConnection.Instance.GetDatabase();
            HashEntry[] hashFields = new HashEntry[3];
            hashFields[0] = new HashEntry("MasterAccessionNo", this.MasterAccessionNo);
            hashFields[1] = new HashEntry("Address", address);
            hashFields[2] = new HashEntry("TimeAquired", DateTime.Now.ToString());
            db.HashSet(this.HashKey, hashFields);

            this.m_Address = address;
            this.m_TimeAquired = DateTime.Now;
            this.NotifyPropertyChanged(string.Empty);
        }
 public void DeleteHashValue(HashEntry entry, RedisKeyObject hashKey)
 {
     Task.Run(async () => await DeleteHashValueAsync(entry, hashKey)).Wait();
 }
 public abstract Task DeleteHashValueAsync(HashEntry entry, RedisKeyObject hashKey, CancellationToken token = default(CancellationToken));
        public void Intercept(IInvocation invocation)
        {
            var prop = ((IProxyTargetAccessor)invocation.Proxy).GetTargetPropertyInfo();

            var hashKey = new RedisKeyObject(prop, _commonData.Id);

            _commonData.RedisObjectManager.RedisBackup?.RestoreHash(_commonData.RedisDatabase, hashKey);

            // We will need the Original value no matter what
            var accessor = (IProxyTargetAccessor)invocation.Proxy;
            var original = (accessor.DynProxyGetTarget() as IDictionary)?[invocation.Arguments[0]];
            if (original == null) return;

            object dictKey = null, dictValue = null;

            // Determine if this is a KeyValuePair or a 2 argument
            if (invocation.Arguments.Length == 2)
            {
                dictKey = invocation.Arguments[0];
                dictValue = invocation.Arguments[1];
            }
            else
            {
                var valuePairType = invocation.Arguments[0].GetType();
                if (valuePairType.Name.StartsWith("KeyValuePair", StringComparison.Ordinal))
                {
                    dictKey = valuePairType.GetProperty("Key").GetValue(invocation.Arguments[0]);
                    dictValue = valuePairType.GetProperty("Value").GetValue(invocation.Arguments[0]);
                }
            }

            if (dictKey == null || dictValue == null)
            {
                throw new NullReferenceException("Key or Value cannot be Null");
            }

            var valueRedis = dictValue as IRedisObject;
            if (valueRedis != null)
            {
                RedisKeyObject key;
                if (!(dictValue is IProxyTargetAccessor))
                {
                    //var proxy = CreateProxy(valueRedis, out key);
                    var proxy = valueRedis.CreateProxy(_commonData, out key);
                    invocation.Arguments[1] = proxy;
                    dictValue = proxy;
                }
                else
                {
                    key = new RedisKeyObject(valueRedis.GetType(), string.Empty);
                    _commonData.RedisDatabase.GenerateId(key, dictValue, _commonData.RedisObjectManager.RedisBackup);
                }

                if (_commonData.Processing)
                {
                    invocation.Proceed();
                    return;
                }

                // TODO we will need to try to remove the old RedisObject
                var hashEntry = new HashEntry((string)dictKey, key.RedisKey);
                _commonData.RedisObjectManager.RedisBackup?.UpdateHashValue(hashEntry, hashKey);

                _commonData.RedisDatabase.HashSet(hashKey.RedisKey, hashEntry.Name, hashEntry.Value);
                _commonData.RedisObjectManager.SaveObject(dictValue, key.Id, _commonData.RedisDatabase);
            }
            else
            {
                if (_commonData.Processing)
                {
                    invocation.Proceed();
                    return;
                }

                var hashValue = new HashEntry((string)dictKey, (RedisValue)dictValue);
                _commonData.RedisObjectManager.RedisBackup?.UpdateHashValue(hashValue, hashKey);
                _commonData.RedisDatabase.HashSet(hashKey.RedisKey, hashValue.Name, hashValue.Value);
            }

            invocation.Proceed();
        }
Beispiel #31
0
 private void GetHashEntry(int index, out HashEntry h)
 {
     h.Name1 = hashTable[index * 4 + 0];
     h.Name2 = hashTable[index * 4 + 1];
     h.BlockIndex = hashTable[index * 4 + 3];
 }
Beispiel #32
0
 private static HashEntry GetHashEntry(Type enumType)
 {
     HashEntry entry = (HashEntry) fieldInfoHash[enumType];
     if (entry == null)
     {
         if (fieldInfoHash.Count > 100)
         {
             fieldInfoHash.Clear();
         }
         ulong[] values = null;
         string[] names = null;
         if (enumType.BaseType == typeof(Enum))
         {
             InternalGetEnumValues(enumType, ref values, ref names);
         }
         else
         {
             FieldInfo[] fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
             values = new ulong[fields.Length];
             names = new string[fields.Length];
             for (int i = 0; i < fields.Length; i++)
             {
                 names[i] = fields[i].Name;
                 values[i] = ToUInt64(fields[i].GetValue(null));
             }
             for (int j = 1; j < values.Length; j++)
             {
                 int index = j;
                 string str = names[j];
                 ulong num4 = values[j];
                 bool flag = false;
                 while (values[index - 1] > num4)
                 {
                     names[index] = names[index - 1];
                     values[index] = values[index - 1];
                     index--;
                     flag = true;
                     if (index == 0)
                     {
                         break;
                     }
                 }
                 if (flag)
                 {
                     names[index] = str;
                     values[index] = num4;
                 }
             }
         }
         entry = new HashEntry(names, values);
         fieldInfoHash[enumType] = entry;
     }
     return entry;
 }
 /**
  * Adds an entry into this map, maintaining insertion order.
  * <p>
  * This implementation adds the entry to the data storage table and
  * to the end of the linked list.
  *
  * @param entry  the entry to add
  * @param hashIndex  the index into the data array to store at
  */
 protected override void addEntry(HashEntry entry, int hashIndex)
 {
     LinkEntry link = (LinkEntry)entry;
     link.after = header;
     link.before = header.before;
     header.before.after = link;
     header.before = link;
     data[hashIndex] = entry;
 }
        public void Intercept(IInvocation invocation)
        {
            var prop = ((IProxyTargetAccessor)invocation.Proxy).GetTargetPropertyInfo();
            var hashKey = new RedisKeyObject(prop, _commonData.Id);

            _commonData.RedisObjectManager.RedisBackup?.RestoreHash(_commonData.RedisDatabase, hashKey);

            object dictKey = null, dictValue = null;

            // Determine if this is a KeyValuePair or a 2 argument
            if (invocation.Arguments.Length == 2)
            {
                dictKey = invocation.Arguments[0];
                dictValue = invocation.Arguments[1];
            }
            else
            {
                var valuePairType = invocation.Arguments[0].GetType();
                if (valuePairType.Name.StartsWith("KeyValuePair", StringComparison.Ordinal))
                {
                    dictKey = valuePairType.GetProperty("Key").GetValue(invocation.Arguments[0]);
                    dictValue = valuePairType.GetProperty("Value").GetValue(invocation.Arguments[0]);
                }
            }

            if (dictKey == null || dictValue == null)
            {
                throw new NullReferenceException("Key or Value cannot be null");
            }

            var containsKeyMethod = invocation.Proxy.GetType().GetMethod("ContainsKey", new[] { dictKey.GetType() });
            if ((bool)containsKeyMethod.Invoke(invocation.Proxy, new[] { dictKey }))
            {
                invocation.Proceed();
                return;
            }

            var redisObject = dictValue as IRedisObject;
            if (redisObject != null)
            {
                RedisKeyObject key;
                if (!(dictValue is IProxyTargetAccessor))
                {
                    var proxy = redisObject.CreateProxy(_commonData, out key);
                    invocation.Arguments[1] = proxy;
                    dictValue = proxy;
                }
                else
                {
                    key = new RedisKeyObject(redisObject.GetType());
                    _commonData.RedisDatabase.GenerateId(key, dictValue, _commonData.RedisObjectManager.RedisBackup);
                }

                if (_commonData.Processing)
                {
                    invocation.Proceed();
                    return;
                }

                HashEntry hashEntry;
                if (dictKey is RedisValue)
                {
                    hashEntry = new HashEntry((RedisValue) dictKey, key.RedisKey);
                }
                else
                {
                    RedisValue redisKey;
                    if (!_commonData.RedisObjectManager.TryConvertToRedisValue(dictKey, out redisKey))
                    {
                        throw new Exception("Invalid Key Type...");
                    }
                    hashEntry = new HashEntry(redisKey, key.RedisKey);
                }

                _commonData.RedisObjectManager.RedisBackup?.UpdateHashValue(hashEntry, hashKey);
                _commonData.RedisDatabase.HashSet(hashKey.RedisKey, hashEntry.Name, hashEntry.Value);
                _commonData.RedisObjectManager.SaveObject(dictValue, key.Id, _commonData.RedisDatabase);
            }
            else
            {
                if (_commonData.Processing)
                {
                    invocation.Proceed();
                    return;
                }

                // Converter can get rid of this too
                RedisValue newDictValue;
                if (!(dictValue is RedisValue))
                {
                    if (!_commonData.RedisObjectManager.TryConvertToRedisValue(dictValue, out newDictValue))
                    {
                        throw new Exception("Cannot convert to RedisValue");
                    }
                }
                else
                {
                    newDictValue = (RedisValue)dictValue;
                }

                HashEntry hashEntry;
                if (dictKey is RedisValue)
                {
                    hashEntry = new HashEntry((RedisValue) dictKey, newDictValue);
                }
                else
                {
                    RedisValue redisKey;
                    if (!_commonData.RedisObjectManager.TryConvertToRedisValue(dictKey, out redisKey))
                    {
                        throw new Exception("Cannot convert to RedisValue");
                    }
                    hashEntry = new HashEntry(redisKey, newDictValue);
                }

                _commonData.RedisObjectManager.RedisBackup?.UpdateHashValue(hashEntry, hashKey);
                _commonData.RedisDatabase.HashSet(hashKey.RedisKey, hashEntry.Name, hashEntry.Value);
            }

            invocation.Proceed();
        }
 /**
  * Creates an entry to store the data.
  * This implementation creates an IdentityEntry instance.
  *
  * @param next  the next entry in sequence
  * @param hashCode  the hash code to use
  * @param key  the key to store
  * @param value  the value to store
  * @return the newly created entry
  */
 protected override HashEntry createEntry(HashEntry next, int hashCode, Object key, Object value)
 {
     return new IdentityEntry(next, hashCode, key, value);
 }
        /// <summary>
        /// Instantiates a new instance of the RedisSessionStateItemCollection class with data from
        ///     Redis
        /// </summary>
        /// <param name="redisHashData">An array of keys to values from the redis hash</param>
        /// <param name="redisConnName">The name of the connection from the redis connection wrapper</param>
        public RedisSessionStateItemCollection(
            HashEntry[] redisHashData, 
            string redisConnName,
            byte constructorSignatureDifferentiator)
        {
            int byteDataTotal = 0;
            int concLevel = RedisSessionConfig.SessionAccessConcurrencyLevel;
            if (concLevel < 1)
            {
                concLevel = 1;
            }

            int numItems = 0;
            if (redisHashData != null)
            {
                numItems = redisHashData.Length;
            }

            // To match ASP.NET behavior, dictionaries should match keys case insensitively
            this.Items = new ConcurrentDictionary<string, object>(concLevel, numItems, StringComparer.InvariantCultureIgnoreCase);
            this.SerializedRawData = new ConcurrentDictionary<string, string>(concLevel, numItems, StringComparer.InvariantCultureIgnoreCase);
            if (redisHashData != null)
            {
                foreach (var sessDataEntry in redisHashData)
                {
                    string hashItemKey = sessDataEntry.Name.ToString();
                    string hashItemValue = sessDataEntry.Value.ToString();

                    if (this.SerializedRawData.TryAdd(
                        hashItemKey,
                        hashItemValue))
                    {
                        this.Items.TryAdd(
                            hashItemKey,
                            new NotYetDeserializedPlaceholderValue());
                    }

                    byteDataTotal += hashItemValue.Length;
                }
            }

            // To match ASP.NET behavior, dictionaries should match keys case insensitively
            this.ChangedKeysDict = new ConcurrentDictionary<string, ActionAndValue>(StringComparer.InvariantCultureIgnoreCase);

            if (byteDataTotal != 0 && !string.IsNullOrEmpty(redisConnName) &&
                RedisConnectionConfig.LogRedisSessionSize != null)
            {
                RedisConnectionConfig.LogRedisSessionSize(redisConnName, byteDataTotal);
            }

            this.cereal = RedisSerializationConfig.SessionDataSerializer;

            if (byteDataTotal > RedisConnectionConfig.MaxSessionByteSize)
            {
                RedisConnectionConfig.RedisSessionSizeExceededHandler(this, byteDataTotal);
            }
        }
Beispiel #37
0
        public void TestSetPairs() // http://redis.io/commands/hmset
        {
            using (var muxer = Config.GetUnsecuredConnection())
            {
                var conn = muxer.GetDatabase(9);
                conn.KeyDeleteAsync("hashkey");

                var result0 = conn.HashGetAllAsync("hashkey");

                var data = new HashEntry[] {
                    new HashEntry("foo", Encoding.UTF8.GetBytes("abc")),
                    new HashEntry("bar", Encoding.UTF8.GetBytes("def"))
                };
                conn.HashSetAsync("hashkey", data);

                var result1 = conn.HashGetAllAsync("hashkey");

                Assert.AreEqual(0, result0.Result.Length);
                var result = result1.Result.ToStringDictionary();
                Assert.AreEqual(2, result.Count);
                Assert.AreEqual("abc", result["foo"]);
                Assert.AreEqual("def", result["bar"]);
            }
        }
        public override void Load(HashSet<Request> requests)
        {
            lock (this)
            {
                RedisValue[] identities = new RedisValue[requests.Count];
                HashEntry[] items = new HashEntry[requests.Count];
                int i = 0;
                foreach (var request in requests)
                {
                    identities[i] = request.Identity;
                    items[i] = new HashEntry(request.Identity, JsonConvert.SerializeObject(request));
                    ++i;
                }

                Db.SetAdd(SetKey, identities);
                Db.ListRightPush(QueueKey, identities);
                Db.HashSet(ItemKey, items);
            }
        }
 /// <summary>
 /// convert hashEntry array to Dictionary 
 /// </summary>
 /// <param name="entries">HashEntry[]</param>
 /// <returns>IDictionary{string, string}</returns>
 protected IDictionary<string, string> ConvertToDictionaryString(HashEntry[] entries)
 {
     var stringMap = new Dictionary<string, string>();
     if (entries != null)
     {
         foreach (var entry in entries)
         {
             stringMap.Add(entry.Name, entry.Value.ToString());
         }
     }
     return stringMap;
 }
 /**
  * Removes an entry from the map and the linked list.
  * <p>
  * This implementation removes the entry from the linked list chain, then
  * calls the superclass implementation.
  *
  * @param entry  the entry to remove
  * @param hashIndex  the index into the data structure
  * @param previous  the previous entry in the chain
  */
 protected override void removeEntry(HashEntry entry, int hashIndex, HashEntry previous)
 {
     LinkEntry link = (LinkEntry)entry;
     link.before.after = link.after;
     link.after.before = link.before;
     link.after = null;
     link.before = null;
     base.removeEntry(entry, hashIndex, previous);
 }
Beispiel #41
0
        private void TryHashSet()
        {
            IDatabase db = Business.RedisConnection.Instance.GetDatabase();
            HashEntry[] hashFields = new HashEntry[3];
            hashFields[0] = new HashEntry("MasterAccessionNo", this.m_MasterAccessionNo);
            hashFields[1] = new HashEntry("Address", UI.AppMessaging.AccessionLockMessage.GetMyAddress());
            hashFields[2] = new HashEntry("TimeAquired", DateTime.Now.ToString());

            var transaction = db.CreateTransaction();
            transaction.AddCondition(Condition.HashNotExists(this.HashKey, "MasterAccessionNo"));
            transaction.HashSetAsync(this.HashKey, hashFields);
            transaction.SetAddAsync("AccessionLocks", this.HashKey);
            bool committed = transaction.Execute();
        }
 protected internal IdentityEntry(HashEntry next, int hashCode, Object key, Object value)
     : base(next, hashCode, key, value)
 {
 }
Beispiel #43
0
 public AccessionLock(HashEntry[] hashEntries)
 {
     this.m_MasterAccessionNo = hashEntries[0].Value;
     this.m_Address = hashEntries[1].Value;
     this.m_TimeAquired = DateTime.Parse(hashEntries[2].Value);
 }
 public static HashEntry WithName(HashEntry[] hash, string name)
 {
     return hash.Single(h => h.Name == name);
 }
Beispiel #45
0
        /// <summary>
        /// 批量导入
        /// </summary>
        /// <param name="requests">请求对象</param>
        public override void Reload(ICollection <Request> requests)
        {
            var action = new Action(() =>
            {
                lock (_locker)
                {
                    int batchCount = BatchCount;

                    var count               = requests.Count;
                    int cacheSize           = count > batchCount ? batchCount : count;
                    RedisValue[] identities = new RedisValue[cacheSize];
                    HashEntry[] items       = new HashEntry[cacheSize];
                    int i = 0;
                    int j = count % batchCount;
                    int n = count / batchCount;

                    foreach (var request in requests)
                    {
                        identities[i] = request.GetIdentity();
                        items[i]      = new HashEntry(request.GetIdentity(), JsonConvert.SerializeObject(request));
                        ++i;
                        if (i != batchCount)
                        {
                            continue;
                        }
                        --n;

                        _redisConnection.Database.SetAdd(_setKey, identities);
                        _redisConnection.Database.ListRightPush(_queueKey, identities);
                        _redisConnection.Database.HashSet(_itemKey, items);

                        i = 0;
                        if (n != 0)
                        {
                            identities = new RedisValue[batchCount];
                            items      = new HashEntry[batchCount];
                        }
                        else
                        {
                            identities = new RedisValue[j];
                            items      = new HashEntry[j];
                        }
                    }

                    if (i <= 0)
                    {
                        return;
                    }
                    _redisConnection.Database.SetAdd(_setKey, identities);
                    _redisConnection.Database.ListRightPush(_queueKey, identities);
                    _redisConnection.Database.HashSet(_itemKey, items);
                }
            });

            if (UseInternet)
            {
                NetworkCenter.Current.Execute("rds-import", action);
            }
            else
            {
                action();
            }
        }
 public void put(int key, int value)
 {
     int hash = (key % TABLE_SIZE);
     while (table[hash] != null && table[hash].key != EntryDeleted && table[hash].key != key)
         hash = (hash + 1) % TABLE_SIZE;
     table[hash] = new HashEntry(key, value);
 }