예제 #1
0
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            if (e.Exception is DirectoryNotFoundException)
            {
                DirectoryNotFoundException theException = (DirectoryNotFoundException)e.Exception;
                BLIO.WriteError(theException, "Folder not found.");
                ShowError(e.Exception, e.Exception.GetType().ToString(), theException.Message);
            }

            if (e.Exception is UnauthorizedAccessException)
            {
                UnauthorizedAccessException theException = (UnauthorizedAccessException)e.Exception;
                BLIO.WriteError(e.Exception, "Unauthorized!");
                ShowError(e.Exception, "Unauthorized!", "not authorized for this action.\r\nThis can be resolved by running in administrator-mode.");
            }

            //Here we just filter out some type of exceptions and give different messages, at the bottom is the super Exception, which can be anything.
            else if (e.Exception is FileNotFoundException)
            {
                FileNotFoundException theException = (FileNotFoundException)e.Exception; //needs in instance to call .FileName
                BLIO.WriteError(theException, "converteruld not find the file located at \"" + theException.FileName);
                ShowError(e.Exception, "File not found.", "Could not find the file located at \"" + theException.FileName + "\"\r\nHave you moved,renamed or deleted the file?");
            }

            else if (e.Exception is System.Data.Entity.Core.EntityException)
            {
                BLIO.WriteError(e.Exception, "System.Data.Entity.Core.EntityException");
                ShowError(e.Exception, "System.Data.Entity.Core.EntityException", "There was a problem executing SQL!");
            }

            else if (e.Exception is ArgumentNullException)
            {
                BLIO.WriteError(e.Exception, "Null argument");
                ShowError(e.Exception, "Null argument", "Null argument exception! Whoops! this is not on your end!");
            }

            else if (e.Exception is NullReferenceException)
            {
                BLIO.WriteError(e.Exception, "Null reference");
                ShowError(e.Exception, "Null reference", "Null reference exception! Whoops! this is not on your end!");
            }

            else if (e.Exception is SQLiteException)
            {
                BLIO.WriteError(e.Exception, "SQLite Database exception");
                ShowError(e.Exception, "SQLite Database exception", "encountered a database error!\r\nThis might or might not be on your end. It can be on your end if you modified the database file");
            }

            else if (e.Exception is PathTooLongException)
            {
                BLIO.WriteError(e.Exception, "The path to the file is too long.");
                ShowError(e.Exception, "File Path too long.", "The path to the file is too long!.");
            }


            else if (e.Exception is Exception)
            {
                BLIO.WriteError(e.Exception, "Unknown exception in main.");
            }
        }
        private void MetrocamService_CreateUserCompleted(object sender, RequestCompletedEventArgs e)
        {
            // Unsubscribe
            App.MetrocamService.CreateUserCompleted -= new MobileClientLibrary.RequestCompletedEventHandler(MetrocamService_CreateUserCompleted);

            UnauthorizedAccessException err = e.Data as UnauthorizedAccessException;

            if (err != null)
            {
                if (GlobalLoading.Instance.IsLoading)
                {
                    GlobalLoading.Instance.IsLoading = false;
                }
                // There was an error with CreateUser in the webservice
                toastDisplay = GlobalToastPrompt.CreateToastPrompt(
                    "Signup Failure",
                    "This Username and/or Email is already being registered to another account.",
                    3000);
                toastDisplay.Show();
                return;
            }

            // Now we authenticate using the username and password
            App.MetrocamService.AuthenticateCompleted += new RequestCompletedEventHandler(MetrocamService_AuthenticateCompleted);

            // Calls Authenticate to obtain UserInfo object
            App.MetrocamService.Authenticate(this.UsernameInput.Text, this.PasswordInput.Password);
        }
