public void Constructor0_Deny_Unrestricted ()
		{
			CodeTryCatchFinallyStatement ctcfs = new CodeTryCatchFinallyStatement ();
			Assert.AreEqual (0, ctcfs.CatchClauses.Count, "CatchClauses");
			Assert.AreEqual (0, ctcfs.FinallyStatements.Count, "FinallyStatements");
			Assert.AreEqual (0, ctcfs.TryStatements.Count, "TryStatements");
		}
        // Generate a codedom exception handler statement
        public static CodeStatement Emit(ExceptionHandler ex)
        {
            // Create the codedom exception handler statement
            var codeTry = new CodeTryCatchFinallyStatement();

            // Add the statements in the try block
            foreach (var e in ex.Try.ChildExpressions)
                codeTry.TryStatements.Add(CodeDomEmitter.EmitCodeStatement(e));

            // Add all the catch clauses.
            foreach (var c in ex.CatchClauses)
            {
                // Create the codedom catch statement.
                var catchClause = new CodeCatchClause();
                // To do: replace with non-test code
                catchClause.CatchExceptionType = new CodeTypeReference("System.Exception");
                catchClause.LocalName = "ex";
                codeTry.CatchClauses.Add(catchClause);

                // Add the statemnts in the catch block
                foreach(var e in c.ChildExpressions)
                    catchClause.Statements.Add(CodeDomEmitter.EmitCodeStatement(e));
            }

            // Add the statements in the finally block.
            foreach (var e in ex.Finally.ChildExpressions)
                codeTry.FinallyStatements.Add(CodeDomEmitter.EmitCodeStatement(e));

            return codeTry;
        }
		public void Constructor1_Deny_Unrestricted ()
		{
			CodeStatement[] try_statements = new CodeStatement[1] { new CodeStatement () };
			CodeCatchClause[] catch_clauses = new CodeCatchClause[1] { new CodeCatchClause () };
			CodeTryCatchFinallyStatement ctcfs = new CodeTryCatchFinallyStatement (try_statements, catch_clauses);
			Assert.AreEqual (1, ctcfs.CatchClauses.Count, "CatchClauses");
			Assert.AreEqual (0, ctcfs.FinallyStatements.Count, "FinallyStatements");
			Assert.AreEqual (1, ctcfs.TryStatements.Count, "TryStatements");
		}
 public TypescriptTryCatchFinallyStatement(
     IStatementFactory statementFactory,
     IExpressionFactory expressionFactory,
     CodeTryCatchFinallyStatement statement,
     CodeGeneratorOptions options)
 {
     _statementFactory = statementFactory;
     _expressionFactory = expressionFactory;
     _statement = statement;
     _options = options;
     _typescriptTypeMapper = new TypescriptTypeMapper();
 }
 public static CodeTryCatchFinallyStatement Clone(this CodeTryCatchFinallyStatement statement)
 {
     if (statement == null) return null;
     CodeTryCatchFinallyStatement s = new CodeTryCatchFinallyStatement();
     s.CatchClauses.AddRange(statement.CatchClauses.Clone());
     s.EndDirectives.AddRange(statement.EndDirectives);
     s.FinallyStatements.AddRange(statement.FinallyStatements.Clone());
     s.LinePragma = statement.LinePragma;
     s.StartDirectives.AddRange(statement.StartDirectives);
     s.TryStatements.AddRange(statement.TryStatements.Clone());
     s.UserData.AddRange(statement.UserData);
     return s;
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="member"></param>
        /// <param name="inner"></param>
        /// <param name="attrs"></param>
        /// <returns></returns>
        public CodeTypeMember CreateMember(MemberInfo member, CodeFieldReferenceExpression inner, MemberAttributes attrs)
        {
            Debug.Assert(member is MethodInfo);
            MethodInfo method = member as MethodInfo;
            CodeMemberMethod codeMethod = new CodeMemberMethod();

            codeMethod.Name = method.Name;
            codeMethod.ReturnType = new CodeTypeReference(method.ReturnType);
            codeMethod.Attributes = attrs;

            // try
            CodeTryCatchFinallyStatement tryCode = new CodeTryCatchFinallyStatement();

            // decleare parameters
            List<CodeArgumentReferenceExpression> codeParamiteRefrs = new List<CodeArgumentReferenceExpression>();

            foreach (ParameterInfo codeParameter in method.GetParameters()) {
                CodeParameterDeclarationExpression codeParameterDeclare = new CodeParameterDeclarationExpression(codeParameter.ParameterType, codeParameter.Name);
                codeMethod.Parameters.Add(codeParameterDeclare);
                codeParamiteRefrs.Add(new CodeArgumentReferenceExpression(codeParameter.Name));
            }

            // invoke
            CodeMethodInvokeExpression invokeMethod = new CodeMethodInvokeExpression(
                inner, method.Name, codeParamiteRefrs.ToArray());
            if (method.ReturnType.Name.ToLower() == "void") {
                tryCode.TryStatements.Add(invokeMethod);
            } else {
                CodeVariableDeclarationStatement var = new CodeVariableDeclarationStatement(method.ReturnType, "returnObject", invokeMethod);
                //CodeAssignStatement assign = new CodeAssignStatement(var, invokeMethod);
                tryCode.TryStatements.Add(var);

                CodeCommentStatement todo = new CodeCommentStatement("TODO: your code", false);
                tryCode.TryStatements.Add(todo);

                CodeVariableReferenceExpression varRef = new CodeVariableReferenceExpression("returnObject");
                CodeMethodReturnStatement codeReturn = new CodeMethodReturnStatement(varRef);
                tryCode.TryStatements.Add(codeReturn);
            }

            // catch
            CodeTypeReference codeTypeRef = new CodeTypeReference(typeof(Exception));
            CodeCatchClause catchClause = new CodeCatchClause("ex", codeTypeRef);
            catchClause.Statements.Add(new CodeThrowExceptionStatement());
            tryCode.CatchClauses.Add(catchClause);

            codeMethod.Statements.Add(tryCode);
            return codeMethod;
        }
        public override object VisitUsingStatement(UsingStatement usingStatement, object data)
        {
            // using (new expr) { stmts; }
            //
            // emulate with
            //      object _dispose;
            //      try
            //      {
            //          _dispose = new expr;
            //
            //          stmts;
            //      }
            //      finally
            //      {
            //          if (((_dispose != null)
            //              && (typeof(System.IDisposable).IsInstanceOfType(_dispose) == true)))
            //          {
            //              ((System.IDisposable)(_dispose)).Dispose();
            //          }
            //      }
            //

            usingId++; // in case nested using() statements
            string name = "_dispose" + usingId.ToString();

            CodeVariableDeclarationStatement disposable = new CodeVariableDeclarationStatement("System.Object", name, new CodePrimitiveExpression(null));

            AddStmt(disposable);

            CodeTryCatchFinallyStatement tryStmt = new CodeTryCatchFinallyStatement();

            CodeVariableReferenceExpression left1 = new CodeVariableReferenceExpression(name);

            codeStack.Push(NullStmtCollection); // send statements to nul Statement collection
            CodeExpression right1 = (CodeExpression)usingStatement.ResourceAcquisition.AcceptVisitor(this, data);
            codeStack.Pop();

            CodeAssignStatement assign1 = new CodeAssignStatement(left1, right1);

            tryStmt.TryStatements.Add(assign1);
            tryStmt.TryStatements.Add(new CodeSnippetStatement());

            codeStack.Push(tryStmt.TryStatements);
            usingStatement.EmbeddedStatement.AcceptChildren(this, data);
            codeStack.Pop();

            CodeMethodInvokeExpression isInstanceOfType = new CodeMethodInvokeExpression(new CodeTypeOfExpression(typeof(IDisposable)), "IsInstanceOfType", new CodeExpression[] { left1 });

            CodeConditionStatement if1 = new CodeConditionStatement();
            if1.Condition = new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(left1, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)),
                                                             CodeBinaryOperatorType.BooleanAnd,
                                                             new CodeBinaryOperatorExpression(isInstanceOfType, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(true)));
            if1.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeCastExpression(typeof(IDisposable),left1), "Dispose", new CodeExpression[] { }));

            tryStmt.FinallyStatements.Add(if1);

            // Add Statement to Current Statement Collection
            AddStmt(tryStmt);

            return null;
        }
Esempio n. 8
0
		protected override void GenerateTryCatchFinallyStatement (CodeTryCatchFinallyStatement e)
		{
		}
Esempio n. 9
0
		protected override void GenerateTryCatchFinallyStatement (CodeTryCatchFinallyStatement statement)
		{
			TextWriter output = Output;

			output.WriteLine ("Try ");
			++Indent;
			GenerateStatements (statement.TryStatements);
			--Indent;
			
			foreach (CodeCatchClause clause in statement.CatchClauses) {
				output.Write ("Catch ");
				OutputTypeNamePair (clause.CatchExceptionType, clause.LocalName);
				output.WriteLine ();
				++Indent;
				GenerateStatements (clause.Statements);
				--Indent;
			}

			CodeStatementCollection finallies = statement.FinallyStatements;
			if (finallies.Count > 0) {
				output.WriteLine ("Finally");
				++Indent;
				GenerateStatements (finallies);
				--Indent;
			}

			output.WriteLine("End Try");
		}
Esempio n. 10
0
			public void Visit (CodeTryCatchFinallyStatement o)
			{
				g.GenerateTryCatchFinallyStatement (o);
			}
		public override void BuildCodeDomTree (CodeCompileUnit compileUnit)
		{
         
			CodeThisReferenceExpression @this = new CodeThisReferenceExpression ();
			CodeBaseReferenceExpression @base = new CodeBaseReferenceExpression ();
			CodeTypeReferenceExpression thisType = new CodeTypeReferenceExpression (new CodeTypeReference (GeneratedTypeName));
			CodeTypeReference uriType = new CodeTypeReference (typeof(Uri));

			CodeMemberField executableField = new CodeMemberField {
            Name = "_Executable",
            Type = new CodeTypeReference(typeof(XsltExecutable)),
            Attributes = MemberAttributes.Private | MemberAttributes.Static
         };

			// methods

			// cctor
			CodeTypeConstructor cctor = new CodeTypeConstructor {
            CustomAttributes = { 
               new CodeAttributeDeclaration(DebuggerNonUserCodeTypeReference)
            }
         };

			CodeVariableDeclarationStatement procVar = new CodeVariableDeclarationStatement {
            Name = "proc",
            Type = new CodeTypeReference(typeof(IXsltProcessor)),
            InitExpression = new CodeIndexerExpression {
               TargetObject = new CodePropertyReferenceExpression {
                  PropertyName = "Xslt",
                  TargetObject = new CodeTypeReferenceExpression(typeof(Processors))
               },
               Indices = { 
                  new CodePrimitiveExpression(parser.ProcessorName)
               }
            } 
         };

			CodeVariableDeclarationStatement sourceVar = new CodeVariableDeclarationStatement {
            Name = "source",
            Type = new CodeTypeReference(typeof(Stream)),
            InitExpression = new CodePrimitiveExpression(null)
         };

			CodeVariableDeclarationStatement sourceUriVar = new CodeVariableDeclarationStatement {
            Name = "sourceUri",
            Type = uriType,
            InitExpression = new CodeObjectCreateExpression {
               CreateType = uriType,
               Parameters = {
                  new CodePrimitiveExpression(ValidatorUri.AbsoluteUri)
               }
            }
         };

			CodeVariableDeclarationStatement resolverVar = new CodeVariableDeclarationStatement {
            Name = "resolver",
            Type = new CodeTypeReference(typeof(XmlResolver)),
            InitExpression = new CodeObjectCreateExpression(typeof(XmlEmbeddedResourceResolver))
         };

			CodeTryCatchFinallyStatement trySt = new CodeTryCatchFinallyStatement { 
            TryStatements = {
               new CodeAssignStatement {
                  Left = new CodeVariableReferenceExpression(sourceVar.Name),
                  Right = new CodeCastExpression {
                     TargetType = new CodeTypeReference(typeof(Stream)),
                     Expression = new CodeMethodInvokeExpression {
                        Method = new CodeMethodReferenceExpression {
                           MethodName = "GetEntity",
                           TargetObject = new CodeVariableReferenceExpression(resolverVar.Name)
                        },
                        Parameters = {
                           new CodeVariableReferenceExpression(sourceUriVar.Name),
                           new CodePrimitiveExpression(null),
                           new CodeTypeOfExpression(typeof(Stream))
                        }
                     }
                  }
               }
            }
         };

			CodeVariableDeclarationStatement optionsVar = new CodeVariableDeclarationStatement {
            Name = "options",
            Type = new CodeTypeReference(typeof(XsltCompileOptions)),
         };
			optionsVar.InitExpression = new CodeObjectCreateExpression (optionsVar.Type);

			trySt.TryStatements.Add (optionsVar);
			trySt.TryStatements.Add (new CodeAssignStatement {
            Left = new CodePropertyReferenceExpression {
               PropertyName = "BaseUri",
               TargetObject = new CodeVariableReferenceExpression(optionsVar.Name)
            },
            Right = new CodeVariableReferenceExpression(sourceUriVar.Name)
         });
			trySt.TryStatements.Add (new CodeAssignStatement {
            Left = new CodeFieldReferenceExpression {
               FieldName = executableField.Name,
               TargetObject = thisType
            },
            Right = new CodeMethodInvokeExpression(
               new CodeMethodReferenceExpression {
                  MethodName = "Compile",
                  TargetObject = new CodeVariableReferenceExpression(procVar.Name)
               },
               new CodeVariableReferenceExpression(sourceVar.Name),
               new CodeVariableReferenceExpression(optionsVar.Name)
            )
         });

			CodeConditionStatement disposeIf = new CodeConditionStatement {
            Condition = new CodeBinaryOperatorExpression {
               Left = new CodeVariableReferenceExpression(sourceVar.Name),
               Operator = CodeBinaryOperatorType.IdentityInequality,
               Right = new CodePrimitiveExpression(null)
            },
            TrueStatements = {
               new CodeMethodInvokeExpression {
                  Method = new CodeMethodReferenceExpression {
                     MethodName = "Dispose",
                     TargetObject = new CodeVariableReferenceExpression(sourceVar.Name)
                  }
               }
            }
         };

			trySt.FinallyStatements.Add (disposeIf);

			cctor.Statements.AddRange (new CodeStatement[] {
                procVar,
                sourceVar,
                sourceUriVar,
                resolverVar,
                trySt
            });

			// ctor
			CodeConstructor ctor = new CodeConstructor {
            Attributes = MemberAttributes.Public,
            CustomAttributes = { 
               new CodeAttributeDeclaration(DebuggerNonUserCodeTypeReference)
            },
            BaseConstructorArgs = { 
               new CodeFieldReferenceExpression {
                  FieldName = executableField.Name,
                  TargetObject = thisType
               }
            }
         };

			// class
			CodeTypeDeclaration codeType = new CodeTypeDeclaration {
            Name = GeneratedTypeName,
            IsClass = true,
            BaseTypes = { typeof(SchematronXsltValidator) },
            Members = { cctor, ctor, executableField }
         };

			CodeNamespace codeNamespace = new CodeNamespace {
            Name = GeneratedTypeNamespace,
            Types = { codeType }
         };

			compileUnit.Namespaces.Add (codeNamespace);
		}
