Exemplo n.º 1
0
 public CodeForStatement(CodeExpression init, CodeExpression condition,CodeExpression next, CodeStatement statement)
 {
   Init = init;
   Condition = condition;
   Next = next;
   Statement = statement;
 }
Exemplo n.º 2
0
		public void Ctor_String_CodeTypeReference_ParamsCodeStatement(string localName, CodeTypeReference catchExceptionType, CodeStatement[] statements)
		{
			var catchClause = new CodeCatchClause(localName, catchExceptionType, statements);
			Assert.Equal(localName ?? string.Empty, catchClause.LocalName);
			Assert.Equal((catchExceptionType ?? new CodeTypeReference(typeof(Exception))).BaseType, catchClause.CatchExceptionType.BaseType);
			Assert.Equal(statements, catchClause.Statements.Cast<CodeStatement>());
		}
Exemplo n.º 3
0
 public CodeIterationStatement(CodeStatement initStatement, CodeExpression testExpression, CodeStatement incrementStatement, params CodeStatement[] statements)
 {
     InitStatement = initStatement;
     TestExpression = testExpression;
     IncrementStatement = incrementStatement;
     Statements.AddRange(statements);
 }
        private static double AddChildItems(string name, CodeStatement<TSqlStatement> sqlModule, CodeCoverageStore store, double parentStatements, string file, TreeViewItem child, ref double parentCoveredStatements, ref double childStatements, ref double childCoveredStatements)
        {
            if (string.IsNullOrEmpty(name))
                return parentStatements;

            //need to enumerate the statement tree to find statements (flatten tree - have probably already done it?? maybe can just use a visitor - see count lines of code surely?)
            var script = File.ReadAllText(sqlModule.FileName);
            if (script.Length < sqlModule.Length)
            {
                //bad tings....
                return parentStatements;
            }

            IList<ParseError> errors;
            var statementNodes = ScriptDom.GetStatements(script.Substring(sqlModule.StartLocation, sqlModule.Length), out errors);

            if (errors != null && errors.Count > 1)
            {
                //more bad tings
                return parentStatements;
            }

            var coveredStatements = store.GetCoveredStatements(name, sqlModule.FileName);

            var beginEndBlocks = statementNodes.Count(p => p.GetType() == typeof (BeginEndBlockStatement));

            var statementCount = statementNodes.Count - 1 - beginEndBlocks;

            parentStatements += statementCount;
            parentCoveredStatements += coveredStatements?.Count ?? 0;

            childStatements += statementCount;
            childCoveredStatements += coveredStatements?.Count ?? 0;
                                                                                //if the file has changed we can't get anything useful from it...
            if (coveredStatements != null && coveredStatements.Count > 0 && !coveredStatements.Any(p => p.TimeStamp < File.GetLastWriteTimeUtc(file)))
            {
                var coveragePercent = ((double) coveredStatements.Count/(double) statementCount)*100;

                var label = new LabelWithProgressIndicator(string.Format("{0} - {1}% ({2} / {3})", name, coveragePercent, coveredStatements.Count, statementCount), coveragePercent, file);
                label.Configure();

                child.Items.Add(label);
            }
            else
            {
                var label = new LabelWithProgressIndicator(name + " - 0 %", 0, file);
                label.Configure();
                child.Items.Add(label);
            }
            return parentStatements;
        }
Exemplo n.º 5
0
 public virtual void GenerateCodeFromStatement(CodeStatement statement, TextWriter writer, CodeGeneratorOptions options)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 6
0
        private void ValidateStatement(CodeStatement e)
        {
            ValidateCodeDirectives(e.StartDirectives);
            ValidateCodeDirectives(e.EndDirectives);

            if (e is CodeCommentStatement)
            {
                ValidateCommentStatement((CodeCommentStatement)e);
            }
            else if (e is CodeMethodReturnStatement)
            {
                ValidateMethodReturnStatement((CodeMethodReturnStatement)e);
            }
            else if (e is CodeConditionStatement)
            {
                ValidateConditionStatement((CodeConditionStatement)e);
            }
            else if (e is CodeTryCatchFinallyStatement)
            {
                ValidateTryCatchFinallyStatement((CodeTryCatchFinallyStatement)e);
            }
            else if (e is CodeAssignStatement)
            {
                ValidateAssignStatement((CodeAssignStatement)e);
            }
            else if (e is CodeExpressionStatement)
            {
                ValidateExpressionStatement((CodeExpressionStatement)e);
            }
            else if (e is CodeIterationStatement)
            {
                ValidateIterationStatement((CodeIterationStatement)e);
            }
            else if (e is CodeThrowExceptionStatement)
            {
                ValidateThrowExceptionStatement((CodeThrowExceptionStatement)e);
            }
            else if (e is CodeSnippetStatement)
            {
                ValidateSnippetStatement((CodeSnippetStatement)e);
            }
            else if (e is CodeVariableDeclarationStatement)
            {
                ValidateVariableDeclarationStatement((CodeVariableDeclarationStatement)e);
            }
            else if (e is CodeAttachEventStatement)
            {
                ValidateAttachEventStatement((CodeAttachEventStatement)e);
            }
            else if (e is CodeRemoveEventStatement)
            {
                ValidateRemoveEventStatement((CodeRemoveEventStatement)e);
            }
            else if (e is CodeGotoStatement)
            {
                ValidateGotoStatement((CodeGotoStatement)e);
            }
            else if (e is CodeLabeledStatement)
            {
                ValidateLabeledStatement((CodeLabeledStatement)e);
            }
            else
            {
                throw new ArgumentException(SR.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e));
            }
        }
Exemplo n.º 7
0
 /// <summary>
 ///     Determines which statement group the given statement should belong to.  The expression parameter
 ///     is an expression that the statement has been reduced to, and targetType represents the type
 ///     of this statement.  This method returns the name of the component this statement should be grouped
 ///     with.
 /// </summary>
 public virtual string GetTargetComponentName(CodeStatement statement, CodeExpression expression,
                                              Type targetType)
 {
     throw new NotImplementedException(SR.NotImplementedByDesign);
 }
Exemplo n.º 8
0
 public CodeIfStatement(CodeExpression condition, CodeStatement statement, CodeStatement elseStatement)
 {
   Condition = condition;
   Statement = statement;
   ElseStatement = elseStatement;
 }
	public CodeConditionStatement(CodeExpression condition, CodeStatement[] trueStatements, CodeStatement[] falseStatements) {}
Exemplo n.º 10
0
        private void ValidateStatement(CodeStatement e)
        {
            ValidateCodeDirectives(e.StartDirectives);
            ValidateCodeDirectives(e.EndDirectives);

            if (e is CodeCommentStatement)
            {
                ValidateCommentStatement((CodeCommentStatement)e);
            }
            else if (e is CodeMethodReturnStatement)
            {
                ValidateMethodReturnStatement((CodeMethodReturnStatement)e);
            }
            else if (e is CodeConditionStatement)
            {
                ValidateConditionStatement((CodeConditionStatement)e);
            }
            else if (e is CodeTryCatchFinallyStatement)
            {
                ValidateTryCatchFinallyStatement((CodeTryCatchFinallyStatement)e);
            }
            else if (e is CodeAssignStatement)
            {
                ValidateAssignStatement((CodeAssignStatement)e);
            }
            else if (e is CodeExpressionStatement)
            {
                ValidateExpressionStatement((CodeExpressionStatement)e);
            }
            else if (e is CodeIterationStatement)
            {
                ValidateIterationStatement((CodeIterationStatement)e);
            }
            else if (e is CodeThrowExceptionStatement)
            {
                ValidateThrowExceptionStatement((CodeThrowExceptionStatement)e);
            }
            else if (e is CodeSnippetStatement)
            {
                ValidateSnippetStatement((CodeSnippetStatement)e);
            }
            else if (e is CodeVariableDeclarationStatement)
            {
                ValidateVariableDeclarationStatement((CodeVariableDeclarationStatement)e);
            }
            else if (e is CodeAttachEventStatement)
            {
                ValidateAttachEventStatement((CodeAttachEventStatement)e);
            }
            else if (e is CodeRemoveEventStatement)
            {
                ValidateRemoveEventStatement((CodeRemoveEventStatement)e);
            }
            else if (e is CodeGotoStatement)
            {
                ValidateGotoStatement((CodeGotoStatement)e);
            }
            else if (e is CodeLabeledStatement)
            {
                ValidateLabeledStatement((CodeLabeledStatement)e);
            }
            else
            {
                throw new ArgumentException(SR.GetString(SR.InvalidElementType, e.GetType().FullName), "e");
            }
        }
	public CodeLabeledStatement(string label, CodeStatement statement) {}
