public void ValidWebReferenceName()
 {
     Assert.IsTrue(WebReference.IsValidNamespace("a"));
 }
 public void FirstCharacterCannotBeANumber()
 {
     Assert.IsFalse(WebReference.IsValidNamespace("8abc"));
 }
Пример #3
0
        int Run(string[] args)
        {
            try
            {
                // parse command line arguments
                foreach (string argument in args)
                {
                    ImportArgument(argument);
                }

                if (noLogo == false)
                {
                    Console.WriteLine(ProductId);
                }

                if (help || urls.Count == 0)
                {
                    Console.WriteLine(UsageMessage);
                    return(0);
                }

                CodeCompileUnit codeUnit  = new CodeCompileUnit();
                CodeNamespace   proxyCode = GetCodeNamespace();
                codeUnit.Namespaces.Add(proxyCode);

                WebReferenceCollection references = new WebReferenceCollection();

                DiscoveryClientProtocol dcc = CreateClient();

                foreach (string murl in urls)
                {
                    string url = murl;
                    if (!url.StartsWith("http://") && !url.StartsWith("https://") && !url.StartsWith("file://"))
                    {
                        url = new Uri(Path.GetFullPath(url)).ToString();
                    }

                    dcc.DiscoverAny(url);
                    dcc.ResolveAll();
                }

                WebReference reference = new WebReference(dcc.Documents, proxyCode, protocol, appSettingURLKey, appSettingBaseURL);
                references.Add(reference);

                if (sampleSoap != null)
                {
                    ConsoleSampleGenerator.Generate(descriptions, schemas, sampleSoap, protocol);
                }

                if (sampleSoap != null)
                {
                    return(0);
                }

                // generate the code
                GenerateCode(references, codeUnit);
                return(0);
            }
            catch (Exception exception)
            {
                Console.WriteLine("Error: {0}", exception.Message);

                // Supress this except for when debug is enabled
                Console.WriteLine("Stack:\n {0}", exception.StackTrace);
                return(2);
            }
        }
Пример #4
0
    static void Run()
    {
        // Get a WSDL file describing a service.
        ServiceDescription description = ServiceDescription.Read("DataTypes_CS.wsdl");

        // Initialize a service description importer.
        ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

        importer.ProtocolName = "Soap12"; // Use SOAP 1.2.
        importer.AddServiceDescription(description, null, null);

        // Report on the service descriptions.
        Console.WriteLine("Importing {0} service descriptions with {1} associated schemas.",
                          importer.ServiceDescriptions.Count, importer.Schemas.Count);

        // Generate a proxy client.
        importer.Style = ServiceDescriptionImportStyle.Client;

        // Generate properties to represent primitive values.
        importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;

        // Initialize a Code-DOM tree into which we will import the service.
        CodeNamespace   nmspace = new CodeNamespace();
        CodeCompileUnit unit1   = new CodeCompileUnit();

        unit1.Namespaces.Add(nmspace);

        // Import the service into the Code-DOM tree. This creates proxy code
        // that uses the service.
        ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);

        if (warning == 0)
        {
            // Generate and print the proxy code in C#.
            CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");
            provider1.GenerateCodeFromCompileUnit(unit1, Console.Out, new CodeGeneratorOptions());
        }
        else
        {
            // Print an error message.
            Console.WriteLine("Warning: " + warning);
        }


        string url = "AddNumbers.wsdl";

// <snippet1>
        // Read in a WSDL service description.
        XmlTextReader      reader = new XmlTextReader(url);
        ServiceDescription wsdl   = ServiceDescription.Read(reader);
// </snippet1>

// <snippet2>
        // Create a WSDL collection.
        DiscoveryClientDocumentCollection wsdlCollection = new DiscoveryClientDocumentCollection();

        wsdlCollection.Add(url, wsdl);
// </snippet2>

// <snippet3>
        // Create a namespace and a unit for compilation.
        CodeNamespace   space = new CodeNamespace();
        CodeCompileUnit unit  = new CodeCompileUnit();

        unit.Namespaces.Add(space);
// </snippet3>

// <snippet4>
        // Create a web referernce using the WSDL collection.
        WebReference reference = new WebReference(wsdlCollection, space);

        reference.ProtocolName = "Soap12";