Esempio n. 12
0
        /// <include file='doc\CSharpCodeProvider.uex' path='docs/doc[@for="CSharpCodeGenerator.GenerateTryCatchFinallyStatement"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Generates code for the specified CodeDom based try catch finally
        ///       statement representation.
        ///    </para>
        /// </devdoc>
        protected override void GenerateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e) {
            Output.Write("try");
            OutputStartingBrace();
            Indent++;
            GenerateStatements(e.TryStatements);
            Indent--;
            CodeCatchClauseCollection catches = e.CatchClauses;
            if (catches.Count > 0) {
                IEnumerator en = catches.GetEnumerator();
                while (en.MoveNext()) {
                    Output.Write("}");
                    if (Options.ElseOnClosing) {
                        Output.Write(" ");
                    } 
                    else {
                        Output.WriteLine("");
                    }
                    CodeCatchClause current = (CodeCatchClause)en.Current;
                    Output.Write("catch (");
                    OutputType(current.CatchExceptionType);
                    Output.Write(" ");
                    OutputIdentifier(current.LocalName);
                    Output.Write(")");
                    OutputStartingBrace();
                    Indent++;
                    GenerateStatements(current.Statements);
                    Indent--;
                }
            }

            CodeStatementCollection finallyStatements = e.FinallyStatements;
            if (finallyStatements.Count > 0) {
                Output.Write("}");
                if (Options.ElseOnClosing) {
                    Output.Write(" ");
                } 
                else {
                    Output.WriteLine("");
                }
                Output.Write("finally");
                OutputStartingBrace();
                Indent++;
                GenerateStatements(finallyStatements);
                Indent--;
            }
            Output.WriteLine("}");
        }
Esempio n. 13
0
		void VisitCodeTryCatchFinallyStatement(CodeTryCatchFinallyStatement tryStatement)
		{
			WriteLine("VisitCodeTryCatchFinallyStatement");
			using (IDisposable currentLevel = Indentation.IncrementLevel()) {
				WriteLine("Try statements follow: Count: " + tryStatement.TryStatements.Count);
				foreach (CodeStatement statement in tryStatement.TryStatements) {
					VisitCodeStatement(statement);
				}
				
				WriteLine("Catch clauses follow: Count: " + tryStatement.CatchClauses.Count);
				foreach (CodeCatchClause catchClause in tryStatement.CatchClauses) {
					VisitCodeCatchClause(catchClause);
				}				
				
				WriteLine("Finally statements follow: Count: " + tryStatement.FinallyStatements);
				foreach (CodeStatement statement in tryStatement.FinallyStatements) {
					VisitCodeStatement(statement);
				}				
			}
		}
 private void WriteHookupMethods(CodeTypeDeclaration cls)
 {
     if (this.axctlEventsType != null)
     {
         CodeMemberMethod method = new CodeMemberMethod {
             Name = "CreateSink",
             Attributes = MemberAttributes.Family | MemberAttributes.Override
         };
         CodeObjectCreateExpression expression = new CodeObjectCreateExpression(this.axctl + "EventMulticaster", new CodeExpression[0]);
         expression.Parameters.Add(new CodeThisReferenceExpression());
         CodeAssignStatement statement = new CodeAssignStatement(this.multicasterRef, expression);
         CodeObjectCreateExpression expression2 = new CodeObjectCreateExpression(typeof(AxHost.ConnectionPointCookie).FullName, new CodeExpression[0]);
         expression2.Parameters.Add(this.memIfaceRef);
         expression2.Parameters.Add(this.multicasterRef);
         expression2.Parameters.Add(new CodeTypeOfExpression(this.axctlEvents));
         CodeAssignStatement statement2 = new CodeAssignStatement(this.cookieRef, expression2);
         CodeTryCatchFinallyStatement statement3 = new CodeTryCatchFinallyStatement();
         statement3.TryStatements.Add(statement);
         statement3.TryStatements.Add(statement2);
         statement3.CatchClauses.Add(new CodeCatchClause("", new CodeTypeReference(typeof(Exception))));
         method.Statements.Add(statement3);
         cls.Members.Add(method);
         CodeMemberMethod method2 = new CodeMemberMethod {
             Name = "DetachSink",
             Attributes = MemberAttributes.Family | MemberAttributes.Override
         };
         CodeFieldReferenceExpression targetObject = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), this.cookie);
         CodeMethodInvokeExpression expression4 = new CodeMethodInvokeExpression(targetObject, "Disconnect", new CodeExpression[0]);
         statement3 = new CodeTryCatchFinallyStatement();
         statement3.TryStatements.Add(expression4);
         statement3.CatchClauses.Add(new CodeCatchClause("", new CodeTypeReference(typeof(Exception))));
         method2.Statements.Add(statement3);
         cls.Members.Add(method2);
     }
     CodeMemberMethod method3 = new CodeMemberMethod {
         Name = "AttachInterfaces",
         Attributes = MemberAttributes.Family | MemberAttributes.Override
     };
     CodeCastExpression right = new CodeCastExpression(this.axctlType.FullName, new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "GetOcx", new CodeExpression[0]));
     CodeAssignStatement statement4 = new CodeAssignStatement(this.memIfaceRef, right);
     CodeTryCatchFinallyStatement statement5 = new CodeTryCatchFinallyStatement();
     statement5.TryStatements.Add(statement4);
     statement5.CatchClauses.Add(new CodeCatchClause("", new CodeTypeReference(typeof(Exception))));
     method3.Statements.Add(statement5);
     cls.Members.Add(method3);
 }
Esempio n. 15
0
 protected override void GenerateTryCatchFinallyStatement(System.CodeDom.CodeTryCatchFinallyStatement e)
 {
     throw new Exception("The method or operation is not implemented.");
 }
