private void AddProtoFile(CProject project, CProtoFile protoFile)
 {
     project.ProjectContent.Add(new CProjectContent
     {
         Content     = protoFile,
         BuildAction = CBuildAction.None,
         File        = new CFile
         {
             Folder   = $@"Proto",
             FileName = $"{_mGrpcIntegrationBusinessTestProject.ProjectName}.proto"
         }
     });
 }
 private void AddProtoFile(CProject project, CProtoFile protoFile)
 {
     project.ProjectContent.Add(new CProjectContent
     {
         Content     = protoFile,
         BuildAction = CBuildAction.None,
         File        = new CFile
         {
             Folder   = $@"Proto\ProtoRef\Proto",
             FileName = $"{_grpcMServiceClientTestProject.ProjectName}.proto"
         }
     });
 }
Esempio n. 3
0
        // public SProtoFile ProtoFile { get; set; }

        public override void ConfigureMetaData()
        {
            /*
             * if (ProtoFile.Count ==0)
             * {
             *  ProtoFile.Add(new MProtoFile());
             *  return;
             * }
             */
            foreach (var mProtoFile in ProtoFile)
            {
                if (mProtoFile.GeneratedProtoFile != null)
                {
                    continue;
                }
                mProtoFile.GeneratedProtoFile = CProtoFile.FromJson(mProtoFile.ProtoFileText);
            }
        }
 private void AddProtoRpcRef(CProject project, CProtoFile protoFile)
 {
     foreach (var protoService in protoFile.ProtoService)
     {
         foreach (var rpc in protoService.Rpc)
         {
             var protoRpcRef = new CProtoRpcRef {
                 Direction = CProtoRpcRefDataDirection.Undefined, ProtoRpc = rpc
             };
             project.ProjectContent.Add(new CProjectContent
             {
                 Content     = protoRpcRef,
                 BuildAction = CBuildAction.DoNotInclude,
                 File        = new CFile {
                     Folder = $@"Proto", FileName = $"{protoRpcRef.ProtoRpc.RpcName}.json"
                 }
             });
         }
     }
 }
        /*
         * private KProtoFile FindKProtoFile(KGrpcProject grpcKProject, CMethod method)
         * {
         *  KProtoFile kProtoFile = null;
         *
         *  foreach (var mPf in grpcKProject.ProtoFile)
         *  {
         *      foreach (var mRpc in mPf.Rpc)
         *          if (mRpc.RpcName.ToLower() == method.MethodName.ToLower())
         *          {
         *              kProtoFile = mPf;
         *              break;
         *          }
         *      if (kProtoFile != null)
         *          break;
         *  }
         *
         *  if (kProtoFile == null)
         *  {
         *      kProtoFile = grpcKProject.ProtoFile.FirstOrDefault();
         *      if (kProtoFile == null)
         *      {
         *          kProtoFile = new KProtoFile {ProtoFileName = grpcKProject.ProjectName};
         *          grpcKProject.ProtoFile.Add(kProtoFile);
         *      }
         *  }
         *  if (kProtoFile.GeneratedProtoFile == null)
         *  {
         *      var protoNamespace = kProtoFile.CSharpNamespace; //
         *      if (string.IsNullOrEmpty(protoNamespace))
         *          protoNamespace =
         *              $@"{grpcKProject.CompanyName}.{grpcKProject.ProjectName}{grpcKProject.NamespaceSuffix}.{
         *                      grpcKProject.ProjectSuffix
         *                  }.Proto.Types";
         *      kProtoFile.GeneratedProtoFile = BuildProtoFile(grpcKProject, kProtoFile, protoNamespace);
         *  }
         *
         *
         *  return kProtoFile;
         * }*/

        private CProtoFile BuildProtoFile(KGrpcProject grpcKProject, KProtoFile kProtoFile, string protoNamespace)
        {
            var protoFile = new CProtoFile();

            protoFile.Import.Add("google/protobuf/timestamp.proto");
            protoFile.Import.Add("google/protobuf/duration.proto");
            protoFile.Import.Add("google/protobuf/descriptor.proto");

            protoFile.CSharpNamespace = protoNamespace;

            protoFile.Option.Add($@"csharp_namespace = ""{protoNamespace}"";");
            protoFile.Option.Add($@"(version) = ""1.0.0"";");

            var protoService = new CProtoService(protoFile)
            {
                ServiceName = $@"{kProtoFile.ProtoFileName}Service"
            };

            protoFile.ProtoService.Add(protoService);

            return(protoFile);
        }
        private KProtoFile GetProtoFile(string solutionName)
        {
            _sl.SelectWorksheet("Proto");

            var colSolutionName        = GetColumnIndex("SolutionName");
            var colCSharpNamespace     = GetColumnIndex("CSharpNamespace");
            var colServiceName         = GetColumnIndex("ServiceName");
            var colRpcName             = GetColumnIndex("RpcName");
            var colRequestMessageName  = GetColumnIndex("RequestMessageName");
            var colResponseMessageName = GetColumnIndex("ResponseMessageName");

            var currentRow = 2;
            var protoFile  = new CProtoFile();

            while (!string.IsNullOrEmpty(_sl.GetCellValueAsString(currentRow, colSolutionName)))
            {
                if (_sl.GetCellValueAsString(currentRow, colSolutionName) != solutionName)
                {
                    currentRow++;
                    continue;
                }
                protoFile.CSharpNamespace = _sl.GetCellValueAsString(currentRow, colCSharpNamespace);

                var protoService = new CProtoService(protoFile)
                {
                    ServiceName = _sl.GetCellValueAsString(currentRow, colServiceName)
                };

                protoFile.ProtoService.Add(protoService);
                var rpc = new CProtoRpc(protoService)
                {
                    RpcName = _sl.GetCellValueAsString(currentRow, colRpcName)
                };
                rpc.Request = new CProtoMessage(rpc)
                {
                    MessageName = _sl.GetCellValueAsString(currentRow, colRequestMessageName)
                };
                rpc.Response = new CProtoMessage(rpc)
                {
                    MessageName = _sl.GetCellValueAsString(currentRow, colResponseMessageName)
                };


                protoService.Rpc.Add(rpc);

                /*
                 *  while (_sl.GetCellValueAsString(currentRow, colServiceName) == view.ViewName)
                 *  {
                 *      var column = new SColumn(view)
                 *      {
                 *          ColumnName = _sl.GetCellValueAsString(currentRow, colColumnName),
                 *          ColumnTypeRaw = _sl.GetCellValueAsString(currentRow, colColumnSqlDbType),
                 *      };
                 *      view.Column.Add(column);
                 *      currentRow++;
                 *  }
                 */
                currentRow++;
            }
            return(new KProtoFile {
                GeneratedProtoFile = protoFile
            });
        }
