コード例 #1
0
ファイル: ServiceModel.cs プロジェクト: samcook/Fickle
 public ServiceModel(ServiceModelInfo serviceModelInfo, IEnumerable<ServiceEnum> enums, IEnumerable<ServiceClass> classes, IEnumerable<ServiceGateway> gateways)
 {
     this.ServiceModelInfo = serviceModelInfo ?? new ServiceModelInfo();
     this.Enums = enums.ToReadOnlyCollection();
     this.Classes = classes.ToReadOnlyCollection();
     this.Gateways = gateways.ToReadOnlyCollection();
 }
コード例 #2
0
        public virtual void Write(ServiceModelInfo serviceModelInfo)
        {
            this.WriteLine("using System.IO;");
            this.WriteLine();
            this.WriteLine($"namespace {this.codeGenerationOptions.Namespace}");

            using (this.AcquireIndentationContext(BraceLanguageStyleIndentationOptions.IncludeBracesNewLineAfter))
            {
                this.WriteLine("public interface IHttpStreamSerializer");

                using (this.AcquireIndentationContext(BraceLanguageStyleIndentationOptions.IncludeBracesNewLineAfter))
                {
                    this.WriteLine("T Deserialize<T>(Stream inputStream);");
                    this.WriteLine();
                    this.WriteLine("string Serialize<T>(T value);");
                }
            }
        }
コード例 #3
0
ファイル: PodspecWriter.cs プロジェクト: samcook/Fickle
        public virtual void Write(ServiceModelInfo serviceModelInfo)
        {
            this.WriteLine(@"Pod::Spec.new do |s|");

            using (this.AcquireIndentationContext())
            {
                this.WriteLine("s.name = '{0}'", serviceModelInfo.Name);
                this.WriteLine("s.version = '{0}'", serviceModelInfo.Version);
                this.WriteLine("s.summary = '{0}'", serviceModelInfo.Summary);
                this.WriteLine("s.author = '{0}'", serviceModelInfo.Author);
                this.WriteLine("s.license = '{0}'", serviceModelInfo.License);
                this.WriteLine("s.homepage = '{0}'", serviceModelInfo.Homepage);
                this.WriteLine("s.dependency 'PlatformKit', '>= 0.1.8'");

                string value;

                if (serviceModelInfo.ExtendedValues.TryGetValue("podspec.source", out value))
                {
                    this.WriteLine("s.source = { :git => \"" + value + "\", :tag => s.version.to_s }");
                }

                this.WriteLine("s.ios.deployment_target = '5.1'");
                this.WriteLine("s.osx.deployment_target = '10.7'");
                this.WriteLine("s.requires_arc = true");
                this.WriteLine("s.libraries = 'z'");
                this.WriteLine("s.frameworks = 'CFNetwork', 'SystemConfiguration'", "'libz.dylib'");

                if (serviceModelInfo.ExtendedValues.TryGetValue("podspec.source_files", out value))
                {
                    this.WriteLine(@"s.source_files = '{0}'", value);
                }
                else
                {
                    this.WriteLine(@"s.source_files = '**/*.{h,m}'");
                }
            }

            this.WriteLine(@"end");
        }
コード例 #4
0
ファイル: FicklefileParser.cs プロジェクト: samcook/Fickle
 protected virtual void ProcessTopLevel()
 {
     if (this.tokenizer.CurrentToken == FicklefileToken.Keyword)
     {
         switch (this.tokenizer.CurrentKeyword)
         {
         case FicklefileKeyword.Info:
             this.serviceModelInfo = this.ProcessInfo();
             break;
         case FicklefileKeyword.Class:
             this.classes.Add(this.ProcessClass());
             break;
         case FicklefileKeyword.Enum:
             this.enums.Add(this.ProcessEnum());
             break;
         case FicklefileKeyword.Gateway:
             this.gateways.Add(this.ProcessGateway());
             break;
         }
     }
     else
     {
         throw new UnexpectedFicklefileTokenException(this.tokenizer.CurrentToken, this.tokenizer.CurrentValue, FicklefileToken.Keyword);
     }
 }
