Example #1
0
		public void Ctor_String_CodeTypeReference_ParamsCodeStatement(string localName, CodeTypeReference catchExceptionType, CodeStatement[] statements)
		{
			var catchClause = new CodeCatchClause(localName, catchExceptionType, statements);
			Assert.Equal(localName ?? string.Empty, catchClause.LocalName);
			Assert.Equal((catchExceptionType ?? new CodeTypeReference(typeof(Exception))).BaseType, catchClause.CatchExceptionType.BaseType);
			Assert.Equal(statements, catchClause.Statements.Cast<CodeStatement>());
		}
Example #2
0
 public CodeCatchClause(string localName, CodeTypeReference catchExceptionType, params CodeStatement[] statements)
     : this()
 {
     LocalName = localName;
     CatchExceptionType = catchExceptionType;
     Statements.AddRange(statements);
 }
Example #3
0
 public CodeVariableReferenceExpression GenSymAutomatic(string prefix,  CodeTypeReference type, bool parameter)
 {
     int i = 1;
     while (autos.Select(l => l.Key).Contains(prefix + i))
         ++i;
     EnsureLocalVariable(prefix + i, type, parameter);
     return new CodeVariableReferenceExpression(prefix + i);
 }
        public CodeAttributeDeclaration(CodeTypeReference attributeType, params CodeAttributeArgument[] arguments) {
            this.attributeType = attributeType;                
            if( attributeType != null) {
                this.name = attributeType.BaseType;
            }

            if(arguments != null) {
                Arguments.AddRange(arguments);
            }
        }
Example #5
0
    public static bool TypeEquals(this CodeTypeReference self, CodeTypeReference other)
    {
        if (self.BaseType != other.BaseType || self.TypeArguments.Count != other.TypeArguments.Count)
            return false;

        for (int i = 0; i < self.TypeArguments.Count; i++) {
            if (!self.TypeArguments[i].TypeEquals(other.TypeArguments[i]))
                return false;
        }
        return true;
    }
Example #6
0
    // Return the CodeDom type reference corresponding to T, or null
    public CodeTypeReference CppTypeToCodeDomType(CppType t, out bool byref)
    {
        CodeTypeReference rtype = null;

        byref = false;
        Type mtype = t.ToManagedType ();
        if (mtype != null) {
            if (mtype.IsByRef) {
                byref = true;
                mtype = mtype.GetElementType ();
            }
            return new CodeTypeReference (mtype);
        }

        if (t.Modifiers.Count > 0 && t.ElementType != CppTypes.Void && t.ElementType != CppTypes.Class)
            return null;
        switch (t.ElementType) {
        case CppTypes.Void:
            if (t.Modifiers.Count > 0) {
                if (t.Modifiers.Count == 1 && t.Modifiers [0] == CppModifiers.Pointer)
                    rtype = new CodeTypeReference (typeof (IntPtr));
                else
                    return null;
            } else {
                rtype = new CodeTypeReference (typeof (void));
            }
            break;
        case CppTypes.Bool:
            rtype = new CodeTypeReference (typeof (bool));
            break;
        case CppTypes.Int:
            rtype = new CodeTypeReference (typeof (int));
            break;
        case CppTypes.Float:
            rtype = new CodeTypeReference (typeof (float));
            break;
        case CppTypes.Double:
            rtype = new CodeTypeReference (typeof (double));
            break;
        case CppTypes.Char:
            rtype = new CodeTypeReference (typeof (char));
            break;
        case CppTypes.Class:
            // FIXME: Full name
            rtype = new CodeTypeReference (t.ElementTypeName);
            break;
        default:
            return null;
        }
        return rtype;
    }
		public void Ctor_CodeTypeReference(CodeTypeReference attributeType, CodeAttributeArgument[] arguments)
		{
			if (arguments == null || arguments.Length == 0)
			{
				var declaration1 = new CodeAttributeDeclaration(attributeType);
				Assert.Equal(attributeType?.BaseType ?? string.Empty, declaration1.Name);
				Assert.Equal(attributeType, declaration1.AttributeType);
				Assert.Empty(declaration1.Arguments);
			}
			var declaration2 = new CodeAttributeDeclaration(attributeType, arguments);
			Assert.Equal(attributeType?.BaseType ?? string.Empty, declaration2.Name);
			Assert.Equal(attributeType, declaration2.AttributeType);
			Assert.Equal(arguments ?? new CodeAttributeArgument[0], declaration2.Arguments.Cast<CodeAttributeArgument>());
		}
Example #8
0
        public CodeTypeReference(Type type) {
            if (type == null)
                throw new ArgumentNullException("type");
            
            if (type.IsArray) {
                this.arrayRank = type.GetArrayRank();
                this.arrayElementType = new CodeTypeReference(type.GetElementType());
                this.baseType = null;
            } else {
                InitializeFromType(type);
                this.arrayRank = 0;
                this.arrayElementType = null;
            }

            this.isInterface = type.IsInterface;
        }
Example #9
0
 public static void FormatComment(string docs, CodeTypeMember cmp, bool obsolete = false, string tag = "summary")
 {
     StringBuilder obsoleteMessageBuilder = new StringBuilder();
     cmp.Comments.Add(new CodeCommentStatement(string.Format("<{0}>", tag), true));
     foreach (string line in HtmlEncoder.HtmlEncode(docs).Split(Environment.NewLine.ToCharArray(), StringSplitOptions.None))
     {
         cmp.Comments.Add(new CodeCommentStatement(string.Format("<para>{0}</para>", line), true));
         if (obsolete && (line.Contains("instead") || line.Contains("deprecated")))
         {
             obsoleteMessageBuilder.Append(HtmlEncoder.HtmlDecode(line));
             obsoleteMessageBuilder.Append(' ');
         }
     }
     cmp.Comments.Add(new CodeCommentStatement(string.Format("</{0}>", tag), true));
     if (obsoleteMessageBuilder.Length > 0)
     {
         obsoleteMessageBuilder.Remove(obsoleteMessageBuilder.Length - 1, 1);
         CodeTypeReference obsoleteAttribute = new CodeTypeReference(typeof(ObsoleteAttribute));
         CodePrimitiveExpression obsoleteMessage = new CodePrimitiveExpression(obsoleteMessageBuilder.ToString());
         cmp.CustomAttributes.Add(new CodeAttributeDeclaration(obsoleteAttribute, new CodeAttributeArgument(obsoleteMessage)));
     }
 }
Example #10
0
 public CodeMemberField(Type type, string name)
 {
     Type = new CodeTypeReference(type);
     Name = name;
 }
