Ejemplo n.º 1
0
        private void ListMethods(FileDescriptorResponse resp, InfoRS infoRs)
        {
            byte[] bytes = new byte[resp.FileDescriptorProto.First().Length];
            resp.FileDescriptorProto.First().CopyTo(bytes, 0);
            var fdp = ProtobufExtensions.Deserialize <FileDescriptorProto>(bytes);

            foreach (var service in fdp.Services)
            {
                foreach (var method in service.Methods)
                {
                    var name = $"{fdp.Package}.{service.Name}/{method.Name}";
                    infoRs.MethodInfos.Add(new MethodInfo()
                    {
                        Name = name
                    });
                    var inputTypeName  = method.InputType.Split('.').Last();
                    var outputTypeName = method.OutputType.Split('.').Last();
                    var intputType     = fdp.MessageTypes.First(p => p.Name == inputTypeName);
                    var outputType     = fdp.MessageTypes.First(p => p.Name == outputTypeName);
                    var infoMethodRS   = new MethodInfoRS()
                    {
                        RequestJson  = intputType.Fields.ToDictionary(p => p.Name, p => GetFiledDefaultValue(p, fdp.MessageTypes)).ToJson(),
                        ResponseJson = outputType.Fields.ToDictionary(p => p.Name, p => GetFiledDefaultValue(p, fdp.MessageTypes)).ToJson()
                    };
                    dicInfoMethods.AddOrUpdate(name, infoMethodRS, (k, v) => infoMethodRS);
                }
            }
        }
        /// <summary>
        /// 生成Grpc方法(CodeFirst方式)
        /// </summary>
        /// <typeparam name="TRequest"></typeparam>
        /// <typeparam name="TResponse"></typeparam>
        /// <param name="srv"></param>
        /// <param name="methodName"></param>
        /// <param name="package"></param>
        /// <param name="srvName"></param>
        /// <param name="mType"></param>
        /// <returns></returns>
        public static Method <TRequest, TResponse> BuildMethod <TRequest, TResponse>(this Type srv,
                                                                                     string methodName, string package = null, string srvName = null, MethodType mType = MethodType.Unary)
        {
            var serviceName = srvName ??
                              GrpcExtensionsOptions.Instance.GlobalService ??
                              srv.Name;
            var pkg = package ?? GrpcExtensionsOptions.Instance.GlobalPackage;

            if (!string.IsNullOrWhiteSpace(pkg))
            {
                serviceName = $"{pkg}.{serviceName}";
            }
            #region 为生成proto收集信息
            if (!(typeof(IGrpcBaseService).IsAssignableFrom(srv)) || GrpcExtensionsOptions.Instance.GenBaseServiceProtoEnable)
            {
                ProtoInfo.Methods.Add(new ProtoMethodInfo
                {
                    ServiceName  = serviceName,
                    MethodName   = methodName,
                    RequestName  = typeof(TRequest).Name,
                    ResponseName = typeof(TResponse).Name,
                    MethodType   = mType
                });
                ProtoGenerator.AddProto <TRequest>(typeof(TRequest).Name);
                ProtoGenerator.AddProto <TResponse>(typeof(TResponse).Name);
            }
            #endregion
            var request  = Marshallers.Create <TRequest>((arg) => ProtobufExtensions.Serialize <TRequest>(arg), data => ProtobufExtensions.Deserialize <TRequest>(data));
            var response = Marshallers.Create <TResponse>((arg) => ProtobufExtensions.Serialize <TResponse>(arg), data => ProtobufExtensions.Deserialize <TResponse>(data));
            return(new Method <TRequest, TResponse>(mType, serviceName, methodName, request, response));
        }
