//调用委托
        private async Task <AmpMessage> ProcessScheduleAsync(AmpMessage req)
        {
            ScheduleTaskReq request = null;

            if (req.Data == null)
            {
                request = new ScheduleTaskReq();
            }
            else
            {
                request = ScheduleTaskReq.Parser.ParseFrom(req.Data);
            }

            req.FriendlyServiceName = "TaskProducerService.Schedule";

            var result = await ScheduleAsync(request);

            var response = AmpMessage.CreateResponseMessage(req.ServiceId, req.MessageId);

            response.FriendlyServiceName = "TaskProducerService.Schedule";
            response.Code = result.Code;
            if (result.Data != null)
            {
                response.Data = result.Data.ToByteArray();
            }
            return(response);
        }
示例#2
0
        //调用委托
        private async Task <AmpMessage> ProcessSayHelloAgainAsync(AmpMessage req)
        {
            HelloReq request = null;

            if (req.Data == null)
            {
                request = new HelloReq();
            }
            else
            {
                request = HelloReq.Parser.ParseFrom(req.Data);
            }

            req.FriendlyServiceName = "Greeter.SayHelloAgain";

            var result = await SayHelloAgainAsync(request);

            var response = AmpMessage.CreateResponseMessage(req.ServiceId, req.MessageId);

            response.FriendlyServiceName = "Greeter.SayHelloAgain";
            response.Code = result.Code;
            if (result.Data != null)
            {
                response.Data = result.Data.ToByteArray();
            }
            return(response);
        }
示例#3
0
        private async Task <AmpMessage> GetUsersAsync(IServiceProvider serviceProvider, AmpMessage req)
        {
            var rsp     = AmpMessage.CreateResponseMessage(req.ServiceId, req.MessageId);
            var message = Encoding.UTF8.GetString(req.Data);
            var logger  = serviceProvider.GetRequiredService <ILoggerFactory>().CreateLogger <UserService>();

            logger.LogInformation($"ServiceId: {req.ServiceId}, MessageId: {req.MessageId}, Data: {message}");

            var userManager = serviceProvider.GetRequiredService <UserManager <User> >();
            var options     = serviceProvider.GetRequiredService <AdminOptions>();

            if (!options.AllowAnonymousUserQuery)
            {
                return(rsp);
            }

            var ids   = JsonConvert.DeserializeObject <Guid[]>(message);
            var users = await userManager.Users.Where(u => ids.Contains(u.Id)).OrderByDescending(u => u.CreationTime)
                        .Select(u => new
            {
                u.Id,
                Name = u.FirstName + u.LastName,
                u.Title,
                u.Email,
                Mobile = u.PhoneNumber,
                u.OfficePhone,
                u.Group,
                u.Level,
                u.UserName,
                u.CreationTime
            }).ToListAsync();

            rsp.Data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(users));
            return(rsp);
        }
示例#4
0
        /// <summary>
        /// 处理消息请求
        /// </summary>
        /// <param name="req">请求的消息</param>
        /// <returns>返回消息</returns>
        public override async Task <AmpMessage> ProcessAsync(AmpMessage req)
        {
            AmpMessage rsp;
            var        serviceProvider = _serviceProvider.CreateScope().ServiceProvider;

            switch (req.MessageId)
            {
            // 查询
            case 0:
            {
                rsp = await SearchUsersAsync(serviceProvider, req);

                break;
            }

            case 1:
            {
                rsp = await GetUsersAsync(serviceProvider, req);

                break;
            }

            default:
            {
                rsp = AmpMessage.CreateResponseMessage(req.ServiceId, req.MessageId);
                break;
            }
            }

            return(rsp);
        }