Example #11
0
        private static void SetMemberPropertyType(CodeTypeDeclaration typeDeclaration, CodeMemberProperty memberProperty, string typeName)
        {
            var typeReference = new CodeTypeReference(typeName);

            SetMemberPropertyType(typeDeclaration, memberProperty, typeReference);
        }
        CodeMemberMethod GenerateOperationMethod(CodeTypeDeclaration type, ContractDescription cd, OperationDescription od, bool async, out CodeTypeReference returnType)
        {
            CodeMemberMethod cm = new CodeMemberMethod();

            if (od.Behaviors.Find <XmlSerializerMappingBehavior> () != null)
            {
                cm.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlSerializerFormatAttribute))));
            }

            if (async)
            {
                cm.Name = "Begin" + od.Name;
            }
            else
            {
                cm.Name = od.Name;
            }

            if (od.SyncMethod != null)
            {
                ExportParameters(cm, od.SyncMethod.GetParameters());
                if (async)
                {
                    AddBeginAsyncArgs(cm);
                    cm.ReturnType = new CodeTypeReference(typeof(IAsyncResult));
                }
                else
                {
                    cm.ReturnType = new CodeTypeReference(od.SyncMethod.ReturnType);
                }
                returnType = new CodeTypeReference(od.SyncMethod.ReturnType);
            }
            else
            {
                ExportMessages(od.Messages, cm, false);
                returnType = cm.ReturnType;
                if (async)
                {
                    AddBeginAsyncArgs(cm);
                    cm.ReturnType = new CodeTypeReference(typeof(IAsyncResult));
                }
            }

            // [OperationContract (Action = "...", ReplyAction = "..")]
            var ad = new CodeAttributeDeclaration(new CodeTypeReference(typeof(OperationContractAttribute)));

            foreach (MessageDescription md in od.Messages)
            {
                if (md.Direction == MessageDirection.Input)
                {
                    ad.Arguments.Add(new CodeAttributeArgument("Action", new CodePrimitiveExpression(md.Action)));
                }
                else
                {
                    ad.Arguments.Add(new CodeAttributeArgument("ReplyAction", new CodePrimitiveExpression(md.Action)));
                }
            }
            if (async)
            {
                ad.Arguments.Add(new CodeAttributeArgument("AsyncPattern", new CodePrimitiveExpression(true)));
            }
            cm.CustomAttributes.Add(ad);

            return(cm);
        }
        void GenerateEventBasedAsyncSupport(CodeTypeDeclaration type, OperationDescription od, CodeNamespace cns)
        {
            var  method      = FindByName(type, od.Name) ?? FindByName(type, "Begin" + od.Name);
            var  endMethod   = method.Name == od.Name ? null : FindByName(type, "End" + od.Name);
            bool methodAsync = method.Name.StartsWith("Begin", StringComparison.Ordinal);
            var  resultType  = endMethod != null ? endMethod.ReturnType : method.ReturnType;

            var thisExpr        = new CodeThisReferenceExpression();
            var baseExpr        = new CodeBaseReferenceExpression();
            var nullExpr        = new CodePrimitiveExpression(null);
            var asyncResultType = new CodeTypeReference(typeof(IAsyncResult));

            // OnBeginXxx() implementation
            var cm = new CodeMemberMethod()
            {
                Name       = "OnBegin" + od.Name,
                Attributes = MemberAttributes.Private | MemberAttributes.Final,
                ReturnType = asyncResultType
            };

            type.Members.Add(cm);

            AddMethodParam(cm, typeof(object []), "args");
            AddMethodParam(cm, typeof(AsyncCallback), "asyncCallback");
            AddMethodParam(cm, typeof(object), "userState");

            var call = new CodeMethodInvokeExpression(
                thisExpr,
                "Begin" + od.Name);

            for (int idx = 0; idx < method.Parameters.Count - (methodAsync ? 2 : 0); idx++)
            {
                var p = method.Parameters [idx];
                cm.Statements.Add(new CodeVariableDeclarationStatement(p.Type, p.Name, new CodeCastExpression(p.Type, new CodeArrayIndexerExpression(new CodeArgumentReferenceExpression("args"), new CodePrimitiveExpression(idx)))));
                call.Parameters.Add(new CodeVariableReferenceExpression(p.Name));
            }
            call.Parameters.Add(new CodeArgumentReferenceExpression("asyncCallback"));
            call.Parameters.Add(new CodeArgumentReferenceExpression("userState"));
            cm.Statements.Add(new CodeMethodReturnStatement(call));

            // OnEndXxx() implementation
            cm = new CodeMemberMethod()
            {
                Name       = "OnEnd" + od.Name,
                Attributes = MemberAttributes.Private | MemberAttributes.Final,
                ReturnType = new CodeTypeReference(typeof(object []))
            };
            type.Members.Add(cm);

            AddMethodParam(cm, typeof(IAsyncResult), "result");

            var outArgRefs = new List <CodeVariableReferenceExpression> ();

            for (int idx = 0; idx < method.Parameters.Count; idx++)
            {
                var p = method.Parameters [idx];
                if (p.Direction != FieldDirection.In)
                {
                    cm.Statements.Add(new CodeVariableDeclarationStatement(p.Type, p.Name));
                    outArgRefs.Add(new CodeVariableReferenceExpression(p.Name));                       // FIXME: should this work? They need "out" or "ref" modifiers.
                }
            }

            call = new CodeMethodInvokeExpression(
                thisExpr,
                "End" + od.Name,
                new CodeArgumentReferenceExpression("result"));
            call.Parameters.AddRange(outArgRefs.Cast <CodeExpression> ().ToArray());              // questionable

            var retCreate = new CodeArrayCreateExpression(typeof(object));

            if (resultType.BaseType == "System.Void")
            {
                cm.Statements.Add(call);
            }
            else
            {
                cm.Statements.Add(new CodeVariableDeclarationStatement(typeof(object), "__ret", call));
                retCreate.Initializers.Add(new CodeVariableReferenceExpression("__ret"));
            }
            foreach (var outArgRef in outArgRefs)
            {
                retCreate.Initializers.Add(new CodeVariableReferenceExpression(outArgRef.VariableName));
            }

            cm.Statements.Add(new CodeMethodReturnStatement(retCreate));

            // OnXxxCompleted() implementation
            cm = new CodeMemberMethod()
            {
                Name       = "On" + od.Name + "Completed",
                Attributes = MemberAttributes.Private | MemberAttributes.Final
            };
            type.Members.Add(cm);

            AddMethodParam(cm, typeof(object), "state");

            string argsname        = identifiers.AddUnique(od.Name + "CompletedEventArgs", null);
            var    iaargs          = new CodeTypeReference("InvokeAsyncCompletedEventArgs");  // avoid messy System.Type instance for generic nested type :|
            var    iaref           = new CodeVariableReferenceExpression("args");
            var    methodEventArgs = new CodeObjectCreateExpression(new CodeTypeReference(argsname),
                                                                    new CodePropertyReferenceExpression(iaref, "Results"),
                                                                    new CodePropertyReferenceExpression(iaref, "Error"),
                                                                    new CodePropertyReferenceExpression(iaref, "Cancelled"),
                                                                    new CodePropertyReferenceExpression(iaref, "UserState"));

            cm.Statements.Add(new CodeConditionStatement(
                                  new CodeBinaryOperatorExpression(
                                      new CodeEventReferenceExpression(thisExpr, od.Name + "Completed"), CodeBinaryOperatorType.IdentityInequality, nullExpr),
                                  new CodeVariableDeclarationStatement(iaargs, "args", new CodeCastExpression(iaargs, new CodeArgumentReferenceExpression("state"))),
                                  new CodeExpressionStatement(new CodeMethodInvokeExpression(thisExpr, od.Name + "Completed", thisExpr, methodEventArgs))));

            // delegate fields
            type.Members.Add(new CodeMemberField(new CodeTypeReference("BeginOperationDelegate"), "onBegin" + od.Name + "Delegate"));
            type.Members.Add(new CodeMemberField(new CodeTypeReference("EndOperationDelegate"), "onEnd" + od.Name + "Delegate"));
            type.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(SendOrPostCallback)), "on" + od.Name + "CompletedDelegate"));

            // XxxCompletedEventArgs class
            var argsType = new CodeTypeDeclaration(argsname);

            argsType.BaseTypes.Add(new CodeTypeReference(typeof(AsyncCompletedEventArgs)));
            cns.Types.Add(argsType);

            var argsCtor = new CodeConstructor()
            {
                Attributes = MemberAttributes.Public | MemberAttributes.Final
            };

            argsCtor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object []), "results"));
            argsCtor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Exception), "error"));
            argsCtor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(bool), "cancelled"));
            argsCtor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "userState"));
            argsCtor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("error"));
            argsCtor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("cancelled"));
            argsCtor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("userState"));
            var resultsField = new CodeFieldReferenceExpression(thisExpr, "results");

            argsCtor.Statements.Add(new CodeAssignStatement(resultsField, new CodeArgumentReferenceExpression("results")));
            argsType.Members.Add(argsCtor);

            argsType.Members.Add(new CodeMemberField(typeof(object []), "results"));

            if (resultType.BaseType != "System.Void")
            {
                var resultProp = new CodeMemberProperty {
                    Name       = "Result",
                    Type       = resultType,
                    Attributes = MemberAttributes.Public | MemberAttributes.Final
                };
                resultProp.GetStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(resultProp.Type, new CodeArrayIndexerExpression(resultsField, new CodePrimitiveExpression(0)))));
                argsType.Members.Add(resultProp);
            }

            // event field
            var handlerType = new CodeTypeReference(typeof(EventHandler <>));

            handlerType.TypeArguments.Add(new CodeTypeReference(argsType.Name));
            type.Members.Add(new CodeMemberEvent()
            {
                Name       = od.Name + "Completed",
                Type       = handlerType,
                Attributes = MemberAttributes.Public | MemberAttributes.Final
            });

            // XxxAsync() implementations
            bool hasAsync = false;

            foreach (int __x in Enumerable.Range(0, 2))
            {
                cm = new CodeMemberMethod();
                type.Members.Add(cm);
                cm.Name       = od.Name + "Async";
                cm.Attributes = MemberAttributes.Public
                                | MemberAttributes.Final;

                var inArgs = new List <CodeParameterDeclarationExpression> ();

                for (int idx = 0; idx < method.Parameters.Count - (methodAsync ? 2 : 0); idx++)
                {
                    var pd = method.Parameters [idx];
                    inArgs.Add(pd);
                    cm.Parameters.Add(pd);
                }

                // First one is overload without asyncState arg.
                if (!hasAsync)
                {
                    call = new CodeMethodInvokeExpression(thisExpr, cm.Name, inArgs.ConvertAll <CodeExpression> (decl => new CodeArgumentReferenceExpression(decl.Name)).ToArray());
                    call.Parameters.Add(nullExpr);
                    cm.Statements.Add(new CodeExpressionStatement(call));
                    hasAsync = true;
                    continue;
                }

                // Second one is the primary one.

                cm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "userState"));

                // if (onBeginBarOperDelegate == null) onBeginBarOperDelegate = new BeginOperationDelegate (OnBeginBarOper);
                // if (onEndBarOperDelegate == null) onEndBarOperDelegate = new EndOperationDelegate (OnEndBarOper);
                // if (onBarOperCompletedDelegate == null) onBarOperCompletedDelegate = new BeginOperationDelegate (OnBarOperCompleted);
                var beginOperDelegateRef     = new CodeFieldReferenceExpression(thisExpr, "onBegin" + od.Name + "Delegate");
                var endOperDelegateRef       = new CodeFieldReferenceExpression(thisExpr, "onEnd" + od.Name + "Delegate");
                var operCompletedDelegateRef = new CodeFieldReferenceExpression(thisExpr, "on" + od.Name + "CompletedDelegate");

                var ifstmt = new CodeConditionStatement(
                    new CodeBinaryOperatorExpression(beginOperDelegateRef, CodeBinaryOperatorType.IdentityEquality, nullExpr),
                    new CodeAssignStatement(beginOperDelegateRef, new CodeDelegateCreateExpression(new CodeTypeReference("BeginOperationDelegate"), thisExpr, "OnBegin" + od.Name)));
                cm.Statements.Add(ifstmt);
                ifstmt = new CodeConditionStatement(
                    new CodeBinaryOperatorExpression(endOperDelegateRef, CodeBinaryOperatorType.IdentityEquality, nullExpr),
                    new CodeAssignStatement(endOperDelegateRef, new CodeDelegateCreateExpression(new CodeTypeReference("EndOperationDelegate"), thisExpr, "OnEnd" + od.Name)));
                cm.Statements.Add(ifstmt);
                ifstmt = new CodeConditionStatement(
                    new CodeBinaryOperatorExpression(operCompletedDelegateRef, CodeBinaryOperatorType.IdentityEquality, nullExpr),
                    new CodeAssignStatement(operCompletedDelegateRef, new CodeDelegateCreateExpression(new CodeTypeReference(typeof(SendOrPostCallback)), thisExpr, "On" + od.Name + "Completed")));
                cm.Statements.Add(ifstmt);

                // InvokeAsync (onBeginBarOperDelegate, inValues, onEndBarOperDelegate, onBarOperCompletedDelegate, userState);

                inArgs.Add(new CodeParameterDeclarationExpression(typeof(object), "userState"));

                var args = new List <CodeExpression> ();
                args.Add(beginOperDelegateRef);
                args.Add(new CodeArrayCreateExpression(typeof(object), inArgs.ConvertAll <CodeExpression> (decl => new CodeArgumentReferenceExpression(decl.Name)).ToArray()));
                args.Add(endOperDelegateRef);
                args.Add(new CodeFieldReferenceExpression(thisExpr, "on" + od.Name + "CompletedDelegate"));
                args.Add(new CodeArgumentReferenceExpression("userState"));
                call = new CodeMethodInvokeExpression(baseExpr, "InvokeAsync", args.ToArray());
                cm.Statements.Add(new CodeExpressionStatement(call));
            }
        }
        void GenerateProxyClass(ContractDescription cd, CodeNamespace cns)
        {
            string name = cd.Name + "Client";

            if (name [0] == 'I')
            {
                name = name.Substring(1);
            }
            name = identifiers.AddUnique(name, null);
            CodeTypeDeclaration type = GetTypeDeclaration(cns, name);

            if (type != null)
            {
                return;                 // already imported
            }
            CodeTypeReference clientBase = new CodeTypeReference(typeof(ClientBase <>));

            clientBase.TypeArguments.Add(new CodeTypeReference(cd.Name));
            type = new CodeTypeDeclaration(name);
            cns.Types.Add(type);
            type.TypeAttributes = TypeAttributes.Public;
            type.BaseTypes.Add(clientBase);
            type.BaseTypes.Add(new CodeTypeReference(cd.Name));

            // .ctor()
            CodeConstructor ctor = new CodeConstructor();

            ctor.Attributes = MemberAttributes.Public;
            type.Members.Add(ctor);

            // .ctor(string endpointConfigurationName)
            ctor            = new CodeConstructor();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference(typeof(string)), "endpointConfigurationName"));
            ctor.BaseConstructorArgs.Add(
                new CodeArgumentReferenceExpression("endpointConfigurationName"));
            type.Members.Add(ctor);

            // .ctor(string endpointConfigurationName, string remoteAddress)
            ctor            = new CodeConstructor();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference(typeof(string)), "endpointConfigurationName"));
            ctor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference(typeof(string)), "remoteAddress"));
            ctor.BaseConstructorArgs.Add(
                new CodeArgumentReferenceExpression("endpointConfigurationName"));
            ctor.BaseConstructorArgs.Add(
                new CodeArgumentReferenceExpression("remoteAddress"));
            type.Members.Add(ctor);

            // .ctor(string endpointConfigurationName, EndpointAddress remoteAddress)
            ctor            = new CodeConstructor();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference(typeof(string)), "endpointConfigurationName"));
            ctor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference(typeof(EndpointAddress)), "remoteAddress"));
            ctor.BaseConstructorArgs.Add(
                new CodeArgumentReferenceExpression("endpointConfigurationName"));
            ctor.BaseConstructorArgs.Add(
                new CodeArgumentReferenceExpression("remoteAddress"));
            type.Members.Add(ctor);

            // .ctor(Binding,EndpointAddress)
            ctor            = new CodeConstructor();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference(typeof(Binding)), "binding"));
            ctor.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference(typeof(EndpointAddress)), "endpoint"));
            ctor.BaseConstructorArgs.Add(
                new CodeArgumentReferenceExpression("binding"));
            ctor.BaseConstructorArgs.Add(
                new CodeArgumentReferenceExpression("endpoint"));
            type.Members.Add(ctor);

            // service contract methods
            AddImplementationClientMethods(type, cd);

            if (GenerateEventBasedAsync)
            {
                foreach (var od in cd.Operations)
                {
                    GenerateEventBasedAsyncSupport(type, od, cns);
                }
            }
        }
 public virtual string GetTypeOutput(CodeTypeReference type)
 {
     ICodeGenerator cg = CreateGenerator();
     if (cg == null)
         throw GetNotImplemented();
     return cg.GetTypeOutput(type);
 }
 public CodeTypeReference()
 {
     this.baseType = string.Empty;
     this.arrayRank = 0;
     this.arrayElementType = null;
 }