Esempio n. 16
0
        /// <summary>
        /// Generated code for function to do conversion of date from DMTF format to DateTime format
        /// </summary>
        void AddToDateTimeFunction()
        {
            String dmtfParam = "dmtfDate";
            String year    = "year";
            String month = "month";
            String day = "day";
            String hour = "hour";
            String minute = "minute";
            String second = "second";
            String ticks = "ticks";
            String dmtf = "dmtf";
            String tempStr = "tempString";
            String datetimeVariable = "datetime";

            CodeCastExpression cast = null;

            CodeMemberMethod cmmdt = new CodeMemberMethod();
            cmmdt.Name = PrivateNamesUsed["ToDateTimeMethod"].ToString();
            cmmdt.Attributes = MemberAttributes.Final | MemberAttributes.Static;
            cmmdt.ReturnType = new CodeTypeReference("System.DateTime");
            cmmdt.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.String"),dmtfParam));
            cmmdt.Comments.Add(new CodeCommentStatement(GetString("COMMENT_TODATETIME")));

            // create a local variable to initialize from - fixed warnings in MCPP which doesn't
            // like you copying sub items (like year) out of MinValue
            cmmdt.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.DateTime"),"initializer",new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.DateTime"),"MinValue")));
            CodeVariableReferenceExpression cvreInitializer = new CodeVariableReferenceExpression("initializer");
            //Int32 year = initializer.Year;
            cmmdt.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.Int32"),year,new CodePropertyReferenceExpression(cvreInitializer,"Year")));

            //Int32 month = initializer.Month;
            cmmdt.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.Int32"),month,    new CodePropertyReferenceExpression(cvreInitializer,"Month")));

            //Int32 day = initializer.Day;
            cmmdt.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.Int32"),day,new CodePropertyReferenceExpression(cvreInitializer,"Day")));
        
            //Int32 hour = initializer.Hour;
            cmmdt.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.Int32"),hour,new CodePropertyReferenceExpression(cvreInitializer,"Hour")));

            //Int32 minute = Sinitializer.Minute;
            cmmdt.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.Int32"),minute,new CodePropertyReferenceExpression(cvreInitializer,"Minute")));

            //Int32 second = initializer.Second;
            cmmdt.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.Int32"),second,new CodePropertyReferenceExpression(cvreInitializer,"Second")));
            
            //Int32 millisec = 0;
            cmmdt.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.Int64"),ticks,new CodePrimitiveExpression(0)));

            //String dmtf = dmtfDate ;
            cmmdt.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.String"),dmtf,new CodeVariableReferenceExpression(dmtfParam)));
            
            //System.DateTime datetime = System.DateTime.MinValue ;
            CodeFieldReferenceExpression cpreMinVal = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.DateTime"),"MinValue");
            cmmdt.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.DateTime"),datetimeVariable,cpreMinVal));

            //String tempString = String.Empty ;
            cmmdt.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.String"),tempStr,new CodeFieldReferenceExpression(
                new CodeTypeReferenceExpression("System.String"),"Empty")));

            /*
                if (dmtf == null)
                {
                    throw new System.ArgumentOutOfRangeException();
                }
            */

            CodeBinaryOperatorExpression cboe = new CodeBinaryOperatorExpression();
            cboe.Left = new CodeVariableReferenceExpression(dmtf);
            cboe.Right = new CodePrimitiveExpression(null);
            cboe.Operator = CodeBinaryOperatorType.IdentityEquality;

            CodeConditionStatement cis = new CodeConditionStatement();
            cis.Condition = cboe;

            CodeObjectCreateExpression codeThrowException = new CodeObjectCreateExpression();
            codeThrowException.CreateType = new CodeTypeReference(PublicNamesUsed["ArgumentOutOfRangeException"].ToString());
            cis.TrueStatements.Add(new CodeThrowExceptionStatement(codeThrowException));

            cmmdt.Statements.Add(cis);

            /*      
                if (dmtf.Length == 0)
                {
                    throw new System.ArgumentOutOfRangeException();
                }
            */

            cboe = new CodeBinaryOperatorExpression();
            cboe.Left = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression(dmtf),"Length");
            cboe.Right = new CodePrimitiveExpression(0);
            cboe.Operator = CodeBinaryOperatorType.ValueEquality;

            cis = new CodeConditionStatement();
            cis.Condition = cboe;

            cis.TrueStatements.Add(new CodeThrowExceptionStatement(codeThrowException));

            cmmdt.Statements.Add(cis);

            /*
                if (str.Length != DMTF_DATETIME_STR_LENGTH )
                {
                    throw new System.ArgumentOutOfRangeException();
                }
            */
            cboe = new CodeBinaryOperatorExpression();
            cboe.Left = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression(dmtf),"Length");
            cboe.Right = new CodePrimitiveExpression(DMTF_DATETIME_STR_LENGTH);
            cboe.Operator = CodeBinaryOperatorType.IdentityInequality;

            cis = new CodeConditionStatement();
            cis.Condition = cboe;
            cis.TrueStatements.Add(new CodeThrowExceptionStatement(codeThrowException));

            cmmdt.Statements.Add(cis);

            CodeTryCatchFinallyStatement tryblock = new CodeTryCatchFinallyStatement();
            DateTimeConversionFunctionHelper(tryblock.TryStatements,"****",tempStr,dmtf,year,0,4);
            DateTimeConversionFunctionHelper(tryblock.TryStatements,"**",tempStr,dmtf,month,4,2);
            DateTimeConversionFunctionHelper(tryblock.TryStatements,"**",tempStr,dmtf,day,6,2);
            DateTimeConversionFunctionHelper(tryblock.TryStatements,"**",tempStr,dmtf,hour,8,2);
            DateTimeConversionFunctionHelper(tryblock.TryStatements,"**",tempStr,dmtf,minute,10,2);
            DateTimeConversionFunctionHelper(tryblock.TryStatements,"**",tempStr,dmtf,second,12,2);

            /*
                tempString = dmtf.Substring(15, 6);
                if (("******" != tempString)) 
                {
                    ticks = (System.Int64.Parse(tempString)) * (System.TimeSpan.TicksPerMillisecond/1000);
                }
            */

            CodeMethodReferenceExpression  cmre = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(dmtf),"Substring");
            CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression();
            cmie.Method = cmre;
            cmie.Parameters.Add(new CodePrimitiveExpression(15));
            cmie.Parameters.Add(new CodePrimitiveExpression(6));
            tryblock.TryStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(tempStr), cmie));


            cboe = new CodeBinaryOperatorExpression();
            cboe.Left = new CodePrimitiveExpression("******");
            cboe.Right = new CodeVariableReferenceExpression(tempStr);
            cboe.Operator = CodeBinaryOperatorType.IdentityInequality;
            cis = new CodeConditionStatement();
            cis.Condition = cboe;

            CodeMethodReferenceExpression  cmre1 = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression("System.Int64"),"Parse");
            CodeMethodInvokeExpression cmie1 = new CodeMethodInvokeExpression();
            cmie1.Method = cmre1;
            cmie1.Parameters.Add(new CodeVariableReferenceExpression(tempStr));

            cboe = new CodeBinaryOperatorExpression();
            cboe.Left = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.TimeSpan"),"TicksPerMillisecond");
            cboe.Right = new CodePrimitiveExpression(1000);
            cboe.Operator = CodeBinaryOperatorType.Divide;
            cast = new CodeCastExpression("System.Int64", cboe);

            CodeBinaryOperatorExpression cboe2 = new CodeBinaryOperatorExpression();
            cboe2.Left = cmie1;
            cboe2.Right = cast;
            cboe2.Operator = CodeBinaryOperatorType.Multiply;

            cis.TrueStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(ticks),cboe2));
            
            tryblock.TryStatements.Add(cis);

            /*
                if( year < 0 || month < 0 || day < 0 || hour < 0 || minute < 0 || second < 0 || ticks < 0)
                {
                    throw new System.ArgumentOutOfRangeException();
                }
            */

            CodeBinaryOperatorExpression cboeYear = new CodeBinaryOperatorExpression();
            cboeYear.Left = new CodeVariableReferenceExpression(year);
            cboeYear.Right = new CodePrimitiveExpression(0);
            cboeYear.Operator = CodeBinaryOperatorType.LessThan;


            CodeBinaryOperatorExpression cboeMonth = new CodeBinaryOperatorExpression();
            cboeMonth.Left = new CodeVariableReferenceExpression(month);
            cboeMonth.Right = new CodePrimitiveExpression(0);
            cboeMonth.Operator = CodeBinaryOperatorType.LessThan;

            CodeBinaryOperatorExpression cboeDay = new CodeBinaryOperatorExpression();
            cboeDay.Left = new CodeVariableReferenceExpression(day);
            cboeDay.Right = new CodePrimitiveExpression(0);
            cboeDay.Operator = CodeBinaryOperatorType.LessThan;

            CodeBinaryOperatorExpression cboeHour = new CodeBinaryOperatorExpression();
            cboeHour.Left = new CodeVariableReferenceExpression(hour);
            cboeHour.Right = new CodePrimitiveExpression(0);
            cboeHour.Operator = CodeBinaryOperatorType.LessThan;

            CodeBinaryOperatorExpression cboeMinute = new CodeBinaryOperatorExpression();
            cboeMinute.Left = new CodeVariableReferenceExpression(minute);
            cboeMinute.Right = new CodePrimitiveExpression(0);
            cboeMinute.Operator = CodeBinaryOperatorType.LessThan;

            CodeBinaryOperatorExpression cboeSecond = new CodeBinaryOperatorExpression();
            cboeSecond.Left = new CodeVariableReferenceExpression(second);
            cboeSecond.Right = new CodePrimitiveExpression(0);
            cboeSecond.Operator = CodeBinaryOperatorType.LessThan;

            CodeBinaryOperatorExpression cboeTicks = new CodeBinaryOperatorExpression();
            cboeTicks.Left = new CodeVariableReferenceExpression(ticks);
            cboeTicks.Right = new CodePrimitiveExpression(0);
            cboeTicks.Operator = CodeBinaryOperatorType.LessThan;

            CodeBinaryOperatorExpression cboetemp1 = new CodeBinaryOperatorExpression();
            cboetemp1.Left = cboeYear;
            cboetemp1.Right = cboeMonth;
            cboetemp1.Operator = CodeBinaryOperatorType.BooleanOr;

            CodeBinaryOperatorExpression cboetemp2 = new CodeBinaryOperatorExpression();
            cboetemp2.Left = cboetemp1;
            cboetemp2.Right = cboeDay;
            cboetemp2.Operator = CodeBinaryOperatorType.BooleanOr;

            CodeBinaryOperatorExpression cboetemp3 = new CodeBinaryOperatorExpression();
            cboetemp3.Left = cboetemp2;
            cboetemp3.Right = cboeHour;
            cboetemp3.Operator = CodeBinaryOperatorType.BooleanOr;

            CodeBinaryOperatorExpression cboetemp4 = new CodeBinaryOperatorExpression();
            cboetemp4.Left = cboetemp3;
            cboetemp4.Right = cboeMinute;
            cboetemp4.Operator = CodeBinaryOperatorType.BooleanOr;

            CodeBinaryOperatorExpression cboetemp5 = new CodeBinaryOperatorExpression();
            cboetemp5.Left = cboetemp4;
            cboetemp5.Right = cboeMinute;
            cboetemp5.Operator = CodeBinaryOperatorType.BooleanOr;

            CodeBinaryOperatorExpression cboetemp6 = new CodeBinaryOperatorExpression();
            cboetemp6.Left = cboetemp5;
            cboetemp6.Right = cboeSecond;
            cboetemp6.Operator = CodeBinaryOperatorType.BooleanOr;

            CodeBinaryOperatorExpression cboetemp7 = new CodeBinaryOperatorExpression();
            cboetemp7.Left = cboetemp6;
            cboetemp7.Right = cboeTicks;
            cboetemp7.Operator = CodeBinaryOperatorType.BooleanOr;

            cis = new CodeConditionStatement();
            cis.Condition = cboetemp7;

            cis.TrueStatements.Add(new CodeThrowExceptionStatement(codeThrowException));

            tryblock.TryStatements.Add(cis);
            /*
                catch
                {
                    throw new System.ArgumentOutOfRangeException(null, e.Message);
                }
            */
            string exceptVar = "e";
            CodeCatchClause catchblock = new CodeCatchClause(exceptVar);
            
            CodeObjectCreateExpression codeThrowExceptionWithArgs = new CodeObjectCreateExpression();
            codeThrowExceptionWithArgs.CreateType = new CodeTypeReference
                (PublicNamesUsed["ArgumentOutOfRangeException"].ToString());
            codeThrowExceptionWithArgs.Parameters.Add(new CodePrimitiveExpression(null));
            codeThrowExceptionWithArgs.Parameters.Add
                (
                new CodePropertyReferenceExpression
                (
                new CodeVariableReferenceExpression(exceptVar),
                "Message"
                )
                );
            catchblock.Statements.Add(new CodeThrowExceptionStatement(codeThrowExceptionWithArgs));
            //
            // add the catch block to the try block
            //
            tryblock.CatchClauses.Add(catchblock);
            //
            // add the try block to cmmdt
            //
            cmmdt.Statements.Add(tryblock);

            /*
                datetime = new System.DateTime(year, month, day, hour, minute, second, millisec);
            */

            coce = new CodeObjectCreateExpression();
            coce.CreateType = new CodeTypeReference("System.DateTime");
            coce.Parameters.Add(new CodeVariableReferenceExpression(year));
            coce.Parameters.Add(new CodeVariableReferenceExpression(month));
            coce.Parameters.Add(new CodeVariableReferenceExpression(day));
            coce.Parameters.Add(new CodeVariableReferenceExpression(hour));
            coce.Parameters.Add(new CodeVariableReferenceExpression(minute));
            coce.Parameters.Add(new CodeVariableReferenceExpression(second));
            coce.Parameters.Add(new CodePrimitiveExpression(0));

            cmmdt.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(datetimeVariable),coce));
            
            /*
                datetime = datetime.AddTicks(ticks);
            */
            CodeMethodReferenceExpression  cmre2 = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(datetimeVariable),"AddTicks");
            CodeMethodInvokeExpression cmie2 = new CodeMethodInvokeExpression();
            cmie2.Method = cmre2;
            cmie2.Parameters.Add(new CodeVariableReferenceExpression(ticks));

            cmmdt.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(datetimeVariable),cmie2));

            /*
                System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime);
            */
            cmre1 = new CodeMethodReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression("System.TimeZone"),"CurrentTimeZone"),
                "GetUtcOffset");
            cmie1 = new CodeMethodInvokeExpression();
            cmie1.Method = cmre1;
            cmie1.Parameters.Add(new CodeVariableReferenceExpression(datetimeVariable));

            String tickoffset = "tickOffset";
            cmmdt.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.TimeSpan"),tickoffset,cmie1));

            /*
                System.Int32 UTCOffset =  0;
                System.Int32 OffsetToBeAdjusted = 0;
                long OffsetMins = tickOffset.Ticks / System.TimeSpan.TicksPerMinute;
                tempString = dmtf.Substring(22, 3);
            */
            String utcOffset = "UTCOffset";
            cmmdt.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.Int32"),utcOffset,new CodePrimitiveExpression(0)));
            String offsetAdjust = "OffsetToBeAdjusted";
            cmmdt.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.Int32"),offsetAdjust,new CodePrimitiveExpression(0)));
            
            String OffsetMins = "OffsetMins";
            cboe = new CodeBinaryOperatorExpression();
            cboe.Left = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression(tickoffset),"Ticks");
            cboe.Right = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.TimeSpan"),"TicksPerMinute");
            cboe.Operator = CodeBinaryOperatorType.Divide;
            cast = new CodeCastExpression("System.Int64", cboe);
            cmmdt.Statements.Add(
                new CodeVariableDeclarationStatement(
                new CodeTypeReference("System.Int64"),
                OffsetMins,
                cast
                )
                );

            cmre = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(dmtf),"Substring");
            cmie = new CodeMethodInvokeExpression();
            cmie.Method = cmre;
            cmie.Parameters.Add(new CodePrimitiveExpression(22));
            cmie.Parameters.Add(new CodePrimitiveExpression(3));
            cmmdt.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(tempStr), cmie));

            /*
                if (("***" != tempString1)) 
                {
                    tempString1 = dmtf.Substring(21, 4);
                    try
                    {
                        UTCOffset = System.Int32.Parse(tempString1);
                    }
                    catch
                    {
                        throw new System.ArgumentOutOfRangeException();
                    }

                    OffsetToBeAdjusted = UTCOffset-OffsetMins;
                        
                    // We have to substract the minutes from the time
                    datetime = datetime.AddMinutes((System.Double)(OffsetToBeAdjusted));

                }
            */
            cboe = new CodeBinaryOperatorExpression();
            cboe.Left = new CodeVariableReferenceExpression(tempStr);
            cboe.Right = new CodePrimitiveExpression("******");
            cboe.Operator = CodeBinaryOperatorType.IdentityInequality;

            cis = new CodeConditionStatement();
            cis.Condition = cboe;

            cmre = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(dmtf),"Substring");
            cmie = new CodeMethodInvokeExpression();
            cmie.Method = cmre;
            cmie.Parameters.Add(new CodePrimitiveExpression(21));
            cmie.Parameters.Add(new CodePrimitiveExpression(4));
            cis.TrueStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(tempStr), cmie));

            CodeTryCatchFinallyStatement tryblock2 = new CodeTryCatchFinallyStatement();

            cmre = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression("System.Int32"),"Parse");
            cmie = new CodeMethodInvokeExpression();
            cmie.Method = cmre;
            cmie.Parameters.Add(new CodeVariableReferenceExpression(tempStr));
            tryblock2.TryStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(utcOffset), cmie));
            //
            // add the catch block
            //
            tryblock2.CatchClauses.Add(catchblock);
            //
            // add tryblock2 to cis
            //
            cis.TrueStatements.Add(tryblock2);

            cboe = new CodeBinaryOperatorExpression();
            cboe.Left = new CodeVariableReferenceExpression(OffsetMins);
            cboe.Right = new CodeVariableReferenceExpression(utcOffset);
            cboe.Operator = CodeBinaryOperatorType.Subtract;
            cis.TrueStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(offsetAdjust),new CodeCastExpression(new CodeTypeReference("System.Int32"),cboe)));

            cmre = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(datetimeVariable),"AddMinutes");
            cmie = new CodeMethodInvokeExpression();
            cmie.Method = cmre;
            cmie.Parameters.Add(new CodeCastExpression("System.Double",new CodeVariableReferenceExpression(offsetAdjust)));
            cis.TrueStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(datetimeVariable),cmie));

            cmmdt.Statements.Add(cis);
            /*
                    return datetime;
            
            */
            cmmdt.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(datetimeVariable)));
            cc.Members.Add(cmmdt);
        }
        /// <summary>
        /// Gets the load from file CodeDOM method.
        /// </summary>
        /// <param name="type">The type CodeTypeDeclaration.</param>
        /// <returns>return the codeDom LoadFromFile method</returns>
        protected override CodeMemberMethod GetLoadFromFileMethod(CodeTypeDeclaration type)
        {
            var typeName = GeneratorContext.GeneratorParams.GenericBaseClass.Enabled ? "T" : type.Name;

            // ---------------------------------------------
            // public static T LoadFromFile(string fileName)
            // ---------------------------------------------
            var loadFromFileMethod = new CodeMemberMethod
            {
                Attributes = MemberAttributes.Public | MemberAttributes.Static,
                Name = GeneratorContext.GeneratorParams.Serialization.LoadFromFileMethodName
            };

            loadFromFileMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "fileName"));
            if (GeneratorContext.GeneratorParams.Serialization.EnableEncoding)
            {
                loadFromFileMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Encoding), "encoding"));
            }

            loadFromFileMethod.ReturnType = new CodeTypeReference(typeName);

            loadFromFileMethod.Statements.Add(
                new CodeVariableDeclarationStatement(
                        new CodeTypeReference(typeof(IsolatedStorageFile)),
                        "isoFile",
                        new CodePrimitiveExpression(null)));

            loadFromFileMethod.Statements.Add(
                new CodeVariableDeclarationStatement(
                        new CodeTypeReference(typeof(IsolatedStorageFileStream)),
                        "isoStream",
                        new CodePrimitiveExpression(null)));

            loadFromFileMethod.Statements.Add(
               new CodeVariableDeclarationStatement(
                       new CodeTypeReference(typeof(StreamReader)),
                       "sr",
                       new CodePrimitiveExpression(null)));

            var tryStatmanentsCol = new CodeStatementCollection();
            var finallyStatmanentsCol = new CodeStatementCollection();

            tryStatmanentsCol.Add(
                new CodeAssignStatement(
                new CodeVariableReferenceExpression("isoFile"),
                CodeDomHelper.GetInvokeMethod("IsolatedStorageFile", "GetUserStoreForApplication")));

            tryStatmanentsCol.Add(
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("isoStream"),
                    new CodeObjectCreateExpression(
                        typeof(IsolatedStorageFileStream),
                        new CodeExpression[]
                        {
                             new CodeArgumentReferenceExpression("fileName"),
                             CodeDomHelper.GetEnum("FileMode","Open"),
                             new CodeVariableReferenceExpression("isoFile")
                    })));

            CodeExpression[] codeParamExpression;
            if (GeneratorContext.GeneratorParams.Serialization.EnableEncoding)
            {
                codeParamExpression = new CodeExpression[] { new CodeVariableReferenceExpression("isoStream"), new CodeVariableReferenceExpression("encoding") };
            }
            else
            {
                codeParamExpression = new CodeExpression[] { new CodeVariableReferenceExpression("isoStream") };
            }
            tryStatmanentsCol.Add(
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("sr"),
                    new CodeObjectCreateExpression(
                        typeof(StreamReader), codeParamExpression
                       )));
            // ----------------------------------
            // string xmlString = sr.ReadToEnd();
            // ----------------------------------
            var readToEndInvoke = CodeDomHelper.GetInvokeMethod("sr", "ReadToEnd");

            var xmlString = new CodeVariableDeclarationStatement(
                new CodeTypeReference(typeof(string)), "xmlString", readToEndInvoke);

            tryStatmanentsCol.Add(xmlString);
            tryStatmanentsCol.Add(CodeDomHelper.GetInvokeMethod("isoStream", "Close"));
            tryStatmanentsCol.Add(CodeDomHelper.GetInvokeMethod("sr", "Close"));

            // ------------------------------------------------------
            // return Deserialize(xmlString, out obj, out exception);
            // ------------------------------------------------------
            var fileName = new CodeVariableReferenceExpression("xmlString");

            var deserializeInvoke =
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(null, GeneratorContext.GeneratorParams.Serialization.DeserializeMethodName),
                    new CodeExpression[] { fileName });

            var rstmts = new CodeMethodReturnStatement(deserializeInvoke);
            tryStatmanentsCol.Add(rstmts);

            finallyStatmanentsCol.Add(CodeDomHelper.GetDispose("isoFile"));
            finallyStatmanentsCol.Add(CodeDomHelper.GetDispose("isoStream"));
            finallyStatmanentsCol.Add(CodeDomHelper.GetDispose("sr"));

            var tryfinally = new CodeTryCatchFinallyStatement(
                CodeDomHelper.CodeStmtColToArray(tryStatmanentsCol), new CodeCatchClause[0], CodeDomHelper.CodeStmtColToArray(finallyStatmanentsCol));

            loadFromFileMethod.Statements.Add(tryfinally);

            return loadFromFileMethod;
        }
