コード例 #1
0
        public bool SendCommandSafe <T>(out ICommandResponse rsp, T parameter = default(T)) where T : class
        {
            rsp = null;
            bool result = true;

            try
            {
                if (this.CurrentChromeSession == null)
                {
                    throw new Exception("Session=Null,parameter=" + parameter.ToString());
                }
                rsp = this.CurrentChromeSession.SendCommand <T>(parameter);
                if (rsp == null)
                {
                    throw new Exception("SendCommand返回null");
                }
                if (rsp is IErrorResponse)
                {
                    IErrorResponse errorResponse = rsp as IErrorResponse;
                    throw new Exception(string.Concat(new object[]
                    {
                        "SendCommand error,msg=",
                        errorResponse.Error.Message,
                        ",code=",
                        errorResponse.Error.Code
                    }));
                }
            }
            catch (Exception ex)
            {
                result = false;
            }
            return(result);
        }
コード例 #2
0
        public virtual async Task <IAuthToken> AuthenticateAsync()
        {
            HttpContent content = new FormUrlEncodedContent(this.GetAuthParameters());

            var request = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                RequestUri = new Uri(this.TokenRequestUri),
                Content    = content
            };

            var responseMessage = await this.HttpClient.SendAsync(request).ConfigureAwait(false);

            var response = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);

            if (!responseMessage.IsSuccessStatusCode)
            {
                IErrorResponse error = JsonConvert.DeserializeObject <AuthErrorResponse>(response);

                throw new SalesforceAuthException(error.Message)
                      {
                          ErrorCode = error.ErrorCode
                      };
            }

            return(JsonConvert.DeserializeObject <AuthToken>(response));
        }
コード例 #3
0
 public static ErrorResponse Convert(IErrorResponse err, bool nullIsSuccess = true)
 {
     if (err == null)
     {
         return(Create(nullIsSuccess));
     }
     return(new ErrorResponse(err.Succeeded, err.Reason, err.Exception));
 }
コード例 #4
0
        public static async Task <byte[]> ToByteArrayAsync(IErrorResponse resp)
        {
            using (var stream = new MemoryStream())
            {
                stream.WriteByte((byte)resp.ErrorCode);

                await stream.WriteUTF8Async(resp.ErrorMessage, SizeLength.INT);

                await stream.WriteAsync(resp.RequestData);

                return(stream.ToArray());
            }
        }
コード例 #5
0
        public ModListGalleryVM(MainWindowVM mainWindowVM)
            : base(mainWindowVM)
        {
            MWVM = mainWindowVM;

            Observable.Return(Unit.Default)
            .ObserveOn(RxApp.TaskpoolScheduler)
            .SelectTask(async _ =>
            {
                try
                {
                    Error    = null;
                    var list = await ModlistMetadata.LoadFromGithub();
                    return(list.AsObservableChangeSet(x => x.DownloadMetadata?.Hash ?? $"Fallback{missingHashFallbackCounter++}"));
                }
                catch (Exception ex)
                {
                    Utils.Error(ex);
                    Error = ErrorResponse.Fail(ex);
                    return(Observable.Empty <IChangeSet <ModlistMetadata, string> >());
                }
            })
            // Unsubscribe and release when not active
            .FlowSwitch(
                this.WhenAny(x => x.IsActive),
                valueWhenOff: Observable.Return(ChangeSet <ModlistMetadata, string> .Empty))
            // Convert to VM and bind to resulting list
            .Switch()
            .ObserveOnGuiThread()
            .Transform(m => new ModListMetadataVM(this, m))
            .DisposeMany()
            .Bind(ModLists)
            .Subscribe()
            .DisposeWith(CompositeDisposable);

            // Extra GC when navigating away, just to immediately clean up modlist metadata
            this.WhenAny(x => x.IsActive)
            .Where(x => !x)
            .Skip(1)
            .Delay(TimeSpan.FromMilliseconds(50), RxApp.MainThreadScheduler)
            .Subscribe(_ =>
            {
                GC.Collect();
            })
            .DisposeWith(CompositeDisposable);
        }
