Inheritance: IMethodCallMessage, IMethodMessage, IMessage, IInternalMessage, ISerializable
 static internal TransactionMessageProperty TryGet(Message message)
 {
     if (message.Properties.ContainsKey(PropertyName))
         return message.Properties[PropertyName] as TransactionMessageProperty;
     else
         return null;
 }
        static internal Transaction TryGetTransaction(Message message)
        {
            if (!message.Properties.ContainsKey(PropertyName))
                return null;

            return ((TransactionMessageProperty)message.Properties[PropertyName]).Transaction;

        }
        static TransactionMessageProperty GetPropertyAndThrowIfAlreadySet(Message message)
        {
            if (message.Properties.ContainsKey(PropertyName))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new FaultException(SR.GetString(SR.SFxTryAddMultipleTransactionsOnMessage)));
            }

            return new TransactionMessageProperty();
        }
 internal void InitFields(Message m)
 {
     this._m = m;
     if (this._h != null)
     {
         this._h.Clear();
     }
     if (this._d != null)
     {
         this._d.Clear();
     }
 }
        public object GetInstance( InstanceContext instanceContext, Message message )
        {
            var connectionStringKey = GetConnectionStringKey( serviceType );

            var kernel = new StandardKernel( new NinjectSetup( connectionStringKey ) );

            SessionManager = kernel.Get<SessionManager>();
            Transaction = SessionManager.BeginTransaction();

            var instance = kernel.Get( serviceType );

            return instance;
        }
