Example #1
0
        /// <summary>
        /// Codes the STMT col to array.
        /// </summary>
        /// <param name="statmentCollection">The statement collection.</param>
        /// <returns>return CodeStmtColToArray</returns>
        internal static CodeStatement[] CodeStmtColToArray(CodeStatementCollection statmentCollection)
        {
            var tryFinallyStatmanents = new CodeStatement[statmentCollection.Count];

            statmentCollection.CopyTo(tryFinallyStatmanents, 0);
            return(tryFinallyStatmanents);
        }
        private CodeStatement[] GetProcessTransitionStatements(StateType state, TransitionType transition)
        {
            CodeStatementCollection statements = new CodeStatementCollection( );

            string    stateNextName = transition.nextState;
            StateType stateNext     = Model.GetStateType(stateNextName);

            // context.TransitionName
            var contextDotTransitionName = new CodeFieldReferenceExpression(
                new CodeVariableReferenceExpression(Model.settings.context.instance),
                "TransitionName");

            // context.TransitionName  = "EvFoo[condition]"
            statements.Add(
                new CodeAssignStatement(contextDotTransitionName,
                                        new CodePrimitiveExpression(Model.GetTransitionName(transition))));

            WriteProcessTransition(statements, state, stateNextName, "Begin");
            WriteActionsFromTransition(statements, state, transition);
            WriteProcessTransition(statements, state, stateNextName, "End");

            //Special case when the next state is a final state.
            //context.OnEnd();
            WriteContextOnEnd(statements, state, stateNext);

            statements.Add(new CodeMethodReturnStatement( ));
            CodeStatement[] statementArray = new CodeStatement[statements.Count];
            statements.CopyTo(statementArray, 0);
            return(statementArray);
        }
Example #3
0
        private CodeMemberMethod GenerateTypeArrayJSONArray()
        {
            var methodDecl = new CodeMemberMethod
            {
                Name       = methodName,
                Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static
            };

            methodDecl.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(type.FullName + "[]"), "objs"));
            methodDecl.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("Org.Json.JSONArray"), "jsonArray"));

            var innerStatements = new CodeStatementCollection();

            FillJSONArrayMembers(innerStatements);

            var innerStatementsArray = new CodeStatement[innerStatements.Count];

            innerStatements.CopyTo(innerStatementsArray, 0);

            methodDecl.Statements.Add(
                new CodeIterationStatement(new CodeVariableDeclarationStatement(typeof(int), "i", new CodeSnippetExpression("0")),
                                           new CodeSnippetExpression("i < objs.Length"), new CodeSnippetStatement("i++"),
                                           innerStatementsArray));

            return(methodDecl);
        }
        private CodeMemberMethod GenerateTypeArrayJSONArray()
        {
            var methodDecl = new CodeMemberMethod
            {
                Name       = methodName + "Array",
                Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static
            };

            methodDecl.ReturnType = new CodeTypeReference(type.FullName + "[]");
            methodDecl.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("Org.Json.JSONArray"), "jsonArray"));

            var innerStatements = new CodeStatementCollection();

            FillJSONArrayMembers(innerStatements);

            var innerStatementsArray = new CodeStatement[innerStatements.Count];

            innerStatements.CopyTo(innerStatementsArray, 0);

            methodDecl.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference("System.Collections.Generic.List<" + type.FullName + ">"), "result", new CodeObjectCreateExpression("System.Collections.Generic.List<" + type.FullName + ">")));

            methodDecl.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "length",
                                                                           new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("jsonArray"), "Length")));

            methodDecl.Statements.Add(
                new CodeIterationStatement(new CodeVariableDeclarationStatement(typeof(int), "i", new CodeSnippetExpression("0")),
                                           new CodeSnippetExpression("i < length"), new CodeSnippetStatement("i++"),
                                           innerStatementsArray));

            methodDecl.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("result"), "ToArray")));

            return(methodDecl);
        }
        static CodeStatement[] _ToArray(CodeStatementCollection stmts)
        {
            var result = new CodeStatement[stmts.Count];

            stmts.CopyTo(result, 0);
            return(result);
        }
Example #6
0
        private CodeIterationStatement GenerateForRepeat(GroupActivity groupActivity, bool isRepeat)
        {
            var coreGroupMethodStatement = new CodeStatementCollection();

            // get the core loop code
            coreGroupMethodStatement.AddRange(this.GenerateCoreGroupMethod(groupActivity));
            var coreOfTheLoop = new CodeStatement[coreGroupMethodStatement.Count];

            coreGroupMethodStatement.CopyTo(coreOfTheLoop, 0);

            string outCondition;

            if (isRepeat)
            {
                outCondition = "!(" + this.xpathBuilder.Build(groupActivity.RepeatCondition) + ")";
            }
            else
            {
                outCondition = this.xpathBuilder.Build(groupActivity.RepeatCondition);
            }

            var whileLoop = new CodeIterationStatement(
                new CodeSnippetStatement(string.Empty),
                new CodeSnippetExpression(outCondition),
                new CodeSnippetStatement(string.Empty),
                coreOfTheLoop);

            return(whileLoop);
        }