Esempio n. 18
0
        void AddToTimeSpanFunction()
        {
            String tsParam    = "dmtfTimespan";
            String days = "days";
            String hours = "hours";
            String minutes = "minutes";
            String seconds = "seconds";
            String ticks = "ticks";

            CodeMemberMethod cmmts = new CodeMemberMethod();
            cmmts.Name = PrivateNamesUsed["ToTimeSpanMethod"].ToString();
            cmmts.Attributes = MemberAttributes.Final | MemberAttributes.Static;
            cmmts.ReturnType = new CodeTypeReference("System.TimeSpan");
            cmmts.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.String"),tsParam));
            cmmts.Comments.Add(new CodeCommentStatement(GetString("COMMENT_TOTIMESPAN")));


            //Int32 days = 0;
            cmmts.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.Int32"),days,new CodePrimitiveExpression(0)));
            //Int32 hours = 0;
            cmmts.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.Int32"),hours,new CodePrimitiveExpression(0)));
            //Int32 minutes = 0;
            cmmts.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.Int32"),minutes,new CodePrimitiveExpression(0)));
            //Int32 seconds = 0;
            cmmts.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.Int32"),seconds,new CodePrimitiveExpression(0)));
            //Int32 ticks = 0;
            cmmts.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.Int64"),ticks,new CodePrimitiveExpression(0)));

            /*
                if (dmtfTimespan == null)
                {
                    throw new System.ArgumentOutOfRangeException();
                }
            */

            CodeBinaryOperatorExpression cboe = new CodeBinaryOperatorExpression();
            cboe.Left = new CodeVariableReferenceExpression(tsParam);
            cboe.Right = new CodePrimitiveExpression(null);
            cboe.Operator = CodeBinaryOperatorType.IdentityEquality;

            CodeConditionStatement cis = new CodeConditionStatement();
            cis.Condition = cboe;

            CodeObjectCreateExpression codeThrowException = new CodeObjectCreateExpression();
            codeThrowException.CreateType = new CodeTypeReference(PublicNamesUsed["ArgumentOutOfRangeException"].ToString());
            cis.TrueStatements.Add(new CodeThrowExceptionStatement(codeThrowException));

            cmmts.Statements.Add(cis);

            /*      
                if (dmtfTimespan.Length == 0)
                {
                    throw new System.ArgumentOutOfRangeException();
                }
            */

            cboe = new CodeBinaryOperatorExpression();
            cboe.Left = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression(tsParam),"Length");
            cboe.Right = new CodePrimitiveExpression(0);
            cboe.Operator = CodeBinaryOperatorType.ValueEquality;

            cis = new CodeConditionStatement();
            cis.Condition = cboe;

            cis.TrueStatements.Add(new CodeThrowExceptionStatement(codeThrowException));

            cmmts.Statements.Add(cis);

            /*      
                if (dmtfTimespan.Length != DMTF_DATETIME_STR_LENGTH )
                {
                    throw new System.ArgumentOutOfRangeException();
                }
            */

            cboe = new CodeBinaryOperatorExpression();
            cboe.Left = new CodePropertyReferenceExpression(new CodeVariableReferenceExpression(tsParam),"Length");
            cboe.Right = new CodePrimitiveExpression(DMTF_DATETIME_STR_LENGTH);
            cboe.Operator = CodeBinaryOperatorType.IdentityInequality;

            cis = new CodeConditionStatement();
            cis.Condition = cboe;
            cis.TrueStatements.Add(new CodeThrowExceptionStatement(codeThrowException));

            cmmts.Statements.Add(cis);
            
            /*
                if(dmtfTimespan.Substring(21,4) != ":000")
                {
                    throw new System.ArgumentOutOfRangeException();
                }
            */
            
            CodeMethodInvokeExpression cmie = new CodeMethodInvokeExpression();
            cmie.Method = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(tsParam),"Substring");
            cmie.Parameters.Add(new CodePrimitiveExpression(21));
            cmie.Parameters.Add(new CodePrimitiveExpression(4));

            cboe = new CodeBinaryOperatorExpression();
            cboe.Left = cmie;
            cboe.Right = new CodePrimitiveExpression(":000");
            cboe.Operator = CodeBinaryOperatorType.IdentityInequality;

            cis = new CodeConditionStatement();
            cis.Condition = cboe;
            cis.TrueStatements.Add(new CodeThrowExceptionStatement(codeThrowException));

            cmmts.Statements.Add(cis);

            CodeTryCatchFinallyStatement tryblock = new CodeTryCatchFinallyStatement();

            /*
                string tempString = System.String.Empty;
            */

            string strTemp = "tempString";
            tryblock.TryStatements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.String"),strTemp,
                new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.String"),"Empty")));
            /*
                tempString = dmtfTimespan.Substring(0, 8);
                days = System.Int32.Parse(tempString);

                tempString = dmtfTimespan.Substring(8, 2);
                hours = System.Int32.Parse(tempString);

                tempString = dmtfTimespan.Substring(10, 2);
                minutes = System.Int32.Parse(tempString);

                tempString = dmtfTimespan.Substring(12, 2);
                seconds = System.Int32.Parse(tempString);
            */

            ToTimeSpanHelper(0,8,days,tryblock.TryStatements);
            ToTimeSpanHelper(8,2,hours,tryblock.TryStatements);
            ToTimeSpanHelper(10,2,minutes,tryblock.TryStatements);
            ToTimeSpanHelper(12,2,seconds,tryblock.TryStatements);

            /*
                tempString = dmtfTimespan.Substring(15, 6);
            */

            cmie = new CodeMethodInvokeExpression();
            cmie.Method = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(tsParam),"Substring");
            cmie.Parameters.Add(new CodePrimitiveExpression(15));
            cmie.Parameters.Add(new CodePrimitiveExpression(6));

            tryblock.TryStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(strTemp),cmie));

            cmie = new CodeMethodInvokeExpression();
            cmie.Method = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression("System.Int64"),"Parse");
            cmie.Parameters.Add(new CodeVariableReferenceExpression(strTemp));

            /*
                ticks = (System.Int64.Parse(tempString)) * (System.TimeSpan.TicksPerMillisecond/1000);
            */
            tryblock.TryStatements.Add
                (
                new CodeAssignStatement(
                new CodeVariableReferenceExpression(ticks),
                new CodeBinaryOperatorExpression(
                cmie,
                CodeBinaryOperatorType.Multiply,
                new CodeCastExpression(
                "System.Int64",
                new CodeBinaryOperatorExpression(
                new CodeFieldReferenceExpression(
                new CodeTypeReferenceExpression("System.TimeSpan"),
                "TicksPerMillisecond"
                ),
                CodeBinaryOperatorType.Divide,
                new CodePrimitiveExpression(1000)
                )
                )
                )
                )
                );

            /*
                if( days < 0 || hours < 0 || minutes < 0 || seconds < 0 || ticks < 0)
                {
                    throw new System.ArgumentOutOfRangeException();
                }
            */

            CodeBinaryOperatorExpression cboeDays = new CodeBinaryOperatorExpression();
            cboeDays.Left = new CodeVariableReferenceExpression(days);
            cboeDays.Right = new CodePrimitiveExpression(0);
            cboeDays.Operator = CodeBinaryOperatorType.LessThan;


            CodeBinaryOperatorExpression cboeHours = new CodeBinaryOperatorExpression();
            cboeHours.Left = new CodeVariableReferenceExpression(hours);
            cboeHours.Right = new CodePrimitiveExpression(0);
            cboeHours.Operator = CodeBinaryOperatorType.LessThan;

            CodeBinaryOperatorExpression cboeMinutes = new CodeBinaryOperatorExpression();
            cboeMinutes.Left = new CodeVariableReferenceExpression(minutes);
            cboeMinutes.Right = new CodePrimitiveExpression(0);
            cboeMinutes.Operator = CodeBinaryOperatorType.LessThan;

            CodeBinaryOperatorExpression cboeSeconds = new CodeBinaryOperatorExpression();
            cboeSeconds.Left = new CodeVariableReferenceExpression(seconds);
            cboeSeconds.Right = new CodePrimitiveExpression(0);
            cboeSeconds.Operator = CodeBinaryOperatorType.LessThan;

            CodeBinaryOperatorExpression cboeTicks = new CodeBinaryOperatorExpression();
            cboeTicks.Left = new CodeVariableReferenceExpression(ticks);
            cboeTicks.Right = new CodePrimitiveExpression(0);
            cboeTicks.Operator = CodeBinaryOperatorType.LessThan;

            CodeBinaryOperatorExpression cboetemp1 = new CodeBinaryOperatorExpression();
            cboetemp1.Left = cboeDays;
            cboetemp1.Right = cboeHours;
            cboetemp1.Operator = CodeBinaryOperatorType.BooleanOr;

            CodeBinaryOperatorExpression cboetemp2 = new CodeBinaryOperatorExpression();
            cboetemp2.Left = cboetemp1;
            cboetemp2.Right = cboeMinutes;
            cboetemp2.Operator = CodeBinaryOperatorType.BooleanOr;

            CodeBinaryOperatorExpression cboetemp3 = new CodeBinaryOperatorExpression();
            cboetemp3.Left = cboetemp2;
            cboetemp3.Right = cboeSeconds;
            cboetemp3.Operator = CodeBinaryOperatorType.BooleanOr;

            CodeBinaryOperatorExpression cboetemp4 = new CodeBinaryOperatorExpression();
            cboetemp4.Left = cboetemp3;
            cboetemp4.Right = cboeTicks;
            cboetemp4.Operator = CodeBinaryOperatorType.BooleanOr;

            cis = new CodeConditionStatement();
            cis.Condition = cboetemp4;

            cis.TrueStatements.Add(new CodeThrowExceptionStatement(codeThrowException));

            /*
                catch
                {
                    throw new System.ArgumentOutOfRangeException(null, e.Message);
                }
            */
            string exceptVar = "e";
            CodeCatchClause catchblock = new CodeCatchClause(exceptVar);
            
            CodeObjectCreateExpression codeThrowExceptionWithArgs = new CodeObjectCreateExpression();
            codeThrowExceptionWithArgs.CreateType = new CodeTypeReference
                (PublicNamesUsed["ArgumentOutOfRangeException"].ToString());
            codeThrowExceptionWithArgs.Parameters.Add(new CodePrimitiveExpression(null));
            codeThrowExceptionWithArgs.Parameters.Add
                (
                new CodePropertyReferenceExpression
                (
                new CodeVariableReferenceExpression(exceptVar),
                "Message"
                )
                );
            catchblock.Statements.Add(new CodeThrowExceptionStatement(codeThrowExceptionWithArgs));
            //
            // add the catch block to the try block
            //
            tryblock.CatchClauses.Add(catchblock);
            //
            // add the try block to cmmts
            //
            cmmts.Statements.Add(tryblock);

            /*
                timespan = new System.TimeSpan(days, hours, minutes, seconds, 0);
            */

            string timespan = "timespan";
            coce = new CodeObjectCreateExpression();
            coce.CreateType = new CodeTypeReference("System.TimeSpan");
            coce.Parameters.Add(new CodeVariableReferenceExpression(days));
            coce.Parameters.Add(new CodeVariableReferenceExpression(hours));
            coce.Parameters.Add(new CodeVariableReferenceExpression(minutes));
            coce.Parameters.Add(new CodeVariableReferenceExpression(seconds));
            coce.Parameters.Add(new CodePrimitiveExpression(0));

            cmmts.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.TimeSpan"),timespan,coce));

            /*
                TimeSpan tsTemp = System.TimeSpan.FromTicks(ticks);
                timespan = timespan.Add(tsTemp);
            */
            string tsTemp = "tsTemp";
            cmie = new CodeMethodInvokeExpression();
            cmie.Method = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression("System.TimeSpan"),"FromTicks");
            cmie.Parameters.Add(new CodeVariableReferenceExpression(ticks));

            cmmts.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.TimeSpan"),tsTemp,cmie));
            
            cmie = new CodeMethodInvokeExpression();
            cmie.Method = new CodeMethodReferenceExpression(new CodeVariableReferenceExpression(timespan),"Add");
            cmie.Parameters.Add(new CodeVariableReferenceExpression(tsTemp));

            cmmts.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(timespan),cmie));


            /*
                return timespan;
            */
            cmmts.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression(timespan)));

            cc.Members.Add(cmmts);
        }
		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 ()
				)
			);
		}
        CodeMemberMethod GenerateLoadMethod()
        {
            ////Generate the following code:

            //private static System.Reflection.Assembly Load(string assemblyNameVal) {
            //    System.Reflection.AssemblyName assemblyName = new System.Reflection.AssemblyName(assemblyNameVal);
            //    byte[] publicKeyToken = assemblyName.GetPublicKeyToken();
            //    System.Reflection.Assembly asm = null;
            //    try {
            //        asm = System.Reflection.Assembly.Load(assemblyName.FullName);
            //    }
            //    catch (System.Exception ) {
            //        System.Reflection.AssemblyName shortName = new System.Reflection.AssemblyName(assemblyName.Name);
            //        if ((publicKeyToken != null)) {
            //            shortName.SetPublicKeyToken(publicKeyToken);
            //        }
            //        asm = System.Reflection.Assembly.Load(shortName);
            //    }
            //    return asm;
            //}

            CodeMemberMethod loadMethod = new CodeMemberMethod()
            {
                Name = "Load",
                Attributes = MemberAttributes.Private | MemberAttributes.Static,
                ReturnType = new CodeTypeReference(typeof(Assembly))
            };
            loadMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "assemblyNameVal"));
            CodeVariableReferenceExpression assemblyNameVal = new CodeVariableReferenceExpression("assemblyNameVal");

            CodeExpression initAssemblyName = typeof(AssemblyName).New(assemblyNameVal);
            CodeVariableReferenceExpression assemblyName = loadMethod.Statements.DeclareVar(typeof(AssemblyName), "assemblyName", initAssemblyName);

            CodeVariableReferenceExpression publicKeyToken = loadMethod.Statements.DeclareVar(typeof(byte[]),
                "publicKeyToken",
                new CodeMethodInvokeExpression()
                {
                    Method =
                    new CodeMethodReferenceExpression()
                    {
                        MethodName = "GetPublicKeyToken",
                        TargetObject = assemblyName,
                    },
                }
                );
            CodeVariableReferenceExpression asm = loadMethod.Statements.DeclareVar(typeof(Assembly), "asm", new CodePrimitiveExpression(null));

            CodeExpression publicKeyTokenNotNullExp = new CodeBinaryOperatorExpression(publicKeyToken,
                CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null));

            CodeTryCatchFinallyStatement tryCatchExp = new CodeTryCatchFinallyStatement();

            tryCatchExp.TryStatements.Add(new CodeAssignStatement(asm,
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression()
                    {
                        MethodName = "System.Reflection.Assembly.Load"
                    },
                    new CodePropertyReferenceExpression(assemblyName, "FullName")
                )
            ));

            CodeCatchClause catchClause = new CodeCatchClause();
            CodeVariableReferenceExpression shortName = catchClause.Statements.DeclareVar(typeof(AssemblyName), "shortName",
                typeof(AssemblyName).New(new CodePropertyReferenceExpression(assemblyName, "Name")));
            CodeConditionStatement setPublicKeyTokenExp = new CodeConditionStatement();
            setPublicKeyTokenExp.Condition = publicKeyTokenNotNullExp;
            setPublicKeyTokenExp.TrueStatements.Add(
                new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(shortName, "SetPublicKeyToken"), publicKeyToken)
            );
            catchClause.Statements.Add(setPublicKeyTokenExp);
            catchClause.Statements.Add(new CodeAssignStatement(asm,
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression()
                    {
                        MethodName = "System.Reflection.Assembly.Load"
                    },
                    shortName
                )
            ));
            tryCatchExp.CatchClauses.Add(catchClause);

            loadMethod.Statements.Add(tryCatchExp);
            loadMethod.Statements.Add(new CodeMethodReturnStatement(asm));
            return loadMethod;
        }
