Exemplo n.º 1
0
 public static ServerEventsClient RegisterHandlers(this ServerEventsClient client, Dictionary <string, ServerEventCallback> handlers)
 {
     foreach (var entry in handlers)
     {
         client.Handlers[entry.Key] = entry.Value;
     }
     return(client);
 }
Exemplo n.º 2
0
        public static Task <List <ServerEventUser> > GetChannelSubscribersAsync(this ServerEventsClient client)
        {
            var responseTask = client.ServiceClient.GetAsync(new GetEventSubscribers {
                Channels = client.Channels
            });

            return(responseTask.ContinueWith(task => task.Result.Select(x => x.ToServerEventUser()).ToList()));
        }
Exemplo n.º 3
0
        public static List <ServerEventUser> GetChannelSubscribers(this ServerEventsClient client)
        {
            var response = client.ServiceClient.Get(new GetEventSubscribers {
                Channels = client.Channels
            });

            return(response.Select(x => x.ToServerEventUser()).ToList());
        }
Exemplo n.º 4
0
        public static void UpdateSubscriber(this ServerEventsClient client, UpdateEventSubscriber request)
        {
            if (request.Id == null)
            {
                request.Id = client.ConnectionInfo.Id;
            }
            client.ServiceClient.Post(request);

            client.Update(subscribe: request.SubscribeChannels, unsubscribe: request.UnsubscribeChannels);
        }
Exemplo n.º 5
0
 public static void Post(this ServerEventsClient client,
                         SetterType message, string selector = null, string channel = null)
 {
     client.ServiceClient.Post(new PostObjectToChannel
     {
         SetterType = message,
         Channel    = channel ?? EventSubscription.UnknownChannel,
         Selector   = selector,
     });
 }
Exemplo n.º 6
0
 public static Task UnsubscribeFromChannelsAsync(this ServerEventsClient client, params string[] channels)
 {
     return(client.ServiceClient.PostAsync(new UpdateEventSubscriber {
         Id = client.ConnectionInfo.Id, UnsubscribeChannels = channels.ToArray()
     })
            .Then(x => {
         client.Update(unsubscribe: channels);
         return null;
     }));
 }
Exemplo n.º 7
0
 public static void PostRaw(this ServerEventsClient client, string selector, string message, string channel = null)
 {
     client.ServiceClient.Post(new PostRawToChannel
     {
         From     = client.SubscriptionId,
         Message  = message,
         Channel  = channel ?? EventSubscription.UnknownChannel,
         Selector = selector,
     });
 }
Exemplo n.º 8
0
 public static Task UpdateSubscriberAsync(this ServerEventsClient client, UpdateEventSubscriber request)
 {
     if (request.Id == null)
     {
         request.Id = client.ConnectionInfo.Id;
     }
     return(client.ServiceClient.PostAsync(request)
            .Then(x => {
         client.Update(subscribe: request.SubscribeChannels, unsubscribe: request.UnsubscribeChannels);
         return null;
     }));
 }
Exemplo n.º 9
0
        private void ConnectServerEvents()
        {
            if (serverEventsClient == null)
            {
                // var client = new ServerEventsClient("http://chat.servicestack.net", channels: "home")

                // bla.ybookz.com is a copy of the SS Chat sample, that sends 'HAHAHAHA' every second to all listeners
                //serverEventsClient = new ServerEventsClient("http://bla.ybookz.com/", channels: "home")
                //serverEventsClient = new ServerEventsClient("http://10.0.2.2:1337/", channels: "home")
                serverEventsClient = new ServerEventsClient("http://chat.servicestack.net", channels: "home")
                {
                    OnConnect = e => {
                        connectMsg = e;
                    },
                    OnCommand = a => {
                        commands.Add(a);
                    },
                    OnHeartbeat = () => {
                        RunOnUiThread(() => {
                            try
                            {
                                Toast.MakeText(this, "Heartbeat", ToastLength.Short).Show();
                            }
                            catch {}
                        });
                    },
                    OnMessage = a => {
                        msgs.Add(a);
                        if (lastText != a.Data)
                        {
                            lastText = a.Data ?? "";
                            RunOnUiThread(() => {
                                try
                                {
                                    Toast.MakeText(this, lastText, ToastLength.Short).Show();
                                }
                                catch {}
                            });
                        }
                    },
                    OnException = ex => {
                        AddMessage("OnException: " + ex.Message);
                        errors.Add(ex);
                    },
                    HeartbeatRequestFilter = x => {
                        AddMessage("HeartbeatRequestFilter");
                    },
                };

                AddMessage("Started Listening...");
                serverEventsClient.Start();
            }
        }
