示例#1
0
        protected void HandlePendingCallResult(RtmpConnection connection, Notify invoke)
        {
            IServiceCall        serviceCall = invoke.ServiceCall;
            IPendingServiceCall pendingCall = connection.GetPendingCall(invoke.InvokeId);

            if (pendingCall != null)
            {
                pendingCall.Status = serviceCall.Status;
                object[] arguments = serviceCall.Arguments;
                if ((arguments != null) && (arguments.Length > 0))
                {
                    pendingCall.Result = arguments[0];
                }
                IPendingServiceCallback[] callbacks = pendingCall.GetCallbacks();
                if ((callbacks != null) && (callbacks.Length > 0))
                {
                    foreach (IPendingServiceCallback callback in callbacks)
                    {
                        try
                        {
                            callback.ResultReceived(pendingCall);
                        }
                        catch (Exception exception)
                        {
                            log.Error("Error while executing callback " + callback, exception);
                        }
                    }
                }
            }
        }
示例#2
0
文件: Activity.cs 项目: ForNeVeR/pnet
 // Run a batch item sychronously.
 public void SynchronousCall(IServiceCall serviceCall)
 {
     if (serviceCall != null)
     {
         serviceCall.OnCall();
     }
 }
示例#3
0
	// Run a batch item sychronously.
	public void SynchronousCall(IServiceCall serviceCall)
			{
				if(serviceCall != null)
				{
					serviceCall.OnCall();
				}
			}
        private bool ThereIsSupportForBothContriesInCall(IServiceCall call)
        {
            var chargesWhichSupportTheCallType = GetServiceChargesWhichSupportTheCall(call);

            return    HasChargeWithSameCountry(chargesWhichSupportTheCallType, call.FromCountry)
                   && HasChargeWithSameCountry(chargesWhichSupportTheCallType, call.ToCountry);
        }
示例#5
0
 internal Notify() : base(EventType.SERVICE_CALL)
 {
     this._serviceCall = null;
     this._data        = null;
     this._invokeId    = 0;
     base._dataType    = 0x12;
 }
        /// <exception cref="IngestionException"/>
        public async Task ExecuteCallAsync(IServiceCall call)
        {
            if (call.CancellationToken.IsCancellationRequested)
            {
                return;
            }
            var baseUrl = string.IsNullOrEmpty(_baseLogUrl) ? DefaultBaseUrl : _baseLogUrl;

            MobileCenterLog.Verbose(MobileCenterLog.LogTag, $"Calling {baseUrl + ApiVersion}...");

            // Create request headers.
            var requestHeaders = CreateHeaders(call.AppSecret, call.InstallId);

            MobileCenterLog.Verbose(MobileCenterLog.LogTag, "Headers: " +
                                    $"{AppSecret}={GetRedactedAppSecret(call.AppSecret)}, " +
                                    $"{InstallId}={call.InstallId}");

            // Create request content.
            var requestContent = CreateLogsContent(call.Logs);

            MobileCenterLog.Verbose(MobileCenterLog.LogTag, requestContent);

            // Send request.
            await _httpNetwork.SendAsync(baseUrl + ApiVersion, HttpMethod.Post, requestHeaders, requestContent, call.CancellationToken).ConfigureAwait(false);
        }
示例#7
0
 public void Notify(IServiceCall serviceCall, byte channel)
 {
     FluorineFx.Messaging.Rtmp.Event.Notify message = new FluorineFx.Messaging.Rtmp.Event.Notify {
         ServiceCall = serviceCall
     };
     this.GetChannel(channel).Write(message);
 }
示例#8
0
        /// <summary>
        /// Handler for pending call result. Dispatches results to all pending call handlers.
        /// </summary>
        /// <param name="connection">Connection.</param>
        /// <param name="invoke">Pending call result event context.</param>
        protected void HandlePendingCallResult(RtmpConnection connection, Notify invoke)
        {
            IServiceCall        call        = invoke.ServiceCall;
            IPendingServiceCall pendingCall = connection.RetrievePendingCall(invoke.InvokeId);

            if (pendingCall != null)
            {
                pendingCall.Status = call.Status;
                // The client sent a response to a previously made call.
                object[] args = call.Arguments;
                if ((args != null) && (args.Length > 0))
                {
                    pendingCall.Result = args[0];
                }

                IPendingServiceCallback[] callbacks = pendingCall.GetCallbacks();
                if (callbacks != null && callbacks.Length > 0)
                {
                    foreach (IPendingServiceCallback callback in callbacks)
                    {
                        try {
                            callback.ResultReceived(pendingCall);
                        } catch (Exception ex) {
#if !SILVERLIGHT
                            log.Error("Error while executing callback " + callback, ex);
#endif
                        }
                    }
                }
            }
        }
 public void Validate(IServiceCall call)
 {
     if (ServiceCallSupportedBySubscription(call) == false)
     {
         throw new ServiceNotSupportedBySubscriptionException(call);
     }
 }
 public void Validate(IServiceCall call)
 {
     if (call.IsValid() == false)
     {
         throw new InvalidCallException(call);
     }
 }
 public void Validate(IServiceCall call)
 {
     if (ThereIsSupportForBothContriesInCall(call) == false)
     {
         throw new CountriesNotSupportedBySubscriptionException(call);
     }
 }
