public override System.CodeDom.CodeExpression GetCodeExpression(
     BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
 {
     CodeTypeReferenceExpression targetClass =
         new CodeTypeReferenceExpression(typeof(ExpressionBuilderIdentity));
     string targetMethod = "GetIdentity";
     CodeExpression methodParameter =
         new CodePrimitiveExpression(entry.Expression.Trim());
     return new CodeMethodInvokeExpression(
         targetClass, targetMethod, methodParameter);
 }
	public override CodeExpression GetCodeExpression(
		BoundPropertyEntry entry, object parsedData,
		ExpressionBuilderContext context)
	{
		// entry.Expression is the number string
		// (minus the RandomNumber: prefix).
		if (!entry.Expression.Contains(","))
		{
			throw new ArgumentException("Must include two numbers separated by a comma.");
		}
		else
		{
			// Get the two numbers.
			string[] numbers = entry.Expression.Split(',');

			if (numbers.Length != 2)
			{
				throw new ArgumentException("Only include two numbers.");
			}
			else
			{
				int lowerLimit, upperLimit;
				if (Int32.TryParse(numbers[0], out lowerLimit) &&
					Int32.TryParse(numbers[1], out upperLimit))
				{

					// So far all the operations have been performed in
					// normal code. That's because the two numbers are
					// specified in the expression, and so they won't
					// change each time the page is requested.
					// However, the random number should be allowed to
					// change each time, so you need to switch to CodeDOM.
					Type type = entry.DeclaringType;
					PropertyDescriptor descriptor = TypeDescriptor.GetProperties(type)[entry.PropertyInfo.Name];
					CodeExpression[] expressionArray = new CodeExpression[2];
					expressionArray[0] = new CodePrimitiveExpression(lowerLimit);
					expressionArray[1] = new CodePrimitiveExpression(upperLimit); 
					return new CodeCastExpression(descriptor.PropertyType, new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(base.GetType()), "GetRandomNumber", expressionArray));
				}
				else
				{
					throw new ArgumentException("Use valid integers.");
				}

			}
		}
		
	}
    public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
        object parsedData, ExpressionBuilderContext context)
    {
        // entry.Expression - строка с числом 
        // без префикса (например: "1,6").
        if (!entry.Expression.Contains(","))
        {
            throw new ArgumentException(" Должны быть указаны два числа, разделенные запятой");
        }
        else
        {
            // Получить два числа
            string[] numbers = entry.Expression.Split(',');

            if (numbers.Length != 2)
            {
                throw new ArgumentException("Должны быть указаны два числа");
            }
            else
            {
                int min, max;
                if (Int32.TryParse(numbers[0], out min) &&
                    Int32.TryParse(numbers[1], out max))
                {

                    // Получить ссылку на класс, имеющий метод GetRandomNumber(). 
                    // (Это класс, где данный код выполняется.)
                    CodeTypeReferenceExpression typeRef = new CodeTypeReferenceExpression(this.GetType());

                    // Определить параметры для GetRandomNumber().
                    CodeExpression[] methodParameters = new CodeExpression[2];
                    methodParameters[0] = new CodePrimitiveExpression(min);
                    methodParameters[1] = new CodePrimitiveExpression(max);

                    // Вернуть выражение привязки вызвав метод GetRandomNumber()
                    CodeMethodInvokeExpression methodCall = new CodeMethodInvokeExpression(
                        typeRef, "GetRandomNumber", methodParameters);
                    return methodCall;
                }
                else
                {
                    throw new ArgumentException("Должны использоваться допустимые целые числа");
                }

            }
        }
    }
Exemple #4
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)));
     }
 }
 public override CodeExpression GetCodeExpression(System.Web.UI.BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
 {
     if (!entry.Expression.Contains(","))
     {
         throw new ArgumentException(
         "Must include two numbers separated by a comma.");
     }
     else
     {
         // Get the two numbers.
         string[] numbers = entry.Expression.Split(',');
         if (numbers.Length != 2)
         {
             throw new ArgumentException("Only include two numbers.");
         }
         else
         {
             int lowerLimit, upperLimit;
             if (Int32.TryParse(numbers[0], out lowerLimit) &&
             Int32.TryParse(numbers[1], out upperLimit))
             {
                 // Get a reference to the class that has the
                 // GetRandomNumber() method.
                 // (It's the class where this code is executing.)
                 CodeTypeReferenceExpression typeRef = new
                 CodeTypeReferenceExpression(this.GetType());
                 CodeExpression[] methodParameters = new CodeExpression[2];
                 methodParameters[0] = new CodePrimitiveExpression(lowerLimit);
                 methodParameters[1] = new CodePrimitiveExpression(upperLimit);
                 return new CodeMethodInvokeExpression(typeRef, "GetRandomNumber", methodParameters);
             }
             else
             {
                 throw new ArgumentException("Use valid integers.");
             }
         }
     }
 }
        void AddAsyncMembers(string messageName, CodeMemberMethod method)
        {
            CodeThisReferenceExpression ethis = new CodeThisReferenceExpression();
            CodePrimitiveExpression     enull = new CodePrimitiveExpression(null);

            CodeMemberField codeField = new CodeMemberField(typeof(System.Threading.SendOrPostCallback), messageName + "OperationCompleted");

            codeField.Attributes = MemberAttributes.Private;
            CodeTypeDeclaration.Members.Add(codeField);

            // Event arguments class

            string argsClassName          = classNames.AddUnique(messageName + "CompletedEventArgs", null);
            CodeTypeDeclaration argsClass = new CodeTypeDeclaration(argsClassName);

            argsClass.Attributes |= MemberAttributes.Public;
#if NET_2_0
            argsClass.IsPartial = true;
#endif
            argsClass.BaseTypes.Add(new CodeTypeReference("System.ComponentModel.AsyncCompletedEventArgs"));

            CodeMemberField resultsField = new CodeMemberField(typeof(object[]), "results");
            resultsField.Attributes = MemberAttributes.Private;
            argsClass.Members.Add(resultsField);

            CodeConstructor cc = new CodeConstructor();
            cc.Attributes = MemberAttributes.Assembly;
            cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object[]), "results"));
            cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(System.Exception), "exception"));
            cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(bool), "cancelled"));
            cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "userState"));
            cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("exception"));
            cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("cancelled"));
            cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("userState"));
            CodeExpression thisResults = new CodeFieldReferenceExpression(ethis, "results");
            cc.Statements.Add(new CodeAssignStatement(thisResults, new CodeVariableReferenceExpression("results")));
            argsClass.Members.Add(cc);

            int ind = 0;

            if (method.ReturnType.BaseType != "System.Void")
            {
                argsClass.Members.Add(CreateArgsProperty(method.ReturnType, "Result", ind++));
            }

            foreach (CodeParameterDeclarationExpression par in method.Parameters)
            {
                if (par.Direction == FieldDirection.Out || par.Direction == FieldDirection.Ref)
                {
                    argsClass.Members.Add(CreateArgsProperty(par.Type, par.Name, ind++));
                }
            }

            bool needsArgsClass = (ind > 0);
            if (needsArgsClass)
            {
                asyncTypes.Add(argsClass);
            }
            else
            {
                argsClassName = "System.ComponentModel.AsyncCompletedEventArgs";
            }

            // Event delegate type

            CodeTypeDelegate delegateType = new CodeTypeDelegate(messageName + "CompletedEventHandler");
            delegateType.Attributes |= MemberAttributes.Public;
            delegateType.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender"));
            delegateType.Parameters.Add(new CodeParameterDeclarationExpression(argsClassName, "args"));

            // Event member

            CodeMemberEvent codeEvent = new CodeMemberEvent();
            codeEvent.Attributes = codeEvent.Attributes & ~MemberAttributes.AccessMask | MemberAttributes.Public;
            codeEvent.Name       = messageName + "Completed";
            codeEvent.Type       = new CodeTypeReference(delegateType.Name);
            CodeTypeDeclaration.Members.Add(codeEvent);

            // Async method (without user state param)

            CodeMemberMethod am = new CodeMemberMethod();
            am.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            am.Name       = method.Name + "Async";
            am.ReturnType = new CodeTypeReference(typeof(void));
            CodeMethodInvokeExpression inv;
            inv = new CodeMethodInvokeExpression(ethis, am.Name);
            am.Statements.Add(inv);

            // On...Completed method

            CodeMemberMethod onCompleted = new CodeMemberMethod();
            onCompleted.Name       = "On" + messageName + "Completed";
            onCompleted.Attributes = MemberAttributes.Private | MemberAttributes.Final;
            onCompleted.ReturnType = new CodeTypeReference(typeof(void));
            onCompleted.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "arg"));

            CodeConditionStatement anIf = new CodeConditionStatement();

            CodeExpression eventField = new CodeEventReferenceExpression(ethis, codeEvent.Name);
            anIf.Condition = new CodeBinaryOperatorExpression(eventField, CodeBinaryOperatorType.IdentityInequality, enull);
            CodeExpression castedArg  = new CodeCastExpression(typeof(System.Web.Services.Protocols.InvokeCompletedEventArgs), new CodeVariableReferenceExpression("arg"));
            CodeStatement  invokeArgs = new CodeVariableDeclarationStatement(typeof(System.Web.Services.Protocols.InvokeCompletedEventArgs), "invokeArgs", castedArg);
            anIf.TrueStatements.Add(invokeArgs);

            CodeDelegateInvokeExpression delegateInvoke = new CodeDelegateInvokeExpression();
            delegateInvoke.TargetObject = eventField;
            delegateInvoke.Parameters.Add(ethis);
            CodeObjectCreateExpression argsInstance  = new CodeObjectCreateExpression(argsClassName);
            CodeExpression             invokeArgsVar = new CodeVariableReferenceExpression("invokeArgs");
            if (needsArgsClass)
            {
                argsInstance.Parameters.Add(new CodeFieldReferenceExpression(invokeArgsVar, "Results"));
            }
            argsInstance.Parameters.Add(new CodeFieldReferenceExpression(invokeArgsVar, "Error"));
            argsInstance.Parameters.Add(new CodeFieldReferenceExpression(invokeArgsVar, "Cancelled"));
            argsInstance.Parameters.Add(new CodeFieldReferenceExpression(invokeArgsVar, "UserState"));
            delegateInvoke.Parameters.Add(argsInstance);
            anIf.TrueStatements.Add(delegateInvoke);

            onCompleted.Statements.Add(anIf);

            // Async method

            CodeMemberMethod asyncMethod = new CodeMemberMethod();
            asyncMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            asyncMethod.Name       = method.Name + "Async";
            asyncMethod.ReturnType = new CodeTypeReference(typeof(void));

            CodeExpression delegateField = new CodeFieldReferenceExpression(ethis, codeField.Name);
            anIf           = new CodeConditionStatement();
            anIf.Condition = new CodeBinaryOperatorExpression(delegateField, CodeBinaryOperatorType.IdentityEquality, enull);;
            CodeExpression      delegateRef = new CodeMethodReferenceExpression(ethis, onCompleted.Name);
            CodeExpression      newDelegate = new CodeObjectCreateExpression(typeof(System.Threading.SendOrPostCallback), delegateRef);
            CodeAssignStatement cas         = new CodeAssignStatement(delegateField, newDelegate);
            anIf.TrueStatements.Add(cas);
            asyncMethod.Statements.Add(anIf);

            CodeArrayCreateExpression paramsArray = new CodeArrayCreateExpression(typeof(object));

            // Assign parameters

            CodeIdentifiers paramsIds = new CodeIdentifiers();

            foreach (CodeParameterDeclarationExpression par in method.Parameters)
            {
                paramsIds.Add(par.Name, null);
                if (par.Direction == FieldDirection.In || par.Direction == FieldDirection.Ref)
                {
                    CodeParameterDeclarationExpression inpar = new CodeParameterDeclarationExpression(par.Type, par.Name);
                    am.Parameters.Add(inpar);
                    asyncMethod.Parameters.Add(inpar);
                    inv.Parameters.Add(new CodeVariableReferenceExpression(par.Name));
                    paramsArray.Initializers.Add(new CodeVariableReferenceExpression(par.Name));
                }
            }


            inv.Parameters.Add(enull);

            string userStateName = paramsIds.AddUnique("userState", null);
            asyncMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), userStateName));

            CodeExpression userStateVar = new CodeVariableReferenceExpression(userStateName);
            asyncMethod.Statements.Add(BuildInvokeAsync(messageName, paramsArray, delegateField, userStateVar));

            CodeTypeDeclaration.Members.Add(am);
            CodeTypeDeclaration.Members.Add(asyncMethod);
            CodeTypeDeclaration.Members.Add(onCompleted);

            asyncTypes.Add(delegateType);
        }
 private void ValidatePrimitiveExpression(CodePrimitiveExpression e)
 {
 }
 private void GeneratePrimitiveExpression(CodePrimitiveExpression e)
 {
     if (e.Value is char)
     {
         GeneratePrimitiveChar((char)e.Value);
     }
     else if (e.Value is SByte)
     {
         // C# has no literal marker for types smaller than Int32
         Output.Write(((SByte)e.Value).ToString(CultureInfo.InvariantCulture));
     }
     else if (e.Value is UInt16)
     {
         // C# has no literal marker for types smaller than Int32, and you will
         // get a conversion error if you use "u" here.
         Output.Write("0x");
         Output.Write(((UInt16)e.Value).ToString(CultureInfo.InvariantCulture));
     }
     else if (e.Value is UInt32)
     {
         Output.Write("0x");
         Output.Write(((UInt32)e.Value).ToString(CultureInfo.InvariantCulture));
     }
     else if (e.Value is UInt64)
     {
         Output.Write("0x");
         Output.Write(((UInt64)e.Value).ToString(CultureInfo.InvariantCulture));
     }
     else
     {
         GeneratePrimitiveExpressionBase(e);
     }
 }
Exemple #9
0
        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));
            }
        }
Exemple #10
0
            public void AddMethod(MemberAttributes sMemberAttributes,
                                  string szName,
                                  string szComments,
                                  string szType)
            {
                //Establish the structure of the method
                CodeMemberMethod oCodeMemberMethod = new CodeMemberMethod();

                oCodeMemberMethod.Attributes = sMemberAttributes;
                oCodeMemberMethod.Name       = szName;
                oCodeMemberMethod.Comments.Add(new CodeCommentStatement(szComments));
                oCodeMemberMethod.ReturnType = new CodeTypeReference(szType);

                //Indicate the data type and name of the parameter
                oCodeMemberMethod.Parameters.Add(new
                                                 CodeParameterDeclarationExpression("System.Int32", "iCustomerID"));

                //declare a variable within the body of the method
                CodeVariableDeclarationStatement oCodeVariableDeclarationStatement =
                    new CodeVariableDeclarationStatement("System.String", "szSQL");
                CodeArgumentReferenceExpression oCodeArgumentReferenceExpression =
                    new CodeArgumentReferenceExpression("\"DELETE FROM\"");

                oCodeVariableDeclarationStatement.InitExpression =
                    oCodeArgumentReferenceExpression;
                oCodeMemberMethod.Statements.Add(oCodeVariableDeclarationStatement);


                //CodeVariableReferenceExpression oCodeVariableReferenceExpression =
                //    new CodeVariableReferenceExpression("oDatabase.Parameters");
                //CodeMethodInvokeExpression oCodeMethodInvokeExpression =
                //    new CodeMethodInvokeExpression(oCodeVariableReferenceExpression, "Add");
                //oCodeMethodInvokeExpression.Parameters.Add(
                //    new CodeVariableReferenceExpression("iCustomerID"));
                //oCodeMethodInvokeExpression.Parameters.Add(
                //    new CodePrimitiveExpression("12345"));
                //oCodeMemberMethod.Statements.Add(oCodeMethodInvokeExpression);

                CodeVariableReferenceExpression oCodeVariableReferenceExpression =
                    new CodeVariableReferenceExpression("i");
                CodePrimitiveExpression oCodePrimitiveExpression1 =
                    new CodePrimitiveExpression(1);
                CodePrimitiveExpression oCodePrimitiveExpression5 =
                    new CodePrimitiveExpression(5);
                CodeAssignStatement oCodeAssignStatement =
                    new CodeAssignStatement(oCodeVariableReferenceExpression, oCodePrimitiveExpression1);
                CodeBinaryOperatorExpression oCodeBinaryOperatorExpressionLessThan =
                    new CodeBinaryOperatorExpression(oCodeVariableReferenceExpression,
                                                     CodeBinaryOperatorType.LessThan,
                                                     oCodePrimitiveExpression5);
                CodeMethodInvokeExpression oCodeMethodInvokeExpression =
                    new CodeMethodInvokeExpression(oCodeVariableReferenceExpression, "ToString");
                CodeBinaryOperatorExpression oCodeBinaryOperatorExpression =
                    new CodeBinaryOperatorExpression(oCodeVariableReferenceExpression,
                                                     CodeBinaryOperatorType.Add,
                                                     oCodePrimitiveExpression1);
                CodeAssignStatement oCodeAssignStatement1 =
                    new CodeAssignStatement(oCodeVariableReferenceExpression,
                                            oCodeBinaryOperatorExpression);
                CodeTypeReferenceExpression oCodeTypeReferenceExpression =
                    new CodeTypeReferenceExpression("MessageBox");
                CodeMethodReferenceExpression oCodeMethodReferenceExpression =
                    new CodeMethodReferenceExpression(oCodeTypeReferenceExpression, "Show");
                CodeExpressionStatement oCodeExpressionStatement =
                    new CodeExpressionStatement(
                        new CodeMethodInvokeExpression(oCodeVariableReferenceExpression, "ToString"));
                CodeMethodInvokeExpression oCodeMethodInvokeExpressionToString =
                    new CodeMethodInvokeExpression(oCodeVariableReferenceExpression, "ToString");

                CodeIterationStatement oCodeIterationStatement = new CodeIterationStatement(
                    oCodeAssignStatement,
                    oCodeBinaryOperatorExpressionLessThan,
                    oCodeAssignStatement1,
                    new CodeStatement[] { new CodeExpressionStatement(
                                              new CodeMethodInvokeExpression(
                                                  new CodeMethodReferenceExpression(
                                                      oCodeTypeReferenceExpression, "Show"),
                                                  oCodeMethodInvokeExpressionToString)) });

                oCodeMemberMethod.Statements.Add(oCodeIterationStatement);

                oCodeTypeDeclaration.Members.Add(oCodeMemberMethod);
            }
