Exemplo n.º 1
0
        public void Constructor1_Deny_Unrestricted()
        {
            CodeTypeParameter ctp = new CodeTypeParameter("mono");

            Assert.AreEqual(0, ctp.Constraints.Count, "Constraints");
            Assert.AreEqual(0, ctp.CustomAttributes.Count, "CustomAttributes");
            Assert.IsFalse(ctp.HasConstructorConstraint, "HasConstructorConstraint");
            ctp.HasConstructorConstraint = true;
            Assert.AreEqual("mono", ctp.Name);
            ctp.Name = String.Empty;
        }
Exemplo n.º 2
0
        public static CodeMemberMethod Generic(this CodeMemberMethod method, string paramName,
                                               bool hasConstructor, params Type[] constraints)
        {
            var p = new CodeTypeParameter(paramName)
            {
                HasConstructorConstraint = hasConstructor
            };

            p.Constraints.AddRange(constraints.Select((t) => new CodeTypeReference(t)).ToArray());
            method.TypeParameters.Add(p);
            return(method);
        }
        public void Constructor1()
        {
            CodeTypeParameter tp1 = new CodeTypeParameter();
            CodeTypeParameter tp2 = new CodeTypeParameter();

            CodeTypeParameter[]         typeParams = new CodeTypeParameter[] { tp1, tp2 };
            CodeTypeParameterCollection coll       = new CodeTypeParameterCollection(
                typeParams);

            Assert.AreEqual(2, coll.Count, "#1");
            Assert.AreEqual(0, coll.IndexOf(tp1), "#2");
            Assert.AreEqual(1, coll.IndexOf(tp2), "#3");
        }
        public void Type_TypeParameters()
        {
            codeNamespace.Name = "SomeNS";

            CodeTypeDeclaration type = new CodeTypeDeclaration("SomeClass");

            codeNamespace.Types.Add(type);
            type.TypeParameters.Add(new CodeTypeParameter("T"));

            Assert.AreEqual(string.Format(CultureInfo.InvariantCulture,
                                          "{0}" +
                                          "Namespace SomeNS{0}" +
                                          "    {0}" +
                                          "    Public Class SomeClass(Of T){0}" +
                                          "    End Class{0}" +
                                          "End Namespace{0}", NewLine), Generate(), "#1");

            type.TypeParameters.Add(new CodeTypeParameter("As"));
            type.TypeParameters.Add(new CodeTypeParameter("New"));

            Assert.AreEqual(string.Format(CultureInfo.InvariantCulture,
                                          "{0}" +
                                          "Namespace SomeNS{0}" +
                                          "    {0}" +
                                          "    Public Class SomeClass(Of T, As, New){0}" +
                                          "    End Class{0}" +
                                          "End Namespace{0}", NewLine), Generate(), "#2");

            CodeTypeParameter typeParamR = new CodeTypeParameter("R");

            typeParamR.Constraints.Add(new CodeTypeReference(typeof(IComparable)));
            type.TypeParameters.Add(typeParamR);

            Assert.AreEqual(string.Format(CultureInfo.InvariantCulture,
                                          "{0}" +
                                          "Namespace SomeNS{0}" +
                                          "    {0}" +
                                          "    Public Class SomeClass(Of T, As, New, R As System.IComparable){0}" +
                                          "    End Class{0}" +
                                          "End Namespace{0}", NewLine), Generate(), "#3");

            type.TypeParameters.Add(new CodeTypeParameter("S"));

            Assert.AreEqual(string.Format(CultureInfo.InvariantCulture,
                                          "{0}" +
                                          "Namespace SomeNS{0}" +
                                          "    {0}" +
                                          "    Public Class SomeClass(Of T, As, New, R As System.IComparable, S){0}" +
                                          "    End Class{0}" +
                                          "End Namespace{0}", NewLine), Generate(), "#4");
        }
Exemplo n.º 5
0
        public void TypeParameters_AddMultiple_ReturnsExpected()
        {
            var declaration = new CodeTypeDeclaration();

            CodeTypeParameter parameter1 = new CodeTypeParameter("Name1");

            declaration.TypeParameters.Add(parameter1);
            Assert.Equal(new CodeTypeParameter[] { parameter1 }, declaration.TypeParameters.Cast <CodeTypeParameter>());

            CodeTypeParameter parameter2 = new CodeTypeParameter("Name2");

            declaration.TypeParameters.Add(parameter2);
            Assert.Equal(new CodeTypeParameter[] { parameter1, parameter2 }, declaration.TypeParameters.Cast <CodeTypeParameter>());
        }
