private DiscoveryReference GenerateWebReferences(WebReference reference, CodeCompileUnit compileUnit)
        {
            var result = new DiscoveryReference();
            CheckInteroperabilityConformance(reference, result);

            var webReferences = new WebReferenceCollection {reference};
            var options = new WebReferenceOptions
            {
                CodeGenerationOptions = CodeGenerationOptions.GenerateProperties
            };

            ServiceDescriptionImporter.GenerateWebReferences(
                webReferences, _codeProvider, compileUnit, options);
            CheckDescriptionImportValidations(reference, result);

            if (!result.HasErrors)
            {
                result.CodeDom = compileUnit;
                result.CodeProvider = _codeProvider;
                result.Bindings.AddRange(
                    GetSoapBindings(_discovery.GetServices()));
            }

            return result;
        }
Ejemplo n.º 2
0
		[MonoTODO] // where to use Verbose and Extensions in options?
		public static StringCollection GenerateWebReferences (
			WebReferenceCollection webReferences, 
			CodeDomProvider codeGenerator, 
			CodeCompileUnit codeCompileUnit, 
			WebReferenceOptions options)
		{
			StringCollection allWarnings = new StringCollection ();
			ImportContext context = new ImportContext (new CodeIdentifiers(), true);
			
			foreach (WebReference reference in webReferences) 
			{
				ServiceDescriptionImporter importer = new ServiceDescriptionImporter ();
				if (codeGenerator != null)
					importer.CodeGenerator = codeGenerator;
				importer.CodeGenerationOptions = options.CodeGenerationOptions;
				importer.Context = context;
				importer.Style = options.Style;
				importer.ProtocolName = reference.ProtocolName;
				
				importer.AddReference (reference);
				
				reference.Warnings = importer.Import (reference.ProxyCode, codeCompileUnit);
				reference.SetValidationWarnings (context.Warnings);
				foreach (string s in context.Warnings)
					allWarnings.Add (s);

				context.Warnings.Clear ();
			}

			return allWarnings;
		}
Ejemplo n.º 3
0
        public static StringCollection GenerateWebReferences(WebReferenceCollection webReferences, CodeDomProvider codeProvider, System.CodeDom.CodeCompileUnit codeCompileUnit, WebReferenceOptions options)
        {
            if (codeCompileUnit != null)
            {
                codeCompileUnit.ReferencedAssemblies.Add("System.dll");
                codeCompileUnit.ReferencedAssemblies.Add("System.Xml.dll");
                codeCompileUnit.ReferencedAssemblies.Add("System.Web.Services.dll");
                codeCompileUnit.ReferencedAssemblies.Add("System.EnterpriseServices.dll");
            }
            Hashtable namespaces    = new Hashtable();
            Hashtable exportContext = new Hashtable();

            foreach (WebReference reference in webReferences)
            {
                ServiceDescriptionImporter importer = new ServiceDescriptionImporter(codeCompileUnit);
                XmlSchemas schemas = new XmlSchemas();
                ServiceDescriptionCollection descriptions = new ServiceDescriptionCollection();
                foreach (DictionaryEntry entry in reference.Documents)
                {
                    AddDocument((string)entry.Key, entry.Value, schemas, descriptions, reference.ValidationWarnings);
                }
                importer.Schemas.Add(schemas);
                foreach (ServiceDescription description in descriptions)
                {
                    importer.AddServiceDescription(description, reference.AppSettingUrlKey, reference.AppSettingBaseUrl);
                }
                importer.CodeGenerator         = codeProvider;
                importer.ProtocolName          = reference.ProtocolName;
                importer.Style                 = options.Style;
                importer.CodeGenerationOptions = options.CodeGenerationOptions;
                foreach (string str in options.SchemaImporterExtensions)
                {
                    importer.Extensions.Add(Type.GetType(str, true));
                }
                System.Xml.Serialization.ImportContext importContext = Context(reference.ProxyCode, namespaces, options.Verbose);
                reference.Warnings = importer.Import(reference.ProxyCode, importContext, exportContext, reference.ValidationWarnings);
                if (reference.ValidationWarnings.Count != 0)
                {
                    reference.Warnings |= ServiceDescriptionImportWarnings.SchemaValidation;
                }
            }
            StringCollection strings = new StringCollection();

            if (options.Verbose)
            {
                foreach (System.Xml.Serialization.ImportContext context2 in namespaces.Values)
                {
                    foreach (string str2 in context2.Warnings)
                    {
                        strings.Add(str2);
                    }
                }
            }
            return(strings);
        }
		public override void GenerateCode (AssemblyBuilder assemblyBuilder)
		{
			CodeCompileUnit unit = new CodeCompileUnit ();
			CodeNamespace proxyCode = new CodeNamespace ();
			unit.Namespaces.Add (proxyCode);	

			var description = ServiceDescription.Read (OpenReader ());
			var discCollection = new DiscoveryClientDocumentCollection () {
					{VirtualPath, description}
				};
			
			var webref = new WebReferenceCollection () {
					new WebReference (discCollection, proxyCode)
				};

			var options = new WebReferenceOptions ();
			options.Style = ServiceDescriptionImportStyle.Client;
			ServiceDescriptionImporter.GenerateWebReferences (webref, assemblyBuilder.CodeDomProvider, unit, options);

			assemblyBuilder.AddCodeCompileUnit (unit);
		}
 public static StringCollection GenerateWebReferences(WebReferenceCollection webReferences, CodeDomProvider codeProvider, System.CodeDom.CodeCompileUnit codeCompileUnit, WebReferenceOptions options)
 {
     if (codeCompileUnit != null)
     {
         codeCompileUnit.ReferencedAssemblies.Add("System.dll");
         codeCompileUnit.ReferencedAssemblies.Add("System.Xml.dll");
         codeCompileUnit.ReferencedAssemblies.Add("System.Web.Services.dll");
         codeCompileUnit.ReferencedAssemblies.Add("System.EnterpriseServices.dll");
     }
     Hashtable namespaces = new Hashtable();
     Hashtable exportContext = new Hashtable();
     foreach (WebReference reference in webReferences)
     {
         ServiceDescriptionImporter importer = new ServiceDescriptionImporter(codeCompileUnit);
         XmlSchemas schemas = new XmlSchemas();
         ServiceDescriptionCollection descriptions = new ServiceDescriptionCollection();
         foreach (DictionaryEntry entry in reference.Documents)
         {
             AddDocument((string) entry.Key, entry.Value, schemas, descriptions, reference.ValidationWarnings);
         }
         importer.Schemas.Add(schemas);
         foreach (ServiceDescription description in descriptions)
         {
             importer.AddServiceDescription(description, reference.AppSettingUrlKey, reference.AppSettingBaseUrl);
         }
         importer.CodeGenerator = codeProvider;
         importer.ProtocolName = reference.ProtocolName;
         importer.Style = options.Style;
         importer.CodeGenerationOptions = options.CodeGenerationOptions;
         foreach (string str in options.SchemaImporterExtensions)
         {
             importer.Extensions.Add(Type.GetType(str, true));
         }
         System.Xml.Serialization.ImportContext importContext = Context(reference.ProxyCode, namespaces, options.Verbose);
         reference.Warnings = importer.Import(reference.ProxyCode, importContext, exportContext, reference.ValidationWarnings);
         if (reference.ValidationWarnings.Count != 0)
         {
             reference.Warnings |= ServiceDescriptionImportWarnings.SchemaValidation;
         }
     }
     StringCollection strings = new StringCollection();
     if (options.Verbose)
     {
         foreach (System.Xml.Serialization.ImportContext context2 in namespaces.Values)
         {
             foreach (string str2 in context2.Warnings)
             {
                 strings.Add(str2);
             }
         }
     }
     return strings;
 }
