Exemple #1
0
	static void Main ()
	{
		TestWebService svc = new TestWebService ();
		Assert.AreEqual ("Hello World", svc.HelloWorld (), "#1");

		string url = "http://127.0.0.1:8081/TestWebService.asmx?WSDL";

		DiscoveryClientProtocol dcp = new DiscoveryClientProtocol ();

		using (Stream s = dcp.Download (ref url)) {
			ServiceDescription sd = ServiceDescription.Read (s);
#if NET_2_0
			Assert.AreEqual (2, sd.Bindings.Count, "#A1");
			Assert.AreEqual ("TestWebServiceSoap", sd.Bindings [0].Name, "#A2");
			Assert.AreEqual ("http://tempuri.org/:TestWebServiceSoap", sd.Bindings [0].Type.ToString (), "#A3");
			Assert.AreEqual ("TestWebServiceSoap12", sd.Bindings [1].Name, "#A4");
			Assert.AreEqual ("http://tempuri.org/:TestWebServiceSoap", sd.Bindings [1].Type.ToString (), "#A5");
#else
			Assert.AreEqual (1, sd.Bindings.Count, "#A1");
			Assert.AreEqual ("TestWebServiceSoap", sd.Bindings [0].Name, "#A2");
			Assert.AreEqual ("http://tempuri.org/:TestWebServiceSoap", sd.Bindings [0].Type.ToString (), "#A3");
#endif

			Assert.AreEqual (1, sd.PortTypes.Count, "#B1");
			Assert.AreEqual ("TestWebServiceSoap", sd.PortTypes [0].Name, "#B2");
		}
	}
Exemple #2
0
	public static void RetrieveServiceData (ServiceData sd, DiscoveryClientProtocol contract)
	{
		ServiceDescriptionCollection col = new ServiceDescriptionCollection ();
		foreach (object doc in contract.Documents.Values)
			if (doc is ServiceDescription) col.Add ((ServiceDescription)doc);
		
		string loc = GetLocation (col[0]);
		if (loc != null)
		{
			WebResponse res = null;
			try
			{
				WebRequest req = (WebRequest)WebRequest.Create (loc);
				req.Timeout = 15000;
				res = req.GetResponse ();
			}
			catch (Exception ex)
			{
				WebException wex = ex as WebException;
				if (wex != null) res = wex.Response;
			}
			if (res != null)
			{
				sd.ServerType = res.Headers ["Server"] + " # " + res.Headers ["X-Powered-By"];
			}
		}
		
		ArrayList bins = GetBindingTypes (col);
		sd.Protocols = (string[]) bins.ToArray(typeof(string));
	}
Exemple #3
0
	static void Resolve (ServiceData sd)
	{
		Console.Write ("Resolving " + sd.Wsdl + " ");
		try
		{
			DiscoveryClientProtocol contract = new DiscoveryClientProtocol ();
			contract.DiscoverAny (sd.Wsdl);
			
			if (sd.Protocols == null || sd.Protocols.Length==0) 
				RetrieveServiceData (sd, contract);
				
			string wsdlFile = GetWsdlFile (sd);
			CreateFolderForFile (wsdlFile);
			
			ServiceDescription doc = (ServiceDescription) contract.Documents [sd.Wsdl];
			doc.Write (wsdlFile);
			
			Console.WriteLine ("OK");
			CleanFailures (sd);
		}
		catch (Exception ex)
		{
			Console.WriteLine ("FAILED");
			ReportError ("Error resolving: " + sd.Wsdl, ex.ToString ());
			RegisterFailure (sd);
		}
	}
