Пример #1
0
        protected override async Task OnMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs e)
        {
            byte[] packet = e.ApplicationMessage.Payload;
            string txt    = Encoding.UTF8.GetString(packet);

            try
            {
                EventModel data = JsonConvert.DeserializeObject <EventModel>(txt);
                using (var session = sessionFactory.OpenStatelessSession())
                    using (var transaction = session.BeginTransaction())
                    {
                        EventMap map      = session.Get <EventMap>(data.EventCode);
                        string   redisKey = $"SID{data.SiteId}.EVENT.{data.DeviceId}";
                        Program.logger.Info($"Received Event: {data.EventCode} / Status: {data.Status}");
                        switch (data.Status)
                        {
                        case EventStatus.New:
                            await redisDb.HashSetAsync(redisKey, $"{data.EventCode}", bool.TrueString);

                            // 새로 발생한 이벤트
                            IList <EventRecord> ev = await FindNewRaiseEvent(data.EventCode, session.CreateCriteria <EventRecord>());

                            if (ev.Count > 0)
                            {
                                return;
                            }
                            EventRecord newEventRecode = new EventRecord();
                            newEventRecode.CreateDT = new DateTime(1970, 1, 1).AddSeconds(data.UnixTimestamp).ToLocalTime();
                            newEventRecode.EventId  = data.EventCode;
                            newEventRecode.SiteId   = data.SiteId;
                            newEventRecode.DeviceId = data.DeviceId;
                            await session.InsertAsync(newEventRecode);

                            break;

                        case EventStatus.Recovery:
                            await redisDb.HashSetAsync(redisKey, $"{data.EventCode}", bool.FalseString);

                            var rc_result = await FindNewRaiseEvent(data.EventCode, session.CreateCriteria <EventRecord>());

                            if (rc_result.Count > 0)
                            {
                                foreach (EventRecord exist_record in rc_result)
                                {
                                    exist_record.RecoveryDT = new DateTime(1970, 1, 1).AddSeconds(data.UnixTimestamp).ToLocalTime();
                                    await session.UpdateAsync(exist_record);
                                }
                            }
                            break;
                        }
                        await transaction.CommitAsync();
                    }
            }
            catch (Exception ex)
            {
                Program.logger.Error(ex, ex.Message);
            }
        }
        /// <summary>
        /// Sends raw announcement.
        /// </summary>
        /// <param name="payload">The raw announcement data.</param>
        /// <returns>
        /// Return the message id
        /// </returns>
        public async ValueTask <string> SendAsync(Announcement payload)
        {
            IDatabaseAsync db = await _dbTask;

            Metadata meta = payload.Metadata;
            string   id   = meta.MessageId;

            #region var entries = new NameValueEntry[]{...}

            // local method
            NameValueEntry KV(RedisValue key, RedisValue value) => new NameValueEntry(key, value);

            var entries = new NameValueEntry[]
            {
                KV(nameof(meta.MessageId), id),
                KV(nameof(meta.Operation), meta.Operation),
                KV(nameof(meta.ProducedAt), meta.ProducedAt.ToUnixTimeSeconds())
            };

            #endregion // var entries = new NameValueEntry[]{...}

            // TODO: [bnaya 2021-01] enable to replace the segments storage without replacing the strweam

            #region await db.HashSetAsync($"Segments~{id}", segmentsEntities)

            var segmentsEntities = payload.Segments
                                   .Select(sgm =>
                                           new HashEntry(sgm.Key, sgm.Value))
                                   .ToArray();
            await db.HashSetAsync($"Segments~{id}", segmentsEntities);

            #endregion // await db.HashSetAsync($"Segments~{id}", segmentsEntities)

            #region await db.HashSetAsync($"Interceptors~{id}", interceptionsEntities)

            var interceptionsEntities = payload.InterceptorsData
                                        .Select(spt =>
                                                new HashEntry(spt.Key, spt.Value))
                                        .ToArray();
            await db.HashSetAsync($"Interceptors~{id}", interceptionsEntities);

            #endregion // await db.HashSetAsync($"Interceptors~{id}", interceptionsEntities)

            RedisValue messageId = await _resiliencePolicy.ExecuteAsync(() =>
                                                                        db.StreamAddAsync(meta.Key(), entries,
                                                                                          flags: CommandFlags.DemandMaster));


            return(messageId);
        }
        public Task AddRecord(IDatabaseAsync database, IDataKey objectKey, params T[] instances)
        {
            if (database == null)
            {
                throw new ArgumentNullException(nameof(database));
            }

            if (objectKey == null)
            {
                throw new ArgumentNullException(nameof(objectKey));
            }

            if (instances == null)
            {
                throw new ArgumentNullException(nameof(instances));
            }

            log.LogDebug("AddRecords: {0}", instances.Length);
            if (instances.Length > 1)
            {
                throw new ArgumentOutOfRangeException();
            }

            var instance  = instances[0];
            var tasks     = new List <Task>();
            var actualKey = link.GetKey(objectKey);
            var entries   = objectSerialization.GetEntries(instance).ToArray();

            tasks.Add(database.HashSetAsync(actualKey, entries));
            tasks.AddRange(mainIndexManager.Add(database, objectKey));
            return(Task.WhenAll(tasks));
        }
