Microsoft .NET Remoting权威指南中例子错误的解决(不允许类型 System.DelegateSerializationHolder 和从中派生的类型(例如 System.DelegateSerializationHolder)在此安全

Microsoft.NET Remoting权威指南 .net remoting 经典书籍 英文版(PDF)<br> 立即下载

FIX: Remoted Events (Chat) Sample in Framework Documentation Does Not Work as Expected

Article ID:312114
Last Review:March 25, 2003
Revision:2.0
This article was previously published under Q312114
This article refers to the following Microsoft .NET Framework Class Library namespaces:
•System.Runtime.Remoting
•System.Runtime.R

SYMPTOMS

The "Remoting Example: Delegates and Events" sample provided in the .NET Framework SDK documentation does not work as expected. The sample is a chat application that demonstrates the use of remoted delegates and events. Client applications submit callback functions through a delegate to a Remoting server object event. The server object then calls the event, which results in callbacks to the clients.

The sample works as written only if the client, remotable object, and remoting host assemblies reside in the same directory. If the client application and server application are in different directories or on different computers (which is the typical case), the client's attempt to submit a delegate to the server object fails with a FileNotFoundException error.

CAUSE

This behavior occurs because delegates require that the receiving object be able to obtain the type information for the class whose function is being wrapped by the delegate. In the case of the sample, this requires that the client assembly be available to the server. If the client assembly is not available to the server, that type information cannot be loaded.

To make remoted delegates work, an abstract class (MustInherit in Visual Basic .NET, abstract in C#) that contains the callback function must be defined in a common assembly that both client and server have access to. The client can then derive a custom class from this abstract class to implement the logic in the callback. The abstract class needs to have a specific structure. The function to be used for callbacks must be a public function that cannot be overriden. This function must forward all calls to a protected abstract function that is overridden in the derived client classes. The reason for this architecture is that the delegate needs to be able to bind to a concrete implementation of the callback function, and this implementation must not be overridable.

RESOLUTION

The following is the corrected sample code for ChatCoordinator.cs. The common abstract class is RemotelyDelegatableObject. Note that the client application will need to define a class that derives from RemotelyDelegatableObject and implements its callback logic there.
// ChatCoordinator.cs
using System;
using System.Runtime.Remoting;
using System.Collections;

// Define the class that contains the information for a Submission event.
[Serializable]
public class SubmitEventArgs : EventArgs
{

	private string _string = null;
	private string _alias = null;

	public SubmitEventArgs(string contribution, string contributor)
	{
		this._string = contribution;
		this._alias = contributor;
	}

	public string Contribution
	{
		get
		{
			return _string;
		}
	}

	public string Contributor
	{
		get
		{
			return _alias;
		}
	}
}

// The delegate declares the structure of the method that the event will call when it occurs.
// Clients implement a method with this structure, create a delegate that wraps it, and then
// pass that delegate to the event. The runtime implements events as a pair of methods,
// add_Submission and remove_Submission, and both take an instance of this type of delegate
// (which really means a reference to the method on the client that the event will call).
public delegate void SubmissionEventHandler(object sender, SubmitEventArgs submitArgs);

// Define the service.
public class ChatCoordinator : MarshalByRefObject
{

	public ChatCoordinator()
	{

		Console.WriteLine("ChatCoordinator created. Instance: " + this.GetHashCode().ToString());

	}

	// This is to insure that when created as a Singleton, the first instance never dies,
	// regardless of the time between chat users.
	public override object InitializeLifetimeService()
	{
		return null;
	}

	// The client will subscribe and unsubscribe to this event.
	public event SubmissionEventHandler Submission;

	// Method called remotely by any client. This simple chat server merely forwards
	// all messages to any clients that are listening to the Submission event, including
	// whoever made the contribution.
	public void Submit(string contribution, string contributor)
	{
		Console.WriteLine("{0} sent: {1}.", contributor, contribution);

		// Package String in SubmitEventArgs, which will be sent as an argument
		// to all event "sinks", or listeners.
		SubmitEventArgs e = new SubmitEventArgs(contribution, contributor);

		if (Submission != null)
		{
			Console.WriteLine("Broadcasting...");
			// Raise Event. This calls the remote listening method on all clients of this object.
			Submission(this, e);
		}
	}
}

// Class to be used by clients to submit delegates to the ChatCoordinator object.
// Clients must derive a custom class from this and override the InternalSubmissionCallback
// function.  InternalSubmissionCallback is where they need to implement their callback
// logic.  They must use the SubmissionCallback function in their remotable delegates.
public abstract class RemotelyDelegatableObject : MarshalByRefObject
{
	public void SubmissionCallback (object sender, SubmitEventArgs submitArgs)
	{
		InternalSubmissionCallback (sender, submitArgs) ;
	}

	protected abstract void InternalSubmissionCallback (object sender, SubmitEventArgs submitArgs) ;
}
				
Note that the ChatCentral.cs file has not changed:
// ChatCentral.cs
using System;
using System.Runtime.Remoting;

public class ServerProcess
{

	// This simply keeps the ChatCoordinator application domain alive.
	public static void Main(string[] Args)
	{
		RemotingConfiguration.Configure("ChatCentral.exe.config");

		Console.WriteLine("The host application domain is running. Press Enter again to stop the application domain.");
		Console.ReadLine();
		}
	}
}
				
The ChatClient.cs file must be rewritten to look like the following. Note that MyCallbackClass now contains the callback function. It is derived from RemotelyDelegatableObject.
// ChatClient.cs
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;

public class ChatClient
{

	private string _alias = null;

	public ChatClient(string alias)
	{
		this._alias = alias;
	}

	public void Run()
	{
			RemotingConfiguration.Configure("ChatClient.exe.config");

		// Create a proxy to the remote object.
		ChatCoordinator chatcenter = new ChatCoordinator();

		// Create a remotely delegatable object
		MyCallbackClass callback = new MyCallbackClass (_alias) ;

		// Create a new delegate for the method that you want the event to call
		// when it occurs on the server. The SubmissionReceiver method will
		// then be a remote call for the server object; therefore, you must
		// register a channel to listen for this call back from the server.
		chatcenter.Submission += new SubmissionEventHandler(callback.SubmissionCallback);
		String keyState = "";

		while (true)
		{
			Console.WriteLine("Press 0 (zero) and ENTER to Exit:/r/n");
			keyState = Console.ReadLine();

			if (String.Compare(keyState,"0", true) == 0)
				break;
			// Call the server with the string you submitted and your alias.
			chatcenter.Submit(keyState, _alias);
		}
		chatcenter.Submission -= new SubmissionEventHandler(callback.SubmissionCallback);
	}


	// Args[0] is the alias that will be used.
	public static void Main(string[] Args)
	{

		if (Args.Length != 1)
		{
			Console.WriteLine("You need to type an alias.");
			return;
		}

		ChatClient client = new ChatClient(Args[0]);
		client.Run();
	}
}

// MyCallbackClass is the class that contains the callback function to
// which ChatClient will submit a delegate to the server.
// To to pass a reference to this method (that is, a delegate)
// across an application domain boundary, this class must extend
// MarshalByRefObject or a class that extends MarshallByRefObject like all
// other remotable types.  MyCallbackClass extends RemotelyDelegatableObject because
// RemotelyDelegatableObject is a class that the server can obtain type information
// for.
class MyCallbackClass : RemotelyDelegatableObject
{
	private string _alias = null;

	public MyCallbackClass () {}
	public MyCallbackClass (string alias) { _alias = alias ; }

	// InternalSubmissionCallback is the method that is called by
	// RemotelyDelegatableObject.SubmissionCallback().  SubmissionCallback() is
	// sent to the server via a delegate.  You want the chat server to call
	// when the Submission event occurs -- even if the submission is yours.
	// The SubmissionEventHandler delegate wraps this function and is passed
	// to the Add_Submission (SubmissionEventHandler delegate) member of
	// the ChatCoordinator object. The .NET Remoting system handles the transfer
	// of all information about the client object and channel necessary to
	// make a return remote call when the event occurs.
	protected override void InternalSubmissionCallback (object sender, SubmitEventArgs submitArgs)
	{

		// Block out your own submission.
		// This simple chat server does not filter anything.
		if (String.Compare(submitArgs.Contributor, _alias, true) == 0)
		{
			Console.WriteLine("Your message was broadcast.");
		}
		else
			Console.WriteLine(submitArgs.Contributor
				+ " says:/r/n"
				+ new String('-', 80)
				+ submitArgs.Contribution
				+ "/r/n"
				+ new String('-', 80)
				+ "/r/n");
	}

	// This override ensures that if the object is idle for an extended
	// period, waiting for messages, it won't lose its lease. Without this
	// override (or an alternative, such as implementation of a lease
	// sponsor), an idle object that inherits from MarshalByRefObject
	// may be collected even though references to it still exist.
	public override object InitializeLifetimeService()
	{
		return null;
	}
}

				
The ChatCentral.exe.config file has not changed. It is still defined as follows:
<configuration>
   <system.runtime.remoting>
      <application>
         <service>
            <wellknown
               mode="Singleton"
               type="ChatCoordinator, ChatCoordinator"
               objectUri="Chat"
            />
         </service>
         <channels>
            <channel
               ref="http"
               port="8080"
            />
         </channels>
      </application>
   </system.runtime.remoting>
</configuration>
				
The ChatClient.exe.config file has also not changed. It is defined as follows:
<configuration>
   <system.runtime.remoting>
      <application>
         <client>
            <wellknown
               type="ChatCoordinator, ChatCoordinator"
               url="http://localhost:8080/Chat"
            />
         </client>
         <channels>
            <!-- The "0" port is declared to allow remoting to choose -->
            <!-- the most appropriate channel. You must specify a channel -->
            <!-- here, however; if you do not do so, your ChatClient -->
            <!-- will not be listening for the call back from the -->
            <!-- ChatCoordinator object. -->
            <channel
               ref="http"
               port="0"
            />
         </channels>
      </application>
   </system.runtime.remoting>
</configuration>
				
The build instructions for this sample have also not changed. The instructions in the .NET SDK use the command-line compilers.

STATUS

This bug was corrected in .NET Framework SDK.

APPLIES TO
•Microsoft .NET Framework SDK
Keywords: 
kbfix kbsample kbpending kbreadme kbremoting KB312114
粒子滤波在基于误差状态量的INS/GNSS组合导航中的使用技巧-On Particle Filter based Error-State INS/GNSS Intergrated Navigation 本文面向以15维惯导(INS)误差为状态量,3维位置误差为量测量的INS/GNSS组合导航系统,​在西工大严恭敏老师的开源工具箱中PF相关库函数基础上实现基于粒子滤波(PF)的惯导误差状态量的递推估计,设计了粒子重置环节并强调了其在本特定场景下的重要性。 阅读详情

相关推荐

用ADS复现一篇MTT顶刊的GAN功率放大器:从理论推导到版图仿真的完整避坑指南

本文详细解析了如何利用ADS软件复现MTT顶刊中的E/F3类GaN功率放大器设计,从理论推导到版图仿真的全流程。通过核心设计理念解析、ADS环境配置、输出匹配网络优化等关键步骤,提供了一套完整的工程实践指南,帮助工程师跨越学术理论与实际应用的鸿沟,实现高效率射频功率放大器的设计。

weixin_30654583的博客 315

解决“不允许类型 System.DelegateSerializationHolder 和从中派生的类型(例如 System.DelegateSerializationHolder)在此安全级别上被反序列化”错误的办法。

解决“不允许类型 System.DelegateSerializationHolder 和从中派生的类型(例如 System.DelegateSerializationHolder)在此安全级别上被反序列化”错误的办法。在.NET Framework 1.1中安全级别默认是Low的,所以不能被反序列化。以下代码是是一个聊天程序,在修改了配置文件后就可以访问了。远程处理程序:ChatCoordina

二十四画生的专栏 2865

BLE蓝牙胎压监测

胎压监测系统新技术

qq_41851841的博客 1255

Remoting远程处理事件调用的问题

Remoting远程处理事件调用的问题 [%=@titl

风中过客的专栏 1280

Python环境搭建和LabVIEW中的调用

本文主要介绍Python相关的环境搭建、Anaconda的使用以及在LabVIEW中调用Python的方法。

lvxisi的博客 6390

Marvell车载以太网交换机芯片88Q5050

Marvell推出了四款车载用交换机芯片,88Q5050,88Q5050, 88Q5072和88Q6113。其中88Q5030有5 Port用于通信,88Q5050有8 Port用于通信,5072与6113有11 Port用于通信。由于项目中用到了88Q5050,所以本文中只涉及到88Q5050的内容。本文是对使用88Q5050的梳理和总结。

zhuwade的博客 2万+

那些年删过的库,跑过的路,你从中找到解决方法了吗?

导读:本文我们盘点了往年发生的一些删库事件,我们该如何做到更好地预防和处理删库实践呢? 本月,多名网友反馈购物推荐网站什么值得买及APP无法访问。晚上10点多官方发表了公告,称服务器遭遇大面积攻击,网站及APP出现异常,目前正在逐步恢复中。针对之前传闻的数据丢失及泄露,什么值得买官方表示否认。但是此次疑似删库事件在网上也是引发了很多热议,下面我们来盘点下往年发生的一些删库事件,思考我们该如...

Enmotech的博客 525

STM32--基于STM32F103C8T6的OV7670摄像头显示

使用 STM32F103C8T6 微控制器驱动 OV7670 摄像头模组,并将图像数据显示在屏幕上,是嵌入式系统中常见的图像采集与显示应用。OV7670 是一款 CMOS VGA 图像传感器,具有高灵敏度、低电压等特点,适用于嵌入式应用。而 STM32F103C8T6 是一款常用的 MCU 控制器,具有丰富的管脚资源和较高的工作频率。

duierrorshuobu的博客 2145

[Remoting]dotNet Framework升级后Remoting信道使用的安全问题

  [Remoting]dotNet Framework升级后Remoting信道使用的安全问题   编写者:郑昀@UltraPower dotNet  Framwork 1.1 关键字:Channel,remoting 编写时间:2005-5-18   摘要:.NET Framework升级之后,Remoting中的事件就需要对信道进行特别的设置...

weixin_34183910的博客 207

CH592F RISC-V蓝牙LED灯设计:WS2812B驱动与微信小程序控制

蓝牙低功耗(BLE)是嵌入式物联网设备主流无线通信技术,其核心在于协议栈轻量化、射频稳定性与外设协同调度。基于RISC-V内核的蓝牙SoC(如CH592F)凭借高集成度、低待机电流和免外部巴伦的射频设计,显著降低硬件复杂度与BOM成本;而WS2812B作为单线级联RGB LED,依赖微秒级精准时序,需借助定时器+DMA机制规避CPU干预,保障动态效果流畅性。该方案融合电容触摸交互、GATT服务自定义与微信小程序标准Bluetooth API对接,适用于智能照明、DIY彩灯及教学实践等场景,是BLE+LED实

weixin_31163455的博客 433

ZYNQ系列PS侧和PL侧DDR3或DDR4在AD(Altium Designer 25)中的layout布线规则约束

DDR3或DDR4的PCB布线规则通常有相对固定的要求,对应的,在PCB设计时有固定的约束设置。

FPGA艺术家的博客 787

Remoting 错误信息类序列化问题

   在使用Remoting技术时,如果需要使用自己定义错误类即不是简单的使用Exception类时,自定义类除了要从Exception继承外,还要实现序列化接口,才可以使用,下面定义了SyncException类------    public enum SyncE

WDFrog的专栏 798

UG\NX二次开发 找不到指定的dlx文件(Specified Dlx file not found)

有群友问:用Ctrl+U运行的时候就报错,找不到指定的dlx文件Specified Dlx file not found。怎么处理。

王牌飞行员_里海的博客 1130

Microsoft .Net Remoting系列专题之二:Marshal、Disconnect与生命周期以及跟踪服务

我写的.Net Remoting系列专题: Microsoft .Net Remoting系列专题之一:.Net Remoting基础篇 Microsoft .Net Remoting系列专题之三:Remoting事件处理全接触 Microsoft .Net Remoting系列专题之二  一、远程对象的激活 在Remoting中有三种激活方式,一般的实现是通过RemotingSer...

weixin_33901926的博客 262

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

C# System.Runtime.Serialization.InvalidDataContractException:“无法序列化类型“问题解决

问题描述: System.Runtime.Serialization.InvalidDataContractException:“无法序列化类型“Com.ThisFileInfo”。请考虑将其标以 DataContractAttribute 特性,并将其所有要序列化的成员标以 DataMemberAttribute 特性。如果类型为集合,则请考虑将其标以 CollectionDataContractAttribute 特性。有关其他受支持的类型,请参见 Microsoft .NET Framework 文

旭东怪的博客 2786

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

C# Serialize() 抛出System.Runtime.Serialization.SerializationException

因为要往socket发送数据,需要把instance序列化(Serialization),用下面的函数发现会抛出SerializationException,Exception thrown: 'System.Runtime.Serialization.SerializationException' in mscorlib.dll. /// /// 序列化

5369

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

在 System.Security.SecurityException 中第一次偶然出现的“System.Runtime.Serialization.dll”类型的异常

今天在写cocos2d-x的程序的时候,发现了这个问题,在按开始键进入后台,或者按返回键返回程序。引发这样的异常。导致线程中断,无法返回程序。 异常信息如下: 在 System.Security.SecurityException 中第一次偶然出现的“System.Runtime.Serialization.dll”类型的异常 在 System.Reflection.TargetInvoca

做简单的事,做简单的教程 4046

SqlParameter序列化的问题

SqlParameterremoting 客户端调用服务端方法:DataSet ExecuteProc(string procedurename, SqlParameter[] a); 调用: DataSet ds = SqlUtil.ExecuteProc("存储过程名", parameters);// parameters 为 ...

deche3275的博客 401
上一篇: 在VC中实现FTP功能
下一篇: Asp.net中插入脚本传递数据
通者归来
博客等级 码龄25年 18粉丝 55原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值