Exemplo n.º 12
0
        public void GenerateCodeFromStatement(CodeStatement e, TextWriter w, CodeGeneratorOptions o)
        {
            bool setLocal = false;
            if (output != null && w != output.InnerWriter)
            {
                throw new InvalidOperationException("Wrong output writer");
            }
            if (output == null)
            {
                setLocal = true;
                options = (o == null) ? new CodeGeneratorOptions() : o;
                output = new IndentedTextWriter(w, options.IndentString);
            }

            try
            {
                GenerateStatement(e);
            }
            finally
            {
                if (setLocal)
                {
                    output = null;
                    options = null;
                }
            }
        }
Exemplo n.º 13
0
 // Methods
 public int Add(CodeStatement value)
 {
 }
Exemplo n.º 14
0
 /// <summary>
 /// Create a instance cast expression
 /// </summary>
 private CodeStatement CreateCastTryCatch(Type toType, CodeExpression targetObject, CodeExpression sourceObject, CodeStatement failExpression)
 {
     return(new CodeTryCatchFinallyStatement(
                new CodeStatement[] {
         new CodeAssignStatement(targetObject, new CodeCastExpression(new CodeTypeReference(toType), sourceObject)),
     },
                new CodeCatchClause[] {
         new CodeCatchClause("e", new CodeTypeReference(typeof(Exception)),
                             new CodeExpressionStatement(new CodeMethodInvokeExpression(s_traceError, this.CreateStringFormatExpression("Casting Error: {0}", new CodeVariableReferenceExpression("e")))),
                             failExpression)
     }));
 }
Exemplo n.º 15
0
        private void GenerateStatement(CodeStatement e)
        {
            if (e is CodeCommentStatement)
            {
                GenerateCommentStatement((CodeCommentStatement)e);
            }
            else if (e is CodeMethodReturnStatement)
            {
                GenerateMethodReturnStatement((CodeMethodReturnStatement)e);
            }
            else if (e is CodeConditionStatement)
            {
                GenerateConditionStatement((CodeConditionStatement)e);
            }
            else if (e is CodeTryCatchFinallyStatement)
            {
                GenerateTryCatchFinallyStatement((CodeTryCatchFinallyStatement)e);
            }
            else if (e is CodeAssignStatement)
            {
                GenerateAssignStatement((CodeAssignStatement)e);
            }
            else if (e is CodeExpressionStatement)
            {
                GenerateExpressionStatement((CodeExpressionStatement)e);
            }
            else if (e is CodeIterationStatement)
            {
                GenerateIterationStatement((CodeIterationStatement)e);
            }
            else if (e is CodeThrowExceptionStatement)
            {
                GenerateThrowExceptionStatement((CodeThrowExceptionStatement)e);
            }
            else if (e is CodeSnippetStatement)
            {
                // Don't indent snippet statements, in order to preserve the column
                // information from the original code.  This improves the debugging
                // experience.
                int savedIndent = Indent;
                Indent = 0;

                GenerateSnippetStatement((CodeSnippetStatement)e);

                // Restore the indent
                Indent = savedIndent;
            }
            else if (e is CodeVariableDeclarationStatement)
            {
                GenerateVariableDeclarationStatement((CodeVariableDeclarationStatement)e);
            }
            else if (e is CodeAttachEventStatement)
            {
                GenerateAttachEventStatement((CodeAttachEventStatement)e);
            }
            else if (e is CodeRemoveEventStatement)
            {
                GenerateRemoveEventStatement((CodeRemoveEventStatement)e);
            }
            else if (e is CodeLabeledStatement)
            {
                GenerateLabeledStatement((CodeLabeledStatement)e);
            }
            else
            {
                throw new ArgumentException("Invalid element type: " + e.GetType().FullName, "e");
            }
        }
Exemplo n.º 16
0
 public void Ctor_NullObjectInStatements_ThrowsArgumentNullException()
 {
     CodeStatement[] statements = new CodeStatement[] { null };
     AssertExtensions.Throws <ArgumentNullException>("value", () => new CodeCatchClause("name", new CodeTypeReference(typeof(void)), statements));
 }
Exemplo n.º 17
0
 public void GenerateCodeFromStatement(CodeStatement e, TextWriter w, CodeGeneratorOptions o)
 {
     throw new BadImageFormatException("6");
 }
 public CodeTryCatchFinallyStatement(CodeStatement[] tryStatements, CodeCatchClause[] catchClauses, CodeStatement[] finallyStatements)
 {
     TryStatements.AddRange(tryStatements);
     CatchClauses.AddRange(catchClauses);
     FinallyStatements.AddRange(finallyStatements);
 }
Exemplo n.º 19
0
        public static CodeStatement CreateTryCatchStatement(CodeTypeDeclaration classType, CodeStatement statement, CodeGenerationInfo generationInfo)
        {
            var tryStatement = new CodeTryCatchFinallyStatement();

            tryStatement.TryStatements.Add(statement);

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

            var conditionStatement = new CodeConditionStatement
            {
                Condition = new CodeBinaryOperatorExpression(methodInvokeExp, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(false))
            };

            conditionStatement.TrueStatements.Add(new CodeThrowExceptionStatement(new CodeVariableReferenceExpression("e")));

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

            return(tryStatement);
        }
Exemplo n.º 20
0
 public bool Contains(CodeStatement value)
 {
 }
Exemplo n.º 21
0
        public static CodeStatement CreateTryCatchStatement(CodeTypeDeclaration classType, CodeStatement statement, bool isDevmode)
        {
            if (isDevmode == false)
            {
                return(statement);
            }

            var tryStatement = new CodeTryCatchFinallyStatement();

            tryStatement.TryStatements.Add(statement);

            var catchClause     = new CodeCatchClause("e");
            var methodRefExp    = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "onErrorOccured");
            var methodInvokeExp = new CodeMethodInvokeExpression(methodRefExp, new CodeVariableReferenceExpression("e"));

            var conditionStatement = new CodeConditionStatement();

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

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

            return(tryStatement);
        }
Exemplo n.º 22
0
 public int IndexOf(CodeStatement value)
 {
 }
Exemplo n.º 23
0
		public void Ctor_NullObjectInStatements_ThrowsArgumentNullException()
		{
			CodeStatement[] statements = new CodeStatement[] { null };
			Assert.Throws<ArgumentNullException>("value", () => new CodeCatchClause("name", new CodeTypeReference(typeof(void)), statements));
		}
Exemplo n.º 24
0
 public void Insert(int index, CodeStatement value)
 {
 }