示例#12
0
		public bool ServiceCall(IConnection connection, IServiceCall call) {
			IScopeContext context = connection.Scope.Context;
			if (call.ServiceName != null) {
				context.ServiceInvoker.Invoke(call, context);
			} else {
				context.ServiceInvoker.Invoke(call, connection.Scope.Handler);
			}
			return true;
		}
示例#13
0
        public static void InvokeCall(RtmpConnection connection, IServiceCall serviceCall)
        {
            IScope scope = connection.Scope;

            if (!scope.HasHandler || scope.Handler.ServiceCall(connection, serviceCall))
            {
                scope.Context.ServiceInvoker.Invoke(serviceCall, scope);
            }
        }
        private void GenerateRecord(IServiceCharge charge, IServiceCall call)
        {
            var newRecord = new Record(call.PhoneNumber,
                                       call.GetStartTime(),
                                       charge.Description,
                                       call.ToString(),
                                       charge.CalculateCharge(call));

            _recordRepository.SaveRecord(newRecord);
        }
        static ByteBuffer EncodeNotifyOrInvoke(RtmpContext context, Notify invoke)
        {
            //MemoryStreamEx output = new MemoryStreamEx();
            ByteBuffer output = ByteBuffer.Allocate(1024);

            output.AutoExpand = true;
            RtmpWriter writer = new RtmpWriter(output);

            //Set legacy collection flag from context
            writer.UseLegacyCollection = context.UseLegacyCollection;
            writer.UseLegacyThrowable  = context.UseLegacyThrowable;

            IServiceCall serviceCall = invoke.ServiceCall;
            bool         isPending   = serviceCall.Status == Call.STATUS_PENDING;

            if (!isPending)
            {
                //log.debug("Call has been executed, send result");
                writer.WriteData(context.ObjectEncoding, serviceCall.IsSuccess ? "_result" : "_error");
            }
            else
            {
                //log.debug("This is a pending call, send request");
                string action = (serviceCall.ServiceName == null) ? serviceCall.ServiceMethodName : serviceCall.ServiceName + "." + serviceCall.ServiceMethodName;
                writer.WriteData(context.ObjectEncoding, action);
            }
            if (invoke is Invoke)
            {
                writer.WriteData(context.ObjectEncoding, invoke.InvokeId);
                writer.WriteData(context.ObjectEncoding, invoke.ConnectionParameters);
            }
            if (!isPending && (invoke is Invoke))
            {
                IPendingServiceCall pendingCall = (IPendingServiceCall)serviceCall;
                if (!serviceCall.IsSuccess && !(pendingCall.Result is StatusASO))
                {
                    StatusASO status = GenerateErrorResult(StatusASO.NC_CALL_FAILED, serviceCall.Exception);
                    pendingCall.Result = status;
                }
                writer.WriteData(context.ObjectEncoding, pendingCall.Result);
            }
            else
            {
                //log.debug("Writing params");
                object[] args = invoke.ServiceCall.Arguments;
                if (args != null)
                {
                    foreach (object element in args)
                    {
                        writer.WriteData(context.ObjectEncoding, element);
                    }
                }
            }
            return(output);
        }
示例#16
0
		public bool Invoke(IServiceCall call, IScope scope) {
			string serviceName = call.ServiceName;
			object service = GetServiceHandler(scope, serviceName);

			if (service == null) {
				call.Exception = new ServiceNotFoundException(serviceName);
				call.Status = Call.STATUS_SERVICE_NOT_FOUND;
				return false;
			}
			return Invoke(call, service);
		}
        public override async Task ExecuteCallAsync(IServiceCall call)
        {
            var retryableCall = call as RetryableServiceCall;

            if (retryableCall == null)
            {
                await base.ExecuteCallAsync(call).ConfigureAwait(false);

                return;
            }
            await retryableCall.ExecuteAsync().ConfigureAwait(false);
        }
示例#18
0
 public void Effect(IServiceCall effect, bool synchronous = false)
 {
     ActivatableContext.CheckActive();
     Effects.Add(
         new SideEffect
     {
         ServiceName = effect.Ref.Method.Service.FullName,
         CommandName = effect.Ref.Method.Name,
         Payload     = Any.Pack(effect.Message),
         Synchronous = synchronous
     }
         );
 }
示例#19
0
        public bool Invoke(IServiceCall call, IScope scope)
        {
            string serviceName = call.ServiceName;
            object service     = GetServiceHandler(scope, serviceName);

            if (service == null)
            {
                call.Exception = new ServiceNotFoundException(serviceName);
                call.Status    = Call.STATUS_SERVICE_NOT_FOUND;
                return(false);
            }
            return(Invoke(call, service));
        }
        private void SetupEventCallbacks(IServiceCall call)
        {
            foreach (var sem in _eventSemaphores)
            {
                if (sem.CurrentCount != 0)
                {
                    sem.Release(sem.CurrentCount);
                }
            }

            call.ServiceCallSucceededCallback += () => _eventSemaphores[SucceededCallbackSemaphoreIdx].Release();
            call.ServiceCallFailedCallback    += (e) => _eventSemaphores[FailedCallbackSemaphoreIdx].Release();
        }
