public void Constructor1 ()
		{
			string stmt = "mono";

			CodeSnippetStatement css = new CodeSnippetStatement (stmt);
			Assert.IsNull (css.LinePragma, "#1");

			Assert.IsNotNull (css.Value, "#2");
			Assert.AreEqual (stmt, css.Value, "#3");
			Assert.AreSame (stmt, css.Value, "#4");

			Assert.IsNotNull (css.StartDirectives, "#5");
			Assert.AreEqual (0, css.StartDirectives.Count, "#6");

			Assert.IsNotNull (css.EndDirectives, "#7");
			Assert.AreEqual (0, css.EndDirectives.Count, "#8");

			Assert.IsNotNull (css.UserData, "#9");
			Assert.AreEqual (typeof(ListDictionary), css.UserData.GetType (), "#10");
			Assert.AreEqual (0, css.UserData.Count, "#11");
			
			css.Value = null;
			Assert.IsNotNull (css.Value, "#12");
			Assert.AreEqual (string.Empty, css.Value, "#13");

			CodeLinePragma clp = new CodeLinePragma ("mono", 10);
			css.LinePragma = clp;
			Assert.IsNotNull (css.LinePragma, "#14");
			Assert.AreSame (clp, css.LinePragma, "#15");

			css = new CodeSnippetStatement ((string) null);
			Assert.IsNotNull (css.Value, "#16");
			Assert.AreEqual (string.Empty, css.Value, "#17");
		}
 public TypescriptSnippetStatement(
     IExpressionFactory expressionFactory,
     CodeSnippetStatement statement,
     CodeGeneratorOptions options)
 {
     _expressionFactory = expressionFactory;
     _statement = statement;
     _options = options;
 }
Example #3
0
        private void execute_Click(object sender, EventArgs e)
        {
            // eine CompileUnit erstellen die das Programm hält
            CodeCompileUnit compileUnit = new CodeCompileUnit();
            // namespace definieren
            CodeNamespace samples = new CodeNamespace("InjectionExample");
            // genutzte namespaces importieren
            foreach(String import in includes.CheckedItems)
                samples.Imports.Add(new CodeNamespaceImport(import));

            samples.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
            // namespaces zur CompileUnit hinzufügen
            compileUnit.Namespaces.Add(samples);

            // eine neue Klasse definieren
            CodeTypeDeclaration container = new CodeTypeDeclaration("CodeContainerClass");
            // Klasse hinzufügen
            samples.Types.Add(container);

            /*
             * eine public methode erstellen
             */
            CodeMemberMethod pub_method = new CodeMemberMethod();
            pub_method.Name = "execute";
            pub_method.ReturnType = new CodeTypeReference("System.Double");
            pub_method.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            pub_method.Parameters.Add(new CodeParameterDeclarationExpression("Label", "label"));
            CodeSnippetStatement input = new CodeSnippetStatement();
            input.Value = code.Text;
            pub_method.Statements.Add(input);
            container.Members.Add(pub_method); // der Klasse die Methode hinzufügen

            CodeDOMTest.Generator gen;
            if(radio_csharp.Checked)
                gen = new CodeDOMTest.Generator(new CSharpCodeProvider());
            else
                gen = new CodeDOMTest.Generator(new VBCodeProvider());

            // Quellfile erstellen
            String gen_code = gen.GenerateCSharpCode(compileUnit);
            gencode.ResetText();
            gencode.Text = gen_code;

            // Quellfile compilieren
            String compiler_message;
            Assembly compiled_code = gen.CompileCSharpCode(gen_code, out compiler_message);
            compiler_output.ResetText();
            compiler_output.Text = compiler_message;

            // execute the Assembly
            if (compiled_code != null)
            {
                Object[] args = {change_label};
                Double ret = (Double)gen.InvokeMethod(compiled_code, "CodeContainerClass", "execute", args);
                result.Text = ret.ToString();
            }
        }