Exemplo n.º 6
0
        public void TypeParameters_AddMultiple_ReturnsExpected()
        {
            var method = new CodeMemberMethod();

            CodeTypeParameter parameter1 = new CodeTypeParameter("Name1");

            method.TypeParameters.Add(parameter1);
            Assert.Equal(new CodeTypeParameter[] { parameter1 }, method.TypeParameters.Cast <CodeTypeParameter>());

            CodeTypeParameter parameter2 = new CodeTypeParameter("Name2");

            method.TypeParameters.Add(parameter2);
            Assert.Equal(new CodeTypeParameter[] { parameter1, parameter2 }, method.TypeParameters.Cast <CodeTypeParameter>());
        }
        public string Evaluate(CodeTypeParameter codeTypeParameter)
        {
            var typeParameterConstraint = string.Empty;

            if (codeTypeParameter.Constraints.Count > 0)
            {
                var constraint = codeTypeParameter.Constraints.OfType <CodeTypeReference>().First();
                var type       = _typescriptTypeMapper.GetTypeOutput(constraint);
                typeParameterConstraint = $" extends {type}";
            }


            return($"{codeTypeParameter.Name}{typeParameterConstraint}");
        }
        public static CodeTypeParameter TypeParameter(
            string name,
            bool hasConstructorConstraint,
            CodeTypeReference[] constraints,
            CodeAttributeDeclaration[] customAttributes
            )
        {
            var result = new CodeTypeParameter(name);

            result.HasConstructorConstraint = hasConstructorConstraint;
            result.Constraints.AddRange(constraints);
            result.CustomAttributes.AddRange(customAttributes);
            return(result);
        }
        protected override void ValidateElement(object element)
        {
            if (element == null)
            {
                if (AllowNullOrEmpty)
                {
                    return;
                }
                throw new ValidationMetadataException("Type Parameter cannot be null");
            }

            CodeTypeParameter parameter;
            object            baseObject = (element is PSObject) ? ((PSObject)element).BaseObject : element;

            if (baseObject is CodeTypeParameter)
            {
                parameter = (CodeTypeParameter)baseObject;
            }
            else
            {
                string name;
                if (baseObject is string)
                {
                    name = ((string)baseObject);
                }
                else
                {
                    try
                    {
                        if (!LanguagePrimitives.TryConvertTo <string>(element, out name))
                        {
                            throw new PSArgumentOutOfRangeException();
                        }
                    }
                    catch (Exception exception) { throw new ValidationMetadataException("Unable to convert value to string", exception); }
                }
                if (string.IsNullOrWhiteSpace(name))
                {
                    if (AllowNullOrEmpty)
                    {
                        return;
                    }
                    throw new ValidationMetadataException("Type Parameter cannot be empty");
                }
                try { parameter = new CodeTypeParameter(name); }
                catch (Exception exception) { throw new ValidationMetadataException("Unable to convert string to Type Parameter object", exception); }
                parameter.
            }
        }
        public void Insert()
        {
            CodeTypeParameter tp1 = new CodeTypeParameter();
            CodeTypeParameter tp2 = new CodeTypeParameter();

            CodeTypeParameterCollection coll = new CodeTypeParameterCollection();

            coll.Add(tp1);
            Assert.AreEqual(1, coll.Count, "#1");
            Assert.AreEqual(0, coll.IndexOf(tp1), "#2");
            coll.Insert(0, tp2);
            Assert.AreEqual(2, coll.Count, "#3");
            Assert.AreEqual(1, coll.IndexOf(tp1), "#4");
            Assert.AreEqual(0, coll.IndexOf(tp2), "#5");
        }
Exemplo n.º 11
0
        public void Constructor4_Deny_Unrestricted()
        {
            CodeTypeParameter parameter = new CodeTypeParameter("System.Int32");
            CodeTypeReference ctr       = new CodeTypeReference(parameter);

            Assert.IsNull(ctr.ArrayElementType, "ArrayElementType");
            Assert.AreEqual("System.Int32", ctr.BaseType, "BaseType");
            Assert.AreEqual(0, ctr.ArrayRank, "ArrayRank");
            ctr.ArrayElementType = new CodeTypeReference();
            ctr.BaseType         = String.Empty;
            ctr.ArrayRank        = 1;
            Assert.AreEqual(CodeTypeReferenceOptions.GenericTypeParameter, ctr.Options, "Options");
            ctr.Options = CodeTypeReferenceOptions.GlobalReference;
            Assert.AreEqual(0, ctr.TypeArguments.Count, "TypeArguments");
        }
Exemplo n.º 12
0
        public static CodeCompileUnit TestComplexClassAndMethodSignatureCompileUnit()
        {
            CodeCompileUnit     compileUnit      = new CodeCompileUnit();
            CodeNamespace       codeNamespace    = new CodeNamespace("Test.Namespace");
            CodeTypeDeclaration classDeclaration = new CodeTypeDeclaration("TestClass")
            {
                IsClass = true
            };

            classDeclaration.TypeAttributes =
                (classDeclaration.TypeAttributes & ~TypeAttributes.VisibilityMask) | TypeAttributes.Public;
            classDeclaration.TypeAttributes |= TypeAttributes.Abstract;
            var t1 = new CodeTypeParameter("T1");
            var t2 = new CodeTypeParameter("T2");

            t1.Constraints.Add(new CodeTypeReference("A"));
            t1.HasConstructorConstraint = true;
            t2.Constraints.Add(new CodeTypeReference("IA"));
            t2.Constraints.Add(new CodeTypeReference("IB"));

            classDeclaration.BaseTypes.Add(new CodeTypeReference("BaseClass"));
            classDeclaration.BaseTypes.Add(new CodeTypeReference("IInterface"));

            classDeclaration.TypeParameters.Add(t1);
            classDeclaration.TypeParameters.Add(t2);

            CodeMemberMethod method = new CodeMemberMethod()
            {
                Name = "GenericMethod"
            };
            var ta = new CodeTypeParameter("TA");
            var tb = new CodeTypeParameter("TB");

            method.TypeParameters.Add(ta);
            method.TypeParameters.Add(tb);
            method.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("TA"), "a"));
            method.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("TB"), "b"));
            var ienum = new CodeTypeReference("IEnumerable");

            ienum.TypeArguments.Add(new CodeTypeReference("TB"));
            ta.Constraints.Add(ienum);

            classDeclaration.Members.Add(method);
            codeNamespace.Types.Add(classDeclaration);
            compileUnit.Namespaces.Add(codeNamespace);

            return(compileUnit);
        }
        public void Constructor2()
        {
            CodeTypeParameter tp1 = new CodeTypeParameter();
            CodeTypeParameter tp2 = new CodeTypeParameter();

            CodeTypeParameterCollection c = new CodeTypeParameterCollection();

            c.Add(tp1);
            c.Add(tp2);

            CodeTypeParameterCollection coll = new CodeTypeParameterCollection(c);

            Assert.AreEqual(2, coll.Count, "#1");
            Assert.AreEqual(0, coll.IndexOf(tp1), "#2");
            Assert.AreEqual(1, coll.IndexOf(tp2), "#3");
        }
Exemplo n.º 14
0
 private void FillGenericParameters(CodeTypeParameterCollection codes, IEnumerable <GenericParameter> defines)
 {
     foreach (var genericParameter in defines)
     {
         CodeTypeParameter t = new CodeTypeParameter(genericParameter.FullName);
         if (genericParameter.IsContravariant)
         {
             t.HasConstructorConstraint = true;
         }
         foreach (var constraint in genericParameter.Constraints)
         {
             t.Constraints.Add(new CodeTypeReference(constraint.FullName));
         }
         FillCustomAttribute(t.CustomAttributes, genericParameter.CustomAttributes);
         codes.Add(t);
     }
 }