示例#5
0
        //调用委托
        private async Task <AmpMessage> ProcessRegisterAsync(AmpMessage req)
        {
            RegisterReq request = null;

            if (req.Data == null)
            {
                request = new RegisterReq();
            }
            else
            {
                request = RegisterReq.Parser.ParseFrom(req.Data);
            }

            req.FriendlyServiceName = "UserService.Register";

            var result = await RegisterAsync(request);

            var response = AmpMessage.CreateResponseMessage(req.ServiceId, req.MessageId);

            response.FriendlyServiceName = "UserService.Register";
            response.Code = result.Code;
            if (result.Data != null)
            {
                response.Data = result.Data.ToByteArray();
            }
            return(response);
        }
        //调用委托
        private async Task <AmpMessage> ProcessGetAPaperStaAsync(AmpMessage req)
        {
            GetAPaperStaDetailReq request = null;

            if (req.Data == null)
            {
                request = new GetAPaperStaDetailReq();
            }
            else
            {
                request = GetAPaperStaDetailReq.Parser.ParseFrom(req.Data);
            }

            req.FriendlyServiceName = "APaperService.GetAPaperSta";

            var result = await GetAPaperStaAsync(request);

            var response = AmpMessage.CreateResponseMessage(req.ServiceId, req.MessageId);

            response.FriendlyServiceName = "APaperService.GetAPaperSta";
            response.Code = result.Code;
            if (result.Data != null)
            {
                response.Data = result.Data.ToByteArray();
            }
            return(response);
        }
示例#7
0
        //调用委托
        private async Task <AmpMessage> ProcessExcuteAsync(AmpMessage req)
        {
            CommonTaskReq request = null;

            if (req.Data == null)
            {
                request = new CommonTaskReq();
            }
            else
            {
                request = CommonTaskReq.Parser.ParseFrom(req.Data);
            }

            req.FriendlyServiceName = "TaskConsumerService.Excute";

            var result = await ExcuteAsync(request);

            var response = AmpMessage.CreateResponseMessage(req.ServiceId, req.MessageId);

            response.FriendlyServiceName = "TaskConsumerService.Excute";
            response.Code = result.Code;
            if (result.Data != null)
            {
                response.Data = result.Data.ToByteArray();
            }
            return(response);
        }
        //调用委托
        private async Task <AmpMessage> ProcessQueryQPaperListAsync(AmpMessage req)
        {
            QueryQPaperReq request = null;

            if (req.Data == null)
            {
                request = new QueryQPaperReq();
            }
            else
            {
                request = QueryQPaperReq.Parser.ParseFrom(req.Data);
            }

            req.FriendlyServiceName = "QPaperInnerService.QueryQPaperList";

            var result = await QueryQPaperListAsync(request);

            var response = AmpMessage.CreateResponseMessage(req.ServiceId, req.MessageId);

            response.FriendlyServiceName = "QPaperInnerService.QueryQPaperList";
            response.Code = result.Code;
            if (result.Data != null)
            {
                response.Data = result.Data.ToByteArray();
            }
            return(response);
        }
示例#9
0
        /// <summary>
        /// 处理消息请求
        /// </summary>
        /// <param name="req">请求的消息</param>
        /// <returns>返回消息</returns>
        public override Task <AmpMessage> ProcessAsync(AmpMessage req)
        {
            var rsp = AmpMessage.CreateResponseMessage(req.ServiceId, req.MessageId);

            var name = Encoding.UTF8.GetString(req.Data);

            rsp.Data = Encoding.UTF8.GetBytes(string.Format("Hello {0}!", name));
            return(Task.FromResult(rsp));
        }
示例#10
0
//调用委托
        private async Task ReceiveSaveAsync(IRpcContext <AmpMessage> context, AmpMessage req)
        {
            var request = AccountReq.Parser.ParseFrom(req.Data);
            var data    = await SaveAsync(request);

            var response = AmpMessage.CreateResponseMessage(req.ServiceId, req.MessageId);

            response.Sequence = req.Sequence;
            response.Data     = data.ToByteArray();
            await context.SendAsync(response);
        }
示例#11
0
        private void TimeOutCallBack(string id)
        {
            if (this._resultDictionary.TryRemove(id, out var task))
            {
                var message = AmpMessage.CreateResponseMessage(id);
                message.Code = RpcErrorCodes.CODE_TIMEOUT;
                if (!task.TrySetResult(message))
                {
                    this._logger.LogWarning("set timeout result fail,maybe task is completed,message {0}", id);
                }

                this._logger.LogWarning("message {0}, timeout", id);
            }
        }