Example #4
0
        // Generate the CodeDom for our render method
        internal CodeMemberMethod GenerateRenderMemberMethod(string virtualPath)
        {
            Control container = Parent;

            string physicalPath = HostingEnvironment.MapPath(virtualPath);

            CodeMemberMethod renderMethod = new CodeMemberMethod();
            renderMethod.Name = RenderMethodName;
            renderMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "__srh"));

            // REVIEW: we need support for CodeArgumentReferenceExpression, as using a snippet is
            // not guanranteed to be language agnostic
            CodeExpression snippetRenderHelper = new CodeArgumentReferenceExpression("__srh");

            // Go through all the children to build the CodeDOM tree
            for (int controlIndex = 0; controlIndex < container.Controls.Count; controlIndex++) {
                Control c = container.Controls[controlIndex];

                if (!(c is SnippetControl || c is ExpressionSnippetControl)) {

                    // If it's a regular control, generate a call to render it based on its index

                    CodeExpression method = new CodeMethodInvokeExpression(snippetRenderHelper, "RenderControl",
                        new CodePrimitiveExpression(controlIndex));
                    renderMethod.Statements.Add(new CodeExpressionStatement(method));

                    continue;
                }

                BaseCodeControl codeControl = (BaseCodeControl)c;

                string code = codeControl.Code;
                CodeStatement stmt;

                if (codeControl is SnippetControl) {

                    // If it's a <% code %> block, just append the code as is

                    stmt = new CodeSnippetStatement(code);
                } else {

                    // If it's a <%= expr %> block, generate a call to render it

                    CodeExpression method = new CodeMethodInvokeExpression(snippetRenderHelper, "Render",
                        new CodeSnippetExpression(code));
                    stmt = new CodeExpressionStatement(method);
                }

                stmt.LinePragma = new CodeLinePragma(physicalPath, codeControl.Line);
                renderMethod.Statements.Add(stmt);
            }

            return renderMethod;
        }
 public void AddDesignTimeHelperStatement(CodeSnippetStatement statement)
 {
     if (_designTimeHelperMethod == null)
     {
         _designTimeHelperMethod = new CodeMemberMethod()
         {
             Name = DesignTimeHelperMethodName,
             Attributes = MemberAttributes.Private
         };
         _designTimeHelperMethod.Statements.Add(
             new CodeSnippetStatement(BuildCodeString(cw => cw.WriteDisableUnusedFieldWarningPragma())));
         _designTimeHelperMethod.Statements.Add(
             new CodeSnippetStatement(BuildCodeString(cw => cw.WriteRestoreUnusedFieldWarningPragma())));
         GeneratedClass.Members.Insert(0, _designTimeHelperMethod);
     }
     _designTimeHelperMethod.Statements.Insert(_designTimeHelperMethod.Statements.Count - 1, statement);
 }
		/* sample super simple framedecider
		using CNCMaps.Engine.Map;

		namespace SampleSimpleFramedecider {
			class FrameDecider {
				public static int DecideFrame(GameObject obj) {
					if (obj is OwnableObject)
						return (obj as OwnableObject).Direction / 32;
					else
						return 0;
				}
			}
		}
		*/

		public static Func<GameObject, int> CompileFrameDecider(string codeStr) {
			var unit = new CodeCompileUnit();
			var ns = new CodeNamespace("DynamicFrameDeciders");
			ns.Imports.Add(new CodeNamespaceImport("CNCMaps.Engine.Map"));
			unit.Namespaces.Add(ns);

			var @class = new CodeTypeDeclaration("FrameDecider"); //Create class
			ns.Types.Add(@class);

			var method = new CodeMemberMethod();
			method.Attributes = MemberAttributes.Public | MemberAttributes.Static;
			//Make this method an override of base class's method
			method.Name = "DecideFrame";
			method.ReturnType = new CodeTypeReference(typeof(int));
			method.Parameters.Add(new CodeParameterDeclarationExpression("GameObject", "obj"));
			var code = new CodeSnippetStatement(codeStr + ";");
			method.Statements.Add(new CodeSnippetStatement("int frame = 0;"));
			method.Statements.Add(code);
			method.Statements.Add(new CodeSnippetStatement("return frame;"));
			@class.Members.Add(method); //Add method to the class

			// compile DOM
			CodeDomProvider cp = CodeDomProvider.CreateProvider("CS");
			var options = new CompilerParameters();
			
			options.GenerateInMemory = true;
			options.ReferencedAssemblies.Add(typeof(Map.Map).Assembly.Location);
			options.ReferencedAssemblies.Add(typeof(CNCMaps.Shared.ModConfig).Assembly.Location);
			var cpRes = cp.CompileAssemblyFromDom(options, unit);
			AppDomain localDom = AppDomain.CreateDomain("x");

			// now bind the method
			MethodInfo mi = cpRes.CompiledAssembly.GetType("DynamicFrameDeciders.FrameDecider").GetMethod("DecideFrame");

			// and wrap it
			return obj => (int)mi.Invoke(null, new[] {obj});
		}
        protected override void WriteSnippetStatement(CodeSnippetStatement s) {
            string snippet = s.Value;

            // Finally, append the snippet. Make sure that it is indented properly if
            // it has nested newlines
            Writer.Write(IndentSnippetStatement(snippet));
            Writer.Write('\n');

            // See if the snippet changes our indent level
            string lastLine = snippet.Substring(snippet.LastIndexOf('\n') + 1);
            // If the last line is only whitespace, then we have a new indent level
            if (lastLine.Trim('\t', ' ') == "") {
                lastLine = lastLine.Replace("\t", "        ");
                int indentLen = lastLine.Length;
                if (indentLen > _indents.Peek()) {
                    _indents.Push(indentLen);
                }
                else {
                    while (indentLen < _indents.Peek()) {
                        _indents.Pop();
                    }
                }
            }
        }
        public override void GenerateCode(Span target, CodeGeneratorContext context)
        {
            context.GeneratedClass.BaseTypes.Clear();
            context.GeneratedClass.BaseTypes.Add(new CodeTypeReference(ResolveType(context, BaseType.Trim())));

            if (context.Host.DesignTimeMode)
            {
                int generatedCodeStart = 0;
                string code = context.BuildCodeString(cw =>
                {
                    generatedCodeStart = cw.WriteVariableDeclaration(target.Content, "__inheritsHelper", null);
                    cw.WriteEndStatement();
                });

                int paddingCharCount;

                CodeSnippetStatement stmt = new CodeSnippetStatement(
                    CodeGeneratorPaddingHelper.Pad(context.Host, code, target, generatedCodeStart, out paddingCharCount))
                {
                    LinePragma = context.GenerateLinePragma(target, generatedCodeStart + paddingCharCount)
                };
                context.AddDesignTimeHelperStatement(stmt);
            }
        }
 public CodeLanguageSnippetStatement(CodeSnippetStatement csStatement, CodeSnippetStatement vbStatement)
 {
     _csStatement = csStatement;
     _vbStatement = vbStatement;
 }
        private CodeMemberMethod EnsureStyleConnector()
        {
            if (_ccRoot.StyleConnectorFn == null)
            {
                _ccRoot.StyleConnectorFn = new CodeMemberMethod();
                _ccRoot.StyleConnectorFn.Name = CONNECT;
                _ccRoot.StyleConnectorFn.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                _ccRoot.StyleConnectorFn.PrivateImplementationType = new CodeTypeReference(KnownTypes.Types[(int)KnownElements.IStyleConnector]);

                // void IStyleConnector.Connect(int connectionId, object target) {
                //
                CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression(typeof(int), CONNECTIONID);
                CodeParameterDeclarationExpression param2 = new CodeParameterDeclarationExpression(typeof(object), TARGET);
                _ccRoot.StyleConnectorFn.Parameters.Add(param1);
                _ccRoot.StyleConnectorFn.Parameters.Add(param2);

                AddDebuggerNonUserCodeAttribute(_ccRoot.StyleConnectorFn);
                AddGeneratedCodeAttribute(_ccRoot.StyleConnectorFn);
                AddEditorBrowsableAttribute(_ccRoot.StyleConnectorFn);
                AddSuppressMessageAttribute(_ccRoot.StyleConnectorFn, "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes");
                AddSuppressMessageAttribute(_ccRoot.StyleConnectorFn, "Microsoft.Performance", "CA1800:DoNotCastUnnecessarily");
                AddSuppressMessageAttribute(_ccRoot.StyleConnectorFn, "Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity");

                if (SwitchStatementSupported())
                {
                    // switch (connectionId) -- Start Switch
                    // {
                    CodeSnippetStatement css = new CodeSnippetStatement(SWITCH_STATEMENT);
                    _ccRoot.StyleConnectorFn.Statements.Add(css);
                }
            }

            return _ccRoot.StyleConnectorFn;
        }
        internal void ConnectNameAndEvents(string elementName, ArrayList events, int connectionId)
        {
            CodeContext cc = (CodeContext)_codeContexts.Peek();
            bool isAllowedNameScope = cc.IsAllowedNameScope;

            if (_codeContexts.Count > 1 && KnownTypes.Types[(int)KnownElements.INameScope].IsAssignableFrom(cc.ElementType))
            {
                cc.IsAllowedNameScope = false;
            }

            if ((elementName == null || !isAllowedNameScope) && (events == null || events.Count == 0))
            {
                _typeArgsList = null;
                return;
            }

            EnsureHookupFn();

            CodeConditionStatement ccsConnector = null;

            if (SwitchStatementSupported())
            {
                // case 1:
                //
                CodeSnippetStatement cssCase = new CodeSnippetStatement(CASE_STATEMENT + connectionId + COLON);
                _ccRoot.HookupFn.Statements.Add(cssCase);
            }
            else
            {
                // if (connectionId == 1)
                //
                ccsConnector = new CodeConditionStatement();
                ccsConnector.Condition = new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression(CONNECTIONID),
                                                                          CodeBinaryOperatorType.ValueEquality,
                                                                          new CodePrimitiveExpression(connectionId));
            }


            // (System.Windows.Controls.Footype)target;
            CodeArgumentReferenceExpression careTarget = new CodeArgumentReferenceExpression(TARGET);
            CodeCastExpression cceTarget = new CodeCastExpression(cc.ElementTypeReference, careTarget);
            CodeExpression ceEvent = cceTarget;

            // Names in nested Name scopes not be hooked up via ICC.Connect() as no fields are generated in this case.
            if (elementName != null && isAllowedNameScope)
            {
                // this.fooId = (System.Windows.Controls.Footype)target;
                //
                ceEvent = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), elementName);
                CodeAssignStatement casName = new CodeAssignStatement(ceEvent, cceTarget);
                if (SwitchStatementSupported())
                {
                    _ccRoot.HookupFn.Statements.Add(casName);
                }
                else
                {
                    ccsConnector.TrueStatements.Add(casName);
                }
            }

            if (events != null)
            {
                foreach (MarkupEventInfo mei in events)
                {
                    CodeStatement csEvent = AddCLREvent(cc, ceEvent, mei);

                    if (SwitchStatementSupported())
                    {
                        _ccRoot.HookupFn.Statements.Add(csEvent);
                    }
                    else
                    {
                        ccsConnector.TrueStatements.Add(csEvent);
                    }
                }
            }

            // return;
            //
            if (SwitchStatementSupported())
            {
                _ccRoot.HookupFn.Statements.Add(new CodeMethodReturnStatement());
            }
            else
            {
                ccsConnector.TrueStatements.Add(new CodeMethodReturnStatement());
                _ccRoot.HookupFn.Statements.Add(ccsConnector);
            }

            _typeArgsList = null;
        }
