Remoting from IIS Hosted component to ASP.NET Client application

Introduction

This walkthrough will show how to set up a simple component on IIS and access it through an ASP.NET webapp. Please refer to other articles to get background information on remoting. The goal of this project is to:

  1. Make a remote service hosted on IIS that authenticates users
  2. Make wrapper classes to abstract the remoting "fabric" to the client
  3. Set up an ASP.NET web application to consume the remote service through the wrapper assembly

No demo project is provided here because you'll have to do some setup with IIS an so forth yourselves. I didn't get this subject myself before I actually struggled with it on my own. So the intent here is to guide you through the process.

Background

There are a lot of literature on .NET remoting out there. Ingo Rammer's book "Advanced .NET Remoting" is told to be great and his website (www.dotnetremoting.cc) for sure are. Other sources for this subject can be somewhat complex from time-to-time because they often are written by experienced COM/DCOM programmers. For me it seemed as they made it more difficult than it is. This is why I made this simple straight-forward walkthrough to get remoting up and running in a known environment for ASP.NET programmers. Here is my blog from yesterday with some more background.

First off: Define your service

Before you start coding, decide what your service is supposed to do, because you're going to make an interface. The interface will be built in a separate assembly (DLL) and deployed with both client and server application, so they have a common ground. My service, in this case, is supposed to authenticate users so I'll define my interface like this:

Collapse code snippet
public interface IAuthenticationService
{
string Authenticate(string username, string password);
}

The interface takes username/password as parameters and returns an encrypted FormsAuthenticationTicket (as String) that the ASP.NET application will use for creating a cookie for the authenticated user.

Secondly: The server application

To be able to run a class as a .NET remoting service you have to make a class that inherits MarshalByRefOBject. We also want the class to implement the IAuthenticationService interface defined above, so the client can use it.

Collapse
public class AuthenticationService : MarshalByRefObject, 
IAuthenticationService
{
private IUserDAO UserDAO;

public AuthenticationService()
{
// Get an instance of our User Data Access Object

UserDAO = (IUserDAO)ServiceLocator.Instance.
DataAccessObjectGet(StorageTypes.SqlServer,
Services.UserService);
}


public string Authenticate(string username, string password)
{
UserItem user;
try
{
// Get the user from the datastore and validate password

user = UserDAO.UserByEmailGet(username);
if(!(user.Password.CompareTo(password) == 0))
return "";
}
catch(eFactory.Data.NoDataFoundException)
{
// User Not found

return "";
}

// Create Userdata - omitted for clarity

return encryptedTicket;
}
}

Piece of cake. Inherit MarshalByRefObject (from System.Runtime.Remoting) and implement the interface we made earlier. In this example I use a singleton ServiceLocator class to delver an instance of a data access object for the data-service, UserService. Then this service (UserDAO) is used to fetch the user object that contains the password.

Now we can compile our server component and deploy our service to IIS. If you have IIS installed the simplest thing to do is:

  1. Create a new virtual folder on IIS (through inetmgr.exe) that points to the directory containing our server project. Beware that the name you provide for the folder also will be the application name in IIS.

    You might experience some trouble with setting up the virtual folder on IIS. One hint is that all parent directories of the one you assign as a virtual IIS folder must allow the ASPNET user to read, execute and list. Otherwise consult MSDN for advice on setting up virtual folders.

  2. Make sure that the DLL is placed directly under the /bin folder (not in /bin/debug!)
  3. Create a Web.Config file in the root of the virtual folder (our project folder). This Web.config file needs to hold the remoting settings (deployment description). Additionally you'd probably want to include some database connection strings and so forth if you are doing lookups in your authenticate method. The server web.config looks like this:
    Collapse
    <configuration>
    <system.runtime.remoting>
    <application>
    <service>
    <wellknown
    mode="SingleCall"
    type="CodeProject.AuthenticationService,
    AuthenticationServiceComponent"

    objectUri="AuthenticationService.soap" />
    </service>
    <channels>
    <channel
    name="TheChannel"
    priority="100"
    ref="http" />
    </channels>
    </application>
    </system.runtime.remoting>
    <appSettings>
    <add key="SqlServer" value="connstring"/>
    </appSettings>
    </configuration>