// </snippet4>

// <snippet5>
        // Print some information about the web reference.
        Console.WriteLine("Base Url = {0}", reference.AppSettingBaseUrl);
        Console.WriteLine("Url Key = {0}", reference.AppSettingUrlKey);
        Console.WriteLine("Documents = {0}", reference.Documents.Count);
// </snippet5>

// <snippet6>
        // Create a web reference collection.
        WebReferenceCollection references = new WebReferenceCollection();

        references.Add(reference);
// </snippet6>

// <snippet7>
        // Compile a proxy client and print out the code.
        CodeDomProvider     provider = CodeDomProvider.CreateProvider("CSharp");
        WebReferenceOptions options  = new WebReferenceOptions();

        options.Style = ServiceDescriptionImportStyle.Client;
        options.CodeGenerationOptions = CodeGenerationOptions.GenerateNewAsync;
        ServiceDescriptionImporter.GenerateWebReferences(
            references,
            provider,
            unit,
            options
            );
        provider.GenerateCodeFromCompileUnit(unit, Console.Out, new CodeGeneratorOptions());
// </snippet7>
    }
 public int IndexOf(WebReference webReference)
 {
 }
 public void Remove(WebReference webReference)
 {
 }
 public static bool CheckConformance(System.Web.Services.WsiProfiles claims, WebReference webReference, BasicProfileViolationCollection violations)
 {
 }
Пример #8
0
 public void EmptyStringIsNotAValidReferenceName()
 {
     Assert.IsFalse(WebReference.IsValidReferenceName(String.Empty));
 }
Пример #9
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);
        }
Пример #10
0
 public void ReferenceNameCannotContainABackslash()
 {
     Assert.IsFalse(WebReference.IsValidReferenceName("ab\\c"));
 }