Example #12
0
 protected override void GenerateSnippetStatement(CodeSnippetStatement e)
 {
     base.Output.WriteLine(e.Value);
 }
Example #13
0
		protected virtual void GenerateSnippetStatement (CodeSnippetStatement s)
		{
			output.WriteLine (s.Value);
		}
 private  void GenerateSnippetStatement(CodeSnippetStatement e) {
     Output.WriteLine(e.Value);
 }
Example #15
0
        /// <summary>生成Render方法</summary>
        /// <param name="blocks"></param>
        /// <param name="lineNumbers"></param>
        /// <param name="typeDec"></param>
        private static void CreateRenderMethod(List<Block> blocks, Boolean lineNumbers, CodeTypeDeclaration typeDec)
        {
            CodeMemberMethod method = new CodeMemberMethod();
            typeDec.Members.Add(method);
            method.Name = "Render";
            method.Attributes = MemberAttributes.Override | MemberAttributes.Public;
            method.ReturnType = new CodeTypeReference(typeof(String));

            // 生成代码
            CodeStatementCollection statementsMain = method.Statements;
            Boolean firstMemberFound = false;
            foreach (Block block in blocks)
            {
                if (block.Type == BlockType.Directive) continue;
                if (block.Type == BlockType.Member)
                {
                    // 遇到类成员代码块,标识取反
                    firstMemberFound = !firstMemberFound;
                    continue;
                }
                // 只要现在还在类成员代码块区域内,就不做处理
                if (firstMemberFound) continue;

                if (block.Type == BlockType.Statement)
                {
                    // 代码语句,直接拼接
                    CodeSnippetStatement statement = new CodeSnippetStatement(block.Text);
                    if (lineNumbers)
                        AddStatementWithLinePragma(block, statementsMain, statement);
                    else
                        statementsMain.Add(statement);
                }
                else if (block.Type == BlockType.Text)
                {
                    // 模版文本,直接Write
                    if (!String.IsNullOrEmpty(block.Text))
                    {
                        CodeMethodInvokeExpression exp = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Write", new CodeExpression[] { new CodePrimitiveExpression(block.Text) });
                        //statementsMain.Add(exp);
                        CodeExpressionStatement statement = new CodeExpressionStatement(exp);
                        if (lineNumbers)
                            AddStatementWithLinePragma(block, statementsMain, statement);
                        else
                            statementsMain.Add(statement);
                    }
                }
                else
                {
                    // 表达式,直接Write
                    CodeMethodInvokeExpression exp = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Write", new CodeExpression[] { new CodeArgumentReferenceExpression(block.Text.Trim()) });
                    CodeExpressionStatement statement = new CodeExpressionStatement(exp);
                    if (lineNumbers)
                        AddStatementWithLinePragma(block, statementsMain, statement);
                    else
                        statementsMain.Add(statement);
                }
            }

            statementsMain.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Output"), "ToString"), new CodeExpression[0])));
        }
Example #16
0
 private void ValidateSnippetStatement(CodeSnippetStatement e) {
 }
