/// <summary>
        /// Generate the code to access the model. Use to CodeDomProvider so we are language-agnostic
        /// </summary>
        /// <param name="directiveName"></param>
        /// <param name="codeBuffer"></param>
        /// <param name="languageProvider"></param>
        /// <param name="requiresArguments"></param>
        /// <param name="providesArguments"></param>
        protected override void GenerateTransformCode(string directiveName, StringBuilder codeBuffer, CodeDomProvider languageProvider, IDictionary <string, string> requiresArguments, IDictionary <string, string> providesArguments)
        {
            if ((StringComparer.InvariantCultureIgnoreCase.Compare(directiveName, "schemamodel") == 0))
            {
                if (languageProvider != null)
                {
                    // Create a field to store the model once it is loaded
                    CodeMemberField schemamodel = new CodeMemberField();
                    schemamodel.Name       = providesArguments["SchemaModel"].ToLower(CultureInfo.InvariantCulture) + "Value";
                    schemamodel.Type       = new CodeTypeReference(typeof(ISpySoft.SFSchemaLanguage.DomainModel.SchemaModel));
                    schemamodel.Attributes = MemberAttributes.Private;

                    // Create a property for the Model that delay-loads the model
                    CodeMemberProperty schemamodelProperty = new CodeMemberProperty();
                    schemamodelProperty.Name       = providesArguments["SchemaModel"];
                    schemamodelProperty.Type       = new CodeTypeReference(typeof(ISpySoft.SFSchemaLanguage.DomainModel.SchemaModel));
                    schemamodelProperty.Attributes = MemberAttributes.Private;
                    schemamodelProperty.HasSet     = false;
                    schemamodelProperty.HasGet     = true;
                    schemamodelProperty.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), schemamodel.Name)));

                    // Generate the actual code using the CodeDomProvider
                    CodeGeneratorOptions options = new CodeGeneratorOptions();
                    options.BlankLinesBetweenMembers = true;
                    options.IndentString             = "    ";
                    options.VerbatimOrder            = true;
                    options.BracingStyle             = "C";
                    using (StringWriter writer = new StringWriter(codeBuffer, CultureInfo.InvariantCulture))
                    {
                        languageProvider.GenerateCodeFromMember(schemamodel, writer, options);
                        languageProvider.GenerateCodeFromMember(schemamodelProperty, writer, options);
                    }
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Generates the code that will be added to the generated template. For
        /// each argument a private field is generated that will hold the argument
        /// value. Also a readonly public property is generated to access the argument
        /// value. When a convertor of editor is defined there is a attribute genereted
        /// for each of them.
        /// </summary>
        /// <returns>The fields and arguments</returns>
        public override string GetClassCodeForProcessingRun()
        {
            using (var writer = new StringWriter(CultureInfo.InvariantCulture))
            {
                foreach (ArgumentInfo argument in _argumentInfos.Values)
                {
                    //Create field
                    var field = new CodeMemberField(argument.Type, argument.FieldName)
                    {
                        Attributes = MemberAttributes.Private
                    };

                    _provider.GenerateCodeFromMember(field, writer, _options);

                    //Create the property for each argument
                    var property = new CodeMemberProperty
                    {
                        Name       = argument.Name,
                        Type       = new CodeTypeReference(argument.Type),
                        Attributes = MemberAttributes.Public,
                        HasGet     = true,
                        HasSet     = false
                    };
                    property.GetStatements.Add(
                        new CodeMethodReturnStatement(new CodeFieldReferenceExpression(
                                                          new CodeThisReferenceExpression(),
                                                          argument.FieldName)));
                    //Add editor attribute
                    if (!string.IsNullOrEmpty(argument.EditorType))
                    {
                        property.CustomAttributes.Add(new CodeAttributeDeclaration(
                                                          new CodeTypeReference(typeof(EditorAttribute)),
                                                          new CodeAttributeArgument(
                                                              new CodeTypeOfExpression(argument.EditorType)),
                                                          new CodeAttributeArgument(
                                                              new CodeTypeOfExpression(typeof(UITypeEditor)))));
                    }

                    //Add convertor attribute
                    if (!string.IsNullOrEmpty(argument.ConverterType))
                    {
                        property.CustomAttributes.Add(new CodeAttributeDeclaration(
                                                          new CodeTypeReference(typeof(TypeConverter)),
                                                          new CodeAttributeArgument(
                                                              new CodeTypeOfExpression(argument.ConverterType))));
                    }

                    _provider.GenerateCodeFromMember(property, writer, _options);
                }

                return(writer.ToString());
            }
        }
