protected internal ClientConnectionScope(HubServiceEndpoint endpoint, IServiceConnection outboundConnection, bool isDiagnosticClient)
        {
            // Only allow to carry one copy of connection properties regardless of how many nested scopes are created
            if (!IsScopeEstablished)
            {
                _needCleanup = true;

                // The lifetime of the async local we're about to create can be much longer than some of the objects we store inside.
                // Instances of IServiceConnection can be stopped and replaced over time and nobody should keep references to the old ones.
                // So we keep them inside async local wrapped in weak references to avoid unnecessarily prolonging their lifetime.
                ConcurrentDictionary <long, WeakReference <IServiceConnection> > dict = new ConcurrentDictionary <long, WeakReference <IServiceConnection> >();
                if (endpoint != null)
                {
                    dict.TryAdd(endpoint.UniqueIndex, new WeakReference <IServiceConnection>(outboundConnection));
                }

                ScopePropertiesAccessor <ClientConnectionScopeProperties> .Current =
                    new ScopePropertiesAccessor <ClientConnectionScopeProperties>()
                {
                    Properties = new ClientConnectionScopeProperties()
                    {
                        OutboundServiceConnections = dict,
                        IsDiagnosticClient         = isDiagnosticClient
                    }
                };
            }
            else
            {
                Debug.Assert(outboundConnection == default && isDiagnosticClient == default, "Attempt to replace an already established scope");
            }
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.multi_recycler_view);

            wrv_multiView = (WearableRecyclerView)FindViewById(Resource.Id.wrv_multi_view);
            SnapHelper snapHelper = new LinearSnapHelper();

            snapHelper.AttachToRecyclerView(wrv_multiView);
            adapter = new AdapterMetricsMultiView(this, wrv_multiView, new List <int> {
                ListItemType.MetricsLayout, ListItemType.LapList
            }, false);
            wrv_multiView.SetAdapter(adapter);

            SetAmbientEnabled();


            app           = GlobalDataDash.GetInstance();
            serviceIntent = new Intent(this, typeof(ServiceWorkout));

            serviceConnection = new ServiceConnection(this);

            if (!app.isServiceRunning)
            {
                StartService(serviceIntent);
            }
            DoBindService();

            StartUIThread();
        }
        public ServiceWorker(IServiceBroker <TNotification> broker, IServiceConnection <TNotification> connection)
        {
            Broker     = broker;
            Connection = connection;

            CancelTokenSource = new CancellationTokenSource();
        }
Example #4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DownloaderServiceConnection"/> class.
 /// </summary>
 /// <param name="clientType">
 /// The client type.
 /// </param>
 /// <param name="serviceType">
 /// The service type.
 /// </param>
 public DownloaderServiceConnection(IDownloaderClient clientType, Type serviceType)
 {
     this.messenger         = new Messenger(new Handler(this.SendMessage));
     this.serviceConnection = new ServiceConnection(this);
     this.clientType        = clientType;
     this.serviceTypeType   = serviceType;
 }
Example #5
0
 internal MockServiceConnection(IMockService mockService, IServiceConnection serviceConnection)
 {
     _mockService       = mockService;
     _serviceConnection = serviceConnection;
     ConnectionNumber   = Interlocked.Increment(ref s_num);
     _mockService.RegisterSDKConnection(this);
 }
Example #6
0
        public IServiceTransport CreateConnection(OpenConnectionMessage message, IServiceConnection serviceConnection)
        {
            var dispatcher = new HubDispatcher(_configuration);

            dispatcher.Initialize(_configuration.Resolver);

            var responseStream = new MemoryStream();
            var hostContext    = GetHostContext(message, responseStream, serviceConnection);

            if (dispatcher.Authorize(hostContext.Request))
            {
                // ProcessRequest checks if the connectionToken matches "{connectionid}:{userName}" format with context.User
                _ = dispatcher.ProcessRequest(hostContext);

                // TODO: check for errors written to the response
                if (hostContext.Response.StatusCode != 200)
                {
                    Log.ProcessRequestError(_logger, message.ConnectionId, hostContext.Request.QueryString.ToString());
                    Debug.Fail("Response StatusCode is " + hostContext.Response.StatusCode);
                    var errorResponse = GetContentAndDispose(responseStream);
                    throw new InvalidOperationException(errorResponse);
                }

                return((AzureTransport)hostContext.Environment[AspNetConstants.Context.AzureSignalRTransportKey]);
            }

            // This happens when hub is not found
            Debug.Fail("Unauthorized");
            throw new InvalidOperationException("Unable to authorize request");
        }