Esempio n. 7
0
        public void AddModelToProtoMethods(CClass extensionsClass, CProtoFile protoFile, CClass modelClass,
                                           string protoNamespace)
        {
            var alias = "ProtoAlias";

            extensionsClass.NamespaceRef.Add(new CNamespaceRef("System.Collections.Generic"));
            extensionsClass.NamespaceRef.Add(new CNamespaceRef("System.Linq"));

            extensionsClass.NamespaceRef.Add(new CNamespaceRef {
                ReferenceTo = new CNamespace {
                    Alias = alias, NamespaceName = protoNamespace
                }
            });

            foreach (var protoMessageIn in protoFile.ProtoMessage)
            {
                CClass convertFromModelClass = null;
                //foreach (var modelClass in convertFromModelClasses)
                {
                    var pm = modelClass?.DerivedFrom?.DerivedFrom as CProtoMessage;
                    if (pm != null && pm.MessageName == protoMessageIn.MessageName)
                    {
                        convertFromModelClass = modelClass;
                        break;
                    }
                }
                if (convertFromModelClass == null)
                {
                    return;
                }

                var protoMessage = protoMessageIn; //protoFile.ProtoMessage.FirstOrDefault(m => m.MessageName == convertFromClass.ClassName);
                // var protoMessage2 = convertFromModelClass?.DerivedFrom?.DerivedFrom as CProtoMessage;
                //if (protoMessage2 == null)
                //    continue;

                if (protoMessage.ProtoField.Count == 1 &&
                    protoMessage.ProtoField.First().FieldType == GrpcType.__message)
                {
                    protoMessage = protoMessage.Rpc.ProtoService.ProtoFile.GetRepeatedMessagesUsedInAResponse()
                                   .FirstOrDefault(m => m.MessageName == protoMessage.ProtoField.First().MessageType);
                }

                if (protoMessage == null)
                {
                    return;
                }

                var toProtoMethod = new CMethod
                {
                    IsStatic          = true,
                    IsExtensionMethod = true,
                    ReturnType        = $"{alias}.{protoMessage.MessageName}",
                    MethodName        = "ToProto"
                };

                //todo: create method for fully qualified name
                toProtoMethod.Parameter.Add(new CParameter
                {
                    Type          = $"{convertFromModelClass.Namespace.NamespaceName}.{convertFromModelClass.ClassName}",
                    ParameterName = "source"
                });

                var codeWriter = new CodeWriter();
                codeWriter.WriteLine($"return new {alias}.{protoMessage.MessageName}");
                codeWriter.WriteLine("{");
                codeWriter.Indent();

                var first = true;
                foreach (var property in convertFromModelClass.Property)
                {
                    //var protoField = protoMessage.ProtoField.FirstOrDefault(pf => pf.FieldName == property.PropertyName.Replace("@", ""));

                    var protoField = FindProtoMessageField(protoMessage, property);
                    if (!first)
                    {
                        codeWriter.WriteLine(",");
                    }
                    first = false;

                    if (protoField == null)
                    {
                        codeWriter.Write($"//<unknownProtoField> = source.{property.PropertyName}");
                    }
                    else if (property.Type.ToLower() == "char[]" && protoField.FieldType == GrpcType.__string)
                    {
                        codeWriter.Write($"{protoField.FieldName} = source.{property.PropertyName}");

                        //assume tostring is needed
                        codeWriter.Write(".ToString()");
                    }
                    else if (property.Type.ToLower() == "decimal" && protoField.FieldType == GrpcType.__string)
                    {
                        codeWriter.Write($"{protoField.FieldName} = source.{property.PropertyName}");

                        //assume tostring is needed
                        codeWriter.Write(".ToString()");
                    }
                    else if (property.Type.ToLower() == "decimal" &&
                             protoField.FieldType == GrpcType.__company_Decimal64Value)
                    {
                        codeWriter.Write($"{protoField.FieldName} = new Decimal64Value() ");
                    }
                    else if (property.Type.ToLower() == "byte" && protoField.FieldType == GrpcType.__int32)
                    {
                        codeWriter.Write($"{protoField.FieldName} = (int) source.{property.PropertyName}");
                    }
                    else if (property.Type.ToLower() == "datetime" &&
                             protoField.FieldType == GrpcType.__google_protobuf_Timestamp)
                    {
                        codeWriter.Write(
                            $"{protoField.FieldName} = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime(DateTime.SpecifyKind(source.{property.PropertyName}, DateTimeKind.Utc))");
                    }
                    else if (property.Type.ToLower() == "datetimeoffset" &&
                             protoField.FieldType == GrpcType.__google_protobuf_Timestamp)
                    {
                        codeWriter.Write(
                            $"{protoField.FieldName} = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime(DateTime.SpecifyKind(source.{property.PropertyName}.DateTime, DateTimeKind.Utc))");
                    }
                    else if (property.Type.ToLower() == "byte[]" && protoField.FieldType == GrpcType.__bytes)
                    {
                        codeWriter.Write(
                            $"{protoField.FieldName} = Google.Protobuf.ByteString.CopyFrom(source.{property.PropertyName})");
                    }

                    else
                    {
                        codeWriter.Write($"{protoField.FieldName} = source.{property.PropertyName}");
                    }
                }

                codeWriter.WriteLine(string.Empty);
                codeWriter.Unindent();
                codeWriter.WriteLine("};");
                toProtoMethod.CodeSnippet = codeWriter.ToString();
                extensionsClass.Method.Add(toProtoMethod);


                var toProtoForListMethod = new CMethod
                {
                    IsStatic          = true,
                    IsExtensionMethod = true,
                    ReturnType        = $"IEnumerable<{alias}.{protoMessage.MessageName}>",
                    MethodName        = "ToProto"
                };

                //todo: create method for fully qualified name
                var parameterType = string.Empty;

                parameterType =
                    $"IEnumerable<{convertFromModelClass.Namespace.NamespaceName}.{convertFromModelClass.ClassName}>";
                toProtoForListMethod.Parameter.Add(new CParameter {
                    Type = parameterType, ParameterName = "source"
                });

                var codeWriter3 = new CodeWriter();
                codeWriter3.WriteLine($"return source.Select(s => s.ToProto()).ToList();");
                toProtoForListMethod.CodeSnippet = codeWriter3.ToString();
                extensionsClass.Method.Add(toProtoForListMethod);
            }
        }
        public CProtoFile Convert(List <CStoredProcedure> storedProcedures, bool addCRUD = false, bool addBulkRpc = true)
        {
            var protoFile = new CProtoFile();

            protoFile.Import.Add("google/protobuf/timestamp.proto");
            protoFile.Import.Add("google/protobuf/descriptor.proto");

            //protoFile.Import.Add("google/protobuf/duration.proto");
            protoFile.CSharpNamespace = NamespaceName;

            protoFile.Option.Add($@"csharp_namespace = ""{NamespaceName}"";");

            var messagesToAddToBulkRpc = new List <CProtoMessage>();
            var protoService           = new CProtoService(protoFile)
            {
                ServiceName = ServiceName
            };

            protoFile.ProtoService.Add(protoService);

            foreach (var storedProcedure in storedProcedures)
            {
                if (!addCRUD)
                {
                    if (storedProcedure.DataOperationIs.HasFlag(COperationIs.CRUD))
                    {
                        continue;
                    }
                }

                var rpc = new CProtoRpc(protoService)
                {
                    RpcName        = storedProcedure.StoredProcedureName,
                    RpcDescription = storedProcedure.StoredProcedureDescription,
                    //DomainModelName = storedProcedure.ResultSetName,
                    DerivedFrom = storedProcedure
                };
                rpc.Request = new CProtoMessage(rpc)
                {
                    IsRequest   = true,
                    MessageName = $"{storedProcedure.StoredProcedureName}Request"
                };
                rpc.Response = new CProtoMessage(rpc)
                {
                    IsResponse  = true,
                    MessageName = $"{storedProcedure.StoredProcedureName}Response"
                };

                var requestMessage = rpc.Request;
                if (!string.IsNullOrEmpty(storedProcedure.ParameterSetName))
                {
                    rpc.Request.ProtoField.Add(new CProtoMessageField(storedProcedure)
                    {
                        IsScalar    = false,
                        MessageType = storedProcedure.ParameterSetName,
                        FieldName   = storedProcedure.ParameterSetName
                    });

                    requestMessage = new CProtoMessage(rpc)
                    {
                        IsRequest   = true,
                        MessageName = storedProcedure.ParameterSetName
                    };
                    if (!protoFile.ProtoMessage.Exists(pm => pm.MessageName == requestMessage.MessageName))
                    {
                        protoFile.ProtoMessage.Add(requestMessage);

                        if (addBulkRpc)
                        {
                            messagesToAddToBulkRpc.Add(requestMessage);
                        }
                    }
                }
                foreach (var parameter in storedProcedure.Parameter)
                {
                    var sqlType = SqlDbType.VarChar;
                    if (!parameter.ParameterTypeIsUserDefined)
                    {
                        sqlType = SqlMapper.ParseValueAsSqlDbType(parameter.ParameterTypeRaw);
                    }

                    var field = new CProtoMessageField(parameter)
                    {
                        FieldName = parameter.ParameterName, //.SourceColumn.ColumnName,
                        FieldType = SqlMapper.SqlDbTypeToGrpcType(sqlType)
                    };

                    if (parameter.ParameterTypeIsUserDefined)
                    {
                        field.Repeated = true;
                    }
                    requestMessage.ProtoField.Add(field);
                }

                var responseMessage = rpc.Response;
                if (!string.IsNullOrEmpty(storedProcedure.ResultSetName))
                {
                    rpc.Response.ProtoField.Add(new CProtoMessageField(null)
                    {
                        IsScalar    = false,
                        Repeated    = true,
                        MessageType = storedProcedure.ResultSetName,
                        FieldName   = storedProcedure.ResultSetName
                    });

                    responseMessage = new CProtoMessage(rpc)
                    {
                        IsResponse  = true,
                        MessageName = storedProcedure.ResultSetName
                    };
                    if (!protoFile.ProtoMessage.Exists(pm => pm.MessageName == responseMessage.MessageName))
                    {
                        protoFile.ProtoMessage.Add(responseMessage);
                    }
                }
                foreach (var resultColumn in storedProcedure.ResultSet)
                {
                    var field = new CProtoMessageField(resultColumn)
                    {
                        FieldName = resultColumn.ColumnName,
                        FieldType = SqlMapper.SqlDbTypeToGrpcType(resultColumn.ColumnSqlDbType)
                    };

                    responseMessage.ProtoField.Add(field);
                }

                protoService.Rpc.Add(rpc);
            }

            /*
             * if (addBulkRpc)
             * {
             *  var rpc = new SProtoRpc(protoService)
             *  {
             *      RpcName = $"{BulkStoreRpcName}",
             *      OperationIs = SOperationIs.Bulk | SOperationIs.Add | SOperationIs.Update
             *  };
             *
             *  var request = new SProtoMessage
             *  {
             *      IsRequest = true,
             *      MessageName = $"{rpc.RpcName}Request"
             *
             *  };
             *
             *  rpc.Request = request;
             *  foreach (var message in messagesToAddToBulkRpc)
             *  {
             *      request.ProtoField.Add(new SProtoMessageField (null) { IsScalar = false, Repeated = true, MessageType = message.MessageName, FieldName = $"{message.MessageName}" });
             *  }
             *
             *  var response = new SProtoMessage
             *  {
             *      IsResponse = true,
             *      MessageName = $"{rpc.RpcName}Response"
             *  };
             *  rpc.Response = response;
             *
             *
             *  protoService.Rpc.Add(rpc);
             * }*/

            return(protoFile);
        }
        public void AddProtoToModelMethods(CClass extensionsClass, CProtoFile protoFile, CClass convertFromProtoClass,
                                           string protoNamespace)
        {
            var alias = "ProtoAlias";

            extensionsClass.NamespaceRef.Add(new CNamespaceRef {
                ReferenceTo = new CNamespace {
                    NamespaceName = "System.Collections.Generic"
                }
            });

            extensionsClass.NamespaceRef.Add(new CNamespaceRef {
                ReferenceTo = new CNamespace {
                    NamespaceName = protoNamespace
                }
            });
            //todo: should we use SProtoFile instead?
            //foreach (var convertFromProtoClass in convertFromProtoClasses)
            {
                var protoMessage = protoFile.ProtoMessage.FirstOrDefault(m => m.MessageName == convertFromProtoClass.ClassName);

                if (protoMessage == null)
                {
                    return;
                }

                var toProtoMethod = new CMethod
                {
                    IsStatic          = true,
                    IsExtensionMethod = true,
                    ReturnType        = convertFromProtoClass.ClassName,
                    MethodName        = "ToModel"
                };

                //todo: create method for fully qualified name
                toProtoMethod.Parameter.Add(new CParameter
                {
                    Type          = $"{convertFromProtoClass.Namespace.NamespaceName}.{convertFromProtoClass.ClassName}",
                    ParameterName = "source"
                });

                var codeWriter = new CodeWriter();
                codeWriter.WriteLine($"return new {convertFromProtoClass.ClassName}");
                codeWriter.WriteLine("{");
                codeWriter.Indent();

                var first = true;
                foreach (var property in convertFromProtoClass.Property)
                {
                    //var protoField = protoMessage.ProtoField.FirstOrDefault(pf => pf.FieldName == property.PropertyName.Replace("@", ""));

                    var protoField = FindProtoMessageField(protoMessage, property);
                    if (!first)
                    {
                        codeWriter.WriteLine(",");
                    }
                    first = false;

                    if (protoField == null)
                    {
                        codeWriter.Write($"//<unknownProtoField> = source.{property.PropertyName}");
                    }
                    else if (property.Type.ToLower() == "char[]" && protoField.FieldType == GrpcType.__string)
                    {
                        codeWriter.Write($"{protoField.FieldName} = source.{property.PropertyName}");

                        //assume tostring is needed
                        codeWriter.Write(".ToString()");
                    }
                    else if (property.Type.ToLower() == "decimal" && protoField.FieldType == GrpcType.__string)
                    {
                        codeWriter.Write($"{protoField.FieldName} = source.{property.PropertyName}");

                        //assume tostring is needed
                        codeWriter.Write(".ToString()");
                    }
                    else if (property.Type.ToLower() == "byte" && protoField.FieldType == GrpcType.__int32)
                    {
                        codeWriter.Write($"{protoField.FieldName} = (int) source.{property.PropertyName}");
                    }
                    else if (property.Type.ToLower() == "datetime" &&
                             protoField.FieldType == GrpcType.__google_protobuf_Timestamp)
                    {
                        codeWriter.Write(
                            $"{protoField.FieldName} = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime(DateTime.SpecifyKind(source.{property.PropertyName}, DateTimeKind.Utc))");
                    }
                    else if (property.Type.ToLower() == "datetimeoffset" &&
                             protoField.FieldType == GrpcType.__google_protobuf_Timestamp)
                    {
                        codeWriter.Write(
                            $"{protoField.FieldName} = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime(DateTime.SpecifyKind(source.{property.PropertyName}.DateTime, DateTimeKind.Utc))");
                    }
                    else if (property.Type.ToLower() == "byte[]" && protoField.FieldType == GrpcType.__bytes)
                    {
                        codeWriter.Write(
                            $"{protoField.FieldName} = Google.Protobuf.ByteString.CopyFrom(source.{property.PropertyName})");
                    }

                    else
                    {
                        codeWriter.Write($"{protoField.FieldName} = source.{property.PropertyName}");
                    }
                }
                codeWriter.WriteLine(string.Empty);
                codeWriter.Unindent();
                codeWriter.WriteLine("};");
                toProtoMethod.CodeSnippet = codeWriter.ToString();
                extensionsClass.Method.Add(toProtoMethod);
            }
        }
        private CMethod GetTestMethod(CProtoFile protoFile, CProtoRpc rpc)
        {
            var codeWriter = new CodeWriter();

            var methodName = $"{rpc.RpcName}_Success";

            var method = new CMethod
            {
                ReturnType = "Task",
                IsAsync    = true,
                IsStatic   = false,
                MethodName = methodName,
                Parameter  = new List <CParameter>
                {
                    new CParameter
                    {
                        Type          = $"{rpc.ProtoService.ServiceName}.{rpc.ProtoService.ServiceName}Client",
                        ParameterName = "client"
                    }
                }
            };

            method.Attribute.Add(new CMethodAttribute {
                AttributeName = "TestMethod"
            });

            codeWriter.WriteLine("//Arrange");
            codeWriter.WriteLine();
            codeWriter.WriteLine($"var request = new {rpc.Request.MessageName}();");

            /*
             * if (!rpc.OperationIs.HasFlag(SOperationIs.Bulk)) //ignore, for now
             * {
             *  foreach (var field in rpc.Request.ProtoField)
             *  {
             *      if (!field.IsScalar)
             *      {
             *          var childMessage = protoFile.ProtoMessage.First(pm => pm.MessageName == field.MessageType);
             *          codeWriter.WriteLine($"request.{field.FieldName} = new {field.MessageType}();");
             *          foreach (var childField in childMessage.ProtoField)
             *          {
             *              if (childField.IsScalar)
             *              {
             *                  codeWriter.WriteLine($"request.{field.FieldName}.{childField.FieldName} = {SampleDataService.GetSampleData(childField, SOperationIs.Undefined)}; ");
             *              }
             *          }
             *      }
             *      else
             *      {
             *          codeWriter.WriteLine($"request.{field.FieldName} = {SampleDataService.GetSampleData(field, SOperationIs.Undefined)}; ");
             *
             *      }
             *  }
             * }
             */
            codeWriter.WriteLine(string.Empty);
            codeWriter.WriteLine("//Act");

            codeWriter.WriteLine(string.Empty);

            codeWriter.WriteLine($"var response = await client.{rpc.RpcName}Async(request);");

            codeWriter.WriteLine(string.Empty);
            codeWriter.WriteLine("//Assert");

            codeWriter.WriteLine(string.Empty);
            codeWriter.WriteLine($@"Assert.Fail(""{method.MethodName}() test is not implemented"");");

            method.CodeSnippet = codeWriter.ToString();

            return(method);
        }
        private void AddProgramClass(CProject project, CProtoFile protoFile)
        {
            var programClass = new CClass("Program")
            {
                Namespace = new CNamespace
                {
                    NamespaceName =
                        $"{_mGrpcIntegrationBusinessTestProject.CompanyName}.{_mGrpcIntegrationBusinessTestProject.ProjectName}{_mGrpcIntegrationBusinessTestProject.NamespaceSuffix}.{_mGrpcIntegrationBusinessTestProject.ProjectSuffix}"
                }
            };

            programClass.NamespaceRef.Add(
                new CNamespaceRef {
                ReferenceTo = new CNamespace {
                    NamespaceName = "Grpc.Core"
                }
            });
            programClass.NamespaceRef.Add(new CNamespaceRef
            {
                ReferenceTo = new CNamespace {
                    NamespaceName = "Google.Protobuf.WellKnownTypes"
                }
            });
            programClass.NamespaceRef.Add(new CNamespaceRef
            {
                ReferenceTo = new CNamespace {
                    NamespaceName = "Microsoft.VisualStudio.TestTools.UnitTesting"
                }
            });
            foreach (var protoService in protoFile.ProtoService)
            {
                programClass.NamespaceRef.Add(new CNamespaceRef
                {
                    ReferenceTo = new CNamespace {
                        NamespaceName = $"{protoService.ProtoFile.CSharpNamespace}"
                    }
                });
            }

            var methodSnippet = new CodeWriter();
            var mainMethod    =
                new CMethod
            {
                ReturnType = "void",
                IsStatic   = true,
                MethodName = "Main",
                Parameter  = new List <CParameter> {
                    new CParameter {
                        Type = "string []", ParameterName = "args"
                    }
                }
            };

            methodSnippet.WriteLine($@"Console.WriteLine(""Press any key once the service has started"");");
            methodSnippet.WriteLine(@"Console.ReadKey();");
            methodSnippet.WriteLine(@"Channel channel = new Channel(""0.0.0.0:50025"", ChannelCredentials.Insecure); ");


            programClass.Method.Add(mainMethod);

            foreach (var protoService in protoFile.ProtoService)
            {
                methodSnippet.WriteLine(
                    $"var client = new {protoService.ServiceName}.{protoService.ServiceName}Client(channel);");
            }
            mainMethod.CodeSnippet = methodSnippet.ToString();
            methodSnippet.WriteLine(@"Console.WriteLine(""Completed"");");

            methodSnippet.WriteLine(@"Console.ReadKey();");
            project.ProjectContent.Add(new CProjectContent
            {
                Content     = programClass,
                BuildAction = CBuildAction.DoNotInclude,
                File        = new CFile {
                    Folder = $@"", FileName = $"{programClass.ClassName}.cs"
                }
            });
        }