Пример #11
0
        private Assembly GenerateWebServiceProxyAssembly(string NameSpace, string ClassName)
        {
            object   obj = null;
            Assembly assembly;
            DiscoveryClientProtocol discoveryClientProtocol = new DiscoveryClientProtocol();

            if (this._usedefaultcredential.IsPresent)
            {
                discoveryClientProtocol.UseDefaultCredentials = true;
            }
            if (base.ParameterSetName.Equals("Credential", StringComparison.OrdinalIgnoreCase))
            {
                discoveryClientProtocol.Credentials = this._credential.GetNetworkCredential();
            }
            try
            {
                discoveryClientProtocol.AllowAutoRedirect = true;
                discoveryClientProtocol.DiscoverAny(this._uri.ToString());
                discoveryClientProtocol.ResolveAll();
                goto Label0;
            }
            catch (WebException webException1)
            {
                WebException webException = webException1;
                ErrorRecord  errorRecord  = new ErrorRecord(webException, "WebException", ErrorCategory.ObjectNotFound, this._uri);
                if (webException.InnerException != null)
                {
                    errorRecord.ErrorDetails = new ErrorDetails(webException.InnerException.Message);
                }
                base.WriteError(errorRecord);
                assembly = null;
            }
            catch (InvalidOperationException invalidOperationException1)
            {
                InvalidOperationException invalidOperationException = invalidOperationException1;
                ErrorRecord errorRecord1 = new ErrorRecord(invalidOperationException, "InvalidOperationException", ErrorCategory.InvalidOperation, this._uri);
                base.WriteError(errorRecord1);
                assembly = null;
            }
            return(assembly);

Label0:
            CodeNamespace codeNamespace = new CodeNamespace();

            if (!string.IsNullOrEmpty(NameSpace))
            {
                codeNamespace.Name = NameSpace;
            }
            if (!string.IsNullOrEmpty(ClassName))
            {
                CodeTypeDeclaration codeTypeDeclaration = new CodeTypeDeclaration(ClassName);
                codeTypeDeclaration.IsClass    = true;
                codeTypeDeclaration.Attributes = MemberAttributes.Public;
                codeNamespace.Types.Add(codeTypeDeclaration);
            }
            WebReference           webReference           = new WebReference(discoveryClientProtocol.Documents, codeNamespace);
            WebReferenceCollection webReferenceCollection = new WebReferenceCollection();

            webReferenceCollection.Add(webReference);
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

            codeCompileUnit.Namespaces.Add(codeNamespace);
            WebReferenceOptions webReferenceOption = new WebReferenceOptions();

            webReferenceOption.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateOldAsync;
            webReferenceOption.Verbose = true;
            CSharpCodeProvider cSharpCodeProvider = new CSharpCodeProvider();
            StringCollection   stringCollections  = ServiceDescriptionImporter.GenerateWebReferences(webReferenceCollection, cSharpCodeProvider, codeCompileUnit, webReferenceOption);
            StringBuilder      stringBuilder      = new StringBuilder();
            StringWriter       stringWriter       = new StringWriter(stringBuilder, CultureInfo.InvariantCulture);

            try
            {
                cSharpCodeProvider.GenerateCodeFromCompileUnit(codeCompileUnit, stringWriter, null);
            }
            catch (NotImplementedException notImplementedException1)
            {
                NotImplementedException notImplementedException = notImplementedException1;
                ErrorRecord             errorRecord2            = new ErrorRecord(notImplementedException, "NotImplementedException", ErrorCategory.ObjectNotFound, this._uri);
                base.WriteError(errorRecord2);
            }
            this.sourceHash = stringBuilder.ToString().GetHashCode();
            if (!NewWebServiceProxy.srccodeCache.ContainsKey(this.sourceHash))
            {
                CompilerParameters compilerParameter = new CompilerParameters();
                CompilerResults    compilerResult    = null;
                foreach (string str in stringCollections)
                {
                    base.WriteWarning(str);
                }
                compilerParameter.ReferencedAssemblies.Add("System.dll");
                compilerParameter.ReferencedAssemblies.Add("System.Data.dll");
                compilerParameter.ReferencedAssemblies.Add("System.Xml.dll");
                compilerParameter.ReferencedAssemblies.Add("System.Web.Services.dll");
                compilerParameter.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
                this.GetReferencedAssemblies(typeof(Cmdlet).Assembly, compilerParameter);
                compilerParameter.GenerateInMemory      = true;
                compilerParameter.TreatWarningsAsErrors = false;
                compilerParameter.WarningLevel          = 4;
                compilerParameter.GenerateExecutable    = false;
                try
                {
                    string[] strArrays = new string[1];
                    strArrays[0]   = stringBuilder.ToString();
                    compilerResult = cSharpCodeProvider.CompileAssemblyFromSource(compilerParameter, strArrays);
                }
                catch (NotImplementedException notImplementedException3)
                {
                    NotImplementedException notImplementedException2 = notImplementedException3;
                    ErrorRecord             errorRecord3             = new ErrorRecord(notImplementedException2, "NotImplementedException", ErrorCategory.ObjectNotFound, this._uri);
                    base.WriteError(errorRecord3);
                }
                return(compilerResult.CompiledAssembly);
            }
            else
            {
                NewWebServiceProxy.srccodeCache.TryGetValue(this.sourceHash, out obj);
                base.WriteObject(obj, true);
                return(null);
            }
        }
Пример #12
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);
        }
 public static bool CheckConformance(System.Web.Services.WsiProfiles claims, WebReference webReference, BasicProfileViolationCollection violations)
 {
 }
 public void SecondCharacterCanBeAnUnderscore()
 {
     Assert.IsTrue(WebReference.IsValidNamespace("a_"));
 }
 public void Insert(int index, WebReference webReference)
 {
 }
 public void FirstCharacterCanBeAnUnderscore()
 {
     Assert.IsTrue(WebReference.IsValidNamespace("_aa"));
 }
 public int IndexOf(WebReference webReference)
 {
 }
 public WebReferenceNode(WebReference webReference) : this(webReference.Directory)
 {
     ProjectItem = webReference.WebReferenceUrl;
 }
 public bool Contains(WebReference webReference)
 {
 }
 public void Insert(int index, WebReference webReference)
 {
 }
 public void Remove(WebReference webReference)
 {
 }
 public WebReferenceTest()
 {
     _reference = null;
 }
 // Methods
 public int Add(WebReference webReference)
 {
 }