示例#21
0
        /// <summary>
        /// Remoting call invocation handler.
        /// </summary>
        /// <param name="connection">RTMP connection.</param>
        /// <param name="serviceCall">Service call.</param>
        /// <param name="service">Server-side service object.</param>
        /// <returns><code>true</code> if the call was performed, otherwise <code>false</code>.</returns>
        private static bool InvokeCall(RtmpConnection connection, IServiceCall serviceCall, object service)
        {
            IScope        scope   = connection.Scope;
            IScopeContext context = scope.Context;

            if (log.IsDebugEnabled)
            {
                log.Debug("Scope: " + scope);
                log.Debug("Service: " + service);
                log.Debug("Context: " + context);
            }
            return(context.ServiceInvoker.Invoke(serviceCall, service));
        }
示例#22
0
        public bool ServiceCall(IConnection connection, IServiceCall call)
        {
            IScopeContext context = connection.Scope.Context;

            if (call.ServiceName != null)
            {
                context.ServiceInvoker.Invoke(call, context);
            }
            else
            {
                context.ServiceInvoker.Invoke(call, connection.Scope.Handler);
            }
            return(true);
        }
示例#23
0
 public void Invoke(IServiceCall serviceCall, byte channel)
 {
     FluorineFx.Messaging.Rtmp.Event.Invoke message = new FluorineFx.Messaging.Rtmp.Event.Invoke {
         ServiceCall = serviceCall,
         InvokeId    = this.InvokeId
     };
     if (serviceCall is IPendingServiceCall)
     {
         lock (((ICollection)this._pendingCalls).SyncRoot)
         {
             this._pendingCalls[message.InvokeId] = serviceCall;
         }
     }
     this.GetChannel(channel).Write(message);
 }
        public override async Task ExecuteCallAsync(IServiceCall call)
        {
            await _mutex.WaitAsync().ConfigureAwait(false);

            _calls.Add(call);
            _mutex.Release();
            try
            {
                await ExecuteCallAsyncHelper(call);
            }
            finally
            {
                // Regardless of success, the call must be removed from the collection
                RemoveCall(call);
            }
        }
        public void Forward(IServiceCall to)
        {
            ActivatableContext.CheckActive();
            if (ForwardMessage.HasValue)
            {
                throw new InvalidOperationException("This context has already forwarded.");
            }

            ForwardMessage = Optional.Option.Some(
                new Forward
            {
                ServiceName = to.Ref.Method.Service.FullName,
                CommandName = to.Ref.Method.Name,
                Payload     = Any.Pack(to.Message)
            }
                );
        }
示例#26
0
        public bool Invoke(IServiceCall call, IScope scope)
        {
            string serviceName = call.ServiceName;

            this._log.Debug("Service name " + serviceName);
            object serviceHandler = this.GetServiceHandler(scope, serviceName);

            if (serviceHandler == null)
            {
                call.Exception = new ServiceNotFoundException(serviceName);
                call.Status    = 0x10;
                this._log.Warn("Service not found: " + serviceName);
                return(false);
            }
            this._log.Debug("Service found: " + serviceName);
            return(this.Invoke(call, serviceHandler));
        }
示例#27
0
        public static void InvokeCall(RtmpConnection connection, IServiceCall serviceCall)
        {
            IScope scope = connection.Scope;

            if (scope.HasHandler)
            {
                IScopeHandler handler = scope.Handler;
                if (!handler.ServiceCall(connection, serviceCall))
                {
                    // What do do here? Return an error?
                    return;
                }
            }
            IScopeContext context = scope.Context;

            context.ServiceInvoker.Invoke(serviceCall, scope);
        }
示例#28
0
        private void RetryCallContinuation(ServiceCall call, IServiceCall result, int retry)
        {
            // Canceled.
            if (call.IsCanceled)
            {
                return;
            }
            if (result.IsCanceled)
            {
                call.Cancel();
                return;
            }

            // Faulted.
            if (result.IsFaulted)
            {
                var isRecoverable = result.Exception is IngestionException ingestionException && ingestionException.IsRecoverable;
                if (!isRecoverable || retry - 1 >= _retryIntervals.Length)
                {
                    call.SetException(result.Exception);
                    return;
                }

                // Shedule next retry.
                var timer = IntervalCall(retry, () =>
                {
                    lock (_calls)
                    {
                        if (!_calls.Remove(call))
                        {
                            return;
                        }
                    }
                    RetryCall(call, retry);
                });
                lock (_calls)
                {
                    _calls.Add(call, timer);
                }
                return;
            }

            // Succeeded.
            call.SetResult(result.Result);
        }