Exemplo n.º 10
0
        private static void CreateServerEventsClient(int noOfClients)
        {
            var clients = new List<ServerEventsClient>();
            for (int i = 0; i < noOfClients; i++)
            {
                var clientId = i;
                var client = new ServerEventsClient(Url, "HOME") {
                    OnMessage = e => Console.WriteLine("ServerEventsClient #{0} {1}", clientId, e.Data)
                }.Start();

                clients.Add(client);
            }
        }
        public MainPage()
        {
            InitializeComponent();

            string baseUri = "http://irrigationcontroller.azurewebsites.net/";
            client = new JsonServiceClient(baseUri);
            seClient = new ServerEventsClient(baseUri, "relay");
            seClient.OnMessage = HandleRelayCommand;

            seClient.Start();

            InitGPIO();
        }
Exemplo n.º 12
0
        public override void Configure(Container container)
        {
            container.Register <IDbConnectionFactory>(
                new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider));

            using (var db = container.Resolve <IDbConnectionFactory>().Open())
            {
                db.DropAndCreateTable <Rockstar>();
                db.InsertAll(SeedRockstars);
            }

            Plugins.Add(new AutoQueryFeature {
                MaxLimit = 100
            });
            Plugins.Add(new AdminFeature());

            var msgs  = new List <string>();
            int count = 0;

            var client = new ServerEventsClient("http://chat.servicestack.net", "home")
            {
                OnMessage = m =>
                {
                    try
                    {
                        lock (msgs)
                        {
                            msgs.Add(m.Dump());
                        }
                    }
                    catch (Exception ex)
                    {
                        msgs.Add("OnMessage Exception: " + ex.Message);
                    }
                }
            }.Start();

            timer = new Timer(_ =>
            {
                lock (msgs)
                {
                    for (; count < msgs.Count; count++)
                    {
                        Console.WriteLine(msgs[count]);
                    }
                }
                timer.Change(1000, Timeout.Infinite);
            }, null, 1000, Timeout.Infinite);
        }
Exemplo n.º 13
0
        private static void CreateServerEventsClient(int noOfClients)
        {
            var clients = new List <ServerEventsClient>();

            for (int i = 0; i < noOfClients; i++)
            {
                var clientId = i;
                var client   = new ServerEventsClient(Url, "HOME")
                {
                    OnMessage = e => Console.WriteLine("ServerEventsClient #{0} {1}", clientId, e.Data)
                }.Start();

                clients.Add(client);
            }
        }
 public static void UpdateCookiesFromIntent(this MainActivity mainActivity, ServerEventsClient client)
 {
     if (mainActivity.Intent == null)
         return;
     string cookieStr = mainActivity.Intent.GetStringExtra("SSCookie");
     if (string.IsNullOrEmpty(cookieStr) || !cookieStr.Contains(';'))
         return;
     var cookies = cookieStr.Split(';');
     foreach (var c in cookies)
     {
         var key = c.Split('=')[0].Trim();
         var val = c.Split('=')[1].Trim();
         client.ServiceClient.SetCookie(key, val);
     }
 }
Exemplo n.º 15
0
        public ServerEventsClient CreateServerEventsClient(params string[] channels)
        {
            ServicePointManager.DefaultConnectionLimit = 10;
            var client = new ServerEventsClient(GetHostUrl(), channels)
            {
                OnConnect   = evt => connectMsg = evt,
                OnCommand   = ServerEventCommands.Add,
                OnMessage   = ServerEventMessages.Add,
                OnException = ServerEventErrors.Add,
                //OnReconnect = Reconnects.Add,
                //OnUpdate = Updates.Add,
                ServiceClient = ServiceClient,
            };

            return(client);
        }
        public static Task ChangeChannel(this ServerEventsClient client, string channel, ChatCommandHandler cmdReceiver)
        {
            if (cmdReceiver.FullHistory.ContainsKey(channel) && client.Channels.Contains(channel))
            {
                cmdReceiver.ChangeChannel(channel);
                cmdReceiver.SyncAdapter();
                return(Task.CompletedTask);
            }

            return(client.SubscribeToChannelsAsync(channel)
                   .Then(t =>
            {
                cmdReceiver.CurrentChannel = channel;
                return client.UpdateChatHistory(cmdReceiver);
            }));
        }