Example #17
0
 public CodeTypeReferenceExpression(CodeTypeReference type)
 {
     Type = type;
 }
Example #18
0
 public static CodeMemberMethod Method(CodeTypeReference ReturnType)
 {
     return(Method(null, ReturnType));
 }
Example #19
0
        internal bool ParseXaml(TextReader xaml)
        {
            var xmlDoc = new XmlDocument();

            xmlDoc.Load(xaml);

            // if the following xml processing instruction is present
            //
            // <?xaml-comp compile="true" ?>
            //
            // we will generate a xaml.g.cs file with the default ctor calling InitializeComponent, and a XamlCompilation attribute
            var hasXamlCompilationProcessingInstruction = GetXamlCompilationProcessingInstruction(xmlDoc);

            var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);

            nsmgr.AddNamespace("__f__", XamlParser.XFUri);

            var root = xmlDoc.SelectSingleNode("/*", nsmgr);

            if (root == null)
            {
                Logger?.LogMessage(MessageImportance.Low, " No root node found");
                return(false);
            }

            foreach (XmlAttribute attr in root.Attributes)
            {
                if (attr.Name == "xmlns")
                {
                    nsmgr.AddNamespace("", attr.Value);                     //Add default xmlns
                }
                if (attr.Prefix != "xmlns")
                {
                    continue;
                }
                nsmgr.AddNamespace(attr.LocalName, attr.Value);
            }

            var rootClass = root.Attributes["Class", XamlParser.X2006Uri]
                            ?? root.Attributes["Class", XamlParser.X2009Uri];

            if (rootClass != null)
            {
                string rootType, rootNs, rootAsm, targetPlatform;
                XmlnsHelper.ParseXmlns(rootClass.Value, out rootType, out rootNs, out rootAsm, out targetPlatform);
                RootType         = rootType;
                RootClrNamespace = rootNs;
            }
            else if (hasXamlCompilationProcessingInstruction)
            {
                RootClrNamespace            = "__XamlGeneratedCode__";
                RootType                    = $"__Type{Guid.NewGuid().ToString("N")}";
                GenerateDefaultCtor         = true;
                AddXamlCompilationAttribute = true;
                HideFromIntellisense        = true;
            }
            else
            {                              // rootClass == null && !hasXamlCompilationProcessingInstruction) {
                XamlResourceIdOnly = true; //only generate the XamlResourceId assembly attribute
                return(true);
            }

            NamedFields = GetCodeMemberFields(root, nsmgr);
            var typeArguments = GetAttributeValue(root, "TypeArguments", XamlParser.X2006Uri, XamlParser.X2009Uri);
            var xmlType       = new XmlType(root.NamespaceURI, root.LocalName, typeArguments != null ? TypeArgumentsParser.ParseExpression(typeArguments, nsmgr, null) : null);

            BaseType = GetType(xmlType, root.GetNamespaceOfPrefix);

            return(true);
        }
Example #20
0
        CodeMemberMethod ImplementFindFragment(CodeTypeReference typeForParent, CodeTypeReference typeForOverloadCall = null, Func <CodeVariableReferenceExpression, CodeExpression> constructParentViewCall = null)
        {
            CodeMemberMethod method = CreateMethod("__FindFragment", MethodAccessibility.Private, MethodScope.Final);

            var typeParam = new CodeTypeParameter("T")
            {
                Constraints =
                {
                    new CodeTypeReference("Android.App.Fragment", CodeTypeReferenceOptions.GlobalReference),
                },
            };

            method.TypeParameters.Add(typeParam);
            method.Parameters.Add(new CodeParameterDeclarationExpression(typeForParent, "activity"));
            method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "id"));

            var tReference = new CodeTypeReference(typeParam);

            method.ReturnType = tReference;

            // T fragment = FragmentManager.FindFragmentById<T> (id);
            var id = new CodeVariableReferenceExpression("id");

            var findByIdRef = new CodeMethodReferenceExpression(
                new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("activity"), "FragmentManager"),
                "FindFragmentById",
                new[] { tReference }
                );

            var findByIdInvoke = new CodeMethodInvokeExpression(findByIdRef, new[] { id });
            var viewVar        = new CodeVariableDeclarationStatement(tReference, "fragment", findByIdInvoke);

            method.Statements.Add(viewVar);

            // if (view == null) {
            //     OnLayoutFragmentNotFound (resourceId, ref view);
            // }
            // if (view != null)
            //     return view;
            // throw new System.InvalidOperationException($"Fragment not found (ID: {id})");

            var viewVarRef    = new CodeVariableReferenceExpression("fragment");
            var ifViewNotNull = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(viewVarRef, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)),
                new CodeStatement[] { new CodeMethodReturnStatement(viewVarRef) }
                );

            var viewRefParam       = new CodeDirectionExpression(FieldDirection.Ref, viewVarRef);
            var viewNotFoundInvoke = new CodeMethodInvokeExpression(
                new CodeThisReferenceExpression(),
                "OnLayoutFragmentNotFound",
                new CodeExpression[] { id, viewRefParam }
                );

            var ifViewNull = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(viewVarRef, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null)),
                new CodeStatement[] { new CodeExpressionStatement(viewNotFoundInvoke) }
                );

            method.Statements.Add(ifViewNull);
            method.Statements.Add(ifViewNotNull);

            var throwInvOp = new CodeThrowExceptionStatement(
                new CodeObjectCreateExpression(
                    new CodeTypeReference(typeof(InvalidOperationException), CodeTypeReferenceOptions.GlobalReference),
                    new[] { new CodeSnippetExpression("$\"Fragment not found (ID: {id})\"") }
                    )
                );

            method.Statements.Add(throwInvOp);

            return(method);
        }