Example #6
0
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            ClientApplicationContext.Current = reply.GetApplicationContext<ClientApplicationContext>();

            try
            {
                var setting = WcfSettingManager.CurrentClientSetting((correlationState as Type));
                var logSetting = setting.WcfLogSetting;
                if (logSetting.Enabled && logSetting.MessageInfoSetting.Enabled)
                {
                    var direct = logSetting.MessageInfoSetting.MessageDirection;
                    if (direct == MessageDirection.Both || direct == MessageDirection.Receive)
                    {
                        var log = WcfLogProvider.GetClientMessageInfo(
                          (correlationState as Type).FullName,
                          ClientApplicationContext.Current.RequestIdentity,
                          "ClientMessageInspector.AfterReceiveReply",
                          MessageDirection.Receive,
                          reply.ToString());

                        MongodbService.MongodbInsertService.Insert(log);
                    }
                }

                var securitySetting = setting.WcfSecuritySetting;
                if (securitySetting.PasswordCheck.Enable)
                {
                    if (securitySetting.PasswordCheck.Direction == OperationDirection.Both || securitySetting.PasswordCheck.Direction == OperationDirection.Reply)
                    {
                        if (ClientApplicationContext.Current.Password != securitySetting.PasswordCheck.Password)
                            throw new WcfSecurityException(string.Format("PasswordCheck failed in reply for {0}!", (correlationState as Type).FullName));
                    }
                }
            }
            catch (Exception ex)
            {
                ex.Handle(WcfLogProvider.ModuleName, "ClientMessageInspector", "AfterReceiveReply");
                if (ex is WcfSecurityException) throw;
            }
        }
        private static void Invoke(object NotUsed, ref MessageData msgData)
        {
            Message reqMcmMsg = new Message();
            reqMcmMsg.InitFields(msgData);
            Delegate thisPtr = reqMcmMsg.GetThisPtr() as Delegate;
            if (thisPtr == null)
            {
                throw new RemotingException(Environment.GetResourceString("Remoting_Default"));
            }
            RemotingProxy realProxy = (RemotingProxy) RemotingServices.GetRealProxy(thisPtr.Target);
            if (realProxy != null)
            {
                realProxy.InternalInvoke(reqMcmMsg, true, reqMcmMsg.GetCallType());
            }
            else
            {
                int callType = reqMcmMsg.GetCallType();
                switch (callType)
                {
                    case 1:
                    case 9:
                    {
                        reqMcmMsg.Properties[Message.CallContextKey] = CallContext.GetLogicalCallContext().Clone();
                        AsyncResult retVal = new AsyncResult(reqMcmMsg);
                        AgileAsyncWorkerItem state = new AgileAsyncWorkerItem(reqMcmMsg, ((callType & 8) != 0) ? null : retVal, thisPtr.Target);
                        ThreadPool.QueueUserWorkItem(new WaitCallback(AgileAsyncWorkerItem.ThreadPoolCallBack), state);
                        if ((callType & 8) != 0)
                        {
                            retVal.SyncProcessMessage(null);
                        }
                        reqMcmMsg.PropagateOutParameters(null, retVal);
                        break;
                    }
                    case 2:
                        RealProxy.EndInvokeHelper(reqMcmMsg, false);
                        return;

                    case 10:
                        break;

                    default:
                        return;
                }
            }
        }
        /// <remarks>
        /// The Remoting call is packaged as a message and sent to all group members.
        /// The response will be choosen using a chooser if present otherwise the 
        /// response with the most 'votes' will be chosen.
        /// </remarks>
        /// <summary>
        /// Processes the Remoting call.
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public IMessage SyncProcessMessage(IMessage msg)
        {
            IMethodCallMessage mcm = msg as IMethodCallMessage;
            currentMethodCall = mcm;
            IMessage retMsg = null;

            long		time_to_wait;
            long		start_time;

            try
            {
                Address dest = null;;
                if (objectURI == null)
                    return null;

                if (channelURI != null)
                {
                    String ip = "";
                    int port = 0;
                    int startpos = (channelURI.IndexOf("//")+2);
                    int endpos = (channelURI.IndexOf(":",startpos));
                    ip = channelURI.Substring(startpos,endpos-startpos);
                    if(String.Compare(ip,"null")==0)
                        dest = null;
                    else
                    {
                        ++endpos;
                        string tmpPort = channelURI.Substring(endpos,channelURI.Length-endpos);
                        port = Convert.ToInt32(tmpPort);
                        dest = new Address(ip, port);
                    }
                }

                if(dest!=null && !members.Contains(dest))
                    throw new Exception("Remoting request cannot be sent to non-member");

                Message remotingMsg = new Message(dest,null,null);
                StackHeader hdr = new StackHeader(StackHeader.REMOTE_REQ,mcm,objectURI);
                remotingMsg.putHeader(name,hdr);

                remotingResponses.Clear();

                down(new Event(Event.MSG,remotingMsg));

                lock(remotingResponses)
                {
                    start_time = System.Environment.TickCount;
                    time_to_wait = remotingTimeout;
                    int responsesDesired = 1;
                    if(dest==null)
                        responsesDesired = members.Count;

                    while(remotingResponses.Count < responsesDesired && time_to_wait > 0)
                    {

                        if(Trace.trace)
                            Trace.info(name + ".SyncProcessMessage()", "waiting for responses: time_to_wait=" + time_to_wait +
                            ", got " + remotingResponses.Count + "|"+  responsesDesired + " rsps");

                        Monitor.Wait(remotingResponses, (int)time_to_wait, true);
                        time_to_wait -= System.Environment.TickCount - start_time;
                    }
                    if(Trace.trace)
                        Trace.info(name + ".SyncProcessMessage()", "No longer waiting for responses as Initial Members = " + remotingResponses.Count   + "|" +responsesDesired + "   TimeToWait = " + time_to_wait );

                    retMsg = determineResponse();

                    if (retMsg ==null)
                        throw new NullReferenceException("No remoting response to request");

                }

            }
            catch (Exception e)
            {
                if(Trace.trace)
                    Trace.error(name + ".SyncProcessMessage()", "General error occured: " + e + "/n" + e.StackTrace);
                retMsg = new ReturnMessage(e, mcm);
            }

            currentMethodCall = null;
            return retMsg;
        }
