Пример #1
0
        private void AddNamespaceImports(RazorChunkTree chunkTree, CSharpSourceLoweringContext context)
        {
            var defaultImports = _host.NamespaceImports;

            foreach (var import in defaultImports)
            {
                var importSource = new ImportNamespace
                {
                    Namespace = import
                };
                context.Builder.Add(importSource);
            }

            new UsingDirectiveVisitor(defaultImports, context).Accept(chunkTree.Root);
        }
Пример #2
0
        /// <summary>
        /// Calculates the list of namespaces for current location.
        /// </summary>
        protected void InternalGetNamespaces(CodeElement element, IList <string> resultNamespaces)
        {
            if (element.Kind == vsCMElement.vsCMElementImportStmt)
            {
                EditPoint startEdit = element.StartPoint.CreateEditPoint();
                string    text      = startEdit.GetText(element.EndPoint);

                // check if specified namespace name can be extracted from element:
                Match match = ImportNamespace.Match(text);
                if (match.Groups.Count > 2)
                {
                    resultNamespaces.Add(match.Groups[1].Value.Replace(" ", string.Empty).Replace("\t", string.Empty));
                }
            }

            // check other namespaces for 'import' directives:
            if (element.Kind == vsCMElement.vsCMElementNamespace)
            {
                foreach (CodeElement children in element.Children)
                {
                    InternalGetNamespaces(children, resultNamespaces);
                }
            }
        }
Пример #3
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(dotFlex.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(dotFlex.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);
        }
 private void Render(ImportNamespace source, CSharpRenderingContext context)
 {
     context.Writer.WriteUsing(source.Namespace);
 }
Пример #5
0
        private static Assembly GenerateAssembly(string asmxFile)
        {
            StringReader       input       = new StringReader(WsdlFromUrl(GetApplicationPath() + "/" + asmxFile + "?wsdl"));
            XmlTextReader      reader      = new XmlTextReader(input);
            ServiceDescription description = ServiceDescription.Read(reader);

            reader.Close();
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
            CodeNamespace   namespace2      = new CodeNamespace("FluorineFx");

            codeCompileUnit.Namespaces.Add(namespace2);
            CodeNamespace namespace3 = new CodeNamespace(FluorineConfiguration.Instance.WsdlProxyNamespace);

            codeCompileUnit.Namespaces.Add(namespace3);
            DiscoveryClientDocumentCollection documents = new DiscoveryClientDocumentCollection();

            documents.Add(asmxFile, description);
            WebReference webReference = new WebReference(documents, namespace3)
            {
                ProtocolName = "Soap12"
            };
            WebReferenceCollection webReferences = new WebReferenceCollection();

            webReferences.Add(webReference);
            WebReferenceOptions options = new WebReferenceOptions {
                Style = ServiceDescriptionImportStyle.Client,
                CodeGenerationOptions = CodeGenerationOptions.None
            };

            options.SchemaImporterExtensions.Add(typeof(DataTableSchemaImporterExtension).AssemblyQualifiedName);
            CSharpCodeProvider codeProvider = new CSharpCodeProvider();

            ServiceDescriptionImporter.GenerateWebReferences(webReferences, codeProvider, codeCompileUnit, options);
            if (!FluorineConfiguration.Instance.WsdlGenerateProxyClasses)
            {
                foreach (CodeNamespace namespace4 in codeCompileUnit.Namespaces)
                {
                    ArrayList list = new ArrayList();
                    foreach (CodeTypeDeclaration declaration in namespace4.Types)
                    {
                        bool flag = false;
                        foreach (CodeTypeReference reference2 in declaration.BaseTypes)
                        {
                            if (reference2.BaseType == "System.Web.Services.Protocols.SoapHttpClientProtocol")
                            {
                                flag = true;
                                break;
                            }
                        }
                        if (!flag)
                        {
                            list.Add(declaration);
                        }
                        else
                        {
                            CodeAttributeDeclaration declaration2 = new CodeAttributeDeclaration(typeof(RemotingServiceAttribute).FullName);
                            declaration.CustomAttributes.Add(declaration2);
                            foreach (CodeTypeMember member in declaration.Members)
                            {
                                CodeConstructor constructor = member as CodeConstructor;
                                if (constructor != null)
                                {
                                    CodeSnippetStatement statement = new CodeSnippetStatement("this.CookieContainer = new System.Net.CookieContainer(); //Session Cookie");
                                    constructor.Statements.Add(statement);
                                }
                            }
                        }
                    }
                    foreach (CodeTypeDeclaration declaration in list)
                    {
                        namespace3.Types.Remove(declaration);
                    }
                }
                if (FluorineConfiguration.Instance.ImportNamespaces != null)
                {
                    for (int i = 0; i < FluorineConfiguration.Instance.ImportNamespaces.Count; i++)
                    {
                        ImportNamespace namespace5 = FluorineConfiguration.Instance.ImportNamespaces[i];
                        namespace3.Imports.Add(new CodeNamespaceImport(namespace5.Namespace));
                    }
                }
            }
            StringBuilder sb     = new StringBuilder();
            StringWriter  writer = new StringWriter(sb);

            codeProvider.GenerateCodeFromCompileUnit(codeCompileUnit, writer, null);
            string str2 = sb.ToString();

            writer.Close();
            CompilerParameters parameters = new CompilerParameters();

            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("System.Data.dll");
            parameters.ReferencedAssemblies.Add("System.Xml.dll");
            parameters.ReferencedAssemblies.Add("System.Web.Services.dll");
            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                if (assembly.GlobalAssemblyCache)
                {
                    if (assembly.GetName().Name.StartsWith("System") && !parameters.ReferencedAssemblies.Contains(assembly.GetName().Name + ".dll"))
                    {
                        parameters.ReferencedAssemblies.Add(assembly.Location);
                    }
                }
                else if (!assembly.GetName().Name.StartsWith("mscorlib"))
                {
                    try
                    {
                        if ((assembly.Location != null) && (assembly.Location != string.Empty))
                        {
                            parameters.ReferencedAssemblies.Add(assembly.Location);
                        }
                    }
                    catch (NotSupportedException)
                    {
                    }
                }
            }
            parameters.GenerateExecutable      = false;
            parameters.GenerateInMemory        = false;
            parameters.IncludeDebugInformation = false;
            CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, new string[] { str2 });

            if (results.Errors.Count > 0)
            {
                ILog logger = null;
                try
                {
                    logger = LogManager.GetLogger(typeof(WsdlHelper));
                }
                catch
                {
                }
                StringBuilder builder2 = new StringBuilder();
                builder2.Append(string.Format("Build failed: {0} errors", results.Errors.Count));
                if (logger.get_IsErrorEnabled())
                {
                    logger.Error(__Res.GetString("Wsdl_ProxyGenFail"));
                }
                foreach (CompilerError error in results.Errors)
                {
                    logger.Error(__Res.GetString("Compiler_Error", new object[] { error.Line, error.Column, error.ErrorText }));
                    builder2.Append("\n");
                    builder2.Append(error.ErrorText);
                }
                throw new FluorineException(builder2.ToString());
            }
            return(results.CompiledAssembly);
        }