示例#29
0
        private void button1_Click(object sender, EventArgs e)
        {
            //declate service proxy.
            serviceProxy = new ServiceCallProxy();
            //subscribe to on complete event to show the response.
            serviceProxy.OnRequestComplete += ServiceProxy_OnRequestComplete;
            //initiate the request.
            serviceProxy.Request = new ServiceRequest()
            {
                UserName = "******", Password = "******"
            };
            //show place holding response.
            resultLBL.Text = serviceProxy.Response.AccountStatus;


            callServiceBTN.Enabled = false;
            refreshBTN.Enabled     = true;
        }
示例#30
0
 public void CopyState(IServiceCall source)
 {
     if (_disposed)
     {
         throw new ObjectDisposedException(nameof(ServiceCall));
     }
     if (source.IsCanceled)
     {
         Cancel();
         return;
     }
     if (source.IsFaulted)
     {
         SetException(source.Exception);
         return;
     }
     SetResult(source.Result);
 }
示例#31
0
        private static ByteBuffer EncodeNotifyOrInvoke(RtmpContext context, Notify invoke)
        {
            ByteBuffer stream = ByteBuffer.Allocate(0x400);

            stream.AutoExpand = true;
            RtmpWriter   writer      = new RtmpWriter(stream);
            IServiceCall serviceCall = invoke.ServiceCall;
            bool         flag        = serviceCall.Status == 1;

            if (!flag)
            {
                writer.WriteData(context.ObjectEncoding, "_result");
            }
            else
            {
                string data = (serviceCall.ServiceName == null) ? serviceCall.ServiceMethodName : (serviceCall.ServiceName + "." + serviceCall.ServiceMethodName);
                writer.WriteData(context.ObjectEncoding, data);
            }
            if (invoke is Invoke)
            {
                writer.WriteData(context.ObjectEncoding, invoke.InvokeId);
                writer.WriteData(context.ObjectEncoding, invoke.ConnectionParameters);
            }
            if (!flag && (invoke is Invoke))
            {
                IPendingServiceCall call2 = (IPendingServiceCall)serviceCall;
                if (!serviceCall.IsSuccess)
                {
                    StatusASO saso = GenerateErrorResult("NetConnection.Call.Failed", serviceCall.Exception);
                    call2.Result = saso;
                }
                writer.WriteData(context.ObjectEncoding, call2.Result);
                return(stream);
            }
            object[] arguments = invoke.ServiceCall.Arguments;
            if (arguments != null)
            {
                foreach (object obj2 in arguments)
                {
                    writer.WriteData(context.ObjectEncoding, obj2);
                }
            }
            return(stream);
        }
示例#32
0
 private void HandleSendingResult(State state, string batchId, IServiceCall call)
 {
     // Get a lock without checking the state here.
     using (_mutex.GetLock())
     {
         _calls.Remove(call);
     }
     try
     {
         if (call.IsCanceled)
         {
             AppCenterLog.Debug(AppCenterLog.LogTag, $"Sending logs for channel '{Name}', batch '{batchId}' canceled");
             HandleSendingFailure(state, batchId, new CancellationException());
         }
         else if (call.IsFaulted)
         {
             AppCenterLog.Error(AppCenterLog.LogTag, $"Sending logs for channel '{Name}', batch '{batchId}' failed: {call.Exception?.ToString()}");
             var isRecoverable = call.Exception is IngestionException ingestionException && ingestionException.IsRecoverable;
             if (isRecoverable)
             {
                 using (_mutex.GetLock(state))
                 {
                     var removedLogs = _sendingBatches[batchId];
                     _sendingBatches.Remove(batchId);
                     _pendingLogCount += removedLogs.Count;
                 }
             }
             else
             {
                 HandleSendingFailure(state, batchId, call.Exception);
             }
             Suspend(state, !isRecoverable, call.Exception);
         }
         else
         {
             HandleSendingSuccess(state, batchId);
         }
     }
     catch (StatefulMutexException)
     {
         AppCenterLog.Debug(AppCenterLog.LogTag, "Handle sending operation has been canceled. Callbacks were invoked when channel suspended.");
     }
 }