Example #9
0
        // Private method invoked by the transparent proxy
        private void PrivateInvoke(ref MessageData msgData, int type)
        {
            IMessage reqMsg = null;
            CallType callType = (CallType)type;
            IMessage retMsg = null;
            int msgFlags = -1;
            
            // Create a message object based on the type of call
            if(CallType.MethodCall == callType)
            {
                Message msg = new Message();
                msg.InitFields(msgData);
                reqMsg = msg;
                msgFlags = msg.GetCallType();
            }
            else if (CallType.ConstructorCall == (CallType)callType)
            {
                // We use msgFlags to handle CallContext around 
                // the virtual call to Invoke()
                msgFlags = Message.Sync;
                
                ConstructorCallMessage ctorMsg = null;
                RemotingProxy rp = this as RemotingProxy;
                if(null == rp)
                {
                    // Create a new constructor call message
                    ctorMsg = new ConstructorCallMessage(null, null, null, GetProxiedType());                    
                }                                
                else
                {
                    // Extract the constructor message set in the first step of activation.
                    ctorMsg = rp.ConstructorMessage;                                         
                }

                // If the proxy is a wellknown client proxy, we don't need to run the c'tor.
                bool bIsWellKnown = false;
                if (rp != null)
                {
                    Identity id = rp.IdentityObject;
                    if (id != null)
                        bIsWellKnown = id.IsWellKnown();
                }
                
                if ((null == ctorMsg) || bIsWellKnown)
                {
                    // This is also used to short-circuit the activation path
                    // when we have a well known proxy that has already been
                    // initialized (there's a race condition if we don't do this).
                    //      
                
                    // This is a special case, where we have a remoting proxy
                    // but the constructormessage hasn't been setup.
                    // so let us just bail out.. 
                    // this is currently used by ServicedComponent's for cross appdomain
                    // pooling:                     
                    //

                    /*
                    ProxyAttribute pa = null;                            
                    BCLDebug.Assert(((pa = ActivationServices.GetProxyAttribute(GetProxiedType()) is Object) || true);
                    BCLDebug.Assert(pa != null && pa.GetType() != typeof(ProxyAttribute));
                    */
                    ctorMsg = new ConstructorCallMessage(null, null, null, GetProxiedType());                    
                    // Set the constructor frame info in the CCM
                    ctorMsg.SetFrame(msgData); 
                    reqMsg = ctorMsg;

                    // If this was the default ctor, check that default .ctor was called.
                    if (bIsWellKnown)
                    {
                        // We did execute a Connect. Throw if the client
                        // code is also trying to use a non-default constructor at
                        // the same time.
                        if (ctorMsg.ArgCount != 0)
                        {
                            throw new RemotingException(
                                Environment.GetResourceString(
                                    "Remoting_Activation_WellKnownCTOR"));
                        }
                    }
                    
                    // Create a constructor return message
                    retMsg = 
                        new ConstructorReturnMessage((MarshalByRefObject)GetTransparentProxy(), 
                            null, 
                            0, 
                            null, 
                            ctorMsg);
                }
                else
                {                
                    // Set the constructor frame info in the CCM
                    ctorMsg.SetFrame(msgData);
                    reqMsg = ctorMsg;
                }
            }
            else
            {
                BCLDebug.Assert(false, "Unknown call type");
            }

            // Make sure that outgoing remote calls are counted.
            ChannelServices.IncrementRemoteCalls();


            // Invoke
            BCLDebug.Assert(null != reqMsg, "null != reqMsg");
            if (null == retMsg)
            {
                // NOTE: there are cases where we setup a return message 
                // and we don't want the activation call to go through
                // refer to the note above for ServicedComponents and Cross Appdomain
                // pooling

                LogicalCallContext cctx = null;
                Thread currentThread = Thread.CurrentThread;
                // Pick up or clone the call context from the thread 
                // and install it in the reqMsg as appropriate
                cctx = currentThread.GetLogicalCallContext();   
                SetCallContextInMessage(reqMsg, msgFlags, cctx);
                
                // Add the outgoing "Header"'s to the message.
                cctx.PropagateOutgoingHeadersToMessage(reqMsg);
                
                retMsg = Invoke(reqMsg);

                // Get the call context returned and set it on the thread
                ReturnCallContextToThread(currentThread, retMsg, msgFlags);

                // Pull response "Header"'s out of the message
                CallContext.GetLogicalCallContext().PropagateIncomingHeadersToCallContext(retMsg);
            }

            // Propagate out parameters
            HandleReturnMessage(reqMsg, retMsg);

            // For constructor calls do some extra bookkeeping
            if(CallType.ConstructorCall == callType)
            {
                // NOTE: It is the responsiblity of the callee to propagate
                // the out parameters

                // Everything went well, we are ready to return
                // a proxy to the caller
                // Extract the return value
                MarshalByRefObject retObj = null;
                IConstructionReturnMessage ctorRetMsg = retMsg as IConstructionReturnMessage;
                if(null == ctorRetMsg)
                {
                    throw new RemotingException(
                        Environment.GetResourceString("Remoting_Proxy_BadReturnTypeForActivation"));
                }

                ConstructorReturnMessage crm = ctorRetMsg as ConstructorReturnMessage;
                if (null != crm)
                {
                    retObj = (MarshalByRefObject)crm.GetObject();
                    if (retObj == null)
                    {
                        throw new RemotingException(
                            Environment.GetResourceString("Remoting_Activation_NullReturnValue"));
                    }
                }
                else
                {
                    // Fetch the objRef out of the returned message and unmarshal it
                    retObj = (MarshalByRefObject)RemotingServices.InternalUnmarshal(
                                (ObjRef)ctorRetMsg.ReturnValue,
                                GetTransparentProxy(),
                                true /*fRefine*/);

                    if (retObj == null)
                    {
                        throw new RemotingException(
                            Environment.GetResourceString("Remoting_Activation_NullFromInternalUnmarshal"));
                    }
                }

                if (retObj != (MarshalByRefObject)GetTransparentProxy())
                {
                    throw new RemotingException(
                        Environment.GetResourceString(
                            "Remoting_Activation_InconsistentState"));
                }
            }
        }
        static internal ICollection<RequestSecurityTokenResponse> TryGetIssuedTokens(Message message)
        {
            TransactionFlowProperty property = TransactionFlowProperty.TryGet(message);
            if (property == null)
                return null;

            // use this when reading only, consistently return null if no tokens.
            if (property.issuedTokens == null || property.issuedTokens.Count == 0)
                return null;

            return property.issuedTokens;
        }
        static TransactionFlowProperty GetPropertyAndThrowIfAlreadySet(Message message)
        {
            TransactionFlowProperty property = TryGet(message);

            if (property != null)
            {
                if (property.flowedTransaction != null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FaultException(SR.GetString(SR.SFxTryAddMultipleTransactionsOnMessage)));
                }
            }
            else
            {
                property = new TransactionFlowProperty();
            }

            return property;
        }
 internal void SetFrame(MessageData msgData)
 {
     this._message = new Message();
     this._message.InitFields(msgData);
 }