Esempio n. 12
0
        public CClass BuildExtensionsClass(KGrpcProject grpcKProject, CClass domainModelClass, CProtoFile protoFile,
                                           string protoNamespace)
        {
            var extensionClass = new CClass($"{domainModelClass.ClassName}Extensions")
            {
                IsStatic  = true,
                Namespace = new CNamespace
                {
                    NamespaceName =
                        $"{grpcKProject.CompanyName}.{grpcKProject.ProjectName}{grpcKProject.NamespaceSuffix}.{grpcKProject.ProjectSuffix}.Extensions"
                }
            };


            return(extensionClass);
        }
Esempio n. 13
0
        public void AddEntityToModelMethods(CClass extensionsClass, CProtoFile protoFile, IList <CClass> modelClasses,
                                            List <CClass> convertFromEntityClasses,
                                            string modelNamespace)
        {
            var alias = "Model";

            extensionsClass.NamespaceRef.Add(new CNamespaceRef {
                ReferenceTo = new CNamespace {
                    NamespaceName = "System"
                }
            });
            extensionsClass.NamespaceRef.Add(new CNamespaceRef {
                ReferenceTo = new CNamespace {
                    NamespaceName = "System.Linq"
                }
            });

            extensionsClass.NamespaceRef.Add(new CNamespaceRef {
                ReferenceTo = new CNamespace {
                    Alias = alias, NamespaceName = modelNamespace
                }
            });
            //todo: should we use SProtoFile instead?

            foreach (var convertFromClass in convertFromEntityClasses)
            {
                //this is a little "fuzzy" since one stored proc could produce 2 "Models". One for the params and another for resultset
                var convertFrompProtoRpc = convertFromClass.DerivedFrom?.DerivedFrom as CProtoMessage;
                //var modelClass = modelClasses.FirstOrDefault(mc => (mc.DerivedFrom?.DerivedFrom as CProtoMessage)?.Rpc == convertFrompProtoRpc);
                if (convertFrompProtoRpc == null)
                {
                    _logger.LogWarning($"convertFrompProtoRpc is null");
                    continue;
                }
                var modelClass =
                    modelClasses.FirstOrDefault(mc => mc.ClassName == convertFrompProtoRpc.DomainModelNameForOutput);

                if (modelClass == null)
                {
                    continue;
                }
                var toModelMethod = new CMethod
                {
                    IsStatic          = true,
                    IsExtensionMethod = true,
                    ReturnType        = $"{alias}.{modelClass.ClassName}",
                    MethodName        = "ToModel"
                };

                //todo: create method for fully qualified name
                toModelMethod.Parameter.Add(new CParameter
                {
                    Type          = $"{convertFromClass.Namespace.NamespaceName}.{convertFromClass.ClassName}",//$"Model.{convertFrompProtoRpc.DomainModelNameForOutput}",// $"{convertFromClass.Namespace.NamespaceName}.{convertFromClass.ClassName}",
                    ParameterName = "source"
                });

                var codeWriter = new CodeWriter();
                //var protoMessage = protoFile.ProtoMessage.FirstOrDefault(m => m.MessageName == convertFromClass.ClassName);


                if (modelClass == null)
                {
                    codeWriter.WriteLine("throw new NotImplementedException();");
                }
                else
                {
                    codeWriter.WriteLine($"return new {alias}.{ modelClass.ClassName}");
                    codeWriter.WriteLine("{");
                    codeWriter.Indent();

                    var first = true;
                    foreach (var convertToProperty in modelClass.Property)
                    {
                        var convertFromProperty =
                            convertFromClass.Property.FirstOrDefault(p =>
                                                                     p.PropertyName == convertToProperty.PropertyName);
                        if (convertFromProperty == null)
                        {
                            continue;
                        }

                        if (!first)
                        {
                            codeWriter.WriteLine(",");
                        }
                        first = false;


                        codeWriter.Write($"{convertToProperty.PropertyName} = source.{convertFromProperty.PropertyName}");
                    }

                    codeWriter.Unindent();
                    codeWriter.WriteLine("};");
                }
                toModelMethod.CodeSnippet = codeWriter.ToString();
                extensionsClass.Method.Add(toModelMethod);
            }
        }
        public string Convert(CProtoFile protoFile)
        {
            var codeWriter = new CodeWriter();

            codeWriter.WriteLine($@"syntax = ""{protoFile.ProtoSyntax}"";");
            codeWriter.WriteLine(string.Empty);
            if (protoFile.Package != null)
            {
                foreach (var package in protoFile.Package)
                {
                    codeWriter.WriteLine($@"package {package};");
                }
            }
            codeWriter.WriteLine();

            foreach (var import in protoFile.Import)
            {
                codeWriter.WriteLine($@"import ""{import}"";");
            }

            codeWriter.WriteLine();

            //todo: remove hard coding
            codeWriter.WriteLine(@"extend google.protobuf.FileOptions {");
            codeWriter.WriteLine(@"     string version = 50000;");
            codeWriter.WriteLine(@"}");

            foreach (var option in protoFile.Option)
            {
                codeWriter.WriteLine($"option {option}");
            }

            codeWriter.WriteLine();

            foreach (var service in protoFile.ProtoService)
            {
                codeWriter.WriteLine($"service {service.ServiceName} {{");
                codeWriter.Indent();
                foreach (var rpc in service.Rpc)
                {
                    codeWriter.WriteLine();
                    if (!string.IsNullOrEmpty(rpc.RpcDescription) && !string.IsNullOrWhiteSpace(rpc.RpcDescription))
                    {
                        codeWriter.WriteLine($@"/* {rpc.RpcDescription} */");
                    }
                    codeWriter.Write($"rpc {rpc.RpcName} ({rpc.Request.MessageName}) ");
                    codeWriter.WriteLine($"returns ({rpc.Response.MessageName});");
                }
                codeWriter.Unindent();
                codeWriter.WriteLine("}");
            }
            codeWriter.WriteLine();

            var messages = new List <CProtoMessage>();

            messages.AddRange(protoFile.ProtoMessage);
            foreach (var service in protoFile.ProtoService)
            {
                foreach (var rpc in service.Rpc)
                {
                    messages.Add(rpc.Request);
                    messages.Add(rpc.Response);
                }
            }

            foreach (var message in messages)
            {
                if (message.IsExternal)
                {
                    continue;
                }
                codeWriter.WriteLine($"message {message.MessageName} {{");
                codeWriter.Indent();

                var position = 1;
                foreach (var field in message.ProtoField)
                {
                    if (field.Repeated)
                    {
                        codeWriter.Write("repeated ");
                    }

                    var fieldType = string.Empty;
                    if (field.FieldType == GrpcType.__message)
                    {
                        fieldType = field.MessageType;
                    }
                    else if (field.FieldType == GrpcType.__enum)
                    {
                        fieldType = field.EnumType;
                    }
                    else if (field.FieldType == GrpcType.__map)
                    {
                        fieldType = field.MapType;
                    }
                    else
                    {
                        fieldType = field.FieldType.ToString().Replace("__", "").Replace("_", ".");
                    }
                    codeWriter.WriteLine($"{fieldType} {field.FieldNameGrpc} = {position}; // {field.Comment}");
                    position++;
                }

                codeWriter.Unindent();
                codeWriter.WriteLine("}");
            }
            codeWriter.WriteLine(string.Empty);

            foreach (var enumItem in protoFile.ProtoEnum)
            {
                codeWriter.WriteLine($"enum {enumItem.EnumName} {{");
                codeWriter.Indent();

                var position = 1;
                foreach (var enumItemValue in enumItem.EnumValue)
                {
                    codeWriter.WriteLine($"{enumItemValue.EnumValueName} = {enumItemValue.EnumValueNumber}; ");
                    position++;
                }

                codeWriter.Unindent();
                codeWriter.WriteLine("}");
            }
            codeWriter.WriteLine(string.Empty);
            return(codeWriter.ToString());
        }
        private CProtoRpc BuildRpcFromStoredProc(CProtoFile protoFile, CProtoService protoService, CMethod method,
                                                 CStoredProcedure storedProcedure)
        {
            var rpc = new CProtoRpc(protoService)
            {
                RpcName        = storedProcedure.StoredProcedureName,
                RpcDescription = storedProcedure.StoredProcedureDescription,
                //DomainModelName = storedProcedure.ResultSetName,
                DerivedFrom = storedProcedure
            };

            rpc.Request = new CProtoMessage(rpc)
            {
                IsRequest   = true,
                MessageName = $"{storedProcedure.StoredProcedureName}Request"
            };
            rpc.Response = new CProtoMessage(rpc)
            {
                IsResponse  = true,
                MessageName = $"{storedProcedure.StoredProcedureName}Response"
            };

            var requestMessage = rpc.Request;

            if (!string.IsNullOrEmpty(storedProcedure.ParameterSetName))
            {
                rpc.Request.ProtoField.Add(new CProtoMessageField(storedProcedure)
                {
                    IsScalar    = false,
                    MessageType = storedProcedure.ParameterSetName,
                    FieldName   = storedProcedure.ParameterSetName
                });

                requestMessage = new CProtoMessage(rpc)
                {
                    IsRequest   = true,
                    MessageName = storedProcedure.ParameterSetName
                };
                if (!protoFile.ProtoMessage.Exists(pm => pm.MessageName == requestMessage.MessageName))
                {
                    protoFile.ProtoMessage.Add(requestMessage);
                }
            }
            foreach (var parameter in storedProcedure.Parameter)
            {
                var field = new CProtoMessageField(parameter)
                {
                    FieldName = parameter.ParameterName //.SourceColumn.ColumnName,
                };

                if (!parameter.ParameterTypeIsUserDefined)
                {
                    var sqlType = SqlMapper.ParseValueAsSqlDbType(parameter.ParameterTypeRaw);
                    field.FieldType = SqlMapper.SqlDbTypeToGrpcType(sqlType);
                }
                else
                {
                    //todo: property handle user defined sql types (tables)
                    //lookup table type
                    //for now, use the data type of the first column, assumes single column table
                    var tableType = FindTableType(parameter.ParameterTypeRaw);
                    var converter = new CTableTypeToCClassConverter();
                    var @class    = converter.Convert(tableType.GeneratedTableType);
                    field.FieldType   = GrpcType.__string;
                    field.IsScalar    = false;
                    field.Repeated    = true;
                    field.MessageType = $@"{@class.ClassName}";

                    if (!protoFile.ProtoMessage.Exists(pm => pm.MessageName == field.MessageType))
                    {
                        //create a message
                        var tableTypeDerivedMessage = new CProtoMessage(rpc)
                        {
                            MessageName = field.MessageType
                        };
                        foreach (var property in @class.Property)
                        {
                            var field2 = new CProtoMessageField(property)
                            {
                                FieldName = property.PropertyName,
                                FieldType = SqlMapper.ClrTypeToGrpcType(SqlMapper.ClrTypeAliasToClrType(property.Type))
                            };

                            tableTypeDerivedMessage.ProtoField.Add(field2);
                        }
                        protoFile.ProtoMessage.Add(tableTypeDerivedMessage);
                    }
                }

                requestMessage.ProtoField.Add(field);
            }

            var responseMessage = rpc.Response;

            if (!string.IsNullOrEmpty(storedProcedure.ResultSetName))
            {
                rpc.Response.ProtoField.Add(new CProtoMessageField(null)
                {
                    IsScalar    = false,
                    Repeated    = true,
                    MessageType = storedProcedure.ResultSetName,
                    FieldName   = storedProcedure.ResultSetName
                });

                responseMessage = new CProtoMessage(rpc)
                {
                    IsResponse  = true,
                    MessageName = storedProcedure.ResultSetName
                };
                if (!protoFile.ProtoMessage.Exists(pm => pm.MessageName == responseMessage.MessageName))
                {
                    protoFile.ProtoMessage.Add(responseMessage);
                }
            }
            foreach (var resultColumn in storedProcedure.ResultSet)
            {
                var field = new CProtoMessageField(resultColumn)
                {
                    FieldName = resultColumn.ColumnName,
                    FieldType = SqlMapper.SqlDbTypeToGrpcType(resultColumn.ColumnSqlDbType)
                };

                responseMessage.ProtoField.Add(field);
            }
            return(rpc);
        }
        private CProtoRpc BuildBulkRpcFromStoredProcList(CProtoFile protoFile, CProtoService protoService,
                                                         CMethod method, CStoredProcList storedProcedureList)
        {
            var rpc = new CProtoRpc(protoService)
            {
                RpcName = method.MethodName,
                //DomainModelName = "Junk", // storedProcedure.ResultSetName,,
                DerivedFrom = storedProcedureList
            };

            rpc.Request = new CProtoMessage(rpc)
            {
                IsRequest   = true,
                MessageName = $"{method.MethodName}Request"
            };
            rpc.Response = new CProtoMessage(rpc)
            {
                IsResponse  = true,
                MessageName = $"{method.MethodName}Response"
            };


            var requestMessage = rpc.Request;

            foreach (var storedProcedure in storedProcedureList.List)
            {
                if (!string.IsNullOrEmpty(storedProcedure.ParameterSetName))
                {
                    rpc.Request.ProtoField.Add(new CProtoMessageField(storedProcedure)
                    {
                        IsScalar    = false,
                        MessageType = storedProcedure.ParameterSetName,
                        FieldName   = storedProcedure.ParameterSetName,
                        Repeated    = true
                    });

                    requestMessage = new CProtoMessage(rpc)
                    {
                        IsRequest   = true,
                        MessageName = storedProcedure.ParameterSetName
                    };
                    if (!protoFile.ProtoMessage.Exists(pm => pm.MessageName == requestMessage.MessageName))
                    {
                        protoFile.ProtoMessage.Add(requestMessage);
                    }
                }
                foreach (var parameter in storedProcedure.Parameter)
                {
                    var sqlType = SqlDbType.VarChar;
                    if (!parameter.ParameterTypeIsUserDefined)
                    {
                        sqlType = SqlMapper.ParseValueAsSqlDbType(parameter.ParameterTypeRaw);
                    }

                    var field = new CProtoMessageField(parameter)
                    {
                        FieldName = parameter.ParameterName, //.SourceColumn.ColumnName,
                        FieldType = SqlMapper.SqlDbTypeToGrpcType(sqlType)
                    };

                    if (parameter.ParameterTypeIsUserDefined)
                    {
                        field.Repeated = true;
                    }
                    requestMessage.ProtoField.Add(field);
                }

                /*
                 * var responseMessage = rpc.Response;
                 * if (!string.IsNullOrEmpty(storedProcedure.ResultSetName))
                 * {
                 *  rpc.Response.ProtoField.Add(new SProtoMessageField(null)
                 *  {
                 *      IsScalar = false,
                 *      Repeated = true,
                 *      MessageType = storedProcedure.ResultSetName,
                 *      FieldName = storedProcedure.ResultSetName
                 *  });
                 *
                 *  responseMessage = new SProtoMessage
                 *  {
                 *      IsResponse = true,
                 *      MessageName = storedProcedure.ResultSetName
                 *  };
                 *  if (!protoFile.ProtoMessage.Exists(pm => pm.MessageName == responseMessage.MessageName))
                 *  {
                 *      protoFile.ProtoMessage.Add(responseMessage);
                 *
                 *  }
                 *
                 * }
                 * foreach (var resultColumn in storedProcedure.ResultSet)
                 * {
                 *  var field = new SProtoMessageField(resultColumn)
                 *  {
                 *      FieldName = resultColumn.ColumnName,
                 *      FieldType = SqlMapper.SqlDbTypeToGrpcType(resultColumn.ColumnSqlDbType)
                 *  };
                 *
                 *  responseMessage.ProtoField.Add(field);
                 * }*/
            }
            return(rpc);
        }