Exemplo n.º 25
0
	// Generate code for a statement.
	protected void GenerateStatement(CodeStatement e)
			{
				LinePragmaStart(e.LinePragma);
				if(e is CodeAttachEventStatement)
				{
					GenerateAttachEventStatement
						((CodeAttachEventStatement)e);
				}
				else if(e is CodeCommentStatement)
				{
					GenerateCommentStatement
						((CodeCommentStatement)e);
				}
				else if(e is CodeConditionStatement)
				{
					GenerateConditionStatement
						((CodeConditionStatement)e);
				}
				else if(e is CodeRemoveEventStatement)
				{
					GenerateRemoveEventStatement
						((CodeRemoveEventStatement)e);
				}
				else if(e is CodeVariableDeclarationStatement)
				{
					GenerateVariableDeclarationStatement
						((CodeVariableDeclarationStatement)e);
				}
				else if(e is CodeAssignStatement)
				{
					GenerateAssignStatement
						((CodeAssignStatement)e);
				}
				else if(e is CodeExpressionStatement)
				{
					GenerateExpressionStatement
						((CodeExpressionStatement)e);
				}
				else if(e is CodeGotoStatement)
				{
					GenerateGotoStatement
						((CodeGotoStatement)e);
				}
				else if(e is CodeIterationStatement)
				{
					GenerateIterationStatement
						((CodeIterationStatement)e);
				}
				else if(e is CodeLabeledStatement)
				{
					GenerateLabeledStatement
						((CodeLabeledStatement)e);
				}
				else if(e is CodeMethodReturnStatement)
				{
					GenerateMethodReturnStatement
						((CodeMethodReturnStatement)e);
				}
				else if(e is CodeSnippetStatement)
				{
					GenerateSnippetStatement
						((CodeSnippetStatement)e);
				}
				else if(e is CodeThrowExceptionStatement)
				{
					GenerateThrowExceptionStatement
						((CodeThrowExceptionStatement)e);
				}
				else if(e is CodeTryCatchFinallyStatement)
				{
					GenerateTryCatchFinallyStatement
						((CodeTryCatchFinallyStatement)e);
				}
				else
				{
					throw new ArgumentException
						(S._("Arg_InvalidCodeDom"), "e");
				}
				LinePragmaEnd(e.LinePragma);
			}
Exemplo n.º 26
0
 public void Remove(CodeStatement value)
 {
 }
Exemplo n.º 27
0
		void ICodeGenerator.GenerateCodeFromStatement(CodeStatement statement, TextWriter output, CodeGeneratorOptions options)
		{
			InitOutput(output, options);
			GenerateStatement(statement);
		}
Exemplo n.º 28
0
 public virtual void GenerateCodeFromStatement(CodeStatement statement, TextWriter writer, CodeGeneratorOptions options) =>
     CreateGeneratorHelper().GenerateCodeFromStatement(statement, writer, options);
	public CodeCatchClause(string localName, CodeTypeReference catchExceptionType, CodeStatement[] statements) {}
Exemplo n.º 30
0
        /// <summary>
        ///  Generates methods for loading data from xml files and other types
        /// to memory
        /// </summary>

        public void LoadXml()
        {
            CodeMemberMethod LoadXmlMethod = BuildMethodSignature("LoadXml", MemberAttributes.Public, new System.Collections.Generic.List <System.Collections.Generic.KeyValuePair <string, string> >()
            {
                new System.Collections.Generic.KeyValuePair <string, string>("TableList<T>", "table")
            });

            TheType.Members.Add(LoadXmlMethod);
            CodeStatement TableNameAssignment = GetAssignment("System.String", "tableName", new CodeVariableReferenceExpression("table.Name"));

            LoadXmlMethod.Statements.Add(TableNameAssignment);
            // CodeStatement cas12 = GetMethodInvokationAssignment("string", "fileName", "string", "Format", new System.Collections.Generic.List<KeyValuePair<string, bool>>() { new KeyValuePair<string, bool>("{0}.{1}", false), new KeyValuePair<string, bool>("tableName", true), new KeyValuePair<string, bool>("table.Format", true) });
            CodeExpression FormatMethodInvokationStatement = GetMethodInvokationExpression("System.String", "Format", new System.Collections.Generic.List <KeyValuePair <string, bool> >()
            {
                new KeyValuePair <string, bool>("{0}\\\\Files\\\\{1}.{2}", false), new KeyValuePair <string, bool>(generateDirectory, false), new KeyValuePair <string, bool>("tableName", true), new KeyValuePair <string, bool>("Format", true)
            });
            CodeStatement FileNameAssignmentStatement = GetAssignment("System.String", "fileName", FormatMethodInvokationStatement);

            LoadXmlMethod.Statements.Add(FileNameAssignmentStatement);
            CodeExpression LoadMethodInvokationStatement = GetMethodInvokationExpression("XDocument", "Load", new System.Collections.Generic.List <KeyValuePair <string, bool> > {
                new KeyValuePair <string, bool>("fileName", true)
            });

            CodeStatement  XmlAssignmentStatement             = GetAssignment("XDocument", "xdTable", LoadMethodInvokationStatement);
            CodeStatement  DataElementNameAssignmentStatement = GetAssignment("System.String", "xmlDataElement", new CodePrimitiveExpression("Data"));
            CodeExpression ElementMethodInvokationExpression  = GetMethodInvokationExpression("xdTable.Root", "Element", new System.Collections.Generic.List <KeyValuePair <string, bool> >()
            {
                new KeyValuePair <string, bool>("xmlDataElement", true)
            });
            CodeStatement DataElementAssignmentStatement = GetAssignment("XElement", "xu", ElementMethodInvokationExpression);
            CodeStatement CheckThatDataExistsStatement   = GetUnoConditionIf("xu", CodeBinaryOperatorType.ValueEquality, "null", new List <CodeStatement>()
            {
                new CodeMethodReturnStatement()
            });
            CodeExpression ElementsXmlSearchExpression = GetMethodInvokationExpression("xu", "Elements", new List <KeyValuePair <string, bool> >()
            {
                new KeyValuePair <string, bool>("Elements", false)
            });
            CodeStatement  ElementsAssignmentStatement           = GetAssignment("IEnumerable<XElement>", "elements", ElementsXmlSearchExpression);
            CodeExpression ToListMethodInvokationExpression      = GetMethodInvokationExpression("elements", "ToList", new List <KeyValuePair <string, bool> >());
            CodeStatement  ElementListAssignmentStatement        = GetAssignment("List<XElement>", "lstElements", ToListMethodInvokationExpression);
            CodeStatement  CollectionAddMethodnvokationStatement = GetMethodInvokationStatement("table", "Add", new List <string>()
            {
                "xu.Elements(\"Element\")[i]"
            });

            LoadXmlMethod.Statements.Add(DataElementNameAssignmentStatement);
            LoadXmlMethod.Statements.Add(XmlAssignmentStatement);
            LoadXmlMethod.Statements.Add(DataElementAssignmentStatement);
            LoadXmlMethod.Statements.Add(ElementMethodInvokationExpression);
            LoadXmlMethod.Statements.Add(CheckThatDataExistsStatement);
            LoadXmlMethod.Statements.Add(ElementsAssignmentStatement);
            LoadXmlMethod.Statements.Add(ElementListAssignmentStatement);
            //LoadXmlMethod.Statements.Add(CollectionAddMethodnvokationStatement);
            List <CodeStatement>  lstLoadDbRecordsStatements = CreateLoadXmlStatements("lstElements", "i");
            CodeCompoundStatement LoadDbRecordCycleStatement = GetSimpleForInteger("i", new System.Collections.Generic.KeyValuePair <int, string>(0, "lstElements.Count"), 1, lstLoadDbRecordsStatements);

            LoadXmlMethod.Statements.AddRange(LoadDbRecordCycleStatement.Statements.ToArray());
            CodeMemberMethod LoadJsonMethod = BuildMethodSignature("LoadJson", MemberAttributes.Public, new System.Collections.Generic.List <System.Collections.Generic.KeyValuePair <string, string> >()
            {
                new System.Collections.Generic.KeyValuePair <string, string>("TableList<T>", "table")
            });

            TheType.Members.Add(LoadJsonMethod);
            CodeMemberMethod LoadOtherTypesMethod = BuildMethodSignature("LoadOtherTypes", MemberAttributes.Public, new System.Collections.Generic.List <System.Collections.Generic.KeyValuePair <string, string> >()
            {
                new System.Collections.Generic.KeyValuePair <string, string>("TableList<T>", "table")
            });

            TheType.Members.Add(LoadOtherTypesMethod);
        }
 internal static CodeStatement Try(CodeStatement tryStmnt, CodeCatchClause catchClause)
 {
     return(new CodeTryCatchFinallyStatement(new CodeStatement[] { tryStmnt }, new CodeCatchClause[] { catchClause }));
 }