示例#12
0
//调用委托
        private async Task <AmpMessage> ProcessAddAsync(AmpMessage req)
        {
            AddReq request = null;

            if (req.Data == null)
            {
                request = new AddReq();
            }
            else
            {
                request = AddReq.Parser.ParseFrom(req.Data);
            }
            var data = await AddAsync(request);

            var response = AmpMessage.CreateResponseMessage(req.ServiceId, req.MessageId);

            response.Data = data.ToByteArray();
            return(response);
        }
示例#13
0
        private void ErrorCallBack(string id)
        {
            if (!this._resultDictionary.ContainsKey(id))
            {
                return;
            }

            if (this._resultDictionary.TryRemove(id, out var task))
            {
                var message = AmpMessage.CreateResponseMessage(id);
                message.Code = RpcErrorCodes.CODE_INTERNAL_ERROR;
                if (!task.TrySetResult(message))
                {
                    this._logger.LogWarning("set error result fail,maybe task is completed");
                }

                this._logger.LogWarning("message {0}, error", id);
            }
        }
示例#14
0
        public override async Task <AmpMessage> ProcessAsync(AmpMessage req)
        {
            var rsp     = AmpMessage.CreateResponseMessage(req.ServiceId, req.MessageId);
            var message = Encoding.UTF8.GetString(req.Data);
            var logger  = _serviceProvider.GetRequiredService <ILoggerFactory>().CreateLogger <UserService>();

            logger.LogInformation($"Message: {message}");

            var userManager = _serviceProvider.GetRequiredService <UserManager <User> >();
            var dbContext   = _serviceProvider.GetRequiredService <IDbContext>();

            var dto = JsonConvert.DeserializeObject <PermissionCheckDto>(message);
            var key = $"{dto.UserId}_{dto.Permission}";

            var isGrant =
                await dbContext.UserPermissionKeys.AnyAsync(up => up.Permission == key);

            rsp.Data = Encoding.UTF8.GetBytes(isGrant ? "true" : "false");
            return(rsp);
        }
示例#15
0
//调用委托
        private async Task <AmpMessage> ProcessFindByAccountAsync(AmpMessage req)
        {
            FindAccountReq request = null;

            if (req.Data == null)
            {
                request = new FindAccountReq();
            }
            else
            {
                request = FindAccountReq.Parser.ParseFrom(req.Data);
            }
            var data = await FindByAccountAsync(request);

            var response = AmpMessage.CreateResponseMessage(req.ServiceId, req.MessageId);

            response.Sequence = req.Sequence;
            response.Data     = data.ToByteArray();
            return(response);
        }
示例#16
0
        //调用委托
        private async Task <AmpMessage> ProcessEchoAsync(AmpMessage req)
        {
            BenchmarkMessage request = null;

            if (req.Data == null)
            {
                request = new BenchmarkMessage();
            }
            else
            {
                request = BenchmarkMessage.Parser.ParseFrom(req.Data);
            }
            var data = await EchoAsync(request);

            var response = AmpMessage.CreateResponseMessage(req.ServiceId, req.MessageId);

            response.Sequence = req.Sequence;
            response.Data     = data.ToByteArray();
            return(response);
        }
示例#17
0
        public Task <AmpMessage> AddAsync(AmpMessage reqMsg)
        {
            var rsp = AmpMessage.CreateResponseMessage(reqMsg.ServiceId, reqMsg.MessageId);



            AddReq req = AddReq.Parser.ParseFrom(reqMsg.Data);

            if (req != null)
            {
                var res = new AddRes();
                res.C    = req.A + req.B;
                rsp.Data = res.ToByteArray();
                Logger.Debug("{0}${1}${2}  ,code=0  ,req={3}  ,res={4}", reqMsg.ServiceId, reqMsg.MessageId, reqMsg.Sequence, req.ToString(), res.ToString());
            }
            else
            {
                rsp.Code = ErrorCodes.CODE_INTERNAL_ERROR;
                Logger.Error("{0}${1}${2}  ,code={3}  ,req={4}  ,res=null", reqMsg.ServiceId, reqMsg.MessageId, reqMsg.Sequence, rsp.Code, req.ToString());
            }
            return(Task.FromResult(rsp));
        }