예제 #3
0
        public async Task ExecuteOperationAsync_UnexpectedExceptionIsWrappedInFatalClientException()
        {
            var mockPipeline = new Mock <IPipeline>(MockBehavior.Strict);

            // some unexpected exception
            var innerException = new UnauthorizedAccessException();

            mockPipeline
            .Setup(h => h.ProcessAsync(
                       It.IsAny <PipelineContext <BasicTestEntity> >(),
                       It.IsAny <ILogger>(),
                       It.IsAny <CancellationToken>()))
            .Callback((PipelineContext <BasicTestEntity> context, ILogger log, CancellationToken cancellationToken) => {
                throw innerException;
            })
            .Returns(Task.CompletedTask);

            this.mockPipelineFactory
            .Setup(h => h.GetPipeline(
                       It.IsAny <PipelineContext <BasicTestEntity> >()))
            .Returns(mockPipeline.Object);

            var getContext = new GetContext <BasicTestEntity>(EndpointName.Tests, null);

            try
            {
                await this.apiService.ExecuteOperationAsync(getContext, default).ConfigureAwait(false);

                Assert.Fail($"Expected {nameof(FatalClientException)} to be thrown.");
            }
            catch (FatalClientException e)
            {
                Assert.IsInstanceOfType(e.InnerException, innerException.GetType());
            }
        }
예제 #4
0
            private static Exception ToIoException(CodeContext context, string name, UnauthorizedAccessException e)
            {
                Exception excp = new IOException(e.Message, e);

                AddFilename(context, name, excp);
                return(excp);
            }
예제 #5
0
        private bool SetPolicyFromAuthenticodePrompt(string path, PSHost host, ref Exception reason, Signature signature)
        {
            bool policyCheckPassed = false;

            string            reasonMessage;
            RunPromptDecision decision = AuthenticodePrompt(path, signature, host);

            switch (decision)
            {
            case RunPromptDecision.RunOnce:
                policyCheckPassed = true; break;

            case RunPromptDecision.AlwaysRun:
            {
                TrustPublisher(signature);
                policyCheckPassed = true;
            }; break;

            case RunPromptDecision.DoNotRun:
                policyCheckPassed = false;
                reasonMessage     = StringUtil.Format(Authenticode.Reason_DoNotRun, path);
                reason            = new UnauthorizedAccessException(reasonMessage);
                break;

            case RunPromptDecision.NeverRun:
            {
                UntrustPublisher(signature);
                reasonMessage     = StringUtil.Format(Authenticode.Reason_NeverRun, path);
                reason            = new UnauthorizedAccessException(reasonMessage);
                policyCheckPassed = false;
            }; break;
            }

            return(policyCheckPassed);
        }
예제 #6
0
        public static void AssertSuccess(Win32ErrorCode code)
        {
            switch (code)
            {
            case Win32ErrorCode.Success:
            case Win32ErrorCode.MORE_DATA:
                // No error occured, so exit gracefully.
                return;
            }

            var       genericException = new Win32Exception((int)code);
            Exception exceptionToThrow;

            // We will try to translate the generic Win32 exception to a more specific built-in exception.
            switch (code)
            {
            case Win32ErrorCode.DS_INVALID_DN_SYNTAX:
            case Win32ErrorCode.INVALID_PARAMETER:
                exceptionToThrow = new ArgumentException(genericException.Message, genericException);
                break;

            case Win32ErrorCode.FILE_NOT_FOUND:
                exceptionToThrow = new FileNotFoundException(genericException.Message, genericException);
                break;

            case Win32ErrorCode.ACCESS_DENIED:
            case Win32ErrorCode.DS_DRA_ACCESS_DENIED:
            case Win32ErrorCode.WRONG_PASSWORD:
            case Win32ErrorCode.PASSWORD_EXPIRED:
                exceptionToThrow = new UnauthorizedAccessException(genericException.Message, genericException);
                break;

            case Win32ErrorCode.NOT_ENOUGH_MEMORY:
            case Win32ErrorCode.OUTOFMEMORY:
            case Win32ErrorCode.DS_DRA_OUT_OF_MEM:
            case Win32ErrorCode.RPC_S_OUT_OF_RESOURCES:
                exceptionToThrow = new OutOfMemoryException(genericException.Message, genericException);
                break;

            case Win32ErrorCode.NO_LOGON_SERVERS:
            case Win32ErrorCode.NO_SUCH_DOMAIN:
            case Win32ErrorCode.RPC_S_SERVER_UNAVAILABLE:
            case Win32ErrorCode.RPC_S_CALL_FAILED:
                exceptionToThrow = new ActiveDirectoryServerDownException(genericException.Message, genericException);
                break;

            case Win32ErrorCode.DS_OBJ_NOT_FOUND:
            // This error code means either a non-existing DN or Access Denied.
            case Win32ErrorCode.DS_DRA_BAD_DN:
                exceptionToThrow = new DirectoryObjectNotFoundException(null, genericException);
                break;

            // TODO: Add translation for ActiveDirectoryOperationException and for other exception types.
            default:
                // We were not able to translate the Win32Exception to a more specific type.
                exceptionToThrow = genericException;
                break;
            }
            throw exceptionToThrow;
        }
        public async Task <Token> RefreshToken(RefreshTokenCredentials refreshTokenCredentials)
        {
            var unauthorizedException = new UnauthorizedAccessException("Unauthorized token refresh action");
            var userRefreshToken      = context.RefreshToken.SingleOrDefault(t => t.Token == refreshTokenCredentials.Token && t.UserId == refreshTokenCredentials.UserId);

            if (userRefreshToken == null)
            {
                throw unauthorizedException;
            }

            var tokenManager = new JwtSecurityTokenHandler();
            var token        = tokenManager.ReadJwtToken(refreshTokenCredentials.Token);

            var tokenUserGuid = token.Claims.Where(c => c.Type == "UserId").Select(c => c.Value).FirstOrDefault();

            if (tokenUserGuid == null || tokenUserGuid != refreshTokenCredentials.UserId.ToString())
            {
                throw unauthorizedException;
            }

            var user = await userManager.FindByIdAsync(refreshTokenCredentials.UserId.ToString());

            if (user == null)
            {
                throw unauthorizedException;
            }

            return(GenerateUserToken(user));
        }
        protected HttpResponseMessage CreateUnauthenticatedMessage(UnauthorizedAccessException ex)
        {
            var resp = Request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex);

            resp.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Basic", "Realm=" + Request.RequestUri.AbsolutePath));
            return(resp);
        }