Exemplo n.º 32
0
        /// <summary>
        /// Generating the code to load each property from xml to current record in memory(element in collection)
        /// </summary>
        /// <param name="propertyElementName">Name of variable that is collection of properties</param>
        /// <param name="indexName">Name of index for cycle(index)</param>
        /// <returns>List of load property statements(for inner for cycle)</returns>
        private List <CodeStatement> CreateLoadPropertyStatements(string propertyElementName, string indexName)
        {
            List <CodeStatement> lst = new List <CodeStatement>();
            CodeStatement        CurrentPropertyXElementAssignStatement = GetAssignment("XElement", "xeCurrentProperty", new CodeVariableReferenceExpression(string.Format("{0}[{1}]", propertyElementName, indexName)));

            lst.Add(CurrentPropertyXElementAssignStatement);

            CodeExpression GetAttributeValueInvokationExpression = GetMethodInvokationExpression("this", "GetAttribute", new System.Collections.Generic.List <KeyValuePair <string, bool> >()
            {
                new KeyValuePair <string, bool>("xeCurrentProperty", true), new KeyValuePair <string, bool>("PropertyValue", false)
            });
            CodeExpression GetAttributeNameInvokeExpression = GetMethodInvokationExpression("this", "GetAttribute", new System.Collections.Generic.List <KeyValuePair <string, bool> >()
            {
                new KeyValuePair <string, bool>("xeCurrentProperty", true), new KeyValuePair <string, bool>("PropertyName", false)
            });
            CodeStatement PropertyValueAssignStatement = GetAssignment("System.String", "propertyValue", GetAttributeValueInvokationExpression);
            CodeStatement PropertyNameAssignStatement  = GetAssignment("System.String", "propertyName", GetAttributeNameInvokeExpression);

            lst.Add(PropertyNameAssignStatement);
            lst.Add(PropertyValueAssignStatement);

            CodeExpression GetTypeInvokeExpression   = GetMethodInvokationExpression("record", "GetType", new List <KeyValuePair <string, bool> >());
            CodeStatement  RecordTypeAssignStatement = GetAssignment("Type", "recordType", GetTypeInvokeExpression);

            lst.Add(RecordTypeAssignStatement);
            CodeExpression GetPropertyInvokationExpression = GetMethodInvokationExpression("recordType", "GetProperty", new List <KeyValuePair <string, bool> >()
            {
                new KeyValuePair <string, bool>("propertyName", true)
            });
            CodeStatement CurrentPropertyAssignStatement = GetAssignment("PropertyInfo", "currentProperty", GetPropertyInvokationExpression);

            lst.Add(CurrentPropertyAssignStatement);

            CodeStatement CurrentPropertyTypeAssignStatement = GetAssignment("Type", "currentPropertyType", new CodeVariableReferenceExpression("currentProperty.PropertyType"));

            lst.Add(CurrentPropertyTypeAssignStatement);
            CodeExpression ToStringMethodInvokeExpression    = GetMethodInvokationExpression("currentPropertyType", "ToString", new List <KeyValuePair <string, bool> >());
            CodeStatement  PropertyTypeStringAssignStatement = GetAssignment("System.String", "propTypeStr", ToStringMethodInvokeExpression);
            //lst.Add(PropertyTypeStringAssignStatement);
            CodeExpression CreateInstanceInvokationExpression = GetMethodInvokationExpression("Activator", "CreateInstance", new List <KeyValuePair <string, bool> >()
            {
                new KeyValuePair <string, bool>("currentPropertyType", true), new KeyValuePair <string, bool>("propertyValue", true)
            });
            CodeStatement PropertyObjectAssignStatement = GetAssignmentWithExpression("objProperty", CreateInstanceInvokationExpression);

            CodeStatement SetValueInvokationStatement = GetMethodInvokationStatement("currentProperty", "SetValue", new List <string>()
            {
                "record", "objProperty"
            });
            CodeStatement SetValueInvokationStatement0 = GetMethodInvokationStatement("pp", "SetValue", new List <string>()
            {
                "PropertyObject", "objProperty"
            });
            //lst.Add(PropertyObjectAssignStatement);
            CodeExpression ce = GetMethodInvokationExpression("TypeDescriptor", "GetConverter", new List <CodeExpression>()
            {
                new CodeVariableReferenceExpression("currentPropertyType")
            });
            CodeStatement  cs  = GetAssignment("TypeConverter", "tcConvert", ce);
            CodeExpression ce1 = GetMethodInvokationExpression("tcConvert", "ConvertFromString", new List <CodeExpression>()
            {
                new CodeVariableReferenceExpression("propertyValue")
            });
            CodeStatement cs1 = GetAssignmentWithExpression("objProperty", ce1);
            CodeStatement cs0 = GetDeclaration("objProperty", "System.Object");

            lst.Add(cs0);
            CodeExpression cee0 = GetMethodInvokationExpression("currentProperty", "GetValue", new List <CodeExpression>()
            {
                new CodeVariableReferenceExpression("record")
            });
            CodeStatement  cse0 = GetAssignment("System.Object", "PropertyObject", cee0);
            CodeExpression cee  = GetMethodInvokationExpression("currentPropertyType", "GetProperty", new List <CodeExpression>()
            {
                new CodePrimitiveExpression("Value")
            });
            CodeStatement  cse = GetAssignment("PropertyInfo", "pp", cee);
            CodeExpression ce2 = GetMethodInvokationExpression("TypeDescriptor", "GetConverter", new List <CodeExpression>()
            {
                new CodeVariableReferenceExpression("pp.PropertyType")
            });
            CodeStatement cs2           = GetAssignment("TypeConverter", "tcConvert", ce2);
            CodeStatement cs3           = GetAssignmentWithExpression("objProperty", ce1);
            CodeStatement csIfValueType = GetUnoConditionIf("currentPropertyType.BaseType.Name", CodeBinaryOperatorType.IdentityInequality, "ValueType", false, new List <CodeStatement>()
            {
                cse0, cse, cs2, cs3, SetValueInvokationStatement0
            }, new List <CodeStatement>()
            {
                cs, cs1, SetValueInvokationStatement
            });

            lst.Add(csIfValueType);
            // lst.Add(SetValueInvokationStatement);

            return(lst);
        }
Exemplo n.º 33
0
 /// <summary>
 ///     This method deserializes a single statement.  It is equivalent of calling
 ///     DeserializeStatement, except that it returns an object instance if the
 ///     resulting statement was a variable assign statement, a variable
 ///     declaration with an init expression, or a field assign statement.
 /// </summary>
 protected object DeserializeStatementToInstance(IDesignerSerializationManager manager, CodeStatement statement)
 {
     throw new NotImplementedException(SR.NotImplementedByDesign);
 }
