public void GetAllAudio(Action <BackendResult <List <AudioObj>, ResultCode> > callback, long?userOrGroupId = null, bool isGroup = false, long?albumId = null, int offset = 0, int count = 0)
 {
     /*
      * Dictionary<string, string> parameters = new Dictionary<string, string>();
      * if (userOrGroupId.HasValue && !isGroup)
      *  parameters["user_id"] = userOrGroupId.Value.ToString();
      * if (userOrGroupId.HasValue & isGroup)
      *  parameters["group_id"] = userOrGroupId.Value.ToString();
      * if (albumId.HasValue)
      *  parameters["album_id"] = albumId.Value.ToString();
      * parameters["offset"] = offset.ToString();
      * VKRequestsDispatcher.DispatchRequestToVK<List<AudioObj>>("audio.get", parameters, callback, AudioService._deserializeAudioList, false, true, new CancellationToken?(), null);
      */
     /*
      * Dictionary<string, string> parameters = new Dictionary<string, string>();
      * parameters["owner_id"] = userOrGroupId.Value.ToString();
      * parameters["need_owner"] = "1";
      * parameters["need_playlists"] = "1";
      * parameters["playlists_count"] = "12";
      * parameters["audio_offset"] = "0";
      * parameters["audio_count"] = "100";
      * VKRequestsDispatcher.DispatchRequestToVK<List<AudioObj>>("execute.getMusicPage", parameters, callback,
      *  (Func<string, List<AudioObj>>)(jsonStr =>
      *      {
      *          return JsonConvert.DeserializeObject<GenericRoot<VKList<AudioObj>>>(jsonStr).response.items;
      *      }),
      *  false, true, new CancellationToken?(), null);*/
     VKRequestsDispatcher.RefreshToken((a) =>
     {
         Dictionary <string, string> parameters = new Dictionary <string, string>();
         parameters["owner_id"]        = userOrGroupId.Value.ToString();
         parameters["need_owner"]      = "1";
         parameters["need_playlists"]  = "1";
         parameters["playlists_count"] = "12";
         parameters["audio_offset"]    = "0";
         parameters["audio_count"]     = "100";
         VKRequestsDispatcher.DispatchRequestToVK <List <AudioObj> >("execute.getMusicPage", parameters, callback,
                                                                     (Func <string, List <AudioObj> >)(jsonStr =>
         {
             return(JsonConvert.DeserializeObject <GenericRoot <VKList <AudioObj> > >(jsonStr).response.items);
         }),
                                                                     false, true, new CancellationToken?(), null);
     });
 }
        private static void DoDispatch <R>(string baseUrl, string methodName, Dictionary <string, string> parameters, Action <BackendResult <R, ResultCode> > callback, Func <string, R> customDeserializationFunc = null, bool lowPriority = false, bool pageDataRequest = true, CancellationToken?cancellationToken = null, Action confirmationRequiredHandler = null)
        {
            parameters["v"] = VKConstants.API_VERSION;
            VKRequestsDispatcher.AddLangParameter(parameters);
            parameters["https"] = "1";

            if (!string.IsNullOrEmpty(VKRequestsDispatcher._autorizationData != null ? VKRequestsDispatcher._autorizationData.access_token : null))
            {
                parameters["access_token"] = VKRequestsDispatcher._autorizationData.access_token;
            }

            if (!string.IsNullOrEmpty(VKRequestsDispatcher._autorizationData != null ? VKRequestsDispatcher._autorizationData.secret : null))
            {
                if (parameters.ContainsKey("sig"))
                {
                    parameters.Remove("sig");
                }
                string str1 = JsonWebRequest.ConvertDictionaryToQueryString(parameters, false);
                if (str1 != string.Empty)
                {
                    str1 = "?" + str1;
                }
                string str2 = VKRequestsDispatcher.HashString("/method/" + methodName + str1 + VKRequestsDispatcher._autorizationData.secret);
                parameters["sig"] = str2.ToLower();
            }
            JsonWebRequest.SendHTTPRequestAsync(/*!VKRequestsDispatcher.USE_HTTP ?*/ "https://" + baseUrl /*: "http://" + baseUrl*/, parameters, (Action <JsonResponseData>)(jsonResp =>
            {
                BackendResult <R, ResultCode> backendResult = new BackendResult <R, ResultCode>(ResultCode.CommunicationFailed);
                if (jsonResp.IsSucceeded)
                {
                    VKRequestsDispatcher.ResultData resultFromJson = VKRequestsDispatcher.GetResultFromJson(JObject.Parse(jsonResp.JsonString));
                    backendResult.ResultCode = resultFromJson.ResultCode;
                    backendResult.Error      = resultFromJson.error;
                    if (resultFromJson.error != null)
                    {
                        int i = 0;
                    }
                    if (backendResult.ResultCode == ResultCode.UserAuthorizationFailed)
                    {
                        if (!string.IsNullOrEmpty(VKRequestsDispatcher._autorizationData != null ? VKRequestsDispatcher._autorizationData.access_token : null))
                        {
                            Logger.Instance.Error("RECEIVED AUTHORIZATION FAILURE!!! JSON STR = " + jsonResp.JsonString ?? "");
                            LogoutRequestHandler.InvokeLogoutRequest();
                        }
                    }
                    if (backendResult.ResultCode == ResultCode.CaptchaRequired)
                    {
                        CaptchaUserRequestHandler.InvokeCaptchaRequest(new CaptchaUserRequest()
                        {
                            CaptchaSid = resultFromJson.captcha_sid,
                            Url        = resultFromJson.captcha_img
                        }, (Action <CaptchaUserResponse>)(captchaResp =>
                        {
                            if (!captchaResp.IsCancelled)
                            {
                                Dictionary <string, string> parameters1 = parameters;
                                parameters1["captcha_sid"] = captchaResp.Request.CaptchaSid;
                                parameters1["captcha_key"] = captchaResp.EnteredString;
                                VKRequestsDispatcher.DoDispatch <R>(baseUrl, methodName, parameters1, callback, customDeserializationFunc, lowPriority, pageDataRequest, cancellationToken, null);
                            }
                            else
                            {
                                VKRequestsDispatcher.InvokeCallback((Action)(() => callback(new BackendResult <R, ResultCode>(ResultCode.CaptchaControlCancelled))), cancellationToken);
                            }
                        }));
                    }
                    else if (backendResult.ResultCode == ResultCode.ValidationRequired)
                    {
                        if (resultFromJson.validation_type == "2fa_app" || resultFromJson.validation_type == "2fa_sms")
                        {
                            if (parameters.ContainsKey("force_sms") || parameters.ContainsKey("code"))
                            {
                                R r = customDeserializationFunc != null ? customDeserializationFunc("") : default(R);
                                VKRequestsDispatcher.InvokeCallback((Action)(() => callback(new BackendResult <R, ResultCode>(ResultCode.Succeeded, r))), cancellationToken);
                            }
                            else
                            {
                                CaptchaUserRequestHandler.InvokeValidation2FARequest(new Validation2FAUserRequest()
                                {
                                    username       = parameters.ContainsKey("username") ? parameters["username"] : "",
                                    password       = parameters.ContainsKey("password") ? parameters["password"] : "",
                                    phoneMask      = resultFromJson.phone_mask,
                                    validationType = resultFromJson.validation_type,
                                    validationSid  = resultFromJson.validation_sid
                                }, (Action <ValidationUserResponse>)(valResp => VKRequestsDispatcher.ProcessValidationResponse <R>(valResp, baseUrl, methodName, parameters, callback, customDeserializationFunc, lowPriority, pageDataRequest, cancellationToken)));
                            }
                        }
                        else
                        {
                            CaptchaUserRequestHandler.InvokeValidationRequest(new ValidationUserRequest()
                            {
                                ValidationUri = resultFromJson.redirect_uri
                            }, (Action <ValidationUserResponse>)(valResp => VKRequestsDispatcher.ProcessValidationResponse <R>(valResp, baseUrl, methodName, parameters, callback, customDeserializationFunc, lowPriority, pageDataRequest, cancellationToken)));
                        }
                    }
                    else if (backendResult.ResultCode == ResultCode.ConfirmationRequired)
                    {
                        if (!VKRequestsDispatcher.GetIsResponseCancelled(cancellationToken))
                        {
                            Action action = confirmationRequiredHandler;
                            if (action != null)
                            {
                                action();
                            }
                            IBackendConfirmationHandler confirmationHandler = ServiceLocator.Resolve <IBackendConfirmationHandler>();
                            if (confirmationHandler != null)
                            {
                                confirmationHandler.Confirm(resultFromJson.confirmation_text, (Action <bool>)(confirmed =>
                                {
                                    if (confirmed)
                                    {
                                        parameters["confirm"] = "1";
                                        VKRequestsDispatcher.DoDispatch <R>(baseUrl, methodName, parameters, callback, customDeserializationFunc, lowPriority, pageDataRequest, cancellationToken, null);
                                    }
                                    else
                                    {
                                        VKRequestsDispatcher.InvokeCallback((Action)(() => callback(new BackendResult <R, ResultCode>(ResultCode.ConfirmationCancelled))), cancellationToken);
                                    }
                                }));
                            }
                        }
                    }
                    else if (backendResult.ResultCode == ResultCode.NotEnoughMoney)
                    {
                        if (!VKRequestsDispatcher.GetIsResponseCancelled(cancellationToken))
                        {
                            IBackendNotEnoughMoneyHandler enoughMoneyHandler = ServiceLocator.Resolve <IBackendNotEnoughMoneyHandler>();
                            Action action1 = (() => VKRequestsDispatcher.DoDispatch <R>(baseUrl, methodName, parameters, callback, customDeserializationFunc, lowPriority, pageDataRequest, cancellationToken, null));
                            Action action2 = (Action)(() => VKRequestsDispatcher.InvokeCallback((Action)(() => callback(new BackendResult <R, ResultCode>(ResultCode.BalanceRefillCancelled))), cancellationToken));
                            if (enoughMoneyHandler != null)
                            {
                                Action refilledCallback  = action1;
                                Action cancelledCallback = action2;
                                enoughMoneyHandler.RequestBalanceRefill(refilledCallback, cancelledCallback);
                            }
                        }
                    }
                    else if (backendResult.ResultCode == ResultCode.Succeeded)
                    {
                        try
                        {
                            List <ExecuteError> executeErrorList = null;
                            R r;
                            if (customDeserializationFunc != null)
                            {
                                r = customDeserializationFunc(jsonResp.JsonString);
                            }
                            else if (typeof(R) == typeof(VKClient.Common.Backend.DataObjects.ResponseWithId))
                            {
                                r = JsonConvert.DeserializeObject <R>(jsonResp.JsonString);
                            }
                            else
                            {
                                VKRequestsDispatcher.GenericRoot <R> genericRoot = JsonConvert.DeserializeObject <VKRequestsDispatcher.GenericRoot <R> >(jsonResp.JsonString);
                                r = genericRoot.response;
                                executeErrorList = genericRoot.execute_errors;
                            }
                            backendResult.ResultData    = r;
                            backendResult.ExecuteErrors = executeErrorList;
                        }
                        catch (Exception ex)
                        {
                            Logger.Instance.Error("Error during deserialization", ex);
                            backendResult.ResultCode = ResultCode.DeserializationError;
                        }
                    }
                    else if (backendResult.ResultCode == ResultCode.TokenConfirmationRequired)
                    {
                        VKRequestsDispatcher.RefreshToken((a) =>
                        {
                            VKRequestsDispatcher.DoDispatch <R>(baseUrl, methodName, parameters, callback, customDeserializationFunc, lowPriority, pageDataRequest, cancellationToken, null);
                        });
                        int aa = 0;
                    }
                }
                if (backendResult.ResultCode == ResultCode.CaptchaRequired || backendResult.ResultCode == ResultCode.ValidationRequired || (backendResult.ResultCode == ResultCode.ConfirmationRequired || backendResult.ResultCode == ResultCode.NotEnoughMoney || backendResult.ResultCode == ResultCode.TokenConfirmationRequired))
                {
                    return;
                }
                VKRequestsDispatcher.InvokeCallback((Action)(() =>
                {
                    Action <BackendResult <R, ResultCode> > action = callback;
                    if (action == null)
                    {
                        return;
                    }

                    action(backendResult);
                }), cancellationToken);
            }), true, lowPriority, pageDataRequest);
        }