Пример #1
0
        public void VerifyAccount(string account, int opcode, int channelId, string data, VerifyAccountCB cb)
        {
            uint   msgId      = MessageMapping.Query(typeof(LB_VerifyAccount));
            string timeoutKey = string.Format("{0}:{1}", msgId, account);

            if (m_VerifyAccountWatch.Exists(timeoutKey))
            {
                cb(account, false, "");
            }
            else
            {
                LB_VerifyAccount.Builder builder = LB_VerifyAccount.CreateBuilder();
                builder.Account   = account;
                builder.OpCode    = opcode;
                builder.ChannelId = channelId;
                builder.Data      = data;
                if (!channel_.Send(builder.Build()))
                {
                    cb(account, false, "");
                }
                else
                {
                    m_VerifyAccountWatch.Add(timeoutKey);
                    m_VerifyAccountTimeout.Set(timeoutKey, cb, () => cb.Invoke(account, false, ""));
                }
            }
        }
Пример #2
0
        private void HandleLoadGMPUser(uint msgId, string key, MyAction <DSLoadResult, string, IMessage> cb)
        {
            string   error    = null;
            IMessage data     = null;
            Type     dataType = MessageMapping.Query(msgId);

            try {
                uint             userTypeId      = MessageMapping.Query(typeof(DS_UserInfo));
                GMP_User.Builder dataUserBuilder = GMP_User.CreateBuilder();
                DbThreadManager.Instance.LoadActionQueue.QueueAction(() => {
                    DS_UserInfo dataUserBasic = DataLoadImpl.LoadSingleRow(typeof(DS_UserInfo), key) as DS_UserInfo;
                    if (dataUserBasic != null)
                    {
                        dataUserBuilder.SetUserGuid(dataUserBasic.Guid);
                        dataUserBuilder.SetUserBasic(dataUserBasic);
                    }
                    else
                    {
                        error = string.Format("GMServer Load from Database MISS: key:({0}), data({1})", key, dataType.Name);
                        cb(DSLoadResult.NotFound, error, null);
                        LogSys.Log(LOG_TYPE.INFO, error);
                        return;
                    }
                    data = dataUserBuilder.Build();
                    cb(DSLoadResult.Success, null, data);
                    LogSys.Log(LOG_TYPE.DEBUG, "GMServer Load from Database: key:({0}), data({1})", key, dataType.Name);
                });
            } catch (Exception e) {
                error = e.Message;
                cb(DSLoadResult.PostError, error, data);
                LogSys.Log(LOG_TYPE.ERROR, "GMServer Load from Database ERROR: key:{0}, data:{1}, error:{2},stacktrace:{3}",
                           key, dataType.Name, error, e.StackTrace);
                return;
            }
        }
Пример #3
0
        public void Load <T>(string key, LoadCallback <T> cb)
            where T : IMessage
        {
            uint dsMsgId = MessageMapping.Query(typeof(T));

            if (dsMsgId == uint.MaxValue)
            {
                cb(DSLoadResult.PrepError, string.Format("unknown data message: {0}", typeof(T).Name), default(T));
                return;
            }
            string timeoutKey = string.Format("{0}:{1}", dsMsgId, key);

            if (loadOpt_timeout_.Exists(timeoutKey))
            {
                cb(DSLoadResult.PrepError, "Load operation are too frequent", default(T));
            }
            else
            {
                LNReq_Load.Builder loadBuilder = LNReq_Load.CreateBuilder();
                loadBuilder.SetDsMsgId(dsMsgId);
                loadBuilder.SetKey(key);
                LNReq_Load loadData = loadBuilder.Build();
                if (!channel_.Send(loadData))
                {
                    cb(DSLoadResult.PrepError, "Create protobuf data error.", default(T));
                }
                else
                {
                    LoadCBBox cbbox      = new LoadCBBoxI <T>(cb);
                    string    timeoutTip = string.Format("DataStore load request timeout. MsgId:{0}, Key:{1}", dsMsgId, key);
                    loadOpt_timeout_.Set(timeoutKey, cbbox, () => cbbox.Invoke(DSLoadResult.TimeoutError, timeoutTip, null));
                }
            }
        }