示例#33
0
        public static Task <string> ToTask(this IServiceCall @this)
        {
            var source = new TaskCompletionSource <string>();

            @this.ContinueWith(serviceCall =>
            {
                if (serviceCall.IsCanceled)
                {
                    source.SetCanceled();
                }
                else if (serviceCall.IsFaulted)
                {
                    source.SetException(serviceCall.Exception);
                }
                else
                {
                    source.SetResult(serviceCall.Result);
                }
            });
            return(source.Task);
        }
        /// <exception cref="IngestionException"/>
        public async Task ExecuteCallAsync(IServiceCall call)
        {
            if (call.CancellationToken.IsCancellationRequested)
            {
                return;
            }
            var requestContent = CreateLogsContent(call.Logs);

            using (var request = CreateRequest(call.AppSecret, call.InstallId, requestContent))
                using (var response = await _httpNetwork.SendAsync(request, call.CancellationToken).ConfigureAwait(false))
                {
                    if (response == null)
                    {
                        throw new IngestionException("Null response received");
                    }
                    var responseContent = "(null)";
                    if (response.Content != null)
                    {
                        responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    }
                    MobileCenterLog.Verbose(MobileCenterLog.LogTag, $"HTTP response status={(int)response.StatusCode} ({response.StatusCode}) payload={responseContent}");
                    if (call.CancellationToken.IsCancellationRequested)
                    {
                        return;
                    }
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        var ex = new HttpIngestionException($"Operation returned an invalid status code '{response.StatusCode}'")
                        {
                            Method          = request.Method,
                            RequestUri      = request.RequestUri,
                            StatusCode      = response.StatusCode,
                            RequestContent  = requestContent,
                            ResponseContent = responseContent
                        };
                        throw ex;
                    }
                }
        }
        private async Task ExecuteCallAsyncHelper(IServiceCall call)
        {
            if (_networkStateAdapter.IsConnected)
            {
                try
                {
                    await base.ExecuteCallAsync(call).ConfigureAwait(false);
                }
                // Recursion case in case network goes out during the base ExecuteCallAsync call
                catch (NetworkIngestionException)
                {
                    // Since we caught a NetworkIngestionException, just wait for network and then retry
                    await PauseExecutionUntilNetworkBecomesAvailable().ConfigureAwait(false);
                    await ExecuteCallAsyncHelper(call).ConfigureAwait(false);
                }
                return;
            }

            // Recursion case
            await PauseExecutionUntilNetworkBecomesAvailable().ConfigureAwait(false);
            await ExecuteCallAsyncHelper(call).ConfigureAwait(false);
        }
示例#36
0
        /// <exception cref="NetworkUnavailableException"/>
        public override async Task ExecuteCallAsync(IServiceCall call)
        {
            await _mutex.WaitAsync().ConfigureAwait(false);

            _calls.Add(call);
            _mutex.Release();

            if (_networkState.IsConnected)
            {
                try
                {
                    await base.ExecuteCallAsync(call).ConfigureAwait(false);
                }
                finally
                {
                    RemoveCall(call);
                }
            }
            else
            {
                throw new NetworkUnavailableException();
            }
        }
 public InvalidCallException(IServiceCall call)
 {
     _call = call;
 }
示例#38
0
        internal RtmpConnection(IRtmpHandler handler, RtmpMode mode, string path, IDictionary parameters)
            : base(path, parameters)
		{
            _handler = handler;
            _channels = new CopyOnWriteDictionary<int,RtmpChannel>(4);
            _streams = new CopyOnWriteDictionary<int,IClientStream>();
            _pendingVideos = new CopyOnWriteDictionary<int,AtomicInteger>();
            _streamCount = new AtomicInteger();
            _streamBuffers = new CopyOnWriteDictionary<int,int>();
            _reservedStreams = new BitArray(0);
            _pendingCalls = new CopyOnWriteDictionary<int, IServiceCall>();
            _pendingReceive = null;
			// We start with an anonymous connection without a scope.
			// These parameters will be set during the call of "connect" later.
            _context = new RtmpContext(mode);
            //Transaction id depends on server/client mode
            //When server mode is set we cannot push messages with transaction id = 1 (connect)
            _invokeId = mode == RtmpMode.Server ? new AtomicInteger(1) : new AtomicInteger(0);
		}
示例#39
0
		/// <summary>
		/// Notifies service using service call object.
		/// </summary>
		/// <param name="serviceCall">Service call object.</param>
		public void Notify(IServiceCall serviceCall) {
			Notify(serviceCall, (byte)3);
		}
示例#40
0
	// Run a batch item asychronously.
	public void AsynchronousCall(IServiceCall serviceCall)
			{
				// We do everything synchronously in this implementation.
				SynchronousCall(serviceCall);
			}
示例#41
0
        internal Invoke(IServiceCall serviceCall)
            : base(serviceCall)
		{
            _dataType = Constants.TypeInvoke;
		}
        public void RegisterACall(IServiceCall serviceCall)
        {
            _validator.ValidateCall(serviceCall);

            _callRepository.RegisterACallForPhone(serviceCall);
        }
 public ServiceNotSupportedBySubscriptionException(IServiceCall call)
 {
     _call = call;
 }
示例#44
0
		public InvokeData(FluorineContext context, IServiceCall call, byte channel) {
			_context = context;
			_call = call;
			_channel = channel;
		}
示例#45
0
		/// <summary>
		/// Notifies service using service call object and channel.
		/// </summary>
		/// <param name="serviceCall">Service call object.</param>
		/// <param name="channel">Channel to use.</param>
		public void Notify(IServiceCall serviceCall, byte channel) {
			Notify notify = new Notify();
			notify.ServiceCall = serviceCall;
			GetChannel(channel).Write(notify);
		}
示例#46
0
 /// <summary>
 /// Register pending receive (remote function receive to come).
 /// </summary>
 /// <param name="invokeId">Deferred operation id.</param>
 /// <param name="call">Call service.</param>
 internal void RegisterPendingReceive(IPendingServiceCall call)
 {
     _pendingReceive = call;
 }
示例#47
0
        internal Notify(IServiceCall serviceCall)
            : this()
		{
			_serviceCall = serviceCall;
		}
 public abstract decimal CalculateCharge(IServiceCall call);