Example #21
0
        CodeMemberMethod ImplementFindView(CodeTypeReference typeForParent, CodeTypeReference typeForOverloadCall = null, Func <CodeVariableReferenceExpression, CodeExpression> constructParentViewCall = null)
        {
            CodeMemberMethod method = CreateMethod("__FindView", MethodAccessibility.Private, MethodScope.Final);

            // T __FindView<T> (int resourceId) where T: Android.Views.View
            var typeParam = new CodeTypeParameter("T");

            typeParam.Constraints.Add(new CodeTypeReference("Android.Views.View", CodeTypeReferenceOptions.GlobalReference));
            method.TypeParameters.Add(typeParam);
            method.Parameters.Add(new CodeParameterDeclarationExpression(typeForParent, "parentView"));
            method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "resourceId"));

            var tReference = new CodeTypeReference(typeParam);

            method.ReturnType = tReference;

            // T view = parentView.FindViewById<T> (resourceId);
            var parentViewRef    = new CodeVariableReferenceExpression("parentView");
            var resourceIdVarRef = new CodeVariableReferenceExpression("resourceId");

            if (typeForOverloadCall != null)
            {
                var findViewRef = new CodeMethodReferenceExpression(
                    new CodeThisReferenceExpression(),
                    "__FindView",
                    new [] { tReference }
                    );

                CodeExpression parentViewParam;
                if (constructParentViewCall != null)
                {
                    parentViewParam = constructParentViewCall(parentViewRef);
                }
                else
                {
                    parentViewParam = parentViewRef;
                }
                var findViewCall = new CodeMethodInvokeExpression(findViewRef, new CodeExpression [] { parentViewParam, resourceIdVarRef });
                method.Statements.Add(new CodeMethodReturnStatement(findViewCall));

                return(method);
            }

            var findByIdRef = new CodeMethodReferenceExpression(
                parentViewRef,
                "FindViewById",
                new [] { tReference }
                );

            var findByIdInvoke = new CodeMethodInvokeExpression(findByIdRef, new [] { resourceIdVarRef });
            var viewVar        = new CodeVariableDeclarationStatement(tReference, "view", findByIdInvoke);

            method.Statements.Add(viewVar);

            // if (view == null) {
            //     OnLayoutViewNotFound (resourceId, ref view);
            // }
            // if (view != null)
            //     return view;
            // throw new System.InvalidOperationException($"View not found (ID: {resourceId})");

            var viewVarRef    = new CodeVariableReferenceExpression("view");
            var ifViewNotNull = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(viewVarRef, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)),
                new CodeStatement [] { new CodeMethodReturnStatement(viewVarRef) }
                );

            var viewRefParam       = new CodeDirectionExpression(FieldDirection.Ref, viewVarRef);
            var viewNotFoundInvoke = new CodeMethodInvokeExpression(
                new CodeThisReferenceExpression(),
                "OnLayoutViewNotFound",
                new CodeExpression [] { resourceIdVarRef, viewRefParam }
                );

            var ifViewNull = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(viewVarRef, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null)),
                new CodeStatement [] { new CodeExpressionStatement(viewNotFoundInvoke) }
                );

            method.Statements.Add(ifViewNull);
            method.Statements.Add(ifViewNotNull);

            var throwInvOp = new CodeThrowExceptionStatement(
                new CodeObjectCreateExpression(
                    new CodeTypeReference(typeof(InvalidOperationException), CodeTypeReferenceOptions.GlobalReference),
                    new [] { new CodeSnippetExpression("$\"View not found (ID: {resourceId})\"") }
                    )
                );

            method.Statements.Add(throwInvOp);

            return(method);
        }
Example #22
0
        CodeMemberMethod CreateMethod(string methodName, MethodAccessibility access, MethodScope scope, CodeTypeReference returnType)
        {
            var ret = new CodeMemberMethod {
                Name = methodName,
            };

            if (returnType != null)
            {
                ret.ReturnType = returnType;
            }

            MemberAttributes attrs;

            switch (access)
            {
            case MethodAccessibility.Internal:
                attrs = MemberAttributes.FamilyAndAssembly;
                break;

            case MethodAccessibility.Private:
                attrs = MemberAttributes.Private;
                break;

            case MethodAccessibility.Protected:
                attrs = MemberAttributes.Family;
                break;

            case MethodAccessibility.Public:
                attrs = MemberAttributes.Public;
                break;

            default:
                throw new NotSupportedException($"Method accessibility {access} is not supported");
            }

            if ((scope & MethodScope.Static) == MethodScope.Static)
            {
                attrs |= MemberAttributes.Static | MemberAttributes.Final;
            }
            else if ((scope & MethodScope.Abstract) == MethodScope.Abstract)
            {
                attrs |= MemberAttributes.Abstract;
            }
            else
            {
                if ((scope & MethodScope.Override) == MethodScope.Override)
                {
                    attrs |= MemberAttributes.Override;
                }
                else if ((scope & MethodScope.Virtual) == MethodScope.Virtual)
                {
                }
                else
                {
                    attrs |= MemberAttributes.Final;
                }
            }

            ret.Attributes = attrs;
            return(ret);
        }
Example #23
0
        private static void SetMemberPropertyType(CodeTypeDeclaration typeDeclaration, CodeMemberProperty memberProperty, CodeTypeReference typeReference)
        {
            var memberField = GetMemberField(typeDeclaration, memberProperty.Name + "Field");

            memberField.Type    = typeReference;
            memberProperty.Type = typeReference;
        }
Example #24
0
 public CodeVariableReferenceExpression GenSymParameter(string prefix, CodeTypeReference type)
 {
     return GenSymAutomatic(prefix, type, true);
 }
        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");
        }
Example #26
0
 public CodeTypeReferenceExpression(Type type)
 {
     Type = new CodeTypeReference(type);
 }
 public CodeTypeReference(string baseType, int rank)
 {
     this.baseType = null;
     this.arrayRank = rank;
     this.arrayElementType = new CodeTypeReference(baseType);
 }
	public void CopyTo(CodeTypeReference[] array, int index) {}
	public CodeTypeOfExpression(CodeTypeReference type) {}
	public void Insert(int index, CodeTypeReference value) {}