Пример #4
0
        protected override async Task OnApplicationMessageReceived(string ClientId, string Topic, string ContentType, uint QosLevel, byte[] payload)
        {
            try
            {
                string      data       = Encoding.UTF8.GetString(payload);
                JObject     jObj       = JObject.Parse(data);
                int         groupId    = jObj["groupid"].Value <int>();
                int         siteId     = jObj["siteId"].Value <int>();
                string      deviceId   = jObj["normalizedeviceid"].Value <string>();
                string      redisKey   = CommonFactory.CreateRedisKey(siteId, groupId, deviceId);
                HashEntry[] hashValues = CreateHashEntry(jObj);
                await db.HashSetAsync(redisKey, hashValues);

                //if(groupId == 4) // PV일 경우
                //{
                //    float totalActivePower = jObj["EnergyTotalActivePower"].Value<float>();
                //    string sub_redis_key = CommonFactory.CreateRedisKey(siteId, groupId, "EnergyTotalActivePower");
                //    int deviceIndex = int.Parse(deviceId.TrimStart("PV".ToCharArray()));
                //    if(await db.KeyExistsAsync(sub_redis_key) == false)
                //    {
                //        await db.ListLeftPushAsync(sub_redis_key, new RedisValue[] { 0, 0, 0, 0 });
                //    }
                //    await db.ListSetByIndexAsync(sub_redis_key, deviceIndex - 1, totalActivePower);
                //}
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Method: OnApplicationMessageReceived\n" + ex.Message);
            }
        }
        public async Task <bool> HashSetAsync(RedisKey key, RedisValue hashField, RedisValue value, TimeSpan?expiry = null, When when = When.Always)
        {
            key = $"{productID}_{key}";
            IDatabaseAsync db      = null;
            ITransaction   context = CallContext.GetData(KEY_WORD_REDIS_CONTEXT) as ITransaction;

            if (context == null)
            {
                db = Database();
                if (db == null)
                {
                    return(false);
                }
            }
            else
            {
                db = context;
            }
            UsingCount();
            bool is_success = await db.HashSetAsync(key, hashField, value, when);

            if (expiry != null)
            {
                await db.KeyExpireAsync(key, expiry);
            }
            return(is_success);
        }
        public async Task <bool> UpsertPollSummary(PollSummary summary)
        {
            try
            {
                var memoryStream = new MemoryStream();
                using (var outputStream = new Google.Protobuf.CodedOutputStream(memoryStream))
                {
                    summary.WriteTo(outputStream);
                }


                var summaryData = memoryStream.ToArray();

                var pollId = summary.Poll?.Id;
                if (pollId == null || pollId == "")
                {
                    return(false);
                }

                var response = await _database.HashSetAsync(PollSummaryHashKey, pollId, summaryData, When.Always);

                var didPublish = await _pubSub.PublishUpdate(summary);

                return(didPublish);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Error while poll summary to database");
                return(false);
            }
        }
        public async Task WriteAsync(string databaseKey, JobModel job)
        {
            var data = await Task.Run(() =>
                                      JsonConvert.SerializeObject(job, Formatting.None)).ConfigureAwait(false);

            await _redis.HashSetAsync(databaseKey, job.JobId, data).ConfigureAwait(false);
        }
        private static async Task UpdateRowCacheInRedis(IDatabaseAsync db, RootIndexRow row)
        {
            var redisSetKey           = GetRedisKeyForColumn(row.ColumnName);
            var redisFilesToValuesKey = GetRedisFilesToValuesKeyForColumn(row.ColumnName);
            var redisValuesToFilesKey = GetRedisValuesToFilesKeyForColumn(row.ColumnName);
            var currentMaxValue       = await db.HashGetAsync(redisFilesToValuesKey, row.FileName);

            if (currentMaxValue != default)
            {
                await db.HashDeleteAsync(redisValuesToFilesKey, currentMaxValue);

                await db.SortedSetRemoveAsync(redisSetKey, currentMaxValue);
            }

            await db.HashSetAsync(redisValuesToFilesKey, row.FileName, row.Max);

            await db.HashSetAsync(redisValuesToFilesKey, row.Max, row.FileName);

            await db.SortedSetAddAsync(redisSetKey, row.Max, 0);
        }