示例#18
0
        public Task <AmpMessage> AddAsync(AmpMessage reqMsg)
        {
            var rsp = AmpMessage.CreateResponseMessage(reqMsg.ServiceId, reqMsg.MessageId);

            AddReq req = MessagePackSerializer.Deserialize <AddReq>(reqMsg.Data);

            if (req != null)
            {
                var res = new AddRes();
                res.C = req.A + req.B;

                rsp.Data = MessagePackSerializer.Serialize(res);

                Logger.Debug("{0}${1}${2}  ,code=0  ,req={3}  ,res={4}", reqMsg.ServiceId, reqMsg.MessageId, reqMsg.Sequence, MessagePackSerializer.ToJson(req), MessagePackSerializer.ToJson(res));
            }
            else
            {
                rsp.Code = ErrorCodes.CODE_INTERNAL_ERROR;
                Logger.Error("{0}${1}${2}  ,code={3}  ,req={4}  ,res=null", reqMsg.ServiceId, reqMsg.MessageId, reqMsg.Sequence, rsp.Code, MessagePackSerializer.ToJson(req));
            }
            return(Task.FromResult(rsp));
        }
示例#19
0
        public Task <AmpMessage> AddAsync(AmpMessage reqMsg)
        {
            var rsp = AmpMessage.CreateResponseMessage(reqMsg.ServiceId, reqMsg.MessageId);


            var    json = Encoding.UTF8.GetString(reqMsg.Data);
            AddReq req  = JSON.Deserialize <AddReq>(json);

            if (req != null)
            {
                var res = new AddRes();
                res.C = req.A + req.B;
                var resJson = JSON.Serialize(res);
                rsp.Data = Encoding.UTF8.GetBytes(resJson);
                Logger.Debug("{0}${1}${2}  ,code=0  ,req={3}  ,res={4}", reqMsg.ServiceId, reqMsg.MessageId, reqMsg.Sequence, json, resJson);
            }
            else
            {
                rsp.Code = ErrorCodes.CODE_INTERNAL_ERROR;
                Logger.Error("{0}${1}${2}  ,code={3}  ,req={4}  ,res=null", reqMsg.ServiceId, reqMsg.MessageId, reqMsg.Sequence, rsp.Code, json);
            }
            return(Task.FromResult(rsp));
        }
