public void VolumeUp(ResponseListener listener)
        {
            const string uri = "ssap://audio/volumeUp";
            var request = new ServiceCommand(this, uri, null, listener);

            request.Send();
        }
        public void GetApplication(string appName, ResponseListener listener)
        {
            var responseListener = new ResponseListener
            (
                loadEventArg =>
                {
                    var strObj = LoadEventArgs.GetValue<string>(loadEventArg);

                    var appId = new AppInfo(Util.DecToHex(strObj));

                    if (!string.IsNullOrEmpty(strObj))
                    {
                        Util.PostSuccess(listener, appId);
                    }
                },
                serviceCommandError =>
                {
                    if (listener != null)
                        Util.PostError(listener, serviceCommandError);
                }
            );

            var uri = UdapPathApptoappData + appName;
            var requestUrl = GetUdapRequestUrl(uri);

            var command = new ServiceCommand(this, requestUrl, null, responseListener) { HttpMethod = ServiceCommand.TypeGet };
            command.Send();
        }
        public void GetChannelList(ResponseListener listener)
        {
            var requestUrl = GetUdapRequestUrl(UdapPathData, TargetChannelList);

            var responseListener = new ResponseListener
            (
                loadEventArg =>
                {
                    var lea = loadEventArg as LoadEventArgs;
                    if (lea == null) return;
                    var load = lea.Load.GetPayload() as HttpResponseMessage;

                    if (load == null) return;
                    var strObj = load.Content.ReadAsStringAsync().Result;

                    var ser = new XmlSerializer(typeof(envelope));
                    var obj = ser.Deserialize(new StringReader(strObj)) as envelope;

                    if (obj != null)
                    {
                        var channels = new List<ChannelInfo>();
                        for (var i = 0; i < obj.dataList.data.Count(); i++)
                        {
                            channels.Add(new ChannelInfo
                            {
                                Id = obj.dataList.data[i].displayMajor.ToString(),
                                Number = obj.dataList.data[i].displayMajor.ToString(),
                                Name = obj.dataList.data[i].chname.ToString(),
                                MajorNumber = obj.dataList.data[i].displayMajor,
                                MinorNumber = obj.dataList.data[i].displayMinor,
                            });
                        }
                        Util.PostSuccess(listener, channels);
                    }
                    else
                    {
                        Util.PostError(listener, new ServiceCommandError(0, null));
                    }
                },
                serviceCommandError => Util.PostError(listener, serviceCommandError)
            );

            var command = new ServiceCommand(this, requestUrl, null, responseListener) { HttpMethod = ServiceCommand.TypeGet };
            command.Send();
        }
        private void MoveMouse()
        {
            var requestUrl = GetUdapRequestUrl(UdapPathCommand);

            var x = (int)mMouseDistance.X;
            var y = (int)mMouseDistance.Y;

            var ps = new Dictionary<string, string>
            {
                {"name", "HandleTouchMove"},
                {"x", x.ToString()},
                {"y", y.ToString()}
            };

            mMouseDistance.X = mMouseDistance.Y = 0;

            var mouseService = this;

            var responseListener = new ResponseListener
            (
                loadEventArg =>
                {
                    if (mMouseDistance.X > 0 || mMouseDistance.Y > 0)
                        mouseService.MoveMouse();
                    else
                        mMouseIsMoving = false;
                },
                serviceCommandError =>
                {
                    Logger.Current.AddMessage("Netcast TV's mouse move has failed");
                    mMouseIsMoving = false;
                }
            );

            var httpMessage = GetUdapMessageBody(UdapApiCommand, ps);

            var request = new ServiceCommand(this, requestUrl, httpMessage, responseListener);
            request.Send();
        }
        private void SetMouseCursorVisible(bool visible, ResponseListener listener)
        {
            var requestUrl = GetUdapRequestUrl(UdapPathEvent);

            var ps = new Dictionary<string, string>
            {
                {"name", "CursorVisible"},
                {"value", visible ? "true" : "false"},
                {"mode", "auto"}
            };

            var httpMessage = GetUdapMessageBody(UdapApiEvent, ps);

            var request = new ServiceCommand(this, requestUrl, httpMessage, listener);
            request.Send();
        }
        private void GetVolumeStatus(ResponseListener listener)
        {
            var responseListener = new ResponseListener
            (
                loadEventArg =>
                {
                    var strObj =
                        (new StreamReader(
                            (((HttpResponseMessage)((LoadEventArgs)loadEventArg).Load.GetPayload()).Content.ReadAsStreamAsync()
                                .Result)))
                            .ReadToEnd();

                    var reader = Util.GenerateStreamFromstring(strObj);
                    var xmlReader = XmlReader.Create(reader);
                    var isMute = false;
                    var volume = 0;
                    while (xmlReader.Read())
                    {
                        if (xmlReader.Name == "mute")
                            isMute = bool.Parse(xmlReader.ReadElementContentAsString());
                        if (xmlReader.Name == "level")
                            volume = int.Parse(xmlReader.ReadElementContentAsString());
                    }

                    Util.PostSuccess(listener, new VolumeStatus(isMute, volume));
                },
                serviceCommandError => Util.PostError(listener, serviceCommandError)
            );

            var requestUrl = GetUdapRequestUrl(UdapPathData, TargetVolumeInfo);

            var request = new ServiceCommand(this, requestUrl, null,
                responseListener) { HttpMethod = ServiceCommand.TypeGet };
            request.Send();
        }
        private void HandleKeyboardInput(string state, string buffer)
        {
            var responseListener = new ResponseListener();

            var requestUrl = GetUdapRequestUrl(UdapPathEvent);

            var ps = new Dictionary<string, string> { { "name", "TextEdited" }, { "state", state }, { "value", buffer } };

            var httpMessage = GetUdapMessageBody(UdapApiEvent, ps);

            var request = new ServiceCommand(this, requestUrl, httpMessage, responseListener);
            request.Send();
        }
        public void GetExternalInputList(ResponseListener listener)
        {
            const string uri = "ssap://tv/getExternalInputList";

            var responseListener = new ResponseListener
            (
            loadEventArg =>
            {
                var res = LoadEventArgs.GetValue<JsonObject>(loadEventArg);
                if (res != null)
                {
                    var devices = res.GetNamedArray("devices");
                    Util.PostSuccess(listener, devices);
                }
            },
            serviceCommandError => Util.PostError(listener, serviceCommandError));

            var request = new ServiceCommand(this, uri, null, responseListener);
            request.Send();
        }
        public void GetSystemInfo(ResponseListener listener)
        {
            const string uri = "ssap://api/getServiceList";

            var responseListener = new ResponseListener
                (
                loadEventArg =>
                {
                    var loadEventArgs = loadEventArg as LoadEventArgs;
                    if (loadEventArgs == null) return;
                    var jsonObj = (JsonObject) (loadEventArgs.Load.GetPayload());
                    if (jsonObj.ContainsKey("features"))
                    {
                        listener.OnSuccess(new ServiceCommandError(0, jsonObj.GetNamedArray("features")));
                    }
                },
                serviceCommandError => Util.PostError(listener, serviceCommandError)
                );

            var request = new ServiceCommand(this, uri, null, responseListener);
            request.Send();
        }
        public void FastForward(ResponseListener listener)
        {
            const string uri = "ssap://media.controls/fastForward";
            var request = new ServiceCommand(this, uri, null, listener);

            request.Send();
        }
        public void GetAppList(ResponseListener listener)
        {
            const string uri = "ssap://com.webos.applicationManager/listApps";

            var responseListener = new ResponseListener
                (
                loadEventArg =>
                {
                    try
                    {
                        var jsonObj = (JsonObject)(((LoadEventArgs)loadEventArg).Load.GetPayload());

                        var apps = jsonObj.GetNamedArray("apps");
                        var appList = (from t in apps
                            select t.GetObject()
                            into appObj
                            where appObj != null
                            select new AppInfo(appObj.GetNamedString("id"))
                            {
                                Name = appObj.GetNamedString("title"), Url = appObj.GetNamedString("icon"), RawData = appObj
                            }).ToList();

                        Util.PostSuccess(listener, appList);
                    }
                    catch
                    {
                    }
                },
                serviceCommandError => Util.PostError(listener, serviceCommandError)
                );
            var request = new ServiceCommand(this, uri, null, responseListener);
            request.Send();
        }
        private void SendToast(JsonObject payload, ResponseListener listener)
        {
            if (!payload.ContainsKey("iconData"))
            {
                //todo: find a way to get the icon and add it to the request
                //Context context = DiscoveryManager.getInstance().getContext();

                //try
                //{
                //    Drawable drawable = context.getPackageManager().getApplicationIcon(context.getPackageName());

                //    if (drawable != null)
                //    {
                //        BitmapDrawable bitDw = ((BitmapDrawable)drawable);
                //        Bitmap bitmap = bitDw.getBitmap();

                //        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                //        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);

                //        byte[] bitmapByte = stream.toByteArray();
                //        bitmapByte = Base64.encode(bitmapByte, Base64.NO_WRAP);
                //        String bitmapData = new String(bitmapByte);

                //        payload.put("iconData", bitmapData);
                //        payload.put("iconExtension", "png");
                //    }
                //}
                //catch (NameNotFoundException e)
                //{
                //    e.printStackTrace();
                //}
                //catch (JSONException e)
                //{
                //    e.printStackTrace();
                //}
            }

            const string uri = "palm://system.notifications/createToast";
            var request = new ServiceCommand(this, uri, payload, listener);
            request.Send();
        }
        private void DisplayMedia(JsonObject ps, ResponseListener listener)
        {
            const string uri = "ssap://media.viewer/open";

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

                    LaunchSession launchSession = LaunchSession.LaunchSessionForAppId(obj.GetNamedString("id"));
                    launchSession.Service = this;
                    launchSession.SessionId = obj.GetNamedString("sessionId");
                    launchSession.SessionType = LaunchSessionType.Media;

                    Util.PostSuccess(listener, new MediaLaunchObject(launchSession, this));
                },
                serviceCommandError => Util.PostError(listener, serviceCommandError)
            );

            var request = new ServiceCommand(this, uri, ps, responseListener);
            request.Send();
        }
        private void ConnectMouse(ResponseListener listener)
        {
            const string uri = "ssap://com.webos.service.networkinput/getPointerInputSocket";

            var request = new ServiceCommand(this, uri, null, listener);
            request.Send();
        }
        private void GetApplications(int type, int number, ResponseListener listener)
        {
            var responseListener = new ResponseListener
            (
                loadEventArg =>
                {
                    var lea = loadEventArg as LoadEventArgs;
                    if (lea == null) return;
                    var load = lea.Load.GetPayload() as HttpResponseMessage;

                    if (load == null) return;
                    var strObj = load.Content.ReadAsStringAsync().Result;

                    var appList = new List<AppInfo>();

                    var reader = Util.GenerateStreamFromstring(strObj);
                    var xmlReader = XmlReader.Create(reader);

                    while (xmlReader.Read())
                    {
                        if (xmlReader.Name.Equals("data", StringComparison.OrdinalIgnoreCase))
                            appList.Add(new AppInfo(""));
                        if (xmlReader.Name.Equals("auid", StringComparison.OrdinalIgnoreCase))
                            appList[appList.Count - 1].Id = xmlReader.ReadElementContentAsString();
                        if (xmlReader.Name.Equals("name", StringComparison.OrdinalIgnoreCase))
                            appList[appList.Count - 1].Name = xmlReader.ReadElementContentAsString();
                    }
                    appList = (from a in appList where !string.IsNullOrEmpty(a.Name) select a).ToList();
                    if (listener != null)
                    {
                        Util.PostSuccess(listener, appList);
                    }
                },
                serviceCommandError =>
                {

                }
            );

            var requestUrl = GetUdapRequestUrl(UdapPathData, TargetApplistGet, type.ToString(), "0",
                number.ToString());

            var command = new ServiceCommand(this, requestUrl, null, responseListener) { HttpMethod = ServiceCommand.TypeGet };
            command.Send();
        }
        // TODO add this when user cancel pairing
        public void RemovePairingKeyOnTv()
        {
            var responseListener = new ResponseListener
            (
                loadEventArg => { },
                serviceCommandError => { }
            );

            var requestUrl = GetUdapRequestUrl(UdapPathPairing);

            var ps = new Dictionary<string, string> { { "name", "CancelAuthKeyReq" } };

            var httpMessage = GetUdapMessageBody(UdapApiPairing, ps);

            var command = new ServiceCommand(this, requestUrl, httpMessage, responseListener);
            command.Send();
        }
        private void GetTotalNumberOfApplications(int type, ResponseListener listener)
        {
            var responseListener = new ResponseListener
            (
                loadEventArg =>
                {
                    var lea = loadEventArg as LoadEventArgs;
                    if (lea == null) return;
                    var load = lea.Load.GetPayload() as HttpResponseMessage;

                    if (load == null) return;

                    var strObj = load.Content.ReadAsStringAsync().Result;

                    JsonObject jsonObject;
                    JsonObject.TryParse(strObj, out jsonObject);

                    //var tarray = jsonObject.GetNamedArray("Channel List", new JsonArray());
                    var applicationNumber = ParseAppNumberXmlToJson(strObj);

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

            var requestUrl = GetUdapRequestUrl(UdapPathData, TargetAppnumGet, type.ToString());

            var command = new ServiceCommand(this, requestUrl, null,
                responseListener) { HttpMethod = ServiceCommand.TypeGet };
            command.Send();
        }
        public void Scroll(double dx, double dy)
        {
            if (isMouseConnected) ConnectMouse();

            var responseListener = new ResponseListener();

            var requestUrl = GetUdapRequestUrl(UdapPathCommand);

            var ps = new Dictionary<string, string> { { "name", "HandleTouchWheel" }, { "value", dy > 0 ? "up" : "down" } };

            var httpMessage = GetUdapMessageBody(UdapApiCommand, ps);

            var request = new ServiceCommand(this, requestUrl, httpMessage, responseListener);
            request.Send();
        }
        public void CloseApp(LaunchSession launchSession, ResponseListener listener)
        {
            var requestUrl = GetUdapRequestUrl(UdapPathApptoappCommand);

            var ps = new Dictionary<string, string> { { "name", "AppTerminate" }, { "auid", launchSession.AppId } };
            if (launchSession.AppName != null)
                ps.Add("appname", HttpMessage.Encode(launchSession.AppName));

            var httpMessage = GetUdapMessageBody(UdapApiCommand, ps);

            var command = new ServiceCommand(launchSession.Service,
                requestUrl, httpMessage, listener);
            command.Send();
        }
        public override void SendPairingKey(string pairingKey)
        {
            ServiceConnectionState = ConnectionState.Pairing;

            if (!(ServiceConfig is NetcastTvServiceConfig))
            {
                ServiceConfig = new NetcastTvServiceConfig(ServiceConfig.ServiceUuid);
            }

            var responseListener = new ResponseListener
            (
                loadEventArg =>
                {
                    ServiceConnectionState = ConnectionState.Paired;
                    ((NetcastTvServiceConfig)ServiceConfig).PairingKey = pairingKey;
                    ConnectSuccess();
                },
                serviceCommandError =>
                {
                    ServiceConnectionState = ConnectionState.Initial;

                    if (Listener != null)
                        Listener.OnConnectionFailure(this, new Exception(serviceCommandError.ToString()));
                }
            );

            var requestUrl = GetUdapRequestUrl(UdapPathPairing);

            var ps = new Dictionary<string, string>
            {
                {"name", "hello"},
                {"value", pairingKey},
                {"port", ServiceDescription.Port.ToString()}
            };

            var httpMessage = GetUdapMessageBody(UdapApiPairing, ps);

            var command = new ServiceCommand(this, requestUrl,
                httpMessage, responseListener);
            command.Send();
        }
        private void LaunchApplication(string appName, string auid, string contentId, ResponseListener listener)
        {
            var responseListener = new ResponseListener
            (
                loadEventArg =>
                {
                    var launchSession = LaunchSession.LaunchSessionForAppId(auid);
                    launchSession.AppName = appName;
                    launchSession.Service = this;
                    launchSession.SessionType = LaunchSessionType.App;

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

            var requestUrl = GetUdapRequestUrl(UdapPathApptoappCommand);

            var ps = new Dictionary<string, string> { { "name", "AppExecute" }, { "auid", auid } };
            if (appName != null)
            {
                ps.Add("appname", appName);
            }
            if (contentId != null)
            {
                ps.Add("contentid", contentId);
            }

            var httpMessage = GetUdapMessageBody(UdapApiCommand, ps);

            var request = new ServiceCommand(this, requestUrl,
                httpMessage, responseListener);
            request.Send();
        }
        public void SetChannel(ChannelInfo channelInfo, ResponseListener listener)
        {
            var responseListener = new ResponseListener
            (
                loadEventArg =>
                {
                    //((ConnectSdk.Windows.Service.Capability.Listeners.LoadEventArgs)(o)).Load.payload

                    var loa = loadEventArg as LoadEventArgs;
                    if (loa != null)
                    {
                        var channelList = loa.Load.GetPayload() as List<ChannelInfo>;
                        if (channelList != null)
                        {
                            var requestUrl = GetUdapRequestUrl(UdapPathCommand);

                            var ps = new Dictionary<string, string>();

                            foreach (var ch in channelList)
                            {
                                //var rawData = ch.RawData;

                                var major = channelInfo.MajorNumber;
                                var minor = channelInfo.MinorNumber;

                                var majorNumber = ch.MajorNumber;
                                var minorNumber = ch.MinorNumber;

                                if (major != majorNumber || minor != minorNumber) continue;
                                ps.Add("name", "HandleChannelChange");
                                ps.Add("major", major.ToString());
                                ps.Add("minor", minor.ToString());

                                break;
                            }
                            var httpMessage = GetUdapMessageBody(UdapApiCommand, ps);

                            var request = new ServiceCommand(this, requestUrl, httpMessage, listener);
                            request.Send();
                        }
                        else
                        {
                            Util.PostError(listener, new ServiceCommandError(500, "Could not retrieve channel list"));
                        }
                    }
                    else
                    {
                        Util.PostError(listener, new ServiceCommandError(500, "Could not retrieve channel list"));
                    }
                },
                serviceCommandError => Util.PostError(listener, serviceCommandError)
            );

            GetChannelList(responseListener);
        }
        private void SendVirtualKeyCode(int keycode, ResponseListener listener)
        {
            var responseListener = new ResponseListener
                (
                loadEventArg =>
                {
                    var requestUrl = GetUdapRequestUrl(UdapPathCommand);
                    var httpMessage = GetHttpMessageForHandleKeyInput(keycode);

                    var request = new ServiceCommand(this, requestUrl, httpMessage, listener);
                    request.Send();
                },
                serviceCommandError => Util.PostError(listener, serviceCommandError)
                );

            SetMouseCursorVisible(false, responseListener);
        }
        public void ShowPairingKeyOnTv()
        {
            ServiceConnectionState = ConnectionState.Connecting;

            var responseListener = new ResponseListener
            (
                loadEventArg =>
                {
                    if (Listener != null)
                        Listener.OnPairingRequired(this, PairingType.PIN_CODE, null);
                },
                serviceCommandError =>
                {
                    ServiceConnectionState = ConnectionState.Initial;

                    if (Listener != null)
                        Listener.OnConnectionFailure(this, new Exception(serviceCommandError.ToString()));
                }
            );

            var requestUrl = GetUdapRequestUrl(UdapPathPairing);

            var ps = new Dictionary<string, string> { { "name", "showKey" } };

            string httpMessage = GetUdapMessageBody(UdapApiPairing, ps);

            var command = new ServiceCommand(this, requestUrl,
                httpMessage, responseListener);
            command.Send();
        }
        public void Get3DEnabled(ResponseListener listener)
        {
            var responseListener = new ResponseListener
            (
                loadEventArg =>
                {
                    var strObj = (string)loadEventArg;
                    var upperStr = strObj.ToUpper();

                    Util.PostSuccess(listener, upperStr.Contains("TRUE"));
                },
                serviceCommandError => Util.PostError(listener, serviceCommandError)
            );

            var requestUrl = GetUdapRequestUrl(UdapPathData, TargetIs_3D);
            var request = new ServiceCommand(this, requestUrl, null, responseListener)
            {
                HttpMethod = ServiceCommand.TypeGet
            };
            request.Send();
        }
        private void EndPairing(ResponseListener listener)
        {
            var requestUrl = GetUdapRequestUrl(UdapPathPairing);

            var ps = new Dictionary<string, string>
            {
                {"name", "byebye"},
                {"port", ServiceDescription.Port.ToString()}
            };

            var httpMessage = GetUdapMessageBody(UdapApiPairing, ps);

            var command = new ServiceCommand(this, requestUrl,
                httpMessage, listener);
            command.Send();
        }
        public void GetAppState(LaunchSession launchSession, ResponseListener listener)
        {
            var requestUrl = string.Format("{0}{1}", GetUdapRequestUrl(UdapPathApptoappData),
                string.Format("/{0}/status", launchSession.AppId));

            var responseListener = new ResponseListener
            (
                loadEventArg =>
                {
                    var response = (string)loadEventArg;
                    AppState appState;
                    if (response.Equals("NONE"))
                        appState = new AppState(false, false);
                    else if (response.Equals("LOAD"))
                        appState = new AppState(false, true);
                    else if (response.Equals("RUN_NF"))
                        appState = new AppState(true, false);
                    else if (response.Equals("TERM"))
                        appState = new AppState(false, true);
                    else
                        appState = new AppState(false, false);

                    Util.PostSuccess(listener, appState);

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

            var command = new ServiceCommand(this, requestUrl, null, responseListener) { HttpMethod = ServiceCommand.TypeGet };
            command.Send();
        }
        public void Click()
        {
            if (isMouseConnected) ConnectMouse();

            var responseListener = new ResponseListener();

            var requestUrl = GetUdapRequestUrl(UdapPathCommand);

            var ps = new Dictionary<string, string> { { "name", "HandleTouchClick" } };

            var httpMessage = GetUdapMessageBody(UdapApiCommand, ps);

            var request = new ServiceCommand(this, requestUrl, httpMessage, responseListener);
            request.Send();
        }
        public void GetCurrentChannel(ResponseListener listener)
        {
            var requestUrl = GetUdapRequestUrl(UdapPathData, TargetCurrentChannel);

            var responseListener = new ResponseListener
            (
                loadEventArg =>
                {
                    //TODO: fix this
                    //var strObj = (string)o;
                    //SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
                    //InputStream stream = new ByteArrayInputStream(strObj.getBytes("UTF-8"));
                    //SAXParser saxParser = saxParserFactory.newSAXParser();

                    //NetcastChannelParser parser = new NetcastChannelParser();
                    //saxParser.parse(stream, parser);

                    //JSONArray channelArray = parser.getJSONChannelArray();

                    //if ( channelArrayLength > 0 ) {
                    //    JsonObject rawData = (JsonObject) channelArray.get(0);

                    //    ChannelInfo channel = NetcastChannelParser.parseRawChannelData(rawData);

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

            var request = new ServiceCommand(this, requestUrl, null, responseListener);
            request.Send();
        }
        public void CloseWebApp(LaunchSession launchSession, ResponseListener listener)
        {
            if (launchSession == null || launchSession.AppId == null || launchSession.AppId.Length == 0)
            {
                Util.PostError(listener, new ServiceCommandError(0, null));
                return;
            }

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

            if (webAppSession != null && webAppSession.IsConnected())
            {
                var serviceCommand = new JsonObject();
                var closeCommand = new JsonObject();

                try
                {
                    serviceCommand.Add("type", JsonValue.CreateStringValue("close"));

                    closeCommand.Add("contentType", JsonValue.CreateStringValue("connectsdk.serviceCommand"));
                    closeCommand.Add("serviceCommand", serviceCommand);
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                var responseListener = new ResponseListener
                (
                    loadEventArg =>
                    {
                        webAppSession.DisconnectFromWebApp();

                        if (listener != null)
                            listener.OnSuccess(loadEventArg);
                    },
                    serviceCommandError =>
                    {
                        webAppSession.DisconnectFromWebApp();

                        if (listener != null)
                            listener.OnError(serviceCommandError);
                    }
                );

                webAppSession.SendMessage(closeCommand, responseListener);
            }
            else
            {
                //if (webAppSession != null)
                //    webAppSession.DisconnectFromWebApp();

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

                try
                {
                    if (launchSession.AppId != null)
                        payload.Add("webAppId", JsonValue.CreateStringValue(launchSession.AppId));
                    if (launchSession.SessionId != null)
                        payload.Add("sessionId", JsonValue.CreateStringValue(launchSession.SessionId));
                }
                catch (Exception e)
                {
                    throw e;
                }

                var request = new ServiceCommand(this, uri, payload, listener);
                request.Send();
            }
        }