Exemple #11
0
        private CodeAttributeArgument[] GetDefaultValueArguments(PrimitiveMapping mapping, object value, out CodeExpression initExpression)
        {
            initExpression = null;
            if (value == null)
            {
                return(null);
            }

            CodeExpression valueExpression = null;
            CodeExpression typeofValue     = null;
            Type           type            = value.GetType();

            CodeAttributeArgument[] arguments = null;

            if (mapping is EnumMapping)
            {
#if DEBUG
                // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
                if (value.GetType() != typeof(string))
                {
                    throw new InvalidOperationException(string.Format(ResXml.XmlInternalErrorDetails, "Invalid enumeration type " + value.GetType().Name));
                }
#endif

                if (((EnumMapping)mapping).IsFlags)
                {
                    string[] values = ((string)value).Split(null);
                    for (int i = 0; i < values.Length; i++)
                    {
                        if (values[i].Length == 0)
                        {
                            continue;
                        }
                        CodeExpression enumRef = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(mapping.TypeDesc.FullName), values[i]);
                        if (valueExpression != null)
                        {
                            valueExpression = new CodeBinaryOperatorExpression(valueExpression, CodeBinaryOperatorType.BitwiseOr, enumRef);
                        }
                        else
                        {
                            valueExpression = enumRef;
                        }
                    }
                }
                else
                {
                    valueExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(mapping.TypeDesc.FullName), (string)value);
                }
                initExpression = valueExpression;
                arguments      = new CodeAttributeArgument[] { new CodeAttributeArgument(valueExpression) };
            }
            else if (type == typeof(bool) ||
                     type == typeof(Int32) ||
                     type == typeof(string) ||
                     type == typeof(double))
            {
                initExpression = valueExpression = new CodePrimitiveExpression(value);
                arguments      = new CodeAttributeArgument[] { new CodeAttributeArgument(valueExpression) };
            }
            else if (type == typeof(Int16) ||
                     type == typeof(Int64) ||
                     type == typeof(float) ||
                     type == typeof(byte) ||
                     type == typeof(decimal))
            {
                valueExpression = new CodePrimitiveExpression(Convert.ToString(value, NumberFormatInfo.InvariantInfo));
                typeofValue     = new CodeTypeOfExpression(type.FullName);
                arguments       = new CodeAttributeArgument[] { new CodeAttributeArgument(typeofValue), new CodeAttributeArgument(valueExpression) };
                initExpression  = new CodeCastExpression(type.FullName, new CodePrimitiveExpression(value));
            }
            else if (type == typeof(sbyte) ||
                     type == typeof(UInt16) ||
                     type == typeof(UInt32) ||
                     type == typeof(UInt64))
            {
                // need to promote the non-CLS complient types

                value = PromoteType(type, value);

                valueExpression = new CodePrimitiveExpression(Convert.ToString(value, NumberFormatInfo.InvariantInfo));
                typeofValue     = new CodeTypeOfExpression(type.FullName);
                arguments       = new CodeAttributeArgument[] { new CodeAttributeArgument(typeofValue), new CodeAttributeArgument(valueExpression) };
                initExpression  = new CodeCastExpression(type.FullName, new CodePrimitiveExpression(value));
            }
            else if (type == typeof(DateTime))
            {
                DateTime dt = (DateTime)value;
                string   dtString;
                long     ticks;
                if (mapping.TypeDesc.FormatterName == "Date")
                {
                    dtString = XmlCustomFormatter.FromDate(dt);
                    ticks    = (new DateTime(dt.Year, dt.Month, dt.Day)).Ticks;
                }
                else if (mapping.TypeDesc.FormatterName == "Time")
                {
                    dtString = XmlCustomFormatter.FromDateTime(dt);
                    ticks    = dt.Ticks;
                }
                else
                {
                    dtString = XmlCustomFormatter.FromDateTime(dt);
                    ticks    = dt.Ticks;
                }
                valueExpression = new CodePrimitiveExpression(dtString);
                typeofValue     = new CodeTypeOfExpression(type.FullName);
                arguments       = new CodeAttributeArgument[] { new CodeAttributeArgument(typeofValue), new CodeAttributeArgument(valueExpression) };
                initExpression  = new CodeObjectCreateExpression(new CodeTypeReference(typeof(DateTime)), new CodeExpression[] { new CodePrimitiveExpression(ticks) });
            }
            else if (type == typeof(Guid))
            {
                valueExpression = new CodePrimitiveExpression(Convert.ToString(value, NumberFormatInfo.InvariantInfo));
                typeofValue     = new CodeTypeOfExpression(type.FullName);
                arguments       = new CodeAttributeArgument[] { new CodeAttributeArgument(typeofValue), new CodeAttributeArgument(valueExpression) };
                initExpression  = new CodeObjectCreateExpression(new CodeTypeReference(typeof(Guid)), new CodeExpression[] { valueExpression });
            }
            if (mapping.TypeDesc.FullName != type.ToString() && !(mapping is EnumMapping))
            {
                // generate cast
                initExpression = new CodeCastExpression(mapping.TypeDesc.FullName, initExpression);
            }
            return(arguments);
        }
        public static CodeExpression CreateFacets(ClrSimpleTypeInfo type)
        {
            //object o = null;
            CodeExpression             codePrimitiveExpression;
            CompiledFacets             facets       = type.RestrictionFacets;
            CodeObjectCreateExpression createFacets = new CodeObjectCreateExpression()
            {
                CreateType = new CodeTypeReference("Xml.Schema.Linq.RestrictionFacets")
            };

            Xml.Schema.Linq.RestrictionFlags flags = facets.Flags;
            if ((int)flags != 0)
            {
                CodeCastExpression cast = new CodeCastExpression(new CodeTypeReference("Xml.Schema.Linq.RestrictionFlags"), new CodePrimitiveExpression((object)Convert.ToInt32(flags, CultureInfo.InvariantCulture.NumberFormat)));
                createFacets.Parameters.Add(cast);
                if ((int)(flags & Xml.Schema.Linq.RestrictionFlags.Enumeration) == 0)
                {
                    createFacets.Parameters.Add(new CodePrimitiveExpression(null));
                }
                else
                {
                    CodeArrayCreateExpression enums = new CodeArrayCreateExpression()
                    {
                        CreateType = new CodeTypeReference("System.Object")
                    };
                    foreach (object o in facets.Enumeration)
                    {
                        SimpleTypeCodeDomHelper.GetCreateValueExpression(o, type, enums.Initializers);
                    }
                    createFacets.Parameters.Add(enums);
                }
                int fractionDigits = 0;
                if ((int)(flags & Xml.Schema.Linq.RestrictionFlags.FractionDigits) != 0)
                {
                    fractionDigits = facets.FractionDigits;
                }
                createFacets.Parameters.Add(new CodePrimitiveExpression((object)fractionDigits));
                int length = 0;
                if ((int)(flags & Xml.Schema.Linq.RestrictionFlags.Length) != 0)
                {
                    length = facets.Length;
                }
                createFacets.Parameters.Add(new CodePrimitiveExpression((object)length));
                object maxExclusive = null;
                if ((int)(flags & Xml.Schema.Linq.RestrictionFlags.MaxExclusive) != 0)
                {
                    maxExclusive = facets.MaxExclusive;
                }
                SimpleTypeCodeDomHelper.GetCreateValueExpression(maxExclusive, type, createFacets.Parameters);
                object maxInclusive = null;
                if ((int)(flags & Xml.Schema.Linq.RestrictionFlags.MaxInclusive) != 0)
                {
                    maxInclusive = facets.MaxInclusive;
                }
                SimpleTypeCodeDomHelper.GetCreateValueExpression(maxInclusive, type, createFacets.Parameters);
                int maxLength = 0;
                if ((int)(flags & Xml.Schema.Linq.RestrictionFlags.MaxLength) != 0)
                {
                    maxLength = facets.MaxLength;
                }
                createFacets.Parameters.Add(new CodePrimitiveExpression((object)maxLength));
                object minExclusive = null;
                if ((int)(flags & Xml.Schema.Linq.RestrictionFlags.MinExclusive) != 0)
                {
                    minExclusive = facets.MinExclusive;
                }
                SimpleTypeCodeDomHelper.GetCreateValueExpression(minExclusive, type, createFacets.Parameters);
                object minInclusive = null;
                if ((int)(flags & Xml.Schema.Linq.RestrictionFlags.MinInclusive) != 0)
                {
                    minInclusive = facets.MinInclusive;
                }
                SimpleTypeCodeDomHelper.GetCreateValueExpression(minInclusive, type, createFacets.Parameters);
                int minLength = 0;
                if ((int)(flags & Xml.Schema.Linq.RestrictionFlags.MinLength) != 0)
                {
                    minLength = facets.MinLength;
                }
                createFacets.Parameters.Add(new CodePrimitiveExpression((object)minLength));
                if ((int)(flags & Xml.Schema.Linq.RestrictionFlags.Pattern) == 0)
                {
                    createFacets.Parameters.Add(new CodePrimitiveExpression(null));
                }
                else
                {
                    CodeArrayCreateExpression patternStrs = new CodeArrayCreateExpression()
                    {
                        CreateType = new CodeTypeReference(XTypedServices.typeOfString)
                    };
                    foreach (object pattern in facets.Patterns)
                    {
                        string str = pattern.ToString();
                        patternStrs.Initializers.Add(new CodePrimitiveExpression(str));
                    }
                    createFacets.Parameters.Add(patternStrs);
                }
                int totalDigits = 0;
                if ((int)(flags & Xml.Schema.Linq.RestrictionFlags.TotalDigits) != 0)
                {
                    totalDigits = facets.TotalDigits;
                }
                createFacets.Parameters.Add(new CodePrimitiveExpression((object)totalDigits));
                Xml.Schema.Linq.XmlSchemaWhiteSpace ws = facets.WhiteSpace;
                createFacets.Parameters.Add(CodeDomHelper.CreateFieldReference("XmlSchemaWhiteSpace", ws.ToString()));
                codePrimitiveExpression = createFacets;
            }
            else
            {
                codePrimitiveExpression = new CodePrimitiveExpression(null);
            }
            return(codePrimitiveExpression);
        }
        public CodeExpression GenerateLoadPixbuf(string name, Gtk.IconSize size)
        {
            bool found = false;

            foreach (CodeTypeDeclaration t in cns.Types)
            {
                if (t.Name == "IconLoader")
                {
                    found = true;
                    break;
                }
            }

            if (!found)
            {
                CodeTypeDeclaration cls = new CodeTypeDeclaration("IconLoader");
                cls.Attributes     = MemberAttributes.Private;
                cls.TypeAttributes = System.Reflection.TypeAttributes.NestedAssembly;
                cns.Types.Add(cls);

                CodeMemberMethod met = new CodeMemberMethod();
                cls.Members.Add(met);
                met.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                met.Name       = "LoadIcon";
                met.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Gtk.Widget), "widget"));
                met.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "name"));
                met.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Gtk.IconSize), "size"));
                met.ReturnType = new CodeTypeReference(typeof(Gdk.Pixbuf));

                CodeExpression widgetExp = new CodeVariableReferenceExpression("widget");
                CodeExpression nameExp   = new CodeVariableReferenceExpression("name");
                CodeExpression sizeExp   = new CodeVariableReferenceExpression("size");
                CodeExpression szExp     = new CodeVariableReferenceExpression("sz");
                CodeExpression mgExp     = new CodeBinaryOperatorExpression(szExp, CodeBinaryOperatorType.Divide, new CodePrimitiveExpression(4));
                CodeExpression pmapExp   = new CodeVariableReferenceExpression("pmap");
                CodeExpression gcExp     = new CodeVariableReferenceExpression("gc");
                CodeExpression szM1Exp   = new CodeBinaryOperatorExpression(szExp, CodeBinaryOperatorType.Subtract, new CodePrimitiveExpression(1));
                CodeExpression zeroExp   = new CodePrimitiveExpression(0);
                CodeExpression resExp    = new CodeVariableReferenceExpression("res");

                met.Statements.Add(
                    new CodeVariableDeclarationStatement(typeof(Gdk.Pixbuf), "res",
                                                         new CodeMethodInvokeExpression(
                                                             widgetExp,
                                                             "RenderIcon",
                                                             nameExp,
                                                             sizeExp,
                                                             new CodePrimitiveExpression(null)
                                                             )
                                                         )
                    );

                CodeConditionStatement nullcheck = new CodeConditionStatement();
                met.Statements.Add(nullcheck);
                nullcheck.Condition = new CodeBinaryOperatorExpression(
                    resExp,
                    CodeBinaryOperatorType.IdentityInequality,
                    new CodePrimitiveExpression(null)
                    );
                nullcheck.TrueStatements.Add(new CodeMethodReturnStatement(resExp));

                // int sz, h;
                // Gtk.Icon.SizeLookup (size, out sz, out h);

                nullcheck.FalseStatements.Add(new CodeVariableDeclarationStatement(typeof(int), "sz"));
                nullcheck.FalseStatements.Add(new CodeVariableDeclarationStatement(typeof(int), "sy"));
                nullcheck.FalseStatements.Add(new CodeMethodInvokeExpression(
                                                  new CodeTypeReferenceExpression(typeof(Gtk.Icon).ToGlobalTypeRef()),
                                                  "SizeLookup",
                                                  sizeExp,
                                                  new CodeDirectionExpression(FieldDirection.Out, szExp),
                                                  new CodeDirectionExpression(FieldDirection.Out, new CodeVariableReferenceExpression("sy"))
                                                  ));

                CodeTryCatchFinallyStatement trycatch = new CodeTryCatchFinallyStatement();
                nullcheck.FalseStatements.Add(trycatch);
                trycatch.TryStatements.Add(
                    new CodeMethodReturnStatement(
                        new CodeMethodInvokeExpression(
                            new CodePropertyReferenceExpression(
                                new CodeTypeReferenceExpression(new CodeTypeReference(typeof(Gtk.IconTheme))),
                                "Default"
                                ),
                            "LoadIcon",
                            nameExp,
                            szExp,
                            zeroExp
                            )
                        )
                    );

                CodeCatchClause ccatch = new CodeCatchClause();
                trycatch.CatchClauses.Add(ccatch);

                CodeConditionStatement cond = new CodeConditionStatement();
                ccatch.Statements.Add(cond);

                cond.Condition = new CodeBinaryOperatorExpression(
                    nameExp,
                    CodeBinaryOperatorType.IdentityInequality,
                    new CodePrimitiveExpression("gtk-missing-image")
                    );

                cond.TrueStatements.Add(
                    new CodeMethodReturnStatement(
                        new CodeMethodInvokeExpression(
                            new CodeTypeReferenceExpression(cns.Name + "." + cls.Name),
                            "LoadIcon",
                            widgetExp,
                            new CodePrimitiveExpression("gtk-missing-image"),
                            sizeExp
                            )
                        )
                    );

                CodeStatementCollection stms = cond.FalseStatements;

                stms.Add(
                    new CodeVariableDeclarationStatement(typeof(Gdk.Pixmap), "pmap",
                                                         new CodeObjectCreateExpression(
                                                             typeof(Gdk.Pixmap),
                                                             new CodePropertyReferenceExpression(
                                                                 new CodePropertyReferenceExpression(
                                                                     new CodeTypeReferenceExpression(typeof(Gdk.Screen)),
                                                                     "Default"
                                                                     ),
                                                                 "RootWindow"
                                                                 ),
                                                             szExp,
                                                             szExp
                                                             )
                                                         )
                    );
                stms.Add(
                    new CodeVariableDeclarationStatement(typeof(Gdk.GC), "gc",
                                                         new CodeObjectCreateExpression(typeof(Gdk.GC), pmapExp)
                                                         )
                    );
                stms.Add(
                    new CodeAssignStatement(
                        new CodePropertyReferenceExpression(
                            gcExp,
                            "RgbFgColor"
                            ),
                        new CodeObjectCreateExpression(
                            typeof(Gdk.Color),
                            new CodePrimitiveExpression(255),
                            new CodePrimitiveExpression(255),
                            new CodePrimitiveExpression(255)
                            )
                        )
                    );
                stms.Add(
                    new CodeMethodInvokeExpression(
                        pmapExp,
                        "DrawRectangle",
                        gcExp,
                        new CodePrimitiveExpression(true),
                        zeroExp,
                        zeroExp,
                        szExp,
                        szExp
                        )
                    );
                stms.Add(
                    new CodeAssignStatement(
                        new CodePropertyReferenceExpression(
                            gcExp,
                            "RgbFgColor"
                            ),
                        new CodeObjectCreateExpression(
                            typeof(Gdk.Color),
                            zeroExp, zeroExp, zeroExp
                            )
                        )
                    );
                stms.Add(
                    new CodeMethodInvokeExpression(
                        pmapExp,
                        "DrawRectangle",
                        gcExp,
                        new CodePrimitiveExpression(false),
                        zeroExp,
                        zeroExp,
                        szM1Exp,
                        szM1Exp
                        )
                    );
                stms.Add(
                    new CodeMethodInvokeExpression(
                        gcExp,
                        "SetLineAttributes",
                        new CodePrimitiveExpression(3),
                        new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Gdk.LineStyle)), "Solid"),
                        new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Gdk.CapStyle)), "Round"),
                        new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Gdk.JoinStyle)), "Round")
                        )
                    );
                stms.Add(
                    new CodeAssignStatement(
                        new CodePropertyReferenceExpression(
                            gcExp,
                            "RgbFgColor"
                            ),
                        new CodeObjectCreateExpression(
                            typeof(Gdk.Color),
                            new CodePrimitiveExpression(255),
                            zeroExp,
                            zeroExp
                            )
                        )
                    );
                stms.Add(
                    new CodeMethodInvokeExpression(
                        pmapExp,
                        "DrawLine",
                        gcExp,
                        mgExp,
                        mgExp,
                        new CodeBinaryOperatorExpression(szM1Exp, CodeBinaryOperatorType.Subtract, mgExp),
                        new CodeBinaryOperatorExpression(szM1Exp, CodeBinaryOperatorType.Subtract, mgExp)
                        )
                    );
                stms.Add(
                    new CodeMethodInvokeExpression(
                        pmapExp,
                        "DrawLine",
                        gcExp,
                        new CodeBinaryOperatorExpression(szM1Exp, CodeBinaryOperatorType.Subtract, mgExp),
                        mgExp,
                        mgExp,
                        new CodeBinaryOperatorExpression(szM1Exp, CodeBinaryOperatorType.Subtract, mgExp)
                        )
                    );
                stms.Add(
                    new CodeMethodReturnStatement(
                        new CodeMethodInvokeExpression(
                            new CodeTypeReferenceExpression(typeof(Gdk.Pixbuf)),
                            "FromDrawable",
                            pmapExp,
                            new CodePropertyReferenceExpression(pmapExp, "Colormap"),
                            zeroExp, zeroExp, zeroExp, zeroExp, szExp, szExp
                            )
                        )
                    );
            }

            int sz, h;

            Gtk.Icon.SizeLookup(size, out sz, out h);

            return(new CodeMethodInvokeExpression(
                       new CodeTypeReferenceExpression(new CodeTypeReference(cns.Name + ".IconLoader", CodeTypeReferenceOptions.GlobalReference)),
                       "LoadIcon",
                       rootObject,
                       new CodePrimitiveExpression(name),
                       new CodeFieldReferenceExpression(
                           new CodeTypeReferenceExpression(new CodeTypeReference(typeof(Gtk.IconSize), CodeTypeReferenceOptions.GlobalReference)),
                           size.ToString()
                           )
                       ));
        }
