/// <summary>
        /// Defines the fully qualified base type name for the class model.
        /// </summary>
        /// <param name="source">The source interface model to generate the type name from.</param>
        /// <param name="manager">Namespace manager used to format type names.This is an optional parameter.</param>
        /// <returns>The full type name or null if model data was missing.</returns>
        public static string CSharpFormatBaseTypeName(this CsClass source, NamespaceManager manager = null)
        {
            if (source == null)
            {
                return(null);
            }
            if (!source.IsLoaded)
            {
                return(null);
            }

            StringBuilder baseNameBuilder  = new StringBuilder();
            var           namespaceManager = manager ?? new NamespaceManager(null);

            var targetNamespace = namespaceManager.AppendingNamespace(source.Namespace);

            baseNameBuilder.Append(targetNamespace == null ? source.Name : $"{targetNamespace}.{source.Name}");


            if (source.IsGeneric)
            {
                baseNameBuilder.Append(
                    source.GenericParameters.CSharpFormatGenericParametersSignature(namespaceManager));
            }

            return(baseNameBuilder.ToString());
        }
Beispiel #2
0
        public static string GeneratePartialClass(CsClass source, NamespaceManager manager = null)
        {
            if (source == null)
            {
                return(null);
            }
            if (!source.IsLoaded)
            {
                return(null);
            }
            SourceFormatter formatter = new SourceFormatter();

            StringBuilder classBuilder = new StringBuilder($"{source.Security.CSharpFormatKeyword()} partial {Keywords.Class} {source.Name}");

            if (source.IsGeneric)
            {
                classBuilder.Append(source.GenericParameters.CSharpFormatGenericParametersSignature(manager));
            }

            formatter.AppendCodeLine(0);
            formatter.AppendCodeLine(0, $"namespace {source.Namespace}");
            formatter.AppendCodeLine(0, "{");
            formatter.AppendCodeLine(0);
            formatter.AppendCodeLine(1, classBuilder.ToString());
            formatter.AppendCodeLine(1, "{");
            formatter.AppendCodeLine(1);
            formatter.AppendCodeLine(1, "}");
            formatter.AppendCodeLine(0);
            formatter.AppendCodeLine(0, "}");
            return(formatter.ReturnSource());
        }
Beispiel #3
0
        private static TsFile RewriteController(CsClass controllerType)
        {
            var name = controllerType.Name.Replace("Controller", "Api");

            return(new TsFile
            {
                Name = name,
                Directory =
                    controllerType.Namespace.Replace('.', Path.DirectorySeparatorChar),
                Declarations = new[]
                {
                    new TsNamespace
                    {
                        Name = name,
                        ExportKind = TsExportKind.Named,
                        Declarations = controllerType
                                       .Members
                                       .OfType <CsMethod>()
                                       .Where(x => x.AccessModifier ==
                                              CsAccessModifier.Public &&
                                              !x.IsStatic)
                                       .Select(RewriteMethod)
                                       .ToArray()
                    }
                }
            });
        }
Beispiel #4
0
        protected virtual TsInterface Rewrite(CsClass csClass)
        {
            var properties = csClass.Members
                             .Where(x => !x.IsStatic)
                             .OfType <CsProperty>()
                             .Select(Rewrite)
                             .ToArray();

            var fields = csClass.Members
                         .OfType <CsField>()
                         .Select(Rewrite)
                         .ToArray();

            return(new TsInterface
            {
                CsType = csClass.CsType,
                Name = csClass.Name,
                ExportKind = TsExportKind.Named,
                TypeParameters = csClass.TypeParameters,
                Base = csClass.CsType.OriginalType.BaseType == typeof(object)
                                  ? Array.Empty <TsType>()
                                  : new[]
                {
                    TsType.From(new CsType(csClass.CsType.OriginalType
                                           .BaseType))
                },
                Properties = properties.Concat(fields).ToArray()
            });
        }