Exemple #4
0
	static void UpdateReferences (string url, string ignoreFile)
	{	
		Console.WriteLine ();
		Console.WriteLine ("Updating service references");
		Console.WriteLine ("---------------------------");
		
		ArrayList ignoreList = new ArrayList ();
		
		if (ignoreFile != null)
		{
			StreamReader sr = new StreamReader (ignoreFile);
			string line;
			while ((line = sr.ReadLine ()) != null)
			{
				int i = line.IndexOfAny (new char[] {' ','\t'});
				if (i != -1) line = line.Substring (0,i);
				ignoreList.Add (line);
			}
		}
		
		DiscoveryClientProtocol client = new DiscoveryClientProtocol ();
		client.DiscoverAny (url);
		
		ArrayList list = new ArrayList (client.References.Values);
		foreach (DiscoveryReference re in list)
		{
			if (!(re is ContractReference)) continue;
			
			bool ignore = ignoreList.Contains (re.Url);
			
			ServiceData sd = FindService (re.Url);
			
			if (ignore)
			{
				if (sd != null) {
					RemoveService (re.Url);
					Console.WriteLine ("Removed " + re.Url);
				}
				continue;
			}
			
			if (sd == null)
			{
				sd = CreateServiceData (re);
				Console.WriteLine ("Added " + re.Url);
				services.services.Add (sd);
			}
		}
		Console.WriteLine ("Done");
		Console.WriteLine ();
	}
        public override void FixtureSetUp()
        {
            base.FixtureSetUp();
            // Set up the project.
            MSBuildBasedProject project = WebReferenceTestHelper.CreateTestProject("C#");

            project.FileName = FileName.Create("c:\\projects\\test\\foo.csproj");

            // Web references item.
            WebReferencesProjectItem webReferencesItem = new WebReferencesProjectItem(project);

            webReferencesItem.Include = "Web References\\";
            ProjectService.AddProjectItem(project, webReferencesItem);

            // Web reference url.
            WebReferenceUrl webReferenceUrl = new WebReferenceUrl(project);

            webReferenceUrl.Include       = "http://localhost/test.asmx";
            webReferenceUrl.UpdateFromURL = "http://localhost/test.asmx";
            webReferenceUrl.RelPath       = "Web References\\localhost";
            ProjectService.AddProjectItem(project, webReferenceUrl);

            FileProjectItem discoFileItem = new FileProjectItem(project, ItemType.None);

            discoFileItem.Include = "Web References\\localhost\\test.disco";
            ProjectService.AddProjectItem(project, discoFileItem);

            FileProjectItem wsdlFileItem = new FileProjectItem(project, ItemType.None);

            wsdlFileItem.Include = "Web References\\localhost\\test.wsdl";
            ProjectService.AddProjectItem(project, wsdlFileItem);

            // Proxy
            FileProjectItem proxyItem = new FileProjectItem(project, ItemType.Compile);

            proxyItem.Include       = "Web References\\localhost\\Reference.cs";
            proxyItem.DependentUpon = "Reference.map";
            ProjectService.AddProjectItem(project, proxyItem);

            // Reference map.
            FileProjectItem mapItem = new FileProjectItem(project, ItemType.None);

            mapItem.Include = "Web References\\localhost\\Reference.map";
            ProjectService.AddProjectItem(project, mapItem);

            // System.Web.Services reference.
            ReferenceProjectItem webServicesReferenceItem = new ReferenceProjectItem(project, "System.Web.Services");

            ProjectService.AddProjectItem(project, webServicesReferenceItem);

            // Set up the web reference.
            DiscoveryClientProtocol    protocol     = new DiscoveryClientProtocol();
            DiscoveryDocumentReference discoveryRef = new DiscoveryDocumentReference();

            discoveryRef.Url = "http://localhost/new.asmx";
            protocol.References.Add(discoveryRef);

            ContractReference contractRef = new ContractReference();

            contractRef.Url            = "http://localhost/new.asmx?wsdl";
            contractRef.ClientProtocol = new DiscoveryClientProtocol();
            ServiceDescription desc = new ServiceDescription();

            contractRef.ClientProtocol.Documents.Add(contractRef.Url, desc);
            protocol.References.Add(contractRef);

            WebReferenceTestHelper.InitializeProjectBindings();

            var webReference = new Gui.WebReference(project, "http://localhost/new.asmx", "localhost", "ProxyNamespace", protocol);

            changes = webReference.GetChanges(project);
        }
Exemple #6
0
 public WebReference(IProject project, string url, string name, string proxyNamespace, DiscoveryClientProtocol protocol)
 {
     this.project        = project;
     this.url            = url;
     this.protocol       = protocol;
     this.proxyNamespace = proxyNamespace;
     this.name           = name;
     GetRelativePath();
 }