示例#20
0
        private async Task <AmpMessage> SearchUsersAsync(IServiceProvider serviceProvider, AmpMessage req)
        {
            var rsp     = AmpMessage.CreateResponseMessage(req.ServiceId, req.MessageId);
            var message = Encoding.UTF8.GetString(req.Data);
            var logger  = serviceProvider.GetRequiredService <ILoggerFactory>().CreateLogger <UserService>();

            logger.LogInformation($"ServiceId: {req.ServiceId}, MessageId: {req.MessageId}, Data: {message}");
            var dbContext = serviceProvider.GetRequiredService <IDbContext>();
            var options   = serviceProvider.GetRequiredService <AdminOptions>();

            if (!options.AllowAnonymousUserQuery)
            {
                return(rsp);
            }

            var dto = JsonConvert.DeserializeObject <PagedQueryUserDto>(message);

            Expression <Func <User, bool> > where = null;
            dto.Q     = string.IsNullOrWhiteSpace(dto.Q) ? null : dto.Q.Trim();
            dto.Group = string.IsNullOrWhiteSpace(dto.Group) ? null : dto.Group.Trim();
            if (!string.IsNullOrWhiteSpace(dto.Q))
            {
                where = u =>
                        (u.FirstName + u.LastName).Contains(dto.Q) ||
                        (u.LastName + u.FirstName).Contains(dto.Q) || u.Email.Contains(dto.Q) ||
                        u.PhoneNumber.Contains(dto.Q);
            }

            if (!string.IsNullOrWhiteSpace(dto.Group))
            {
                if (where == null)
                {
                    where = u => u.Group == dto.Group.Trim();
                }
                else
                {
                    where = where.AndAlso(u => u.Group == dto.Group.Trim());
                }
            }

            if (dto.Titles != null && dto.Titles.Length > 0)
            {
                if (where == null)
                {
                    where = u => dto.Titles.Contains(u.Title);
                }
                else
                {
                    where = where.AndAlso(u => dto.Titles.Contains(u.Title));
                }
            }

            if (dto.Roles == null || dto.Roles.Length == 0)
            {
                var output = await dbContext.Users.OrderByDescending(u => u.CreationTime).PagedQueryAsync(dto, where);

                var result = new PagedQueryResult
                {
                    Page   = output.Page,
                    Size   = output.Size,
                    Total  = output.Total,
                    Result = output.Result.Select(u => new
                    {
                        u.Id,
                        Name = String.CompareOrdinal(u.LastName, u.FirstName),
                        u.Title,
                        u.Email,
                        Mobile = u.PhoneNumber,
                        u.OfficePhone,
                        u.Group,
                        u.Level,
                        u.UserName,
                        u.IsDeleted
                    }).ToList()
                };
                rsp.Data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(result));
            }
            else
            {
                var roleIds = await dbContext.Roles.Where(r => dto.Roles.Contains(r.Name)).Select(r => r.Id)
                              .ToListAsync();

                var result = await dbContext.Users.OrderByDescending(u => u.CreationTime).Join(dbContext.UserRoles,
                                                                                               u => u.Id, ur => ur.UserId, (u, ur) =>
                                                                                               new TmpUser
                {
                    Id           = u.Id,
                    Name         = string.Concat(u.LastName, u.FirstName),
                    Title        = u.Title,
                    Email        = u.Email,
                    Mobile       = u.PhoneNumber,
                    OfficePhone  = u.OfficePhone,
                    Group        = u.Group,
                    Level        = u.Level,
                    RoleId       = ur.RoleId,
                    UserName     = u.UserName,
                    CreationTime = u.CreationTime,
                    IsDeleted    = u.IsDeleted
                }).Where(t =>
                         roleIds.Contains(t.RoleId) &&
                         (string.IsNullOrWhiteSpace(dto.Q) || t.Name.Contains(dto.Q) || t.Email.Contains(dto.Q) ||
                          t.Mobile.Contains(dto.Q)) &&
                         (string.IsNullOrWhiteSpace(dto.Group) || t.Group == dto.Group) &&
                         (dto.Titles == null || dto.Titles.Length == 0 || dto.Titles.Contains(t.Title))).Distinct()
                             .PagedQueryAsync(dto);

                var output = new PagedQueryResult
                {
                    Total  = result.Total,
                    Size   = result.Size,
                    Page   = result.Page,
                    Result = result.Result.Select(r => new
                    {
                        r.Id,
                        r.Name,
                        r.Title,
                        r.Email,
                        r.Mobile,
                        r.OfficePhone,
                        r.Group,
                        r.Level,
                        r.UserName,
                        r.IsDeleted
                    })
                };
                rsp.Data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(output));
            }

            return(rsp);
        }