Esempio n. 21
0
        // Add a new vertex method to the DryadLinq vertex class
        internal CodeMemberMethod AddVertexMethod(DLinqQueryNode node)
        {
            CodeMemberMethod vertexMethod = new CodeMemberMethod();
            vertexMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            vertexMethod.ReturnType = new CodeTypeReference(typeof(int));
            vertexMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "args"));
            vertexMethod.Name = MakeUniqueName(node.NodeType.ToString());

            CodeTryCatchFinallyStatement tryBlock = new CodeTryCatchFinallyStatement();

            string startedMsg = "DryadLinqLog.AddInfo(\"Vertex " + vertexMethod.Name + 
                " started at {0}\", DateTime.Now.ToString(\"MM/dd/yyyy HH:mm:ss.fff\"))";
            vertexMethod.Statements.Add(new CodeSnippetExpression(startedMsg));

            // We need to add a call to CopyResources()
            vertexMethod.Statements.Add(new CodeSnippetExpression("CopyResources()"));
            
            if (StaticConfig.LaunchDebugger)
            {
                // If static config requests it, we do an unconditional Debugger.Launch() at vertex entry.
                // Currently this isn't used because StaticConfig.LaunchDebugger is hardcoded to false
                System.Console.WriteLine("Launch debugger: may block application");

                CodeExpression launchExpr = new CodeSnippetExpression("System.Diagnostics.Debugger.Launch()");
                vertexMethod.Statements.Add(new CodeExpressionStatement(launchExpr));
            }
            else
            {
                // Otherwise (the default behavior), we check an environment variable to decide whether
                // to launch the debugger, wait for a manual attach or simply skip straigt into vertex code.
                CodeMethodInvokeExpression debuggerCheckExpr = new CodeMethodInvokeExpression(
                        new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(HelperClassName), 
                                                          DebugHelperMethodName));

                vertexMethod.Statements.Add(new CodeExpressionStatement(debuggerCheckExpr));
            }
            
            vertexMethod.Statements.Add(MakeVertexParamsDecl(node));
            vertexMethod.Statements.Add(SetVertexParamField("VertexStageName", vertexMethod.Name));
            vertexMethod.Statements.Add(SetVertexParamField("UseLargeBuffer", node.UseLargeWriteBuffer));
            Int32[] portCountArray = node.InputPortCounts();
            bool[] keepPortOrderArray = node.KeepInputPortOrders();
            for (int i = 0; i < node.InputArity; i++)
            {
                CodeExpression setParamsExpr = new CodeMethodInvokeExpression(
                                                       new CodeVariableReferenceExpression(VertexParamName),
                                                       "SetInputParams",
                                                       new CodePrimitiveExpression(i),
                                                       new CodePrimitiveExpression(portCountArray[i]),
                                                       new CodePrimitiveExpression(keepPortOrderArray[i]));
                vertexMethod.Statements.Add(new CodeExpressionStatement(setParamsExpr));
            }
            // YY: We could probably do better here.
            for (int i = 0; i < node.GetReferencedQueries().Count; i++)
            {
                CodeExpression setParamsExpr = new CodeMethodInvokeExpression(
                                                       new CodeVariableReferenceExpression(VertexParamName),
                                                       "SetInputParams",
                                                       new CodePrimitiveExpression(i + node.InputArity),
                                                       new CodePrimitiveExpression(1),
                                                       new CodePrimitiveExpression(false));
                vertexMethod.Statements.Add(new CodeExpressionStatement(setParamsExpr));
            }
            
            // Push the parallel-code settings into DryadLinqVertex
            bool multiThreading = this.m_context.EnableMultiThreadingInVertex;
            vertexMethod.Statements.Add(SetVertexParamField("MultiThreading", multiThreading));
            vertexMethod.Statements.Add(
                  new CodeAssignStatement(
                     new CodeFieldReferenceExpression(DLVTypeExpr, "s_multiThreading"),
                     new CodePrimitiveExpression(multiThreading)));
                                                                 
            vertexMethod.Statements.Add(MakeVertexEnvDecl(node));

            Type[] outputTypes = node.OutputTypes;
            string[] writerNames = new string[outputTypes.Length];
            for (int i = 0; i < outputTypes.Length; i++)
            {
                CodeVariableDeclarationStatement
                    writerDecl = MakeVertexWriterDecl(outputTypes[i], this.GetStaticFactoryName(outputTypes[i]));
                vertexMethod.Statements.Add(writerDecl);
                writerNames[i] = writerDecl.Name;
            }

            // Add side readers:
            node.AddSideReaders(vertexMethod);

            // Generate code based on the node type:
            switch (node.NodeType)
            {
                case QueryNodeType.Where:
                case QueryNodeType.OrderBy:
                case QueryNodeType.Distinct:
                case QueryNodeType.Skip:
                case QueryNodeType.SkipWhile:
                case QueryNodeType.Take:
                case QueryNodeType.TakeWhile:
                case QueryNodeType.Merge:
                case QueryNodeType.Select:
                case QueryNodeType.SelectMany:
                case QueryNodeType.Zip:
                case QueryNodeType.GroupBy:
                case QueryNodeType.BasicAggregate:
                case QueryNodeType.Aggregate:                
                case QueryNodeType.Contains:
                case QueryNodeType.Join:
                case QueryNodeType.GroupJoin:
                case QueryNodeType.Union:
                case QueryNodeType.Intersect:
                case QueryNodeType.Except:
                case QueryNodeType.RangePartition:
                case QueryNodeType.HashPartition:
                case QueryNodeType.Apply:
                case QueryNodeType.Fork:
                case QueryNodeType.Dynamic:
                {
                    Type[] inputTypes = node.InputTypes;
                    string[] sourceNames = new string[inputTypes.Length];
                    for (int i = 0; i < inputTypes.Length; i++)
                    {
                        CodeVariableDeclarationStatement 
                            readerDecl = MakeVertexReaderDecl(inputTypes[i], this.GetStaticFactoryName(inputTypes[i]));
                        vertexMethod.Statements.Add(readerDecl);
                        sourceNames[i] = readerDecl.Name;
                    }
                    string sourceToSink = this.m_vertexCodeGen.AddVertexCode(node, vertexMethod, sourceNames, writerNames);
                    if (sourceToSink != null)
                    {
                        CodeExpression sinkExpr = new CodeMethodInvokeExpression(
                                                           new CodeVariableReferenceExpression(writerNames[0]),
                                                           "WriteItemSequence",
                                                           new CodeVariableReferenceExpression(sourceToSink));
                        vertexMethod.Statements.Add(sinkExpr);
                    }
                    break;
                }
                case QueryNodeType.Super:
                {
                    string sourceToSink = this.m_vertexCodeGen.AddVertexCode(node, vertexMethod, null, writerNames);
                    if (sourceToSink != null)
                    {
                        CodeExpression sinkExpr = new CodeMethodInvokeExpression(
                                                           new CodeVariableReferenceExpression(writerNames[0]),
                                                           "WriteItemSequence",
                                                           new CodeVariableReferenceExpression(sourceToSink));
                        vertexMethod.Statements.Add(sinkExpr);
                    }
                    break;
                }
                default:
                {
                    //@@TODO: this should not be reachable. could change to Assert/InvalidOpEx
                    throw new DryadLinqException(DryadLinqErrorCode.Internal,
                                                 String.Format(SR.AddVertexNotHandled, node.NodeType));
                }
            }

            string completedMsg = "DryadLinqLog.AddInfo(\"Vertex " + vertexMethod.Name + 
                " completed at {0}\", DateTime.Now.ToString(\"MM/dd/yyyy HH:mm:ss.fff\"))";
            vertexMethod.Statements.Add(new CodeSnippetExpression(completedMsg));
            
            // add a catch block
            CodeCatchClause catchBlock = new CodeCatchClause("e");
            CodeTypeReferenceExpression errorReportClass = new CodeTypeReferenceExpression("VertexEnv");
            CodeMethodReferenceExpression
                errorReportMethod = new CodeMethodReferenceExpression(errorReportClass, "ReportVertexError");
            CodeVariableReferenceExpression exRef = new CodeVariableReferenceExpression(catchBlock.LocalName);
            catchBlock.Statements.Add(new CodeMethodInvokeExpression(errorReportMethod, exRef));
            tryBlock.CatchClauses.Add(catchBlock);
            
            // wrap the entire vertex method in a try/catch block
            tryBlock.TryStatements.AddRange(vertexMethod.Statements);
            vertexMethod.Statements.Clear();
            vertexMethod.Statements.Add(tryBlock);
            
            // Always add "return 0", to make CLR hosting happy...
            vertexMethod.Statements.Add(new CodeMethodReturnStatement(ZeroExpr));

            this.m_dryadVertexClass.Members.Add(vertexMethod);
            return vertexMethod;
        }
        CodeMemberMethod GenerateInitializeMethod(ClassData classData, List<CodeMemberField> memberFields)
        {
            // /// <summary> InitializeComponent </summary>
            // [DebuggerNonUserCodeAttribute]
            // [System.CodeDom.Compiler.GeneratedCodeAttribute("<%= AssemblyName %>", "<%= AssemblyVersion %>")]
            // public void InitializeComponent() {
            //
            CodeMemberMethod initializeMethod = new CodeMemberMethod()
                {
                    Name = "InitializeComponent",
                    Attributes = MemberAttributes.Public | MemberAttributes.Final,
                    CustomAttributes =
                    {
                        new CodeAttributeDeclaration(new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute))),
                        GeneratedCodeAttribute
                    }
                };

            initializeMethod.Comments.AddRange(GenerateXmlComments(initializeMethod.Name));

            // if (__contentLoaded) { return; }
            initializeMethod.Statements.Add(
                new CodeConditionStatement()
                {
                    Condition = new CodeBinaryOperatorExpression()
                    {
                        Left = new CodeFieldReferenceExpression() { FieldName = "_contentLoaded", TargetObject = new CodeThisReferenceExpression() },
                        Operator = CodeBinaryOperatorType.ValueEquality,
                        Right = new CodePrimitiveExpression(true)
                    },
                    TrueStatements = {
                        new CodeMethodReturnStatement()
                    }
                }
                );

            // __contentLoaded = true;
            initializeMethod.Statements.Add(
                new CodeAssignStatement()
                {
                    Left = new CodeFieldReferenceExpression() { FieldName = "_contentLoaded", TargetObject = new CodeThisReferenceExpression() },
                    Right = new CodePrimitiveExpression(true)
                }
                );

            if (ArePartialMethodsSupported())
            {
                // bool isInitialized = false;
                // BeforeInitializeComponent(ref isInitialized);
                // if (isInitialized) {
                //    AfterInitializeComponent();
                //    return;
                // }
                initializeMethod.Statements.Add(new CodeVariableDeclarationStatement(
                    typeof(bool), "isInitialized", new CodePrimitiveExpression(false)));
                initializeMethod.Statements.Add(new CodeMethodInvokeExpression(
                    new CodeThisReferenceExpression(), "BeforeInitializeComponent",
                    new CodeDirectionExpression(FieldDirection.Ref, new CodeVariableReferenceExpression("isInitialized"))
                ));
                initializeMethod.Statements.Add(
                    new CodeConditionStatement
                    {
                        Condition = new CodeBinaryOperatorExpression(
                            new CodeVariableReferenceExpression("isInitialized"),
                            CodeBinaryOperatorType.ValueEquality,
                            new CodePrimitiveExpression(true)
                        ),
                        TrueStatements =
                        {
                            new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "AfterInitializeComponent"),
                            new CodeMethodReturnStatement()
                        }
                    }
                );
            }

            //     string resourceName = FindResource();
            CodeVariableReferenceExpression resourceNameVar =
                initializeMethod.Statements.DeclareVar(
                typeof(string),
                "resourceName",
                new CodeMethodInvokeExpression()
                {
                    Method =
                    new CodeMethodReferenceExpression()
                    {
                        MethodName = "FindResource",
                        TargetObject = new CodeThisReferenceExpression(),
                    },
                }
                );

            //     Stream initializeXaml = typeof(<%= className %>).Assembly.GetManifestResourceStream(resourceName);
            //
            CodeVariableReferenceExpression initializeXamlVar =
                initializeMethod.Statements.DeclareVar(
                typeof(Stream),
                "initializeXaml",
                new CodeMethodInvokeExpression()
                {
                    Method =
                    new CodeMethodReferenceExpression()
                    {
                        MethodName = "GetManifestResourceStream",
                        TargetObject =
                        new CodePropertyReferenceExpression()
                        {
                            PropertyName = "Assembly",
                            TargetObject =
                            new CodeTypeOfExpression()
                            {
                                Type = new CodeTypeReference(classData.Name)
                            }
                        }
                    },
                    Parameters =
                    {
                        new CodeVariableReferenceExpression(resourceNameVar.VariableName),
                    }
                }
                );

            //     var reader = new System.Xaml.XamlXmlReader(new System.IO.StreamReader(initializeXaml));
            //
            CodeVariableReferenceExpression xmlReaderVar = initializeMethod.Statements.DeclareVar(
                typeof(XmlReader), "xmlReader", new CodePrimitiveExpression(null));

            CodeVariableReferenceExpression xamlReaderVar = initializeMethod.Statements.DeclareVar(
                typeof(XamlReader), "reader", new CodePrimitiveExpression(null));

            CodeVariableReferenceExpression objWriterVar = initializeMethod.Statements.DeclareVar(
                typeof(XamlObjectWriter), "objectWriter", new CodePrimitiveExpression(null));

            // Enclose in try finally block
            // This is to call Dispose on the xmlReader in the finally block, which is the CodeDom way of the C# "using" block
            CodeTryCatchFinallyStatement tryCatchFinally = new CodeTryCatchFinallyStatement();
            tryCatchFinally.TryStatements.AddRange(GetInitializeMethodTryStatements(xmlReaderVar, xamlReaderVar, objWriterVar, initializeXamlVar, classData, memberFields));
            tryCatchFinally.FinallyStatements.AddRange(GetInitializeMethodFinallyStatements(xmlReaderVar, xamlReaderVar, objWriterVar));
            initializeMethod.Statements.Add(tryCatchFinally);

            if (ArePartialMethodsSupported())
            {
                // AfterInitializeComponent();
                initializeMethod.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "AfterInitializeComponent"));
            }

            return initializeMethod;
        }
