示例#1
0
        protected override void AddPageTypeCtorStatements(CodeStatementCollection statements)
        {
            base.AddPageTypeCtorStatements(statements);

            bool useInitialContextNode = initialContextNodeField != null;
            var  uriType = new CodeTypeReference(typeof(Uri));

            var 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)
                    }
                }
            };

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

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

            var 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))
                        }
                    }
                }
            };

            var icnSourceVar = new CodeVariableDeclarationStatement {
                Name           = "initialContextNodeSource",
                Type           = new CodeTypeReference(typeof(Stream)),
                InitExpression = new CodePrimitiveExpression(null)
            };

            var icnVirtualPathVar = new CodeVariableDeclarationStatement {
                Name           = "initialContextNodeVirtualPath",
                Type           = new CodeTypeReference(typeof(String)),
                InitExpression = new CodePrimitiveExpression(VirtualPathUtility.ToAppRelative(this.parser.AppRelativeVirtualPath))
            };

            var icnUriVar = new CodeVariableDeclarationStatement {
                Name           = "initialContextNodeUri",
                Type           = uriType,
                InitExpression = new CodeObjectCreateExpression {
                    CreateType = uriType,
                    Parameters =
                    {
                        new CodeMethodInvokeExpression      {
                            Method = new CodeMethodReferenceExpression{
                                MethodName   = "MapPath",
                                TargetObject = new CodeTypeReferenceExpression(typeof(HostingEnvironment))
                            },
                            Parameters =
                            {
                                new CodeVariableReferenceExpression(icnVirtualPathVar.Name)
                            }
                        },
                        new CodePropertyReferenceExpression {
                            PropertyName = "Absolute",
                            TargetObject = new CodeTypeReferenceExpression(typeof(UriKind))
                        }
                    }
                }
            };

            statements.AddRange(new CodeStatement[] { procVar, sourceVar, virtualPathVar, sourceUriVar });

            if (useInitialContextNode)
            {
                statements.AddRange(new CodeStatement[] { icnSourceVar, icnVirtualPathVar, icnUriVar });
            }

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

            optionsVar.InitExpression = new CodeObjectCreateExpression(optionsVar.Type);

            var trySt = new CodeTryCatchFinallyStatement {
                TryStatements =
                {
                    new CodeAssignStatement                   {
                        Left  = new CodeVariableReferenceExpression(sourceVar.Name),
                        Right = new CodeMethodInvokeExpression{
                            Method = new CodeMethodReferenceExpression{
                                MethodName   = "Open",
                                TargetObject = new CodeMethodInvokeExpression{
                                    Method = new CodeMethodReferenceExpression{
                                        MethodName   = "GetFile",
                                        TargetObject = new CodePropertyReferenceExpression{
                                            PropertyName = "VirtualPathProvider",
                                            TargetObject = new CodeTypeReferenceExpression(typeof(HostingEnvironment))
                                        }
                                    },
                                    Parameters =
                                    {
                                        new CodeVariableReferenceExpression(virtualPathVar.Name)
                                    }
                                }
                            }
                        }
                    },
                    optionsVar,
                    new CodeAssignStatement                   {
                        Left = new CodePropertyReferenceExpression{
                            PropertyName = "BaseUri",
                            TargetObject = new CodeVariableReferenceExpression(optionsVar.Name)
                        },
                        Right = new CodeVariableReferenceExpression(sourceUriVar.Name)
                    },
                    new CodeAssignStatement                   {
                        Left = new CodeFieldReferenceExpression{
                            FieldName    = executableField.Name,
                            TargetObject = PageTypeReferenceExpression
                        },
                        Right = new CodeMethodInvokeExpression(
                            new CodeMethodReferenceExpression {
                            MethodName   = "Compile",
                            TargetObject = new CodeVariableReferenceExpression(procVar.Name)
                        },
                            new CodeVariableReferenceExpression(sourceVar.Name),
                            new CodeVariableReferenceExpression(optionsVar.Name)
                            )
                    }
                },
                FinallyStatements =
                {
                    new CodeConditionStatement                    {
                        Condition = new CodeBinaryOperatorExpression{
                            Left     = new CodeVariableReferenceExpression(sourceVar.Name),
                            Operator = CodeBinaryOperatorType.IdentityInequality,
                            Right    = new CodePrimitiveExpression(null)
                        },
                        TrueStatements =
                        {
                            new CodeMethodInvokeExpression(
                                new CodeMethodReferenceExpression {
                                MethodName   = "Dispose",
                                TargetObject = new CodeVariableReferenceExpression(sourceVar.Name)
                            }
                                )
                        }
                    }
                }
            };

            if (useInitialContextNode)
            {
                trySt.TryStatements.Add(new CodeAssignStatement {
                    Left  = new CodeVariableReferenceExpression(icnSourceVar.Name),
                    Right = new CodeMethodInvokeExpression {
                        Method = new CodeMethodReferenceExpression {
                            MethodName   = "Open",
                            TargetObject = new CodeMethodInvokeExpression {
                                Method = new CodeMethodReferenceExpression {
                                    MethodName   = "GetFile",
                                    TargetObject = new CodePropertyReferenceExpression {
                                        PropertyName = "VirtualPathProvider",
                                        TargetObject = new CodeTypeReferenceExpression(typeof(HostingEnvironment))
                                    }
                                },
                                Parameters =
                                {
                                    new CodeVariableReferenceExpression(icnVirtualPathVar.Name)
                                }
                            }
                        }
                    }
                });

                var icnOptVar = new CodeVariableDeclarationStatement {
                    Name           = "initialContextNodeOptions",
                    Type           = new CodeTypeReference(typeof(XmlParsingOptions)),
                    InitExpression = new CodeObjectCreateExpression {
                        CreateType = new CodeTypeReference(typeof(XmlParsingOptions))
                    }
                };

                trySt.TryStatements.Add(icnOptVar);

                trySt.TryStatements.Add(
                    new CodeAssignStatement {
                    Left = new CodePropertyReferenceExpression {
                        PropertyName = "BaseUri",
                        TargetObject = new CodeVariableReferenceExpression(icnOptVar.Name)
                    },
                    Right = new CodeVariableReferenceExpression(icnUriVar.Name)
                }
                    );

                trySt.TryStatements.Add(
                    new CodeAssignStatement {
                    Left  = new CodeFieldReferenceExpression(this.PageTypeReferenceExpression, initialContextNodeField.Name),
                    Right = new CodeMethodInvokeExpression {
                        Method = new CodeMethodReferenceExpression {
                            MethodName   = "CreateNodeReadOnly",
                            TargetObject = new CodePropertyReferenceExpression {
                                PropertyName = "ItemFactory",
                                TargetObject = new CodeVariableReferenceExpression {
                                    VariableName = procVar.Name
                                }
                            }
                        },
                        Parameters =
                        {
                            new CodeVariableReferenceExpression(icnSourceVar.Name),
                            new CodeVariableReferenceExpression(icnOptVar.Name)
                        }
                    }
                }
                    );

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

            statements.Add(trySt);
        }
示例#2
0
        /// <summary>
        /// Creates a method to handle moving the deleted records from the active data model to the deleted data model.
        /// </summary>
        /// <param name="schema">The data model schema.</param>
        public CompressLogMethod(DataModelSchema dataModelSchema)
        {
            //		/// <summary>
            //		/// Compresses multiple updates to a single record and removes deleted records.
            //		/// </summary>
            //		private void CompressLog()
            //		{
            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement("Purges the deleted data model of obsolete rows.", true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            this.Attributes = MemberAttributes.Private | MemberAttributes.Final;
            this.Name       = "CompressLog";

            //			global::System.Collections.Generic.LinkedListNode<TransactionLogItem> currentLink = null;
            this.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeTypeReference("global::System.Collections.Generic.LinkedListNode<TransactionLogItem>"),
                    "currentLink",
                    new CodePrimitiveExpression(null)));

            //			global::System.Collections.Generic.Dictionary<TransactionLogItem, global::System.Collections.Generic.LinkedListNode<TransactionLogItem>> deletedDictionary = new global::System.Collections.Generic.Dictionary<TransactionLogItem, global::System.Collections.Generic.LinkedListNode<TransactionLogItem>>();
            this.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeTypeReference("global::System.Collections.Generic.Dictionary<TransactionLogItem, global::System.Collections.Generic.LinkedListNode<TransactionLogItem>>"),
                    "deletedDictionary",
                    new CodeObjectCreateExpression(
                        new CodeTypeReference("global::System.Collections.Generic.Dictionary<TransactionLogItem, global::System.Collections.Generic.LinkedListNode<TransactionLogItem>>"))));

            //			global::System.Collections.Generic.Dictionary<TransactionLogItem, global::System.Collections.Generic.Dictionary<int, object>> updatedDictionary = new global::System.Collections.Generic.Dictionary<TransactionLogItem, global::System.Collections.Generic.Dictionary<int, object>>();
            this.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeTypeReference("global::System.Collections.Generic.Dictionary<TransactionLogItem, global::System.Collections.Generic.Dictionary<int, object>>"),
                    "updatedDictionary",
                    new CodeObjectCreateExpression(
                        new CodeTypeReference("global::System.Collections.Generic.Dictionary<TransactionLogItem, global::System.Collections.Generic.Dictionary<int, object>>"))));

            //			global::System.Collections.Generic.List<global::System.Collections.Generic.LinkedListNode<TransactionLogItem>> deletedItemList = new global::System.Collections.Generic.List<global::System.Collections.Generic.LinkedListNode<TransactionLogItem>>();
            this.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeTypeReference("global::System.Collections.Generic.List<global::System.Collections.Generic.LinkedListNode<TransactionLogItem>>"),
                    "deletedItemList",
                    new CodeObjectCreateExpression(
                        new CodeTypeReference("global::System.Collections.Generic.List<global::System.Collections.Generic.LinkedListNode<TransactionLogItem>>"))));

            //			global::System.Collections.Generic.List<FieldCollector> updatedItemList = new global::System.Collections.Generic.List<FieldCollector>();
            this.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeTypeReference("global::System.Collections.Generic.List<FieldCollector>"),
                    "updatedItemList",
                    new CodeObjectCreateExpression(new CodeTypeReference("global::System.Collections.Generic.List<FieldCollector>"))));

            //			for (
            //			; true;
            //			)
            //			{
            CodeIterationStatement whileCollecting = new CodeIterationStatement(new CodeSnippetStatement(), new CodePrimitiveExpression(true), new CodeSnippetStatement());

            //				global::System.DateTime currentTime = global::System.DateTime.Now;
            whileCollecting.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(DateTime)),
                    "currentTime",
                    new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(DateTime)), "Now")));

            //				try
            //				{
            CodeTryCatchFinallyStatement tryReadLock = new CodeTryCatchFinallyStatement();

            //					this.transactionLogLock.EnterReadLock();
            tryReadLock.TryStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "transactionLogLock"),
                    "EnterReadLock"));

            //					for (int count = 0; (count < this.transactionLogCompressionSize); count = (count + 1))
            //					{
            CodeIterationStatement forCount = new CodeIterationStatement(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Int32)),
                    "count",
                    new CodePrimitiveExpression(0)),
                new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("count"),
                    CodeBinaryOperatorType.LessThan,
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "transactionLogCompressionSize")),
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("count"),
                    new CodeBinaryOperatorExpression(
                        new CodeVariableReferenceExpression("count"),
                        CodeBinaryOperatorType.Add,
                        new CodePrimitiveExpression(1))));

            //						if ((currentLink == null))
            //						{
            CodeConditionStatement ifListStart = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("currentLink"),
                    CodeBinaryOperatorType.IdentityEquality,
                    new CodePrimitiveExpression(null)));

            //							currentLink = this.transactionLog.Last;
            ifListStart.TrueStatements.Add(
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("currentLink"),
                    new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "transactionLog"), "Last")));

            //						}
            forCount.Statements.Add(ifListStart);

            //						if ((currentLink != null))
            //						{
            CodeConditionStatement ifLink = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("currentLink"),
                    CodeBinaryOperatorType.IdentityInequality,
                    new CodePrimitiveExpression(null)));

            //							if ((currentTime.Subtract(currentLink.Value.timeStamp) > this.transactionLogAge))
            //							{
            CodeConditionStatement ifRecordOld = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                    new CodeMethodInvokeExpression(
                        new CodeVariableReferenceExpression("currentTime"),
                        "Subtract",
                        new CodeFieldReferenceExpression(
                            new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("currentLink"), "Value"),
                            "timeStamp")),
                    CodeBinaryOperatorType.GreaterThan,
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "transactionLogAge")));

            //								object[] transactionLogData = currentLink.Value.data;
            ifRecordOld.TrueStatements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Object[])),
                    "transactionLogData",
                    new CodeFieldReferenceExpression(
                        new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("currentLink"), "Value"),
                        "data")));

            //								if ((((int)(transactionLogData[0])) == global::FluidTrade.Core.RecordState.Deleted))
            //								{
            CodeConditionStatement ifDeleted = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                    new CodeCastExpression(
                        new CodeGlobalTypeReference(typeof(Int32)),
                        new CodeIndexerExpression(new CodeVariableReferenceExpression("transactionLogData"), new CodePrimitiveExpression(0))),
                    CodeBinaryOperatorType.IdentityEquality,
                    new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(RecordState)), "Deleted")));

            //									deletedDictionary.Add(currentLink.Value, currentLink);
            ifDeleted.TrueStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeVariableReferenceExpression("deletedDictionary"),
                    "Add",
                    new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("currentLink"), "Value"),
                    new CodeVariableReferenceExpression("currentLink")));

            //									deletedItemList.Add(currentLink);
            ifDeleted.TrueStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeVariableReferenceExpression("deletedItemList"),
                    "Add",
                    new CodeVariableReferenceExpression("currentLink")));

            //								}
            ifRecordOld.TrueStatements.Add(ifDeleted);

            //								if ((((int)(transactionLogData[0])) == global::FluidTrade.Core.RecordState.Modified))
            //								{
            CodeConditionStatement ifModified = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                    new CodeCastExpression(
                        new CodeGlobalTypeReference(typeof(Int32)),
                        new CodeIndexerExpression(new CodeVariableReferenceExpression("transactionLogData"), new CodePrimitiveExpression(0))),
                    CodeBinaryOperatorType.IdentityEquality,
                    new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(RecordState)), "Modified")));

            //									if (deletedDictionary.ContainsKey(currentLink.Value))
            //									{
            CodeConditionStatement ifInDeletedDictionary0 = new CodeConditionStatement(
                new CodeMethodInvokeExpression(
                    new CodeVariableReferenceExpression("deletedDictionary"),
                    "ContainsKey",
                    new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("currentLink"), "Value")));

            //										deletedItemList.Add(currentLink);
            ifInDeletedDictionary0.TrueStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeVariableReferenceExpression("deletedItemList"),
                    "Add",
                    new CodeVariableReferenceExpression("currentLink")));

            //									}
            //									else
            //									{
            //										int offset = (2 + currentLink.Value.keyLength);
            ifInDeletedDictionary0.FalseStatements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Int32)),
                    "offset",
                    new CodeBinaryOperatorExpression(
                        new CodePrimitiveExpression(2),
                        CodeBinaryOperatorType.Add,
                        new CodeFieldReferenceExpression(
                            new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("currentLink"), "Value"),
                            "keyLength"))));

            //										global::System.Collections.Generic.Dictionary<int, object> fieldTable;
            ifInDeletedDictionary0.FalseStatements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Dictionary <Int32, Object>)),
                    "fieldTable"));

            //										if (updatedDictionary.TryGetValue(currentLink.Value, out fieldTable))
            //										{
            CodeConditionStatement ifInUpdatedDictionary0 = new CodeConditionStatement(
                new CodeMethodInvokeExpression(
                    new CodeVariableReferenceExpression("updatedDictionary"),
                    "TryGetValue",
                    new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("currentLink"), "Value"),
                    new CodeDirectionExpression(FieldDirection.Out, new CodeVariableReferenceExpression("fieldTable"))));

            //											for (int fieldIndex = offset; (fieldIndex < transactionLogData.Length); fieldIndex = (fieldIndex + 2))
            //											{
            CodeIterationStatement forFieldIndex0 = new CodeIterationStatement(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Int32)),
                    "fieldIndex",
                    new CodeVariableReferenceExpression("offset")),
                new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("fieldIndex"),
                    CodeBinaryOperatorType.LessThan,
                    new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("transactionLogData"), "Length")),
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("fieldIndex"),
                    new CodeBinaryOperatorExpression(
                        new CodeVariableReferenceExpression("fieldIndex"),
                        CodeBinaryOperatorType.Add,
                        new CodePrimitiveExpression(2))));

            //												if ((fieldTable.ContainsKey(((int)(transactionLogData[fieldIndex]))) == false))
            //												{
            CodeConditionStatement ifLacksField0 = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                    new CodeMethodInvokeExpression(
                        new CodeVariableReferenceExpression("fieldTable"),
                        "ContainsKey",
                        new CodeCastExpression(
                            new CodeGlobalTypeReference(typeof(Int32)),
                            new CodeIndexerExpression(
                                new CodeVariableReferenceExpression("transactionLogData"),
                                new CodeVariableReferenceExpression("fieldIndex")))),
                    CodeBinaryOperatorType.IdentityEquality,
                    new CodePrimitiveExpression(false)));

            //													fieldTable.Add(((int)(transactionLogData[fieldIndex])), transactionLogData[(fieldIndex + 1)]);
            ifLacksField0.TrueStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeVariableReferenceExpression("fieldTable"),
                    "Add",
                    new CodeCastExpression(
                        new CodeGlobalTypeReference(typeof(Int32)),
                        new CodeIndexerExpression(
                            new CodeVariableReferenceExpression("transactionLogData"),
                            new CodeVariableReferenceExpression("fieldIndex"))),
                    new CodeIndexerExpression(
                        new CodeVariableReferenceExpression("transactionLogData"),
                        new CodeBinaryOperatorExpression(
                            new CodeVariableReferenceExpression("fieldIndex"),
                            CodeBinaryOperatorType.Add,
                            new CodePrimitiveExpression(1)))));

            //												}
            forFieldIndex0.Statements.Add(ifLacksField0);

            //											}
            ifInUpdatedDictionary0.TrueStatements.Add(forFieldIndex0);

            //											deletedItemList.Add(currentLink);
            ifInUpdatedDictionary0.TrueStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeVariableReferenceExpression("deletedItemList"),
                    "Add",
                    new CodeVariableReferenceExpression("currentLink")));

            //										}
            //										else
            //										{
            //											fieldTable = new global::System.Collections.Generic.Dictionary<int, object>();
            ifInUpdatedDictionary0.FalseStatements.Add(
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("fieldTable"),
                    new CodeObjectCreateExpression(
                        new CodeGlobalTypeReference(typeof(Dictionary <Int32, Object>)))));

            //											for (int fieldIndex = offset; (fieldIndex < transactionLogData.Length); fieldIndex = (fieldIndex + 2))
            //											{
            CodeIterationStatement forFieldIndex1 = new CodeIterationStatement(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Int32)),
                    "fieldIndex",
                    new CodeVariableReferenceExpression("offset")),
                new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("fieldIndex"),
                    CodeBinaryOperatorType.LessThan,
                    new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("transactionLogData"), "Length")),
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("fieldIndex"),
                    new CodeBinaryOperatorExpression(
                        new CodeVariableReferenceExpression("fieldIndex"),
                        CodeBinaryOperatorType.Add,
                        new CodePrimitiveExpression(2))));

            //												fieldTable.Add(((int)(transactionLogData[fieldIndex])), transactionLogData[(fieldIndex + 1)]);
            forFieldIndex1.Statements.Add(
                new CodeMethodInvokeExpression(
                    new CodeVariableReferenceExpression("fieldTable"),
                    "Add",
                    new CodeCastExpression(
                        new CodeGlobalTypeReference(typeof(Int32)),
                        new CodeIndexerExpression(
                            new CodeVariableReferenceExpression("transactionLogData"),
                            new CodeVariableReferenceExpression("fieldIndex"))),
                    new CodeIndexerExpression(
                        new CodeVariableReferenceExpression("transactionLogData"),
                        new CodeBinaryOperatorExpression(
                            new CodeVariableReferenceExpression("fieldIndex"),
                            CodeBinaryOperatorType.Add,
                            new CodePrimitiveExpression(1)))));

            //											}
            ifInUpdatedDictionary0.FalseStatements.Add(forFieldIndex1);

            //											updatedDictionary.Add(currentLink.Value, fieldTable);
            ifInUpdatedDictionary0.FalseStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeVariableReferenceExpression("updatedDictionary"),
                    "Add",
                    new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("currentLink"), "Value"),
                    new CodeVariableReferenceExpression("fieldTable")));

            //											updatedItemList.Add(new FieldCollector(currentLink, fieldTable));
            ifInUpdatedDictionary0.FalseStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeVariableReferenceExpression("updatedItemList"),
                    "Add",
                    new CodeObjectCreateExpression(
                        new CodeTypeReference("FieldCollector"),
                        new CodeVariableReferenceExpression("currentLink"),
                        new CodeVariableReferenceExpression("fieldTable"))));

            //										}
            ifInDeletedDictionary0.FalseStatements.Add(ifInUpdatedDictionary0);

            //									}
            ifModified.TrueStatements.Add(ifInDeletedDictionary0);

            //								}
            ifRecordOld.TrueStatements.Add(ifModified);

            //								if ((((int)(transactionLogData[0])) == global::FluidTrade.Core.RecordState.Added))
            //								{
            CodeConditionStatement ifAdded = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                    new CodeCastExpression(
                        new CodeGlobalTypeReference(typeof(Int32)),
                        new CodeIndexerExpression(new CodeVariableReferenceExpression("transactionLogData"), new CodePrimitiveExpression(0))),
                    CodeBinaryOperatorType.IdentityEquality,
                    new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(RecordState)), "Added")));

            //									if (deletedDictionary.ContainsKey(currentLink.Value))
            //									{
            CodeConditionStatement ifInDeletedDictionary1 = new CodeConditionStatement(
                new CodeMethodInvokeExpression(
                    new CodeVariableReferenceExpression("deletedDictionary"),
                    "ContainsKey",
                    new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("currentLink"), "Value")));

            //										deletedItemList.Add(currentLink);
            ifInDeletedDictionary1.TrueStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeVariableReferenceExpression("deletedItemList"),
                    "Add",
                    new CodeVariableReferenceExpression("currentLink")));

            //									}
            //									else
            //									{
            //										global::System.Collections.Generic.Dictionary<int, object> fieldTable;
            ifInDeletedDictionary1.FalseStatements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Dictionary <Int32, Object>)),
                    "fieldTable"));

            //										if (updatedDictionary.TryGetValue(currentLink.Value, out fieldTable))
            //										{
            CodeConditionStatement ifInUpdatedDictionary1 = new CodeConditionStatement(
                new CodeMethodInvokeExpression(
                    new CodeVariableReferenceExpression("updatedDictionary"),
                    "TryGetValue",
                    new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("currentLink"), "Value"),
                    new CodeDirectionExpression(FieldDirection.Out, new CodeVariableReferenceExpression("fieldTable"))));

            //										int offset = (2 + currentLink.Value.keyLength);
            ifInUpdatedDictionary1.TrueStatements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Int32)),
                    "offset",
                    new CodeBinaryOperatorExpression(
                        new CodePrimitiveExpression(2),
                        CodeBinaryOperatorType.Add,
                        new CodeFieldReferenceExpression(
                            new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("currentLink"), "Value"),
                            "keyLength"))));

            //											for (int fieldIndex = offset; (fieldIndex < transactionLogData.Length); fieldIndex = (fieldIndex + 2))
            //											{
            CodeIterationStatement forFieldIndex2 = new CodeIterationStatement(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Int32)),
                    "fieldIndex",
                    new CodeVariableReferenceExpression("offset")),
                new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("fieldIndex"),
                    CodeBinaryOperatorType.LessThan,
                    new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("transactionLogData"), "Length")),
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("fieldIndex"),
                    new CodeBinaryOperatorExpression(
                        new CodeVariableReferenceExpression("fieldIndex"),
                        CodeBinaryOperatorType.Add,
                        new CodePrimitiveExpression(2))));

            //												if ((fieldTable.ContainsKey(((int)(transactionLogData[fieldIndex]))) == false))
            //												{
            CodeConditionStatement ifLacksField1 = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                    new CodeMethodInvokeExpression(
                        new CodeVariableReferenceExpression("fieldTable"),
                        "ContainsKey",
                        new CodeCastExpression(
                            new CodeGlobalTypeReference(typeof(Int32)),
                            new CodeIndexerExpression(
                                new CodeVariableReferenceExpression("transactionLogData"),
                                new CodeVariableReferenceExpression("fieldIndex")))),
                    CodeBinaryOperatorType.IdentityEquality,
                    new CodePrimitiveExpression(false)));

            //													fieldTable.Add(((int)(transactionLogData[fieldIndex])), transactionLogData[(fieldIndex + 1)]);
            ifLacksField1.TrueStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeVariableReferenceExpression("fieldTable"),
                    "Add",
                    new CodeCastExpression(
                        new CodeGlobalTypeReference(typeof(Int32)),
                        new CodeIndexerExpression(
                            new CodeVariableReferenceExpression("transactionLogData"),
                            new CodeVariableReferenceExpression("fieldIndex"))),
                    new CodeIndexerExpression(
                        new CodeVariableReferenceExpression("transactionLogData"),
                        new CodeBinaryOperatorExpression(
                            new CodeVariableReferenceExpression("fieldIndex"),
                            CodeBinaryOperatorType.Add,
                            new CodePrimitiveExpression(1)))));

            //												}
            forFieldIndex2.Statements.Add(ifLacksField1);

            //											}
            ifInUpdatedDictionary1.TrueStatements.Add(forFieldIndex2);

            //											deletedItemList.Add(currentLink);
            ifInUpdatedDictionary1.TrueStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeVariableReferenceExpression("deletedItemList"),
                    "Add",
                    new CodeVariableReferenceExpression("currentLink")));

            //										}
            ifInDeletedDictionary1.FalseStatements.Add(ifInUpdatedDictionary1);

            //									}
            ifAdded.TrueStatements.Add(ifInDeletedDictionary1);

            //								}
            ifRecordOld.TrueStatements.Add(ifAdded);

            //							}
            ifLink.TrueStatements.Add(ifRecordOld);

            //							currentLink = currentLink.Previous;
            ifLink.TrueStatements.Add(
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("currentLink"),
                    new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("currentLink"), "Previous")));

            //						}
            forCount.Statements.Add(ifLink);

            //						if ((currentLink == null))
            //						{
            CodeConditionStatement ifStartOfList = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("currentLink"),
                    CodeBinaryOperatorType.IdentityEquality,
                    new CodePrimitiveExpression(null)));

            //							count = this.transactionLogCompressionSize;
            ifStartOfList.TrueStatements.Add(
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("count"),
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "transactionLogCompressionSize")));

            //							deletedDictionary.Clear();
            ifStartOfList.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("deletedDictionary"), "Clear"));

            //							updatedDictionary.Clear();
            ifStartOfList.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("updatedDictionary"), "Clear"));

            //							this.transactionLogLock.ExitReadLock();
            ifStartOfList.TrueStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "transactionLogLock"),
                    "ExitReadLock"));

            //							global::System.Threading.Thread.Sleep(0);
            ifStartOfList.TrueStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeGlobalTypeReferenceExpression(typeof(Thread)),
                    "Sleep",
                    new CodePrimitiveExpression(0)));

            //							try
            //							{
            CodeTryCatchFinallyStatement tryWriteLock = new CodeTryCatchFinallyStatement();

            //								this.transactionLogLock.EnterWriteLock();
            tryWriteLock.TryStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "transactionLogLock"),
                    "EnterWriteLock"));

            //								for (int deletedIndex = 0; (deletedIndex < deletedItemList.Count); deletedIndex = (deletedIndex + 1))
            //								{
            CodeIterationStatement forDeletedIndex = new CodeIterationStatement(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Int32)),
                    "deletedIndex",
                    new CodePrimitiveExpression(0)),
                new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("deletedIndex"),
                    CodeBinaryOperatorType.LessThan,
                    new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("deletedItemList"), "Count")),
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("deletedIndex"),
                    new CodeBinaryOperatorExpression(
                        new CodeVariableReferenceExpression("deletedIndex"),
                        CodeBinaryOperatorType.Add,
                        new CodePrimitiveExpression(1))));

            //									this.transactionLog.Remove(deletedItemList[deletedIndex]);
            forDeletedIndex.Statements.Add(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "transactionLog"),
                    "Remove",
                    new CodeIndexerExpression(
                        new CodeVariableReferenceExpression("deletedItemList"),
                        new CodeVariableReferenceExpression("deletedIndex"))));

            //								}
            tryWriteLock.TryStatements.Add(forDeletedIndex);

            //								deletedItemList.Clear();
            tryWriteLock.TryStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("deletedItemList"), "Clear"));

            //								for (int updateIndex = 0; (updateIndex < updatedItemList.Count); updateIndex = (updateIndex + 1))
            //								{
            CodeIterationStatement forUpdateIndex = new CodeIterationStatement(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Int32)),
                    "updateIndex",
                    new CodePrimitiveExpression(0)),
                new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("updateIndex"),
                    CodeBinaryOperatorType.LessThan,
                    new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("updatedItemList"), "Count")),
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("updateIndex"),
                    new CodeBinaryOperatorExpression(
                        new CodeVariableReferenceExpression("updateIndex"),
                        CodeBinaryOperatorType.Add,
                        new CodePrimitiveExpression(1))));

            //									FieldCollector fieldCollector = updatedItemList[updateIndex];
            forUpdateIndex.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeTypeReference("FieldCollector"),
                    "fieldCollector",
                    new CodeIndexerExpression(
                        new CodeVariableReferenceExpression("updatedItemList"),
                        new CodeVariableReferenceExpression("updateIndex"))));

            //									global::System.Collections.Generic.Dictionary<int, object> fieldTable = fieldCollector.fieldTable;
            forUpdateIndex.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Dictionary <Int32, Object>)),
                    "fieldTable",
                    new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("fieldCollector"), "fieldTable")));

            //									int keyLength = fieldCollector.linkedListNode.Value.keyLength;
            forUpdateIndex.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Int32)),
                    "keyLength",
                    new CodeFieldReferenceExpression(
                        new CodePropertyReferenceExpression(
                            new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("fieldCollector"), "linkedListNode"),
                            "Value"),
                        "keyLength")));

            //									int offset = (2 + keyLength);
            forUpdateIndex.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Int32)),
                    "offset",
                    new CodeBinaryOperatorExpression(
                        new CodePrimitiveExpression(2),
                        CodeBinaryOperatorType.Add,
                        new CodeVariableReferenceExpression("keyLength"))));

            //									object[] data = new object[(offset
            //															+ (fieldTable.Count * 2))];
            forUpdateIndex.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Object[])),
                    "data",
                    new CodeArrayCreateExpression(
                        new CodeGlobalTypeReference(typeof(Object[])),
                        new CodeBinaryOperatorExpression(
                            new CodeVariableReferenceExpression("offset"),
                            CodeBinaryOperatorType.Add,
                            new CodeBinaryOperatorExpression(
                                new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("fieldTable"), "Count"),
                                CodeBinaryOperatorType.Multiply,
                                new CodePrimitiveExpression(2))))));

            //									data[0] = global::FluidTrade.Core.RecordState.Added;
            forUpdateIndex.Statements.Add(
                new CodeAssignStatement(
                    new CodeIndexerExpression(new CodeVariableReferenceExpression("data"), new CodePrimitiveExpression(0)),
                    new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(RecordState)), "Added")));

            //									data[1] = fieldCollector.linkedListNode.Value.data[1];
            forUpdateIndex.Statements.Add(
                new CodeAssignStatement(
                    new CodeIndexerExpression(new CodeVariableReferenceExpression("data"), new CodePrimitiveExpression(1)),
                    new CodeIndexerExpression(
                        new CodeFieldReferenceExpression(
                            new CodePropertyReferenceExpression(
                                new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("fieldCollector"), "linkedListNode"),
                                "Value"),
                            "data"),
                        new CodePrimitiveExpression(1))));

            //									for (int keyIndex = 2; (keyIndex
            //																< (2 + keyLength)); keyIndex = (keyIndex + 1))
            //									{
            CodeIterationStatement forKeyIndex = new CodeIterationStatement(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Int32)),
                    "keyIndex",
                    new CodePrimitiveExpression(2)),
                new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("keyIndex"),
                    CodeBinaryOperatorType.LessThan,
                    new CodeBinaryOperatorExpression(
                        new CodePrimitiveExpression(2),
                        CodeBinaryOperatorType.Add,
                        new CodeVariableReferenceExpression("keyLength"))),
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("keyIndex"),
                    new CodeBinaryOperatorExpression(
                        new CodeVariableReferenceExpression("keyIndex"),
                        CodeBinaryOperatorType.Add,
                        new CodePrimitiveExpression(1))));

            //										data[keyIndex] = fieldCollector.linkedListNode.Value.data[keyIndex];
            forKeyIndex.Statements.Add(
                new CodeAssignStatement(
                    new CodeIndexerExpression(new CodeVariableReferenceExpression("data"), new CodeVariableReferenceExpression("keyIndex")),
                    new CodeIndexerExpression(
                        new CodeFieldReferenceExpression(
                            new CodePropertyReferenceExpression(
                                new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("fieldCollector"), "linkedListNode"),
                                "Value"),
                            "data"),
                        new CodeVariableReferenceExpression("keyIndex"))));

            //									}
            forUpdateIndex.Statements.Add(forKeyIndex);

            //									int index = offset;
            forUpdateIndex.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Int32)),
                    "index",
                    new CodeVariableReferenceExpression("offset")));

            //									global::System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<int, object>> fieldEnumerator = fieldTable.GetEnumerator();
            forUpdateIndex.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(IEnumerator <KeyValuePair <Int32, Object> >)),
                    "fieldEnumerator",
                    new CodeMethodInvokeExpression(
                        new CodeVariableReferenceExpression("fieldTable"),
                        "GetEnumerator")));

            //								fieldLoop:
            forUpdateIndex.Statements.Add(new CodeLabeledStatement("fieldLoop"));

            //									if ((fieldEnumerator.MoveNext() == false))
            //									{
            CodeConditionStatement ifListEnd = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                    new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("fieldEnumerator"), "MoveNext"),
                    CodeBinaryOperatorType.IdentityEquality,
                    new CodePrimitiveExpression(false)));

            //										goto fieldEnd;
            ifListEnd.TrueStatements.Add(new CodeGotoStatement("fieldEnd"));

            //									}
            forUpdateIndex.Statements.Add(ifListEnd);

            //									data[index] = fieldEnumerator.Current.Key;
            forUpdateIndex.Statements.Add(
                new CodeAssignStatement(
                    new CodeIndexerExpression(new CodeVariableReferenceExpression("data"), new CodeVariableReferenceExpression("index")),
                    new CodePropertyReferenceExpression(
                        new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("fieldEnumerator"), "Current"),
                        "Key")));

            //									index = (index + 1);
            forUpdateIndex.Statements.Add(
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("index"),
                    new CodeBinaryOperatorExpression(
                        new CodeVariableReferenceExpression("index"),
                        CodeBinaryOperatorType.Add,
                        new CodePrimitiveExpression(1))));

            //									data[index] = fieldEnumerator.Current.Value;
            forUpdateIndex.Statements.Add(
                new CodeAssignStatement(
                    new CodeIndexerExpression(new CodeVariableReferenceExpression("data"), new CodeVariableReferenceExpression("index")),
                    new CodePropertyReferenceExpression(
                        new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("fieldEnumerator"), "Current"),
                        "Value")));

            //									index = (index + 1);
            forUpdateIndex.Statements.Add(
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("index"),
                    new CodeBinaryOperatorExpression(
                        new CodeVariableReferenceExpression("index"),
                        CodeBinaryOperatorType.Add,
                        new CodePrimitiveExpression(1))));

            //									goto fieldLoop;
            forUpdateIndex.Statements.Add(new CodeGotoStatement("fieldLoop"));

            //								fieldEnd:
            forUpdateIndex.Statements.Add(new CodeLabeledStatement("fieldEnd"));

            //									fieldCollector.linkedListNode.Value.data = data;
            forUpdateIndex.Statements.Add(
                new CodeAssignStatement(
                    new CodeFieldReferenceExpression(
                        new CodePropertyReferenceExpression(
                            new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("fieldCollector"), "linkedListNode"),
                            "Value"),
                        "data"),
                    new CodeVariableReferenceExpression("data")));

            //								}
            tryWriteLock.TryStatements.Add(forUpdateIndex);

            //								updatedItemList.Clear();
            tryWriteLock.TryStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("updatedItemList"), "Clear"));

            //							}
            //							finally
            //							{
            //								this.transactionLogLock.ExitWriteLock();
            tryWriteLock.FinallyStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "transactionLogLock"),
                    "ExitWriteLock"));

            //							}
            ifStartOfList.TrueStatements.Add(tryWriteLock);

            //							global::System.Threading.Thread.Sleep(this.transactionLogCompressionTime);
            ifStartOfList.TrueStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeGlobalTypeReferenceExpression(typeof(Thread)),
                    "Sleep",
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "transactionLogCompressionTime")));

            //							this.transactionLogLock.EnterReadLock();
            ifStartOfList.TrueStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "transactionLogLock"),
                    "EnterReadLock"));

            //						}
            forCount.Statements.Add(ifStartOfList);

            //					}
            tryReadLock.TryStatements.Add(forCount);

            //				}
            //				finally
            //				{
            //					this.transactionLogLock.ExitReadLock();
            tryReadLock.FinallyStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "transactionLogLock"),
                    "ExitReadLock"));

            //				}
            whileCollecting.Statements.Add(tryReadLock);

            //				global::System.Threading.Thread.Sleep(0);
            whileCollecting.Statements.Add(
                new CodeMethodInvokeExpression(new CodeGlobalTypeReferenceExpression(typeof(Thread)), "Sleep", new CodePrimitiveExpression(0)));

            //			}
            this.Statements.Add(whileCollecting);

            //		}
        }