Exemplo n.º 34
0
        /// <summary>
        /// Generates method that saves records of table to xml file
        /// </summary>
        private void SaveXml()
        {
            CodeMemberMethod SaveXmlmethod = BuildMethodSignature("SaveXml", MemberAttributes.Public, new System.Collections.Generic.List <System.Collections.Generic.KeyValuePair <string, string> >()
            {
                new System.Collections.Generic.KeyValuePair <string, string>("TableList<T>", "table")
            });

            TheType.Members.Add(SaveXmlmethod);
            CodeStatement TableNameAssignStatement = GetAssignment("System.String", "tableName", new CodeVariableReferenceExpression("table.Name"));

            SaveXmlmethod.Statements.Add(TableNameAssignStatement);
            // CodeStatement cas12 = GetMethodInvokationAssignment("string", "fileName", "string", "Format", new System.Collections.Generic.List<KeyValuePair<string, bool>>() { new KeyValuePair<string, bool>("{0}.{1}", false), new KeyValuePair<string, bool>("tableName", true), new KeyValuePair<string, bool>("table.Format", true) });
            CodeExpression FormatMethodInvokeStatement = GetMethodInvokationExpression("System.String", "Format", new System.Collections.Generic.List <KeyValuePair <string, bool> >()
            {
                new KeyValuePair <string, bool>("{0}\\\\Files\\\\{1}.{2}", false), new KeyValuePair <string, bool>(generateDirectory, false), new KeyValuePair <string, bool>("tableName", true), new KeyValuePair <string, bool>("Format", true)
            });
            CodeStatement FileNameAssignStatement = GetAssignment("System.String", "fileName", FormatMethodInvokeStatement);

            SaveXmlmethod.Statements.Add(FileNameAssignStatement);
            CodeExpression LoadMethodInvokeExpression = GetMethodInvokationExpression("XDocument", "Load", new System.Collections.Generic.List <KeyValuePair <string, bool> > {
                new KeyValuePair <string, bool>("fileName", true)
            });

            CodeStatement  TableXElementAssignmentStatement   = GetAssignment("XDocument", "xdTable", LoadMethodInvokeExpression);
            CodeStatement  DataElementXElementAssignStatement = GetAssignment("System.String", "xmlDataElement", new CodePrimitiveExpression("Data"));
            CodeExpression SearchElementInXmlStatement        = GetMethodInvokationExpression("xdTable.Root", "Element", new System.Collections.Generic.List <KeyValuePair <string, bool> >()
            {
                new KeyValuePair <string, bool>("xmlDataElement", true)
            });
            CodeStatement XElementAssignStatement          = GetAssignment("XElement", "xu", SearchElementInXmlStatement);
            CodeStatement CreateDataElementXmlObjStatement = GetObjectCreateStatement("XElement", "xu", true, new List <string>()
            {
                "Data"
            });
            CodeStatement AddXElementToXmlStatement = GetMethodInvokationStatement("xdTable.Root", "Add", new List <string>()
            {
                "xu"
            });
            CodeStatement RemoveAllInvokationStatement  = GetMethodInvokationStatement("xu", "RemoveAll", new List <string>());
            CodeStatement CheckRecordExistanceStatement = GetUnoConditionIf("xu", CodeBinaryOperatorType.ValueEquality, "null", new List <CodeStatement>()
            {
                CreateDataElementXmlObjStatement, AddXElementToXmlStatement
            }, new List <CodeStatement>()
            {
                RemoveAllInvokationStatement
            });
            CodeExpression RemoveMethodInvokationExpression = GetMethodInvokationExpression("xu.Elements()", "Remove", new List <KeyValuePair <string, bool> >());
            CodeStatement  RemoveMethodInvokationStatement  = new CodeExpressionStatement(RemoveMethodInvokationExpression);
            CodeStatement  CollectionAddInvokationStatement = GetMethodInvokationStatement("table", "Add", new List <string>()
            {
                "xu.Elements(\"Element\")[i]"
            });
            CodeExpression SearchElementsXElementExpression = GetMethodInvokationExpression("xu", "Elements", new List <KeyValuePair <string, bool> >()
            {
                new KeyValuePair <string, bool>("Elements", false)
            });
            CodeStatement ElementAssignStatement = GetAssignment("IEnumerable<XElement>", "elements", SearchElementsXElementExpression);

            SaveXmlmethod.Statements.Add(TableXElementAssignmentStatement);
            SaveXmlmethod.Statements.Add(DataElementXElementAssignStatement);
            SaveXmlmethod.Statements.Add(XElementAssignStatement);
            SaveXmlmethod.Statements.Add(CheckRecordExistanceStatement);
            SaveXmlmethod.Statements.Add(ElementAssignStatement);
            SaveXmlmethod.Statements.Add(RemoveMethodInvokationStatement);
            List <CodeStatement>  SaveRecordStatements     = CreateSaveXmlStatements("table", "i");
            CodeCompoundStatement SaveRecordCycleStatement = GetSimpleForInteger("i", new System.Collections.Generic.KeyValuePair <int, string>(0, "table.Count"), 1, SaveRecordStatements);

            SaveXmlmethod.Statements.AddRange(SaveRecordCycleStatement.Statements.ToArray());
            CodeStatement XDocumentSaveInvokeStatement = GetMethodInvokationStatement("xdTable", "Save", new List <string>()
            {
                "fileName"
            });

            SaveXmlmethod.Statements.Add(XDocumentSaveInvokeStatement);

            CodeMemberMethod SaveOtherTypesMethod = BuildMethodSignature("SaveOtherTypes", MemberAttributes.Public, new System.Collections.Generic.List <System.Collections.Generic.KeyValuePair <string, string> >()
            {
                new System.Collections.Generic.KeyValuePair <string, string>("TableList<T>", "table")
            });

            TheType.Members.Add(SaveOtherTypesMethod);
        }
Exemplo n.º 35
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
        }
Exemplo n.º 36
0
        /// <summary>
        /// Generate inner cycle statements for saving table field value to xml
        /// </summary>
        /// <param name="propertyElementName">Name of proerty</param>
        /// <param name="indexName">Cycle index(commonly i,j, k)</param>
        /// <returns>List of cycle statements</returns>
        private List <CodeStatement> CreateSavePropertyStatements(string propertyElementName, string indexName)
        {
            List <CodeStatement> lst = new List <CodeStatement>();
            CodeStatement        CurrentPropertyAssignStatement = GetAssignment("PropertyInfo", "pj", new CodeVariableReferenceExpression(string.Format("{0}[{1}]", propertyElementName, indexName)));

            lst.Add(CurrentPropertyAssignStatement);
            CodeStatement PropertyXElementDeclarationStatement = GetDeclaration("xeProperty", "XElement");

            lst.Add(PropertyXElementDeclarationStatement);
            CodeStatement PropertyXElementObjectCreateStatement = GetObjectCreateStatement("XElement", "xeProperty", true, new List <string>()
            {
                "Property"
            });

            lst.Add(PropertyXElementObjectCreateStatement);
            CodeExpression PropertyValueGetAttributeInvokeStatement = GetMethodInvokationExpression("this", "GetAttribute", new System.Collections.Generic.List <KeyValuePair <string, bool> >()
            {
                new KeyValuePair <string, bool>("xeProperty", true), new KeyValuePair <string, bool>("PropertyValue", false)
            });
            CodeExpression PropertyNameGetAttributeInvokeStatement = GetMethodInvokationExpression("this", "GetAttribute", new System.Collections.Generic.List <KeyValuePair <string, bool> >()
            {
                new KeyValuePair <string, bool>("xeProperty", true), new KeyValuePair <string, bool>("PropertyName", false)
            });
            CodeStatement NameDeclarationStatement = GetDeclaration("name", "System.String");

            lst.Add(NameDeclarationStatement);
            CodeStatement NameAssignStatement = GetAssignment("name", new KeyValuePair <string, bool>("pj.Name", true));

            lst.Add(NameAssignStatement);
            CodeStatement PropertyNameAssignmentStatement = GetAssignment("System.String", "propertyName", PropertyNameGetAttributeInvokeStatement);

            lst.Add(PropertyNameAssignmentStatement);
            CodeExpression PropertyGetValueInvokeStatement = GetMethodInvokationExpression("pj", "GetValue", new System.Collections.Generic.List <KeyValuePair <string, bool> >()
            {
                new KeyValuePair <string, bool>("record", true)
            });
            CodeStatement PropertyValueAssignmentStatement = GetAssignment("System.object", "pvalue", PropertyGetValueInvokeStatement);

            lst.Add(PropertyValueAssignmentStatement);

            CodeExpression PropertyTypeInvokeExpression    = GetMethodInvokationExpression("pvalue", "GetType", new List <KeyValuePair <string, bool> >());
            CodeStatement  PropertyTypeAssignmentStatement = GetAssignment("Type", "tt", PropertyTypeInvokeExpression);

            lst.Add(PropertyTypeAssignmentStatement);

            CodeExpression ValueGetPropertyInvokationExpression = GetMethodInvokationExpression("tt", "GetProperty", new List <KeyValuePair <string, bool> >()
            {
                new KeyValuePair <string, bool>("Value", false)
            });
            CodeStatement ValuePropertyInfoAssignStatement = GetAssignment("PropertyInfo", "pw", ValueGetPropertyInvokationExpression);

            lst.Add(ValuePropertyInfoAssignStatement);
            CodeStatement csDeclare = GetDeclaration("value", "System.Object");

            lst.Add(csDeclare);
            CodeExpression ValueGetValueInvokeStatement = GetMethodInvokationExpression("pw", "GetValue", new List <KeyValuePair <string, bool> >()
            {
                new KeyValuePair <string, bool>("pvalue", true)
            });
            CodeStatement ValueAssignStatement = GetAssignmentWithExpression("value", ValueGetValueInvokeStatement);
            //lst.Add(ValueAssignStatement);
            CodeStatement css  = GetAssignment("value", new KeyValuePair <string, bool> ("pvalue", true));
            CodeStatement csIf = GetUnoConditionIf("pw", CodeBinaryOperatorType.IdentityInequality, "null", new List <CodeStatement>()
            {
                ValueAssignStatement
            }, new List <CodeStatement>()
            {
                css
            });

            lst.Add(csIf);
            CodeExpression SetAttributeValueOfNameInvokationExpression = GetMethodInvokationExpression("xeProperty", "SetAttributeValue", new List <KeyValuePair <string, bool> >()
            {
                new KeyValuePair <string, bool>("PropertyName", false), new KeyValuePair <string, bool>("name", true)
            });
            CodeStatement SetAttributeValueNameInvokeStatement = new CodeExpressionStatement(SetAttributeValueOfNameInvokationExpression);

            lst.Add(SetAttributeValueNameInvokeStatement);
            CodeExpression SetAttributeValueValueInvokationExpression = GetMethodInvokationExpression("xeProperty", "SetAttributeValue", new List <KeyValuePair <string, bool> >()
            {
                new KeyValuePair <string, bool>("PropertyValue", false), new KeyValuePair <string, bool>("value", true)
            });
            CodeStatement SetAttributeValueValueInvokationStatement = new CodeExpressionStatement(SetAttributeValueValueInvokationExpression);

            lst.Add(SetAttributeValueValueInvokationStatement);
            CodeStatement XElementAddPropertyInvokeStatement = GetMethodInvokationStatement("xeCurrent", "Add", new List <string>()
            {
                "xeProperty"
            });

            lst.Add(XElementAddPropertyInvokeStatement);

            return(lst);
        }