Пример #4
0
    public async Task SendAzureSearchResultAsync(ITurnContext turnContext, CancellationToken cancellationToken,
                                                 MessageMapping messageMapping, string azureSearchResultJson)
    {
        Activity replyActivity = await CreateReplyFromAzureSearchMappingAsync(turnContext, messageMapping, azureSearchResultJson);

        await turnContext.SendActivityAsync(replyActivity);
    }
Пример #5
0
 internal void Init()
 {
     GMMessageHandlerDispatcher.Instance.RegisterLoadHandler(MessageMapping.Query(typeof(GMP_Account)), HandleLoadGMPAccount);
     GMMessageHandlerDispatcher.Instance.RegisterLoadHandler(MessageMapping.Query(typeof(GMP_User)), HandleLoadGMPUser);
     Start();
     LogSys.Log(LOG_TYPE.INFO, "DataOperator initialized");
 }
Пример #6
0
 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
     FileLocationMapping.Mapping(modelBuilder.Entity <FileLocation>());
     StickersMapping.Mapping(modelBuilder.Entity <Sticker>());
     MessageMapping.Mapping(modelBuilder.Entity <Message>());
     PermissionMaping.Mapping(modelBuilder.Entity <Permissions>());
     UserMaping.Mapping(modelBuilder.Entity <User>());
 }
Пример #7
0
        private void DoVerfifyAccountResult(BL_VerifyAccountResult msg, PBChannel channel, int src, uint seq)
        {
            uint   msgId      = MessageMapping.Query(typeof(LB_VerifyAccount));
            string timeoutKey = string.Format("{0}:{1}", msgId, msg.Account);

            m_VerifyAccountWatch.Remove(timeoutKey);
            VerifyAccountCB cb = m_VerifyAccountTimeout.Get(timeoutKey);

            if (cb != null)
            {
                cb(msg.Account, msg.Result, msg.AccountId);
                m_VerifyAccountTimeout.Remove(timeoutKey);
            }
        }
Пример #8
0
    private void SaveHandler(LNReq_Save msg, PBChannel channel, int handle, uint seq)
    {
        if (!Enable)
        {
            LogSys.Log(LOG_TYPE.ERROR, "Save a message while DataOperator is Disable");
            return;
        }
        var reply = NLRep_Save.CreateBuilder();

        reply.SetDsMsgId(msg.DsMsgId);
        reply.SetKey(msg.Key);
        reply.Result = NLRep_Save.Types.SaveResult.Success;
        try
        {
            byte[] data_bytes    = ByteString.Unsafe.GetBuffer(msg.DsBytes);
            int    calc_checksum = Crc32.Compute(data_bytes);
            if (msg.Checksum != calc_checksum)
            {
                throw new DataChecksumError(msg.Checksum, calc_checksum);
            }
            string dataTypeName = string.Empty;
            if (m_DSDMessages.TryGetValue(msg.DsMsgId, out dataTypeName))
            {
                DataCacheSystem.Instance.QueueAction(DataCacheSystem.Instance.DirectSave, msg.DsMsgId, msg.Key, data_bytes);
            }
            else
            {
                dataTypeName = MessageMapping.Query(msg.DsMsgId).Name;
                if (dataTypeName.StartsWith("DSD_"))
                {
                    //直接写入数据库
                    m_DSDMessages.AddOrUpdate(msg.DsMsgId, dataTypeName, (key, oldValue) => dataTypeName);
                    DataCacheSystem.Instance.QueueAction(DataCacheSystem.Instance.DirectSave, msg.DsMsgId, msg.Key, data_bytes);
                }
                else
                {
                    //写入数据缓存
                    DataCacheSystem.Instance.SaveActionQueue.QueueAction(DataCacheSystem.Instance.Save, msg.DsMsgId, msg.Key, data_bytes);
                }
            }
        }
        catch (Exception e)
        {
            reply.Result = NLRep_Save.Types.SaveResult.Error;
            reply.SetError(e.Message);
            LogSys.Log(LOG_TYPE.ERROR, "Save data ERROR: msgId:({0}) seq:({1}) error:({2}) detail:{3}", msg.DsMsgId, seq, e.Message, e.StackTrace);
        }
        channel.Send(reply.Build());
    }