Exemple #7
0
        /// <summary>Generate a text description for the specified DiscoveryClientProtocol.</summary>
        /// <param name="protocol">A DiscoveryClientProtocol containing the information for the service.</param>
        /// <returns>An XmlDocument containing the generated xml for the specified discovery protocol.</returns>
        public static void GenerateWsdlXml(StringBuilder text, DiscoveryClientProtocol protocol)
        {
            // Code Namespace & Compile Unit
            var codeNamespace = new CodeNamespace();
            var codeUnit      = new CodeCompileUnit();

            codeUnit.Namespaces.Add(codeNamespace);

            // Import and set the warning
            ServiceDescriptionImporter importer = ReadServiceDescriptionImporter(protocol);

            importer.Import(codeNamespace, codeUnit);

            foreach (CodeTypeDeclaration type in codeNamespace.Types)
            {
                if (type.BaseTypes.Count == 0 || type.BaseTypes[0].BaseType != "System.Web.Services.Protocols.SoapHttpClientProtocol")
                {
                    continue;
                }

                text.AppendFormat("<big><b><u>{0}</u></b></big>\n\n", type.Name);
                string coms = GetCommentElements(type);
                if (coms != null)
                {
                    text.Append(coms).Append("\n\n");
                }

                foreach (CodeTypeMember mem in type.Members)
                {
                    var met = mem as CodeMemberMethod;
                    if (met != null && !(mem is CodeConstructor))
                    {
                        // Method
                        // Asynch Begin & End Results
                        string returnType = met.ReturnType.BaseType;
                        if (met.Name.StartsWith("Begin", StringComparison.Ordinal) && returnType == "System.IAsyncResult")
                        {
                            continue;                                   // BeginXXX method
                        }
                        if (met.Name.EndsWith("Async", StringComparison.Ordinal))
                        {
                            continue;
                        }
                        if (met.Name.StartsWith("On", StringComparison.Ordinal) && met.Name.EndsWith("Completed", StringComparison.Ordinal))
                        {
                            continue;
                        }
                        if (met.Parameters.Count > 0)
                        {
                            CodeParameterDeclarationExpression par = met.Parameters [met.Parameters.Count - 1];
                            if (met.Name.StartsWith("End", StringComparison.Ordinal) && par.Type.BaseType == "System.IAsyncResult")
                            {
                                continue;                                       // EndXXX method
                            }
                        }
                        text.AppendFormat("<b>{0}</b> (", met.Name);
                        // Parameters
                        for (int n = 0; n < met.Parameters.Count; n++)
                        {
                            CodeParameterDeclarationExpression par = met.Parameters [n];
                            if (n > 0)
                            {
                                text.Append(", ");
                            }
                            text.AppendFormat("{0}: <i>{1}</i>", par.Name, par.Type.BaseType);
                        }
                        text.Append(")");
                        if (returnType != "System.Void")
                        {
                            text.AppendFormat(": <i>{0}</i>", returnType);
                        }

                        // Comments
                        coms = GetCommentElements(met);
                        if (coms != null)
                        {
                            text.Append("\n").Append(coms);
                        }
                        text.Append("\n\n");
                    }
                }
            }
        }
Exemple #8
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);
            }
        }
        static object Call(string url, string servername, string methodname, params object[] args)
        {
            string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";

            try
            { //获取WSDL
                WebClient                  wc     = new WebClient();
                Stream                     stream = wc.OpenRead(url);
                ServiceDescription         sd     = ServiceDescription.Read(stream);
                ServiceDescriptionImporter sdi    = new ServiceDescriptionImporter();
                sdi.ProtocolName          = "Soap";
                sdi.Style                 = ServiceDescriptionImportStyle.Client; //生成客户端代理
                sdi.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
                sdi.AddServiceDescription(sd, null, null);                        //添加WSDL文档

                //@namespace = string.Format(@namespace, sd.Services[0].Name);
                CodeNamespace cn = new CodeNamespace(@namespace);
                //生成客户端代理类代码
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                DiscoveryClientProtocol dcp = new DiscoveryClientProtocol();
                dcp.DiscoverAny(url);
                dcp.ResolveAll();
                foreach (object osd in dcp.Documents.Values)
                {
                    if (osd is ServiceDescription)
                    {
                        sdi.AddServiceDescription((ServiceDescription)osd, null, null);
                    }
                    ;
                    if (osd is XmlSchema)
                    {
                        sdi.Schemas.Add((XmlSchema)osd);
                    }
                }
                sdi.Import(cn, ccu);
                CSharpCodeProvider icc = new CSharpCodeProvider();
                //设定编译参数
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory   = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");
                //编译代理类
                CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                if (!cr.Errors.HasErrors)
                {
                    Assembly asm = cr.CompiledAssembly;
                    Type     t   = asm.GetType(@namespace + "." + servername); // 如果在前面为代理类添加了命名空间,此处需要将命名空间添加到类型前面。

                    object     o      = Activator.CreateInstance(t);
                    MethodInfo method = t.GetMethod(methodname);
                    return(method.Invoke(o, args));
                }
                return(null);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }
        private Assembly GenerateWebServiceProxyAssembly(string NameSpace, string ClassName)
        {
            DiscoveryClientProtocol dcp = new DiscoveryClientProtocol();

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

            //if paramset is credential, assign the credentials
            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 references 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);
        }