Example #7
0
        private async Task StartResilientStream(TimeSpan connectionTimeout)
        {
            if (_cancel.IsCancellationRequested)
            {
                return;
            }

            Current = ConnectionProvider.GetNextConnection(_onError, _onSuccess, Current == null ? null : Current.Endpoint);

            var isConnectionSet = await Current.Initialize();

            if (!isConnectionSet)
            {
                //if the connection failed to reach endpoint, we delay and try again
                await Task.Delay(connectionTimeout);
                await StartResilientStream(connectionTimeout);
            }
            else
            {
                Current.StatusStream.Subscribe(async current =>
                {
                    //if the connection abrutly closed, then we immediatly try to reach the next endpoint
                    if (current.ConnectionStatus == ConnectionStatus.Closed)
                    {
                        await StartResilientStream(connectionTimeout);
                    }
                });

                //if we conect to the current endpoint, then wire up the stream
                GetResilientStream(connectionTimeout);
            }
        }
Example #8
0
		/// <summary>
		/// Starts the setup process. This will start up the setup process asynchronously.
		/// You will be notified through the listener when the setup process is complete.
		/// This method is safe to call from a UI thread.
		/// </summary>
		/// <param name="listener"> The listener to notify when the setup process is complete. </param>
		public void startSetup(OnIabSetupFinishedListener listener)
		{
			// If already set up, can't do it again.
			checkNotDisposed();
			if (mSetupDone)
			{
				throw new IllegalStateException("IAB helper is already set up.");
			}

			// Connection to IAB service
			logDebug("Starting in-app billing setup.");
			mServiceConn = new ServiceConnectionAnonymousInnerClassHelper(this, listener);

			Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
			serviceIntent.SetPackage("com.android.vending");

            var list = mContext.PackageManager.QueryIntentServices(serviceIntent, 0);

            if ((list == null) ? false : list.Any())
			{
				// service available to handle that Intent
				mContext.BindService(serviceIntent, mServiceConn, Bind.AutoCreate);
			}
			else
			{
				// no service available to handle that Intent
				if (listener != null)
				{
					listener.onIabSetupFinished(new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE, "Billing service unavailable on device."));
				}
			}
		}
Example #9
0
            static public ServiceConnection <ServiceType> Bind(Activity activity, IServiceConnection <ServiceType> altConnection, Android.Content.Bind bindFlags = Android.Content.Bind.AutoCreate)
            {
                Intent intent = new Intent(activity, typeof(ServiceType));

                var realConnection = new ServiceConnection <ServiceType>(activity, altConnection);

                activity.BindService(intent, realConnection, bindFlags);
                return(realConnection);
            }
Example #10
0
 void IServiceConnection.OnServiceDisconnected(ComponentName name)
 {
     if (connection != null)
     {
         this.connection.OnServiceDisconnected(name);
     }
     this.connection = null;
     isBound         = false;
 }
Example #11
0
 protected void ReplaceFixedConnections(int index, IServiceConnection serviceConnection)
 {
     lock (_lock)
     {
         var newImmutableConnections = FixedServiceConnections.ToList();
         newImmutableConnections[index] = serviceConnection;
         FixedServiceConnections        = newImmutableConnections;
     }
 }
Example #12
0
        public IServiceTransport CreateConnection(OpenConnectionMessage message, IServiceConnection serviceConnection)
        {
            var transport = new TestTransport
            {
                ConnectionId = message.ConnectionId
            };

            CurrentTransports.TryAdd(message.ConnectionId, transport);
            return(transport);
        }
            // make the intent explicit
            public override bool BindService(Intent service, IServiceConnection conn, Bind flags)
            {
                var action = service.Action;

                if (!string.IsNullOrEmpty(action) && action.StartsWith("com.microsoft.band"))
                {
                    service.SetPackage("com.microsoft.kapp");
                }
                return(base.BindService(service, conn, flags));
            }
