Exemplo n.º 1
0
		public void Ctor_String(string localName)
		{
			var catchClause = new CodeCatchClause(localName);
			Assert.Equal(localName ?? string.Empty, catchClause.LocalName);
			Assert.Equal(typeof(Exception).ToString(), catchClause.CatchExceptionType.BaseType);
			Assert.Empty(catchClause.Statements);
		}
Exemplo n.º 2
0
		public void Ctor_String_CodeTypeReference_ParamsCodeStatement(string localName, CodeTypeReference catchExceptionType, CodeStatement[] statements)
		{
			var catchClause = new CodeCatchClause(localName, catchExceptionType, statements);
			Assert.Equal(localName ?? string.Empty, catchClause.LocalName);
			Assert.Equal((catchExceptionType ?? new CodeTypeReference(typeof(Exception))).BaseType, catchClause.CatchExceptionType.BaseType);
			Assert.Equal(statements, catchClause.Statements.Cast<CodeStatement>());
		}
Exemplo n.º 3
0
		public void Ctor_Default()
		{
			var catchClause = new CodeCatchClause();
			Assert.Empty(catchClause.LocalName);
			Assert.Empty(catchClause.Statements);

			Assert.Equal(new CodeTypeReference(typeof(Exception)).BaseType, catchClause.CatchExceptionType.BaseType);
		}
        public CodeCatchClause[] ToCodeDomArray()
        {
            CodeCatchClause[] cc = new CodeCatchClause[this.Count];
            int i = 0;

            foreach (CatchClause st in this)
            {
                cc[i++] = st.ToCodeDom();
            }
            return(cc);
        }
Exemplo n.º 5
0
        public void Constructor2_Deny_Unrestricted()
        {
            CodeTypeReference ctr = new CodeTypeReference("System.Void");
            CodeCatchClause   ccc = new CodeCatchClause("mono", ctr);

            Assert.AreEqual("System.Void", ccc.CatchExceptionType.BaseType, "CatchExceptionType.BaseType");
            ccc.CatchExceptionType = new CodeTypeReference("System.Int32");
            Assert.AreEqual("mono", ccc.LocalName, "LocalName");
            ccc.LocalName = String.Empty;
            Assert.AreEqual(0, ccc.Statements.Count, "Statements");
        }