示例#3
0
        public override async System.Threading.Tasks.Task GCode_CodeDom_GenerateCode(CodeTypeDeclaration codeClass, CodeStatementCollection codeStatementCollection, CodeGenerateSystem.Base.LinkPinControl element, CodeGenerateSystem.Base.GenerateCodeContext_Method context)
        {
            if (element == null || element == mCtrlMethodIn)
            {
                var param     = CSParam as ClassCastControlConstructParam;
                var paramName = GCode_GetValueName(mCastResultPin, context);

                if (!mTargetPin.GetLinkedObject(0).IsOnlyReturnValue)
                {
                    await mTargetPin.GetLinkedObject(0).GCode_CodeDom_GenerateCode(codeClass, codeStatementCollection, mTargetPin.GetLinkedPinControl(0), context);
                }

                if (!context.Method.Statements.Contains(mVariableDeclaration))
                {
                    mVariableDeclaration = new CodeVariableDeclarationStatement(param.ResultType, paramName, new CodePrimitiveExpression(null));
                    context.Method.Statements.Insert(0, mVariableDeclaration);
                }

                #region Debug
                // 收集用于调试的数据的代码
                var debugCodes = CodeDomNode.BreakPoint.BeginMacrossDebugCodeStatments(codeStatementCollection);
                CodeDomNode.BreakPoint.GetGatherDataValueCodeStatement(debugCodes, TargetPin.GetLinkPinKeyName(), GCode_CodeDom_GetValue(mTargetPin, context), GCode_GetTypeString(mTargetPin, context), context);
                var breakCondStatement = CodeDomNode.BreakPoint.BreakCodeStatement(codeClass, debugCodes, HostNodesContainer.GUID, Id);
                CodeDomNode.BreakPoint.EndMacrossDebugCodeStatements(codeStatementCollection, debugCodes);
                #endregion

                var tryCatchStatement = new CodeTryCatchFinallyStatement();
                codeStatementCollection.Add(tryCatchStatement);
                tryCatchStatement.TryStatements.Add(new CodeAssignStatement(
                                                        new CodeVariableReferenceExpression(paramName),
                                                        new CodeGenerateSystem.CodeDom.CodeCastExpression(
                                                            param.ResultType,
                                                            mTargetPin.GetLinkedObject(0).GCode_CodeDom_GetValue(mTargetPin.GetLinkedPinControl(0), context))));

                var catchClause = new CodeCatchClause("catchException", new CodeTypeReference(typeof(System.Exception)),
                                                      new CodeAssignStatement(
                                                          new CodeVariableReferenceExpression(paramName),
                                                          new CodePrimitiveExpression(null)));
                tryCatchStatement.CatchClauses.Add(catchClause);

                #region Debug
                // 转换之后收集一次数据
                var debugCodesAfter = CodeDomNode.BreakPoint.BeginMacrossDebugCodeStatments(codeStatementCollection);
                CodeDomNode.BreakPoint.GetGatherDataValueCodeStatement(debugCodesAfter, CastResultPin.GetLinkPinKeyName(), GCode_CodeDom_GetValue(CastResultPin, context), GCode_GetTypeString(CastResultPin, context), context);
                CodeDomNode.BreakPoint.EndMacrossDebugCodeStatements(codeStatementCollection, debugCodesAfter);
                #endregion

                var condStatement = new CodeConditionStatement();
                codeStatementCollection.Add(condStatement);
                condStatement.Condition = new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression(paramName),
                    CodeBinaryOperatorType.IdentityInequality,
                    new CodePrimitiveExpression(null));

                if (mCtrlMethodOut.HasLink)
                {
                    await mCtrlMethodOut.GetLinkedObject(0).GCode_CodeDom_GenerateCode(codeClass, condStatement.TrueStatements, mCtrlMethodOut.GetLinkedPinControl(0), context);
                }
                if (mCastFailedPin.HasLink)
                {
                    await mCastFailedPin.GetLinkedObject(0).GCode_CodeDom_GenerateCode(codeClass, condStatement.FalseStatements, mCastFailedPin.GetLinkedPinControl(0), context);
                }
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
示例#4
0
 protected override void GenerateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e)
 {
 }
示例#5
0
 public CodeTryCatchFinallyStatement Try(
     Action genTryStatements,
     IEnumerable<CodeCatchClause> catchClauses,
     Action genFinallyStatements)
 {
     var t = new CodeTryCatchFinallyStatement();
     var oldScope = Scope;
     Scope = t.TryStatements;
     genTryStatements();
     t.CatchClauses.AddRange(catchClauses);
     Scope = t.FinallyStatements;
     genFinallyStatements();
     Scope = oldScope;
     Scope.Add(t);
     return t;
 }
示例#6
0
        private void ValidateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e)
        {
            ValidateStatements(e.TryStatements);
            CodeCatchClauseCollection catches = e.CatchClauses;
            if (catches.Count > 0)
            {
                foreach (CodeCatchClause current in catches)
                {
                    ValidateTypeReference(current.CatchExceptionType);
                    ValidateIdentifier(current, nameof(current.LocalName), current.LocalName);
                    ValidateStatements(current.Statements);
                }
            }

            CodeStatementCollection finallyStatements = e.FinallyStatements;
            if (finallyStatements.Count > 0)
            {
                ValidateStatements(finallyStatements);
            }
        }
示例#7
0
        /// <summary>
        /// Creates the CodeDOM for a method to delete a record from a table using transacted logic.
        /// </summary>
        /// <param name="tableSchema">A description of the table.</param>
        public Delete(TableSchema tableSchema)
        {
            // Initialize the object.
            this.tableSchema = tableSchema;

            // To reduce the frequency of deadlocking, the tables are always locked in alphabetical order.  This section collects
            // all the table locks that are used for this operation and organizes them in a list that is used to generate the
            // locking and releasing statements below.
            List <LockRequest> tableLockList = new List <LockRequest>();

            foreach (TableSchema familyTable in tableSchema.TableHierarchy)
            {
                tableLockList.Add(new WriteRequest(familyTable));
            }
            foreach (TableSchema childTable in tableSchema.Descendants)
            {
                tableLockList.Add(new WriteRequest(childTable));
            }
            tableLockList.Sort();

            // Shorthand notations for the elements used to construct the interface to this table:
            string tableTypeName        = string.Format("{0}.{1}DataTable", tableSchema.DataModelSchema.Name, tableSchema.Name);
            string tableVariableName    = string.Format("{0}Table", tableSchema.Name[0].ToString().ToLower() + tableSchema.Name.Remove(0, 1));
            string rowTypeName          = string.Format("{0}.{1}Row", tableSchema.DataModelSchema.Name, tableSchema.Name);
            string rowVariableName      = string.Format("{0}Row", tableSchema.Name[0].ToString().ToLower() + tableSchema.Name.Remove(0, 1));
            string identityColumnName   = tableSchema.PrimaryKey == null ? string.Empty : tableSchema.PrimaryKey.Fields[0].Name;
            string identityVariableName = tableSchema.PrimaryKey == null ? string.Empty : identityColumnName[0].ToString().ToLower() + identityColumnName.Remove(0, 1);

            //		/// <summary>Deletes a Employee record.</summary>
            //		/// <param name="employeeId">The value for the EmployeeId column.</param>
            //		/// <param name="rowVersion">Used for Optimistic Concurrency Checking.</param>
            //		public static void Delete(int employeeId, ref long rowVersion)
            //		{
            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement(string.Format("Deletes a {0} record.", tableSchema.Name), true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            foreach (ColumnSchema columnSchema in tableSchema.Columns)
            {
                if (tableSchema.IsPrimaryKeyColumn(columnSchema) && columnSchema.DeclaringType == tableSchema.TypeSchema)
                {
                    this.Comments.Add(new CodeCommentStatement(string.Format(@"<param name=""{0}"">The value for the {1} column.</param>", Generate.CamelCase(columnSchema.Name), columnSchema.Name), true));
                }
            }
            this.Comments.Add(new CodeCommentStatement(@"<param name=""rowVersion"">Used for Optimistic Concurrency Checking.</param>", true));
            this.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
            this.Name       = "Delete";
            foreach (ColumnSchema columnSchema in tableSchema.Columns)
            {
                if (tableSchema.IsPrimaryKeyColumn(columnSchema) && columnSchema.DeclaringType == tableSchema.TypeSchema)
                {
                    Type typeColumn    = columnSchema.DataType;
                    Type parameterType = tableSchema.IsPrimaryKeyColumn(columnSchema) ? typeColumn : typeof(object);
                    CodeParameterDeclarationExpression parameter = new CodeParameterDeclarationExpression(parameterType, Generate.CamelCase(columnSchema.Name));
                    this.Parameters.Add(parameter);
                }
            }
            CodeParameterDeclarationExpression rowVersionParameter = new CodeParameterDeclarationExpression(typeof(long), "rowVersion");

            this.Parameters.Add(rowVersionParameter);

            //			// This method is part of a larger transaction.  Instead of passing the transaction and the resource managers down
            //			// through several layers of methods, they are acccessed as ambient properties of the Transaction class.
            //			Transaction transaction = Transaction.Current;
            //			AdoResourceManager adoResourceManager = ((AdoResourceManager)(transaction["ADO Data Model"]));
            //			SqlResourceManager sqlResourceManager = ((SqlResourceManager)(transaction["SQL Data Model"]));
            this.Statements.Add(new CodeCommentStatement("This method is part of a larger transaction.  Instead of passing the transaction and the resource managers down"));
            this.Statements.Add(new CodeCommentStatement("through several layers of methods, they are acccessed as ambient properties of the Transaction class."));
            this.Statements.Add(new CodeVariableDeclarationStatement("Transaction", "transaction", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("Transaction"), "Current")));
            this.Statements.Add(new CodeVariableDeclarationStatement("AdoResourceManager", "adoResourceManager", new CodeCastExpression("AdoResourceManager", new CodeIndexerExpression(new CodeVariableReferenceExpression("transaction"), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(string.Format("{0}DataTable", tableSchema.Name)), "VolatileResource")))));
            this.Statements.Add(new CodeVariableDeclarationStatement("SqlResourceManager", "sqlResourceManager", new CodeCastExpression("SqlResourceManager", new CodeIndexerExpression(new CodeVariableReferenceExpression("transaction"), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(string.Format("{0}DataTable", tableSchema.Name)), "DurableResource")))));

            //				// This is used below to assemble the SQL commands.
            //				SqlCommand sqlCommand = null;
            this.Statements.Add(new CodeCommentStatement("This is used below to assemble the SQL commands."));
            this.Statements.Add(new CodeVariableDeclarationStatement("SqlCommand", "sqlCommand", new CodePrimitiveExpression(null)));

            //				// The Department record is locked for the duration of the transaction.
            //				ServerDataModel.DepartmentRow departmentRow = ((ServerDataModel.DepartmentRow)(ServerDataModel.Department.FindByDepartmentId(departmentId)));
            //				if ((departmentRow == null))
            //				{
            //					throw new System.Exception(string.Format("Attempt to update a Department record ({0}) that doesn\'t exist", departmentId));
            //				}
            //				departmentRow.ReaderWriterLock.AcquireWriterLock(System.Threading.Timeout.Infinite);
            TableSchema rootTable = tableSchema.RootTable;

            this.Statements.Add(new CodeCommentStatement(string.Format("The {0} record is deleted from the most distant descendant back up to the root object in order to preserved", rootTable.Name)));
            this.Statements.Add(new CodeCommentStatement("the integrity of the cascading relations."));
            string rowVariable      = string.Format("{0}Row", Generate.CamelCase(rootTable.Name));
            string rowType          = string.Format("{0}.{1}Row", tableSchema.DataModelSchema.Name, rootTable.Name);
            string findMethodName   = string.Format("FindBy");
            string exceptionFormat  = string.Empty;
            int    parameterCounter = 0;
            List <CodeExpression> methodParameters    = new List <CodeExpression>();
            List <CodeExpression> exceptionParameters = new List <CodeExpression>();

            if (tableSchema.PrimaryKey != null)
            {
                foreach (ColumnSchema columnSchema in tableSchema.PrimaryKey.Fields)
                {
                    methodParameters.Add(new CodeArgumentReferenceExpression(Generate.CamelCase(columnSchema.Name)));
                    exceptionParameters.Add(new CodeArgumentReferenceExpression(Generate.CamelCase(columnSchema.Name)));
                    exceptionFormat += string.Format("{{0}}", parameterCounter++);
                }
                foreach (ColumnSchema columnSchema in rootTable.PrimaryKey.Fields)
                {
                    findMethodName += columnSchema.Name;
                }
            }
            exceptionParameters.Insert(0, new CodePrimitiveExpression(string.Format("Attempt to delete a {0} record ({1}) that doesn't exist", rootTable.Name, exceptionFormat)));
            this.Statements.Add(new CodeVariableDeclarationStatement(string.Format("{0}.{1}Row", tableSchema.DataModelSchema.Name, rootTable.Name), rowVariable, new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(tableSchema.DataModelSchema.Name), rootTable.Name), findMethodName, methodParameters.ToArray())));
            this.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression(rowVariable), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null)),
                                                           new CodeThrowExceptionStatement(new CodeObjectCreateExpression("MarkThree.RecordNotFoundException", exceptionParameters.ToArray()))));
            this.Statements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(rowVariable), "ReaderWriterLock"), "AcquireWriterLock", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.Threading.Timeout)), "Infinite")));
            this.Statements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("adoResourceManager"), "Add", new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(rowVariable), "ReaderWriterLock"))));

            DeleteChildren(rootTable, this.Statements);

            //					// Delete the Department record from the SQL data model.
            //					sqlCommand = new SqlCommand("delete \"Department\" where \"DepartmentId\"=@departmentId", sqlResourceManager.SqlConnection);
            //					sqlCommand.Parameters.Add(new SqlParameter("@departmentId", SqlDbType.Int, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, departmentRow[ServerDataModel.Department.DepartmentIdColumn]));
            //					sqlCommands.Add(sqlCommand);
            if (tableSchema.IsPersistent)
            {
                this.Statements.Add(new CodeCommentStatement(string.Format("Delete the {0} record from the SQL data model.", rootTable.Name)));
                string whereClause = string.Empty;
                if (rootTable.PrimaryKey != null)
                {
                    foreach (ColumnSchema columnSchema in rootTable.PrimaryKey.Fields)
                    {
                        whereClause += string.Format("\"{0}\"=@{1}", columnSchema.Name, Generate.CamelCase(columnSchema.Name));
                    }
                }
                string deleteCommandText = string.Format("delete \"{0}\" where {1}", rootTable.Name, whereClause);
                this.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("sqlCommand"), new CodeObjectCreateExpression("SqlCommand", new CodePrimitiveExpression(deleteCommandText), new CodeFieldReferenceExpression(new CodeArgumentReferenceExpression("sqlResourceManager"), "SqlConnection"))));
                if (rootTable.PrimaryKey != null)
                {
                    foreach (ColumnSchema columnSchema in rootTable.PrimaryKey.Fields)
                    {
                        string         variableName   = Generate.CamelCase(columnSchema.Name);
                        CodeExpression codeExpression = new CodeIndexerExpression(new CodeVariableReferenceExpression(string.Format("{0}Row", Generate.CamelCase(rootTable.Name))), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(string.Format("{0}.{1}", tableSchema.DataModelSchema.Name, rootTable.Name)), string.Format("{0}Column", columnSchema.Name)));
                        this.Statements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("sqlCommand"), "Parameters"), "Add", new CodeExpression[] { new CodeObjectCreateExpression("SqlParameter", new CodeExpression[] { new CodePrimitiveExpression(string.Format("@{0}", variableName)), TypeConverter.Convert(columnSchema.DataType), new CodePrimitiveExpression(0), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("ParameterDirection"), "Input"), new CodePrimitiveExpression(false), new CodePrimitiveExpression(0), new CodePrimitiveExpression(0), new CodePrimitiveExpression(null), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DataRowVersion"), "Current"), codeExpression }) }));
                    }
                }
                this.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("sqlCommand"), "ExecuteNonQuery"));
            }

            //					// Delete the Department record from the ADO data model.
            //					adoResourceManager.Add(departmentRow);
            //					departmentRow[ServerDataModel.Department.RowVersionColumn] = ServerDataModel.IncrementRowVersion();
            //					departmentRow.Delete();
            this.Statements.Add(new CodeCommentStatement(string.Format("Delete the {0} record from the ADO data model.", rootTable.Name)));
            this.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("adoResourceManager"), "Add", new CodeVariableReferenceExpression(rowVariable)));
            CodeTryCatchFinallyStatement tryFinallyStatement = new CodeTryCatchFinallyStatement();

            tryFinallyStatement.TryStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(rowVariable), "BeginEdit"));
            tryFinallyStatement.TryStatements.Add(new CodeAssignStatement(new CodeIndexerExpression(new CodeVariableReferenceExpression(rowVariable), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(string.Format("{0}.{1}", tableSchema.DataModelSchema.Name, rootTable.Name)), "RowVersionColumn")), new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(tableSchema.DataModelSchema.Name), "IncrementRowVersion")));
            tryFinallyStatement.TryStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(rowVariable), "Delete"));
            tryFinallyStatement.FinallyStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(rowVariable), "EndEdit"));
            this.Statements.Add(tryFinallyStatement);
        }
        public void ProviderSupports()
        {
            CodeDomProvider provider = GetProvider();

            var cu = new CodeCompileUnit();
            var nspace = new CodeNamespace("NSPC");
            nspace.Imports.Add(new CodeNamespaceImport("System"));
            nspace.Imports.Add(new CodeNamespaceImport("System.Drawing"));
            nspace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
            nspace.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
            cu.Namespaces.Add(nspace);

            var cd = new CodeTypeDeclaration("TEST");
            cd.IsClass = true;
            nspace.Types.Add(cd);

            // Arrays of Arrays
            var cmm = new CodeMemberMethod();
            cmm.Name = "ArraysOfArrays";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public;
            if (provider.Supports(GeneratorSupport.ArraysOfArrays))
            {
                cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int[][])),
                    "arrayOfArrays", new CodeArrayCreateExpression(typeof(int[][]),
                    new CodeArrayCreateExpression(typeof(int[]), new CodePrimitiveExpression(3), new CodePrimitiveExpression(4)),
                    new CodeArrayCreateExpression(typeof(int[]), new CodeExpression[] { new CodePrimitiveExpression(1) }))));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeArrayIndexerExpression(
                    new CodeArrayIndexerExpression(new CodeVariableReferenceExpression("arrayOfArrays"), new CodePrimitiveExpression(0))
                    , new CodePrimitiveExpression(1))));
            }
            else
            {
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(0)));
            }
            cd.Members.Add(cmm);

            // assembly attributes
            if (provider.Supports(GeneratorSupport.AssemblyAttributes))
            {
                CodeAttributeDeclarationCollection attrs = cu.AssemblyCustomAttributes;
                attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new
                    CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly"))));
                attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new
                    CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2"))));
            }

            CodeTypeDeclaration class1 = new CodeTypeDeclaration();
            if (provider.Supports(GeneratorSupport.ChainedConstructorArguments))
            {
                class1.Name = "Test2";
                class1.IsClass = true;
                nspace.Types.Add(class1);

                class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(String)), "stringField"));
                CodeMemberProperty prop = new CodeMemberProperty();
                prop.Name = "accessStringField";
                prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                prop.Type = new CodeTypeReference(typeof(String));
                prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
                    "stringField")));
                prop.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new
                    CodeThisReferenceExpression(), "stringField"),
                    new CodePropertySetValueReferenceExpression()));
                class1.Members.Add(prop);

                CodeConstructor cctor = new CodeConstructor();
                cctor.Attributes = MemberAttributes.Public;
                cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression("testingString"));
                cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null));
                cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null));
                class1.Members.Add(cctor);

                CodeConstructor cc = new CodeConstructor();
                cc.Attributes = MemberAttributes.Public | MemberAttributes.Overloaded;
                cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p1"));
                cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p2"));
                cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p3"));
                cc.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression()
                    , "stringField"), new CodeVariableReferenceExpression("p1")));
                class1.Members.Add(cc);
                // verify chained constructors work
                cmm = new CodeMemberMethod();
                cmm.Name = "ChainedConstructorUse";
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.ReturnType = new CodeTypeReference(typeof(String));
                // utilize constructor
                cmm.Statements.Add(new CodeVariableDeclarationStatement("Test2", "t", new CodeObjectCreateExpression("Test2")));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression(
                    new CodeVariableReferenceExpression("t"), "accessStringField")));
                cd.Members.Add(cmm);
            }

            // complex expressions
            if (provider.Supports(GeneratorSupport.ComplexExpressions))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "ComplexExpressions";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public;
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
                cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("i"),
                    new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Multiply,
                    new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add,
                    new CodePrimitiveExpression(3)))));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("i")));
                cd.Members.Add(cmm);
            }

            if (provider.Supports(GeneratorSupport.DeclareEnums))
            {
                CodeTypeDeclaration ce = new CodeTypeDeclaration("DecimalEnum");
                ce.IsEnum = true;
                nspace.Types.Add(ce);

                // things to enumerate
                for (int k = 0; k < 5; k++)
                {
                    CodeMemberField Field = new CodeMemberField("System.Int32", "Num" + (k).ToString());
                    Field.InitExpression = new CodePrimitiveExpression(k);
                    ce.Members.Add(Field);
                }
                cmm = new CodeMemberMethod();
                cmm.Name = "OutputDecimalEnumVal";
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
                cmm.Parameters.Add(param);
                CodeBinaryOperatorExpression eq = new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality,
                    new CodePrimitiveExpression(3));
                CodeMethodReturnStatement truestmt = new CodeMethodReturnStatement(
                    new CodeCastExpression(typeof(int),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num3")));
                CodeConditionStatement condstmt = new CodeConditionStatement(eq, truestmt);
                cmm.Statements.Add(condstmt);

                eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
                    CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(4));
                truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num4")));
                condstmt = new CodeConditionStatement(eq, truestmt);
                cmm.Statements.Add(condstmt);
                eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
                    CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(2));
                truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num2")));
                condstmt = new CodeConditionStatement(eq, truestmt);
                cmm.Statements.Add(condstmt);

                eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
                    CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(1));
                truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num1")));
                condstmt = new CodeConditionStatement(eq, truestmt);
                cmm.Statements.Add(condstmt);

                eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
                    CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(0));
                truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num0")));
                condstmt = new CodeConditionStatement(eq, truestmt);
                cmm.Statements.Add(condstmt);

                cmm.ReturnType = new CodeTypeReference("System.int32");

                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(10))));
                cd.Members.Add(cmm);
            }

            if (provider.Supports(GeneratorSupport.DeclareInterfaces))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "TestSingleInterface";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.Statements.Add(new CodeVariableDeclarationStatement("TestSingleInterfaceImp", "t", new CodeObjectCreateExpression("TestSingleInterfaceImp")));
                CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t")
                    , "InterfaceMethod");
                methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i"));
                cmm.Statements.Add(new CodeMethodReturnStatement(methodinvoke));
                cd.Members.Add(cmm);

                class1 = new CodeTypeDeclaration("InterfaceA");
                class1.IsInterface = true;
                nspace.Types.Add(class1);
                cmm = new CodeMemberMethod();
                cmm.Attributes = MemberAttributes.Public;
                cmm.Name = "InterfaceMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
                class1.Members.Add(cmm);

                if (provider.Supports(GeneratorSupport.MultipleInterfaceMembers))
                {
                    CodeTypeDeclaration classDecl = new CodeTypeDeclaration("InterfaceB");
                    classDecl.IsInterface = true;
                    nspace.Types.Add(classDecl);
                    cmm = new CodeMemberMethod();
                    cmm.Name = "InterfaceMethod";
                    cmm.Attributes = MemberAttributes.Public;
                    cmm.ReturnType = new CodeTypeReference(typeof(int));
                    cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
                    classDecl.Members.Add(cmm);

                    CodeTypeDeclaration class2 = new CodeTypeDeclaration("TestMultipleInterfaceImp");
                    class2.BaseTypes.Add(new CodeTypeReference("System.Object"));
                    class2.BaseTypes.Add(new CodeTypeReference("InterfaceB"));
                    class2.BaseTypes.Add(new CodeTypeReference("InterfaceA"));
                    class2.IsClass = true;
                    nspace.Types.Add(class2);
                    cmm = new CodeMemberMethod();
                    cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA"));
                    cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceB"));
                    cmm.Name = "InterfaceMethod";
                    cmm.ReturnType = new CodeTypeReference(typeof(int));
                    cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
                    cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                    cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
                    class2.Members.Add(cmm);

                    cmm = new CodeMemberMethod();
                    cmm.Name = "TestMultipleInterfaces";
                    cmm.ReturnType = new CodeTypeReference(typeof(int));
                    cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
                    cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                    cmm.Statements.Add(new CodeVariableDeclarationStatement("TestMultipleInterfaceImp", "t", new CodeObjectCreateExpression("TestMultipleInterfaceImp")));
                    cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceA", "interfaceAobject", new CodeCastExpression("InterfaceA",
                        new CodeVariableReferenceExpression("t"))));
                    cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceB", "interfaceBobject", new CodeCastExpression("InterfaceB",
                        new CodeVariableReferenceExpression("t"))));
                    methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceAobject")
                        , "InterfaceMethod");
                    methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i"));
                    CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceBobject")
                        , "InterfaceMethod");
                    methodinvoke2.Parameters.Add(new CodeVariableReferenceExpression("i"));
                    cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(
                        methodinvoke,
                        CodeBinaryOperatorType.Subtract, methodinvoke2)));
                    cd.Members.Add(cmm);
                }

                class1 = new CodeTypeDeclaration("TestSingleInterfaceImp");
                class1.BaseTypes.Add(new CodeTypeReference("System.Object"));
                class1.BaseTypes.Add(new CodeTypeReference("InterfaceA"));
                class1.IsClass = true;
                nspace.Types.Add(class1);
                cmm = new CodeMemberMethod();
                cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA"));
                cmm.Name = "InterfaceMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
                cmm.Attributes = MemberAttributes.Public;
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
                class1.Members.Add(cmm);
            }

            if (provider.Supports(GeneratorSupport.DeclareValueTypes))
            {
                CodeTypeDeclaration structA = new CodeTypeDeclaration("structA");
                structA.IsStruct = true;

                CodeTypeDeclaration structB = new CodeTypeDeclaration("structB");
                structB.Attributes = MemberAttributes.Public;
                structB.IsStruct = true;

                CodeMemberField firstInt = new CodeMemberField(typeof(int), "int1");
                firstInt.Attributes = MemberAttributes.Public;
                structB.Members.Add(firstInt);

                CodeMemberField innerStruct = new CodeMemberField("structB", "innerStruct");
                innerStruct.Attributes = MemberAttributes.Public;

                structA.Members.Add(structB);
                structA.Members.Add(innerStruct);
                nspace.Types.Add(structA);

                CodeMemberMethod nestedStructMethod = new CodeMemberMethod();
                nestedStructMethod.Name = "NestedStructMethod";
                nestedStructMethod.ReturnType = new CodeTypeReference(typeof(int));
                nestedStructMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                CodeVariableDeclarationStatement varStructA = new CodeVariableDeclarationStatement("structA", "varStructA");
                nestedStructMethod.Statements.Add(varStructA);
                nestedStructMethod.Statements.Add
                    (
                    new CodeAssignStatement
                    (
                    /* Expression1 */ new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1"),
                    /* Expression1 */ new CodePrimitiveExpression(3)
                    )
                    );
                nestedStructMethod.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1")));
                cd.Members.Add(nestedStructMethod);
            }
            if (provider.Supports(GeneratorSupport.EntryPointMethod))
            {
                CodeEntryPointMethod cep = new CodeEntryPointMethod();
                cd.Members.Add(cep);
            }
            // goto statements
            if (provider.Supports(GeneratorSupport.GotoStatements))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "GoToMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
                cmm.Parameters.Add(param);
                CodeConditionStatement condstmt = new CodeConditionStatement(new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(1)),
                    new CodeGotoStatement("comehere"));
                cmm.Statements.Add(condstmt);
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(6)));
                cmm.Statements.Add(new CodeLabeledStatement("comehere",
                    new CodeMethodReturnStatement(new CodePrimitiveExpression(7))));
                cd.Members.Add(cmm);
            }
            if (provider.Supports(GeneratorSupport.NestedTypes))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "CallingPublicNestedScenario";
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference
                    ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"), "t",
                    new CodeObjectCreateExpression(new CodeTypeReference
                    ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"))));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"),
                    "publicNestedClassesMethod",
                    new CodeVariableReferenceExpression("i"))));
                cd.Members.Add(cmm);

                class1 = new CodeTypeDeclaration("PublicNestedClassA");
                class1.IsClass = true;
                nspace.Types.Add(class1);
                CodeTypeDeclaration nestedClass = new CodeTypeDeclaration("PublicNestedClassB1");
                nestedClass.IsClass = true;
                nestedClass.TypeAttributes = TypeAttributes.NestedPublic;
                class1.Members.Add(nestedClass);
                nestedClass = new CodeTypeDeclaration("PublicNestedClassB2");
                nestedClass.TypeAttributes = TypeAttributes.NestedPublic;
                nestedClass.IsClass = true;
                class1.Members.Add(nestedClass);
                CodeTypeDeclaration innerNestedClass = new CodeTypeDeclaration("PublicNestedClassC");
                innerNestedClass.TypeAttributes = TypeAttributes.NestedPublic;
                innerNestedClass.IsClass = true;
                nestedClass.Members.Add(innerNestedClass);
                cmm = new CodeMemberMethod();
                cmm.Name = "publicNestedClassesMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
                innerNestedClass.Members.Add(cmm);
            }
            // Parameter Attributes
            if (provider.Supports(GeneratorSupport.ParameterAttributes))
            {
                CodeMemberMethod method1 = new CodeMemberMethod();
                method1.Name = "MyMethod";
                method1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression(typeof(string), "blah");
                param1.CustomAttributes.Add(
                    new CodeAttributeDeclaration(
                    "System.Xml.Serialization.XmlElementAttribute",
                    new CodeAttributeArgument(
                    "Form",
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
                    new CodeAttributeArgument(
                    "IsNullable",
                    new CodePrimitiveExpression(false))));
                method1.Parameters.Add(param1);
                cd.Members.Add(method1);
            }
            // public static members
            if (provider.Supports(GeneratorSupport.PublicStaticMembers))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "PublicStaticMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(16)));
                cd.Members.Add(cmm);
            }
            // reference parameters
            if (provider.Supports(GeneratorSupport.ReferenceParameters))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "Work";
                cmm.ReturnType = new CodeTypeReference("System.void");
                cmm.Attributes = MemberAttributes.Static;
                // add parameter with ref direction
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
                param.Direction = FieldDirection.Ref;
                cmm.Parameters.Add(param);
                // add parameter with out direction
                param = new CodeParameterDeclarationExpression(typeof(int), "j");
                param.Direction = FieldDirection.Out;
                cmm.Parameters.Add(param);
                cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("i"),
                    new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression("i"),
                    CodeBinaryOperatorType.Add, new CodePrimitiveExpression(4))));
                cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("j"),
                    new CodePrimitiveExpression(5)));
                cd.Members.Add(cmm);

                cmm = new CodeMemberMethod();
                cmm.Name = "CallingWork";
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                CodeParameterDeclarationExpression parames = new CodeParameterDeclarationExpression(typeof(int), "a");
                cmm.Parameters.Add(parames);
                cmm.ReturnType = new CodeTypeReference("System.int32");
                cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"),
                    new CodePrimitiveExpression(10)));
                cmm.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "b"));
                // invoke the method called "work"
                CodeMethodInvokeExpression methodinvoked = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression
                    (new CodeTypeReferenceExpression("TEST"), "Work"));
                // add parameter with ref direction
                CodeDirectionExpression parameter = new CodeDirectionExpression(FieldDirection.Ref,
                    new CodeVariableReferenceExpression("a"));
                methodinvoked.Parameters.Add(parameter);
                // add parameter with out direction
                parameter = new CodeDirectionExpression(FieldDirection.Out, new CodeVariableReferenceExpression("b"));
                methodinvoked.Parameters.Add(parameter);
                cmm.Statements.Add(methodinvoked);
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression
                    (new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression("b"))));
                cd.Members.Add(cmm);
            }
            if (provider.Supports(GeneratorSupport.ReturnTypeAttributes))
            {
                CodeMemberMethod function1 = new CodeMemberMethod();
                function1.Name = "MyFunction";
                function1.ReturnType = new CodeTypeReference(typeof(string));
                function1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                function1.ReturnTypeCustomAttributes.Add(new
                    CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute"));
                function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new
                    CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new
                    CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe"))));
                function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return")));
                cd.Members.Add(function1);
            }
            if (provider.Supports(GeneratorSupport.StaticConstructors))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "TestStaticConstructor";
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a");
                cmm.Parameters.Add(param);
                // utilize constructor
                cmm.Statements.Add(new CodeVariableDeclarationStatement("Test4", "t", new CodeObjectCreateExpression("Test4")));
                // set then get number
                cmm.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("t"), "i")
                    , new CodeVariableReferenceExpression("a")));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression(
                    new CodeVariableReferenceExpression("t"), "i")));
                cd.Members.Add(cmm);

                class1 = new CodeTypeDeclaration();
                class1.Name = "Test4";
                class1.IsClass = true;
                nspace.Types.Add(class1);

                class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(int)), "number"));
                CodeMemberProperty prop = new CodeMemberProperty();
                prop.Name = "i";
                prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                prop.Type = new CodeTypeReference(typeof(int));
                prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("number")));
                prop.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("number"),
                    new CodePropertySetValueReferenceExpression()));
                class1.Members.Add(prop);
                CodeTypeConstructor ctc = new CodeTypeConstructor();
                class1.Members.Add(ctc);
            }
            if (provider.Supports(GeneratorSupport.TryCatchStatements))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "TryCatchMethod";
                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);
            }
            if (provider.Supports(GeneratorSupport.DeclareEvents))
            {
                CodeNamespace ns = new CodeNamespace();
                ns.Name = "MyNamespace";
                ns.Imports.Add(new CodeNamespaceImport("System"));
                ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));
                ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
                ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
                cu.Namespaces.Add(ns);
                class1 = new CodeTypeDeclaration("Test");
                class1.IsClass = true;
                class1.BaseTypes.Add(new CodeTypeReference("Form"));
                ns.Types.Add(class1);

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

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

                CodeMemberEvent evt = new CodeMemberEvent();
                evt.Name = "MyEvent";
                evt.Type = new CodeTypeReference("System.EventHandler");
                evt.Attributes = MemberAttributes.Public;
                class1.Members.Add(evt);

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

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

                  [assembly: System.Reflection.AssemblyTitle(""MyAssembly"")]
                  [assembly: System.Reflection.AssemblyVersion(""1.0.6.2"")]

                  namespace NSPC {
                      using System;
                      using System.Drawing;
                      using System.Windows.Forms;
                      using System.ComponentModel;

                      public class TEST {

                          public int ArraysOfArrays() {
                              int[][] arrayOfArrays = new int[][] {
                                      new int[] { 3, 4},
                                      new int[] { 1}};
                              return arrayOfArrays[0][1];
                          }

                          public static string ChainedConstructorUse() {
                              Test2 t = new Test2();
                              return t.accessStringField;
                          }

                          public int ComplexExpressions(int i) {
                              i = (i * (i + 3));
                              return i;
                          }

                          public static int OutputDecimalEnumVal(int i) {
                              if ((i == 3)) {
                                  return ((int)(DecimalEnum.Num3));
                              }
                              if ((i == 4)) {
                                  return ((int)(DecimalEnum.Num4));
                              }
                              if ((i == 2)) {
                                  return ((int)(DecimalEnum.Num2));
                              }
                              if ((i == 1)) {
                                  return ((int)(DecimalEnum.Num1));
                              }
                              if ((i == 0)) {
                                  return ((int)(DecimalEnum.Num0));
                              }
                              return (i + 10);
                          }

                          public static int TestSingleInterface(int i) {
                              TestSingleInterfaceImp t = new TestSingleInterfaceImp();
                              return t.InterfaceMethod(i);
                          }

                          public static int TestMultipleInterfaces(int i) {
                              TestMultipleInterfaceImp t = new TestMultipleInterfaceImp();
                              InterfaceA interfaceAobject = ((InterfaceA)(t));
                              InterfaceB interfaceBobject = ((InterfaceB)(t));
                              return (interfaceAobject.InterfaceMethod(i) - interfaceBobject.InterfaceMethod(i));
                          }

                          public static int NestedStructMethod() {
                              structA varStructA;
                              varStructA.innerStruct.int1 = 3;
                              return varStructA.innerStruct.int1;
                          }

                          public static void Main() { }

                          public int GoToMethod(int i) {
                              if ((i < 1)) {
                                  goto comehere;
                              }
                              return 6;
                          comehere:
                              return 7;
                          }

                          public static int CallingPublicNestedScenario(int i) {
                              PublicNestedClassA.PublicNestedClassB2.PublicNestedClassC t = new PublicNestedClassA.PublicNestedClassB2.PublicNestedClassC();
                              return t.publicNestedClassesMethod(i);
                          }

                          public void MyMethod([System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] string blah) {
                          }

                          public static int PublicStaticMethod() {
                              return 16;
                          }

                          static void Work(ref int i, out int j) {
                              i = (i + 4);
                              j = 5;
                          }

                          public static int CallingWork(int a) {
                              a = 10;
                              int b;
                              TEST.Work(ref a, out b);
                              return (a + b);
                          }

                          [return: System.Xml.Serialization.XmlIgnoreAttribute()]
                          [return: System.Xml.Serialization.XmlRootAttribute(Namespace=""Namespace Value"", ElementName=""Root, hehehe"")]
                          public string MyFunction() {
                              return ""Return"";
                          }

                          public static int TestStaticConstructor(int a) {
                              Test4 t = new Test4();
                              t.i = a;
                              return t.i;
                          }

                          public static int TryCatchMethod(int a) {
                              try {
                              }
                              finally {
                                  a = (a + 5);
                              }
                              return a;
                          }
                      }

                      public class Test2 {

                          private string stringField;

                          public Test2() :
                                  this(""testingString"", null, null) {
                          }

                          public Test2(string p1, string p2, string p3) {
                              this.stringField = p1;
                          }

                          public string accessStringField {
                              get {
                                  return this.stringField;
                              }
                              set {
                                  this.stringField = value;
                              }
                          }
                      }

                      public enum DecimalEnum {
                          Num0 = 0,
                          Num1 = 1,
                          Num2 = 2,
                          Num3 = 3,
                          Num4 = 4,
                      }

                      public interface InterfaceA {
                          int InterfaceMethod(int a);
                      }

                      public interface InterfaceB {
                          int InterfaceMethod(int a);
                      }

                      public class TestMultipleInterfaceImp : object, InterfaceB, InterfaceA {
                          public int InterfaceMethod(int a) {
                              return a;
                          }
                      }

                      public class TestSingleInterfaceImp : object, InterfaceA {
                          public virtual int InterfaceMethod(int a) {
                              return a;
                          }
                      }

                      public struct structA {
                          public structB innerStruct;

                          public struct structB {
                              public int int1;
                          }
                      }

                      public class PublicNestedClassA {

                          public class PublicNestedClassB1 { }

                          public class PublicNestedClassB2 {
                              public class PublicNestedClassC {
                                  public int publicNestedClassesMethod(int a) {
                                      return a;
                                  }
                              }
                          }
                      }

                      public class Test4 {

                          private int number;

                          static Test4() {
                          }

                          public int i {
                              get {
                                  return number;
                              }
                              set {
                                  number = value;
                              }
                          }
                      }
                  }
                  namespace MyNamespace {
                      using System;
                      using System.Drawing;
                      using System.Windows.Forms;
                      using System.ComponentModel;

                      public class Test : Form {
                          private Button b = new Button();

                          public Test() {
                              this.Size = new Size(600, 600);
                              b.Text = ""Test"";
                              b.TabIndex = 0;
                              b.Location = new Point(400, 525);
                              this.MyEvent += new EventHandler(this.b_Click);
                          }

                          public event System.EventHandler MyEvent;

                          private void b_Click(object sender, System.EventArgs e) {
                          }
                      }
                  }");
        }