Example #13
0
        } // ValidateReturnArg

        // This is shared code path that executes when an EndInvoke is called 
        // either on a delegate on a proxy 
        // OR a regular delegate (called asynchronously).
        internal static IMessage EndInvokeHelper(Message reqMsg, bool bProxyCase)
        {
            AsyncResult ar = reqMsg.GetAsyncResult() as AsyncResult;
            IMessage retMsg = null; // used for proxy case only!
            if (ar == null)
            {
                throw new RemotingException(
                    Environment.GetResourceString(
                        "Remoting_Message_BadAsyncResult"));                    
            }
            if (ar.AsyncDelegate != reqMsg.GetThisPtr())
            {
                throw new InvalidOperationException(Environment.GetResourceString(
                        "InvalidOperation_MismatchedAsyncResult"));
            }
            if (!ar.IsCompleted)
            {
                // Note: using ThreadPoolAware to detect if this is a 
                // ThreadAffinity or Synchronization context.
                ar.AsyncWaitHandle.WaitOne(
                        Int32.MaxValue,
                        Thread.CurrentContext.IsThreadPoolAware);
            }

            lock (ar)
            {
                if (ar.EndInvokeCalled)
                    throw new InvalidOperationException(
                        Environment.GetResourceString(
                            "InvalidOperation_EndInvokeCalledMultiple"));

                ar.EndInvokeCalled = true;
            

                IMethodReturnMessage mrm =  
                    (IMethodReturnMessage) ar.GetReplyMessage();

                BCLDebug.Assert(
                    mrm != null, 
                    "Reply sink should ensure we have a reply message before signalling");

                // For the proxy case this is handled by RealProxy
                if (!bProxyCase)
                {
                    Exception e = mrm.Exception;

                    if (e != null)
                    {
                        // throw e;
                        throw e.PrepForRemoting();
                    }
                    else
                    {
                        reqMsg.PropagateOutParameters(
                            mrm.Args, 
                            mrm.ReturnValue);

                    }
                }
                else
                {
                    retMsg = mrm;
                }
                // Merge the call context back into the thread that 
                // called EndInvoke
                CallContext.GetLogicalCallContext().Merge(
                    mrm.LogicalCallContext);
            }
            // Will be non-null only for proxy case!
            return retMsg;
        } // EndInvokeHelper