コード例 #6
0
        public IErrorResponse SendEnhancedNotification(IEnhancedNotification enhancedNotification)
        {
            this.connection.Connect();
            this.connection.Write(enhancedNotification.ToByteArray());
            var response = new byte[6];

            this.connection.Read(response, 0, response.Length);
            this.connection.Disconnect();
            IErrorResponse errorResponse = null;

            if (response[0] == 0x08)
            {
                // we received an error response...
                errorResponse = new ErrorResponse(BitConverter.ToInt32(response, 2), (ErrorResponseStatusCode)response[1]);
            }

            return(errorResponse);
        }
コード例 #7
0
        public string GetError(HttpStatusCode httpStatus, IErrorResponse errorResponse = null)
        {
            // Todo! Log errorResponse.Details

            switch (httpStatus)
            {
            case HttpStatusCode.BadRequest:
                // An auth or sign request with personal number was sent, but an order for the
                // user is already in progress. The order is aborted. No order is created
                // Either invalidParameters or alreadyInProgress
                return(errorResponse != null && errorResponse.ErrorCode.Equals("invalidParameters") ? codes["RFA22"] : codes["RFA4"]);

            case HttpStatusCode.Unauthorized:
            case HttpStatusCode.Forbidden:
                // RP does not have access to the service.
                return(codes["RFA22"]);

            case HttpStatusCode.NotFound:
                // An erroneously URL path was used.
                return(codes["RFA22"]);

            case HttpStatusCode.RequestTimeout:
                // It took too long time to transmit the request
                return(codes["RFA5"]);

            case HttpStatusCode.UnsupportedMediaType:
                // Adding a "charset" parameter after 'application/json' is not allowed since the MIME type
                // "application/json" has neither optional nor required parameters. The type is missing or erroneously.
                return(codes["RFA22"]);

            case HttpStatusCode.InternalServerError:
                // Internal technical error in the BankID system
                return(codes["RFA5"]);

            case HttpStatusCode.ServiceUnavailable:
                // The service is temporarily out of service
                return(codes["RFA5"]);
            }

            return(null);
        }
コード例 #8
0
        public static bool AddErrorData(ref IErrorResponse response, string message, string data = "", string stackTrace = "", string errorCode = "")
        {
            if (response != null)
            {
                if (response.ErrorList == null)
                {
                    response.ErrorList = new List <ErrorData>();
                }

                response.ErrorList.Add(new ErrorData
                {
                    Data       = data,
                    Message    = message,
                    StackTrace = stackTrace,
                    ErrorCode  = errorCode
                });
                return(true);
            }
            else
            {
                throw new Exception("[ResponseHelper:AddErrorData] - Response is null");
            }
        }