示例#9
0
        protected void GenerateStatement(CodeStatement s)
        {
            bool handled = false;

#if NET_2_0
            if (s.StartDirectives.Count > 0)
            {
                GenerateDirectives(s.StartDirectives);
            }
#endif
            if (s.LinePragma != null)
            {
                GenerateLinePragmaStart(s.LinePragma);
            }

            CodeAssignStatement assign = s as CodeAssignStatement;
            if (assign != null)
            {
                GenerateAssignStatement(assign);
                handled = true;
            }
            CodeAttachEventStatement attach = s as CodeAttachEventStatement;
            if (attach != null)
            {
                GenerateAttachEventStatement(attach);
                handled = true;
            }
            CodeCommentStatement comment = s as CodeCommentStatement;
            if (comment != null)
            {
                GenerateCommentStatement(comment);
                handled = true;
            }
            CodeConditionStatement condition = s as CodeConditionStatement;
            if (condition != null)
            {
                GenerateConditionStatement(condition);
                handled = true;
            }
            CodeExpressionStatement expression = s as CodeExpressionStatement;
            if (expression != null)
            {
                GenerateExpressionStatement(expression);
                handled = true;
            }
            CodeGotoStatement gotostmt = s as CodeGotoStatement;
            if (gotostmt != null)
            {
                GenerateGotoStatement(gotostmt);
                handled = true;
            }
            CodeIterationStatement iteration = s as CodeIterationStatement;
            if (iteration != null)
            {
                GenerateIterationStatement(iteration);
                handled = true;
            }
            CodeLabeledStatement label = s as CodeLabeledStatement;
            if (label != null)
            {
                GenerateLabeledStatement(label);
                handled = true;
            }
            CodeMethodReturnStatement returnstmt = s as CodeMethodReturnStatement;
            if (returnstmt != null)
            {
                GenerateMethodReturnStatement(returnstmt);
                handled = true;
            }
            CodeRemoveEventStatement remove = s as CodeRemoveEventStatement;
            if (remove != null)
            {
                GenerateRemoveEventStatement(remove);
                handled = true;
            }
            CodeSnippetStatement snippet = s as CodeSnippetStatement;
            if (snippet != null)
            {
#if NET_2_0
                int indent = Indent;
                try {
                    Indent = 0;
                    GenerateSnippetStatement(snippet);
                } finally {
                    Indent = indent;
                }
#else
                GenerateSnippetStatement(snippet);
#endif
                handled = true;
            }
            CodeThrowExceptionStatement exception = s as CodeThrowExceptionStatement;
            if (exception != null)
            {
                GenerateThrowExceptionStatement(exception);
                handled = true;
            }
            CodeTryCatchFinallyStatement trycatch = s as CodeTryCatchFinallyStatement;
            if (trycatch != null)
            {
                GenerateTryCatchFinallyStatement(trycatch);
                handled = true;
            }
            CodeVariableDeclarationStatement declaration = s as CodeVariableDeclarationStatement;
            if (declaration != null)
            {
                GenerateVariableDeclarationStatement(declaration);
                handled = true;
            }

            if (!handled)
            {
                throw new ArgumentException("Element type " + s + " is not supported.");
            }

            if (s.LinePragma != null)
            {
                GenerateLinePragmaEnd(s.LinePragma);
            }

#if NET_2_0
            if (s.EndDirectives.Count > 0)
            {
                GenerateDirectives(s.EndDirectives);
            }
#endif
        }
示例#10
0
        private void DeleteChildren(TableSchema parentTable, CodeStatementCollection codeStatements)
        {
            //				// Delete each of the child Department records in a cascade.
            //				ServerDataModel.DepartmentRow[] departmentRows = objectRow.GetDepartmentRows();
            //				for (int departmentIndex = 0; departmentIndex < departmentRows.Length; departmentIndex = (departmentIndex + 1))
            //				{
            //					// Get the next department in the list.
            //					ServerDataModel.DepartmentRow departmentRow = departmentRows[departmentIndex];
            //					// Lock the ADO record.
            //					departmentRow.ReaderWriterLock.AcquireWriterLock(System.Threading.Timeout.Infinite);
            //					adoResourceManager.Add(departmentRow.ReaderWriterLock);
            //					// Optimistic Concurrency Check.
            //					if ((departmentRow.RowVersion != rowVersion))
            //					{
            //						throw new System.Exception("This record is busy.  Please try again later.");
            //					}
            //					// Delete the SQL record as part of a transaction.
            //					SqlCommand departmentCommand = new SqlCommand(@"delete ""Department"" where ""DepartmentId""=@departmentId", sqlResourceManager.SqlConnection);
            //					departmentCommand.Parameters.Add(new SqlParameter("@departmentId", SqlDbType.Int, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, departmentRow[ServerDataModel.Department.DepartmentIdColumn]));
            //					sqlCommands.Add(departmentCommand);
            //					// Delete the ADO record as part of a transaction.
            //					adoResourceManager.Add(departmentRow);
            //					departmentRow[ServerDataModel.Department.RowVersionColumn] = ServerDataModel.IncrementRowVersion();
            //					departmentRow.Delete();
            //				}
            foreach (KeyrefSchema childKeyref in parentTable.ChildKeyrefs)
            {
                TableSchema childTable = childKeyref.Selector;
                if (childTable.RootTable == parentTable && childTable != this.tableSchema)
                {
                    continue;
                }

                string parentRowVariable = string.Format("{0}Row", Generate.CamelCase(parentTable.Name));
                string rowArrayType      = string.Format("{0}.{1}Row[]", tableSchema.DataModelSchema.Name, childTable.Name);
                string rowArrayVariable  = string.Format("{0}{1}Rows", Generate.CamelCase(parentTable.Name), childTable.Name);
                string rowType           = string.Format("{0}.{1}Row", tableSchema.DataModelSchema.Name, childTable.Name);
                string rowVariable       = string.Format("{0}Row", Generate.CamelCase(childTable.Name));
                string methodName        = string.Format("Get{0}Rows", childTable.Name);
                string iteratorVariable  = string.Format("{0}Index", Generate.CamelCase(childTable.Name));
                codeStatements.Add(new CodeCommentStatement(string.Format("Delete each of the child {0} records in a cascade.", childTable.Name)));
                codeStatements.Add(new CodeVariableDeclarationStatement(rowArrayType, rowArrayVariable, new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(parentRowVariable), methodName)));

                CodeStatementCollection iteratorStatements = new CodeStatementCollection();
                iteratorStatements.Add(new CodeCommentStatement(string.Format("Get the next {0} row in the list of children and lock it for the duration of the transaction.", childTable.Name)));
                iteratorStatements.Add(new CodeVariableDeclarationStatement(rowType, rowVariable, new CodeIndexerExpression(new CodeVariableReferenceExpression(rowArrayVariable), new CodeVariableReferenceExpression(iteratorVariable))));
                iteratorStatements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(rowVariable), "ReaderWriterLock"), "AcquireWriterLock", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.Threading.Timeout)), "Infinite"))));
                iteratorStatements.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("adoResourceManager"), "Add", new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(rowVariable), "ReaderWriterLock"))));

                //				// The Optimistic Concurrency check allows only one client to update a record at a time.
                //				if ((departmentRow.RowVersion != rowVersion))
                //				{
                //					throw new System.Exception("This record is busy.  Please try again later.");
                //				}
                if (childTable == this.tableSchema)
                {
                    iteratorStatements.Add(new CodeCommentStatement("The Optimistic Concurrency check allows only one client to update a record at a time."));
                    iteratorStatements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(rowVariable), "RowVersion"), CodeBinaryOperatorType.IdentityInequality, new CodeArgumentReferenceExpression("rowVersion")),
                                                                      new CodeThrowExceptionStatement(new CodeObjectCreateExpression(typeof(System.Exception), new CodePrimitiveExpression("This record is busy.  Please try again later.")))));
                }

                DeleteChildren(childTable, iteratorStatements);

                //					// Delete the Department record from the SQL data model.
                //					sqlCommand = new SqlCommand("delete \"Department\" where \"DepartmentId\"=@departmentId", sqlResourceManager.SqlConnection);
                //					sqlCommand.Parameters.Add(new SqlParameter("@departmentId", SqlDbType.Int, 0, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, departmentRow[ServerDataModel.Department.DepartmentIdColumn]));
                //					sqlCommands.Add(sqlCommand);
                if (childTable.IsPersistent)
                {
                    iteratorStatements.Add(new CodeCommentStatement(string.Format("Delete the {0} record from the SQL data model.", childTable.Name)));
                    string whereClause = string.Empty;
                    if (childTable.PrimaryKey != null)
                    {
                        foreach (ColumnSchema columnSchema in childTable.PrimaryKey.Fields)
                        {
                            whereClause += string.Format("\"{0}\"=@{1}", columnSchema.Name, Generate.CamelCase(columnSchema.Name));
                        }
                    }
                    string deleteCommandText = string.Format("delete \"{0}\" where {1}", childTable.Name, whereClause);
                    iteratorStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("sqlCommand"), new CodeObjectCreateExpression("SqlCommand", new CodePrimitiveExpression(deleteCommandText), new CodeFieldReferenceExpression(new CodeArgumentReferenceExpression("sqlResourceManager"), "SqlConnection"))));
                    if (childTable.PrimaryKey != null)
                    {
                        foreach (ColumnSchema columnSchema in childTable.PrimaryKey.Fields)
                        {
                            string         variableName   = Generate.CamelCase(columnSchema.Name);
                            CodeExpression codeExpression = new CodeIndexerExpression(new CodeVariableReferenceExpression(string.Format("{0}Row", Generate.CamelCase(childTable.Name))), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(string.Format("{0}.{1}", tableSchema.DataModelSchema.Name, childTable.Name)), string.Format("{0}Column", columnSchema.Name)));
                            iteratorStatements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("sqlCommand"), "Parameters"), "Add", new CodeExpression[] { new CodeObjectCreateExpression("SqlParameter", new CodeExpression[] { new CodePrimitiveExpression(string.Format("@{0}", variableName)), TypeConverter.Convert(columnSchema.DataType), new CodePrimitiveExpression(0), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("ParameterDirection"), "Input"), new CodePrimitiveExpression(false), new CodePrimitiveExpression(0), new CodePrimitiveExpression(0), new CodePrimitiveExpression(null), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DataRowVersion"), "Current"), codeExpression }) }));
                        }
                    }
                    iteratorStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("sqlCommand"), "ExecuteNonQuery"));
                }

                //					// Delete the Department record from the ADO data model.
                //					adoResourceManager.Add(departmentRow);
                //					departmentRow[ServerDataModel.Department.RowVersionColumn] = ServerDataModel.IncrementRowVersion();
                //					departmentRow.Delete();
                iteratorStatements.Add(new CodeCommentStatement(string.Format("Delete the {0} record from the ADO data model.", childTable.Name)));
                iteratorStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("adoResourceManager"), "Add", new CodeVariableReferenceExpression(rowVariable)));

                CodeTryCatchFinallyStatement tryFinallyStatement = new CodeTryCatchFinallyStatement();
                tryFinallyStatement.TryStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(rowVariable), "BeginEdit"));
                tryFinallyStatement.TryStatements.Add(new CodeAssignStatement(new CodeIndexerExpression(new CodeVariableReferenceExpression(rowVariable), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(string.Format("{0}.{1}", tableSchema.DataModelSchema.Name, childTable.Name)), "RowVersionColumn")), new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(tableSchema.DataModelSchema.Name), "IncrementRowVersion")));
                tryFinallyStatement.TryStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(rowVariable), "Delete"));
                tryFinallyStatement.FinallyStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(rowVariable), "EndEdit"));
                iteratorStatements.Add(tryFinallyStatement);

                CodeStatement[] iteratorArray = new CodeStatement[iteratorStatements.Count];
                iteratorStatements.CopyTo(iteratorArray, 0);
                codeStatements.Add(new CodeIterationStatement(new CodeVariableDeclarationStatement(typeof(System.Int32), iteratorVariable, new CodePrimitiveExpression(0)),
                                                              new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression(iteratorVariable), CodeBinaryOperatorType.LessThan, new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(rowArrayVariable), "Length")),
                                                              new CodeAssignStatement(new CodeVariableReferenceExpression(iteratorVariable), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression(iteratorVariable), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))), iteratorArray));
            }
        }
        /// <summary>
        /// Creates a method to read an XML file.
        /// </summary>
        /// <param name="schema">The data model schema.</param>
        public OnTransactionCompletedMethod(DataModelSchema dataModelSchema)
        {
            //		/// <summary>
            //		/// Processes the completion of a transaction.
            //		/// </summary>
            //		/// <param name="sender">The object that originated the event.</param>
            //		/// <param name="transactionEventArgs">The event arguments.</param>
            //		private static void OnTransactionCompleted(object sender, global::System.Transactions.TransactionEventArgs transactionEventArgs)
            //		{
            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement("Processes the completion of a transaction.", true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            this.Comments.Add(new CodeCommentStatement("<param name=\"sender\">The object that originated the event.</param>", true));
            this.Comments.Add(new CodeCommentStatement("<param name=\"transactionEventArgs\">The event arguments.</param>", true));
            this.CustomAttributes.AddRange(new CodeCustomAttributesForMethods());
            this.Attributes = MemberAttributes.Private | MemberAttributes.Final;
            this.Name       = "OnTransactionCompleted";
            this.Parameters.Add(new CodeParameterDeclarationExpression(new CodeGlobalTypeReference(typeof(Object)), "sender"));
            this.Parameters.Add(new CodeParameterDeclarationExpression(new CodeGlobalTypeReference(typeof(TransactionEventArgs)), "transactionEventArgs"));

            //			try
            //			{
            CodeTryCatchFinallyStatement tryLockRoot = new CodeTryCatchFinallyStatement();

            //				global::System.Threading.Monitor.Enter(DataModelTransaction.syncRoot);
            tryLockRoot.TryStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeGlobalTypeReferenceExpression(typeof(Monitor)),
                    "Enter",
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "syncRoot")));

            //				global::System.Transactions.Transaction transaction = e.Transaction;
            tryLockRoot.TryStatements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Transaction)),
                    "transaction",
                    new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("transactionEventArgs"), "Transaction")));

            //				string localIdentifier = transaction.TransactionInformation.LocalIdentifier;
            tryLockRoot.TryStatements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(String)),
                    "localIdentifier",
                    new CodePropertyReferenceExpression(
                        new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("transaction"), "TransactionInformation"),
                        "LocalIdentifier")));

            //				DataModelTransaction dataModelTransaction;
            tryLockRoot.TryStatements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeTypeReference(String.Format("{0}Transaction", dataModelSchema.Name)),
                    String.Format("{0}Transaction", CommonConversion.ToCamelCase(dataModelSchema.Name))));

            //				if (DataModel.transactionTable.TryGetValue(localIdentifier, out dataModelTransaction))
            //				{
            CodeConditionStatement ifNewTransaction = new CodeConditionStatement(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "transactionTable"),
                    "TryGetValue",
                    new CodeVariableReferenceExpression("localIdentifier"),
                    new CodeDirectionExpression(FieldDirection.Out, new CodeVariableReferenceExpression("dataModelTransaction"))));

            //					dataModelTransaction.SqlConnection.Close();
            ifNewTransaction.TrueStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodePropertyReferenceExpression(
                        new CodeVariableReferenceExpression(String.Format("{0}Transaction", CommonConversion.ToCamelCase(dataModelSchema.Name))),
                        "SqlConnection"),
                    "Close"));

            //					DataModel.transactionTable.Remove(localIdentifier);
            ifNewTransaction.TrueStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "transactionTable"),
                    "Remove",
                    new CodeVariableReferenceExpression("localIdentifier")));

            //				}
            //			}
            tryLockRoot.TryStatements.Add(ifNewTransaction);

            //			}
            //			finally
            //			{
            //				global::System.Threading.Monitor.Exit(DataModelTransaction.syncRoot);
            //			}
            tryLockRoot.FinallyStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeGlobalTypeReferenceExpression(typeof(Monitor)),
                    "Exit",
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "syncRoot")));

            //		}
            this.Statements.Add(tryLockRoot);
        }
示例#12
0
        private 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("}");
        }
	protected override void GenerateTryCatchFinallyStatement
				(CodeTryCatchFinallyStatement e)
			{
				Output.WriteLine("Try");
				++Indent;
				GenerateStatements(e.TryStatements);
				--Indent;
				CodeCatchClauseCollection clauses = e.CatchClauses;
				if(clauses.Count > 0)
				{
					foreach(CodeCatchClause clause in clauses)
					{
						if(clause.CatchExceptionType != null)
						{
							Output.Write("Catch ");
							OutputIdentifier(clause.LocalName);
							Output.Write(" As ");
							OutputType(clause.CatchExceptionType);
							Output.WriteLine();
						}
						else
						{
							Output.WriteLine("Catch");
						}
						++Indent;
						GenerateStatements(clause.Statements);
						--Indent;
					}
				}
				CodeStatementCollection fin = e.FinallyStatements;
				if(fin.Count > 0)
				{
					Output.WriteLine("Finally");
					++Indent;
					GenerateStatements(fin);
					--Indent;
				}
				Output.WriteLine("End Try");
			}