Exemplo n.º 17
0
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            client           = new ServerEventsClient("http://localhost:25036/", "home");
            client.OnMessage = eventMessage =>
            {
                message = eventMessage.Json.FromJson <HelloResponse>().Result;
            };
            client.OnConnect = connect =>
            {
                Console.WriteLine("Connected");
            };
            client.Start();
            base.Initialize();
        }
 public static Task UpdateChatHistory(this ServerEventsClient client, ChatCommandHandler cmdReceiver)
 {
     return(client.ServiceClient.GetAsync(new GetChatHistory {
         Channels = client.Channels
     }).Success(chatHistory =>
     {
         cmdReceiver.FullHistory = new Dictionary <string, List <ChatMessage> >();
         foreach (var channel in client.Channels)
         {
             var currentChannel = channel;
             cmdReceiver.FullHistory.Add(channel,
                                         chatHistory.Results
                                         .Where(x => x.Channel == currentChannel)
                                         .Select(x => x).ToList());
         }
         cmdReceiver.SyncAdapter();
     }));
 }
        public async Task Does_dispose_SSE_Connection_when_Exception_in_OnInit_handler()
        {
            ServerEventsClient client = null;

            using (client = new ServerEventsClient(Config.AbsoluteBaseUri)
            {
                // OnException = e => client.Dispose()
            })
            {
                try
                {
                    await client.Connect();
                }
                catch (WebException e)
                {
                    Assert.That(e.GetStatus(), Is.EqualTo(HttpStatusCode.InternalServerError));
                }
            }
        }
        public async Task Does_reconnect_when_remote_AppServer_restarts()
        {
            var client = new ServerEventsClient("http://localhost:11001", "home")
            {
                OnConnect   = ctx => "OnConnect: {0}".Print(ctx.Channel),
                OnCommand   = msg => "OnCommand: {0}".Print(msg.Data),
                OnException = ex => "OnException: {0}".Print(ex.Message),
                OnMessage   = msg => "OnMessage: {0}".Print(msg.Data),
                OnHeartbeat = () => "OnHeartbeat".Print()
            };

            client.Handlers["chat"] = (source, msg) =>
            {
                "Received Chat: {0}".Print(msg.Data);
            };

            await client.Connect();

            await Task.Delay(TimeSpan.FromMinutes(10));
        }
        public async Task Does_reconnect_when_remote_AppServer_restarts()
        {
            var client = new ServerEventsClient("http://localhost:11001", "home")
            {
                OnConnect = ctx => "OnConnect: {0}".Print(ctx.Channel),
                OnCommand = msg => "OnCommand: {0}".Print(msg.Data),
                OnException = ex => "OnException: {0}".Print(ex.Message),
                OnMessage = msg => "OnMessage: {0}".Print(msg.Data),
                OnHeartbeat = () => "OnHeartbeat".Print()
            };

            client.Handlers["chat"] = (source, msg) =>
            {
                "Received Chat: {0}".Print(msg.Data);
            };

            await client.Connect();

            await Task.Delay(TimeSpan.FromMinutes(10));
        }
        public static void UpdateCookiesFromIntent(this MainActivity mainActivity, ServerEventsClient client)
        {
            if (mainActivity.Intent == null)
            {
                return;
            }
            string cookieStr = mainActivity.Intent.GetStringExtra("SSCookie");

            if (string.IsNullOrEmpty(cookieStr) || !cookieStr.Contains(';'))
            {
                return;
            }
            var cookies = cookieStr.Split(';');

            foreach (var c in cookies)
            {
                var key = c.Split('=')[0].Trim();
                var val = c.Split('=')[1].Trim();
                client.ServiceClient.SetCookie(key, val);
            }
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            //ServiceClientHelper sch = new ServiceClientHelper();
            ServerEventsClient eventsClient = GlobalContext.Instance.CreateServerEventsClient("test");

            eventsClient.OnMessage = msg => Console.WriteLine($"OnMessage - {msg.Data}");
            eventsClient.OnJoin    = jn => Console.WriteLine($"OnJoin - {jn.DisplayName}");
            eventsClient.OnCommand = cm => Console.WriteLine($"OnCommand - {cm.Json}");
            //eventsClient.OnReconnect => Console.WriteLine($"OnReconnect - ");
            eventsClient.OnException = ex => Console.WriteLine($"OnException - {ex.Message}");
            eventsClient.Start();

            string key = "";

            while (key != "exit")
            {
                key = Console.ReadLine();

                if (key == "id")
                {
                    Console.WriteLine("My Id:{0}", eventsClient.ConnectionInfo.Id);
                }
                if (key == "notify")
                {
                    foreach (var sub in eventsClient.GetChannelSubscribers())
                    {
                        Console.WriteLine($"Get Channel subs:{sub.Channels} - {sub.UserId}");
                    }
                }
                if (key == "data")
                {
                    Console.WriteLine($"Post a SyncEventData object to the test channel.");
                    //eventsClient.ServiceClient.Post(new SyncEventData
                    //{
                    //    Channel = "test",
                    //    Selector = "test",
                    //    //From = eventsClient.SubscriptionId,
                    //    FromUserId = eventsClient.ConnectionInfo.UserId,
                    //    Message = $"From Client {eventsClient.ConnectionInfo.Id}",
                    //    EntityInfo = new EventEntityInfo
                    //    {
                    //        EntityType = "".GetType(),
                    //        EntityRecordId = 1,
                    //        ActionTriggered = "CREATE"
                    //    }
                    //});
                }
                if (key.StartsWithIgnoreCase("sub"))
                {
                    Console.WriteLine($"Subscribe and Post a SyncEventData object to the {key.Substring(key.IndexOf("-"))} channel.");
                    eventsClient.SubscribeToChannels(key.Substring(key.IndexOf("-")));
                    //eventsClient.ServiceClient.Post(new SyncEventData
                    //{
                    //    Channel = key.Substring(key.IndexOf("-")),
                    //    Selector = "test",
                    //    //From = eventsClient.SubscriptionId,
                    //    FromUserId = eventsClient.ConnectionInfo.UserId,
                    //    Message = $"From Client {eventsClient.ConnectionInfo.Id} on chanel{eventsClient.ConnectionInfo.Channel}",
                    //    EntityInfo = new EventEntityInfo
                    //    {
                    //        EntityType = "".GetType(),
                    //        EntityRecordId = 1,
                    //        ActionTriggered = "CREATE"
                    //    }
                    //});
                }
                if (key.StartsWith("unsub", true, CultureInfo.CurrentCulture))
                {
                    Console.WriteLine($"Un-Subscribe and Post a SyncEventData object to the {key.Substring(key.IndexOf("-"))} channel.");
                    eventsClient.UnsubscribeFromChannels(key.Substring(key.IndexOf("-")));
                    //this should fail?
                    //eventsClient.ServiceClient.Post(new SyncEventData
                    //{
                    //    Channel = key.Substring(key.IndexOf("-")),
                    //    Selector = "test",
                    //    //From = eventsClient.SubscriptionId,
                    //    FromUserId = eventsClient.ConnectionInfo.UserId,
                    //    Message = $"From Client {eventsClient.ConnectionInfo.Id} on chanel{eventsClient.ConnectionInfo.Channel}",
                    //    EntityInfo = new EventEntityInfo
                    //    {
                    //        EntityType = "".GetType(),
                    //        EntityRecordId = 1,
                    //        ActionTriggered = "CREATE"
                    //    }
                    //});
                }
            }
        }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            LogManager.LogFactory = new GenericLogFactory(Console.WriteLine);

            // 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 sendButton = FindViewById <Button>(Resource.Id.sendMessageButton);

            messageBox = FindViewById <EditText>(Resource.Id.message);
            SupportToolbar toolbar = FindViewById <SupportToolbar>(Resource.Id.toolbar);

            drawerLayout   = FindViewById <DrawerLayout>(Resource.Id.drawer_layout);
            navigationView = FindViewById <NavigationView>(Resource.Id.nav_view);
            rightDrawer    = FindViewById <ListView>(Resource.Id.right_drawer);
            var messageHistoryList = FindViewById <ListView>(Resource.Id.messageHistory);
            var chatBackground     = FindViewById <ImageView>(Resource.Id.chat_background);

            InitDefaultBackground(chatBackground);

            navigationView.Tag = 0;
            rightDrawer.Tag    = 1;

            var messageHistoryAdapter = new MessageListViewAdapter(this, new List <ChatMessage>(), () => this.subscriberList);

            messageHistoryList.Adapter = messageHistoryAdapter;

            var channels = new[] { "home" };

            cmdReceiver = new ChatCommandHandler(this, messageHistoryAdapter, "home");
            var activity = this;

            client = new ServerEventsClient(BaseUrl, channels)
            {
                OnConnect = connectMsg =>
                {
                    client.UpdateChatHistory(cmdReceiver)
                    .ContinueWith(t =>
                                  connectMsg.UpdateUserProfile(activity));
                },
                OnCommand = command =>
                {
                    if (command is ServerEventJoin)
                    {
                        client.GetChannelSubscribersAsync()
                        .ContinueWith(t => {
                            subscriberList = t.Result;
                            Application.SynchronizationContext.Post(_ => {
                                // Refresh profile icons when users join
                                messageHistoryAdapter.NotifyDataSetChanged();
                            }, null);
                        });
                    }
                },
                OnException = error => {
                    Application.SynchronizationContext.Post(
                        _ => { Toast.MakeText(this, "Error : " + error.Message, ToastLength.Long); }, null);
                },
                //ServiceClient = new JsonHttpClient(BaseUrl),
                Resolver = new MessageResolver(cmdReceiver)
            };
            client.RegisterNamedReceiver <ChatReceiver>("cmd");
            client.RegisterNamedReceiver <TvReciever>("tv");
            client.RegisterNamedReceiver <CssReceiver>("css");

            SetSupportActionBar(toolbar);

            var rightDataSet = new List <string>(commands.Keys);
            var rightAdapter = new ActionListViewAdapter(this, rightDataSet);

            rightDrawer.Adapter    = rightAdapter;
            rightDrawer.ItemClick += (sender, args) =>
            {
                Application.SynchronizationContext.Post(_ =>
                {
                    messageBox.Text = commands[rightDataSet[args.Position]];
                    drawerLayout.CloseDrawer(rightDrawer);
                }, null);
            };

            drawerToggle = new ChatActionBarDrawerToggle(
                this,                          //Host Activity
                drawerLayout,                  //DrawerLayout
                toolbar,                       // Instance of toolbar, if you use other ctor, the hamburger icon/arrow animation won't work..
                Resource.String.openDrawer,    //Opened Message
                Resource.String.closeDrawer    //Closed Message
                );

            SupportActionBar.SetHomeButtonEnabled(true);
            SupportActionBar.SetDisplayShowTitleEnabled(true);

            drawerLayout.SetDrawerListener(drawerToggle);
            drawerToggle.SyncState();

            navigationView.NavigationItemSelected += OnChannelClick;
            sendButton.Click += async(e, args) => { await OnSendClick(e, args); };
        }