Exemple #14
0
        internal /*public*/ static CodeExpression GenerateExpressionForValue(PropertyInfo propertyInfo, object value, Type valueType)
        {
#if DEBUG
            if (WebFormsCompilation.Enabled)
            {
                Debug.WriteLine("GenerateExpressionForValue() {");
                Debug.Indent();
            }
#endif // DEBUG
            CodeExpression rightExpr = null;

            if (valueType == null)
            {
                throw new ArgumentNullException("valueType");
            }

            PropertyDescriptor pd = null;
            if (propertyInfo != null)
            {
                pd = TypeDescriptor.GetProperties(propertyInfo.ReflectedType)[propertyInfo.Name];
            }

            if (valueType == typeof(string) && value is string)
            {
                if (WebFormsCompilation.Enabled)
                {
                    Debug.WriteLine("simple string");
                }
                rightExpr = new CodePrimitiveExpression((string)value);
            }
            else if (valueType.IsPrimitive)
            {
                if (WebFormsCompilation.Enabled)
                {
                    Debug.WriteLine("primitive");
                }
                rightExpr = new CodePrimitiveExpression(value);
            }
            else if (propertyInfo == null && valueType == typeof(object) &&
                     (value == null || value.GetType().IsPrimitive))
            {
                // If the type is object, and the value is a primitive, simply use a
                // CodePrimitiveExpression instead of trying to use a TypeConverter (VSWhidbey 518773)
                if (WebFormsCompilation.Enabled)
                {
                    Debug.WriteLine("primitive to object");
                }
                rightExpr = new CodePrimitiveExpression(value);
            }
            else if (valueType.IsArray)
            {
                if (WebFormsCompilation.Enabled)
                {
                    Debug.WriteLine("array");
                }
                Array array = (Array)value;
                CodeArrayCreateExpression exp = new CodeArrayCreateExpression();
                exp.CreateType = new CodeTypeReference(valueType.GetElementType());
                if (array != null)
                {
                    foreach (object o in array)
                    {
                        exp.Initializers.Add(GenerateExpressionForValue(null, o, valueType.GetElementType()));
                    }
                }
                rightExpr = exp;
            }
            else if (valueType == typeof(Type))
            {
                rightExpr = new CodeTypeOfExpression((Type)value);
            }
            else
            {
                if (WebFormsCompilation.Enabled)
                {
                    Debug.WriteLine("other");
                }
                TypeConverter converter = null;
                if (pd != null)
                {
                    converter = pd.Converter;
                }
                else
                {
                    converter = TypeDescriptor.GetConverter(valueType);
                }

                bool added = false;

                if (converter != null)
                {
                    InstanceDescriptor desc = null;

                    if (converter.CanConvertTo(typeof(InstanceDescriptor)))
                    {
                        desc = (InstanceDescriptor)converter.ConvertTo(value, typeof(InstanceDescriptor));
                    }
                    if (desc != null)
                    {
                        if (WebFormsCompilation.Enabled)
                        {
                            Debug.WriteLine("has converter with instance descriptor");
                        }

                        // static field ref...
                        //
                        if (desc.MemberInfo is FieldInfo)
                        {
                            if (WebFormsCompilation.Enabled)
                            {
                                Debug.WriteLine("persistinfo is a field ref");
                            }
                            CodeFieldReferenceExpression fieldRef = new CodeFieldReferenceExpression(BuildGlobalCodeTypeReferenceExpression(desc.MemberInfo.DeclaringType.FullName), desc.MemberInfo.Name);
                            rightExpr = fieldRef;
                            added     = true;
                        }
                        // static property ref
                        else if (desc.MemberInfo is PropertyInfo)
                        {
                            if (WebFormsCompilation.Enabled)
                            {
                                Debug.WriteLine("persistinfo is a property ref");
                            }
                            CodePropertyReferenceExpression propRef = new CodePropertyReferenceExpression(BuildGlobalCodeTypeReferenceExpression(desc.MemberInfo.DeclaringType.FullName), desc.MemberInfo.Name);
                            rightExpr = propRef;
                            added     = true;
                        }

                        // static method invoke
                        //
                        else
                        {
                            object[] args = new object[desc.Arguments.Count];
                            desc.Arguments.CopyTo(args, 0);
                            CodeExpression[] expressions = new CodeExpression[args.Length];

                            if (desc.MemberInfo is MethodInfo)
                            {
                                MethodInfo      mi         = (MethodInfo)desc.MemberInfo;
                                ParameterInfo[] parameters = mi.GetParameters();

                                for (int i = 0; i < args.Length; i++)
                                {
                                    expressions[i] = GenerateExpressionForValue(null, args[i], parameters[i].ParameterType);
                                }

                                if (WebFormsCompilation.Enabled)
                                {
                                    Debug.WriteLine("persistinfo is a method invoke");
                                }
                                CodeMethodInvokeExpression methCall = new CodeMethodInvokeExpression(BuildGlobalCodeTypeReferenceExpression(desc.MemberInfo.DeclaringType.FullName), desc.MemberInfo.Name);
                                foreach (CodeExpression e in expressions)
                                {
                                    methCall.Parameters.Add(e);
                                }
                                rightExpr = new CodeCastExpression(valueType, methCall);
                                added     = true;
                            }
                            else if (desc.MemberInfo is ConstructorInfo)
                            {
                                ConstructorInfo ci         = (ConstructorInfo)desc.MemberInfo;
                                ParameterInfo[] parameters = ci.GetParameters();

                                for (int i = 0; i < args.Length; i++)
                                {
                                    expressions[i] = GenerateExpressionForValue(null, args[i], parameters[i].ParameterType);
                                }

                                if (WebFormsCompilation.Enabled)
                                {
                                    Debug.WriteLine("persistinfo is a constructor call");
                                }
                                CodeObjectCreateExpression objectCreate = new CodeObjectCreateExpression(desc.MemberInfo.DeclaringType.FullName);
                                foreach (CodeExpression e in expressions)
                                {
                                    objectCreate.Parameters.Add(e);
                                }
                                rightExpr = objectCreate;
                                added     = true;
                            }
                        }
                    }
                }

                if (!added)
                {
#if DEBUG
                    if (WebFormsCompilation.Enabled)
                    {
                        Debug.WriteLine("unabled to determine type, attempting Parse");
                        Debug.Indent();
                        Debug.WriteLine("value.GetType  == " + value.GetType().FullName);
                        Debug.WriteLine("value.ToString == " + value.ToString());
                        Debug.WriteLine("valueType      == " + valueType.FullName);
                        if (propertyInfo != null)
                        {
                            Debug.WriteLine("propertyInfo   == " + propertyInfo.ReflectedType.FullName + "." + propertyInfo.Name + " : " + propertyInfo.PropertyType.FullName);
                        }
                        else
                        {
                            Debug.WriteLine("propertyInfo   == (null)");
                        }

                        Debug.Unindent();
                    }
#endif // DEBUG


                    // Not a known type: try calling Parse

                    // If possible, pass it an InvariantCulture (ASURT 79412)
                    if (valueType.GetMethod("Parse", new Type[] { typeof(string), typeof(CultureInfo) }) != null)
                    {
                        CodeMethodInvokeExpression methCall = new CodeMethodInvokeExpression(BuildGlobalCodeTypeReferenceExpression(valueType.FullName), "Parse");

                        // Convert the object to a string.
                        // If we have a type converter, use it to convert to a string in a culture
                        // invariant way (ASURT 87094)
                        string s;
                        if (converter != null)
                        {
                            s = converter.ConvertToInvariantString(value);
                        }
                        else
                        {
                            s = value.ToString();
                        }

                        methCall.Parameters.Add(new CodePrimitiveExpression(s));
                        methCall.Parameters.Add(new CodePropertyReferenceExpression(BuildGlobalCodeTypeReferenceExpression(typeof(CultureInfo)), "InvariantCulture"));
                        rightExpr = methCall;
                    }
                    else if (valueType.GetMethod("Parse", new Type[] { typeof(string) }) != null)
                    {
                        // Otherwise, settle for passing just the string
                        CodeMethodInvokeExpression methCall = new CodeMethodInvokeExpression(BuildGlobalCodeTypeReferenceExpression(valueType.FullName), "Parse");
                        methCall.Parameters.Add(new CodePrimitiveExpression(value.ToString()));
                        rightExpr = methCall;
                    }
                    else
                    {
                        throw new HttpException(SR.GetString(SR.CantGenPropertySet, propertyInfo.Name, valueType.FullName));
                    }
                }
            }

#if DEBUG
            if (WebFormsCompilation.Enabled)
            {
                Debug.Unindent();
                Debug.WriteLine("}");
            }
#endif // DEBUG
            return(rightExpr);
        }
Exemple #15
0
        void AddDefaultValueAttribute(CodeMemberField field, CodeAttributeDeclarationCollection metadata, object value, TypeMapping mapping)
        {
            #if DEBUG
            // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
            if (!(mapping is PrimitiveMapping))
            {
                throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, "Default value is invalid for " + mapping.GetType().Name));
            }
            else if (mapping.IsList)
            {
                throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, "Default value is invalid for " + mapping.GetType().Name));
            }
            #endif

            if (value == null)
            {
                return;
            }

            CodeExpression          valueExpression = null;
            CodeExpression          initExpression  = null;
            CodeExpression          typeofValue     = null;
            string                  typeName        = mapping.TypeDesc.FullName;
            Type                    type            = value.GetType();
            CodeAttributeArgument[] arguments       = null;

            if (mapping is EnumMapping)
            {
                #if DEBUG
                // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
                if (value.GetType() != typeof(string))
                {
                    throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, "Invalid enumeration type " + value.GetType().Name));
                }
                #endif

                if (((EnumMapping)mapping).IsFlags)
                {
                    string[] values = ((string)value).Split(null);
                    for (int i = 0; i < values.Length; i++)
                    {
                        if (values[i].Length == 0)
                        {
                            continue;
                        }
                        CodeExpression enumRef = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeName), values[i]);
                        if (valueExpression != null)
                        {
                            valueExpression = new CodeBinaryOperatorExpression(valueExpression, CodeBinaryOperatorType.BitwiseOr, enumRef);
                        }
                        else
                        {
                            valueExpression = enumRef;
                        }
                    }
                }
                else
                {
                    valueExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeName), (string)value);
                }
                initExpression = valueExpression;
                arguments      = new CodeAttributeArgument[] { new CodeAttributeArgument(valueExpression) };
            }
            else if (type == typeof(bool) ||
                     type == typeof(Int32) ||
                     type == typeof(string) ||
                     type == typeof(double))
            {
                initExpression = valueExpression = new CodePrimitiveExpression(value);
                arguments      = new CodeAttributeArgument[] { new CodeAttributeArgument(valueExpression) };
            }
            else if (type == typeof(Int16) ||
                     type == typeof(Int64) ||
                     type == typeof(float) ||
                     type == typeof(byte) ||
                     type == typeof(decimal))
            {
                valueExpression = new CodePrimitiveExpression(value.ToString());
                typeofValue     = new CodeTypeOfExpression(CodeIdentifier.EscapeKeywords(type.FullName));
                arguments       = new CodeAttributeArgument[] { new CodeAttributeArgument(typeofValue), new CodeAttributeArgument(valueExpression) };
                initExpression  = new CodeCastExpression(type.FullName, new CodePrimitiveExpression(value));
            }
            else if (type == typeof(sbyte) ||
                     type == typeof(UInt16) ||
                     type == typeof(UInt32) ||
                     type == typeof(UInt64))
            {
                // need to promote the non-CLS complient types

                value = PromoteType(type, value);

                valueExpression = new CodePrimitiveExpression(value.ToString());
                typeofValue     = new CodeTypeOfExpression(CodeIdentifier.EscapeKeywords(type.FullName));
                arguments       = new CodeAttributeArgument[] { new CodeAttributeArgument(typeofValue), new CodeAttributeArgument(valueExpression) };
                initExpression  = new CodeCastExpression(type.FullName, new CodePrimitiveExpression(value));
            }
            else if (type == typeof(DateTime))
            {
                DateTime dt = (DateTime)value;
                string   dtString;
                long     ticks;
                if (mapping.TypeDesc.FormatterName == "Date")
                {
                    dtString = XmlCustomFormatter.FromDate(dt);
                    ticks    = (new DateTime(dt.Year, dt.Month, dt.Day)).Ticks;
                }
                else if (mapping.TypeDesc.FormatterName == "Time")
                {
                    dtString = XmlCustomFormatter.FromDateTime(dt);
                    ticks    = dt.Ticks;
                }
                else
                {
                    dtString = XmlCustomFormatter.FromDateTime(dt);
                    ticks    = dt.Ticks;
                }
                valueExpression = new CodePrimitiveExpression(dtString);
                typeofValue     = new CodeTypeOfExpression(CodeIdentifier.EscapeKeywords(type.FullName));
                arguments       = new CodeAttributeArgument[] { new CodeAttributeArgument(typeofValue), new CodeAttributeArgument(valueExpression) };
                initExpression  = new CodeObjectCreateExpression(new CodeTypeReference(typeof(DateTime)), new CodeExpression[] { new CodePrimitiveExpression(ticks) });
            }
            if (arguments != null)
            {
                if (field != null)
                {
                    field.InitExpression = initExpression;
                }
                AddCustomAttribute(metadata, typeof(DefaultValueAttribute), arguments);
            }
        }