示例#14
0
        /// <summary>
        /// Creates a method to handle moving the deleted records from the active data model to the deleted data model.
        /// </summary>
        /// <param name="schema">The data model schema.</param>
        public CollectGarbageMethod(DataModelSchema schema)
        {
            //		/// <summary>
            //		/// Purges the deleted data model of obsolete rows.
            //		/// </summary>
            //		private static void CollectGarbage()
            //		{
            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement("Purges the deleted data model of obsolete rows.", true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            this.Name       = "CollectGarbage";
            this.Attributes = MemberAttributes.Private | MemberAttributes.Static;

            //			// The tread can be terminated gracefully from another thread by clearing this value.
            //			DataModel.IsGarbageCollecting = true;
            //			for (
            //			; DataModel.IsGarbageCollecting == true;
            //			)
            //			{
            this.Statements.Add(new CodeCommentStatement("The tread can be terminated gracefully from another thread by clearing this value."));
            this.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(schema.Name), "IsGarbageCollecting"), new CodePrimitiveExpression(true)));
            CodeIterationStatement whileCollecting = new CodeIterationStatement(new CodeSnippetStatement(), new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(schema.Name), "IsGarbageCollecting"), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(true)), new CodeSnippetStatement());

            //				// To keep this thread from using up too much of the CPU time, it will wait here when there is no data in the
            //				// deleted data model.  The flag is set when records are added to the deleted data model and cleared when there are
            //				// no more deleted records to process.
            //				DataModel.deletedEvent.WaitOne();
            whileCollecting.Statements.Add(new CodeCommentStatement("To keep this thread from using up too much of the CPU time, it will wait here when there is no data in the"));
            whileCollecting.Statements.Add(new CodeCommentStatement("deleted data model.  The flag is set when records are added to the deleted data model and cleared when there are"));
            whileCollecting.Statements.Add(new CodeCommentStatement("no more deleted records to process."));
            whileCollecting.Statements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(schema.Name), "deletedEvent"), "WaitOne"));

            //				// These values are used to calculate the amount of time to sleep between scanning the tables for deleted records
            //				// that have expired.  Each time through the loop an attempt is made to guess at the time the oldest deleted
            //				// record will expire.  The looping mechanism tries to spend as little time as possible checking the tables for
            //				// records that are ready to be purged.
            //				TimeSpan sleepTime = TimeSpan.Zero;
            //				DateTime maxTime = DateTime.MinValue;
            //				try
            //				{
            whileCollecting.Statements.Add(new CodeCommentStatement("These values are used to calculate the amount of time to sleep between scanning the tables for deleted records"));
            whileCollecting.Statements.Add(new CodeCommentStatement("that have expired.  Each time through the loop an attempt is made to guess at the time the oldest deleted"));
            whileCollecting.Statements.Add(new CodeCommentStatement("record will expire.  The looping mechanism tries to spend as little time as possible checking the tables for"));
            whileCollecting.Statements.Add(new CodeCommentStatement("records that are ready to be purged."));
            whileCollecting.Statements.Add(new CodeVariableDeclarationStatement(typeof(System.TimeSpan), "sleepTime", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.TimeSpan)), "Zero")));
            whileCollecting.Statements.Add(new CodeVariableDeclarationStatement(typeof(System.DateTime), "maxTime", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.DateTime)), "MinValue")));
            CodeTryCatchFinallyStatement tryMutex = new CodeTryCatchFinallyStatement();

            //					// The deleted data model can't be modified while it is purged.
            //					DataModel.deletedExclusion.WaitOne();
            tryMutex.TryStatements.Add(new CodeCommentStatement("The deleted data model can't be modified while it is purged."));
            tryMutex.TryStatements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(schema.Name), "deletedExclusion"), "WaitOne"));

            //					// This time is used to calculate the expiration time of all the records in this pass through the deleted data
            //					// model.
            //					DateTime now = DateTime.Now;
            //					// Examine each table looking for expired rows.
            //					for (int tableIndex = 0; tableIndex < DataModel.deletedDataSet.Tables.Count; tableIndex = (tableIndex + 1))
            //					{
            tryMutex.TryStatements.Add(new CodeCommentStatement("This time is used to calculate the expiration time of all the records in this pass through the deleted data "));
            tryMutex.TryStatements.Add(new CodeCommentStatement("model."));
            tryMutex.TryStatements.Add(new CodeVariableDeclarationStatement(typeof(System.DateTime), "now", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.DateTime)), "Now")));
            tryMutex.TryStatements.Add(new CodeCommentStatement("Examine each table looking for expired rows."));
            CodeIterationStatement tableLoop = new CodeIterationStatement(new CodeVariableDeclarationStatement(typeof(System.Int32), "tableIndex", new CodePrimitiveExpression(0)), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("tableIndex"), CodeBinaryOperatorType.LessThan, new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(schema.Name), "deletedDataSet"), "Tables"), "Count")), new CodeAssignStatement(new CodeVariableReferenceExpression("tableIndex"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("tableIndex"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))));

            //						// Select the next table in the deleted data model.
            //						DataTable dataTable = DataModel.deletedDataSet.Tables[tableIndex];
            //						// Examine each row for expired records.
            //						for (int rowIndex = 0; rowIndex < dataTable.Rows.Count; )
            //						{
            tableLoop.Statements.Add(new CodeCommentStatement("Select the next table in the deleted data model."));
            tableLoop.Statements.Add(new CodeVariableDeclarationStatement(typeof(System.Data.DataTable), "dataTable", new CodeIndexerExpression(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(schema.Name), "deletedDataSet"), "Tables"), new CodeVariableReferenceExpression("tableIndex"))));
            tableLoop.Statements.Add(new CodeCommentStatement("Examine each row for expired records."));
            CodeIterationStatement rowLoop = new CodeIterationStatement(new CodeVariableDeclarationStatement(typeof(System.Int32), "rowIndex", new CodePrimitiveExpression(0)), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("rowIndex"), CodeBinaryOperatorType.LessThan, new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("dataTable"), "Rows"), "Count")), new CodeSnippetStatement());

            //							// Extract the time that the record was deleted.
            //							DataRow dataRow = dataTable.Rows[rowIndex];
            //							DateTime deletedTime = (DateTime)dataRow[DataModel.deletedTimeColumn];
            rowLoop.Statements.Add(new CodeCommentStatement("Extract the time that the record was deleted."));
            rowLoop.Statements.Add(new CodeVariableDeclarationStatement(typeof(System.Data.DataRow), "dataRow", new CodeIndexerExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("dataTable"), "Rows"), new CodeVariableReferenceExpression("rowIndex"))));
            rowLoop.Statements.Add(new CodeVariableDeclarationStatement(typeof(System.DateTime), "deletedTime", new CodeCastExpression(typeof(System.DateTime), new CodeIndexerExpression(new CodeVariableReferenceExpression("dataRow"), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(schema.Name), "deletedTimeColumn")))));

            //							// This value will be used to determine how much time to sleep between cycles that read the deleted
            //							// data model. This variable will hold the oldest record that hasn't been deleted after reading the
            //							// entire data model.  That time can be used to calculate how long to sleep until the next cycle.
            //							if (deletedTime > maxTime)
            //							{
            //								maxTime = deletedTime;
            //							}
            rowLoop.Statements.Add(new CodeCommentStatement("This value will be used to determine how much time to sleep between cycles that read the deleted"));
            rowLoop.Statements.Add(new CodeCommentStatement("data model. This variable will hold the oldest record that hasn't been deleted after reading the"));
            rowLoop.Statements.Add(new CodeCommentStatement("entire data model.  That time can be used to calculate how long to sleep until the next cycle."));
            rowLoop.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("deletedTime"), CodeBinaryOperatorType.GreaterThan, new CodeVariableReferenceExpression("maxTime")),
                                                              new CodeAssignStatement(new CodeVariableReferenceExpression("maxTime"), new CodeVariableReferenceExpression("deletedTime"))));

            //							// A row is obsolete after a constant time (generally about a minute).  At this time it is assumed that
            //							// all the client data models have had a chance to reconcile with the server and have removed the
            //							// deleted records.  If the row just read from this table has not yet expired, then there's no need to
            //							// continue deleting because the rest of the records in the table are younger than this one.
            //							// Otherwise, the record is purged from the data model.
            //							if (now.Subtract(deletedTime) < DataModel.freshnessTime)
            //								rowIndex = dataTable.Rows.Count;
            //							else
            //								dataTable.Rows.Remove(dataRow);
            rowLoop.Statements.Add(new CodeCommentStatement("A row is obsolete after a constant time (generally about a minute).  At this time it is assumed that"));
            rowLoop.Statements.Add(new CodeCommentStatement("all the client data models have had a chance to reconcile with the server and have removed the"));
            rowLoop.Statements.Add(new CodeCommentStatement("deleted records.  If the row just read from this table has not yet expired, then there's no need to"));
            rowLoop.Statements.Add(new CodeCommentStatement("continue deleting because the rest of the records in the table are younger than this one."));
            rowLoop.Statements.Add(new CodeCommentStatement("Otherwise, the record is purged from the data model."));
            CodeConditionStatement ifObsolete = new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("now"), "Subtract", new CodeVariableReferenceExpression("deletedTime")), CodeBinaryOperatorType.LessThan, new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(schema.Name), "freshnessTime")));

            ifObsolete.TrueStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("rowIndex"), new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("dataTable"), "Rows"), "Count")));
            ifObsolete.FalseStatements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("dataTable"), "Rows"), "Remove", new CodeVariableReferenceExpression("dataRow")));
            rowLoop.Statements.Add(ifObsolete);

            //						}
            tableLoop.Statements.Add(rowLoop);

            //					}
            tryMutex.TryStatements.Add(tableLoop);

            //				}
            //				finally
            //				{
            //					// Allow the other threads to examine the deleted data model.
            //					DataModel.deletedExclusion.ReleaseMutex();
            //				}
            tryMutex.FinallyStatements.Add(new CodeCommentStatement("Allow the other threads to examine the deleted data model."));
            tryMutex.FinallyStatements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(schema.Name), "deletedExclusion"), "ReleaseMutex"));
            whileCollecting.Statements.Add(tryMutex);

            //				// This thread is put to sleep when there are no more values in the deleted data model.
            //				if (maxTime == DateTime.MinValue)
            //				{
            //					DataModel.deletedEvent.Reset();
            //				}
            //				// This sleep time is calculated to put this thread to sleep until the row at the output end of the queue is ready
            //				// to expire.  The idea is to spend as much time in this low level worker thread as possible.
            //				sleepTime = DataModel.freshnessTime.Subtract(DateTime.Now.Subtract(maxTime));
            //				if (sleepTime < TimeSpan.Zero)
            //					sleepTime = TimeSpan.Zero;
            //				Thread.Sleep(sleepTime);
            whileCollecting.Statements.Add(new CodeCommentStatement("This thread is put to sleep when there are no more values in the deleted data model."));
            whileCollecting.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("maxTime"), CodeBinaryOperatorType.IdentityEquality, new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.DateTime)), "MinValue")),
                                                                      new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(schema.Name), "deletedEvent"), "Reset"))));
            whileCollecting.Statements.Add(new CodeCommentStatement("This sleep time is calculated to put this thread to sleep until the row at the output end of the queue is ready"));
            whileCollecting.Statements.Add(new CodeCommentStatement("to expire.  The idea is to spend as much time in this low level worker thread as possible."));
            whileCollecting.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("sleepTime"), new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(schema.Name), "freshnessTime"), "Subtract", new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.DateTime)), "Now"), "Subtract", new CodeVariableReferenceExpression("maxTime")))));
            whileCollecting.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("sleepTime"), CodeBinaryOperatorType.LessThan, new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.TimeSpan)), "Zero")),
                                                                      new CodeAssignStatement(new CodeVariableReferenceExpression("sleepTime"), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.TimeSpan)), "Zero"))));
            whileCollecting.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(System.Threading.Thread)), "Sleep", new CodeVariableReferenceExpression("sleepTime")));

            //			}
            this.Statements.Add(whileCollecting);

            //		}
        }
示例#15
0
        /// <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);
        }
示例#16
0
        /// <summary>
        /// Creates the CodeDOM for a method to update a record in a table using transacted logic.
        /// </summary>
        /// <param name="tableSchema">A description of the table.</param>
        public UpdateMethod(TableSchema tableSchema)
        {
            // Create a matrix of parameters for this operation.
            UpdateParameterMatrix updateParameterMatrix = new UpdateParameterMatrix(tableSchema);

            // This is the key used to identify the record to be deleted.
            CodeArgumentReferenceExpression primaryKeyExpression = null;

            foreach (KeyValuePair <string, ExternalParameterItem> externalParamterPair in updateParameterMatrix.ExternalParameterItems)
            {
                if (externalParamterPair.Value is UniqueConstraintParameterItem)
                {
                    primaryKeyExpression = new CodeArgumentReferenceExpression(externalParamterPair.Value.Name);
                }
            }

            //        /// <summary>
            //        /// Updates a Employee record.
            //        /// </summary>
            //        /// <param name="age">The optional value for the Age column.</param>
            //        /// <param name="departmentId">The optional value for the DepartmentId column.</param>
            //        /// <param name="employeeId">The required value for the EmployeeId column.</param>
            //        /// <param name="raceCode">The optional value for the RaceCode column.</param>
            //        /// <param name="rowVersion">Used for Optimistic Concurrency Checking.</param>
            //        [global::System.ServiceModel.OperationBehaviorAttribute(TransactionScopeRequired=true)]
            //        [FluidTrade.Core.ClaimsPrincipalPermission(global::System.Security.Permissions.SecurityAction.Demand, ClaimType=global::FluidTrade.Core.ClaimTypes.Update, Resource=global::FluidTrade.Core.Resources.Application)]
            //        public void UpdateEmployee(object age, object departmentId, int employeeId, object raceCode, ref long rowVersion) {
            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement(string.Format("Updates a {0} record.", tableSchema.Name), true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            foreach (KeyValuePair <string, ExternalParameterItem> parameterPair in updateParameterMatrix.ExternalParameterItems)
            {
                this.Comments.Add(new CodeCommentStatement(string.Format("<param name=\"{0}\">{1}</param>", parameterPair.Value.Name, parameterPair.Value.Description), true));
            }
            this.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeGlobalTypeReference(typeof(System.ServiceModel.OperationBehaviorAttribute)), new CodeAttributeArgument("TransactionScopeRequired", new CodePrimitiveExpression(true))));
            //AR FB 408 - Remove Claims requirement
            //this.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeGlobalTypeReference(typeof(ClaimsPrincipalPermission)), new CodeAttributeArgument(new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(System.Security.Permissions.SecurityAction)), "Demand")),
            //    new CodeAttributeArgument("ClaimType", new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(ClaimTypes)), "Update")),
            //    new CodeAttributeArgument("Resource", new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(Resources)), "Application"))));
            this.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            this.Name       = string.Format("Update{0}", tableSchema.Name);
            foreach (KeyValuePair <string, ExternalParameterItem> parameterPair in updateParameterMatrix.ExternalParameterItems)
            {
                this.Parameters.Add(parameterPair.Value.CodeParameterDeclarationExpression);
            }

            // There is no way to find the existing record without a primary unique key.
            if (tableSchema.PrimaryKey == null)
            {
                return;
            }

            //            // This provides a context for the middle tier transactions.
            //            global::FluidTrade.Core.MiddleTierContext middleTierTransaction = global::FluidTrade.Core.MiddleTierContext.Current;
            CodeVariableReferenceExpression transactionExpression = new CodeRandomVariableReferenceExpression();

            this.Statements.Add(new CodeCreateMiddleTierContextStatement(tableSchema.DataModel, transactionExpression));

            //            // This is the record that will be updated
            //            global::System.Object[] employeeKey = new global::System.Object(new object[] {
            //                        employeeId});
            //            FluidTrade.UnitTest.Server.DataModel.EmployeeRow employeeRow = FluidTrade.UnitTest.Server.DataModel.Employee.FindByEmployeeId(employeeKey);
            //            if ((employeeRow == null)) {
            //                throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Employee record ({0}) that doesn\'t exist", employeeKey));
            //            }
            CodeVariableReferenceExpression rowVariableExpression = new CodeRandomVariableReferenceExpression();

            this.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(string.Format("{0}Row", tableSchema.Name)), rowVariableExpression.VariableName, new CodeFindByIndexExpression(tableSchema, primaryKeyExpression)));
            this.Statements.Add(new CodeCheckRecordExistsStatement(tableSchema, rowVariableExpression, primaryKeyExpression));
            this.Statements.Add(new CodeAcquireRecordWriterLockExpression(transactionExpression, rowVariableExpression, tableSchema));
            this.Statements.Add(new CodeAddLockToTransactionExpression(transactionExpression, rowVariableExpression));

            //            // This makes sure the record wasn't deleted between the time it was found and the time it was locked.
            //            if ((employeeRow.RowState == global::System.Data.DataRowState.Detached)) {
            //                throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Employee record ({0}) that doesn\'t exist", employeeId));
            //            }
            this.Statements.Add(new CodeCheckRecordDetachedStatement(tableSchema, rowVariableExpression, primaryKeyExpression));

            //            // The Optimistic Concurrency check allows only one client to update a record at a time.
            //            if ((employeeRow.RowVersion != rowVersion)) {
            //                throw new global::System.ServiceModel.FaultException<OptimisticConcurrencyFault>(new global::FluidTrade.Core.OptimisticConcurrencyFault("The Employee record (Employee) is busy.  Please try again later.", employeeId));
            //            }
            this.Statements.Add(new CodeCheckConcurrencyStatement(tableSchema, rowVariableExpression, primaryKeyExpression));

            //            // This will provide the defaults elements of the Employee table that haven't changed.
            //            if ((age == null)) {
            //                age = employeeRow[FluidTrade.UnitTest.Server.DataModel.Employee.AgeColumn];
            //            }
            //            if ((departmentId == null)) {
            //                departmentId = employeeRow[FluidTrade.UnitTest.Server.DataModel.Employee.DepartmentIdColumn];
            //            }
            //            if ((raceCode == null)) {
            //                raceCode = employeeRow[FluidTrade.UnitTest.Server.DataModel.Employee.RaceCodeColumn];
            //            }
            bool isDefaultCommentEmitted = false;

            foreach (ColumnSchema columnSchema in tableSchema.Columns.Values)
            {
                if (!columnSchema.IsRowVersion)
                {
                    if (!isDefaultCommentEmitted)
                    {
                        isDefaultCommentEmitted = true;
                    }
                    this.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression(CommonConversion.ToCamelCase(columnSchema.Name)), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null)),
                                                                   new CodeAssignStatement(new CodeArgumentReferenceExpression(CommonConversion.ToCamelCase(columnSchema.Name)), new CodeIndexerExpression(rowVariableExpression, new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(tableSchema.DataModel.Name), tableSchema.Name), string.Format("{0}Column", columnSchema.Name))))));
                }
            }

            //            // The current parent Department record is locked for reading for the duration of the transaction.
            //            employeeRow.DepartmentRow.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, FluidTrade.UnitTest.Server.DataModel.lockTimeout);
            //            middleTierTransaction.AdoResourceManager.AddLock(employeeRow.DepartmentRow);
            //            // This makes sure the record wasn't deleted in the time between when it was found and the time it was locked.
            //            if ((employeeRow.DepartmentRow.RowState == global::System.Data.DataRowState.Detached)) {
            //                throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Department record ({0}) that doesn\'t exist", departmentId));
            //            }
            //            // The current parent Object record is locked for reading for the duration of the transaction.
            //            employeeRow.ObjectRow.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, FluidTrade.UnitTest.Server.DataModel.lockTimeout);
            //            middleTierTransaction.AdoResourceManager.AddLock(employeeRow.ObjectRow);
            //            // This makes sure the record wasn't deleted in the time between when it was found and the time it was locked.
            //            if ((employeeRow.ObjectRow.RowState == global::System.Data.DataRowState.Detached)) {
            //                throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Object record ({0}) that doesn\'t exist", employeeId));
            //            }
            //            // The current parent Race record is locked for reading for the duration of the transaction.
            //            if ((employeeRow.RaceRow != null)) {
            //                employeeRow.RaceRow.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, FluidTrade.UnitTest.Server.DataModel.lockTimeout);
            //                middleTierTransaction.AdoResourceManager.AddLock(employeeRow.RaceRow);
            //                // This makes sure the record wasn't deleted in the time between when it was found and the time it was locked.
            //                if ((employeeRow.RaceRow.RowState == global::System.Data.DataRowState.Detached)) {
            //                    throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Race record ({0}) that doesn\'t exist", raceCode));
            //                }
            //            }
            foreach (KeyValuePair <string, RelationSchema> relationPair in tableSchema.ParentRelations)
            {
                if (tableSchema != relationPair.Value.ParentTable)
                {
                    // This is the table containing the parent record that is to be locked for the transaction.
                    TableSchema parentTable = relationPair.Value.ParentTable;

                    // The varible name for the parent row is decorated with the foreign key name thus making it unique.
                    string parentRowName     = string.Format("{0}RowBy{1}", CommonConversion.ToCamelCase(parentTable.Name), relationPair.Value.Name);
                    string parentRowTypeName = string.Format("{0}Row", parentTable.Name);
                    CodePropertyReferenceExpression parentRowExpression = relationPair.Value.IsDistinctPathToParent ?
                                                                          new CodePropertyReferenceExpression(rowVariableExpression, string.Format("{0}Row", parentTable.Name)) :
                                                                          new CodePropertyReferenceExpression(rowVariableExpression, string.Format("{0}RowBy{1}", parentTable.Name, relationPair.Value.Name));

                    //            // The current parent Department record is locked for reading for the duration of the transaction.
                    //            employeeRow.DepartmentRow.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, FluidTrade.UnitTest.Server.DataModel.lockTimeout);
                    //            middleTierTransaction.AdoResourceManager.AddLock(employeeRow.DepartmentRow);
                    CodeStatementCollection codeStatementCollection;
                    if (relationPair.Value.ChildKeyConstraint.IsNullable)
                    {
                        CodeConditionStatement ifParentKeyExists = new CodeConditionStatement(new CodeBinaryOperatorExpression(parentRowExpression, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)));
                        codeStatementCollection = ifParentKeyExists.TrueStatements;
                        this.Statements.Add(ifParentKeyExists);
                    }
                    else
                    {
                        codeStatementCollection = this.Statements;
                    }
                    codeStatementCollection.Add(new CodeAcquireRecordReaderLockExpression(transactionExpression, parentRowExpression, parentTable.DataModel));
                    codeStatementCollection.Add(new CodeAddLockToTransactionExpression(transactionExpression, parentRowExpression));

                    //            // This makes sure the record wasn't deleted in the time between when it was found and the time it was locked.
                    //            if ((employeeRow.DepartmentRow.RowState == global::System.Data.DataRowState.Detached)) {
                    //                throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Department record ({0}) that doesn\'t exist", departmentId));
                    //            }
                    codeStatementCollection.Add(new CodeCheckRecordDetachedStatement(parentTable, parentRowExpression, new CodeKeyCreateExpression(relationPair.Value.ChildColumns)));
                }
            }

            //            // Find the new proposed parent Department record if it is required for a foreign key constraint.
            //            FluidTrade.UnitTest.Server.DataModel.DepartmentRow departmentRowByFK_Department_Employee = FluidTrade.UnitTest.Server.DataModel.Department.FindByDepartmentId(new object[] {
            //                        departmentId});
            //            if ((departmentRowByFK_Department_Employee == null)) {
            //                throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Department record ({0}) that doesn\'t exist", departmentId));
            //            }
            //            departmentRowByFK_Department_Employee.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, FluidTrade.UnitTest.Server.DataModel.lockTimeout);
            //            middleTierTransaction.AdoResourceManager.AddLock(departmentRowByFK_Department_Employee);
            //            // This makes sure the record wasn't deleted in the time between when it was found and the time it was locked.
            //            if ((departmentRowByFK_Department_Employee.RowState == global::System.Data.DataRowState.Detached)) {
            //                throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Department record ({0}) that doesn\'t exist", departmentId));
            //            }
            //            // Find the new proposed parent Object record if it is required for a foreign key constraint.
            //            FluidTrade.UnitTest.Server.DataModel.ObjectRow objectRowByFK_Object_Employee = FluidTrade.UnitTest.Server.DataModel.Object.FindByObjectId(new object[] {
            //                        employeeId});
            //            if ((objectRowByFK_Object_Employee == null)) {
            //                throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Object record ({0}) that doesn\'t exist", employeeId));
            //            }
            //            objectRowByFK_Object_Employee.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, FluidTrade.UnitTest.Server.DataModel.lockTimeout);
            //            middleTierTransaction.AdoResourceManager.AddLock(objectRowByFK_Object_Employee);
            //            // This makes sure the record wasn't deleted in the time between when it was found and the time it was locked.
            //            if ((objectRowByFK_Object_Employee.RowState == global::System.Data.DataRowState.Detached)) {
            //                throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Object record ({0}) that doesn\'t exist", employeeId));
            //            }
            //            // Find the new proposed parent Race record if it is required for a foreign key constraint.
            //            if ((raceCode != global::System.DBNull.Value)) {
            //                FluidTrade.UnitTest.Server.DataModel.RaceRow raceRowByFK_Race_Employee = FluidTrade.UnitTest.Server.DataModel.Race.FindByRaceCode(new object[] {
            //                            raceCode});
            //                if ((raceRowByFK_Race_Employee == null)) {
            //                    throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Race record ({0}) that doesn\'t exist", raceCode));
            //                }
            //                raceRowByFK_Race_Employee.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, FluidTrade.UnitTest.Server.DataModel.lockTimeout);
            //                middleTierTransaction.AdoResourceManager.AddLock(raceRowByFK_Race_Employee);
            //                // This makes sure the record wasn't deleted in the time between when it was found and the time it was locked.
            //                if ((raceRowByFK_Race_Employee.RowState == global::System.Data.DataRowState.Detached)) {
            //                    throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Race record ({0}) that doesn\'t exist", raceCode));
            //                }
            //            }
            foreach (KeyValuePair <string, RelationSchema> relationPair in tableSchema.ParentRelations)
            {
                if (tableSchema != relationPair.Value.ParentTable)
                {
                    // This is the table containing the parent record that is to be locked for the transaction.
                    TableSchema parentTable = relationPair.Value.ParentTable;

                    // The varible name for the parent row is decorated with the foreign key name thus making it unique.
                    CodeVariableReferenceExpression parentRowVariableExpression = new CodeRandomVariableReferenceExpression();
                    CodeTypeReference parentRowType = new CodeTypeReference(string.Format("{0}Row", parentTable.Name));

                    //            // Find the new proposed parent Race record if it is required for a foreign key constraint.
                    //            if ((raceCode != global::System.DBNull.Value)) {
                    CodeExpression lockConditions = null;
                    foreach (ColumnSchema columnSchema in relationPair.Value.ChildColumns)
                    {
                        if (columnSchema.IsNullable)
                        {
                            lockConditions = lockConditions == null ? new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression(CommonConversion.ToCamelCase(columnSchema.Name)), CodeBinaryOperatorType.IdentityInequality, new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(System.DBNull)), "Value")) :
                                             new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression(CommonConversion.ToCamelCase(columnSchema.Name)), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)), CodeBinaryOperatorType.BitwiseAnd, lockConditions);
                        }
                    }
                    CodeStatementCollection codeStatementCollection;
                    if (lockConditions == null)
                    {
                        codeStatementCollection = this.Statements;
                    }
                    else
                    {
                        CodeConditionStatement ifParentKeyExists = new CodeConditionStatement(lockConditions);
                        this.Statements.Add(ifParentKeyExists);
                        codeStatementCollection = ifParentKeyExists.TrueStatements;
                    }

                    //                global::System.Object[] raceRowByFK_Race_EmployeeKey = new object[] {
                    //                            employeeId});
                    //                FluidTrade.UnitTest.Server.DataModel.RaceRow raceRowByFK_Race_Employee = FluidTrade.UnitTest.Server.DataModel.Race.FindByRaceCode(new object[] {
                    //                            raceCode});
                    //                if ((raceRowByFK_Race_Employee == null)) {
                    //                    throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Race record ({0}) that doesn\'t exist", raceCode));
                    //                }
                    CodeVariableReferenceExpression parentKeyExpression = new CodeRandomVariableReferenceExpression();
                    codeStatementCollection.Add(new CodeVariableDeclarationStatement(new CodeGlobalTypeReference(typeof(System.Object[])), parentKeyExpression.VariableName, new CodeKeyCreateExpression(relationPair.Value.ChildColumns)));
                    if (tableSchema.PrimaryKey == null)
                    {
                        codeStatementCollection.Add(new CodeVariableDeclarationStatement(parentRowType, parentRowVariableExpression.VariableName, new CodeFindByRowExpression(parentTable, parentKeyExpression)));
                    }
                    else
                    {
                        codeStatementCollection.Add(new CodeVariableDeclarationStatement(parentRowType, parentRowVariableExpression.VariableName, new CodeFindByIndexExpression(parentTable, parentKeyExpression)));
                    }
                    codeStatementCollection.Add(new CodeCheckRecordExistsStatement(parentTable, parentRowVariableExpression, parentKeyExpression));

                    //                raceRowByFK_Race_Employee.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, FluidTrade.UnitTest.Server.DataModel.lockTimeout);
                    //                middleTierTransaction.AdoResourceManager.AddLock(raceRowByFK_Race_Employee);
                    codeStatementCollection.Add(new CodeAcquireRecordReaderLockExpression(transactionExpression, parentRowVariableExpression, parentTable.DataModel));
                    codeStatementCollection.Add(new CodeAddLockToTransactionExpression(transactionExpression, parentRowVariableExpression));

                    //                // This makes sure the record wasn't deleted in the time between when it was found and the time it was locked.
                    //                if ((raceRowByFK_Race_Employee.RowState == global::System.Data.DataRowState.Detached)) {
                    //                    throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Race record ({0}) that doesn\'t exist", raceCode));
                    //                }
                    //            }
                    codeStatementCollection.Add(new CodeCheckRecordDetachedStatement(parentTable, parentRowVariableExpression, parentKeyExpression));
                }
            }

            //            // Update the Employee record in the ADO data model.
            //            middleTierTransaction.AdoResourceManager.AddRecord(employeeRow);
            //            try {
            //                FluidTrade.UnitTest.Server.DataModel.Department.AcquireLock();
            //                FluidTrade.UnitTest.Server.DataModel.Employee.AcquireLock();
            //                FluidTrade.UnitTest.Server.DataModel.Object.AcquireLock();
            //                FluidTrade.UnitTest.Server.DataModel.Race.AcquireLock();
            //                employeeRow.BeginEdit();
            //                employeeRow[FluidTrade.UnitTest.Server.DataModel.Employee.AgeColumn] = age;
            //                employeeRow[FluidTrade.UnitTest.Server.DataModel.Employee.DepartmentIdColumn] = departmentId;
            //                employeeRow[FluidTrade.UnitTest.Server.DataModel.Employee.RaceCodeColumn] = raceCode;
            //                employeeRow[FluidTrade.UnitTest.Server.DataModel.Employee.RowVersionColumn] = global::System.Threading.Interlocked.Increment(ref FluidTrade.UnitTest.Server.DataModel.masterRowVersion);
            //            }
            //            finally {
            //                employeeRow.EndEdit();
            //                FluidTrade.UnitTest.Server.DataModel.Department.ReleaseLock();
            //                FluidTrade.UnitTest.Server.DataModel.Employee.ReleaseLock();
            //                FluidTrade.UnitTest.Server.DataModel.Object.ReleaseLock();
            //                FluidTrade.UnitTest.Server.DataModel.Race.ReleaseLock();
            //            }
            this.Statements.Add(new CodeAddRecordToTransactionExpression(transactionExpression, rowVariableExpression));
            CodeTryCatchFinallyStatement tryFinallyStatement = new CodeTryCatchFinallyStatement();

            tryFinallyStatement.TryStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(tableSchema.DataModel.Name), "DataLock"),
                    "EnterWriteLock"));
            tryFinallyStatement.TryStatements.Add(new CodeMethodInvokeExpression(rowVariableExpression, "BeginEdit"));
            foreach (ColumnSchema columnSchema in tableSchema.Columns.Values)
            {
                if (columnSchema.IsAutoIncrement || columnSchema.IsPrimaryKey)
                {
                    continue;
                }
                CodeExpression sourceExpression;
                if (columnSchema.IsRowVersion)
                {
                    sourceExpression = sourceExpression = new CodeMethodInvokeExpression(
                        new CodeFieldReferenceExpression(
                            new CodeTypeReferenceExpression(tableSchema.DataModel.Name),
                            String.Format("{0}DataSet", CommonConversion.ToCamelCase(tableSchema.DataModel.Name))),
                        "IncrementRowVersion");
                }
                else
                {
                    sourceExpression = new CodeArgumentReferenceExpression(CommonConversion.ToCamelCase(columnSchema.Name));
                }
                tryFinallyStatement.TryStatements.Add(new CodeAssignStatement(new CodeIndexerExpression(rowVariableExpression, new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(tableSchema.DataModel.Name), tableSchema.Name), string.Format("{0}Column", columnSchema.Name))), sourceExpression));
            }
            tryFinallyStatement.FinallyStatements.Add(new CodeMethodInvokeExpression(rowVariableExpression, "EndEdit"));
            tryFinallyStatement.FinallyStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(tableSchema.DataModel.Name), "DataLock"),
                    "ExitWriteLock"));
            this.Statements.Add(tryFinallyStatement);

            //            // Update the Employee record in the SQL data model.
            //            global::System.Data.SqlClient.SqlCommand sqlCommand = new global::System.Data.SqlClient.SqlCommand("update \"Employee\" set \"Age\"=@age,\"DepartmentId\"=@departmentId,\"RaceCode\"=@raceCod" +
            //                    "e,\"RowVersion\"=@rowVersion,\"RowVersion\"=@rowVersion where \"EmployeeId\"=@employee" +
            //                    "Id", middleTierTransaction.SqlConnection);
            //            sqlCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@age", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, false, 0, 0, null, global::System.Data.DataRowVersion.Current, age));
            //            sqlCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@departmentId", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, false, 0, 0, null, global::System.Data.DataRowVersion.Current, departmentId));
            //            sqlCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@employeeId", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, false, 0, 0, null, global::System.Data.DataRowVersion.Current, employeeId));
            //            sqlCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@raceCode", global::System.Data.SqlDbType.Int, 0, global::System.Data.ParameterDirection.Input, false, 0, 0, null, global::System.Data.DataRowVersion.Current, raceCode));
            //            sqlCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@rowVersion", global::System.Data.SqlDbType.BigInt, 0, global::System.Data.ParameterDirection.Input, false, 0, 0, null, global::System.Data.DataRowVersion.Current, employeeRow[FluidTrade.UnitTest.Server.DataModel.Employee.RowVersionColumn]));
            //            sqlCommand.ExecuteNonQuery();
            if (tableSchema.IsPersistent)
            {
                CodeVariableReferenceExpression sqlCommandExpression = new CodeRandomVariableReferenceExpression();
                string setList = string.Empty;
                foreach (ColumnSchema columnSchema in tableSchema.Columns.Values)
                {
                    if (columnSchema.IsPersistent && !columnSchema.IsAutoIncrement)
                    {
                        setList += string.Format(setList == string.Empty ? "\"{0}\"=@{1}" : ",\"{0}\"=@{1}", columnSchema.Name, CommonConversion.ToCamelCase(columnSchema.Name));
                    }
                }
                string whereClause = string.Empty;
                foreach (ColumnSchema columnSchema in tableSchema.PrimaryKey.Columns)
                {
                    whereClause += string.Format(whereClause == string.Empty ? "\"{0}\"=@key{0}" : " and \"{0}\"=@key{0}", columnSchema.Name);
                }
                string insertCommandText = string.Format("update \"{0}\" set {1} where {2}", tableSchema.Name, setList, whereClause);
                this.Statements.Add(new CodeVariableDeclarationStatement(new CodeGlobalTypeReference(typeof(System.Data.SqlClient.SqlCommand)), sqlCommandExpression.VariableName, new CodeObjectCreateExpression(new CodeGlobalTypeReference(typeof(System.Data.SqlClient.SqlCommand)), new CodePrimitiveExpression(insertCommandText), new CodePropertyReferenceExpression(transactionExpression, "SqlConnection"))));

                foreach (ColumnSchema columnSchema in tableSchema.Columns.Values)
                {
                    if (columnSchema.IsPersistent)
                    {
                        string variableName = CommonConversion.ToCamelCase(columnSchema.Name);
                        if (!columnSchema.IsAutoIncrement)
                        {
                            CodeExpression sourceExpression = columnSchema.IsRowVersion ?
                                                              (CodeExpression) new CodeIndexerExpression(rowVariableExpression, new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(tableSchema.DataModel.Name), tableSchema.Name), "RowVersionColumn")) :
                                                              (CodeExpression) new CodeArgumentReferenceExpression(variableName);
                            this.Statements.Add(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(sqlCommandExpression, "Parameters"), "Add", new CodeObjectCreateExpression(new CodeGlobalTypeReference(typeof(System.Data.SqlClient.SqlParameter)), new CodePrimitiveExpression(string.Format("@{0}", variableName)), TypeConverter.Convert(columnSchema.DataType), new CodePrimitiveExpression(0), new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(System.Data.ParameterDirection)), "Input"), new CodePrimitiveExpression(false), new CodePrimitiveExpression(0), new CodePrimitiveExpression(0), new CodePrimitiveExpression(null), new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(System.Data.DataRowVersion)), "Current"), sourceExpression)));
                        }
                    }
                }

                foreach (ColumnSchema columnSchema in tableSchema.PrimaryKey.Columns)
                {
                    string         variableName     = string.Format("key{0}", columnSchema.Name);
                    CodeExpression sourceExpression = new CodePropertyReferenceExpression(rowVariableExpression, columnSchema.Name);
                    this.Statements.Add(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(sqlCommandExpression, "Parameters"), "Add", new CodeObjectCreateExpression(new CodeGlobalTypeReference(typeof(System.Data.SqlClient.SqlParameter)), new CodePrimitiveExpression(string.Format("@{0}", variableName)), TypeConverter.Convert(columnSchema.DataType), new CodePrimitiveExpression(0), new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(System.Data.ParameterDirection)), "Input"), new CodePrimitiveExpression(false), new CodePrimitiveExpression(0), new CodePrimitiveExpression(0), new CodePrimitiveExpression(null), new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(System.Data.DataRowVersion)), "Current"), sourceExpression)));
                }

                this.Statements.Add(new CodeMethodInvokeExpression(sqlCommandExpression, "ExecuteNonQuery"));
            }

            //			DataModel.DestinationOrder.OnRowValidate(new DestinationOrderRowChangeEventArgs(pe9564f2717374e96a76d5222e2258784, System.Data.DataRowAction.Change));
            this.Statements.Add(
                new CodeMethodInvokeExpression(
                    new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(tableSchema.DataModel.Name), tableSchema.Name),
                    "OnRowValidate",
                    new CodeObjectCreateExpression(
                        string.Format("{0}RowChangeEventArgs", tableSchema.Name),
                        rowVariableExpression,
                        new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(System.Data.DataRowAction)), "Change"))));

            //        }
        }