Beispiel #5
0
        /// <summary>
        /// Extension method that determines if a target class inherits a target base class.
        /// </summary>
        /// <param name="source">The source class to check for inheritance.</param>
        /// <param name="name">The name of the inherited class</param>
        /// <param name="nameSpace">Optional parameter for the namespace of the inherited class.</param>
        /// <returns>True if the class is inherited or false if not.</returns>
        public static bool InheritsBaseClass(this CsClass source, string name, string nameSpace = null)
        {
            if (source == null)
            {
                return(false);
            }
            if (!source.IsLoaded)
            {
                return(false);
            }
            if (string.IsNullOrEmpty(name))
            {
                return(false);
            }

            var baseClass = source.BaseClass;

            if (baseClass == null)
            {
                return(false);
            }

            bool result = nameSpace == null
                ? baseClass.Name == name
                : (baseClass.Namespace == nameSpace & baseClass.Name == name);

            if (!result & baseClass.BaseClass != null)
            {
                result = baseClass.InheritsBaseClass(name, nameSpace);
            }

            return(result);
        }
        /// <summary>
        /// Gets all the members that are part of the contract definition that is missing.
        /// </summary>
        /// <param name="source">target class to implement the contract on.</param>
        /// <param name="missingMembers">All missing members.</param>
        /// <returns>Null or the contract members that are missing.</returns>
        public static IEnumerable <CsMember> MissingContractMembers(CsClass source, IEnumerable <CsMember> missingMembers)
        {
            if (source == null)
            {
                return(null);
            }
            if (missingMembers == null)
            {
                return(null);
            }
            if (!missingMembers.Any())
            {
                return(null);
            }

            var contract          = GetContract(source);
            var contractInterface = contract.contract;

            if (contractInterface == null)
            {
                return(null);
            }

            var contractMembers = contractInterface.Members;

            var contractHashCodes = contractMembers.Select(member => member.FormatCSharpMemberComparisonHashCode(MemberComparisonType.Full)).ToList();

            var result = new List <CsMember>();

            return(missingMembers.Where(m => contractHashCodes.Contains(m.FormatCSharpMemberComparisonHashCode(MemberComparisonType.Full))).ToList());
        }
        public void MakeExtensionMethod(CsClass target)
        {
            if (EnumOptions is null)
            {
                return;
            }

            var paramValue = target.GetTypeName(TypeName);

            var writer = CsCodeWriter.Create <ShellEnumOptionsGenerator>();

            writer.Open("switch (value)");
            foreach (var i in EnumOptions.Items)
            {
                var line = $"case {paramValue}.{i.CsValue}: return {i.LinuxValue.CsEncode()};";
                writer.WriteLine(line);
            }

            var notSupportedException = target.GetTypeName <NotSupportedException>();

            writer.WriteLine($"default: throw new {notSupportedException}();");
            writer.Close();

            var parameter = new CsMethodParameter("value", paramValue)
            {
                UseThis = target.IsStatic
            };

            target.AddMethod(extensionMethodName, "string")
            .WithBody(writer)
            .WithStatic()
            .WithParameter(parameter);
        }
        /// <summary>
        /// Determines if the class supports the MVC controller base class.
        /// </summary>
        /// <param name="sourceClass"></param>
        /// <returns></returns>
        public static bool IsController(CsClass sourceClass)
        {
            var baseClass = sourceClass?.BaseClass;

            if (baseClass == null)
            {
                return(false);
            }

            if (sourceClass.Namespace != AspNetConstants.MvcNamespace)
            {
                return(false);
            }

            if (sourceClass.Name == AspNetConstants.ControllerBaseClassName)
            {
                return(true);
            }

            bool isBaseClass = false;

            if (baseClass.BaseClass != null)
            {
                isBaseClass = IsController(baseClass);
            }

            return(isBaseClass);
        }
Beispiel #9
0
        protected virtual TsInterface Rewrite(CsClass csClass)
        {
            var properties = csClass.Members
                             .Where(x => !x.IsStatic)
                             .OfType <CsProperty>()
                             .Select(Rewrite)
                             .ToArray();

            var fields = csClass.Members
                         .OfType <CsField>()
                         .Select(Rewrite)
                         .ToArray();

            var baseTypes = new List <Type>();

            if (csClass.CsType.OriginalType.BaseType != typeof(object))
            {
                baseTypes.Add(csClass.CsType.OriginalType.BaseType);
            }

            baseTypes.AddRange(GetInterfaces(csClass.CsType.OriginalType, false));

            return(new TsInterface
            {
                CsType = csClass.CsType,
                Name = csClass.Name,
                ExportKind = TsExportKind.Named,
                TypeParameters = csClass.TypeParameters,
                Base = baseTypes.Select(x => TsType.From(new CsType(x))).ToArray(),
                Properties = properties.Concat(fields).ToArray()
            });
        }