Exemplo n.º 3
0
        public override string GetClassCodeForProcessingRun()
        {
            CodeGeneratorOptions options = new CodeGeneratorOptions();
            var langTool = new CodeMemberField()
            {
                Attributes       = MemberAttributes.Public
                , Name           = "languageTool"
                , Type           = new CodeTypeReference(typeof(LanguageTool))
                , InitExpression = new CodeObjectCreateExpression(typeof(LanguageTool))
            };

            languageProvider.GenerateCodeFromMember(langTool, fieldWriter, options);
            return(fieldWriter.GetStringBuilder().ToString());
        }
Exemplo n.º 4
0
        /// <summary>
        /// Create the code added as members to the transform class.
        /// </summary>
        private void GenerateClassCode(string nameValue, string typeValue, out CodeMemberField field)
        {
            field              = new CodeMemberField(typeValue, string.Format(CultureInfo.InvariantCulture, "_{0}Field", nameValue));
            field.Attributes   = MemberAttributes.Private;
            field.Type.Options = CodeTypeReferenceOptions.GlobalReference;
            CodeMemberProperty codeMemberProperty = new CodeMemberProperty();

            codeMemberProperty.Name = nameValue;
            codeMemberProperty.Type = new CodeTypeReference(typeValue, CodeTypeReferenceOptions.GlobalReference);
            codeMemberProperty.GetStatements.Add(new CodeMethodReturnStatement(field.Ref()));
            codeMemberProperty.AddSummaryComment("Access the " + nameValue + " parameter of the template.");
            CodeGeneratorOptions standardOptions = StandardOptions;

            using (StringWriter writer = new StringWriter(codeBuffer, CultureInfo.InvariantCulture))
            {
                languageCodeDomProvider.GenerateCodeFromMember(field, writer, standardOptions);
                languageCodeDomProvider.GenerateCodeFromMember(codeMemberProperty, writer, standardOptions);
            }
        }
        public override string GetClassCodeForProcessingRun()
        {
            var options = new CodeGeneratorOptions();

            using (var sw = new StringWriter()) {
                foreach (CodeTypeMember member in members)
                {
                    languageProvider.GenerateCodeFromMember(member, sw, options);
                }
                return(Indent(sw.ToString(), "        "));
            }
        }
        public override void ProcessDirective(string directiveName, IDictionary <string, string> arguments)
        {
            string name      = arguments["name"];
            string fieldName = string.Format("_{0}", arguments["name"]);
            string type      = arguments["type"];

            var field = new CodeMemberField(type, fieldName)
            {
                Attributes = MemberAttributes.Private
            };

            _provider.GenerateCodeFromMember(field, _classCodeWriter, _options);

            var property = new CodeMemberProperty
            {
                Name       = name,
                Type       = new CodeTypeReference(type),
                Attributes = MemberAttributes.Public,
                HasGet     = true,
                HasSet     = false
            };

            property.GetStatements.Add(
                new CodeMethodReturnStatement(
                    new CodeFieldReferenceExpression(
                        new CodeThisReferenceExpression(), fieldName)));

            _provider.GenerateCodeFromMember(property, _classCodeWriter, _options);

            CodeAssignStatement assignment = new CodeAssignStatement(
                new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fieldName),
                new CodeCastExpression(
                    new CodeTypeReference(type),
                    new CodeMethodInvokeExpression(
                        new CodeTypeReferenceExpression(typeof(CallContext)),
                        "LogicalGetData",
                        new CodePrimitiveExpression(name))));

            _provider.GenerateCodeFromStatement(assignment, _initializationCodeWriter, _options);
        }