Example #17
0
        static string GetTableClass(DataTable TableSchema, string ClassNamespace, string ClassName)
        {
            string result = string.Empty;

            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
            CodeNamespace tableClassNamespace = new CodeNamespace(ClassNamespace);
            codeCompileUnit.Namespaces.Add(tableClassNamespace);

            //we need this for AppDomain to work since we need to use MarshalByRefObject
            CodeNamespaceImport codeNamespaceImport = null;
            codeNamespaceImport = new CodeNamespaceImport()
            {
                Namespace = "System"
            };
            tableClassNamespace.Imports.Add(codeNamespaceImport);
            codeNamespaceImport = new CodeNamespaceImport()
            {
                Namespace = "System.Reflection"
            };
            tableClassNamespace.Imports.Add(codeNamespaceImport);

            CodeTypeDeclaration trackerTableClass = new CodeTypeDeclaration()
            {
                Name = ClassName,
                IsClass = true,
                IsEnum = false,
                IsInterface = false,
                IsPartial = false,
                IsStruct = false
            };
            //we need this for AppDomain
            //trackerTableClass.BaseTypes.Add("MarshalByRefObject");
            tableClassNamespace.Types.Add(trackerTableClass);

            CodeMemberProperty columnProperty = null;
            CodeCommentStatement codeCommentStatement = null;
            CodeSnippetStatement codeSnippetStatement = null;
            CodeMethodReturnStatement codeMethodReturnStatement = null;

            //define constructor for POCO
            CodeConstructor codeConstructor = new CodeConstructor()
            {
                Attributes = MemberAttributes.Public
            };

            //add properties to the POCO
            foreach (DataRow row in from dataRow in TableSchema.Rows.Cast<DataRow>()
                                    orderby int.Parse(dataRow[ColumnOrdinal].ToString())
                                    select dataRow)
            {
                if (!bool.Parse(row[IsIdentity].ToString()))
                {
                    //create the property
                    columnProperty = new CodeMemberProperty()
                    {
                        Name = CleanColumnName(row[ColumnName].ToString()),
                        Type = new CodeTypeReference(Type.GetType(row[DataType].ToString())),
                        Attributes = MemberAttributes.Public | MemberAttributes.Final,
                        HasGet = true,
                        HasSet = false
                    };

                    //comment this property
                    codeCommentStatement = new CodeCommentStatement(string.Format("[{0}] column", row[ColumnName].ToString()));
                    columnProperty.Comments.Add(codeCommentStatement);

                    //add the get statements for this property
                    string script = GetColumnScript(row[ColumnName].ToString());

                    if (string.IsNullOrWhiteSpace(script))
                    {
                        //add comment that the script file was not found
                        codeCommentStatement = new CodeCommentStatement(string.Format("script file not found for column {0}.", row[ColumnName].ToString()));
                        columnProperty.GetStatements.Add(codeCommentStatement);
                        codeMethodReturnStatement = new CodeMethodReturnStatement(new CodeSnippetExpression(@""""""));
                        columnProperty.GetStatements.Add(codeMethodReturnStatement);

                    }
                    else
                    {
                        //add the script code snippet
                        codeSnippetStatement = new CodeSnippetStatement(script);
                        columnProperty.GetStatements.Add(codeSnippetStatement);
                    }

                    //add this property to the class
                    trackerTableClass.Members.Add(columnProperty);
                }
                else
                {
                    codeCommentStatement = new CodeCommentStatement(string.Format("Property {0} for table column {1} not created because it is the identity column.", CleanColumnName(row[ColumnName].ToString()), row[ColumnName].ToString()));
                    trackerTableClass.Comments.Add(codeCommentStatement);
                }
            }

            #region render code
            CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions()
            {
                BracingStyle = "C",
                VerbatimOrder = true,
                BlankLinesBetweenMembers = true,
                ElseOnClosing = false
            };

            CodeDomProvider codeDomProvider = null;
            using (StringWriter stringWriter = new StringWriter())
            {
                codeDomProvider = new CSharpCodeProvider();
                codeDomProvider.GenerateCodeFromCompileUnit(codeCompileUnit,
                                                            stringWriter,
                                                            codeGeneratorOptions);
                result = stringWriter.ToString();
            }
            #endregion

            return result;
        }
        public static CodeCompileUnit GenerateCompileUnit(ITextTemplatingEngineHost host, ParsedTemplate pt,
		                                                   TemplateSettings settings)
        {
            //prep the compile unit
            var ccu = new CodeCompileUnit ();
            var namespac = new CodeNamespace (settings.Namespace);
            ccu.Namespaces.Add (namespac);

            var imports = new HashSet<string> ();
            imports.UnionWith (settings.Imports);
            imports.UnionWith (host.StandardImports);
            foreach (string ns in imports)
                namespac.Imports.Add (new CodeNamespaceImport (ns));

            //prep the type
            var type = new CodeTypeDeclaration (settings.Name);
            type.IsPartial = true;
            if (!String.IsNullOrEmpty (settings.Inherits))
                type.BaseTypes.Add (new CodeTypeReference (settings.Inherits));
            else
                type.BaseTypes.Add (new CodeTypeReference (typeof (TextTransformation)));
            namespac.Types.Add (type);

            //prep the transform method
            var transformMeth = new CodeMemberMethod () {
                Name = "TransformText",
                ReturnType = new CodeTypeReference (typeof (String)),
                Attributes = MemberAttributes.Public | MemberAttributes.Override
            };

            //method references that will need to be used multiple times
            var writeMeth = new CodeMethodReferenceExpression (new CodeThisReferenceExpression (), "Write");
            var toStringMeth = new CodeMethodReferenceExpression (new CodeTypeReferenceExpression (typeof (ToStringHelper)), "ToStringWithCulture");
            bool helperMode = false;

            //build the code from the segments
            foreach (TemplateSegment seg in pt.Content) {
                CodeStatement st = null;
                var location = new CodeLinePragma (seg.StartLocation.FileName ?? host.TemplateFile, seg.StartLocation.Line);
                switch (seg.Type) {
                case SegmentType.Block:
                    if (helperMode)
                        //TODO: are blocks permitted after helpers?
                        throw new ParserException ("Blocks are not permitted after helpers", seg.StartLocation);
                    st = new CodeSnippetStatement (seg.Text);
                    break;
                case SegmentType.Expression:
                    st = new CodeExpressionStatement (
                        new CodeMethodInvokeExpression (writeMeth,
                            new CodeMethodInvokeExpression (toStringMeth, new CodeSnippetExpression (seg.Text))));
                    break;
                case SegmentType.Content:
                    st = new CodeExpressionStatement (new CodeMethodInvokeExpression (writeMeth, new CodePrimitiveExpression (seg.Text)));
                    break;
                case SegmentType.Helper:
                    type.Members.Add (new CodeSnippetTypeMember (seg.Text) { LinePragma = location });
                    helperMode = true;
                    break;
                default:
                    throw new InvalidOperationException ();
                }
                if (st != null) {
                    if (helperMode) {
                        //convert the statement into a snippet member and attach it to the top level type
                        //TODO: is there a way to do this for languages that use indentation for blocks, e.g. python?
                        using (var writer = new StringWriter ()) {
                            settings.Provider.GenerateCodeFromStatement (st, writer, null);
                            type.Members.Add (new CodeSnippetTypeMember (writer.ToString ()) { LinePragma = location });
                        }
                    } else {
                        st.LinePragma = location;
                        transformMeth.Statements.Add (st);
                        continue;
                    }
                }
            }

            //complete the transform method
            transformMeth.Statements.Add (new CodeMethodReturnStatement (
                new CodeMethodInvokeExpression (
                    new CodePropertyReferenceExpression (
                        new CodeThisReferenceExpression (),
                        "GenerationEnvironment"),
                        "ToString")));
            type.Members.Add (transformMeth);

            //generate the Host property if needed
            if (settings.HostSpecific) {
                var hostField = new CodeMemberField (new CodeTypeReference (typeof (ITextTemplatingEngineHost)), "hostValue");
                hostField.Attributes = (hostField.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private;
                type.Members.Add (hostField);

                var hostProp = new CodeMemberProperty () {
                    Name = "Host",
                    Attributes = MemberAttributes.Public,
                    HasGet = true,
                    HasSet = true,
                    Type = hostField.Type
                };
                var hostFieldRef = new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "hostValue");
                hostProp.SetStatements.Add (new CodeAssignStatement (hostFieldRef, new CodePropertySetValueReferenceExpression ()));
                hostProp.GetStatements.Add (new CodeMethodReturnStatement (hostFieldRef));
                type.Members.Add (hostProp);
            }

            return ccu;
        }
		public void CodeSnippetStatementTest ()
		{
			CodeSnippetStatement css = new CodeSnippetStatement ();
			statement = css;

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

			css.Value = "class";
			Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
				"class{0}", NewLine), Generate (), "#2");

			css.Value = null;
			Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
				"{0}", NewLine), Generate (), "#3");
		}