コード例 #9
0
        public ModListMetadataVM(ModListGalleryVM parent, ModlistMetadata metadata)
        {
            _parent            = parent;
            Metadata           = metadata;
            Location           = Path.Combine(Consts.ModListDownloadFolder, Metadata.Links.MachineURL + ExtensionManager.Extension);
            IsBroken           = metadata.ValidationSummary.HasFailures;
            OpenWebsiteCommand = ReactiveCommand.Create(() => Process.Start($"https://www.wabbajack.org/modlist/{Metadata.Links.MachineURL}"));
            ExecuteCommand     = ReactiveCommand.CreateFromObservable <Unit, Unit>(
                canExecute: this.WhenAny(x => x.IsBroken).Select(x => !x),
                execute: (unit) =>
                Observable.Return(unit)
                .WithLatestFrom(
                    this.WhenAny(x => x.Exists),
                    (_, e) => e)
                // Do any download work on background thread
                .ObserveOn(RxApp.TaskpoolScheduler)
                .SelectTask(async(exists) =>
            {
                if (!exists)
                {
                    try
                    {
                        var success = await Download();
                        if (!success)
                        {
                            Error = ErrorResponse.Fail("Download was marked unsuccessful");
                            return(false);
                        }
                    }
                    catch (Exception ex)
                    {
                        Error = ErrorResponse.Fail(ex);
                        return(false);
                    }
                    // Return an updated check on exists
                    return(File.Exists(Location));
                }
                return(exists);
            })
                .Where(exists => exists)
                // Do any install page swap over on GUI thread
                .ObserveOnGuiThread()
                .Select(_ =>
            {
                _parent.MWVM.OpenInstaller(Path.GetFullPath(Location));

                // Wait for modlist member to be filled, then open its readme
                return(_parent.MWVM.Installer.Value.WhenAny(x => x.ModList)
                       .NotNull()
                       .Take(1)
                       .Do(modList =>
                {
                    try
                    {
                        modList.OpenReadmeWindow();
                    }
                    catch (Exception ex)
                    {
                        Utils.Error(ex);
                    }
                }));
            })
                .Switch()
                .Unit());

            _Exists = Observable.Interval(TimeSpan.FromSeconds(0.5))
                      .Unit()
                      .StartWith(Unit.Default)
                      .FlowSwitch(_parent.WhenAny(x => x.IsActive))
                      .Select(_ =>
            {
                try
                {
                    return(!metadata.NeedsDownload(Location));
                }
                catch (Exception)
                {
                    return(true);
                }
            })
                      .ToGuiProperty(this, nameof(Exists));

            var imageObs = Observable.Return(Metadata.Links.ImageUri)
                           .DownloadBitmapImage((ex) => Utils.Log($"Error downloading modlist image {Metadata.Title}"));

            _Image = imageObs
                     .ToGuiProperty(this, nameof(Image));

            _LoadingImage = imageObs
                            .Select(x => false)
                            .StartWith(true)
                            .ToGuiProperty(this, nameof(LoadingImage));
        }
コード例 #10
0
ファイル: ApiException.cs プロジェクト: mccj/BaseAPIClient
 public ApiException(IErrorResponse error) : base(error.ErrorMessage)
 {
     this.Error = error;
 }
コード例 #11
0
 public BankIDException(HttpStatusCode httpStatusCode, IErrorResponse errorResponse, string message, Exception inner)
     : base(message: message, inner: null)
 {
 }
コード例 #12
0
 public ValidationException(string requestId, HttpMethod method, IErrorResponse errorResponse)
     : base(requestId, 422, $"{method:G} failed.{errorResponse?.Message.PadLeft(errorResponse.Message.Length + 1)}")
 {
     this.Errors = errorResponse?.Errors ?? new Error[0];
 }
コード例 #13
0
 public static bool AddErrorData(ref IErrorResponse response, Exception ex)
 {
     return(AddErrorData(ref response, ex.Message, ex.Data.ToString(), ex.StackTrace, string.Empty));
 }
コード例 #14
0
 public BankIDException(HttpStatusCode httpStatusCode, IErrorResponse errorResponse, string message)
     : this(httpStatusCode, errorResponse, message, null)
 {
 }
コード例 #15
0
 public ErrorResponseException(IErrorResponse error) : base(error.Error ?? error.Message)
 {
 }