示例#49
0
        public static void InvokeCall(RtmpConnection connection, IServiceCall serviceCall) 
		{
			IScope scope = connection.Scope;
			if(scope.HasHandler) 
			{
				IScopeHandler handler = scope.Handler;
				if(!handler.ServiceCall(connection, serviceCall)) 
				{
					// What do do here? Return an error?
					return;
				}
			}
			IScopeContext context = scope.Context;
			context.ServiceInvoker.Invoke(serviceCall, scope);
		}
示例#50
0
		/// <summary>
		/// Invokes service using service call object.
		/// </summary>
		/// <param name="serviceCall">Service call object.</param>
		public void Invoke(IServiceCall serviceCall) {
			Invoke(serviceCall, (byte)3);
		}
示例#51
0
        /// <summary>
        /// Remoting call invocation handler.
        /// </summary>
        /// <param name="connection">RTMP connection.</param>
        /// <param name="serviceCall">Service call.</param>
        /// <param name="service">Server-side service object.</param>
        /// <returns><code>true</code> if the call was performed, otherwise <code>false</code>.</returns>
	    private static bool InvokeCall(RtmpConnection connection, IServiceCall serviceCall, object service) 
        {
		    IScope scope = connection.Scope;
		    IScopeContext context = scope.Context;
		    if (log.IsDebugEnabled) 
            {
			    log.Debug("Scope: " + scope);
			    log.Debug("Service: " + service);
			    log.Debug("Context: " + context);
		    }
            return context.ServiceInvoker.Invoke(serviceCall, service);
	    }
示例#52
0
		/// <summary>
		/// Invokes service using service call object and channel.
		/// </summary>
		/// <param name="serviceCall">Service call object.</param>
		/// <param name="channel">Channel to use.</param>
		public void Invoke(IServiceCall serviceCall, byte channel) {
			// We need to use Invoke for all calls to the client
			Invoke invoke = new Invoke();
			invoke.ServiceCall = serviceCall;
			invoke.InvokeId = this.InvokeId;
			if (serviceCall is IPendingServiceCall) {
				_pendingCalls[invoke.InvokeId] = serviceCall;
			}
			GetChannel(channel).Write(invoke);
		}
示例#53
0
文件: Activity.cs 项目: kumpera/mono
		public void SynchronousCall (IServiceCall serviceCall)
		{
			throw new NotImplementedException ();
		}
示例#54
0
		/// <summary>
		/// Begins an asynchronous operation to invoke a service using service call object and channel.
		/// </summary>
		/// <param name="asyncCallback">The AsyncCallback delegate.</param>
		/// <param name="serviceCall">Service call object.</param>
		/// <param name="channel">Channel to use.</param>
		/// <returns>An IAsyncResult that references the asynchronous invocation.</returns>
		/// <remarks>
		/// <para>
		/// You can create a callback method that implements the AsyncCallback delegate and pass its name to the BeginInvoke method.
		/// </para>
		/// <para>
		/// Your callback method should invoke the EndInvoke method. When your application calls BeginInvoke, the system will use a separate thread to execute the specified callback method, and will block on EndInvoke until the client is invoked successfully or throws an exception.
		/// </para>
		/// </remarks>        
		public IAsyncResult BeginInvoke(AsyncCallback asyncCallback, IServiceCall serviceCall, byte channel) {
			// Create IAsyncResult object identifying the asynchronous operation
			AsyncResultNoResult ar = new AsyncResultNoResult(asyncCallback, new InvokeData(FluorineContext.Current, serviceCall, channel));
			// Use a thread pool thread to perform the operation
			GodLesZ.Library.Amf.Threading.ThreadPoolEx.Global.QueueUserWorkItem(new System.Threading.WaitCallback(OnBeginInvoke), ar);
			// Return the IAsyncResult to the caller
			return ar;
		}