Пример #9
0
        public override void Set(
            IDatabaseAsync context,
            IEnumerable <TValue> items
            )
        {
            var indexName = _indexCollectionName;

            context.HashSetAsync(indexName, items.ToHashEntries(IndexedKeyExtractor.ExtractKey, IndexedValueExtractor));

            if (Expiry.HasValue)
            {
                context.KeyExpireAsync(indexName, Expiry);
            }
        }
Пример #10
0
        private static async Task SyncRedisKeyAsync(IDatabaseAsync srcDatabase, RedisKey redisKey, IDatabaseAsync destDatabase)
        {
            if (await destDatabase.KeyExistsAsync(redisKey))
            {
                await destDatabase.KeyDeleteAsync(redisKey);
            }
            var type = await srcDatabase.KeyTypeAsync(redisKey);

            switch (type)
            {
            case RedisType.String:
                var strVal = await srcDatabase.StringGetAsync(redisKey);

                await destDatabase.StringSetAsync(redisKey, strVal);

                break;

            case RedisType.List:
                var list = await srcDatabase.ListRangeAsync(redisKey);

                await destDatabase.ListRightPushAsync(redisKey, list);

                break;

            case RedisType.Set:
                var set = await srcDatabase.SetMembersAsync(redisKey);

                await destDatabase.SetAddAsync(redisKey, set);

                break;

            case RedisType.SortedSet:
                var zset = await srcDatabase.SortedSetRangeByRankWithScoresAsync(redisKey);

                await destDatabase.SortedSetAddAsync(redisKey, zset);

                break;

            case RedisType.Hash:
                var hash = await srcDatabase.HashGetAllAsync(redisKey);

                await destDatabase.HashSetAsync(redisKey, hash);

                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Пример #11
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("execute worker");
            string target_ip   = Environment.GetEnvironmentVariable("UDP_TARGET_IP");
            string target_port = Environment.GetEnvironmentVariable("UDP_TARGET_PORT");

            _logger.LogInformation("Target UDP Server: {0} : {1}", target_ip, target_port);
            int portNum = 11000;

            int.TryParse(target_port, out portNum);
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    //_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                    JObject jObj = await packetQueue.DequeueAsync(stoppingToken);

                    int    groupId  = jObj["groupid"].Value <int>();
                    int    siteId   = jObj["siteId"].Value <int>();
                    string deviceId = jObj["normalizedeviceid"].Value <string>();

                    //if (groupId == 4 && siteId == 6)
                    //{
                    //    PvPacket packet = ConvertPacket(jObj);
                    //    int packSize = packet.GetSize();
                    //    var pack = packet.ToByteArray();
                    //    int packLength = pack.Length;
                    //    int sendpackets = udpClient.Send(pack, packLength, target_ip, portNum);
                    //    _logger.LogInformation("SENDING PACKET ({0} bytes)", sendpackets);
                    //}


                    string      redisKey   = CreateRedisKey(siteId, groupId, deviceId);
                    HashEntry[] hashValues = CreateHashEntry(jObj);
                    await db.HashSetAsync(redisKey, hashValues);

                    await Task.Delay(100, stoppingToken);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, ex.Message);
                }
            }
        }
Пример #12
0
        protected virtual Task AddManyLoginsAsync(TUser user, IEnumerable <UserLoginInfo> logins, ITransaction transaction = null)
        {
            Contract.Requires(logins != null && logins.Count() > 0);

            IDatabaseAsync db = transaction == null ? Database : (IDatabaseAsync)transaction;

            Task setTask = db.SetAddAsync
                           (
                string.Format(UserLoginSetKey, ((IUser)user).Id),
                logins.Select(login => (RedisValue)JsonConvert.SerializeObject(login)).ToArray()
                           );

            Task hashTask = db.HashSetAsync
                            (
                UserLoginHashKey,
                logins.Select(login => new HashEntry(string.Format("{0}:{1}", login.LoginProvider, login.ProviderKey), ((IUser)user).Id)).ToArray()
                            );

            return(Task.WhenAll(setTask, hashTask));
        }
Пример #13
0
        public Task <bool> HashSetAsync(RedisKey key, RedisValue hashField, RedisValue value, When when = When.Always)
        {
            IDatabaseAsync db      = null;
            ITransaction   context = CallContext.GetData(KEY_WORD_REDIS_CONTEXT) as ITransaction;

            if (context == null)
            {
                db = Database();
                if (db == null)
                {
                    return(Task.FromResult(false));
                }
            }
            else
            {
                db = context;
            }

            UsingCount();
            return(db.HashSetAsync(key, hashField, value, when));
        }
