static BasicMimeTypesX()
        {
            MTIDict_ByEnums      = AllTypes.ToDictionary(v => v.MimeType, v => v);
            MTIDict_ByMimeNames  = AllTypes.ToDictionary(v => v.MimeTypeString, v => v);
            MTIDict_ByExtensions = AllTypes.Where(v => v.Extension.NotNulle()).ToDictionary(v => v.Extension, v => v);

            for (int i = 0; i < AllTypes.Length; i++)
            {
                MTI mti = AllTypes[i];

                if (mti.ExtraMimeStrings.NotNulle())
                {
                    foreach (string extMimeStr in mti.ExtraMimeStrings)
                    {
                        if (!MTIDict_ByMimeNames.ContainsKey(extMimeStr))
                        {
                            MTIDict_ByMimeNames.Add(extMimeStr, mti);
                        }
                    }
                }

                if (mti.ExtraExtensions.NotNulle())
                {
                    foreach (string ext in mti.ExtraExtensions)
                    {
                        if (!MTIDict_ByExtensions.ContainsKey(ext))
                        {
                            MTIDict_ByExtensions.Add(ext, mti);
                        }
                    }
                }
            }
        }
Example #2
0
    //static EndpointConfiguration DistributionConfig(string endpointName)
    //{
    //    #region DistributionEndpointName
    //    var distributionEndpointName = $"{endpointName}.{Utils.GetUniqueDataDistributionId()}";
    //    var distributionConfig = new EndpointConfiguration(distributionEndpointName);

    //    #endregion

    //    #region DistributionEndpointTypes
    //    var typesToExclude = AllTypes
    //        .Where(t => t.Namespace != "DataDistribution")
    //        .ToArray();
    //    var scanner = distributionConfig.AssemblyScanner();
    //    scanner.ExcludeTypes(typesToExclude);
    //    #endregion

    //    var transport = distributionConfig.UseTransport<MsmqTransport>();
    //    var routing = transport.Routing();
    //    routing.RegisterPublisher(
    //        publisherEndpoint: "Samples.DataDistribution.Server-2",
    //        eventType: typeof(OrderAccepted));

    //    ApplyDefaults(distributionConfig);
    //    return distributionConfig;
    //}

    static EndpointConfiguration MainConfig(string endpointName)
    {
        #region MainConfig

        var mainConfig = new EndpointConfiguration(endpointName);

        var typesToExclude = AllTypes
                             .Where(t => t.Namespace == "DataDistribution")
                             .ToArray();
        var scanner = mainConfig.AssemblyScanner();
        scanner.ExcludeTypes(typesToExclude);
        var transport   = mainConfig.UseTransport <MsmqTransport>();
        var mainRouting = transport.Routing();
        mainRouting.RouteToEndpoint(
            messageType: typeof(PlaceOrder),
            destination: "Samples.DataDistribution.Server-2");
        //mainRouting.RegisterPublisher(
        //    publisherEndpoint: "Samples.DataDistribution.Server-2",
        //    eventType: typeof(OrderAccepted));

        #endregion

        ApplyDefaults(mainConfig);
        return(mainConfig);
    }
    static EndpointConfiguration DistributionConfig(string endpointName)
    {
        #region DistributionEndpointName
        var distributionEndpointName = $"{endpointName}.{Utils.GetUniqueDataDistributionId()}";
        var distributionConfig       = new EndpointConfiguration(distributionEndpointName);

        #endregion

        #region DistributionEndpointTypes
        var typesToExclude = AllTypes
                             .Where(t => t.Namespace != "DataDistribution")
                             .ToArray();
        var assemblyScanner = distributionConfig.AssemblyScanner();
        assemblyScanner.ExcludeTypes(typesToExclude);
        #endregion

        var transport = distributionConfig.UseTransport <MsmqTransport>();
        var routing   = transport.Routing();
        routing.RegisterPublisher(
            publisherEndpoint: "Samples.DataDistribution.Server",
            eventType: typeof(OrderAccepted));

        ApplyDefaults(distributionConfig);
        return(distributionConfig);
    }
Example #4
0
            public override string ToString()
            {
                string result = null;

                foreach (var rt in AllTypes.Where(rt => this[rt] > 0))
                {
                    result  = result ?? "";
                    result += $"{rt}:{this[rt]} ";
                }
                return(result ?? "<none>");
            }