Beispiel #10
0
        public static void Add_FromMethods(Type t, XValueTypeName valueTypeName,
                                           TypesGroup types, CsClass target, IRelatedUnitDefinition u)
        {
#if DEBUG
            if (target.Name == "Power")
            {
                System.Diagnostics.Debug.Write("");
            }
#endif
            foreach (var inputType in "decimal,double,int,long".Split(','))
            {
                var arg = "value";
                if (inputType == OtherValuePropertyType)
                {
                    arg = $"({ValuePropertyType}){arg}";
                }

                var args = new CsArguments(arg, types.Container + "." + u.FieldName)
                           .Create(target.Name);
                var valueIn           = $" value in {u.UnitShortCode.EffectiveValue}";
                var methodName        = "From" + u.FromMethodNameSufix.CoalesceNullOrWhiteSpace(u.FieldName);
                var methodDescription = $"creates {types.Value.FirstLower()} from{valueIn}";

                var cw = Ext.Create(t);
                cw.WriteReturn(args);
                var m = target.AddMethod(methodName, target.Name, methodDescription)
                        .WithStatic()
                        .WithBody(cw);
                m.AddParam("value", inputType).Description = string.Format("{0}{1}", valueTypeName, valueIn);
            }
        }
Beispiel #11
0
        private static void AddEnumToOutput(string[] parts, CsNamespace ns, CsEnum en)
        {
            if (!parts.Any())
            {
                ns.AddEnum(en);
                return;
            }

            CsClass cl = null;

            foreach (var ii in parts)
            {
                CsClass newClass;
                if (cl is null)
                {
                    newClass = ns.GetOrCreateClass(ii);
                }
                else
                {
                    newClass = cl.GetOrCreateNested(ii);
                }

                cl = newClass;
            }

            throw new NotSupportedException("Need nested enum which is not supported by isukces.code yet");
        }
Beispiel #12
0
        public static CsMethod AddOperator(this CsClass cl, string operatorName, CsArguments csArgument, string resultType = null)
        {
            resultType = resultType.CoalesceNullOrWhiteSpace(cl.Name);
            var code = csArgument.Create(resultType);

            return(cl.AddMethod(operatorName, resultType, "implements " + operatorName + " operator")
                   .WithBodyFromExpression(code));
        }
 public string GetTypeName(CsClass str, NamespaceAndName valueEnumTypeName)
 {
     if (FixedType != null)
     {
         return(str.GetTypeName(FixedType));
     }
     return(str.GetTypeName(valueEnumTypeName));
 }
Beispiel #14
0
        public static TheClass Get(CsNode pNode, FactoryExpressionCreator pCreator)
        {
            if (pNode == null)
            {
                return(null);
            }

            CsExpression csExpression = pNode as CsExpression;

            if (csExpression != null && csExpression.ec != expression_classification.ec_nothing)
            {
                return(Get((CsEntity)csExpression.entity, pCreator));
            }

            while (pNode != null)
            {
                if (pNode is CsTypeRef || pNode is CsClass || pNode is CsInterface)
                {
                    break;
                }

                pNode = pNode.parent;
            }

            CsClass klass = pNode as CsClass;

            if (klass != null)
            {
                if (!_classes.ContainsKey(klass))
                {
                    _classes[klass] = new TheClass(klass, pCreator);
                }

                return(_classes[klass]);
            }

            CsTypeRef csTypeRef = pNode as CsTypeRef;

            if (csTypeRef != null)
            {
                return(csTypeRef.entity_typeref == null ? null : Get((CsEntityClass)(csTypeRef.entity_typeref.u), pCreator));
            }

            CsInterface csInterface = pNode as CsInterface;

            if (csInterface != null)
            {
                if (!_interfaces.ContainsKey(csInterface))
                {
                    _interfaces[csInterface] = new TheClass(csInterface, pCreator);
                }

                return(_interfaces[csInterface]);
            }

            throw new Exception();
        }