Пример #24
0
        ///
        /// <summary>
        ///	Generate code for the specified ServiceDescription.
        /// </summary>
        ///
        public bool GenerateCode(WebReferenceCollection references, CodeCompileUnit codeUnit)
        {
            bool hasWarnings = false;

            CodeDomProvider provider = GetProvider();

            StringCollection    validationWarnings;
            WebReferenceOptions opts = new WebReferenceOptions();

            opts.CodeGenerationOptions = options;
            opts.Style         = style;
            opts.Verbose       = verbose;
            validationWarnings = ServiceDescriptionImporter.GenerateWebReferences(references, provider, codeUnit, opts);

            for (int n = 0; n < references.Count; n++)
            {
                WebReference wr = references [n];

                BasicProfileViolationCollection violations = new BasicProfileViolationCollection();
                if (String.Compare(protocol, "SOAP", StringComparison.OrdinalIgnoreCase) == 0 && !WebServicesInteroperability.CheckConformance(WsiProfiles.BasicProfile1_1, wr, violations))
                {
                    wr.Warnings |= ServiceDescriptionImportWarnings.WsiConformance;
                }

                if (wr.Warnings != 0)
                {
                    if (!hasWarnings)
                    {
                        WriteText("", 0, 0);
                        WriteText("There where some warnings while generating the code:", 0, 0);
                    }

                    WriteText("", 0, 0);
                    WriteText(urls[n], 2, 2);

                    if ((wr.Warnings & ServiceDescriptionImportWarnings.WsiConformance) > 0)
                    {
                        WriteText("- This web reference does not conform to WS-I Basic Profile v1.1", 4, 6);
                        foreach (BasicProfileViolation vio in violations)
                        {
                            WriteText(vio.NormativeStatement + ": " + vio.Details, 8, 8);
                            foreach (string ele in vio.Elements)
                            {
                                WriteText("* " + ele, 10, 12);
                            }
                        }
                    }

                    if ((wr.Warnings & ServiceDescriptionImportWarnings.NoCodeGenerated) > 0)
                    {
                        WriteText("- WARNING: No proxy class was generated", 4, 6);
                    }
                    if ((wr.Warnings & ServiceDescriptionImportWarnings.NoMethodsGenerated) > 0)
                    {
                        WriteText("- WARNING: The proxy class generated includes no methods", 4, 6);
                    }
                    if ((wr.Warnings & ServiceDescriptionImportWarnings.OptionalExtensionsIgnored) > 0)
                    {
                        WriteText("- WARNING: At least one optional extension has been ignored", 4, 6);
                    }
                    if ((wr.Warnings & ServiceDescriptionImportWarnings.RequiredExtensionsIgnored) > 0)
                    {
                        WriteText("- WARNING: At least one necessary extension has been ignored", 4, 6);
                    }
                    if ((wr.Warnings & ServiceDescriptionImportWarnings.UnsupportedBindingsIgnored) > 0)
                    {
                        WriteText("- WARNING: At least one binding is of an unsupported type and has been ignored", 4, 6);
                    }
                    if ((wr.Warnings & ServiceDescriptionImportWarnings.UnsupportedOperationsIgnored) > 0)
                    {
                        WriteText("- WARNING: At least one operation is of an unsupported type and has been ignored", 4, 6);
                    }

                    hasWarnings = true;
                }
            }

            if (hasWarnings)
            {
                WriteText("", 0, 0);
            }

            string filename    = outFilename;
            bool   hasBindings = false;

            foreach (object doc in references[0].Documents.Values)
            {
                ServiceDescription desc = doc as ServiceDescription;
                if (desc == null)
                {
                    continue;
                }

                if (desc.Services.Count > 0 && filename == null)
                {
                    filename = desc.Services[0].Name + "." + provider.FileExtension;
                }

                if (desc.Bindings.Count > 0 || desc.Services.Count > 0)
                {
                    hasBindings = true;
                }
            }

            if (filename == null)
            {
                filename = "output." + provider.FileExtension;
            }

            if (hasBindings)
            {
                WriteText("Writing file '" + filename + "'", 0, 0);
                StreamWriter writer = new StreamWriter(filename);

                CodeGeneratorOptions compilerOptions = new CodeGeneratorOptions();
                provider.GenerateCodeFromCompileUnit(codeUnit, writer, compilerOptions);
                writer.Close();
            }

            return(hasWarnings);
        }