Example #31
0
 public CodeMemberField(CodeTypeReference type, string name)
 {
     Type = type;
     Name = name;
 }
	public CodeTypeReferenceCollection(CodeTypeReference[] value) {}
        CodeMemberMethod GenerateImplementationClientMethod(CodeTypeDeclaration type, ContractDescription cd, OperationDescription od, bool async, out CodeTypeReference returnTypeFromMessageContract)
        {
            CodeMemberMethod cm = new CodeMemberMethod();

            if (async)
            {
                cm.Name = "Begin" + od.Name;
            }
            else
            {
                cm.Name = od.Name;
            }
            cm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            returnTypeFromMessageContract = null;

            List <CodeExpression> args = new List <CodeExpression> ();

            if (od.SyncMethod != null)
            {
                ParameterInfo [] pars = od.SyncMethod.GetParameters();
                ExportParameters(cm, pars);
                cm.ReturnType = new CodeTypeReference(od.SyncMethod.ReturnType);
                int i = 0;
                foreach (ParameterInfo pi in pars)
                {
                    args.Add(new CodeArgumentReferenceExpression(pi.Name));
                }
            }
            else
            {
                args.AddRange(ExportMessages(od.Messages, cm, true));
                returnTypeFromMessageContract = cm.ReturnType;
                if (async)
                {
                    AddBeginAsyncArgs(cm);
                    cm.ReturnType = new CodeTypeReference(typeof(IAsyncResult));
                }
            }
            if (async)
            {
                args.Add(new CodeArgumentReferenceExpression("asyncCallback"));
                args.Add(new CodeArgumentReferenceExpression("userState"));
            }

            CodeExpression call = new CodeMethodInvokeExpression(
                new CodePropertyReferenceExpression(
                    new CodeBaseReferenceExpression(),
                    "Channel"),
                cm.Name,
                args.ToArray());

            if (cm.ReturnType.BaseType == "System.Void")
            {
                cm.Statements.Add(new CodeExpressionStatement(call));
            }
            else
            {
                cm.Statements.Add(new CodeMethodReturnStatement(call));
            }
            return(cm);
        }
    static CodeNamespace CreateMimsyNamespace()
    {
        CodeNamespace mimsyNamespace =
            new CodeNamespace("Mimsy");

        mimsyNamespace.Imports.AddRange(new[]
        {
            new CodeNamespaceImport("System"),
            new CodeNamespaceImport("System.Text"),
            new CodeNamespaceImport("System.Collections")
        });

        CodeTypeDeclaration jubjubClass =
            new CodeTypeDeclaration("Jubjub")
        {
            TypeAttributes = TypeAttributes.Public
        };

        CodeMemberField wabeCountFld =
            new CodeMemberField(typeof(int), "_wabeCount")
        {
            Attributes = MemberAttributes.Private
        };

        jubjubClass.Members.Add(wabeCountFld);

        var typrefArrayList =
            new CodeTypeReference("ArrayList");

        CodeMemberField updatesFld =
            new CodeMemberField(typrefArrayList, "_updates");

        jubjubClass.Members.Add(updatesFld);

        mimsyNamespace.Types.Add(jubjubClass);

        CodeConstructor jubjubCtor =
            new CodeConstructor()
        {
            Attributes = MemberAttributes.Public
        };

        var jubjubCtorParam =
            new CodeParameterDeclarationExpression(
                typeof(int), "wabeCount");

        jubjubCtor.Parameters.Add(jubjubCtorParam);

        var refUpdatesFld =
            new CodeFieldReferenceExpression(
                new CodeThisReferenceExpression(),
                "_updates");
        var newArrayList =
            new CodeObjectCreateExpression(typrefArrayList);
        var assignUpdates =
            new CodeAssignStatement(
                refUpdatesFld, newArrayList);

        jubjubCtor.Statements.Add(assignUpdates);

        var refWabeCountFld =
            new CodeFieldReferenceExpression(
                new CodeThisReferenceExpression(),
                "_wabeCount");
        var refWabeCountProp =
            new CodePropertyReferenceExpression(
                new CodeThisReferenceExpression(),
                "WabeCount");
        var refWabeCountArg =
            new CodeArgumentReferenceExpression("wabeCount");
        var assignWabeCount =
            new CodeAssignStatement(
                refWabeCountProp, refWabeCountArg);

        jubjubCtor.Statements.Add(assignWabeCount);

        jubjubClass.Members.Add(jubjubCtor);

        CodeMemberProperty wabeCountProp =
            new CodeMemberProperty()
        {
            Attributes = MemberAttributes.Public
                         | MemberAttributes.Final,
            Type = new CodeTypeReference(typeof(int)),
            Name = "WabeCount"
        };

        wabeCountProp.GetStatements.Add(
            new CodeMethodReturnStatement(refWabeCountFld));

        var suppliedPropertyValue =
            new CodePropertySetValueReferenceExpression();
        var zero = new CodePrimitiveExpression(0);

        var suppliedPropValIsLessThanZero =
            new CodeBinaryOperatorExpression(
                suppliedPropertyValue,
                CodeBinaryOperatorType.LessThan,
                zero);

        var testSuppliedPropValAndAssign =
            new CodeConditionStatement(
                suppliedPropValIsLessThanZero,
                new CodeStatement[]
        {
            new CodeAssignStatement(
                refWabeCountFld,
                zero)
        },
                new CodeStatement[]
        {
            new CodeAssignStatement(
                refWabeCountFld,
                suppliedPropertyValue)
        });

        wabeCountProp.SetStatements.Add(
            testSuppliedPropValAndAssign);

        wabeCountProp.SetStatements.Add(
            new CodeMethodInvokeExpression(
                new CodeMethodReferenceExpression(
                    refUpdatesFld,
                    "Add"),
                refWabeCountFld));

        jubjubClass.Members.Add(wabeCountProp);

        CodeMemberMethod methGetWabeCountHistory =
            new CodeMemberMethod()
        {
            Attributes = MemberAttributes.Public
                         | MemberAttributes.Final,
            Name       = "GetWabeCountHistory",
            ReturnType = new CodeTypeReference(typeof(String))
        };

        jubjubClass.Members.Add(methGetWabeCountHistory);

        methGetWabeCountHistory.Statements.Add(
            new CodeVariableDeclarationStatement(
                "StringBuilder", "result"));
        var refResultVar =
            new CodeVariableReferenceExpression("result");

        methGetWabeCountHistory.Statements.Add(
            new CodeAssignStatement(
                refResultVar,
                new CodeObjectCreateExpression(
                    "StringBuilder")));

        methGetWabeCountHistory.Statements.Add(
            new CodeVariableDeclarationStatement(
                typeof(int), "ndx"));
        var refNdxVar =
            new CodeVariableReferenceExpression("ndx");

        methGetWabeCountHistory.Statements.Add(
            new CodeIterationStatement(
                new CodeAssignStatement(
                    refNdxVar,
                    new CodePrimitiveExpression(0)),
                new CodeBinaryOperatorExpression(
                    refNdxVar,
                    CodeBinaryOperatorType.LessThan,
                    new CodePropertyReferenceExpression(
                        refUpdatesFld,
                        "Count")),
                new CodeAssignStatement(
                    refNdxVar,
                    new CodeBinaryOperatorExpression(
                        refNdxVar,
                        CodeBinaryOperatorType.Add,
                        new CodePrimitiveExpression(1))),
                new CodeConditionStatement(
                    new CodeBinaryOperatorExpression(
                        refNdxVar,
                        CodeBinaryOperatorType.ValueEquality,
                        new CodePrimitiveExpression(0)),
                    new CodeStatement[]
        {
            new CodeExpressionStatement(
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        refResultVar,
                        "AppendFormat"),
                    new CodePrimitiveExpression("{0}"),
                    new CodeArrayIndexerExpression(
                        refUpdatesFld,
                        refNdxVar)))
        },
                    new CodeStatement[]
        {
            new CodeExpressionStatement(
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        refResultVar,
                        "AppendFormat"),
                    new CodePrimitiveExpression(", {0}"),
                    new CodeArrayIndexerExpression(
                        refUpdatesFld,
                        refNdxVar)))
        })));

        methGetWabeCountHistory.Statements.Add(
            new CodeMethodReturnStatement(
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        refResultVar, "ToString"))));

        return(mimsyNamespace);
    }
Example #35
0
 private static CodeTypeReference GetCollectionType(ITypedElement property, CodeTypeReference elementType, ITransformationContext context)
 {
     return(new CodeTypeReference(typeof(IEnumerable <>).Name, elementType));
 }
Example #36
0
        private static void SetExtensibleEnum(CodeTypeDeclaration typeDeclaration, CodeMemberProperty memberProperty, string typeName)
        {
            var typeReference = new CodeTypeReference(typeof(DataAccess.ExtensibleEnum <>).FullName, new[] { new CodeTypeReference(typeName) });

            SetMemberPropertyType(typeDeclaration, memberProperty, typeReference);
        }
	public bool Contains(CodeTypeReference value) {}
Example #38
0
        private static string CSharpTypeName(CSharpCodeProvider provider, Type type)
        {
            CodeTypeReference typeRef = new CodeTypeReference(type);

            return(provider.GetTypeOutput(typeRef).Replace("System.", string.Empty));
        }
	public int IndexOf(CodeTypeReference value) {}
Example #40
0
        public static CodeExpression Serialize(object val)
        {
            if (null == val)
            {
                return(new CodePrimitiveExpression(null));
            }
            if (val is bool ||
                val is string ||
                val is short ||
                val is ushort ||
                val is int ||
                val is uint ||
                val is ulong ||
                val is long ||
                val is byte ||
                val is sbyte ||
                val is float ||
                val is double ||
                val is decimal ||
                val is char)
            {
                return(new CodePrimitiveExpression(val));
            }
            if (val is Array && 1 == ((Array)val).Rank && 0 == ((Array)val).GetLowerBound(0))
            {
                return(_SerializeArray((Array)val));
            }
            var conv = TypeDescriptor.GetConverter(val);

            if (null != conv)
            {
                if (conv.CanConvertTo(typeof(InstanceDescriptor)))
                {
                    var desc = conv.ConvertTo(val, typeof(InstanceDescriptor)) as InstanceDescriptor;
                    if (!desc.IsComplete)
                    {
                        throw new NotSupportedException(
                                  string.Format(
                                      "The type \"{0}\" could not be serialized.",
                                      val.GetType().FullName));
                    }
                    var ctor = desc.MemberInfo as ConstructorInfo;
                    if (null != ctor)
                    {
                        var result = new CodeObjectCreateExpression(ctor.DeclaringType);
                        foreach (var arg in desc.Arguments)
                        {
                            result.Parameters.Add(Serialize(arg));
                        }
                        return(result);
                    }
                    throw new NotSupportedException(
                              string.Format(
                                  "The instance descriptor for type \"{0}\" is not supported.",
                                  val.GetType().FullName));
                }
                else
                {
                    // we special case for KeyValuePair types.
                    if (val.GetType().GetGenericTypeDefinition() == typeof(KeyValuePair <,>))
                    {
                        // TODO: Find a workaround for the bug with VBCodeProvider
                        // may need to modify the reference source
                        var kvpType = new CodeTypeReference(typeof(KeyValuePair <,>));
                        foreach (var arg in val.GetType().GetGenericArguments())
                        {
                            kvpType.TypeArguments.Add(arg);
                        }
                        var result = new CodeObjectCreateExpression(kvpType);
                        for (int ic = kvpType.TypeArguments.Count, i = 0; i < ic; ++i)
                        {
                            var prop = val.GetType().GetProperty(0 == i?"Key":"Value");
                            result.Parameters.Add(Serialize(prop.GetValue(val)));
                        }
                        return(result);
                    }
                    throw new NotSupportedException(
                              string.Format("The type \"{0}\" could not be serialized.",
                                            val.GetType().FullName));
                }
            }
            else
            {
                throw new NotSupportedException(
                          string.Format(
                              "The type \"{0}\" could not be serialized.",
                              val.GetType().FullName));
            }
        }
	public void Remove(CodeTypeReference value) {}
Example #42
0
 static CodeTypeReference MakeReadonly(CodeTypeReference typeReference)
 {
     return(ModifyCodeTypeReference(typeReference, "readonly"));
 }
	// Methods
	public int Add(CodeTypeReference value) {}
Example #44
0
 static CodeTypeReference MakeAsync(CodeTypeReference typeReference)
 {
     return(ModifyCodeTypeReference(typeReference, "async"));
 }
Example #45
0
 private void EnsureLocalVariable(string name, CodeTypeReference type, bool parameter)
 {
     if (!autos.ContainsKey(name))
         autos.Add(name, new LocalSymbol(name, type, parameter));
 }
Example #46
0
 static CodeTypeReference ModifyCodeTypeReference(CodeTypeReference typeReference, string modifier)
 {
     using (var provider = new CSharpCodeProvider())
         return(new CodeTypeReference(modifier + " " + provider.GetTypeOutput(typeReference)));
 }
