Click here to Skip to main content
15,861,125 members
Articles / Desktop Programming / Windows Forms
Article

A Remoting Event (Simple and Efficient for Enterprise Solutions)

Rate me:
Please Sign up or sign in to vote.
4.84/5 (25 votes)
21 Aug 2006CPOL2 min read 160.5K   2.1K   85   50
This article contains the simplest solutions for: the security problem for DelegateSerializationHolder, the IO problem, and the messaging speed problem. Note: Messaging speed problem will appear when your application has worked for a long time.

demo project Image

Background

I always had an interest in socket programming. I have created several chat applications and complex socket based applications. When I learned about events in Remoting I was so glad, and the first thing that I thought about was creating a chat application. But in the test, I met with some problems.

Problem 1

The first problem was a security exception:

System.Security.SecurityException: Type System.DelegateSerializationHolder 
and the types derived from it (such as System.DelegateSerializationHolder) 
are not permitted to be deserialized at this security level.

Security Exception Image

Solution 1

This problem was solved by adding the typeFilterLevel attribute with Full value to the formatter element of both configuration files.

XML
<formatter ref="soap" typeFilterLevel="Full" />

Problem 2

But again, it did not work and an IO exception occurred:

System.Reflection.TargetInvocationException: 
Exception has been thrown by the target of an invocation. ---> 
System.IO.FileNotFoundException: Could not load file or assembly 
'Client, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' 
or one of its dependencies. The system cannot find the file specified.

This exception occurs while the request is deserialized at the server. The server tries to call the event handler whereas the event handler exists in the client assembly. Because the client assembly is not available at the server, the exception is thrown.

IO exception Image

Solution 2

An intermediate wrapper class, MarshalByRefObject will solve this problem. This wrapper class is located in the shared assembly, accessible for both the client and the server; therefore, a delegate can resolve the method's signature. In the client application, we will associate the shared object event with the WrapperMessageReceivedHandler method of the wrapper class and associate an event handler on the client with the MessageReceived event of the wrapper class.

Sequense of events Image

Why [OneWay] Attribute

Without defining the remote method as [OneWay], an exception will occur when the client is unreachable or has been disconnected without disassociating the event handler. By using [OneWay], no exception will occur on the client, but it will be in the invocation list of the server and, in longtime, will make your server slower to respond.

Solution 3

Instead of using the normal event invocation mechanism, you must invoke each delegate on your own, and if an exception occurs, you must disassociate the delegate from the invocation list of the event. In the end, you can remove the [OneWay] attribute.

Shared Class

C#
/// <summary>
/// Represents the method that will handle
/// the Remotable.RemoteClass.MessageReceived event.
/// </summary>
/// <param name="message">Received message</param>

[Serializable]
public delegate void MessageHandler(string message);

/// <summary>
/// Shared remoting class that orchestrate messaging tasks 
/// </summary>

public class RemoteClass:MarshalByRefObject
{

    /// <summary>
    /// Occurs when a broadcast message received.
    /// </summary>

    public event MessageHandler MessageReceived;
    /// <summary>
    /// Initializes a new instance of the Remotable.RemoteClass class.
    /// </summary>

    public RemoteClass()
    {
       
    }

    /// <summary>
    /// Obtains a lifetime service object to control the lifetime policy for this
    /// instance.
    /// </summary>
    /// <returns>
    ///An object of type 
    ///System.Runtime.Remoting.Lifetime.ILease used to control
    ///the lifetime policy for this instance. This is the current lifetime service
    ///object for this instance if one exists; otherwise, a new lifetime service
    ///object initialized to the value of the 
    ///System.Runtime.Remoting.Lifetime.LifetimeServices.LeaseManagerPollTime
    ///property.
    ///null value means this object has to live forever.
    /// </returns>

    public override object InitializeLifetimeService()
    {
        return null;
    }

    /// <summary>
    /// Broadcast message to all clients
    /// </summary>
    /// <param name="message">message string</param>

