Exemplo n.º 1
0
        public void unfreezeOperator(string op_url)
        {
            RemoteOperator rm_op = (RemoteOperator)Activator.GetObject(typeof(RemoteOperator), op_url);

            RemoteAsyncDelegate RemoteDel = new RemoteAsyncDelegate(rm_op.unfreeze);
            IAsyncResult        RemAr     = RemoteDel.BeginInvoke(null, null);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Makes an async remote invocation of TSpaceServer.ProcessRequest
        /// </summary>
        /// <param name="message">Argument of the ProcessRequest method.</param>
        /// <param name="asyncCallback">Callback function of the remote call.</param>
        private void Multicast(TSpaceMsg message, AsyncCallback asyncCallback)
        {
            //Never happens in this implementation
            if (message.Code.Equals("badView") && message.MsgView.ID > TSMan.ServerView.ID)
            {
                AcksCounter = 0;
            }

            List <ITSpaceServer> servers = TSMan.ServerView.GetProxys(TSMan.URL);
            RemoteAsyncDelegate  remoteDel;

            foreach (ITSpaceServer server in servers)
            {
                // Create delegate for remote method
                remoteDel = new RemoteAsyncDelegate(server.ProcessRequest);
                try
                {
                    // Call remote method
                    remoteDel.BeginInvoke(message, asyncCallback, null);
                }
                catch (Exception)
                {
                    Console.WriteLine("Failed to send");
                }
            }
        }
Exemplo n.º 3
0
        public override void execute(string[] args)
        {
            if (args.Length < 2)
            {
                throw new WrongNumberOfArgsException();
            }

            OperatorBuilder opb;
            int             repIndex;

            if ((opb = operatorsInfo.getOpInfo(args[0])) == null)
            {
                throw new WrongOperatorException();
            }

            if (!int.TryParse(args[1], out repIndex))
            {
                throw new WrongTypeOfArgException();
            }

            if (!(repIndex < opb.Addresses.Count && repIndex >= 0))
            {
                throw new IndexOutOfBoundsException();
            }

            ReplicaInterface    obj       = (ReplicaInterface)Activator.GetObject(typeof(ReplicaInterface), opb.Addresses[repIndex]);
            RemoteAsyncDelegate RemoteDel = new RemoteAsyncDelegate(obj.Unfreeze);
            IAsyncResult        RemAr     = RemoteDel.BeginInvoke(null, obj);
        }
Exemplo n.º 4
0
        /****************************************************************
        *                   CALLBACK FUNCTIONS
        ****************************************************************/
        private void PropesedSeqCallback(IAsyncResult result)
        {
            RemoteAsyncDelegate del = (RemoteAsyncDelegate)((AsyncResult)result).AsyncDelegate;

            // Retrieve results.
            TSpaceMsg response = del.EndInvoke(result);

            if (!ValidView(response))
            {
                return;
            }


            if (response.Code.Equals("proposedSeq"))
            {
                //Console.WriteLine("Proposed Seq");

                lock (ProposedSeq)
                {
                    // Store porposed sequence number
                    ProposedSeq.Add(response.SequenceNumber);
                    Interlocked.Increment(ref AcksCounter);
                }
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Send Commands to all the others Servers in an asyncronous way
        /// </summary>
        /// <param name="cmd"></param>
        public static void UpdateAll(Command cmd)
        {
            for (int i = 0; i < Server.AllServers.Count; i++)
            {
                if (Server.AllServers[i].ID == Server.My_Identification.ID) //Avoid sending to himself
                {
                    continue;
                }
                try
                {
                    ServerService       obj            = (ServerService)Activator.GetObject(typeof(ServerService), Server.AllServers[i].UID.AbsoluteUri + "MyRemoteObjectName");
                    RemoteAsyncDelegate RemoteDel      = new RemoteAsyncDelegate(obj.TakeCommand);
                    AsyncCallback       RemoteCallback = new AsyncCallback(OurRemoteAsyncCallBack);
                    IAsyncResult        RemAr          = RemoteDel.BeginInvoke(cmd, RemoteCallback, null);

                    Console.WriteLine("-------UpdateAll-------: {0}", Server.AllServers[i].UID.AbsoluteUri);
                }
                catch (Exception e)
                {
                    //Console.WriteLine("IN STATE_MACHINE_NETWORK_START: EXCEPTION");
                    Console.WriteLine("-------UpdateAll------- DEAD: {0}", Server.AllServers[i].UID.AbsoluteUri);
                    //Console.WriteLine(e);
                }
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Callback function for the read operation.
        /// </summary>
        /// <param name="result">Async callback result.</param>
        public void ReadCallback(IAsyncResult result)
        {
            RemoteAsyncDelegate del = (RemoteAsyncDelegate)((AsyncResult)result).AsyncDelegate;

            // Retrieve results.
            TSpaceMsg response = del.EndInvoke(result);

            if (!ValidView(response))
            {
                return;
            }

            // Stores the tuple returned
            // and the RequestID of the server that answered
            if (response.Code.Equals("OK"))
            {
                lock (LockRef)
                {
                    if (response.Tuple != null)
                    {
                        Tuple = response.Tuple;
                    }
                }
                IncrementAcksCounter(response.RequestID);
            }
        }
Exemplo n.º 7
0
 // This is the call that the AsyncCallBack delegate will reference.
 public void OurRemoteAsyncCallBack(IAsyncResult ar)
 {
     Monitor.Enter(this);
     try
     {
         try
         {
             RemoteAsyncDelegate del = (RemoteAsyncDelegate)((AsyncResult)ar).AsyncDelegate;
             _status = del.EndInvoke(ar);
             Console.WriteLine("\nSIGNALLED STATUS" + _status);
             waiter.Set();
             Thread.Sleep(WAIT_TIME);
         }
         catch (Exception e)
         {
             Console.WriteLine("Exception" + e.Message);
             _status = false;
             Console.WriteLine("\nFAILURE SIGNALLED STATUS" + _status);
             waiter.Set();
             Thread.Sleep(WAIT_TIME);
         }
         return;
     }
     finally
     {
         Monitor.Exit(this);
     }
 }
Exemplo n.º 8
0
        public static void Main(string [] args)
        {
            TcpChannel chan = new TcpChannel();
            ChannelServices.RegisterChannel(chan);

                ObjetoRemoto obj = (ObjetoRemoto) Activator.GetObject(
                typeof(TestCode.Remoting.ObjetoRemoto),
                    "tcp://127.0.0.1:9191/ObjetoRemoto");
                if( obj.Equals(null) )
                {
                    System.Console.WriteLine("Error: no se puede localizar el servidor");
                }
                else
                {
                    SampleClient client = new SampleClient();
                    AsyncCallback fin_llamada_asincrona = new AsyncCallback(client.fin_contador);
                    RemoteAsyncDelegate RemoteDel = new RemoteAsyncDelegate(obj.contador);
                    while (true){
                        Console.WriteLine("Empezar a contar");
                        Console.ReadLine();
                        IAsyncResult RemAr = RemoteDel.BeginInvoke(ref client.cuenta, fin_llamada_asincrona, null);

                        // Esperar a que la llamada termine: Si se quita while ya no espera
                        int y = 0;
                        while(!RemAr.IsCompleted){
                      //Console.WriteLine("Enviando petición al servidor, espere por favor: ");
                            //Console.WriteLine((++y));
                      Thread.Sleep(10);
                        }
                    }
                }
        }
Exemplo n.º 9
0
        private void ReadCallback(IAsyncResult result)
        {
            RemoteAsyncDelegate del = (RemoteAsyncDelegate)((AsyncResult)result).AsyncDelegate;

            // Retrieve results.
            TSpaceMsg response = del.EndInvoke(result);


            if (!ValidView(response))
            {
                return;
            }

            // Stores the tuple returned
            // and the OperationID of the server that answered
            if (response.Code.Equals("OK"))
            {
                if (response.Tuple != null)
                {
                    lock (LockRef)
                    {
                        Tuple = response.Tuple;
                    }
                    if (verbose)
                    {
                        Console.WriteLine("Response:");
                        Console.WriteLine(response);
                    }
                }

                Interlocked.Increment(ref AcksCounter);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Makes an async remote invocation of TSpaceServer.ProcessRequest
        /// </summary>
        /// <param name="message">Argument of the ProcessRequest method.</param>
        /// <param name="asyncCallback">Callback function of the remote call.</param>
        private void Multicast(TSpaceMsg message, AsyncCallback asyncCallback)
        {
            if (CheckNeedUpdateView())
            {
                Console.WriteLine("Update to " + GetCurrentView());
                message.MsgView = GetCurrentView();
            }

            //Console.WriteLine("Sending " + message.Code + " in view " + message.MsgView);

            RemoteAsyncDelegate remoteDel;

            foreach (ITSpaceServer server in View)
            {
                // Create delegate for remote method
                remoteDel = new RemoteAsyncDelegate(server.ProcessRequest);
                try
                {
                    // Call remote method
                    remoteDel.BeginInvoke(message, asyncCallback, null);
                }catch (Exception e)
                {
                    Console.WriteLine("Failed to send");
                }
            }
        }
Exemplo n.º 11
0
        private void WaitAnyCallback(IAsyncResult asyncResult)
        {
            AsyncResult         ar              = (AsyncResult)asyncResult;
            RemoteAsyncDelegate remoteDel       = (RemoteAsyncDelegate)ar.AsyncDelegate;
            Message             responseMessage = remoteDel.EndInvoke(asyncResult);
            CallbackState       state           = (CallbackState)ar.AsyncState;

            Message originalMessage = state.OriginalMessage;
            string  remoteUrl       = state.RemoteUrl;

            lock (ReplyResultQueue)
            {
                ReplyResultQueue.TryGetValue(originalMessage, out var replyResult);
                if (replyResult == null)
                {
                    return;
                }

                // save the result
                replyResult.AddResult(remoteUrl, responseMessage);

                // if ANY result, notify the caller (the one who initiated the multi-cast)
                if (replyResult.IsDone())
                {
                    PulseMessage(originalMessage);
                }
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Callback function for the phase 1 of the take operation.
        /// </summary>
        /// <param name="result">Async calback result.</param>
        public void Take1Callback(IAsyncResult result)
        {
            RemoteAsyncDelegate del = (RemoteAsyncDelegate)((AsyncResult)result).AsyncDelegate;

            // Retrieve results.
            TSpaceMsg response = del.EndInvoke(result);

            //Console.WriteLine("take1" + response);

            if (!ValidView(response))
            {
                return;
            }


            // Stores the list of matching tuples
            // and the RequestID of the server that answered
            if (response.Code.Equals("OK"))
            {
                // Tuples have to be added before the acks are incremented
                lock (MatchingTuples) {
                    MatchingTuples.Add(new List <ITuple>(response.Tuples));

                    Interlocked.Increment(ref AcksCounter);
                }
                if (verbose)
                {
                    Console.WriteLine("Response:");
                    Console.WriteLine(response);
                }
            }
        }
Exemplo n.º 13
0
 public void StartOp(string id)
 {
     foreach (string repl_url in operators[id].replicas_url)
     {
         RemoteAsyncDelegate RemoteDel = new RemoteAsyncDelegate(replicas_by_url[repl_url].Start);
         RemoteDel.BeginInvoke(null, null);
     }
 }
Exemplo n.º 14
0
 public void OurRemoteAsyncCallBack(IAsyncResult ar)
 {
     lock (_sync)
     {
         RemoteAsyncDelegate del = (RemoteAsyncDelegate)((AsyncResult)ar).AsyncDelegate;
         del.EndInvoke(ar);
         //e.Set();
     }
 }
Exemplo n.º 15
0
        // This is the call that the AsyncCallBack delegate will reference.
        public static void OurRemoteAsyncCallBack(IAsyncResult ar)
        {
            // Alternative 2: Use the callback to get the return value
            RemoteAsyncDelegate del = (RemoteAsyncDelegate)((AsyncResult)ar).AsyncDelegate;

            Console.WriteLine("\r\n**SUCCESS**: Result of the remote AsyncCallBack: " + del.EndInvoke(ar));

            return;
        }
Exemplo n.º 16
0
        public void crashOperator(string op_url)
        {
            try {
                RemoteOperator rm_op = (RemoteOperator)Activator.GetObject(typeof(RemoteOperator), op_url);

                RemoteAsyncDelegate RemoteDel = new RemoteAsyncDelegate(rm_op.crashOperator);
                IAsyncResult        RemAr     = RemoteDel.BeginInvoke(null, null);
            }
            catch { }
        }
Exemplo n.º 17
0
 internal void abort()
 {
     // If at least one participant responded 'no'
     foreach (String url in _participantURLs.Keys)
     {
         IParticipant participant = (IParticipant)Activator.GetObject(typeof(IParticipant), url);
         //participant.doCommit(TX.TXID, MY_URL);
         RemoteAsyncDelegate RemoteDel = new RemoteAsyncDelegate(participant.doAbort);
         // Call delegate to remote method
         IAsyncResult RemAr = RemoteDel.BeginInvoke(TX.TXID, MY_URL, null, null);
     }
 }
Exemplo n.º 18
0
        static public void create_replicas()
        {
            pcs_obj = (Ipcs)Activator.GetObject(typeof(Ipcs), "tcp://localhost:10000/pcs");

            funcaoCallBack = new AsyncCallback(OnExit);                                 //aponta para a função de retorno da função assincrona
            RemoteAsyncDelegate dele = new RemoteAsyncDelegate(pcs_obj.create_replica); //aponta para a função a ser chamada assincronamente

            foreach (Operator op in op_list)
            {
                IAsyncResult result = dele.BeginInvoke(op.rep_factor, op.address, op.operator_spec, op.operator_id, funcaoCallBack, null);
            }
        }
Exemplo n.º 19
0
    public void OurRemoteAsyncCallBack(IAsyncResult ar)
    {
        // ASyncResult encapsule le résultat issu d'un appel asynchrone ;
        // AsyncDelegate permet de récupérer l'objet delegate sur lequel l'appel asynchrone a été invoqué.
        // ligne suivante, on ne fait donc que récupérer dans del le delegate sur lequel l'appel asynchrone a été effectué
        RemoteAsyncDelegate del = (RemoteAsyncDelegate)((AsyncResult)ar).AsyncDelegate;

        Console.WriteLine("\r\n**SUCCESS**: Result of the remote AsyncCallBack: " + del.EndInvoke(ar));

        // Signal the thread. Set : événement signalé, les threads en attente peuvent poursuivre
        e.Set();
        return;
    }
 private void Crash(string serverId)
 {
     try
     {
         safeSleep();
         Puppet p = new Puppet(serverId, null);
         RemoteAsyncDelegate remDelegate = new RemoteAsyncDelegate(Servers[p].Crash);
         remDelegate.BeginInvoke(null, null);
         Servers.Remove(p);
     } catch (SocketException)
     {
         System.Console.WriteLine("Could not locate server");
     }
 }
Exemplo n.º 21
0
        static void Main()
        {
            // allocate and register channel
            TcpChannel channel = new TcpChannel();

            ChannelServices.RegisterChannel(channel, true);
            // get reference to remote service
            MyRemoteInterface obj = (MyRemoteInterface)Activator.GetObject(
                typeof(MyRemoteInterface),
                "tcp://localhost:8086/MyRemoteObjectName");

            try {
                // first a simple synchronous call
                Console.WriteLine(obj.MetodoOla());

                // change this to true to use the callback (alt.2)
                bool useCallback = false;

                if (!useCallback)
                {
                    // Alternative 1: asynchronous call without callback
                    // Create delegate to remote method
                    RemoteAsyncDelegate RemoteDel = new RemoteAsyncDelegate(obj.MetodoOla);
                    // Call delegate to remote method
                    IAsyncResult RemAr = RemoteDel.BeginInvoke(null, null);
                    // Wait for the end of the call and then explictly call EndInvoke
                    RemAr.AsyncWaitHandle.WaitOne();
                    Console.WriteLine(RemoteDel.EndInvoke(RemAr));
                }
                else
                {
                    // Alternative 2: asynchronous call with callback
                    // Create delegate to remote method
                    RemoteAsyncDelegate RemoteDel = new RemoteAsyncDelegate(obj.MetodoOla);
                    // Create delegate to local callback
                    AsyncCallback RemoteCallback = new AsyncCallback(Client.OurRemoteAsyncCallBack);
                    // Call remote method
                    IAsyncResult RemAr = RemoteDel.BeginInvoke(RemoteCallback, null);
                }
            }
            catch (SocketException) {
                System.Console.WriteLine("Could not locate server");
            }
            catch (MyException e) {
                Console.WriteLine("I caught an exception: " + e.campo);
                Console.WriteLine("I caught an exception: " + e.mo.OlaSemExcepcao());
            }

            Console.ReadLine();
        }
Exemplo n.º 22
0
        private void MulticastSingleUrl(string remoteURL, Message message, AsyncCallback asyncCallback)
        {
            var remotingEndpoint = GetRemoteEndpoint(remoteURL);

            try {
                RemoteAsyncDelegate remoteDel = remotingEndpoint.OnReceiveMessage;
                CallbackState       state     = new CallbackState(message, remoteURL);
                remoteDel.BeginInvoke(message, asyncCallback, state);
            }
            catch (Exception e) {
                Log("Server at " + remoteURL + " is unreachable.");
                throw;
            }
        }
Exemplo n.º 23
0
        public override void doOperation(Tuple input)
        {
            this.tupleCounter++;
            this.result = Tuple.fromString(this.tupleCounter.ToString());
            for (int i = 0; i < replicas_url.Length; i++)
            {
                if (String.Compare(op_url, replicas_url[i]) != 0)
                {
                    Count count_op = (Count)Activator.GetObject(typeof(Count), replicas_url[i]);

                    RemoteAsyncDelegate RemoteDel = new RemoteAsyncDelegate(count_op.updateCount);
                    IAsyncResult        RemAr     = RemoteDel.BeginInvoke(null, null);
                }
            }
        }
Exemplo n.º 24
0
 public Message SendMessageToRemote(RemotingEndpoint remotingEndpoint, Message message)
 {
     try {
         RemoteAsyncDelegate remoteDel = new RemoteAsyncDelegate(remotingEndpoint.OnReceiveMessage);
         IAsyncResult        ar        = remoteDel.BeginInvoke(message, null, null);
         //ar.AsyncWaitHandle.WaitOne();
         // This should not be necessary, since EndInvoke already waits for completion
         // unless we want to provide a timeout a do something with it
         return(remoteDel.EndInvoke(ar));
     }
     catch (Exception e) {
         Log("Server at " + remotingEndpoint.EndpointURL + " is unreachable. (For more detail: " + e.Message + ")");
         throw new SocketException();
     }
 }
 private void Status()
 {
     try
     {
         safeSleep();
         foreach (IMSDADServerPuppet server in Servers.Values)
         {
             RemoteAsyncDelegate remDelegate = new RemoteAsyncDelegate(server.Status);
             remDelegate.BeginInvoke(null, null);
         }
     } catch (SocketException)
     {
         System.Console.WriteLine("Could not locate server");
     }
 }
Exemplo n.º 26
0
        public void Run(object[] ClientInfo, string ModuleName, string MethodName, object[]objParams, CliUtils.CallBack justdo)
        {
            // Enable this and the e.WaitOne call at the bottom if you
            // are going to make more than one asynchronous call.
            fjustdo = justdo;

            e = new ManualResetEvent(false);

            // This is the only thing you must do in a remoting scenario
            // for either synchronous or asynchronous programming
            // configuration.

            // The remaining steps are identical to single-
            // AppDomain programming.
            /*Rich marked...
            ServiceClass obj = new ServiceClass();
             * */

            // This delegate is an asynchronous delegate. Two delegates must
            // be created. The first is the system-defined AsyncCallback
            // delegate, which references the method that the remote type calls
            // back when the remote method is done.

            AsyncCallback RemoteCallback = new AsyncCallback(this.OurRemoteAsyncCallBack);

            // Create the delegate to the remote method you want to use
            // asynchronously.
            RemoteAsyncDelegate RemoteDel = new RemoteAsyncDelegate(CliUtils.RemoteObject.CallMethod);

            // Start the method call. Note that execution on this
            // thread continues immediately without waiting for the return of
            // the method call.
            IAsyncResult RemAr = RemoteDel.BeginInvoke(ClientInfo, ModuleName, MethodName, objParams, RemoteCallback, null);
            //已经调用方法了...

            // If you want to stop execution on this thread to
            // wait for the return from this specific call, retrieve the
            // IAsyncResult returned from the BeginIvoke call, obtain its
            // WaitHandle, and pause the thread, such as the next line:
            // RemAr.AsyncWaitHandle.WaitOne();

            // To wait in general, if, for example, many asynchronous calls
            // have been made and you want notification of any of them, or,
            // like this example, because the application domain can be
            // recycled before the callback can print the result to the
            // console.
            //e.WaitOne();
        }
Exemplo n.º 27
0
        // TODO: should run a separate thread to receive replies
        // only the coordinator should call this
        internal void prepare()
        {
            lock (_participantURLs)
            {
                Console.WriteLine("I'm the coordinator: " + MY_URL);
                if (_participantURLs.Count > 0)
                {
                    foreach (String url in _participantURLs.Keys)
                    {
                        // TODO: A thread per participant
                        // after all thread are sent, create one main thread responsible
                        // for receiving votes (yes or no) - Assync callback (ver exemplo da aula 4)
                        // and another one to run the timer
                        Console.WriteLine("URL: " + url);
                        IParticipant participant = (IParticipant)Activator.GetObject(typeof(IParticipant), url);
                        //participant.canCommit(TX.TXID, MY_URL);

                        // Create delegate to remote method
                        RemoteAsyncDelegate RemoteDel = new RemoteAsyncDelegate(participant.canCommit);
                        // Call delegate to remote method
                        IAsyncResult RemAr = RemoteDel.BeginInvoke(TX.TXID, MY_URL, null, null);
                        // Wait for the end of the call and then explictly call EndInvoke
                        //RemAr.AsyncWaitHandle.WaitOne();
                        //Console.WriteLine(RemoteDel.EndInvoke(RemAr));
                    }
                    timer(10000);
                    MY_DECISION = waitParticipantsResponse();
                    evaluateMyDecision();
                }
                else
                {
                    // Coordinator decision
                    // Default commit
                    MY_DECISION = TransactionDecision.COMMIT;
                    Console.WriteLine("AFTER MY_DECISION is commit and there are no participants");

                    // Send an update to the replica if there is one

                    Replica.updateSucessor(TX.WRITTENOBJECTS);
                }
                // First phase of commit, temporary write to disk
                //writeAheadLog();

                // if (MY_DECISION.Equals(TransactionDecision.COMMIT))
                //writePermanentLog();
            }
        }
Exemplo n.º 28
0
 public void AsyncCall()
 {
     //e = new ManualResetEvent(false);
     try
     {
         string serviceUrl                    = System.Configuration.ConfigurationManager.AppSettings["ServiceURL"];
         RemoteObject.MyObject app            = (RemoteObject.MyObject)Activator.GetObject(typeof(RemoteObject.MyObject), serviceUrl);
         AsyncCallback         RemoteCallback = new AsyncCallback(this.OurRemoteAsyncCallBack);
         RemoteAsyncDelegate   RemoteDel      = new RemoteAsyncDelegate(app.TimeConsumingRemoteCall);
         IAsyncResult          RemAr          = RemoteDel.BeginInvoke(RemoteCallback, null);
         Response.Write("Async Function calling... ");
         RemAr.AsyncWaitHandle.WaitOne();
     }
     catch (Exception)
     {
     }
 }
Exemplo n.º 29
0
        /***********************************************************
        *                  CALLBACK FUNCTIONS
        ***********************************************************/

        /// <summary>
        /// Callback function for the acknowledgements.
        /// </summary>
        /// <param name="result">Async callback result.</param>
        public void AddCallback(IAsyncResult result)
        {
            RemoteAsyncDelegate del = (RemoteAsyncDelegate)((AsyncResult)result).AsyncDelegate;
            // Retrieve results.
            TSpaceMsg response = del.EndInvoke(result);


            if (!ValidView(response))
            {
                return;
            }

            if (response.Code.Equals("ACK"))
            {
                IncrementAcksCounter(response.RequestID);
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// Callback function for the acknowledgements.
        /// </summary>
        /// <param name="result">Async call result.</param>
        private void AcksCallback(IAsyncResult result)
        {
            RemoteAsyncDelegate del = (RemoteAsyncDelegate)((AsyncResult)result).AsyncDelegate;
            // Retrieve results.
            TSpaceMsg response = del.EndInvoke(result);

            if (!ValidView(response))
            {
                return;
            }


            if (response.Code.Equals("ACK"))
            {
                Interlocked.Increment(ref AcksCounter);
            }
        }
Exemplo n.º 31
0
        // send and ignore result
        // can throw exception
        public IAsyncResult NewSendMessageToRemoteURL(string remoteURL, Message message)
        {
            var remotingEndpoint = GetRemoteEndpoint(remoteURL);

            try {
                RemoteAsyncDelegate remoteDel = remotingEndpoint.OnReceiveMessage;
                return(remoteDel.BeginInvoke(message, delegate(IAsyncResult ar)
                {
                    var result = (AsyncResult)ar;
                    var caller = (RemoteAsyncDelegate)result.AsyncDelegate;
                    caller.EndInvoke(ar);
                }, null));
            }
            catch (Exception e) {
                Log("Server at " + remoteURL + " is unreachable.");
                throw;
            }
        }
Exemplo n.º 32
0
 public void Status()
 {
     foreach (string op_id in operators.Keys)
     {
         foreach (string repl_url in operators[op_id].replicas_url)
         {
             RemoteAsyncDelegate RemoteDel = new RemoteAsyncDelegate(() => {
                 try{
                     replicas_by_url[repl_url].Status();
                 }catch (Exception) {
                     Console.WriteLine("Replica crashed!");
                     log("[" + op_id + " " + repl_url + "] crashed!");
                 }
             });
             RemoteDel.BeginInvoke(null, null);
         }
     }
 }
Exemplo n.º 33
0
        public void Send(Message m, string uri)
        {
            // If channel is paused, then throw exception
            // so that deferred send continues after
            // the client re-connects

            m.SetSourceUri (GetURI ());

            // get reference to remote object
            PointToPointInterface p2p_send;
            if (m_dummy == null)
            {
                DebugLogic ("Sending to {0}", uri);
                p2p_send = (PointToPointInterface) Activator.GetObject (typeof (PointToPointInterface), uri);
            }
            else
            {
                p2p_send = m_dummy;
            }

            // ohoy!
            if (p2p_send == null)
            {
                DebugLogic ("Crash! Cannot find recipient: {0}", uri);
            }
            else
            {
                AsyncCallback cb = new AsyncCallback(MyCallBack);
                RemoteAsyncDelegate d = new RemoteAsyncDelegate (p2p_send.Deliver);
                d.BeginInvoke(m, cb, null);

                e.WaitOne ();
            }
        }
Exemplo n.º 34
0
        /// <summary>
        /// Method the will be called by the threads the DisseminateReservationw will create.
        /// This method will make a remote call to a specific user (proxy)
        /// </summary>
        /// <param name="proxy"></param>
        /// <param name="reservation"></param>
        /// 
        private void CallSendReservation(object context)
        {
            Console.WriteLine("[Calling] CallSendReservation");
            lock (User.userLoger)
            {
                User.userLoger.IncrementNumberOfExchangedMessages("CallSendReservation");
            }
            ThreadInfo threadInfo = context as ThreadInfo;
            UserInterface proxy = threadInfo.proxy;
            Reservation reservation = threadInfo.reservationMessage.reservation;
            Console.WriteLine("Thread Number: " + threadInfo.threadNumber);

            ReservationMessage response = null;
            RemoteAsyncDelegate remoteDelegate = new RemoteAsyncDelegate(proxy.SendReservation);

            String userName = threadInfo.userName;
            int originalMessageCounter = threadInfo.reservationMessage.messageCounter;

            String threadName = Thread.CurrentThread.Name;

            JacobsonKarels timeoutAlgoritm = User.KnownUsersTimeout[userName];
            timeoutAlgoritm.ModifiedUpdateTimeout();

            int timeout = timeoutAlgoritm.GetTimeout();

            //dissemination
            if (threadName.Length == 3)
            {
                timeout = timeout / 2;
            }

            IAsyncResult result = remoteDelegate.BeginInvoke(threadInfo.reservationMessage, timeout, null, null);
            //colocar timeout dinamico!
            bool responseInTime = result.AsyncWaitHandle.WaitOne(timeout, true);

            Console.WriteLine("Work time is over! Response in time? " + responseInTime);

            //didn't get a response till timeout
            if (responseInTime == false) {
                Console.WriteLine("Timeout! Did not receive any answer!");
                result.AsyncWaitHandle.Close();
                response = new ReservationMessage();
                //add an empty dicionary indicating that the user did not answered
                response.AddSlotResponse(userName, new Dictionary<int, String>());
                result.AsyncWaitHandle.Close();
            }
            else {
                IncrementUserTrust(threadInfo.userName);
                response = remoteDelegate.EndInvoke(result);
                Console.WriteLine("Received: " + response);
                result.AsyncWaitHandle.Close();
            }

            String currentThreadName = Thread.CurrentThread.Name;
            char[] separator = { ' ' };
            String[] splitedThreadName = currentThreadName.Split(separator);
            String currentThreadNumber = splitedThreadName[0];
            int currentTNumber = int.Parse(currentThreadNumber);

            if (threadResponses.ContainsKey(currentTNumber)) {
                threadResponses.Remove(currentTNumber);
            }

            //adds the response the response dicionary
            //if is the retry
            if (originalMessageCounter < 0) {
                if (threadResponses2.ContainsKey(threadInfo.userName))
                    threadResponses2.Remove(threadInfo.userName);
                threadResponses2.Add(threadInfo.userName, response);
            }
            else
                threadResponses.Add(threadInfo.threadNumber, response);
        }
Exemplo n.º 35
0
        private void CallCommitReservation(object context)
        {
            ThreadInfo threadInfo = context as ThreadInfo;
            UserInterface proxy = threadInfo.proxy;
            Console.WriteLine("Thread Number: " + threadInfo.threadNumber);
            lock (User.userLoger)
            {
                User.userLoger.IncrementNumberOfExchangedMessages("CallCommitReservation");
            }
            ReservationMessage response = null;
            RemoteAsyncDelegate remoteDelegate = new RemoteAsyncDelegate(proxy.CommitReservation);

            String userName = threadInfo.userName;

            JacobsonKarels timeoutAlgoritm = User.KnownUsersTimeout[userName];
            timeoutAlgoritm.ModifiedUpdateTimeout();

            int timeout = timeoutAlgoritm.GetTimeout();

            IAsyncResult result = remoteDelegate.BeginInvoke(threadInfo.reservationMessage, timeout, null, null);
            bool responseInTime = result.AsyncWaitHandle.WaitOne(timeout, true);

            Console.WriteLine("Work time is over! Response in time? " + responseInTime);

            //didn't get a response till timeout
            if (responseInTime == false)
            {
                Console.WriteLine("Timeout! Did not receive any answer!");
                result.AsyncWaitHandle.Close();
                return;
            }
            IncrementUserTrust(threadInfo.userName);
            response = remoteDelegate.EndInvoke(result);
            Console.WriteLine("Commit!");
            result.AsyncWaitHandle.Close();
            return;
        }
Exemplo n.º 36
0
        private void CallTwoPhaseCommit(object context)
        {
            ThreadInfo threadInfo = context as ThreadInfo;
            UserInterface proxy = threadInfo.proxy;
            Console.WriteLine("Thread Number: " + threadInfo.threadNumber);
            lock (User.userLoger)
            {
                User.userLoger.IncrementNumberOfExchangedMessages("CallTwoPhaseCommit");
            }
            ReservationMessage response = new ReservationMessage();
            RemoteAsyncDelegate remoteDelegate = new RemoteAsyncDelegate(proxy.TwoPhaseCommit);

            String userName = threadInfo.userName;

            JacobsonKarels timeoutAlgoritm = User.KnownUsersTimeout[userName];
            timeoutAlgoritm.ModifiedUpdateTimeout();

            int timeout = timeoutAlgoritm.GetTimeout();

            IAsyncResult result = remoteDelegate.BeginInvoke(threadInfo.reservationMessage, timeout, null, null);
            bool responseInTime = result.AsyncWaitHandle.WaitOne(timeout, true);

            Console.WriteLine("Work time is over! Response in time? " + responseInTime);

            //didn't get a response till timeout
            if (responseInTime == false)
            {
                Console.WriteLine("Timeout! Did not receive any answer!");
                if(!response.response2PC.ContainsKey(userName))
                    response.response2PC.Add(userName,"Timeout");;
                result.AsyncWaitHandle.Close();
                return;
            }

            if (!response.response2PC.ContainsKey(userName))
                 response.response2PC.Add(userName, "YES");
            IncrementUserTrust(threadInfo.userName);
            response = remoteDelegate.EndInvoke(result);
            Console.WriteLine("Can Commit!");
            result.AsyncWaitHandle.Close();

            String currentThreadName = Thread.CurrentThread.Name;
            char[] separator = { ' ' };
            String[] splitedThreadName = currentThreadName.Split(separator);
            String currentThreadNumber = splitedThreadName[0];
            int currentTNumber = int.Parse(currentThreadNumber);

            if (threadResponses.ContainsKey(currentTNumber))
            {
                threadResponses.Remove(currentTNumber);
            }

            int originalMessageCounter = threadInfo.reservationMessage.messageCounter;
            //if is the retry
            if (originalMessageCounter < 0)
            {
                if (threadResponses2.ContainsKey(threadInfo.userName))
                    threadResponses2.Remove(threadInfo.userName);
                threadResponses2.Add(threadInfo.userName, response);
            }
            else
                threadResponses.Add(threadInfo.threadNumber, response);
        }
Exemplo n.º 37
0
    public void Run()
    {
        // Enable this and the e.WaitOne call at the bottom if you
        // are going to make more than one asynchronous call.
        e = new ManualResetEvent(false); // false : evt non signalé

        Console.WriteLine("Remote synchronous and asynchronous delegates.");
        Console.WriteLine(new String('-',80));
        Console.WriteLine();

        // This is the only thing you must do in a remoting scenario
        // for either synchronous or asynchronous programming
        // configuration.
        RemotingConfiguration.Configure("SyncAsync.exe.config", true);

        // The remaining steps are identical to single-
        // AppDomain programming. Sauf si on veut utiliser la ligne suivante, plus prudente qu'un new
           // ServiceClass obj = (ServiceClass)Activator.GetObject(typeof(ServiceClass), "tcp://localhost:8085/ServiceClass.rem");
        ServiceClass obj = new ServiceClass(); // attention, on récupère un proxy ...

        // This delegate is a remote synchronous delegate.
        RemoteSyncDelegate Remotesyncdel = new RemoteSyncDelegate(obj.VoidCall);

        // When invoked, program execution waits until the method returns.
        // This delegate can be passed to another application domain
        // to be used as a callback to the obj.VoidCall method.
        Console.WriteLine(Remotesyncdel());
        Console.WriteLine("Pause 1");
        Console.Read();
        // This delegate is an asynchronous delegate. Two delegates must
        // be created. The first is the system-defined AsyncCallback
        // delegate, which references the method that the remote type calls
        // back when the remote method is done.

        AsyncCallback RemoteCallback = new AsyncCallback(this.OurRemoteAsyncCallBack);

        // Create the delegate to the remote method you want to use
        // asynchronously.
        RemoteAsyncDelegate RemoteDel = new RemoteAsyncDelegate(obj.TimeConsumingRemoteCall);

        // Start the method call. Note that execution on this
        // thread continues immediately without waiting for the return of
        // the method call.
        IAsyncResult RemAr = RemoteDel.BeginInvoke(RemoteCallback, null); // BeginInvoke est générée : prend d'abord les paramètres s'il y en a (ici : non, TimeConsumingRemoteCall ne prend pas de param), puis le callback, puis un objet qcq, qui peut être utile par exemple à passer des informations d'état)
        Console.WriteLine("Pause 2");
        Console.Read();
        // If you want to stop execution on this thread to
        // wait for the return from this specific call, retrieve the
        // IAsyncResult returned from the BeginIvoke call, obtain its
        // WaitHandle, and pause the thread, such as the next line:
        // RemAr.AsyncWaitHandle.WaitOne();

        // To wait in general, if, for example, many asynchronous calls
        // have been made and you want notification of any of them, or,
        // like this example, because the application domain can be
        // recycled before the callback can print the result to the
        // console.
        //e.WaitOne();

           // This simulates some other work going on in this thread while the
           // async call has not returned.
           int count = 0;
           while(!RemAr.IsCompleted){
          Console.Write("\rNot completed: " + (++count).ToString());
          // Make sure the callback thread can invoke callback.
          Thread.Sleep(1);
           }
           Console.Read();
    }