Example #5
0
        private void RefreshInheritanceMap(IEnumerable <TypeDefinition> types)
        {
            var mapDelta = AllTypes.Where(x => x.BaseType != null).ToLookup(x => x.BaseType, comparer);

            foreach (var item in mapDelta)
            {
                var derivedTypes = InheritanceMap.GetValue(item.Key) ?? new HashSet <TypeDefinition>(comparer);
                derivedTypes.UnionWith(item);
                InheritanceMap[item.Key] = derivedTypes;
            }
        }
Example #6
0
 public void Aggregate()
 {
     if (!File.Exists(assemblyPath))
     {
         throw new FileNotFoundException("Imported assembly does not exist.", assemblyPath);
     }
     assemblyDirectory = Path.GetDirectoryName(assemblyPath);
     AllTypes          = LoadTypes();
     PublicClasses     = ApplyIncludeExcludeRules(AllTypes.Where(t => IsObjCClassCandidate(t)));
     PublicStructs     = ApplyIncludeExcludeRules(AllTypes.Where(t => IsStructCandidate(t)));
     PublicProtocols   = ApplyIncludeExcludeRules(AllTypes.Where(t => IsObjCProtocolCandidate(t)));
     PublicEnums       = ApplyIncludeExcludeRules(AllTypes.Where(t => t.IsPublic && t.IsEnum));
 }
Example #7
0
        private void RefreshInterfaceMap(IEnumerable <TypeDefinition> types)
        {
            var mapDelta = AllTypes.Where(x => x.Interfaces.Any())
                           .SelectMany(x => x.Interfaces.Select(y => new { i = y, t = x }))
                           .ToLookup(x => x.i, x => x.t, comparer);

            foreach (var item in mapDelta)
            {
                var implementations = InterfaceMap.GetValue(item.Key) ?? new HashSet <TypeDefinition>(comparer);
                implementations.UnionWith(item);
                InterfaceMap[item.Key] = implementations;
            }
        }
Example #8
0
        /// <summary>
        /// Discovers the types.
        /// </summary>
        protected void DiscoverTypes()
        {
            FailedAssemblies.Clear();

            var assemblies = GetComposablePartAssemblies().ToList();

            foreach (var assembly in assemblies)
            {
                Logger.Info("Loading {0}", assembly.FullName);
            }

            AllTypes = assemblies.SelectMany(GetTypes).ToArray();

            AllConcreteTypes = AllTypes.Where(t => t.IsClass && !t.IsAbstract && !t.IsInterface && !t.IsGenericType).ToArray();
        }
Example #9
0
    static EndpointConfiguration FilterNamespace1(string endpointName)
    {
        var mainConfig     = new EndpointConfiguration(endpointName);
        var typesToExclude = AllTypes.Where(t => t.Namespace == "DataDistribution").ToArray();

        mainConfig.ExcludeTypes(typesToExclude);

        #region FilterNamespace1

        var transport   = mainConfig.UseTransport <MsmqTransport>();
        var mainRouting = transport.Routing();

        #endregion

        mainRouting.RouteToEndpoint(typeof(PlaceOrder), "Samples.DataDistribution.Server");
        mainRouting.RegisterPublisher(typeof(OrderAccepted), "Samples.DataDistribution.Server");
        ApplyDefaults(mainConfig);
        return(mainConfig);
    }
Example #10
0
    static EndpointConfiguration FilterNamespace2(string endpointName)
    {
        var distributionConfig = new EndpointConfiguration($"{endpointName}.{GetUniqueDataDistributionId()}");

        #region FilterNamespace2

        var typesToExclude = AllTypes
                             .Where(t => t.Namespace != "DataDistribution")
                             .ToArray();
        distributionConfig.ExcludeTypes(typesToExclude);

        #endregion

        var transport = distributionConfig.UseTransport <MsmqTransport>();
        var routing   = transport.Routing();
        routing.RegisterPublisher(
            publisherEndpoint: "Samples.DataDistribution.Server",
            eventType: typeof(OrderAccepted));
        ApplyDefaults(distributionConfig);
        return(distributionConfig);
    }