Esempio n. 23
0
		protected abstract void GenerateTryCatchFinallyStatement (CodeTryCatchFinallyStatement s);
 public bool ValidateCodeTryCatchFinallyStatement (CodeTryCatchFinallyStatement exp) {
     PushError ("CodeTryCatchFinallyStatement is not in the subset.");
     return false;
 }
		protected override void AddPageTypeCtorStatements (CodeStatementCollection statements)
		{
			base.AddPageTypeCtorStatements (statements);

			CodeTypeReference uriType = new CodeTypeReference (typeof(Uri));

			CodeVariableDeclarationStatement procVar = new CodeVariableDeclarationStatement {
            Name = "proc",
            Type = new CodeTypeReference(typeof(IXQueryProcessor)),
            InitExpression = new CodeIndexerExpression {
               TargetObject = new CodePropertyReferenceExpression {
                  PropertyName = "XQuery",
                  TargetObject = new CodeTypeReferenceExpression(typeof(Processors))
               },
               Indices = { 
                  new CodePrimitiveExpression(parser.ProcessorName)
               }
            }
         };

			CodeVariableDeclarationStatement sourceVar = new CodeVariableDeclarationStatement {
            Name = "source",
            Type = new CodeTypeReference(typeof(Stream)),
            InitExpression = new CodePrimitiveExpression(null)
         };

			CodeVariableDeclarationStatement virtualPathVar = new CodeVariableDeclarationStatement {
            Name = "virtualPath",
            Type = new CodeTypeReference(typeof(String)),
            InitExpression = new CodePrimitiveExpression(this.parser.AppRelativeVirtualPath)
         };

			CodeVariableDeclarationStatement sourceUriVar = new CodeVariableDeclarationStatement {
            Name = "sourceUri",
            Type = uriType,
            InitExpression = new CodeObjectCreateExpression {
               CreateType = uriType,
               Parameters = { 
                  new CodeMethodInvokeExpression {
                     Method = new CodeMethodReferenceExpression {
                        MethodName = "MapPath",
                        TargetObject = new CodeTypeReferenceExpression(typeof(HostingEnvironment))
                     },
                     Parameters = {
                        new CodeVariableReferenceExpression(virtualPathVar.Name)
                     }
                  },
                  new CodePropertyReferenceExpression {
                     PropertyName = "Absolute",
                     TargetObject = new CodeTypeReferenceExpression(typeof(UriKind))
                  }
               }
            }
         };
         
			CodeTryCatchFinallyStatement trySt = new CodeTryCatchFinallyStatement ();
			trySt.TryStatements.Add (new CodeAssignStatement {
            Left = new CodeVariableReferenceExpression(sourceVar.Name),
            Right = new CodeCastExpression {
               TargetType = new CodeTypeReference(typeof(Stream)),
               Expression = new CodeMethodInvokeExpression {
                  Method = new CodeMethodReferenceExpression {
                     MethodName = "OpenRead",
                     TargetObject = new CodeTypeReferenceExpression(typeof(File))
                  },
                  Parameters = { 
                     new CodePropertyReferenceExpression {
                        PropertyName = "LocalPath",
                        TargetObject = new CodeVariableReferenceExpression(sourceUriVar.Name)
                     }
                  }
               }
            }
         });

			CodeVariableDeclarationStatement optionsVar = new CodeVariableDeclarationStatement {
            Name = "options",
            Type = new CodeTypeReference(typeof(XQueryCompileOptions)),
         };
			optionsVar.InitExpression = new CodeObjectCreateExpression (optionsVar.Type);

			trySt.TryStatements.Add (optionsVar);
			trySt.TryStatements.Add (new CodeAssignStatement {
            Left = new CodePropertyReferenceExpression {
               PropertyName = "BaseUri",
               TargetObject = new CodeVariableReferenceExpression(optionsVar.Name)
            },
            Right = new CodeVariableReferenceExpression(sourceUriVar.Name)
         });
			trySt.TryStatements.Add (new CodeAssignStatement {
            Left = new CodeFieldReferenceExpression {
               FieldName = executableField.Name,
               TargetObject = PageTypeReferenceExpression
            },
            Right = new CodeMethodInvokeExpression { 
               Method = new CodeMethodReferenceExpression {
                  MethodName = "Compile",
                  TargetObject = new CodeVariableReferenceExpression(procVar.Name)
               },
               Parameters = {
                  new CodeVariableReferenceExpression(sourceVar.Name),
                  new CodeVariableReferenceExpression(optionsVar.Name)
               }
            }
         });

			CodeConditionStatement disposeIf = new CodeConditionStatement {
            Condition = new CodeBinaryOperatorExpression {
               Left = new CodeVariableReferenceExpression(sourceVar.Name),
               Operator = CodeBinaryOperatorType.IdentityInequality,
               Right = new CodePrimitiveExpression(null)
            }
         };
			disposeIf.TrueStatements.Add (new CodeMethodInvokeExpression (
            new CodeMethodReferenceExpression {
               MethodName = "Dispose",
               TargetObject = new CodeVariableReferenceExpression(sourceVar.Name)
            }
			));

			trySt.FinallyStatements.Add (disposeIf);

			statements.AddRange (new CodeStatement[] {
                procVar,
                sourceVar,
                virtualPathVar,
                sourceUriVar,
                trySt
            });
		}
