Esempio n. 1
0
        public void NoModifierMeansRequired()
        {
            var foo = ProtozbuffLoader.Load(new StringReader(@"<?xml version=""1.0"" encoding=""utf-8"" ?>
<protozbuff xmlns=""http://tempuri.org/protoZ.xsd"">
  <message name=""Folder"" description=""Document definition"">
    <field id=""1"" name=""size"" type=""double""
           description=""Folder size."" />
  </message>
</protozbuff>"));

            const string result = @"package bar;

message FolderHeader
{
    required double size= 1;
}

message LocalMessageDescriptor
{
    repeated int32 coordinate = 1 [packed=true];
}
";
            var          writer = new StringWriter();

            ProtoGenerator.Generate(foo, writer, "bar");
            Assert.That(writer.ToString().RemoveCarriageReturn(), Is.EqualTo(result.RemoveCarriageReturn()));
        }
Esempio n. 2
0
        private async void ExcuteTransfer(IEnumerable items)
        {
            Console.WriteLine("Excute");
            var         sels  = ProtoFiles.ToList().FindAll(item => item.IsSelected);
            List <Task> tlist = new List <Task>();

            foreach (var s in sels)
            {
                var orginPath = s.ProtoFile.FilePath;
                var dirPath   = ".\\SrcProto";
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                Task t = new Task(() =>
                {
                    var src = Path.Combine(dirPath, Path.GetFileName(orginPath));
                    File.Copy(orginPath, src, true);
                    var state = ProtoGenerator.DoGen((output) => { s.ProtoFile.OutputMessage = output; }, $"{src}", $"--csharp_out={OutputDir}");
                    if (!state)
                    {
                        s.ProtoFile.ErrMsg = s.ProtoFile.OutputMessage;
                    }
                    else
                    {
                        s.ProtoFile.ErrMsg       = "Generated Succeed";
                        s.ProtoFile.InputMessage = File.ReadAllText(src);
                    }
                });
                tlist.Add(t);
            }
            tlist.ForEach(t => t.Start());
            Task.WaitAll(tlist.ToArray());
        }
        /// <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));
        }
Esempio n. 4
0
        public ClassData ToProtoClass()
        {
            ClassData data = new ClassData();

            data.className = sheetName;
            ProtoGenerator generator = new ProtoGenerator(sheetName);

            for (int i = 0; i < memberNames.Length; i++)
            {
                Type filterType = GetFilterType(fieldTypes[i]);
                generator.AddProperty(memberNames[i], fieldTypes[i]);
                if (filterType != null)
                {
                    MethodInfo usingMethod = filterType.GetMethod("GetUsings");
                    if (usingMethod == null)
                    {
                        continue;
                    }
                    object   filterObj  = Activator.CreateInstance(filterType);
                    string[] usingNames = usingMethod.Invoke(filterObj, null) as string[];
                    if (usingNames == null)
                    {
                        continue;
                    }
                    foreach (string name in usingNames)
                    {
                        generator.AddUsingName(name);
                    }
                }
            }
            data.classContent = generator.ToString();
            return(data);
        }
Esempio n. 5
0
        /// <summary>
        /// CodeFirst生成proto文件
        /// </summary>
        /// <param name="dir">生成目录</param>
        /// <param name="spiltProto">是否拆分service和message协议</param>
        /// <returns></returns>
        public ServerBuilder UseProtoGenerate(string dir, bool spiltProto = true)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                ProtoGenerator.Gen(dir, spiltProto);
            }

            return(this);
        }
Esempio n. 6
0
        /// <summary>
        /// CodeFirst生成proto文件
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="dir">生成目录</param>
        /// <param name="spiltProto">是否拆分service和message协议</param>
        /// <returns></returns>
        public static IApplicationBuilder UseProtoGenerate(this IApplicationBuilder builder, string dir, bool spiltProto = true)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                ProtoGenerator.Gen(dir, spiltProto);
            }

            return(builder);
        }