The remoting part of the config file is contained by the <system.runtime.remoting> tags. The application element inside is set up automatically by ASP.NET and IIS so we don't have to specify any attributes (specifying the name attribute would conflict because the name of our application is already set to be the same as the name of the virtual directory).

Then we specify our services. ASP.NET only supports well-known services (not client-activated) so we don't have to think much about that. The really important thing here is the type attribute. The first parameter here is the fully qualified class name of our service. My AuthenticationService class was compiled in the namespace CodeProject as you can see. The second parameter in the type attribute is the name of the DLL file. This file resides in the /bin directory of the IIS virtual folder and contains the class CodeProject.AuthenticationService. The third attribute is objectUri and defines a URI for our service. Just set it to [classname.soap] for now.

What's left here is to define a channel for IIS to use for this service. We'll give it a name, TheChannel, set a priority flag and make a reference to the pre-defined "HTTP" channel in machine.config.

Finally I had to add my database connection string:)

Now you should be able to check out your service by entering it's URL and get the WSDL. like this:

http://hostname/VirtualFolderName/objectUri?wsdl in my case: http://localhost/AuthenticationRemotingService/AuthenticationService.soap?wsdl.

Really cool isn't it?

Next lets make the client! Or not yet?

I found it convenient to wrap all remoting code in a supporting assembly to catch remoting errors and such. Because others (other coders) that are going to use this service have to import my Interface assembly anyways, it won't hurt to supply some wrappers.

I chose to make a singleton class to front my service. The only thing it does is to get the remote object and call on the authenticate service and return it's value as a HttpCookie. If something goes wrong it catches the exception. It also hides some semi-nasty implementation code to be able to instantiate an object of our interface type without having to hardcode the URL. I did a slight rewrite of Ingo Rammers RemotingHelper class, converting it to a singleton to accomplish this.

This is the LoginHandler wrapper class:

Collapse
public sealed class LoginHandler
{
public static readonly LoginHandler Instance = new LoginHandler();

private LoginHandler(){}

public HttpCookie DoLogin(string username, string password)
{
try
{
IAuthenticationService auth =
(IAuthenticationService)RemotingHelper.Instance.GetObject
(typeof(IAuthenticationService));
}
catch(System.Runtime.Remoting.RemotingException ex)
{
//do some logging

return "";
}

string ticket = auth.Authenticate(username, password);
if(ticket == "")
return null;
else
return new System.Web.HttpCookie(FormsAuthentication.
FormsCookieName, ticket);

}
}

The rewrite of Ingo Rammer's class:

Collapse
internal sealed class RemotingHelper 
{
public static readonly RemotingHelper Instance =
new RemotingHelper();

private IDictionary wellKnownTypes;

private RemotingHelper()
{
wellKnownTypes = new Hashtable();
foreach (WellKnownClientTypeEntry entr in
RemotingConfiguration.GetRegisteredWellKnownClientTypes())
{
if (entr.ObjectType == null)
{
throw new RemotingException("A configured
type could not be found. Please check spelling"
);
}
wellKnownTypes.Add (entr.ObjectType,entr);
}
}

public Object GetObject(Type type)
{
WellKnownClientTypeEntry entr =
(WellKnownClientTypeEntry)wellKnownTypes[type];
if(entr == null)
{
throw new RemotingException("Type not found!");
}
return Activator.GetObject(entr.ObjectType,entr.ObjectUrl);
}
}

When instantiated this class reads all available well-known types from the registered types collection in the RemotingConfiguration. It then compares the class name you provide in GetObject to the well-known types. Without this class, you'd have to hardcode the service server URL or get this from the config file.

Off to the ASP.NET client webapp!