Ejemplo n.º 6
0
		[MonoTODO] // where to use Verbose and Extensions in options?
		public static StringCollection GenerateWebReferences (
			WebReferenceCollection webReferences, 
			CodeDomProvider codeGenerator, 
			CodeCompileUnit codeCompileUnit, 
			WebReferenceOptions options)
		{
			StringCollection allWarnings = new StringCollection ();
			ImportContext context = new ImportContext (new CodeIdentifiers(), true);
			
			foreach (WebReference reference in webReferences) 
			{
				ServiceDescriptionImporter importer = new ServiceDescriptionImporter ();
				if (codeGenerator != null)
					importer.CodeGenerator = codeGenerator;
				importer.CodeGenerationOptions = options.CodeGenerationOptions;
				importer.Context = context;
				importer.Style = options.Style;
				importer.ProtocolName = reference.ProtocolName;
				
				importer.AddReference (reference);
				
				reference.Warnings = importer.Import (reference.ProxyCode, codeCompileUnit);
				reference.SetValidationWarnings (context.Warnings);
				foreach (string s in context.Warnings)
					allWarnings.Add (s);

				context.Warnings.Clear ();
			}

			return allWarnings;
		}
Ejemplo n.º 7
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 were 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;
		}
Ejemplo n.º 8
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;
			}
		}
Ejemplo n.º 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;
        }
    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
    }