Example #7
0
        private CodeIterationStatement GenerateForLoop(GroupActivity groupActivity)
        {
            var coreGroupMethodStatement = new CodeStatementCollection();

            // put the current element in the declare variable
            // TODO convert the $Variable in variable like in Xpath
            var iterationElementSlotDeclaration = new CodeVariableDeclarationStatement("var", groupActivity.IterationElementSlot, new CodeVariableReferenceExpression(this.xpathBuilder.Build(groupActivity.Over) + "[" + groupActivity.IndexSlot + "]"));

            coreGroupMethodStatement.Add(iterationElementSlotDeclaration);

            // Get the core loop code
            coreGroupMethodStatement.AddRange(this.GenerateCoreGroupMethod(groupActivity));
            var coreOfTheLoop = new CodeStatement[coreGroupMethodStatement.Count];

            coreGroupMethodStatement.CopyTo(coreOfTheLoop, 0);

            // put it then in the loop
            var forLoop = new CodeIterationStatement(
                new CodeVariableDeclarationStatement(typeof(int), groupActivity.IndexSlot, new CodePrimitiveExpression(0)),
                new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression(groupActivity.IndexSlot), CodeBinaryOperatorType.LessThan, new CodeVariableReferenceExpression(this.xpathBuilder.Build(groupActivity.Over) + ".Length")),
                new CodeAssignStatement(new CodeVariableReferenceExpression(groupActivity.IndexSlot), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression(groupActivity.IndexSlot), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))),
                coreOfTheLoop);

            return(forLoop);
        }
        public CodeStatement[] ToCodeDomArray()
        {
            var col = new CodeStatementCollection();

            ToCodeDom(col);

            CodeStatement[] sts = new CodeStatement[col.Count];
            col.CopyTo(sts, 0);

            return(sts);
        }
Example #9
0
        /// <summary>
        /// Transform CodeStatementCollection into CodeStatement[]
        /// </summary>
        /// <param name="collection">The collection.</param>
        /// <returns>array of CodeStatement</returns>
        internal static CodeStatement[] ToArray(this CodeStatementCollection collection)
        {
            CodeStatement[] cdst = null;
            if (collection != null)
            {
                cdst = new CodeStatement[collection.Count];
                collection.CopyTo(cdst, 0);
            }

            return(cdst);
        }
Example #10
0
        public void Constructor1_Deny_Unrestricted()
        {
            CodeStatementCollection coll = new CodeStatementCollection(array);

            coll.CopyTo(array, 0);
            Assert.AreEqual(1, coll.Add(cs), "Add");
            Assert.AreSame(cs, coll[0], "this[int]");
            coll.AddRange(array);
            coll.AddRange(coll);
            Assert.IsTrue(coll.Contains(cs), "Contains");
            Assert.AreEqual(0, coll.IndexOf(cs), "IndexOf");
            coll.Insert(0, cs);
            coll.Remove(cs);
        }
        private IEnumerable <CodeStatement> GetPathTraversalStatements()
        {
            string exp = "";
            IList <AggregateExpressionPathItem> pathItems
                = ExpressionParser.BuildAggregatePathItem(m_contexts[0].Descriptor, m_contexts[0].Member);

            foreach (AggregateExpressionPathItem pathItem in pathItems)
            {
                if (pathItem.IsCollection)
                {
                    exp += string.Format("foreach({0} {1} in {2}.{3})",
                                         TypeHelper.GetTypeDefinition(pathItem.Type),
                                         pathItem.Object,
                                         pathItem.Target,
                                         pathItem.Expression);
                }
            }

            exp += Environment.NewLine + "\t\t\t\t{" + Environment.NewLine;
            foreach (AggregateFunctionContext context in m_contexts)
            {
                IEnumerable <string> itemExpressions = context.Generator.GetIterationStatements(context, context.PathItems);
                foreach (string itemExpression in itemExpressions)
                {
                    exp += "\t\t\t\t\t";
                    exp += itemExpression;
                    if (!exp.EndsWith(";"))
                    {
                        exp += ";";
                    }
                    exp += Environment.NewLine;                     // todo: smarter way
                }
            }
            exp += "\t\t\t\t}";

            CodeConditionStatement ifStatement = new CodeConditionStatement(
                new CodeSnippetExpression(pathItems[0].Target + "." + pathItems[0].Expression + " != null"),
                new CodeStatement[] { new CodeExpressionStatement(new CodeSnippetExpression(exp)) },
                new CodeStatement[0]);


            CodeStatementCollection statements = new CodeStatementCollection();

            statements.Add(ifStatement);

            CodeStatement[] arr = new CodeStatement[statements.Count];
            statements.CopyTo(arr, 0);
            return(arr);
        }
        /// <summary>
        /// Creates the method that is the starting point for the document creation.
        /// </summary>
        /// <param name="dataTransform">Describes how to create a document from an abstract data model.</param>
        public DataTransformBuildViewMethod(DataTransform dataTransform)
        {
            //		/// <summary>
            //		/// Builds the root of the document.
            //		/// </summary>
            //		/// <returns>The root table of the document</returns>
            //		public override MarkThree.Forms.ViewerTable BuildView()
            //		{
            this.Comments.Add(new CodeCommentStatement("<summary>", true));
            this.Comments.Add(new CodeCommentStatement("Builds the root of the document.", true));
            this.Comments.Add(new CodeCommentStatement("</summary>", true));
            this.Comments.Add(new CodeCommentStatement("<returns>The root table of the document</returns>", true));
            this.Attributes = MemberAttributes.Public | MemberAttributes.Override;
            this.ReturnType = new CodeTypeReference(typeof(ViewerTable));
            this.Name       = "BuildView";

            //			// This will be the document root.
            //			MarkThree.Forms.ViewerTable viewerTable = new MarkThree.Forms.ViewerTable();
            this.Statements.Add(new CodeCommentStatement("This will be the document root."));
            this.Statements.Add(new CodeVariableDeclarationStatement(typeof(ViewerTable), "viewerTable", new CodeObjectCreateExpression(typeof(ViewerTable))));

            //			try
            //			{
            //				// Prevent the data model from being modified while the document is created.
            //				SimulatedDatabase.Lock.AcquireReaderLock(System.Threading.Timeout.Infinite);
            CodeStatementCollection tryStatementCollection = new CodeStatementCollection();

            tryStatementCollection.Add(new CodeCommentStatement("Prevent the data model from being modified while the document is created."));
            foreach (DataTransform.LockNode lockNode in dataTransform.Locks)
            {
                tryStatementCollection.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(lockNode.Lock), "AcquireReaderLock", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(System.Threading.Timeout)), "Infinite")));
            }
            //				// Call each of the templates that match the document root.
            //				this.SlashTemplate(viewerTable, this.documentViewer.constantRow);
            //			}
            tryStatementCollection.Add(new CodeCommentStatement("Call each of the templates that match the document root."));
            foreach (DataTransform.TemplateNode templateNode in dataTransform.Templates)
            {
                if (templateNode.Match.StartsWith("/"))
                {
                    string methodName = string.Format("{0}Template", templateNode.Match.Replace("/", "Slash"));
                    tryStatementCollection.Add(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), methodName), new CodeVariableReferenceExpression("viewerTable"), new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "documentViewer"), "ConstantRow")));
                }
            }
            //			finally
            //			{
            //				// Release the locks on the document data.
            //				SimulatedDatabase.Lock.ReleaseReaderLock();
            //			}
            CodeStatementCollection finallyStatementCollection = new CodeStatementCollection();

            finallyStatementCollection.Add(new CodeCommentStatement("Release the locks on the document data."));
            foreach (DataTransform.LockNode lockNode in dataTransform.Locks)
            {
                finallyStatementCollection.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(lockNode.Lock), "ReleaseReaderLock"));
            }

            // Assemble the Try/Catch/Finally block.
            CodeStatement[] tryStatements = new CodeStatement[tryStatementCollection.Count];
            tryStatementCollection.CopyTo(tryStatements, 0);
            CodeStatement[] finallyStatements = new CodeStatement[finallyStatementCollection.Count];
            finallyStatementCollection.CopyTo(finallyStatements, 0);
            CodeCatchClause[] codeCatchClause = new CodeCatchClause[0];
            this.Statements.Add(new CodeTryCatchFinallyStatement(tryStatements, codeCatchClause, finallyStatements));

            //			// This is the final set of rows and their children that is ready to be displayed in a viewer.
            //			return viewerTable;
            this.Statements.Add(new CodeCommentStatement("This is the final set of rows and their children that is ready to be displayed in a viewer."));
            this.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("viewerTable")));
        }
