UrlAttribute Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Определяет атрибут, который можно использовать на сайте вызова, чтобы указать URL-адрес, в котором будет происходить активация. Этот класс не наследуется.
public ref class UrlAttribute sealed : System::Runtime::Remoting::Contexts::ContextAttribute
[System.Serializable]
public sealed class UrlAttribute : System.Runtime.Remoting.Contexts.ContextAttribute
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class UrlAttribute : System.Runtime.Remoting.Contexts.ContextAttribute
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
[System.Security.SecurityCritical]
public sealed class UrlAttribute : System.Runtime.Remoting.Contexts.ContextAttribute
[<System.Serializable>]
type UrlAttribute = class
inherit ContextAttribute
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type UrlAttribute = class
inherit ContextAttribute
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
[<System.Security.SecurityCritical>]
type UrlAttribute = class
inherit ContextAttribute
Public NotInheritable Class UrlAttribute
Inherits ContextAttribute
- Наследование
- Атрибуты
Примеры
В следующем примере кода показано использование удаленного UrlAttribute взаимодействия, активированного клиентом. Пример содержит три части: клиент, сервер и удаленный объект, используемый клиентом и сервером.
В следующем примере кода показан клиент:
#using <System.Runtime.Remoting.dll>
#using <System.dll>
#using "RemoteObject.dll"
using namespace System;
using namespace System::Runtime::Remoting;
using namespace System::Runtime::Remoting::Activation;
using namespace System::Runtime::Remoting::Channels;
using namespace System::Runtime::Remoting::Channels::Tcp;
[STAThread]
int main()
{
// Report initial status.
Console::WriteLine( "Client starting." );
// Register TCP channel.
ChannelServices::RegisterChannel( gcnew TcpChannel );
// Create UrlAttribute.
UrlAttribute^ attribute = gcnew UrlAttribute( "tcp://localhost:1234/RemoteApp" );
Console::WriteLine( "UrlAttribute value: {0}", attribute->UrlValue );
array<Object^>^activationAttributes = {attribute};
// Use UrlAttribute to register for client activated remote object.
RemotingConfiguration::RegisterActivatedClientType( RemoteObject::typeid, "tcp://localhost:1234/RemoteApp" );
// Activate remote object.
Console::WriteLine( "Activating remote object." );
RemoteObject ^ obj = dynamic_cast<RemoteObject^>(Activator::CreateInstance( RemoteObject::typeid, nullptr, activationAttributes ));
// Invoke a method on it.
Console::WriteLine( "Invoking Hello() on remote object." );
obj->Hello();
// Inform user of termination.
Console::WriteLine( "Terminating client." );
}
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Activation;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
public class Client
{
[STAThread]
public static void Main()
{
// Report the initial status.
Console.WriteLine("Starting client.");
// Register the TCP channel.
ChannelServices.RegisterChannel(new TcpChannel());
// Create a url attribute object.
UrlAttribute attribute =
new UrlAttribute("tcp://localhost:1234/RemoteApp");
Console.WriteLine("UrlAttribute value: {0}", attribute.UrlValue);
object[] activationAttributes = new object[] { attribute };
// Register the client for the remote object.
RemotingConfiguration.RegisterActivatedClientType(
typeof(RemoteObject),
"tcp://localhost:1234/RemoteApp");
// Activate the remote object.
Console.WriteLine("Activating remote object.");
RemoteObject obj = (RemoteObject) Activator.CreateInstance(
typeof(RemoteObject), null, activationAttributes);
// Invoke a method on the remote object.
Console.WriteLine("Invoking Hello() on remote object.");
obj.Hello();
// Inform the user that the program is exiting.
Console.WriteLine("The client is exiting.");
}
}
В следующем примере кода показан сервер для этого клиента:
#using <System.Runtime.Remoting.dll>
#using <System.dll>
#using "RemoteObject.dll"
using namespace System;
using namespace System::Runtime::Remoting;
using namespace System::Runtime::Remoting::Channels;
using namespace System::Runtime::Remoting::Channels::Tcp;
[STAThread]
int main()
{
// Report status to user.
Console::WriteLine( "Server starting." );
// Register the TCP channel.
ChannelServices::RegisterChannel( gcnew TcpChannel( 1234 ) );
// Set application name.
RemotingConfiguration::ApplicationName = "RemoteApp";
// Register object for client activated remoting.
RemotingConfiguration::RegisterActivatedServiceType( RemoteObject::typeid );
// Wait until termination.
Console::WriteLine( "Press enter to end." );
Console::ReadLine();
Console::WriteLine( "Terminating server." );
}
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
public class Server
{
[STAThread]
public static void Main()
{
// Report the status to the user.
Console.WriteLine("Starting server.");
// Register the TCP channel.
ChannelServices.RegisterChannel(new TcpChannel(1234));
// Set the application name.
RemotingConfiguration.ApplicationName = "RemoteApp";
// Register the object for remoting.
RemotingConfiguration.RegisterActivatedServiceType(
typeof(RemoteObject));
// Wait until the user presses ENTER.
Console.WriteLine("Press ENTER to exit.");
Console.ReadLine();
Console.WriteLine("The server is exiting.");
}
}
В следующем примере кода показан удаленный объект, используемый клиентом и сервером:
using namespace System;
using namespace System::Security;
using namespace System::Security::Permissions;
[assembly:AllowPartiallyTrustedCallersAttribute];
public ref class RemoteObject: public MarshalByRefObject
{
public:
RemoteObject()
{
// Report object construction to server's console.
Console::WriteLine( "You have called the constructor." );
}
void Hello()
{
// Report method invocation to server's console.
Console::WriteLine( "You have called Hello()." );
}
};
using System;
using System.Security;
using System.Security.Permissions;
public class RemoteObject : MarshalByRefObject
{
public RemoteObject()
{
Console.WriteLine("You have called the constructor.");
}
public void Hello()
{
Console.WriteLine("You have called Hello().");
}
}
Комментарии
Передается UrlAttribute в массив атрибутов активации в качестве параметра Activator.CreateInstance при создании активированных объектов с CreateInstance помощью метода.
Дополнительные сведения об использовании атрибутов см. в разделе "Атрибуты".
Конструкторы
| Имя | Описание |
|---|---|
| UrlAttribute(String) |
Создает новый экземпляр класса UrlAttribute. |
Поля
| Имя | Описание |
|---|---|
| AttributeName |
Этот API поддерживает инфраструктуру продукта и не предназначен для использования непосредственно из программного кода. Указывает имя атрибута контекста. (Унаследовано от ContextAttribute) |
Свойства
| Имя | Описание |
|---|---|
| Name |
Этот API поддерживает инфраструктуру продукта и не предназначен для использования непосредственно из программного кода. Возвращает имя атрибута контекста. (Унаследовано от ContextAttribute) |
| TypeId |
При реализации в производном классе получает уникальный идентификатор для этого Attribute. (Унаследовано от Attribute) |
| UrlValue |
Возвращает значение URL-адреса объекта UrlAttribute. |
Методы
| Имя | Описание |
|---|---|
| Equals(Object) |
Проверяет, ссылается ли указанный объект на тот же URL-адрес, что и текущий экземпляр. |
| Freeze(Context) |
Этот API поддерживает инфраструктуру продукта и не предназначен для использования непосредственно из программного кода. Вызывается при замороженном контексте. (Унаследовано от ContextAttribute) |
| GetHashCode() |
Возвращает хэш-значение для текущего UrlAttribute. |
| GetPropertiesForNewContext(IConstructionCallMessage) |
Принудительно создает контекст и объект сервера внутри контекста по указанному URL-адресу. |
| GetType() |
Возвращает Type текущего экземпляра. (Унаследовано от Object) |
| IsContextOK(Context, IConstructionCallMessage) |
Возвращает логическое значение, указывающее, соответствует Contextли указанный UrlAttribute параметр требованиям. |
| IsDefaultAttribute() |
При переопределении в производном классе указывает, является ли значение этого экземпляра значением по умолчанию для производного класса. (Унаследовано от Attribute) |
| IsNewContextOK(Context) |
Этот API поддерживает инфраструктуру продукта и не предназначен для использования непосредственно из программного кода. Возвращает логическое значение, указывающее, совместимо ли свойство контекста с новым контекстом. (Унаследовано от ContextAttribute) |
| Match(Object) |
При переопределении в производном классе возвращает значение, указывающее, равен ли этот экземпляр указанному объекту. (Унаследовано от Attribute) |
| MemberwiseClone() |
Создает неглубокую копию текущей Object. (Унаследовано от Object) |
| ToString() |
Возвращает строку, представляющую текущий объект. (Унаследовано от Object) |
Явные реализации интерфейса
| Имя | Описание |
|---|---|
| _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Сопоставляет набор имен соответствующему набору идентификаторов диспетчеризации. (Унаследовано от Attribute) |
| _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Извлекает сведения о типе объекта, который можно использовать для получения сведений о типе для интерфейса. (Унаследовано от Attribute) |
| _Attribute.GetTypeInfoCount(UInt32) |
Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1). (Унаследовано от Attribute) |
| _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Предоставляет доступ к свойствам и методам, предоставляемым объектом. (Унаследовано от Attribute) |