Exemplo n.º 7
0
        private string GetCodeString(CodeDomProvider provider, CodeTypeMember typeMember)
        {
            StringBuilder        sb      = new StringBuilder();
            StringWriter         sw      = new StringWriter(sb);
            CodeGeneratorOptions options = new CodeGeneratorOptions();

            options.IndentString = "";
            options.BracingStyle = "C";

            provider.GenerateCodeFromMember(typeMember, sw, options);

            return(sb.ToString());
        }
Exemplo n.º 8
0
        /// <summary>
        /// Generates a notification partial method for the specified method, this is of the form
        /// OnCreated(args...) for the Created(args...) method.
        /// </summary>
        /// <param name="methodName">The name of the method to create a notification method for.</param>
        /// <param name="parameters">the method parameters, if any.</param>
        /// <returns>Code snippet for the notification partial method.</returns>
        private CodeSnippetTypeMember CreateNotificationPartialMethod(string methodName, CodeParameterDeclarationExpressionCollection parameters)
        {
            CodeMemberMethod method = new CodeMemberMethod();

            method.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            method.Name       = "On" + methodName;
            method.Parameters.AddRange(parameters);

            if (this.proxyGenerator.ClientProxyCodeGenerationOptions.UseFullTypeNames)
            {
                foreach (CodeParameterDeclarationExpression paramExp in parameters.Cast <CodeParameterDeclarationExpression>())
                {
                    SetGlobalTypeReference(paramExp.Type);
                }
            }

            StringBuilder snippet = null;

            using (CodeDomProvider provider = CodeDomProvider.CreateProvider(this.isCSharp ? "CSharp" : "VisualBasic"))
            {
                using (StringWriter snippetWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture))
                {
                    provider.GenerateCodeFromMember(method, snippetWriter, new CodeGeneratorOptions());
                    snippet = snippetWriter.GetStringBuilder();
                }
            }

            // replace 'public' with 'partial' - partial methods cannot be public.
            // observe we replace 'ublic' only to get the proper language keyword capitalization.
            snippet.Replace("\r\n", string.Empty);
            snippet.Replace("ublic", "artial", 1, "ublic".Length);

            if (this.isCSharp)
            {
                int idx = snippet.ToString().LastIndexOf(')');
                snippet.Remove(idx + 1, snippet.Length - idx - 1);
                snippet.Append(";");
            }
            else // VB.net
            {
                snippet.Insert(0, "Private ");
                int idx = snippet.ToString().IndexOf("End Sub", StringComparison.Ordinal);
                snippet.Insert(idx, string.Concat("\r\n", this.indent));
            }

            snippet.Insert(0, this.indent);

            return(new CodeSnippetTypeMember(snippet.ToString()));
        }
Exemplo n.º 9
0
        //<Snippet3>
        static void GenCodeFromMember(CodeDomProvider provider, CodeGeneratorOptions options)
        {
            options.BracingStyle = "C";
            CodeMemberMethod method1 = new CodeMemberMethod();

            method1.Name       = "ReturnString";
            method1.Attributes = MemberAttributes.Public;
            method1.ReturnType = new CodeTypeReference("System.String");
            method1.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "text"));
            method1.Statements.Add(new CodeMethodReturnStatement(new CodeArgumentReferenceExpression("text")));
            StringWriter sw = new StringWriter();

            provider.GenerateCodeFromMember(method1, sw, options);
            snippetMethod = new CodeSnippetTypeMember(sw.ToString());
        }