Пример #25
0
    public static void Main()
    {
        // Read in a WSDL service description.
        string             url    = "http://www.contoso.com/Example/WebService.asmx?WSDL";
        XmlTextReader      reader = new XmlTextReader(url);
        ServiceDescription wsdl   = ServiceDescription.Read(reader);

        // Create a WSDL collection.
        DiscoveryClientDocumentCollection wsdlCollection =
            new DiscoveryClientDocumentCollection();

        wsdlCollection.Add(url, wsdl);

        // Define the parameters needed to create web references.
        CodeNamespace proxyNamespace = new CodeNamespace("ExampleNamespace");
        string        baseUrl        = "http://www.contoso.com";
        string        protocolName   = "Soap12";

        // Create some web references.
        WebReference reference1 = new WebReference(
            wsdlCollection, proxyNamespace, protocolName,
            "UrlKey1", baseUrl);
        WebReference reference2 = new WebReference(
            wsdlCollection, proxyNamespace, protocolName,
            "UrlKey2", baseUrl);
        WebReference reference3 = new WebReference(
            wsdlCollection, proxyNamespace, protocolName,
            "UrlKey3", baseUrl);

        // Create a web reference collection.
        WebReferenceCollection references = new WebReferenceCollection();

        references.Add(reference1);
        references.Add(reference2);

        // Confirm that the references were inserted.
        Console.WriteLine("The collection contains {0} references.",
                          references.Count);

        // Insert another reference into the collection.
        references.Insert(2, reference3);

        // Print the index of the inserted reference.
        int index = references.IndexOf(reference3);

        Console.WriteLine("The index of reference3 is {0}.", index);

        // Remove the inserted reference from the collection.
        references.Remove(reference3);

        // Determine if the collection contains reference3.
        if (references.Contains(reference3))
        {
            Console.WriteLine("The collection contains reference3.");
        }
        else
        {
            Console.WriteLine("The collection does not contain reference3.");
        }

        // Print the URL key of the first reference in the collection.
        Console.WriteLine(
            "The URL key of the first reference in the collection is {0}.",
            references[0].AppSettingUrlKey);

        // Copy the collection to an array leaving the first array slot empty.
        WebReference[] referenceArray = new WebReference[3];
        references.CopyTo(referenceArray, 1);
        Console.WriteLine(
            "The URL key of the first reference in the array is {0}.",
            referenceArray[1].AppSettingUrlKey);
    }
Пример #26
0
        public static TreeNode AddWebReference(WebReferencesFolderNode webReferencesFolderNode, WebReference webReference)
        {
            WebReferenceNode node = new WebReferenceNode(webReference);

            node.FileNodeStatus = FileNodeStatus.InProject;
            node.InsertSorted(webReferencesFolderNode);
            return(node);
        }