Example #14
0
 protected ServiceConnection(Activity activity, IServiceConnection <ServiceType> altConnection)
 {
     if (null != altConnection)
     {
         this.connection = altConnection;
     }
     else
     {
         this.connection = activity as IServiceConnection <ServiceType>;
     }
 }
        /// <summary>
        /// Sets the service connection for the end-point.
        /// </summary>
        /// <param name="serviceConnection">A PushSharp service connection.</param>
        protected void SetConnection(IServiceConnection <TPushSharpNotification> serviceConnection)
        {
            Throw.IfArgumentNull(serviceConnection, nameof(serviceConnection));

            if (this.serviceConnection != null)
            {
                throw new InvalidOperationException("The end-point has already been connected.");
            }

            this.serviceConnection = serviceConnection;
        }
        public ClientConnectionContext(IServiceConnection sc, string connectionId, string instanceId = null)
        {
            _serviceConnection = sc;

            ConnectionId = connectionId;
            InstanceId   = instanceId;
            var channel = Channel.CreateUnbounded <ServiceMessage>();

            Input  = channel.Reader;
            Output = channel.Writer;
        }
Example #17
0
 protected override void OnResume()
 {
     serviceConnection = new TunnelServiceConnection(OnBoundToTunnelService, OnUnBoundToTunnelService);
     ApplicationContext.BindService(new Intent(this, typeof(TunnelService)), serviceConnection, Bind.AutoCreate);
     Console.WriteLine("On Resume");
     logView.SetText(savedText, TextView.BufferType.Editable);
     scrollView.ScrollTo(0, logView.Height);
     scrollView.FullScroll(FocusSearchDirection.Down);
     SetupBluetooth();
     base.OnResume();
 }
Example #18
0
 /// <summary>
 /// Start and manage the whole connection lifetime
 /// </summary>
 /// <returns></returns>
 protected async Task StartCoreAsync(IServiceConnection connection, string target = null)
 {
     try
     {
         await connection.StartAsync(target);
     }
     finally
     {
         await OnConnectionComplete(connection);
     }
 }
 public override void UnbindService(IServiceConnection conn)
 {
     if (conn != null)
     {
         base.UnbindService(conn);
         Toast.MakeText(this, "UnBinding Service from Client... ", ToastLength.Short).Show();
     }
     else
     {
         Toast.MakeText(this, "OJO - Couldn't UnBind Service from Client... ", ToastLength.Short).Show();
     }
 }
Example #20
0
        public static Task WriteAsync(this IServiceConnection serviceConnection, string connectionId, object value, IServiceProtocol protocol, JsonSerializer serializer, IMemoryPool pool)
        {
            using (var writer = new MemoryPoolTextWriter(pool))
            {
                serializer.Serialize(writer, value);
                writer.Flush();

                // Reuse ConnectionDataMessage to wrap the payload
                var wrapped = new ConnectionDataMessage(string.Empty, writer.Buffer);
                return(serviceConnection.WriteAsync(new ConnectionDataMessage(connectionId, protocol.GetMessageBytes(wrapped))));
            }
        }
Example #21
0
        public HostedActivityManager(Context context)
        {
            Context        = context;
            serviceActions = new List <Action> ();
            sessionId      = -1;
            mainLooper     = new global::Android.OS.Handler(global::Android.OS.Looper.MainLooper);

            connection = new HostedServiceConnection {
                OnServiceConnectedHandler = (name, service) => {
                    if (browserConnectionCallback == null)
                    {
                        browserConnectionCallback = new BrowserConnectionCallback {
                            Handler = (sessionId, url, extras) => {
                                var evt = UserNavigation;
                                if (evt != null)
                                {
                                    evt(sessionId, url, extras);
                                }
                            }
                        };
                    }

                    //var svcBinder = service as BrowserConnectionServiceBinder;
                    connectionService = IBrowserConnectionServiceStub.AsInterface(service);  //IBrowserConnectionService.Stub.AsInterface (service); // svcBinder.GetSvc (); // IBrowserConnectionService.AsInterface(service);
                    try {
                        if (browserConnectionCallback != null)
                        {
                            connectionService.FinishSetup(browserConnectionCallback);
                        }
                        sessionId = connectionService.NewSession();
                    } catch (global::Android.OS.RemoteException e) {
                        sessionId         = -1;
                        connectionService = null;
                        return;
                    }
                    serviceConnected = true;
                    foreach (var a in serviceActions)
                    {
                        mainLooper.Post(a);
                    }
                    serviceActions.Clear();
                },
                OnServiceDisconnectedHandler = (name) => {
                    serviceConnected = false;

                    if (shouldRebind)
                    {
                        BindService();
                    }
                }
            };
        }