示例#17
0
        /// <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);
        }
示例#18
0
 protected abstract void GenerateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e);
示例#19
0
        /// <summary>
        /// Creates a property that gets the parent row.
        /// </summary>
        /// <param name="relationSchema">The foreign key that references the parent table.</param>
        public ParentRowProperty(RelationSchema relationSchema)
        {
            // These constructs are used several times to generate the property.
            TableSchema childTable     = relationSchema.ChildTable;
            TableSchema parentTable    = relationSchema.ParentTable;
            string      rowTypeName    = String.Format("{0}Row", parentTable.Name);
            string      tableFieldName = String.Format("table{0}", childTable.Name);
            string      relationName   = relationSchema.IsDistinctPathToParent ?
                                         String.Format("{0}{1}Relation", parentTable.Name, childTable.Name) :
                                         String.Format("{0}{1}By{2}Relation", relationSchema.ParentTable.Name, relationSchema.ChildTable.Name, relationSchema.Name);
            string relationFieldName = relationSchema.IsDistinctPathToParent ?
                                       String.Format("{0}{1}Relation", relationSchema.ParentTable.Name, relationSchema.ChildTable.Name) :
                                       String.Format("{0}{1}By{2}Relation", relationSchema.ParentTable.Name, relationSchema.ChildTable.Name, relationSchema.Name);

            //		/// <summary>
            //		/// Gets the parent row in the Currency table.
            //		/// </summary>
            //		public CurrencyRow CurrencyRow
            //		{
            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement(String.Format("Gets the parent row in the {0} table.", relationSchema.ParentTable.Name), true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            this.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeGlobalTypeReference(typeof(DebuggerNonUserCodeAttribute))));
            this.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            this.Type       = new CodeTypeReference(rowTypeName);
            this.Name       = relationSchema.IsDistinctPathToParent ? rowTypeName : String.Format("{0}By{1}", rowTypeName, relationSchema.Name);

            //			get
            //			{
            //				DataModelTransaction k7494 = DataModel.CurrentTransaction;
            CodeVariableReferenceExpression transactionExpression = new CodeRandomVariableReferenceExpression();

            this.GetStatements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeTypeReference(String.Format("{0}Transaction", parentTable.DataModel.Name)),
                    transactionExpression.VariableName,
                    new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(parentTable.DataModel.Name), "CurrentTransaction")));

            //				if ((this.IsLockHeld(k7494.TransactionId) == false))
            //				{
            //					throw new global::System.ServiceModel.FaultException<Teraque.SynchronizationLockFault>(new global::Teraque.SynchronizationLockFault("AccountBase"));
            //				}
            this.GetStatements.AddRange(
                new CodeCheckReaderLockHeldStatements(new CodeThisReferenceExpression(), relationSchema.ChildTable, transactionExpression));

            //				try
            //				{
            //					((TenantDataModel)this.Table.DataSet).dataLock.EnterReadLock();
            //					return ((CurrencyRow)(this.GetParentRow(this.tableAccountBase.CurrencyAccountBaseRelation)));
            CodeTryCatchFinallyStatement tryCatchFinallyStatement = new CodeTryCatchFinallyStatement();

            tryCatchFinallyStatement.TryStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(
                        new CodeCastExpression(
                            new CodeTypeReference(String.Format("Tenant{0}", parentTable.DataModelSchema.Name)),
                            new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Table"), "DataSet")),
                        "dataLock"),
                    "EnterReadLock"));
            tryCatchFinallyStatement.TryStatements.Add(
                new CodeMethodReturnStatement(
                    new CodeCastExpression(
                        rowTypeName,
                        new CodeMethodInvokeExpression(
                            new CodeThisReferenceExpression(),
                            "GetParentRow",
                            new CodePropertyReferenceExpression(
                                new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), tableFieldName),
                                relationFieldName)))));

            //				}
            //				finally
            //				{
            //					((TenantDataModel)this.Table.DataSet).dataLock.ExitReadLock();
            //				}
            tryCatchFinallyStatement.FinallyStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(
                        new CodeCastExpression(
                            new CodeTypeReference(String.Format("Tenant{0}", parentTable.DataModelSchema.Name)),
                            new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Table"), "DataSet")),
                        "dataLock"),
                    "ExitReadLock"));
            this.GetStatements.Add(tryCatchFinallyStatement);

            //			}
            //		}
        }
示例#20
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");
        }
示例#21
0
        /// <summary>
        /// Creates a method to read an XML file.
        /// </summary>
        /// <param name="schema">The data model schema.</param>
        public RollbackMethod(DataModelSchema dataModelSchema)
        {
            //		/// <summary>
            //		/// Rollback (undo) any of the changes made during the transaction.
            //		/// </summary>
            //		/// <param name="enlistment">Facilitates communication between an enlisted transaction and the transaction manager during the
            //		/// final phase of the transaction.</param>
            //		public void Rollback(global::System.Transactions.Enlistment enlistment)
            //		{
            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement("Adds a row lock to the list of locks that must be released at the end of a transaction.", true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            this.Comments.Add(new CodeCommentStatement("<param name=\"enlistment\">Facilitates communication bewtween an enlisted transaction participant and the transaction", true));
            this.Comments.Add(new CodeCommentStatement("manager during the final phase of the transaction.</param>", true));
            this.CustomAttributes.AddRange(new CodeCustomAttributesForMethods());
            this.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            this.Name       = "Rollback";
            this.Parameters.Add(new CodeParameterDeclarationExpression(new CodeGlobalTypeReference(typeof(Enlistment)), "enlistment"));

            //			this.recordList.Reverse();
            this.Statements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "recordList"), "Reverse"));

            //			try
            //			{
            CodeTryCatchFinallyStatement tryEnterLock = new CodeTryCatchFinallyStatement();

            //				DataModel.DataLock.EnterWriteLock();
            tryEnterLock.TryStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "DataLock"),
                    "EnterWriteLock"));

            //				for (int recordIndex = 0; (recordIndex < this.recordList.Count); recordIndex = (recordIndex + 1))
            //				{
            CodeIterationStatement forRecordList = new CodeIterationStatement(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Int32)),
                    "recordIndex",
                    new CodePrimitiveExpression(0)),
                new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("recordIndex"),
                    CodeBinaryOperatorType.LessThan,
                    new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "recordList"), "Count")),
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("recordIndex"),
                    new CodeBinaryOperatorExpression(
                        new CodeVariableReferenceExpression("recordIndex"),
                        CodeBinaryOperatorType.Add,
                        new CodePrimitiveExpression(1))));

            //					IRow iRow = this.recordList[recordIndex];
            forRecordList.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(FluidTrade.Core.IRow)),
                    "iRow",
                    new CodeIndexerExpression(
                        new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "recordList"),
                        new CodeVariableReferenceExpression("recordIndex"))));

            //					if ((iRow.RowState == global::System.Data.DataRowState.Added) ||
            //								((iRow.RowState == global::System.Data.DataRowState.Deleted) ||
            //												(iRow.RowState == global::System.Data.DataRowState.Modified)))
            //					{
            CodeConditionStatement ifRejectable = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                    new CodeBinaryOperatorExpression(
                        new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("iRow"), "RowState"),
                        CodeBinaryOperatorType.IdentityEquality,
                        new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(DataRowState)), "Added")),
                    CodeBinaryOperatorType.BooleanOr,
                    new CodeBinaryOperatorExpression(
                        new CodeBinaryOperatorExpression(
                            new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("iRow"), "RowState"),
                            CodeBinaryOperatorType.IdentityEquality,
                            new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(DataRowState)), "Deleted")),
                        CodeBinaryOperatorType.BooleanOr,
                        new CodeBinaryOperatorExpression(
                            new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("iRow"), "RowState"),
                            CodeBinaryOperatorType.IdentityEquality,
                            new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(DataRowState)), "Modified")))));

            //						iRow.RejectChanges();
            ifRejectable.TrueStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("iRow"), "RejectChanges"));

            //					}
            forRecordList.Statements.Add(ifRejectable);

            //				}
            tryEnterLock.TryStatements.Add(forRecordList);

            //				for (int recordIndex = 0; recordIndex < this.lockList.Count; recordIndex = (recordIndex + 1))
            //				{
            CodeIterationStatement forLockList = new CodeIterationStatement(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Int32)),
                    "lockIndex",
                    new CodePrimitiveExpression(0)),
                new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("lockIndex"),
                    CodeBinaryOperatorType.LessThan,
                    new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "lockList"), "Count")),
                new CodeAssignStatement(
                    new CodeVariableReferenceExpression("lockIndex"),
                    new CodeBinaryOperatorExpression(
                        new CodeVariableReferenceExpression("lockIndex"),
                        CodeBinaryOperatorType.Add,
                        new CodePrimitiveExpression(1))));

            //					this.lockList[recordIndex].ReleaseLock(this.transactionId);
            forLockList.Statements.Add(
                new CodeMethodInvokeExpression(
                    new CodeIndexerExpression(
                        new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "lockList"),
                        new CodeVariableReferenceExpression("lockIndex")),
                    "ReleaseLock",
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "transactionId")));

            //				}
            tryEnterLock.TryStatements.Add(forLockList);

            //			}
            //			finally
            //			{
            //				DataModel.DataLock.ExitWriteLock();
            tryEnterLock.FinallyStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "DataLock"),
                    "ExitWriteLock"));

            //			}
            this.Statements.Add(tryEnterLock);

            //			enlistment.Done();
            this.Statements.Add(new CodeMethodInvokeExpression(new CodeArgumentReferenceExpression("enlistment"), "Done"));

            //		}
        }
示例#22
0
			public void Visit(CodeTryCatchFinallyStatement o)
			{
				g.GenerateTryCatchFinallyStatement(o);
			}
示例#23
0
        private static CodeStatementCollection GenerateInvokeExpressionWithPins(CodeMemberMethod f)
        {
            CodeVariableReferenceExpression[] parameters = new CodeVariableReferenceExpression[f.Parameters.Count];
            CodeTryCatchFinallyStatement      m          = new CodeTryCatchFinallyStatement();
            CodeStatementCollection           statements = new CodeStatementCollection();

            int h = 0;
            int i = 0;

            foreach (CodeParameterDeclarationExpression p in f.Parameters)
            {
                // Do manual marshalling for objects and arrays, but not strings.
                if (p.Type.BaseType.ToLower().Contains("object") ||
                    (p.Type.ArrayRank > 0 && !p.Type.BaseType.ToLower().Contains("string")) ||
                    ((p.Direction == FieldDirection.Ref ||
                      p.Direction == FieldDirection.Out) &&
                     !p.Type.BaseType.ToLower().Contains("string")))
                {
                    if (p.Direction == FieldDirection.Out)
                    {
                        statements.Add(
                            new CodeAssignStatement(
                                new CodeVariableReferenceExpression(p.Name),
                                new CodeSnippetExpression("default(" + p.Type.BaseType + ")")
                                )
                            );
                    }

                    // Pin the object and store the resulting GCHandle to h0, h1, ...
                    CodeVariableDeclarationStatement s = new CodeVariableDeclarationStatement();
                    s.Type           = new CodeTypeReference("GCHandle");
                    s.Name           = "h" + h;
                    s.InitExpression =
                        new CodeMethodInvokeExpression(
                            new CodeTypeReferenceExpression("GCHandle"),
                            "Alloc",
                            new CodeTypeReferenceExpression[] {
                        new CodeTypeReferenceExpression(p.Name),
                        new CodeTypeReferenceExpression("GCHandleType.Pinned")
                    }
                            );
                    statements.Add(s);

                    // Free the object using the h0, h1, ... variables
                    m.FinallyStatements.Add(
                        new CodeMethodInvokeExpression(
                            new CodeTypeReferenceExpression("h" + h),
                            "Free"
                            )
                        );
                    // Add the h(n) variable to the list of parameters
                    parameters[i] = new CodeVariableReferenceExpression("h" + h + ".AddrOfPinnedObject()");

                    // Add an assignment statement: "variable_name = (variable_type)h(n).Target" for out parameters.
                    if (p.Direction == FieldDirection.Out)
                    {
                        m.TryStatements.Add(
                            new CodeAssignStatement(
                                new CodeVariableReferenceExpression(p.Name),
                                new CodeSnippetExpression("(" + p.Type.BaseType + ")h" + h + ".Target")
                                )
                            );
                    }

                    h++;
                }
                else
                {
                    // Add the normal paramater to the parameter list
                    parameters[i] = new CodeVariableReferenceExpression(p.Name);
                }
                i++;
            }

            if (f.ReturnType.BaseType.Contains("Void"))
            {
                m.TryStatements.Insert(0,
                                       new CodeExpressionStatement(
                                           new CodeMethodInvokeExpression(
                                               new CodeTypeReferenceExpression("Delegates"),
                                               f.Name,
                                               parameters
                                               )
                                           )
                                       );
            }
            else
            {
                m.TryStatements.Insert(0, new CodeVariableDeclarationStatement(f.ReturnType, "retval"));
                m.TryStatements.Insert(1,
                                       new CodeAssignStatement(
                                           new CodeVariableReferenceExpression("retval"),
                                           new CodeMethodInvokeExpression(
                                               new CodeTypeReferenceExpression("Delegates"),
                                               f.Name,
                                               parameters
                                               )
                                           )
                                       );

                m.TryStatements.Add(
                    new CodeMethodReturnStatement(new CodeVariableReferenceExpression("retval"))
                    );
            }

            statements.Add(m);

            return(statements);
        }
    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);
        }
    }
示例#25
0
 protected override void GenerateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e)
 {
     Output.Write("tryCatchFinally");
 }
        /// <summary>
        /// Generates a method to get a list of child rows.
        /// </summary>
        /// <param name="relationSchema">A description of the relation between two tables.</param>
        public GetChildRowsMethod(RelationSchema relationSchema)
        {
            // These variables are used to construct the method.
            TableSchema childTable       = relationSchema.ChildTable;
            TableSchema parentTable      = relationSchema.ParentTable;
            string      rowTypeName      = String.Format("{0}Row", childTable.Name);
            string      tableFieldName   = String.Format("table{0}", parentTable.Name);
            string      childRowTypeName = String.Format("{0}Row", relationSchema.ChildTable.Name);

            //		/// <summary>
            //		/// Gets the children rows in the AccountGroup table.
            //		/// </summary>
            //		public AccountGroupRow[] GetAccountGroupRows()
            //		{
            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement(String.Format("Gets the children rows in the {0} table.", relationSchema.ChildTable.Name), true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            this.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            this.ReturnType = new CodeTypeReference(childRowTypeName, 1);
            this.Name       = relationSchema.IsDistinctPathToChild ?
                              String.Format("Get{0}s", childRowTypeName) :
                              String.Format("Get{0}sBy{1}", childRowTypeName, relationSchema.Name);
            string relationName = relationSchema.IsDistinctPathToChild ?
                                  String.Format("{0}{1}Relation", relationSchema.ParentTable.Name, relationSchema.ChildTable.Name) :
                                  String.Format("{0}{1}By{2}Relation", relationSchema.ParentTable.Name, relationSchema.ChildTable.Name, relationSchema.Name);

            //			DataModelTransaction p7519 = DataModel.CurrentTransaction;
            CodeVariableReferenceExpression transactionExpression = new CodeRandomVariableReferenceExpression();

            this.Statements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeTypeReference(String.Format("{0}Transaction", parentTable.DataModel.Name)),
                    transactionExpression.VariableName,
                    new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(parentTable.DataModel.Name), "CurrentTransaction")));

            //			if ((this.IsLockHeld(p7519.TransactionId) == false))
            //			{
            //				throw new global::System.ServiceModel.FaultException<Teraque.SynchronizationLockFault>(new global::Teraque.SynchronizationLockFault("AccountBase"));
            //			}
            this.Statements.AddRange(new CodeCheckReaderLockHeldStatements(new CodeThisReferenceExpression(), relationSchema.ParentTable, transactionExpression));

            //			try
            //			{
            CodeTryCatchFinallyStatement tryCatchFinallyStatement = new CodeTryCatchFinallyStatement();

            //				((TenantDataModel)(this.Table.DataSet)).dataLock.EnterReadLock();
            tryCatchFinallyStatement.TryStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(
                        new CodeCastExpression(
                            new CodeTypeReference(String.Format("Tenant{0}", parentTable.DataModel.Name)),
                            new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Table"), "DataSet")),
                        "dataLock"),
                    "EnterReadLock"));

            //				return ((AccountGroupRow[])(this.GetChildRows(this.tableAccountBase.AccountBaseAccountGroupRelation)));
            tryCatchFinallyStatement.TryStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(new CodeTypeReference(childRowTypeName, 1), new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "GetChildRows", new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), tableFieldName), relationName)))));

            //			}
            //			finally
            //			{
            //				((TenantTarget)(this.Table.DataSet)).dataLock.ExitReadLock();
            tryCatchFinallyStatement.FinallyStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(
                        new CodeCastExpression(
                            new CodeTypeReference(String.Format("Tenant{0}", parentTable.DataModelSchema.Name)),
                            new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Table"), "DataSet")),
                        "dataLock"),
                    "ExitReadLock"));
            this.Statements.Add(tryCatchFinallyStatement);

            //			}
            //		}
        }
示例#27
0
        /// <summary>
        /// Creates the CodeDOM for a method to insert a record into a table using transacted logic.
        /// </summary>
        /// <param name="tableSchema">A description of the table.</param>
        public CreateMethod(TableSchema tableSchema)
        {
            // Create a matrix of parameters for this operation.
            CreateParameterMatrix createParameterMatrix = new CreateParameterMatrix(tableSchema);

            //        /// <summary>
            //        /// Creates a Employee record.
            //        /// </summary>
            //        /// <param name="age">The required value for the Age column.</param>
            //        /// <param name="departmentId">The required value for the DepartmentId column.</param>
            //        /// <param name="employeeId">The required value for the EmployeeId column.</param>
            //        /// <param name="raceCode">The optional value for the RaceCode column.</param>
            //        [global::System.ServiceModel.OperationBehaviorAttribute(TransactionScopeRequired=true)]
            //        [FluidTrade.Core.ClaimsPrincipalPermission(System.Security.Permissions.SecurityAction.Demand, ClaimType=FluidTrade.Core.ClaimTypes.Create, Resource=FluidTrade.Core.Resources.Application)]
            //        public void CreateEmployee(int age, int departmentId, int employeeId, object raceCode) {
            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement(string.Format("Creates a {0} record.", tableSchema.Name), true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            foreach (KeyValuePair <string, ExternalParameterItem> parameterPair in createParameterMatrix.ExternalParameterItems)
            {
                this.Comments.Add(new CodeCommentStatement(string.Format("<param name=\"{0}\">{1}</param>", parameterPair.Value.Name, parameterPair.Value.Description), true));
            }
            this.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeGlobalTypeReference(typeof(System.ServiceModel.OperationBehaviorAttribute)), new CodeAttributeArgument("TransactionScopeRequired", new CodePrimitiveExpression(true))));
            //AR FB 408 - Remove Claims requirement
            //this.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeGlobalTypeReference(typeof(ClaimsPrincipalPermission)), new CodeAttributeArgument(new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(System.Security.Permissions.SecurityAction)), "Demand")),
            //    new CodeAttributeArgument("ClaimType", new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(ClaimTypes)), "Create")),
            //    new CodeAttributeArgument("Resource", new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(Resources)), "Application"))));
            this.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            this.Name       = string.Format("Create{0}", tableSchema.Name);
            foreach (KeyValuePair <string, ExternalParameterItem> parameterPair in createParameterMatrix.ExternalParameterItems)
            {
                this.Parameters.Add(parameterPair.Value.CodeParameterDeclarationExpression);
            }

            //            // This provides a context for the middle tier transactions.
            //            global::FluidTrade.Core.MiddleTierContext middleTierTransaction = global::FluidTrade.Core.MiddleTierContext.Current;
            CodeVariableReferenceExpression transactionExpression = new CodeRandomVariableReferenceExpression();

            this.Statements.Add(new CodeCreateMiddleTierContextStatement(tableSchema.DataModel, transactionExpression));

            //            // Apply the defaults to optional parameters.
            //            if ((raceCode == null)) {
            //                raceCode = System.DBNull.Value;
            //            }
            foreach (ColumnSchema columnSchema in tableSchema.Columns.Values)
            {
                if (columnSchema.IsNullable || columnSchema.DefaultValue != DBNull.Value)
                {
                    CodeConditionStatement ifIsNull = new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression(CommonConversion.ToCamelCase(columnSchema.Name)), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null)));
                    ifIsNull.TrueStatements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression(CommonConversion.ToCamelCase(columnSchema.Name)), CodeConvert.CreateConstantExpression(columnSchema.DefaultValue)));
                    this.Statements.Add(ifIsNull);
                }
            }

            //            // Find the parent Department record if it is required for a foreign key constraint.
            //            FluidTrade.UnitTest.Server.DataModel.DepartmentRow departmentRowByFK_Department_Employee = FluidTrade.UnitTest.Server.DataModel.Department.FindByDepartmentId(new object[] {
            //                        departmentId});
            //            if ((departmentRowByFK_Department_Employee == null)) {
            //                throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Department record ({0}) that doesn\'t exist", departmentId));
            //            }
            //            // This record locked for reading for the duration of the transaction.
            //            departmentRowByFK_Department_Employee.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, FluidTrade.UnitTest.Server.DataModel.lockTimeout);
            //            middleTierTransaction.AdoResourceManager.AddLock(departmentRowByFK_Department_Employee);
            //            // This makes sure the record wasn't deleted in the time between when it was found and the time it was locked.
            //            if ((departmentRowByFK_Department_Employee.RowState == System.Data.DataRowState.Detached)) {
            //                throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Department record ({0}) that doesn\'t exist", departmentId));
            //            }
            //            // Find the parent Object record if it is required for a foreign key constraint.
            //            FluidTrade.UnitTest.Server.DataModel.ObjectRow objectRowByFK_Object_Employee = FluidTrade.UnitTest.Server.DataModel.Object.FindByObjectId(new object[] {
            //                        employeeId});
            //            if ((objectRowByFK_Object_Employee == null)) {
            //                throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Object record ({0}) that doesn\'t exist", employeeId));
            //            }
            //            // This record locked for reading for the duration of the transaction.
            //            objectRowByFK_Object_Employee.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, FluidTrade.UnitTest.Server.DataModel.lockTimeout);
            //            middleTierTransaction.AdoResourceManager.AddLock(objectRowByFK_Object_Employee);
            //            // This makes sure the record wasn't deleted in the time between when it was found and the time it was locked.
            //            if ((objectRowByFK_Object_Employee.RowState == System.Data.DataRowState.Detached)) {
            //                throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Object record ({0}) that doesn\'t exist", employeeId));
            //            }
            //            // Find the parent Race record if it is required for a foreign key constraint.
            //            if ((raceCode != System.DBNull.Value)) {
            //                FluidTrade.UnitTest.Server.DataModel.RaceRow raceRowByFK_Race_Employee = FluidTrade.UnitTest.Server.DataModel.Race.FindByRaceCode(new object[] {
            //                            raceCode});
            //                if ((raceRowByFK_Race_Employee == null)) {
            //                    throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Race record ({0}) that doesn\'t exist", raceCode));
            //                }
            //                // This record locked for reading for the duration of the transaction.
            //                raceRowByFK_Race_Employee.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, FluidTrade.UnitTest.Server.DataModel.lockTimeout);
            //                middleTierTransaction.AdoResourceManager.AddLock(raceRowByFK_Race_Employee);
            //                // This makes sure the record wasn't deleted in the time between when it was found and the time it was locked.
            //                if ((raceRowByFK_Race_Employee.RowState == System.Data.DataRowState.Detached)) {
            //                    throw new global::System.ServiceModel.FaultException<RecordNotFoundFault>(new global::FluidTrade.Core.RecordNotFoundFault("Attempt to access a Race record ({0}) that doesn\'t exist", raceCode));
            //                }
            //            }
            foreach (KeyValuePair <string, RelationSchema> relationPair in tableSchema.ParentRelations)
            {
                if (tableSchema != relationPair.Value.ParentTable)
                {
                    // This is the table containing the parent record that is to be locked for the transaction.
                    TableSchema parentTable = relationPair.Value.ParentTable;

                    // The varible name for the parent row is decorated with the foreign key name thus making it unique.
                    CodeVariableReferenceExpression parentRowVariableExpression = new CodeRandomVariableReferenceExpression();
                    CodeTypeReference parentRowType = new CodeTypeReference(string.Format("{0}Row", parentTable.Name));

                    // This chains all the non-null values of the primary key into an expression that tests if the given key values
                    // to the parent table have been provided in the input arguments to this method.  If the provided values are
                    // null, and the columns allow nulls, then there is no need to find the parent record.
                    CodeExpression lockConditions = null;
                    foreach (ColumnSchema columnSchema in relationPair.Value.ChildColumns)
                    {
                        if (columnSchema.IsNullable)
                        {
                            lockConditions = lockConditions == null ? new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression(CommonConversion.ToCamelCase(columnSchema.Name)), CodeBinaryOperatorType.IdentityInequality, new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(System.DBNull)), "Value")) :
                                             new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression(CommonConversion.ToCamelCase(columnSchema.Name)), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)), CodeBinaryOperatorType.BitwiseAnd, lockConditions);
                        }
                    }

                    // The statements to lock the row are added conditionally when the column is nullable.  They are added to the
                    // main part of the method when the constraint is required to match up with a parent record.
                    CodeStatementCollection codeStatementCollection;
                    if (lockConditions == null)
                    {
                        codeStatementCollection = this.Statements;
                    }
                    else
                    {
                        CodeConditionStatement ifParentKeyExists = new CodeConditionStatement(lockConditions);
                        this.Statements.Add(ifParentKeyExists);
                        codeStatementCollection = ifParentKeyExists.TrueStatements;
                    }

                    //			FluidTrade.UnitTest.Server.DataModel.DepartmentRow departmentRowByFK_Department_Employee = FluidTrade.UnitTest.Server.DataModel.Department.FindByDepartmentId(new object[] {
                    //						departmentId});
                    //			if ((departmentRowByFK_Department_Employee == null))
                    //			{
                    //				throw new FluidTrade.Core.RecordNotFoundException("Attempt to access a Department record ({0}) that doesn\'t exist", departmentId);
                    //			}
                    CodeVariableReferenceExpression parentKeyExpression = new CodeRandomVariableReferenceExpression();
                    codeStatementCollection.Add(new CodeVariableDeclarationStatement(new CodeGlobalTypeReference(typeof(System.Object[])), parentKeyExpression.VariableName, new CodeKeyCreateExpression(relationPair.Value.ChildColumns)));
                    if (tableSchema.PrimaryKey == null)
                    {
                        codeStatementCollection.Add(new CodeVariableDeclarationStatement(parentRowType, parentRowVariableExpression.VariableName, new CodeFindByRowExpression(parentTable, parentKeyExpression)));
                    }
                    else
                    {
                        codeStatementCollection.Add(new CodeVariableDeclarationStatement(parentRowType, parentRowVariableExpression.VariableName, new CodeFindByIndexExpression(parentTable, parentKeyExpression)));
                    }
                    codeStatementCollection.Add(new CodeCheckRecordExistsStatement(parentTable, parentRowVariableExpression, parentKeyExpression));

                    //			// This record locked for reading for the duration of the transaction.
                    //			departmentRowByFK_Department_Employee.AcquireReaderLock(middleTierTransaction.AdoResourceManager.Guid, FluidTrade.UnitTest.Server.DataModel.lockTimeout);
                    //			middleTierTransaction.AdoResourceManager.AddLock(departmentRowByFK_Department_Employee);
                    codeStatementCollection.Add(new CodeAcquireRecordReaderLockExpression(transactionExpression, parentRowVariableExpression, parentTable.DataModel));
                    codeStatementCollection.Add(new CodeAddLockToTransactionExpression(transactionExpression, parentRowVariableExpression));

                    //			// This makes sure the record wasn't deleted in the time between when it was found and the time it was locked.
                    //			if ((departmentRowByFK_Department_Employee.RowState == System.Data.DataRowState.Detached))
                    //			{
                    //				throw new FluidTrade.Core.RecordNotFoundException("Attempt to access a Department record ({0}) that doesn\'t exist", departmentId);
                    //			}
                    codeStatementCollection.Add(new CodeCheckRecordDetachedStatement(parentTable, parentRowVariableExpression, parentKeyExpression));
                }
            }

            //            // Create the Employee record.
            //            FluidTrade.UnitTest.Server.DataModel.EmployeeRow employeeRow;
            //            try {
            //                FluidTrade.UnitTest.Server.DataModel.ReaderWriterLock.EnterWriteLock();
            //                employeeRow = ((FluidTrade.UnitTest.Server.DataModel.EmployeeRow)(FluidTrade.UnitTest.Server.DataModel.Employee.NewRow()));
            //            }
            //            finally {
            //                FluidTrade.UnitTest.Server.DataModel.ReaderWriterLock.ExitWriteLock();
            //            }
            CodeVariableReferenceExpression rowVariableExpression = new CodeRandomVariableReferenceExpression();

            this.Statements.Add(new CodeVariableDeclarationStatement(string.Format("{0}Row", tableSchema.Name), rowVariableExpression.VariableName));
            CodeTryCatchFinallyStatement tryCreateRecord = new CodeTryCatchFinallyStatement();

            tryCreateRecord.TryStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(tableSchema.DataModel.Name), "DataLock"), "EnterWriteLock"));
            tryCreateRecord.TryStatements.Add(new CodeAssignStatement(rowVariableExpression,
                                                                      new CodeCastExpression(new CodeTypeReference(string.Format("{0}Row", tableSchema.Name)), new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(tableSchema.DataModel.Name), tableSchema.Name), "NewRow"))));
            tryCreateRecord.FinallyStatements.Add(
                new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(tableSchema.DataModel.Name), "DataLock"), "ExitWriteLock"));
            this.Statements.Add(tryCreateRecord);

            //            // This record is locked for writing for the duration of the transaction.
            //            employeeRow.AcquireWriterLock(middleTierTransaction.AdoResourceManager.Guid, FluidTrade.UnitTest.Server.DataModel.lockTimeout);
            //            middleTierTransaction.AdoResourceManager.AddLock(employeeRow);
            this.Statements.Add(new CodeAcquireRecordWriterLockExpression(transactionExpression, rowVariableExpression, tableSchema));
            this.Statements.Add(new CodeAddLockToTransactionExpression(transactionExpression, rowVariableExpression));

            //            // Create the Employee record in the ADO data model.
            //            middleTierTransaction.AdoResourceManager.AddRecord(employeeRow);
            this.Statements.Add(new CodeAddRecordToTransactionExpression(transactionExpression, rowVariableExpression));

            //            try {
            //                // Lock the owner table and any parent tables while the record is populated.  Note that table locks are always held
            //                // momentarily.
            //                FluidTrade.UnitTest.Server.DataModel.ReaderWriterLock.EnterReadLock();
            //                employeeRow.BeginEdit();
            //                employeeRow[FluidTrade.UnitTest.Server.DataModel.Employee.AgeColumn] = age;
            //                employeeRow[FluidTrade.UnitTest.Server.DataModel.Employee.DepartmentIdColumn] = departmentId;
            //                employeeRow[FluidTrade.UnitTest.Server.DataModel.Employee.EmployeeIdColumn] = employeeId;
            //                employeeRow[FluidTrade.UnitTest.Server.DataModel.Employee.RaceCodeColumn] = raceCode;
            //                employeeRow[FluidTrade.UnitTest.Server.DataModel.Employee.RowVersionColumn] = System.Threading.Interlocked.Increment(ref FluidTrade.UnitTest.Server.DataModel.masterRowVersion);
            //                FluidTrade.UnitTest.Server.DataModel.Employee.Rows.Add(employeeRow);
            //            }
            //            finally {
            //                // The record create is finished and the momentary table locks are no longer needed.
            //                employeeRow.EndEdit();
            //                FluidTrade.UnitTest.Server.DataModel.ReaderWriterLock.ExitWriteLock();
            //            }
            CodeTryCatchFinallyStatement tryFinallyStatement = new CodeTryCatchFinallyStatement();

            tryFinallyStatement.TryStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(tableSchema.DataModel.Name), "DataLock"),
                    "EnterWriteLock"));
            tryFinallyStatement.TryStatements.Add(new CodeMethodInvokeExpression(rowVariableExpression, "BeginEdit"));
            foreach (ColumnSchema columnSchema in tableSchema.Columns.Values)
            {
                if (!columnSchema.IsAutoIncrement)
                {
                    CodeExpression sourceExpression;
                    if (columnSchema.IsRowVersion)
                    {
                        sourceExpression = new CodeMethodInvokeExpression(
                            new CodeFieldReferenceExpression(
                                new CodeTypeReferenceExpression(tableSchema.DataModel.Name),
                                String.Format("{0}DataSet", CommonConversion.ToCamelCase(tableSchema.DataModel.Name))),
                            "IncrementRowVersion");
                    }
                    else
                    {
                        sourceExpression = new CodeArgumentReferenceExpression(CommonConversion.ToCamelCase(columnSchema.Name));
                    }
                    tryFinallyStatement.TryStatements.Add(new CodeAssignStatement(new CodeIndexerExpression(rowVariableExpression, new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(tableSchema.DataModel.Name), tableSchema.Name), string.Format("{0}Column", columnSchema.Name))), sourceExpression));
                }
            }
            tryFinallyStatement.TryStatements.Add(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(tableSchema.DataModel.Name), tableSchema.Name), "Rows"), "Add", rowVariableExpression));
            tryFinallyStatement.FinallyStatements.Add(new CodeMethodInvokeExpression(rowVariableExpression, "EndEdit"));
            tryFinallyStatement.FinallyStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(tableSchema.DataModel.Name), "DataLock"),
                    "ExitWriteLock"));
            this.Statements.Add(tryFinallyStatement);

            //            // Add the Employee record to the SQL data model.
            //            System.Data.SqlClient.SqlCommand sqlCommand = new global::System.Data.SqlClient.SqlCommand("insert \"Employee\" (\"Age\",\"DepartmentId\",\"EmployeeId\",\"RaceCode\",\"RowVersion\",\"Row" +
            //                    "Version\") values (@age,@departmentId,@employeeId,@raceCode,@rowVersion,@rowVersi" +
            //                    "on)", middleTierTransaction.SqlConnection);
            //            sqlCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@age", System.Data.SqlDbType.Int, 0, System.Data.ParameterDirection.Input, false, 0, 0, null, System.Data.DataRowVersion.Current, age));
            //            sqlCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@departmentId", System.Data.SqlDbType.Int, 0, System.Data.ParameterDirection.Input, false, 0, 0, null, System.Data.DataRowVersion.Current, departmentId));
            //            sqlCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@employeeId", System.Data.SqlDbType.Int, 0, System.Data.ParameterDirection.Input, false, 0, 0, null, System.Data.DataRowVersion.Current, employeeId));
            //            sqlCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@raceCode", System.Data.SqlDbType.Int, 0, System.Data.ParameterDirection.Input, false, 0, 0, null, System.Data.DataRowVersion.Current, raceCode));
            //            sqlCommand.Parameters.Add(new global::System.Data.SqlClient.SqlParameter("@rowVersion", System.Data.SqlDbType.BigInt, 0, System.Data.ParameterDirection.Input, false, 0, 0, null, System.Data.DataRowVersion.Current, employeeRow[FluidTrade.UnitTest.Server.DataModel.Employee.RowVersionColumn]));
            //            sqlCommand.ExecuteNonQuery();
            if (tableSchema.IsPersistent)
            {
                CodeVariableReferenceExpression sqlCommandExpression = new CodeRandomVariableReferenceExpression();
                string columnList   = string.Empty;
                string variableList = string.Empty;
                int    columnIndex  = 0;
                foreach (ColumnSchema columnSchema in tableSchema.Columns.Values)
                {
                    if (columnSchema.IsPersistent)
                    {
                        columnList   += string.Format(columnIndex < tableSchema.Columns.Count - 1 ? "\"{0}\"," : "\"{0}\"", columnSchema.Name);
                        variableList += string.Format(columnIndex < tableSchema.Columns.Count - 1 ? "@{0}," : "@{0}", CommonConversion.ToCamelCase(columnSchema.Name));
                        columnIndex++;
                    }
                }
                string insertCommandText = string.Format("insert \"{0}\" ({1}) values ({2})", tableSchema.Name, columnList, variableList);
                this.Statements.Add(new CodeVariableDeclarationStatement(new CodeGlobalTypeReference(typeof(System.Data.SqlClient.SqlCommand)), sqlCommandExpression.VariableName, new CodeObjectCreateExpression(new CodeGlobalTypeReference(typeof(System.Data.SqlClient.SqlCommand)), new CodePrimitiveExpression(insertCommandText), new CodePropertyReferenceExpression(transactionExpression, "SqlConnection"))));
                foreach (ColumnSchema columnSchema in tableSchema.Columns.Values)
                {
                    if (columnSchema.IsPersistent)
                    {
                        string variableName = CommonConversion.ToCamelCase(columnSchema.Name);
                        if (columnSchema.IsAutoIncrement)
                        {
                            CodeExpression codeExpression = new CodeIndexerExpression(rowVariableExpression, new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(tableSchema.DataModel.Name), tableSchema.Name), string.Format("{0}Column", columnSchema.Name)));
                            this.Statements.Add(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(sqlCommandExpression, "Parameters"), "Add", new CodeObjectCreateExpression(new CodeGlobalTypeReference(typeof(System.Data.SqlClient.SqlParameter)), new CodePrimitiveExpression(string.Format("@{0}", variableName)), TypeConverter.Convert(columnSchema.DataType), new CodePrimitiveExpression(0), new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(System.Data.ParameterDirection)), "Input"), new CodePrimitiveExpression(false), new CodePrimitiveExpression(0), new CodePrimitiveExpression(0), new CodePrimitiveExpression(null), new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(System.Data.DataRowVersion)), "Current"), codeExpression)));
                        }
                        else
                        {
                            CodeExpression sourceExpression = columnSchema.IsRowVersion ?
                                                              (CodeExpression) new CodeIndexerExpression(rowVariableExpression, new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(tableSchema.DataModel.Name), tableSchema.Name), "RowVersionColumn")) :
                                                              (CodeExpression) new CodeArgumentReferenceExpression(variableName);
                            this.Statements.Add(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(sqlCommandExpression, "Parameters"), "Add", new CodeObjectCreateExpression(new CodeGlobalTypeReference(typeof(System.Data.SqlClient.SqlParameter)), new CodePrimitiveExpression(string.Format("@{0}", variableName)), TypeConverter.Convert(columnSchema.DataType), new CodePrimitiveExpression(0), new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(System.Data.ParameterDirection)), "Input"), new CodePrimitiveExpression(false), new CodePrimitiveExpression(0), new CodePrimitiveExpression(0), new CodePrimitiveExpression(null), new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(System.Data.DataRowVersion)), "Current"), sourceExpression)));
                        }
                    }
                }
                this.Statements.Add(new CodeMethodInvokeExpression(sqlCommandExpression, "ExecuteNonQuery"));
            }

            //			DataModel.DestinationOrder.OnRowValidate(new DestinationOrderRowChangeEventArgs(pe9564f2717374e96a76d5222e2258784, System.Data.DataRowAction.Add));
            this.Statements.Add(
                new CodeMethodInvokeExpression(
                    new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(tableSchema.DataModel.Name), tableSchema.Name),
                    "OnRowValidate",
                    new CodeObjectCreateExpression(
                        string.Format("{0}RowChangeEventArgs", tableSchema.Name),
                        rowVariableExpression,
                        new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(System.Data.DataRowAction)), "Add"))));


            // Cast the Auto-Increment values back to their native types when returning from this method.
            foreach (KeyValuePair <string, ColumnSchema> columnPair in tableSchema.Columns)
            {
                ColumnSchema columnSchema = columnPair.Value;
                if (columnSchema.IsAutoIncrement)
                {
                    this.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression(CommonConversion.ToCamelCase(columnSchema.Name)),
                                                                new CodeCastExpression(new CodeGlobalTypeReference(columnSchema.DataType), new CodeIndexerExpression(rowVariableExpression, new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(tableSchema.DataModel.Name), tableSchema.Name), string.Format("{0}Column", columnSchema.Name))))));
                }
            }

            //        }
        }