Example #14
0
        // This is called from InternalInvoke above when someone makes an
        // Async (or a one way) call on a TP
        internal void InternalInvokeAsync(IMessageSink ar,  Message reqMsg, 
            bool useDispatchMessage, int callType)
        {
            IMessageCtrl cc = null;
            Identity idObj = IdentityObject;
            ServerIdentity serverID = idObj as ServerIdentity;
            MethodCall cpyMsg= new MethodCall(reqMsg);
            IInternalMessage iim = ((IInternalMessage)cpyMsg);

            // Set the identity in the message object
            iim.IdentityObject = idObj;
            if (null != serverID)
            {
                Message.DebugOut("Setting SrvID on deser msg\n");
                iim.ServerIdentityObject = serverID;                    
            }

            if (useDispatchMessage)
            {
                Message.DebugOut(
                    "RemotingProxy.Invoke: Calling AsyncDispatchMessage\n");

                BCLDebug.Assert(ar != null,"ar != null");
                BCLDebug.Assert( (callType & Message.BeginAsync) != 0,
                                "BeginAsync flag not set!");

                Message.DebugOut("Calling AsynDispatchMessage \n");
                cc = ChannelServices.AsyncDispatchMessage(
                                        cpyMsg, 
                                        ((callType & Message.OneWay) != 0) 
                                        ? null : ar);
            }
            else if (null != idObj.EnvoyChain)
            {
                Message.DebugOut("RemotingProxy.Invoke: Calling AsyncProcessMsg on the envoy chain\n");

                cc = idObj.EnvoyChain.AsyncProcessMessage(
                                        cpyMsg, 
                                        ((callType & Message.OneWay) != 0) 
                                        ? null : ar);
            }
            else
            {
                // Channel sink cannot be null since it is the last sink in
                // the client context
                // Assert if Invoke is called without a channel sink
                BCLDebug.Assert(false, "How did we get here?");
                throw new ExecutionEngineException(
                    Environment.GetResourceString("Remoting_Proxy_InvalidState"));
            }

            if ((callType & Message.BeginAsync) != 0)
            {

                if ((callType & Message.OneWay) != 0)
                {
                    ar.SyncProcessMessage(null);
                }
            }
        }
 static public void Set(Transaction transaction, Message message)
 {
     TransactionMessageProperty property = GetPropertyAndThrowIfAlreadySet(message);
     property.flowedTransaction = transaction;
     message.Properties.Add(PropertyName, property);
 }
 internal void InternalInvokeAsync(IMessageSink ar, Message reqMsg, bool useDispatchMessage, int callType)
 {
     Identity identityObject = this.IdentityObject;
     ServerIdentity identity2 = identityObject as ServerIdentity;
     MethodCall msg = new MethodCall(reqMsg);
     IInternalMessage message = msg;
     message.IdentityObject = identityObject;
     if (identity2 != null)
     {
         message.ServerIdentityObject = identity2;
     }
     if (useDispatchMessage)
     {
         ChannelServices.AsyncDispatchMessage(msg, ((callType & 8) != 0) ? null : ar);
     }
     else
     {
         if (identityObject.EnvoyChain == null)
         {
             throw new InvalidOperationException(Environment.GetResourceString("Remoting_Proxy_InvalidState"));
         }
         identityObject.EnvoyChain.AsyncProcessMessage(msg, ((callType & 8) != 0) ? null : ar);
     }
     if (((callType & 1) != 0) && ((callType & 8) != 0))
     {
         ar.SyncProcessMessage(null);
     }
 }
        /// <summary>
        /// Sends request into infrastructure, then passes back result.
        /// </summary>
        /// <param name="hdr">Header contain request.</param>
        private void handleRemotingRequest(StackHeader hdr)
        {
            IMessage responseMsg;
            ITransportHeaders responseHeaders;
            Stream responseStream;
            IMessage req = hdr.Message;

            ServerChannelSinkStack sinkStack = new ServerChannelSinkStack();
            ProcessMessage(sinkStack,req,null,null,out responseMsg,out responseHeaders,out responseStream);

            //send response back down the stack
            Address dest = hdr.Source;
            Message remotingMsg = new Message(dest,local_addr,null);
            StackHeader rspHdr = new StackHeader(StackHeader.REMOTE_RSP,responseMsg, "");
            remotingMsg.putHeader(name,rspHdr);

            down(new Event(Event.MSG,remotingMsg));
        }
        static internal bool IsValidAction(Message message, string action)
        {
            if (message == null)
            {
                return false;
            }

            if (message.IsFault)
            {
                return true;
            }

            if (action == MessageHeaders.WildcardAction)
            {
                return true;
            }

            return (String.CompareOrdinal(message.Headers.Action, action) == 0);
        }
 static internal void Set(TransactionInfo transactionInfo, Message message)
 {
     TransactionMessageProperty property = GetPropertyAndThrowIfAlreadySet(message);
     property.flowedTransactionInfo = transactionInfo;
     message.Properties.Add(PropertyName, property);
 }