コード例 #5
0
ファイル: FicklefileParser.cs プロジェクト: samcook/Fickle
        protected virtual ServiceModelInfo ProcessInfo()
        {
            this.ReadNextToken();

            var retval = new ServiceModelInfo();

            if (this.tokenizer.CurrentToken == FicklefileToken.Indent)
            {
                this.ReadNextToken();

                while (true)
                {
                    if (this.tokenizer.CurrentToken == FicklefileToken.Annotation)
                    {
                        var annotation = this.ProcessAnnotation();

                        var property = retval.GetType().GetProperty(annotation.Key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);

                        if (property == null)
                        {
                            throw new FicklefileParserException($"Unexpected annotation: {annotation.Key}={annotation.Value}");
                        }

                        property.SetValue(retval, Convert.ChangeType(annotation.Value, property.PropertyType));
                    }
                    else
                    {
                        break;
                    }
                }

                this.Expect(FicklefileToken.Dedent);
                this.ReadNextToken();
            }

            return retval;
        }
コード例 #6
0
        public override ServiceModel Reflect()
        {
            var descriptions = configuration.Services.GetApiExplorer().ApiDescriptions.AsEnumerable()
                .Where(c => !c.ActionDescriptor.GetCustomAttributes<FickleExcludeAttribute>().Any())
                .ToList();

            if (this.options.ControllersTypesToIgnore != null)
            {
                descriptions = descriptions.Where(x => !this.options.ControllersTypesToIgnore.Contains(x.ActionDescriptor.ControllerDescriptor.ControllerType)).ToList();
            }

            bool secureByDefault = false;

            var enums = new List<ServiceEnum>();
            var classes = new List<ServiceClass>();
            var gateways = new List<ServiceGateway>();

            var referencedTypes = GetReferencedTypes(descriptions).ToList();
            var controllers = descriptions.Select(c => c.ActionDescriptor.ControllerDescriptor).ToHashSet();

            var serviceModelInfo = new ServiceModelInfo();

            foreach (var enumType in referencedTypes.Where(c => c.BaseType == typeof(Enum)))
            {
                var serviceEnum = new ServiceEnum
                {
                    Name = GetTypeName(enumType),
                    Values = Enum.GetNames(enumType).Select(c => new ServiceEnumValue { Name = c, Value = Convert.ToInt64(Enum.Parse(enumType, c)) }).ToList()
                };

                enums.Add(serviceEnum);
            }

            foreach (var type in referencedTypes
                .Where(TypeSystem.IsNotPrimitiveType)
                .Where(c => c.BaseType != typeof(Enum))
                .Where(c => !c.IsInterface)
                .Where(c => !typeof(IList<>).IsAssignableFromIgnoreGenericParameters(c)))
            {
                var baseTypeName = GetTypeName(type.BaseType);
                var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
                    .Where(c => !c.GetCustomAttributes<FickleExcludeAttribute>().Any())
                    .Select(c => new ServiceProperty
                    {
                        Name = c.Name,
                        TypeName = GetTypeName(c.PropertyType)
                    }).ToList();

                var serviceClass = new ServiceClass
                {
                    Name = GetTypeName(type),
                    BaseTypeName = baseTypeName,
                    Properties = properties
                };

                classes.Add(serviceClass);
            }

            var allowedMethods = new HashSet<string>(new[] { "GET", "POST" }, StringComparer.InvariantCultureIgnoreCase);

            foreach (var controller in controllers)
            {
                var methods = new List<ServiceMethod>();

                secureByDefault = this.referencingAssembly.GetCustomAttributes<FickleSecureAttribute>()?.FirstOrDefault()?.Secure ?? false;

                var controllerSecureByDefault = controller.GetCustomAttributes<FickleSecureAttribute>(true)?.FirstOrDefault()?.Secure ?? secureByDefault;

                var serviceNameSuffix = "Service";
                var attribute = this.referencingAssembly.GetCustomAttribute<FickleSdkInfoAttribute>();

                if (attribute != null)
                {
                    serviceNameSuffix = attribute.ServiceNameSuffix ?? serviceNameSuffix;
                    serviceModelInfo.Name = attribute.Name ?? serviceModelInfo.Name;
                    serviceModelInfo.Summary = attribute.Summary ?? serviceModelInfo.Summary;
                    serviceModelInfo.Author = attribute.Author ?? serviceModelInfo.Author;
                    serviceModelInfo.Version = attribute.Version ?? serviceModelInfo.Version;
                }

                foreach (var api in descriptions
                    .Where(c => c.ActionDescriptor.ControllerDescriptor == controller &&
                                allowedMethods.Contains(c.HttpMethod.Method)))
                {
                    var formatters = api.ActionDescriptor.ControllerDescriptor.Configuration.Formatters;
                    var returnType = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;

                    if (!formatters.Any(c => c is JsonMediaTypeFormatter))
                    {
                        returnType = typeof(string);
                    }

                    var parameters = api.ParameterDescriptions.Select(d => new ServiceParameter
                    {
                        Name = d.ParameterDescriptor.ParameterName,
                        TypeName = GetTypeName(d.ParameterDescriptor.ParameterType)
                    }).ToList();

                    ServiceParameter contentServiceParameter = null;
                    var contentParameter = api.ParameterDescriptions.SingleOrDefault(c => c.Source == ApiParameterSource.FromBody);

                    var uniqueNameMaker = new UniqueNameMaker(c => api.ParameterDescriptions.Any(d => d.Name.EqualsIgnoreCase(c)));

                    if (contentParameter == null
                        && api.HttpMethod.Method.EqualsIgnoreCaseInvariant("POST")
                        && api.ActionDescriptor.GetCustomAttributes<NoBodyAttribute>().Count == 0)
                    {
                        contentServiceParameter = new ServiceParameter { Name = uniqueNameMaker.Make("content"), TypeName = GetTypeName(typeof(byte[])) };

                        parameters.Add(contentServiceParameter);
                    }
                    else if (contentParameter != null)
                    {
                        contentServiceParameter = new ServiceParameter { Name = contentParameter.Name, TypeName = GetTypeName(contentParameter.ParameterDescriptor.ParameterType) };
                    }

                    var serviceMethod = new ServiceMethod
                    {
                        Authenticated = api.ActionDescriptor.GetCustomAttributes<AuthorizeAttribute>(true).Count > 0,
                        Secure = api.ActionDescriptor.GetCustomAttributes<FickleSecureAttribute>(true)?.FirstOrDefault()?.Secure ?? controllerSecureByDefault,
                        Name = api.ActionDescriptor.ActionName,
                        Path = StringUriUtils.Combine(this.configuration.VirtualPathRoot, api.RelativePath),
                        Returns = GetTypeName(returnType),
                        ReturnFormat = "json",
                        Method = api.HttpMethod.Method.ToLower(),
                        Parameters = parameters
                    };

                    if (contentServiceParameter != null)
                    {
                        serviceMethod.Content = contentServiceParameter.Name;
                        serviceMethod.ContentServiceParameter = contentServiceParameter;
                    }

                    methods.Add(serviceMethod);
                }

                var serviceGateway = new ServiceGateway
                {
                    BaseTypeName = null,
                    Name = controller.ControllerName + serviceNameSuffix,
                    Hostname = hostname,
                    Methods = methods
                };

                gateways.Add(serviceGateway);
            }

            return new ServiceModel(serviceModelInfo, enums, classes, gateways);
        }