Beispiel #15
0
 private static IEnumerable <string> GetListTypes2(CsClass cl)
 {
     return(new[]
     {
         "IList",
         "IEnumerable",
         "NdArray"
     });
 }
Beispiel #16
0
 private static IEnumerable <string> GetListTypes(CsClass cl)
 {
     return(new[]
     {
         cl.TypeName(typeof(IList <double>)),
         cl.TypeName(typeof(IEnumerable <double>)),
         "NdArray<double>"
     });
 }
        private static void AddToStringMethod(CsClass cl, KeysGeneratorDef def)
        {
            var m = cl.AddMethod(nameof(ToString), "string");

            m.Overriding = OverridingType.Override;
            var e = def.GetToStringExpression();

            m.Body = $"return {e};";
        }
 public OneArgMethodGenerator(string dotnetName, string pyName, CsClass cl)
 {
     _cl = cl;
     if (pyName == null)
     {
         pyName = dotnetName.ToLower();
     }
     DotnetName = dotnetName;
     PyName     = pyName;
 }
Beispiel #19
0
        private async Task <CsSource> AddMethodMember(CsClass targetClass, CsMethod member, bool logging, bool cdf, bool cdfAspNet, string targetFilePath, NamespaceManager manager)
        {
            CsSource result     = null;
            string   sourceCode = null;

            if (cdfAspNet)
            {
                if (WebApiSupport.IsControllerAction(member))
                {
                    sourceCode = CSharpSourceGenerationCommonDeliveryFramework.GenerateControllerActionMethodSourceCode(member,
                                                                                                                        manager, true, true, CsSecurity.Public, logging, "_logger");
                }
                else
                {
                    sourceCode = CSharpSourceGenerationCommonDeliveryFramework.GenerateStandardMethodSourceCode(member,
                                                                                                                manager, true, true, CsSecurity.Public, logging, "_logger");
                }
            }
            else
            {
                if (cdf)
                {
                    sourceCode = CSharpSourceGenerationCommonDeliveryFramework.GenerateStandardMethodSourceCode(member,
                                                                                                                manager, true, true, CsSecurity.Public, logging, "_logger");
                }
                else
                {
                    if (logging)
                    {
                        sourceCode = CSharpSourceGenerationNetCommon.GenerateStandardMethodSourceCode(member,
                                                                                                      manager, true, true, CsSecurity.Public, true, "_logger");
                    }
                    else
                    {
                        sourceCode = CSharpSourceGenerationCommon.GenerateStandardMethodSourceCode(member,
                                                                                                   manager, true, true);
                    }
                }
            }

            if (string.IsNullOrEmpty(sourceCode))
            {
                throw new CodeFactoryException("Was not able to generate the source code for the member method.");
            }

            result = await targetClass.AddToEndAsync(targetFilePath, CsSourceFormatter.IndentCodeBlock(2, sourceCode));

            if (result == null)
            {
                throw new CodeFactoryException("Could not load the source code after adding the member.");
            }

            return(result);
        }
Beispiel #20
0
 private static void Add_Atan2(CsClass cl)
 {
     TwoArgs(cl, nameof(Math.Atan2), "arctan2", "y", "x",
             (cf, type1, type2) =>
     {
         var xx = IsNdArray(type2) ? "x.AsEnumerable()" : "x";
         var yy = IsNdArray(type1) ? "y.AsEnumerable()" : "y";
         cf.Writeln("return " + xx + ".Zip(" + yy +
                    ", (a, b) => new {X = a, Y = b}).PyMap(q => Math.Atan2(q.Y, q.X));");
     });
 }
Beispiel #21
0
 private static void Add_Hypot(CsClass cl)
 {
     TwoArgs(cl, "Hypot", null, "x", "y",
             (cf, type1, type2) =>
     {
         var xx = IsNdArray(type1) ? "x.AsEnumerable()" : "x";
         var yy = IsNdArray(type2) ? "y.AsEnumerable()" : "y";
         cf.Writeln(
             "return " + xx + ".Zip(" + yy +
             ", (a, b) => new {X = a, Y = b}).PyMap(q => Math.Sqrt(q.Y * q.Y + q.X * q.X));");
     });
 }