Exemplo n.º 6
0
        /// <summary>
        /// Creates a method that finds a row containing the given elements of an index.
        /// </summary>
        /// <param name="uniqueConstraintSchema">A description of a unique constraint.</param>
        public FindByKeyMethod(UniqueConstraintSchema uniqueConstraintSchema)
        {
            //        /// <summary>
            //        /// Finds a row in the Configuration table containing the key elements.
            //        /// </summary>
            //        /// <param name="key">An array of key elements.</param>
            //        /// <returns>A ConfigurationKey row that contains the key elements, or null if there is no match.</returns>
            //        public new ConfigurationRow Find(object[] key) {
            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement(string.Format("Finds a row in the {0} table containing the key elements.", uniqueConstraintSchema.Table.Name), true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            this.Comments.Add(new CodeCommentStatement("<param name=\"key\">An array of key elements.</param>", true));
            this.Comments.Add(new CodeCommentStatement(string.Format("<returns>A {0} row that contains the key elements, or null if there is no match.</returns>", uniqueConstraintSchema.Name), true));
            this.Attributes = MemberAttributes.Public | MemberAttributes.New | MemberAttributes.Final;
            this.ReturnType = new CodeTypeReference(string.Format("{0}Row", uniqueConstraintSchema.Table.Name));
            this.Name       = "Find";
            this.Parameters.Add(new CodeParameterDeclarationExpression(new CodeGlobalTypeReference(typeof(System.Object[])), "key"));

            //            try {
            //                DataModel.Configuration.AcquireLock();
            //                return ((ConfigurationRow)(base.Find(key)));
            //            }
            //            catch (global::System.ArgumentException argumentException) {
            //                throw new global::System.ServiceModel.FaultException<ArgumentFault>(new global::FluidTrade.Core.ArgumentFault(argumentException.Message));
            //            }
            //            finally {
            //                DataModel.Configuration.ReleaseLock();
            //            }
            CodeTryCatchFinallyStatement    tryCatchFinallyStatement = new CodeTryCatchFinallyStatement();
            CodePropertyReferenceExpression tableExpression          = new CodePropertyReferenceExpression(
                new CodeTypeReferenceExpression(string.Format("{0}", uniqueConstraintSchema.Table.DataModel.Name)), uniqueConstraintSchema.Table.Name);

            tryCatchFinallyStatement.TryStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(uniqueConstraintSchema.Table.DataModel.Name), "DataLock"),
                    "EnterReadLock"));
            tryCatchFinallyStatement.TryStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(this.ReturnType, new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), "Find", new CodeArgumentReferenceExpression("key")))));
            CodeCatchClause catchArgumentException = new CodeCatchClause("argumentException", new CodeGlobalTypeReference(typeof(System.ArgumentException)));

            catchArgumentException.Statements.Add(new CodeThrowArgumentExceptionStatement(new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("argumentException"), "Message")));
            tryCatchFinallyStatement.CatchClauses.Add(catchArgumentException);
            CodeCatchClause catchFormatException = new CodeCatchClause("formatException", new CodeGlobalTypeReference(typeof(System.FormatException)));

            catchFormatException.Statements.Add(new CodeThrowFormatExceptionStatement(new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("formatException"), "Message")));
            tryCatchFinallyStatement.CatchClauses.Add(catchFormatException);
            tryCatchFinallyStatement.FinallyStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(uniqueConstraintSchema.Table.DataModel.Name), "DataLock"),
                    "ExitReadLock"));
            this.Statements.Add(tryCatchFinallyStatement);

            //        }
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        private CodeMemberMethod Set_DefaultNodeConfig_Tree()
        {
            CodeMemberMethod           Set_DefaultNodeConfig_Tree = null;
            CodeMethodInvokeExpression MethodInvokation           = null;

            try
            {
                Set_DefaultNodeConfig_Tree = new CodeMemberMethod
                {
                    Name       = "Set_DefaultNodeConfig_Tree",
                    Attributes = MemberAttributes.Public | MemberAttributes.Final,
                    ReturnType = new CodeTypeReference(typeof(Object))
                };

                //try block
                CodeTryCatchFinallyStatement tryblock = AddTryBlock(Set_DefaultNodeConfig_Tree);

                IEnumerable <IGrouping <string, Tree> > treeGroups = _ilbo.Trees.GroupBy(t => t.Name);

                foreach (IGrouping <string, Tree> treeGrp in treeGroups)
                {
                    Tree tree = treeGrp.First();

                    foreach (TreeInfo treeinfo in tree.Info)
                    {
                        tryblock.AddStatement(MethodInvocationExp(TypeReferenceExp("oDefaultNTConfig"), "Add").AddParameters(new Object[] { Convert.ToString(treeinfo.OpenImage), string.Format("{0}~~{1}~~{2}", tree.Name, treeinfo.NodeType, "vwt_openimage") }));
                        tryblock.AddStatement(MethodInvocationExp(TypeReferenceExp("oDefaultNTConfig"), "Add").AddParameters(new Object[] { Convert.ToString(treeinfo.NotExpandedImage), string.Format("{0}~~{1}~~{2}", tree.Name, treeinfo.NodeType, "vwt_notexpandedimage") }));
                        tryblock.AddStatement(MethodInvocationExp(TypeReferenceExp("oDefaultNTConfig"), "Add").AddParameters(new Object[] { Convert.ToString(treeinfo.ExpandableImage), string.Format("{0}~~{1}~~{2}", tree.Name, treeinfo.NodeType, "vwt_expandableimage") }));
                        tryblock.AddStatement(MethodInvocationExp(TypeReferenceExp("oDefaultNTConfig"), "Add").AddParameters(new Object[] { Convert.ToString(treeinfo.ExpandedImage), string.Format("{0}~~{1}~~{2}", tree.Name, treeinfo.NodeType, "vwt_expandedimage") }));
                        tryblock.AddStatement(MethodInvocationExp(TypeReferenceExp("oDefaultNTConfig"), "Add").AddParameters(new Object[] { Convert.ToString(treeinfo.CloseImage), string.Format("{0}~~{1}~~{2}", tree.Name, treeinfo.NodeType, "vwt_closeimage") }));
                        tryblock.AddStatement(MethodInvocationExp(TypeReferenceExp("oDefaultNTConfig"), "Add").AddParameters(new Object[] { Convert.ToString(treeinfo.CheckImage), string.Format("{0}~~{1}~~{2}", tree.Name, treeinfo.NodeType, "vwt_checkimage") }));
                        tryblock.AddStatement(MethodInvocationExp(TypeReferenceExp("oDefaultNTConfig"), "Add").AddParameters(new Object[] { Convert.ToString(treeinfo.UnCheckImage), string.Format("{0}~~{1}~~{2}", tree.Name, treeinfo.NodeType, "vwt_uncheckimage") }));
                        tryblock.AddStatement(MethodInvocationExp(TypeReferenceExp("oDefaultNTConfig"), "Add").AddParameters(new Object[] { Convert.ToString(treeinfo.PartialCheckImage), string.Format("{0}~~{1}~~{2}", tree.Name, treeinfo.NodeType, "chkbox_parial_chkimg") }));
                    }
                }

                tryblock.TryStatements.Add(ReturnExpression(SnippetExpression("null")));

                //catch block
                CodeCatchClause catchblock = AddCatchBlock(tryblock);

                MethodInvokation = MethodInvocationExp(TypeReferenceExp("Trace"), "WriteLineIf");
                AddParameters(MethodInvokation, new Object[] { PrimitiveExpression(false), PrimitiveExpression("Set_DefaultNodeConfig_Tree"), SnippetExpression("e.Message.ToString()") });
                catchblock.Statements.Add(MethodInvokation);

                catchblock.Statements.Add(ReturnExpression(SnippetExpression("null")));
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("GenerateTreeClass.Set_DefaultNodeConfig_Tree()->{0}", !object.Equals(ex.InnerException, null) ? ex.InnerException.Message : ex.Message));
            }
            return(Set_DefaultNodeConfig_Tree);
        }
        internal static CodeCatchClause Catch(CodeTypeReference type, string name, CodeStatement catchStmnt)
        {
            CodeCatchClause clause = new CodeCatchClause {
                CatchExceptionType = type,
                LocalName          = name
            };

            if (catchStmnt != null)
            {
                clause.Statements.Add(catchStmnt);
            }
            return(clause);
        }
        public void Constructor1()
        {
            CodeCatchClause cc1 = new CodeCatchClause();
            CodeCatchClause cc2 = new CodeCatchClause();

            CodeCatchClause[]         catchClauses = new CodeCatchClause[] { cc1, cc2 };
            CodeCatchClauseCollection coll         = new CodeCatchClauseCollection(
                catchClauses);

            Assert.AreEqual(2, coll.Count, "#1");
            Assert.AreEqual(0, coll.IndexOf(cc1), "#2");
            Assert.AreEqual(1, coll.IndexOf(cc2), "#3");
        }
        public static CodeCatchClause Clone(this CodeCatchClause clause)
        {
            if (clause == null)
            {
                return(null);
            }
            CodeCatchClause c = new CodeCatchClause();

            c.CatchExceptionType = clause.CatchExceptionType.Clone();
            c.LocalName          = clause.LocalName;
            c.Statements.AddRange(clause.Statements.Clone());
            return(c);
        }
        public void CatchClauses_AddMultiple_ReturnsExpected()
        {
            var tryCatchFinally = new CodeTryCatchFinallyStatement();

            CodeCatchClause catchClause1 = new CodeCatchClause("Local1");

            tryCatchFinally.CatchClauses.Add(catchClause1);
            Assert.Equal(new CodeCatchClause[] { catchClause1 }, tryCatchFinally.CatchClauses.Cast <CodeCatchClause>());

            CodeCatchClause catchClause2 = new CodeCatchClause("Local2");

            tryCatchFinally.CatchClauses.Add(catchClause2);
            Assert.Equal(new CodeCatchClause[] { catchClause1, catchClause2 }, tryCatchFinally.CatchClauses.Cast <CodeCatchClause>());
        }
Exemplo n.º 12
0
        void VisitCodeCatchClause(CodeCatchClause catchClause)
        {
            WriteLine("VisitCodeCatchClause");
            WriteLine("Exception caught: " + catchClause.CatchExceptionType.BaseType);
            WriteLine("Exception variable: " + catchClause.LocalName);

            WriteLine("Catch statements follow: Count: " + catchClause.Statements.Count);
            using (IDisposable currentLevel = Indentation.IncrementLevel()) {
                foreach (CodeStatement statement in catchClause.Statements)
                {
                    VisitCodeStatement(statement);
                }
            }
        }
Exemplo n.º 13
0
        public void Statements_AddMultiple_ReturnsExpected()
        {
            var catchClause = new CodeCatchClause();

            CodeStatement statement1 = new CodeCommentStatement("Value1");

            catchClause.Statements.Add(statement1);
            Assert.Equal(new CodeStatement[] { statement1 }, catchClause.Statements.Cast <CodeStatement>());

            CodeStatement statement2 = new CodeCommentStatement("Value1");

            catchClause.Statements.Add(statement2);
            Assert.Equal(new CodeStatement[] { statement1, statement2 }, catchClause.Statements.Cast <CodeStatement>());
        }
Exemplo n.º 14
0
        /// <summary>
        /// Gets the throw clause.
        /// </summary>
        /// <returns>return catch...throw statement</returns>
        internal static CodeCatchClause[] GetThrowClause()
        {
            var catchStatmanents = new CodeStatementCollection();

            catchStatmanents.Add(new CodeThrowExceptionStatement(new CodeVariableReferenceExpression("ex")));
            var catchClause = new CodeCatchClause(
                "ex",
                new CodeTypeReference(typeof(Exception)),
                catchStatmanents.ToArray());

            var catchClauses = new[] { catchClause };

            return(catchClauses);
        }