Exemplo n.º 15
0
        private static IEnumerable <CodeTypeParameter> GetTypeParametersFrom(MethodBase method)
        {
            foreach (var typeParam in method.GetGenericArguments())
            {
                var ctp         = new CodeTypeParameter(typeParam.Name);
                var constraints = typeParam.GetGenericParameterConstraints();

                if (constraints.Any())
                {
                    foreach (var constraint in constraints)
                    {
                        ctp.Constraints.Add(new CodeTypeReference(constraint));
                    }
                }
                yield return(ctp);
            }
        }
Exemplo n.º 16
0
        static void PopulateGenericParameters(IGenericParameterProvider publicType, CodeTypeParameterCollection parameters, HashSet <string> excludeAttributes)
        {
            foreach (var parameter in publicType.GenericParameters)
            {
                // A little hacky. Means we get "in" and "out" prefixed on any constraints, but it's either that
                // or add it as a custom attribute
                var name = parameter.Name;
                if (parameter.IsCovariant)
                {
                    name = "out " + name;
                }
                if (parameter.IsContravariant)
                {
                    name = "in " + name;
                }

                var attributeCollection = new CodeAttributeDeclarationCollection();
                if (parameter.HasCustomAttributes)
                {
                    PopulateCustomAttributes(parameter, attributeCollection, excludeAttributes);
                }

                var typeParameter = new CodeTypeParameter(name)
                {
                    HasConstructorConstraint =
                        parameter.HasDefaultConstructorConstraint && !parameter.HasNotNullableValueTypeConstraint
                };

                typeParameter.CustomAttributes.AddRange(attributeCollection.OfType <CodeAttributeDeclaration>().ToArray());

                if (parameter.HasNotNullableValueTypeConstraint)
                {
                    typeParameter.Constraints.Add(" struct"); // Extra space is a hack!
                }
                if (parameter.HasReferenceTypeConstraint)
                {
                    typeParameter.Constraints.Add(" class");
                }
                foreach (var constraint in parameter.Constraints.Where(t => t.FullName != "System.ValueType"))
                {
                    // for generic constraints like IEnumerable<T> call to GetElementType() returns TypeReference with Name = !0
                    typeParameter.Constraints.Add(CreateCodeTypeReference(constraint /*.GetElementType()*/));
                }
                parameters.Add(typeParameter);
            }
        }
        public void Remove()
        {
            CodeTypeParameter ctp1 = new CodeTypeParameter();
            CodeTypeParameter ctp2 = new CodeTypeParameter();

            CodeTypeParameterCollection coll = new CodeTypeParameterCollection();

            coll.Add(ctp1);
            coll.Add(ctp2);
            Assert.AreEqual(2, coll.Count, "#1");
            Assert.AreEqual(0, coll.IndexOf(ctp1), "#2");
            Assert.AreEqual(1, coll.IndexOf(ctp2), "#3");
            coll.Remove(ctp1);
            Assert.AreEqual(1, coll.Count, "#4");
            Assert.AreEqual(-1, coll.IndexOf(ctp1), "#5");
            Assert.AreEqual(0, coll.IndexOf(ctp2), "#6");
        }
        public CodeMemberMethod[] GetFindByNameExMethods()
        {
            string methodName = "FindByNameEx";

            SAPAutomationHelper.Current.SetSAPApiAssembly();
            Assembly asm = SAPAutomationHelper.Current.SAPGuiApiAssembly;

            var interfaces = asm.GetTypes().Where(t => t.IsInterface && t.Name.StartsWith("Gui") && t.GetInterfaces()[0].GetMethod(methodName) != null).ToArray();

            CodeMemberMethod[] methods = new CodeMemberMethod[interfaces.Count()];

            for (int i = 0; i < interfaces.Count(); i++)
            {
                methods[i]            = new CodeMemberMethod();
                methods[i].Name       = methodName;
                methods[i].Attributes = MemberAttributes.Public | MemberAttributes.Static;
                CodeParameterDeclarationExpression para1 = new CodeParameterDeclarationExpression(new CodeTypeReference("this " + interfaces[i].Name), interfaces[i].Name.Substring(3));
                methods[i].Parameters.Add(para1);
                CodeParameterDeclarationExpression para2 = new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(string)), "Name");
                methods[i].Parameters.Add(para2);
                CodeParameterDeclarationExpression para3 = new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "TypeId");
                methods[i].Parameters.Add(para3);
                methods[i].ReturnType = new CodeTypeReference("T");

                CodeTypeParameter param = new CodeTypeParameter("T");
                param.Constraints.Add(" class");
                methods[i].TypeParameters.Add(param);

                methods[i].Statements.Add(new CodeMethodReturnStatement(
                                              new CodeMethodInvokeExpression(
                                                  new CodeMethodReferenceExpression(null, "findByNameExTemplate", new CodeTypeReference("T")),
                                                  new CodeVariableReferenceExpression("Name"),
                                                  new CodeVariableReferenceExpression("TypeId"),
                                                  new CodeArgumentReferenceExpression(interfaces[i].Name.Substring(3) + "." + methodName)


                                                  )));
            }



            return(methods);
        }