Example #20
0
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            try
            {
                var channelType = channel.GetType();

                var serverContext = new ServerApplicationContext();

                if (HttpContext.Current != null
                    && HttpContext.Current.Items != null
                    && HttpContext.Current.Items[AppInfoCenterConfiguration.Const.ContextIdentityKey] != null)
                {
                    serverContext.RequestIdentity = HttpContext.Current.Items[AppInfoCenterConfiguration.Const.ContextIdentityKey].ToString();
                }
                else if (CallContext.GetData(AppInfoCenterConfiguration.Const.ContextIdentityKey) != null)
                {
                    serverContext.RequestIdentity = CallContext.GetData(AppInfoCenterConfiguration.Const.ContextIdentityKey).ToString();
                }
                else
                {
                    serverContext.RequestIdentity = Guid.NewGuid().ToString();
                }

                var clientContext = new ClientApplicationContext();
                clientContext.RequestIdentity = serverContext.RequestIdentity;
                ClientApplicationContext.Current = clientContext;

                var setting = WcfSettingManager.CurrentClientSetting(channelType);
                var securitySetting = setting.WcfSecuritySetting;
                if (securitySetting.PasswordCheck.Enable)
                {
                    if (securitySetting.PasswordCheck.Direction == OperationDirection.Both || securitySetting.PasswordCheck.Direction == OperationDirection.Request)
                    {
                        serverContext.Password = securitySetting.PasswordCheck.Password;
                    }
                }

                var logSetting = setting.WcfLogSetting;
                if (logSetting.Enabled && logSetting.MessageInfoSetting.Enabled)
                {
                    var direct = logSetting.MessageInfoSetting.MessageDirection;
                    if (direct == MessageDirection.Both || direct == MessageDirection.Send)
                    {
                        var log = WcfLogProvider.GetClientMessageInfo(
                        channelType.FullName,
                        ClientApplicationContext.Current.RequestIdentity,
                        "ClientMessageInspector.BeforeSendRequest",
                        MessageDirection.Send,
                        request.ToString());
                        MongodbService.MongodbInsertService.Insert(log);
                    }
                }

                serverContext.ClientMachineIP = CommonConfiguration.MachineIP;

                if (!contractVersionCache.ContainsKey(channelType.FullName))
                {
                    lock (locker)
                    {
                        if (!contractVersionCache.ContainsKey(channelType.FullName))
                        {
                            contractVersionCache.Add(channelType.FullName, channelType.Assembly.GetName().Version.ToString());
                        }
                    }
                }
                serverContext.ClientVersion = contractVersionCache[channelType.FullName];
                request.SetApplicationContext(serverContext);

                return channelType;
            }
            catch (Exception ex)
            {
                ex.Handle(WcfLogProvider.ModuleName, "ClientMessageInspector" , "BeforeSendRequest");
            }
            return channel.GetType();
        }