Exemplo n.º 10
0
        static void GenerateAction(CodeTypeDeclaration type, string name, CodeTypeReference senderType, CodeDomProvider provider,
                                   CodeGeneratorOptions generatorOptions, ref StringWriter actionStubWriter)
        {
            if (provider is Microsoft.CSharp.CSharpCodeProvider)
            {
                type.Members.Add(new CodeSnippetTypeMember("[MonoTouch.Foundation.Export(\"" + name + "\")]"));
                type.Members.Add(new CodeSnippetTypeMember(
                                     String.Format("partial void {1} ({2} sender);\n",
                                                   name, provider.CreateValidIdentifier(name.TrimEnd(':')), senderType.BaseType)));
                return;
            }
            else if (provider.FileExtension == "pas")
            {
                var m = new CodeMemberMethod();
                m.Name = provider.CreateValidIdentifier(name.TrimEnd(':'));
                m.Parameters.Add(new CodeParameterDeclarationExpression(senderType.BaseType, "sender"));
                m.UserData ["OxygenePartial"] = "YES";
                m.UserData ["OxygeneEmpty"]   = "YES";
                var a = new CodeAttributeDeclaration("MonoTouch.Foundation.Export");
                a.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(name)));
                m.CustomAttributes.Add(a);
                type.Members.Add(m);
                return;
            }


            var meth = CreateEventMethod(name, senderType);

            bool actionStubWriterCreated = false;

            if (actionStubWriter == null)
            {
                actionStubWriterCreated = true;
                actionStubWriter        = new StringWriter();
                actionStubWriter.WriteLine("Action method stubs:");
                actionStubWriter.WriteLine();
            }
            try {
                provider.GenerateCodeFromMember(meth, actionStubWriter, generatorOptions);
                actionStubWriter.WriteLine();
            } catch {
                //clear the header if generation failed
                if (actionStubWriterCreated)
                {
                    actionStubWriter = null;
                }
            }
        }
Exemplo n.º 11
0
        public void ConvertContentDefinition(CodeMemberField field, TextWriter writer)
        {
            LoggingService.Info("Generate field declaration for: " + field.Name);

            CodeGeneratorOptions options = codeDOMGeneratorUtility.CreateCodeGeneratorOptions;

            options.IndentString = indentation;
            try {
                codeProvider.GenerateCodeFromMember(field, writer, options);
            } catch (Exception e) {
                codeProvider.GenerateCodeFromStatement(new CodeCommentStatement("TODO: Error while generating statement : " + e.Message),
                                                       writer,
                                                       options);
                LoggingService.Error(e);
            }
        }
        void GenerateCodeFromMembers(StringWriter sw, CodeGeneratorOptions options)
        {
            if (!useMonoHack)
            {
                foreach (CodeTypeMember member in members)
                {
                    provider.GenerateCodeFromMember(member, sw, options);
                }
            }

            var cgType     = typeof(CodeGenerator);
            var cgInit     = cgType.GetMethod("InitOutput", BindingFlags.NonPublic | BindingFlags.Instance);
            var cgFieldGen = cgType.GetMethod("GenerateField", BindingFlags.NonPublic | BindingFlags.Instance);
            var cgPropGen  = cgType.GetMethod("GenerateProperty", BindingFlags.NonPublic | BindingFlags.Instance);

#pragma warning disable 0618
            var generator = (CodeGenerator)provider.CreateGenerator();
#pragma warning restore 0618
            var dummy = new CodeTypeDeclaration("Foo");

            foreach (CodeTypeMember member in members)
            {
                var f = member as CodeMemberField;
                if (f != null)
                {
                    cgInit.Invoke(generator, new object[] { sw, options });
                    cgFieldGen.Invoke(generator, new object[] { f });
                    continue;
                }
                var p = member as CodeMemberProperty;
                if (p != null)
                {
                    cgInit.Invoke(generator, new object[] { sw, options });
                    cgPropGen.Invoke(generator, new object[] { p, dummy });
                    continue;
                }
            }
        }