Exemplo n.º 25
0
        private static ServerEventsClient CreateServerEventsClient()
        {
            var client = new ServerEventsClient(Config.AbsoluteBaseUri);

            return(client);
        }
Exemplo n.º 26
0
 public static Task <AuthenticateResponse> AuthenticateAsync(this ServerEventsClient client, Authenticate request)
 {
     return(client.ServiceClient.PostAsync(request));
 }
Exemplo n.º 27
0
 public static AuthenticateResponse Authenticate(this ServerEventsClient client, Authenticate request)
 {
     return(client.ServiceClient.Post(request));
 }
Exemplo n.º 28
0
        private void ConnectServerEvents()
        {
            if (serverEventsClient == null)
            {
                // var client = new ServerEventsClient("http://chat.servicestack.net", channels: "home")

                // bla.ybookz.com is a copy of the SS Chat sample, that sends 'HAHAHAHA' every second to all listeners
                //serverEventsClient = new ServerEventsClient("http://bla.ybookz.com/", channels: "home")
                //serverEventsClient = new ServerEventsClient("http://10.0.2.2:1337/", channels: "home")
                serverEventsClient = new ServerEventsClient("http://chat.servicestack.net", channels: "home")
                {
                    OnConnect = e => {
                        connectMsg = e;
                    },
                    OnCommand = a => {
                        commands.Add(a);
                    },
                    OnHeartbeat = () => {

                        RunOnUiThread(() => {
                            try
                            {
                                Toast.MakeText(this, "Heartbeat", ToastLength.Short).Show();
                            }
                            catch {}
                        });
                    },
                    OnMessage = a => {
                        msgs.Add(a);
                        if (lastText != a.Data)
                        {
                            lastText = a.Data ?? "";
                            RunOnUiThread(() => {
                                try
                                {
                                    Toast.MakeText(this, lastText, ToastLength.Short).Show();
                                }
                                catch {}
                            });
                        }
                    },
                    OnException = ex => {
                        AddMessage("OnException: " + ex.Message);
                        errors.Add(ex);
                    },
                    HeartbeatRequestFilter = x => {
                        AddMessage("HeartbeatRequestFilter");
                    },
                };

                AddMessage("Started Listening...");
                serverEventsClient.Start();
            }
        }