예제 #9
0
        internal async Task OnObjectCall(BlockCall request)
        {
            var reply = new BlockReply {
                RequestID = request.RequestID
            };

            try
            {
                if (CanCall(request))
                {
                    var resultStream = new MemoryStream();
                    if (request.ObjectID < 0)
                    {
                        OnChannelCall(request, resultStream);
                    }
                    else
                    {
                        _serviceCache.CallObject(request, resultStream);
                    }
                    reply.Success    = true;
                    reply.DataStream = resultStream;
                }
                else
                {
                    var ex = new UnauthorizedAccessException("Access token error");
                    reply = BlockReply.BuildFromException(ex, request.RequestID);
                }
            }
            catch (Exception ex)
            {
                reply = BlockReply.BuildFromException(ex, request.RequestID);
            }
            await SendBlockAsync(reply);
        }
 static bool IsExceptionTransient(Exception exception)
 {
     return(exception switch
     {
         UnauthorizedAccessException _ => false,
         _ => true
     });
예제 #11
0
        public async Task <Response> QueryAsync(Type type, string payload)
        {
            if (!token.HasValue)
            {
                token.Value = await interop.LoadTokenAsync();

                EnsureAuthorization();
            }

            string url = queryMapper.FindUrlByType(type);

            if (url != null)
            {
                HttpResponseMessage response = await http.PostAsync($"/api/query/{url}", new StringContent(payload, Encoding.UTF8, "text/json"));

                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    ClearAuthorization();
                    UnauthorizedAccessException exception = new UnauthorizedAccessException();
                    exceptionHandler.Handle(exception);
                    throw exception;
                }

                string responseContent = await response.Content.ReadAsStringAsync();

                return(SimpleJson.SimpleJson.DeserializeObject <JsResponse>(responseContent));
            }
            else
            {
                return(await http.PostJsonAsync <Response>($"/api/query", CreateRequest(type, payload)));
            }
        }
        public void ThrowAnUnauthorizedAccessExceptionWhenAUserIsNotAuthenticated()
        {
            // GIVEN a UserDTO containing a user's e-mail and password
            UserDTO user = new UserDTO
            {
                EmailAddress = "*****@*****.**",
                Password     = "******"
            };
            UnauthorizedAccessException mockException = new UnauthorizedAccessException("Username or password is incorrect.");

            // WHEN a user is not correctly authenticated
            TrainerCredentials mockTrainerCredentials = new TrainerCredentials
            {
                EmailAddress = "*****@*****.**",
                // NOTE: the hash should be "$2b$10$sCfS.t4SiS21G9rhNcqKue/PkEiitv/OfB0DojqdkMQneiUQw0l06"
                Hash = PASSWORD1234_HASH,
                Salt = PASSWORD1234_SALT
            };

            accountContextMock.Setup(a => a.TrainerCredentials.Find(user.EmailAddress)).Returns(mockTrainerCredentials);

            // THEN ensure an UnauthorizedAccessException is thrown
            UnauthorizedAccessException ex = Assert.Throws <UnauthorizedAccessException>(() => accountServices.AuthorizeTrainer(user));

            // AND ensure the message reads "Username or password is incorrect."
            Assert.Equal("Username or password is incorrect.", mockException.Message);
        }