Example #11
0
        protected virtual void WriteNestedTypes()
        {
            if (NestedTypes != null && NestedTypes.Any())
            {
                if (!Emitter.IsNewLine)
                {
                    WriteNewLine();
                }

                var    typeDef = Emitter.GetTypeDefinition();
                string name    = Emitter.Validator.GetCustomTypeName(typeDef, Emitter, true);
                if (name.IsEmpty())
                {
                    name = H5Types.ToJsName(TypeInfo.Type, Emitter, true, true, nomodule: true);
                }

                Write("module ");
                Write(name);
                WriteSpace();
                BeginBlock();

                var last = NestedTypes.LastOrDefault();
                foreach (var nestedType in NestedTypes)
                {
                    Emitter.Translator.EmitNode = nestedType.TypeDeclaration;

                    if (nestedType.IsObjectLiteral)
                    {
                        continue;
                    }

                    ITypeInfo typeInfo;

                    if (Emitter.TypeInfoDefinitions.ContainsKey(nestedType.Key))
                    {
                        typeInfo = Emitter.TypeInfoDefinitions[nestedType.Key];

                        nestedType.Module       = typeInfo.Module;
                        nestedType.FileName     = typeInfo.FileName;
                        nestedType.Dependencies = typeInfo.Dependencies;
                        typeInfo = nestedType;
                    }
                    else
                    {
                        typeInfo = nestedType;
                    }

                    Emitter.TypeInfo = nestedType;

                    var nestedTypes = AllTypes.Where(t => t.ParentType == nestedType);
                    new ClassBlock(Emitter, Emitter.TypeInfo, nestedTypes, AllTypes, Namespace).Emit();
                    WriteNewLine();
                    if (nestedType != last)
                    {
                        WriteNewLine();
                    }
                }

                EndBlock();
            }
        }