Esempio n. 17
0
        public KProtoFile Convert(string protoFileName, string protoFileContent)
        {
            //1. save file to temp folder
            //2. run protoc compiler, convert to C# class
            //3. Compile the code in memory
            //4. Read the .Descriptor
            //5. Converto SProtoFile
            var codePath      = GenerateCodeFromProto(protoFileContent);
            var code          = GetGeneratedCode(codePath);
            var assembly      = CompileCodeToAssembly(code);
            var descriptors   = GetFileDescriptorsFromAssembly(assembly);
            var messagesAdded = new List <CProtoMessage>();
            var protoFile     = new CProtoFile();

            protoFile.SourceProtoText = protoFileContent;

            foreach (var descriptorPair in descriptors)
            {
                var descriptor = descriptorPair.Value;
                protoFile.CSharpNamespace = descriptorPair.Key;

                protoFile.Import.Add("google/protobuf/timestamp.proto");
                protoFile.Import.Add("google/protobuf/duration.proto");
                protoFile.Import.Add("google/protobuf/descriptor.proto");

                protoFile.Option.Add($@"csharp_namespace = ""{protoFile.CSharpNamespace}"";");
                protoFile.Option.Add($@"(version) = ""1.0.0"";");

                foreach (var service in descriptor.Services)
                {
                    var protoService = new CProtoService(protoFile)
                    {
                        ServiceName = service.Name
                    };
                    foreach (var method in service.Methods)
                    {
                        var protoServiceMethod = new CProtoRpc(protoService)
                        {
                            RpcName = method.Name
                        };
                        protoService.Rpc.Add(protoServiceMethod);
                        protoServiceMethod.Request = new CProtoMessage(protoServiceMethod)
                        {
                            MessageName = method.InputType.Name
                        };
                        messagesAdded.Add(protoServiceMethod.Request);

                        foreach (var field in method.InputType.Fields.InFieldNumberOrder())
                        {
                            //protoServiceMethod.Request.ProtoField.Add(BuildProtoMessageField(field));
                            ProcessField(field, descriptor, protoServiceMethod.Request, messagesAdded);
                        }

                        protoServiceMethod.Response = new CProtoMessage(protoServiceMethod)
                        {
                            MessageName = method.OutputType.Name
                        };
                        messagesAdded.Add(protoServiceMethod.Response);
                        foreach (var field in method.OutputType.Fields.InFieldNumberOrder())
                        {
                            //protoServiceMethod.Response.ProtoField.Add(BuildProtoMessageField(field));
                            ProcessField(field, descriptor, protoServiceMethod.Response, messagesAdded);
                        }
                    }
                    protoFile.ProtoService.Add(protoService);
                }
                foreach (var enumType in descriptor.EnumTypes)
                {
                    if (protoFile.ProtoEnum.Exists(pe => pe.EnumName == enumType.Name))
                    {
                        continue;
                    }
                    var protoEnum = new CProtoEnum {
                        EnumName = enumType.Name
                    };
                    foreach (var enumTypeItem in enumType.Values)
                    {
                        var enumValue = new CProtoEnumValue
                        {
                            EnumValueName   = enumTypeItem.Name,
                            EnumValueNumber = enumTypeItem.Number
                        };
                        protoEnum.EnumValue.Add(enumValue);
                    }
                    protoFile.ProtoEnum.Add(protoEnum);
                }
                foreach (var message in descriptor.MessageTypes)
                {
                    if (messagesAdded.Exists(pm => pm.MessageName == message.Name))
                    {
                        continue;
                    }
                    var protoMessage = new CProtoMessage(null)
                    {
                        MessageName = message.Name
                    };

                    foreach (var field in message.Fields.InFieldNumberOrder())
                    {
                        ProcessField(field, descriptor, protoMessage, messagesAdded);
                    }

                    protoFile.ProtoMessage.Add(protoMessage);
                    messagesAdded.Add(protoMessage);
                }
                foreach (var dependency in descriptor.Dependencies)
                {
                    foreach (var message in dependency.MessageTypes)
                    {
                        if (messagesAdded.Exists(pm => pm.MessageName == message.Name))
                        {
                            continue;
                        }
                        var protoMessage = new CProtoMessage(null)
                        {
                            MessageName = message.Name, IsExternal = true
                        };
                        protoFile.ProtoMessage.Add(protoMessage);
                        messagesAdded.Add(protoMessage);
                    }
                }
            }
            return(new KProtoFile
            {
                ProtoFileFile = protoFileName,
                GeneratedProtoFile = protoFile
            });
        }