Exemple #11
0
        ///
        /// <summary>
        ///	Driver's main control flow:
        ///	 - parse arguments
        ///	 - report required messages
        ///	 - terminate if no input
        ///	 - report errors
        /// </summary>
        ///
        int Run(string[] args)
        {
            try
            {
                // parse command line arguments
                foreach (string argument in args)
                {
                    ImportArgument(argument);
                }

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

                if (help || (!hasURL && className == null))
                {
                    Console.WriteLine(UsageMessage);
                    return(0);
                }

                if (className == null)
                {
                    DiscoveryClientProtocol dcc = CreateClient();

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

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

                    foreach (object doc in dcc.Documents.Values)
                    {
                        if (doc is ServiceDescription)
                        {
                            descriptions.Add((ServiceDescription)doc);
                        }
                        else if (doc is XmlSchema)
                        {
                            schemas.Add((XmlSchema)doc);
                        }
                    }

                    if (descriptions.Count == 0)
                    {
                        Console.WriteLine("Warning: no classes were generated.");
                        return(0);
                    }
                }
                else
                {
                    string[] names = className.Split(',');
                    if (names.Length != 2)
                    {
                        throw new Exception("Invalid parameter value for 'type'");
                    }
                    string cls      = names[0].Trim();
                    string assembly = names[1].Trim();

                    Assembly asm = Assembly.LoadFrom(assembly);
                    Type     t   = asm.GetType(cls);
                    if (t == null)
                    {
                        throw new Exception("Type '" + cls + "' not found in assembly " + assembly);
                    }
                    ServiceDescriptionReflector reflector = new ServiceDescriptionReflector();
                    foreach (string url in urls)
                    {
                        reflector.Reflect(t, url);
                    }
                    foreach (XmlSchema s in reflector.Schemas)
                    {
                        schemas.Add(s);
                    }

                    foreach (ServiceDescription sd in reflector.ServiceDescriptions)
                    {
                        descriptions.Add(sd);
                    }
                }

                if (sampleSoap != null)
                {
                    ConsoleSampleGenerator.Generate(descriptions, schemas, sampleSoap, generator.Protocol);
                    return(0);
                }

                // generate the code
                generator.GenerateCode(descriptions, schemas);
                return(0);
            }
            catch (NullReferenceException e)
            {
                Console.WriteLine(e);
                return(2);
            }
            catch (InvalidCastException e)
            {
                Console.WriteLine(e);
                return(2);
            }
            catch (Exception exception)
            {
                Console.WriteLine("Error: {0}", exception.Message);
                // FIXME: surpress this except for when debug is enabled
                //Console.WriteLine("Stack:\n {0}", exception.StackTrace);
                return(2);
            }
        }
    static void Main()
    {
        try
        {
            DiscoveryClientProtocol myDiscoveryClientProtocol =
                new DiscoveryClientProtocol();

            // Get the collection of DiscoveryClientResult objects.
            DiscoveryClientResultCollection myDiscoveryClientResultCollection =
                myDiscoveryClientProtocol.ReadAll("results.discomap");

            Console.WriteLine("The number of DiscoveryClientResult objects: "
                              + myDiscoveryClientResultCollection.Count);

            Console.WriteLine(
                "Removing a DiscoveryClientResult from the collection...");
// <Snippet1>
            // Remove the first DiscoveryClientResult from the collection.
            myDiscoveryClientResultCollection.Remove(
                myDiscoveryClientResultCollection[0]);
// </Snippet1>
            Console.WriteLine(
                "Adding a DiscoveryClientResult to the collection...");
// <Snippet2>
// <Snippet3>
// <Snippet4>
// <Snippet5>
// <Snippet6>
            // Initialize new instance of the DiscoveryClientResult class.
            DiscoveryClientResult myDiscoveryClientResult =
                new DiscoveryClientResult();

            // Set the type of reference in the discovery document as
            // DiscoveryDocumentReference.
            myDiscoveryClientResult.ReferenceTypeName =
                "System.Web.Services.Discovery.DiscoveryDocumentReference";

            // Set the URL for the reference.
            myDiscoveryClientResult.Url =
                "http://localhost/Discovery/Service1_cs.asmx?disco";

            // Set the name of the file in which the reference is saved.
            myDiscoveryClientResult.Filename = "Service1_cs.disco";

            // Add the DiscoveryClientResult to the collection.
            myDiscoveryClientResultCollection.Add(myDiscoveryClientResult);
// </Snippet6>
// </Snippet5>
// </Snippet4>
// </Snippet3>
// </Snippet2>

// <Snippet7>
            if (myDiscoveryClientResultCollection.Contains(
                    myDiscoveryClientResult))
            {
                Console.WriteLine(
                    "The collection contains the specified " +
                    "DiscoveryClientResult instance.");
            }
// </Snippet7>
            Console.WriteLine("Displaying the items in collection");

// <Snippet8>
            for (int i = 0; i < myDiscoveryClientResultCollection.Count; i++)
            {
                DiscoveryClientResult myClientResult =
                    myDiscoveryClientResultCollection[i];
                Console.WriteLine("DiscoveryClientResult " + (i + 1));
                Console.WriteLine("Type of reference in the discovery document: "
                                  + myClientResult.ReferenceTypeName);
                Console.WriteLine("Url for reference:" + myClientResult.Url);
                Console.WriteLine("File for saving the reference: "
                                  + myClientResult.Filename);
            }
// </Snippet8>
        }
        catch (Exception e)
        {
            Console.WriteLine("Error is " + e.Message);
        }
    }
 public WebServiceDiscoveryResultWS(DiscoveryClientProtocol protocol, WebReferenceItem item) : base(WebReferencesService.WsEngine, item)
 {
     this.protocol = protocol;
 }