Example #12
0
        public string GetCode(MetadataTypes metadata, IRequest request, INativeTypesMetadata nativeTypes)
        {
            var typeNamespaces = new HashSet <string>();
            var includeList    = metadata.RemoveIgnoredTypes(Config);

            metadata.Types.Each(x => typeNamespaces.Add(x.Namespace));
            metadata.Operations.Each(x => typeNamespaces.Add(x.Request.Namespace));

            var defaultImports = !Config.DefaultImports.IsEmpty()
                ? Config.DefaultImports
                : DefaultImports;

            var globalNamespace = Config.GlobalNamespace;

            string defaultValue(string k) => request.QueryString[k].IsNullOrEmpty() ? "//" : "";

            var sbInner = StringBuilderCache.Allocate();
            var sb      = new StringBuilderWrapper(sbInner);

            sb.AppendLine("/* Options:");
            sb.AppendLine("Date: {0}".Fmt(DateTime.Now.ToString("s").Replace("T", " ")));
            sb.AppendLine("Version: {0}".Fmt(Env.VersionString));
            sb.AppendLine("Tip: {0}".Fmt(HelpMessages.NativeTypesDtoOptionsTip.Fmt("//")));
            sb.AppendLine("BaseUrl: {0}".Fmt(Config.BaseUrl));
            if (Config.UsePath != null)
            {
                sb.AppendLine("UsePath: {0}".Fmt(Config.UsePath));
            }

            sb.AppendLine();
            sb.AppendLine("{0}GlobalNamespace: {1}".Fmt(defaultValue("GlobalNamespace"), Config.GlobalNamespace));

            sb.AppendLine("{0}MakePropertiesOptional: {1}".Fmt(defaultValue("MakePropertiesOptional"), Config.MakePropertiesOptional));
            sb.AppendLine("{0}AddServiceStackTypes: {1}".Fmt(defaultValue("AddServiceStackTypes"), Config.AddServiceStackTypes));
            sb.AppendLine("{0}AddResponseStatus: {1}".Fmt(defaultValue("AddResponseStatus"), Config.AddResponseStatus));
            sb.AppendLine("{0}AddImplicitVersion: {1}".Fmt(defaultValue("AddImplicitVersion"), Config.AddImplicitVersion));
            sb.AppendLine("{0}AddDescriptionAsComments: {1}".Fmt(defaultValue("AddDescriptionAsComments"), Config.AddDescriptionAsComments));
            sb.AppendLine("{0}IncludeTypes: {1}".Fmt(defaultValue("IncludeTypes"), Config.IncludeTypes.Safe().ToArray().Join(",")));
            sb.AppendLine("{0}ExcludeTypes: {1}".Fmt(defaultValue("ExcludeTypes"), Config.ExcludeTypes.Safe().ToArray().Join(",")));
            sb.AppendLine("{0}DefaultImports: {1}".Fmt(defaultValue("DefaultImports"), defaultImports.Join(",")));

            sb.AppendLine("*/");
            sb.AppendLine();

            string lastNS = null;

            var existingTypes = new HashSet <string>();

            var requestTypes    = metadata.Operations.Select(x => x.Request).ToHashSet();
            var requestTypesMap = metadata.Operations.ToSafeDictionary(x => x.Request);
            var responseTypes   = metadata.Operations
                                  .Where(x => x.Response != null)
                                  .Select(x => x.Response).ToHashSet();
            var types = metadata.Types.CreateSortedTypeList();

            AllTypes = metadata.GetAllTypesOrdered();
            AllTypes.RemoveAll(x => x.IgnoreType(Config, includeList));
            AllTypes = FilterTypes(AllTypes);

            //TypeScript doesn't support reusing same type name with different generic airity
            var conflictPartialNames = AllTypes.Map(x => x.Name).Distinct()
                                       .GroupBy(g => g.LeftPart('`'))
                                       .Where(g => g.Count() > 1)
                                       .Select(g => g.Key)
                                       .ToList();

            this.conflictTypeNames = AllTypes
                                     .Where(x => conflictPartialNames.Any(name => x.Name.StartsWith(name)))
                                     .Map(x => x.Name);

            foreach (var import in defaultImports)
            {
                var pos = import.IndexOf(':');
                sb.AppendLine(pos == -1
                    ? $"import {import};"
                    : $"import {{ {import.Substring(0, pos)} }} from \"{import.Substring(pos + 1).StripQuotes()}\";");
            }

            if (!string.IsNullOrEmpty(globalNamespace))
            {
                var moduleDef = Config.ExportAsTypes ? "export " : "declare ";
                sb.AppendLine();
                sb.AppendLine("{0}module {1}".Fmt(moduleDef, globalNamespace.SafeToken()));
                sb.AppendLine("{");

                sb = sb.Indent();
            }

            var insertCode = InsertCodeFilter?.Invoke(AllTypes, Config);

            if (insertCode != null)
            {
                sb.AppendLine(insertCode);
            }

            //ServiceStack core interfaces
            foreach (var type in AllTypes)
            {
                var fullTypeName = type.GetFullName();
                if (requestTypes.Contains(type))
                {
                    if (!existingTypes.Contains(fullTypeName))
                    {
                        MetadataType response = null;
                        if (requestTypesMap.TryGetValue(type, out var operation))
                        {
                            response = operation.Response;
                        }

                        lastNS = AppendType(ref sb, type, lastNS,
                                            new CreateTypeOptions
                        {
                            Routes       = metadata.Operations.GetRoutes(type),
                            ImplementsFn = () =>
                            {
                                if (!Config.AddReturnMarker &&
                                    operation?.ReturnsVoid != true &&
                                    operation?.ReturnType == null)
                                {
                                    return(null);
                                }

                                if (operation?.ReturnsVoid == true)
                                {
                                    return(nameof(IReturnVoid));
                                }
                                if (operation?.ReturnType != null)
                                {
                                    return(Type("IReturn`1", new[] { Type(operation.ReturnType) }));
                                }
                                return(response != null
                                        ? Type("IReturn`1", new[] { Type(response.Name, response.GenericArgs) })
                                        : null);
                            },
                            IsRequest = true,
                        });

                        existingTypes.Add(fullTypeName);
                    }
                }
                else if (responseTypes.Contains(type))
                {
                    if (!existingTypes.Contains(fullTypeName) &&
                        !Config.IgnoreTypesInNamespaces.Contains(type.Namespace))
                    {
                        lastNS = AppendType(ref sb, type, lastNS,
                                            new CreateTypeOptions
                        {
                            IsResponse = true,
                        });

                        existingTypes.Add(fullTypeName);
                    }
                }
                else if (types.Contains(type) && !existingTypes.Contains(fullTypeName))
                {
                    lastNS = AppendType(ref sb, type, lastNS,
                                        new CreateTypeOptions {
                        IsType = true
                    });

                    existingTypes.Add(fullTypeName);
                }
            }

            var addCode = AddCodeFilter?.Invoke(AllTypes, Config);

            if (addCode != null)
            {
                sb.AppendLine(addCode);
            }

            if (!string.IsNullOrEmpty(globalNamespace))
            {
                sb = sb.UnIndent();
                sb.AppendLine();
                sb.AppendLine("}");
            }

            sb.AppendLine(); //tslint

            return(StringBuilderCache.ReturnAndFree(sbInner));
        }