Exemplo n.º 19
0
        public static CodeCompileUnit TestInterfaceCompileUnit()
        {
            CodeCompileUnit     compileUnit          = new CodeCompileUnit();
            CodeNamespace       codeNamespace        = new CodeNamespace("Test.Namespace");
            CodeTypeDeclaration interfaceDeclaration = new CodeTypeDeclaration("IInterface")
            {
                IsInterface = true
            };

            interfaceDeclaration.TypeAttributes =
                (interfaceDeclaration.TypeAttributes & ~TypeAttributes.VisibilityMask) | TypeAttributes.Public;
            interfaceDeclaration.BaseTypes.Add(new CodeTypeReference("IAnotherInterface"));

            CodeMemberMethod method = new CodeMemberMethod()
            {
                Name       = "GenericMethod",
                ReturnType = Types.Int,
                Attributes = MemberAttributes.Public
            };
            var ta = new CodeTypeParameter("TA");
            var tb = new CodeTypeParameter("TB");

            method.TypeParameters.Add(ta);
            method.TypeParameters.Add(tb);
            method.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("TA"), "a"));
            method.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("TB"), "b"));
            var ienum = new CodeTypeReference("IEnumerable");

            ienum.TypeArguments.Add(new CodeTypeReference("TB"));
            ta.Constraints.Add(ienum);

            interfaceDeclaration.Members.Add(method);
            interfaceDeclaration.Members.Add(new CodeMemberMethod()
            {
                Name       = "AnotherMethod",
                Attributes = MemberAttributes.Public
            });
            codeNamespace.Types.Add(interfaceDeclaration);
            compileUnit.Namespaces.Add(codeNamespace);

            return(compileUnit);
        }