Exemple #16
0
        /// <summary>
        /// create a CodeExpression to generate an object
        /// </summary>
        /// <param name="v">the object to be generated</param>
        /// <returns>the CodeExpression generating the object</returns>
        public static CodeExpression ObjectCreationCode(object v)
        {
            //===simple values===
            if (v == null)
            {
                return(new CodePrimitiveExpression(null));
            }
            if (v == System.DBNull.Value)
            {
                return(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(System.DBNull)), "Value"));
            }

            Type t = v.GetType();

            if (t.Equals(typeof(EventArgs)))
            {
                return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(EventArgs)), "Empty"));
            }
            if (t.IsPrimitive)
            {
                if (t.Equals(typeof(IntPtr)) || t.Equals(typeof(UIntPtr)))
                {
                    CodeObjectCreateExpression coce;
                    if (t.Equals(typeof(IntPtr)))
                    {
                        IntPtr val = (IntPtr)v;
                        if (IntPtr.Size == 4)
                        {
                            coce = new CodeObjectCreateExpression(t, new CodePrimitiveExpression(val.ToInt32()));
                        }
                        else
                        {
                            coce = new CodeObjectCreateExpression(t, new CodePrimitiveExpression(val.ToInt64()));
                        }
                    }
                    else
                    {
                        UIntPtr val = (UIntPtr)v;
                        if (IntPtr.Size == 4)
                        {
                            coce = new CodeObjectCreateExpression(t, new CodePrimitiveExpression(val.ToUInt32()));
                        }
                        else
                        {
                            coce = new CodeObjectCreateExpression(t, new CodePrimitiveExpression(val.ToUInt64()));
                        }
                    }
                    return(coce);
                }
                else
                {
                    CodePrimitiveExpression cpi = new CodePrimitiveExpression(v);
                    if (VPLUtil.IsNumber(t))
                    {
                        if (!typeof(int).Equals(t))
                        {
                            return(new CodeCastExpression(t, cpi));
                        }
                    }
                    return(cpi);
                }
            }
            if (t.Equals(typeof(string)))
            {
                return(new CodePrimitiveExpression(v));
            }
            if (t.IsEnum)
            {
                return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(t), v.ToString()));
            }
            if (t.IsArray)
            {
                Type  te = t.GetElementType();
                Array a  = (Array)v;
                if (a.Rank == 1)
                {
                    CodeExpression[] inits = new CodeExpression[a.Length];
                    for (int i = 0; i < inits.Length; i++)
                    {
                        object val = a.GetValue(i);
                        if (val == null)
                        {
                            inits[i] = GetDefaultValueExpression(te);
                        }
                        else
                        {
                            inits[i] = ObjectCreationCodeGen.ObjectCreationCode(val);
                        }
                    }
                    CodeArrayCreateExpression ac = new CodeArrayCreateExpression(t, inits);
                    return(ac);
                }
                else
                {
                    StringBuilder sb = new StringBuilder(CreateArrayCreationCodeString(a.Rank, te.Name));
                    sb.Append("{");
                    for (int i = 0; i < a.Rank; i++)
                    {
                        if (i > 0)
                        {
                            sb.Append(",");
                        }
                        sb.Append("{");
                        for (int j = a.GetLowerBound(i); j <= a.GetUpperBound(i); j++)
                        {
                            if (j > 0)
                            {
                                sb.Append(",");
                            }
                            sb.Append(ObjectCreationCodeGen.GetObjectCreationCodeSnippet(a.GetValue(i, j)));
                        }
                        sb.Append("}");
                    }
                    sb.Append("}");
                    return(new CodeSnippetExpression(sb.ToString()));
                }
            }
            //===use plug-ins to handle it===
            if (creators != null)
            {
                foreach (IGetObjectCreationCode occ in creators.Values)
                {
                    CodeExpression ce = occ.ObjectCreationCode(v);
                    if (ce != null)
                    {
                        return(ce);
                    }
                }
            }
            //===use default handlers===
            if (t.Equals(typeof(Size)))
            {
                Size v1 = (Size)v;
                return(new CodeObjectCreateExpression(t,
                                                      new CodePrimitiveExpression(v1.Width),
                                                      new CodePrimitiveExpression(v1.Height)));
            }
            if (t.Equals(typeof(Point)))
            {
                Point v1 = (Point)v;
                return(new CodeObjectCreateExpression(t,
                                                      new CodePrimitiveExpression(v1.X),
                                                      new CodePrimitiveExpression(v1.Y)));
            }
            if (t.Equals(typeof(Color)))
            {
                Color v1 = (Color)v;
                return(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Color)), "FromArgb"),
                                                      new CodeCastExpression(typeof(int), new CodePrimitiveExpression(v1.A)),
                                                      new CodeCastExpression(typeof(int), new CodePrimitiveExpression(v1.R)),
                                                      new CodeCastExpression(typeof(int), new CodePrimitiveExpression(v1.G)),
                                                      new CodeCastExpression(typeof(int), new CodePrimitiveExpression(v1.B))
                                                      ));
            }
            if (t.Equals(typeof(Cursor)))
            {
                //System.Windows.Forms.Cursors.
                Cursor v1 = (Cursor)v;
                if (v1 == Cursors.AppStarting)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "AppStarting"));
                }
                else if (v1 == Cursors.Arrow)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "Arrow"));
                }
                else if (v1 == Cursors.Cross)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "Cross"));
                }
                else if (v1 == Cursors.Default)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "Default"));
                }
                else if (v1 == Cursors.Hand)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "Hand"));
                }
                else if (v1 == Cursors.Help)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "Help"));
                }
                else if (v1 == Cursors.HSplit)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "HSplit"));
                }
                else if (v1 == Cursors.IBeam)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "IBeam"));
                }
                else if (v1 == Cursors.No)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "No"));
                }
                else if (v1 == Cursors.NoMove2D)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "NoMove2D"));
                }
                else if (v1 == Cursors.NoMoveHoriz)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "NoMoveHoriz"));
                }
                else if (v1 == Cursors.NoMoveVert)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "NoMoveVert"));
                }
                else if (v1 == Cursors.PanEast)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "PanEast"));
                }
                else if (v1 == Cursors.PanNE)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "PanNE"));
                }
                else if (v1 == Cursors.PanNorth)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "PanNorth"));
                }
                else if (v1 == Cursors.PanNW)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "PanNW"));
                }
                else if (v1 == Cursors.PanSE)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "PanSE"));
                }
                else if (v1 == Cursors.PanSouth)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "PanSouth"));
                }
                else if (v1 == Cursors.PanSW)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "PanSW"));
                }
                else if (v1 == Cursors.PanWest)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "PanWest"));
                }
                else if (v1 == Cursors.SizeAll)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "SizeAll"));
                }
                else if (v1 == Cursors.SizeNESW)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "SizeNESW"));
                }
                else if (v1 == Cursors.SizeNS)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "SizeNS"));
                }
                else if (v1 == Cursors.SizeNWSE)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "SizeNWSE"));
                }
                else if (v1 == Cursors.SizeWE)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "SizeWE"));
                }
                else if (v1 == Cursors.UpArrow)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "UpArrow"));
                }
                else if (v1 == Cursors.VSplit)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "VSplit"));
                }
                else if (v1 == Cursors.WaitCursor)
                {
                    return(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(Cursors)), "WaitCursor"));
                }
                else
                {
                    CursorConverter cc = new CursorConverter();
                    string          s  = cc.ConvertToString(v);
                    return(new CodeMethodInvokeExpression(
                               new CodeObjectCreateExpression(typeof(CursorConverter), null),
                               "ConvertFromString",
                               new CodePrimitiveExpression(s)
                               ));
                }
            }
            if (t.Equals(typeof(Font)))
            {
                Font f = (Font)v;
                return(new CodeObjectCreateExpression(typeof(Font), new CodePrimitiveExpression(f.FontFamily.ToString()), new CodePrimitiveExpression(f.Size)));
            }
            //use string converter ===================================
            TypeConverter sc = TypeDescriptor.GetConverter(t);

            if (sc != null)
            {
                if (sc.CanConvertTo(typeof(string)) && sc.CanConvertFrom(typeof(string)))
                {
                    string svalue = sc.ConvertToInvariantString(v);
                    CodeMethodInvokeExpression mgc = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(TypeDescriptor)), "GetConverter", new CodeTypeOfExpression(t));
                    CodeMethodInvokeExpression fs  = new CodeMethodInvokeExpression(mgc, "ConvertFromInvariantString", new CodePrimitiveExpression(svalue));
                    //
                    return(new CodeCastExpression(t, fs));
                }
            }
            //===use TypeConverter as the last resort===
            PropertyDescriptorCollection pifs = TypeDescriptor.GetProperties(v);

            if (pifs == null || pifs.Count == 0)
            {
                return(new CodeObjectCreateExpression(t));
            }
            int nCount = 0;

            for (int i = 0; i < pifs.Count; i++)
            {
                if (pifs[i].IsBrowsable && !pifs[i].IsReadOnly)
                {
                    nCount++;
                }
            }
            if (nCount == 0)
            {
                return(new CodeObjectCreateExpression(t));
            }
            string sCodeSnippet = GetObjectCreationCodeSnippet(v);

            return(new CodeSnippetExpression(sCodeSnippet));
        }
Exemple #17
0
        public override void ProcessDirective(string directiveName, IDictionary <string, string> arguments)
        {
            if (!arguments.TryGetValue("name", out string name) || string.IsNullOrEmpty(name))
            {
                throw new DirectiveProcessorException("Proxymodel directive has no name argument");
            }

            if (!arguments.TryGetValue("type", out string type) || string.IsNullOrEmpty(type))
            {
                type = typeof(ProxyModel).ToString();
            }

            string fieldName = "_" + name + "Field";
            var    typeRef   = new CodeTypeReference(type);
            var    thisRef   = new CodeThisReferenceExpression();
            var    fieldRef  = new CodeFieldReferenceExpression(thisRef, fieldName);

            members.Add(new CodeMemberField(typeRef, fieldName));

            var property = new CodeMemberProperty()
            {
                Name       = name,
                Attributes = MemberAttributes.Public | MemberAttributes.Final,
                HasGet     = true,
                HasSet     = false,
                Type       = typeRef
            };

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

            members.Add(property);

            var valRef        = new CodeVariableReferenceExpression("data");
            var namePrimitive = new CodePrimitiveExpression(name);
            var sessionRef    = new CodePropertyReferenceExpression(thisRef, "Session");

            bool hasAcquiredCheck = hostSpecific;


            string acquiredName        = "_" + name + "Acquired";
            var    acquiredVariable    = new CodeVariableDeclarationStatement(typeof(bool), acquiredName, new CodePrimitiveExpression(false));
            var    acquiredVariableRef = new CodeVariableReferenceExpression(acquiredVariable.Name);

            if (hasAcquiredCheck)
            {
                postStatements.Add(acquiredVariable);
            }

            //checks the local called "data" can be cast and assigned to the field, and if successful, sets acquiredVariable to true
            var checkCastThenAssignVal = new CodeConditionStatement(
                new CodeMethodInvokeExpression(
                    new CodeTypeOfExpression(typeRef), "IsAssignableFrom", new CodeMethodInvokeExpression(valRef, "GetType")),
                hasAcquiredCheck
                                        ? new CodeStatement[] {
                new CodeAssignStatement(fieldRef, new CodeCastExpression(typeRef, valRef)),
                new CodeAssignStatement(acquiredVariableRef, new CodePrimitiveExpression(true)),
            }
                                        : new CodeStatement[] {
                new CodeAssignStatement(fieldRef, new CodeCastExpression(typeRef, valRef)),
            }
                ,
                new CodeStatement[] {
                new CodeExpressionStatement(new CodeMethodInvokeExpression(thisRef, "Error",
                                                                           new CodePrimitiveExpression("The type '" + type + "' of the parameter '" + name +
                                                                                                       "' did not match the type passed to the template"))),
            });


            //tries to gets the value from the session
            var checkSession = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(NotNull(sessionRef), CodeBinaryOperatorType.BooleanAnd,
                                                 new CodeMethodInvokeExpression(sessionRef, "ContainsKey", namePrimitive)),
                new CodeVariableDeclarationStatement(typeof(object), "data", new CodeIndexerExpression(sessionRef, namePrimitive)),
                checkCastThenAssignVal);

            this.postStatements.Add(checkSession);
        }
        // generate CodeDOM for code that displays message nDisplays times.
        static CodeCompileUnit GenerateProgram(string message, int nDisplays)
        {
            // Create Main method
            CodeEntryPointMethod mainMethod = new CodeEntryPointMethod();

            mainMethod.Name = "Main";

            // generate this expression: Console
            CodeTypeReferenceExpression consoleType = new
                                                      CodeTypeReferenceExpression();

            consoleType.Type = new CodeTypeReference(typeof(Console));

            // generate this statement: int i=0;
            CodeVariableDeclarationStatement declareI = new CodeVariableDeclarationStatement();

            declareI.Name           = "i";
            declareI.InitExpression = new CodePrimitiveExpression(0);
            declareI.Type           = new CodeTypeReference(typeof(int));

            // generate this expression: i;
            CodeVariableReferenceExpression iVar = new CodeVariableReferenceExpression(declareI.Name);

            // generate this statement: i=i+1;
            CodeAssignStatement incrI = new CodeAssignStatement();

            incrI.Left  = iVar;
            incrI.Right = new CodeBinaryOperatorExpression(iVar, CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1));

            // generate this for loop: for (int i=0 ; i<nDisplays ; i++)
            CodeIterationStatement forLoop = new CodeIterationStatement();

            forLoop.InitStatement      = declareI;
            forLoop.TestExpression     = new CodeBinaryOperatorExpression(iVar, CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(nDisplays));
            forLoop.IncrementStatement = incrI;

            // Set up the argument list to pass to Console.WriteLine()
            CodeExpression[]        writeLineArgs = new CodeExpression[1];
            CodePrimitiveExpression arg0          = new CodePrimitiveExpression(message);

            writeLineArgs[0] = arg0;

            // generate this statement: Console.WriteLine(message)
            CodeMethodReferenceExpression writeLineRef = new
                                                         CodeMethodReferenceExpression(consoleType, "WriteLine");
            CodeMethodInvokeExpression writeLine = new
                                                   CodeMethodInvokeExpression(writeLineRef, writeLineArgs);

            // insert Console.WriteLine() statement into for loop
            forLoop.Statements.Add(writeLine);

            // add the for loop to the Main() method
            mainMethod.Statements.Add(forLoop);

            // Add a return statement to the Main() method
            CodeMethodReturnStatement ret = new CodeMethodReturnStatement();

            mainMethod.Statements.Add(ret);

            // Add Main() method to a class
            CodeTypeDeclaration theClass = new CodeTypeDeclaration();

            theClass.Members.Add(mainMethod);
            theClass.Name = "EntryPoint";

            // Add namespace and add class
            CodeNamespace ns = new CodeNamespace("Apress.ExpertDotNet.CodeDomSample");

            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Types.Add(theClass);

            // Create whole program (code compile unit)
            CodeCompileUnit unit = new CodeCompileUnit();

            unit.Namespaces.Add(ns);

            return(unit);
        }
        private CodeBinaryOperatorExpression ParseBinaryOperatorExpression(string expression, out TypeCode expressionType)
        {
            if (!string.IsNullOrEmpty(expression))
            {
                string[] operands = expression.Split(s_operatorSymbols, StringSplitOptions.None);

                // Expression is only valid if there are exactly two operands
                if (operands.Length == 2)
                {
                    CodePrimitiveExpression leftOperand, rightOperand;
                    CodeBinaryOperatorType  operatorType;

                    if (int.TryParse(operands[0], out int left) && int.TryParse(operands[1], out int right))
                    {
                        // Both operands can be compared as integers
                        leftOperand    = new CodePrimitiveExpression(left);
                        rightOperand   = new CodePrimitiveExpression(right);
                        expressionType = TypeCode.Int32;
                    }
                    else if (double.TryParse(operands[0], out double leftF) && double.TryParse(operands[1], out double rightF))
                    {
                        // Both operands can be compared as doubles
                        leftOperand    = new CodePrimitiveExpression(leftF);
                        rightOperand   = new CodePrimitiveExpression(rightF);
                        expressionType = TypeCode.Double;
                    }
                    else
                    {
                        // Default to string comparison of operands
                        leftOperand    = new CodePrimitiveExpression(operands[0]);
                        rightOperand   = new CodePrimitiveExpression(operands[1]);
                        expressionType = TypeCode.String;
                    }

                    // Determine operator type - order of detection is critical                         Symbol:
                    if (expression.Contains(s_operatorSymbols[OperatorType.Equality]))
                    {
                        operatorType = CodeBinaryOperatorType.IdentityEquality;                         // ==
                    }
                    else if (expression.Contains(s_operatorSymbols[OperatorType.Inequality]))
                    {
                        operatorType = CodeBinaryOperatorType.IdentityInequality;                       // !=
                    }
                    else if (expression.Contains(s_operatorSymbols[OperatorType.Inequality2]))
                    {
                        operatorType = CodeBinaryOperatorType.IdentityInequality;                       // <>
                    }
                    else if (expression.Contains(s_operatorSymbols[OperatorType.LessThanOrEqual]))
                    {
                        operatorType = CodeBinaryOperatorType.LessThanOrEqual;                          // <=
                    }
                    else if (expression.Contains(s_operatorSymbols[OperatorType.LessThan]))
                    {
                        operatorType = CodeBinaryOperatorType.LessThan;                                 // <
                    }
                    else if (expression.Contains(s_operatorSymbols[OperatorType.GreaterThanOrEqual]))
                    {
                        operatorType = CodeBinaryOperatorType.GreaterThanOrEqual;                       // >=
                    }
                    else if (expression.Contains(s_operatorSymbols[OperatorType.GreaterThan]))
                    {
                        operatorType = CodeBinaryOperatorType.GreaterThan;                              // >
                    }
                    else
                    {
                        operatorType = CodeBinaryOperatorType.IdentityEquality;                         // =
                    }
                    return(new CodeBinaryOperatorExpression(leftOperand, operatorType, rightOperand));
                }
            }

            expressionType = TypeCode.Object;
            return(null);
        }
Exemple #20
0
        // Generate code for a primitive expression.
        protected virtual void GeneratePrimitiveExpression
            (CodePrimitiveExpression e)
        {
            Object value = e.Value;

            if (value == null)
            {
                Output.Write(NullToken);
            }
            else if (value is String)
            {
                Output.Write(QuoteSnippetString((String)value));
            }
            else if (value is Char)
            {
                char   ch = (char)value;
                String chvalue;
                switch (ch)
                {
                case '\'':      chvalue = "'\\''"; break;

                case '\\':      chvalue = "'\\\\'"; break;

                case '\n':      chvalue = "'\\n'"; break;

                case '\r':      chvalue = "'\\r'"; break;

                case '\t':      chvalue = "'\\t'"; break;

                case '\f':      chvalue = "'\\f'"; break;

                case '\v':      chvalue = "'\\v'"; break;

                case '\a':      chvalue = "'\\a'"; break;

                case '\b':      chvalue = "'\\b'"; break;

                default:
                {
                    if (ch >= ' ' && ch <= 0x7E)
                    {
                        chvalue = "\"" + ch.ToString() + "\"";
                    }
                    else if (ch < 0x0100)
                    {
                        chvalue = "\"\\x" +
                                  hexchars[(ch >> 4) & 0x0F] +
                                  hexchars[ch & 0x0F] + "\"";
                    }
                    else
                    {
                        chvalue = "\"\\u" +
                                  hexchars[(ch >> 12) & 0x0F] +
                                  hexchars[(ch >> 8) & 0x0F] +
                                  hexchars[(ch >> 4) & 0x0F] +
                                  hexchars[ch & 0x0F] + "\"";
                    }
                }
                break;
                }
                Output.Write(chvalue);
            }
            else if (value is SByte)
            {
                Output.Write((int)(sbyte)value);
            }
            else if (value is Byte)
            {
                Output.Write((int)(byte)value);
            }
            else if (value is Int16)
            {
                Output.Write((int)(short)value);
            }
            else if (value is UInt16)
            {
                Output.Write((int)(ushort)value);
            }
            else if (value is Int32)
            {
                Output.Write((int)value);
            }
            else if (value is UInt32)
            {
                Output.Write((uint)value);
            }
            else if (value is Int64)
            {
                Output.Write((long)value);
            }
            else if (value is UInt64)
            {
                Output.Write((ulong)value);
            }
            else if (value is Single)
            {
                GenerateSingleFloatValue((float)value);
            }
            else if (value is Double)
            {
                GenerateDoubleValue((double)value);
            }
            else if (value is Decimal)
            {
                GenerateDecimalValue((Decimal)value);
            }
            else if (value is Boolean)
            {
                if ((bool)value)
                {
                    Output.Write("true");
                }
                else
                {
                    Output.Write("false");
                }
            }
            else
            {
                throw new ArgumentException
                          (S._("Arg_InvalidCodeDom"), "e");
            }
        }