Example #13
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[]", this.ServerSchema.Name, childTable.Name);
                string rowArrayVariable  = string.Format("{0}{1}Rows", Generate.CamelCase(parentTable.Name), childTable.Name);
                string rowType           = string.Format("{0}.{1}Row", this.ServerSchema.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;
                    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"))));
                    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}", this.ServerSchema.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}", this.ServerSchema.Name, childTable.Name)), "RowVersionColumn")), new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(this.ServerSchema.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));
            }
        }
Example #14
0
        // CodeStatementCollection
        public void CodeStatementCollectionSample()
        {
            //<Snippet1>
            //<Snippet2>
            // Creates an empty CodeStatementCollection.
            CodeStatementCollection collection = new CodeStatementCollection();

            //</Snippet2>

            //<Snippet3>
            // Adds a CodeStatement to the collection.
            collection.Add(new CodeCommentStatement("Test comment statement"));
            //</Snippet3>

            //<Snippet4>
            // Adds an array of CodeStatement objects to the collection.
            CodeStatement[] statements =
            {
                new CodeCommentStatement("Test comment statement"),
                new CodeCommentStatement("Test comment statement")
            };
            collection.AddRange(statements);

            // Adds a collection of CodeStatement objects to the collection.
            CodeStatement           testStatement        = new CodeCommentStatement("Test comment statement");
            CodeStatementCollection statementsCollection = new CodeStatementCollection();

            statementsCollection.Add(new CodeCommentStatement("Test comment statement"));
            statementsCollection.Add(new CodeCommentStatement("Test comment statement"));
            statementsCollection.Add(testStatement);

            collection.AddRange(statementsCollection);
            //</Snippet4>

            //<Snippet5>
            // Tests for the presence of a CodeStatement in the
            // collection, and retrieves its index if it is found.
            int itemIndex = -1;

            if (collection.Contains(testStatement))
            {
                itemIndex = collection.IndexOf(testStatement);
            }

            //</Snippet5>

            //<Snippet6>
            // Copies the contents of the collection beginning at index 0 to the specified CodeStatement array.
            // 'statements' is a CodeStatement array.
            CodeStatement[] statementArray = new CodeStatement[collection.Count];
            collection.CopyTo(statementArray, 0);
            //</Snippet6>

            //<Snippet7>
            // Retrieves the count of the items in the collection.
            int collectionCount = collection.Count;

            //</Snippet7>

            //<Snippet8>
            // Inserts a CodeStatement at index 0 of the collection.
            collection.Insert(0, new CodeCommentStatement("Test comment statement"));
            //</Snippet8>

            //<Snippet9>
            // Removes the specified CodeStatement from the collection.
            collection.Remove(testStatement);
            //</Snippet9>

            //<Snippet10>
            // Removes the CodeStatement at index 0.
            collection.RemoveAt(0);
            //</Snippet10>
            //</Snippet1>
        }
        /// <summary>
        /// Constructs the CodeDOM method used to transform abstract data into a readable document.
        /// </summary>
        /// <param name="templateNode">Contains the specification for the template.</param>
        public DataTransformTemplateMethod(DataTransform.TemplateNode templateNode)
        {
            // This is a rudimentary test for the start of the document.  The idea is to follow the XSL language where possible
            // but the rigours of an XPATH parser are beyond the scope of this function at the time of this writing.  In the future
            // it should be expanded to follow an XPATH like specification into the data model.
            bool isRootTemplate = templateNode.Match.StartsWith("/");

            // Some top-level information will be needed to construct the template, such as the class name to reference constants.
            DataTransform dataTransform = templateNode.TopLevelNode as DataTransform;

            //		/// <summary>
            //		/// Transforms a row of data into screen instructions.
            //		/// </summary>
            //		/// <param name="viewerTable">The current outline level of the document.</param>
            //		/// <param name="dataRow">The source of the data for this template.</param>
            //		public virtual void SlashTemplate(MarkThree.Forms.ViewerTable viewerTable, System.Data.DataRow dataRow)
            //		{
            this.Comments.Add(new CodeCommentStatement(@"<summary>", true));
            this.Comments.Add(new CodeCommentStatement(@"Transforms a row of data into screen instructions.", true));
            this.Comments.Add(new CodeCommentStatement(@"</summary>", true));
            this.Comments.Add(new CodeCommentStatement(@"<param name=""viewerTable"">The current outline level of the document.</param>", true));
            this.Comments.Add(new CodeCommentStatement(@"<param name=""dataRow"">The source of the data for this template.</param>", true));
            this.Name       = string.Format("{0}Template", templateNode.Match.Replace("/", "Slash"));
            this.Attributes = MemberAttributes.Public;
            this.Parameters.Add(new CodeParameterDeclarationExpression(typeof(ViewerTable), "viewerTable"));
            string rowType         = isRootTemplate ? "DataRow" : string.Format(string.Format("{0}Row", templateNode.Match));
            string rowNamespace    = isRootTemplate ? "System.Data" : dataTransform.Source;
            string rowVariableName = CamelCase.Convert(rowType);

            this.Parameters.Add(new CodeParameterDeclarationExpression(string.Format("{0}.{1}", rowNamespace, rowType), rowVariableName));

            // This will create the instructions for generating each row that appears in the template.
            int rowIndex = 0;

            foreach (DataTransform.RowNode rowNode in templateNode.Rows)
            {
                //				// Execution
                //				MarkThree.Forms.ViewerRow viewerRow0 = new MarkThree.Forms.ViewerRow();
                //				viewerRow0.Data = new object[17];
                //				viewerRow0.Tiles = new ViewerTile[17];
                //				viewerRow0.Children = new ViewerTable[2];

                string viewerRowVariableName = string.Format("viewerRow{0}", rowIndex++);
                this.Statements.Add(new CodeCommentStatement(rowNode.RowId));
                this.Statements.Add(new CodeVariableDeclarationStatement(typeof(ViewerRow), viewerRowVariableName, new CodeObjectCreateExpression(typeof(ViewerRow))));
                this.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(viewerRowVariableName), "Data"),
                                                            new CodeArrayCreateExpression(typeof(object), new CodePrimitiveExpression(dataTransform.Columns.Count))));
                this.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(viewerRowVariableName), "Tiles"),
                                                            new CodeArrayCreateExpression(typeof(ViewerTile), new CodePrimitiveExpression(dataTransform.View.Count))));
                int childTableCount = 0;
                foreach (DataTransform.ApplyTemplateNode applyTemplateNode in rowNode.ApplyTemplates)
                {
                    if (applyTemplateNode.RowFilter.ToLower() != bool.FalseString.ToLower())
                    {
                        childTableCount++;
                    }
                }
                if (childTableCount != 0)
                {
                    this.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(viewerRowVariableName), "Children"),
                                                                new CodeArrayCreateExpression(typeof(ViewerTable), new CodePrimitiveExpression(childTableCount))));
                }

                // Add in any temporary variables that need to be calculated.
                if (rowNode.ScratchList.Count != 0)
                {
                    // This will add any temporary variables needed to compute the data in a column.
                    this.Statements.Add(new CodeCommentStatement("This will calculate intermediate values used in the row."));
                    foreach (DataTransform.ScratchNode scratchNode in rowNode.ScratchList)
                    {
                        this.Statements.Add(new CodeSnippetExpression(scratchNode.Text.Trim().Trim(';')));
                    }
                }

                // This will create instructions for generating each of the tiles that appear in the row.
                this.Statements.Add(new CodeCommentStatement("Populate the data image of the row."));
                foreach (DataTransform.ColumnNode columnNode in dataTransform.Columns)
                {
                    // The 'View' describes the order of the columns.  Attempt to find the corresponding column in the row
                    // definition.  If it doesn't exist in the row, it will likely screw up the spacing of the document, but it
                    // won't crash with this check.
                    DataTransform.TileNode tileNode;
                    if (!rowNode.Tiles.TryGetValue(columnNode.ColumnId, out tileNode))
                    {
                        continue;
                    }

                    //					viewerRow0.Data[PrototypeViewer.workingStatusImageIndex] = this.variables["WorkingStatusHeaderImage"];
                    CodeExpression dataReferenceExpression = tileNode.Data != string.Empty ? (CodeExpression) new CodeSnippetExpression(tileNode.Data) :
                                                             tileNode.VariableName != string.Empty ? (CodeExpression) new CodeIndexerExpression(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "documentViewer"), "Variables"), new CodePrimitiveExpression(tileNode.VariableName)) :
                                                             (CodeExpression) new CodePrimitiveExpression(DBNull.Value);
                    this.Statements.Add(new CodeAssignStatement(new CodeIndexerExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(viewerRowVariableName), "Data"),
                                                                                          new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.DataTransformId), string.Format("{0}Index", CamelCase.Convert(columnNode.ColumnId)))),
                                                                dataReferenceExpression));
                }

                // This is a common value for all tiles in the row.
                CodeFieldReferenceExpression heightExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.DataTransformId), string.Format("{0}Height", CamelCase.Convert(rowNode.RowId)));

                // This will create instructions for generating each of the tiles that appear in the row.
                int tileIndex = 0;
                foreach (DataTransform.ColumnReferenceNode columnReferenceNode in dataTransform.View)
                {
                    // The 'View' describes the order of the columns.  Attempt to find the corresponding column in the row
                    // definition.  If it doesn't exist in the row, it will likely screw up the spacing of the document, but it
                    // won't crash with this check.
                    DataTransform.TileNode tileNode;
                    if (!rowNode.Tiles.TryGetValue(columnReferenceNode.ColumnId, out tileNode))
                    {
                        continue;
                    }

                    //					// WorkingStatusImage
                    //					MarkThree.Forms.ViewerTile viewerTile0 = this.documentViewer.GetTile(executionRow, PrototypeView.workingStatusImageIndex);
                    this.Statements.Add(new CodeCommentStatement(columnReferenceNode.ColumnId));
                    string tileVariableName = string.Format("viewerTile{0}", tileIndex);
                    string constantName     = CamelCase.Convert(columnReferenceNode.ColumnId) + "Index";
                    this.Statements.Add(new CodeVariableDeclarationStatement(typeof(ViewerTile), tileVariableName, new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "documentViewer"), "GetTile"), new CodeVariableReferenceExpression(rowVariableName), new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.DataTransformId), constantName))));

                    //					string viewerStyleId0 = "HeaderImage";
                    //					if (viewerStyleId0 != viewerTile0.ViewerStyleId)
                    //					{
                    //						viewerTile0.ViewerStyleId = viewerStyleId0;
                    //						viewerTile0.IsModified = true;
                    //					}
                    if (tileNode.StyleId != string.Empty)
                    {
                        string styleIdVariableName = string.Format("viewerStyleId{0}", tileIndex);
                        this.Statements.Add(new CodeVariableDeclarationStatement(typeof(string), styleIdVariableName, new CodeSnippetExpression(tileNode.StyleId)));
                        CodeStatement[] trueStatements0 = new CodeStatement[2];
                        trueStatements0[0] = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "ViewerStyleId"), new CodeVariableReferenceExpression(styleIdVariableName));
                        trueStatements0[1] = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "IsModified"), new CodePrimitiveExpression(true));
                        this.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression(styleIdVariableName), CodeBinaryOperatorType.IdentityInequality, new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "ViewerStyleId")), trueStatements0));
                    }

                    //					if ((viewerRow0.Data[PrototypeView.workingStatusImageOrdinal].Equals(viewerTile0.Data) != true))
                    //					{
                    //						viewerTile0.Data = viewerRow0.Data[PrototypeView.workingStatusImageOrdinal];
                    //						viewerTile0.IsModified = true;
                    //					}
                    CodeStatement[] trueStatements = new CodeStatement[2];
                    trueStatements[0] = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "Data"), new CodeIndexerExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(viewerRowVariableName), "Data"),
                                                                                                                                                                                           new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.DataTransformId), string.Format("{0}Index", CamelCase.Convert(columnReferenceNode.ColumnId)))));
                    trueStatements[1] = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "IsModified"), new CodePrimitiveExpression(true));
                    this.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeMethodInvokeExpression(new CodeIndexerExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(viewerRowVariableName), "Data"),
                                                                                                                                                             new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.DataTransformId), string.Format("{0}Index", CamelCase.Convert(columnReferenceNode.ColumnId)))), "Equals",
                                                                                                                                   new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "Data")), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(true)), trueStatements));

                    //					SizeF sizeF0 = new SizeF(PrototypeView.workingStatusImageWidth, PrototypeView.headerHeight);
                    //					if ((sizeF0 != viewerTile0.RectangleF.Size))
                    //					{
                    //						viewerTile0.RectangleF.Size = sizeF0;
                    //						viewerTile0.IsModified = true;
                    //					}
                    //CodeFieldReferenceExpression widthExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.DataTransformId), string.Format("{0}Width", CamelCase.Convert(columnReferenceNode.ColumnId)));
                    //string sizeVariableName = string.Format("sizeF{0}", tileIndex);
                    //this.Statements.Add(new CodeVariableDeclarationStatement(typeof(SizeF), sizeVariableName, new CodeObjectCreateExpression(typeof(SizeF), widthExpression, heightExpression)));
                    //CodeStatement[] trueStatements1 = new CodeStatement[2];
                    //trueStatements1[0] = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "RectangleF"), "Size"), new CodeVariableReferenceExpression(sizeVariableName));
                    //trueStatements1[1] = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "IsModified"), new CodePrimitiveExpression(true));
                    //this.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression(sizeVariableName), CodeBinaryOperatorType.IdentityInequality, new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "RectangleF"), "Size")), trueStatements1));

                    //					if ((PrototypeView.workingStatusImageWidth != viewerTile0.RectangleF.Width))
                    //					{
                    //						viewerTile0.RectangleF.Width = PrototypeView.workingStatusImageWidth;
                    //						viewerTile0.IsModified = true;
                    //					}
                    CodeFieldReferenceExpression widthExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.DataTransformId), string.Format("{0}Width", CamelCase.Convert(columnReferenceNode.ColumnId)));
                    CodeStatement[] trueStatements1 = new CodeStatement[2];
                    trueStatements1[0] = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "RectangleF"), "Width"), widthExpression);
                    trueStatements1[1] = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "IsModified"), new CodePrimitiveExpression(true));
                    this.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(widthExpression, CodeBinaryOperatorType.IdentityInequality, new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "RectangleF"), "Width")), trueStatements1));

                    //					if ((PrototypeView.headerHeight != viewerTile0.RectangleF.Height))
                    //					{
                    //						viewerTile0.RectangleF.Height = PrototypeView.headerHeight;
                    //						viewerTile0.IsModified = true;
                    //					}
                    CodeStatement[] trueStatements2 = new CodeStatement[2];
                    trueStatements2[0] = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "RectangleF"), "Height"), heightExpression);
                    trueStatements2[1] = new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "IsModified"), new CodePrimitiveExpression(true));
                    this.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(heightExpression, CodeBinaryOperatorType.IdentityInequality, new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "RectangleF"), "Height")), trueStatements2));

                    //					viewerTile0.Cursor.Width = PrototypeView.workingStatusImageWidth;
                    //					viewerTile0.Cursor.Height = 0;
                    if (tileIndex < dataTransform.View.Count - 1)
                    {
                        this.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "Cursor"), "Width"), widthExpression));
                        this.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "Cursor"), "Height"), new CodePrimitiveExpression(0.0f)));
                    }
                    else
                    {
                        CodeExpression columnWidthExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.DataTransformId), string.Format("{0}Width", CamelCase.Convert(dataTransform.View[tileIndex].Column.ColumnId)));
                        CodeExpression rowWidthExpression    = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.DataTransformId), string.Format("{0}Width", CamelCase.Convert(rowNode.RowId)));
                        this.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "Cursor"), "Width"), new CodeBinaryOperatorExpression(columnWidthExpression, CodeBinaryOperatorType.Subtract, rowWidthExpression)));
                        this.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(tileVariableName), "Cursor"), "Height"), heightExpression));
                    }

                    //					viewerRow0.Tiles[PrototypeViewer.statusImageOrdinal] = viewerTile0;
                    this.Statements.Add(new CodeAssignStatement(new CodeIndexerExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(viewerRowVariableName), "Tiles"),
                                                                                          new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.DataTransformId), string.Format("{0}Ordinal", CamelCase.Convert(columnReferenceNode.ColumnId)))),
                                                                new CodeVariableReferenceExpression(tileVariableName)));

                    // This indexer will keep the variable names distinct for each column.
                    tileIndex++;
                }

                // Each row can have one or more relationship to child rows that are specified in the 'ApplyTemplate' node.  This
                // specification works very similar to the XSL analog in that it traces through the child nodes seeing if there are
                // any templates that can be applied.
                int childIndex = 0;
                foreach (DataTransform.ApplyTemplateNode applyTemplateNode in rowNode.ApplyTemplates)
                {
                    // It's possible for debugging to include a 'False' row filter, which would remove all the children from the
                    // applied templates.  Unfortunately, an expression that always evaluates to 'False' will result in a warning
                    // about unreachable code.  This will remove the entire reference to the children when the row filter
                    // expression is 'False'.
                    if (applyTemplateNode.RowFilter.ToLower() != bool.FalseString.ToLower())
                    {
                        //						// This will add the child relations for this row to the document.
                        //						MarkThree.Forms.ViewerTable workingOrderTable = new MarkThree.Forms.ViewerTable();
                        //						for (int rowIndex = 0; (rowIndex < SimulatedDatabase.WorkingOrder.Count); rowIndex = (rowIndex + 1))
                        //						{
                        //							SimulatedDatabase.WorkingOrderRow workingOrderRow = SimulatedDatabase.WorkingOrder[rowIndex];
                        //							if (workingOrderRow.StatusCode != 6)
                        //							{
                        //								this.WorkingOrderTemplate(workingOrderTable, workingOrderRow);
                        //							}
                        //						}
                        this.Statements.Add(new CodeCommentStatement("This will add the child relations for this row to the document."));
                        string tableVariableName = string.Format("{0}Table", CamelCase.Convert(applyTemplateNode.Select));
                        this.Statements.Add(new CodeVariableDeclarationStatement(typeof(ViewerTable), tableVariableName, new CodeObjectCreateExpression(typeof(ViewerTable))));
                        CodeExpression childRows = isRootTemplate ?
                                                   (CodeExpression) new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dataTransform.Source), applyTemplateNode.Select) :
                                                   (CodeExpression) new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeArgumentReferenceExpression(rowVariableName), string.Format("Get{0}Rows", applyTemplateNode.Select)));
                        string                  countingMember          = isRootTemplate ? "Count" : "Length";
                        CodeStatement           initializationStatement = new CodeVariableDeclarationStatement(typeof(int), "rowIndex", new CodePrimitiveExpression(0));
                        CodeExpression          testExpression          = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("rowIndex"), CodeBinaryOperatorType.LessThan, new CodeFieldReferenceExpression(childRows, countingMember));
                        CodeStatement           incrementStatement      = new CodeAssignStatement(new CodeVariableReferenceExpression("rowIndex"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("rowIndex"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1)));
                        CodeStatementCollection iterationBody           = new CodeStatementCollection();
                        string                  childRowName            = CamelCase.Convert(string.Format("{0}Row", applyTemplateNode.Select));
                        iterationBody.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(string.Format("{0}.{1}Row", dataTransform.Source, applyTemplateNode.Select)), childRowName, new CodeIndexerExpression(childRows, new CodeVariableReferenceExpression("rowIndex"))));
                        if (applyTemplateNode.RowFilter == string.Empty)
                        {
                            iterationBody.Add(new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), string.Format("{0}Template", applyTemplateNode.Select), new CodeVariableReferenceExpression(tableVariableName), new CodeVariableReferenceExpression(childRowName))));
                        }
                        else
                        {
                            iterationBody.Add(new CodeConditionStatement(new CodeSnippetExpression(applyTemplateNode.RowFilter), new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), string.Format("{0}Template", applyTemplateNode.Select), new CodeVariableReferenceExpression(tableVariableName), new CodeVariableReferenceExpression(childRowName)))));
                        }
                        CodeStatement[] iterationArray = new CodeStatement[iterationBody.Count];
                        iterationBody.CopyTo(iterationArray, 0);
                        this.Statements.Add(new CodeIterationStatement(initializationStatement, testExpression, incrementStatement, iterationArray));
                        if (applyTemplateNode.Sorts.Count > 0)
                        {
                            this.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(tableVariableName), "Sort", new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), string.Format("{0}RowComparer", CamelCase.Convert(applyTemplateNode.Select)))));
                        }

                        //						// The child table is associated to the parent row here.
                        //						viewerRow0.Children[0] = workingOrderTable;
                        this.Statements.Add(new CodeCommentStatement("The child table is associated to the parent row here."));
                        this.Statements.Add(new CodeAssignStatement(new CodeIndexerExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression(viewerRowVariableName), "Children"), new CodePrimitiveExpression(childIndex)), new CodeVariableReferenceExpression(tableVariableName)));
                    }
                }

                //				// The child rows are added to the parent tables when they've been built.  In this way the hierarchical document is
                //				// built.
                //				viewerTable.Add(viewerRow0);
                this.Statements.Add(new CodeCommentStatement("The child rows are added to the parent tables when they've been built.  In this way the hierarchical document is"));
                this.Statements.Add(new CodeCommentStatement("built."));
                this.Statements.Add(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("viewerTable"), "Add", new CodeVariableReferenceExpression(viewerRowVariableName)));
            }
        }