Пример #9
0
    public static async Task <string> SaveTwilioMapping(
        [ActivityTrigger] string orchestrationId,
        [Table(MessageMapping.TableName)] IAsyncCollector <MessageMapping> table)
    {
        var mapping = new MessageMapping()
        {
            PartitionKey    = "Sms",
            RowKey          = Guid.NewGuid().ToString("N"),
            OrchestrationId = orchestrationId
        };

        await table.AddAsync(mapping);

        return(mapping.RowKey);
    }
        public static IServiceCollection RegisterNotificationHandler <TNotification, THandler>(this IServiceCollection services)
            where THandler : INotificationHandler <TNotification>
            where TNotification : INotification
        {
            Type messageType = typeof(Message <TNotification>);

            MessageMapping mapping = new MessageMapping(messageType,
                                                        typeof(TNotification),
                                                        typeof(THandler),
                                                        typeof(INotificationHandler <TNotification>),
                                                        typeof(NotificationHandlerWrapper <TNotification>));

            MainConfiguration.AddMapping(mapping);
            services.TryAddTransient(mapping.HandlerInterfaceType, mapping.HandlerType);

            return(services);
        }
Пример #11
0
        public void Save(string key, IMessage data, SaveCallback cb, bool isForce)
        {
            Constraints.MaxSize(data);
            string     error    = null;
            LNReq_Save saveData = null;
            uint       dsMsgId  = MessageMapping.Query(data.GetType());

            if (dsMsgId == uint.MaxValue)
            {
                error = string.Format("unknown data message: " + data.GetType().Name);
            }
            string timeoutKey = string.Format("{0}:{1}", dsMsgId, key);

            if (!isForce && saveOpt_timeout_.Exists(timeoutKey))
            {
                error = "Save operation are too frequent";
                cb(DSSaveResult.PrepError, error);
                return;
            }
            try {
                byte[]             bytes       = data.ToByteArray();
                LNReq_Save.Builder saveBuilder = LNReq_Save.CreateBuilder();
                saveBuilder.SetDsMsgId(dsMsgId);
                saveBuilder.SetKey(key);
                saveBuilder.SetDsBytes(ByteString.Unsafe.FromBytes(bytes));
                saveBuilder.SetChecksum(Crc32.Compute(bytes));
                saveData = saveBuilder.Build();
            } catch (Exception e) {
                error = e.Message;
            }
            if (null != error)
            {
                cb(DSSaveResult.PrepError, error);
                return;
            }
            if (!channel_.Send(saveData))
            {
                cb(DSSaveResult.PrepError, "unknown");
            }
            else
            {
                //添加到超时验证
                string timeoutTip = string.Format("DataStore save request timeout. MsgId:{0}, Key:{1}", dsMsgId, key);
                saveOpt_timeout_.Set(timeoutKey, cb, () => cb(DSSaveResult.TimeoutError, timeoutTip));
            }
        }
        public static IServiceCollection RegisterCommandHandler <TCommand, THandler, TResult>(this IServiceCollection services)
            where THandler : ICommandHandler <TCommand, TResult>
            where TCommand : ICommand <TResult>
        {
            Type messageType = typeof(Message <TCommand>);

            MessageMapping mapping = new MessageMapping(messageType,
                                                        typeof(TCommand),
                                                        typeof(TResult),
                                                        typeof(THandler),
                                                        typeof(ICommandHandler <TCommand, TResult>),
                                                        typeof(CommandHandlerWrapper <TCommand, TResult>));

            MainConfiguration.AddMapping(mapping);
            services.TryAddTransient(mapping.HandlerInterfaceType, mapping.HandlerType);

            return(services);
        }