Now its playtime. All the hard work is nearly done. Finish off by:

  1. Create a new ASP.NET web application.
  2. Add references to the Wrapper-, and Interface assemblies.
  3. Open the client application web.config file.

    You will need to let your client application know where to find the implementation of the interface defined in the assembly you just added. It's the implementation of this interface we will "remote". Just like for the server config file you have to place a system.runtime.remoting element as a sub-element to <configuration> Its done like this:

    Collapse
    <system.runtime.remoting>
    <application>
    <client url="http:/localhost/YourIISVirtualFolderName
    /AuthenticationService"
    >
    <wellknown
    type="CodeProject.IAuthenticationService,
    RemotingInterfacesComponent"

    url="http://localhost/YourIISVirtualFolderName/
    AuthenticationService.soap"
    />
    </client>
    </application>
    </system.runtime.remoting>

    The URL of the client element is the address of your virtual folder on IIS that you defined for your server component. Then we define a well-known type which is describing the fully qualified name for the interface we made first off in this walkthrough, and the second parameter is (like in the server config) the name of the DLL containing this interface. This DLL must of course be available and referenced by our ASP.NET client web app. The last parameter is the URL to the service + the objectUri that we defined in the server web.config file. We don't need to set up any channels here. IIS will handle it.

  4. Finally to make your client actually set up the remoting you have to kick start it when the application starts up. Open the global.asax and enter this line in the Application_Start event handler.
    Collapse
    protected void Application_Start(Object sender, EventArgs e)
    {
    RemotingConfiguration.Configure(Server.MapPath("Web.config"));//这里可以不注册web.config?
    }

    This will read the remoting section in the web.config and set it all in place (or generate a kick-ass remotingexception when you start up your webapp:)

Now go ahead and call the wrapper class LoginHandler from your web-client and enjoy the HttpCookie from the service:) Good luck!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Mads Nissen


http://weblogs.asp.net/mnissen
http://www.puzzlepart.com
Occupation: Software Developer (Senior)
Location: Norway Norway
深度学习是机器学习的一个子领域,它基于人工神经网络的研究,特别是利用多层次的神经网络来进行学习和模式识别。深度学习模型能够学习数据的高层次特征,这些特征对于图像和语音识别、自然语言处理、医学图像分析等应用至关重要。以下是深度学习的一些关键概念和组成部分: 1. **神经网络(Neural Networks)**:深度学习的基础是人工神经网络,它是由多个层组成的网络结构,包括输入层、隐藏层和输出层。每个层由多个神经元组成,神经元之间通过权重连接。 2. **前馈神经网络(Feedforward Neural Networks)**:这是最常见的神经网络类型,信息从输入层流向隐藏层,最终到达输出层。 3. **卷积神经网络(Convolutional Neural Networks, CNNs)**:这种网络特别适合处理具有网格结构的数据,如图像。它们使用卷积层来提取图像的特征。 4. **循环神经网络(Recurrent Neural Networks, RNNs)**:这种网络能够处理序列数据,如时间序列或自然语言,因为它们具有记忆功能,能够捕捉数据中的时间依赖性。 5. **长短期记忆网络(Long Short-Term Memory, LSTM)**:LSTM 是一种特殊的 RNN,它能够学习长期依赖关系,非常适合复杂的序列预测任务。 6. **生成对抗网络(Generative Adversarial Networks, GANs)**:由两个网络组成,一个生成器和一个判别器,它们相互竞争,生成器生成数据,判别器评估数据的真实性。 7. **深度学习框架**:如 TensorFlow、Keras、PyTorch 等,这些框架提供了构建、训练和部署深度学习模型的工具和库。 8. **激活函数(Activation Functions)**:如 ReLU、Sigmoid、Tanh 等,它们在神经网络中用于添加非线性,使得网络能够学习复杂的函数。 9. **损失函数(Loss Functions)**:用于评估模型的预测与真实值之间的差异,常见的损失函数包括均方误差(MSE)、交叉熵(Cross-Entropy)等。 10. **优化算法(Optimization Algorithms)**:如梯度下降(Gradient Descent)、随机梯度下降(SGD)、Adam 等,用于更新网络权重,以最小化损失函数。 11. **正则化(Regularization)**:技术如 Dropout、L1/L2 正则化等,用于防止模型过拟合。 12. **迁移学习(Transfer Learning)**:利用在一个任务上训练好的模型来提高另一个相关任务的性能。 深度学习在许多领域都取得了显著的成就,但它也面临着一些挑战,如对大量数据的依赖、模型的解释性差、计算资源消耗大等。研究人员正在不断探索新的方法来解决这些问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值