Exemplo n.º 15
0
        internal void UCodeAddTestMethod(string methodName, Dictionary <string, string> methodAttribute,
                                         string reportCollection = "unifiedLogCollection", string reportInstance = "unifiedReport")
        {
            string           testCaseDescription = string.Empty;
            CodeMemberMethod sampleMethod        = new CodeMemberMethod();

            sampleMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            sampleMethod.Name       = methodName;
            sampleMethod.ReturnType =
                new CodeTypeReference(typeof(void));
            CodeAttributeDeclarationCollection collection = new CodeAttributeDeclarationCollection();

            if (methodAttribute != null)
            {
                foreach (KeyValuePair <string, string> singleItem in methodAttribute)
                {
                    if (singleItem.Key.ToLower().ToString().Contains("description"))
                    {
                        testCaseDescription = "\"" + singleItem.Value + "\"";
                    }
                    if (string.IsNullOrEmpty(singleItem.Value))
                    {
                        collection.Add(new CodeAttributeDeclaration(singleItem.Key));
                    }
                    else
                    {
                        collection.Add(new CodeAttributeDeclaration(singleItem.Key,
                                                                    new CodeAttributeArgument(new CodePrimitiveExpression(singleItem.Value))));
                    }
                }
                foreach (CodeAttributeDeclaration singleDeclaration in collection)
                {
                    sampleMethod.CustomAttributes.Add(singleDeclaration);
                }
            }
            sampleMethod.Statements.Add(new CodeSnippetExpression(reportCollection + ".Add(" + reportInstance + ".StartTest(" + testCaseDescription + "));"));
            CodeTryCatchFinallyStatement testMethodTry = new CodeTryCatchFinallyStatement();

            testMethodTry.TryStatements.Add(new CodeCommentStatement("Please fill in you code here"));
            sampleMethod.Statements.Add(testMethodTry);

            CodeCatchClause testMethodCatch = new CodeCatchClause("ex");

            testMethodCatch.Statements.Add(new CodeCommentStatement("Code to handle the Exception"));
            testMethodTry.CatchClauses.Add(testMethodCatch);

            testMethodTry.FinallyStatements.Add(new CodeCommentStatement("Handle any finally block"));

            targetClass.Members.Add(sampleMethod);
        }
        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 void Insert()
        {
            CodeCatchClause cc1 = new CodeCatchClause();
            CodeCatchClause cc2 = new CodeCatchClause();

            CodeCatchClauseCollection coll = new CodeCatchClauseCollection();

            coll.Add(cc1);
            Assert.AreEqual(1, coll.Count, "#1");
            Assert.AreEqual(0, coll.IndexOf(cc1), "#2");
            coll.Insert(0, cc2);
            Assert.AreEqual(2, coll.Count, "#3");
            Assert.AreEqual(1, coll.IndexOf(cc1), "#4");
            Assert.AreEqual(0, coll.IndexOf(cc2), "#5");
        }
        public void CodeTryCatchFinallyStatementTest()
        {
            CodeStatement        cs   = new CodeGotoStatement("exit");
            CodeCatchClause      ccc1 = new CodeCatchClause("ex1", new CodeTypeReference("System.ArgumentException"));
            CodeCatchClause      ccc2 = new CodeCatchClause(null, new CodeTypeReference("System.ApplicationException"));
            CodeSnippetStatement fin1 = new CodeSnippetStatement("A");
            CodeSnippetStatement fin2 = new CodeSnippetStatement("B");

            statement = new CodeTryCatchFinallyStatement(new CodeStatement[] { cs },
                                                         new CodeCatchClause[] { ccc1, ccc2 }, new CodeStatement[] { fin1, fin2 });

            Assert.AreEqual(string.Format(CultureInfo.InvariantCulture,
                                          "try {{{0}" +
                                          "    goto exit;{0}" +
                                          "}}{0}" +
                                          "catch (System.ArgumentException ex1) {{{0}" +
                                          "}}{0}" +
                                          "catch (System.ApplicationException ) {{{0}" +
                                          "}}{0}" +
                                          "finally {{{0}" +
                                          "A{0}" +
                                          "B{0}" +
                                          "}}{0}", NewLine), Generate(), "#1");

            options.ElseOnClosing = true;

            Assert.AreEqual(string.Format(CultureInfo.InvariantCulture,
                                          "try {{{0}" +
                                          "    goto exit;{0}" +
                                          "}} catch (System.ArgumentException ex1) {{{0}" +
                                          "}} catch (System.ApplicationException ) {{{0}" +
                                          "}} finally {{{0}" +
                                          "A{0}" +
                                          "B{0}" +
                                          "}}{0}", NewLine), Generate(), "#2");

            statement = new CodeTryCatchFinallyStatement();

            Assert.AreEqual(string.Format(CultureInfo.InvariantCulture,
                                          "try {{{0}" +
                                          "}}{0}", NewLine), Generate(), "#3");

            options.ElseOnClosing = false;

            Assert.AreEqual(string.Format(CultureInfo.InvariantCulture,
                                          "try {{{0}" +
                                          "}}{0}", NewLine), Generate(), "#4");
        }
        public void Constructor2()
        {
            CodeCatchClause cc1 = new CodeCatchClause();
            CodeCatchClause cc2 = new CodeCatchClause();

            CodeCatchClauseCollection c = new CodeCatchClauseCollection();

            c.Add(cc1);
            c.Add(cc2);

            CodeCatchClauseCollection coll = new CodeCatchClauseCollection(c);

            Assert.AreEqual(2, coll.Count, "#1");
            Assert.AreEqual(0, coll.IndexOf(cc1), "#2");
            Assert.AreEqual(1, coll.IndexOf(cc2), "#3");
        }