Exemplo n.º 37
0
 public void GenerateCodeFromStatement(CodeStatement e, TextWriter w, CodeGeneratorOptions o)
 {
     GenerateCodeFromCodeObject(e, w, o);
 }
        static CodeIterationStatement _ParseForStatement(_PC pc)
        {
            // expects to be on for
            if (!pc.Advance())
            {
                throw new ArgumentException("Unterminated for statement", "input");
            }
            _SkipComments(pc);
            if (ST.lparen != pc.SymbolId || !pc.Advance())
            {
                throw new ArgumentException("Unterminated for statement", "input");
            }
            _SkipComments(pc);
            CodeStatement init = null;

            if (pc.IsEnded)
            {
                throw new ArgumentException("Unterminated for statement", "input");
            }
            if (ST.semi != pc.SymbolId)
            {
                var pc2 = pc.GetLookAhead();
                pc2.EnsureStarted();
                try
                {
                    init = _ParseVariableDeclaration(pc2);
                }
                catch { init = null; }
            }
            if (null != init)
            {
                _ParseVariableDeclaration(pc);
                _SkipComments(pc);
            }
            else
            {
                _SkipComments(pc);
                if (ST.semi != pc.SymbolId)
                {
                    var e   = _ParseExpression(pc);
                    var bbo = e as CodeBinaryOperatorExpression;
                    if (null == e)
                    {
                        throw new NotImplementedException("Expression in init statement was null");
                    }
                    if (null != bbo && CodeBinaryOperatorType.Assign == bbo.Operator)
                    {
                        init = new CodeAssignStatement(bbo.Left, bbo.Right);
                    }
                    else
                    {
                        init = new CodeExpressionStatement(e);
                    }
                    _SkipComments(pc);
                    if (ST.semi != pc.SymbolId)
                    {
                        throw new ArgumentException("Invalid init statement in for statement", "input");
                    }
                    if (pc.IsEnded)
                    {
                        throw new ArgumentException("Unterminated for statement", "input");
                    }
                }
            }
            if (null == init)
            {
                if (ST.semi != pc.SymbolId)
                {
                    throw new ArgumentException("Invalid for statement", "input");
                }
                pc.Advance();
                _SkipComments(pc);
            }
            if (pc.IsEnded)
            {
                throw new ArgumentException("Unterminated for statement", "input");
            }
            CodeExpression test = null;

            if (ST.semi != pc.SymbolId)
            {
                test = _ParseExpression(pc);
                _SkipComments(pc);
                if (ST.semi != pc.SymbolId)
                {
                    throw new ArgumentException("Invalid test expression in for statement", "input");
                }
                if (!pc.Advance())
                {
                    throw new ArgumentException("Unterminated for statement", "input");
                }
            }
            _SkipComments(pc);
            if (pc.IsEnded)
            {
                throw new ArgumentException("Unterminated for statement", "input");
            }
            CodeExpression inc = null;

            if (ST.rparen != pc.SymbolId)
            {
                inc = _ParseExpression(pc);
                _SkipComments(pc);
            }
            if (ST.rparen != pc.SymbolId)
            {
                throw new ArgumentNullException("Invalid incremement statement in for loop");
            }
            if (!pc.Advance())
            {
                throw new ArgumentException("Unterminated for statement", "input");
            }
            _SkipComments(pc);
            if (pc.IsEnded)
            {
                throw new ArgumentException("Unterminated for statement", "input");
            }
            var           bo   = inc as CodeBinaryOperatorExpression;
            CodeStatement incs = null;

            if (null != inc)
            {
                if (null != bo && CodeBinaryOperatorType.Assign == bo.Operator)
                {
                    incs = new CodeAssignStatement(bo.Left, bo.Right);
                }
                else
                {
                    incs = new CodeExpressionStatement(inc);
                }
            }
            if (null == init)
            {
                init = new CodeSnippetStatement();
            }
            if (null == incs)
            {
                incs = new CodeSnippetStatement();
            }
            if (null == test)
            {
                test = new CodeSnippetExpression();
            }
            var result = new CodeIterationStatement(init, test, incs);

            if (ST.lbrace == pc.SymbolId)
            {
                if (!pc.Advance())
                {
                    throw new ArgumentException("Unterminated for statement", "input");
                }
                while (!pc.IsEnded && ST.rbrace != pc.SymbolId)
                {
                    result.Statements.Add(_ParseStatement(pc, true));
                }
                if (ST.rbrace != pc.SymbolId)
                {
                    throw new ArgumentException("Unterminated for statement", "input");
                }
                pc.Advance();
                _SkipComments(pc);
                if (pc.IsEnded)
                {
                    return(result);
                }
            }
            else
            {
                result.Statements.Add(_ParseStatement(pc));
            }

            _SkipComments(pc);
            return(result);
        }
Exemplo n.º 39
0
 public void PublicGenerateCodeFromStatement(CodeStatement e, TextWriter w, CodeGeneratorOptions o)
 {
     ((ICodeGenerator)this).GenerateCodeFromStatement(e, w, o);
 }
