ServiceDescriptionImporter Класс

Определение

Предоставляет средства создания клиентских прокси-классов для веб-служб XML.

public ref class ServiceDescriptionImporter
public class ServiceDescriptionImporter
type ServiceDescriptionImporter = class
Public Class ServiceDescriptionImporter
Наследование
ServiceDescriptionImporter

Примеры

В следующем примере показано использование ServiceDescriptionImporter класса для создания кода прокси-клиента, вызывающего веб-службу XML, описанную WSDL-файлом.

#using <System.Xml.dll>
#using <System.Web.Services.dll>
#using <System.dll>

using namespace System;
using namespace System::Web::Services::Description;
using namespace System::CodeDom;
using namespace System::CodeDom::Compiler;

int main()
{
   // Get a WSDL file describing a service.
   ServiceDescription^ description = ServiceDescription::Read( "service.wsdl" );

   // Initialize a service description importer.
   ServiceDescriptionImporter^ importer = gcnew ServiceDescriptionImporter;
   importer->ProtocolName = "Soap12"; // Use SOAP 1.2.
   importer->AddServiceDescription( description, nullptr, nullptr );

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

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

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

   // Initialize a Code-DOM tree into which we will import the service.
   CodeNamespace^ nmspace = gcnew CodeNamespace;
   CodeCompileUnit^ unit = gcnew CodeCompileUnit;
   unit->Namespaces->Add( nmspace );
   
   // Import the service into the Code-DOM tree. This creates proxy code
   // that uses the service.
   ServiceDescriptionImportWarnings warning = importer->Import(nmspace,unit);
   if ( warning == (ServiceDescriptionImportWarnings)0 )
   {
      // Generate and print the proxy code in C#.
      CodeDomProvider^ provider = CodeDomProvider::CreateProvider( "CSharp" );
      ICodeGenerator^ generator = provider->CreateGenerator();
      generator->GenerateCodeFromCompileUnit( unit, Console::Out, gcnew CodeGeneratorOptions );
   }
   else
   {
      // Print an error message.
      Console::WriteLine( warning );
   }
}
using System;
using System.Web.Services.Description;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Security.Permissions;

public class Import {

    public static void Main() 
    {
        Run();
    }

    [PermissionSetAttribute(SecurityAction.Demand, Name = "Full Trust")]
    public static void Run()
    {
    // Get a WSDL file describing a service.
    ServiceDescription description = ServiceDescription.Read("service.wsdl");

    // Initialize a service description importer.
    ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
    importer.ProtocolName = "Soap12";  // Use SOAP 1.2.
    importer.AddServiceDescription(description,null,null);

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

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

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

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

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

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

Комментарии

Интерфейс веб-службы XML обычно описывается файлом языка описания веб-служб (WSDL). Например, чтобы получить описание веб-службы WSDL с помощью ASP.NET, предоставляемых в http://localhost/service.asmx, просто перейдите к http://localhost/service.asmx?WSDL.

Класс ServiceDescriptionImporter позволяет легко импортировать сведения, содержащиеся в описании WSDL, в System.CodeDom.CodeCompileUnit объект. Изменив значение Style параметра, можно указать ServiceDescriptionImporter экземпляру создать класс прокси клиента, который предоставляет функциональные возможности веб-службы, прозрачно вызывая его или создавая абстрактный класс, инкапсулирующий функциональные возможности веб-службы, не реализуя его.

Затем код в результирующем CodeCompileUnit объекте можно вызвать напрямую или экспортировать на выбранный вами язык.

Important

Не используйте ServiceDescriptionImporter ненадежные входные данные. Импорт ServiceDescription из ненадежных источников может привести к получению кода, которое обращается к произвольным URL-адресам или создает экземпляры произвольных .NET типов, что может привести к уязвимостям системы безопасности.

Конструкторы

Имя Описание
ServiceDescriptionImporter()

Инициализирует новый экземпляр класса ServiceDescriptionImporter.

Свойства

Имя Описание
CodeGenerationOptions

Возвращает или задает различные параметры для создания кода.

CodeGenerator

Возвращает или задает генератор кода, используемый импортом описания службы.

ProtocolName

Возвращает или задает протокол, используемый для доступа к описанным веб-службам XML.

Schemas

Возвращает используемый XmlSchemas свойством ServiceDescriptions .

ServiceDescriptions

Возвращает коллекцию экземпляров, ServiceDescription импортируемых.

Style

Возвращает или задает значение, определяющее стиль кода (клиента или сервера), создаваемого при ServiceDescriptions импорте значений.

Методы

Имя Описание
AddServiceDescription(ServiceDescription, String, String)

Добавляет указанный ServiceDescription в коллекцию значений, импортируемых ServiceDescriptions .

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GenerateWebReferences(WebReferenceCollection, CodeDomProvider, CodeCompileUnit, WebReferenceOptions)

Компилирует коллекцию веб-ссылок для создания прокси-сервера или заглушки сервера.

GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает Type текущего экземпляра.

(Унаследовано от Object)
Import(CodeNamespace, CodeCompileUnit)

Импортирует указанные ServiceDescriptions значения, которые создают код, указанный свойством Style .

MemberwiseClone()

Создает неглубокую копию текущей Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Применяется к