Exemplo n.º 20
0
        /// <summary>
        /// 创建一个Try
        /// </summary>
        /// <param name="tryCode"></param>
        /// <returns></returns>
        public CodeTryCatchFinallyStatement CreateTry(Func <CodeStatementCollection> tryCode)
        {
            CodeCatchClause @catch = new CodeCatchClause
            {
                CatchExceptionType = new CodeTypeReference(typeof(Exception)),
                LocalName          = "ex"
            };

            @catch.Statements.Add(new CodeSnippetExpression("throw ex;"));

            CodeTryCatchFinallyStatement codeTryCatchFinallyStatement = new CodeTryCatchFinallyStatement();

            codeTryCatchFinallyStatement.TryStatements.AddRange(tryCode());
            codeTryCatchFinallyStatement.CatchClauses.Add(@catch);

            return(codeTryCatchFinallyStatement);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Return catch statements
        /// </summary>
        /// <returns>CodeCatchClause statements</returns>
        internal static CodeCatchClause[] GetCatchClause()
        {
            var catchStatmanents = new CodeStatement[2];

            catchStatmanents[0] = new CodeAssignStatement(
                new CodeVariableReferenceExpression("exception"),
                new CodeVariableReferenceExpression("ex"));

            catchStatmanents[1] = GetReturnFalse();
            var catchClause = new CodeCatchClause(
                "ex",
                new CodeTypeReference(typeof(Exception)),
                catchStatmanents);

            var catchClauses = new[] { catchClause };

            return(catchClauses);
        }
Exemplo n.º 22
0
        private CodeMemberMethod ResetChartControls()
        {
            CodeMemberMethod ResetChartControls = null;

            try
            {
                ResetChartControls = new CodeMemberMethod
                {
                    Name       = "ResetChartControls",
                    Attributes = MemberAttributes.Public | MemberAttributes.Final,
                    ReturnType = new CodeTypeReference(typeof(bool)),
                };

                CodeParameterDeclarationExpression parameter = new CodeParameterDeclarationExpression();
                parameter.Name      = "cContextItemsChart";
                parameter.Type      = new CodeTypeReference(typeof(Dictionary <String, Object>));
                parameter.Direction = FieldDirection.Ref;

                ResetChartControls.Parameters.Add(parameter);

                CodeTryCatchFinallyStatement tryBlock = new CodeTryCatchFinallyStatement();
                foreach (string sChartName in _ilbo.Charts.Select(c => c.Name).Distinct())
                {
                    CodeConditionStatement ifKeyExists = IfCondition();
                    ifKeyExists.Condition = BinaryOpertorExpression(MethodInvocationExp(MethodInvocationExp(VariableReferenceExp("cContextItemsChart"), "ContainsKey").AddParameter(PrimitiveExpression(string.Format("ICT_ILBO_CHART_{0}", sChartName))), "ToString"), CodeBinaryOperatorType.IdentityEquality, PrimitiveExpression("True"));
                    ifKeyExists.TrueStatements.Add(MethodInvocationExp(VariableReferenceExp("cContextItemsChart"), "Remove").AddParameter(PrimitiveExpression(string.Format("ICT_ILBO_CHART_{0}", sChartName))));
                    tryBlock.AddStatement(ifKeyExists);
                }
                tryBlock.AddStatement(ReturnExpression(PrimitiveExpression(true)));

                CodeCatchClause catchBlock = AddCatchBlock(tryBlock, "e");
                catchBlock.AddStatement(MethodInvocationExp(TypeReferenceExp("Trace"), "WriteLineIf").AddParameters(new CodeExpression[] { PrimitiveExpression(false), PrimitiveExpression("ResetChartControls"), MethodInvocationExp(GetProperty("e", "Message"), "ToString") }));

                ResetChartControls.AddStatement(tryBlock);

                ResetChartControls.AddStatement(ReturnExpression(PrimitiveExpression(false)));

                return(ResetChartControls);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("ResetChartControls->{0}", ex.InnerException != null ? ex.InnerException.Message : ex.Message));
            }
        }
Exemplo n.º 23
0
        internal void UCodeAddMethod(string methodName, Dictionary <string, string> methodAttribute = null, bool tryCatchBlock = false)
        {
            CodeMemberMethod sampleMethod = new CodeMemberMethod();

            sampleMethod.Attributes = MemberAttributes.Public;
            sampleMethod.Name       = methodName;
            sampleMethod.ReturnType =
                new CodeTypeReference(typeof(void));
            CodeAttributeDeclarationCollection collection = new CodeAttributeDeclarationCollection();

            if (methodAttribute != null)
            {
                foreach (KeyValuePair <string, string> singleItem in methodAttribute)
                {
                    if (string.IsNullOrEmpty(singleItem.Value))
                    {
                        collection.Add(new CodeAttributeDeclaration(singleItem.Key));
                    }
                    else
                    {
                        collection.Add(new CodeAttributeDeclaration(singleItem.Key,
                                                                    new CodeAttributeArgument(new CodePrimitiveExpression(singleItem.Value))));
                    }
                }
                foreach (CodeAttributeDeclaration singleDeclaration in collection)
                {
                    sampleMethod.CustomAttributes.Add(singleDeclaration);
                }
            }
            if (tryCatchBlock)
            {
                CodeTryCatchFinallyStatement testMethodTry = new CodeTryCatchFinallyStatement();
                testMethodTry.TryStatements.Add(new CodeCommentStatement("Please fill in you code here"));
                sampleMethod.Statements.Add(testMethodTry);

                CodeCatchClause testMethodCatch = new CodeCatchClause("ex");
                testMethodCatch.Statements.Add(new CodeCommentStatement("Code to handle the Exception"));
                testMethodTry.CatchClauses.Add(testMethodCatch);

                testMethodTry.FinallyStatements.Add(new CodeCommentStatement("Handle any finally block"));
            }
            targetClass.Members.Add(sampleMethod);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Creates a property that gets or sets the value of an item in a row.
        /// </summary>
        /// <param name="tableSchema">The table to which this row belongs.</param>
        /// <param name="columnSchema">The nullable column.</param>
        public ColumnProperty(TableSchema tableSchema, ColumnSchema columnSchema)
        {
            //        /// <summary>
            //        /// Gets or sets the data in the RaceCode column.
            //        /// </summary>
            //        public int RaceCode {
            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement(string.Format("Gets or sets the data in the {0} column.", columnSchema.Name), true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            this.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            this.Type       = new CodeGlobalTypeReference(columnSchema.DataType);
            this.Name       = columnSchema.Name;

            //            get {
            //                try {
            //                    return ((int)(this[this.tableEmployee.RaceCodeColumn]));
            //                }
            //                catch (global::System.InvalidCastException e) {
            //                    throw new global::System.Data.StrongTypingException("Cannot get value because it is DBNull.", e);
            //                }
            //            }
            if (columnSchema.IsNullable)
            {
                CodeTryCatchFinallyStatement tryCatchBlock = new CodeTryCatchFinallyStatement();
                tryCatchBlock.TryStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(this.Type, new CodeArrayIndexerExpression(new CodeThisReferenceExpression(), new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), string.Format("table{0}", tableSchema.Name)), string.Format("{0}Column", columnSchema.Name))))));
                CodeCatchClause catchStrongTypeException = new CodeCatchClause("e", new CodeGlobalTypeReference(typeof(System.InvalidCastException)));
                catchStrongTypeException.Statements.Add(new CodeThrowExceptionStatement(new CodeObjectCreateExpression(new CodeGlobalTypeReference(typeof(System.Data.StrongTypingException)), new CodePrimitiveExpression("Cannot get value because it is DBNull."), new CodeArgumentReferenceExpression("e"))));
                tryCatchBlock.CatchClauses.Add(catchStrongTypeException);
                this.GetStatements.Add(tryCatchBlock);
            }
            else
            {
                this.GetStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(this.Type, new CodeArrayIndexerExpression(new CodeThisReferenceExpression(), new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), string.Format("table{0}", tableSchema.Name)), string.Format("{0}Column", columnSchema.Name))))));
            }

            //            set {
            //                this[this.tableEmployee.RaceCodeColumn] = value;
            //            }
            this.SetStatements.Add(new CodeAssignStatement(new CodeArrayIndexerExpression(new CodeThisReferenceExpression(), new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), string.Format("table{0}", tableSchema.Name)), string.Format("{0}Column", columnSchema.Name))), new CodePropertySetValueReferenceExpression()));

            //        }
        }