コード例 #7
0
ファイル: Program.cs プロジェクト: techpub/Fickle
        static int Main(string[] args)
        {
            ServiceModel serviceModel;
            var options = new CommandLineOptions();

            if (!CommandLine.Parser.Default.ParseArguments(args, options))
            {
                Console.Error.WriteLine("Unable to parse command line arguments");

                return 1;
            }

            if (options.Input == null)
            {
                Console.Error.WriteLine("Must specify input file");

                return 1;
            }

            TextReader textReader = null;

            foreach (var url in options.Input)
            {
                var currentUrl = url;

                if (currentUrl.IndexOf(":", StringComparison.Ordinal) <= 0)
                {
                    currentUrl = "./" + url;
                }

                var reader = FileSystemManager.Default.ResolveFile(currentUrl).GetContent().GetReader(FileShare.Read);

                textReader = textReader == null ? reader : textReader.Concat(reader);
            }

            if (!string.IsNullOrEmpty(options.Output) && options.Output.IndexOf(":", StringComparison.Ordinal) <= 0)
            {
                options.Output = "./" + options.Output;
            }

            using (var reader = textReader)
            {
                serviceModel = FicklefileParser.Parse(reader);
            }

            object outputObject = Console.Out;

            if (!string.IsNullOrEmpty(options.Output))
            {
                var dir = FileSystemManager.Default.ResolveDirectory(options.Output);

                dir.Create(true);

                outputObject = dir;
            }

            var codeGenerationOptions = new CodeGenerationOptions();
            var defaultServiceModelInfo = codeGenerationOptions.ServiceModelInfo;
            var serviceModelInfo = new ServiceModelInfo();

            serviceModelInfo.Import(defaultServiceModelInfo);
            serviceModelInfo.Import(serviceModel.ServiceModelInfo);

            if (options.Author != null)
            {
                serviceModelInfo.Author = options.Author;
            }

            if (options.Name != null)
            {
                serviceModelInfo.Name = options.Name;
            }

            if (options.Summary != null)
            {
                serviceModelInfo.Summary = options.Summary;
            }

            if (options.Version != null)
            {
                serviceModelInfo.Version = options.Version;
            }

            if (options.PodspecSource != null)
            {
                serviceModelInfo.ExtendedValues["podspec.source"] = options.PodspecSource;
            }

            if (options.PodspecSource != null)
            {
                serviceModelInfo.ExtendedValues["podspec.source_files"] = options.PodspecSourceFiles;
            }

            codeGenerationOptions.ServiceModelInfo = serviceModelInfo;

            using (var codeGenerator = ServiceModelCodeGenerator.GetCodeGenerator(options.Language, outputObject, codeGenerationOptions))
            {
                codeGenerator.Generate(serviceModel);
            }

            return 0;
        }