Пример #27
0
        private Assembly GenerateWebServiceProxyAssembly(string NameSpace, string ClassName)
        {
            DiscoveryClientProtocol dcp = new DiscoveryClientProtocol();

            //if paramset is defualtcredential, set the flag in wcclient
            if (_usedefaultcredential.IsPresent)
            {
                dcp.UseDefaultCredentials = true;
            }

            //if paramset is credential, assign the crdentials
            if (ParameterSetName.Equals("Credential", StringComparison.OrdinalIgnoreCase))
            {
                dcp.Credentials = _credential.GetNetworkCredential();
            }

            try
            {
                dcp.AllowAutoRedirect = true;
                dcp.DiscoverAny(_uri.ToString());
                dcp.ResolveAll();
            }
            catch (WebException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "WebException", ErrorCategory.ObjectNotFound, _uri);
                if (ex.InnerException != null)
                {
                    er.ErrorDetails = new ErrorDetails(ex.InnerException.Message);
                }
                WriteError(er);
                return(null);
            }
            catch (InvalidOperationException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, _uri);
                WriteError(er);
                return(null);
            }

            // create the namespace
            CodeNamespace codeNS = new CodeNamespace();

            if (!string.IsNullOrEmpty(NameSpace))
            {
                codeNS.Name = NameSpace;
            }

            //create the class and add it to the namespace
            if (!string.IsNullOrEmpty(ClassName))
            {
                CodeTypeDeclaration codeClass = new CodeTypeDeclaration(ClassName);
                codeClass.IsClass    = true;
                codeClass.Attributes = MemberAttributes.Public;
                codeNS.Types.Add(codeClass);
            }

            //create a web reference to the uri docs
            WebReference           wref  = new WebReference(dcp.Documents, codeNS);
            WebReferenceCollection wrefs = new WebReferenceCollection();

            wrefs.Add(wref);

            //create a codecompileunit and add the namespace to it
            CodeCompileUnit codecompileunit = new CodeCompileUnit();

            codecompileunit.Namespaces.Add(codeNS);

            WebReferenceOptions wrefOptions = new WebReferenceOptions();

            wrefOptions.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateNewAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateOldAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
            wrefOptions.Verbose = true;

            //create a csharpprovider and compile it
            CSharpCodeProvider csharpprovider = new CSharpCodeProvider();
            StringCollection   Warnings       = ServiceDescriptionImporter.GenerateWebReferences(wrefs, csharpprovider, codecompileunit, wrefOptions);

            StringBuilder codegenerator = new StringBuilder();
            StringWriter  writer        = new StringWriter(codegenerator, CultureInfo.InvariantCulture);

            try
            {
                csharpprovider.GenerateCodeFromCompileUnit(codecompileunit, writer, null);
            }
            catch (NotImplementedException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "NotImplementedException", ErrorCategory.ObjectNotFound, _uri);
                WriteError(er);
            }
            //generate the hashcode of the CodeCompileUnit
            _sourceHash = codegenerator.ToString().GetHashCode();

            //if the sourcehash matches the hashcode in the cache,the proxy hasnt changed and so
            // return the instance of th eproxy in the cache
            if (s_srccodeCache.ContainsKey(_sourceHash))
            {
                object obj;
                s_srccodeCache.TryGetValue(_sourceHash, out obj);
                WriteObject(obj, true);
                return(null);
            }
            CompilerParameters options = new CompilerParameters();
            CompilerResults    results = null;

            foreach (string warning in Warnings)
            {
                this.WriteWarning(warning);
            }

            // add the refernces to the required assemblies
            options.ReferencedAssemblies.Add("System.dll");
            options.ReferencedAssemblies.Add("System.Data.dll");
            options.ReferencedAssemblies.Add("System.Xml.dll");
            options.ReferencedAssemblies.Add("System.Web.Services.dll");
            options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
            GetReferencedAssemblies(typeof(Cmdlet).Assembly, options);
            options.GenerateInMemory      = true;
            options.TreatWarningsAsErrors = false;
            options.WarningLevel          = 4;
            options.GenerateExecutable    = false;
            try
            {
                results = csharpprovider.CompileAssemblyFromSource(options, codegenerator.ToString());
            }
            catch (NotImplementedException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "NotImplementedException", ErrorCategory.ObjectNotFound, _uri);
                WriteError(er);
            }

            return(results.CompiledAssembly);
        }
 public void EmptyStringIsNotValid()
 {
     Assert.IsFalse(WebReference.IsValidNamespace(String.Empty));
 }
        public override void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
            // Only attempt to get the Indigo provider once
            if (!s_triedToGetWebRefType)
            {
                s_indigoWebRefProviderType = BuildManager.GetType(IndigoWebRefProviderTypeName, false /*throwOnError*/);
                s_triedToGetWebRefType     = true;
            }

            // If we have an Indigo provider, instantiate it and forward the GenerateCode call to it
            if (s_indigoWebRefProviderType != null)
            {
                BuildProvider buildProvider = (BuildProvider)HttpRuntime.CreateNonPublicInstance(s_indigoWebRefProviderType);
                buildProvider.SetVirtualPath(VirtualPathObject);
                buildProvider.GenerateCode(assemblyBuilder);
            }

            // e.g "/MyApp/Application_WebReferences"
            VirtualPath rootWebRefDirVirtualPath = HttpRuntime.WebRefDirectoryVirtualPath;

            // e.g "/MyApp/Application_WebReferences/Foo/Bar"
            string currentWebRefDirVirtualPath = _vdir.VirtualPath;

            Debug.Assert(StringUtil.StringStartsWithIgnoreCase(
                             currentWebRefDirVirtualPath, rootWebRefDirVirtualPath.VirtualPathString));

            string ns;

            if (rootWebRefDirVirtualPath.VirtualPathString.Length == currentWebRefDirVirtualPath.Length)
            {
                // If it's the root WebReferences dir, use the empty namespace
                ns = String.Empty;
            }
            else
            {
                // e.g. "Foo/Bar"
                Debug.Assert(rootWebRefDirVirtualPath.HasTrailingSlash);
                currentWebRefDirVirtualPath = UrlPath.RemoveSlashFromPathIfNeeded(currentWebRefDirVirtualPath);
                currentWebRefDirVirtualPath = currentWebRefDirVirtualPath.Substring(
                    rootWebRefDirVirtualPath.VirtualPathString.Length);

                // Split it into chunks separated by '/'
                string[] chunks = currentWebRefDirVirtualPath.Split('/');

                // Turn all the relevant chunks into valid namespace chunks
                for (int i = 0; i < chunks.Length; i++)
                {
                    chunks[i] = Util.MakeValidTypeNameFromString(chunks[i]);
                }

                // Put the relevant chunks back together to form the namespace
                ns = String.Join(".", chunks);
            }