Пример #14
0
        public async Task <IActionResult> GetEventMapList(int siteid, string source, int count)
        {
            using (var session = peiuGridDataContext.SessionFactory.OpenStatelessSession())
            {
                var map_row = await session.CreateCriteria <EventMap>()
                              .Add(Restrictions.Eq("Source", source))
                              .ListAsync <EventMap>();

                foreach (EventMap map in map_row)
                {
                    for (int idx = 1; idx <= count; idx++)
                    {
                        string redisKey = $"SID{siteid}.EVENT.{source}{idx}";
                        if (await db.HashExistsAsync(redisKey, map.EventId) == false)
                        {
                            await db.HashSetAsync(redisKey, map.EventId, bool.FalseString);
                        }
                    }
                }
            }
            return(Ok());
        }
Пример #15
0
        /// <summary>
        ///     Using HashSetAsync
        /// </summary>
        /// <param name="db"></param>
        /// <returns></returns>
        private static async Task GenerateClocks(IDatabaseAsync db)
        {
            var sw     = Stopwatch.StartNew();
            var random = new Random();

            for (var i = 0; i < Total; i++)
            {
                var id    = $"GT-{i}";
                var clock = new ClockInfo
                {
                    DeviceId     = id,
                    SerialNumber = id.ToLower(),
                    ClientId     = random.Next(10000, 99999),
                    ClockGroupId = Guid.NewGuid()
                };
                await db.HashSetAsync($"clock:{id}", clock.ToHashEntries());

                await db.KeyExpireAsync($"clock:{id}", DateTime.Now.AddMinutes(5));
            }

            Console.WriteLine(
                $"Storing {Total} Using original HashSetAsync (v1): {Math.Round(sw.Elapsed.TotalMilliseconds, 3)}ms");
        }
        //private async Task SendQueue(string topic, JObject msg_oridinary, CancellationToken token)
        //{
        //    foreach (var mqtt_proxy in mqtt_clients)
        //    {
        //        try
        //        {

        //            var msg = CreateMqttMessage(topic, msg_oridinary.ToString(), mqtt_proxy.Options.QosLevel);
        //            var mqtt_client = mqtt_proxy.MqttClient;

        //            if (mqtt_client.IsConnected == false)
        //                continue;
        //            await mqtt_client.PublishAsync(msg, token);
        //            Thread.Sleep(10);
        //            break;
        //        }
        //        catch (Exception ex)
        //        {
        //            logger.LogError(ex, ex.Message);
        //        }
        //    }
        //}

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                stoppingToken.ThrowIfCancellationRequested();
                try
                {
                    bool isConnected = modbusFactory.ReconnectWhenDisconnected(stoppingToken, 3);
                    if (isConnected == false)
                    {
                        logger.LogWarning("모드버스 접속에 실패했습니다. 5초후 재개");
                        await Task.Delay(5000, stoppingToken);

                        continue;
                    }



                    stoppingToken.ThrowIfCancellationRequested();
                    //var parallelResult = Parallel.ForEach<GroupPoint>(modbus.GroupPoints, (async x =>
                    foreach (var x in modbus.GroupDigitalPoints)
                    {
                        if (x.Disable == true)
                        {
                            continue;
                        }
                        List <DiMap> results = await modbusFactory.ReadModbusEvent(x);


                        foreach (DiMap map in results)
                        {
                            if (map.DocumentAddress == 40132)
                            {
                            }
                            if (map.Disable == true)
                            {
                                continue;
                            }



                            //cache.Get()
                            //datarow.Add(map.Name, map.Value);
                            string redis_key   = $"{modbus.DeviceName}.{map.DocumentAddress}";
                            ushort redis_value = 0;
                            if (await redis.KeyExistsAsync(redis_key))
                            {
                                string redis_str = await redis.StringGetAsync(redis_key);

                                redis_value = ushort.Parse(redis_str);
                            }

                            if (map.Value == redis_value)
                            {
                                continue;
                            }
                            else
                            {
                                await redis.StringSetAsync(redis_key, map.Value.ToString());
                            }



                            using (var session = dbAccess.SessionFactory.OpenSession())
                            {
                                using (var transaction = session.BeginTransaction())
                                {
                                    EventSummary summary = new EventSummary();
                                    summary.SiteId     = SiteId;
                                    summary.DeviceName = modbus.DeviceName;
                                    summary.GroupName  = map.Name;

                                    summary.SetTimestamp(DateTime.Now);
                                    foreach (DiFlag evt in map.Flags)
                                    {
                                        EventField ef = event_map.FirstOrDefault(Tx => Tx.Register == map.DocumentAddress && Tx.BitValue == evt.BitValue);


                                        bool IsActive = evt.IsActivate(map.Value);
                                        if (evt.EventCode.HasValue)
                                        {
                                            summary.ActiveEvents.Add(evt.EventCode.Value);
                                        }
                                        string redis_event_key = redis_key + "." + evt.No;

                                        if (await redis.KeyExistsAsync(redis_event_key) == false)
                                        {
                                            await redis.HashSetAsync(redis_event_key, CreateEventNode(map, evt));
                                        }
                                        else
                                        {
                                            await redis.HashSetAsync(redis_event_key, "Status", IsActive);
                                        }

                                        if (map.Disable == true || map.Level == 0)
                                        {
                                            continue;
                                        }

                                        string mysql_key_str = $"{modbus.DeviceName}{map.DocumentAddress}{evt.No}";

                                        string normalizeDeviceName = map.Source + DeviceIndex;
                                        //ActiveEvent existEvent = session.Get<ActiveEvent>(mysql_key_str);
                                        ActiveEvent existEvent = await GetLatestActiveEventAsync(session, mysql_key_str, stoppingToken);

                                        //if (existEvent == null)
                                        //    continue;
                                        switch (EventStatus(existEvent, IsActive, session))
                                        {
                                        case Hubbub.EventStatus.Already:
                                            mysql_key_str             = GetNextEventId(mysql_key_str, session);
                                            existEvent                = new ActiveEvent();
                                            existEvent.Description    = evt.BitName;
                                            existEvent.DeviceName     = modbus.DeviceName;
                                            existEvent.EventLevel     = map.Level;
                                            existEvent.EventName      = evt.BitName;
                                            existEvent.Source         = map.Source;
                                            existEvent.OccurTimestamp = DateTime.Now;
                                            existEvent.EventId        = mysql_key_str;
                                            await session.SaveAsync(existEvent, stoppingToken);

                                            break;

                                        case Hubbub.EventStatus.New:
                                            existEvent                = new ActiveEvent();
                                            existEvent.Description    = evt.BitName;
                                            existEvent.DeviceName     = modbus.DeviceName;
                                            existEvent.EventLevel     = map.Level;
                                            existEvent.EventName      = evt.BitName;
                                            existEvent.Source         = map.Source;
                                            existEvent.OccurTimestamp = DateTime.Now;
                                            existEvent.EventId        = mysql_key_str;
                                            await session.SaveAsync(existEvent, stoppingToken);

                                            if (evt.EventCode.HasValue)
                                            {
                                                summary.NewEvents.Add(evt.EventCode.Value);
                                            }
                                            if (ef != null)
                                            {
                                                await eventPublisherWorker.PublishEvent(SiteId, normalizeDeviceName, ef.Code, Events.Alarm.EventStatus.New, stoppingToken);
                                            }

                                            break;

                                        case Hubbub.EventStatus.Recover:
                                            if (evt.EventCode.HasValue)
                                            {
                                                summary.RecoverEvents.Add(evt.EventCode.Value);
                                            }
                                            RecoversEvent(existEvent.EventId, session);
                                            if (ef != null)
                                            {
                                                await eventPublisherWorker.PublishEvent(SiteId, normalizeDeviceName, ef.Code, Events.Alarm.EventStatus.Recovery, stoppingToken);
                                            }
                                            //existEvent.HasRecovered = true;
                                            //existEvent.RecoverTimestamp = DateTime.Now;
                                            //await session.SaveOrUpdateAsync(existEvent, stoppingToken);
                                            break;
                                        }
                                    }
                                    await transaction.CommitAsync(stoppingToken);

                                    //var msg = CreateMqttMessage(peiu_event_topic, summary.ToString(), 2);
                                    //await mqtt_clients.PeiuEventBrokerProxy.MqttClient.PublishAsync(msg, stoppingToken);
                                }
                            }
                        }
                    }
                }catch (Exception ex)
                {
                }

                //await SendQueue(peiu_event_topic, datarow, stoppingToken);
                await Task.Delay(UpdatePeriod.Milliseconds);

                //Thread.Sleep(UpdatePeriod);
            }
        }