Example #20
0
		void AddCodeRender (ControlBuilder parent, CodeRenderBuilder cr)
		{
			if (cr.Code == null || cr.Code.Trim () == "")
				return;

			if (!cr.IsAssign) {
				CodeSnippetStatement code = new CodeSnippetStatement (cr.Code);
				parent.RenderMethod.Statements.Add (AddLinePragma (code, cr));
				return;
			}

			CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression ();
			expr.Method = new CodeMethodReferenceExpression (
							new CodeArgumentReferenceExpression ("__output"),
							"Write");

			expr.Parameters.Add (GetWrappedCodeExpression (cr));
			parent.RenderMethod.Statements.Add (AddLinePragma (expr, cr));
		}
		public void CodeTryCatchFinallyStatementTest ()
		{
			CodeStatement cs = new CodeGotoStatement ("exit");
			CodeCatchClause ccc1 = new CodeCatchClause ("ex1", new CodeTypeReference ("System.ArgumentException"));
			CodeCatchClause ccc2 = new CodeCatchClause (null, new CodeTypeReference ("System.ApplicationException"));
			CodeSnippetStatement fin1 = new CodeSnippetStatement ("A");
			CodeSnippetStatement fin2 = new CodeSnippetStatement ("B");

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

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

			options.ElseOnClosing = true;

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

			statement = new CodeTryCatchFinallyStatement ();

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

			options.ElseOnClosing = false;

			Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
				"try {{{0}" +
				"}}{0}", NewLine), Generate (), "#4");
		}
Example #22
0
        /// <summary>
        /// Processes the generators.
        /// </summary>
        /// <param name="source">source</param>
        /// <param name="classType">Type of the class.</param>
        /// <param name="method">The initialize method.</param>
        /// <param name="generateFields">if set to <c>true</c> [generate fields].</param>
        /// <returns></returns>
        public CodeExpression ProcessGenerators(object source, CodeTypeDeclaration classType, CodeMemberMethod method, bool generateFields)
        {
            if (source == null)
            {
                return null;
            }

            IGeneratorType generator;
            Type elementType = source.GetType();

            bool customUserControl = false;
            if (elementType.BaseType == typeof(UserControl))
            {
                // we have to retype any custom user control to fake generator so we can generate code for it
                customUserControl = true;
                elementType = typeof(CustomUserControlGeneratorType);
            }

            if (Generators.TryGetValue(elementType, out generator))
            {
                DependencyObject xamlSource = source as DependencyObject;

                if (xamlSource != null)
                {
                    CodeExpression parent = generator.Generate(xamlSource, classType, method, generateFields);
                    CodeComHelper.GenerateAttachedProperties(method, parent, xamlSource);

                    Type oldDataType = BindingGenerator.Instance.ActiveDataType;
                    Type newType = xamlSource.GetValue(GeneratedBindings.DataTypeProperty) as Type;
                    if (newType != null)
                    {
                        BindingGenerator.Instance.ActiveDataType = newType;
                    }

                    FrameworkElement elem = source as FrameworkElement;
                    if (elem != null)
                    {
                        CodeComHelper.GenerateBindings(method, parent, elem, elem.Name);
                        CodeComHelper.GenerateResourceReferences(method, parent, elem);

                        if (!customUserControl && (elem.Resources.Count != 0 || elem.Resources.MergedDictionaries.Count != 0))
                        {
                            ResourceDictionaryGenerator resourcesGenerator = new ResourceDictionaryGenerator();

                            CodeMemberMethod resourcesMethod = new CodeMemberMethod();
                            resourcesMethod.Attributes = MemberAttributes.Static | MemberAttributes.Private;
                            resourcesMethod.Name = "InitializeElement" + elem.Name + "Resources";
                            resourcesMethod.Parameters.Add(new CodeParameterDeclarationExpression("UIElement", "elem"));
                            classType.Members.Add(resourcesMethod);
                            resourcesGenerator.Generate(elem.Resources, classType, resourcesMethod,
                                new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("elem"), "Resources"));

                            method.Statements.Add(new CodeMethodInvokeExpression(null,resourcesMethod.Name, parent));
                        }
                    }

                    IEnumerable children = generator.GetChildren(xamlSource);
                    if (children != null)
                    {
                        foreach (DependencyObject child in children)
                        {
                            if (child == null)
                            {
                                continue;
                            }

                            int index = method.Statements.Count;
                            CodeExpression childRef = ProcessGenerators(child, classType, method, generateFields);
                            if (childRef != null)
                            {
                                generator.AddChild(parent, childRef, method, index + 2); // +1 for creating instance +1 for comment
                            }
                        }
                    }

                    BindingGenerator.Instance.ActiveDataType = oldDataType;

                    return parent;
                }
            }

            string errorText = "Unknown type : " + source.GetType();
            Console.WriteLine(errorText);
            CodeSnippetStatement error = new CodeSnippetStatement("#error " + errorText);
            method.Statements.Add(error);

            return null;
        }
Example #23
0
		public void Constructor1_Deny_Unrestricted ()
		{
			CodeSnippetStatement css = new CodeSnippetStatement ("mono");
			Assert.AreEqual ("mono", css.Value, "Value");
			css.Value = String.Empty;
		}
        private void EndStyleEventConnection()
        {
            if (_ccRoot.StyleConnectorFn != null)
            {
                _ccRoot.CodeClass.BaseTypes.Add(KnownTypes.Types[(int)KnownElements.IStyleConnector].FullName);

                if (SwitchStatementSupported())
                {
                    // break any last case staement as we are done with style event connections.
                    if (_ccRoot.StyleConnectorFn.Statements.Count > 1)
                    {
                        CodeSnippetStatement cssBreak = new CodeSnippetStatement(BREAK_STATEMENT);
                        _ccRoot.StyleConnectorFn.Statements.Add(cssBreak);
                    }

                    // switch (connectionId)
                    // {
                    // } -- End Switch
                    CodeSnippetStatement css = new CodeSnippetStatement(INDENT12 + ENDCURLY);
                    _ccRoot.StyleConnectorFn.Statements.Add(css);
                }

                _ccRoot.CodeClass.Members.Add(_ccRoot.StyleConnectorFn);
                _ccRoot.StyleConnectorFn = null;
            }
        }
Example #25
0
 /// <devdoc>
 ///    <para>
 ///       Generates code for the specified CodeDom based snippet statement
 ///       representation.
 ///    </para>
 /// </devdoc>
 protected virtual void GenerateSnippetStatement(CodeSnippetStatement e) {
     Output.WriteLine(e.Value);
 }
        private void EndHookups()
        {
            if (_ccRoot.HookupFn != null)
            {
                var iComponentConnector = new CodeTypeReference(KnownTypes.Types[(int)KnownElements.IComponentConnector]);
                _ccRoot.CodeClass.BaseTypes.Add(iComponentConnector);

                // Visual Basic requires InitializeComponent to explicitly implement IComponentConnector.InitializeComponent
                // if the class implements the interface. GenerateInitializeComponent handles the cases where the class is not
                // the entry point for any programming language.
                if (IsLanguageVB && IsCompilingEntryPointClass)
                {
                    _ccRoot.InitializeComponentFn.ImplementationTypes.Add(iComponentConnector);
                }

                if (SwitchStatementSupported())
                {
                    // Don't generate an empty Switch block!
                    if (_ccRoot.HookupFn.Statements.Count == 1 &&
                        _ccRoot.HookupFn.Statements[0] is CodeSnippetStatement)
                    {
                        _ccRoot.HookupFn.Statements.Clear();
                    }
                    else
                    {
                        // switch (connectionId)
                        // {
                        // } -- End Switch
                        CodeSnippetStatement css = new CodeSnippetStatement(INDENT12 + ENDCURLY);
                        _ccRoot.HookupFn.Statements.Add(css);
                    }
                }

                // _contentLoaded = true;
                //
                CodeFieldReferenceExpression cfreContentLoaded = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), CONTENT_LOADED);
                CodeAssignStatement casContentLoaded = new CodeAssignStatement(cfreContentLoaded, new CodePrimitiveExpression(true));
                _ccRoot.HookupFn.Statements.Add(casContentLoaded);

                _ccRoot.CodeClass.Members.Add(_ccRoot.HookupFn);
                _ccRoot.HookupFn = null;
            }
        }