Esempio n. 18
0
        public void AddToModelAsListMethods(CClass extensionsClass, CClass domainModelClass, CProtoFile protoFile, string protoNamespace)
        {
            var alias = "ProtoAlias";

            extensionsClass.NamespaceRef.Add(new CNamespaceRef {
                ReferenceTo = new CNamespace {
                    NamespaceName = protoNamespace
                }
            });
            extensionsClass.NamespaceRef.Add(new CNamespaceRef {
                ReferenceTo = new CNamespace {
                    NamespaceName = "System.Collections.Generic"
                }
            });
            extensionsClass.NamespaceRef.Add(new CNamespaceRef {
                ReferenceTo = new CNamespace {
                    NamespaceName = "System.Linq"
                }
            });
            extensionsClass.NamespaceRef.Add(new CNamespaceRef
            {
                ReferenceTo = new CNamespace {
                    NamespaceName = "Google.Protobuf.Collections"
                }
            });

            {
                if (!protoFile.ProtoMessage.Exists(m => m.MessageName == domainModelClass.ClassName))
                {
                    return;
                }

                var toModelMethod = new CMethod
                {
                    IsStatic          = true,
                    IsExtensionMethod = true,
                    ReturnType        = $"IEnumerable<{domainModelClass.Namespace.NamespaceName}.{domainModelClass.ClassName}>",
                    MethodName        = "ToModel"
                };

                //todo: create method for fully qualified name
                var parameterType = string.Empty;

                parameterType = $"RepeatedField<{alias}.{domainModelClass.ClassName}>";
                toModelMethod.Parameter.Add(new CParameter {
                    Type = parameterType, ParameterName = "source"
                });

                var codeWriter = new CodeWriter();
                codeWriter.WriteLine($"return source.Select(s => s.ToModel()).ToList();");
                toModelMethod.CodeSnippet = codeWriter.ToString();
                extensionsClass.Method.Add(toModelMethod);
            }
        }