Exemple #21
0
        protected virtual void processInterface(Protocol protocol)
        {
            // Create abstract class
            string protocolNameMangled = CodeGenUtil.Instance.Mangle(protocol.Name);

            var ctd = new CodeTypeDeclaration(protocolNameMangled);

            ctd.TypeAttributes = TypeAttributes.Abstract | TypeAttributes.Public;
            ctd.IsClass        = true;
            ctd.BaseTypes.Add("Avro.Specific.ISpecificProtocol");

            AddProtocolDocumentation(protocol, ctd);

            // Add static protocol field.
            var protocolField = new CodeMemberField();

            protocolField.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final;
            protocolField.Name       = "protocol";
            protocolField.Type       = new CodeTypeReference("readonly Avro.Protocol");

            var cpe  = new CodePrimitiveExpression(protocol.ToString());
            var cmie = new CodeMethodInvokeExpression(
                new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Protocol)), "Parse"),
                new CodeExpression[] { cpe });

            protocolField.InitExpression = cmie;

            ctd.Members.Add(protocolField);

            // Add overridden Protocol method.
            var property = new CodeMemberProperty();

            property.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            property.Name       = "Protocol";
            property.Type       = new CodeTypeReference("Avro.Protocol");
            property.HasGet     = true;


            property.GetStatements.Add(new CodeTypeReferenceExpression("return protocol"));
            ctd.Members.Add(property);

            //var requestMethod = CreateRequestMethod();
            //ctd.Members.Add(requestMethod);

            var requestMethod = CreateRequestMethod();
            //requestMethod.Attributes |= MemberAttributes.Override;
            var builder = new StringBuilder();

            if (protocol.Messages.Count > 0)
            {
                builder.Append("switch(messageName)\n\t\t\t{");

                foreach (var a in protocol.Messages)
                {
                    builder.Append("\n\t\t\t\tcase \"").Append(a.Key).Append("\":\n");

                    bool   unused = false;
                    string type   = getType(a.Value.Response, false, ref unused);

                    builder.Append("\t\t\t\trequestor.Request<")
                    .Append(type)
                    .Append(">(messageName, args, callback);\n");
                    builder.Append("\t\t\t\tbreak;\n");
                }

                builder.Append("\t\t\t}");
            }
            var cseGet = new CodeSnippetExpression(builder.ToString());

            requestMethod.Statements.Add(cseGet);
            ctd.Members.Add(requestMethod);

            AddMethods(protocol, false, ctd);

            string nspace = protocol.Namespace;

            if (string.IsNullOrEmpty(nspace))
            {
                throw new CodeGenException("Namespace required for enum schema " + nspace);
            }
            CodeNamespace codens = addNamespace(nspace);

            codens.Types.Add(ctd);

            // Create callback abstract class
            ctd = new CodeTypeDeclaration(protocolNameMangled + "Callback");
            ctd.TypeAttributes = TypeAttributes.Abstract | TypeAttributes.Public;
            ctd.IsClass        = true;
            ctd.BaseTypes.Add(protocolNameMangled);

            // Need to override



            AddProtocolDocumentation(protocol, ctd);

            AddMethods(protocol, true, ctd);

            codens.Types.Add(ctd);
        }
Exemple #22
0
            private void ImplementSetParentMethod(IReference input, CodeTypeDeclaration output, CodeTypeReference elementTypeReference, CodeMemberMethod method, ITransformationContext context)
            {
                var opposite = input.Opposite;

                var item   = new CodeArgumentReferenceExpression("item");
                var parent = new CodeArgumentReferenceExpression("parent");

                var thisRef   = new CodeThisReferenceExpression();
                var nullRef   = new CodePrimitiveExpression(null);
                var item_opp  = new CodePropertyReferenceExpression(item, context.Trace.ResolveIn(Rule <Reference2Property>(), opposite).Name);
                var ifNotNull = new CodeConditionStatement(new CodeBinaryOperatorExpression(parent, CodeBinaryOperatorType.IdentityInequality, nullRef));

                var targetClass = input.Type;

                var eventName = input.IsContainment ? "ParentChanged" : "Deleted";
                var eventType = input.IsContainment ? typeof(ValueChangedEventArgs).ToTypeReference() : typeof(EventArgs).ToTypeReference();

                var onItemDeleted = new CodeMemberMethod()
                {
                    Name       = "OnItem" + eventName,
                    Attributes = MemberAttributes.Private,
                    ReturnType = new CodeTypeReference(typeof(void))
                };

                onItemDeleted.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender"));
                onItemDeleted.Parameters.Add(new CodeParameterDeclarationExpression(eventType, "e"));
                var actualRemove = new CodeMethodInvokeExpression(
                    thisRef, "Remove", new CodeCastExpression(elementTypeReference, new CodeArgumentReferenceExpression("sender")));

                if (input.IsContainment)
                {
                    var newValue  = new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("e"), "NewValue");
                    var parentRef = new CodePropertyReferenceExpression(thisRef, "Parent");
                    onItemDeleted.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(newValue, CodeBinaryOperatorType.IdentityInequality, parentRef),
                                                                            new CodeExpressionStatement(actualRemove)));
                }
                else
                {
                    onItemDeleted.Statements.Add(actualRemove);
                }
                output.Members.Add(onItemDeleted);

                ifNotNull.TrueStatements.Add(new CodeAttachEventStatement(item, eventName, new CodeMethodReferenceExpression(thisRef, onItemDeleted.Name)));
                ifNotNull.FalseStatements.Add(new CodeRemoveEventStatement(item, eventName, new CodeMethodReferenceExpression(thisRef, onItemDeleted.Name)));


                if (opposite.UpperBound == 1)
                {
                    var assignStatement = new CodeAssignStatement(item_opp, parent);
                    ifNotNull.TrueStatements.Add(assignStatement);
                    ifNotNull.FalseStatements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(
                                                                                 item_opp, CodeBinaryOperatorType.IdentityEquality, new CodePropertyReferenceExpression(thisRef, "Parent")),
                                                                             assignStatement));
                }
                else
                {
                    ifNotNull.FalseStatements.Add(new CodeMethodInvokeExpression(item_opp, "Remove", new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Parent")));
                    ifNotNull.TrueStatements.Add(new CodeMethodInvokeExpression(item_opp, "Add", parent));
                }

                method.Statements.Add(ifNotNull);
            }
Exemple #23
0
 private void ConditionalBranch(Instruction il, bool test)
 {
     var rhs = new CodePrimitiveExpression(test);
     var lhs = Pop();
     var condition = OptimizeBinaryExpression(lhs, CodeBinaryOperator.IdentityEquality, rhs);
     var stmt = new CodeExpressionStatement(condition);
     AddStatment(stmt);
 }
        private static CodeExpression CreateTypedValueExpression(XmlSchemaDatatype dataType, object value)
        {
            CodeExpression codePrimitiveExpression;

            CodeExpression[] codeExpressionArray;
            switch (dataType.TypeCode)
            {
            case XmlTypeCode.None:
            case XmlTypeCode.Item:
            case XmlTypeCode.AnyAtomicType:
            case XmlTypeCode.Idref:
            case XmlTypeCode.Entity:
            {
                throw new InvalidOperationException();
            }

            case XmlTypeCode.Node:
            case XmlTypeCode.Document:
            case XmlTypeCode.Element:
            case XmlTypeCode.Attribute:
            case XmlTypeCode.Namespace:
            case XmlTypeCode.ProcessingInstruction:
            case XmlTypeCode.Comment:
            case XmlTypeCode.Text:
            case XmlTypeCode.UntypedAtomic:
            {
                throw new InvalidOperationException();
            }

            case XmlTypeCode.String:
            case XmlTypeCode.Notation:
            case XmlTypeCode.NormalizedString:
            case XmlTypeCode.Token:
            case XmlTypeCode.Language:
            case XmlTypeCode.Id:
            {
                string str = value as string;
                Debug.Assert(str != null);
                codePrimitiveExpression = new CodePrimitiveExpression(str);
                break;
            }

            case XmlTypeCode.Boolean:
            {
                Debug.Assert(value is bool);
                codePrimitiveExpression = new CodePrimitiveExpression(value);
                break;
            }

            case XmlTypeCode.Decimal:
            case XmlTypeCode.Integer:
            case XmlTypeCode.NonPositiveInteger:
            case XmlTypeCode.NegativeInteger:
            case XmlTypeCode.Long:
            case XmlTypeCode.Int:
            case XmlTypeCode.Short:
            case XmlTypeCode.Byte:
            case XmlTypeCode.NonNegativeInteger:
            case XmlTypeCode.UnsignedLong:
            case XmlTypeCode.UnsignedInt:
            case XmlTypeCode.UnsignedShort:
            case XmlTypeCode.UnsignedByte:
            case XmlTypeCode.PositiveInteger:
            {
                codePrimitiveExpression = new CodePrimitiveExpression(value);
                break;
            }

            case XmlTypeCode.Float:
            case XmlTypeCode.Double:
            {
                Debug.Assert((value is double?true: value is float));
                codePrimitiveExpression = new CodePrimitiveExpression(value);
                break;
            }

            case XmlTypeCode.Duration:
            {
                Debug.Assert(value is TimeSpan);
                TimeSpan ts   = (TimeSpan)value;
                Type     type = typeof(TimeSpan);
                codeExpressionArray     = new CodeExpression[] { new CodePrimitiveExpression((object)ts.Ticks) };
                codePrimitiveExpression = new CodeObjectCreateExpression(type, codeExpressionArray);
                break;
            }

            case XmlTypeCode.DateTime:
            case XmlTypeCode.Time:
            case XmlTypeCode.Date:
            case XmlTypeCode.GYearMonth:
            case XmlTypeCode.GYear:
            case XmlTypeCode.GMonthDay:
            case XmlTypeCode.GDay:
            case XmlTypeCode.GMonth:
            {
                Debug.Assert(value is DateTime);
                DateTime dt    = (DateTime)value;
                Type     type1 = typeof(DateTime);
                codeExpressionArray     = new CodeExpression[] { new CodePrimitiveExpression((object)dt.Ticks) };
                codePrimitiveExpression = new CodeObjectCreateExpression(type1, codeExpressionArray);
                break;
            }

            case XmlTypeCode.HexBinary:
            case XmlTypeCode.Base64Binary:
            {
                codePrimitiveExpression = SimpleTypeCodeDomHelper.CreateByteArrayExpression(value);
                break;
            }

            case XmlTypeCode.AnyUri:
            {
                Debug.Assert(value is Uri);
                Type type2 = typeof(Uri);
                codeExpressionArray     = new CodeExpression[] { new CodePrimitiveExpression(((Uri)value).OriginalString) };
                codePrimitiveExpression = new CodeObjectCreateExpression(type2, codeExpressionArray);
                break;
            }

            case XmlTypeCode.QName:
            {
                XmlQualifiedName qname = value as XmlQualifiedName;
                Type             type3 = typeof(XmlQualifiedName);
                codeExpressionArray     = new CodeExpression[] { new CodePrimitiveExpression(qname.Name), new CodePrimitiveExpression(qname.Namespace) };
                codePrimitiveExpression = new CodeObjectCreateExpression(type3, codeExpressionArray);
                break;
            }

            case XmlTypeCode.NmToken:
            case XmlTypeCode.Name:
            case XmlTypeCode.NCName:
            {
                CodeTypeReferenceExpression codeTypeReferenceExpression = new CodeTypeReferenceExpression(typeof(XmlConvert));
                codeExpressionArray     = new CodeExpression[] { new CodePrimitiveExpression(value.ToString()) };
                codePrimitiveExpression = CodeDomHelper.CreateMethodCall(codeTypeReferenceExpression, "EncodeName", codeExpressionArray);
                break;
            }

            default:
            {
                throw new InvalidOperationException();
            }
            }
            return(codePrimitiveExpression);
        }
        public List <string> GenerateUnitTestsForClass(string solutionPath,
                                                       string generatedUnitTestProject, List <string> projClasses)
        {
            List <string> generatedTestClasses = new List <string>();

            // analyze solution, discover basic information about each project
            var            solutionAnalyzer = new SolutionAnalyzer(solutionPath);
            var            analyedSolution  = solutionAnalyzer.AnalyzeSolution();
            CompilerHelper compileHelper    = new CompilerHelper(_generatedTestClassesDirectory);

            foreach (AnalyzedProject proj in analyedSolution.Projects)
            {
                if (proj.Name != generatedUnitTestProject)
                {
                    var assembly = Assembly.LoadFile(proj.OutputFilePath); //TODO: what if the assembly does not exist because the project is not compiled??
                    _assemblyExportedTypes = assembly.GetExportedTypes();
                    inputParamGenerator    = new InputParamGenerator(_assemblyExportedTypes);

                    foreach (Type type in _assemblyExportedTypes)
                    {
                        if (projClasses.Any(pc => pc == type.Name))
                        {
                            if (!type.IsInterface) // don't want to write unit tests for interfaces
                            {
                                // create a class
                                CodeTypeDeclaration targetClass = new CodeTypeDeclaration
                                                                      (string.Format("{0}UnitTestsClass", type.Name))
                                {
                                    IsClass        = true,
                                    TypeAttributes = TypeAttributes.Public
                                };

                                // create a code unit (the in-memory representation of a class)
                                CodeCompileUnit codeUnit        = CreateCodeCompileUnit(proj.Name, type.Name, targetClass);
                                string          classSourceName = string.Format("{0}UnitTestsClass.cs", type.Name);

                                // generate the constructor for the unit test class in which all the
                                // external dependencies/calls will be mocked
                                var cut_ConstructorGenerator = new CUT_AddConstructor(inputParamGenerator, selectedProjectName);
                                cut_ConstructorGenerator.AddTestClassConstructor(classSourceName, targetClass, type, analyedSolution);

                                // generate a unit test for each method
                                // the method will be called and a Assert.NotNull assertion will be added
                                var methods = type.GetMethods(BindingFlags.Public
                                                              | BindingFlags.Instance | BindingFlags.DeclaredOnly);

                                foreach (MethodInfo m in methods)
                                {
                                    // randomly generate method parameters
                                    var methodParameters        = m.GetParameters();
                                    CodeExpression[] parameters = new CodeExpression[methodParameters.Length];
                                    int j = 0;
                                    foreach (ParameterInfo p in methodParameters)
                                    {
                                        // TODO: Rethink this !!!
                                        if (p.ParameterType.Name == "String" || p.ParameterType.Name == "Int32")
                                        {
                                            parameters[j] = new CodePrimitiveExpression(
                                                inputParamGenerator.ResolveParameter(p.ParameterType.Name));
                                        }
                                        else
                                        {
                                            CodeObjectCreateExpression createObjectExpression =
                                                inputParamGenerator.CreateCustomType(p.ParameterType.Name);
                                            parameters[j] = createObjectExpression;
                                        }
                                        j++;
                                    }

                                    var cut_addTestMethod = new CUT_AddTestMethod(inputParamGenerator);

                                    // Assert.NotNull(result);
                                    // Assert.NotThrow(() => targetObj.SomePublicMethod())
                                    cut_addTestMethod.AddTestMethod_ShouldNotThrowExceptionResultShouldNotBeNull(targetClass, m.Name,
                                                                                                                 parameters, type, "CallShouldNotThrowExceptionAndResultShouldNotBeNull");

                                    // Assert.AreEqual(result, "Insert expected value here.");
                                    cut_addTestMethod.AddTestMethod_ExpectedResultPlaceholder(targetClass, m.Name,
                                                                                              parameters, type, "ResultShouldBeAsExpected");
                                }

                                // generate the c# code based on the created code unit
                                string generatedTestClassPath = compileHelper.GenerateCSharpCode(codeUnit, classSourceName);

                                // compile the above generated code into a DLL/EXE
                                bool isGeneratedClassCompiled = compileHelper.CompileAsDLL(classSourceName, new List <string>()
                                {
                                    string.Format("{0}\\{1}", _packagesFolder, "NUnit.3.10.1\\lib\\net45\\nunit.framework.dll"),
                                    string.Format("{0}\\{1}", _packagesFolder, "Moq.4.10.0\\lib\\net45\\Moq.dll"),
                                    proj.OutputFilePath,
                                    typeof(System.Linq.Enumerable).Assembly.Location
                                });

                                if (!string.IsNullOrEmpty(generatedTestClassPath) && isGeneratedClassCompiled)
                                {
                                    generatedTestClasses.Add(generatedTestClassPath);
                                }
                            }
                        }
                    }
                }
            }

            return(generatedTestClasses);
        }
Exemple #26
0
        protected override void CreateConstructor(CodeStatementCollection localVars,
                                                  CodeStatementCollection trueStmt)
        {
#if NET_2_0
            if (!String.IsNullOrEmpty(pageParser.MasterPageFile))
            {
                // This is here just to trigger master page build, so that its type
                // is available when compiling the page itself.
                BuildManager.GetCompiledType(pageParser.MasterPageFile);
            }
#endif
            if (pageParser.ClientTarget != null)
            {
                CodeExpression prop;
                prop = new CodePropertyReferenceExpression(thisRef, "ClientTarget");
                CodeExpression ct = new CodePrimitiveExpression(pageParser.ClientTarget);
                if (localVars == null)
                {
                    localVars = new CodeStatementCollection();
                }
                localVars.Add(new CodeAssignStatement(prop, ct));
            }

            ArrayList deps      = pageParser.Dependencies;
            int       depsCount = deps != null ? deps.Count : 0;

            if (depsCount > 0)
            {
                if (localVars == null)
                {
                    localVars = new CodeStatementCollection();
                }
                if (trueStmt == null)
                {
                    trueStmt = new CodeStatementCollection();
                }

                CodeAssignStatement assign;
#if NET_2_0
                localVars.Add(
                    new CodeVariableDeclarationStatement(
                        typeof(string[]),
                        "dependencies")
                    );

                CodeVariableReferenceExpression dependencies = new CodeVariableReferenceExpression("dependencies");
                trueStmt.Add(
                    new CodeAssignStatement(dependencies, new CodeArrayCreateExpression(typeof(string), depsCount))
                    );

                CodeArrayIndexerExpression arrayIndex;
                object o;

                for (int i = 0; i < depsCount; i++)
                {
                    o          = deps [i];
                    arrayIndex = new CodeArrayIndexerExpression(dependencies, new CodeExpression[] { new CodePrimitiveExpression(i) });
                    assign     = new CodeAssignStatement(arrayIndex, new CodePrimitiveExpression(o));
                    trueStmt.Add(assign);
                }

                CodeMethodInvokeExpression getDepsCall = new CodeMethodInvokeExpression(
                    thisRef,
                    "GetWrappedFileDependencies",
                    new CodeExpression[] { dependencies }
                    );
                assign = new CodeAssignStatement(GetMainClassFieldReferenceExpression("__fileDependencies"), getDepsCall);
#else
                localVars.Add(new CodeVariableDeclarationStatement(
                                  typeof(ArrayList),
                                  "dependencies")
                              );

                CodeVariableReferenceExpression dependencies = new CodeVariableReferenceExpression("dependencies");
                trueStmt.Add(
                    new CodeAssignStatement(dependencies, new CodeObjectCreateExpression(typeof(ArrayList), new CodeExpression[] { new CodePrimitiveExpression(depsCount) }))
                    );

                CodeMethodInvokeExpression invoke;
                for (int i = 0; i < depsCount; i++)
                {
                    invoke = new CodeMethodInvokeExpression(dependencies, "Add", new CodeExpression[] { new CodePrimitiveExpression(deps [i]) });
                    trueStmt.Add(invoke);
                }
                assign = new CodeAssignStatement(GetMainClassFieldReferenceExpression("__fileDependencies"), dependencies);
#endif

                trueStmt.Add(assign);
            }

            base.CreateConstructor(localVars, trueStmt);
        }
Exemple #27
0
        private void GenerateXmlLoadAndSaveCode(CodeConstructor xmlConstructor, CodeMemberMethod saveToXmlMethod, Relation relation, string foreignClassShort)
        {
            /*
             *      XmlNodeList nodeList = xmlNode.SelectNodes("SubNodeName");
             *      for(int i = 0; i < nodeList.Count; i = i + 1)
             *      {
             *              XmlNode subNode = nodeList[i];
             *              this.relationField.Add(new RelatedType(subNode));
             *      }
             */
            TargetLanguage targetLanguage = ApplicationController.Instance.AssemblyNode.Assembly.TargetLanguage;
            string         xpath          = null;

            if (relation.IsForeign)
            {
                xpath = ((ForeignFkRelation)relation).XPath;
            }
            else
            {
                throw new Exception("Internal Error 132 in RelationGenerator: Relation is not a ForeignFkRelation.");
            }

            string nodeListName = relation.FieldName + "NodeList";
            CodeVariableReferenceExpression nsManager  = new CodeVariableReferenceExpression("NamespaceManager");
            CodePropertyReferenceExpression nsInstance = new CodePropertyReferenceExpression(nsManager, "Instance");

            CodeVariableDeclarationStatement nodeListDecl = new CodeVariableDeclarationStatement("XmlNodeList", nodeListName,
                                                                                                 new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("xmlNode"), "SelectNodes", new CodePrimitiveExpression(xpath), nsInstance));

            xmlConstructor.Statements.Add(nodeListDecl);

            CodeVariableReferenceExpression iExpr         = new CodeVariableReferenceExpression("i");
            CodeFieldReferenceExpression    relationField = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), relation.FieldName);

            CodeIterationStatement forLoop = new CodeIterationStatement(
                new CodeAssignStatement(iExpr, new CodePrimitiveExpression(0)),
                new CodeBinaryOperatorExpression(
                    iExpr,
                    CodeBinaryOperatorType.LessThan,
                    new CodeVariableReferenceExpression(nodeListName + ".Count")),                 // should work in C# and VB
                new CodeAssignStatement(
                    iExpr,
                    new CodeBinaryOperatorExpression(
                        iExpr,
                        CodeBinaryOperatorType.Add,
                        new CodePrimitiveExpression(1))),
                new CodeVariableDeclarationStatement("XmlNode", "subNode",
                                                     new CodeIndexerExpression(
                                                         new CodeVariableReferenceExpression(nodeListName),
                                                         iExpr)),
                new CodeExpressionStatement(
                    new CodeMethodInvokeExpression(relationField, "Add",
                                                   new CodeObjectCreateExpression(foreignClassShort,
                                                                                  new CodeVariableReferenceExpression("subNode")))));

            xmlConstructor.Statements.Add(forLoop);

            /*
             * for ( int i = 0; i < relatedContainer.Count; i = i + 1 )
             * {
             *      RelatedType relObject = relContainer[i];
             *      relObject.Save(newElement, "Elementname", "Namespace");
             * }
             */
            string elementNodeName = null;

            string[] xpathParts = xpath.Split('/');
            if (xpath.IndexOf('/') > -1)
            {
                elementNodeName = GenerateNestedXpathCode(xpathParts, saveToXmlMethod);
            }
            else
            {
                elementNodeName = "myElement";
            }

            string elementPath = xpathParts[xpathParts.Length - 1];
            string namespc     = this.namespaceWrapper[NamespaceWrapper.GetPrefixFromQualifiedName(elementPath)];

            elementPath = NamespaceWrapper.GetXpathFromQualifiedName(elementPath);

            CodeExpression namespcExpr = new CodePrimitiveExpression(namespc);

            forLoop = new CodeIterationStatement(
                new CodeAssignStatement(iExpr, new CodePrimitiveExpression(0)),
                new CodeBinaryOperatorExpression(
                    iExpr,
                    CodeBinaryOperatorType.LessThan,
                    new CodePropertyReferenceExpression(relationField, "Count")),
                new CodeAssignStatement(
                    iExpr,
                    new CodeBinaryOperatorExpression(
                        iExpr,
                        CodeBinaryOperatorType.Add,
                        new CodePrimitiveExpression(1))),
                new CodeVariableDeclarationStatement(foreignClassShort, "relObject",
                                                     new CodeIndexerExpression(relationField, iExpr)),
                new CodeExpressionStatement(
                    new CodeMethodInvokeExpression(
                        new CodeVariableReferenceExpression("relObject"), "Save",
                        new CodeVariableReferenceExpression(elementNodeName),
                        new CodePrimitiveExpression(elementPath), namespcExpr)));

            saveToXmlMethod.Statements.Add(forLoop);
        }