Ejemplo n.º 11
0
        /// <include file='doc\ServiceDescriptionImporter.uex' path='docs/doc[@for="ServiceDescriptionImporter.GenerateWebReferences1"]/*' />
        public static StringCollection GenerateWebReferences(WebReferenceCollection webReferences, CodeDomProvider codeProvider, CodeCompileUnit codeCompileUnit, WebReferenceOptions options)
        {
            if (codeCompileUnit != null)
            {
                codeCompileUnit.ReferencedAssemblies.Add("System.dll");
                codeCompileUnit.ReferencedAssemblies.Add("System.Xml.dll");
                codeCompileUnit.ReferencedAssemblies.Add("System.Web.Services.dll");
                codeCompileUnit.ReferencedAssemblies.Add("System.EnterpriseServices.dll");
            }
            Hashtable namespaces       = new Hashtable();
            Hashtable exportedMappings = new Hashtable();

            foreach (WebReference webReference in webReferences)
            {
                ServiceDescriptionImporter importer = new ServiceDescriptionImporter(codeCompileUnit);

                // separate descriptions and schemas
                XmlSchemas schemas = new XmlSchemas();
                ServiceDescriptionCollection descriptions = new ServiceDescriptionCollection();

                foreach (DictionaryEntry entry in webReference.Documents)
                {
                    AddDocument((string)entry.Key, entry.Value, schemas, descriptions, webReference.ValidationWarnings);
                }

                importer.Schemas.Add(schemas);
                foreach (ServiceDescription source in descriptions)
                {
                    importer.AddServiceDescription(source, webReference.AppSettingUrlKey, webReference.AppSettingBaseUrl);
                }
                importer.CodeGenerator         = codeProvider;
                importer.ProtocolName          = webReference.ProtocolName;
                importer.Style                 = options.Style;
                importer.CodeGenerationOptions = options.CodeGenerationOptions;
                foreach (string extensionType in options.SchemaImporterExtensions)
                {
                    importer.Extensions.Add(Type.GetType(extensionType, true /*throwOnError*/));
                }
                ImportContext context = Context(webReference.ProxyCode, namespaces, options.Verbose);

                webReference.Warnings = importer.Import(webReference.ProxyCode, context, exportedMappings, webReference.ValidationWarnings);
                if (webReference.ValidationWarnings.Count != 0)
                {
                    webReference.Warnings |= ServiceDescriptionImportWarnings.SchemaValidation;
                }
            }

            StringCollection shareWarnings = new StringCollection();

            if (options.Verbose)
            {
                foreach (ImportContext context in namespaces.Values)
                {
                    foreach (string warning in context.Warnings)
                    {
                        shareWarnings.Add(warning);
                    }
                }
            }
            return(shareWarnings);
        }
        /// <include file='doc\ServiceDescriptionImporter.uex' path='docs/doc[@for="ServiceDescriptionImporter.GenerateWebReferences1"]/*' />
        public static StringCollection GenerateWebReferences(WebReferenceCollection webReferences, CodeDomProvider codeProvider, CodeCompileUnit codeCompileUnit, WebReferenceOptions options) {
            if (codeCompileUnit != null) {
                codeCompileUnit.ReferencedAssemblies.Add("System.dll");
                codeCompileUnit.ReferencedAssemblies.Add("System.Xml.dll");
                codeCompileUnit.ReferencedAssemblies.Add("System.Web.Services.dll");
                codeCompileUnit.ReferencedAssemblies.Add("System.EnterpriseServices.dll");
            }
            Hashtable namespaces = new Hashtable();
            Hashtable exportedMappings = new Hashtable();
            foreach (WebReference webReference in webReferences) {
                ServiceDescriptionImporter importer = new ServiceDescriptionImporter(codeCompileUnit);

                // separate descriptions and schemas
                XmlSchemas schemas = new XmlSchemas();
                ServiceDescriptionCollection descriptions = new ServiceDescriptionCollection();

                foreach (DictionaryEntry entry in webReference.Documents) {
                    AddDocument((string)entry.Key, entry.Value, schemas, descriptions, webReference.ValidationWarnings);
                }

                importer.Schemas.Add(schemas);
                foreach (ServiceDescription source in descriptions)
                    importer.AddServiceDescription(source, webReference.AppSettingUrlKey, webReference.AppSettingBaseUrl);
                importer.CodeGenerator = codeProvider;
                importer.ProtocolName = webReference.ProtocolName;
                importer.Style = options.Style;
                importer.CodeGenerationOptions = options.CodeGenerationOptions;
                foreach (string extensionType in options.SchemaImporterExtensions) {
                    importer.Extensions.Add(Type.GetType(extensionType, true /*throwOnError*/));
                }
                ImportContext context = Context(webReference.ProxyCode, namespaces, options.Verbose);

                webReference.Warnings = importer.Import(webReference.ProxyCode, context, exportedMappings, webReference.ValidationWarnings);
                if (webReference.ValidationWarnings.Count != 0) {
                    webReference.Warnings |= ServiceDescriptionImportWarnings.SchemaValidation;
                }
            }

            StringCollection shareWarnings = new StringCollection();

            if (options.Verbose) {
                foreach (ImportContext context in namespaces.Values) {
                    foreach (string warning in context.Warnings) {
                        shareWarnings.Add(warning);
                    }
                }
            }
            return shareWarnings;
        }
Ejemplo n.º 13
0
        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;
        }
		public static StringCollection GenerateWebReferences (
			WebReferenceCollection webReferences, 
			CodeGenerationOptions options, 
			ServiceDescriptionImportStyle style, 
			ICodeGenerator codeGenerator)
		{
			CodeCompileUnit codeCompileUnit = new CodeCompileUnit ();
			return GenerateWebReferences (webReferences, options, style, codeGenerator, codeCompileUnit, false);
		}
Ejemplo n.º 15
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;
			}
		}
 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);
     }
 }