public static CodeStatementCollection BuildDetectChangedMembers(TableViewTableTypeBase table) { CodeStatementCollection ValidationSetStatement = new CodeStatementCollection(); String PocoTypeName = "this"; ValidationSetStatement.Add(new CodeSnippetExpression("Boolean bResult = new Boolean()")); ValidationSetStatement.Add(new CodeSnippetExpression("bResult = false")); foreach (Column c in table.Columns) { MemberGraph mGraph = new MemberGraph(c); CodeConditionStatement csTest1 = new CodeConditionStatement(); if (mGraph.IsNullable) { csTest1.Condition = new CodeSnippetExpression(PocoTypeName + "." + mGraph.PropertyName() + ".HasValue == true"); csTest1.TrueStatements.Add(new CodeSnippetExpression("bResult = true")); } else { csTest1.Condition = new CodeSnippetExpression(PocoTypeName + "." + mGraph.PropertyName() + " == null"); csTest1.TrueStatements.Add(new CodeSnippetExpression("")); csTest1.FalseStatements.Add(new CodeSnippetExpression("bResult = true")); } } return ValidationSetStatement; }
/// <summary> /// Builds List of Code Statmenets that converts a Type into a DAL Parameter Statement /// </summary> /// <param name="table"></param> /// <returns></returns> public static CodeStatementCollection BuildAttributeSetStatement(TableViewTableTypeBase table) { CodeStatementCollection AttributeSetStatement = new CodeStatementCollection(); String PocoTypeName = table.Name; String FullPocoTypeName = PocoTypeName; foreach (Column c in table.Columns) { MemberGraph mGraph = new MemberGraph(c); if (mGraph.IsReadOnly) { // nothing yet } else { String DotNetTypeName = TypeConvertor.ToNetType(c.DataType.SqlDataType).ToString(); System.CodeDom.CodeConditionStatement ccsField = new CodeConditionStatement(); if (mGraph.IsNullable) { ccsField.Condition = new CodeSnippetExpression("query." + mGraph.PropertyName() + ".HasValue"); ccsField.TrueStatements.Add(new CodeSnippetExpression("this.Access.AddParameter(\"" + mGraph.PropertyName() + "\",query." + mGraph.PropertyName() + ".Value, ParameterDirection.Input)")); ccsField.FalseStatements.Add(new CodeSnippetExpression("this.Access.AddParameter(\"" + mGraph.PropertyName() + "\", null , ParameterDirection.Input)")); } else { ccsField.Condition = new CodeSnippetExpression("query." + mGraph.PropertyName() + " == null"); ccsField.TrueStatements.Add(new CodeSnippetExpression("this.Access.AddParameter(\"" + mGraph.PropertyName() + "\", null , ParameterDirection.Input)")); ccsField.FalseStatements.Add(new CodeSnippetExpression("this.Access.AddParameter(\"" + mGraph.PropertyName() + "\",query." + mGraph.PropertyName() + ", ParameterDirection.Input)")); } AttributeSetStatement.Add(ccsField); } } return AttributeSetStatement; }
public static CodeConditionStatement IfTrueReturnNull (CodeExpression condition) { CodeConditionStatement cond = new CodeConditionStatement (); cond.Condition = condition; cond.TrueStatements.Add (new CodeMethodReturnStatement (Null)); return cond; }
internal static void BuildEvalExpression(string field, string formatString, string propertyName, Type propertyType, ControlBuilder controlBuilder, CodeStatementCollection methodStatements, CodeStatementCollection statements, CodeLinePragma linePragma, bool isEncoded, ref bool hasTempObject) { // Altogether, this function will create a statement that looks like this: // if (this.Page.GetDataItem() != null) { // target.{{propName}} = ({{propType}}) this.Eval(fieldName, formatString); // } // this.Eval(fieldName, formatString) CodeMethodInvokeExpression evalExpr = new CodeMethodInvokeExpression(); evalExpr.Method.TargetObject = new CodeThisReferenceExpression(); evalExpr.Method.MethodName = EvalMethodName; evalExpr.Parameters.Add(new CodePrimitiveExpression(field)); if (!String.IsNullOrEmpty(formatString)) { evalExpr.Parameters.Add(new CodePrimitiveExpression(formatString)); } CodeStatementCollection evalStatements = new CodeStatementCollection(); BuildPropertySetExpression(evalExpr, propertyName, propertyType, controlBuilder, methodStatements, evalStatements, linePragma, isEncoded, ref hasTempObject); // if (this.Page.GetDataItem() != null) CodeMethodInvokeExpression getDataItemExpr = new CodeMethodInvokeExpression(); getDataItemExpr.Method.TargetObject = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Page"); getDataItemExpr.Method.MethodName = GetDataItemMethodName; CodeConditionStatement ifStmt = new CodeConditionStatement(); ifStmt.Condition = new CodeBinaryOperatorExpression(getDataItemExpr, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)); ifStmt.TrueStatements.AddRange(evalStatements); statements.Add(ifStmt); }
/// <summary> /// if (string.IsNullOrEmpty(APIKey) == false) /// request = request.WithAPIKey(APIKey) /// </summary> /// <returns></returns> internal CodeConditionStatement CreateWithApiKey() { // !string.IsNullOrEmpty(Key) var condition = new CodeBinaryOperatorExpression( new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(string)), "IsNullOrEmpty", new CodeVariableReferenceExpression(ApiKeyServiceDecorator.PropertyName)), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(false)); //var condition = //new CodeSnippetExpression("!string.IsNullOrEmpty(" + ApiKeyServiceDecorator.PropertyName + ")"); // if (...) { var block = new CodeConditionStatement(condition); // request = request.WithKey(APIKey) var getProperty = new CodePropertyReferenceExpression( new CodeThisReferenceExpression(), ApiKeyServiceDecorator.PropertyName); var request = new CodeMethodInvokeExpression( new CodeVariableReferenceExpression("request"), "WithKey", getProperty); var trueCase = new CodeAssignStatement(new CodeVariableReferenceExpression("request"), request); // } block.TrueStatements.Add(trueCase); return block; }
// Emits the codedom statement for an if conditional block. public static CodeStatement Emit(IfBlock ifBlock) { // Create the codedom if statement. var i = new CodeConditionStatement(); // Emit the conditional statements for the if block. i.Condition = CodeDomEmitter.EmitCodeExpression(ifBlock.Conditional.ChildExpressions[0]); // Emit the lists of statements for the true and false bodies of the if block. // Comments need to be added in case the bodies are empty: these two properties // of the CodeConditionStatement can't be null. i.FalseStatements.Add(new CodeCommentStatement("If condition is false, execute these statements.")); i.TrueStatements.Add(new CodeCommentStatement("If condition is true, execute these statements.")); // Emit the statements for the true block foreach (var e in ifBlock.TrueBlock.ChildExpressions) i.TrueStatements.Add(CodeDomEmitter.EmitCodeStatement(e)); // Emit the statements for the false block. foreach (var e in ifBlock.FalseBlock.ChildExpressions) i.FalseStatements.Add(CodeDomEmitter.EmitCodeStatement(e)); return i; }
public void Constructor0_Deny_Unrestricted () { CodeConditionStatement css = new CodeConditionStatement (); Assert.IsNull (css.Condition, "Condition"); css.Condition = new CodeExpression (); Assert.AreEqual (0, css.FalseStatements.Count, "FalseStatements"); Assert.AreEqual (0, css.TrueStatements.Count, "TrueStatements"); }
public void Constructor1_Deny_Unrestricted () { CodeExpression condition = new CodeExpression (); CodeStatement[] cs = new CodeStatement[1] { new CodeStatement () }; CodeConditionStatement css = new CodeConditionStatement (condition, cs); Assert.AreSame (condition, css.Condition, "Condition"); css.Condition = new CodeExpression (); Assert.AreEqual (0, css.FalseStatements.Count, "FalseStatements"); Assert.AreEqual (1, css.TrueStatements.Count, "TrueStatements"); }
void EmitConditionStatement(CodeConditionStatement cond) { writer.Write(Parser.FlowIf); writer.Write(Parser.SingleSpace); writer.Write(Parser.ParenOpen); EmitExpression(cond.Condition); writer.Write(Parser.ParenClose); if (cond.TrueStatements.Count > 1) { WriteSpace(); writer.Write(Parser.BlockOpen); } depth++; EmitStatements(cond.TrueStatements); depth--; if (cond.TrueStatements.Count > 1) { WriteSpace(); writer.Write(Parser.BlockClose); } if (cond.FalseStatements.Count > 0) { if (options.ElseOnClosing) writer.Write(Parser.SingleSpace); else WriteSpace(); writer.Write(Parser.FlowElse); if (cond.FalseStatements.Count > 1) { if (options.ElseOnClosing) writer.Write(Parser.SingleSpace); else WriteSpace(); writer.Write(Parser.BlockOpen); } depth++; EmitStatements(cond.FalseStatements); depth--; if (cond.FalseStatements.Count > 1) { WriteSpace(); writer.Write(Parser.BlockClose); } } }
/// <summary> /// Generates the specified dictionary. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="classType">Type of the class.</param> /// <param name="initMethod">The initialize method.</param> /// <param name="fieldReference">The field reference.</param> public void Generate(ResourceDictionary dictionary, CodeTypeDeclaration classType, CodeMemberMethod initMethod, CodeExpression fieldReference) { foreach (var mergedDict in dictionary.MergedDictionaries) { string name = string.Empty; if (mergedDict.Source.IsAbsoluteUri) { name = Path.GetFileNameWithoutExtension(mergedDict.Source.LocalPath); } else { name = Path.GetFileNameWithoutExtension(mergedDict.Source.OriginalString); } if (string.IsNullOrEmpty(name)) { Console.WriteLine("Dictionary name not found."); continue; } CodeMethodInvokeExpression addMergedDictionary = new CodeMethodInvokeExpression( fieldReference, "MergedDictionaries.Add", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(name), "Instance")); initMethod.Statements.Add(addMergedDictionary); } ValueGenerator valueGenerator = new ValueGenerator(); List<object> keys = dictionary.Keys.Cast<object>().OrderBy(k => k.ToString()).ToList(); foreach (var resourceKey in keys) { object resourceValue = dictionary[resourceKey]; CodeComment comment = new CodeComment("Resource - [" + resourceKey.ToString() + "] " + resourceValue.GetType().Name); initMethod.Statements.Add(new CodeCommentStatement(comment)); CodeExpression keyExpression = CodeComHelper.GetResourceKeyExpression(resourceKey); CodeExpression valueExpression = valueGenerator.ProcessGenerators(classType, initMethod, resourceValue, "r_" + uniqueId, dictionary); if (valueExpression != null) { CodeMethodInvokeExpression addResourceMethod = new CodeMethodInvokeExpression(fieldReference, "Add", keyExpression, valueExpression); var check = new CodeConditionStatement( new CodeMethodInvokeExpression(fieldReference, "Contains", keyExpression), new CodeStatement[] { }, new CodeStatement[] { new CodeExpressionStatement(addResourceMethod) }); initMethod.Statements.Add(check); } uniqueId++; } }
public CodeSwitchOption(CodeExpression[] values, params CodeStatement[] statements) { _actualStmt = this; _values = new CodeNotificationExpressionCollection(Refresh, values); if (statements != null) { _actualStmt.TrueStatements.AddRange(statements); } Refresh(); }
public static CodeConditionStatement Clone(this CodeConditionStatement statement) { if (statement == null) return null; CodeConditionStatement s = new CodeConditionStatement(); s.Condition = statement.Condition.Clone(); s.EndDirectives.AddRange(statement.EndDirectives); s.FalseStatements.AddRange(statement.FalseStatements.Clone()); s.LinePragma = statement.LinePragma; s.StartDirectives.AddRange(statement.StartDirectives); s.TrueStatements.AddRange(statement.TrueStatements.Clone()); s.UserData.AddRange(statement.UserData); return s; }
public override void FinishProcessingRun () { var statement = new CodeConditionStatement ( new CodeBinaryOperatorExpression ( new CodePropertyReferenceExpression ( new CodePropertyReferenceExpression (new CodeThisReferenceExpression (), "Errors"), "HasErrors"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression (false)), postStatements.ToArray ()); postStatements.Clear (); postStatements.Add (statement); }
internal void SetActualStmt(CodeConditionStatement actualStmt) { if (actualStmt == null) { actualStmt = this; } if (actualStmt != _actualStmt) { actualStmt.Condition = _actualStmt.Condition; actualStmt.TrueStatements.Clear(); actualStmt.TrueStatements.AddRange(_actualStmt.TrueStatements); _actualStmt = actualStmt; } }
public void Visit(WhenBooleanStatement statement) { var arg = VisitChild(statement.Expression, new CodeDomArg() { Scope = _codeStack.Peek().Scope }); if (arg.Tag != null) _codeStack.Peek().Tag = arg.Tag; var condition = new CodeConditionStatement(); condition.Condition = arg.CodeExpression; var then = VisitChild(statement.Then, new CodeDomArg() { Scope = _codeStack.Peek().Scope }); condition.TrueStatements.Add(new CodeMethodReturnStatement(then.CodeExpression)); if (arg.Tag != null) _codeStack.Peek().Tag = arg.Tag; _codeStack.Peek().ParentStatements.Add(condition); }
public void SetNodeValue(XmlNode n) { for (int i = 0; i < n.Attributes.Count; i++) { string value = n.Attributes[i].Value; //AddField(n.Attributes[i].Name, value, MemberAttributes.Private); fieldList.Add(new ItemField(n.Attributes[i].Name, value, MemberAttributes.Private)); ItemProperty item = new ItemProperty(n.Attributes[i].Name); item.SetGetName(); item.SetValueType(value); item.SetModifier(MemberAttributes.Public | MemberAttributes.Final); propertyList.Add(item); CodeConditionStatement condition = new CodeConditionStatement(); condition.Condition = new CodeVariableReferenceExpression("inArg0.ContainsKey(\"" + n.Attributes[i].Name + "\")"); string parseLeft = ""; string parseRight = ""; if (Stringer.IsNumber(value)) { parseLeft = value.Contains(".") ? "float.Parse(" : "uint.Parse("; parseRight = ")"; } CodeVariableReferenceExpression right = new CodeVariableReferenceExpression(parseLeft + "inArg0[\"" + n.Attributes[i].Name + "\"]" + parseRight); CodePropertyReferenceExpression left = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "_" + Stringer.FirstLetterLower(n.Attributes[i].Name)); if (Stringer.IsNumber(value)) { CodeConditionStatement numCondition = new CodeConditionStatement(); numCondition.Condition = new CodeVariableReferenceExpression("inArg0[\"" + n.Attributes[i].Name + "\"] == \"\""); numCondition.TrueStatements.Add(new CodeAssignStatement(left, new CodeVariableReferenceExpression("0"))); numCondition.FalseStatements.Add(new CodeAssignStatement(left, right)); condition.TrueStatements.Add(numCondition); } else { condition.TrueStatements.Add(new CodeAssignStatement(left, right)); } AddConditionStatement(condition); } Create(); }
public void GetKeywordFromCodeDom() { CodeStatement st = new CodeExpressionStatement(new CodeArgumentReferenceExpression("foo")); CodeExpression exp = new CodeArgumentReferenceExpression("foo"); CodeIterationStatement it = new CodeIterationStatement(st, exp, st); CodeConditionStatement cond = new CodeConditionStatement(exp); new Microsoft.CSharp.CSharpCodeProvider().GenerateCodeFromStatement( it, Console.Out, new System.CodeDom.Compiler.CodeGeneratorOptions()); new Microsoft.CSharp.CSharpCodeProvider().GenerateCodeFromStatement( cond, Console.Out, new System.CodeDom.Compiler.CodeGeneratorOptions()); new Microsoft.VisualBasic.VBCodeProvider().GenerateCodeFromStatement( it, Console.Out, new System.CodeDom.Compiler.CodeGeneratorOptions()); new Microsoft.VisualBasic.VBCodeProvider().GenerateCodeFromStatement( cond, Console.Out, new System.CodeDom.Compiler.CodeGeneratorOptions()); }
public static CodeStatement[] CreateMappingStatements(ClassMappingDescriptor descriptor, CodeGeneratorContext context) { Dictionary<string, List<MemberMappingDescriptor>> aggregateGroups = new Dictionary<string, List<MemberMappingDescriptor>>(); List<CodeStatement> statements = new List<CodeStatement>(20); foreach (MemberMappingDescriptor member in descriptor.MemberDescriptors) { if (member.IsAggregateExpression) { // group all agregates by expression to avoid multiple traversals over same path //string path = GetPath(member.Expression); string path = GetPath(descriptor, member); if(!aggregateGroups.ContainsKey(path)) aggregateGroups[path] = new List<MemberMappingDescriptor>(1); aggregateGroups[path].Add(member); } else { CodeStatement[] st = CreateNonAggregateMappingStatements(descriptor, member, context); if(member.HasNullValue) { CodeStatement[] falseStatements = st; CodeStatement[] trueStatements = new CodeStatement[1]; trueStatements[0] = new CodeAssignStatement( new CodeVariableReferenceExpression("target." + member.Member), new CodeSnippetExpression(member.NullValue.ToString())); string checkExpression = GetNullablePartsCheckExpression(member); CodeExpression ifExpression = new CodeSnippetExpression(checkExpression); st = new CodeStatement[1]; st[0] = new CodeConditionStatement(ifExpression, trueStatements, falseStatements); } statements.AddRange(st); } } foreach (List<MemberMappingDescriptor> group in aggregateGroups.Values) { CodeStatement[] st = CreateAggregateMappingStatements(descriptor, group, context); statements.AddRange(st); } return statements.ToArray(); }
/// <summary> /// /// </summary> /// <param name="table"></param> /// <returns></returns> public CodeMemberMethod BuildSelectBE(TableViewTableTypeBase table) { CodeMemberMethod cmSelect = new CodeMemberMethod(); cmSelect.Attributes = MemberAttributes.Public; cmSelect.ReturnType = new CodeTypeReference("System.Data.DataSet"); String cp_name = "ssp_" + table.Name; String PocoTypeName = table.Name; String FullPocoTypeName = PocoTypeName; CodeParameterDeclarationExpression cpdePoco = new CodeParameterDeclarationExpression(); cpdePoco.Name = "query"; cpdePoco.Type = new CodeTypeReference(table.Name); cpdePoco.Direction = FieldDirection.In; cmSelect.Parameters.Add(cpdePoco); cmSelect.Attributes = MemberAttributes.Public; cmSelect.Name = "Select"; cmSelect.Statements.Add(new CodeSnippetExpression("this.Access.CreateProcedureCommand(\"" + cp_name + "\")")); foreach (Column c in table.Columns) { MemberGraph mGraph = new MemberGraph(c); String DotNetTypeName = TypeConvertor.ToNetType(c.DataType.SqlDataType).ToString(); System.CodeDom.CodeConditionStatement ccsField = new CodeConditionStatement(); if (mGraph.IsNullable) { ccsField.Condition = new CodeSnippetExpression("query." + mGraph.PropertyName() + ".HasValue"); ccsField.TrueStatements.Add(new CodeSnippetExpression("this.Access.AddParameter(\"" + mGraph.PropertyName() + "\",query." + mGraph.PropertyName() + ".Value, ParameterDirection.Input)")); ccsField.FalseStatements.Add(new CodeSnippetExpression("this.Access.AddParameter(\"" + mGraph.PropertyName() + "\", null , ParameterDirection.Input)")); } else { ccsField.Condition = new CodeSnippetExpression("query." + mGraph.PropertyName() + " == null"); ccsField.TrueStatements.Add(new CodeSnippetExpression("this.Access.AddParameter(\"" + mGraph.PropertyName() + "\", null , ParameterDirection.Input)")); ccsField.FalseStatements.Add(new CodeSnippetExpression("this.Access.AddParameter(\"" + mGraph.PropertyName() + "\",query." + mGraph.PropertyName() + ", ParameterDirection.Input)")); } cmSelect.Statements.Add(ccsField); } cmSelect.Statements.Add(new CodeSnippetExpression("return this.Access.ExecuteDataSet()")); cmSelect.Comments.Add(new CodeCommentStatement("Select by Object [Implements Query By Example], returns DataSet")); return cmSelect; }
internal static CodeMemberMethod CreateTransformMethod(bool withNullParameter) { CodeMemberMethod method = new CodeMemberMethod(); method.Name = "Transform<T,S>"; method.ReturnType = new CodeTypeReference("T"); // this parameter is only neede for the compiler to deduce the type parameter // it is not used inside the function method.Parameters.Add(new CodeParameterDeclarationExpression("T", "target")); method.Parameters[0].Direction = FieldDirection.In; method.Parameters.Add(new CodeParameterDeclarationExpression("S", "source")); method.Parameters[1].Direction = FieldDirection.In; if (withNullParameter) { method.Parameters.Add(new CodeParameterDeclarationExpression("T", "nullValue")); method.Parameters[2].Direction = FieldDirection.In; } AddNullHandling(method, withNullParameter, true); CodeStatement[] statements = new CodeStatement[3]; statements[0] = new CodeVariableDeclarationStatement("IAssembler<T, S>", "converter", new CodeSnippetExpression("this as IAssembler<T, S>")); statements[1] = new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeSnippetExpression("converter"), CodeBinaryOperatorType.ValueEquality, new CodeSnippetExpression("null")), new CodeStatement[]{ new CodeVariableDeclarationStatement(typeof(string), "msg", new CodeSnippetExpression("string.Format(\"Assembler for transformation [{0} -> {1}] is not configured\", typeof(S).FullName, typeof(T).FullName)")), new CodeThrowExceptionStatement(new CodeSnippetExpression("new OtisException(msg)")) }, new CodeStatement[0] ); statements[2] = CreateReturnStatement("converter.AssembleFrom(source)"); method.Statements.AddRange(statements); return method; }
internal static CodeStatement CreateNullHandlingStatement(bool replaceNullValue, bool hasReturnType, bool useNullInsteadOfDefault) { string retValue = ""; CodeStatement[] trueStatements = new CodeStatement[1]; if(hasReturnType) { retValue = replaceNullValue ? "nullValue" : (useNullInsteadOfDefault ? "null" : "default(T)"); } trueStatements[0] = CreateReturnStatement(retValue); CodeExpression ifExpression = new CodeBinaryOperatorExpression( new CodeSnippetExpression("source"), CodeBinaryOperatorType.ValueEquality, new CodeSnippetExpression("null")); CodeConditionStatement st = new CodeConditionStatement(ifExpression, trueStatements, new CodeStatement[0]); return st; }
private void EmitConditionStatement(CodeConditionStatement Condition) { Label False = Generator.DefineLabel(); Label End = Generator.DefineLabel(); // TODO: emitting condition statements could probably be done more efficiently EmitExpression(Condition.Condition); Generator.Emit(OpCodes.Ldc_I4_0); Generator.Emit(OpCodes.Beq, False); // Execute code for true and jump to end EmitStatementCollection(Condition.TrueStatements); Generator.Emit(OpCodes.Br, End); // Execute code for false and move on Generator.MarkLabel(False); EmitStatementCollection(Condition.FalseStatements); Generator.MarkLabel(End); }
public void Visit(WhenLiteralStatement statement) { CodeStatementCollection collection = new CodeStatementCollection(); var arg = VisitChild(statement.Literal); var condition = new CodeConditionStatement(); if (arg.Tag != null) //this is a null literal { condition.Condition = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("var"), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null)); } else { var preCondition = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("var"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)); condition.Condition = new CodeBinaryOperatorExpression(preCondition, CodeBinaryOperatorType.BooleanAnd, new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("var"), "Equals", arg.CodeExpression)); } var then = VisitChild(statement.Then); condition.TrueStatements.Add(new CodeMethodReturnStatement(then.CodeExpression)); _codeStack.Peek().Tag = then.Tag; _codeStack.Peek().ParentStatements.Add(condition); }
internal static void BuildEvalExpression(string field, string formatString, string propertyName, Type propertyType, ControlBuilder controlBuilder, CodeStatementCollection methodStatements, CodeStatementCollection statements, CodeLinePragma linePragma, ref bool hasTempObject) { CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression { Method = { TargetObject = new CodeThisReferenceExpression(), MethodName = "Eval" } }; expression.Parameters.Add(new CodePrimitiveExpression(field)); if (!string.IsNullOrEmpty(formatString)) { expression.Parameters.Add(new CodePrimitiveExpression(formatString)); } CodeStatementCollection statements2 = new CodeStatementCollection(); BuildPropertySetExpression(expression, propertyName, propertyType, controlBuilder, methodStatements, statements2, linePragma, ref hasTempObject); CodeMethodInvokeExpression left = new CodeMethodInvokeExpression { Method = { TargetObject = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Page"), MethodName = "GetDataItem" } }; CodeConditionStatement statement = new CodeConditionStatement { Condition = new CodeBinaryOperatorExpression(left, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)) }; statement.TrueStatements.AddRange(statements2); statements.Add(statement); }
// Generate a series of codedom if statements representing a switch block. // (Codedom doesn't support switch) public static CodeStatement Emit(SwitchBlock switchBlock) { // Create the expression for whatever we're switching on. var codeVar = CodeDomEmitter.EmitCodeExpression(switchBlock.Variable.ChildExpressions[0]); // Store the first and previous if statements here, since it's needed on future loops. CodeConditionStatement codeIf = null; CodeConditionStatement lastIf = null; foreach(var e in switchBlock.ChildExpressions) { // Get the value being compared to: the right operand. var right = CodeDomEmitter.EmitCodeExpression((e as CaseBlock).Variable.ChildExpressions[0]); // Create the next if statement. var nestedIf = new CodeConditionStatement(); // Each case block will compare codeVar (left) to the right operand. nestedIf.Condition = new CodeBinaryOperatorExpression(codeVar, CodeBinaryOperatorType.ValueEquality, right); nestedIf.TrueStatements.Add(new CodeCommentStatement("If condition is true, execute these statements.")); foreach (var s in e.ChildExpressions) nestedIf.TrueStatements.Add(CodeDomEmitter.EmitCodeStatement(s)); nestedIf.FalseStatements.Add(new CodeCommentStatement("If condition is false, execute these statements.")); // if codeIf is null, this is the first if statement. if (codeIf == null) { codeIf = nestedIf; } else // It's not the first if statement, so attach it to the previous one. { lastIf.FalseStatements.Add(nestedIf); } // Store the last if block for the next iteration. lastIf = nestedIf; } return codeIf; }
static void Main(string[] args) { CodeCompileUnit compileUnit = new CodeCompileUnit(); CodeNamespace myNamespace = new CodeNamespace("TestNamespace"); myNamespace.Imports.Add(new CodeNamespaceImport("System")); CodeTypeDeclaration myClass = new CodeTypeDeclaration("MyClass"); CodeEntryPointMethod start = new CodeEntryPointMethod(); CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("Console"), "WriteLine", new CodePrimitiveExpression("Hello World!")); CodeMemberField memberField = new CodeMemberField(); memberField.Type = new CodeTypeReference(typeof(float)); CodeMemberProperty memberPropery = new CodeMemberProperty(); //memberPropery.ha CodeConditionStatement cond = new CodeConditionStatement(); compileUnit.Namespaces.Add(myNamespace); myNamespace.Types.Add(myClass); myClass.Members.Add(start); start.Statements.Add(cs1); CSharpCodeProvider provider = new CSharpCodeProvider(); using (StreamWriter sw = new StreamWriter("Helloworld.cs", false)) { IndentedTextWriter tw = new IndentedTextWriter(sw, " "); provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions()); tw.Close(); } }
/// <summary> /// Creates the property changed method. /// </summary> /// <returns>CodeMemberMethod on Property Change handler</returns> /// <remarks> /// <code> /// protected virtual void OnPropertyChanged(string info) { /// PropertyChangedEventHandler handler = PropertyChanged; /// if (handler != null) { /// handler(this, new PropertyChangedEventArgs(info)); /// } /// } /// </code> /// </remarks> internal static CodeMemberMethod CreatePropertyChangedMethod() { const string paramName = "propertyName"; const string variableName = "handler"; var propertyChangedMethod = new CodeMemberMethod { Name = "OnPropertyChanged", Attributes = MemberAttributes.Public }; propertyChangedMethod.Parameters.Add(new CodeParameterDeclarationExpression( new CodeTypeReference(typeof(String)), paramName)); if (GeneratorContext.GeneratorParams.TrackingChanges.Enabled && GeneratorContext.GeneratorParams.Language == GenerationLanguage.CSharp) { propertyChangedMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "value")); // this.ChangeTracker.RecordCurrentValue(info, value); var changeTrackerParams = new CodeExpression[] { new CodeArgumentReferenceExpression(paramName), new CodeArgumentReferenceExpression(("value")) }; var changeTrackerInvokeExpression = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "ChangeTracker.RecordCurrentValue"), changeTrackerParams); propertyChangedMethod.Statements.Add(changeTrackerInvokeExpression); } //Declare temp variable holding the event var vardec = new CodeVariableDeclarationStatement( new CodeTypeReference(typeof(PropertyChangedEventHandler)), variableName); vardec.InitExpression = new CodeEventReferenceExpression( new CodeThisReferenceExpression(), "PropertyChanged"); propertyChangedMethod.Statements.Add(vardec); //The part of the true, create the event and invoke it //var createArgs = new CodeObjectCreateExpression( // new CodeTypeReference(typeof(PropertyChangedEventArgs)), // new CodeArgumentReferenceExpression(paramName)); var createArgs = CodeDomHelper.CreateInstance(typeof(PropertyChangedEventArgs), paramName); var raiseEvent = new CodeDelegateInvokeExpression( new CodeVariableReferenceExpression(variableName), new CodeThisReferenceExpression(), createArgs); //The Condition CodeExpression condition = new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression(variableName), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)); //The if condition var ifTempIsNull = new CodeConditionStatement(); ifTempIsNull.Condition = condition; ifTempIsNull.TrueStatements.Add(raiseEvent); propertyChangedMethod.Statements.Add(ifTempIsNull); return propertyChangedMethod; }
public override object Visit(IfElseStatement ifElseStatement, object data) { ProcessSpecials(ifElseStatement.Specials); CodeConditionStatement ifStmt = new CodeConditionStatement(); ifStmt.Condition = (CodeExpression)ifElseStatement.Condition.AcceptVisitor(this, data); codeStack.Push(ifStmt.TrueStatements); ifElseStatement.EmbeddedStatement.AcceptChildren(this, data); codeStack.Pop(); codeStack.Push(ifStmt.FalseStatements); ifElseStatement.EmbeddedElseStatement.AcceptChildren(this, data); codeStack.Pop(); AddStmt(ifStmt); return ifStmt; }
private void AddINotifyPropertyChangedRegion(CodeTypeDeclaration declaration) { CodeMemberEvent memberEvent = new CodeMemberEvent(); declaration.Members.Add(memberEvent); memberEvent.Attributes = MemberAttributes.Public; memberEvent.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "INotifyPropertyChanged Members")); memberEvent.Name = "PropertyChanged"; memberEvent.Type = new CodeTypeReference("PropertyChangedEventHandler"); CodeMemberMethod propertyChangedMethod = new CodeMemberMethod(); declaration.Members.Add(propertyChangedMethod); propertyChangedMethod.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, null)); propertyChangedMethod.Attributes = MemberAttributes.Family; propertyChangedMethod.Name = Common.PropertyChangedInternalMethod; propertyChangedMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof (string), "information")); CodeConditionStatement ifStatement = new CodeConditionStatement( new CodeBinaryOperatorExpression( new CodeFieldReferenceExpression(null, "PropertyChanged"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null) ), new CodeExpressionStatement( new CodeMethodInvokeExpression(null, "PropertyChanged", new CodeThisReferenceExpression(), new CodeObjectCreateExpression( "PropertyChangedEventArgs", new CodeFieldReferenceExpression(null, "information")))) ); propertyChangedMethod.Statements.Add(ifStatement); }
private void GenerateCodeFromCodeConditionStatement(CodeConditionStatement e, TextWriter w) { w.Write("if ("); GenerateCodeFromExpression(e.Condition, w, null); w.WriteLine(")"); w.WriteLine("{"); foreach (CodeStatement codeStatement in e.TrueStatements) { GenerateCodeFromStatement(codeStatement, w, null); } w.WriteLine("}"); if (e.FalseStatements.Count > 0) { w.WriteLine("else"); w.WriteLine("{"); foreach (CodeStatement codeStatement in e.FalseStatements) { GenerateCodeFromStatement(codeStatement, w, null); } w.WriteLine("}"); } }
protected override void GenerateConditionStatement(System.CodeDom.CodeConditionStatement e) { throw new Exception("The method or operation is not implemented."); }