Exemplo n.º 25
0
        public static CodeStatement CreateTryCatchStatement(CodeTypeDeclaration classType, CodeStatement statement, CodeGenerationInfo generationInfo)
        {
            var tryStatement = new CodeTryCatchFinallyStatement();

            tryStatement.TryStatements.Add(statement);

            var catchClause     = new CodeCatchClause("e", new CodeTypeReference("std::exception&"));
            var methodRefExp    = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression($"{generationInfo.BaseNamespace}.CremaData"), "InvokeErrorOccured");
            var methodInvokeExp = new CodeMethodInvokeExpression(methodRefExp, new CodeVariableReferenceExpression("e"));

            var conditionStatement = new CodeConditionStatement();

            conditionStatement.Condition = new CodeBinaryOperatorExpression(methodInvokeExp, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(false));
            conditionStatement.TrueStatements.Add(new CodeThrowExceptionStatement(new CodeVariableReferenceExpression("e")));

            catchClause.Statements.Add(conditionStatement);
            tryStatement.CatchClauses.Add(catchClause);

            return(tryStatement);
        }
Exemplo n.º 26
0
        public void TestCodeTryCatchStatement()
        {
            CodeTryCatchFinallyStatement try1 = new CodeTryCatchFinallyStatement();

            try1.TryStatements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "ThrowApplicationException"));

            CodeCatchClause catch1 = new CodeCatchClause("ex", new CodeTypeReference("System.ApplicationException"));

            catch1.Statements.Add(new CodeCommentStatement("Handle any System.ApplicationException here."));
            try1.CatchClauses.Add(catch1);

            TestCodeStatement(try1,
                              @"    try {
        this.ThrowApplicationException();
    }
    catch (ex) {
        // Handle any System.ApplicationException here.
    }
");
        }
        /// <summary>
        /// Constructs FillMessageObject
        /// </summary>
        /// <returns>CodeMemberMethod</returns>
        private CodeMemberMethod FillMessageObject()
        {
            CodeMemberMethod FillMessageObject = null;

            try
            {
                FillMessageObject = new CodeMemberMethod
                {
                    Name       = "FillMessageObject",
                    Attributes = MemberAttributes.Private
                };

                //method parameters
                FillMessageObject.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "sMethod"));
                FillMessageObject.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "sErrNumber"));
                FillMessageObject.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "sErrMessage"));

                //method summary
                AddMethodSummary(FillMessageObject, "Fills the Message object when an error occurs");

                CodeTryCatchFinallyStatement TryBlock = AddTryBlock(FillMessageObject);

                TryBlock.TryStatements.Add(AddTrace(FillMessageObject, TraceSeverity.Info));
                TryBlock.TryStatements.Add(DeclareVariableAndAssign("ISessionManager", "ISManager", true, SnippetExpression("(ISessionManager)System.Web.HttpContext.Current.Session[\"SessionManager\"]")));
                TryBlock.TryStatements.Add(DeclareVariableAndAssign("IMessage", "Imsg", true, SnippetExpression("ISManager.GetMessageObject()")));

                CodeMethodInvokeExpression AddMessage = MethodInvocationExp(TypeReferenceExp("Imsg"), "AddMessage");
                AddParameters(AddMessage, new object[] { ArgumentReferenceExp("sErrNumber"), ArgumentReferenceExp("sErrMessage"), ArgumentReferenceExp("sMethod"), GetProperty(TypeReferenceExp(typeof(string)), "Empty"), PrimitiveExpression("5") });
                TryBlock.TryStatements.Add(AddMessage);

                CodeCatchClause catchBlock = CodeDomHelper.AddCatchBlock(TryBlock);
                catchBlock.Statements.Add(AddTrace(FillMessageObject, TraceSeverity.Error));
                CodeDomHelper.ThrowException(catchBlock);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("FillMessageObject->{0}", !object.Equals(ex.InnerException, null) ? ex.InnerException.Message : ex.Message));
            }
            return(FillMessageObject);
        }
Exemplo n.º 28
0
        private static CodeMemberMethod CreateClassMethod(string name, string inType, string inName, string outType, string noun, string verb, string attribute)
        {
            CodeMemberMethod method = new CodeMemberMethod()
            {
                Name       = name,
                Attributes = MemberAttributes.Public | MemberAttributes.Final,
                ReturnType = new CodeTypeReference(outType)
            };

            method.Parameters.Add(new CodeParameterDeclarationExpression(inType, inName));

            if (attribute != "")
            {
                method.CustomAttributes.Add(new string[] { $"{attribute}" });
            }

            CodeTryCatchFinallyStatement try1 = new CodeTryCatchFinallyStatement();
            CodeCatchClause catch1            = new CodeCatchClause("e1");

            if (IsEvent(verb))
            {
                try1.TryStatements.Add(new CodeSnippetExpression($"{inName}.{ChangeinType(inType, verb)}Message.IsHeaderOk(false, false)"));
            }
            else
            {
                try1.TryStatements.Add(new CodeSnippetExpression($"{inName}.{ChangeinType(inType, verb)}Message.IsHeaderOk(false, false, false)"));
                try1.TryStatements.Add(new CodeSnippetExpression($"{inName}.{ChangeinType(inType, verb)}Message.IsRequestOk(true, true, true, true)"));
            }

            try1.TryStatements.Add(new CodeSnippetStatement($""));
            try1.TryStatements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), $"{verb}Handler", new CodeExpression[] { new CodeArgumentReferenceExpression($"{inName}") })));

            catch1.Statements.Add(new CodeSnippetStatement(GetErrorReplyStatement(inType, outType, noun, verb)));

            try1.CatchClauses.Add(catch1);

            method.Statements.Add(try1);

            return(method);
        }
Exemplo n.º 29
0
        private void ValidateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e)
        {
            this.ValidateStatements(e.TryStatements);
            CodeCatchClauseCollection catchClauses = e.CatchClauses;

            if (catchClauses.Count > 0)
            {
                IEnumerator enumerator = catchClauses.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    CodeCatchClause current = (CodeCatchClause)enumerator.Current;
                    ValidateTypeReference(current.CatchExceptionType);
                    ValidateIdentifier(current, "LocalName", current.LocalName);
                    this.ValidateStatements(current.Statements);
                }
            }
            CodeStatementCollection finallyStatements = e.FinallyStatements;

            if (finallyStatements.Count > 0)
            {
                this.ValidateStatements(finallyStatements);
            }
        }