예제 #13
0
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                var response = context.Response;
                response.ContentType = "application/json";

                var responseModel = ApiResponse <string> .Fail(ex.Message);

                response.StatusCode = ex switch
                {
                    ApiException e => (int)HttpStatusCode.BadRequest,
                    KeyNotFoundException e => (int)HttpStatusCode.NotFound,
                    ArgumentNullException e => (int)HttpStatusCode.NotFound,
                    UnauthorizedAccessException e => (int)HttpStatusCode.Unauthorized,
                    _ => (int)HttpStatusCode.InternalServerError
                };

                var result = JsonSerializer.Serialize(responseModel);

                await response.WriteAsync(result);
            }
        }
    }
예제 #14
0
 protected override void LogUnauthorizedAccess(string fullName, UnauthorizedAccessException ex)
 {
     this.xmlWriter.WriteStartElement("accessDenied");
     this.xmlWriter.WriteAttributeString("path", fullName);
     this.xmlWriter.WriteAttributeString("message", ex.Message);
     this.xmlWriter.WriteEndElement();
 }
예제 #15
0
 private static void UnauthorizedAccessExceptionDisplay(UnauthorizedAccessException ex)
 {
     Console.WriteLine(ex.Message);
     Console.WriteLine("\n\rHey! It seems you didn't launch this application in administrator!");
     Console.WriteLine("Sadly, this is required for the app to work.");
     Console.WriteLine("Please launch the application by right-clicking on it and clicking \"Run as Administrator\".\n\r");
 }
예제 #16
0
    public async Task RecursePath_GetFiles_OutputException()
    {
        const string path = "/unAuthorizedPath";

        const string expected = "Get Dirs: Write was called";

        // Given
        var expectedException = new UnauthorizedAccessException(expected);

        _fileSystemService.GetFiles(path).Throws(expectedException);

        var origOutWriter = Console.Error;

        await using (var sw = new StringWriter())
        {
            Console.SetError(sw);

            // When
            await _fileWalker.RecursePath(path);

            var actual = sw.ToString();

            // Then
            Assert.Contains(expected, actual);
        }

        Console.SetError(origOutWriter);
    }
예제 #17
0
        public Error Create(IExceptionHandlerFeature contextFeature)
        {
            Error error = contextFeature.Error switch
            {
                NotFoundException notFoundException
                => notFoundException.Errors == null
                    ? new NotFoundError(notFoundException.Message)
                    : new NotFoundError(notFoundException.Message,
                                        new ErrorDetailsCollection(notFoundException.Errors)),

                UnauthorizedAccessException unauthorizedAccessException
                => new UnauthorizedAccessError(unauthorizedAccessException.Message),

                AppException appException
                => new AppError(appException.Message, new ErrorDetailsCollection(appException.Errors)),

                DomainException domainException
                => new DomainError(domainException.Message, new ErrorDetailsCollection(domainException.Errors)),
                _
                => new InternalServerError(contextFeature.Error.Message)
            };

            return(error);
        }
    }
        internal static Exception CreateException(SystemSettingsError err, string msg)
        {
            Exception exp;

            switch (err)
            {
            case SystemSettingsError.InvalidParameter:
                exp = new ArgumentException(msg);
                break;

            case SystemSettingsError.NotSupported:
                exp = new NotSupportedException(msg);
                break;

            case SystemSettingsError.OutOfMemory:
            //fall through
            case SystemSettingsError.IoError:
            //fall through
            case SystemSettingsError.PermissionDenied:
                exp = new UnauthorizedAccessException(msg);
                break;

            case SystemSettingsError.LockScreenAppPasswordMode:
            //fall through
            default:
                exp = new InvalidOperationException(msg);
                break;
            }
            return(exp);
        }