Exemple #28
0
        protected void AddInitializeRuntimeOptionsStatements(CodeStatementCollection statements, CodeVariableReferenceExpression optionsVar)
        {
            // Initial template
            //------------------------------------------------

            BindingExpressionInfo bind         = parser.InitialTemplateBinding;
            XmlQualifiedName      initialTempl = parser.InitialTemplate;

            if (bind != null || initialTempl != null)
            {
                CodeAssignStatement assignFromPrimitive = null;

                if (initialTempl != null)
                {
                    assignFromPrimitive = new CodeAssignStatement {
                        Left = new CodePropertyReferenceExpression {
                            PropertyName = "InitialTemplate",
                            TargetObject = optionsVar
                        },
                        Right = new CodeObjectCreateExpression(
                            typeof(XmlQualifiedName),
                            new CodePrimitiveExpression(initialTempl.Name),
                            new CodePrimitiveExpression(initialTempl.Namespace)
                            )
                    };
                }

                if (bind != null)
                {
                    bool bindRequired = initialTempl == null;

                    var paramName = new CodePrimitiveExpression(bind.ParsedValues.ContainsKey("name") ? bind.ParsedValues["name"] : bind.Expression);

                    var initialTemplVar = new CodeVariableDeclarationStatement {
                        Name           = "initialTempl",
                        Type           = new CodeTypeReference(typeof(String)),
                        InitExpression = new CodeMethodInvokeExpression {
                            Method = new CodeMethodReferenceExpression {
                                MethodName   = "CheckParamLength",
                                TargetObject = new CodeThisReferenceExpression()
                            },
                            Parameters =
                            {
                                paramName,
                                bind.GetCodeExpression(),
                                new CodePrimitiveExpression(bindRequired ? 1 : 0),
                                new CodePrimitiveExpression(1)
                            }
                        }
                    };

                    if (bind.LineNumber > 0)
                    {
                        initialTemplVar.LinePragma = new CodeLinePragma(this.parser.PhysicalPath.LocalPath, bind.LineNumber);
                    }

                    if (bind.ParsedValues.ContainsKey("accept"))
                    {
                        initialTemplVar.InitExpression = new CodeMethodInvokeExpression {
                            Method = new CodeMethodReferenceExpression {
                                MethodName   = "CheckParamValues",
                                TargetObject = new CodeThisReferenceExpression()
                            },
                            Parameters =
                            {
                                paramName,
                                initialTemplVar.InitExpression,
                                new CodeArrayCreateExpression(typeof(string), ((string[])bind.ParsedValues["accept"]).Select(s => new CodePrimitiveExpression(s)).ToArray())
                            }
                        };
                    }

                    initialTemplVar.InitExpression = new CodeMethodInvokeExpression {
                        Method = new CodeMethodReferenceExpression {
                            MethodName   = "AsString",
                            TargetObject = new CodeThisReferenceExpression()
                        },
                        Parameters =
                        {
                            initialTemplVar.InitExpression
                        }
                    };

                    statements.Add(initialTemplVar);

                    var assignFromVar = new CodeAssignStatement {
                        Left = new CodePropertyReferenceExpression {
                            PropertyName = "InitialTemplate",
                            TargetObject = optionsVar
                        },
                        Right = new CodeObjectCreateExpression(
                            typeof(XmlQualifiedName),
                            new CodeMethodInvokeExpression {
                            Method = new CodeMethodReferenceExpression {
                                MethodName   = "ToString",
                                TargetObject = new CodeVariableReferenceExpression(initialTemplVar.Name)
                            }
                        }
                            )
                    };

                    if (bindRequired)
                    {
                        statements.Add(assignFromVar);
                    }
                    else
                    {
                        var ifStatement = new CodeConditionStatement {
                            Condition = new CodeBinaryOperatorExpression {
                                Left     = new CodeVariableReferenceExpression(initialTemplVar.Name),
                                Operator = CodeBinaryOperatorType.IdentityInequality,
                                Right    = new CodePrimitiveExpression(null)
                            },
                            TrueStatements  = { assignFromVar },
                            FalseStatements = { assignFromPrimitive }
                        };

                        statements.Add(ifStatement);
                    }
                }
                else
                {
                    statements.Add(assignFromPrimitive);
                }
            }

            // Initial context node
            //------------------------------------------------

            if (initialContextNodeField != null || this.parser.PageType == XsltPageType.SimplifiedStylesheet)
            {
                if (initialContextNodeField != null)
                {
                    statements.Add(
                        new CodeAssignStatement {
                        Left = new CodePropertyReferenceExpression {
                            PropertyName = "InitialContextNode",
                            TargetObject = optionsVar
                        },
                        Right = new CodeFieldReferenceExpression {
                            FieldName    = initialContextNodeField.Name,
                            TargetObject = PageTypeReferenceExpression
                        }
                    }
                        );
                }
                else
                {
                    statements.Add(
                        new CodeAssignStatement {
                        Left = new CodePropertyReferenceExpression {
                            PropertyName = "InitialContextNode",
                            TargetObject = optionsVar
                        },
                        Right = new CodeMethodInvokeExpression {
                            Method = new CodeMethodReferenceExpression {
                                MethodName   = "CreateNodeReadOnly",
                                TargetObject = new CodePropertyReferenceExpression {
                                    PropertyName = "ItemFactory",
                                    TargetObject = new CodePropertyReferenceExpression {
                                        PropertyName = "Processor",
                                        TargetObject = new CodePropertyReferenceExpression {
                                            PropertyName = "Executable",
                                            TargetObject = new CodeThisReferenceExpression()
                                        }
                                    }
                                }
                            },
                        }
                    }
                        );
                }
            }
        }
Exemple #29
0
        private CodeTypeDeclaration GetTypeDecalaration(StructDeclaration structDeclaration)
        {
            CodeTypeDeclaration type = new CodeTypeDeclaration(structDeclaration.Name)
            {
                IsClass   = structDeclaration.IsRef,
                IsStruct  = !structDeclaration.IsRef,
                IsPartial = true
            };
            string serializerName     = structDeclaration.Name + "Serializer";
            string serializerFullName = $"{structDeclaration.Name}.{serializerName}";

            AddMemorySizeAttribute(type, (int)structDeclaration.Size);
            AddSerializeByAttribute(type, serializerFullName);
            AddSerializableAttribute(type);
            AddMessageMethods(type);

            if (structDeclaration.Doc != null)
            {
                type.Comments.Add(GetDocument(structDeclaration.Doc));
            }

            switch (structDeclaration.Visibility)
            {
            case TypeVisibility.Internal when structDeclaration.IsNested:
                type.TypeAttributes = TypeAttributes.NestedAssembly;
                break;

            case TypeVisibility.Internal:
                type.TypeAttributes = TypeAttributes.NotPublic;
                break;

            case TypeVisibility.Private:
                type.TypeAttributes = TypeAttributes.NestedPrivate;
                break;

            case TypeVisibility.PrivateProtected:
                type.TypeAttributes = TypeAttributes.NestedFamANDAssem;
                break;

            case TypeVisibility.Protected:
                type.TypeAttributes = TypeAttributes.NestedFamily;
                break;

            case TypeVisibility.ProtectedInternal:
                type.TypeAttributes = TypeAttributes.NestedFamORAssem;
                break;

            case TypeVisibility.Public:
                type.TypeAttributes = TypeAttributes.Public;
                break;
            }

            if (structDeclaration.IsFinal)
            {
                type.TypeAttributes |= TypeAttributes.Sealed;
            }

            CodeTypeReference structRef = new CodeTypeReference(structDeclaration.Name);

            AddShortcutMethod(type, structDeclaration.Name, structRef);

            AddSerializerType(type, structRef, serializerName, structDeclaration.Name, out var serializeMethod, out var deserializeMethod);

            foreach (var declaration in structDeclaration.Declarations.Declarations)
            {
                switch (declaration)
                {
                case FieldDeclaration fieldDeclaration:
                    string fieldName = "m_" + fieldDeclaration.Name;
                    string typeName  = ValidateType(fieldDeclaration.Type.RawString);

                    CodeTypeReference            fieldType = GetTypeReference(typeName, fieldDeclaration.Type);
                    CodeFieldReferenceExpression fieldRef  = new CodeFieldReferenceExpression(s_ObjRef, fieldName);
                    CodePrimitiveExpression      index     = new CodePrimitiveExpression((int)fieldDeclaration.Index);
                    CodeTypeReferenceExpression  realType  = fieldDeclaration.RealType == null ? null : new CodeTypeReferenceExpression(GetTypeReference(ValidateType(fieldDeclaration.RealType.RawString), fieldDeclaration.Type));

                    CodeMemberField field = new CodeMemberField()
                    {
                        Attributes = MemberAttributes.Private | MemberAttributes.Final,
                        Name       = fieldName,
                        Type       = fieldType,
                    };

                    if (fieldDeclaration.IsNeverNull)
                    {
                        field.CustomAttributes.Add(s_NeverNullAttr);
                    }

                    if (fieldDeclaration.IsObsolete)
                    {
                        field.CustomAttributes.Add(s_ObsoleteAttr);
                    }

                    AddSerialIndexAttribute(field, index);

                    if (realType != null)
                    {
                        AddFacadeTypeAttribute(field, realType.Type);
                    }

#if UNITY
                    field.CustomAttributes.Add(s_SerializeFieldAttr);
#endif

                    CodeMemberProperty property = new CodeMemberProperty()
                    {
                        Attributes = MemberAttributes.Public | MemberAttributes.Final,
                        Name       = fieldDeclaration.Name,
                        Type       = fieldType,
                        HasGet     = true,
                        HasSet     = true
                    };

                    if (fieldDeclaration.Doc != null)
                    {
                        property.Comments.Add(GetDocument(fieldDeclaration.Doc));
                    }

                    if (fieldDeclaration.IsObsolete)
                    {
                        property.CustomAttributes.Add(s_ObsoleteAttr);
                    }

                    SetPropertyMethods(property, fieldName);

                    type.Members.Add(field);
                    type.Members.Add(property);

                    if (!fieldDeclaration.IsObsolete)
                    {
                        AddSerializedField(serializeMethod, fieldRef, index, realType, fieldDeclaration.IsNeverNull);
                    }

                    break;

                case StructDeclaration structDeclaration1:
                    CodeTypeDeclaration type1 = GetTypeDecalaration(structDeclaration1);
                    type.Members.Add(type1);
                    break;
                }
            }

            deserializeMethod.Statements.Add(GetDeserializeMethodBody(structDeclaration.Declarations.Declarations));
            deserializeMethod.Statements.Add(s_OnAfterDeserialization);
            deserializeMethod.Statements.Add(s_ReturnResult);

            return(type);
        }
        public override void ProcessDirective(string directiveName, IDictionary <string, string> arguments)
        {
            string name = arguments["name"];
            string type = arguments["type"];

            if (string.IsNullOrEmpty(name))
            {
                throw new DirectiveProcessorException("Parameter directive has no name argument");
            }
            if (string.IsNullOrEmpty(type))
            {
                throw new DirectiveProcessorException("Parameter directive has no type argument");
            }

            string fieldName = "_" + name + "Field";
            var    typeRef   = new CodeTypeReference(type);
            var    thisRef   = new CodeThisReferenceExpression();
            var    fieldRef  = new CodeFieldReferenceExpression(thisRef, fieldName);

            var property = new CodeMemberProperty()
            {
                Name       = name,
                Attributes = MemberAttributes.Public | MemberAttributes.Final,
                HasGet     = true,
                HasSet     = false,
                Type       = typeRef
            };

            property.GetStatements.Add(new CodeMethodReturnStatement(fieldRef));
            members.Add(new CodeMemberField(typeRef, fieldName));
            members.Add(property);

            string acquiredName           = "_" + name + "Acquired";
            var    valRef                 = new CodeVariableReferenceExpression("data");
            var    namePrimitive          = new CodePrimitiveExpression(name);
            var    sessionRef             = new CodePropertyReferenceExpression(thisRef, "Session");
            var    callContextTypeRefExpr = new CodeTypeReferenceExpression("System.Runtime.Remoting.Messaging.CallContext");
            var    nullPrim               = new CodePrimitiveExpression(null);

            var acquiredVariable    = new CodeVariableDeclarationStatement(typeof(bool), acquiredName, new CodePrimitiveExpression(false));
            var acquiredVariableRef = new CodeVariableReferenceExpression(acquiredVariable.Name);

            this.postStatements.Add(acquiredVariable);

            //checks the local called "data" can be cast and assigned to the field, and if successful, sets acquiredVariable to true
            var checkCastThenAssignVal = new CodeConditionStatement(
                new CodeMethodInvokeExpression(
                    new CodeTypeOfExpression(typeRef), "IsAssignableFrom", new CodeMethodInvokeExpression(valRef, "GetType")),
                new CodeStatement[] {
                new CodeAssignStatement(fieldRef, new CodeCastExpression(typeRef, valRef)),
                new CodeAssignStatement(acquiredVariableRef, new CodePrimitiveExpression(true)),
            },
                new CodeStatement[] {
                new CodeExpressionStatement(new CodeMethodInvokeExpression(thisRef, "Error",
                                                                           new CodePrimitiveExpression("The type '" + type + "' of the parameter '" + name +
                                                                                                       "' did not match the type passed to the template"))),
            });

            //tries to gets the value from the session
            var checkSession = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(NotNull(sessionRef), CodeBinaryOperatorType.BooleanAnd,
                                                 new CodeMethodInvokeExpression(sessionRef, "ContainsKey", namePrimitive)),
                new CodeVariableDeclarationStatement(typeof(object), "data", new CodeIndexerExpression(sessionRef, namePrimitive)),
                checkCastThenAssignVal);

            this.postStatements.Add(checkSession);

            //if acquiredVariable is false, tries to gets the value from the host
            if (hostSpecific)
            {
                var hostRef   = new CodePropertyReferenceExpression(thisRef, "Host");
                var checkHost = new CodeConditionStatement(
                    BooleanAnd(IsFalse(acquiredVariableRef), NotNull(hostRef)),
                    new CodeVariableDeclarationStatement(typeof(string), "data",
                                                         new CodeMethodInvokeExpression(hostRef, "ResolveParameterValue", nullPrim, nullPrim, namePrimitive)),
                    new CodeConditionStatement(NotNull(valRef), checkCastThenAssignVal));

                this.postStatements.Add(checkHost);
            }

            //if acquiredVariable is false, tries to gets the value from the call context
            var checkCallContext = new CodeConditionStatement(
                IsFalse(acquiredVariableRef),
                new CodeVariableDeclarationStatement(typeof(object), "data",
                                                     new CodeMethodInvokeExpression(callContextTypeRefExpr, "LogicalGetData", namePrimitive)),
                new CodeConditionStatement(NotNull(valRef), checkCastThenAssignVal));

            this.postStatements.Add(checkCallContext);
        }