コード例 #16
0
        public ModListMetadataVM(ModListGalleryVM parent, ModlistMetadata metadata)
        {
            _parent        = parent;
            Metadata       = metadata;
            Location       = Consts.ModListDownloadFolder.Combine(Metadata.Links.MachineURL + (string)Consts.ModListExtension);
            ModListTagList = new List <ModListTag>();
            Metadata.tags.ForEach(tag =>
            {
                ModListTagList.Add(new ModListTag(tag));
            });
            DownloadSizeText = "Download size : " + UIUtils.FormatBytes(Metadata.DownloadMetadata.SizeOfArchives);
            InstallSizeText  = "Installation size : " + UIUtils.FormatBytes(Metadata.DownloadMetadata.SizeOfInstalledFiles);
            IsBroken         = metadata.ValidationSummary.HasFailures;
            //https://www.wabbajack.org/#/modlists/info?machineURL=eldersouls
            OpenWebsiteCommand = ReactiveCommand.Create(() => Utils.OpenWebsite(new Uri($"https://www.wabbajack.org/#/modlists/info?machineURL={Metadata.Links.MachineURL}")));
            ExecuteCommand     = ReactiveCommand.CreateFromObservable <Unit, Unit>(
                canExecute: this.WhenAny(x => x.IsBroken).Select(x => !x),
                execute: (unit) =>
                Observable.Return(unit)
                .WithLatestFrom(
                    this.WhenAny(x => x.Exists),
                    (_, e) => e)
                // Do any download work on background thread
                .ObserveOn(RxApp.TaskpoolScheduler)
                .SelectTask(async(exists) =>
            {
                if (!exists)
                {
                    try
                    {
                        var success = await Download();
                        if (!success)
                        {
                            Error = ErrorResponse.Fail("Download was marked unsuccessful");
                            return(false);
                        }
                    }
                    catch (Exception ex)
                    {
                        Error = ErrorResponse.Fail(ex);
                        return(false);
                    }
                    // Return an updated check on exists
                    return(Location.Exists);
                }
                return(exists);
            })
                .Where(exists => exists)
                // Do any install page swap over on GUI thread
                .ObserveOnGuiThread()
                .Select(_ =>
            {
                _parent.MWVM.OpenInstaller(Location);

                // Wait for modlist member to be filled, then open its readme
                return(_parent.MWVM.Installer.Value.WhenAny(x => x.ModList)
                       .NotNull()
                       .Take(1)
                       .Do(modList =>
                {
                    try
                    {
                        modList.OpenReadme();
                    }
                    catch (Exception ex)
                    {
                        Utils.Error(ex);
                    }
                }));
            })
                .Switch()
                .Unit());

            _Exists = Observable.Interval(TimeSpan.FromSeconds(0.5))
                      .Unit()
                      .StartWith(Unit.Default)
                      .FlowSwitch(_parent.WhenAny(x => x.IsActive))
                      .SelectAsync(async _ =>
            {
                try
                {
                    return(!IsDownloading && !(await metadata.NeedsDownload(Location)));
                }
                catch (Exception)
                {
                    return(true);
                }
            })
                      .ToGuiProperty(this, nameof(Exists));

            var imageObs = Observable.Return(Metadata.Links.ImageUri)
                           .DownloadBitmapImage((ex) => Utils.Log($"Error downloading modlist image {Metadata.Title}"));

            _Image = imageObs
                     .ToGuiProperty(this, nameof(Image));

            _LoadingImage = imageObs
                            .Select(x => false)
                            .StartWith(true)
                            .ToGuiProperty(this, nameof(LoadingImage));
        }
 public static bool AddErrorData(this IErrorResponse response, string message, string data = "", string stackTrack = "", string errorCode = "")
 {
     return(ResponseHelper.AddErrorData(ref response, message, data, stackTrack, errorCode));
 }
 public static bool AddErrorData(this IErrorResponse response, Exception ex)
 {
     return(ResponseHelper.AddErrorData(ref response, ex));
 }
コード例 #19
0
 public static bool Equals(IErrorResponse x, IErrorResponse y)
 {
     return(x.ErrorCode == y.ErrorCode &&
            x.ErrorMessage == y.ErrorMessage &&
            x.RequestData.EqualsContent(y.RequestData));
 }
コード例 #20
0
 public UnauthorizedException(string requestId, int httpStatusCode, IErrorResponse errorResponse) : base(requestId, httpStatusCode, errorResponse?.Message)
 {
     this.Errors = errorResponse?.Errors ?? new Error[0];
 }
コード例 #21
0
 protected ErrorResult Error(IErrorResponse response)
 {
     return(new ErrorResult(response.Errors));
 }