Esempio n. 1
0
        public void Execute(GeneratorExecutionContext context)
        {
            var defFiles = context.AdditionalFiles.Where(f => f.Path.EndsWith("ControllerDefinition.json"));

            foreach (AdditionalText defFile in defFiles)
            {
                ApiDefinition definition;

                string definitionString = File.ReadAllText(defFile.Path);
                definition = JsonConvert.DeserializeObject <ApiDefinition>(definitionString);

                var controllerClass = GenerateController(definition);
                var modelClasses    = GenerateModels(definition);

                if (string.IsNullOrWhiteSpace(definition.Name))
                {
                    throw new ArgumentException("Invalid definition name");
                }

                string controllerNamespaceName = $"{definition.Namespace}.Controllers";
                string modelNamespaceName      = $"{definition.Namespace}.Models";

                // Controller
                var controllerNamespace = new CodeGenNamespace(controllerNamespaceName);

                controllerNamespace.Content.Add(controllerClass);
                controllerNamespace.Usings.Add("System");
                controllerNamespace.Usings.Add("System.Threading.Tasks");
                controllerNamespace.Usings.Add("Microsoft.AspNetCore.Mvc");
                controllerNamespace.Usings.Add("Microsoft.Extensions.DependencyInjection");
                controllerNamespace.Usings.Add(definition.Namespace);
                controllerNamespace.Usings.Add(modelNamespaceName);

                context.Add(controllerNamespace, $"{definition.Name}Controller.cs");

                // Models
                foreach (CodeGenClass modelClass in modelClasses)
                {
                    var modelNamespace = new CodeGenNamespace(modelNamespaceName);
                    modelNamespace.Content.Add(modelClass);
                    context.Add(modelNamespace, $"{modelClass.Name}.cs");
                }
            }
        }