示例#55
0
        protected override void OnInvoke(RtmpConnection connection, RtmpChannel channel, RtmpHeader header, Notify invoke)
        {
            IServiceCall call = invoke.ServiceCall;

            if (invoke.EventType == EventType.STREAM_DATA)
            {
#if !SILVERLIGHT
                if (Log.IsDebugEnabled)
                {
                    Log.Debug(string.Format("Ignoring stream data notify with header {0}", header));
                }
#endif
                return;
            }

            if (call.ServiceMethodName == "_result" || call.ServiceMethodName == "_error")
            {
                if (call.ServiceMethodName == "_error")
                {
                    call.Status = Messaging.Rtmp.Service.Call.STATUS_INVOCATION_EXCEPTION;
                }
                if (call.ServiceMethodName == "_result")
                {
                    call.Status = Messaging.Rtmp.Service.Call.STATUS_SUCCESS_RESULT;
                }
                //Get the panding call, if any, as HandlePendingCallResult will remove it
                IPendingServiceCall pendingCall = connection.GetPendingCall(invoke.InvokeId);
                HandlePendingCallResult(connection, invoke);

                if (call.IsSuccess && invoke.InvokeId == 1)
                {
                    // Should keep this as an Object to stay compatible with FMS3 etc
                    IDictionary aso = call.Arguments[0] as IDictionary;
                    if (aso != null)
                    {
                        object clientId = null;
                        if (aso.Contains("clientid"))
                        {
                            clientId = aso["clientid"];
                        }
#if !SILVERLIGHT
                        if (Log.IsDebugEnabled)
                        {
                            Log.Debug(string.Format("Client id: {0}", clientId));
                        }
#endif
                        _netConnection.SetClientId(clientId != null ? clientId.ToString() : null);
                    }
                }

                //Notify via NetConnection if no IPendingServiceCallback was defined but the call failed
                if (call.ServiceMethodName == "_error")
                {
                    object[] args      = call.Arguments;
                    ASObject statusAso = null;
                    if ((args != null) && (args.Length > 0))
                    {
                        statusAso = args[0] as ASObject;
                    }
                    bool raiseError = false;
                    if (pendingCall != null)
                    {
                        IPendingServiceCallback[] callbacks = pendingCall.GetCallbacks();
                        if (callbacks == null || callbacks.Length == 0)
                        {
                            raiseError = true;
                        }
                    }
                    else
                    {
                        raiseError = true;
                    }
                    if (raiseError)
                    {
                        if (statusAso != null)
                        {
                            _netConnection.RaiseNetStatus(statusAso);
                        }
                        else
                        {
                            string msg = __Res.GetString(__Res.Invocation_Failed, pendingCall != null ? pendingCall.ServiceMethodName : string.Empty, "Invocation failed");
                            _netConnection.RaiseNetStatus(msg);
                        }
                    }
                }
                return;
            }

            bool onStatus = call.ServiceMethodName.Equals("onStatus") || call.ServiceMethodName.Equals("onMetaData") ||
                            call.ServiceMethodName.Equals("onPlayStatus");
            if (onStatus)
            {
                /*
                 * IDictionary aso = call.Arguments[0] as IDictionary;
                 * // Should keep this as an Object to stay compatible with FMS3 etc
                 * object clientId = null;
                 * if( aso.Contains("clientid") )
                 *  clientId = aso["clientid"];
                 * if (clientId == null)
                 *  clientId = header.StreamId;
                 #if !SILVERLIGHT
                 * if (log.IsDebugEnabled)
                 *  log.Debug(string.Format("Client id: {0}", clientId));
                 #endif
                 * if (clientId != null)
                 * {
                 *  NetStream stream = _connection.GetStreamById((int)clientId) as NetStream;
                 *  if (stream != null)
                 *  {
                 *      stream.OnStreamEvent(invoke);
                 *  }
                 * }
                 */
                NetStream stream = _connection.GetStreamById(header.StreamId) as NetStream;
                if (stream != null)
                {
                    stream.OnStreamEvent(invoke);
                }
                return;
            }

            if (call is IPendingServiceCall)
            {
                IPendingServiceCall psc = call as IPendingServiceCall;

                /*
                 * object result = psc.Result;
                 * object result = psc.Result;
                 * if (result is DeferredResult)
                 * {
                 *  DeferredResult dr = result as DeferredResult;
                 *  dr.InvokeId = invoke.InvokeId;
                 *  dr.ServiceCall = psc;
                 *  dr.Channel = channel;
                 *  connection.RegisterDeferredResult(dr);
                 * }
                 * else
                 * {
                 *  Invoke reply = new Invoke();
                 *  reply.ServiceCall = call;
                 *  reply.InvokeId = invoke.InvokeId;
                 *  channel.Write(reply);
                 * }
                 */
                MethodInfo mi = MethodHandler.GetMethod(_netConnection.Client.GetType(), call.ServiceMethodName, call.Arguments, false, false);
                if (mi != null)
                {
                    ParameterInfo[] parameterInfos = mi.GetParameters();
                    object[]        args           = new object[parameterInfos.Length];
                    call.Arguments.CopyTo(args, 0);
                    TypeHelper.NarrowValues(args, parameterInfos);
                    try
                    {
                        InvocationHandler invocationHandler = new InvocationHandler(mi);
                        object            result            = invocationHandler.Invoke(_netConnection.Client, args);
                        if (mi.ReturnType == typeof(void))
                        {
                            call.Status = Messaging.Rtmp.Service.Call.STATUS_SUCCESS_VOID;
                        }
                        else
                        {
                            call.Status = result == null ? Messaging.Rtmp.Service.Call.STATUS_SUCCESS_NULL : Messaging.Rtmp.Service.Call.STATUS_SUCCESS_RESULT;
                            psc.Result  = result;
                        }
                    }
                    catch (Exception exception)
                    {
                        call.Exception = exception;
                        call.Status    = Messaging.Rtmp.Service.Call.STATUS_INVOCATION_EXCEPTION;
                        //log.Error("Error while invoking method " + call.ServiceMethodName + " on client", exception);
                    }
                }
                else// if (!onStatus)
                {
                    string msg = __Res.GetString(__Res.Invocation_NoSuitableMethod, call.ServiceMethodName);
                    call.Status    = Messaging.Rtmp.Service.Call.STATUS_METHOD_NOT_FOUND;
                    call.Exception = new FluorineException(msg);
                    _netConnection.RaiseNetStatus(call.Exception);

                    //log.Error(msg, call.Exception);
                }
                if (call.Status == Messaging.Rtmp.Service.Call.STATUS_SUCCESS_VOID || call.Status == Messaging.Rtmp.Service.Call.STATUS_SUCCESS_NULL)
                {
#if !SILVERLIGHT
                    if (Log.IsDebugEnabled)
                    {
                        Log.Debug("Method does not have return value, do not reply");
                    }
#endif
                    return;
                }
                Invoke reply = new Invoke();
                reply.ServiceCall = call;
                reply.InvokeId    = invoke.InvokeId;
                channel.Write(reply);
            }
            else
            {
                IPendingServiceCall pendingCall = connection.RetrievePendingCall(invoke.InvokeId);
                Unreferenced.Parameter(pendingCall);
            }
        }