示例#28
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 BlotterConfiguration table containing the key elements.
            //		/// </summary>
            //		/// <param name="key">An array of key elements.</param>
            //		/// <returns>A BlotterConfigurationKey row that contains the key elements, or null if there is no match.</returns>
            //		public new BlotterConfigurationRow 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(Object[])), "key"));

            //			try
            //			{
            //				((TenantDataModel)this.Table.DataSet).dataLock.EnterReadLock();
            //				return ((BlotterConfigurationRow)(base.Find(key)));
            CodeTryCatchFinallyStatement tryCatchFinallyStatement = new CodeTryCatchFinallyStatement();

            tryCatchFinallyStatement.TryStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(
                        new CodeCastExpression(
                            new CodeTypeReference(String.Format("Tenant{0}", uniqueConstraintSchema.Table.DataModelSchema.Name)),
                            new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Table"), "DataSet")),
                        "dataLock"),
                    "EnterReadLock"));
            tryCatchFinallyStatement.TryStatements.Add(
                new CodeMethodReturnStatement(
                    new CodeCastExpression(this.ReturnType, new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), "Find", new CodeArgumentReferenceExpression("key")))));

            //			}
            //			catch (global::System.ArgumentException argumentException)
            //			{
            //				throw new global::System.ServiceModel.FaultException<Teraque.ArgumentFault>(new global::Teraque.ArgumentFault(argumentException.Message));
            //			}
            CodeCatchClause catchArgumentException = new CodeCatchClause("argumentException", new CodeGlobalTypeReference(typeof(ArgumentException)));

            catchArgumentException.Statements.Add(new CodeThrowArgumentExceptionStatement(new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("argumentException"), "Message")));
            tryCatchFinallyStatement.CatchClauses.Add(catchArgumentException);

            //			catch (global::System.FormatException formatException)
            //			{
            //				throw new global::System.ServiceModel.FaultException<Teraque.FormatFault>(new global::Teraque.FormatFault(formatException.Message));
            //			}
            CodeCatchClause catchFormatException = new CodeCatchClause("formatException", new CodeGlobalTypeReference(typeof(FormatException)));

            catchFormatException.Statements.Add(new CodeThrowFormatExceptionStatement(new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("formatException"), "Message")));
            tryCatchFinallyStatement.CatchClauses.Add(catchFormatException);

            //			finally
            //			{
            //				((TenantDataModel)this.Table.DataSet).dataLock.ExitReadLock();
            //			}
            tryCatchFinallyStatement.FinallyStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(
                        new CodeCastExpression(
                            new CodeTypeReference(String.Format("Tenant{0}", uniqueConstraintSchema.Table.DataModelSchema.Name)),
                            new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Table"), "DataSet")),
                        "dataLock"),
                    "ExitReadLock"));
            this.Statements.Add(tryCatchFinallyStatement);

            //		}
            //	}
        }
        /// <summary>
        /// Converts an <see cref="OpenXmlPackage"/> into a CodeDom object that can be used
        /// to build code in a given .NET language to build the referenced <paramref name="pkg"/>.
        /// </summary>
        /// <param name="pkg">
        /// The <see cref="OpenXmlPackage"/> object to generate source code for.
        /// </param>
        /// <param name="settings">
        /// The <see cref="ISerializeSettings"/> to use during the code generation
        /// process.
        /// </param>
        /// <returns>
        /// A new <see cref="CodeCompileUnit"/> containing the instructions to build
        /// the referenced <see cref="OpenXmlPackage"/>.
        /// </returns>
        public static CodeCompileUnit GenerateSourceCode(this OpenXmlPackage pkg, ISerializeSettings settings)
        {
            const string pkgVarName = "pkg";
            const string paramName = "pathToFile";
            var result = new CodeCompileUnit();
            var pkgType = pkg.GetType();
            var pkgTypeName = pkgType.Name;
            var partTypeCounts = new Dictionary<string, int>();
            var namespaces = new SortedSet<string>();
            var mainNamespace = new CodeNamespace(settings.NamespaceName);
            var bluePrints = new OpenXmlPartBluePrintCollection();
            CodeConditionStatement conditionStatement;
            CodeMemberMethod entryPoint;
            CodeMemberMethod createParts;
            CodeTypeDeclaration mainClass;
            CodeTryCatchFinallyStatement tryAndCatch;
            CodeFieldReferenceExpression docTypeVarRef = null;
            Type docTypeEnum;
            string docTypeEnumVal;
            KeyValuePair<string, Type> rootVarType;

            // Add all initial namespace names first
            namespaces.Add("System");

            // The OpenXmlDocument derived parts all contain a property called "DocumentType"
            // but the property types differ depending on the derived part.  Need to get both
            // the enum name of selected value to use as a parameter for the Create statement.
            switch (pkg)
            {
                case PresentationDocument p:
                    docTypeEnum = p.DocumentType.GetType();
                    docTypeEnumVal = p.DocumentType.ToString();
                    break;
                case SpreadsheetDocument s:
                    docTypeEnum = s.DocumentType.GetType();
                    docTypeEnumVal = s.DocumentType.ToString();
                    break;
                case WordprocessingDocument w:
                    docTypeEnum = w.DocumentType.GetType();
                    docTypeEnumVal = w.DocumentType.ToString();
                    break;
                default:
                    throw new ArgumentException("object is not a recognized OpenXmlPackage type.", nameof(pkg));
            }

            // Create the entry method
            entryPoint = new CodeMemberMethod()
            {
                Name = "CreatePackage",
                ReturnType = new CodeTypeReference(),
                Attributes = MemberAttributes.Public | MemberAttributes.Final
            };
            entryPoint.Parameters.Add(
                new CodeParameterDeclarationExpression(typeof(string).Name, paramName));

            // Create package declaration expression first
            entryPoint.Statements.Add(new CodeVariableDeclarationStatement(pkgTypeName, pkgVarName,
                new CodePrimitiveExpression(null)));

            // Add the required DocumentType parameter here, if available
            if (docTypeEnum != null)
            {
                namespaces.Add(docTypeEnum.Namespace);

                var simpleFieldRef = new CodeVariableReferenceExpression(
                    docTypeEnum.GetObjectTypeName(settings.NamespaceAliasOptions.Order));
                docTypeVarRef = new CodeFieldReferenceExpression(simpleFieldRef, docTypeEnumVal);
            }

            // initialize package var
            var pkgCreateMethod = new CodeMethodReferenceExpression(
                new CodeTypeReferenceExpression(pkgTypeName),
                "Create");
            var pkgCreateInvoke = new CodeMethodInvokeExpression(pkgCreateMethod,
                new CodeArgumentReferenceExpression(paramName),
                docTypeVarRef);
            var initializePkg = new CodeAssignStatement(
                new CodeVariableReferenceExpression(pkgVarName),
                pkgCreateInvoke);

            // Call CreateParts method
            var partsCreateMethod = new CodeMethodReferenceExpression(
                new CodeThisReferenceExpression(),
                "CreateParts");
            var partsCreateInvoke = new CodeMethodInvokeExpression(
                partsCreateMethod,
                new CodeDirectionExpression(FieldDirection.Ref,
                    new CodeVariableReferenceExpression(pkgVarName)));

            // Clean up pkg var
            var pkgDisposeMethod = new CodeMethodReferenceExpression(
                new CodeVariableReferenceExpression(pkgVarName),
                "Dispose");
            var pkgDisposeInvoke = new CodeMethodInvokeExpression(
                pkgDisposeMethod);

            // Setup the try/catch statement to properly initialize the pkg var
            tryAndCatch = new CodeTryCatchFinallyStatement();

            // Try statements
            tryAndCatch.TryStatements.Add(initializePkg);
            tryAndCatch.TryStatements.AddBlankLine();
            tryAndCatch.TryStatements.Add(partsCreateInvoke);

            // If statement to ensure pkgVarName is not null before trying to dispose
            conditionStatement = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression(pkgVarName),
                    CodeBinaryOperatorType.IdentityInequality,
                    new CodePrimitiveExpression(null)));

            conditionStatement.TrueStatements.Add(pkgDisposeInvoke);

            // Finally statements
            tryAndCatch.FinallyStatements.Add(conditionStatement);
            entryPoint.Statements.Add(tryAndCatch);

            // Create the CreateParts method
            createParts = new CodeMemberMethod()
            {
                Name = "CreateParts",
                ReturnType = new CodeTypeReference(),
                Attributes = MemberAttributes.Private | MemberAttributes.Final
            };
            createParts.Parameters.Add(new CodeParameterDeclarationExpression(pkgTypeName, pkgVarName)
                { Direction = FieldDirection.Ref });

            // Add all of the child part references here
            if (pkg.Parts != null)
            {
                var customNewPartTypes = new Type[] { typeof(PresentationPart), typeof(WorkbookPart), typeof(MainDocumentPart) };
                OpenXmlPartBluePrint bpTemp;
                CodeMethodReferenceExpression referenceExpression;
                CodeMethodInvokeExpression invokeExpression;
                CodeMethodReferenceExpression methodReference;
                Type currentPartType;
                string varName = null;
                string initMethodName = null;
                string mainPartTypeName;

                foreach (var pair in pkg.Parts)
                {
                    // Need special handling rules for WorkbookPart, MainDocumentPart, and PresentationPart
                    // objects.  They cannot be created using the usual "AddNewPart" methods, unfortunately.
                    currentPartType = pair.OpenXmlPart.GetType();
                    if (customNewPartTypes.Contains(currentPartType))
                    {
                        namespaces.Add(currentPartType.Namespace);
                        mainPartTypeName = currentPartType.Name;
                        if (pair.OpenXmlPart is PresentationPart)
                        {
                            varName = "presentationPart";
                            initMethodName = "AddPresentationPart";
                        }
                        else if (pair.OpenXmlPart is WorkbookPart)
                        {
                            varName = "workbookPart";
                            initMethodName = "AddWorkbookPart";
                        }
                        else if (pair.OpenXmlPart is MainDocumentPart)
                        {
                            varName = "mainDocumentPart";
                            initMethodName = "AddMainDocumentPart";
                        }
                        rootVarType = new KeyValuePair<string, Type>(varName, currentPartType);

                        // Setup the blueprint
                        bpTemp = new OpenXmlPartBluePrint(pair.OpenXmlPart, varName);

                        // Setup the add new part statement for the current OpenXmlPart object
                        referenceExpression = new CodeMethodReferenceExpression(
                            new CodeArgumentReferenceExpression(pkgVarName), initMethodName);

                        invokeExpression = new CodeMethodInvokeExpression(referenceExpression);

                        createParts.Statements.Add(new CodeVariableDeclarationStatement(mainPartTypeName, varName, invokeExpression));

                        // Add the call to the method to populate the current OpenXmlPart object
                        methodReference = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), bpTemp.MethodName);
                        createParts.Statements.Add(new CodeMethodInvokeExpression(methodReference,
                            new CodeDirectionExpression(FieldDirection.Ref, new CodeVariableReferenceExpression(varName))));

                        // Add the current main part to the collection of blueprints to ensure that the appropriate 'Generate*'
                        // method is added to the collection of helper methods.
                        bluePrints.Add(bpTemp);

                        // Add a blank line for clarity
                        createParts.Statements.AddBlankLine();

                        // now create the child parts for the current one an continue the loop to avoid creating
                        // an additional invalid 'AddNewPart' method for the current main part.
                        foreach (var child in pair.OpenXmlPart.Parts)
                        {
                            createParts.Statements.AddRange(
                                OpenXmlPartExtensions.BuildEntryMethodCodeStatements(
                                    child, settings, partTypeCounts, namespaces, bluePrints, rootVarType));
                        }
                        continue;
                    }

                    rootVarType = new KeyValuePair<string, Type>(pkgVarName, pkgType);
                    createParts.Statements.AddRange(
                        OpenXmlPartExtensions.BuildEntryMethodCodeStatements(
                            pair, settings, partTypeCounts, namespaces, bluePrints, rootVarType));
                }
            }

            // Setup the main class next
            mainClass = new CodeTypeDeclaration($"{pkgTypeName}BuilderClass")
            {
                IsClass = true,
                Attributes = MemberAttributes.Public
            };

            // Setup the main class members
            mainClass.Members.Add(entryPoint);
            mainClass.Members.Add(createParts);
            mainClass.Members.AddRange(OpenXmlPartExtensions.BuildHelperMethods
                (bluePrints, settings, namespaces));

            // Setup the imports
            var codeNameSpaces = new List<CodeNamespaceImport>(namespaces.Count);
            foreach (var ns in namespaces)
            {
                codeNameSpaces.Add(ns.GetCodeNamespaceImport(settings.NamespaceAliasOptions));
            }
            codeNameSpaces.Sort(new CodeNamespaceImportComparer());

            mainNamespace.Imports.AddRange(codeNameSpaces.ToArray());
            mainNamespace.Types.Add(mainClass);

            // Finish up
            result.Namespaces.Add(mainNamespace);
            return result;
        }
示例#30
0
        /// <summary>
        /// Creates a method to handle moving the deleted records from the active data model to the deleted data model.
        /// </summary>
        /// <param name="schema">The data model schema.</param>
        public IsReconcilingProperty(DataModelSchema dataModelSchema)
        {
            //        /// <summary>
            //        /// Gets or sets an indication of whether the background thread that reconciles the client data model is running or not.
            //        /// </summary>
            //        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
            //        [global::System.ComponentModel.BrowsableAttribute(false)]
            //        [global::System.ComponentModel.DesignerSerializationVisibility(global::System.ComponentModel.DesignerSerializationVisibility.Content)]
            //        public static bool IsReading {
            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement("Gets or sets an indication of whether the background thread that reconciles the client data model is running or not.", true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            this.CustomAttributes.AddRange(new CodeCustomAttributesForMethods());
            this.Name       = "IsReading";
            this.Type       = new CodeGlobalTypeReference(typeof(Boolean));
            this.Attributes = MemberAttributes.Public | MemberAttributes.Static;

            //            get {
            //                try {
            //                    // Prevent other threads from modifying the flag while it is returned to the caller.
            //                    global::System.Threading.Monitor.Enter(DataModel.syncRoot);
            //                    return DataModel.isReading;
            //                }
            //                finally {
            //                    global::System.Threading.Monitor.Exit(DataModel.syncRoot);
            //                }
            //            }
            CodeTryCatchFinallyStatement getTry = new CodeTryCatchFinallyStatement();

            getTry.TryStatements.Add(new CodeCommentStatement("Prevent other threads from modifying the flag while it is returned to the caller."));
            getTry.TryStatements.Add(new CodeMethodInvokeExpression(new CodeGlobalTypeReferenceExpression(typeof(Monitor)), "Enter", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "syncRoot")));
            getTry.TryStatements.Add(new CodeMethodReturnStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "isReading")));
            getTry.FinallyStatements.Add(new CodeMethodInvokeExpression(new CodeGlobalTypeReferenceExpression(typeof(Monitor)), "Exit", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "syncRoot")));
            this.GetStatements.Add(getTry);

            //            set {
            //                try {
            //                    // Prevent other threads from modifying the flag while it is set.
            //                    global::System.Threading.Monitor.Enter(DataModel.syncRoot);
            CodeTryCatchFinallyStatement setTry = new CodeTryCatchFinallyStatement();

            setTry.TryStatements.Add(new CodeCommentStatement("Prevent other threads from modifying the flag while it is set."));
            setTry.TryStatements.Add(new CodeMethodInvokeExpression(new CodeGlobalTypeReferenceExpression(typeof(Monitor)), "Enter", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "syncRoot")));

            //                    // If the state of the reconciling thread has changed, then either start or stop the background thread
            //                    // depending on the new value.
            //                    if ((DataModel.isReading != value)) {
            setTry.TryStatements.Add(new CodeCommentStatement("If the state of the reconciling thread has changed, then either start or stop the background thread"));
            setTry.TryStatements.Add(new CodeCommentStatement("depending on the new value."));
            CodeConditionStatement isReconcilingChanged = new CodeConditionStatement();

            isReconcilingChanged.Condition = new CodeBinaryOperatorExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "isReading"), CodeBinaryOperatorType.IdentityInequality, new CodeArgumentReferenceExpression("value"));

            //                        // The background thread that keeps the data model synchronized with the server data model is either
            //                        // started or stopped based on the new value.
            //                        if ((DataModel.isReading = value)) {
            isReconcilingChanged.TrueStatements.Add(new CodeCommentStatement("The background thread that keeps the data model synchronized with the server data model is either"));
            isReconcilingChanged.TrueStatements.Add(new CodeCommentStatement("started or stopped based on the new value."));
            CodeConditionStatement isReconciling = new CodeConditionStatement(
                new CodeBinaryOperatorExpression(
                    new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "isReading"),
                    CodeBinaryOperatorType.Assign,
                    new CodeArgumentReferenceExpression("value")));

            //							// This will pre-load the data model to save time starting up.
            isReconciling.TrueStatements.Add(new CodeCommentStatement("This will pre-load the data model to save time starting up."));

            //                            // This thread will periodically ask the server for records missing from the client version of the
            //                            // data model.
            //                            DataModel.reconcilerThread = new global::System.Threading.Thread(DataModel.ReadDataModel);
            //                            DataModel.reconcilerThread.Name = "Data Model Reader Thread";
            //                            DataModel.reconcilerThread.Start();
            //                        }
            isReconciling.TrueStatements.Add(new CodeCommentStatement("This thread will periodically ask the server for records missing from the client version of the"));
            isReconciling.TrueStatements.Add(new CodeCommentStatement("data model."));
            isReconciling.TrueStatements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "reconcilerThread"), new CodeObjectCreateExpression(new CodeGlobalTypeReference(typeof(Thread)), new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "ReadDataModel"))));
            isReconciling.TrueStatements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "reconcilerThread"), "Name"), new CodePrimitiveExpression("Data Model Reader Thread")));
            isReconciling.TrueStatements.Add(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "reconcilerThread"), "Start"));

            //                        else {
            //                            // This will kill the reconciling thread.  Special consideration is given if the caller is the
            //                            // reconciling thread to make sure that the locking of the monitor is balanced out.
            //                            if ((global::System.Threading.Thread.CurrentThread == DataModel.reconcilerThread)) {
            //                                // If this property accessed by the reconciling thread, then there is no need to join the thread to
            //                                // abort it.
            //                                global::System.Threading.Thread.CurrentThread.Abort();
            //                            }
            isReconciling.FalseStatements.Add(new CodeCommentStatement("This will kill the reconciling thread.  Special consideration is given if the caller is the"));
            isReconciling.FalseStatements.Add(new CodeCommentStatement("reconciling thread to make sure that the locking of the monitor is balanced out."));
            CodeConditionStatement isCurrentThread = new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(Thread)), "CurrentThread"), CodeBinaryOperatorType.IdentityEquality,
                                                                                                                 new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "reconcilerThread")));

            isCurrentThread.TrueStatements.Add(new CodeCommentStatement("If this property accessed by the reconciling thread, then there is no need to join the thread to"));
            isCurrentThread.TrueStatements.Add(new CodeCommentStatement("abort it."));
            isCurrentThread.TrueStatements.Add(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(Thread)), "CurrentThread"), "Abort"));

            //                            else {
            //                                // When joining the thread to shut it down gracefully, the critical code lock must be released in
            //                                // order to allow the Reconciling thread to run.  That same lock must be re acquired in order to
            //                                // leave the books balanced when the property access method exits.
            //                                global::System.Threading.Monitor.Exit(DataModel.syncRoot);
            //                                if ((DataModel.reconcilerThread.Join(DataModel.threadWaitTime) == false)) {
            //                                    DataModel.reconcilerThread.Abort();
            //                                }
            //                                global::System.Threading.Monitor.Enter(DataModel.syncRoot);
            //                            }
            isCurrentThread.FalseStatements.Add(new CodeCommentStatement("When joining the thread to shut it down gracefully, the critical code lock must be released in"));
            isCurrentThread.FalseStatements.Add(new CodeCommentStatement("order to allow the Reconciling thread to run.  That same lock must be re acquired in order to"));
            isCurrentThread.FalseStatements.Add(new CodeCommentStatement("leave the books balanced when the property access method exits."));
            isCurrentThread.FalseStatements.Add(new CodeMethodInvokeExpression(new CodeGlobalTypeReferenceExpression(typeof(Monitor)), "Exit", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "syncRoot")));
            CodeConditionStatement ifReaderRunning = new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "reconcilerThread"), "Join", new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "threadWaitTime")), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(false)));

            ifReaderRunning.TrueStatements.Add(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "reconcilerThread"), "Abort"));
            isCurrentThread.FalseStatements.Add(ifReaderRunning);
            isCurrentThread.FalseStatements.Add(new CodeMethodInvokeExpression(new CodeGlobalTypeReferenceExpression(typeof(Monitor)), "Enter", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "syncRoot")));

            //                        }
            isReconciling.FalseStatements.Add(isCurrentThread);

            //                    }
            isReconcilingChanged.TrueStatements.Add(isReconciling);

            //                }
            setTry.TryStatements.Add(isReconcilingChanged);

            //                finally {
            //                    global::System.Threading.Monitor.Exit(DataModel.syncRoot);
            //                }
            //            }
            setTry.FinallyStatements.Add(new CodeMethodInvokeExpression(new CodeGlobalTypeReferenceExpression(typeof(Monitor)), "Exit", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "syncRoot")));
            this.SetStatements.Add(setTry);

            //        }
        }
示例#31
0
        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.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "sz"));
                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));

                CodeTryCatchFinallyStatement trycatch = new CodeTryCatchFinallyStatement();
                nullcheck.FalseStatements.Add(trycatch);
                trycatch.TryStatements.Add(
                    new CodeMethodReturnStatement(
                        new CodeMethodInvokeExpression(
                            new CodePropertyReferenceExpression(
                                new CodeTypeReferenceExpression(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,
                            szExp
                            )
                        )
                    );

                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(cns.Name + ".IconLoader"),
                       "LoadIcon",
                       rootObject,
                       new CodePrimitiveExpression(name),
                       new CodeFieldReferenceExpression(
                           new CodeTypeReferenceExpression(typeof(Gtk.IconSize)),
                           size.ToString()
                           ),
                       new CodePrimitiveExpression(sz)
                       ));
        }
示例#32
0
        /// <summary>
        /// Creates a method to write the data model to isolated storage.
        /// </summary>
        /// <param name="schema">The data model schema.</param>
        public WriteMethod(DataModelSchema dataModelSchema)
        {
            //		/// <summary>
            //		/// Writes the DataModel to the local cache.
            //		/// </summary>
            //		public static void Write()
            //		{
            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement(string.Format("Writes the {0} to the local cache.", dataModelSchema.Name), true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            this.CustomAttributes.AddRange(new CodeCustomAttributesForMethods());
            this.Name       = "Write";
            this.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            this.Parameters.Add(new CodeParameterDeclarationExpression(new CodeGlobalTypeReference(typeof(String)), "path"));

            //			try
            //          {
            CodeTryCatchFinallyStatement tryLock = new CodeTryCatchFinallyStatement();

            //              Monitor.Enter(DataModel.syncRoot);
            tryLock.TryStatements.Add(new CodeMethodInvokeExpression(new CodeGlobalTypeReferenceExpression(typeof(System.Threading.Monitor)), "Enter", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "syncRoot")));

            //				global::System.IO.IsolatedStorage.IsolatedStorageFileStream isolatedStorageFileStream = new global::System.IO.IsolatedStorage.IsolatedStorageFileStream(path, global::System.IO.FileMode.Create);
            tryLock.TryStatements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(IsolatedStorageFileStream)),
                    "isolatedStorageFileStream",
                    new CodeObjectCreateExpression(
                        new CodeGlobalTypeReference(typeof(IsolatedStorageFileStream)),
                        new CodeArgumentReferenceExpression("path"),
                        new CodeFieldReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(FileMode)), "Create"))));

            //				global::System.Security.Cryptography.Rijndael rijnadael = global::System.Security.Cryptography.Rijndael.Create();
            tryLock.TryStatements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Rijndael)),
                    "rijnadael",
                    new CodeMethodInvokeExpression(new CodeGlobalTypeReferenceExpression(typeof(Rijndael)), "Create")));

            //				global::System.Byte[] iV = new global::System.Byte[] { 30, 35, 156, 47, 45, 115, 62, 120, 15, 107, 194, 83, 209, 127, 82, 95 };
            tryLock.TryStatements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Byte[])),
                    "iV",
                    new CodeArrayCreateExpression(
                        new CodeGlobalTypeReference(typeof(Byte[])),
                        new CodePrimitiveExpression(30),
                        new CodePrimitiveExpression(35),
                        new CodePrimitiveExpression(156),
                        new CodePrimitiveExpression(47),
                        new CodePrimitiveExpression(45),
                        new CodePrimitiveExpression(115),
                        new CodePrimitiveExpression(62),
                        new CodePrimitiveExpression(120),
                        new CodePrimitiveExpression(15),
                        new CodePrimitiveExpression(107),
                        new CodePrimitiveExpression(194),
                        new CodePrimitiveExpression(83),
                        new CodePrimitiveExpression(209),
                        new CodePrimitiveExpression(127),
                        new CodePrimitiveExpression(82),
                        new CodePrimitiveExpression(95))));

            //				global::System.Byte[] key = new global::System.Byte[] { 89, 91, 187, 183, 109, 169, 67, 155, 150, 145, 142, 46, 110, 148, 91, 156, 48, 8, 158, 199, 2, 107, 227, 160, 125, 235, 174, 109, 149, 180, 31, 140 };
            tryLock.TryStatements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(Byte[])),
                    "key",
                    new CodeArrayCreateExpression(
                        new CodeGlobalTypeReference(typeof(Byte[])),
                        new CodePrimitiveExpression(89),
                        new CodePrimitiveExpression(91),
                        new CodePrimitiveExpression(187),
                        new CodePrimitiveExpression(183),
                        new CodePrimitiveExpression(109),
                        new CodePrimitiveExpression(169),
                        new CodePrimitiveExpression(67),
                        new CodePrimitiveExpression(155),
                        new CodePrimitiveExpression(150),
                        new CodePrimitiveExpression(145),
                        new CodePrimitiveExpression(142),
                        new CodePrimitiveExpression(46),
                        new CodePrimitiveExpression(110),
                        new CodePrimitiveExpression(148),
                        new CodePrimitiveExpression(91),
                        new CodePrimitiveExpression(156),
                        new CodePrimitiveExpression(48),
                        new CodePrimitiveExpression(8),
                        new CodePrimitiveExpression(158),
                        new CodePrimitiveExpression(199),
                        new CodePrimitiveExpression(2),
                        new CodePrimitiveExpression(107),
                        new CodePrimitiveExpression(227),
                        new CodePrimitiveExpression(160),
                        new CodePrimitiveExpression(125),
                        new CodePrimitiveExpression(235),
                        new CodePrimitiveExpression(174),
                        new CodePrimitiveExpression(109),
                        new CodePrimitiveExpression(149),
                        new CodePrimitiveExpression(180),
                        new CodePrimitiveExpression(31),
                        new CodePrimitiveExpression(140))));

            //				global::System.Security.Cryptography.CryptoStream cryptoStream = new global::System.Security.Cryptography.CryptoStream(isolatedStorageFileStream, rijnadael.CreateDecryptor(key, iV), global::System.Security.Cryptography.CryptoStreamMode.Write);
            tryLock.TryStatements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(CryptoStream)),
                    "cryptoStream",
                    new CodeObjectCreateExpression(
                        new CodeGlobalTypeReference(typeof(CryptoStream)),
                        new CodeVariableReferenceExpression("isolatedStorageFileStream"),
                        new CodeMethodInvokeExpression(
                            new CodeVariableReferenceExpression("rijnadael"),
                            "CreateEncryptor",
                            new CodeVariableReferenceExpression("key"),
                            new CodeVariableReferenceExpression("iV")),
                        new CodeFieldReferenceExpression(new CodeGlobalTypeReferenceExpression(typeof(CryptoStreamMode)), "Write"))));

            //				global::System.IO.BinaryWriter binaryWriter = new System.IO.BinaryWriter(cryptoStream);
            tryLock.TryStatements.Add(
                new CodeVariableDeclarationStatement(
                    new CodeGlobalTypeReference(typeof(BinaryWriter)),
                    "binaryWriter",
                    new CodeObjectCreateExpression(
                        new CodeGlobalTypeReference(typeof(BinaryWriter)),
                        new CodeVariableReferenceExpression("cryptoStream"))));

            //				binaryWriter.Write(DataModel.sequence);
            tryLock.TryStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeVariableReferenceExpression("binaryWriter"),
                    "Write",
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "sequence")));

            //				binaryWriter.Write(DataModel.dataSetId.ToByteArray());
            tryLock.TryStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeVariableReferenceExpression("binaryWriter"),
                    "Write",
                    new CodeMethodInvokeExpression(
                        new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "dataSetId"), "ToByteArray")));

            //				DataModel.dataSet.WriteXml(cryptoStream);
            tryLock.TryStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "dataSet"),
                    "WriteXml",
                    new CodeVariableReferenceExpression("cryptoStream")));

            //				binaryWriter.Close();
            tryLock.TryStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("binaryWriter"), "Close"));

            //				cryptoStream.Close();
            tryLock.TryStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("cryptoStream"), "Close"));

            //				isolatedStorageFileStream.Close();
            tryLock.TryStatements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("isolatedStorageFileStream"), "Close"));

            //          }

            //			catch (System.Exception )
            //			{
            //			}
            tryLock.CatchClauses.Add(new CodeCatchClause());

            //          finally
            //          {
            //              Monitor.Exit(DataModel.syncRoot);
            tryLock.FinallyStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeGlobalTypeReferenceExpression(typeof(System.Threading.Monitor)),
                    "Exit",
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataModelSchema.Name), "syncRoot")));

            //          }
            this.Statements.Add(tryLock);

            //		}
        }