#if !FEATURE_PAL // FEATURE_PAL does not support System.Web.Services
            CodeNamespace codeNamespace = new CodeNamespace(ns);

            // for each discomap file, read all references and add them to the WebReferenceCollection
            WebReferenceCollection webs = new WebReferenceCollection();

            bool hasDiscomap = false;

            // Go through all the discomap in the directory
            foreach (VirtualFile child in _vdir.Files)
            {
                string extension = UrlPath.GetExtension(child.VirtualPath);
                extension = extension.ToLower(CultureInfo.InvariantCulture);

                if (extension == ".discomap")
                {
                    // NOTE: the WebReferences code requires physical path, so this feature
                    // cannot work with a non-file based VirtualPathProvider
                    string physicalPath = HostingEnvironment.MapPath(child.VirtualPath);

                    DiscoveryClientProtocol client = new DiscoveryClientProtocol();
                    client.AllowAutoRedirect = true;
                    client.Credentials       = CredentialCache.DefaultCredentials;

                    client.ReadAll(physicalPath);

                    WebReference webRefTemp = new WebReference(client.Documents, codeNamespace);

                    //

                    string fileName          = System.IO.Path.ChangeExtension(UrlPath.GetFileName(child.VirtualPath), null);
                    string appSetttingUrlKey = ns + "." + fileName;

                    WebReference web = new WebReference(client.Documents, codeNamespace, webRefTemp.ProtocolName, appSetttingUrlKey, null);

                    webs.Add(web);

                    hasDiscomap = true;
                }
            }

            // If we didn't find any discomap files, we have nothing to generate
            if (!hasDiscomap)
            {
                return;
            }

            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
            codeCompileUnit.Namespaces.Add(codeNamespace);

            //public static StringCollection GenerateWebReferences(WebReferenceCollection webReferences, CodeDomProvider codeProvider, CodeCompileUnit codeCompileUnit, WebReferenceOptions options) {
            WebReferenceOptions options = new WebReferenceOptions();
            options.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateOldAsync;
            options.Style   = ServiceDescriptionImportStyle.Client;
            options.Verbose = true;
            StringCollection shareWarnings = ServiceDescriptionImporter.GenerateWebReferences(webs, assemblyBuilder.CodeDomProvider, codeCompileUnit, options);
            // Add the CodeCompileUnit to the compilation
            assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit);
#else // !FEATURE_PAL
            return;