Ejemplo n.º 3
0
        private object ConvertObject(PropertyInfo property, IRecord element)
        {
            var value = property.GetValue(element);

            if (value == null)
            {
                return(null);
            }
            if (property.PropertyType == typeof(DateTime))
            {
                value = ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
            }
            else if (property.PropertyType == typeof(Boolean))
            {
                value = Convert.ToByte(value);
            }
            else if (property.CustomAttributes.Count() > 0 && property.GetCustomAttribute <ProtoSerializeAttribute>() != null)
            {
                byte[] content = ProtobufExtensions.Serialize(value);
                return(content);
            }
            else if (CustomSerializationMethods.ContainsKey(property.PropertyType))
            {
                value = CustomSerializationMethods[property.PropertyType].Invoke(null, new object[] { value });
            }
            else if (value is Enum)
            {
                value = value.ToString();
            }
            else if (property.PropertyType.IsGenericType)
            {
                List <object> results = new List <object>();

                Type genericType = property.PropertyType.GetGenericTypeDefinition();

                if (genericType == typeof(List <>))
                {
                    var values = (IList)value;

                    foreach (var v in values)
                    {
                        results.Add(v);
                    }
                    return(string.Join(",", results));
                }
                else
                {
                    throw new Exception("Unhandled generic type " + property.PropertyType.Name);
                }
            }

            return(value);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 生成Grpc方法(CodeFirst方式,用于生成BaseService)
        /// </summary>
        /// <typeparam name="TRequest"></typeparam>
        /// <typeparam name="TResponse"></typeparam>
        /// <param name="srv"></param>
        /// <param name="methodName"></param>
        /// <param name="package"></param>
        /// <param name="srvName"></param>
        /// <param name="mType"></param>
        /// <returns></returns>
        public static Method <TRequest, TResponse> BuildMethod <TRequest, TResponse>(this IGrpcService srv,
                                                                                     string methodName, string package = null, string srvName = null, MethodType mType = MethodType.Unary)
        {
            var serviceName = srvName ??
                              GrpcExtensionsOptions.Instance.GlobalService ??
                              srv.GetType().Name;
            var pkg = package ?? GrpcExtensionsOptions.Instance.GlobalPackage;

            if (!string.IsNullOrWhiteSpace(pkg))
            {
                serviceName = $"{pkg}.{serviceName}";
            }
            var request  = Marshallers.Create <TRequest>((arg) => ProtobufExtensions.Serialize <TRequest>(arg), data => ProtobufExtensions.Deserialize <TRequest>(data));
            var response = Marshallers.Create <TResponse>((arg) => ProtobufExtensions.Serialize <TResponse>(arg), data => ProtobufExtensions.Deserialize <TResponse>(data));

            return(new Method <TRequest, TResponse>(mType, serviceName, methodName, request, response));
        }
        private object ConvertObject(object obj, PropertyInfo property)
        {
            if (property.PropertyType.BaseType == typeof(Enum))
            {
                return(Enum.Parse(property.PropertyType, obj.ToString()));
            }
            else if (property.CustomAttributes.Count() > 0 && property.GetCustomAttribute <ProtoSerializeAttribute>() != null)
            {
                return(ProtobufExtensions.Deserialize((byte[])obj, property.PropertyType));
            }
            else if (CustomDeserializationMethods.ContainsKey(property.PropertyType))
            {
                return(CustomDeserializationMethods[property.PropertyType].Invoke(null, new object[] { obj }));
            }
            else if (property.PropertyType.IsGenericType)
            {
                if (property.PropertyType.GetGenericTypeDefinition() == typeof(List <>))
                {
                    var genericType = property.PropertyType.GetGenericArguments()[0];
                    var newList     = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(genericType));

                    var split = obj.ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();

                    foreach (var element in split)
                    {
                        newList.Add(Convert.ChangeType(element, genericType, CultureInfo.InvariantCulture));
                    }
                    return(newList);
                }
            }
            else if (property.PropertyType == typeof(bool))
            {
                return(Convert.ToBoolean(Convert.ToInt16(obj)));
            }
            try
            {
                return(Convert.ChangeType(obj, property.PropertyType, CultureInfo.InvariantCulture));
            }
            catch
            {
                string exception = string.Format("Unknown constructor for '{0}', ({1}).", property.PropertyType.Name, property.Name);
                throw new Exception(exception);
            }
        }
        /// <summary>
        /// 生成Grpc方法(CodeFirst方式)
        /// </summary>
        /// <typeparam name="TRequest"></typeparam>
        /// <typeparam name="TResponse"></typeparam>
        /// <param name="srv"></param>
        /// <param name="methodName"></param>
        /// <param name="package"></param>
        /// <param name="srvName"></param>
        /// <param name="mType"></param>
        /// <returns></returns>
        public static Method <TRequest, TResponse> BuildMethod <TRequest, TResponse>(this IGrpcService srv,
                                                                                     string methodName, string package = null, string srvName = null, MethodType mType = MethodType.Unary)
        {
            var serviceName = srvName ??
                              GrpcExtensionsOptions.Instance.GlobalService ??
                              (srv.GetType().FullName.StartsWith("Castle.Proxies.") ? srv.GetType().Name.Substring(0, srv.GetType().Name.Length - 5) : srv.GetType().Name);
            var pkg = package ?? GrpcExtensionsOptions.Instance.GlobalPackage;

            if (!string.IsNullOrWhiteSpace(pkg))
            {
                serviceName = $"{pkg}.{serviceName}";
            }
            #region 为生成proto收集信息
            if (!(srv is IGrpcBaseService) || GrpcExtensionsOptions.Instance.GenBaseServiceProtoEnable)
            {
                var protoMethodInfo = new ProtoMethodInfo
                {
                    ServiceName  = serviceName,
                    MethodName   = methodName,
                    RequestName  = typeof(TRequest).Name,
                    ResponseName = typeof(TResponse).Name,
                    MethodType   = mType
                };
                if (typeof(TRequest).IsGenericType)
                {
                    protoMethodInfo.RequestName = $"{protoMethodInfo.RequestName.Substring(0, protoMethodInfo.RequestName.IndexOf('`'))}_{typeof(TRequest).GetGenericArguments()[0].Name}";
                }
                if (typeof(TResponse).IsGenericType)
                {
                    protoMethodInfo.ResponseName = $"{protoMethodInfo.ResponseName.Substring(0, protoMethodInfo.ResponseName.IndexOf('`'))}_{typeof(TResponse).GetGenericArguments()[0].Name}";
                }

                ProtoInfo.Methods.Add(protoMethodInfo);
                ProtoGenerator.AddProto <TRequest>(protoMethodInfo.RequestName);
                ProtoGenerator.AddProto <TResponse>(protoMethodInfo.ResponseName);
            }
            #endregion
            var request  = Marshallers.Create <TRequest>((arg) => ProtobufExtensions.Serialize <TRequest>(arg), data => ProtobufExtensions.Deserialize <TRequest>(data));
            var response = Marshallers.Create <TResponse>((arg) => ProtobufExtensions.Serialize <TResponse>(arg), data => ProtobufExtensions.Deserialize <TResponse>(data));
            return(new Method <TRequest, TResponse>(mType, serviceName, methodName, request, response));
        }