Exemple #31
0
        private void AddSerializedField(CodeMemberMethod serializeMethod, CodeFieldReferenceExpression fieldRef, CodePrimitiveExpression index, CodeTypeReferenceExpression realType, bool isNeverNull)
        {
            CodeExpression param = realType == null ? fieldRef as CodeExpression : new CodeCastExpression(realType.Type, fieldRef);
            CodeExpression expr  = new CodeMethodInvokeExpression(s_WriterRef, "WriteValue", index, param);

            if (isNeverNull)
            {
                serializeMethod.Statements.Add(expr);
            }
            else
            {
                CodeConditionStatement condition = new CodeConditionStatement(new CodeBinaryOperatorExpression(fieldRef, CodeBinaryOperatorType.IdentityInequality, s_Null), new CodeExpressionStatement(expr));
                serializeMethod.Statements.Add(condition);
            }
        }
Exemple #32
0
        private static void BuildStandardMethod(
            CodeTypeDeclaration declaration,
            string methodName,
            string rpcMethodName,
            Type[] argTypes,
            string[] argNames,
            Type returnType,
            Type implementationType)
        {
            var cmm = new CodeMemberMethod();

            // normal, unqualified type names are public
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            cmm.ImplementationTypes.Add(implementationType);
            cmm.Name = methodName;

            // set the return type
            var ctrReturn = new CodeTypeReference(returnType);

            cmm.ReturnType = ctrReturn;

            MakeParameterList(cmm, argTypes, argNames);

            // add an XmlRpcMethod attribute to the type
            var cad = new CodeAttributeDeclaration();

            cad.Name = typeof(XmlRpcMethodAttribute).FullName;

            var caa = new CodeAttributeArgument();
            var cpe = new CodePrimitiveExpression(rpcMethodName);

            caa.Value = cpe;

            cad.Arguments.Add(caa);

            cmm.CustomAttributes.Add(cad);

            // generate the method body:

            // if non-void return, declared locals for processing return value
            if (returnType != typeof(void))
            {
                // add some local variables
                MakeTempVariable(cmm, typeof(object));
                MakeReturnVariable(cmm, returnType);
            }

            MakeTempParameterArray(cmm, argTypes, argNames);

            // construct a call to the base Invoke method
            var ctre = new CodeThisReferenceExpression();

            var cmre = new CodeMethodReferenceExpression(ctre, "Invoke");

            var cmie = new CodeMethodInvokeExpression();

            cmie.Method = cmre;
            cmie.Parameters.Add(new CodePrimitiveExpression(methodName));
            cmie.Parameters.Add(new CodeVariableReferenceExpression(DEFAULT_ARR));

            if (returnType != typeof(void))
            {
                // assign the result to tempRetVal
                var casTemp = new CodeAssignStatement();
                casTemp.Left  = new CodeVariableReferenceExpression(DEFAULT_TEMP);
                casTemp.Right = cmie;

                cmm.Statements.Add(casTemp);
            }
            else
            {
                // discard return type
                cmm.Statements.Add(cmie);
            }

            MakeReturnStatement(cmm, returnType);

            // add the finished method to the type
            declaration.Members.Add(cmm);
        }
 public void VisitPrimitive(CodePrimitiveExpression p)
 {
     if (p.Value == null)
         writer.Write("null");
     else if (p.Value is string)
         WriteStringLiteral(p.Value as string);
     else if (p.Value is int)
         writer.Write(p.Value.ToString());
     else if (p.Value is long)
         writer.Write("{0}L", p.Value);
     else if (p.Value is bool)
         writer.Write((bool)p.Value ? "true" : "false");
     else if (p.Value is double)
     {
         var s = p.Value.ToString();
         if (!s.Contains('.') && !s.Contains('e') && !s.Contains('E'))
             s += ".0";
         writer.Write(s);
     }
     else if (p.Value is Syntax.Str)
         WriteStringLiteral((Syntax.Str)p.Value);
     else
         throw new NotImplementedException("" + p.Value);
 }
 private void GeneratePrimitiveExpressionBase(CodePrimitiveExpression e)
 {
     if (e.Value == null)
     {
         Output.Write(NullToken);
     }
     else if (e.Value is string)
     {
         Output.Write(QuoteSnippetString((string)e.Value));
     }
     else if (e.Value is char)
     {
         Output.Write("'" + e.Value.ToString() + "'");
     }
     else if (e.Value is byte)
     {
         Output.Write(((byte)e.Value).ToString(CultureInfo.InvariantCulture));
     }
     else if (e.Value is Int16)
     {
         Output.Write(((Int16)e.Value).ToString(CultureInfo.InvariantCulture));
     }
     else if (e.Value is Int32)
     {
         Output.Write(((Int32)e.Value).ToString(CultureInfo.InvariantCulture));
     }
     else if (e.Value is Int64)
     {
         Output.Write(((Int64)e.Value).ToString(CultureInfo.InvariantCulture));
     }
     else if (e.Value is Single)
     {
         GenerateSingleFloatValue((Single)e.Value);
     }
     else if (e.Value is Double)
     {
         GenerateDoubleValue((Double)e.Value);
     }
     else if (e.Value is Decimal)
     {
         GenerateDecimalValue((Decimal)e.Value);
     }
     else if (e.Value is bool)
     {
         if ((bool)e.Value)
         {
             Output.Write("true");
         }
         else
         {
             Output.Write("false");
         }
     }
     else
     {
         throw new ArgumentException("Invalid primitive type", e.Value.GetType().ToString());
     }
 }
		protected virtual void GeneratePrimitiveExpression(CodePrimitiveExpression e)
		{
			object value = e.Value;
			if (value == null)
			{
				output.Write(NullToken);
				return;
			}
 
			Type type = value.GetType();
			TypeCode typeCode = Type.GetTypeCode(type);
			switch (typeCode)
			{
				case TypeCode.Boolean:
					output.Write(value.ToString().ToLower(CultureInfo.InvariantCulture));
					break;
				case TypeCode.Char:
					output.Write("'" + value.ToString() + "'");
					break;
				case TypeCode.String:
					output.Write(EscapeString((string)value));
					break;
				case TypeCode.Single:
					GenerateSingleFloatValue((float)value);
					break;
				case TypeCode.Double:
					GenerateDoubleValue((double)value);
					break;
				case TypeCode.Decimal:
					GenerateDecimalValue((decimal)value);
					break;
				case TypeCode.Byte:
				case TypeCode.Int16:
				case TypeCode.Int32:
				case TypeCode.Int64:
					output.Write(((IFormattable)value).ToString(null, CultureInfo.InvariantCulture));
					break;
				default:
					throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
					"Invalid Primitive Type: {0}. Only CLS compliant primitive " +
						"types can be used. Consider using CodeObjectCreateExpression.",
					type.FullName));
			}
		}
	// Generate code for a primitive expression.
	protected virtual void GeneratePrimitiveExpression
				(CodePrimitiveExpression e)
			{
				Object value = e.Value;
				if(value == null)
				{
					Output.Write(NullToken);
				}
				else if(value is String)
				{
					Output.Write(QuoteSnippetString((String)value));
				}
				else if(value is Char)
				{
					char ch = (char)value;
					String chvalue;
					switch(ch)
					{
						case '\'':	chvalue = "'\\''"; break;
						case '\\':	chvalue = "'\\\\'"; break;
						case '\n':	chvalue = "'\\n'"; break;
						case '\r':	chvalue = "'\\r'"; break;
						case '\t':	chvalue = "'\\t'"; break;
						case '\f':	chvalue = "'\\f'"; break;
						case '\v':	chvalue = "'\\v'"; break;
						case '\a':	chvalue = "'\\a'"; break;
						case '\b':	chvalue = "'\\b'"; break;
						default:
						{
							if(ch >= ' ' && ch <= 0x7E)
							{
								chvalue = "\"" + ch.ToString() + "\"";
							}
							else if(ch < 0x0100)
							{
								chvalue = "\"\\x" +
									hexchars[(ch >> 4) & 0x0F] +
									hexchars[ch & 0x0F] + "\"";
							}
							else
							{
								chvalue = "\"\\u" +
									hexchars[(ch >> 12) & 0x0F] +
									hexchars[(ch >> 8) & 0x0F] +
									hexchars[(ch >> 4) & 0x0F] +
									hexchars[ch & 0x0F] + "\"";
							}
						}
						break;
					}
					Output.Write(chvalue);
				}
				else if(value is SByte)
				{
					Output.Write((int)(sbyte)value);
				}
				else if(value is Byte)
				{
					Output.Write((int)(byte)value);
				}
				else if(value is Int16)
				{
					Output.Write((int)(short)value);
				}
				else if(value is UInt16)
				{
					Output.Write((int)(ushort)value);
				}
				else if(value is Int32)
				{
					Output.Write((int)value);
				}
				else if(value is UInt32)
				{
					Output.Write((uint)value);
				}
				else if(value is Int64)
				{
					Output.Write((long)value);
				}
				else if(value is UInt64)
				{
					Output.Write((ulong)value);
				}
				else if(value is Single)
				{
					GenerateSingleFloatValue((float)value);
				}
				else if(value is Double)
				{
					GenerateDoubleValue((double)value);
				}
				else if(value is Decimal)
				{
					GenerateDecimalValue((Decimal)value);
				}
				else if(value is Boolean)
				{
					if((bool)value)
					{
						Output.Write("true");
					}
					else
					{
						Output.Write("false");
					}
				}
				else
				{
					throw new ArgumentException
						(S._("Arg_InvalidCodeDom"), "e");
				}
			}
Exemple #37
0
 public static string Print(CodePrimitiveExpression expr)
 {
     return(expr.Value.ToString());
 }
			public void Visit(CodePrimitiveExpression o)
			{
				g.GeneratePrimitiveExpression(o);
			}
        private static void CreateLoad(CodeTypeDeclaration classType, CodeGenerationInfo generationInfo)
        {
            var cc = new CodeMemberMethod()
            {
                Attributes = MemberAttributes.Public | MemberAttributes.Final,
                Name       = "Load",
            };

            cc.Parameters.Add("IDataSet", "dataSet");
            cc.Parameters.Add(new CodeTypeReference(typeof(bool)), "verifyRevision");

            var dataSet = new CodeVariableReferenceExpression("dataSet");

            {
                var ccs = CreateCompareDataBaseStatement(classType, generationInfo);
                var tst = CreateTryCatchStatement(classType, ccs, generationInfo);
                cc.Statements.Add(tst);
            }

            {
                var ccs = CreateCompareRevisionStatement(classType, generationInfo);
                var tst = CreateTryCatchStatement(classType, ccs, generationInfo);
                cc.Statements.Add(tst);
            }

            {
                var field    = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_name");
                var property = new CodePropertyReferenceExpression(dataSet, "Name");
                cc.Statements.AddAssign(field, property);
            }

            {
                var field    = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_revision");
                var property = new CodePropertyReferenceExpression(dataSet, "Revision");
                cc.Statements.AddAssign(field, property);
            }

            {
                var field    = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_typesHashValue");
                var property = new CodePropertyReferenceExpression(dataSet, "TypesHashValue");
                cc.Statements.AddAssign(field, property);
            }

            {
                var field    = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_tablesHashValue");
                var property = new CodePropertyReferenceExpression(dataSet, "TablesHashValue");
                cc.Statements.AddAssign(field, property);
            }

            {
                var field    = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_tags");
                var property = new CodePropertyReferenceExpression(dataSet, "Tags");
                cc.Statements.AddAssign(field, property);
            }

            foreach (var item in generationInfo.GetTables(true))
            {
                var tableName  = new CodePrimitiveExpression(item.Name);
                var tablesProp = new CodePropertyReferenceExpression(dataSet, "Tables");
                var table      = new CodeIndexerExpression(tablesProp, tableName);

                var field           = item.GetFieldExpression();
                var instance        = new CodeObjectCreateExpression(item.GetCodeType(), table);
                var assignStatement = new CodeAssignStatement(field, instance);

                if (generationInfo.IsDevmode == true)
                {
                    var tryStatement = CreateTryCatchStatement(classType, assignStatement, generationInfo);
                    cc.Statements.Add(tryStatement);
                }
                else
                {
                    cc.Statements.Add(assignStatement);
                }
            }

            classType.Members.Add(cc);
        }
        CodeMemberMethod GenerateMethod(CodeIdentifiers memberIds, HttpOperationBinding httpOper, XmlMembersMapping inputMembers, XmlTypeMapping outputMember)
        {
            CodeIdentifiers  pids        = new CodeIdentifiers();
            CodeMemberMethod method      = new CodeMemberMethod();
            CodeMemberMethod methodBegin = new CodeMemberMethod();
            CodeMemberMethod methodEnd   = new CodeMemberMethod();

            method.Attributes      = MemberAttributes.Public;
            methodBegin.Attributes = MemberAttributes.Public;
            methodEnd.Attributes   = MemberAttributes.Public;

            // Find unique names for temporary variables

            for (int n = 0; n < inputMembers.Count; n++)
            {
                pids.AddUnique(inputMembers[n].MemberName, inputMembers[n]);
            }

            string varAsyncResult = pids.AddUnique("asyncResult", "asyncResult");
            string varCallback    = pids.AddUnique("callback", "callback");
            string varAsyncState  = pids.AddUnique("asyncState", "asyncState");

            string messageName = memberIds.AddUnique(CodeIdentifier.MakeValid(Operation.Name), method);

            method.Name      = Operation.Name;
            methodBegin.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("Begin" + Operation.Name), method);
            methodEnd.Name   = memberIds.AddUnique(CodeIdentifier.MakeValid("End" + Operation.Name), method);

            method.ReturnType    = new CodeTypeReference(typeof(void));
            methodEnd.ReturnType = new CodeTypeReference(typeof(void));
            methodEnd.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IAsyncResult), varAsyncResult));

            CodeExpression[] paramArray = new CodeExpression [inputMembers.Count];

            for (int n = 0; n < inputMembers.Count; n++)
            {
                string ptype = GetSimpleType(inputMembers[n]);
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(ptype, inputMembers[n].MemberName);

                param.Direction = FieldDirection.In;
                method.Parameters.Add(param);
                methodBegin.Parameters.Add(param);
                paramArray [n] = new CodeVariableReferenceExpression(param.Name);
            }

            bool isVoid = true;

            if (outputMember != null)
            {
                method.ReturnType    = new CodeTypeReference(outputMember.TypeFullName);
                methodEnd.ReturnType = new CodeTypeReference(outputMember.TypeFullName);
                xmlExporter.AddMappingMetadata(method.ReturnTypeCustomAttributes, outputMember, "");
                isVoid = false;
            }

            methodBegin.Parameters.Add(new CodeParameterDeclarationExpression(typeof(AsyncCallback), varCallback));
            methodBegin.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), varAsyncState));
            methodBegin.ReturnType = new CodeTypeReference(typeof(IAsyncResult));

            // Array of input parameters

            CodeArrayCreateExpression methodParams;

            if (paramArray.Length > 0)
            {
                methodParams = new CodeArrayCreateExpression(typeof(object), paramArray);
            }
            else
            {
                methodParams = new CodeArrayCreateExpression(typeof(object), 0);
            }

            // Generate method url

            CodeThisReferenceExpression ethis = new CodeThisReferenceExpression();

            CodeExpression               thisURlExp        = new CodeFieldReferenceExpression(ethis, "Url");
            CodePrimitiveExpression      metUrl            = new CodePrimitiveExpression(httpOper.Location);
            CodeBinaryOperatorExpression expMethodLocation = new CodeBinaryOperatorExpression(thisURlExp, CodeBinaryOperatorType.Add, metUrl);

            // Invoke call

            CodePrimitiveExpression    varMsgName = new CodePrimitiveExpression(messageName);
            CodeMethodInvokeExpression inv;

            inv = new CodeMethodInvokeExpression(ethis, "Invoke", varMsgName, expMethodLocation, methodParams);
            if (!isVoid)
            {
                method.Statements.Add(new CodeMethodReturnStatement(new CodeCastExpression(method.ReturnType, inv)));
            }
            else
            {
                method.Statements.Add(inv);
            }

            // Begin Invoke Call

            CodeExpression expCallb  = new CodeVariableReferenceExpression(varCallback);
            CodeExpression expAsyncs = new CodeVariableReferenceExpression(varAsyncState);

            inv = new CodeMethodInvokeExpression(ethis, "BeginInvoke", varMsgName, expMethodLocation, methodParams, expCallb, expAsyncs);
            methodBegin.Statements.Add(new CodeMethodReturnStatement(inv));

            // End Invoke call

            CodeExpression varAsyncr = new CodeVariableReferenceExpression(varAsyncResult);

            inv = new CodeMethodInvokeExpression(ethis, "EndInvoke", varAsyncr);
            if (!isVoid)
            {
                methodEnd.Statements.Add(new CodeMethodReturnStatement(new CodeCastExpression(methodEnd.ReturnType, inv)));
            }
            else
            {
                methodEnd.Statements.Add(inv);
            }

            // Attributes

            CodeAttributeDeclaration att = new CodeAttributeDeclaration("System.Web.Services.Protocols.HttpMethodAttribute");

            att.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(GetOutMimeFormatter())));
            att.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(GetInMimeFormatter())));
            AddCustomAttribute(method, att, true);

            CodeTypeDeclaration.Members.Add(method);
            CodeTypeDeclaration.Members.Add(methodBegin);
            CodeTypeDeclaration.Members.Add(methodEnd);

            return(method);
        }