Beispiel #22
0
        protected void Save(CsFile file, CsClass cl, params string[] subDirs)
        {
            var a = new List <string> {
                BasePath.FullName
            };

            a.AddRange(subDirs);
            a.Add(cl.GetShortName());
            var fileName = Path.Combine(a.ToArray());

            file.SaveIfDifferent(fileName);
        }
Beispiel #23
0
 private static TsTypeMember[] GetProperties(CsClass csClass)
 {
     return(csClass.Members
            .OfType <CsProperty>()
            .Select(p => new TsPropertySignature
     {
         Name = p.Name,
         Type = TsType.From(p.Type),
         Optional = false
     })
            .ToArray());
 }
Beispiel #24
0
        private void Add_ArrayMethods(CsClass cl)
        {
            /* [DirectCall("array")]
             * public static NdArray2D<int> Array(
             *  IEnumerable<IEnumerable<int>> obj,
             *  bool             copy  = true,
             *  NumpyArrayOrder  order = NumpyArrayOrder.K)
             * {
             *  return NdArray.Make(obj, copy, order);
             * }*/

            var f = CreateFile();

            f.AddImportNamespace("System.Collections.Generic");
            f.AddImportNamespace("System.Linq");
            for (var dimension = 1; dimension <= MaxDim; dimension++)
            {
                NdArrayLevel1Generator.Generate(f, dimension);
                foreach (var wrappedType in NumpyArrayWrappedTypes)
                {
                    var classLevel2 = NdArrayLevel2Generator.Generate(f, dimension, wrappedType);
                    var resultType  = classLevel2.Name;
                    var m           = cl.AddMethod("Array" + dimension, resultType)
                                      .WithDirectCall("array")
                                      .WithStatic()
                                      .WithBodyComment($"Generated by {nameof(NumpyGenerator)}.{nameof(Add_ArrayMethods)}/1")
                                      .WithBody($"return new {resultType}(obj, copy, order);");
                    NdArrayLevel2Generator.WithAddParams(m, wrappedType, dimension);
                }

                // other types
                {
                    const string wrappedType = "T";
                    // var          classLevel2 = NdArrayLevel2Generator.Generate(f, dimension, wrappedType);
                    foreach (var i in new[] { true })
                    {
                        var resultType = $"NdArray{dimension}D<T>";
                        var m          = cl.AddMethod("Array" + (i ? $"{dimension}" : "") + "<T>", resultType)
                                         .WithDirectCall("array")
                                         .WithStatic()
                                         .WithBodyComment($"Generated by {nameof(NumpyGenerator)}.{nameof(Add_ArrayMethods)}/2")
                                         .WithBody($"return new {resultType}(obj, copy, order);");
                        NdArrayLevel2Generator.WithAddParams(m, wrappedType, dimension);
                    }
                }
            }

            var fileName = Path.Combine(BasePath.FullName, "Lang.Python", "+compatibility", "Numpy", "NdArray.Auto.cs");

            f.SaveIfDifferent(fileName);
        }
Beispiel #25
0
        private static List <CsClass> ParseCsFile(ProjectInSolution solutionProject, ProjectItemElement csFile)
        {
            var        filePath          = csFile.Include;
            var        fileAbsolutePath  = Path.Combine(Path.GetDirectoryName(solutionProject.AbsolutePath), filePath);
            var        source            = File.ReadAllText(fileAbsolutePath);
            SyntaxTree projectSyntaxTree = CSharpSyntaxTree.ParseText(source);
            var        projectTree       = (CompilationUnitSyntax)projectSyntaxTree.GetRoot();

            var namespaceTree = projectTree.Members.OfType <NamespaceDeclarationSyntax>().SingleOrDefault();

            var csFileClasses = new List <CsClass>();

            if (namespaceTree == null)
            {
                return(csFileClasses);
            }

            foreach (var classTree in namespaceTree.Members.OfType <ClassDeclarationSyntax>())
            {
                if (classTree.BaseList?.Types == null)
                {
                    continue;
                }

                foreach (var baseType in classTree.BaseList?.Types.OfType <SimpleBaseTypeSyntax>())
                {
                    var props = classTree.Members.OfType <PropertyDeclarationSyntax>()
                                .Select(x => new CsProperty()
                    {
                        Name = x.Identifier.ToString(), Type = x.Type.ToString()
                    });

                    var methods = classTree.Members.OfType <MethodDeclarationSyntax>()
                                  .Select(x => ParseMethod(x));

                    var csClass = new CsClass()
                    {
                        Name       = classTree.Identifier.ToString(),
                        ParentName = baseType?.Type.ToString(),
                        Properties = props,
                        Methods    = methods
                    };

                    csFileClasses.Add(csClass);
                }
            }

            return(csFileClasses);
        }