Пример #13
0
        /// <inheritdoc />
        public async Task <Message[]> GetRecentMessagesAsync()
        {
            var groupName = _settingsProvider.GetGroupName();

            if (string.IsNullOrWhiteSpace(groupName))
            {
                throw new InvalidOperationException("Rocket.Chat group chat name cannot be empty.");
            }

            var messageCount = _settingsProvider.GetRequestedMessageCount();

            if (messageCount == 0)
            {
                throw new InvalidOperationException("The number of chat messages to request cannot be less than 1.");
            }

            var recentMessagesDto = await GetNewMessagesAsync(groupName, messageCount).ConfigureAwait(false);

            var messages = recentMessagesDto.Select(dto => MessageMapping.ToMessage(dto)).ToArray();

            return(messages);
        }
Пример #14
0
    public static async Task <HttpResponseMessage> TwilioHandler(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "TwilioHandler/{id}")]
        HttpRequestMessage req,
        [OrchestrationClient] DurableOrchestrationClient client,
        [Table(MessageMapping.TableName, "Sms", "{id}")] MessageMapping mapping,
        ILogger log)
    {
        var content = await req.Content.ReadAsStringAsync();

        var formBody = ParseForm(content);
        var status   = formBody["SmsStatus"];

        if (status == "delivered" || status == "failed")
        {
            await client.RaiseEventAsync(mapping.OrchestrationId, "TwilioCallback", status);
        }

        var response = req.CreateResponse(HttpStatusCode.OK);

        response.Content = new StringContent("OK", Encoding.UTF8, "text/xml");
        return(response);
    }
Пример #15
0
        private Tuple <string, LNReq_Save> BuildSaveRequestMsg(IMessage data)
        {
            uint id = MessageMapping.Query(data.GetType());

            if (id == uint.MaxValue)
            {
                return(Tuple.Create("unknown data message: " + data.GetType().Name, default(LNReq_Save)));
            }
            try
            {
                byte[] bytes = data.ToByteArray();
                return(Tuple.Create(
                           default(string),
                           LNReq_Save.CreateBuilder()
                           .SetDsMsgId(id)
                           .SetDsBytes(ByteString.Unsafe.FromBytes(bytes))
                           .SetChecksum(Crc32.Compute(bytes))
                           .Build()));
            }
            catch (Exception e)
            {
                return(Tuple.Create(e.Message, default(LNReq_Save)));
            }
        }
Пример #16
0
    private async Task <Activity> CreateReplyFromAzureSearchMappingAsync(ITurnContext turnContext, MessageMapping messageMapping, string azureSearchResultJson)
    {
        try
        {
            // Parse Json into AzureSearchResult structure
            JObject azureSearchResult = JObject.Parse(azureSearchResultJson);

            // select all returned values of the AzureSearchResult
            JArray searchResultArray = (JArray)azureSearchResult.SelectToken("value");

            var reply = turnContext.Activity.CreateReply();

            // Send default message, if there are no results
            if (searchResultArray?.Count == 0)
            {
                reply = await CreateMessageFromDialogStructureMessageAsync(turnContext, _dialogModel.DefaultMessage);

                return(reply);
            }

            reply.Attachments      = new List <Attachment>();
            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            reply.Text             = messageMapping.Text;

            // Go through all search results
            foreach (JObject searchResult in searchResultArray.Children <JObject>())
            {
                // Create Image List
                var imageList = new List <CardImage>();

                // Get the value for the imageUrlPlaceholder from the mapping
                var imageUrlPlaceholder = messageMapping.Card.ImageUrl;

                // If the value exists, replace it with the value from the AzureSearchResult
                if (!String.IsNullOrEmpty(imageUrlPlaceholder))
                {
                    // Replace all occurences of searchResult properties with their respective values
                    var imageUrl = MapSearchResultsToString(imageUrlPlaceholder, searchResult);

                    // Add the image to the list
                    imageList.Add(
                        new CardImage {
                        Url = imageUrl
                    }
                        );
                }

                // Create Button List
                var buttonList = new List <CardAction>();

                if (messageMapping.Card.Options != null)
                {
                    foreach (var button in messageMapping.Card.Options)
                    {
                        buttonList.Add(new CardAction(
                                           Microsoft.Bot.Schema.ActionTypes.ImBack,
                                           title: button,
                                           value: button
                                           ));
                    }
                }


                var card = new HeroCard
                {
                    Images   = imageList,
                    Text     = MapSearchResultsToString(messageMapping.Card.Text, searchResult),
                    Title    = MapSearchResultsToString(messageMapping.Card.Title, searchResult),
                    Subtitle = MapSearchResultsToString(messageMapping.Card.Subtitle, searchResult),
                    Buttons  = buttonList
                };

                // Add the card to our reply.
                reply.Attachments.Add(card.ToAttachment());
            }

            return(reply);
        }
        catch (Exception e)
        {
            throw new Exception("[DialogMessageHandler] Error while mapping AzureSearchResult to Message format.", e);
        }
    }