示例#21
0
        /// <summary>
        ///  Remote Call
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        protected override async Task <AmpMessage> ProcessAsync(ISocketContext <AmpMessage> context, AmpMessage req)
        {
            var resMsg = AmpMessage.CreateResponseMessage(req.ServiceId, req.MessageId);

            resMsg.Sequence  = req.Sequence;
            resMsg.CodecType = (CodecType)Enum.ToObject(typeof(CodecType), Serializer.CodecType);

            string key = $"{req.ServiceId}${req.MessageId}";

            if (METHOD_CACHE.TryGetValue(key, out var m))
            {
                var parameterInfos = m.GetParameters();
                if (parameterInfos.Length < 1 || parameterInfos.Length > 2)
                {
                    new RpcException("rpc method parameters count error,must be [1,2]");
                }

                object arg1         = Serializer.Deserialize(req.Data, parameterInfos[0].ParameterType);
                bool   withResponse = req.InvokeMessageType == InvokeMessageType.InvokeWithoutResponse;

                RpcResult <object> retVal;
                if (parameterInfos.Length == 2)
                {
                    var newArgs = new object[2];
                    newArgs[0] = arg1;

                    if (parameterInfos[1].ParameterType == typeof(bool))
                    {
                        newArgs[1] = withResponse;
                    }
                    else
                    {
                        newArgs[1] = parameterInfos[1].HasDefaultValue ? parameterInfos[1].DefaultValue : 3000;
                    }

                    retVal = await InvokeInner(m, context, newArgs);
                }
                else
                {
                    retVal = await InvokeInner(m, context, arg1);
                }

                if (retVal == null)
                {
                    resMsg.Code = RpcErrorCodes.CODE_INTERNAL_ERROR;
                    return(resMsg);
                }

                resMsg.Code = retVal.Code;
                if (retVal.Data != null)
                {
                    resMsg.Data = Serializer.Serialize(retVal.Data);
                }
            }
            else
            {
                resMsg.Code = RpcErrorCodes.CODE_SERVICE_NOT_FOUND;
            }

            return(resMsg);
        }
示例#22
0
        /// <summary>
        ///  Remote Call
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        protected override async Task <AmpMessage> ProcessAsync(AmpMessage req)
        {
            var resMsg = AmpMessage.CreateResponseMessage(req.ServiceId, req.MessageId);

            resMsg.Sequence = req.Sequence;
            string key = $"{req.ServiceId}${req.MessageId}";

            if (METHOD_CACHE.TryGetValue(key, out var m))
            {
                var parameterInfos = m.GetParameters();
                if (parameterInfos.Length < 1 || parameterInfos.Length > 2)
                {
                    new RpcException("rpc method parameters count error,must be [1,2]");
                }

                object arg1         = Serializer.Deserialize(req.Data, parameterInfos[0].ParameterType);
                bool   withResponse = req.InvokeMessageType == InvokeMessageType.InvokeWithoutResponse;

                object retVal;
                if (parameterInfos.Length == 2)
                {
                    var newArgs = new object[2];
                    newArgs[0] = arg1;

                    if (parameterInfos[1].ParameterType == typeof(bool))
                    {
                        newArgs[1] = withResponse;
                    }
                    else
                    {
                        newArgs[1] = parameterInfos[1].HasDefaultValue ? parameterInfos[1].DefaultValue : 3000;
                    }
                    retVal = m.Invoke(this, newArgs);
                }
                else
                {
                    retVal = m.Invoke(this, new[] { arg1 });
                }

                var retValType = retVal.GetType();
                if (retValType == typeof(Task))
                {
                    return(resMsg);
                }

                var tType = retValType.GenericTypeArguments[0];
                if (tType == typeof(RpcResult))
                {
                    Task <RpcResult> retTask = retVal as Task <RpcResult>;
                    var result = await retTask;
                    resMsg.Code = result.Code;
                }
                else if (tType.IsGenericType)
                {
                    Task retTask = retVal as Task;
                    await retTask.AnyContext();

                    var resultProp = retValType.GetProperty("Result");
                    if (resultProp == null)
                    {
                        resMsg.Code = RpcErrorCodes.CODE_INTERNAL_ERROR;
                        return(resMsg);
                    }

                    object result = resultProp.GetValue(retVal);

                    object dataVal  = null;
                    var    dataProp = tType.GetProperty("Data");
                    if (dataProp != null)
                    {
                        dataVal = dataProp.GetValue(result);
                    }

                    if (dataVal != null)
                    {
                        resMsg.Data = Serializer.Serialize(dataVal);
                    }
                }
                else
                {
                    resMsg.Code = RpcErrorCodes.CODE_INTERNAL_ERROR;
                    //LOG Error;
                }
            }
            else
            {
                resMsg.Code = RpcErrorCodes.CODE_SERVICE_NOT_FOUND;
            }

            return(resMsg);
        }