Beispiel #26
0
        /// <summary>
        /// Checks the target class to see if it supports any subscriptions.
        /// </summary>
        /// <param name="source">Source class to check for subscriptions</param>
        /// <returns>List of the fields that need to be subscribed to.</returns>
        public static IReadOnlyList <CsField> GetSubscriptions(CsClass source)
        {
            if (source == null)
            {
                return(null);
            }
            if (!source.IsLoaded)
            {
                return(null);
            }

            var fields = source.Fields;

            if (!fields.Any())
            {
                return(null);
            }

            var resultFields = new List <CsField>();

            foreach (var csField in fields)
            {
                if (!csField.DataType.IsInterface)
                {
                    continue;
                }

                var fieldInterface = csField.DataType.GetInterfaceModel();
                if (fieldInterface == null)
                {
                    continue;
                }
                if (!fieldInterface.IsLoaded)
                {
                    continue;
                }

                var contractType = ContractType(fieldInterface);

                if (contractType.controller | contractType.abstraction | contractType.presenter)
                {
                    resultFields.Add(csField);
                }
            }

            return(resultFields.Any() ? resultFields.ToImmutableList(): null);
        }
        private static void AddOperatorMethod(CsClass cl, MulDivDefinition i)
        {
            var l     = Gv(i.Left, "left");
            var r     = Gv(i.Right, "right");
            var value = $"{l} {i.Operator} {r}";

            if (!i.Result.Equals(UnitDefinition.Scalar))
            {
                value = $"new {i.Result.ClassName}({value})";
            }
            var m = cl.AddMethod(i.Operator, i.Result.ClassName)
                    .WithBody($"return {value};");

            m.AddParam("left", i.Left.ClassName);
            m.AddParam("right", i.Right.ClassName);
            m.Description = i.Description;
        }
Beispiel #28
0
 private static void Add_Degrees_Radians(CsClass cl)
 {
     for (var i = 0; i < 2; i++)
     {
         var c = i == 0
             ? "const double mul = 180.0 / Math.PI;"
             : "const double mul = Math.PI / 180.0;";
         OneArg(cl, i == 0 ? "Degrees" : "Radians", null, q =>
         {
             var cf = new CodeFormatter();
             cf.Writeln(c);
             var map = q.Map("# * mul");
             cf.Writeln("return " + map + ";");
             q.Make(cf.Text);
         });
     }
 }
Beispiel #29
0
        /// <summary>
        /// Defines the transient registration statement that will register the class.
        /// </summary>
        /// <param name="classData">The class model to get the registration from.</param>
        /// <param name="serviceCollectionParameterName">The name of the service collection parameter that the transient is being made to.</param>
        /// <param name="manager">Optional parameter that contains the namespace manager that contains the known using statements and target namespace for the class that will host this registration data.</param>
        /// <returns>The formatted transient registration call or null if the class does not meet the criteria.</returns>
        private static string FormatTransientRegistration(CsClass classData, string serviceCollectionParameterName, NamespaceManager manager = null)
        {
            //Cannot find the class data will return null
            if (classData == null)
            {
                return(null);
            }

            string registrationType = null;
            string classType        = null;

            ICsMethod constructorData = classData.Constructors.FirstOrDefault();

            //Confirming we have a constructor
            if (constructorData == null)
            {
                return(null);
            }

            //Getting the fully qualified type name for the formatters library for the class.
            classType = classData.CSharpFormatBaseTypeName(manager);

            //if we are not able to format the class name correctly return null.
            if (classType == null)
            {
                return(null);
            }

            //Assuming the first interface inherited will be used for dependency injection if any are provided.
            if (classData.InheritedInterfaces.Any())
            {
                CsInterface interfaceData = classData.InheritedInterfaces.FirstOrDefault();

                if (interfaceData != null)
                {
                    registrationType = interfaceData.CSharpFormatInheritanceTypeName(manager);
                }
            }

            //Creating statement to add the the container.
            string diStatement = registrationType != null
                ? $"{serviceCollectionParameterName}.AddTransient<{registrationType},{classType}>();" :
                                 $"{serviceCollectionParameterName}.AddTransient<{classType}>();";

            return(diStatement);
        }