Exemplo n.º 40
0
        private static void EmitBasicClassMembers(CodeTypeDeclaration srClass, String nameSpace, String baseName, String resourcesNamespace, bool internalClass, bool useStatic)
        {
            const String tmpVarName = "temp";
            String       resMgrCtorParam;

            if (resourcesNamespace != null)
            {
                if (resourcesNamespace.Length > 0)
                {
                    resMgrCtorParam = resourcesNamespace + '.' + baseName;
                }
                else
                {
                    resMgrCtorParam = baseName;
                }
            }
            else if (!string.IsNullOrEmpty(nameSpace))
            {
                resMgrCtorParam = nameSpace + '.' + baseName;
            }
            else
            {
                resMgrCtorParam = baseName;
            }

            var suppressMessageAttrib = new CodeAttributeDeclaration(new CodeTypeReference(typeof(SuppressMessageAttribute)));

            suppressMessageAttrib.AttributeType.Options = CodeTypeReferenceOptions.GlobalReference;
            suppressMessageAttrib.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("Microsoft.Performance")));
            suppressMessageAttrib.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression("CA1811:AvoidUncalledPrivateCode")));

            // Emit a constructor - make it protected even if it is a "static" class to allow subclassing
            CodeConstructor ctor = new CodeConstructor();

            ctor.CustomAttributes.Add(suppressMessageAttrib);
            if (useStatic || internalClass)
            {
                ctor.Attributes = MemberAttributes.FamilyAndAssembly;
            }
            else
            {
                ctor.Attributes = MemberAttributes.Public;
            }
            srClass.Members.Add(ctor);

            // Emit _resMgr field.
            var ResMgrCodeTypeReference = new CodeTypeReference(typeof(ResourceManager), CodeTypeReferenceOptions.GlobalReference);
            var field = new CodeMemberField(ResMgrCodeTypeReference, ResMgrFieldName)
            {
                Attributes = MemberAttributes.Private
            };

            if (useStatic)
            {
                field.Attributes |= MemberAttributes.Static;
            }
            srClass.Members.Add(field);

            // Emit _resCulture field, and leave it set to null.
            var CultureTypeReference = new CodeTypeReference(typeof(CultureInfo), CodeTypeReferenceOptions.GlobalReference);

            field            = new CodeMemberField(CultureTypeReference, CultureInfoFieldName);
            field.Attributes = MemberAttributes.Private;
            if (useStatic)
            {
                field.Attributes |= MemberAttributes.Static;
            }
            srClass.Members.Add(field);

            // Emit ResMgr property
            CodeMemberProperty resMgr = new CodeMemberProperty();

            srClass.Members.Add(resMgr);
            resMgr.Name   = ResMgrPropertyName;
            resMgr.HasGet = true;
            resMgr.HasSet = false;
            resMgr.Type   = ResMgrCodeTypeReference;
            if (internalClass)
            {
                resMgr.Attributes = MemberAttributes.Assembly;
            }
            else
            {
                resMgr.Attributes = MemberAttributes.Public;
            }
            if (useStatic)
            {
                resMgr.Attributes |= MemberAttributes.Static;
            }

            // Mark the ResMgr property as advanced
            var editorBrowsableStateTypeRef =
                new CodeTypeReference(typeof(System.ComponentModel.EditorBrowsableState))
            {
                Options = CodeTypeReferenceOptions.GlobalReference
            };

            var editorBrowsableStateAdvanced     = new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(editorBrowsableStateTypeRef), "Advanced"));
            var editorBrowsableAdvancedAttribute = new CodeAttributeDeclaration("System.ComponentModel.EditorBrowsableAttribute", editorBrowsableStateAdvanced);

            editorBrowsableAdvancedAttribute.AttributeType.Options = CodeTypeReferenceOptions.GlobalReference;
            resMgr.CustomAttributes.Add(editorBrowsableAdvancedAttribute);

            // Emit the Culture property (read/write)
            var culture = new CodeMemberProperty();

            srClass.Members.Add(culture);
            culture.Name   = CultureInfoPropertyName;
            culture.HasGet = true;
            culture.HasSet = true;
            culture.Type   = CultureTypeReference;
            if (internalClass)
            {
                culture.Attributes = MemberAttributes.Assembly;
            }
            else
            {
                culture.Attributes = MemberAttributes.Public;
            }

            if (useStatic)
            {
                culture.Attributes |= MemberAttributes.Static;
            }

            // Mark the Culture property as advanced
            culture.CustomAttributes.Add(editorBrowsableAdvancedAttribute);

            /*
             * // Here's what I'm trying to emit.  Since not all languages support
             * // try/finally, we'll avoid our double lock pattern here.
             * // This will only hurt perf when we get two threads racing through
             * // this method the first time.  Unfortunate, but not a big deal.
             * // Also, the .NET Compact Framework doesn't support
             * // Thread.MemoryBarrier (they only run on processors w/ a strong
             * // memory model, and who knows about IA64...)
             * // Once we have Interlocked.CompareExchange<T>, we should use it here.
             * if (_resMgr == null) {
             *    ResourceManager tmp = new ResourceManager("<resources-name-with-namespace>", typeof("<class-name>").Assembly);
             *    _resMgr = tmp;
             * }
             * return _resMgr;
             */
            var field_resMgr        = new CodeFieldReferenceExpression(null, ResMgrFieldName);
            var object_equalsMethod = new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Object)), "ReferenceEquals");

            var isResMgrNull = new CodeMethodInvokeExpression(object_equalsMethod, field_resMgr, new CodePrimitiveExpression(null));

            // typeof(<class-name>).Assembly
            var getAssembly = new CodePropertyReferenceExpression(new CodeTypeOfExpression(new CodeTypeReference(srClass.Name)), "Assembly");

            // new ResourceManager(resMgrCtorParam, typeof(<class-name>).Assembly);
            var newResMgr = new CodeObjectCreateExpression(ResMgrCodeTypeReference, new CodePrimitiveExpression(resMgrCtorParam), getAssembly);

            var init = new CodeStatement[2];

            init[0] = new CodeVariableDeclarationStatement(ResMgrCodeTypeReference, tmpVarName, newResMgr);
            init[1] = new CodeAssignStatement(field_resMgr, new CodeVariableReferenceExpression(tmpVarName));

            resMgr.GetStatements.Add(new CodeConditionStatement(isResMgrNull, init));
            resMgr.GetStatements.Add(new CodeMethodReturnStatement(field_resMgr));

            // Add a doc comment to the ResourceManager property
            resMgr.Comments.Add(new CodeCommentStatement(DocCommentSummaryStart, true));
            resMgr.Comments.Add(new CodeCommentStatement(SR.GetString(SR.ResMgrPropertyComment), true));
            resMgr.Comments.Add(new CodeCommentStatement(DocCommentSummaryEnd, true));

            // Emit code for Culture property
            var field_resCulture = new CodeFieldReferenceExpression(null, CultureInfoFieldName);

            culture.GetStatements.Add(new CodeMethodReturnStatement(field_resCulture));

            var newCulture = new CodePropertySetValueReferenceExpression();

            culture.SetStatements.Add(new CodeAssignStatement(field_resCulture, newCulture));

            // Add a doc comment to Culture property
            culture.Comments.Add(new CodeCommentStatement(DocCommentSummaryStart, true));
            culture.Comments.Add(new CodeCommentStatement(SR.GetString(SR.CulturePropertyComment1), true));
            culture.Comments.Add(new CodeCommentStatement(SR.GetString(SR.CulturePropertyComment2), true));
            culture.Comments.Add(new CodeCommentStatement(DocCommentSummaryEnd, true));
        }
	public void Remove(CodeStatement value) {}
 public void Ctor_NullObjectInStatements_ThrowsArgumentNullException()
 {
     CodeStatement[] statements = new CodeStatement[] { null };
     AssertExtensions.Throws <ArgumentNullException>("value", () => new CodeIterationStatement(null, null, null, statements));
 }
Exemplo n.º 43
0
 public CodeForEachStatement(CodeVariableReference id, CodeExpression container, CodeStatement statement)
 {
   Container = container;
   Id = id;
   Statement = statement;
 }
Exemplo n.º 44
0
        private static void AddStatementWithLinePragma(Block block, CodeStatementCollection statements, CodeStatement statement)
        {
            var lineNumber = (block.StartLine > 0) ? block.StartLine : 1;

            if (String.IsNullOrEmpty(block.Name))
            {
                statements.Add(new CodeSnippetStatement("#line " + lineNumber));
            }
            else
            {
                statement.LinePragma = new CodeLinePragma(block.Name, lineNumber);
            }
            statements.Add(statement);
            if (String.IsNullOrEmpty(block.Name))
            {
                statements.Add(new CodeSnippetStatement("#line default"));
            }
        }
Exemplo n.º 45
0
	// Generate code from a CodeDom statement.
	void ICodeGenerator.GenerateCodeFromStatement(CodeStatement e,
								   				  TextWriter w,
								   				  CodeGeneratorOptions o)
			{
				bool initialized = SetupForCodeGeneration(w, o);
				try
				{
					GenerateStatement(e);
				}
				finally
				{
					FinalizeCodeGeneration(initialized);
				}
			}
