private static void establishClassInterfaceRelationships(List <InterfaceGenerator> interfaceList, List <ClassGenerator> list) { int numberOfInterfaces = interfaceList.Count; int maxInterfacesToImplement = ConfigurationXMLParser.getPropertyAsInt("maxInterfacesToImplement"); if (numberOfInterfaces == 0) { Console.WriteLine("No interfaces generated!"); return; } foreach (ClassGenerator generator in list) { List <InterfaceGenerator> generatorInterfaceList = generator.InterfaceList; Random random = new Random(); //A class can implement 0 or more interfaces. int numberOfInterfacesToImplement = random.Next(maxInterfacesToImplement); for (int j = 0; j < numberOfInterfacesToImplement; j++) { InterfaceGenerator interfaceGenerator = interfaceList[random.Next(interfaceList.Count)]; if (generatorInterfaceList.Contains(interfaceGenerator)) { continue; } generatorInterfaceList.Add(interfaceGenerator); } } }
public async Task ExecuteToFileTest() { var fileName = ".\\test-project.mdj"; var project = await DVDpro.StarUML.FileFormat.Project.LoadAsync(fileName); var tmpFile = System.IO.Path.GetTempFileName(); try { var generator = new InterfaceGenerator(); using (var outStream = new CSharpWriter(tmpFile)) { foreach (var model in project.GetChildrenByType <DVDpro.StarUML.FileFormat.Nodes.UmlModelNode>()) { var node = model.GetChildrenByType <DVDpro.StarUML.FileFormat.Nodes.UmlInterfaceNode>().First(r => r.Name == "Interface1"); generator.Generate(outStream, node); } } var output = await System.IO.File.ReadAllTextAsync(tmpFile); Assert.Equal("public interface Interface1 : Interface1Base\r\n{\r\n int InterfaceAttribute { get; }\r\n}\r\n", output); } finally { System.IO.File.Delete(tmpFile); } }
private void CheckTypeScriptInterfaceFile(string interfaceFileSubPath) { var contractFile = new FileInfo(GetTypeScriptContractFullPath(interfaceFileSubPath)); contractFile.Exists.Should().BeTrue( $"The Typescript contract file {interfaceFileSubPath} does not exist. Please run the `src/interface-generator` tool with option --out-file {contractFile.FullName}."); var actual = File.ReadAllText(contractFile.FullName); var expected = InterfaceGenerator.Generate(); var compareResult = new DefaultStringComparer(true).Compare(actual, expected); compareResult .Error .Should() .BeNullOrEmpty( because: $@"{contractFile.Name} should match the checked-in version. If the contract change is deliberate, then the TypeScript contracts file '{interfaceFileSubPath}' needs to be regenerated. Please run the following: dotnet run -p src/interface-generator -- --out-file {contractFile.FullName} "); }
public void DeleteTest() { // Act var ret = InterfaceGenerator.GenerateDelete(model); // Assert Assert.Contains($"void DeleteUser(User user);", ret); }
public void InsertTestAsync() { // Act var ret = InterfaceGenerator.GenerateInsert(model, true, false); // Assert Assert.Contains($"Task InsertUser(User user);", ret); }
public void UpdateTestAsync() { // Act var ret = InterfaceGenerator.GenerateUpdate(model, true); // Assert Assert.Contains($"Task UpdateUser(User user);", ret); }
public void InsertReturnIdTest() { // Act var ret = InterfaceGenerator.GenerateInsert(model, false, true); // Assert Assert.Contains($"int InsertUser(User user);", ret); }
public void InsertReturnIdTestAsync() { // Act var ret = InterfaceGenerator.GenerateInsert(model, true, true); // Assert Assert.Contains($"Task<int> InsertUser(User user);", ret); }
public void InsertTest() { // Act var ret = InterfaceGenerator.GenerateInsert(model); // Assert Assert.Contains($"void InsertUser(User user);", ret); }
public void SelectTest() { // Act var ret = InterfaceGenerator.GenerateSelect(model, false); // Assert Assert.Contains($"IEnumerable<User> SelectUser();", ret); }
public void SelectTest() { // Act var ret = InterfaceGenerator.GenerateSelect(model); // Assert Assert.Contains($"List<User> SelectUser();", ret); }
private static void writeToFile(InterfaceGenerator generator) { if (generator == null) { return; } write(generator.Name, generator.ToString()); }
public void SelectTestAsync() { // Act var ret = InterfaceGenerator.GenerateSelect(model, true); // Assert Assert.Contains($"Task<IEnumerable<User>> SelectUser();", ret); }
public void Next() { var TestObject = new InterfaceGenerator(); ITestInterface Result = (ITestInterface)TestObject.Next(typeof(TestClass).GetMethod("TestMethod").GetParameters()[0]); Result.Value.Should().NotBeNull(); Result.Method().Returns(1); Result.Method().Should().Equals(1); }
public void GenerateInterfaceBody() { // Act var ret = InterfaceGenerator.GenerateInterfaceBody(model); // Assert Assert.Contains("public interface IUserRepository", ret); }
public void SetUp() { Configuration = CodeGeneratorConfiguration.Create().DocumentTypes; Generator = new InterfaceGenerator( Configuration ); ContentType = new DocumentType { Info = { Alias = "Mixin" } }; ns = new CodeNamespace("ANamespace"); }
public static void PrintInterface(Interface iface, string root, List <string> imports) { string packageDirectory = Path.Combine(root, JavaConventionHelper.packageConvention(iface.Namespace.Name)); Directory.CreateDirectory(packageDirectory); using (StreamWriter writer = new StreamWriter(Path.Combine(packageDirectory, iface.Name + ".java"))) { InterfaceGenerator javaGen = new InterfaceGenerator(); writer.WriteLine(javaGen.Generate(iface, imports)); } }
/// <summary> /// A list with all the generators /// </summary> /// <param name="context">The context</param> public AllGenerators(WalkerContext context) { AddAssignment = new AssignmentGenerator(context, AssignmentType.Add); AddressOfExpression = new AddressOfExpressionGenerator(context); ArgumentList = new ArgumentListGenerator(context); ArrayCreationExpression = new ArrayCreationExpressionGenerator(context); ArrayInitializerExpression = new ArrayInitializerGenerator(context); BinaryAndAssignment = new AssignmentGenerator(context, AssignmentType.BinaryAnd); BinaryOrAssignment = new AssignmentGenerator(context, AssignmentType.BinaryOr); Block = new BlockGenerator(context); CastExpression = new CastExpressionGenerator(context); ConditionalAccessExpression = new ConditionalAccessExpressionGenerator(context); ClassCode = new ClassCodeGenerator(context); DelegateDeclaration = new DelegateDeclarationGenerator(context); DoStatement = new DoStatementGenerator(context); DivideAssignment = new AssignmentGenerator(context, AssignmentType.Divide); ElementAccess = new ElementAccessGenerator(context); Enum = new EnumGenerator(context); ExclusiveOrAssignment = new AssignmentGenerator(context, AssignmentType.ExclusiveOr); Expression = new ExpressionGenerator(context); ExpressionStatement = new ExpressionStatementGenerator(context); FixedStatement = new FixedStatementGenerator(context); ForStatement = new ForStatementGenerator(context); GotoStatement = new GotoStatementGenerator(context); IfStatement = new IfStatementGenerator(context); Invocation = new InvocationGenerator(context); Interface = new InterfaceGenerator(context); IdentifierName = new IdentifierNameGenerator(context); LabeledStatement = new LabeledStatementGenerator(context); LeftShiftAssignment = new AssignmentGenerator(context, AssignmentType.LeftShift); LocalDeclaration = new LocalDeclarationGenerator(context); MethodDeclaration = new MethodGenerator(context); ModuloAssignment = new AssignmentGenerator(context, AssignmentType.Modulo); MultiplyAssignment = new AssignmentGenerator(context, AssignmentType.Multiply); ObjectCreationExpression = new ObjectCreationExpressionGenerator(context); PreIncrementExpression = new PrePostExpressionGenerator(context, ExpressionType.PreIncrement); PreDecrementExpression = new PrePostExpressionGenerator(context, ExpressionType.PreDecrement); PostIncrementExpression = new PrePostExpressionGenerator(context, ExpressionType.PostIncrement); PostDecrementExpression = new PrePostExpressionGenerator(context, ExpressionType.PostDecrement); PointerMemberAccessExpression = new PointerMemberAccessGenerator(context); Property = new PropertyGenerator(context); ReturnStatement = new ReturnStatementGenerator(context); RightShiftAssignment = new AssignmentGenerator(context, AssignmentType.RightShift); SimpleAssignment = new SimpleAssignmentGenerator(context); SimpleMemberAccess = new SimpleMemberAccessGenerator(context); SizeOfExpression = new SizeofExpressionGenerator(context); Struct = new StructGenerator(context); SubstractAssignment = new AssignmentGenerator(context, AssignmentType.Substract); SwitchStatement = new SwitchStatementGenerator(context); checkedStatement = new checkedStatementGenerator(context); Variable = new VariableGenerator(context); WhileStatement = new WhileStatementGenerator(context); }
private void CheckTypeScriptInterfaceFile(string interfaceFileSubPath) { var contractFile = new FileInfo(GetTypeScriptContractFullPath(interfaceFileSubPath)); contractFile.Exists.Should().BeTrue($"The Typescript contract file {interfaceFileSubPath} does not exist. Please run the `src/interface-generator` tool with option --out-file {contractFile.FullName}."); var actual = File.ReadAllText(contractFile.FullName); var expected = InterfaceGenerator.Generate(); actual.Should() .Be(expected, $"The contents of the TypeScript contracts file '{interfaceFileSubPath}' needs to be updated. Please re-run the `src/interface-generator` tool with option --out-file {contractFile.FullName}."); }
string Render(InterfaceType interfaceType) { Symbols.MapTypeToPackage("myInterfaceFqn", interfaceType.Assembly); Symbols.MapNamespace(interfaceType.QualifiedNamespace, "MyNamespace"); Symbols.MapTypeName("myInterfaceFqn", "MyInterface", kind: JsonModel.Spec.TypeKind.Interface); InterfaceGenerator generator = new InterfaceGenerator(interfaceType.Assembly, interfaceType, Symbols, Namespaces); SyntaxTree syntaxTree = generator.CreateSyntaxTree(); return(syntaxTree.ToString()); }
/// <summary> /// Load a native interface /// </summary> /// <returns></returns> public object?LoadNativeInterface(Type t) { if (!t.IsInterface) { throw new InvalidOperationException($"{t.Name} must be an interface"); } if (LibraryLoader == null) { throw new InvalidOperationException("A native library is not already loaded"); } var ilGenerator = new CalliILGenerator(); var interfaceGenerator = new InterfaceGenerator(LibraryLoader, ilGenerator); return(interfaceGenerator.GenerateImplementation(t)); }
/// <summary> /// Load a native interface /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public T?LoadNativeInterface <T>() where T : class { if (!typeof(T).IsInterface) { throw new InvalidOperationException($"{typeof(T).Name} must be an interface"); } if (LibraryLoader == null) { throw new InvalidOperationException("A native library is not already loaded"); } var ilGenerator = new CalliILGenerator(); var interfaceGenerator = new InterfaceGenerator(LibraryLoader, ilGenerator); return(interfaceGenerator.GenerateImplementation <T>()); }
public void TestGenerateInterface() { var gen = new CodeUnitGenerator("TestCodeGen"); var interfaceGen = new InterfaceGenerator("IMyInterface"); var method = new MethodGenerator("MyInterfaceMethod") .AddParameter(new CodeTypeReference(typeof(bool)), "arg"); interfaceGen.AddMember(method.Method); gen.AddType(interfaceGen); var ccu = gen.GenerateCompileUnit(); var output = StringCompiler.CompileToString(ccu); Debug.Log(output); Assert.IsTrue(output.Contains("interface IMyInterface")); Assert.IsTrue(output.Contains("void MyInterfaceMethod(bool arg);")); }
protected internal override void DoPrepare(DocumentGenerator generator, ContractDefinition definition) { InterfaceGenerator interfaceGenerator = new InterfaceGenerator { ContractDefinition = definition, ForceAsynchronous = ForceAsyncMethod, ForceSynchronous = ForceSyncMethod, InterfaceSuffix = Suffix, ExcludedInterfaces = ExcludedInterfaces, Name = Name, Modifier = Modifier }; if (!string.IsNullOrEmpty(Suffix)) { interfaceGenerator.InterfaceSuffix = Suffix; } generator.Add(interfaceGenerator); }
public static void Generate(TypeMap typeMap, string fname, string name) { StreamReader sr = new StreamReader(fname); XmlSerializer sz = new XmlSerializer(typeof(xcb)); xcb xcb = (xcb)sz.Deserialize(sr); string extName = xcb.extensionxname ?? ""; TypesGenerator tg = new TypesGenerator(typeMap); tg.Generate(xcb, name, extName); InterfaceGenerator ig = new InterfaceGenerator(typeMap); ig.Generate(xcb, name); ClassGenerator cg = new ClassGenerator(typeMap); cg.Generate(xcb, name, extName); }
public static Type GenerateService(Type typeForMethods, Type typeRealization) { var interfaceType = InterfaceGenerator.GenerateInterface(typeForMethods); AssemblyName assemblyName = new AssemblyName("MagicOnionServer.DynamicServices"); string moduleName = String.Format("{0}.dll", assemblyName.Name); var assembly = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); var module = assembly.DefineDynamicModule(moduleName); var type = module.DefineType("DynamicMyFirstService", TypeAttributes.Public, typeof(ServiceBase <>).MakeGenericType(interfaceType), new[] { interfaceType }); var fld = type.DefineField("_service", typeRealization, FieldAttributes.Private | FieldAttributes.InitOnly); var ctor = type.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes); var il = ctor.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Call, type.BaseType.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, Type.EmptyTypes, null)); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Newobj, typeRealization.GetConstructor(Type.EmptyTypes)); il.Emit(OpCodes.Stfld, fld); il.Emit(OpCodes.Ret); foreach (var m in interfaceType.GetMethods()) { if (!m.IsAbstract) { continue; } var realMet = typeRealization.GetMethod(m.Name); // TODO Добавить проверку на наличие метода и перегрузки var met = type.DefineMethod(m.Name, MethodAttributes.Public | MethodAttributes.ReuseSlot | MethodAttributes.Virtual, //| MethodAttributes.HideBySig, CallingConventions.HasThis, m.ReturnType, m.GetParameters().Select(p => p.ParameterType).ToArray() ); il = met.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, fld); int paramCnt = m.GetParameters().Length; for (int j = 0; j < paramCnt; j++) { il.Emit(OpCodes.Ldarg, j + 1); } il.Emit(OpCodes.Call, realMet); Type retType = realMet.ReturnType; if (!retType.IsGenericType || retType.GetGenericTypeDefinition() != typeof(UnaryResult <>)) { if (retType == typeof(void)) { retType = typeof(MessagePack.Nil); il.Emit(OpCodes.Ldsfld, retType.GetField(nameof(MessagePack.Nil.Default))); } retType = typeof(UnaryResult <>).MakeGenericType(retType); il.Emit(OpCodes.Newobj, retType.GetConstructor(new[] { retType.GenericTypeArguments[0] })); } il.Emit(OpCodes.Ret); } return(type.CreateTypeInfo().AsType()); }
public override string Generate(int indent) { if (Data != null) { var output = string.Empty; NamespaceGenerator @namespace = NamespaceGenerator.Namespace(Data.category); InterfaceGenerator @interface = InterfaceGenerator.Interface(Data.title.LegalMemberName()); if (string.IsNullOrEmpty(Data.title)) { return(output); } for (int i = 0; i < Data.variables.Count; i++) { var prop = Data.variables[i]; if (string.IsNullOrEmpty(prop.name) || prop.type == null) { continue; } if (!prop.get && !prop.set) { prop.get = true; } @interface.AddProperty(InterfacePropertyGenerator.Property(prop.name, prop.type, prop.get, prop.set)); } for (int i = 0; i < Data.methods.Count; i++) { var method = Data.methods[i]; if (string.IsNullOrEmpty(method.name) || method.returnType == null) { continue; } var methodGen = InterfaceMethodGenerator.Method(method.name, method.returnType); for (int paramIndex = 0; paramIndex < Data.methods[i].parameters.Count; paramIndex++) { var parameter = Data.methods[i].parameters[paramIndex]; if (string.IsNullOrEmpty(parameter.name) || parameter.type == null) { continue; } methodGen.AddParameter(ParameterGenerator.Parameter(parameter.name, parameter.type, parameter.modifier)); } @interface.AddMethod(methodGen); } #if VISUAL_SCRIPTING_1_7 if (Data.lastCompiledName != Data.GetFullTypeName() && !string.IsNullOrEmpty(Data.GetFullTypeName()) && !string.IsNullOrEmpty(Data.lastCompiledName)) { @interface.AddAttribute(AttributeGenerator.Attribute <RenamedFromAttribute>().AddParameter(Data.lastCompiledName)); } #endif @namespace.AddInterface(@interface); return(@namespace.Generate(indent)); } return(string.Empty); }
public void CanGenerate() { var TestObject = new InterfaceGenerator(); TestObject.CanGenerate(typeof(TestClass).GetMethod("TestMethod").GetParameters()[0]).Should().BeTrue(); }
public void Creation() { var TestObject = new InterfaceGenerator(); TestObject.Should().NotBeNull(); }
private void GenerateCrud() { try { Logger.Log("Initializing generation process..."); SetLoading(true); txtOutput.Text = string.Empty; foreach (var item in lstFiles.CheckedItems) { var model = item.ToString(); IList <PropertyInfo> properties = GetPropertyInfos(model); IList <PropertyInfo> propertiesUpdate = GetPropertyInfos(model); IList <PropertyInfo> propertiesDelete = GetPropertyInfos(model); string output = string.Empty; if (chkClass.Checked) { output += ClassGenerator.GenerateClassBody(model, chkInterface.Checked); if (chkSelect.Checked) { output += MethodGenerator.GenerateSelect( DapperGenerator.Select(model, properties, chkGenerateMethod.Checked, chkClass.Checked, chkAsync.Checked), model, chkClass.Checked, chkAsync.Checked); } if (chkInsert.Checked) { output += MethodGenerator.GenerateInsert( DapperGenerator.Insert(model, properties, chkGenerateMethod.Checked, chkClass.Checked, chkAutoIncrement.Checked, chkAsync.Checked, chkReturnIdentity.Checked), model, chkClass.Checked, chkAsync.Checked, chkReturnIdentity.Checked); } if (chkUpdate.Checked) { output += MethodGenerator.GenerateUpdate( DapperGenerator.Update(model, propertiesUpdate, chkGenerateMethod.Checked, chkClass.Checked, chkAutoIncrement.Checked, chkAsync.Checked), model, chkClass.Checked, chkAsync.Checked); } if (chkDelete.Checked) { output += MethodGenerator.GenerateDelete( DapperGenerator.Delete(model, propertiesDelete, chkGenerateMethod.Checked, chkClass.Checked, chkAsync.Checked), model, chkClass.Checked, chkAsync.Checked); } output += "}"; txtOutput.Text += output; if (chkGenerateFiles.Checked) { FileHelper.GenerateClass(output, model, Projectpath); } } else { if (chkGenerateMethod.Checked) { if (chkSelect.Checked) { txtOutput.Text += MethodGenerator.GenerateSelect(DapperGenerator.Select(model, properties, chkGenerateMethod.Checked, chkClass.Checked, chkAsync.Checked), model, chkClass.Checked, chkAsync.Checked); } if (chkInsert.Checked) { txtOutput.Text += MethodGenerator.GenerateInsert(DapperGenerator.Insert(model, properties, chkGenerateMethod.Checked, chkClass.Checked, chkAutoIncrement.Checked, chkAsync.Checked, chkReturnIdentity.Checked), model, chkClass.Checked, chkAsync.Checked, chkReturnIdentity.Checked); } if (chkUpdate.Checked) { txtOutput.Text += MethodGenerator.GenerateUpdate(DapperGenerator.Update(model, propertiesUpdate, chkGenerateMethod.Checked, chkClass.Checked, chkAutoIncrement.Checked, chkAsync.Checked), model, chkClass.Checked, chkAsync.Checked); } if (chkDelete.Checked) { txtOutput.Text += MethodGenerator.GenerateDelete(DapperGenerator.Delete(model, propertiesDelete, chkGenerateMethod.Checked, chkClass.Checked, chkAsync.Checked), model, chkClass.Checked, chkAsync.Checked); } } else { if (chkSelect.Checked) { txtOutput.Text += DapperGenerator.Select(model, properties, chkGenerateMethod.Checked, chkClass.Checked, chkAsync.Checked); } if (chkInsert.Checked) { txtOutput.Text += DapperGenerator.Insert(model, properties, chkGenerateMethod.Checked, chkClass.Checked, chkAutoIncrement.Checked, chkAsync.Checked, chkReturnIdentity.Checked); } if (chkUpdate.Checked) { txtOutput.Text += DapperGenerator.Update(model, propertiesUpdate, chkGenerateMethod.Checked, chkClass.Checked, chkAutoIncrement.Checked, chkAsync.Checked); } if (chkDelete.Checked) { txtOutput.Text += DapperGenerator.Delete(model, propertiesDelete, chkGenerateMethod.Checked, chkClass.Checked, chkAsync.Checked); } } } if (chkInterface.Checked) { output = InterfaceGenerator.GenerateInterfaceBody(model); if (chkSelect.Checked) { output += InterfaceGenerator.GenerateSelect(model, chkAsync.Checked); } if (chkInsert.Checked) { output += InterfaceGenerator.GenerateInsert(model, chkAsync.Checked, chkReturnIdentity.Checked); } if (chkUpdate.Checked) { output += InterfaceGenerator.GenerateUpdate(model, chkAsync.Checked); } if (chkDelete.Checked) { output += InterfaceGenerator.GenerateDelete(model, chkAsync.Checked); } output += "}"; txtOutput.Text += output; if (chkGenerateFiles.Checked) { FileHelper.GenerateInterface(output, model, Projectpath); } } } SetLoading(false); Logger.Log($"Process Completed Successfully!"); } catch (Exception ex) { SetLoading(false); Logger.Log($"Error during the operation: {ex.Message} InnerException {ex.InnerException} StackTrace {ex.StackTrace} Code {AssemblyHelper.codeGlobal}"); txtOutputLog.ForeColor = Color.Red; txtOutputLog.Text = $"Error during the operation: {ex.Message} InnerException {ex.InnerException} StackTrace {ex.StackTrace} Code {AssemblyHelper.codeGlobal}"; } }