Example #27
0
        private static Assembly GenerateAssembly(string asmxFile)
        {
            string strWsdl = WsdlFromUrl(GetApplicationPath() + "/" + asmxFile + "?wsdl");
            // Xml text reader
            StringReader wsdlStringReader = new StringReader(strWsdl);
            XmlTextReader tr = new XmlTextReader(wsdlStringReader);
            ServiceDescription sd = ServiceDescription.Read(tr);
            tr.Close();

            // WSDL service description importer 
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
            CodeNamespace codeNamespaceFluorine = new CodeNamespace("FluorineFx");
            codeCompileUnit.Namespaces.Add(codeNamespaceFluorine);
            CodeNamespace codeNamespace = new CodeNamespace(FluorineConfiguration.Instance.WsdlProxyNamespace);
            codeCompileUnit.Namespaces.Add(codeNamespace);

#if (NET_1_1)
            ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
            sdi.AddServiceDescription(sd, null, null);
            sdi.ProtocolName = "Soap";
            sdi.Import(codeNamespace, codeCompileUnit);
			CSharpCodeProvider provider = new CSharpCodeProvider();
#else
            // Create a WSDL collection.
            DiscoveryClientDocumentCollection wsdlCollection = new DiscoveryClientDocumentCollection();
            wsdlCollection.Add(asmxFile, sd);
            // Create a web refererence using the WSDL collection.
            WebReference reference = new WebReference(wsdlCollection, codeNamespace);
            reference.ProtocolName = "Soap12";
            // Create a web reference collection.
            WebReferenceCollection references = new WebReferenceCollection();
            references.Add(reference);

            WebReferenceOptions options = new WebReferenceOptions();
            options.Style = ServiceDescriptionImportStyle.Client;
            options.CodeGenerationOptions = CodeGenerationOptions.None;
            options.SchemaImporterExtensions.Add(typeof(DataTableSchemaImporterExtension).AssemblyQualifiedName);

            CSharpCodeProvider provider = new CSharpCodeProvider();
            ServiceDescriptionImporter.GenerateWebReferences(references, provider, codeCompileUnit, options);
            // Compile a proxy client
            //provider.GenerateCodeFromCompileUnit(codeCompileUnit, Console.Out, new CodeGeneratorOptions());

#endif

            //http://support.microsoft.com/default.aspx?scid=kb;en-us;326790
            //http://pluralsight.com/wiki/default.aspx/Craig.RebuildingWsdlExe
            if (!FluorineConfiguration.Instance.WsdlGenerateProxyClasses)
            {

                //Strip any code that isn't the proxy class itself.
                foreach (CodeNamespace cns in codeCompileUnit.Namespaces)
                {
                    // Remove anything that isn't the proxy itself
                    ArrayList typesToRemove = new ArrayList();
                    foreach (CodeTypeDeclaration codeType in cns.Types)
                    {
                        bool webDerived = false;
                        foreach (CodeTypeReference baseType in codeType.BaseTypes)
                        {
                            if (baseType.BaseType == "System.Web.Services.Protocols.SoapHttpClientProtocol")
                            {
                                webDerived = true;
                                break;
                            }
                        }
                        if (!webDerived)
                            typesToRemove.Add(codeType);
                        else
                        {
                            CodeAttributeDeclaration codeAttributeDeclaration = new CodeAttributeDeclaration(typeof(FluorineFx.RemotingServiceAttribute).FullName);
                            codeType.CustomAttributes.Add(codeAttributeDeclaration);
                            foreach (CodeTypeMember member in codeType.Members)
                            {
                                CodeConstructor ctor = member as CodeConstructor;
                                if (ctor != null)
                                {
                                    // We got a constructor
                                    // Add CookieContainer code
                                    // this.CookieContainer = new System.Net.CookieContainer(); //Session Cookie
                                    CodeSnippetStatement statement = new CodeSnippetStatement("this.CookieContainer = new System.Net.CookieContainer(); //Session Cookie");
                                    ctor.Statements.Add(statement);
                                }
                            }
                        }
                    }

                    foreach (CodeTypeDeclaration codeType in typesToRemove)
                    {
                        codeNamespace.Types.Remove(codeType);
                    }
                }
            }
            else
            {
                foreach (CodeNamespace cns in codeCompileUnit.Namespaces)
                {
                    foreach (CodeTypeDeclaration codeType in cns.Types)
                    {
                        bool webDerived = false;
                        foreach (CodeTypeReference baseType in codeType.BaseTypes)
                        {
                            if (baseType.BaseType == "System.Web.Services.Protocols.SoapHttpClientProtocol")
                            {
                                webDerived = true;
                                break;
                            }
                        }
                        if (webDerived)
                        {
                            CodeAttributeDeclaration codeAttributeDeclaration = new CodeAttributeDeclaration(typeof(FluorineFx.RemotingServiceAttribute).FullName);
                            codeType.CustomAttributes.Add(codeAttributeDeclaration);
                            foreach (CodeTypeMember member in codeType.Members)
                            {
                                CodeConstructor ctor = member as CodeConstructor;
                                if (ctor != null)
                                {
                                    // We got a constructor
                                    // Add CookieContainer code
                                    // this.CookieContainer = new System.Net.CookieContainer(); //Session Cookie
                                    CodeSnippetStatement statement = new CodeSnippetStatement("this.CookieContainer = new System.Net.CookieContainer(); //Session Cookie");
                                    ctor.Statements.Add(statement);
                                }
                            }
                        }
                    }
                }
            }
            if (FluorineConfiguration.Instance.ImportNamespaces != null)
            {
                for (int i = 0; i < FluorineConfiguration.Instance.ImportNamespaces.Count; i++)
                {
                    ImportNamespace importNamespace = FluorineConfiguration.Instance.ImportNamespaces[i];
                    codeNamespace.Imports.Add(new CodeNamespaceImport(importNamespace.Namespace));
                }
            }

            // source code generation
            StringBuilder srcStringBuilder = new StringBuilder();
            StringWriter sw = new StringWriter(srcStringBuilder);
#if (NET_1_1)
			ICodeGenerator icg = provider.CreateGenerator();
			icg.GenerateCodeFromCompileUnit(codeCompileUnit, sw, null);
#else
            provider.GenerateCodeFromCompileUnit(codeCompileUnit, sw, null);
#endif
            string srcWSProxy = srcStringBuilder.ToString();
            sw.Close();

            // assembly compilation.
            CompilerParameters cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add("System.Data.dll");
            cp.ReferencedAssemblies.Add("System.Xml.dll");
            cp.ReferencedAssemblies.Add("System.Web.Services.dll");

            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                if (assembly.GlobalAssemblyCache)
                {
                    //Only System namespace
                    if (assembly.GetName().Name.StartsWith("System"))
                    {
                        if (!cp.ReferencedAssemblies.Contains(assembly.GetName().Name + ".dll"))
                            cp.ReferencedAssemblies.Add(assembly.Location);
                    }
                }
                else
                {
                    if (assembly.GetName().Name.StartsWith("mscorlib"))
                        continue;
                    //if( assembly.Location.ToLower().StartsWith(System.Web.HttpRuntime.CodegenDir.ToLower()) )
                    //	continue;

                    try
                    {
                        if (assembly.Location != null && assembly.Location != string.Empty)
                            cp.ReferencedAssemblies.Add(assembly.Location);
                    }
                    catch (NotSupportedException)
                    {
                        //NET2
                    }
                }
            }

            cp.GenerateExecutable = false;
            //http://support.microsoft.com/kb/815251
            //http://support.microsoft.com/kb/872800
            cp.GenerateInMemory = false;//true; 
            cp.IncludeDebugInformation = false;