    public void Send(string message)
    {
        if (MessageReceived != null)
        {
            MessageHandler messageDelegate = null;
            Delegate[] invocationList_ = null;
            try
            {
                invocationList_ = MessageReceived.GetInvocationList();
            }
            catch (MemberAccessException ex)
            {
                throw ex;
            }
            if (invocationList_ != null)
            {
                lock (this)
                {
                    foreach (Delegate del in invocationList_)
                    {
                        try
                        {
                            messageDelegate = (MessageHandler)del;
                            messageDelegate(message);
                        }
                        catch (Exception e)
                        {
                            MessageReceived -= messageDelegate;
                        }
                    }
                }
            }
        }
    }

Client Application

C#
RemoteClass remoteClass;
WrapperClass wrapperClass;

private void Form1_Load(object sender, EventArgs e)
{
    //Configure remoting.

    RemotingConfiguration.Configure(Application.StartupPath + 
                          "\\Client.exe.config",false);

    // Create a proxy from remote object.

    remoteClass = (RemoteClass)Activator.GetObject(typeof(RemoteClass), 
                   "http://localhost:8080/Chat");
    //Create an instance of wrapper class.

    wrapperClass = new WrapperClass();
  
    //Associate remote object event with wrapper method.

    remoteClass.MessageReceived += new 
          MessageHandler(wrapperClass.WrapperMessageReceivedHandler);
    //Associate wrapper event with current form event handler.

    wrapperClass.WrapperMessageReceived += new 
           MessageHandler(MessageReceivedHandler);
}

Wrapper Class

C#
/// <summary>
/// Occurs when a broadcast message received.
/// </summary>

public event MessageHandler WrapperMessageReceived;
/// <summary>
/// Wrapper method for sending message to the clients.
/// </summary>
/// <param name="sender">Caller object</param>
/// <param name="args">Message data</param>

public void WrapperMessageReceivedHandler(string message)
{
    // forward the message to the client

    if(WrapperMessageReceived != null)
        WrapperMessageReceived(message);
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Program Manager System Group
Iran (Islamic Republic of) Iran (Islamic Republic of)
Hossein Ghahvei Araghi
Birth date: 1978
Birth place: Iran
Academic Credentials : BS(Tehran University)
Microsoft Credentials : MCP, MCAD, MCTS 2.0, MCTS 3.5, MCPD 2.0, MCPD 3.5

Comments and Discussions

 
QuestionThanks for this example. Pin
dcarl66128-Jul-16 6:12
dcarl66128-Jul-16 6:12 
QuestionGreat sample! Pin
leiyangge21-Apr-15 16:10
leiyangge21-Apr-15 16:10 
GeneralMultiple Event Pin
borchanii7-Sep-10 0:10
borchanii7-Sep-10 0:10 
GeneralRe: Multiple Event Pin
ysgepl27-Jul-11 19:49
ysgepl27-Jul-11 19:49 
GeneralSerilizable tag Pin
xandytsui26-Nov-08 14:02
xandytsui26-Nov-08 14:02 
GeneralThat's what I really need! Pin
xandytsui20-Nov-08 13:50
xandytsui20-Nov-08 13:50 
GeneralTrying to do this without the app.config files Pin
ObsidianPC10-Nov-08 14:09
ObsidianPC10-Nov-08 14:09 
GeneralRe: Trying to do this without the app.config files Pin
ObsidianPC10-Nov-08 14:44
ObsidianPC10-Nov-08 14:44 
GeneralRe: Trying to do this without the app.config files [modified] Pin
ObsidianPC10-Nov-08 14:51
ObsidianPC10-Nov-08 14:51 
QuestionQuestion about broadcasting Pin
Mazdak22-Jul-07 20:43
Mazdak22-Jul-07 20:43 
AnswerRe: Question about broadcasting Pin
ObsidianPC11-Nov-08 7:08
ObsidianPC11-Nov-08 7:08 
Generalconvert to VB.NET Pin
fyclinic23-May-07 23:47
fyclinic23-May-07 23:47 
QuestionWrapper Woes. Please Help Pin
Roey9928-Oct-06 8:57
Roey9928-Oct-06 8:57 
GeneralRemoting Pin
hariram2811-Oct-06 7:07
hariram2811-Oct-06 7:07 
Could any one help how to resolve my problem in remoting in VB.NET

I like to inform you that I’m in between beginner and moderate level. I’m developing a application in VB.NET using remoting concept for my academic purpose. I need replica of a object which is created in a server application to be accessed in other remote client machine…
Kindly help me as I’m nearing my dealine…


I’ll explain you briefly through a sample code…

First I’ll run this application and initialize the object…

Application 1(server):

Class file :
Class x
Public y as integer


End class

VB file:

Function init()
Dim ab as x

Ab.y=5
End function

After running the application 1, then I’m running the client machine.

Application 2(Remote Client):

VB file:


Dim obj as remoteobj
dim x as integer

x=obj.y

so that the value gets stored in the variable x.


Hariram
QuestionREmoting Pin
hariram2811-Oct-06 6:57
hariram2811-Oct-06 6:57 
QuestionAny new client do not communicate to the existing one Pin
Jeetu00725-Sep-06 14:50
Jeetu00725-Sep-06 14:50 
GeneralUsing Across a network Pin
mcstarSatx20-Sep-06 6:32
mcstarSatx20-Sep-06 6:32 
GeneralRe: Using Across a network Pin
gio_ch28-Jul-11 7:25
gio_ch28-Jul-11 7:25 
GeneralRe: Using Across a network Pin
Hossein Ghahvei Araghi30-Jul-11 21:07
Hossein Ghahvei Araghi30-Jul-11 21:07 
GeneralRequested service not found Pin
Jeetu0075-Sep-06 14:38
Jeetu0075-Sep-06 14:38 
GeneralRe: Requested service not found Pin
Jeetu00713-Sep-06 15:34
Jeetu00713-Sep-06 15:34 
QuestionRe: Requested service not found Pin
camariei11-Dec-06 11:40
camariei11-Dec-06 11:40 
GeneralVB.Net Pin
FuSe51224-Aug-06 16:19
FuSe51224-Aug-06 16:19 
GeneralRe: VB.Net Pin
FuSe51224-Aug-06 16:58
FuSe51224-Aug-06 16:58 
Questionabout the NAT Pin
yonking23-Aug-06 22:41
yonking23-Aug-06 22:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.