Beispiel #30
0
        /// <summary>
        /// Checks class data to determine if it qualifies for transient dependency injection.
        /// - Checks to make sure the class only has 1 interface defined.
        /// - Checks to see the class only has 1 constructor defined.
        /// - Checks to see if the class is a asp.net controller if it it remove it
        /// - Checks to see the class name is a startup class if so will be removed.
        /// - Confirms the constructor has no well known types if so will be removed.
        /// </summary>
        /// <param name="classData">The class data to check.</param>
        /// <returns>Boolean state if it qualifies.</returns>
        public static bool IsTransientClass(CsClass classData)
        {
            if (classData == null)
            {
                return(false);
            }

            if (classData.IsStatic)
            {
                return(false);
            }
            if (classData.InheritedInterfaces.Any())
            {
                if (classData.InheritedInterfaces.Count > 1)
                {
                    return(false);
                }
            }
            if (!classData.Constructors.Any())
            {
                return(false);
            }
            if (CsClassExtensions.IsController(classData))
            {
                return(false);
            }

            if (classData.Constructors.Count > 1)
            {
                return(false);
            }

            var constructor = classData.Constructors.FirstOrDefault(m => m.HasParameters);

            if (constructor == null)
            {
                return(false);
            }

            if (classData.Name == "Startup")
            {
                return(false);
            }

            return(!constructor.Parameters.Any(p => p.ParameterType.IsWellKnownType));
        }