Esempio n. 26
0
		protected override void GenerateTryCatchFinallyStatement (CodeTryCatchFinallyStatement statement)
		{
			TextWriter output = Output;
			CodeGeneratorOptions options = Options;

			output.Write ("try");
			OutputStartBrace ();
			++Indent;
			GenerateStatements (statement.TryStatements);
			--Indent;
			
			foreach (CodeCatchClause clause in statement.CatchClauses) {
				output.Write ('}');
				if (options.ElseOnClosing)
					output.Write (' ');
				else
					output.WriteLine ();
				output.Write ("catch (");
				OutputTypeNamePair (clause.CatchExceptionType, GetSafeName(clause.LocalName));
				output.Write (")");
				OutputStartBrace ();
				++Indent;
				GenerateStatements (clause.Statements);
				--Indent;
			}

			CodeStatementCollection finallies = statement.FinallyStatements;
			if (finallies.Count > 0) {
				output.Write ('}');
				if (options.ElseOnClosing)
					output.Write (' ');
				else
					output.WriteLine ();
				output.Write ("finally");
				OutputStartBrace ();
				++Indent;
				GenerateStatements (finallies);
				--Indent;
			}

			output.WriteLine('}');
		}
Esempio n. 27
0
 protected override void GenerateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e)
 {
     base.Output.WriteLine("Try ");
     base.Indent++;
     this.GenerateVBStatements(e.TryStatements);
     base.Indent--;
     CodeCatchClauseCollection catchClauses = e.CatchClauses;
     if (catchClauses.Count > 0)
     {
         IEnumerator enumerator = catchClauses.GetEnumerator();
         while (enumerator.MoveNext())
         {
             CodeCatchClause current = (CodeCatchClause)enumerator.Current;
             base.Output.Write("Catch ");
             this.OutputTypeNamePair(current.CatchExceptionType, current.LocalName);
             base.Output.WriteLine("");
             base.Indent++;
             this.GenerateVBStatements(current.Statements);
             base.Indent--;
         }
     }
     CodeStatementCollection finallyStatements = e.FinallyStatements;
     if (finallyStatements.Count > 0)
     {
         base.Output.WriteLine("Finally");
         base.Indent++;
         this.GenerateVBStatements(finallyStatements);
         base.Indent--;
     }
     base.Output.WriteLine("End Try");
 }
Esempio n. 28
0
        private void ValidateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e) {
            ValidateStatements(e.TryStatements);
            CodeCatchClauseCollection catches = e.CatchClauses;
            if (catches.Count > 0) {
                IEnumerator en = catches.GetEnumerator();
                while (en.MoveNext()) {
                    CodeCatchClause current = (CodeCatchClause)en.Current;
                    ValidateTypeReference(current.CatchExceptionType);
                    ValidateIdentifier(current,"LocalName",current.LocalName);
                    ValidateStatements(current.Statements);
                }
            }

            CodeStatementCollection finallyStatements = e.FinallyStatements;
            if (finallyStatements.Count > 0) {
                ValidateStatements(finallyStatements);
            }
        }
		protected override void GenerateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e)
		{
			Output.WriteLine("[CodeTryCatchFinallyStatement: {0}]", e.ToString());
		}
        /// <summary>
        /// Gets the Silverlight save to isolate storage file.
        /// </summary>
        /// <param name="type">CodeTypeDeclaration type.</param>
        /// <returns>return the save to file code DOM method statment </returns>
        protected override CodeMemberMethod GetSaveToFileMethod()
        {
            // -----------------------------------------------
            // public virtual void SaveToFile(string fileName)
            // -----------------------------------------------
            var saveToFileMethod = new CodeMemberMethod
            {
                Attributes = MemberAttributes.Public,
                Name = GeneratorContext.GeneratorParams.Serialization.SaveToFileMethodName
            };

            saveToFileMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "fileName"));

            if (GeneratorContext.GeneratorParams.Serialization.EnableEncoding)
            {
                saveToFileMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Encoding), "encoding"));
            }

            saveToFileMethod.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeTypeReference(typeof(StreamWriter)),
                    "streamWriter",
                    new CodePrimitiveExpression(null)));

            saveToFileMethod.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeTypeReference(typeof(IsolatedStorageFile)),
                    "isoFile",
                    new CodePrimitiveExpression(null)));

            saveToFileMethod.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeTypeReference(typeof(IsolatedStorageFileStream)),
                    "isoStream",
                    new CodePrimitiveExpression(null)));

            // ------------------------
            // try {...} finally {...}
            // -----------------------
            var tryExpression = new CodeStatementCollection();

            tryExpression.Add(
                new CodeAssignStatement(
                new CodeVariableReferenceExpression("isoFile"),
                CodeDomHelper.GetInvokeMethod("IsolatedStorageFile", "GetUserStoreForApplication")));

            tryExpression.Add(
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("isoStream"),
                    new CodeObjectCreateExpression(
                        typeof(IsolatedStorageFileStream),
                        new CodeExpression[]
                        {
                             new CodeArgumentReferenceExpression("fileName"),
                             CodeDomHelper.GetEnum("FileMode","Create"),
                             new CodeVariableReferenceExpression("isoFile")
                    })));

            tryExpression.Add(
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("streamWriter"),
                    new CodeObjectCreateExpression(
                        typeof(StreamWriter),
                        new CodeExpression[]
                        {
                            new CodeVariableReferenceExpression("isoStream"),
                    })));
            // ---------------------------------------
            // string xmlString = Serialize(encoding);
            // ---------------------------------------

            CodeMethodInvokeExpression serializeMethodInvoke;
            if (GeneratorContext.GeneratorParams.Serialization.EnableEncoding)
            {
                serializeMethodInvoke = new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(null,
                                                      GeneratorContext.GeneratorParams.Serialization.SerializeMethodName),
                    new CodeExpression[] { new CodeArgumentReferenceExpression("encoding") });
            }
            else
            {
                serializeMethodInvoke = new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(null,
                                                      GeneratorContext.GeneratorParams.Serialization.SerializeMethodName));
            }

            var xmlString = new CodeVariableDeclarationStatement(
                new CodeTypeReference(typeof(string)), "xmlString", serializeMethodInvoke);

            tryExpression.Add(xmlString);

            if (GeneratorContext.GeneratorParams.Serialization.EnableEncoding)
            {
                // ----------------------------------------------------------------
                // streamWriter = new StreamWriter(fileName, false, Encoding.UTF8);
                // ----------------------------------------------------------------
                tryExpression.Add(new CodeAssignStatement(
                                      new CodeVariableReferenceExpression("streamWriter"),
                                      new CodeObjectCreateExpression(
                                          typeof(StreamWriter),
                                          new CodeExpression[]
                                              {
                                                  new CodeSnippetExpression("fileName"),
                                                  new CodeSnippetExpression("false"),
                                                  new CodeSnippetExpression(GeneratorContext.GeneratorParams.Serialization.GetEncoderString())
                        })));
            }
            else
            {
                // --------------------------------------------------------------
                // System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
                // --------------------------------------------------------------
                tryExpression.Add(CodeDomHelper.CreateObject(typeof(FileInfo), "xmlFile", new[] { "fileName" }));

                // ----------------------------------------
                // StreamWriter Tex = xmlFile.CreateText();
                // ----------------------------------------
                var createTextMethodInvoke = CodeDomHelper.GetInvokeMethod("xmlFile", "CreateText");

                tryExpression.Add(
                    new CodeAssignStatement(
                        new CodeVariableReferenceExpression("streamWriter"),
                        createTextMethodInvoke));
            }
            // ----------------------------------
            // streamWriter.WriteLine(xmlString);
            // ----------------------------------
            var writeLineMethodInvoke =
                CodeDomHelper.GetInvokeMethod(
                                                "streamWriter",
                                                "WriteLine",
                                                new CodeExpression[]
                                                  {
                                                      new CodeVariableReferenceExpression("xmlString")
                                                  });

            tryExpression.Add(writeLineMethodInvoke);
            tryExpression.Add(CodeDomHelper.GetInvokeMethod("streamWriter", "Close"));
            tryExpression.Add(CodeDomHelper.GetInvokeMethod("isoStream", "Close"));

            var finallyStatmanentsCol = new CodeStatementCollection();
            finallyStatmanentsCol.Add(CodeDomHelper.GetDispose("streamWriter"));
            finallyStatmanentsCol.Add(CodeDomHelper.GetDispose("isoFile"));
            finallyStatmanentsCol.Add(CodeDomHelper.GetDispose("isoStream"));

            var trycatch = new CodeTryCatchFinallyStatement(tryExpression.ToArray(), new CodeCatchClause[0], finallyStatmanentsCol.ToArray());
            saveToFileMethod.Statements.Add(trycatch);

            return saveToFileMethod;
        }
        public override object Visit(TryCatchStatement tryCatchStatement, object data)
        {
            ProcessSpecials(tryCatchStatement.Specials);

            // add a try-catch-finally
            CodeTryCatchFinallyStatement tryStmt = new CodeTryCatchFinallyStatement();

            codeStack.Push(tryStmt.TryStatements);
            ProcessSpecials(tryCatchStatement.StatementBlock.Specials);
            tryCatchStatement.StatementBlock.AcceptChildren(this, data);
            codeStack.Pop();

            if (tryCatchStatement.FinallyBlock != null)
            {
                codeStack.Push(tryStmt.FinallyStatements);
                ProcessSpecials(tryCatchStatement.FinallyBlock.Specials);
                tryCatchStatement.FinallyBlock.AcceptChildren(this,data);
                codeStack.Pop();
            }

            if (tryCatchStatement.CatchClauses != null)
            {
                foreach (CatchClause clause in tryCatchStatement.CatchClauses)
                {
                    CodeCatchClause catchClause = new CodeCatchClause(clause.VariableName);
                    catchClause.CatchExceptionType = new CodeTypeReference(clause.Type);
                    tryStmt.CatchClauses.Add(catchClause);

                    codeStack.Push(catchClause.Statements);
                    ProcessSpecials(clause.StatementBlock.Specials);
                    clause.StatementBlock.AcceptChildren(this, data);
                    codeStack.Pop();
                }
            }

            // Add Statement to Current Statement Collection
            AddStmt(tryStmt);

            return tryStmt;
        }