Exemplo n.º 29
0
 public static void PostChat(this ServerEventsClient client,
                             string message, string channel = null)
 {
     client.ServiceClient.PostChat(client.SubscriptionId, message, channel);
 }
		protected override void OnCreate(Bundle bundle)
		{
			base.OnCreate(bundle);

            LogManager.LogFactory = new GenericLogFactory(Console.WriteLine);

			// 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 sendButton = FindViewById<Button>(Resource.Id.sendMessageButton);
			messageBox = FindViewById<EditText>(Resource.Id.message);
			SupportToolbar mToolbar = FindViewById<SupportToolbar>(Resource.Id.toolbar);
			mDrawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
			navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
			mRightDrawer = FindViewById<ListView>(Resource.Id.right_drawer);
			var messageHistoryList = FindViewById<ListView>(Resource.Id.messageHistory);
            var chatBackground = FindViewById<ImageView>(Resource.Id.chat_background);
            InitDefaultBackground(chatBackground);

            navigationView.Tag = 0;
			mRightDrawer.Tag = 1;

			var messageHistoryAdapter = new MessageListViewAdapter(this, new List<ChatMessage>(), () => this.subscriberList);
			messageHistoryList.Adapter = messageHistoryAdapter;

		    var txtUser = FindViewById<TextView>(Resource.Id.txtUserName);
		    var imgProfile = FindViewById<ImageView>(Resource.Id.imgProfile);
		    var channels = new[] {"home"};
			cmdReceiver = new ChatCommandHandler (this, messageHistoryAdapter, "home");

		    client = new ServerEventsClient(BaseUrl, channels)
		    {
		        OnConnect = connectMsg =>
		        {
		            client.UpdateChatHistory(cmdReceiver).ConfigureAwait(false);
		            connectMsg.UpdateUserProfile(txtUser, imgProfile);
		        },
                OnCommand = command =>
                {
                    if (command is ServerEventJoin)
                    {
						client.GetSubscribers().ContinueWith(result => {
							result.Wait();
                            subscriberList = result.Result;
                            Application.SynchronizationContext.Post(_ =>
                            {
                                // Refresh profile icons when users join
                                messageHistoryAdapter.NotifyDataSetChanged();
                            }, null);
						});
                    }  
                },
		        OnException =
		            error =>
		            {
		                Application.SynchronizationContext.Post(
		                    _ => { Toast.MakeText(this, "Error : " + error.Message, ToastLength.Long); }, null);
		            },
		        //ServiceClient = new JsonHttpClient(BaseUrl),
		        Resolver = new MessageResolver(cmdReceiver)
		    };
		    client.RegisterNamedReceiver<ChatReceiver>("cmd");
            client.RegisterNamedReceiver<TvReciever>("tv");
            client.RegisterNamedReceiver<CssReceiver>("css");
            
            SetSupportActionBar(mToolbar);

		    var mRightDataSet = new List<string>(commands.Keys);
		    var mRightAdapter = new ActionListViewAdapter(this, mRightDataSet);
			mRightDrawer.Adapter = mRightAdapter;
		    mRightDrawer.ItemClick += (sender, args) =>
		    {
               Application.SynchronizationContext.Post(_ =>
               {
                   messageBox.Text = commands[mRightDataSet[args.Position]];
                   mDrawerLayout.CloseDrawer(mRightDrawer);
               },null);
		    };

			mDrawerToggle = new ChatActionBarDrawerToggle(
				this,							//Host Activity
				mDrawerLayout,					//DrawerLayout
				mToolbar,						// Instance of toolbar, if you use other ctor, the hamburger icon/arrow animation won't work..
				Resource.String.openDrawer,		//Opened Message
				Resource.String.closeDrawer		//Closed Message
			);

			SupportActionBar.SetHomeButtonEnabled(true);
			SupportActionBar.SetDisplayShowTitleEnabled(true);

			mDrawerLayout.SetDrawerListener(mDrawerToggle);
			mDrawerToggle.SyncState();

		    navigationView.NavigationItemSelected += OnChannelClick;
            sendButton.Click += OnSendClick;
		}
 public static void SendMessage(this ServerEventsClient client, PostRawToChannel request)
 {
     client.ServiceClient.Post(request);
 }