Beispiel #31
0
		public static void Parse(CsClass pCsClass, CodeBuilder pBuilder, FactoryExpressionCreator pCreator) {
			ExtensionName = null;

			StringBuilder sb = new StringBuilder();
			CodeBuilder privateClasses = new CodeBuilder();

			TheClass myClass = TheClassFactory.Get(pCsClass, pCreator);

			IsMainClass = Helpers.HasAttribute(pCsClass.attributes, "JsMainClassAttribute");
			bool isResource = Helpers.HasAttribute(pCsClass.attributes, "JsEmbedAttribute");
			IsExtension = Helpers.HasAttribute(pCsClass.attributes, "JsExtensionAttribute");

			if (IsMainClass) {
				JsNamespaceParser.MainClassName = myClass.FullName;
				AttributeItem vals = Helpers.GetAttributeValue(pCsClass.attributes, "JsMainClassAttribute", pCreator)[0];
				sb.AppendFormat(@"[SWF(width=""{0}"", height=""{1}"", frameRate=""{2}"", backgroundColor=""{3}"")]",
				                vals.Parameters[0],
								vals.Parameters[1],
								vals.Parameters[2],
								vals.Parameters[3]
					);
				sb.AppendLine();
				sb.Append("\t");
			}

			if (isResource) {
				AttributeItem vals = Helpers.GetAttributeValue(pCsClass.attributes, "JsEmbedAttribute", pCreator)[0];

				string path = vals.Parameters[0] as String;
				if (!string.IsNullOrEmpty(path)) {
					path = Path.Combine(Project.Root, path);
					string ex = Path.GetExtension(path).Substring(1);
					string mimeType;

					if (vals.NamedArguments.ContainsKey("mimeType")) {
						mimeType = vals.NamedArguments["mimeType"].Value;

					} else {
						switch (ex) {
							case @"gif":
							case @"png":
							case @"jpg":
							case @"jpeg":
							case @"svg":
								mimeType = "image/" + ex;
								break;

							case @"mp3":
								mimeType = @"audio/mpeg";
								break;

							case @"swf":
								mimeType = @"application/x-shockwave-flash";
								break;

							case @"ttf":
							case @"otf":
								mimeType = @"application/x-font";
								break;

							default:
								mimeType = @"application/octet-stream";
								break;
						}
					}

					StringBuilder addParams = new StringBuilder();
					foreach (var item in vals.NamedArguments.Where(pItem => !pItem.Key.Equals("mimeType"))) {
						addParams.AppendFormat(@", {0}=""{1}""", item.Key, item.Value.Value);
					}

					sb.AppendFormat(@"[Embed(source=""{0}"", mimeType=""{1}""{2})]",
									path.Replace("\\", "\\\\"),
									mimeType,
									addParams
					);

					sb.AppendLine();
					sb.Append("\t");

				}
			}

			if (!IsExtension) {
				sb.AppendFormat("{1}class {0}",
							myClass.Name,
							JsHelpers.ConvertModifiers(myClass.Modifiers, _notValidClassMod));

				if (myClass.Extends.Count != 0) {
					sb.AppendFormat(" extends {0}", JsHelpers.Convert(myClass.Extends[0]));
				}

				if (myClass.Implements.Count != 0) {
					sb.Append(" implements ");
					foreach (string s in myClass.Implements) {
						sb.Append(JsHelpers.Convert(s));
						sb.Append(", ");
					}

					sb.Remove(sb.Length - 2, 2);
				}

				sb.Append(" {");
				sb.AppendLine();

				pBuilder.Append(sb.ToString());
				pBuilder.AppendLineAndIndent();
			}

			if (IsMainClass) {
				ImportStatementList.List.Add("flash.events.Event");
				pBuilder.AppendFormat(
									  @"public function {0}() {{
			if (stage) $ctor();
			else addEventListener(Event.ADDED_TO_STAGE, __loaded);
		}}

		private function __loaded(e:Event = null):void {{
			removeEventListener(Event.ADDED_TO_STAGE, __loaded);
			$ctor();
		}}
",
				                      myClass.Name);
				pBuilder.AppendLine();
			}

			if (pCsClass.member_declarations != null) {
				if (!myClass.IsPrivate)
					ImportStatementList.List.Add(myClass.NameSpace+".*");

				foreach (CsNode memberDeclaration in pCsClass.member_declarations) {
					if (memberDeclaration is CsConstructor) {
						MethodParser.Parse(myClass.GetConstructor((CsConstructor)memberDeclaration), pBuilder, pCreator);

					} else if (memberDeclaration is CsMethod) {
						MethodParser.Parse(myClass.GetMethod((CsMethod)memberDeclaration), pBuilder, pCreator);
						if (IsExtension && string.IsNullOrEmpty(ExtensionName)) {
							ExtensionName = ((CsMethod)memberDeclaration).identifier.identifier;
						}

					} else if (memberDeclaration is CsIndexer) {
						IndexerParser.Parse(myClass.GetIndexer((CsIndexer)memberDeclaration), pBuilder, pCreator);

					} else if (memberDeclaration is CsVariableDeclaration) {
						VariableParser.Parse(myClass.GetVariable((CsVariableDeclaration)memberDeclaration), pBuilder);

					} else if (memberDeclaration is CsConstantDeclaration) {
						ConstantParser.Parse(myClass.GetConstant((CsConstantDeclaration)memberDeclaration), pBuilder);

					} else if (memberDeclaration is CsDelegate) {
						DelegateParser.Parse(myClass.GetDelegate((CsDelegate)memberDeclaration), pBuilder);

					} else if (memberDeclaration is CsEvent) {
						EventParser.Parse(myClass.GetEvent(((CsEvent)memberDeclaration).declarators.First.Value.identifier.identifier), pBuilder);

					} else if (memberDeclaration is CsProperty) {
						PropertyParser.Parse(myClass.GetProperty((CsProperty)memberDeclaration), pBuilder, pCreator);

					} else if (memberDeclaration is CsClass) {
						Parse((CsClass)memberDeclaration, privateClasses, pCreator);

					} else {
						throw new NotSupportedException();
					}
				}
			}

			string imports = getImports();
			pBuilder.Replace(IMPORT_MARKER, imports);

			pBuilder.AppendLineAndUnindent("}");

			if (IsExtension) {
				return;
			}

			if (!myClass.IsPrivate) {
				pBuilder.AppendLineAndUnindent("}");
			}

			if (privateClasses.Length == 0) {
				return;
			}

			pBuilder.AppendLine();
			pBuilder.Append(JsNamespaceParser.Using);
			pBuilder.AppendLine(imports);
			pBuilder.Append(privateClasses);
		}