Remoting from IIS Hosted component to ASP.NET Client application

本文介绍如何在IIS上配置一个简单的组件,并通过ASP.NET Web应用程序访问该组件。主要内容包括创建远程服务、设置客户端包装类以及配置Web应用程序来消费远程服务。

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
内容概要:本文围绕“考虑隐私保护的分布式联邦学习电力负荷预测研究”展开,提出了一种融合联邦学习框架与隐私保护机制的电力负荷预测方法,旨在解决传统集中式数据处理中潜在的用户隐私泄露问题。通过构建分布式模型训练体系,各参与方在本地完成模型训练,仅向中心服务器上传模型参数或梯度信息,实现“数据不动模型动”的协同建模模式,确保数据“可用不可见”。研究采用Python语言实现了完整的联邦学习流程,涵盖客户端本地训练、全局模型聚合、隐私保护策略(如差分隐私或同态加密)集成、通信机制设计及预测性能评估等核心模块,显著提升了电力负荷预测在隐私安全与模型精度之间的平衡能力。; 适合人群:具备Python编程基础和机器学习基础知识,从事电力系统、智能电网、能源大数据分析、数据隐私保护等相关领域研究的研究生、科研人员及工程技术人员。; 使用场景及目标:①应用于居民或工业级电力负荷预测任务,在保障用户用电数据隐私的前提下实现高精度预测;②为构建符合数据合规要求的智慧能源管理系统提供技术支撑;③推动联邦学习在能源互联网、跨企业数据协作等场景中的落地应用,促进多方协同建模与数据价值释放。; 阅读建议:建议读者结合文中提供的Python代码进行实践操作,重点关注联邦学习的通信轮次设置、本地训练迭代策略、模型聚合算法设计以及隐私噪声添加机制的实现细节,并可根据实际需求替换底层预测模型(如LSTM、XGBoost、Transformer等)以进一步优化预测性能。
内容概要:本文介绍了一种基于噪声抑制半监督学习的锂离子电池SOH(State of Health,健康状态)估计方法的Python代码实现,旨在通过结合半监督学习框架与噪声抑制技术,提升电池健康状态预测的准确性与鲁棒性。该方法充分利用少量有标签样本和大量无标签数据进行模型训练,有效缓解了实际应用中电池老化数据标注成本高、获取困难的问题。文中详细阐述了模型的整体架构设计、关键特征提取策略、噪声处理机制以及半监督学习中的损失函数构建,并提供了完整的可复现代码,便于研究人员理解和二次开发。; 适合人群:具备一定机器学习理论基础和Python编程能力,从事电池管理系统(BMS)、新能源汽车、储能系统等领域的科研人员或工程师,尤其适用于关注电池寿命预测、状态估计及数据驱动建模的研究生与青年学者。; 使用场景及目标:①实现锂离子电池健康状态的高精度估计,服务于电池管理系统的优化与安全预警;②为工业场景下标注数据稀缺的退化建模问题提供一种高效的半监督解决方案;③推动复杂噪声环境下电池性能退化预测的研究进展,增强模型在真实工况中的泛化能力和稳定性; 阅读建议:建议读者结合所提供的Python代码逐模块深入学习,重点理解数据预处理流程、噪声抑制模块的设计原理以及半监督损失函数的实现细节,同时可在不同公开电池数据集上进行迁移实验与对比分析,以全面掌握该方法的有效性与适用边界。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值