Example #47
0
 public CodeVariableReferenceExpression GenSymLocal(string prefix, CodeTypeReference type)
 {
     return GenSymAutomatic(prefix, type, false);
 }
        internal void ConstructType()
        {
            unit = new CodeCompileUnit();
            byte[] md5checksum = parser.MD5Checksum;

            if (md5checksum != null)
            {
                CodeChecksumPragma pragma = new CodeChecksumPragma();
                pragma.FileName            = parser.InputFile;
                pragma.ChecksumAlgorithmId = HashMD5;
                pragma.ChecksumData        = md5checksum;

                unit.StartDirectives.Add(pragma);
            }

            if (parser.IsPartial)
            {
                string partialns        = null;
                string partialclasstype = parser.PartialClassName;

                int partialdot = partialclasstype.LastIndexOf('.');
                if (partialdot != -1)
                {
                    partialns        = partialclasstype.Substring(0, partialdot);
                    partialclasstype = partialclasstype.Substring(partialdot + 1);
                }

                CodeNamespace partialNS = new CodeNamespace(partialns);
                partialClass           = new CodeTypeDeclaration(partialclasstype);
                partialClass.IsPartial = true;
                partialClassExpr       = new CodeTypeReferenceExpression(parser.PartialClassName);

                unit.Namespaces.Add(partialNS);
                partialClass.TypeAttributes = TypeAttributes.Public;
                partialNS.Types.Add(partialClass);
            }

            string mainclasstype = parser.ClassName;
            string mainns        = DEFAULT_NAMESPACE;
            int    maindot       = mainclasstype.LastIndexOf('.');

            if (maindot != -1)
            {
                mainns        = mainclasstype.Substring(0, maindot);
                mainclasstype = mainclasstype.Substring(maindot + 1);
            }

            mainNS    = new CodeNamespace(mainns);
            mainClass = new CodeTypeDeclaration(mainclasstype);
            CodeTypeReference baseTypeRef;

            if (partialClass != null)
            {
                baseTypeRef          = new CodeTypeReference(parser.PartialClassName);
                baseTypeRef.Options |= CodeTypeReferenceOptions.GlobalReference;
            }
            else
            {
                baseTypeRef = new CodeTypeReference(parser.BaseType.FullName);
                if (parser.BaseTypeIsGlobal)
                {
                    baseTypeRef.Options |= CodeTypeReferenceOptions.GlobalReference;
                }
            }
            mainClass.BaseTypes.Add(baseTypeRef);

            mainClassExpr = new CodeTypeReferenceExpression(mainns + "." + mainclasstype);

            unit.Namespaces.Add(mainNS);
            mainClass.TypeAttributes = TypeAttributes.Public;
            mainNS.Types.Add(mainClass);

            foreach (object o in parser.Imports.Keys)
            {
                if (o is string)
                {
                    mainNS.Imports.Add(new CodeNamespaceImport((string)o));
                }
            }

            // StringCollection.Contains has O(n) complexity, but
            // considering the number of comparisons we make on
            // average and the fact that using an intermediate array
            // would be even more costly, this is fine here.
            StringCollection refAsm = unit.ReferencedAssemblies;
            string           asmName;

            if (parser.Assemblies != null)
            {
                foreach (object o in parser.Assemblies)
                {
                    asmName = o as string;
                    if (asmName != null && !refAsm.Contains(asmName))
                    {
                        refAsm.Add(asmName);
                    }
                }
            }

            ArrayList al = WebConfigurationManager.ExtraAssemblies;

            if (al != null && al.Count > 0)
            {
                foreach (object o in al)
                {
                    asmName = o as string;
                    if (asmName != null && !refAsm.Contains(asmName))
                    {
                        refAsm.Add(asmName);
                    }
                }
            }

            IList list = BuildManager.CodeAssemblies;

            if (list != null && list.Count > 0)
            {
                Assembly asm;
                foreach (object o in list)
                {
                    asm = o as Assembly;
                    if (o == null)
                    {
                        continue;
                    }
                    asmName = asm.Location;
                    if (asmName != null && !refAsm.Contains(asmName))
                    {
                        refAsm.Add(asmName);
                    }
                }
            }

            // Late-bound generators specifics (as for MonoBASIC/VB.NET)
            unit.UserData["RequireVariableDeclaration"] = parser.ExplicitOn;
            unit.UserData["AllowLateBound"]             = !parser.StrictOn;

            InitializeType();
            AddInterfaces();
            AddClassAttributes();
            CreateStaticFields();
            AddApplicationAndSessionObjects();
            AddScripts();
            CreateMethods();
            CreateConstructor(null, null);
        }
        public void GlobalKeyword()
        {
            CodeNamespace ns = new CodeNamespace("Foo");
            ns.Comments.Add(new CodeCommentStatement("Foo namespace"));

            CodeTypeDeclaration cd = new CodeTypeDeclaration("Foo");
            ns.Types.Add(cd);

            string fieldName1 = "_verifyGlobalGeneration1";
            CodeMemberField field = new CodeMemberField();
            field.Name = fieldName1;
            field.Type = new CodeTypeReference(typeof(int), CodeTypeReferenceOptions.GlobalReference);
            field.Attributes = MemberAttributes.Public;
            field.InitExpression = new CodePrimitiveExpression(int.MaxValue);
            cd.Members.Add(field);

            string fieldName2 = "_verifyGlobalGeneration2";
            CodeMemberField field2 = new CodeMemberField();
            field2.Name = fieldName2;
            CodeTypeReference typeRef = new CodeTypeReference("System.Nullable", CodeTypeReferenceOptions.GlobalReference);
            typeRef.TypeArguments.Add(new CodeTypeReference(typeof(int), CodeTypeReferenceOptions.GlobalReference));
            field2.Type = typeRef;
            field2.InitExpression = new CodePrimitiveExpression(0);
            cd.Members.Add(field2);

            CodeMemberMethod method1 = new CodeMemberMethod();
            method1.Name = "TestMethod01";
            method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public | MemberAttributes.Static;
            method1.ReturnType = new CodeTypeReference(typeof(int));
            method1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(int.MaxValue)));
            cd.Members.Add(method1);

            CodeMemberMethod method2 = new CodeMemberMethod();
            method2.Name = "TestMethod02";
            method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            method2.ReturnType = new CodeTypeReference(typeof(int));
            method2.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "iReturn"));

            CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression(
                                              new CodeMethodReferenceExpression(
                                              new CodeTypeReferenceExpression(new CodeTypeReference("Foo.Foo", CodeTypeReferenceOptions.GlobalReference)), "TestMethod01"));
            CodeAssignStatement cas = new CodeAssignStatement(new CodeVariableReferenceExpression("iReturn"), cmie);
            method2.Statements.Add(cas);
            method2.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("iReturn")));
            cd.Members.Add(method2);

            CodeMemberMethod method3 = new CodeMemberMethod();
            method3.Name = "TestMethod03";
            method3.Attributes = (method3.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            method3.ReturnType = new CodeTypeReference(typeof(int));
            method3.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "iReturn"));
            CodeTypeReferenceOptions ctro = CodeTypeReferenceOptions.GlobalReference;
            CodeTypeReference ctr = new CodeTypeReference(typeof(Math), ctro);
            cmie = new CodeMethodInvokeExpression(
                                              new CodeMethodReferenceExpression(
                                              new CodeTypeReferenceExpression(ctr), "Abs"), new CodeExpression[] { new CodePrimitiveExpression(-1) });
            cas = new CodeAssignStatement(new CodeVariableReferenceExpression("iReturn"), cmie);
            method3.Statements.Add(cas);
            method3.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("iReturn")));
            cd.Members.Add(method3);

            CodeMemberProperty property = new CodeMemberProperty();
            property.Name = "GlobalTestProperty1";
            property.Type = new CodeTypeReference(typeof(int));
            property.Attributes = (property.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            property.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(fieldName1)));
            property.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(fieldName1), new CodeVariableReferenceExpression("value")));
            cd.Members.Add(property);

            CodeMemberProperty property2 = new CodeMemberProperty();
            property2.Name = "GlobalTestProperty2";
            property2.Type = typeRef;
            property2.Attributes = (property.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            property2.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(fieldName2)));
            property2.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(fieldName2), new CodeVariableReferenceExpression("value")));
            cd.Members.Add(property2);

            AssertEqual(ns,
                @"'Foo namespace
                  Namespace Foo
                      Public Class Foo
                          Public _verifyGlobalGeneration1 As Integer = 2147483647
                          Private _verifyGlobalGeneration2 As Global.System.Nullable(Of Integer) = 0
                          Public Property GlobalTestProperty1() As Integer
                              Get
                                  Return _verifyGlobalGeneration1
                              End Get
                              Set
                                  _verifyGlobalGeneration1 = value
                              End Set
                          End Property
                          Public Property GlobalTestProperty2() As Global.System.Nullable(Of Integer)
                              Get
                                  Return _verifyGlobalGeneration2
                              End Get
                              Set
                                  _verifyGlobalGeneration2 = value
                              End Set
                          End Property
                          Public Shared Function TestMethod01() As Integer
                              Return 2147483647
                          End Function
                          Public Function TestMethod02() As Integer
                              Dim iReturn As Integer
                              iReturn = Global.Foo.Foo.TestMethod01
                              Return iReturn
                          End Function
                          Public Function TestMethod03() As Integer
                              Dim iReturn As Integer
                              iReturn = Global.System.Math.Abs(-1)
                              Return iReturn
                          End Function
                      End Class
                  End Namespace");
        }
 public CodeAttributeDeclaration(CodeTypeReference attributeType) : this(attributeType, null)
 {
 }
        public void MetadataAttributes()
        {
            var cu = new CodeCompileUnit();

            var ns = new CodeNamespace();
            ns.Name = "MyNamespace";
            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));
            ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
            ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
            cu.Namespaces.Add(ns);

            var attrs = cu.AssemblyCustomAttributes;
            attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly"))));
            attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2"))));
            attrs.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false))));

            var class1 = new CodeTypeDeclaration() { Name = "MyClass" };
            class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable"));
            class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Class"))));
            ns.Types.Add(class1);

            var nestedClass = new CodeTypeDeclaration("NestedClass") { IsClass = true, TypeAttributes = TypeAttributes.NestedPublic };
            nestedClass.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable"));
            class1.Members.Add(nestedClass);

            var method1 = new CodeMemberMethod() { Name = "MyMethod" };
            method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Method"))));
            method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.Editor", new CodeAttributeArgument(new CodePrimitiveExpression("This")), new CodeAttributeArgument(new CodePrimitiveExpression("That"))));
            var param1 = new CodeParameterDeclarationExpression(typeof(string), "blah");
            param1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute",
                            new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
                            new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false))));
            method1.Parameters.Add(param1);
            var param2 = new CodeParameterDeclarationExpression(typeof(int[]), "arrayit");
            param2.CustomAttributes.Add(
                        new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute",
                            new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
                            new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false))));
            method1.Parameters.Add(param2);
            class1.Members.Add(method1);

            var function1 = new CodeMemberMethod();
            function1.Name = "MyFunction";
            function1.ReturnType = new CodeTypeReference(typeof(string));
            function1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function"))));
            function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute"));
            function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new
                CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new
                CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe"))));
            function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return")));
            class1.Members.Add(function1);

            CodeMemberMethod function2 = new CodeMemberMethod();
            function2.Name = "GlobalKeywordFunction";
            function2.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(ObsoleteAttribute), CodeTypeReferenceOptions.GlobalReference), new
                CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function"))));
            CodeTypeReference typeRef = new CodeTypeReference("System.Xml.Serialization.XmlIgnoreAttribute", CodeTypeReferenceOptions.GlobalReference);
            CodeAttributeDeclaration codeAttrib = new CodeAttributeDeclaration(typeRef);
            function2.ReturnTypeCustomAttributes.Add(codeAttrib);
            class1.Members.Add(function2);

            CodeMemberField field1 = new CodeMemberField();
            field1.Name = "myField";
            field1.Type = new CodeTypeReference(typeof(string));
            field1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute"));
            field1.InitExpression = new CodePrimitiveExpression("hi!");
            class1.Members.Add(field1);

            CodeMemberProperty prop1 = new CodeMemberProperty();
            prop1.Name = "MyProperty";
            prop1.Type = new CodeTypeReference(typeof(string));
            prop1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Property"))));
            prop1.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "myField")));
            class1.Members.Add(prop1);

            CodeConstructor const1 = new CodeConstructor();
            const1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Constructor"))));
            class1.Members.Add(const1);

            class1 = new CodeTypeDeclaration("Test");
            class1.IsClass = true;
            class1.BaseTypes.Add(new CodeTypeReference("Form"));
            ns.Types.Add(class1);

            CodeMemberField mfield = new CodeMemberField(new CodeTypeReference("Button"), "b");
            mfield.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference("Button"));
            class1.Members.Add(mfield);

            CodeConstructor ctor = new CodeConstructor();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
                                "Size"), new CodeObjectCreateExpression(new CodeTypeReference("Size"),
                                new CodePrimitiveExpression(600), new CodePrimitiveExpression(600))));
            ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
                                "Text"), new CodePrimitiveExpression("Test")));
            ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
                                "TabIndex"), new CodePrimitiveExpression(0)));
            ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
                                "Location"), new CodeObjectCreateExpression(new CodeTypeReference("Point"),
                                new CodePrimitiveExpression(400), new CodePrimitiveExpression(525))));
            ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new
                CodeThisReferenceExpression(), "MyEvent"), new CodeDelegateCreateExpression(new CodeTypeReference("EventHandler")
                , new CodeThisReferenceExpression(), "b_Click")));
            class1.Members.Add(ctor);

            CodeMemberEvent evt = new CodeMemberEvent();
            evt.Name = "MyEvent";
            evt.Type = new CodeTypeReference("System.EventHandler");
            evt.Attributes = MemberAttributes.Public;
            evt.CustomAttributes.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false))));
            class1.Members.Add(evt);

            CodeMemberMethod cmm = new CodeMemberMethod();
            cmm.Name = "b_Click";
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender"));
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(EventArgs), "e"));
            class1.Members.Add(cmm);

            AssertEqual(cu,
                @"'------------------------------------------------------------------------------
                  ' <auto-generated>
                  '     This code was generated by a tool.
                  '     Runtime Version:4.0.30319.42000
                  '
                  '     Changes to this file may cause incorrect behavior and will be lost if
                  '     the code is regenerated.
                  ' </auto-generated>
                  '------------------------------------------------------------------------------

                  Option Strict Off
                  Option Explicit On

                  Imports System
                  Imports System.ComponentModel
                  Imports System.Drawing
                  Imports System.Windows.Forms
                  <Assembly: System.Reflection.AssemblyTitle(""MyAssembly""),  _
                   Assembly: System.Reflection.AssemblyVersion(""1.0.6.2""),  _
                   Assembly: System.CLSCompliantAttribute(false)>

                  Namespace MyNamespace

                      <System.Serializable(),  _
                       System.Obsolete(""Don't use this Class"")>  _
                      Public Class [MyClass]

                          <System.Xml.Serialization.XmlElementAttribute()>  _
                          Private myField As String = ""hi!""

                          <System.Obsolete(""Don't use this Constructor"")>  _
                          Private Sub New()
                              MyBase.New
                          End Sub

                          <System.Obsolete(""Don't use this Property"")>  _
                          Private ReadOnly Property MyProperty() As String
                              Get
                                  Return Me.myField
                              End Get
                          End Property

                          <System.Obsolete(""Don't use this Method""),  _
                           System.ComponentModel.Editor(""This"", ""That"")>  _
                          Private Sub MyMethod(<System.Xml.Serialization.XmlElementAttribute(Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable:=false)> ByVal blah As String, <System.Xml.Serialization.XmlElementAttribute(Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable:=false)> ByVal arrayit() As Integer)
                          End Sub

                          <System.Obsolete(""Don't use this Function"")>  _
                          Private Function MyFunction() As <System.Xml.Serialization.XmlIgnoreAttribute(), System.Xml.Serialization.XmlRootAttribute([Namespace]:=""Namespace Value"", ElementName:=""Root, hehehe"")> String
                              Return ""Return""
                          End Function

                          <Global.System.ObsoleteAttribute(""Don't use this Function"")>  _
                          Private Sub GlobalKeywordFunction()
                          End Sub

                          <System.Serializable()>  _
                          Public Class NestedClass
                          End Class
                      End Class

                      Public Class Test
                          Inherits Form

                          Private b As Button = New Button()

                          Public Sub New()
                              MyBase.New
                              Me.Size = New Size(600, 600)
                              b.Text = ""Test""
                              b.TabIndex = 0
                              b.Location = New Point(400, 525)
                              AddHandler MyEvent, AddressOf Me.b_Click
                          End Sub

                          <System.CLSCompliantAttribute(false)>  _
                          Public Event MyEvent As System.EventHandler

                          Private Sub b_Click(ByVal sender As Object, ByVal e As System.EventArgs)
                          End Sub
                      End Class
                  End Namespace");
        }
Example #52
0
 /// <summary>
 /// Generate a parameter to the current method with a unique name.
 /// </summary>
 /// <param name="prefix">Prefix to use for the parameter</param>
 /// <param name="type">C# type of the parameter</param>
 /// <returns>A variable reference.</returns>
 public CodeVariableReferenceExpression GenSymParameter(string prefix, CodeTypeReference type)
 {
     return(GenSymAutomatic(prefix, type, true));
 }
 public CodeTypeReference(CodeTypeReference arrayType, int rank)
 {
     this.baseType = null;
     this.arrayRank = rank;
     this.arrayElementType = arrayType;
 }
Example #54
0
 /// <summary>
 /// Generate a local variable in the current method with a unique name.
 /// </summary>
 /// <param name="prefix">Prefix to use for the local variable</param>
 /// <param name="type">C# type of the parameter</param>
 /// <returns>A variable reference.</returns>
 public CodeVariableReferenceExpression GenSymLocal(string prefix, CodeTypeReference type)
 {
     return(GenSymAutomatic(prefix, type, false));
 }
 private void Initialize(string typeName, CodeTypeReferenceOptions options)
 {
     this.Options = options;
     if ((typeName == null) || (typeName.Length == 0))
     {
         typeName = typeof(void).FullName;
         this.baseType = typeName;
         this.arrayRank = 0;
         this.arrayElementType = null;
     }
     else
     {
         typeName = this.RipOffAssemblyInformationFromTypeName(typeName);
         int num = typeName.Length - 1;
         int num2 = num;
         this.needsFixup = true;
         Queue queue = new Queue();
         while (num2 >= 0)
         {
             int num3 = 1;
             if (typeName[num2--] != ']')
             {
                 break;
             }
             while ((num2 >= 0) && (typeName[num2] == ','))
             {
                 num3++;
                 num2--;
             }
             if ((num2 < 0) || (typeName[num2] != '['))
             {
                 break;
             }
             queue.Enqueue(num3);
             num2--;
             num = num2;
         }
         num2 = num;
         ArrayList list = new ArrayList();
         Stack stack = new Stack();
         if ((num2 > 0) && (typeName[num2--] == ']'))
         {
             this.needsFixup = false;
             int num4 = 1;
             int num5 = num;
             while (num2 >= 0)
             {
                 if (typeName[num2] == '[')
                 {
                     if (--num4 == 0)
                     {
                         break;
                     }
                 }
                 else if (typeName[num2] == ']')
                 {
                     num4++;
                 }
                 else if ((typeName[num2] == ',') && (num4 == 1))
                 {
                     if ((num2 + 1) < num5)
                     {
                         stack.Push(typeName.Substring(num2 + 1, (num5 - num2) - 1));
                     }
                     num5 = num2;
                 }
                 num2--;
             }
             if ((num2 > 0) && (((num - num2) - 1) > 0))
             {
                 if ((num2 + 1) < num5)
                 {
                     stack.Push(typeName.Substring(num2 + 1, (num5 - num2) - 1));
                 }
                 while (stack.Count > 0)
                 {
                     string str = this.RipOffAssemblyInformationFromTypeName((string) stack.Pop());
                     list.Add(new CodeTypeReference(str));
                 }
                 num = num2 - 1;
             }
         }
         if (num < 0)
         {
             this.baseType = typeName;
         }
         else
         {
             if (queue.Count > 0)
             {
                 CodeTypeReference arrayType = new CodeTypeReference(typeName.Substring(0, num + 1), this.Options);
                 for (int i = 0; i < list.Count; i++)
                 {
                     arrayType.TypeArguments.Add((CodeTypeReference) list[i]);
                 }
                 while (queue.Count > 1)
                 {
                     arrayType = new CodeTypeReference(arrayType, (int) queue.Dequeue());
                 }
                 this.baseType = null;
                 this.arrayRank = (int) queue.Dequeue();
                 this.arrayElementType = arrayType;
             }
             else if (list.Count > 0)
             {
                 for (int j = 0; j < list.Count; j++)
                 {
                     this.TypeArguments.Add((CodeTypeReference) list[j]);
                 }
                 this.baseType = typeName.Substring(0, num + 1);
             }
             else
             {
                 this.baseType = typeName;
             }
             if ((this.baseType != null) && (this.baseType.IndexOf('`') != -1))
             {
                 this.needsFixup = false;
             }
         }
     }
 }
Example #56
0
 public static void Add(this CodeParameterDeclarationExpressionCollection collection, CodeTypeReference type, string name)
 {
     collection.Add(new CodeParameterDeclarationExpression(type, name));
 }
	public CodeMethodReferenceExpression(CodeExpression targetObject, string methodName, CodeTypeReference[] typeParameters) {}
Example #58
0
        public static void Add(this CodeParameterDeclarationExpressionCollection collection, CodeTypeReference type, int rank, string name)
        {
            var codeTypeRef = new CodeTypeReference(type, rank);

            collection.Add(new CodeParameterDeclarationExpression(codeTypeRef, name));
        }
	public CodeParameterDeclarationExpression(CodeTypeReference type, string name) {}
        /// <summary>
        /// Generate a navigation property
        /// </summary>
        /// <param name="target">the other end</param>
        /// <param name="referenceProperty">True to emit Reference navigation property</param>
        /// <returns>the generated property</returns>
        private CodeMemberProperty EmitNavigationProperty(RelationshipEndMember target, bool referenceProperty)
        {
            CodeTypeReference typeRef = GetReturnType(target, referenceProperty);

            // raise the PropertyGenerated event
            PropertyGeneratedEventArgs eventArgs = new PropertyGeneratedEventArgs(Item,
                                                                                  null, // no backing field
                                                                                  typeRef);

            this.Generator.RaisePropertyGeneratedEvent(eventArgs);

            // [System.ComponentModel.Browsable(false)]
            // public TargetType TargetName
            // public EntityReference<TargetType> TargetName
            // or
            // public EntityCollection<targetType> TargetNames
            CodeMemberProperty property = new CodeMemberProperty();

            if (referenceProperty)
            {
                AttributeEmitter.AddBrowsableAttribute(property);
                Generator.AttributeEmitter.EmitGeneratedCodeAttribute(property);
            }
            else
            {
                Generator.AttributeEmitter.EmitNavigationPropertyAttributes(Generator, target, property, eventArgs.AdditionalAttributes);

                // Only reference navigation properties are currently currently supported with XML serialization
                // and thus we should use the XmlIgnore and SoapIgnore attributes on other property types.
                AttributeEmitter.AddIgnoreAttributes(property);
            }

            AttributeEmitter.AddDataMemberAttribute(property);

            CommentEmitter.EmitSummaryComments(Item, property.Comments);

            property.Name = Item.Name;
            if (referenceProperty)
            {
                property.Name += "Reference";
                if (IsNameAlreadyAMemberName(Item.DeclaringType, property.Name, Generator.LanguageAppropriateStringComparer))
                {
                    Generator.AddError(Strings.GeneratedNavigationPropertyNameConflict(Item.Name, Item.DeclaringType.Name, property.Name),
                                       ModelBuilderErrorCode.GeneratedNavigationPropertyNameConflict,
                                       EdmSchemaErrorSeverity.Error, Item.DeclaringType.FullName, property.Name);
                }
            }

            if (eventArgs.ReturnType != null && !eventArgs.ReturnType.Equals(typeRef))
            {
                property.Type = eventArgs.ReturnType;
            }
            else
            {
                property.Type = typeRef;
            }

            property.Attributes = MemberAttributes.Final;

            CodeMethodInvokeExpression getMethod = EmitGetMethod(target);
            CodeExpression             getReturnExpression;

            property.Attributes |= AccessibilityFromGettersAndSetters(Item);
            // setup the accessibility of the navigation property setter and getter
            MemberAttributes propertyAccessibility = property.Attributes & MemberAttributes.AccessMask;

            PropertyEmitter.AddGetterSetterFixUp(Generator.FixUps, GetFullyQualifiedPropertyName(property.Name),
                                                 PropertyEmitter.GetGetterAccessibility(Item), propertyAccessibility, true);
            PropertyEmitter.AddGetterSetterFixUp(Generator.FixUps, GetFullyQualifiedPropertyName(property.Name),
                                                 PropertyEmitter.GetSetterAccessibility(Item), propertyAccessibility, false);

            if (target.RelationshipMultiplicity != RelationshipMultiplicity.Many)
            {
                // insert user-supplied Set code here, before the assignment
                //
                List <CodeStatement> additionalSetStatements = eventArgs.AdditionalSetStatements;
                if (additionalSetStatements != null && additionalSetStatements.Count > 0)
                {
                    try
                    {
                        property.SetStatements.AddRange(additionalSetStatements.ToArray());
                    }
                    catch (ArgumentNullException ex)
                    {
                        Generator.AddError(Strings.InvalidSetStatementSuppliedForProperty(Item.Name),
                                           ModelBuilderErrorCode.InvalidSetStatementSuppliedForProperty,
                                           EdmSchemaErrorSeverity.Error,
                                           ex);
                    }
                }

                CodeExpression valueRef = new CodePropertySetValueReferenceExpression();
                if (typeRef != eventArgs.ReturnType)
                {
                    // we need to cast to the actual type
                    valueRef = new CodeCastExpression(typeRef, valueRef);
                }

                if (referenceProperty)
                {
                    // get
                    //     return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<TTargetEntity>("CSpaceQualifiedRelationshipName", "TargetRoleName");
                    getReturnExpression = getMethod;

                    // set
                    // if (value != null)
                    // {
                    //    ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<TTargetEntity>"CSpaceQualifiedRelationshipName", "TargetRoleName", value);
                    // }

                    CodeMethodReferenceExpression initReferenceMethod = new CodeMethodReferenceExpression();
                    initReferenceMethod.MethodName = "InitializeRelatedReference";

                    initReferenceMethod.TypeArguments.Add(Generator.GetLeastPossibleQualifiedTypeReference(GetEntityType(target)));
                    initReferenceMethod.TargetObject = new CodePropertyReferenceExpression(
                        new CodeCastExpression(TypeReference.IEntityWithRelationshipsTypeBaseClass, ThisRef),
                        "RelationshipManager");

                    // relationships aren't backed by types so we won't map the namespace
                    // or we can't find the relationship again later
                    string cspaceNamespaceNameQualifiedRelationshipName = target.DeclaringType.FullName;

                    property.SetStatements.Add(
                        new CodeConditionStatement(
                            EmitExpressionDoesNotEqualNull(valueRef),
                            new CodeExpressionStatement(
                                new CodeMethodInvokeExpression(
                                    initReferenceMethod, new CodeExpression[] {
                        new CodePrimitiveExpression(cspaceNamespaceNameQualifiedRelationshipName), new CodePrimitiveExpression(target.Name), valueRef
                    }))));
                }
                else
                {
                    CodePropertyReferenceExpression valueProperty = new CodePropertyReferenceExpression(getMethod, ValuePropertyName);

                    // get
                    //     return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<TTargetEntity>("CSpaceQualifiedRelationshipName", "TargetRoleName").Value;
                    getReturnExpression = valueProperty;

                    // set
                    //     ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<TTargetEntity>("CSpaceQualifiedRelationshipName", "TargetRoleName").Value = value;
                    property.SetStatements.Add(
                        new CodeAssignStatement(valueProperty, valueRef));
                }
            }
            else
            {
                // get
                //     return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<TTargetEntity>("CSpaceQualifiedRelationshipName", "TargetRoleName");
                getReturnExpression = getMethod;

                // set
                // if (value != null)
                // {
                //    ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<TTargetEntity>"CSpaceQualifiedRelationshipName", "TargetRoleName", value);
                // }
                CodeExpression valueRef = new CodePropertySetValueReferenceExpression();

                CodeMethodReferenceExpression initCollectionMethod = new CodeMethodReferenceExpression();
                initCollectionMethod.MethodName = "InitializeRelatedCollection";

                initCollectionMethod.TypeArguments.Add(Generator.GetLeastPossibleQualifiedTypeReference(GetEntityType(target)));
                initCollectionMethod.TargetObject = new CodePropertyReferenceExpression(
                    new CodeCastExpression(TypeReference.IEntityWithRelationshipsTypeBaseClass, ThisRef),
                    "RelationshipManager");

                // relationships aren't backed by types so we won't map the namespace
                // or we can't find the relationship again later
                string cspaceNamespaceNameQualifiedRelationshipName = target.DeclaringType.FullName;

                property.SetStatements.Add(
                    new CodeConditionStatement(
                        EmitExpressionDoesNotEqualNull(valueRef),
                        new CodeExpressionStatement(
                            new CodeMethodInvokeExpression(
                                initCollectionMethod, new CodeExpression[] {
                    new CodePrimitiveExpression(cspaceNamespaceNameQualifiedRelationshipName), new CodePrimitiveExpression(target.Name), valueRef
                }))));
            }

            // if additional Get statements were specified by the event subscriber, insert them now
            //
            List <CodeStatement> additionalGetStatements = eventArgs.AdditionalGetStatements;

            if (additionalGetStatements != null && additionalGetStatements.Count > 0)
            {
                try
                {
                    property.GetStatements.AddRange(additionalGetStatements.ToArray());
                }
                catch (ArgumentNullException ex)
                {
                    Generator.AddError(Strings.InvalidGetStatementSuppliedForProperty(Item.Name),
                                       ModelBuilderErrorCode.InvalidGetStatementSuppliedForProperty,
                                       EdmSchemaErrorSeverity.Error,
                                       ex);
                }
            }

            property.GetStatements.Add(new CodeMethodReturnStatement(getReturnExpression));

            return(property);
        }