Exemple #14
0
	static void ReadParameters (string[] args)
	{
		prot = new DiscoveryClientProtocol ();
		NetworkCredential cred = new NetworkCredential ();
		NetworkCredential proxyCred = new NetworkCredential ();
		WebProxy proxy = new WebProxy ();
		url = null;
		
		foreach (string arg in args)
		{
			if (arg.StartsWith ("/") || arg.StartsWith ("-"))
			{
				string parg = arg.Substring (1);
				int i = parg.IndexOf (":");
				string param = null;
				if (i != -1) {
					param = parg.Substring (i+1);
					parg = parg.Substring (0,i);
				}
				
				switch (parg)
				{
					case "nologo":
						logo = false;
						break;
						
					case "nosave":
						save = false;
						break;
						
					case "out":	case "o":
						directory = param;
						break;
						
					case "username": case "u":
						cred.UserName = param;
						break;
						
					case "password": case "p":
						cred.Password = param;
						break;
						
					case "domain": case "d":
						cred.Domain = param;
						break;
						
					case "proxy":
						proxy.Address = new Uri (param);
						break;
						
					case "proxyusername":
						proxyCred.UserName = param;
						break;
						
					case "proxypassword":
						proxyCred.Password = param;
						break;
						
					case "proxydomain":
						proxyCred.Domain = param;
						break;
				}
				
				if (cred.UserName != null)
					prot.Credentials = cred;
					
				if (proxyCred.UserName != null)
					proxy.Credentials = proxyCred;
					
				if (proxy.Address != null)
					prot.Proxy = proxy;
			}
			else
			{
				url = arg;
			}
		}
	}
    static void ReadParameters(string[] args)
    {
        prot = new DiscoveryClientProtocol();
        NetworkCredential cred      = new NetworkCredential();
        NetworkCredential proxyCred = new NetworkCredential();
        WebProxy          proxy     = new WebProxy();

        url = null;

        foreach (string arg in args)
        {
            if (arg.StartsWith("/") || arg.StartsWith("-"))
            {
                string parg  = arg.Substring(1);
                int    i     = parg.IndexOf(":");
                string param = null;
                if (i != -1)
                {
                    param = parg.Substring(i + 1);
                    parg  = parg.Substring(0, i);
                }

                switch (parg)
                {
                case "nologo":
                    logo = false;
                    break;

                case "nosave":
                    save = false;
                    break;

                case "out":
                case "o":
                    directory = param;
                    break;

                case "username":
                case "u":
                    cred.UserName = param;
                    break;

                case "password":
                case "p":
                    cred.Password = param;
                    break;

                case "domain":
                case "d":
                    cred.Domain = param;
                    break;

                case "proxy":
                    proxy.Address = new Uri(param);
                    break;

                case "proxyusername":
                    proxyCred.UserName = param;
                    break;

                case "proxypassword":
                    proxyCred.Password = param;
                    break;

                case "proxydomain":
                    proxyCred.Domain = param;
                    break;
                }

                if (cred.UserName != null)
                {
                    prot.Credentials = cred;
                }

                if (proxyCred.UserName != null)
                {
                    proxy.Credentials = proxyCred;
                }

                if (proxy.Address != null)
                {
                    prot.Proxy = proxy;
                }
            }
            else
            {
                url = arg;
            }
        }
    }
Exemple #16
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);
            }
        }