示例#33
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 FindByMethod(UniqueConstraintSchema uniqueConstraintSchema)
        {
            //        /// <summary>
            //        /// Finds a row in the Configuration table containing the key elements.
            //        /// </summary>
            //        /// <param name="configurationId">The ConfigurationId element of the key.</param>
            //        /// <param name="relationName">The RelationName element of the key.</param>
            //        /// <returns>The Configuration row that contains the key elements, or null if there is no match.</returns>
            //        public ConfigurationRow Find(string configurationId, string relationName) {
            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));
            foreach (ColumnSchema columnSchema in uniqueConstraintSchema.Columns)
            {
                this.Comments.Add(new CodeCommentStatement(string.Format("<param name=\"{0}\">The {1} element of the key.</param>", CommonConversion.ToCamelCase(columnSchema.Name), columnSchema.Name), true));
            }
            this.Comments.Add(new CodeCommentStatement(string.Format("<returns>The {0} row that contains the key elements, or null if there is no match.</returns>", uniqueConstraintSchema.Table.Name), true));
            this.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            this.ReturnType = new CodeTypeReference(string.Format("{0}Row", uniqueConstraintSchema.Table.Name));
            this.Name       = "Find";
            foreach (ColumnSchema columnSchema in uniqueConstraintSchema.Columns)
            {
                this.Parameters.Add(new CodeParameterDeclarationExpression(columnSchema.DataType, CommonConversion.ToCamelCase(columnSchema.Name)));
            }

            //            try {
            //                DataModel.Configuration.AcquireLock();
            //                return ((ConfigurationRow)(base.Find(new object[] {
            //                            configurationId,
            //                            relationName})));
            //            }
            //            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 CodeKeyCreateExpression(uniqueConstraintSchema.Columns)))));
            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);

            //        }
        }
        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;
                      }
                  }");
        }
示例#35
0
        private CodeMemberMethod BuildGetFunction(ServerInfo serverInfo, List <ColumnInfo> cols, bool isDefault, bool isOverloaded, DBReturnTypes returnType)
        {
            var             rt     = new CodeMemberMethod();
            IDBCodeProvider dbCode = DBCodeProviderFactory.GetDBCodeProvider(serverInfo);

            rt.Name       = "Get";
            rt.Attributes = MemberAttributes.Public;
            if (isOverloaded)
            {
                rt.Attributes = rt.Attributes | MemberAttributes.Overloaded;
            }

            // If this is not the default call meaning all data then pass keys in
            if (isOverloaded & !isDefault)
            {
                foreach (var col in cols.Where(c => c.IsKey))
                {
                    rt.Parameters.Add(new CodeParameterDeclarationExpression(col.DataType, col.ColumnName));
                }
            }

            rt.ReturnType = new CodeTypeReference(returnType.ToString());

            //Blank Line
            rt.Statements.Add(new CodeSnippetStatement());

            //Diminsion the return variable
            rt.Statements.Add(new CodeVariableDeclarationStatement(returnType.ToString(), "rt", new CodeObjectCreateExpression(returnType.ToString(), new CodeExpression[] {})));

            //Create Connection and command object
            rt.Statements.Add(new CodeVariableDeclarationStatement(typeof(IDbConnection),
                                                                   "con", new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "GetConnection", new CodeExpression[] {})));


            rt.Statements.Add(new CodeVariableDeclarationStatement(typeof(IDbCommand), "cmd",
                                                                   new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeVariableReferenceExpression("con"), "CreateCommand"))));
            string whereClause = null;

            if (cols.Any(c => c.IsKey))
            {
                whereClause = BuildWhereClause(cols.Where(c => c.IsKey).ToList());
            }

            //Blank Line
            rt.Statements.Add(new CodeSnippetStatement());
            rt.Statements.Add(new CodeVariableDeclarationStatement(typeof(IDbDataAdapter), "da",
                                                                   new CodeObjectCreateExpression(typeof(IDbDataAdapter),
                                                                                                  new CodeExpression[] { new CodeVariableReferenceExpression("cmd") })));
            //Blank Line
            rt.Statements.Add(new CodeSnippetStatement());
            var tryBlock = new CodeTryCatchFinallyStatement();

            tryBlock.TryStatements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("da"), "SelectCommand"),
                                                               new CodeVariableReferenceExpression("cmd")));

            if (cols.Any(c => c.IsKey))
            {
                var exp = new CodeExpression();
                //Set the command text
                tryBlock.TryStatements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("cmd"), "CommandText"),
                                                                   new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("_selectSQL"), CodeBinaryOperatorType.Add, new CodeSnippetExpression(whereClause))));

                //add parameters for keys
                foreach (var key in cols.Where(c => c.IsKey))
                {
                    tryBlock.TryStatements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("cmd"), "Parameters"),
                                                                                                                                          "Add", new CodeExpression[] { new CodeSnippetExpression(String.Format(@"""@{0}""", key.ColumnName)),
                                                                                                                                                                        new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(new CodeTypeReference(key.DbDataType.GetType())), key.DbDataType),
                                                                                                                                                                        new CodePrimitiveExpression(key.Size) }), "Value"), new CodeVariableReferenceExpression()));
                }
                rt.Statements.Add(new CodeSnippetStatement());
            }
            else
            {
                // Set the command text
                tryBlock.TryStatements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("cmd"), "CommandText"),
                                                                   new CodeVariableReferenceExpression("_selectSQL")));
            }

            tryBlock.TryStatements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeVariableReferenceExpression("con"), "Open"), new CodeExpression[] {}));
            tryBlock.TryStatements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeVariableReferenceExpression("da"), "Fill"),
                                                                      new CodeExpression[] { new CodeVariableReferenceExpression("rt") }));
            tryBlock.TryStatements.Add(new CodeSnippetStatement());

            var catchBlock = new CodeCatchClause("exSQL", new CodeTypeReference(dbCode.GetExceptionType()));

            catchBlock.Statements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "ThrowException"),
                                                                     new CodeExpression[] { new CodePrimitiveExpression("An SQL error has occurred retrieving data."),
                                                                                            new CodeVariableReferenceExpression("exSQL") }));
            catchBlock.Statements.Add(new CodeSnippetStatement());
            tryBlock.CatchClauses.Add(catchBlock);

            catchBlock = new CodeCatchClause("ex", new CodeTypeReference(typeof(Exception)));
            catchBlock.Statements.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "ThrowException"),
                                                                     new CodeExpression[] { new CodePrimitiveExpression("An error has occurred retrieving data."),
                                                                                            new CodeVariableReferenceExpression("ex") }));
            catchBlock.Statements.Add(new CodeSnippetStatement());
            tryBlock.CatchClauses.Add(catchBlock);

            var cond = new CodeConditionStatement();

            cond.Condition = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("da"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null));
            cond.TrueStatements.Add(GetDataAdapterDisposeStatement());
            tryBlock.FinallyStatements.Add(cond);

            tryBlock.FinallyStatements.Add(GetConnectionCloseStatement());
            tryBlock.FinallyStatements.Add(GetConnectionDisposeStatement());
            tryBlock.FinallyStatements.Add(GetCommandDisposeStatement());
            tryBlock.FinallyStatements.Add(new CodeSnippetStatement());

            rt.Statements.Add(tryBlock);
            rt.Statements.Add(new CodeSnippetStatement());

            rt.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("rt")));
            rt.Statements.Add(new CodeSnippetStatement());


            return(rt);
        }
示例#36
0
 public void Visit(CodeTryCatchFinallyStatement o)
 {
     g.GenerateTryCatchFinallyStatement(o);
 }
示例#37
0
        /// <summary>
        /// Generates a method to get a list of child rows.
        /// </summary>
        /// <param name="keyrefSchema">The foreign key that references the child table.</param>
        public ChildRowsMethod(KeyrefSchema keyrefSchema)
        {
            // These variables are used to construct the method.
            TableSchema childTable       = keyrefSchema.Selector;
            TableSchema parentTable      = keyrefSchema.Refer.Selector;
            string      rowTypeName      = string.Format("{0}Row", childTable.Name);
            string      tableFieldName   = string.Format("table{0}", parentTable.Name);
            string      relationName     = string.Format("{0}{1}Relation", parentTable.Name, childTable.Name);
            string      childRowTypeName = string.Format("{0}Row", keyrefSchema.Selector.Name);

            // To reduce the frequency of deadlocking, the tables are always locked in alphabetical order.  This section collects
            // all the table locks that are used for this operation and organizes them in a list that is used to generate the
            // locking and releasing statements below.
            List <LockRequest> tableLockList = new List <LockRequest>();

            tableLockList.Add(new ReadRequest(childTable));
            tableLockList.Add(new ReadRequest(parentTable));
            tableLockList.Sort();

            // If the foreign keys share the same primary key, then the names of the methods will need to be decorated with the
            // key name in order to make them unique.  This will test the foreign keys for duplicate primary key names.
            bool isDuplicateKey = false;

            foreach (KeyrefSchema otherforeignKey in childTable.ChildKeyrefs)
            {
                if (otherforeignKey != keyrefSchema && otherforeignKey.Selector == keyrefSchema.Selector)
                {
                    isDuplicateKey = true;
                }
            }

            //			/// <summary>
            //			/// Gets the children rows in the Engineer table.
            //			/// </summary>
            //			public EngineerRow[] GetEngineerRows()
            //			{
            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement(string.Format("Gets the children rows in the {0} table.", keyrefSchema.Selector.Name), true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            this.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            this.ReturnType = new CodeTypeReference(childRowTypeName, 1);
            this.Name       = isDuplicateKey ? string.Format("Get{0}sBy{1}", childRowTypeName, keyrefSchema.Name) : string.Format("Get{0}s", childRowTypeName);

            //				if (this.ReaderWriterLock.IsReaderLockHeld == false && this.ReaderWriterLock.IsWriterLockHeld == false)
            //					throw new LockException("An attempt was made to access an Employee Row without a lock");
            this.Statements.Add(new CodeCommentStatement("This insures the row is locked before attempting to create a list of children."));
            this.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "ReaderWriterLock"), "IsReaderLockHeld"), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(false)), CodeBinaryOperatorType.BooleanAnd, new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "ReaderWriterLock"), "IsWriterLockHeld"), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(false))),
                                                           new CodeThrowExceptionStatement(new CodeObjectCreateExpression(new CodeTypeReference("MarkThree.LockException"), new CodePrimitiveExpression(string.Format("An attempt was made to access a {0} row without a lock", parentTable.Name))))));

            //				try
            //				{
            //					// The child table must be locked to insure it doesn't change while the relation is used to create a list of
            //					// all the child rows of this row.
            //					this.tableEmployee.EmployeeEngineerRelation.ChildTable.ReaderWriterLock.AcquireReaderLock(System.Threading.Timeout.Infinite);
            //					return ((EngineerRow[])(this.GetChildRows(this.tableEmployee.EmployeeEngineerRelation)));
            //				}
            //				finally
            //				{
            //					// The child table can be released once the list is built.
            //					this.tableEmployee.EmployeeEngineerRelation.ChildTable.ReaderWriterLock.ReleaseReaderLock();
            //				}
            //			}
            CodeTryCatchFinallyStatement getTryStatement = new CodeTryCatchFinallyStatement();
            CodeExpression parentRelationExpression      = new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), tableFieldName), relationName);

            getTryStatement.TryStatements.Add(new CodeCommentStatement("The child table must be locked to insure it doesn't change while the relation is used to create a list of"));
            getTryStatement.TryStatements.Add(new CodeCommentStatement("all the child rows of this row."));
            foreach (LockRequest lockRequest in tableLockList)
            {
                getTryStatement.TryStatements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(keyrefSchema.Selector.DataModelSchema.Name), lockRequest.TableSchema.Name), "ReaderWriterLock"), "AcquireReaderLock", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.Threading.Timeout)), "Infinite")));
            }
            getTryStatement.TryStatements.Add(new CodeMethodReturnStatement(new CodeCastExpression(new CodeTypeReference(childRowTypeName, 1), new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "GetChildRows", new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), tableFieldName), string.Format("{0}{1}Relation", keyrefSchema.Refer.Selector.Name, keyrefSchema.Selector.Name))))));
            getTryStatement.FinallyStatements.Add(new CodeCommentStatement("The child table can be released once the list is built."));
            foreach (LockRequest lockRequest in tableLockList)
            {
                getTryStatement.FinallyStatements.Add(new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(keyrefSchema.Selector.DataModelSchema.Name), lockRequest.TableSchema.Name), "ReaderWriterLock"), "ReleaseReaderLock"));
            }
            this.Statements.Add(getTryStatement);
        }
	protected override void GenerateTryCatchFinallyStatement
				(CodeTryCatchFinallyStatement e)
			{
				Output.Write("try");
				StartBlock();
				GenerateStatements(e.TryStatements);
				EndBlock();
				CodeCatchClauseCollection clauses = e.CatchClauses;
				if(clauses.Count > 0)
				{
					foreach(CodeCatchClause clause in clauses)
					{
						if(clause.CatchExceptionType != null)
						{
							Output.Write("catch (");
							OutputType(clause.CatchExceptionType);
							if(clause.LocalName != null)
							{
								Output.Write(" ");
								OutputIdentifier(clause.LocalName);
							}
							Output.Write(")");
						}
						else
						{
							Output.Write("catch");
						}
						StartBlock();
						GenerateStatements(clause.Statements);
						EndBlock();
					}
				}
				CodeStatementCollection fin = e.FinallyStatements;
				if(fin.Count > 0)
				{
					Output.Write("finally");
					StartBlock();
					GenerateStatements(fin);
					EndBlock();
				}
			}
        private static IList <CodeVariableDeclarationStatement> _TraceTryCatchFinallyStatement(CodeTryCatchFinallyStatement s, CodeStatement t, out bool found)
        {
            found = true;
            if (s == t)
            {
                return(new CodeVariableDeclarationStatement[0]);
            }
            found = false;
            var result = new List <CodeVariableDeclarationStatement>();

            foreach (CodeStatement tt in s.TryStatements)
            {
                var r = _TraceStatement(tt, t, out found);
                result.AddRange(r);
                if (found)
                {
                    return(result);
                }
            }
            result.Clear();             // new scope
            foreach (CodeCatchClause cc in s.CatchClauses)
            {
                // each clause we're in a new scope
                var res2 = new List <CodeVariableDeclarationStatement>();
                if (null != cc.CatchExceptionType)
                {
                    // treat catch(Exception e) as a variable declaration of e
                    var vdc = new CodeVariableDeclarationStatement(cc.CatchExceptionType, cc.LocalName);
                    // but flag it later so we know, in case we need to
                    vdc.UserData.Add(_catchClauseKey, cc);
                    res2.Add(vdc);
                }
                foreach (CodeStatement tt in cc.Statements)
                {
                    var r = _TraceStatement(tt, t, out found);
                    res2.AddRange(r);
                    if (found)
                    {
                        result.AddRange(res2);
                        return(result);
                    }
                }
            }
            result.Clear();             // new scope
            foreach (CodeStatement tt in s.FinallyStatements)
            {
                var r = _TraceStatement(tt, t, out found);
                result.AddRange(r);
                if (found)
                {
                    return(result);
                }
            }
            return(new CodeVariableDeclarationStatement[0]);
        }
示例#40
0
 protected abstract void GenerateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e);
 protected override void GenerateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e)
 {
     Output.WriteLine("[CodeTryCatchFinallyStatement: {0}]", e.ToString());
 }
示例#42
0
        public void ProviderSupports()
        {
            CodeDomProvider provider = GetProvider();

            CodeCompileUnit cu = new CodeCompileUnit();
            CodeNamespace nspace = new CodeNamespace("NSPC");
            nspace.Imports.Add(new CodeNamespaceImport("System"));
            nspace.Imports.Add(new CodeNamespaceImport("System.Drawing"));
            nspace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
            nspace.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
            cu.Namespaces.Add(nspace);

            CodeTypeDeclaration cd = new CodeTypeDeclaration("TEST");
            cd.IsClass = true;
            nspace.Types.Add(cd);

            // Arrays of Arrays
            CodeMemberMethod cmm = new CodeMemberMethod();
            cmm.Name = "ArraysOfArrays";
            cmm.ReturnType = new CodeTypeReference(typeof(int));
            cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public;
            if (provider.Supports(GeneratorSupport.ArraysOfArrays))
            {
                cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int[][])),
                    "arrayOfArrays", new CodeArrayCreateExpression(typeof(int[][]),
                    new CodeArrayCreateExpression(typeof(int[]), new CodePrimitiveExpression(3), new CodePrimitiveExpression(4)),
                    new CodeArrayCreateExpression(typeof(int[]), new CodeExpression[] { new CodePrimitiveExpression(1) }))));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeArrayIndexerExpression(
                    new CodeArrayIndexerExpression(new CodeVariableReferenceExpression("arrayOfArrays"), new CodePrimitiveExpression(0))
                    , new CodePrimitiveExpression(1))));
            }
            else
            {
                throw new Exception("not supported");
            }
            cd.Members.Add(cmm);

            // assembly attributes
            if (provider.Supports(GeneratorSupport.AssemblyAttributes))
            {
                CodeAttributeDeclarationCollection attrs = cu.AssemblyCustomAttributes;
                attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new
                    CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly"))));
                attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new
                    CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2"))));
            }

            CodeTypeDeclaration class1 = new CodeTypeDeclaration();
            if (provider.Supports(GeneratorSupport.ChainedConstructorArguments))
            {
                class1.Name = "Test2";
                class1.IsClass = true;
                nspace.Types.Add(class1);

                class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(String)), "stringField"));
                CodeMemberProperty prop = new CodeMemberProperty();
                prop.Name = "accessStringField";
                prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                prop.Type = new CodeTypeReference(typeof(String));
                prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
                    "stringField")));
                prop.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new
                    CodeThisReferenceExpression(), "stringField"),
                    new CodePropertySetValueReferenceExpression()));
                class1.Members.Add(prop);

                CodeConstructor cctor = new CodeConstructor();
                cctor.Attributes = MemberAttributes.Public;
                cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression("testingString"));
                cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null));
                cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null));
                class1.Members.Add(cctor);

                CodeConstructor cc = new CodeConstructor();
                cc.Attributes = MemberAttributes.Public | MemberAttributes.Overloaded;
                cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p1"));
                cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p2"));
                cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p3"));
                cc.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression()
                    , "stringField"), new CodeVariableReferenceExpression("p1")));
                class1.Members.Add(cc);
                // verify chained constructors work
                cmm = new CodeMemberMethod();
                cmm.Name = "ChainedConstructorUse";
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.ReturnType = new CodeTypeReference(typeof(String));
                // utilize constructor
                cmm.Statements.Add(new CodeVariableDeclarationStatement("Test2", "t", new CodeObjectCreateExpression("Test2")));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression(
                    new CodeVariableReferenceExpression("t"), "accessStringField")));
                cd.Members.Add(cmm);
            }

            // complex expressions
            if (provider.Supports(GeneratorSupport.ComplexExpressions))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "ComplexExpressions";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public;
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
                cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("i"),
                    new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Multiply,
                    new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add,
                    new CodePrimitiveExpression(3)))));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("i")));
                cd.Members.Add(cmm);
            }

            if (provider.Supports(GeneratorSupport.DeclareEnums))
            {
                CodeTypeDeclaration ce = new CodeTypeDeclaration("DecimalEnum");
                ce.IsEnum = true;
                nspace.Types.Add(ce);

                // things to enumerate
                for (int k = 0; k < 5; k++)
                {
                    CodeMemberField Field = new CodeMemberField("System.Int32", "Num" + (k).ToString());
                    Field.InitExpression = new CodePrimitiveExpression(k);
                    ce.Members.Add(Field);
                }
                cmm = new CodeMemberMethod();
                cmm.Name = "OutputDecimalEnumVal";
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
                cmm.Parameters.Add(param);
                CodeBinaryOperatorExpression eq = new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality,
                    new CodePrimitiveExpression(3));
                CodeMethodReturnStatement truestmt = new CodeMethodReturnStatement(
                    new CodeCastExpression(typeof(int),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num3")));
                CodeConditionStatement condstmt = new CodeConditionStatement(eq, truestmt);
                cmm.Statements.Add(condstmt);

                eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
                    CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(4));
                truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num4")));
                condstmt = new CodeConditionStatement(eq, truestmt);
                cmm.Statements.Add(condstmt);
                eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
                    CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(2));
                truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num2")));
                condstmt = new CodeConditionStatement(eq, truestmt);
                cmm.Statements.Add(condstmt);

                eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
                    CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(1));
                truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num1")));
                condstmt = new CodeConditionStatement(eq, truestmt);
                cmm.Statements.Add(condstmt);

                eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
                    CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(0));
                truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num0")));
                condstmt = new CodeConditionStatement(eq, truestmt);
                cmm.Statements.Add(condstmt);

                cmm.ReturnType = new CodeTypeReference("System.int32");

                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(10))));
                cd.Members.Add(cmm);
            }

            if (provider.Supports(GeneratorSupport.DeclareInterfaces))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "TestSingleInterface";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.Statements.Add(new CodeVariableDeclarationStatement("TestSingleInterfaceImp", "t", new CodeObjectCreateExpression("TestSingleInterfaceImp")));
                CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t")
                    , "InterfaceMethod");
                methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i"));
                cmm.Statements.Add(new CodeMethodReturnStatement(methodinvoke));
                cd.Members.Add(cmm);

                class1 = new CodeTypeDeclaration("InterfaceA");
                class1.IsInterface = true;
                nspace.Types.Add(class1);
                cmm = new CodeMemberMethod();
                cmm.Attributes = MemberAttributes.Public;
                cmm.Name = "InterfaceMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
                class1.Members.Add(cmm);

                if (provider.Supports(GeneratorSupport.MultipleInterfaceMembers))
                {
                    CodeTypeDeclaration classDecl = new CodeTypeDeclaration("InterfaceB");
                    classDecl.IsInterface = true;
                    nspace.Types.Add(classDecl);
                    cmm = new CodeMemberMethod();
                    cmm.Name = "InterfaceMethod";
                    cmm.Attributes = MemberAttributes.Public;
                    cmm.ReturnType = new CodeTypeReference(typeof(int));
                    cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
                    classDecl.Members.Add(cmm);

                    CodeTypeDeclaration class2 = new CodeTypeDeclaration("TestMultipleInterfaceImp");
                    class2.BaseTypes.Add(new CodeTypeReference("System.Object"));
                    class2.BaseTypes.Add(new CodeTypeReference("InterfaceB"));
                    class2.BaseTypes.Add(new CodeTypeReference("InterfaceA"));
                    class2.IsClass = true;
                    nspace.Types.Add(class2);
                    cmm = new CodeMemberMethod();
                    cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA"));
                    cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceB"));
                    cmm.Name = "InterfaceMethod";
                    cmm.ReturnType = new CodeTypeReference(typeof(int));
                    cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
                    cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                    cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
                    class2.Members.Add(cmm);

                    cmm = new CodeMemberMethod();
                    cmm.Name = "TestMultipleInterfaces";
                    cmm.ReturnType = new CodeTypeReference(typeof(int));
                    cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
                    cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                    cmm.Statements.Add(new CodeVariableDeclarationStatement("TestMultipleInterfaceImp", "t", new CodeObjectCreateExpression("TestMultipleInterfaceImp")));
                    cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceA", "interfaceAobject", new CodeCastExpression("InterfaceA",
                        new CodeVariableReferenceExpression("t"))));
                    cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceB", "interfaceBobject", new CodeCastExpression("InterfaceB",
                        new CodeVariableReferenceExpression("t"))));
                    methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceAobject")
                        , "InterfaceMethod");
                    methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i"));
                    CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceBobject")
                        , "InterfaceMethod");
                    methodinvoke2.Parameters.Add(new CodeVariableReferenceExpression("i"));
                    cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(
                        methodinvoke,
                        CodeBinaryOperatorType.Subtract, methodinvoke2)));
                    cd.Members.Add(cmm);
                }

                class1 = new CodeTypeDeclaration("TestSingleInterfaceImp");
                class1.BaseTypes.Add(new CodeTypeReference("System.Object"));
                class1.BaseTypes.Add(new CodeTypeReference("InterfaceA"));
                class1.IsClass = true;
                nspace.Types.Add(class1);
                cmm = new CodeMemberMethod();
                cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA"));
                cmm.Name = "InterfaceMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
                cmm.Attributes = MemberAttributes.Public;
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
                class1.Members.Add(cmm);
            }

            if (provider.Supports(GeneratorSupport.DeclareValueTypes))
            {
                CodeTypeDeclaration structA = new CodeTypeDeclaration("structA");
                structA.IsStruct = true;

                CodeTypeDeclaration structB = new CodeTypeDeclaration("structB");
                structB.Attributes = MemberAttributes.Public;
                structB.IsStruct = true;

                CodeMemberField firstInt = new CodeMemberField(typeof(int), "int1");
                firstInt.Attributes = MemberAttributes.Public;
                structB.Members.Add(firstInt);

                CodeMemberField innerStruct = new CodeMemberField("structB", "innerStruct");
                innerStruct.Attributes = MemberAttributes.Public;

                structA.Members.Add(structB);
                structA.Members.Add(innerStruct);
                nspace.Types.Add(structA);

                CodeMemberMethod nestedStructMethod = new CodeMemberMethod();
                nestedStructMethod.Name = "NestedStructMethod";
                nestedStructMethod.ReturnType = new CodeTypeReference(typeof(int));
                nestedStructMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                CodeVariableDeclarationStatement varStructA = new CodeVariableDeclarationStatement("structA", "varStructA");
                nestedStructMethod.Statements.Add(varStructA);
                nestedStructMethod.Statements.Add
                    (
                    new CodeAssignStatement
                    (
                    /* Expression1 */ new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1"),
                    /* Expression1 */ new CodePrimitiveExpression(3)
                    )
                    );
                nestedStructMethod.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1")));
                cd.Members.Add(nestedStructMethod);
            }

            if (provider.Supports(GeneratorSupport.EntryPointMethod))
            {
                CodeEntryPointMethod cep = new CodeEntryPointMethod();
                cd.Members.Add(cep);
            }

            // goto statements
            if (provider.Supports(GeneratorSupport.GotoStatements))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "GoToMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
                cmm.Parameters.Add(param);
                CodeConditionStatement condstmt = new CodeConditionStatement(new CodeBinaryOperatorExpression(
                    new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(1)),
                    new CodeGotoStatement("comehere"));
                cmm.Statements.Add(condstmt);
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(6)));
                cmm.Statements.Add(new CodeLabeledStatement("comehere",
                    new CodeMethodReturnStatement(new CodePrimitiveExpression(7))));
                cd.Members.Add(cmm);
            }

            if (provider.Supports(GeneratorSupport.NestedTypes))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "CallingPublicNestedScenario";
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference
                    ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"), "t",
                    new CodeObjectCreateExpression(new CodeTypeReference
                    ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"))));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"),
                    "publicNestedClassesMethod",
                    new CodeVariableReferenceExpression("i"))));
                cd.Members.Add(cmm);

                class1 = new CodeTypeDeclaration("PublicNestedClassA");
                class1.IsClass = true;
                nspace.Types.Add(class1);
                CodeTypeDeclaration nestedClass = new CodeTypeDeclaration("PublicNestedClassB1");
                nestedClass.IsClass = true;
                nestedClass.TypeAttributes = TypeAttributes.NestedPublic;
                class1.Members.Add(nestedClass);
                nestedClass = new CodeTypeDeclaration("PublicNestedClassB2");
                nestedClass.TypeAttributes = TypeAttributes.NestedPublic;
                nestedClass.IsClass = true;
                class1.Members.Add(nestedClass);
                CodeTypeDeclaration innerNestedClass = new CodeTypeDeclaration("PublicNestedClassC");
                innerNestedClass.TypeAttributes = TypeAttributes.NestedPublic;
                innerNestedClass.IsClass = true;
                nestedClass.Members.Add(innerNestedClass);
                cmm = new CodeMemberMethod();
                cmm.Name = "publicNestedClassesMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
                innerNestedClass.Members.Add(cmm);
            }

            // Parameter Attributes
            if (provider.Supports(GeneratorSupport.ParameterAttributes))
            {
                CodeMemberMethod method1 = new CodeMemberMethod();
                method1.Name = "MyMethod";
                method1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression(typeof(string), "blah");
                param1.CustomAttributes.Add(
                    new CodeAttributeDeclaration(
                    "System.Xml.Serialization.XmlElementAttribute",
                    new CodeAttributeArgument(
                    "Form",
                    new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
                    new CodeAttributeArgument(
                    "IsNullable",
                    new CodePrimitiveExpression(false))));
                method1.Parameters.Add(param1);
                cd.Members.Add(method1);
            }

            // public static members
            if (provider.Supports(GeneratorSupport.PublicStaticMembers))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "PublicStaticMethod";
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(16)));
                cd.Members.Add(cmm);
            }

            // reference parameters
            if (provider.Supports(GeneratorSupport.ReferenceParameters))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "Work";
                cmm.ReturnType = new CodeTypeReference("System.void");
                cmm.Attributes = MemberAttributes.Static;
                // add parameter with ref direction
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
                param.Direction = FieldDirection.Ref;
                cmm.Parameters.Add(param);
                // add parameter with out direction
                param = new CodeParameterDeclarationExpression(typeof(int), "j");
                param.Direction = FieldDirection.Out;
                cmm.Parameters.Add(param);
                cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("i"),
                    new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression("i"),
                    CodeBinaryOperatorType.Add, new CodePrimitiveExpression(4))));
                cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("j"),
                    new CodePrimitiveExpression(5)));
                cd.Members.Add(cmm);

                cmm = new CodeMemberMethod();
                cmm.Name = "CallingWork";
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                CodeParameterDeclarationExpression parames = new CodeParameterDeclarationExpression(typeof(int), "a");
                cmm.Parameters.Add(parames);
                cmm.ReturnType = new CodeTypeReference("System.int32");
                cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"),
                    new CodePrimitiveExpression(10)));
                cmm.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "b"));
                // invoke the method called "work"
                CodeMethodInvokeExpression methodinvoked = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression
                    (new CodeTypeReferenceExpression("TEST"), "Work"));
                // add parameter with ref direction
                CodeDirectionExpression parameter = new CodeDirectionExpression(FieldDirection.Ref,
                    new CodeVariableReferenceExpression("a"));
                methodinvoked.Parameters.Add(parameter);
                // add parameter with out direction
                parameter = new CodeDirectionExpression(FieldDirection.Out, new CodeVariableReferenceExpression("b"));
                methodinvoked.Parameters.Add(parameter);
                cmm.Statements.Add(methodinvoked);
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression
                    (new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression("b"))));
                cd.Members.Add(cmm);
            }

            if (provider.Supports(GeneratorSupport.ReturnTypeAttributes))
            {
                CodeMemberMethod function1 = new CodeMemberMethod();
                function1.Name = "MyFunction";
                function1.ReturnType = new CodeTypeReference(typeof(string));
                function1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                function1.ReturnTypeCustomAttributes.Add(new
                    CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute"));
                function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new
                    CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new
                    CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe"))));
                function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return")));
                cd.Members.Add(function1);
            }

            if (provider.Supports(GeneratorSupport.StaticConstructors))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "TestStaticConstructor";
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.ReturnType = new CodeTypeReference(typeof(int));
                CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a");
                cmm.Parameters.Add(param);
                // utilize constructor
                cmm.Statements.Add(new CodeVariableDeclarationStatement("Test4", "t", new CodeObjectCreateExpression("Test4")));
                // set then get number
                cmm.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("t"), "i")
                    , new CodeVariableReferenceExpression("a")));
                cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression(
                    new CodeVariableReferenceExpression("t"), "i")));
                cd.Members.Add(cmm);

                class1 = new CodeTypeDeclaration();
                class1.Name = "Test4";
                class1.IsClass = true;
                nspace.Types.Add(class1);

                class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(int)), "number"));
                CodeMemberProperty prop = new CodeMemberProperty();
                prop.Name = "i";
                prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                prop.Type = new CodeTypeReference(typeof(int));
                prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("number")));
                prop.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("number"),
                    new CodePropertySetValueReferenceExpression()));
                class1.Members.Add(prop);
                CodeTypeConstructor ctc = new CodeTypeConstructor();
                class1.Members.Add(ctc);
            }

            if (provider.Supports(GeneratorSupport.TryCatchStatements))
            {
                cmm = new CodeMemberMethod();
                cmm.Name = "TryCatchMethod";
                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);
            }

            if (provider.Supports(GeneratorSupport.DeclareEvents))
            {
                CodeNamespace ns = new CodeNamespace();
                ns.Name = "MyNamespace";
                ns.Imports.Add(new CodeNamespaceImport("System"));
                ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));
                ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
                ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
                cu.Namespaces.Add(ns);
                class1 = new CodeTypeDeclaration("Test");
                class1.IsClass = true;
                class1.BaseTypes.Add(new CodeTypeReference("Form"));
                ns.Types.Add(class1);

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

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

                CodeMemberEvent evt = new CodeMemberEvent();
                evt.Name = "MyEvent";
                evt.Type = new CodeTypeReference("System.EventHandler");
                evt.Attributes = MemberAttributes.Public;
                class1.Members.Add(evt);

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

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

                  Option Strict Off
                  Option Explicit On

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

                  Namespace NSPC

                      Public Class TEST

                          Public Function ArraysOfArrays() As Integer
                              Dim arrayOfArrays()() As Integer = New Integer()() {New Integer() {3, 4}, New Integer() {1}}
                              Return arrayOfArrays(0)(1)
                          End Function

                          Public Shared Function ChainedConstructorUse() As String
                              Dim t As Test2 = New Test2()
                              Return t.accessStringField
                          End Function

                          Public Function ComplexExpressions(ByVal i As Integer) As Integer
                              i = (i  _
                                          * (i + 3))
                              Return i
                          End Function

                          Public Shared Function OutputDecimalEnumVal(ByVal i As Integer) As Integer
                              If (i = 3) Then
                                  Return CType(DecimalEnum.Num3,Integer)
                              End If
                              If (i = 4) Then
                                  Return CType(DecimalEnum.Num4,Integer)
                              End If
                              If (i = 2) Then
                                  Return CType(DecimalEnum.Num2,Integer)
                              End If
                              If (i = 1) Then
                                  Return CType(DecimalEnum.Num1,Integer)
                              End If
                              If (i = 0) Then
                                  Return CType(DecimalEnum.Num0,Integer)
                              End If
                              Return (i + 10)
                          End Function

                          Public Shared Function TestSingleInterface(ByVal i As Integer) As Integer
                              Dim t As TestSingleInterfaceImp = New TestSingleInterfaceImp()
                              Return t.InterfaceMethod(i)
                          End Function

                          Public Shared Function TestMultipleInterfaces(ByVal i As Integer) As Integer
                              Dim t As TestMultipleInterfaceImp = New TestMultipleInterfaceImp()
                              Dim interfaceAobject As InterfaceA = CType(t,InterfaceA)
                              Dim interfaceBobject As InterfaceB = CType(t,InterfaceB)
                              Return (interfaceAobject.InterfaceMethod(i) - interfaceBobject.InterfaceMethod(i))
                          End Function

                          Public Shared Function NestedStructMethod() As Integer
                              Dim varStructA As structA
                              varStructA.innerStruct.int1 = 3
                              Return varStructA.innerStruct.int1
                          End Function

                          Public Shared Sub Main()
                          End Sub

                          Public Function GoToMethod(ByVal i As Integer) As Integer
                              If (i < 1) Then
                                  goto comehere
                              End If
                              Return 6
                          comehere:
                              Return 7
                          End Function

                          Public Shared Function CallingPublicNestedScenario(ByVal i As Integer) As Integer
                              Dim t As PublicNestedClassA.PublicNestedClassB2.PublicNestedClassC = New PublicNestedClassA.PublicNestedClassB2.PublicNestedClassC()
                              Return t.publicNestedClassesMethod(i)
                          End Function

                          Public Sub MyMethod(<System.Xml.Serialization.XmlElementAttribute(Form:=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable:=false)> ByVal blah As String)
                          End Sub

                          Public Shared Function PublicStaticMethod() As Integer
                              Return 16
                          End Function

                          Shared Sub Work(ByRef i As Integer, ByRef j As Integer)
                              i = (i + 4)
                              j = 5
                          End Sub

                          Public Shared Function CallingWork(ByVal a As Integer) As Integer
                              a = 10
                              Dim b As Integer
                              TEST.Work(a, b)
                              Return (a + b)
                          End Function

                          Public Function MyFunction() As <System.Xml.Serialization.XmlIgnoreAttribute(), System.Xml.Serialization.XmlRootAttribute([Namespace]:=""Namespace Value"", ElementName:=""Root, hehehe"")> String
                              Return ""Return""
                          End Function

                          Public Shared Function TestStaticConstructor(ByVal a As Integer) As Integer
                              Dim t As Test4 = New Test4()
                              t.i = a
                              Return t.i
                          End Function

                          Public Shared Function TryCatchMethod(ByVal a As Integer) As Integer
                              Try
                              Finally
                                  a = (a + 5)
                              End Try
                              Return a
                          End Function
                      End Class

                      Public Class Test2

                          Private stringField As String

                          Public Sub New()
                              Me.New(""testingString"", Nothing, Nothing)
                          End Sub

                          Public Sub New(ByVal p1 As String, ByVal p2 As String, ByVal p3 As String)
                              MyBase.New
                              Me.stringField = p1
                          End Sub

                          Public Property accessStringField() As String
                              Get
                                  Return Me.stringField
                              End Get
                              Set
                                  Me.stringField = value
                              End Set
                          End Property
                      End Class

                      Public Enum DecimalEnum

                          Num0 = 0

                          Num1 = 1

                          Num2 = 2

                          Num3 = 3

                          Num4 = 4
                      End Enum

                      Public Interface InterfaceA

                          Function InterfaceMethod(ByVal a As Integer) As Integer
                      End Interface

                      Public Interface InterfaceB

                          Function InterfaceMethod(ByVal a As Integer) As Integer
                      End Interface

                      Public Class TestMultipleInterfaceImp
                          Inherits Object
                          Implements InterfaceB, InterfaceA

                          Public Function InterfaceMethod(ByVal a As Integer) As Integer Implements InterfaceA.InterfaceMethod , InterfaceB.InterfaceMethod
                              Return a
                          End Function
                      End Class

                      Public Class TestSingleInterfaceImp
                          Inherits Object
                          Implements InterfaceA

                          Public Overridable Function InterfaceMethod(ByVal a As Integer) As Integer Implements InterfaceA.InterfaceMethod
                              Return a
                          End Function
                      End Class

                      Public Structure structA

                          Public innerStruct As structB

                          Public Structure structB

                              Public int1 As Integer
                          End Structure
                      End Structure

                      Public Class PublicNestedClassA

                          Public Class PublicNestedClassB1
                          End Class

                          Public Class PublicNestedClassB2

                              Public Class PublicNestedClassC

                                  Public Function publicNestedClassesMethod(ByVal a As Integer) As Integer
                                      Return a
                                  End Function
                              End Class
                          End Class
                      End Class

                      Public Class Test4

                          Private number As Integer

                          Shared Sub New()
                          End Sub

                          Public Property i() As Integer
                              Get
                                  Return number
                              End Get
                              Set
                                  number = value
                              End Set
                          End Property
                      End Class
                  End Namespace

                  Namespace MyNamespace

                      Public Class Test
                          Inherits Form

                          Private b As Button = New Button()

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

                          Public Event MyEvent As System.EventHandler

                          Private Sub b_Click(ByVal sender As Object, ByVal e As System.EventArgs)
                          End Sub
                      End Class
                  End Namespace");
        }
    public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu)
    {

        CodeNamespace nspace = new CodeNamespace ("NSPC");
        nspace.Imports.Add (new CodeNamespaceImport ("System"));
        nspace.Imports.Add (new CodeNamespaceImport ("System.Drawing"));
        nspace.Imports.Add (new CodeNamespaceImport ("System.Windows.Forms"));
        nspace.Imports.Add (new CodeNamespaceImport ("System.ComponentModel"));
        cu.Namespaces.Add (nspace);

        cu.ReferencedAssemblies.Add ("System.Drawing.dll");
        cu.ReferencedAssemblies.Add ("System.Windows.Forms.dll");
        cu.ReferencedAssemblies.Add ("System.Xml.dll");

        CodeTypeDeclaration cd = new CodeTypeDeclaration ("TEST");
        cd.IsClass = true;
        nspace.Types.Add (cd);

        CodeMemberMethod cmm;

        // Arrays of Arrays
#if !WHIDBEY
        // Everett VB code provider doesn't support array of array initialization
        if (!(provider is Microsoft.VisualBasic.VBCodeProvider)) {
#endif
            if (Supports (provider, GeneratorSupport.ArraysOfArrays)) {
                AddScenario ("CheckArrayOfArrays");
                cmm = new CodeMemberMethod ();
                cmm.Name = "ArraysOfArrays";
                cmm.ReturnType = new CodeTypeReference (typeof (int));
                cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public;
                cmm.Statements.Add (new CodeVariableDeclarationStatement (new CodeTypeReference (typeof (int[][])),
                    "arrayOfArrays", new CodeArrayCreateExpression (typeof (int[][]),
                    new CodeArrayCreateExpression (typeof (int[]), new CodePrimitiveExpression (3), new CodePrimitiveExpression (4)),
                    new CodeArrayCreateExpression (typeof (int[]), new CodeExpression[] {new CodePrimitiveExpression (1)}))));
                cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArrayIndexerExpression (
                    new CodeArrayIndexerExpression (new CodeVariableReferenceExpression ("arrayOfArrays"), new CodePrimitiveExpression (0)),
                    new CodePrimitiveExpression (1))));
                cd.Members.Add (cmm);
            }