Example #21
0
        // Invoke for case where call is in the same context as the server object
        // (This special static method is used for AsyncDelegate-s ... this is called
        // directly from the EE)
        private static void Invoke(Object NotUsed, ref MessageData msgData)
        {
            Message m = new Message();
            m.InitFields(msgData);

            Object thisPtr = m.GetThisPtr();
            Delegate d;
            if ((d = thisPtr as Delegate) != null)
            {
                RemotingProxy rp = (RemotingProxy)
                    RemotingServices.GetRealProxy(d.Target);

                if (rp != null)
                {
                    rp.InternalInvoke(m, true, m.GetCallType());
                }
                else
                {
                    int callType = m.GetCallType();
                    AsyncResult ar;
                    switch (callType)
                    {
                    case Message.BeginAsync:
                    case Message.BeginAsync | Message.OneWay:
                        // pick up call context from the thread
                        m.Properties[Message.CallContextKey] =
                            CallContext.GetLogicalCallContext().Clone();
                        ar = new AsyncResult(m);
                        AgileAsyncWorkerItem  workItem = 
                            new AgileAsyncWorkerItem(
                                    m, 
                                    ((callType & Message.OneWay) != 0) ? 
                                        null : ar, d.Target);

                        ThreadPool.QueueUserWorkItem(
                            new WaitCallback(
                                    AgileAsyncWorkerItem.ThreadPoolCallBack),
                            workItem);

                        if ((callType & Message.OneWay) != 0)
                        {
                            ar.SyncProcessMessage(null);
                        }
                        m.PropagateOutParameters(null, ar);
                        break;

                    case (Message.EndAsync | Message.OneWay):
                        return;

                    case Message.EndAsync:
                        // This will also merge back the call context
                        // onto the thread that called EndAsync
                        RealProxy.EndInvokeHelper(m, false);
                        break;
                    default:
                        BCLDebug.Assert(
                            false, 
                            "Should never be here. Sync delegate code for agile object ended up in remoting");
            break;
                    }
                }
            }
            else
            {
                // Static invoke called with incorrect this pointer ...
                throw new RemotingException(
                    Environment.GetResourceString(
                        "Remoting_Default"));                    
            }
        }
        static internal TransactionFlowProperty Ensure(Message message)
        {
            if (message.Properties.ContainsKey(PropertyName))
                return (TransactionFlowProperty)message.Properties[PropertyName];

            TransactionFlowProperty property = new TransactionFlowProperty();
            message.Properties.Add(PropertyName, property);
            return property;
        }
 internal AsyncResult(Message m)
 {
     m.GetAsyncBeginInfo(out _acbd, out _asyncState);
     _asyncDelegate = (Delegate) m.GetThisPtr();
 }
        private static void Main(string[] args)
        {
            RestRequest request;
            IRestResponse response;
            RestClient client;

            string deviceId;
            string password;
            string sessionId = "";

            Console.WriteLine("Run on local (\"l\" for local, ENTER for Azure)?");
            var tmp = Console.ReadLine();
            client = tmp == "l" ?
                new RestClient("http://localhost:49954")
                : new RestClient("http://qryptowire.azurewebsites.net");

            Console.WriteLine("DeviceId (hit ENTER for: \"asd\"):");
            deviceId = Console.ReadLine();
            if (deviceId == "")
            {
                deviceId = "asdxy";
            }
            Console.WriteLine("Password (hiy ENTER for: \"PASSWORD\"):");
            password = Console.ReadLine();
            if (password == "")
            {
                password = "******";
            }

            Console.WriteLine("For each test input \"n\" to cancel that test or ENTER to proceed.");
            Console.WriteLine();
            Console.WriteLine("Test /Register");
            if (Console.ReadLine() != "n")
            {
                Console.WriteLine("Starting test...");
                request = new RestRequest("api/Register", Method.POST);
                request.AddParameter("DeviceId", deviceId);
                request.AddParameter("Password", password);

                // execute the request
                response = client.Execute(request);
                Console.WriteLine(
                    "Status: "
                    + response.ResponseStatus + " | "
                    + response.StatusCode + " | "
                    + response.ErrorMessage
                    );
                Console.WriteLine(response.Content);
            }

            Console.WriteLine();
            Console.WriteLine("Testing /Login");
            if (Console.ReadLine() != "n")
            {
                Console.WriteLine("Starting test...");
                request = new RestRequest("api/Login", Method.POST);
                request.AddParameter("DeviceId", deviceId);
                request.AddParameter("Password", password);
                // execute the request
                response = client.Execute(request);

                Console.WriteLine(
                    "Status: "
                    + response.ResponseStatus + " | "
                    + response.StatusCode + " | "
                    + response.ErrorMessage
                    );
                var a = new char[1];
                a[0] = '\"';
                sessionId = response.Content.Trim(a);
                Console.WriteLine(sessionId);
            }

            Console.WriteLine();
            Console.WriteLine("Testing /SendMessage");
            if (Console.ReadLine() != "n")
            {
                Console.WriteLine("Starting test...");
                request = new RestRequest($"api/SendMessage/{sessionId}", Method.POST);
                var msg = new Message()
                {
                    Body = "ARAGoRn",
                    DateSent = DateTime.Now,
                    ReceiverId = 311,
                    SenderId = 311,
                    SessionKey = "aaa",
                    Signature = "bbb",
                    InitVector = "ccc"
                };
                request.AddJsonBody(msg);
                response = client.Execute(request);

                Console.WriteLine(
                    "Status: "
                    + response.ResponseStatus + " | "
                    + response.StatusCode + " | "
                    + response.ErrorMessage
                    );
                Console.WriteLine(response.Content);
            }

            Console.WriteLine();
            Console.WriteLine("Testing /FetchMessages");
            if (Console.ReadLine() != "n")
            {
                Console.WriteLine("Starting test...");
                request = new RestRequest($"api/FetchMessages/{sessionId}", Method.GET);
                response = client.Execute(request);

                Console.WriteLine(
                    "Status: "
                    + response.ResponseStatus + " | "
                    + response.StatusCode + " | "
                    + response.ErrorMessage
                    );
                Console.WriteLine(response.Content);
            }

            Console.WriteLine();
            Console.WriteLine("Testing /AddContact");
            if (Console.ReadLine() != "n")
            {
                Console.WriteLine("Starting test...");
                request = new RestRequest($"api/AddContact/{sessionId}", Method.POST);
                var con = new Contact()
                {
                    ReceiverId = 211,
                    Name = "Papa Urf",
                    PublicKey = "keypub2"
                };
                request.AddJsonBody(con);
                response = client.Execute(request);

                Console.WriteLine(
                    "Status: "
                    + response.ResponseStatus + " | "
                    + response.StatusCode + " | "
                    + response.ErrorMessage
                    );
                Console.WriteLine(response.Content);
            }

            Console.WriteLine();
            Console.WriteLine("Testing /FetchContacts");
            if (Console.ReadLine() != "n")
            {
                Console.WriteLine("Starting test...");
                request = new RestRequest($"api/FetchContacts/{sessionId}", Method.GET);
                response = client.Execute(request);

                Console.WriteLine(
                    "Status: "
                    + response.ResponseStatus + " | "
                    + response.StatusCode + " | "
                    + response.ErrorMessage
                    );
                Console.WriteLine(response.Content);
            }

            Console.WriteLine();
            Console.WriteLine("Testing /GetUserId");
            if (Console.ReadLine() != "n")
            {
                Console.WriteLine("Starting test...");
                request = new RestRequest($"api/GetUserId/{sessionId}", Method.GET);
                response = client.Execute(request);

                Console.WriteLine(
                    "Status: "
                    + response.ResponseStatus + " | "
                    + response.StatusCode + " | "
                    + response.ErrorMessage
                    );
                Console.WriteLine(response.Content);
            }

            Console.WriteLine();
            Console.WriteLine("Testing /RegisterPushToken");
            if (Console.ReadLine() != "n")
            {
                Console.WriteLine("Starting test...");
                request = new RestRequest($"api/RegisterPushToken/{sessionId}", Method.POST);
                request.AddJsonBody("ONOMATOPEJA");
                response = client.Execute(request);

                Console.WriteLine(
                    "Status: "
                    + response.ResponseStatus + " | "
                    + response.StatusCode + " | "
                    + response.ErrorMessage
                    );
                Console.WriteLine(response.Content);
            }
            Console.WriteLine();
            Console.WriteLine("Testing /SetPushAllowed true");
            if (Console.ReadLine() != "n")
            {
                Console.WriteLine("Starting test...");
                Console.WriteLine("Set false...");
                request = new RestRequest($"api/SetPushAllowed/{sessionId}", Method.POST);
                request.AddParameter("IsAllowed", false);
                response = client.Execute(request);

                Console.WriteLine(
                    "Status: "
                    + response.ResponseStatus + " | "
                    + response.StatusCode + " | "
                    + response.ErrorMessage
                    );
                Console.WriteLine(response.Content);

                Console.WriteLine("Check if false...");
                request = new RestRequest($"api/IsPushAllowed/{sessionId}", Method.GET);
                response = client.Execute(request);

                Console.WriteLine(
                    "Status: "
                    + response.ResponseStatus + " | "
                    + response.StatusCode + " | "
                    + response.ErrorMessage
                    );
                Console.WriteLine(response.Content);

                Console.WriteLine();
                Console.WriteLine("Set true...");
                request = new RestRequest($"api/SetPushAllowed/{sessionId}", Method.POST);
                request.AddParameter("IsAllowed", true);
                response = client.Execute(request);

                Console.WriteLine(
                    "Status: "
                    + response.ResponseStatus + " | "
                    + response.StatusCode + " | "
                    + response.ErrorMessage
                    );
                Console.WriteLine(response.Content);

                Console.WriteLine("Check if true...");
                request = new RestRequest($"api/IsPushAllowed/{sessionId}", Method.GET);
                response = client.Execute(request);

                Console.WriteLine(
                    "Status: "
                    + response.ResponseStatus + " | "
                    + response.StatusCode + " | "
                    + response.ErrorMessage
                    );
                Console.WriteLine(response.Content);
            }

            Console.WriteLine();
            Console.WriteLine("Testing /UnRegisterPushToken");
            if (Console.ReadLine() != "n")
            {
                Console.WriteLine("Starting test...");
                request = new RestRequest($"api/UnRegisterPushToken/{sessionId}", Method.GET);
                response = client.Execute(request);

                Console.WriteLine(
                    "Status: "
                    + response.ResponseStatus + " | "
                    + response.StatusCode + " | "
                    + response.ErrorMessage
                    );
                Console.WriteLine(response.Content);
            }
        }