Exemplo n.º 13
0
    /// <summary>
    /// An implementation of CodeDomProvider.GenerateCodeFromMember that works on Mono.
    /// </summary>
    public static void GenerateCodeFromMembers(this CodeDomProvider provider, CodeGeneratorOptions options, StringWriter sw, IEnumerable <CodeTypeMember> members)
    {
        if (!useMonoHack)
        {
            foreach (CodeTypeMember member in members)
            {
                provider.GenerateCodeFromMember(member, sw, options);
            }
            return;
        }

#pragma warning disable 0618
        var generator = (CodeGenerator)provider.CreateGenerator();
#pragma warning restore 0618
        var dummy = new CodeTypeDeclaration("Foo");

        foreach (CodeTypeMember member in members)
        {
            if (member is CodeMemberField f)
            {
                initializeCodeGenerator(generator, sw, options);
                cgFieldGen.Invoke(generator, new object[] { f });
                continue;
            }
            if (member is CodeMemberProperty p)
            {
                initializeCodeGenerator(generator, sw, options);
                cgPropGen.Invoke(generator, new object[] { p, dummy });
                continue;
            }
            if (member is CodeMemberMethod m)
            {
                initializeCodeGenerator(generator, sw, options);
                cgMethGen.Invoke(generator, new object[] { m, dummy });
                continue;
            }
        }
    }
        private static string GetPropertyTextWithGetSetLevelDebuggerNonUserCodeAttribute(CodeDomProvider provider, CodeGeneratorOptions options, StringWriter sourceWriter, CodeMemberProperty property)
        {
            provider.GenerateCodeFromMember(property, sourceWriter, options);
            var code = sourceWriter.ToString();

            sourceWriter.GetStringBuilder().Clear(); // Clear String Builder
            var lines = code.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();

            lines.RemoveAt(0);
            lines.RemoveAt(lines.Count - 1);
            for (var i = lines.Count() - 1; i >= 0; i--)
            {
                var line = lines[i];
                lines[i] = "\t\t" + line;
                if (line.TrimStart() == "get" || line.TrimStart() == "set")
                {
                    //Insert attribute above
                    lines.Insert(i, "\t\t\t[System.Diagnostics.DebuggerNonUserCode()]");
                }
            }

            return(string.Join(Environment.NewLine, lines.ToArray()));
        }
Exemplo n.º 15
0
        /// <summary>
        /// Generates source code from given CodeTypeMemberCollection.
        /// </summary>
        public static string GenerateFromMember(CodeDomProvider codeProvider, CodeTypeMemberCollection memberCollection, bool blankLinesBetweenMembers)
        {
            StringBuilder result = new StringBuilder();
            StringWriter  writer = new StringWriter(result);

            CodeGeneratorOptions options = new CodeGeneratorOptions();

            options.BlankLinesBetweenMembers = blankLinesBetweenMembers;
            options.ElseOnClosing            = true;
            options.VerbatimOrder            = true;
            options.BracingStyle             = "C";

            foreach (CodeTypeMember typeMember in memberCollection)
            {
                // generate the code:
                codeProvider.GenerateCodeFromMember(typeMember, writer, options);

                // send it to the StringBuilder object:
                writer.Flush();
            }

            return(result.ToString());
        }
Exemplo n.º 16
0
        private static string GenerateCode(CodeObject c, CodeDomProvider provider)
        {
            var sb      = new StringBuilder();
            var writer  = new StringWriter(sb);
            var options = new CodeGeneratorOptions();

            if (c is CodeStatement)
            {
                provider.GenerateCodeFromStatement((CodeStatement)c, writer, options);
            }
            else if (c is CodeCompileUnit)
            {
                provider.GenerateCodeFromCompileUnit((CodeCompileUnit)c, writer, options);
            }
            else if (c is CodeExpression)
            {
                provider.GenerateCodeFromExpression((CodeExpression)c, writer, options);
            }
            else if (c is CodeTypeMember)
            {
                provider.GenerateCodeFromMember((CodeTypeMember)c, writer, options);
            }
            else if (c is CodeTypeDeclaration)
            {
                provider.GenerateCodeFromType((CodeTypeDeclaration)c, writer, options);
            }
            else if (c is CodeNamespace)
            {
                provider.GenerateCodeFromNamespace((CodeNamespace)c, writer, options);
            }
            else
            {
                throw new ArgumentException($"Tests not set up for unexpected type: {c.GetType()}");
            }

            return(sb.ToString());
        }