Пример #17
0
 public async ValueTask HashSetAsync(string key, IEnumerable <KeyValuePair <string, string> > keyValuePairs)
 {
     var hashEntries = keyValuePairs.Select(x => new HashEntry(x.Key, x.Value)).ToArray();
     await _database.HashSetAsync(key, hashEntries);
 }
        public async Task <IActionResult> getcurrenteventstatus(int siteId, string deviceName, int index)
        {
            try
            {
                int deviceType = 1;
                if (deviceName.ToUpper() == "PCS")
                {
                    deviceType = 1;
                }
                else if (deviceName.ToUpper() == "BMS")
                {
                    deviceType = 2;
                }
                else if (deviceName.ToUpper() == "PV")
                {
                    deviceType = 3;
                }
                else
                {
                    throw new ArgumentException("존재하지 않는 설비명");
                }
                JArray             result    = new JArray();
                VwContractorsiteEF site_info = await _accountContext.VwContractorsites.FindAsync(siteId);

                if (site_info == null)
                {
                    return(BadRequest());
                }


                using (var session = peiuGridDataContext.SessionFactory.OpenSession())
                {
                    var map_row = await session.CreateCriteria <PEIU.Events.Alarm.ModbusDiMap>()
                                  .Add(Restrictions.Eq("FactoryCode", site_info.DeviceGroupCode) && Restrictions.Eq("DeviceType", deviceType))
                                  .ListAsync <PEIU.Events.Alarm.ModbusDiMap>();

                    //map_row = await session.CreateCriteria<PEIU.Events.Alarm.ModbusDiMap>().ListAsync<PEIU.Events.Alarm.ModbusDiMap>();
                    foreach (PEIU.Events.Alarm.ModbusDiMap map in map_row)
                    {
                        JObject row = new JObject();
                        row.Add("code", map.EventCode);

                        row.Add("name", map.Name);
                        row.Add("category", map.DeviceType);
                        row.Add("level", map.Level);


                        string redisKey = $"SID{siteId}.DI.{deviceType}.{index}";
                        if (await db.HashExistsAsync(redisKey, map.EventCode))
                        {
                            string status = await db.HashGetAsync(redisKey, map.EventCode);

                            row.Add("status", status);
                        }
                        else
                        {
                            await db.HashSetAsync(redisKey, map.EventCode, bool.FalseString);

                            row.Add("status", bool.FalseString);
                        }

                        result.Add(row);
                    }
                }
                return(Ok(result));
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return(BadRequest(ex.Message));
            }
        }