Exemple #41
0
 private void ValidatePrimitiveExpression(CodePrimitiveExpression e)
 {
 }
Exemple #42
0
 protected virtual void GeneratePrimitiveExpression(CodePrimitiveExpression e)
 {
     if (e.Value == null)
     {
         Output.Write(NullToken);
     }
     else if (e.Value is string)
     {
         Output.Write(QuoteSnippetString((string)e.Value));
     }
     else if (e.Value is char)
     {
         Output.Write("'" + e.Value.ToString() + "'");
     }
     else if (e.Value is byte)
     {
         Output.Write(((byte)e.Value).ToString(CultureInfo.InvariantCulture));
     }
     else if (e.Value is short)
     {
         Output.Write(((short)e.Value).ToString(CultureInfo.InvariantCulture));
     }
     else if (e.Value is int)
     {
         Output.Write(((int)e.Value).ToString(CultureInfo.InvariantCulture));
     }
     else if (e.Value is long)
     {
         Output.Write(((long)e.Value).ToString(CultureInfo.InvariantCulture));
     }
     else if (e.Value is float)
     {
         GenerateSingleFloatValue((float)e.Value);
     }
     else if (e.Value is double)
     {
         GenerateDoubleValue((double)e.Value);
     }
     else if (e.Value is decimal)
     {
         GenerateDecimalValue((decimal)e.Value);
     }
     else if (e.Value is bool)
     {
         if ((bool)e.Value)
         {
             Output.Write("true");
         }
         else
         {
             Output.Write("false");
         }
     }
     else
     {
         throw new ArgumentException(SR.Format(SR.InvalidPrimitiveType, e.Value.GetType().ToString()));
     }
 }
Exemple #43
0
        void AddSubelementsOfSkippedElement(TableNode parentNode, string xpath)
        {
            if (parentNode.Table.Skipped)
            {
                TableNode pparentNode = (TableNode)parentNode.UserData["parentnode"];
                string    path        = xpath + '/' + parentNode.Name;
                AddSubelementsOfSkippedElement(pparentNode, path);
                return;
                //-------
            }

            CodeCompileUnit     cunit          = (CodeCompileUnit)parentNode.UserData["cunit"];
            CodeNamespace       ns             = cunit.Namespaces[0];
            CodeTypeDeclaration persClass      = ns.Types[0];
            CodeConstructor     xmlConstructor = null;
            CodeMemberMethod    xmlSaveMethod  = null;

            foreach (CodeTypeMember member in persClass.Members)
            {
                if (member.Name == ".ctor")
                {
                    CodeConstructor cc = (CodeConstructor)member;
                    if (cc.Parameters.Count > 0)
                    {
                        xmlConstructor = cc;
                    }
                }
                else if (member.Name == "Save")
                {
                    CodeMemberMethod cmm = (CodeMemberMethod)member;
                    if (cmm.Parameters.Count == 1 && cmm.Parameters[0].Type.BaseType == "XmlNode")
                    {
                        xmlSaveMethod = cmm;
                    }
                }
                if (xmlConstructor != null && xmlSaveMethod != null)
                {
                    break;
                }
            }

            /*
             *                      XmlElement subElement = parentNode.OwnerDocument.CreateElement("MyElement");
             *                      newElement.AppendChild(subElement);
             *                      newElement = subElement;
             */
            int    p           = xpath.LastIndexOf(':');
            string namespc     = this.namespaceWrapper[NamespaceWrapper.GetPrefixFromQualifiedName(xpath)];
            string elementName = NamespaceWrapper.GetXpathFromQualifiedName(xpath);

            CodePrimitiveExpression         myElementName = new CodePrimitiveExpression(elementName);
            CodePrimitiveExpression         myNamespace   = new CodePrimitiveExpression(namespc);
            CodeVariableReferenceExpression newElement    = new CodeVariableReferenceExpression("myElement");
            CodeVariableReferenceExpression subElement    = new CodeVariableReferenceExpression("subElement");
            CodeVariableReferenceExpression ownerDoc      = new CodeVariableReferenceExpression("parentNode.OwnerDocument");
            CodeMethodInvokeExpression      createElementCall;

            if (namespc != null)
            {
                createElementCall = new CodeMethodInvokeExpression(ownerDoc, "CreateElement", myElementName, myNamespace);
            }
            else
            {
                createElementCall = new CodeMethodInvokeExpression(ownerDoc, "CreateElement", myElementName);
            }
            CodeVariableDeclarationStatement newElementAssign = new CodeVariableDeclarationStatement(new CodeTypeReference("XmlElement"), "subElement", createElementCall);

            xmlSaveMethod.Statements.Add(newElementAssign);

            CodeMethodInvokeExpression appendChild = new CodeMethodInvokeExpression(newElement, "AppendChild", subElement);

            xmlSaveMethod.Statements.Add(appendChild);

            CodeAssignStatement backAssign = new CodeAssignStatement(newElement, subElement);

            xmlSaveMethod.Statements.Add(backAssign);

            /*
             * xmlNode = xmlNode.SelectSingleNode("xpath");
             */
            CodeVariableReferenceExpression xmlNode       = new CodeVariableReferenceExpression("xmlNode");
            CodePrimitiveExpression         xPathExpr     = new CodePrimitiveExpression(xpath);
            CodeVariableReferenceExpression nsManager     = new CodeVariableReferenceExpression("NamespaceManager");
            CodePropertyReferenceExpression nsInstance    = new CodePropertyReferenceExpression(nsManager, "Instance");
            CodeMethodInvokeExpression      selectNodes   = new CodeMethodInvokeExpression(xmlNode, "SelectSingleNode", xPathExpr, nsInstance);
            CodeAssignStatement             xmlNodeAssign = new CodeAssignStatement(xmlNode, selectNodes);

            xmlConstructor.Statements.Add(xmlNodeAssign);

            GenerateMembers(persClass, xmlConstructor, xmlSaveMethod);


            // xmlNode = xmlNode.ParentNode;
            CodePropertyReferenceExpression parentNodeProperty = new CodePropertyReferenceExpression(xmlNode, "ParentNode");

            xmlNodeAssign = new CodeAssignStatement(xmlNode, parentNodeProperty);
            xmlConstructor.Statements.Add(xmlNodeAssign);

            // newElement = (XmlElement) newElement.ParentNode;
            parentNodeProperty = new CodePropertyReferenceExpression(newElement, "ParentNode");
            CodeCastExpression xmlElementCast = new CodeCastExpression("XmlElement", parentNodeProperty);

            backAssign = new CodeAssignStatement(newElement, xmlElementCast);
            xmlSaveMethod.Statements.Add(backAssign);
        }
Exemple #44
0
        private static void GenerateProperties(Type t, CodeTypeDeclaration codeType)
        {
            foreach (PropertyInfo property in t.GetProperties())
            {
                if (OmittedProperties.ContainsKey(t.FullName) && OmittedProperties[t.FullName].Contains(property.Name))
                {
                    continue;
                }

                if (property.CustomAttributes.Any(x => x.AttributeType.FullName.Contains("Obsolete")))
                {
                    continue;
                }

                string propertyType        = GetPropertyType(property.PropertyType);
                bool   isGenericCollection = property.PropertyType.IsGenericType &&
                                             (property.PropertyType.GetGenericTypeDefinition() == typeof(IList <>) || property.PropertyType.GetGenericTypeDefinition() == typeof(IEnumerable <>) ||
                                              property.PropertyType.GetGenericTypeDefinition() == typeof(IReadOnlyList <>));

                CodeFieldReferenceExpression    wrappedObject         = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), OmObject);
                CodePropertyReferenceExpression wrappedObjectProperty = new CodePropertyReferenceExpression(wrappedObject, property.Name);
                CodeFieldReferenceExpression    fieldReference        = null;
                if (isGenericCollection || OMtoPSClassMappings.ContainsKey(property.PropertyType.FullName))
                {
                    // Add a backing field for the property with the same name but using camel case.
                    string          fieldName    = string.Format("{0}{1}", property.Name.ToLower()[0], property.Name.Substring(1, property.Name.Length - 1));
                    CodeMemberField backingField = new CodeMemberField();
                    backingField.Attributes = MemberAttributes.Private;
                    backingField.Name       = fieldName;
                    backingField.Type       = new CodeTypeReference(propertyType);
                    codeType.Members.Add(backingField);

                    fieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName);
                }

                CodeMemberProperty codeProperty = new CodeMemberProperty();
                codeProperty.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                codeProperty.Name       = property.Name;
                codeProperty.Type       = new CodeTypeReference(propertyType);

                // For properties with a backing field, the field will not be initialized in the constructor in order to avoid
                // hitting a run time access constraint from the OM. Instead, the field is initialized on the first access of
                // the property.

                if (isGenericCollection)
                {
                    // Collections are not kept in sync with the wrapped OM object. Cmdlets will need to sync them before sending
                    // a request to the server.
                    Type   argType         = property.PropertyType.GetGenericArguments()[0];
                    string wrapperArgType  = argType.FullName.StartsWith("System") ? argType.FullName : OMtoPSClassMappings[argType.FullName];
                    string wrapperListType = string.Format("List<{0}>", wrapperArgType);

                    if (property.GetMethod != null && property.GetMethod.IsPublic)
                    {
                        codeProperty.HasGet = true;
                        // Build a list of wrapper objects
                        const string listVariableName = "list";
                        CodeVariableDeclarationStatement listDeclaration = new CodeVariableDeclarationStatement(wrapperListType, listVariableName);
                        CodeVariableReferenceExpression  listReference   = new CodeVariableReferenceExpression(listVariableName);
                        CodeAssignStatement initializeList = new CodeAssignStatement(listReference, new CodeObjectCreateExpression(wrapperListType));

                        // CodeDom doesn't support foreach loops very well, so instead explicitly get the enumerator and loop on MoveNext() calls
                        const string enumeratorVariableName = "enumerator";
                        CodeVariableDeclarationStatement enumeratorDeclaration = new CodeVariableDeclarationStatement(string.Format("IEnumerator<{0}>", argType.FullName), enumeratorVariableName);
                        CodeVariableReferenceExpression  enumeratorReference   = new CodeVariableReferenceExpression(enumeratorVariableName);
                        CodeAssignStatement    initializeEnumerator            = new CodeAssignStatement(enumeratorReference, new CodeMethodInvokeExpression(wrappedObjectProperty, "GetEnumerator"));
                        CodeIterationStatement loopStatement = new CodeIterationStatement();
                        loopStatement.TestExpression     = new CodeMethodInvokeExpression(enumeratorReference, "MoveNext");
                        loopStatement.IncrementStatement = new CodeSnippetStatement(string.Empty);
                        loopStatement.InitStatement      = new CodeSnippetStatement(string.Empty);
                        CodePropertyReferenceExpression enumeratorCurrent = new CodePropertyReferenceExpression(enumeratorReference, "Current");

                        // Fill the list by individually wrapping each item in the loop
                        if (wrapperArgType.Contains("System"))
                        {
                            CodeMethodInvokeExpression addToList = new CodeMethodInvokeExpression(listReference, "Add", enumeratorCurrent);
                            loopStatement.Statements.Add(addToList);
                        }
                        else
                        {
                            CodeObjectCreateExpression createListItem = new CodeObjectCreateExpression(wrapperArgType, enumeratorCurrent);
                            CodeMethodInvokeExpression addToList      = new CodeMethodInvokeExpression(listReference, "Add", createListItem);
                            loopStatement.Statements.Add(addToList);
                        }

                        // Initialize the backing field with the built list on first access of the property
                        CodeAssignStatement assignStatement;
                        if (property.PropertyType.GetGenericTypeDefinition() == typeof(IReadOnlyList <>))
                        {
                            CodeMethodInvokeExpression asReadOnlyList = new CodeMethodInvokeExpression(listReference, "AsReadOnly");
                            assignStatement = new CodeAssignStatement(fieldReference, asReadOnlyList);
                        }
                        else
                        {
                            assignStatement = new CodeAssignStatement(fieldReference, listReference);
                        }
                        CodePrimitiveExpression      nullExpression           = new CodePrimitiveExpression(null);
                        CodeBinaryOperatorExpression fieldNullCheck           = new CodeBinaryOperatorExpression(fieldReference, CodeBinaryOperatorType.IdentityEquality, nullExpression);
                        CodeBinaryOperatorExpression wrappedPropertyNullCheck = new CodeBinaryOperatorExpression(wrappedObjectProperty, CodeBinaryOperatorType.IdentityInequality, nullExpression);
                        CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(fieldNullCheck, CodeBinaryOperatorType.BooleanAnd, wrappedPropertyNullCheck);
                        CodeConditionStatement       ifBlock   = new CodeConditionStatement(condition, listDeclaration, initializeList, enumeratorDeclaration, initializeEnumerator, loopStatement, assignStatement);
                        codeProperty.GetStatements.Add(ifBlock);
                        codeProperty.GetStatements.Add(new CodeMethodReturnStatement(fieldReference));
                    }
                    if (property.SetMethod != null && property.SetMethod.IsPublic)
                    {
                        // Call the "set" on the OM object to ensure that constraints are enforced.
                        codeProperty.HasSet = true;
                        CodePropertySetValueReferenceExpression valueReference = new CodePropertySetValueReferenceExpression();
                        CodeBinaryOperatorExpression            nullCheck      = new CodeBinaryOperatorExpression(valueReference, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null));
                        CodeAssignStatement    nullAssignment    = new CodeAssignStatement(wrappedObjectProperty, new CodePrimitiveExpression(null));
                        CodeAssignStatement    nonNullAssignment = new CodeAssignStatement(wrappedObjectProperty, new CodeObjectCreateExpression(string.Format("List<{0}>", argType.FullName)));
                        CodeConditionStatement ifBlock           = new CodeConditionStatement(nullCheck, new CodeStatement[] { nullAssignment }, new CodeStatement[] { nonNullAssignment });
                        codeProperty.SetStatements.Add(ifBlock);
                        codeProperty.SetStatements.Add(new CodeAssignStatement(fieldReference, valueReference));
                    }
                }
                else if (OMtoPSClassMappings.ContainsKey(property.PropertyType.FullName))
                {
                    if (property.GetMethod != null && property.GetMethod.IsPublic)
                    {
                        codeProperty.HasGet = true;
                        CodeObjectCreateExpression   createFieldObject        = new CodeObjectCreateExpression(OMtoPSClassMappings[property.PropertyType.FullName], wrappedObjectProperty);
                        CodeAssignStatement          assignStatement          = new CodeAssignStatement(fieldReference, createFieldObject);
                        CodePrimitiveExpression      nullExpression           = new CodePrimitiveExpression(null);
                        CodeBinaryOperatorExpression fieldNullCheck           = new CodeBinaryOperatorExpression(fieldReference, CodeBinaryOperatorType.IdentityEquality, nullExpression);
                        CodeBinaryOperatorExpression wrappedPropertyNullCheck = new CodeBinaryOperatorExpression(wrappedObjectProperty, CodeBinaryOperatorType.IdentityInequality, nullExpression);
                        CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(fieldNullCheck, CodeBinaryOperatorType.BooleanAnd, wrappedPropertyNullCheck);
                        CodeConditionStatement       ifBlock   = new CodeConditionStatement(condition, assignStatement);
                        codeProperty.GetStatements.Add(ifBlock);
                        codeProperty.GetStatements.Add(new CodeMethodReturnStatement(fieldReference));
                    }
                    if (property.SetMethod != null && property.SetMethod.IsPublic)
                    {
                        codeProperty.HasSet = true;
                        CodePropertySetValueReferenceExpression valueReference = new CodePropertySetValueReferenceExpression();
                        CodeBinaryOperatorExpression            nullCheck      = new CodeBinaryOperatorExpression(valueReference, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null));
                        CodeAssignStatement             nullAssignment         = new CodeAssignStatement(wrappedObjectProperty, new CodePrimitiveExpression(null));
                        CodePropertyReferenceExpression valueProperty          = new CodePropertyReferenceExpression(valueReference, OmObject);
                        CodeAssignStatement             nonNullAssignment      = new CodeAssignStatement(wrappedObjectProperty, valueProperty);
                        CodeConditionStatement          ifBlock = new CodeConditionStatement(nullCheck, new CodeStatement[] { nullAssignment }, new CodeStatement[] { nonNullAssignment });
                        codeProperty.SetStatements.Add(ifBlock);
                        codeProperty.SetStatements.Add(new CodeAssignStatement(fieldReference, valueReference));
                    }
                }
                else
                {
                    // By default, just pass through to the wrapped OM object's property.
                    if (property.GetMethod != null && property.GetMethod.IsPublic)
                    {
                        codeProperty.HasGet = true;
                        codeProperty.GetStatements.Add(new CodeMethodReturnStatement(wrappedObjectProperty));
                    }
                    if (property.SetMethod != null && property.SetMethod.IsPublic)
                    {
                        codeProperty.HasSet = true;
                        codeProperty.SetStatements.Add(new CodeAssignStatement(wrappedObjectProperty, new CodePropertySetValueReferenceExpression()));
                    }
                }
                codeType.Members.Add(codeProperty);
            }
        }
Exemple #45
0
 private 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()))
     {
         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 (obsolete)
     {
         if (obsoleteMessageBuilder.Length > 0)
         {
             obsoleteMessageBuilder.Remove(obsoleteMessageBuilder.Length - 1, 1);
         }
         CodeSnippetTypeMember snippet = cmp as CodeSnippetTypeMember;
         if (snippet != null)
         {
             const string template = "        [System.ObsoleteAttribute(\"{0}\")]{1}";
             snippet.Text = snippet.Text.Insert(0, string.Format(template, obsoleteMessageBuilder, Environment.NewLine));
         }
         else
         {
             CodeTypeReference obsoleteAttribute = new CodeTypeReference(typeof(ObsoleteAttribute));
             CodePrimitiveExpression obsoleteMessage = new CodePrimitiveExpression(obsoleteMessageBuilder.ToString());
             cmp.CustomAttributes.Add(new CodeAttributeDeclaration(obsoleteAttribute, new CodeAttributeArgument(obsoleteMessage)));
         }
     }
 }