Exemplo n.º 30
0
        static CodeCatchClause _ParseCatchClause(_PC pc)
        {
            if (ST.catchKeyword != pc.SymbolId)
            {
                pc.Error("Expecting catch");
            }
            pc.Advance();
            if (ST.lparen != pc.SymbolId)
            {
                pc.Error("Expecting ( in catch clause");
            }
            pc.Advance();
            var result = new CodeCatchClause();

            result.CatchExceptionType = _ParseType(pc);
            if (ST.rparen != pc.SymbolId)
            {
                result.LocalName = _ParseIdentifier(pc);
            }
            if (ST.rparen != pc.SymbolId)
            {
                pc.Error("Expecting ) in catch clause");
            }
            pc.Advance();
            if (ST.lbrace != pc.SymbolId)
            {
                pc.Error("Expecting { in catch clause");
            }
            pc.Advance();
            result.Statements.AddRange(_ParseStatements(pc, true));
            if (ST.rbrace != pc.SymbolId)
            {
                pc.Error("Expecting } in catch clause");
            }
            pc.Advance();
            return(result);
        }
        public void Constructor3()
        {
            string            localName = "mono";
            CodeTypeReference cet       = new CodeTypeReference("SomeException");
            CodeStatement     cs1       = new CodeStatement();
            CodeStatement     cs2       = new CodeStatement();

            CodeCatchClause ccc = new CodeCatchClause(localName, cet, cs1, cs2);

            Assert.IsNotNull(ccc.CatchExceptionType, "#1");
            Assert.AreSame(cet, ccc.CatchExceptionType, "#2");

            Assert.IsNotNull(ccc.LocalName, "#3");
            Assert.AreEqual(localName, ccc.LocalName, "#4");
            Assert.AreSame(localName, ccc.LocalName, "#5");

            Assert.IsNotNull(ccc.Statements, "#6");
            Assert.AreEqual(2, ccc.Statements.Count, "#7");
            Assert.AreSame(cs1, ccc.Statements[0], "#8");
            Assert.AreSame(cs2, ccc.Statements[1], "#9");

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

            ccc.CatchExceptionType = null;
            Assert.IsNotNull(ccc.CatchExceptionType, "#10");
            Assert.AreEqual(typeof(Exception).FullName, ccc.CatchExceptionType.BaseType, "#11");

            ccc = new CodeCatchClause((string)null, (CodeTypeReference)null, cs1);
            Assert.IsNotNull(ccc.LocalName, "#12");
            Assert.AreEqual(string.Empty, ccc.LocalName, "#13");
            Assert.IsNotNull(ccc.CatchExceptionType, "#14");
            Assert.AreEqual(typeof(Exception).FullName, ccc.CatchExceptionType.BaseType, "#15");
            Assert.AreEqual(1, ccc.Statements.Count, "#16");
            Assert.AreSame(cs1, ccc.Statements[0], "#17");
        }
        public void Constructor1()
        {
            string localName = "mono";

            CodeCatchClause ccc = new CodeCatchClause(localName);

            Assert.IsNotNull(ccc.CatchExceptionType, "#1");
            Assert.AreEqual(typeof(Exception).FullName, ccc.CatchExceptionType.BaseType, "#2");

            Assert.IsNotNull(ccc.LocalName, "#3");
            Assert.AreEqual(localName, ccc.LocalName, "#4");
            Assert.AreSame(localName, ccc.LocalName, "#5");

            Assert.IsNotNull(ccc.Statements, "#6");
            Assert.AreEqual(0, ccc.Statements.Count, "#7");

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

            ccc = new CodeCatchClause((string)null);
            Assert.IsNotNull(ccc.LocalName, "#10");
            Assert.AreEqual(string.Empty, ccc.LocalName, "#22");
        }
Exemplo n.º 33
0
        // 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 CodeTryCatchFinallyStatement(CodeStatement[] tryStatements, CodeCatchClause[] catchClauses, CodeStatement[] finallyStatements)
 {
     TryStatements.AddRange(tryStatements);
     CatchClauses.AddRange(catchClauses);
     FinallyStatements.AddRange(finallyStatements);
 }
	public CodeTryCatchFinallyStatement(CodeStatement[] tryStatements, CodeCatchClause[] catchClauses, CodeStatement[] finallyStatements) {}
Exemplo n.º 36
0
		public void CatchExceptionType_Set_Get_ReturnsExpected(CodeTypeReference value)
		{
			var catchClause = new CodeCatchClause();
			catchClause.CatchExceptionType = value;
			Assert.Equal((value ?? new CodeTypeReference(typeof(Exception))).BaseType, catchClause.CatchExceptionType.BaseType);
		}
Exemplo n.º 37
0
		public void Statements_AddMultiple_ReturnsExpected()
		{
			var catchClause = new CodeCatchClause();

			CodeStatement statement1 = new CodeCommentStatement("Value1");
			catchClause.Statements.Add(statement1);
			Assert.Equal(new CodeStatement[] { statement1 }, catchClause.Statements.Cast<CodeStatement>());

			CodeStatement statement2 = new CodeCommentStatement("Value1");
			catchClause.Statements.Add(statement2);
			Assert.Equal(new CodeStatement[] { statement1, statement2 }, catchClause.Statements.Cast<CodeStatement>());
		}
	public CodeCatchClauseCollection(CodeCatchClause[] value) {}
	public void Remove(CodeCatchClause value) {}
Exemplo n.º 40
0
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {
        // create a namespace
        CodeNamespace ns = new CodeNamespace ("NS");
        ns.Imports.Add (new CodeNamespaceImport ("System"));
        cu.Namespaces.Add (ns);

        // create a class
        CodeTypeDeclaration class1 = new CodeTypeDeclaration ();
        class1.Name = "Test";
        class1.IsClass = true;
        ns.Types.Add (class1);

        if (Supports (provider, GeneratorSupport.TryCatchStatements)) {

            // try catch statement with just finally
            // GENERATE (C#):
            //       public static int FirstScenario(int a) {
            //            try {
            //            }
            //            finally {
            //                a = (a + 5);
            //            }
            //            return a;
            //        }
            AddScenario ("CheckFirstScenario");
            CodeMemberMethod cmm = new CodeMemberMethod ();
            cmm.Name = "FirstScenario";
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "a");
            cmm.Parameters.Add (param);

            CodeTryCatchFinallyStatement tcfstmt = new CodeTryCatchFinallyStatement ();
            tcfstmt.FinallyStatements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("a"), new
                CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("a"), CodeBinaryOperatorType.Add,
                new CodePrimitiveExpression (5))));
            cmm.Statements.Add (tcfstmt);
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a")));
            class1.Members.Add (cmm);

            // in VB (a = a/a) generates an warning if a is integer. Cast the expression just for VB language. 
            CodeBinaryOperatorExpression cboExpression   = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("a"), CodeBinaryOperatorType.Divide, new CodeArgumentReferenceExpression ("a"));
            CodeAssignStatement          assignStatement = null;
            if (provider is Microsoft.VisualBasic.VBCodeProvider)
                assignStatement = new CodeAssignStatement (new CodeArgumentReferenceExpression ("a"), new CodeCastExpression (typeof (int), cboExpression));
            else
                assignStatement = new CodeAssignStatement (new CodeArgumentReferenceExpression ("a"), cboExpression);

            // try catch statement with just catch
            // GENERATE (C#):
            //        public static int SecondScenario(int a, string exceptionMessage) {
            //            try {
            //                a = (a / a);
            //            }
            //            catch (System.Exception e) {
            //                a = 3;
            //                exceptionMessage = e.ToString();
            //            }
            //            finally {
            //                a = (a + 1);
            //            }
            //            return a;
            //        }
            AddScenario ("CheckSecondScenario");
            cmm = new CodeMemberMethod ();
            cmm.Name = "SecondScenario";
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            param = new CodeParameterDeclarationExpression (typeof (int), "a");
            cmm.Parameters.Add (param);
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (String), "exceptionMessage"));

            tcfstmt = new CodeTryCatchFinallyStatement ();
            CodeCatchClause catchClause = new CodeCatchClause ("e");
            tcfstmt.TryStatements.Add (assignStatement);
            catchClause.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("a"),
                new CodePrimitiveExpression (3)));
            catchClause.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("exceptionMessage"),
                new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("e"), "ToString")));
            tcfstmt.CatchClauses.Add (catchClause);
            tcfstmt.FinallyStatements.Add (CDHelper.CreateIncrementByStatement (new CodeArgumentReferenceExpression ("a"), 1));

            cmm.Statements.Add (tcfstmt);
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a")));

            class1.Members.Add (cmm);

            // try catch statement with multiple catches
            // GENERATE (C#):
            //        public static int ThirdScenario(int a, string exceptionMessage) {
            //            try {
            //                a = (a / a);
            //            }
            //            catch (System.ArgumentNullException e) {
            //                a = 10;
            //                exceptionMessage = e.ToString();
            //            }
            //            catch (System.DivideByZeroException f) {
            //                exceptionMessage = f.ToString();
            //                a = 9;
            //            }
            //            return a;
            //        }
            AddScenario ("CheckThirdScenario");
            cmm = new CodeMemberMethod ();
            cmm.Name = "ThirdScenario";
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            param = new CodeParameterDeclarationExpression (typeof (int), "a");
            cmm.Parameters.Add (param);
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (String), "exceptionMessage"));

            tcfstmt = new CodeTryCatchFinallyStatement ();
            catchClause = new CodeCatchClause ("e", new CodeTypeReference (typeof (ArgumentNullException)));
            tcfstmt.TryStatements.Add (assignStatement);
            catchClause.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("a"),
                new CodePrimitiveExpression (9)));
            catchClause.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("exceptionMessage"),
                new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("e"), "ToString")));
            tcfstmt.CatchClauses.Add (catchClause);

            // add a second catch clause
            catchClause = new CodeCatchClause ("f", new CodeTypeReference (typeof (Exception)));
            catchClause.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("exceptionMessage"),
                new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("f"), "ToString")));
            catchClause.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("a"),
                new CodePrimitiveExpression (9)));
            tcfstmt.CatchClauses.Add (catchClause);

            cmm.Statements.Add (tcfstmt);
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a")));
            class1.Members.Add (cmm);

            // catch throws exception
            // GENERATE (C#):
            //        public static int FourthScenario(int a) {
            //            try {
            //                a = (a / a);
            //            }
            //            catch (System.Exception e) {
            //                // Error handling
            //                throw e;
            //            }
            //            return a;
            //        }
            AddScenario ("CheckFourthScenario");
            cmm = new CodeMemberMethod ();
            cmm.Name = "FourthScenario";
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            param = new CodeParameterDeclarationExpression (typeof (int), "a");
            cmm.Parameters.Add (param);

            tcfstmt = new CodeTryCatchFinallyStatement ();
            catchClause = new CodeCatchClause ("e");
            tcfstmt.TryStatements.Add (assignStatement);
            catchClause.Statements.Add (new CodeCommentStatement ("Error handling"));
            catchClause.Statements.Add (new CodeThrowExceptionStatement (new CodeArgumentReferenceExpression ("e")));
            tcfstmt.CatchClauses.Add (catchClause);
            cmm.Statements.Add (tcfstmt);
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a")));
            class1.Members.Add (cmm);
        }
    }
	public int IndexOf(CodeCatchClause value) {}
	public void CopyTo(CodeCatchClause[] array, int index) {}
	public bool Contains(CodeCatchClause value) {}