Example #16
0
        /// <summary>
        /// Construct a CodeDOM that will find a record based on an external identifier and a configuration.
        /// </summary>
        public FindOptionalKey(ExternalInterfaceSchema ExternalInterfaceSchema, MiddleTierTable middleTierTable)
            : base(ExternalInterfaceSchema, middleTierTable)
        {
            // These are shorthand notations for values that are use often to construct the tables:
            string tableVariable  = string.Format("{0}Table", this.MiddleTierTable.ElementTable.Name[0].ToString().ToLower() + this.MiddleTierTable.ElementTable.Name.Remove(0, 1));
            string primaryKeyName = this.ExternalInterfaceSchema.RemoveXPath(this.MiddleTierTable.PrimaryKey.Fields[0]);

            // Find the primary column element.
            XmlSchemaElement primaryColumnElement = null;

            foreach (XmlSchemaElement xmlSchemaElement in this.MiddleTierTable.ElementColumns)
            {
                if (xmlSchemaElement.Name == this.ExternalInterfaceSchema.RemoveXPath(this.MiddleTierTable.PrimaryKey.Fields[0]))
                {
                    primaryColumnElement = xmlSchemaElement;
                }
            }

            // Method Header:
            //        /// <summary>Finds a a Algorithm record using a configuration and an external identifier.</summary>
            //        /// <param name="configurationId">Specified which mappings (user id columns) to use when looking up external identifiers.</param>
            //        /// <param name="externalId">The external (user supplied) identifier for the record.</param>
            //        public static object FindOptionalKey(string configurationId, object externalId)
            //        {
            this.Comments.Add(new CodeCommentStatement(string.Format("<summary>Finds a a {0} record using a configuration and an external identifier.</summary>", this.MiddleTierTable.ElementTable.Name), true));
            this.Comments.Add(new CodeCommentStatement(@"<param name=""configurationId"">Specified which mappings (user id columns) to use when looking up external identifiers.</param>", true));
            this.Comments.Add(new CodeCommentStatement(@"<param name=""externalId"">The external (user supplied) identifier for the record.</param>", true));
            this.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
            this.ReturnType = new CodeTypeReference(typeof(object));
            this.Name       = "FindOptionalKey";
            this.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "configurationId"));
            this.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "parameterId"));
            this.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "externalId"));

            //            // Look up the internal identifier using the the configuration to specify which ExternalId column to use as an index.
            //            object internalId = null;
            //            if ((externalId != null))
            //            {
            //                internalId = Algorithm.FindKey(configurationId, ((string)(externalId)));
            //                if ((((int)(internalId)) == -1))
            //                {
            //                    throw new Exception(string.Format("The Algorithm table does not have a record identified by \'{0}\'", externalId));
            //                }
            //            }
            Type           returnType  = ((XmlSchemaDatatype)primaryColumnElement.ElementType).ValueType;
            CodeExpression returnValue = returnType == typeof(int) ?
                                         new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(int)), "MinValue") :
                                         new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(string)), "Empty");

            this.Statements.Add(new CodeCommentStatement("Look up the internal identifier using the the configuration to specify which ExternalId column to use as an index."));
            this.Statements.Add(new CodeVariableDeclarationStatement(typeof(object), "internalId", new CodePrimitiveExpression(null)));
            CodeStatementCollection trueStatements = new CodeStatementCollection();

            trueStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("internalId"), new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(this.MiddleTierTable.ElementTable.Name), "FindKey", new CodeExpression[] { new CodeArgumentReferenceExpression("configurationId"), new CodeArgumentReferenceExpression("parameterId"), new CodeCastExpression(typeof(string), new CodeArgumentReferenceExpression("externalId")) })));
            CodeExpression[] exceptionVariables = new CodeExpression[] { new CodePrimitiveExpression(string.Format("The {0} table does not have a record identified by '{1}'", this.MiddleTierTable.ElementTable.Name, "{0}")), new CodeArgumentReferenceExpression("externalId") };
            trueStatements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeCastExpression(returnType, new CodeVariableReferenceExpression("internalId")), CodeBinaryOperatorType.IdentityEquality, returnValue), new CodeThrowExceptionStatement(new CodeObjectCreateExpression("Exception", new CodeExpression[] { new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(string)), "Format", exceptionVariables) }))));
            CodeStatement[] trueStatementArray = new CodeStatement[trueStatements.Count];
            trueStatements.CopyTo(trueStatementArray, 0);
            this.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression("externalId"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)), trueStatementArray));

            //            // Return the internal identifier.
            //            return internalId;
            this.Statements.Add(new CodeCommentStatement("Return the internal identifier."));
            this.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("internalId")));
        }