Esempio n. 7
0
        public static void GenerateCode3()
        {
            ProtoGenerator textClass = new ProtoGenerator("TestClass");

            textClass.SetNamespace("MM");
            textClass.AddProperty("id", "int");
            textClass.AddProperty("id1", "int");
            string classValue = textClass.ToString();

            TxtUtility.StringToFile(classValue);
            //Debug.Log(classValue);
        }
        private void GenerateProtoOutput(ITaskItem inputFile, ParsedContracts contracts)
        {
            if (!ProtoGenerator.HasProtoOutput(contracts))
            {
                return;
            }

            var targetPath = Path.ChangeExtension(GetValidTargetFilePath(inputFile), "proto") ?? throw new InvalidOperationException("Invalid target path");

            var output = ProtoGenerator.Generate(contracts);

            File.WriteAllText(targetPath, output);

            LogDebug($"{inputFile.ItemSpec}: Generated proto file");
        }
        ///<summary>Entry point</summary>
        public bool Launch()
        {
            InstallResources();

            var p = ProtozbuffLoader.Load(ProtoZFile);

            // protobufs package option (i.e. namespace) needs dots
            var protobufPackage = GeneratedNamespace.Replace(NamespaceSeparator, ".");

            ProtoGenerator.Generate(p, ProtoFile, protobufPackage); // generate .proto file

            CallProtocExe();

            return(GenerateLazyImplementation(p));
        }
Esempio n. 10
0
        public void IndexWithDefault()
        {
            var foo = ProtozbuffLoader.Load(new StringReader(@"<?xml version=""1.0"" encoding=""utf-8"" ?>
<protozbuff xmlns=""http://tempuri.org/protoZ.xsd"">
  <message name=""Folder"" description=""Document definition"">
    <field id=""1"" name=""name"" type=""referenceMessage"" messageType=""File""
           description=""Folder Name."" modifier=""repeated"" default=""foo"" />
    <index id=""2"" name=""my_index"" forField=""1"" sortBy=""filename""/>
  </message>
  <message name=""File"" description=""File desc"">
     <field id=""3"" name=""filename"" type=""string"" modifier=""required""/>
  </message>
</protozbuff>"));

            const string result = @"package bar;

message FolderHeader
{
  //repeated FileHeader name= 1 [default=foo];
    repeated LocalMessageDescriptor name= 1 [default=foo];
  //repeated FileHeader my_index= 2 [default=foo];
    repeated LocalMessageDescriptor my_index= 2 [default=foo];
}

message FileHeader
{
    required string filename= 3;
}

message LocalMessageDescriptor
{
    repeated int32 coordinate = 1 [packed=true];
}
";

            Assert.That(foo, Is.Not.Null);
            var writer = new StringWriter();

            ProtoGenerator.Generate(foo, writer, "bar");
            Assert.That(writer.ToString().RemoveCarriageReturn(), Is.EqualTo(result.RemoveCarriageReturn()));
        }
Esempio n. 11
0
        public void EnumTypeForField()
        {
            var foo = ProtozbuffLoader.Load(new StringReader(@"<?xml version=""1.0"" encoding=""utf-8"" ?>
<protozbuff xmlns=""http://tempuri.org/protoZ.xsd"">
  <message name=""Folder"" description=""Document definition"">
    <field id=""1"" modifier=""required"" name=""name"" type=""enum"" enumType=""my_enum""
           description=""Folder Name."" />
  </message>
  <enum name=""my_enum"" description=""description of my enum"">
     <enumItem name=""item1"" description=""first item"" />
     <enumItem name=""item2"" description=""second item"" value=""42""/>
     <enumItem name=""item3"" description=""third item""/>
  </enum>
</protozbuff>"));

            const string result = @"package bar;

message FolderHeader
{
    required my_enum name= 1;
}

enum my_enum
{
    item1;
    item2=42;
    item3;
}

message LocalMessageDescriptor
{
    repeated int32 coordinate = 1 [packed=true];
}
";
            var          writer = new StringWriter();

            ProtoGenerator.Generate(foo, writer, "bar");
            Assert.That(writer.ToString().RemoveCarriageReturn(), Is.EqualTo(result.RemoveCarriageReturn()));
        }
Esempio n. 12
0
 public Serializer()
 {
     _protoGenerator = new ProtoGenerator();
 }
Esempio n. 13
0
 protected override string GenerateRaw(ParsedContracts contracts)
 {
     return(ProtoGenerator.Generate(contracts));
 }