Exemplo n.º 44
0
        public void TryCatchThrow()
        {
            var cd = new CodeTypeDeclaration();
            cd.Name = "Test";
            cd.IsClass = true;

            // try catch statement with just finally
            var cmm = new CodeMemberMethod();
            cmm.Name = "FirstScenario";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a");
            cmm.Parameters.Add(param);

            CodeTryCatchFinallyStatement tcfstmt = new CodeTryCatchFinallyStatement();
            tcfstmt.FinallyStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"), new
                                                                  CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add,
                                                                                               new CodePrimitiveExpression(5))));
            cmm.Statements.Add(tcfstmt);
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
            cd.Members.Add(cmm);

            CodeBinaryOperatorExpression cboExpression = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Divide, new CodeVariableReferenceExpression("a"));
            CodeAssignStatement assignStatement = new CodeAssignStatement(new CodeVariableReferenceExpression("a"), cboExpression);

            // try catch statement with just catch
            cmm = new CodeMemberMethod();
            cmm.Name = "SecondScenario";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            param = new CodeParameterDeclarationExpression(typeof(int), "a");
            cmm.Parameters.Add(param);
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(String), "exceptionMessage"));

            tcfstmt = new CodeTryCatchFinallyStatement();
            CodeCatchClause catchClause = new CodeCatchClause("e");
            tcfstmt.TryStatements.Add(assignStatement);
            catchClause.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"),
                                                               new CodePrimitiveExpression(3)));
            catchClause.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("exceptionMessage"),
                                                               new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("e"), "ToString")));
            tcfstmt.CatchClauses.Add(catchClause);
            tcfstmt.FinallyStatements.Add(CreateVariableIncrementExpression("a", 1));

            cmm.Statements.Add(tcfstmt);
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));

            cd.Members.Add(cmm);

            // try catch statement with multiple catches
            cmm = new CodeMemberMethod();
            cmm.Name = "ThirdScenario";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            param = new CodeParameterDeclarationExpression(typeof(int), "a");
            cmm.Parameters.Add(param);
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(String), "exceptionMessage"));

            tcfstmt = new CodeTryCatchFinallyStatement();
            catchClause = new CodeCatchClause("e", new CodeTypeReference(typeof(ArgumentNullException)));
            tcfstmt.TryStatements.Add(assignStatement);
            catchClause.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"),
                                                               new CodePrimitiveExpression(9)));
            catchClause.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("exceptionMessage"),
                                                               new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("e"), "ToString")));
            tcfstmt.CatchClauses.Add(catchClause);

            // add a second catch clause
            catchClause = new CodeCatchClause("f", new CodeTypeReference(typeof(Exception)));
            catchClause.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("exceptionMessage"),
                                                               new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("f"), "ToString")));
            catchClause.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"),
                                                               new CodePrimitiveExpression(9)));
            tcfstmt.CatchClauses.Add(catchClause);

            cmm.Statements.Add(tcfstmt);
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
            cd.Members.Add(cmm);

            // catch throws exception
            cmm = new CodeMemberMethod();
            cmm.Name = "FourthScenario";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            param = new CodeParameterDeclarationExpression(typeof(int), "a");
            cmm.Parameters.Add(param);

            tcfstmt = new CodeTryCatchFinallyStatement();
            catchClause = new CodeCatchClause("e");
            tcfstmt.TryStatements.Add(assignStatement);
            catchClause.Statements.Add(new CodeCommentStatement("Error handling"));
            catchClause.Statements.Add(new CodeThrowExceptionStatement(new CodeArgumentReferenceExpression("e")));
            tcfstmt.CatchClauses.Add(catchClause);
            cmm.Statements.Add(tcfstmt);
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
            cd.Members.Add(cmm);

            AssertEqual(cd,
                @"public class Test {
                      public static int FirstScenario(int a) {
                          try {
                          }
                          finally {
                              a = (a + 5);
                          }
                          return a;
                      }
                      public static int SecondScenario(int a, string exceptionMessage) {
                          try {
                              a = (a / a);
                          }
                          catch (System.Exception e) {
                              a = 3;
                              exceptionMessage = e.ToString();
                          }
                          finally {
                              a = (a + 1);
                          }
                          return a;
                      }
                      public static int ThirdScenario(int a, string exceptionMessage) {
                          try {
                              a = (a / a);
                          }
                          catch (System.ArgumentNullException e) {
                              a = 9;
                              exceptionMessage = e.ToString();
                          }
                          catch (System.Exception f) {
                              exceptionMessage = f.ToString();
                              a = 9;
                          }
                          return a;
                      }
                      public static int FourthScenario(int a) {
                          try {
                              a = (a / a);
                          }
                          catch (System.Exception e) {
                              // Error handling
                              throw e;
                          }
                          return a;
                      }
                  }");
        }
	// Methods
	public int Add(CodeCatchClause value) {}