예제 #19
0
        private bool SetPolicyFromAuthenticodePrompt(string path, PSHost host, ref Exception reason, System.Management.Automation.Signature signature)
        {
            string str;
            bool   flag = false;

            switch (this.AuthenticodePrompt(path, signature, host))
            {
            case RunPromptDecision.NeverRun:
                this.UntrustPublisher(signature);
                str    = StringUtil.Format(Authenticode.Reason_NeverRun, path);
                reason = new UnauthorizedAccessException(str);
                return(false);

            case RunPromptDecision.DoNotRun:
                flag   = false;
                str    = StringUtil.Format(Authenticode.Reason_DoNotRun, path);
                reason = new UnauthorizedAccessException(str);
                return(flag);

            case RunPromptDecision.RunOnce:
                return(true);

            case RunPromptDecision.AlwaysRun:
                this.TrustPublisher(signature);
                return(true);
            }
            return(flag);
        }
예제 #20
0
        public void AccessDenied()
        {
            var exception        = new UnauthorizedAccessException();
            var observedExitCode = ExitCodeUtilities.ShowException(exception);

            Assert.Equal((int)ExitCodes.AccessDenied, observedExitCode);
        }
예제 #21
0
            public static UnauthorizedAccessException /*!*/ Create(RubyClass /*!*/ self, [DefaultProtocol, DefaultParameterValue(null)] MutableString message)
            {
                UnauthorizedAccessException result = new UnauthorizedAccessException(RubyExceptions.MakeMessage(ref message, "Permission denied"));

                RubyExceptionData.InitializeException(result, message);
                return(result);
            }
예제 #22
0
        /// <summary>
        /// Opens a file with saved data.
        /// </summary>
        private async Task OpenImpl()
        {
            var dialogResult = await _fileDialogService.ShowOpenDialogAsync();

            if (dialogResult is null)
            {
                return;
            }

            try
            {
                _saveLoadManager.Open(dialogResult);
            }
            catch (Exception ex)
            {
                string message = ex switch
                {
                    JsonReaderException _ => "The selected file is not a valid JSON file.",
                    UnauthorizedAccessException _ =>
                    "The file cannot be read.  Check the permissions on the selected file.",
                       _ => ex.Message
                };

                await OpenErrorBox(message);
            }
        }
예제 #23
0
        // Copy texture from cache
        public static bool CopyFileWithRetryOnUnauthorizedAccess(string s, string path)
        {
            UnauthorizedAccessException exception = null;

            for (var k = 0; k < 20; ++k)
            {
                try
                {
                    File.Copy(s, path, true);
                    exception = null;
                }
                catch (UnauthorizedAccessException e)
                {
                    exception = e;
                }
            }

            if (exception != null)
            {
                Debug.LogException(exception);
                // Abort the update, something else is preventing the copy
                return(false);
            }

            return(true);
        }
예제 #24
0
 //Handle UnauthorizedAccessException
 public static void HandleUnauthorizedAccessException(UnauthorizedAccessException ex)
 {
     CustomMessageBox.Error(
         ex.Message.Contains("The process cannot access the file")
             ? LangProvider.GetLang("FileIsInUse")
             : LangProvider.GetLang("UnauthorizedAccess"), LangProvider.GetLang("ExceptionOccurred"));
 }
예제 #25
0
 public static void Permission(UnauthorizedAccessException e)
 {
     Console.ForegroundColor = ConsoleColor.Red;
     Console.WriteLine("unauthorised access at this level of permission");
     Console.WriteLine(e);
     Console.WriteLine("try running the program as admin");
     Console.ForegroundColor = ConsoleColor.Gray;
 }
