How can i tell if an object instance is being created using .NET Remoting

Posted on 2009-02-18
Last Modified: 2013-12-17
I have a simple class named DataServer which inherits from MarshalByRefObject. The dll containing my class lives on the server and my web app is configured to allow clients to create instances of the object remotely using .NET remoting.

There are 2 ways in which these objects can be created on the server.

1. Directly from server side code in my web app i.e. not using remoting
2. From a client i.e. using remoting

Within the DataServer() constructor method, I need to be able to tell if the object is being created by a remote call from a client. How can I do this?

Question by:purplesoup
    LVL 96

    Expert Comment

    by:Bob Learned
    You can use the 'as' keyword, to silently test if an object implements an interface or a base class:

    MarshalByRefObject test = myObject as MarshalByRefObject;

    if (test != null)

    The CLR will silently try to down-cast the object.  If it can't, you won't get an exception, and the result will be 'null'.

    Author Comment

    Thanks for your response, but this doesn't do what I need. My class is set up to allow remoting so I know it inherits from MarshallByRef, and the test you provided will always be true.

    I'm just trying to find out a way for an object to detect whether it is being created over remoting or not. Just because an object inherits from MarshallByRef does not mean that it has to be created remotely. The key thing for me is that this check can be made within the constructor.

    Here is a basic class example. I just need someone to tell me what to put in the ?????????? section

    public class RemotableObject : MarshalByRefObject

         bool wasCreatedRemotely = false;

         // constructor
         public RemotableObject()
              // test if this object is being created by a remoting call
              if (?????????)
                   wasCreatedRemotely = true;
                   wasCreatedRemotely = false;

    LVL 96

    Accepted Solution

    Hmmm...that is a great question.  I wonder if you could do that with a StackFrame?

    printing the calling method name : C#

    Author Comment

    I played around with StackTrace a bit, and there does seem to be enough information in there to give you a clue if the object was created using a remoting call.

    Here is a copy of System.Environment.StackTrace reported my class constructor. As you can see it has several references to System.Runtime.Remoting.  These are not present in the stack trace if you create the object locally i.e. not using remoting.

       at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
       at System.Environment.get_StackTrace()
       at RemotableType.RemotableType..ctor()
       at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck)
       at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache)
       at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
       at System.Activator.CreateInstance(Type type, Boolean nonPublic)
       at System.Runtime.Remoting.RemotingConfigHandler.RemotingConfigInfo.StartupWellKnownObject(String asmName, String svrTypeName, String URI, WellKnownObjectMode mode, Boolean fReplace)
       at System.Runtime.Remoting.RemotingConfigHandler.RemotingConfigInfo.StartupWellKnownObject(String URI)
       at System.Runtime.Remoting.RemotingConfigHandler.CreateWellKnownObject(String uri)
       at System.Runtime.Remoting.IdentityHolder.CasualResolveIdentity(String uri)
       at System.Runtime.Remoting.Messaging.MethodCall.ResolveType()
       at System.Runtime.Remoting.Messaging.MethodCall.ResolveMethod(Boolean bThrowIfNotResolved)
       at System.Runtime.Remoting.Messaging.MethodCall..ctor(Object handlerObject, BinaryMethodCallMessage smuggledMsg)
       at System.Runtime.Serialization.Formatters.Binary.BinaryMethodCall.ReadArray(Object[] callA, Object handlerObject)
       at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
       at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
       at System.Runtime.Remoting.Channels.CoreChannel.DeserializeBinaryRequestMessage(String objectUri, Stream inputStream, Boolean bStrictBinding, TypeFilterLevel securityLevel)
       at System.Runtime.Remoting.Channels.BinaryServerFormatterSink.ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, IMessage& responseMsg, ITransportHeaders& responseHeaders, Stream& responseStream)
       at System.Runtime.Remoting.Channels.Tcp.TcpServerTransportSink.ServiceRequest(Object state)
       at System.Runtime.Remoting.Channels.SocketHandler.ProcessRequestNow()
       at System.Runtime.Remoting.Channels.RequestQueue.ProcessNextRequest(SocketHandler sh)
       at System.Runtime.Remoting.Channels.SocketHandler.BeginReadMessageCallback(IAsyncResult ar)
       at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
       at System.Net.ContextAwareResult.CompleteCallback(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Net.ContextAwareResult.Complete(IntPtr userToken)
       at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
       at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
       at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Training Course: Java/J2EE and SOA

    This course will cover both core and advanced Java concepts like Database connectivity, Threads, Exception Handling, Collections, JSP, Servlets, XMLHandling, and more. You'll also learn various Java frameworks like Hibernate and Spring.

    The object model of .Net can be overwhelming at times – so overwhelming that quite trivial tasks often take hours of research. In this case, the task at hand was to populate the datagrid from SQL Server database in Visual Studio 2008 Windows applica…
    Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
    To add imagery to an HTML email signature, you have two options available to you. You can either add a logo/image by embedding it directly into the signature or hosting it externally and linking to it. The vast majority of email clients display l…
    Sending a Secure fax is easy with eFax Corporate ( First, Just open a new email message.  In the To field, type your recipient's fax number You can even send a secure international fax — just include t…

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now