Exemplo n.º 17
0
        private static string GenerateCode(CodeObject c, CodeDomProvider provider)
        {
            var sb      = new StringBuilder();
            var writer  = new StringWriter(sb);
            var options = new CodeGeneratorOptions();

            if (c is CodeStatement)
            {
                provider.GenerateCodeFromStatement((CodeStatement)c, writer, options);
            }
            else if (c is CodeCompileUnit)
            {
                provider.GenerateCodeFromCompileUnit((CodeCompileUnit)c, writer, options);
            }
            else if (c is CodeExpression)
            {
                provider.GenerateCodeFromExpression((CodeExpression)c, writer, options);
            }
            else if (c is CodeTypeMember)
            {
                provider.GenerateCodeFromMember((CodeTypeMember)c, writer, options);
            }
            else if (c is CodeTypeDeclaration)
            {
                provider.GenerateCodeFromType((CodeTypeDeclaration)c, writer, options);
            }
            else if (c is CodeNamespace)
            {
                provider.GenerateCodeFromNamespace((CodeNamespace)c, writer, options);
            }
            else
            {
                Assert.False(true, $"Unknown type: {c.GetType()}");
            }

            return(sb.ToString());
        }
Exemplo n.º 18
0
        public override void ProcessDirective(string directiveName, IDictionary <string, string> arguments)
        {
            //When the Solution first opens, templateFile is null.
            //I wonder if that is a Bug!
            if (Host.TemplateFile != null && string.Compare(directiveName, "XMLDirective", StringComparison.OrdinalIgnoreCase) == 0)
            {
                string fileName;

                //Arguments are passed with the Key in lowercase.
                if (!arguments.TryGetValue("filename", out fileName))
                {
                    throw new DirectiveProcessorException("Required argument ‘FileName’ not specified.");
                }

                if (string.IsNullOrEmpty(fileName))
                {
                    throw new DirectiveProcessorException("Argument ‘FileName’ is null or empty.");
                }

                //With a little extra work we can find the path of the XML data file.
                string fullPath = Path.Combine(Path.GetDirectoryName(Host.TemplateFile), fileName);

                //Now we add code to the generated transformation class.
                //This directive supports either Visual Basic or C#,

                //so we must use the
                //System.CodeDom to create the code.
                //If a directive supports only one language, you can

                //hard code the code.
                //—————————————————————–

                CodeMemberField documentField = new CodeMemberField();

                documentField.Name       = "document" + directiveCount + "Value";
                documentField.Type       = new CodeTypeReference(typeof(XmlDocument));
                documentField.Attributes = MemberAttributes.Private;

                CodeMemberProperty documentProperty = new CodeMemberProperty();

                documentProperty.Name       = "Document" + directiveCount;
                documentProperty.Type       = new CodeTypeReference(typeof(XmlDocument));
                documentProperty.Attributes = MemberAttributes.Public;
                documentProperty.HasSet     = false;
                documentProperty.HasGet     = true;

                CodeExpression fieldName   = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), documentField.Name);
                CodeExpression booleanTest = new CodeBinaryOperatorExpression

                                                 (fieldName, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null));
                CodeExpression  rightSide = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("XmlReaderHelper"), "ReadXml", new CodePrimitiveExpression(fullPath));
                CodeStatement[] thenSteps = new CodeStatement[] { new CodeAssignStatement(fieldName, rightSide) };

                CodeConditionStatement ifThen = new CodeConditionStatement(booleanTest, thenSteps);
                documentProperty.GetStatements.Add(ifThen);

                CodeStatement s = new CodeMethodReturnStatement(fieldName);
                documentProperty.GetStatements.Add(s);

                CodeGeneratorOptions options = new CodeGeneratorOptions();
                options.BlankLinesBetweenMembers = true;
                options.IndentString             = " ";
                options.VerbatimOrder            = true;
                options.BracingStyle             = "C";

                using (StringWriter writer = new StringWriter(codeBuffer, CultureInfo.InvariantCulture))
                {
                    codeDomProvider.GenerateCodeFromMember(documentField, writer, options);
                    codeDomProvider.GenerateCodeFromMember(documentProperty, writer, options);
                }
            }
            //end XMLDirective

            //Track how many times the processor has been called.
            //—————————————————————–
            directiveCount++;
        }