Esempio n. 32
0
        public async System.Threading.Tasks.Task GCode_CodeDom_GenerateMethodCode(CodeTypeDeclaration codeClass, LinkPinControl element, GenerateCodeContext_Class context, MethodGenerateData data)
        {
            var csParam = CSParam as MethodOverrideConstructParam;

            Type[] paramTypes = new Type[csParam.MethodInfo.Params.Count];
            for (int i = 0; i < paramTypes.Length; i++)
            {
                switch (csParam.MethodInfo.Params[i].FieldDirection)
                {
                case FieldDirection.In:
                    if (csParam.MethodInfo.Params[i].IsParamsArray)
                    {
                        throw new InvalidOperationException("未实现");
                    }
                    else
                    {
                        paramTypes[i] = csParam.MethodInfo.Params[i].ParameterType;
                    }
                    break;

                case FieldDirection.Out:
                case FieldDirection.Ref:
                    if (csParam.MethodInfo.Params[i].IsParamsArray)
                    {
                        throw new InvalidOperationException("未实现");
                    }
                    else
                    {
                        paramTypes[i] = csParam.MethodInfo.Params[i].ParameterType.MakeByRefType();
                    }
                    break;
                }
            }
            EngineNS.Editor.MacrossMemberAttribute.enMacrossType macrossType = EngineNS.Editor.MacrossMemberAttribute.enMacrossType.Overrideable;
            if (csParam.MethodInfo.IsFromMacross)
            {
                macrossType |= EngineNS.Editor.MacrossMemberAttribute.enMacrossType.Callable;
            }
            else
            {
                var methodInfo = csParam.MethodInfo.ParentClassType.GetMethod(csParam.MethodInfo.MethodName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static, null, paramTypes, null);
                var atts       = methodInfo.GetCustomAttributes(typeof(EngineNS.Editor.MacrossMemberAttribute), false);
                if (atts.Length > 0)
                {
                    var macrossMemberAtt = atts[0] as EngineNS.Editor.MacrossMemberAttribute;
                    macrossType = macrossMemberAtt.MacrossType;
                }
            }

            if (element == null || element == mCtrlMethodPin_Next)
            {
                var methodCode = new CodeGenerateSystem.CodeDom.CodeMemberMethod();
                methodCode.Attributes = MemberAttributes.Override;
                //if (mMethodInfo != null)
                //{
                if (csParam.MethodInfo.IsFamily)
                {
                    methodCode.Attributes |= MemberAttributes.Family;
                }
                if (csParam.MethodInfo.IsFamilyAndAssembly)
                {
                    methodCode.Attributes |= MemberAttributes.FamilyAndAssembly;
                }
                if (csParam.MethodInfo.IsFamilyOrAssembly)
                {
                    methodCode.Attributes |= MemberAttributes.FamilyOrAssembly;
                }
                if (csParam.MethodInfo.IsPublic)
                {
                    methodCode.Attributes |= MemberAttributes.Public;
                }
                //}
                //else
                //    methodCode.Attributes |= MemberAttributes.Public;
                methodCode.Name = NodeName;

                var mcType = EngineNS.Editor.MacrossMemberAttribute.enMacrossType.Unknow;
                if (csParam.MethodInfo.MC_Callable)
                {
                    mcType = mcType | EngineNS.Editor.MacrossMemberAttribute.enMacrossType.Callable;
                }
                if (csParam.MethodInfo.MC_Overrideable)
                {
                    mcType = mcType | EngineNS.Editor.MacrossMemberAttribute.enMacrossType.Overrideable;
                }
                if (mcType != EngineNS.Editor.MacrossMemberAttribute.enMacrossType.Unknow)
                {
                    methodCode.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(EngineNS.Editor.MacrossMemberAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression(mcType))));
                }

                if (data != null)
                {
                    foreach (var localParam in data.LocalParams)
                    {
                        var defVal  = CodeGenerateSystem.Program.GetDefaultValueFromType(localParam.ParamType);
                        var initExp = Program.GetValueCode(methodCode.Statements, localParam.ParamType, defVal);
                        methodCode.Statements.Add(new CodeVariableDeclarationStatement(localParam.ParamType, localParam.ParamName, initExp));
                    }
                }

                string paramPreStr = "temp___";
                //bool needUnsafeFlag = false;
                string catchParamName = "(";
                foreach (var paramNode in mChildNodes)
                {
                    var paramExp = new System.CodeDom.CodeParameterDeclarationExpression();
                    if (paramNode is MethodInvokeParameterControl)
                    {
                        var pm      = paramNode as MethodInvokeParameterControl;
                        var pmParam = pm.CSParam as MethodInvokeParameterControl.MethodInvokeParameterConstructionParams;
                        paramExp.Direction = pm.ParamFlag;
                        if (pmParam.ParamInfo.ParameterDisplayType != null)
                        {
                            paramExp.Name = paramPreStr + pmParam.ParamInfo.ParamName;
                            paramExp.Type = new CodeTypeReference(pmParam.ParamInfo.ParameterType);
                        }
                        else
                        {
                            paramExp.Name = pmParam.ParamInfo.ParamName;
                            paramExp.Type = new System.CodeDom.CodeTypeReference(pm.ParamType);
                        }

                        //if (pm.ParamType.IsPointer)
                        //    needUnsafeFlag = true;
                    }
                    else if (paramNode is ParamParameterControl)
                    {
                        var pm = paramNode as ParamParameterControl;
                        paramExp.Name = pm.ParamName;
                        paramExp.Type = new System.CodeDom.CodeTypeReference(pm.ParamType);

                        //if (pm.ParamType.IsPointer)
                        //    needUnsafeFlag = true;
                    }
                    else if (paramNode is MethodInvoke_DelegateControl)
                    {
                        var pm = paramNode as MethodInvoke_DelegateControl;
                        paramExp.Name = pm.ParamName;
                        paramExp.Type = new System.CodeDom.CodeTypeReference(pm.ParamType);
                    }

                    methodCode.Parameters.Add(paramExp);
                    catchParamName += paramExp.Type + " " + paramExp.Name + ",";
                }
                // 所有函数全部unsafe
                //if (needUnsafeFlag)
                {
                    //var typeName = MethodReturnType.FullName;
                    methodCode.ReturnType = new CodeTypeReference(MethodReturnType);
                    if (MethodReturnType == typeof(System.Threading.Tasks.Task) || MethodReturnType.BaseType == typeof(System.Threading.Tasks.Task))
                    {
                        methodCode.IsAsync = true;
                    }
                    else
                    {
                        if (EngineNS.Editor.MacrossMemberAttribute.HasType(macrossType, EngineNS.Editor.MacrossMemberAttribute.enMacrossType.Unsafe))
                        {
                            methodCode.IsUnsafe = true;
                        }
                    }
                }
                //else
                //    methodCode.ReturnType = new CodeTypeReference(MethodReturnType);

                catchParamName  = catchParamName.TrimEnd(',');
                catchParamName += ")";

                var tryCatchExp = new System.CodeDom.CodeTryCatchFinallyStatement();
                tryCatchExp.TryStatements.Add(new CodeGenerateSystem.CodeDom.CodeMethodInvokeExpression(new CodeVariableReferenceExpression(context.ScopFieldName), "Begin", new CodeExpression[0]));
                var exName = "ex_" + EngineNS.Editor.Assist.GetValuedGUIDString(Id);
                var cah    = new System.CodeDom.CodeCatchClause(exName);
                cah.Statements.Add(new System.CodeDom.CodeExpressionStatement(
                                       new CodeGenerateSystem.CodeDom.CodeMethodInvokeExpression(
                                           new System.CodeDom.CodeSnippetExpression("EngineNS.Profiler.Log"), "WriteException",
                                           new System.CodeDom.CodeVariableReferenceExpression(exName),
                                           new CodePrimitiveExpression("Macross异常"))));
                tryCatchExp.CatchClauses.Add(cah);
                tryCatchExp.FinallyStatements.Add(new CodeGenerateSystem.CodeDom.CodeMethodInvokeExpression(new CodeVariableReferenceExpression(context.ScopFieldName), "End", new CodeExpression[0]));

                string paramComment = "";
                // 设置out参数默认值
                foreach (var param in csParam.MethodInfo.Params)
                {
                    if (param.ParameterDisplayType != null)
                    {
                        if (param.FieldDirection == FieldDirection.Out)
                        {
                            methodCode.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(paramPreStr + param.ParamName),
                                                                              new CodePrimitiveExpression(CodeGenerateSystem.Program.GetDefaultValueFromType(param.ParameterType))));
                        }
                        methodCode.Statements.Add(new CodeVariableDeclarationStatement(param.ParameterDisplayType, param.ParamName, new CodeGenerateSystem.CodeDom.CodeCastExpression(param.ParameterDisplayType, new CodeVariableReferenceExpression(paramPreStr + param.ParamName))));
                    }
                    else
                    {
                        if (param.FieldDirection == FieldDirection.Out)
                        {
                            methodCode.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(param.ParamName),
                                                                              new CodePrimitiveExpression(CodeGenerateSystem.Program.GetDefaultValueFromType(param.ParameterType))));
                        }
                    }

                    paramComment += param.FieldDirection + "," + param.ParameterType.FullName + "|";
                }
                paramComment = paramComment.TrimEnd('|');

                methodCode.Statements.Add(tryCatchExp);
                foreach (var param in csParam.MethodInfo.Params)
                {
                    // ref或out,需要将displayType造成的临时变量再赋给原函数参数
                    if ((param.FieldDirection == FieldDirection.Out || param.FieldDirection == FieldDirection.Ref) && param.ParameterDisplayType != null)
                    {
                        methodCode.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression(paramPreStr + param.ParamName), new CodeGenerateSystem.CodeDom.CodeCastExpression(param.ParameterType, new CodeVariableReferenceExpression(param.ParamName))));
                    }
                }

                if (csParam.MethodInfo.ReturnType != typeof(void) && csParam.MethodInfo.ReturnType != typeof(System.Threading.Tasks.Task))
                {
                    var retVal = CodeGenerateSystem.Program.GetDefaultValueFromType(csParam.MethodInfo.ReturnType);
                    methodCode.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(retVal)));
                }


                if (csParam.MethodInfo.IsFromMacross)
                {
                    codeClass.Members.Add(new CodeSnippetTypeMember($"// OverrideStart {csParam.MethodInfo.FuncId.ToString()} {NodeName} {paramComment}"));
                    codeClass.Members.Add(new CodeSnippetTypeMember("#pragma warning disable 1998"));
                    codeClass.Members.Add(methodCode);
                    codeClass.Members.Add(new CodeSnippetTypeMember("#pragma warning restore 1998"));
                    codeClass.Members.Add(new CodeSnippetTypeMember($"// OverrideEnd {csParam.MethodInfo.FuncId.ToString()} {NodeName}"));
                }
                else
                {
                    codeClass.Members.Add(new CodeSnippetTypeMember($"// OverrideStart {NodeName} {paramComment}"));
                    codeClass.Members.Add(new CodeSnippetTypeMember("#pragma warning disable 1998"));
                    codeClass.Members.Add(methodCode);
                    codeClass.Members.Add(new CodeSnippetTypeMember("#pragma warning restore 1998"));
                    codeClass.Members.Add(new CodeSnippetTypeMember($"// OverrideEnd {NodeName}"));
                }

                var methodContext = new CodeGenerateSystem.Base.GenerateCodeContext_Method(context, methodCode);
                // 收集用于调试的数据的代码
                var debugCodes = CodeDomNode.BreakPoint.BeginMacrossDebugCodeStatments(tryCatchExp.TryStatements);
                foreach (var paramNode in mChildNodes)
                {
                    if (paramNode is MethodInvokeParameterControl)
                    {
                        var paramCtrl = paramNode as MethodInvokeParameterControl;
                        CodeDomNode.BreakPoint.GetGatherDataValueCodeStatement(debugCodes, paramCtrl.ParamPin.GetLinkPinKeyName(), paramCtrl.GCode_CodeDom_GetValue(paramCtrl.ParamPin, methodContext), paramCtrl.GCode_GetTypeString(paramCtrl.ParamPin, methodContext), methodContext);
                    }
                    else if (paramNode is ParamParameterControl)
                    {
                        throw new InvalidOperationException();
                    }
                }
                // 断点
                var breakCondStatement = CodeDomNode.BreakPoint.BreakCodeStatement(codeClass, debugCodes, HostNodesContainer.GUID, Id);
                // 设置数据
                foreach (var paramNode in mChildNodes)
                {
                    if (paramNode is MethodInvokeParameterControl)
                    {
                        var paramCtrl = paramNode as MethodInvokeParameterControl;
                        CodeDomNode.BreakPoint.GetSetDataValueCodeStatement(breakCondStatement.TrueStatements, paramCtrl.ParamPin.GetLinkPinKeyName(), paramCtrl.GCode_CodeDom_GetValue(paramCtrl.ParamPin, methodContext), paramCtrl.GCode_GetType(paramCtrl.ParamPin, methodContext));
                    }
                    else if (paramNode is ParamParameterControl)
                    {
                        throw new InvalidOperationException();
                    }
                }
                CodeDomNode.BreakPoint.EndMacrossDebugCodeStatements(tryCatchExp.TryStatements, debugCodes);

                if (mCtrlMethodPin_Next.HasLink)
                {
                    methodContext.ReturnValueType = MethodReturnType;
                    await mCtrlMethodPin_Next.GetLinkedObject(0, false).GCode_CodeDom_GenerateCode(codeClass, tryCatchExp.TryStatements, mCtrlMethodPin_Next.GetLinkedPinControl(0, false), methodContext);
                }
            }
        }