Exemplo n.º 20
0
        private static void PopulateGenericParameters(IGenericParameterProvider publicType,
                                                      CodeTypeParameterCollection parameters)
        {
            foreach (var parameter in publicType.GenericParameters)
            {
                if (parameter.HasCustomAttributes)
                {
                    throw new NotImplementedException("Attributes on type parameters is not supported. And weird");
                }

                // A little hacky. Means we get "in" and "out" prefixed on any constraints, but it's either that
                // or add it as a custom attribute, which looks even weirder
                var name = parameter.Name;
                if (parameter.IsCovariant)
                {
                    name = "out " + name;
                }
                if (parameter.IsContravariant)
                {
                    name = "in " + name;
                }

                var typeParameter = new CodeTypeParameter(name)
                {
                    HasConstructorConstraint =
                        parameter.HasDefaultConstructorConstraint && !parameter.HasNotNullableValueTypeConstraint
                };
                if (parameter.HasNotNullableValueTypeConstraint)
                {
                    typeParameter.Constraints.Add(" struct"); // Extra space is a hack!
                }
                if (parameter.HasReferenceTypeConstraint)
                {
                    typeParameter.Constraints.Add(" class");
                }
                foreach (var constraint in parameter.Constraints.Where(t => t.FullName != "System.ValueType"))
                {
                    typeParameter.Constraints.Add(CreateCodeTypeReference(constraint.GetElementType()));
                }
                parameters.Add(typeParameter);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Creates generic type with possible constraints
        /// </summary>
        /// <param name="lstGenericClassDefinitions">list of GenericClassParameters-struct with generic type name and constraints</param>
        public void CreateGenericType(List <GenericClassParameters> lstGenericClassDefinitions)
        {
            List <string> lstTypeParams = new List <string>();

            foreach (GenericClassParameters GenericClassDefinition in lstGenericClassDefinitions)
            {
                CodeTypeReference ctrGenericTypeReference = new CodeTypeReference(GenericClassDefinition.GenericType);
                CodeTypeReference ctrBaseTypeReference;
                if (!string.IsNullOrEmpty(GenericClassDefinition.BaseType))
                {
                    if (GenericClassDefinition.IsBaseTypeGeneric)
                    {
                        ctrBaseTypeReference = new CodeTypeReference(GenericClassDefinition.BaseType, ctrGenericTypeReference);
                    }
                    else
                    {
                        ctrBaseTypeReference = new CodeTypeReference(GenericClassDefinition.BaseType);
                    }
                    TheType.BaseTypes.Add(ctrBaseTypeReference);
                }

                CodeTypeParameter ctpGenericTypeParameter = new CodeTypeParameter(GenericClassDefinition.GenericType);


                if (GenericClassDefinition.Constraint.Count > 0)
                {
                    foreach (string constraint in GenericClassDefinition.Constraint)
                    {
                        CodeTypeReference ctrGenericConstraintReference = new CodeTypeReference(constraint);
                        ctpGenericTypeParameter.Constraints.Add(ctrGenericConstraintReference);
                    }
                }
                if (!lstTypeParams.Contains(GenericClassDefinition.GenericType))
                {
                    TheType.TypeParameters.Add(ctpGenericTypeParameter);
                }


                lstTypeParams.Add(GenericClassDefinition.GenericType);
            }
        }
        public void Type_TypeParameters_ConstructorConstraint()
        {
            codeNamespace.Name = "SomeNS";

            CodeTypeDeclaration type = new CodeTypeDeclaration("SomeClass");

            codeNamespace.Types.Add(type);

            CodeTypeParameter typeParam = new CodeTypeParameter("T");

            typeParam.HasConstructorConstraint = true;
            type.TypeParameters.Add(typeParam);

            Assert.AreEqual(string.Format(CultureInfo.InvariantCulture,
                                          "{0}" +
                                          "Namespace SomeNS{0}" +
                                          "    {0}" +
                                          "    Public Class SomeClass(Of T As New){0}" +
                                          "    End Class{0}" +
                                          "End Namespace{0}", NewLine), Generate());
        }
        private CodeTypeParameter[] createContextParameters(InterfaceSignature interface_type_descriptor,
                                                            IDictionary <string, int> par_order,
                                                            IList <string> dependency_list,
                                                            IList <string> usings_list)
        {
            //IList<CodeTypeParameter> context_parameter_list = new List<CodeTypeParameter>();

            CodeTypeParameter[] context_parameters = new CodeTypeParameter[interface_type_descriptor.parameters.Count];

            foreach (KeyValuePair <string, InterfaceSignature> ctx_par in interface_type_descriptor.parameters)
            {
                string            var_id           = interface_type_descriptor.varId[ctx_par.Key];
                CodeTypeParameter context_variable = new CodeTypeParameter(var_id);
                CodeTypeReference context_type     = buildCodeTypeReference(ctx_par.Value, dependency_list, usings_list);
                context_variable.Constraints.Add(context_type);
                context_parameters[par_order[ctx_par.Key]] = context_variable;
            }


            //context_parameter_list.CopyTo(context_parameters, 0);
            return(context_parameters);
        }
        public void Constructor1()
        {
            string parameterName = "mono";

            CodeTypeParameter ctp = new CodeTypeParameter(parameterName);

            Assert.IsNotNull(ctp.Constraints, "#1");
            Assert.AreEqual(0, ctp.Constraints.Count, "#2");
            Assert.IsNotNull(ctp.CustomAttributes, "#3");
            Assert.AreEqual(0, ctp.CustomAttributes.Count, "#4");
            Assert.IsFalse(ctp.HasConstructorConstraint, "#5");
            Assert.IsNotNull(ctp.Name, "#6");
            Assert.AreSame(parameterName, ctp.Name, "#7");

            ctp.Name = null;
            Assert.IsNotNull(ctp.Name, "#8");
            Assert.AreEqual(string.Empty, ctp.Name, "#9");

            ctp = new CodeTypeParameter((string)null);
            Assert.IsNotNull(ctp.Name, "#10");
            Assert.AreEqual(string.Empty, ctp.Name, "#11");
        }
Exemplo n.º 25
0
        public void Type_TypeParameters_ConstructorConstraint()
        {
            codeNamespace.Name = "SomeNS";

            CodeTypeDeclaration type = new CodeTypeDeclaration("SomeClass");

            codeNamespace.Types.Add(type);

            CodeTypeParameter typeParam = new CodeTypeParameter("T");

            typeParam.HasConstructorConstraint = true;
            type.TypeParameters.Add(typeParam);

            Assert.AreEqual(string.Format(CultureInfo.InvariantCulture,
                                          "namespace SomeNS {{{0}" +
                                          "    {0}" +
                                          "    {0}" +
                                          "    public class SomeClass<T>{0}" +
                                          "        where T : new() {{{0}" +
                                          "    }}{0}" +
                                          "}}{0}", NewLine), Generate());
        }
Exemplo n.º 26
0
        public void CreateGenericTypeMultiDimension(List <GenericClassParameters> lstGenericClassDefinitions)
        {
            List <string> lstTypeParams = new List <string>();

            foreach (GenericClassParameters GenericClassDefinition in lstGenericClassDefinitions)
            {
                CodeTypeReference ctrBaseTypeReference = new CodeTypeReference(GenericClassDefinition.BaseType);

                foreach (string genType in GenericClassDefinition.GenericTypes)
                {
                    CodeTypeReference ctrGenericTypeReference = new CodeTypeReference(genType);



                    if (GenericClassDefinition.IsBaseTypeGeneric && ctrBaseTypeReference != null)
                    {
                        ctrBaseTypeReference.TypeArguments.Add(ctrGenericTypeReference);
                    }
                    CodeTypeParameter ctpGenericTypeParameter = new CodeTypeParameter(genType);


                    if (GenericClassDefinition.Constraint.Count > 0)
                    {
                        foreach (string constraint in GenericClassDefinition.Constraint)
                        {
                            CodeTypeReference ctrGenericConstraintReference = new CodeTypeReference(constraint);
                            ctpGenericTypeParameter.Constraints.Add(ctrGenericConstraintReference);
                        }
                    }
                    //  if (!lstTypeParams.Contains(genType))
                    //    TheType.TypeParameters.Add(ctpGenericTypeParameter);



                    lstTypeParams.Add(GenericClassDefinition.GenericType);
                }
                TheType.BaseTypes.Add(ctrBaseTypeReference);
            }
        }
Exemplo n.º 27
0
        public static CodeTypeParameterCollection GenericTypeParameters(Type t)
        {
            if (!t.IsGenericType)
            {
                return(null);
            }

            var p = new CodeTypeParameterCollection();

            foreach (var genericParameter in t.GetGenericTypeDefinition().GetGenericArguments())
            {
                var param = new CodeTypeParameter(genericParameter.Name);
                if ((genericParameter.GenericParameterAttributes &
                     GenericParameterAttributes.ReferenceTypeConstraint) != GenericParameterAttributes.None)
                {
                    param.Constraints.Add(" class");
                }
                if ((genericParameter.GenericParameterAttributes &
                     GenericParameterAttributes.NotNullableValueTypeConstraint) != GenericParameterAttributes.None)
                {
                    param.Constraints.Add(" struct");
                }
                var constraints = genericParameter.GetGenericParameterConstraints();
                foreach (var constraintType in constraints)
                {
                    param.Constraints.Add(
                        new CodeTypeReference(TypeUtils.GetParameterizedTemplateName(constraintType, false,
                                                                                     x => true)));
                }
                if ((genericParameter.GenericParameterAttributes &
                     GenericParameterAttributes.DefaultConstructorConstraint) != GenericParameterAttributes.None)
                {
                    param.HasConstructorConstraint = true;
                }
                p.Add(param);
            }
            return(p);
        }
        public void Constructor0()
        {
            CodeTypeParameter ctp = new CodeTypeParameter();

            Assert.IsNotNull(ctp.Constraints, "#1");
            Assert.AreEqual(0, ctp.Constraints.Count, "#2");
            Assert.IsNotNull(ctp.CustomAttributes, "#3");
            Assert.AreEqual(0, ctp.CustomAttributes.Count, "#4");
            Assert.IsFalse(ctp.HasConstructorConstraint, "#5");
            Assert.IsNotNull(ctp.Name, "#6");
            Assert.AreEqual(string.Empty, ctp.Name, "#7");

            ctp.Name = null;
            Assert.IsNotNull(ctp.Name, "#8");
            Assert.AreEqual(string.Empty, ctp.Name, "#9");

            string name = "mono";

            ctp.Name = name;
            Assert.AreSame(name, ctp.Name, "#10");

            ctp.HasConstructorConstraint = true;
            Assert.IsTrue(ctp.HasConstructorConstraint, "#11");
        }
Exemplo n.º 29
0
        static void AddDeserializeMethod(CodeTypeDeclaration targetClass)
        {
            CodeMemberMethod  method = new CodeMemberMethod();
            CodeTypeParameter tType  = new CodeTypeParameter("T");

            method.Name       = "Deserialize";
            method.Attributes = MemberAttributes.Private | MemberAttributes.Static;
            method.TypeParameters.Add(tType);
            method.ReturnType = new CodeTypeReference("T");

            method.Parameters.Add(new CodeParameterDeclarationExpression(
                                      "JsonSerializer", "serializer"));
            method.Parameters.Add(new CodeParameterDeclarationExpression(
                                      "System.String", "jsonText"));

            method.Statements.Add(new CodeSnippetStatement(
                                      $@"			using var r = new JsonTextReader(new StringReader(jsonText));"
                                      ));
            method.Statements.Add(new CodeSnippetStatement(
                                      $@"			return serializer.Deserialize<T>(r);"
                                      ));

            targetClass.Members.Add(method);
        }
	public CodeTypeParameterCollection(CodeTypeParameter[] value) {}
	public CodeTypeReference(CodeTypeParameter typeParameter) {}
	public void CopyTo(CodeTypeParameter[] array, int index) {}
	public int IndexOf(CodeTypeParameter value) {}
	public void Insert(int index, CodeTypeParameter value) {}
	public void Remove(CodeTypeParameter value) {}
	public void AddRange(CodeTypeParameter[] value) {}
Exemplo n.º 37
0
        public void GenericTypesAndConstraints()
        {
            CodeNamespace ns = new CodeNamespace("NS");
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));

            CodeTypeDeclaration class1 = new CodeTypeDeclaration();
            class1.Name = "MyDictionary";
            class1.BaseTypes.Add(new CodeTypeReference("Dictionary", new CodeTypeReference[] { new CodeTypeReference("TKey"), new CodeTypeReference("TValue"), }));
            CodeTypeParameter kType = new CodeTypeParameter("TKey");
            kType.HasConstructorConstraint = true;
            kType.Constraints.Add(new CodeTypeReference(typeof(IComparable)));
            kType.CustomAttributes.Add(new CodeAttributeDeclaration(
                "System.ComponentModel.DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("KeyType"))));

            CodeTypeReference iComparableT = new CodeTypeReference("IComparable");
            iComparableT.TypeArguments.Add(new CodeTypeReference(kType));
            kType.Constraints.Add(iComparableT);

            CodeTypeParameter vType = new CodeTypeParameter("TValue");
            vType.Constraints.Add(new CodeTypeReference(typeof(IList<System.String>)));
            vType.CustomAttributes.Add(new CodeAttributeDeclaration(
                "System.ComponentModel.DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("ValueType"))));

            class1.TypeParameters.Add(kType);
            class1.TypeParameters.Add(vType);
            ns.Types.Add(class1);

            // Declare a generic method.
            CodeMemberMethod printMethod = new CodeMemberMethod();
            CodeTypeParameter sType = new CodeTypeParameter("S");
            sType.HasConstructorConstraint = true;
            CodeTypeParameter tType = new CodeTypeParameter("T");
            sType.HasConstructorConstraint = true;

            printMethod.Name = "Nop";
            printMethod.TypeParameters.Add(sType);
            printMethod.TypeParameters.Add(tType);
            printMethod.Attributes = MemberAttributes.Public;
            class1.Members.Add(printMethod);

            var class2 = new CodeTypeDeclaration();
            class2.Name = "Demo";

            var methodMain = new CodeEntryPointMethod();
            var myClass = new CodeTypeReference(
                "MyDictionary",
                new CodeTypeReference[] {
                    new CodeTypeReference(typeof(int)),
                    new CodeTypeReference("List",
                       new CodeTypeReference[]
                            {new CodeTypeReference("System.String") })});
            methodMain.Statements.Add(new CodeVariableDeclarationStatement(myClass, "dict", new CodeObjectCreateExpression(myClass)));
            string dictionaryTypeName = typeof(System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<string>>[]).FullName;

            var dictionaryType = new CodeTypeReference(dictionaryTypeName);
            methodMain.Statements.Add(
                  new CodeVariableDeclarationStatement(dictionaryType, "dict2",
                     new CodeArrayCreateExpression(dictionaryType, new CodeExpression[1] { new CodePrimitiveExpression(null) })));

            class2.Members.Add(methodMain);
            ns.Types.Add(class2);

            AssertEqual(ns,
                @"Imports System
                  Imports System.Collections.Generic
                  Namespace NS
                      Public Class MyDictionary(Of TKey As  {System.IComparable, IComparable(Of TKey), New}, TValue As System.Collections.Generic.IList(Of String))
                          Inherits Dictionary(Of TKey, TValue)
                          Public Overridable Sub Nop(Of S As New, T)()
                          End Sub
                      End Class
                      Public Class Demo
                          Public Shared Sub Main()
                              Dim dict As MyDictionary(Of Integer, List(Of String)) = New MyDictionary(Of Integer, List(Of String))()
                              Dim dict2() As System.Collections.Generic.Dictionary(Of Integer, System.Collections.Generic.List(Of String)) = New System.Collections.Generic.Dictionary(Of Integer, System.Collections.Generic.List(Of String))() {Nothing}
                          End Sub
                      End Class
                  End Namespace");
        }
Exemplo n.º 38
0
    public override void BuildTree(CodeDomProvider provider, CodeCompileUnit cu) {
#if WHIDBEY
        // GENERATES (C#):
        //  namespace TestNamespace {
        //      using System;
        //      using System.Collections.Generic;
        //      
        //      
        //      public class MyDictionary<K, V> : Dictionary<K, V>
        //          where K : System.IComparable, IComparable<K>, new ()
        //          where V : IList<string> {
        //          
        //          public virtual int Calculate<S, T>(int value1, int value2)
        //              where S : new()
        //           {
        //              return (value1 * value2);
        //          }
        //      }
        //      
        //      public class Test {
        //          
        //          public virtual int MyMethod() {
        //              int dReturn;
        //              MyDictionary<int, List<string>> dict = new MyDictionary<int, List<string>>();
        //              dReturn = dict.Calculate<int, int>(2.5, 11);
        //              return dReturn;
        //          }
        //      }
        //  }
        
        if (!provider.Supports(GeneratorSupport.GenericTypeReference | GeneratorSupport.GenericTypeDeclaration)) {
            return;
        }

        CodeNamespace ns = new CodeNamespace("TestNamespace");
        ns.Imports.Add(new CodeNamespaceImport("System"));
        ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
        cu.Namespaces.Add (ns);

        // Declare a generic class
        CodeTypeDeclaration class1 = new CodeTypeDeclaration();
        class1.Name = "MyDictionary";
        class1.BaseTypes.Add( new CodeTypeReference("Dictionary", 
                                  new CodeTypeReference[] { new CodeTypeReference("K"), new CodeTypeReference("V"),}));

        CodeTypeParameter kType = new CodeTypeParameter("K");
        kType.HasConstructorConstraint= true;

        kType.Constraints.Add( new CodeTypeReference(typeof(IComparable)));
        kType.CustomAttributes.Add(new CodeAttributeDeclaration(
            "System.ComponentModel.DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("KeyType"))));

        CodeTypeReference iComparableT = new CodeTypeReference("IComparable");
        iComparableT.TypeArguments.Add(new CodeTypeReference(kType));            

        kType.Constraints.Add(iComparableT);
        
        CodeTypeParameter vType = new CodeTypeParameter("V");
        vType.Constraints.Add(new CodeTypeReference("IList[System.String]"));

        class1.TypeParameters.Add(kType);
        class1.TypeParameters.Add(vType);
                    
        ns.Types.Add(class1);

        // declare a generic method
        CodeMemberMethod method = new CodeMemberMethod();
        CodeTypeParameter sType = new CodeTypeParameter("S");
        sType.HasConstructorConstraint = true;

        CodeTypeParameter tType = new CodeTypeParameter("T");
        sType.HasConstructorConstraint = true;

        method.Name = "Calculate";
        method.TypeParameters.Add(sType);
        method.TypeParameters.Add(tType);
        method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "value1"));
        method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "value2"));
        method.ReturnType = new CodeTypeReference(typeof(int));

        method.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(new 
                                 CodeVariableReferenceExpression("value1"), CodeBinaryOperatorType.Multiply, new 
                                 CodeVariableReferenceExpression("value2"))));


        method.Attributes = MemberAttributes.Public;
        class1.Members.Add(method);


        CodeTypeDeclaration class2 = new CodeTypeDeclaration();
        class2.Name = "Test";

        AddScenario ("CheckMyMethod");
        CodeMemberMethod method2 =  new CodeMemberMethod();
        method2.Name = "MyMethod";
        method2.Attributes = MemberAttributes.Public;
        method2.ReturnType = new CodeTypeReference(typeof(int));
        method2.Statements.Add( new CodeVariableDeclarationStatement(typeof(int), "dReturn"));

        CodeTypeReference myClass = new CodeTypeReference( "MyDictionary", 
                                    new CodeTypeReference[] { new CodeTypeReference(typeof(int)), new CodeTypeReference("List", 
                                    new CodeTypeReference[] {new CodeTypeReference("System.String") })} ); 

        method2.Statements.Add(  new CodeVariableDeclarationStatement( myClass, "dict", new CodeObjectCreateExpression(myClass) ));

        method2.Statements.Add(new CodeAssignStatement( new CodeVariableReferenceExpression("dReturn"), 
                               new CodeMethodInvokeExpression(
                               new CodeMethodReferenceExpression( new CodeVariableReferenceExpression("dict"), "Calculate",
                               new CodeTypeReference[] {
                               new CodeTypeReference("System.Int32"),
                               new CodeTypeReference("System.Int32"),}), 
                               new CodeExpression[]{new CodePrimitiveExpression(25), new CodePrimitiveExpression(11)})));

        method2.Statements.Add (new CodeMethodReturnStatement(new CodeVariableReferenceExpression("dReturn")));
        class2.Members.Add(method2);
        ns.Types.Add(class2);
#endif
    }
	// Methods
	public int Add(CodeTypeParameter value) {}
        public void Method_TypeParameters_Constraints()
        {
            codeNamespace.Name = "SomeNS";

            CodeTypeDeclaration type = new CodeTypeDeclaration("SomeClass");

            codeNamespace.Types.Add(type);

            CodeMemberMethod method = new CodeMemberMethod();

            method.Name = "SomeMethod";
            type.Members.Add(method);

            CodeTypeParameter typeParamT = new CodeTypeParameter("T");

            typeParamT.Constraints.Add(new CodeTypeReference(typeof(IComparable)));
            method.TypeParameters.Add(typeParamT);

            Assert.AreEqual(string.Format(CultureInfo.InvariantCulture,
                                          "{0}" +
                                          "Namespace SomeNS{0}" +
                                          "    {0}" +
                                          "    Public Class SomeClass{0}" +
                                          "        {0}" +
                                          "        Private Sub SomeMethod(Of T As System.IComparable)(){0}" +
                                          "        End Sub{0}" +
                                          "    End Class{0}" +
                                          "End Namespace{0}", NewLine), Generate(), "#1");

            typeParamT.Constraints.Add(new CodeTypeReference(typeof(ICloneable)));

            Assert.AreEqual(string.Format(CultureInfo.InvariantCulture,
                                          "{0}" +
                                          "Namespace SomeNS{0}" +
                                          "    {0}" +
                                          "    Public Class SomeClass{0}" +
                                          "        {0}" +
                                          "        Private Sub SomeMethod(Of T As  {{System.IComparable, System.ICloneable}})(){0}" +
                                          "        End Sub{0}" +
                                          "    End Class{0}" +
                                          "End Namespace{0}", NewLine), Generate(), "#2");

            typeParamT.HasConstructorConstraint = true;

            Assert.AreEqual(string.Format(CultureInfo.InvariantCulture,
                                          "{0}" +
                                          "Namespace SomeNS{0}" +
                                          "    {0}" +
                                          "    Public Class SomeClass{0}" +
                                          "        {0}" +
                                          "        Private Sub SomeMethod(Of T As  {{System.IComparable, System.ICloneable, New}})(){0}" +
                                          "        End Sub{0}" +
                                          "    End Class{0}" +
                                          "End Namespace{0}", NewLine), Generate(), "#3");

            CodeTypeParameter typeParamS = new CodeTypeParameter("S");

            typeParamS.Constraints.Add(new CodeTypeReference(typeof(IDisposable)));
            method.TypeParameters.Add(typeParamS);

            Assert.AreEqual(string.Format(CultureInfo.InvariantCulture,
                                          "{0}" +
                                          "Namespace SomeNS{0}" +
                                          "    {0}" +
                                          "    Public Class SomeClass{0}" +
                                          "        {0}" +
                                          "        Private Sub SomeMethod(Of T As  {{System.IComparable, System.ICloneable, New}}, S As System.IDisposable)(){0}" +
                                          "        End Sub{0}" +
                                          "    End Class{0}" +
                                          "End Namespace{0}", NewLine), Generate(), "#4");

            CodeTypeParameter typeParamR = new CodeTypeParameter("R");

            typeParamR.HasConstructorConstraint = true;
            method.TypeParameters.Add(typeParamR);

            Assert.AreEqual(string.Format(CultureInfo.InvariantCulture,
                                          "{0}" +
                                          "Namespace SomeNS{0}" +
                                          "    {0}" +
                                          "    Public Class SomeClass{0}" +
                                          "        {0}" +
                                          "        Private Sub SomeMethod(Of T As  {{System.IComparable, System.ICloneable, New}}, S As System.IDisposable, R As New)(){0}" +
                                          "        End Sub{0}" +
                                          "    End Class{0}" +
                                          "End Namespace{0}", NewLine), Generate(), "#5");
        }
Exemplo n.º 41
0
 private void ValidateTypeParameter(CodeTypeParameter e)
 {
     ValidateIdentifier(e, nameof(e.Name), e.Name);
     ValidateTypeReferences(e.Constraints);
     ValidateAttributes(e.CustomAttributes);
 }
	public bool Contains(CodeTypeParameter value) {}
Exemplo n.º 43
0
        public void GenericTypesAndConstraints()
        {
            CodeNamespace ns = new CodeNamespace("NS");
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));

            CodeTypeDeclaration class1 = new CodeTypeDeclaration();
            class1.Name = "MyDictionary";
            class1.BaseTypes.Add(new CodeTypeReference("Dictionary", new CodeTypeReference[] { new CodeTypeReference("TKey"), new CodeTypeReference("TValue"), }));
            CodeTypeParameter kType = new CodeTypeParameter("TKey");
            kType.HasConstructorConstraint = true;
            kType.Constraints.Add(new CodeTypeReference(typeof(IComparable)));
            kType.CustomAttributes.Add(new CodeAttributeDeclaration(
                "System.ComponentModel.DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("KeyType"))));

            CodeTypeReference iComparableT = new CodeTypeReference("IComparable");
            iComparableT.TypeArguments.Add(new CodeTypeReference(kType));
            kType.Constraints.Add(iComparableT);

            CodeTypeParameter vType = new CodeTypeParameter("TValue");
            vType.Constraints.Add(new CodeTypeReference(typeof(IList<System.String>)));
            vType.CustomAttributes.Add(new CodeAttributeDeclaration(
                "System.ComponentModel.DescriptionAttribute", new CodeAttributeArgument(new CodePrimitiveExpression("ValueType"))));

            class1.TypeParameters.Add(kType);
            class1.TypeParameters.Add(vType);
            ns.Types.Add(class1);

            // Declare a generic method.
            CodeMemberMethod printMethod = new CodeMemberMethod();
            CodeTypeParameter sType = new CodeTypeParameter("S");
            sType.HasConstructorConstraint = true;
            CodeTypeParameter tType = new CodeTypeParameter("T");
            sType.HasConstructorConstraint = true;

            printMethod.Name = "Nop";
            printMethod.TypeParameters.Add(sType);
            printMethod.TypeParameters.Add(tType);
            printMethod.Attributes = MemberAttributes.Public;
            class1.Members.Add(printMethod);

            var class2 = new CodeTypeDeclaration();
            class2.Name = "Demo";

            var methodMain = new CodeEntryPointMethod();
            var myClass = new CodeTypeReference(
                "MyDictionary",
                new CodeTypeReference[] {
                    new CodeTypeReference(typeof(int)),
                    new CodeTypeReference("List",
                       new CodeTypeReference[]
                            {new CodeTypeReference("System.String") })});
            methodMain.Statements.Add(new CodeVariableDeclarationStatement(myClass, "dict", new CodeObjectCreateExpression(myClass)));
            string dictionaryTypeName = typeof(System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<string>>[]).FullName;

            var dictionaryType = new CodeTypeReference(dictionaryTypeName);
            methodMain.Statements.Add(
                  new CodeVariableDeclarationStatement(dictionaryType, "dict2",
                     new CodeArrayCreateExpression(dictionaryType, new CodeExpression[1] { new CodePrimitiveExpression(null) })));

            class2.Members.Add(methodMain);
            ns.Types.Add(class2);

            AssertEqual(ns,
                @"namespace NS {
                      using System;
                      using System.Collections.Generic;
                      public class MyDictionary<[System.ComponentModel.DescriptionAttribute(""KeyType"")] TKey, [System.ComponentModel.DescriptionAttribute(""ValueType"")]  TValue> : Dictionary<TKey, TValue>
                          where TKey : System.IComparable, IComparable<TKey>, new ()
                          where TValue : System.Collections.Generic.IList<string>
                      {
                          public virtual void Nop<S, T>() where S : new() { }
                      }

                      public class Demo
                      {
                          public static void Main()
                          {
                              MyDictionary<int, List<string>> dict = new MyDictionary<int, List<string>>();
                              System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<string>>[] dict2 = new System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<string>>[] { null};
                          }
                      }
                  }");
        }