#if (NET_1_1)
			ICodeCompiler icc = provider.CreateCompiler();
			CompilerResults cr = icc.CompileAssemblyFromSource(cp, srcWSProxy);
#else
            CompilerResults cr = provider.CompileAssemblyFromSource(cp, srcWSProxy);
#endif
            if (cr.Errors.Count > 0)
            {
                StringBuilder sbMessage = new StringBuilder();
                sbMessage.Append(string.Format("Build failed: {0} errors", cr.Errors.Count));
                if (log.IsErrorEnabled)
                    log.Error(__Res.GetString(__Res.Wsdl_ProxyGenFail));
                foreach (CompilerError e in cr.Errors)
                {
                    log.Error(__Res.GetString(__Res.Compiler_Error, e.Line, e.Column, e.ErrorText));
                    sbMessage.Append("\n");
                    sbMessage.Append(e.ErrorText);
                }
                StringBuilder sbSourceTrace = new StringBuilder();
                sbSourceTrace.Append("Attempt to compile the generated source code:");
                sbSourceTrace.Append(Environment.NewLine);
                StringWriter swSourceTrace = new StringWriter(sbSourceTrace);
                IndentedTextWriter itw = new IndentedTextWriter(swSourceTrace, "    ");
                provider.GenerateCodeFromCompileUnit(codeCompileUnit, itw, new CodeGeneratorOptions());
                itw.Close();
                log.Error(sbSourceTrace.ToString());
                throw new FluorineException(sbMessage.ToString());
            }

            return cr.CompiledAssembly;
        }
        internal void ConnectStyleEvent(XamlClrEventNode xamlClrEventNode)
        {
            CodeConditionStatement ccsConnector = null;

            // validate the event handler name per C# grammar for identifiers
            ValidateEventHandlerName(xamlClrEventNode.EventName, xamlClrEventNode.Value);

            EnsureStyleConnector();

            if (!xamlClrEventNode.IsSameScope)
            {
                int connectionId = xamlClrEventNode.ConnectionId;
                if (SwitchStatementSupported())
                {
                    // break any previous case staements as we are starting a new connection scope.
                    if (_ccRoot.StyleConnectorFn.Statements.Count > 1)
                    {
                        CodeSnippetStatement cssBreak = new CodeSnippetStatement(BREAK_STATEMENT);
                        _ccRoot.StyleConnectorFn.Statements.Add(cssBreak);
                    }

                    // case 1:
                    //
                    CodeSnippetStatement cssCase = new CodeSnippetStatement(CASE_STATEMENT + connectionId + COLON);
                    _ccRoot.StyleConnectorFn.Statements.Add(cssCase);
                }
                else
                {
                    // if (connectionId == 1)
                    //
                    ccsConnector = new CodeConditionStatement();
                    ccsConnector.Condition = new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression(CONNECTIONID),
                                                                              CodeBinaryOperatorType.ValueEquality,
                                                                              new CodePrimitiveExpression(connectionId));
                }
            }
            else if (!SwitchStatementSupported())
            {
                // if in the same scope then use the if statement that was last generated
                // at the start of the scope
                Debug.Assert(_ccRoot.StyleConnectorFn.Statements.Count > 0);
                ccsConnector = _ccRoot.StyleConnectorFn.Statements[_ccRoot.StyleConnectorFn.Statements.Count - 1] as CodeConditionStatement;
                Debug.Assert(ccsConnector != null);
            }

            CodeArgumentReferenceExpression careTarget = new CodeArgumentReferenceExpression(TARGET);

            if (xamlClrEventNode.IsStyleSetterEvent)
            {
                // EventSetter declaration only once to avoid warning!
                if (!_hasEmittedEventSetterDeclaration)
                {
                    _hasEmittedEventSetterDeclaration = true;
                    
                    // EventSetter eventSetter;
                    //
                    CodeVariableDeclarationStatement cvdsES = new CodeVariableDeclarationStatement(KnownTypes.Types[(int)KnownElements.EventSetter], EVENTSETTER);
                    _ccRoot.StyleConnectorFn.Statements.Insert(0, cvdsES);
                }


                // eventSetter = new EventSetter();
                //
                CodeExpression[] esParams = {};
                CodeVariableReferenceExpression cvreES = new CodeVariableReferenceExpression(EVENTSETTER);
                CodeAssignStatement casES = new CodeAssignStatement(cvreES,
                                                                    new CodeObjectCreateExpression(KnownTypes.Types[(int)KnownElements.EventSetter],
                                                                                                   esParams));

                // eventSetter.Event = Button.ClickEvent;
                //
                CodePropertyReferenceExpression cpreEvent = new CodePropertyReferenceExpression(cvreES, EVENT);
                CodeAssignStatement casEvent = new CodeAssignStatement(cpreEvent,
                                                                       GetEvent(xamlClrEventNode.EventMember,
                                                                                xamlClrEventNode.EventName,
                                                                                xamlClrEventNode.Value));

                // eventSetter.Handler = new RoutedEventHandler(OnClick);
                //
                CodePropertyReferenceExpression cpreHandler = new CodePropertyReferenceExpression(cvreES, HANDLER);
                CodeAssignStatement casHandler = new CodeAssignStatement(cpreHandler,
                                                                         GetEventDelegate(null,
                                                                                          xamlClrEventNode.EventMember,
                                                                                          xamlClrEventNode.EventName,
                                                                                          xamlClrEventNode.Value));

                AddLinePragma(casHandler, xamlClrEventNode.LineNumber);

                // ((Style)target).Setters.Add(eventSetter);
                //
                CodeCastExpression cceTarget = new CodeCastExpression(KnownTypes.Types[(int)KnownElements.Style], careTarget);
                CodePropertyReferenceExpression cpreSetters = new CodePropertyReferenceExpression(cceTarget, SETTERS);
                CodeMethodInvokeExpression cmieAdd = new CodeMethodInvokeExpression(cpreSetters, ADD, cvreES);

                if (SwitchStatementSupported())
                {
                    _ccRoot.StyleConnectorFn.Statements.Add(casES);
                    _ccRoot.StyleConnectorFn.Statements.Add(casEvent);
                    _ccRoot.StyleConnectorFn.Statements.Add(casHandler);
                    _ccRoot.StyleConnectorFn.Statements.Add(new CodeExpressionStatement(cmieAdd));
                }
                else
                {
                    ccsConnector.TrueStatements.Add(casES);
                    ccsConnector.TrueStatements.Add(casEvent);
                    ccsConnector.TrueStatements.Add(casHandler);
                    ccsConnector.TrueStatements.Add(new CodeExpressionStatement(cmieAdd));
                    // Only add if statement at start of new scope
                    if (!xamlClrEventNode.IsSameScope)
                    {
                        _ccRoot.StyleConnectorFn.Statements.Add(ccsConnector);
                    }
                }
            }
            else
            {

                //
                // ((Foo)target).Bar += new BarEventHandler(OnBar);
                //
                // *or*
                //
                // ((Foo)target).AddHandler( Baz.BarEvent, new BarEventHandler(OnBar));
                //

                CodeCastExpression cceTarget;
                Type eventTarget;


                // Create the markup event information

                MarkupEventInfo mei = new MarkupEventInfo( xamlClrEventNode.Value,          // Event handler string
                                                           xamlClrEventNode.EventName,      // Event name string
                                                           xamlClrEventNode.EventMember,    // MemberInfo
                                                           xamlClrEventNode.LineNumber);    // LineNumber


                // Get the type that defines the event (e.g. typeof(Button) for Button.Clicked or typeof(Mouse) for Mouse.MouseMove)

                eventTarget = xamlClrEventNode.ListenerType;


                // Create the type cast expression "(Foo)target"

                cceTarget = new CodeCastExpression( eventTarget, careTarget);


                // Create the whole code statement (either in += form or in AddHandler form)

                CodeStatement csAddCLREvent = AddCLREvent( eventTarget, null, cceTarget, mei );

                if (SwitchStatementSupported())
                {
                    _ccRoot.StyleConnectorFn.Statements.Add( csAddCLREvent );
                }
                else
                {
                    ccsConnector.TrueStatements.Add( csAddCLREvent );

                    // Only add if statement at start of new scope
                    if (!xamlClrEventNode.IsSameScope)
                    {
                        _ccRoot.StyleConnectorFn.Statements.Add(ccsConnector);
                    }
                }
            }
        }