Example #17
0
        /// <summary>
        /// Construct a CodeDOM that will find a record based on an external identifier and a configuration.
        /// </summary>
        public GetExternalKeyIndex(ExternalInterfaceSchema ExternalInterfaceSchema, MiddleTierTable middleTierTable) : base(ExternalInterfaceSchema, middleTierTable)
        {
            // These are shorthand notations for values that are use often to construct the tables:
            string tableVariable  = string.Format("{0}Table", this.MiddleTierTable.ElementTable.Name[0].ToString().ToLower() + this.MiddleTierTable.ElementTable.Name.Remove(0, 1));
            string primaryKeyName = this.ExternalInterfaceSchema.RemoveXPath(this.MiddleTierTable.PrimaryKey.Fields[0]);

            // Method Header:
            //        /// <summary>Finds a a Algorithm record using a configuration and an external identifier.</summary>
            //        /// <param name="configurationId">Specified which mappings (user id columns) to use when looking up external identifiers.</param>
            //        /// <param name="externalId">The external (user supplied) identifier for the record.</param>
            //        public static int GetExternalKeyIndex(string configurationId, string parameterId, string externalId)
            //        {


            // Method Header:
            ///       /// <summary>Calculates which index to uses when searching for external identifiers.</summary>
            ///       /// <param name="configurationId">Specified which mappings (user id columns) to use when looking up external identifiers.</param>
            ///       /// <param name="parameterId">The name of the parameter as specified in the configuration table.</param>
            ///       /// <returns>An index into the array of keys to search for an external identifier.</returns>
            this.Comments.Add(new CodeCommentStatement(@"<summary>Calculates which index to uses when searching for external identifiers.</summary>", true));
            this.Comments.Add(new CodeCommentStatement(@"<param name=""configurationId"">Specified which mappings (user id columns) to use when looking up external identifiers.</param>", true));
            this.Comments.Add(new CodeCommentStatement(@"<param name=""parameterId"">The name of the parameter as specified in the configuration table.</param>", true));
            this.Comments.Add(new CodeCommentStatement(@"<returns>An index into the array of keys to search for an external identifier.</returns>", true));
            this.Attributes = MemberAttributes.Public | MemberAttributes.Final | MemberAttributes.Static;
            this.ReturnType = new CodeTypeReference(typeof(int));
            this.Name       = "GetExternalKeyIndex";
            this.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "configurationId"));
            this.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "parameterId"));

            // Translate the configuration identifier into an index into the user Id columns:
            //            // Translate the configurationId and the predefined parameter name into an index into the array of user ids.  The index
            //            // is where we expect to find the identifier.  That is, an index of 1 will guide the lookup logic to use the external
            //            // identifiers found in the 'ExternalId1' column.
            //            ServerMarketData.ConfigurationRow configurationRow = ServerMarketData.Configuration.FindByConfigurationIdParameterId(configurationId, "AlgorithmId");
            //            int externalKeyIndex = 0;
            //            if ((configurationRow != null))
            //            {
            //                externalKeyIndex = configurationRow.Index;
            //            }
            this.Statements.Add(new CodeCommentStatement("Translate the configurationId and the predefined parameter name into an index into the array of user ids.  The index"));
            this.Statements.Add(new CodeCommentStatement("is where we expect to find the identifier.  That is, an index of 1 will guide the lookup logic to use the external"));
            this.Statements.Add(new CodeCommentStatement("identifiers found in the 'ExternalId1' column."));
            this.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "externalKeyIndex", new CodePrimitiveExpression(0)));
            CodeStatementCollection trueStatements = new CodeStatementCollection();

            trueStatements.Add(new CodeCommentStatement("Attempt to find a external column specification for the given configuration and parameter.  This record tells us"));
            trueStatements.Add(new CodeCommentStatement("which column to use in the array of external columns."));
            trueStatements.Add(new CodeVariableDeclarationStatement(string.Format("{0}.ConfigurationRow", this.ExternalInterfaceSchema.DataSetName), "configurationRow", new CodeMethodInvokeExpression(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(this.ExternalInterfaceSchema.DataSetName), "Configuration"), "FindByConfigurationIdParameterId", new CodeExpression[] { new CodeCastExpression(typeof(string), new CodeArgumentReferenceExpression("configurationId")), new CodeArgumentReferenceExpression("parameterId") })));
            CodeExpression[] exceptionVariables = new CodeExpression[] { new CodePrimitiveExpression(@"The parameter {1} isn't defined for configuration '{0}'"), new CodeArgumentReferenceExpression("configurationId"), new CodeArgumentReferenceExpression("parameterId") };
            CodeStatement    externalKeyIndex   = new CodeAssignStatement(new CodeVariableReferenceExpression("externalKeyIndex"), new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("configurationRow"), "ColumnIndex"));

            trueStatements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("configurationRow"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)), externalKeyIndex));
            CodeStatement[] trueStatementBlock = new CodeStatement[trueStatements.Count];
            trueStatements.CopyTo(trueStatementBlock, 0);
            this.Statements.Add(new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression("configurationId"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)), trueStatementBlock));

            //            // This is the index into the array of keys to be used when searching for an external identifier.
            //            return externalKeyIndex;
            this.Statements.Add(new CodeCommentStatement("This is the index into the array of keys to be used when searching for an external identifier."));
            this.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("externalKeyIndex")));
        }