#endif // !FEATURE_PAL
        }
 public void SecondCharacterCanBeANumber()
 {
     Assert.IsTrue(WebReference.IsValidNamespace("a8"));
 }
 // Methods
 public int Add(WebReference webReference)
 {
 }
 public void SecondCharacterCanBeADot()
 {
     Assert.IsTrue(WebReference.IsValidNamespace("a.b"));
 }
 public bool Contains(WebReference webReference)
 {
 }
 public void InvalidReferenceName()
 {
     Assert.IsFalse(WebReference.IsValidNamespace("Test.10.4.4.4"));
 }
 public void CopyTo(WebReference[] array, int index)
 {
 }
 void DiscoveredWebServices(DiscoveryClientProtocol protocol)
 {
     if (protocol != null) {
         addButton.Enabled = true;
         namespaceTextBox.Text = GetDefaultNamespace();
         referenceNameTextBox.Text = GetReferenceName();
         webServicesView.Add(GetServiceDescriptions(protocol));
         webReference = new WebReference(project, discoveryUri.AbsoluteUri, referenceNameTextBox.Text, namespaceTextBox.Text, protocol);
     } else {
         webReference = null;
         addButton.Enabled = false;
         webServicesView.Clear();
     }
 }
Пример #37
0
        public override void GenerateCode(AssemblyBuilder assemblyBuilder)
        {
            string str2;

            if (!s_triedToGetWebRefType)
            {
                s_indigoWebRefProviderType = BuildManager.GetType("System.Web.Compilation.WCFBuildProvider", false);
                s_triedToGetWebRefType     = true;
            }
            if (s_indigoWebRefProviderType != null)
            {
                BuildProvider provider = (BuildProvider)HttpRuntime.CreateNonPublicInstance(s_indigoWebRefProviderType);
                provider.SetVirtualPath(base.VirtualPathObject);
                provider.GenerateCode(assemblyBuilder);
            }
            VirtualPath webRefDirectoryVirtualPath = HttpRuntime.WebRefDirectoryVirtualPath;
            string      virtualPath = this._vdir.VirtualPath;

            if (webRefDirectoryVirtualPath.VirtualPathString.Length == virtualPath.Length)
            {
                str2 = string.Empty;
            }
            else
            {
                string[] strArray = UrlPath.RemoveSlashFromPathIfNeeded(virtualPath).Substring(webRefDirectoryVirtualPath.VirtualPathString.Length).Split(new char[] { '/' });
                for (int i = 0; i < strArray.Length; i++)
                {
                    strArray[i] = Util.MakeValidTypeNameFromString(strArray[i]);
                }
                str2 = string.Join(".", strArray);
            }
            CodeNamespace          proxyCode     = new CodeNamespace(str2);
            WebReferenceCollection webReferences = new WebReferenceCollection();
            bool flag = false;

            foreach (VirtualFile file in this._vdir.Files)
            {
                if (UrlPath.GetExtension(file.VirtualPath).ToLower(CultureInfo.InvariantCulture) == ".discomap")
                {
                    string topLevelFilename          = HostingEnvironment.MapPath(file.VirtualPath);
                    DiscoveryClientProtocol protocol = new DiscoveryClientProtocol {
                        AllowAutoRedirect = true,
                        Credentials       = CredentialCache.DefaultCredentials
                    };
                    protocol.ReadAll(topLevelFilename);
                    WebReference reference        = new WebReference(protocol.Documents, proxyCode);
                    string       str5             = Path.ChangeExtension(UrlPath.GetFileName(file.VirtualPath), null);
                    string       appSettingUrlKey = str2 + "." + str5;
                    WebReference webReference     = new WebReference(protocol.Documents, proxyCode, reference.ProtocolName, appSettingUrlKey, null);
                    webReferences.Add(webReference);
                    flag = true;
                }
            }
            if (flag)
            {
                CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
                codeCompileUnit.Namespaces.Add(proxyCode);
                WebReferenceOptions options = new WebReferenceOptions {
                    CodeGenerationOptions = CodeGenerationOptions.GenerateOldAsync | CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateProperties,
                    Style   = ServiceDescriptionImportStyle.Client,
                    Verbose = true
                };
                ServiceDescriptionImporter.GenerateWebReferences(webReferences, assemblyBuilder.CodeDomProvider, codeCompileUnit, options);
                assemblyBuilder.AddCodeCompileUnit(this, codeCompileUnit);
            }
        }