Exemplo n.º 46
0
        private bool WriteTry(BasicBlock block, List<CodeStatement> stmts, Context context)
        {
            // find catch/finally blocks that match this try
            // write this block into the try
            // continue until we find the try follow, which is the first block that has a last != leave
            // if the try follow lands on a loop or conditional header, then use their follow instead
            // TODO: deal with nested trys
            var tryStmt = new CodeTryStatement();
            AddStatement(stmts, tryStmt);

            var tryContext = context.NewTry(block.Try);

            WriteCode(null, block, tryStmt.Try, tryContext);

            foreach (BasicBlock catchBlock in block.Try.Catches) {
                var catchType = catchBlock.ExceptionHandler.CatchType;
                var variable = Interpreter.CreateExceptionVariableReference(this.method.Definition, catchType);
                var catchClause = new CodeCatchClause {
                    Type = new CodeTypeReference(catchType),
                    Variable = variable
                };

                tryStmt.Catches.Add(catchClause);

                WriteCode(null, catchBlock, catchClause.Statements, tryContext);
            }

            if (block.Try.Finally != null) {
                WriteCode(null, (BasicBlock)block.Try.Finally, tryStmt.Finally, tryContext);
            }

            if (block.Try.Follow != null) {
                return WriteCode(block, (BasicBlock)block.Try.Follow, stmts, context);
            }

            return true;
        }
	public void Insert(int index, CodeCatchClause value) {}
Exemplo n.º 48
0
        public void TryCatchThrow()
        {
            var cd = new CodeTypeDeclaration();
            cd.Name = "Test";
            cd.IsClass = true;

            // try catch statement with just finally
            CodeMemberMethod cmm = new CodeMemberMethod();
            cmm.Name = "FirstScenario";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a");
            cmm.Parameters.Add(param);

            CodeTryCatchFinallyStatement tcfstmt = new CodeTryCatchFinallyStatement();
            tcfstmt.FinallyStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"), new
                                                                  CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add,
                                                                                               new CodePrimitiveExpression(5))));
            cmm.Statements.Add(tcfstmt);
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
            cd.Members.Add(cmm);

            CodeBinaryOperatorExpression cboExpression = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Divide, new CodeVariableReferenceExpression("a"));
            CodeAssignStatement assignStatement = new CodeAssignStatement(new CodeVariableReferenceExpression("a"), cboExpression);

            // try catch statement with just catch
            cmm = new CodeMemberMethod();
            cmm.Name = "SecondScenario";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            param = new CodeParameterDeclarationExpression(typeof(int), "a");
            cmm.Parameters.Add(param);
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(String), "exceptionMessage"));

            tcfstmt = new CodeTryCatchFinallyStatement();
            CodeCatchClause catchClause = new CodeCatchClause("e");
            tcfstmt.TryStatements.Add(assignStatement);
            catchClause.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"),
                                                               new CodePrimitiveExpression(3)));
            catchClause.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("exceptionMessage"),
                                                               new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("e"), "ToString")));
            tcfstmt.CatchClauses.Add(catchClause);
            tcfstmt.FinallyStatements.Add(CreateVariableIncrementExpression("a", 1));

            cmm.Statements.Add(tcfstmt);
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));

            cd.Members.Add(cmm);

            // try catch statement with multiple catches
            cmm = new CodeMemberMethod();
            cmm.Name = "ThirdScenario";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            param = new CodeParameterDeclarationExpression(typeof(int), "a");
            cmm.Parameters.Add(param);
            cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(String), "exceptionMessage"));

            tcfstmt = new CodeTryCatchFinallyStatement();
            catchClause = new CodeCatchClause("e", new CodeTypeReference(typeof(ArgumentNullException)));
            tcfstmt.TryStatements.Add(assignStatement);
            catchClause.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"),
                                                               new CodePrimitiveExpression(9)));
            catchClause.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("exceptionMessage"),
                                                               new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("e"), "ToString")));
            tcfstmt.CatchClauses.Add(catchClause);

            // add a second catch clause
            catchClause = new CodeCatchClause("f", new CodeTypeReference(typeof(Exception)));
            catchClause.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("exceptionMessage"),
                                                               new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("f"), "ToString")));
            catchClause.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"),
                                                               new CodePrimitiveExpression(9)));
            tcfstmt.CatchClauses.Add(catchClause);

            cmm.Statements.Add(tcfstmt);
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
            cd.Members.Add(cmm);

            // catch throws exception
            cmm = new CodeMemberMethod();
            cmm.Name = "FourthScenario";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            param = new CodeParameterDeclarationExpression(typeof(int), "a");
            cmm.Parameters.Add(param);

            tcfstmt = new CodeTryCatchFinallyStatement();
            catchClause = new CodeCatchClause("e");
            tcfstmt.TryStatements.Add(assignStatement);
            catchClause.Statements.Add(new CodeCommentStatement("Error handling"));
            catchClause.Statements.Add(new CodeThrowExceptionStatement(new CodeArgumentReferenceExpression("e")));
            tcfstmt.CatchClauses.Add(catchClause);
            cmm.Statements.Add(tcfstmt);
            cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
            cd.Members.Add(cmm);

            AssertEqual(cd,
                @"Public Class Test
                      Public Shared Function FirstScenario(ByVal a As Integer) As Integer
                          Try
                          Finally
                              a = (a + 5)
                          End Try
                          Return a
                      End Function
                      Public Shared Function SecondScenario(ByVal a As Integer, ByVal exceptionMessage As String) As Integer
                          Try
                              a = (a / a)
                          Catch e As System.Exception
                              a = 3
                              exceptionMessage = e.ToString
                          Finally
                              a = (a + 1)
                          End Try
                          Return a
                      End Function
                      Public Shared Function ThirdScenario(ByVal a As Integer, ByVal exceptionMessage As String) As Integer
                          Try
                              a = (a / a)
                          Catch e As System.ArgumentNullException
                              a = 9
                              exceptionMessage = e.ToString
                          Catch f As System.Exception
                              exceptionMessage = f.ToString
                              a = 9
                          End Try
                          Return a
                      End Function
                      Public Shared Function FourthScenario(ByVal a As Integer) As Integer
                          Try
                              a = (a / a)
                          Catch e As System.Exception
                              'Error handling
                              Throw e
                          End Try
                          Return a
                      End Function
                  End Class");
        }
	public void AddRange(CodeCatchClause[] value) {}
Exemplo n.º 50
0
		public void LocalName_Set_Get_ReturnsExpected(string value)
		{
			var catchClause = new CodeCatchClause();
			catchClause.LocalName = value;
			Assert.Equal(value ?? string.Empty, catchClause.LocalName);
		}