public void ConnectToWebApp(WebOsWebAppSession webAppSession, bool joinOnly, ResponseListener connectionListener)
        {
            if (WebAppSessions == null)
                WebAppSessions = new Dictionary<string, WebOsWebAppSession>();

            if (AppToAppIdMappings == null)
                AppToAppIdMappings = new Dictionary<string, string>();

            if (webAppSession == null || webAppSession.LaunchSession == null)
            {
                Util.PostError(connectionListener, new ServiceCommandError(0, "You must provide a valid LaunchSession object"));

                return;
            }

            var tappId = webAppSession.LaunchSession.AppId;

            var tidKey = webAppSession.LaunchSession.SessionType == LaunchSessionType.WebApp ? "webAppId" : "appId";

            if (string.IsNullOrEmpty(tappId))
            {
                Util.PostError(connectionListener, new ServiceCommandError(-1, "You must provide a valid web app session"));

                return;
            }

            var appId = tappId;
            var idKey = tidKey;

            const string uri = "ssap://webapp/connectToApp";
            var payload = new JsonObject();

            try
            {
                payload.Add(idKey, JsonValue.CreateStringValue(appId));

            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch (Exception)
            {

            }

            var responseListener = new ResponseListener
            (
                loadEventArg =>
                {
                    var loadEventArgs = loadEventArg as LoadEventArgs;
                    if (loadEventArgs != null)
                    {
                        var jsonObj = (JsonObject)(loadEventArgs.Load.GetPayload());
                        var state = jsonObj.GetNamedString("state");
                        if (!state.Equals("Connected", StringComparison.OrdinalIgnoreCase))
                        {
                            if (joinOnly && state.Equals("WAITING_FOR_APP", StringComparison.OrdinalIgnoreCase))
                            {
                                Util.PostError(connectionListener,
                                    new ServiceCommandError(0, "Web app is not currently running"));
                            }
                            return;
                        }
                        var fullAppId = jsonObj.GetNamedString("appId");
                        if (!string.IsNullOrEmpty(fullAppId))
                        {
                            if (webAppSession.LaunchSession.SessionType == LaunchSessionType.WebApp && !AppToAppIdMappings.ContainsKey(fullAppId))
                                AppToAppIdMappings.Add(fullAppId, appId);
                            webAppSession.SetFullAppId(fullAppId);
                        }
                    }
                    if (connectionListener != null)
                        connectionListener.OnSuccess(loadEventArg);
                },
                serviceCommandError =>
                {
                    webAppSession.DisconnectFromWebApp();
                    var appChannelDidClose = false;
                    if (serviceCommandError != null && serviceCommandError.GetPayload() != null)
                        appChannelDidClose = serviceCommandError.GetPayload().ToString().Contains("app channel closed");

                    if (appChannelDidClose)
                    {
                        if (webAppSession.WebAppSessionListener != null)
                        {
                            webAppSession.WebAppSessionListener.OnWebAppSessionDisconnect(webAppSession);
                        }
                    }
                    else
                    {
                        Util.PostError(connectionListener, serviceCommandError);

                    }
                }
            );

            webAppSession.AppToAppSubscription = new UrlServiceSubscription(this, uri, payload, true, responseListener);;
            webAppSession.AppToAppSubscription.Subscribe();

            ////todo: this is a workaround! Normally the subscribed event should arrive sooner but now we suppose that the existing subscription was successfull
            //UrlServiceSubscription v;
            //if (subscriptions.ContainsKey(uri))
            //{
            //    subscriptions.TryGetValue(uri, out v);
            //    webAppSession.AppToAppSubscription = v;
            //}
            //else
            //{
            //    v = new UrlServiceSubscription(this, uri, payload, true, responseListener);
            //    subscriptions.TryAdd(uri, v);
            //    webAppSession.AppToAppSubscription = v;
            //    webAppSession.AppToAppSubscription.Subscribe();
            //}
        }
        public void LaunchWebApp(string webAppId, JsonObject ps, ResponseListener listener)
        {
            if (string.IsNullOrEmpty(webAppId))
            {
                Util.PostError(listener, new ServiceCommandError(-1, null));

                return;
            }

            var webAppSession = WebAppSessions.ContainsKey(webAppId) ? WebAppSessions[webAppId] : null;

            const string uri = "ssap://webapp/launchWebApp";
            var payload = new JsonObject();

            try
            {
                payload.Add("webAppId", JsonValue.CreateStringValue(webAppId));

                if (ps != null)
                    payload.Add("urlps", ps);
            }
            catch (Exception e)
            {
                throw e;
            }

            var responseListener = new ResponseListener
            (
                loadEventArg =>
                {
                    JsonObject obj;
                    if (loadEventArg is LoadEventArgs)
                        obj = (loadEventArg as LoadEventArgs).Load.GetPayload() as JsonObject;
                    else obj = (JsonObject)loadEventArg;

                    LaunchSession launchSession;

                    if (webAppSession != null)
                        launchSession = webAppSession.LaunchSession;
                    else
                    {
                        launchSession = LaunchSession.LaunchSessionForAppId(webAppId);
                        webAppSession = new WebOsWebAppSession(launchSession, this);
                        WebAppSessions.Add(webAppId,
                            webAppSession);
                    }
                    //todo: check this
                    // //     ,webAppSession.Connected = true;

                    launchSession.Service = this;
                    if (obj != null)
                    {
                        launchSession.SessionId = obj.GetNamedString("sessionId");
                        launchSession.SessionType = LaunchSessionType.WebApp;
                        launchSession.RawData = obj;
                    }

                    Util.PostSuccess(listener, webAppSession);

                },
                serviceCommandError => Util.PostError(listener, serviceCommandError)
            );

            var request = new ServiceCommand(this, uri, payload, responseListener);
            request.Send();
        }
        private WebOsWebAppSession WebAppSessionForLaunchSession(LaunchSession launchSession)
        {
            if (WebAppSessions == null)
                WebAppSessions = new Dictionary<String, WebOsWebAppSession>();

            if (launchSession.Service == null)
                launchSession.Service = this;

            WebOsWebAppSession webAppSession = WebAppSessions.ContainsKey(launchSession.AppId) ? WebAppSessions[launchSession.AppId] : null;

            if (webAppSession == null)
            {
                webAppSession = new WebOsWebAppSession(launchSession, this);
                WebAppSessions.Add(launchSession.AppId, webAppSession);
            }

            return webAppSession;
        }
 public WebOstvServiceSocketClientListener(WebOsWebAppSession webOsWebAppSession)
 {
     this.webOsWebAppSession = webOsWebAppSession;
 }
        private void OpenWebApp_Click(object sender, RoutedEventArgs e)
        {
            const string webappname = "SampleWebApp";

            var webostvService = (WebOstvService)model.SelectedDevice.GetServiceByName(WebOstvService.Id);

            var listener = new ResponseListener
                (
                loadEventArg =>
                {
                    var v = loadEventArg as LoadEventArgs;
                    if (v != null)
                    {
                        launchSession = v.Load.GetPayload() as WebOsWebAppSession;
                    }
                },
                serviceCommandError =>
                {
                    var msg =
                        new MessageDialog(
                            "Something went wrong; The application could not be started. Press 'Close' to continue");
                    msg.ShowAsync();
                }
                );

            webostvService.LaunchWebApp(webappname, listener);
        }
        private void MediaPlayerMedia_Click(object sender, RoutedEventArgs e)
        {
            var webostvService = (WebOstvService)model.SelectedDevice.GetServiceByName(WebOstvService.Id);

            if (launchSession == null && webostvService != null)
            {
                const string webappname = "MediaPlayer";

                var listener = new ResponseListener
                    (
                    loadEventArg =>
                    {
                        var v = loadEventArg as LoadEventArgs;
                        if (v != null)
                        {
                            launchSession = v.Load.GetPayload() as WebOsWebAppSession;

                            var listener2 = new ResponseListener
                                (
                                loadEventArg2 => webostvService.PlayMedia("http://connectsdk.com/files/8913/9657/0225/test_video.mp4", "video/mp4", "Sintel Trailer", "Blender Open Movie Project", "http://www.connectsdk.com/files/7313/9657/0225/test_video_icon.jpg", false, null),
                                serviceCommandError =>
                                {

                                });

                            if (launchSession != null) launchSession.Connect(listener2);
                        }
                    },
                    serviceCommandError =>
                    {
                        var msg =
                            new MessageDialog(
                                "Something went wrong; The application could not be started. Press 'Close' to continue");
                        msg.ShowAsync();
                    }
                    );

                webostvService.LaunchWebApp(webappname, listener);
            }
            else
            {
                if (webostvService != null)
                    webostvService.PlayMedia("http://www.connectsdk.com/files/8913/9657/0225/test_video.mp4", "video/mp4", "Sintel Trailer", "Blender Open Movie Project", "http://www.connectsdk.com/files/7313/9657/0225/test_video_icon.jpg", false, null);
            }
        }
        private void CloserWebApp_Click(object sender, RoutedEventArgs e)
        {
            var webostvService = (WebOstvService)model.SelectedDevice.GetServiceByName(WebOstvService.Id);

            var responseListener = new ResponseListener
            (
                loadEventArg =>
                {
                    launchSession = null;
                },
                serviceCommandError =>
                {
                    var msg =
                        new MessageDialog(
                            "Something went wrong; The application could not be stopped. Press 'Close' to continue");
                    msg.ShowAsync();
                }
            );

            webostvService.CloseWebApp(launchSession.LaunchSession, responseListener);
            launchSession = null;
        }
        private void CloseApp_Click(object sender, RoutedEventArgs e)
        {
            var webostvService = (WebOstvService)model.SelectedDevice.GetServiceByName(WebOstvService.Id);

            var responseListener = new ResponseListener
            (
                loadEventArg =>
                {
                    launchSession = null;
                },
                serviceCommandError =>
                {

                }
            );
            if (launchSession == null && webostvService != null)
                webostvService.CloseApp(applaunchSession, responseListener);
        }