Exemplo n.º 19
0
        public override CodeTypeMember HandleProperty(IDLInterface idlIntf, IDLProperty idlProperty)
        {
            CodeMemberProperty property = (CodeMemberProperty)base.HandleProperty(idlIntf, idlProperty);

            if (property.HasGet || property.HasSet)
            {
                // Generate the property out of context.
                CodeDomProvider      provider   = CodeDomProvider.CreateProvider("CSharp");
                CodeGeneratorOptions genOptions = CodeBuilderHelper.getCodeGeneratorOptions();
                StringWriter         temp       = new StringWriter();
                provider.GenerateCodeFromMember(property, temp, genOptions);
                string propertyText = temp.ToString();
                propertyText = propertyText.TrimStart();

                //Get ready to store all the output
                StringBuilder result = new StringBuilder();

                // Figure out how much comments exist before doing the real work
                int posSkipStatements = 0;
                while (posSkipStatements + 1 < propertyText.Length && propertyText[posSkipStatements] == '/' && propertyText[posSkipStatements + 1] == '/')
                {
                    posSkipStatements  = propertyText.IndexOf(temp.NewLine, posSkipStatements);
                    posSkipStatements += temp.NewLine.Length;
                }

                //Insert comments into output
                if (posSkipStatements > 0)
                {
                    result.Append(propertyText.Substring(0, posSkipStatements));
                    propertyText = propertyText.Substring(posSkipStatements);
                }

                //Remove abstract modifiers
                const string abstractName = "abstract ";
                if (propertyText.StartsWith(abstractName))
                {
                    propertyText = propertyText.Substring(abstractName.Length);
                }

                // Hacky rewrite of the getter/setter for CSharp.
                if (property.HasGet)
                {
                    propertyText = AddOperationContractToProperty(propertyText, "get;", temp.NewLine);
                }
                if (property.HasSet)
                {
                    propertyText = AddOperationContractToProperty(propertyText, "set;", temp.NewLine);
                }

                // Add the altered text.
                result.Append(propertyText);

                // Mess around with padding.
                string resultText = result.ToString();
                resultText = resultText.Replace(temp.NewLine, temp.NewLine + "        ");
                resultText = "        " + resultText;

                // Add the snippet.
                CodeSnippetTypeMember snipProperty = new CodeSnippetTypeMember(resultText);
                snipProperty.Name = property.Name;
                return(snipProperty);
            }
            else
            {
                return(property);
            }
        }
 protected override void ProcessRecord()
 {
     if (CompileUnit != null && CompileUnit.Length > 0)
     {
         foreach (CodeCompileUnit compileUnit in CompileUnit)
         {
             if (compileUnit != null)
             {
                 _provider.GenerateCodeFromCompileUnit(compileUnit, _indentedWriter, Options);
             }
         }
     }
     else if (Expression != null && Expression.Length > 0)
     {
         foreach (CodeExpression expr in Expression)
         {
             if (expr != null)
             {
                 _provider.GenerateCodeFromExpression(expr, _indentedWriter, Options);
             }
         }
     }
     else if (Member != null && Member.Length > 0)
     {
         foreach (CodeTypeMember member in Member)
         {
             if (member != null)
             {
                 _provider.GenerateCodeFromMember(member, _indentedWriter, Options);
             }
         }
     }
     else if (NS != null && NS.Length > 0)
     {
         foreach (CodeNamespace ns in NS)
         {
             if (ns != null)
             {
                 _provider.GenerateCodeFromNamespace(ns, _indentedWriter, Options);
             }
         }
     }
     else if (Statement != null && Statement.Length > 0)
     {
         foreach (CodeStatement st in Statement)
         {
             if (st != null)
             {
                 _provider.GenerateCodeFromStatement(st, _indentedWriter, Options);
             }
         }
     }
     else if (Type != null && Type.Length > 0)
     {
         foreach (CodeTypeDeclaration t in Type)
         {
             if (t != null)
             {
                 _provider.GenerateCodeFromType(t, _indentedWriter, Options);
             }
         }
     }
 }