Exemplo n.º 32
0
        static void Main(string[] args)
        {
            var skey   = AesUtils.CreateKey();
            var keyXml = skey.ToXml();
            var kUrl   = skey.ToBase64UrlSafe();

            JarsCore.Container = MEFBusinessLoader.Init();
            Logger.Info("MEF Loaded!");

            //add license
            string licPath = "~/ServiceStackLicense.txt".MapAbsolutePath();

            Logger.Info($"Registering ServiceStack Licence looking for:{licPath}");
            try
            {
                Licensing.RegisterLicenseFromFileIfExists(licPath);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Press any key to close");
                Console.ReadLine();
                return;
            }
            //setup service
            var listeningOn = args.Length == 0 ? GetHostUrl() : args;
            //start setting up the service stack host
            JarsServiceAppHost appHost = new JarsServiceAppHost(AssemblyLoaderUtil.ServicesAssemblies.ToArray());

            appHost.OnConnect   = (evtSub, dictVal) => { Console.WriteLine($"OnConnect - Connection UserId:{evtSub.UserId} UserName: {evtSub.UserName} dictVals:{dictVal.Values}"); };
            appHost.OnSubscribe = (evtSub) => { Console.WriteLine($"OnSubscribe - sub:{evtSub.UserId}"); };
            appHost.OnPublish   = (sub, res, msg) => { if (!msg.Contains("cmd.onHeartbeat"))
                                                       {
                                                           Console.WriteLine($"Publish - DisplayName:{sub.DisplayName} Res.Status:{res.StatusCode} MsgLen:{msg.Length}");
                                                       }
            };
            appHost.OnUnsubscribe            = (evtSub) => { Console.WriteLine($"OnUnsubscribe - sub:{evtSub.UserId}"); };
            appHost.LimitToAuthenticatedUser = true;
            try
            {   //start the service
                appHost.Init().Start(listeningOn);
            }
            catch (Exception ex)
            {
                Logger.Info($"Error:{ex.Message}");
                Console.WriteLine("\r\n Press key to close app");
                Console.ReadLine();
                return;
            }

            string listeningOnVals = "";

            listeningOn.ToList().ForEach(s => listeningOnVals += $"ip: {s.ToString()}{Environment.NewLine}");

            Console.WriteLine($"AppHost Created at {DateTime.Now}, listening on: {Environment.NewLine}{listeningOnVals}");

            Console.WriteLine("write 'exit' to close, 'notify' to send notification to all subscribers, test to notify 'test' channel or sub-[chanel name] to notify that channel");

            //resolve the events plugin loaded in the configuration.
            IServerEvents se = appHost.TryResolve <IServerEvents>();

            int    i   = 0;
            string key = "start";

            while (key != "exit")
            {
                Console.Write("Subs: {0}", se.GetAllSubscriptionInfos().Count);
                key = Console.ReadLine();

                if (key == "notify")
                {
                    se.NotifyAll($"Notify All count({i})");
                }

                if (key == "test")
                {
                    se.NotifyChannel("test", $"Notify all in test channel : count({i})");
                }

                if (key.Contains("sub"))
                {
                    se.NotifyChannel(key.Substring(key.IndexOf("-")), $"Notify channel {key.Substring(key.IndexOf("-"))} : count({i})");
                }

                if (key.Contains("infos"))
                {
                    List <SubscriptionInfo> infs = se.GetAllSubscriptionInfos();

                    foreach (var si in infs)
                    {
                        Console.Write($"DisplayName:{si.DisplayName}, Auth:{si.IsAuthenticated}, SubId:{si.SubscriptionId}, UserId:{si.UserId}, UserName:{si.UserName}");
                        Console.WriteLine();
                    }
                }
                if (key.Contains("login"))
                {
                    ServerEventsClient   client = new ServerEventsClient("http://localhost:3337/", "test");
                    AuthenticateResponse aResp  = client.Authenticate(new Authenticate()
                    {
                        UserName = "******", Password = "******", RememberMe = true
                    });
                    Console.Write($"Auth DisplayName:{aResp.DisplayName}, BT:{aResp.BearerToken}, Un:{aResp.UserName}, UserId:{aResp.UserId}");
                }
                if (key.Contains("req"))
                {
                }
                i++;
            }
        }