示例#56
0
		/// <summary>
		/// Begins an asynchronous operation to invoke a service using service call object.
		/// </summary>
		/// <param name="asyncCallback">The AsyncCallback delegate.</param>
		/// <param name="serviceCall">Service call object.</param>
		/// <returns>An IAsyncResult that references the asynchronous invocation.</returns>
		/// <remarks>
		/// <para>
		/// You can create a callback method that implements the AsyncCallback delegate and pass its name to the BeginInvoke method.
		/// </para>
		/// <para>
		/// Your callback method should invoke the EndInvoke method. When your application calls BeginInvoke, the system will use a separate thread to execute the specified callback method, and will block on EndInvoke until the client is invoked successfully or throws an exception.
		/// </para>
		/// </remarks>        
		public IAsyncResult BeginInvoke(AsyncCallback asyncCallback, IServiceCall serviceCall) {
			return BeginInvoke(asyncCallback, serviceCall, (byte)3);
		}
 public void ValidateCall(IServiceCall call)
 {
     _rules.ForEach(rule => rule.Validate(call));
 }
 public void RegisterACallForPhone(IServiceCall serviceCall)
 {
     _calls.Add(serviceCall);
 }
 public TestServiceCall(IServiceCall decoratedApi) : base(decoratedApi)
 {
 }
		public bool Invoke(IServiceCall call, object service)
		{
            string serviceMethod = call.ServiceMethodName;
            object[] arguments = call.Arguments;

            // First, search for method with exact parameter type match
            MethodInfo mi = MethodHandler.GetMethod(service.GetType(), serviceMethod, arguments, true, false, false);
            if (mi == null)
            {
                // Second, search for method with type conversions
                // This second call will trace 'suitable method' errors too
                mi = MethodHandler.GetMethod(service.GetType(), serviceMethod, arguments, false, false, true);
                if (mi == null)
                {
                    string msg = __Res.GetString(__Res.Invocation_NoSuitableMethod, serviceMethod);
                    call.Status = Call.STATUS_METHOD_NOT_FOUND;
                    call.Exception = new FluorineException(msg);
                    return false;
                }
            }

            try
            {
                ParameterInfo[] parameterInfos = mi.GetParameters();
                object[] parameters = new object[parameterInfos.Length];
                arguments.CopyTo(parameters, 0);
                TypeHelper.NarrowValues(parameters, parameterInfos);

                object result = null;
                if (mi.ReturnType == typeof(void))
                {
                    InvocationHandler invocationHandler = new InvocationHandler(mi);
                    invocationHandler.Invoke(service, parameters);
                    call.Status = Call.STATUS_SUCCESS_VOID;
                }
                else
                {
                    InvocationHandler invocationHandler = new InvocationHandler(mi);
                    result = invocationHandler.Invoke(service, parameters);
                    call.Status = result == null ? Call.STATUS_SUCCESS_NULL : Call.STATUS_SUCCESS_RESULT;
                }
                if (call is IPendingServiceCall)
                    (call as IPendingServiceCall).Result = result;
            }
            catch (SecurityException exception)
            {
                call.Exception = exception;
                call.Status = Call.STATUS_ACCESS_DENIED;
                if (log.IsDebugEnabled)
                    log.Debug(exception.Message);
                return false;
            }
            catch (UnauthorizedAccessException exception)
            {
                call.Exception = exception;
                call.Status = Call.STATUS_ACCESS_DENIED;
                if (log.IsDebugEnabled)
                    log.Debug(exception.Message);
                return false;
            }
            catch (TargetInvocationException exception)
            {
                call.Exception = exception.InnerException;
                call.Status = Call.STATUS_INVOCATION_EXCEPTION;
                if (log.IsDebugEnabled)
                    log.Debug(__Res.GetString(__Res.Invocation_Failed, mi.Name, exception.InnerException.Message));
                return false;
            }
            catch (Exception exception)
            {
                call.Exception = exception;
                call.Status = Call.STATUS_GENERAL_EXCEPTION;
                if (log.IsDebugEnabled)
                    log.Debug(__Res.GetString(__Res.Invocation_Failed, mi.Name, exception.Message));
                return false;
            }
            return true;
		}