Example #29
0
        // Create a CodeDOM graph.
        static void CreateGraph(CodeCompileUnit cu)
        {
            cu.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start,
                                                           "Compile Unit Region"));
            cu.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End,
                                                         string.Empty));
            CodeChecksumPragma pragma1 = new CodeChecksumPragma();

            pragma1.FileName            = "c:\\temp\\test\\OuterLinePragma.txt";
            pragma1.ChecksumAlgorithmId = HashMD5;
            pragma1.ChecksumData        = new byte[] { 0xAA, 0xAA };
            cu.StartDirectives.Add(pragma1);
            CodeChecksumPragma pragma2 = new CodeChecksumPragma("test.txt", HashSHA1, new byte[] { 0xBB, 0xBB, 0xBB });

            cu.StartDirectives.Add(pragma2);

            CodeNamespace ns = new CodeNamespace("Namespace1");

            ns.Imports.Add(new CodeNamespaceImport("System"));
            ns.Imports.Add(new CodeNamespaceImport("System.IO"));
            cu.Namespaces.Add(ns);
            ns.Comments.Add(new CodeCommentStatement("Namespace Comment"));
            CodeTypeDeclaration cd = new CodeTypeDeclaration("Class1");

            ns.Types.Add(cd);

            cd.Comments.Add(new CodeCommentStatement("Outer Type Comment"));
            cd.LinePragma = new CodeLinePragma("c:\\temp\\test\\OuterLinePragma.txt", 300);

            CodeMemberMethod method1 = new CodeMemberMethod();

            method1.Name       = "Method1";
            method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;


            CodeMemberMethod method2 = new CodeMemberMethod();

            method2.Name       = "Method2";
            method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            method2.Comments.Add(new CodeCommentStatement("Method 2 Comment"));

            cd.Members.Add(method1);
            cd.Members.Add(method2);

            cd.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start,
                                                           "Outer Type Region"));

            cd.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End,
                                                         string.Empty));

            CodeMemberField field1 = new CodeMemberField(typeof(String), "field1");

            cd.Members.Add(field1);
            field1.Comments.Add(new CodeCommentStatement("Field 1 Comment"));

            CodeRegionDirective codeRegionDirective1 = new CodeRegionDirective(CodeRegionMode.Start,
                                                                               "Field Region");

            field1.StartDirectives.Add(codeRegionDirective1);
            CodeRegionDirective codeRegionDirective2 = new CodeRegionDirective(CodeRegionMode.End,
                                                                               "");

            codeRegionDirective2.RegionMode = CodeRegionMode.End;
            codeRegionDirective2.RegionText = string.Empty;
            field1.EndDirectives.Add(codeRegionDirective2);

            CodeSnippetStatement snippet1 = new CodeSnippetStatement();

            snippet1.Value = "            Console.WriteLine(field1);";

            CodeRegionDirective regionStart = new CodeRegionDirective(CodeRegionMode.End, "");

            regionStart.RegionText = "Snippet Region";
            regionStart.RegionMode = CodeRegionMode.Start;
            snippet1.StartDirectives.Add(regionStart);
            snippet1.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            // CodeStatement example
            CodeConstructor constructor1 = new CodeConstructor();

            constructor1.Attributes = (constructor1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
            CodeStatement codeAssignStatement1 = new CodeAssignStatement(
                new CodeFieldReferenceExpression(
                    new CodeThisReferenceExpression(),
                    "field1"),
                new CodePrimitiveExpression("value1"));

            codeAssignStatement1.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Statements Region"));
            cd.Members.Add(constructor1);
            codeAssignStatement1.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
            method2.Statements.Add(codeAssignStatement1);
            method2.Statements.Add(snippet1);
        }
        public override object Visit(EmptyStatement emptyStatement, object data)
        {
            CodeSnippetStatement emptyStmt = new CodeSnippetStatement();

            AddStmt(emptyStmt);

            return emptyStmt;
        }
 public bool ValidateCodeSnippetStatement (CodeSnippetStatement exp) {
     return true;
 }