Пример #19
0
        protected override Task AddRawIndex(IDatabaseAsync database, IIndexKey index, string rawKey)
        {
            var hashIndex = (HashIndexKey)index;

            return(database.HashSetAsync(Link.GetIndexKey(index), new[] { new HashEntry(hashIndex.HashKey, rawKey) }));
        }
Пример #20
0
        private static TupleList <string, Task> RunStackExchangeAsync(string prefix, IDatabaseAsync db)
        {
            var tasks = new TupleList <string, Func <Task> >()
            {
                { "DebugObjectAsync", () => db.DebugObjectAsync($"{prefix}DebugObjectAsync") },
                { "ExecuteAsync", () => db.ExecuteAsync("DDCUSTOM", "COMMAND") },
                { "GeoAddAsync", () => db.GeoAddAsync($"{prefix}GeoAddAsync", new GeoEntry(1.5, 2.5, "member")) },
                { "GeoDistanceAsync", () => db.GeoDistanceAsync($"{prefix}GeoDistanceAsync", "member1", "member2") },
                { "GeoHashAsync", () => db.GeoHashAsync($"{prefix}GeoHashAsync", "member") },
                { "GeoPositionAsync", () => db.GeoPositionAsync($"{prefix}GeoPositionAsync", "member") },
                { "GeoRadiusAsync", () => db.GeoRadiusAsync($"{prefix}GeoRadiusAsync", "member", 2.3) },
                { "GeoRemoveAsync", () => db.GeoRemoveAsync($"{prefix}GeoRemoveAsync", "member") },
                { "HashDecrementAsync", () => db.HashDecrementAsync($"{prefix}HashDecrementAsync", "hashfield", 4.5) },
                { "HashDeleteAsync", () => db.HashDeleteAsync($"{prefix}HashDeleteAsync", "hashfield") },
                { "HashExistsAsync", () => db.HashExistsAsync($"{prefix}HashExistsAsync", "hashfield") },
                { "HashGetAllAsync", () => db.HashGetAllAsync($"{prefix}HashGetAllAsync") },
                { "HashIncrementAsync", () => db.HashIncrementAsync($"{prefix}HashIncrementAsync", "hashfield", 1.5) },
                { "HashKeysAsync", () => db.HashKeysAsync($"{prefix}HashKeysAsync") },
                { "HashLengthAsync", () => db.HashLengthAsync($"{prefix}HashLengthAsync") },
                { "HashSetAsync", () => db.HashSetAsync($"{prefix}HashSetAsync", new HashEntry[] { new HashEntry("x", "y") }) },
                { "HashValuesAsync", () => db.HashValuesAsync($"{prefix}HashValuesAsync") },
                { "HyperLogLogAddAsync", () => db.HyperLogLogAddAsync($"{prefix}HyperLogLogAddAsync", "value") },
                { "HyperLogLogLengthAsync", () => db.HyperLogLogLengthAsync($"{prefix}HyperLogLogLengthAsync") },
                { "HyperLogLogMergeAsync", () => db.HyperLogLogMergeAsync($"{prefix}HyperLogLogMergeAsync", new RedisKey[] { "key1", "key2" }) },
                { "IdentifyEndpointAsync", () => db.IdentifyEndpointAsync() },
                { "KeyDeleteAsync", () => db.KeyDeleteAsync("key") },
                { "KeyDumpAsync", () => db.KeyDumpAsync("key") },
                { "KeyExistsAsync", () => db.KeyExistsAsync("key") },
                { "KeyExpireAsync", () => db.KeyExpireAsync("key", DateTime.Now) },
                // () => db.KeyMigrateAsync("key", ???)
                { "KeyMoveAsync", () => db.KeyMoveAsync("key", 1) },
                { "KeyPersistAsync", () => db.KeyPersistAsync("key") },
                { "KeyRandomAsync", () => db.KeyRandomAsync() },
                { "KeyRenameAsync", () => db.KeyRenameAsync("key1", "key2") },
                { "KeyRestoreAsync", () => db.KeyRestoreAsync("key", new byte[] { 0, 1, 2, 3, 4 }) },
                { "KeyTimeToLiveAsync", () => db.KeyTimeToLiveAsync("key") },
                { "KeyTypeAsync", () => db.KeyTypeAsync("key") },
                { "ListGetByIndexAsync", () => db.ListGetByIndexAsync("listkey", 0) },
                { "ListInsertAfterAsync", () => db.ListInsertAfterAsync("listkey", "value1", "value2") },
                { "ListInsertBeforeAsync", () => db.ListInsertBeforeAsync("listkey", "value1", "value2") },
                { "ListLeftPopAsync", () => db.ListLeftPopAsync("listkey") },
                { "ListLeftPushAsync", () => db.ListLeftPushAsync("listkey", new RedisValue[] { "value3", "value4" }) },
                { "ListLengthAsync", () => db.ListLengthAsync("listkey") },
                { "ListRangeAsync", () => db.ListRangeAsync("listkey") },
                { "ListRemoveAsync", () => db.ListRemoveAsync("listkey", "value3") },
                { "ListRightPopAsync", () => db.ListRightPopAsync("listkey") },
                { "ListRightPopLeftPushAsync", () => db.ListRightPopLeftPushAsync("listkey", "listkey2") },
                { "ListRightPushAsync", () => db.ListRightPushAsync("listkey", new RedisValue[] { "value5", "value6" }) },
                { "ListSetByIndexAsync", () => db.ListSetByIndexAsync("listkey", 0, "value7") },
                { "ListTrimAsync", () => db.ListTrimAsync("listkey", 0, 1) },
                { "LockExtendAsync", () => db.LockExtendAsync("listkey", "value7", new TimeSpan(0, 0, 10)) },
                { "LockQueryAsync", () => db.LockQueryAsync("listkey") },
                { "LockReleaseAsync", () => db.LockReleaseAsync("listkey", "value7") },
                { "LockTakeAsync", () => db.LockTakeAsync("listkey", "value8", new TimeSpan(0, 0, 10)) },
                { "PublishAsync", () => db.PublishAsync(new RedisChannel("channel", RedisChannel.PatternMode.Auto), "somemessage") },
                // { "ScriptEvaluateAsync", () => db.ScriptEvaluateAsync(}
                { "SetAddAsync", () => db.SetAddAsync("setkey", "value1") },
                { "SetCombineAndStoreAsync", () => db.SetCombineAndStoreAsync(SetOperation.Union, "setkey", new RedisKey[] { "value2" }) },
                { "SetCombineAsync", () => db.SetCombineAsync(SetOperation.Union, new RedisKey[] { "setkey1", "setkey2" }) },
                { "SetContainsAsync", () => db.SetContainsAsync("setkey", "value1") },
                { "SetLengthAsync", () => db.SetLengthAsync("setkey") },
                { "SetMembersAsync", () => db.SetMembersAsync("setkey") },
                { "SetMoveAsync", () => db.SetMoveAsync("setkey1", "setkey2", "value2") },
                { "SetPopAsync", () => db.SetPopAsync("setkey1") },
                { "SetRandomMemberAsync", () => db.SetRandomMemberAsync("setkey") },
                { "SetRandomMembersAsync", () => db.SetRandomMembersAsync("setkey", 2) },
                { "SetRemoveAsync", () => db.SetRemoveAsync("setkey", "value2") },
                { "SortAndStoreAsync", () => db.SortAndStoreAsync("setkey2", "setkey") },
                { "SortAsync", () => db.SortAsync("setkey") },
                { "SortedSetAddAsync", () => db.SortedSetAddAsync("ssetkey", new SortedSetEntry[] { new SortedSetEntry("value1", 1.5), new SortedSetEntry("value2", 2.5) }) },
                { "SortedSetCombineAndStoreAsync", () => db.SortedSetCombineAndStoreAsync(SetOperation.Union, "ssetkey1", "ssetkey2", "ssetkey3") },
                { "SortedSetDecrementAsync", () => db.SortedSetDecrementAsync("ssetkey", "value1", 1) },
                { "SortedSetIncrementAsync", () => db.SortedSetIncrementAsync("ssetkey", "value2", 1) },
                { "SortedSetLengthAsync", () => db.SortedSetLengthAsync("ssetkey") },
                { "SortedSetLengthByValueAsync", () => db.SortedSetLengthByValueAsync("ssetkey", "value1", "value2") },
                { "SortedSetRangeByRankAsync", () => db.SortedSetRangeByRankAsync("ssetkey") },
                { "SortedSetRangeByRankWithScoresAsync", () => db.SortedSetRangeByRankWithScoresAsync("ssetkey") },
                { "SortedSetRangeByScoreAsync", () => db.SortedSetRangeByScoreAsync("ssetkey") },
                { "SortedSetRangeByScoreWithScoresAsync", () => db.SortedSetRangeByScoreWithScoresAsync("ssetkey") },
                { "SortedSetRangeByValueAsync", () => db.SortedSetRangeByValueAsync("ssetkey") },
                { "SortedSetRankAsync", () => db.SortedSetRankAsync("ssetkey", "value1") },
                { "SortedSetRemoveAsync", () => db.SortedSetRemoveAsync("ssetkey", "value1") },
                { "SortedSetRemoveRangeByRankAsync", () => db.SortedSetRemoveRangeByRankAsync("ssetkey", 0, 1) },
                { "SortedSetRemoveRangeByScoreAsync", () => db.SortedSetRemoveRangeByScoreAsync("ssetkey", 0, 1) },
                { "SortedSetRemoveRangeByValueAsync", () => db.SortedSetRemoveRangeByValueAsync("ssetkey", "value1", "value2") },
                { "SortedSetScoreAsync", () => db.SortedSetScoreAsync("ssestkey", "value1") },
                { "StringAppendAsync", () => db.StringAppendAsync("ssetkey", "value1") },
                { "StringBitCountAsync", () => db.StringBitCountAsync("ssetkey") },
                { "StringBitOperationAsync", () => db.StringBitOperationAsync(Bitwise.And, "ssetkey1", new RedisKey[] { "ssetkey2", "ssetkey3" }) },
                { "StringBitPositionAsync", () => db.StringBitPositionAsync("ssetkey1", true) },
                { "StringDecrementAsync", () => db.StringDecrementAsync("key", 1.45) },
                { "StringGetAsync", () => db.StringGetAsync("key") },
                { "StringGetBitAsync", () => db.StringGetBitAsync("key", 3) },
                { "StringGetRangeAsync", () => db.StringGetRangeAsync("key", 0, 1) },
                { "StringGetSetAsync", () => db.StringGetSetAsync("key", "value") },
                { "StringGetWithExpiryAsync", () => db.StringGetWithExpiryAsync("key") },
                { "StringIncrementAsync", () => db.StringIncrementAsync("key", 1) },
                { "StringLengthAsync", () => db.StringLengthAsync("key") },
                { "StringSetAsync", () => db.StringSetAsync(new KeyValuePair <RedisKey, RedisValue>[] { new KeyValuePair <RedisKey, RedisValue>("key", "value") }) },
                { "StringSetBitAsync", () => db.StringSetBitAsync("key", 0, true) },
                { "StringSetRangeAsync", () => db.StringSetRangeAsync("key", 3, "value") },
            };

            var pending = new TupleList <string, Task>();

            foreach (var item in tasks)
            {
                try
                {
                    pending.Add(item.Item1, item.Item2());
                }
                catch (Exception e)
                {
                    while (e.InnerException != null)
                    {
                        e = e.InnerException;
                    }
                    Console.WriteLine($"{e.Message}");
                }
            }

            return(pending);
        }