Пример #17
0
        ///==============================================================================================
        /// 只能在本线程调用的方法。
        ///==============================================================================================
        private void HandleLoadGMPAccount(uint msgId, string key, MyAction <DSLoadResult, string, IMessage> cb)
        {
            string   error    = null;
            IMessage data     = null;
            Type     dataType = MessageMapping.Query(msgId);

            try {
                DbThreadManager.Instance.LoadActionQueue.QueueAction(() => {
                    GMP_Account.Builder dataAccountBuilder = GMP_Account.CreateBuilder();
                    DS_Account dataAccountBasic            = DataLoadImpl.LoadSingleRow(typeof(DS_Account), key) as DS_Account;
                    if (dataAccountBasic != null)
                    {
                        dataAccountBuilder.SetAccount(dataAccountBasic.Account);
                        dataAccountBuilder.SetAccountBasic(dataAccountBasic);
                    }
                    else
                    {
                        error = string.Format("GMServer Load from Database MISS: key:({0}), data({1})", key, dataType.Name);
                        cb(DSLoadResult.NotFound, error, null);
                        LogSys.Log(LOG_TYPE.INFO, error);
                        return;
                    }
                    List <DS_UserInfo> dataUserList = new List <DS_UserInfo>();
                    if (dataAccountBasic.UserGuid1 > 0)
                    {
                        DS_UserInfo dataUser = DataLoadImpl.LoadSingleRow(typeof(DS_UserInfo), dataAccountBasic.UserGuid1.ToString()) as DS_UserInfo;
                        if (dataUser != null)
                        {
                            dataUserList.Add(dataUser);
                        }
                    }
                    if (dataAccountBasic.UserGuid2 > 0)
                    {
                        DS_UserInfo dataUser = DataLoadImpl.LoadSingleRow(typeof(DS_UserInfo), dataAccountBasic.UserGuid2.ToString()) as DS_UserInfo;
                        if (dataUser != null)
                        {
                            dataUserList.Add(dataUser);
                        }
                    }
                    if (dataAccountBasic.UserGuid3 > 0)
                    {
                        DS_UserInfo dataUser = DataLoadImpl.LoadSingleRow(typeof(DS_UserInfo), dataAccountBasic.UserGuid3.ToString()) as DS_UserInfo;
                        if (dataUser != null)
                        {
                            dataUserList.Add(dataUser);
                        }
                    }
                    foreach (var dataUser in dataUserList)
                    {
                        dataAccountBuilder.UserListList.Add(dataUser as DS_UserInfo);
                    }
                    data = dataAccountBuilder.Build();
                    cb(DSLoadResult.Success, null, data);
                    LogSys.Log(LOG_TYPE.DEBUG, "GMServer Load from Database: key:({0}), data({1})", key, dataType.Name);
                });
            } catch (Exception e) {
                error = e.Message;
                cb(DSLoadResult.PostError, error, data);
                LogSys.Log(LOG_TYPE.ERROR, "GMServer Load from Database ERROR: key:({0}), data({1}), error({2})", key, dataType.Name, error);
                return;
            }
        }