Example #22
0
        protected virtual async Task OnConnectionComplete(IServiceConnection serviceConnection)
        {
            if (serviceConnection == null)
            {
                throw new ArgumentNullException(nameof(serviceConnection));
            }

            var index = FixedServiceConnections.IndexOf(serviceConnection);

            if (index != -1)
            {
                await RestartServiceConnectionCoreAsync(index);
            }
        }
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);
			serviceConnection = new TunnelServiceConnection(
				delegate(TunnelService.TunnelBinder binder){//On connect
					tunnel = binder.Tunnel;
					OnBoundToTunnelService(tunnel);
					//isBound = true;
				},
				delegate(TunnelService.TunnelBinder binder){//On disconnect
					//isBound = false;
				}
			);
			ApplicationContext.BindService (new Intent (this, typeof (TunnelService)), serviceConnection, Bind.AutoCreate);
		}
Example #24
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.MyButton);

            button.Click += button_Click;

            sc = new com.MessengerAppEx.ServiceConnection(this);
        }
Example #25
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById <Button>(Resource.Id.MyButton);

            button.Click += button_Click;

            sc = new MessengerAppEx2.ServiceConnection(this);
        }
Example #26
0
 protected override void OnCreate(Bundle bundle)
 {
     base.OnCreate(bundle);
     serviceConnection = new TunnelServiceConnection(
         delegate(TunnelService.TunnelBinder binder){                //On connect
         tunnel = binder.Tunnel;
         OnBoundToTunnelService(tunnel);
         //isBound = true;
     },
         delegate(TunnelService.TunnelBinder binder){                //On disconnect
         //isBound = false;
     }
         );
     ApplicationContext.BindService(new Intent(this, typeof(TunnelService)), serviceConnection, Bind.AutoCreate);
 }
Example #27
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Main);

            i = new Intent(this, typeof(HTTPService));

            connection = this;

            handler = new Handler();

            /* objetos de interface são instânciados aqui (FindViewById) */

            pingTime = 0;

            StartService(i);
        }
        private bool BindService()
        {
            Log.Info(TAG, "bindService");
            if (context == null)
            {
                Log.Error(TAG, "context is null");
                return(false);
            }
            serviceConnection = new InstallReferrerServiceConnection(this);
            Intent intent = new Intent(Constants.ServiceAction);

            intent.SetPackage(Constants.TestServicePackageName);
            // Bind HUAWEI Ads kit
            bool result = context.BindService(intent, serviceConnection, Bind.AutoCreate);

            Log.Info(TAG, "BindService result: " + result);
            return(result);
        }
Example #29
0
		/// <summary>
		/// Dispose of object, releasing resources. It's very important to call this
		/// method when you are done with this object. It will release any resources
		/// used by it such as service connections. Naturally, once the object is
		/// disposed of, it can't be used again.
		/// </summary>
		public void dispose()
		{
			logDebug("Disposing.");
			mSetupDone = false;
			if (mServiceConn != null)
			{
				logDebug("Unbinding from service.");
				if (mContext != null)
				{
					mContext.UnbindService(mServiceConn);
				}
			}
			mDisposed = true;
			mContext = null;
			mServiceConn = null;
			mService = null;
			mPurchaseListener = null;
		}
Example #30
0
        private bool BindService()
        {
            Log.Info(TAG, "bindService");
            if (mContext == null)
            {
                Log.Error(TAG, "context is null");
                return(false);
            }
            mServiceConnection = new InstallReferrerServiceConnection(this);
            Intent intent = new Intent(Constants.SERVICE_ACTION);

            intent.SetPackage(Constants.TEST_SERVICE_PACKAGE_NAME);
            // Bind HUAWEI Ads kit
            bool result = mContext.BindService(intent, mServiceConnection, Bind.AutoCreate);

            Log.Info(TAG, "bindService result: " + result);
            return(result);
        }