コード例 #8
0
        static int Main(string[] args)
        {
            ServiceModel serviceModel;
            var          options = new CommandLineOptions();

            if (!CommandLine.Parser.Default.ParseArguments(args, options))
            {
                Console.Error.WriteLine("Unable to parse command line arguments");

                return(1);
            }

            if (options.Input == null)
            {
                Console.Error.WriteLine("Must specify input file");

                return(1);
            }

            TextReader textReader = null;

            foreach (var url in options.Input)
            {
                var currentUrl = url;

                if (currentUrl.IndexOf(":", StringComparison.Ordinal) <= 0)
                {
                    currentUrl = "./" + url;
                }

                var reader = FileSystemManager.Default.ResolveFile(currentUrl).GetContent().GetReader(FileShare.Read);

                textReader = textReader == null ? reader : textReader.Concat(reader);
            }

            if (!string.IsNullOrEmpty(options.Output) && options.Output.IndexOf(":", StringComparison.Ordinal) <= 0)
            {
                options.Output = "./" + options.Output;
            }

            using (var reader = textReader)
            {
                serviceModel = FicklefileParser.Parse(reader);
            }

            object outputObject = Console.Out;

            if (!string.IsNullOrEmpty(options.Output))
            {
                var dir = FileSystemManager.Default.ResolveDirectory(options.Output);

                dir.Create(true);

                outputObject = dir;
            }

            var codeGenerationOptions   = new CodeGenerationOptions();
            var defaultServiceModelInfo = codeGenerationOptions.ServiceModelInfo;
            var serviceModelInfo        = new ServiceModelInfo();

            serviceModelInfo.Import(defaultServiceModelInfo);
            serviceModelInfo.Import(serviceModel.ServiceModelInfo);

            if (options.Author != null)
            {
                serviceModelInfo.Author = options.Author;
            }

            if (options.Name != null)
            {
                serviceModelInfo.Name = options.Name;
            }

            if (options.Summary != null)
            {
                serviceModelInfo.Summary = options.Summary;
            }

            if (options.Version != null)
            {
                serviceModelInfo.Version = options.Version;
            }

            if (options.Homepage != null)
            {
                serviceModelInfo.Homepage = options.Homepage;
            }

            if (options.License != null)
            {
                serviceModelInfo.License = options.License;
            }

            if (options.PodspecSource != null)
            {
                serviceModelInfo.ExtendedValues["podspec.source"] = options.PodspecSource;
            }

            if (options.PodspecSourceFiles != null)
            {
                serviceModelInfo.ExtendedValues["podspec.source_files"] = options.PodspecSourceFiles;
            }

            codeGenerationOptions.GeneratePod = options.Pod;
            codeGenerationOptions.ImportDependenciesAsFramework = options.ImportDependenciesAsFramework;
            codeGenerationOptions.ServiceModelInfo = serviceModelInfo;

            using (var codeGenerator = ServiceModelCodeGenerator.GetCodeGenerator(options.Language, outputObject, codeGenerationOptions))
            {
                codeGenerator.Generate(serviceModel);
            }

            return(0);
        }