예제 #26
0
        public void Erreur_UnauthorizedAccessException_Bien_Traite()
        {
            UnauthorizedAccessException ex = new UnauthorizedAccessException("UnauthorizedAccessException");

            GestionErreur.GerrerErreur(ex);
            msbs.Verify(mm => mm.ShowError(AxLanguage.Languages.REAplan_Erreur_Admin + "\n" + AxLanguage.Languages.REAplan_Erreur_Call + "\n" + AxLanguage.Languages.REAplan_Erreur_NumeroTelephone));
            log.Verify(ll => ll.Error(ex.GetType().Name + " | " + ex.Message + " |" + ex.StackTrace));
        }
        protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
        {
            Response.StatusCode  = 401;
            Response.ContentType = ProblemDetailsContentType;
            var problemDetails = new UnauthorizedAccessException("Unauthorized Access :(");

            await Response.WriteAsync(JsonConvert.SerializeObject(problemDetails));
        }
예제 #28
0
        public FileSystemAcccesDeniedException(UnauthorizedAccessException ex) : base(null, ex)
        {
            //"Access to the path 'C:\SoapLogDefaultService\2017-10-31' is denied."
            originalMessage = ex.Message;

            //never returns null
            currentUserName = WindowsIdentity.GetCurrent().Name;
        }
예제 #29
0
        protected IActionResult Forbidden <T>(UnauthorizedAccessException ex)
        {
            var response = new ResponseMessage <T>();

            response.AddError(ex);
            ControllerContext.HttpContext.Response.StatusCode = StatusCodes.Status403Forbidden;
            return(Ok(response));
        }
예제 #30
0
        // Third method, UnauthorizedAccessException
        public void WriteEventLog(UnauthorizedAccessException ex)
        {
            EventLog myLog = new EventLog
            {
                Source = "GoDaddy Update Tool"
            };

            myLog.WriteEntry(ex.Message, EventLogEntryType.Error);
        }
예제 #31
0
        /// <summary>
        /// Throws a <see cref="RequestException"/> if the current <see cref=
        /// "Response.Message.StatusCode"/> is different than <see cref=
        /// "expected"/>.
        /// </summary>
        /// <param name="expected">
        /// The expected <see cref="HttpStatusCode"/>.
        /// </param>
        /// <returns></returns>
        public async Task EnsureStatusCodeAsync(HttpStatusCode expected)
        {
            var statusCode = this.Message.StatusCode;

            if (statusCode == expected)
                return;

            var details = await Splunk.Client.Message.ReadMessagesAsync(this.XmlReader);
            RequestException requestException;

            switch (statusCode)
            {
                case HttpStatusCode.Forbidden:
                    requestException = new UnauthorizedAccessException(this.Message, details);
                    break;
                case HttpStatusCode.NotFound:
                    requestException = new ResourceNotFoundException(this.Message, details);
                    break;
                case HttpStatusCode.Unauthorized:
                    requestException = new AuthenticationFailureException(this.Message, details);
                    break;
                default:
                    requestException = new RequestException(this.Message, details);
                    break;
            }

            throw requestException;
        }
예제 #32
0
        /// <summary>
        /// Throw request exception asynchronous.
        /// </summary>
        /// <exception cref="RequestException">
        /// Thrown when a Request error condition occurs.
        /// </exception>
        /// <returns>
        /// A <see cref="Task"/> representing the operation.
        /// </returns>
        internal async Task ThrowRequestExceptionAsync()
        {
            var details = await Splunk.Client.Message.ReadMessagesAsync(this.XmlReader).ConfigureAwait(false);
            RequestException requestException;

            switch (this.Message.StatusCode)
            {
                case HttpStatusCode.BadRequest:
                    requestException = new BadRequestException(this.Message, details);
                    break;
                case HttpStatusCode.Forbidden:
                    requestException = new UnauthorizedAccessException(this.Message, details);
                    break;
                case HttpStatusCode.InternalServerError:
                    requestException = new InternalServerErrorException(this.Message, details);
                    break;
                case HttpStatusCode.NotFound:
                    requestException = new ResourceNotFoundException(this.Message, details);
                    break;
                case HttpStatusCode.Unauthorized:
                    requestException = new AuthenticationFailureException(this.Message, details);
                    break;
                default:
                    requestException = new RequestException(this.Message, details);
                    break;
            }

            throw requestException;
        }