Example #31
0
        private bool InitialiseServiceConnection(bool allowUserAdminActionInput = true)
        {
            // Reset things
            TTService = null;
            deskbandControl.UpdateUIImage(inoperableOverride: true, UserControl1.EnableDisableButtonToolTips.ServiceNotConnected);

            // Attempt to form a connection to the installed Windows service
            if (ServiceHelper.IsServiceInstalled() && ServiceHelper.IsServiceRunning())
            {
                try
                {
                    // Establish a connection to the service
                    TTService = ServiceConnectionClient.Start(
                        onClose: (object sender, EventArgs e) => deskbandControl.UpdateUIImage(inoperableOverride: true, UserControl1.EnableDisableButtonToolTips.ServiceNotConnected)
                        );

                    serviceConnectionTicker.Start();

                    // Once a connection is established, immediately get the device status
                    GetTouchDeviceStatus();

                    // Initialisation success
                    return(true);
                }
                catch (System.ServiceModel.EndpointNotFoundException)
                {
                    // The Windows service is detected to be running but it is not functioning correctly
                    MessageBox.Show("There was an error connecting to the installed service.", "Touch Toggle Service Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                return(false);
            }
            else
            {
                // The user may need to install or start the Windows service
                if (allowUserAdminActionInput)
                {
                    return(GetUserAdminActionInput());
                }

                // Return initialisation failure
                return(false);
            }
        }
        public async Task TestIfConnectionWillRestartAfterShutdown()
        {
            List <IServiceConnection> connections = new List <IServiceConnection>
            {
                new SimpleTestServiceConnection(),
                new SimpleTestServiceConnection() // A connection which is not in Connected status could be replaced.
            };

            IServiceConnection connection = connections[1];

            using TestServiceConnectionContainer container = new TestServiceConnectionContainer(connections, factory: new SimpleTestServiceConnectionFactory());
            container.ShutdownForTest();

            await container.OnConnectionCompleteForTestShutdown(connection);

            // connection should be replaced, but it's StartAsync method should not be called.
            Assert.NotEqual(container.Connections[1], connection);
            Assert.NotEqual(ServiceConnectionStatus.Connected, container.Connections[1].Status);
        }
Example #33
0
 public SmsServiceActivity()
 {
     _connection = new PrattleSmsServiceConnection (this);
 }
 public void UnbindService(IServiceConnection connection)
 {
     context.UnbindService (connection);
 }
 public Binding()
 {
     connection = new MyServiceConnection (this);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="DownloaderServiceConnection"/> class.
 /// </summary>
 /// <param name="clientType">
 /// The client type.
 /// </param>
 /// <param name="serviceType">
 /// The service type.
 /// </param>
 public DownloaderServiceConnection(IDownloaderClient clientType, Type serviceType)
 {
     this.messenger = new Messenger(new Handler(this.SendMessage));
     this.serviceConnection = new ServiceConnection(this);
     this.clientType = clientType;
     this.serviceTypeType = serviceType;
 }
Example #37
0
 public Activity1()
 {
     connection = new MyServiceConnection (this);
 }
 public bool BindService(Intent intent, IServiceConnection connection, Bind bind)
 {
     return context.BindService (intent, connection, bind);
 }
		protected override void OnResume(){
			serviceConnection = new TunnelServiceConnection (OnBoundToTunnelService, OnUnBoundToTunnelService);
			ApplicationContext.BindService (new Intent (this, typeof(TunnelService)), serviceConnection, Bind.AutoCreate);
			Console.WriteLine("On Resume");
			logView.SetText(savedText,TextView.BufferType.Editable);
			scrollView.ScrollTo(0,logView.Height);
			scrollView.FullScroll(FocusSearchDirection.Down);
			SetupBluetooth();
			base.OnResume();
		}
Example #40
0
 public DotaCalculationBridge(IServiceConnection connectioToApi)
 {
     _connectioToApi = connectioToApi;
 }