#if !WHIDBEY
        }
#endif

        // assembly attributes
        if (Supports (provider, GeneratorSupport.AssemblyAttributes)) {
            AddScenario ("CheckAssemblyAttributes");
            CodeAttributeDeclarationCollection attrs = cu.AssemblyCustomAttributes;
            attrs.Add (new CodeAttributeDeclaration ("System.Reflection.AssemblyTitle", new
                CodeAttributeArgument (new CodePrimitiveExpression ("MyAssembly"))));
            attrs.Add (new CodeAttributeDeclaration ("System.Reflection.AssemblyVersion", new
                CodeAttributeArgument (new CodePrimitiveExpression ("1.0.6.2"))));
        }

        CodeTypeDeclaration class1 = new CodeTypeDeclaration ();
        if (Supports (provider, GeneratorSupport.ChainedConstructorArguments)) {
            AddScenario ("CheckChainedConstructorArgs");
            class1.Name = "Test2";
            class1.IsClass = true;
            nspace.Types.Add (class1);

            class1.Members.Add (new CodeMemberField (new CodeTypeReference (typeof (String)), "stringField"));
            CodeMemberProperty prop = new CodeMemberProperty ();
            prop.Name = "accessStringField";
            prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            prop.Type = new CodeTypeReference (typeof (String));
            prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression (),
                "stringField")));
            prop.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new
                CodeThisReferenceExpression (), "stringField"),
                new CodePropertySetValueReferenceExpression ()));
            class1.Members.Add (prop);

            CodeConstructor cctor = new CodeConstructor ();
            cctor.Attributes = MemberAttributes.Public;
            cctor.ChainedConstructorArgs.Add (new CodePrimitiveExpression ("testingString"));
            cctor.ChainedConstructorArgs.Add (new CodePrimitiveExpression (null));
            cctor.ChainedConstructorArgs.Add (new CodePrimitiveExpression (null));
            class1.Members.Add (cctor);

            CodeConstructor cc = new CodeConstructor ();
            cc.Attributes = MemberAttributes.Public | MemberAttributes.Overloaded;
            cc.Parameters.Add (new CodeParameterDeclarationExpression (typeof (string), "p1"));
            cc.Parameters.Add (new CodeParameterDeclarationExpression (typeof (string), "p2"));
            cc.Parameters.Add (new CodeParameterDeclarationExpression (typeof (string), "p3"));
            cc.Statements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (new CodeThisReferenceExpression ()
                , "stringField"), new CodeArgumentReferenceExpression ("p1")));
            class1.Members.Add (cc);

            // verify chained constructors work
            cmm = new CodeMemberMethod ();
            cmm.Name = "ChainedConstructorUse";
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            cmm.ReturnType = new CodeTypeReference (typeof (String));
            // utilize constructor
            cmm.Statements.Add (new CodeVariableDeclarationStatement ("Test2", "t", new CodeObjectCreateExpression ("Test2")));
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression (
                new CodeVariableReferenceExpression ("t"), "accessStringField")));
            cd.Members.Add (cmm);
        }

        // complex expressions
        if (Supports (provider, GeneratorSupport.ComplexExpressions)) {
            AddScenario ("CheckComplexExpressions");
            cmm = new CodeMemberMethod ();
            cmm.Name = "ComplexExpressions";
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public;
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i"));
            cmm.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("i"),
                new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.Multiply,
                new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.Add,
                new CodePrimitiveExpression (3)))));
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("i")));
            cd.Members.Add (cmm);
        }

        if (Supports (provider, GeneratorSupport.DeclareEnums)) {
            AddScenario ("CheckDeclareEnums");
            CodeTypeDeclaration ce = new CodeTypeDeclaration ("DecimalEnum");
            ce.IsEnum = true;
            nspace.Types.Add (ce);

            // things to enumerate
            for (int k = 0; k < 5; k++)
            {
                CodeMemberField Field = new CodeMemberField ("System.Int32", "Num" + (k).ToString ());
                Field.InitExpression = new CodePrimitiveExpression (k);
                ce.Members.Add (Field);
            }
            cmm = new CodeMemberMethod ();
            cmm.Name = "OutputDecimalEnumVal";
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "i");
            cmm.Parameters.Add (param);
            CodeBinaryOperatorExpression eq       = new CodeBinaryOperatorExpression (
                new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.ValueEquality,
                new CodePrimitiveExpression (3));
            CodeMethodReturnStatement    truestmt = new CodeMethodReturnStatement (
                new CodeCastExpression (typeof (int),
                new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("DecimalEnum"), "Num3")));
            CodeConditionStatement       condstmt = new CodeConditionStatement (eq, truestmt);
            cmm.Statements.Add (condstmt);

            eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"),
                CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (4));
            truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new
                CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("DecimalEnum"), "Num4")));
            condstmt = new CodeConditionStatement (eq, truestmt);
            cmm.Statements.Add (condstmt);
            eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"),
                CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (2));
            truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new
                CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("DecimalEnum"), "Num2")));
            condstmt = new CodeConditionStatement (eq, truestmt);
            cmm.Statements.Add (condstmt);

            eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"),
                CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (1));
            truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new
                CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("DecimalEnum"), "Num1")));
            condstmt = new CodeConditionStatement (eq, truestmt);
            cmm.Statements.Add (condstmt);

            eq = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"),
                CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (0));
            truestmt = new CodeMethodReturnStatement (new CodeCastExpression (typeof (int), new
                CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("DecimalEnum"), "Num0")));
            condstmt = new CodeConditionStatement (eq, truestmt);
            cmm.Statements.Add (condstmt);

            cmm.ReturnType = new CodeTypeReference ("System.Int32");

            cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (
                new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression (10))));
            cd.Members.Add (cmm);
        }

        if (Supports (provider, GeneratorSupport.DeclareInterfaces)) {
            AddScenario ("CheckDeclareInterfaces");
            cmm = new CodeMemberMethod ();
            cmm.Name = "TestSingleInterface";
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i"));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            cmm.Statements.Add (new CodeVariableDeclarationStatement ("TestSingleInterfaceImp", "t", new CodeObjectCreateExpression ("TestSingleInterfaceImp")));
            CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("t")
                , "InterfaceMethod");
            methodinvoke.Parameters.Add (new CodeArgumentReferenceExpression ("i"));
            cmm.Statements.Add (new CodeMethodReturnStatement (methodinvoke));
            cd.Members.Add (cmm);

            class1 = new CodeTypeDeclaration ("InterfaceA");
            class1.IsInterface = true;
            nspace.Types.Add (class1);
            cmm = new CodeMemberMethod ();
            cmm.Attributes = MemberAttributes.Public;
            cmm.Name = "InterfaceMethod";
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a"));
            class1.Members.Add (cmm);

            if (Supports (provider, GeneratorSupport.MultipleInterfaceMembers)) {
                AddScenario ("CheckMultipleInterfaceMembers");
                CodeTypeDeclaration classDecl = new CodeTypeDeclaration ("InterfaceB");
                classDecl.IsInterface = true;
                nspace.Types.Add (classDecl);
                cmm = new CodeMemberMethod ();
                cmm.Name = "InterfaceMethod";
                cmm.Attributes = MemberAttributes.Public;
                cmm.ReturnType = new CodeTypeReference (typeof (int));
                cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a"));
                classDecl.Members.Add (cmm);

                CodeTypeDeclaration class2 = new CodeTypeDeclaration ("TestMultipleInterfaceImp");
                class2.BaseTypes.Add (new CodeTypeReference ("System.Object"));
                class2.BaseTypes.Add (new CodeTypeReference ("InterfaceB"));
                class2.BaseTypes.Add (new CodeTypeReference ("InterfaceA"));
                class2.IsClass = true;
                nspace.Types.Add (class2);
                cmm = new CodeMemberMethod ();
                cmm.ImplementationTypes.Add (new CodeTypeReference ("InterfaceA"));
                cmm.ImplementationTypes.Add (new CodeTypeReference ("InterfaceB"));
                cmm.Name = "InterfaceMethod";
                cmm.ReturnType = new CodeTypeReference (typeof (int));
                cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a"));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a")));
                class2.Members.Add (cmm);

                cmm = new CodeMemberMethod ();
                cmm.Name = "TestMultipleInterfaces";
                cmm.ReturnType = new CodeTypeReference (typeof (int));
                cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i"));
                cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                cmm.Statements.Add (new CodeVariableDeclarationStatement ("TestMultipleInterfaceImp", "t", new CodeObjectCreateExpression ("TestMultipleInterfaceImp")));
                cmm.Statements.Add (new CodeVariableDeclarationStatement ("InterfaceA", "interfaceAobject", new CodeCastExpression ("InterfaceA",
                    new CodeVariableReferenceExpression ("t"))));
                cmm.Statements.Add (new CodeVariableDeclarationStatement ("InterfaceB", "interfaceBobject", new CodeCastExpression ("InterfaceB",
                    new CodeVariableReferenceExpression ("t"))));
                methodinvoke = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("interfaceAobject")
                    , "InterfaceMethod");
                methodinvoke.Parameters.Add (new CodeArgumentReferenceExpression ("i"));
                CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("interfaceBobject")
                    , "InterfaceMethod");
                methodinvoke2.Parameters.Add (new CodeArgumentReferenceExpression ("i"));
                cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression (
                    methodinvoke,
                    CodeBinaryOperatorType.Subtract, methodinvoke2)));
                cd.Members.Add (cmm);
            }

            class1 = new CodeTypeDeclaration ("TestSingleInterfaceImp");
            class1.BaseTypes.Add (new CodeTypeReference ("System.Object"));
            class1.BaseTypes.Add (new CodeTypeReference ("InterfaceA"));
            class1.IsClass = true;
            nspace.Types.Add (class1);
            cmm = new CodeMemberMethod ();
            cmm.ImplementationTypes.Add (new CodeTypeReference ("InterfaceA"));
            cmm.Name = "InterfaceMethod";
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a"));
            cmm.Attributes = MemberAttributes.Public;
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a")));
            class1.Members.Add (cmm);
        }

        /*if (Supports (provider, GeneratorSupport.DeclareValueTypes)) {
            AddScenario ("CheckDeclareValueTypes");

            // create first struct to test nested structs
            //     GENERATE (C#):
            //	public struct structA {
            //		public structB innerStruct;
            //		public struct structB {
            //    		public int int1;
            //		}
            //	}
            CodeTypeDeclaration structA = new CodeTypeDeclaration ("structA");
            structA.IsStruct = true;

            CodeTypeDeclaration structB = new CodeTypeDeclaration ("structB");
            structB.TypeAttributes = TypeAttributes.NestedPublic;
            structB.Attributes = MemberAttributes.Public;
            structB.IsStruct = true;

            CodeMemberField firstInt = new CodeMemberField (typeof (int), "int1");
            firstInt.Attributes = MemberAttributes.Public;
            structB.Members.Add (firstInt);

            CodeMemberField innerStruct = new CodeMemberField ("structB", "innerStruct");
            innerStruct.Attributes = MemberAttributes.Public;

            structA.Members.Add (structB);
            structA.Members.Add (innerStruct);
            nspace.Types.Add (structA);

            CodeMemberMethod nestedStructMethod = new CodeMemberMethod ();
            nestedStructMethod.Name = "NestedStructMethod";
            nestedStructMethod.ReturnType = new CodeTypeReference (typeof (int));
            nestedStructMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            CodeVariableDeclarationStatement varStructA = new CodeVariableDeclarationStatement ("structA", "varStructA");
            nestedStructMethod.Statements.Add (varStructA);
            nestedStructMethod.Statements.Add
                (
                new CodeAssignStatement
                (
									new CodeFieldReferenceExpression (new CodeFieldReferenceExpression (new CodeVariableReferenceExpression ("varStructA"), "innerStruct"), "int1"),
									new CodePrimitiveExpression (3)
                )
                );
            nestedStructMethod.Statements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (new CodeFieldReferenceExpression (new CodeVariableReferenceExpression ("varStructA"), "innerStruct"), "int1")));
            cd.Members.Add (nestedStructMethod);
        }*/
        if (Supports (provider, GeneratorSupport.EntryPointMethod)) {
            AddScenario ("CheckEntryPointMethod");
            CodeEntryPointMethod cep = new CodeEntryPointMethod ();
            cd.Members.Add (cep);
        }
        // goto statements
        if (Supports (provider, GeneratorSupport.GotoStatements)) {
            AddScenario ("CheckGotoStatements");
            cmm = new CodeMemberMethod ();
            cmm.Name = "GoToMethod";
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "i");
            cmm.Parameters.Add (param);
            CodeConditionStatement condstmt = new CodeConditionStatement (new CodeBinaryOperatorExpression (
                new CodeArgumentReferenceExpression ("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression (1)),
                new CodeGotoStatement ("comehere"));
            cmm.Statements.Add (condstmt);
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (6)));
            cmm.Statements.Add (new CodeLabeledStatement ("comehere",
                new CodeMethodReturnStatement (new CodePrimitiveExpression (7))));
            cd.Members.Add (cmm);
        }
        if (Supports (provider, GeneratorSupport.NestedTypes)) {
            AddScenario ("CheckNestedTypes");
            cmm = new CodeMemberMethod ();
            cmm.Name = "CallingPublicNestedScenario";
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "i"));
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            cmm.Statements.Add (new CodeVariableDeclarationStatement (new CodeTypeReference
                ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"), "t",
                new CodeObjectCreateExpression (new CodeTypeReference
                ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"))));
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("t"),
                "publicNestedClassesMethod",
                new CodeArgumentReferenceExpression ("i"))));
            cd.Members.Add (cmm);

            class1 = new CodeTypeDeclaration ("PublicNestedClassA");
            class1.IsClass = true;
            nspace.Types.Add (class1);
            CodeTypeDeclaration nestedClass = new CodeTypeDeclaration ("PublicNestedClassB1");
            nestedClass.IsClass = true;
            nestedClass.TypeAttributes = TypeAttributes.NestedPublic;
            class1.Members.Add (nestedClass);
            nestedClass = new CodeTypeDeclaration ("PublicNestedClassB2");
            nestedClass.TypeAttributes = TypeAttributes.NestedPublic;
            nestedClass.IsClass = true;
            class1.Members.Add (nestedClass);
            CodeTypeDeclaration innerNestedClass = new CodeTypeDeclaration ("PublicNestedClassC");
            innerNestedClass.TypeAttributes = TypeAttributes.NestedPublic;
            innerNestedClass.IsClass = true;
            nestedClass.Members.Add (innerNestedClass);
            cmm = new CodeMemberMethod ();
            cmm.Name = "publicNestedClassesMethod";
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (int), "a"));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a")));
            innerNestedClass.Members.Add (cmm);
        }
        // Parameter Attributes
        if (Supports (provider, GeneratorSupport.ParameterAttributes)) {
            AddScenario ("CheckParameterAttributes");
            CodeMemberMethod method1 = new CodeMemberMethod ();
            method1.Name = "MyMethod";
            method1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression (typeof (string), "blah");
            param1.CustomAttributes.Add (
                new CodeAttributeDeclaration (
                "System.Xml.Serialization.XmlElementAttribute",
                new CodeAttributeArgument (
                "Form",
                new CodeFieldReferenceExpression (new CodeTypeReferenceExpression ("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
                new CodeAttributeArgument (
                "IsNullable",
                new CodePrimitiveExpression (false))));
            method1.Parameters.Add (param1);
            cd.Members.Add (method1);
        }
        // public static members
        if (Supports (provider, GeneratorSupport.PublicStaticMembers)) {
            AddScenario ("CheckPublicStaticMembers");
            cmm = new CodeMemberMethod ();
            cmm.Name = "PublicStaticMethod";
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression (16)));
            cd.Members.Add (cmm);
        }
        // reference parameters
        if (Supports (provider, GeneratorSupport.ReferenceParameters)) {
            AddScenario ("CheckReferenceParameters");
            cmm = new CodeMemberMethod ();
            cmm.Name = "Work";
            cmm.ReturnType = new CodeTypeReference ("System.void");
            cmm.Attributes = MemberAttributes.Static;
            // add parameter with ref direction
            CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "i");
            param.Direction = FieldDirection.Ref;
            cmm.Parameters.Add (param);
            // add parameter with out direction
            param = new CodeParameterDeclarationExpression (typeof (int), "j");
            param.Direction = FieldDirection.Out;
            cmm.Parameters.Add (param);
            cmm.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("i"),
                new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("i"),
                CodeBinaryOperatorType.Add, new CodePrimitiveExpression (4))));
            cmm.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("j"),
                new CodePrimitiveExpression (5)));
            cd.Members.Add (cmm);

            cmm = new CodeMemberMethod ();
            cmm.Name = "CallingWork";
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            CodeParameterDeclarationExpression parames = new CodeParameterDeclarationExpression (typeof (int), "a");
            cmm.Parameters.Add (parames);
            cmm.ReturnType = new CodeTypeReference ("System.Int32");
            cmm.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("a"),
                new CodePrimitiveExpression (10)));
            cmm.Statements.Add (new CodeVariableDeclarationStatement (typeof (int), "b"));
            // invoke the method called "work"
            CodeMethodInvokeExpression methodinvoked = new CodeMethodInvokeExpression (new CodeMethodReferenceExpression
                (new CodeTypeReferenceExpression ("TEST"), "Work"));
            // add parameter with ref direction
            CodeDirectionExpression parameter = new CodeDirectionExpression (FieldDirection.Ref,
                new CodeArgumentReferenceExpression ("a"));
            methodinvoked.Parameters.Add (parameter);
            // add parameter with out direction
            parameter = new CodeDirectionExpression (FieldDirection.Out, new CodeVariableReferenceExpression ("b"));
            methodinvoked.Parameters.Add (parameter);
            cmm.Statements.Add (methodinvoked);
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodeBinaryOperatorExpression
                (new CodeArgumentReferenceExpression ("a"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression ("b"))));
            cd.Members.Add (cmm);
        }
        if (Supports (provider, GeneratorSupport.ReturnTypeAttributes)) {
            AddScenario ("CheckReturnTypeAttributes");
            CodeMemberMethod function1 = new CodeMemberMethod ();
            function1.Name = "MyFunction";
            function1.ReturnType = new CodeTypeReference (typeof (string));
            function1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            function1.ReturnTypeCustomAttributes.Add (new
                CodeAttributeDeclaration ("System.Xml.Serialization.XmlIgnoreAttribute"));
            function1.ReturnTypeCustomAttributes.Add (new CodeAttributeDeclaration ("System.Xml.Serialization.XmlRootAttribute", new
                CodeAttributeArgument ("Namespace", new CodePrimitiveExpression ("Namespace Value")), new
                CodeAttributeArgument ("ElementName", new CodePrimitiveExpression ("Root, hehehe"))));
            function1.Statements.Add (new CodeMethodReturnStatement (new CodePrimitiveExpression ("Return")));
            cd.Members.Add (function1);
        }
        if (Supports (provider, GeneratorSupport.StaticConstructors)) {
            AddScenario ("CheckStaticConstructors");
            cmm = new CodeMemberMethod ();
            cmm.Name = "TestStaticConstructor";
            cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            cmm.ReturnType = new CodeTypeReference (typeof (int));
            CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "a");
            cmm.Parameters.Add (param);
            // utilize constructor
            cmm.Statements.Add (new CodeVariableDeclarationStatement ("Test4", "t", new CodeObjectCreateExpression ("Test4")));
            // set then get number
            cmm.Statements.Add (new CodeAssignStatement (new CodePropertyReferenceExpression (new CodeVariableReferenceExpression ("t"), "i")
                , new CodeArgumentReferenceExpression ("a")));
            cmm.Statements.Add (new CodeMethodReturnStatement (new CodePropertyReferenceExpression (
                new CodeVariableReferenceExpression ("t"), "i")));
            cd.Members.Add (cmm);

            class1 = new CodeTypeDeclaration ();
            class1.Name = "Test4";
            class1.IsClass = true;
            nspace.Types.Add (class1);

            class1.Members.Add (new CodeMemberField (new CodeTypeReference (typeof (int)), "number"));
            CodeMemberProperty prop = new CodeMemberProperty ();
            prop.Name = "i";
            prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            prop.Type = new CodeTypeReference (typeof (int));
            prop.GetStatements.Add (new CodeMethodReturnStatement (new CodeFieldReferenceExpression (null, "number")));
            prop.SetStatements.Add (new CodeAssignStatement (new CodeFieldReferenceExpression (null, "number"),
                new CodePropertySetValueReferenceExpression ()));
            class1.Members.Add (prop);
            CodeTypeConstructor ctc = new CodeTypeConstructor ();
            class1.Members.Add (ctc);
        }
        if (Supports (provider, GeneratorSupport.TryCatchStatements)) {
            AddScenario ("CheckTryCatchStatements");
            cmm = new CodeMemberMethod ();
            cmm.Name = "TryCatchMethod";
            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")));
            cd.Members.Add (cmm);
        }
        if (Supports (provider, GeneratorSupport.DeclareEvents)) {
            AddScenario ("CheckDeclareEvents");
            CodeNamespace ns = new CodeNamespace ();
            ns.Name = "MyNamespace";
            ns.Imports.Add (new CodeNamespaceImport ("System"));
            ns.Imports.Add (new CodeNamespaceImport ("System.Drawing"));
            ns.Imports.Add (new CodeNamespaceImport ("System.Windows.Forms"));
            ns.Imports.Add (new CodeNamespaceImport ("System.ComponentModel"));
            cu.Namespaces.Add (ns);
            class1 = new CodeTypeDeclaration ("Test");
            class1.IsClass = true;
            class1.BaseTypes.Add (new CodeTypeReference ("Form"));
            ns.Types.Add (class1);

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

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

            CodeMemberEvent evt = new CodeMemberEvent ();
            evt.Name = "MyEvent";
            evt.Type = new CodeTypeReference ("System.EventHandler");
            evt.Attributes = MemberAttributes.Public;
            class1.Members.Add (evt);

            cmm = new CodeMemberMethod ();
            cmm.Name = "b_Click";
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "sender"));
            cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (EventArgs), "e"));
            class1.Members.Add (cmm);
        }
        if (Supports (provider, GeneratorSupport.MultidimensionalArrays)) {
            // no codedom language represents declaration of multidimensional arrays
        }
    }