Exemplo n.º 46
0
 public void GenerateCodeFromStatement(CodeStatement e, TextWriter w, CodeGeneratorOptions o)
 {
     throw new BadImageFormatException("6");
 }
	public CodeIterationStatement(CodeStatement initStatement, CodeExpression testExpression, CodeStatement incrementStatement, CodeStatement[] statements) {}
        private void GenerateMemberAssignment(CodeMemberMethod initComponentMethod, MemberNode member, CodeExpression targetExpression, CodeExpression valueExpression,
                                              CodeDomObjectNode targetObjectNode)
        {
            CodeStatement cs = null;

            //if (member.Member.IsUnknown)
            //{
            //    throw new Exception("Unknown member " + member.Member.Name);
            //}
            if (member.Member == XamlLanguage.Items)
            {
                var      parentObjectNode = member.ParentObjectNode;
                XamlType parentType       = null;
                if (parentObjectNode.IsGetObject)
                {
                    parentType = parentObjectNode.ParentMemberNode.Member.Type;
                }
                else
                {
                    parentType = parentObjectNode.Type;
                }
                if (parentType.IsDictionary)
                {
                    if (!typeof(IDictionary).IsAssignableFrom(parentType.UnderlyingType))
                    {
                        throw new NotImplementedException("Support non-IDictionary adds");
                    }
                    CodeExpression keyExpression;
                    if (targetObjectNode.XKeyNode != null)
                    {
                        keyExpression = new CodeSnippetExpression("\"" + ((ValueNode)targetObjectNode.XKeyNode.ItemNodes[0]).Value + "\"");
                    }
                    else
                    {
                        if (targetObjectNode.DictionaryKeyProperty == null)
                        {
                            throw new NotSupportedException("No key on dictionary entry");
                        }
                        throw new NotImplementedException();
                    }
                    cs = new CodeExpressionStatement(
                        new CodeMethodInvokeExpression(new CodeCastExpression(typeof(IDictionary), targetExpression), "Add", keyExpression, valueExpression));
                }
                else
                {
                    if (!typeof(IList).IsAssignableFrom(parentType.UnderlyingType))
                    {
                        throw new NotImplementedException("Support non-IList adds");
                    }
                    //TODO: calling Add directly is how I'll leave it for now...
                    //cs = new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeCastExpression(typeof(IList), targetExpression), "Add", valueExpression));
                    cs = new CodeExpressionStatement(new CodeMethodInvokeExpression(targetExpression, "Add", valueExpression));
                }
            }
            else if (member.Member.IsEvent)
            {
                throw new NotImplementedException();
            }
            else
            {
                if (member.Member.IsAttachable)
                {
                    cs = new CodeExpressionStatement(new CodeMethodInvokeExpression(
                                                         new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(member.Member.DeclaringType.UnderlyingType.Name),
                                                                                           "Set" + member.Member.Name), targetExpression, valueExpression));
                }
                else //normal property
                {
                    cs = new CodeAssignStatement(
                        new CodePropertyReferenceExpression(targetExpression, member.Member.Name), valueExpression);
                }
            }
            initComponentMethod.Statements.Add(cs);
        }
Exemplo n.º 49
0
		protected void GenerateStatement(CodeStatement s)
		{
			try
			{
				s.Accept(visitor);
			}
			catch (NotImplementedException)
			{
				throw new ArgumentException("Element type " + s.GetType() + " is not supported.", "s");
			}
		}
Exemplo n.º 50
0
        void ICodeGenerator.GenerateCodeFromStatement(CodeStatement e, TextWriter w, CodeGeneratorOptions o)
        {
            bool setLocal = false;
            if (_output != null && w != _output.InnerWriter)
            {
                throw new InvalidOperationException(SR.CodeGenOutputWriter);
            }
            if (_output == null)
            {
                setLocal = true;
                _options = o ?? new CodeGeneratorOptions();
                _output = new ExposedTabStringIndentedTextWriter(w, _options.IndentString);
            }

            try
            {
                GenerateStatement(e);
            }
            finally
            {
                if (setLocal)
                {
                    _output = null;
                    _options = null;
                }
            }
        }
Exemplo n.º 51
0
 public CodeLabeledStatement(string label, CodeStatement statement)
 {
     _label = label;
     Statement = statement;
 }
	public CodeStatementCollection(CodeStatement[] value) {}
Exemplo n.º 53
0
 public CodeSwitchCase(CodeExpression condition, CodeStatement statement)
 {
   Condition = condition;
   Statement = statement;
 }
	public void Insert(int index, CodeStatement value) {}
 internal static CodeStatement ForLoop(CodeStatement initStmt, CodeExpression testExpression, CodeStatement incrementStmt, CodeStatement[] statements)
 {
     return(new CodeIterationStatement(initStmt, testExpression, incrementStmt, statements));
 }
	// Methods
	public int Add(CodeStatement value) {}
Exemplo n.º 57
0
        protected void GenerateStatement(CodeStatement e)
        {
            if (e.StartDirectives.Count > 0)
            {
                GenerateDirectives(e.StartDirectives);
            }

            if (e.LinePragma != null)
            {
                GenerateLinePragmaStart(e.LinePragma);
            }

            if (e is CodeCommentStatement)
            {
                GenerateCommentStatement((CodeCommentStatement)e);
            }
            else if (e is CodeMethodReturnStatement)
            {
                GenerateMethodReturnStatement((CodeMethodReturnStatement)e);
            }
            else if (e is CodeConditionStatement)
            {
                GenerateConditionStatement((CodeConditionStatement)e);
            }
            else if (e is CodeTryCatchFinallyStatement)
            {
                GenerateTryCatchFinallyStatement((CodeTryCatchFinallyStatement)e);
            }
            else if (e is CodeAssignStatement)
            {
                GenerateAssignStatement((CodeAssignStatement)e);
            }
            else if (e is CodeExpressionStatement)
            {
                GenerateExpressionStatement((CodeExpressionStatement)e);
            }
            else if (e is CodeIterationStatement)
            {
                GenerateIterationStatement((CodeIterationStatement)e);
            }
            else if (e is CodeThrowExceptionStatement)
            {
                GenerateThrowExceptionStatement((CodeThrowExceptionStatement)e);
            }
            else if (e is CodeSnippetStatement)
            {
                // Don't indent snippet statements, in order to preserve the column
                // information from the original code.  This improves the debugging
                // experience.
                int savedIndent = Indent;
                Indent = 0;

                GenerateSnippetStatement((CodeSnippetStatement)e);

                // Restore the indent
                Indent = savedIndent;
            }
            else if (e is CodeVariableDeclarationStatement)
            {
                GenerateVariableDeclarationStatement((CodeVariableDeclarationStatement)e);
            }
            else if (e is CodeAttachEventStatement)
            {
                GenerateAttachEventStatement((CodeAttachEventStatement)e);
            }
            else if (e is CodeRemoveEventStatement)
            {
                GenerateRemoveEventStatement((CodeRemoveEventStatement)e);
            }
            else if (e is CodeGotoStatement)
            {
                GenerateGotoStatement((CodeGotoStatement)e);
            }
            else if (e is CodeLabeledStatement)
            {
                GenerateLabeledStatement((CodeLabeledStatement)e);
            }
            else
            {
                throw new ArgumentException(SR.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e));
            }

            if (e.LinePragma != null)
            {
                GenerateLinePragmaEnd(e.LinePragma);
            }
            if (e.EndDirectives.Count > 0)
            {
                GenerateDirectives(e.EndDirectives);
            }
        }
 internal static CodeStatement If(CodeExpression cond, CodeStatement trueStm)
 {
     return(If(cond, new CodeStatement[] { trueStm }));
 }
 public virtual void GenerateCodeFromStatement(CodeStatement statement, TextWriter writer, CodeGeneratorOptions options)
 {
     ICodeGenerator cg = CreateGenerator();
     if (cg == null)
         throw GetNotImplemented();
     cg.GenerateCodeFromStatement(statement, writer, options);
 }
 internal static CodeStatement If(CodeExpression cond, CodeStatement trueStm, CodeStatement falseStm)
 {
     return(new CodeConditionStatement(cond, new CodeStatement[] { trueStm }, new CodeStatement[] { falseStm }));
 }