Exemplo n.º 21
0
        /// <summary>
        /// Generates the GetEntityState helper method that allows POCO types to retrieve their
        /// entity state from the contect.  It is not available on the POCO types directly.
        /// </summary>
        /// <param name="codeGenContext">The context in which we are generating code.</param>
        /// <param name="businessLogicClass">The class we are generating.</param>
        /// <returns>The <see cref="CodeTypeMember"/> containing the helper method.</returns>
        private static CodeTypeMember GenerateGetEntityState(CodeGenContext codeGenContext, CodeTypeDeclaration businessLogicClass)
        {
            // Add an import for System.Data.Objects
            CodeNamespace codeNamespace = codeGenContext.GetNamespace(businessLogicClass);

            if (codeNamespace != null)
            {
                codeNamespace.Imports.Add(new CodeNamespaceImport("System.Data.Entity.Core.Objects"));
            }

            //private EntityState GetEntityState(object entity)
            //{
            //    ObjectStateEntry stateEntry = null;
            //    if (!this.ObjectContext.ObjectStateManager.TryGetObjectStateEntry(entity, out stateEntry))
            //    {
            //        return EntityState.Detached;
            //    }
            //    return stateEntry.State;
            //}

            // Declaration
            CodeMemberMethod method = new CodeMemberMethod();

            method.Name       = LinqToEntitiesContext.GetEntityStateHelperMethodName;
            method.ReturnType = new CodeTypeReference(typeof(EntityState).Name);
            method.Attributes = MemberAttributes.Private;
            method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "entity"));

            // ObjectStateEntry stateEntry = null;
            method.Statements.Add(new CodeVariableDeclarationStatement("ObjectStateEntry", "stateEntry", new CodePrimitiveExpression(null)));

            CodeArgumentReferenceExpression entityArgRef = new CodeArgumentReferenceExpression("entity");
            CodeExpression contextRef = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "ObjectContext");

            CodeFieldReferenceExpression    detachedStateRef  = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(EntityState).Name), Enum.GetName(typeof(EntityState), EntityState.Detached));
            CodePropertyReferenceExpression objectStateMgrRef = new CodePropertyReferenceExpression(contextRef, "ObjectStateManager");

            CodeVariableReferenceExpression entityStateRef = new CodeVariableReferenceExpression("stateEntry");

            // The "_out_" prefix will be replaced below with the language-appropriate modifier to make an out param.
            // CodeDom does not support this, so we must do some string manipulation
            CodeVariableReferenceExpression outEntityStateRef = new CodeVariableReferenceExpression("_out_stateEntry");

            // this.ObjectContext.ObjectStateManager.TryGetObjectStateEntry(entity, out stateEntry)
            CodeMethodInvokeExpression getObjectStateEntryCall = new CodeMethodInvokeExpression(objectStateMgrRef, "TryGetObjectStateEntry", entityArgRef, outEntityStateRef);

            // if (...TryGet())
            CodeExpression tryGetTest = CodeGenUtilities.MakeEqual(typeof(bool), getObjectStateEntryCall, new CodePrimitiveExpression(false), codeGenContext.IsCSharp);

            // if (...TryGet..) { return EntityState.Detached; }
            CodeMethodReturnStatement returnDetached = new CodeMethodReturnStatement(detachedStateRef);
            CodeConditionStatement    ifTryGet       = new CodeConditionStatement(tryGetTest, returnDetached);

            method.Statements.Add(ifTryGet);

            // Return entityState.State;
            method.Statements.Add(new CodeMethodReturnStatement(new CodePropertyReferenceExpression(entityStateRef, "State")));

            // CodeDom does not support specifying 'out' parameters at the method call site.
            // So convert the entire method into a snippet of text

            StringBuilder   snippet  = null;
            CodeDomProvider provider = codeGenContext.Provider;

            using (StringWriter snippetWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture))
            {
                provider.GenerateCodeFromMember(method, snippetWriter, codeGenContext.CodeGeneratorOptions);
                snippet = snippetWriter.GetStringBuilder();
            }

            // Our convention above is that "_out_" will be replaced by the language-appropriate "out" parameter modifier.
            // In the case of VB, it is the default
            snippet.Replace("_out_", codeGenContext.IsCSharp ? "out " : string.Empty);

            // We need to indent the entire snippet 2 levels
            string indent = codeGenContext.CodeGeneratorOptions.IndentString;

            indent += indent;

            string snippetText = indent + snippet.ToString().Replace(Environment.NewLine, Environment.NewLine + indent).TrimEnd(' ');
            CodeSnippetTypeMember methodAsText = new CodeSnippetTypeMember(snippetText);

            return(methodAsText);
        }