コード例 #1
0
        public static Boolean SendErrorMessage(Exception ex)
        {
            factory = new ConnectionFactory()
            {
                HostName = "192.168.1.2",
                Port     = /*AmqpTcpEndpoint.UseDefaultPort*/ 5672,
                UserName = "******",
                Password = "******"
            };

            CustomError customError = new CustomError();

            customError.application_name = "frontend";
            customError.timestamp        = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fff");
            customError.message          = ex.ToString();

            string xmlResponse = XsdValidation.XmlObjectValidation(customError);

            if (xmlResponse != null)
            {
                using (var connection = factory.CreateConnection())
                    using (var channel = connection.CreateModel())
                    {
                        var addUserBody = Encoding.UTF8.GetBytes(xmlResponse);
                        channel.BasicPublish(exchange: "errors.exchange",
                                             routingKey: "",
                                             body: addUserBody
                                             );
                    }

                return(true);
            }
            return(false);
        }
コード例 #2
0
ファイル: Field.cs プロジェクト: Sckorn/battleships
    public Field(string fieldName, int player)
    {
        CustomError ce = new CustomError("Field", "constructor");

        this.cells = new Cell[this.byX, this.byY];

        for (int i = 0; i < this.byX; i++)
        {
            for (int j = 0; j < this.byY; j++)
            {
                this.cells[i, j] = new Cell(i, j);
            }
        }

        Morpher mphr = GameObject.Find("Morpher").GetComponent <Morpher>();

        mphr.InstAField(fieldName, ref this.realObjectReference);
        if (player == 1)
        {
            this.crossHair       = mphr.InstACross().GetComponent <GUITexture>();
            this.allocatingShips = true;
        }
        else
        {
            this.allocatingShips = false;
        }

        EventManager.OnResize += this.ResizeAfterCreate;
    }
コード例 #3
0
        public static async Task <(User, CustomError)> Login(string email, string password)
        {
            HttpClient  client = new HttpClient();
            User        u      = new User();
            CustomError c      = new CustomError();

            try
            {
                var loginInput = new
                {
                    email    = email,
                    password = password,
                };

                var stringPayload = JsonConvert.SerializeObject(loginInput);
                var httpContent   = new StringContent(stringPayload, Encoding.UTF8, "application/json");
                var result        = await client.PostAsync("https://na2backend.azurewebsites.net/api/user", httpContent);



                if (result.Content != null)
                {
                    var responseContent = await result.Content.ReadAsStringAsync();

                    try
                    {
                        u       = (User)JObject.Parse(responseContent);
                        AppUser = u;
                    }
                    catch
                    {
                        if (responseContent.ToLower().Contains("[error]"))
                        {
                            if (responseContent.ToLower().Contains("password"))
                            {
                                c.Scope   = "password";
                                c.Message = responseContent;
                            }
                            else if (responseContent.ToLower().Contains("email"))
                            {
                                c.Scope   = "email";
                                c.Message = responseContent;
                            }
                            else
                            {
                                c.Scope   = "app";
                                c.Message = responseContent;
                            }
                        }
                    }
                }
            }
            catch
            {
                c.Scope   = "app";
                c.Message = "Something went wrong with the connection to the server. Please contact your admin!";
            }

            return(u, c);
        }
コード例 #4
0
        public async Task <IActionResult> Index()
        {
            try
            {
                var model = new ContactFormViewModel();

                if (User.Identity.IsAuthenticated)
                {
                    var userName    = this.HttpContext.User.Identity.Name;
                    var currentUser = await this.usersService.GetByUserName(userName);

                    model.FirstName   = currentUser.FirstName;
                    model.LastName    = currentUser.LastName;
                    model.Email       = currentUser.Email;
                    model.PhoneNumber = currentUser.PhoneNumber;
                }
                return(View(model));
            }
            catch (Exception ex)
            {
                var error = new CustomError()
                {
                    InnerException = "",
                    Message        = ex.Message,
                    Source         = ex.Source,
                    StackTrace     = ex.StackTrace,
                    CustomMessage  = ""
                };

                await this.customErrors.Add(error);

                return(this.View());
            }
        }
コード例 #5
0
        public void SerializeError_CustomError_CanSerialize()
        {
            // Arrange
            var error           = new CustomError(507, "title", "detail", "custom");
            var errorCollection = new ErrorCollection();

            errorCollection.Add(error);

            var expectedJson = JsonConvert.SerializeObject(new
            {
                errors = new dynamic[] {
                    new {
                        myCustomProperty = "custom",
                        title            = "title",
                        detail           = "detail",
                        status           = "507"
                    }
                }
            });
            var serializer = GetResponseSerializer <OneToManyPrincipal>();

            // Act
            var result = serializer.Serialize(errorCollection);

            // Assert
            Assert.Equal(expectedJson, result);
        }
コード例 #6
0
        /// <summary>
        /// Async method to send POST request to xMatters API
        /// </summary>
        /// <param name="customError">Custom error created by GenerateCustomError method.</param>
        /// <returns>Result containing boolean of true/false which is provided back to the requestor.</returns>
        private async Task <bool> ReportException(CustomError customError)
        {
            // Visual Studio Debug only output
            Debug.WriteLine("exception found!");
            Debug.WriteLine("ID:" + customError.ID);
            Debug.WriteLine("Error Code:" + customError.ErrorCode);
            Debug.WriteLine("ErrorDate:" + customError.ErrorDate);
            Debug.WriteLine("CustomErrorText:" + customError.CustomErrorText);
            Debug.WriteLine("RawErrorData:" + customError.RawErrorData);

            // Create the HttpClient and submit the custom error to xMatters API Endpoint to be processed by the Workflow

            using (var client = new HttpClient())
            {
                var uri        = "https://mariamatthews.xmatters.com/api/integration/1/functions/79312140-319c-438e-aec7-2f84cf0d86d1/triggers?apiKey=8382e5fc-b711-4185-81f7-66b4741dc5bf";
                var jsonString = JsonSerializer.Serialize(customError);

                var response = await client.PostAsync(uri, new StringContent(jsonString, Encoding.UTF8, "application/json"));

                if (response.IsSuccessStatusCode)
                {
                    // return success if the response was a success
                    return(true);
                }
            }

            return(false);
        }
コード例 #7
0
ファイル: Field.cs プロジェクト: Sckorn/battleships
    public Field(string fieldName, int player)
    {
        CustomError ce = new CustomError("Field", "constructor");
        this.cells = new Cell[this.byX, this.byY];

        for (int i = 0; i < this.byX; i++)
        {
            for (int j = 0; j < this.byY; j++)
            {
                this.cells[i, j] = new Cell(i, j);
            }
        }

        Morpher mphr = GameObject.Find("Morpher").GetComponent<Morpher>();
        mphr.InstAField(fieldName, ref this.realObjectReference);
        if (player == 1)
        {
            this.crossHair = mphr.InstACross().GetComponent<GUITexture>();
            this.allocatingShips = true;
        }
        else
        {
            this.allocatingShips = false;
        }

        EventManager.OnResize += this.ResizeAfterCreate;
    }
コード例 #8
0
        public ActionResult TableNames(FormCollection form)
        {
            try
            {
                Dictionary <string, string> conElts = new Dictionary <string, string>();
                conElts.Add("dbProvider", form["dbProvider"]);
                conElts.Add("dbServer", form["dbServer"]);
                conElts.Add("dbInstance", form["dbInstance"]);
                conElts.Add("serName", form["serName"]);
                conElts.Add("dbName", form["dbName"]);
                conElts.Add("dbSchema", form["dbSchema"]);
                conElts.Add("dbUserName", form["dbUserName"]);
                conElts.Add("dbPassword", form["dbPassword"]);
                conElts.Add("portNumber", form["portNumber"]);

                List <string> tableNames = _repository.GetTableNames(form["scope"], form["app"], conElts);
                return(Json(new { success = true, data = tableNames }));
            }
            catch (Exception e)
            {
                // return Json(new { success = false, error = e.ToString() });
                _logger.Error(e.ToString());
                _CustomErrorLog = new CustomErrorLog();
                _CustomError    = _CustomErrorLog.customErrorLogger(ErrorMessages.errUITableName, e, _logger);
                return(Json(new { success = false, message = "[ Message Id " + _CustomError.msgId + "] - " + _CustomError.errMessage, stackTraceDescription = _CustomError.stackTraceDescription }, JsonRequestBehavior.AllowGet));
            }
        }
コード例 #9
0
        public ActionResult <OutProductObject> updateProduct(UpdateProductObject newProduct)
        {
            if (newProduct == null)
            {
                return(BadRequest(ModelState));
            }
            product selected = _repo.getProduct(newProduct.productId);

            if (selected == null)
            {
                return(NotFound());
            }
            product newProd = _mapper.Map <product> (newProduct);

            if (selected.productName != newProd.productName)
            {
                if (_repo.productExistsByName(newProd.productName))
                {
                    CustomError productAlreadyExists = new CustomError(
                        alreadyExistsHeader,
                        alreadyExistsBody,
                        alreadyExistsCode);
                    return(NotFound(productAlreadyExists));
                }
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            newProd.productRegisterDate = DateTime.Now;
            _repo.updateProduct(newProd);
            OutProductObject outProduct = _mapper.Map <OutProductObject> (newProd);

            return(Ok(outProduct));
        }
コード例 #10
0
        public JsonResult ImportCache(FormCollection form)
        {
            try
            {
                string scope     = form["scope"];
                string app       = form["app"];
                string importURI = form["importURI"];
                int    timeout   = int.Parse(form["timeout"]);

                Response response = _repository.ImportCache(scope, app, importURI, timeout);

                if (response.Level == StatusLevel.Error)
                {
                    return(Json(new { success = false, message = response.Messages, stackTraceDescription = response.StatusText }, JsonRequestBehavior.AllowGet));
                }


                return(Json(new { success = true, response, JsonRequestBehavior.AllowGet }));
            }

            catch (Exception e)
            {
                _CustomErrorLog = new CustomErrorLog();
                _CustomError    = _CustomErrorLog.customErrorLogger(ErrorMessages.errUIImportCache, e, _logger);
                return(Json(new { success = false, message = "[ Message Id " + _CustomError.msgId + "] - " + _CustomError.errMessage, stackTraceDescription = _CustomError.stackTraceDescription }, JsonRequestBehavior.AllowGet));
            }
        }
コード例 #11
0
ファイル: MainMenu.cs プロジェクト: pjephec/Ephec-Airlines
 private void cmbDateVolAller_SelectedIndexChanged(object sender, EventArgs e)
 {
     if (radioAllerRetour.Checked)
     {
         PLA_GetDateByVolId_Result     oDateSimple = (PLA_GetDateByVolId_Result)cmbDateVolAller.SelectedItem; //Date vol simple
         VOL_SelectAllListChoix_Result oVol        = (VOL_SelectAllListChoix_Result)cmbVolAller.SelectedItem;
         BLPlannings oBl = new BLPlannings();
         List <PLA_GetDateByVolIdDateCritere_Result> oList      = new List <PLA_GetDateByVolIdDateCritere_Result>();
         VOL_SelectAllListChoixRetour_Result         oVolRetour = new VOL_SelectAllListChoixRetour_Result();
         try {
             oVolRetour = BLVols.GetVolRetour(oVol.VOL_ID_VILLE_ARR, oVol.VOL_ID_VILLE_DEP);
             oList      = BLPlannings.GetDatesVol(oVolRetour.VOL_ID, oDateSimple.PLAN_VOL_DATE);
             cmbDateVolRetour.DataSource    = oList;
             cmbDateVolRetour.ValueMember   = "PLAN_ID";
             cmbDateVolRetour.DisplayMember = "PLAN_VOL_DATE";
         }
         catch (CustomError cEx) {
             MessageBox.Show(cEx.Message);
         }
         catch (Exception ex) {
             CustomError cEx = new CustomError(666);
             MessageBox.Show(cEx.Message);
         }
     }
 }
コード例 #12
0
    protected void btnRun_Click(object sender, EventArgs e)
    {
        txtOutput.Text = "";

        foreach (string line in txtUsersToDelete.Text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None))
        {
            string userToDelete = line.Trim().TrimStart('0');
            if (userToDelete != "")
            {
                if (userToDelete.ToLower().Contains("admin"))
                {
                    AddMessage(userToDelete, "Må ikke slettes");
                }
                else
                {
                    CustomError error = ADUser.Delete(userToDelete);

                    if (error.HasErrors)
                    {
                        AddMessage(userToDelete, error.ToString());
                    }
                    else
                    {
                        AddMessage(userToDelete, "Slettet");
                    }
                }
            }
        }
    }
コード例 #13
0
ファイル: EditADUser.aspx.cs プロジェクト: Neophear/ADUC
    private void ChangePassword()
    {
        string newPassword    = pwfPassword.Password;
        bool   mustChangePass = User.IsInRole("Admin") ? chkbxForceChangePassword.Checked : !pwfPassword.IsPasswordGenerated;
        string MANR           = ViewState["MANR"].ToString();

        CustomError userErrors = ADUser.ChangePassword(MANR, newPassword, mustChangePass, pwdGenerated: pwfPassword.IsPasswordGenerated);

        if (!userErrors.HasErrors)
        {
            pwfPassword.GeneratePassword();
            mailPassword         = newPassword;
            btnSendEmail.Text    = "Email koden til: 00" + MANR + "@mil.dk ?";
            btnSendEmail.Visible = true;
            SetMessage(String.Format("Password ændret til: {0}", newPassword));
            hplPrint.NavigateUrl = String.Format("~/Print/{0}/{1}", MANR, newPassword);
            hplPrint.Visible     = true;
            txtMANR.Focus();
            chkbxChangePassword.Checked      = false;
            chkbxForceChangePassword.Checked = false;
        }
        else
        {
            SetMessage(userErrors.ToString(), true);
        }
    }
コード例 #14
0
 public ActionResult DBDictionary(FormCollection form)
 {
     try
     {
         DatabaseDictionary dbDict = _repository.GetDBDictionary(form["scope"], form["app"]);
         return(Json(dbDict, JsonRequestBehavior.AllowGet));
     }
     catch (Exception e)
     {
         _logger.Error(e.ToString());
         if (e.InnerException != null)
         {
             string      description    = ((System.Net.HttpWebResponse)(((System.Net.WebException)(e.InnerException)).Response)).StatusDescription;
             var         jsonSerialiser = new JavaScriptSerializer();
             CustomError json           = (CustomError)jsonSerialiser.Deserialize(description, typeof(CustomError));
             return(Json(new { success = false, message = "[ Message Id " + json.msgId + "] - " + json.errMessage, stackTraceDescription = json.stackTraceDescription }, JsonRequestBehavior.AllowGet));
         }
         else
         {
             _CustomErrorLog = new CustomErrorLog();
             _CustomError    = _CustomErrorLog.customErrorLogger(ErrorMessages.errUIDBDictionary, e, _logger);
             return(Json(new { success = false, message = "[ Message Id " + _CustomError.msgId + "] - " + _CustomError.errMessage, stackTraceDescription = _CustomError.stackTraceDescription }, JsonRequestBehavior.AllowGet));
         }
         //throw e;
     }
 }
コード例 #15
0
        public ActionResult CacheInfo(FormCollection form)
        {
            try
            {
                CacheInfo cacheInfo = _repository.GetCacheInfo(form["scope"], form["app"]);

                // NOTE: default ASP .NET serializer has issue with datetime fields, use JSON. NET library
                string json = JsonConvert.SerializeObject(cacheInfo);
                return(Content(json));
            }
            catch (Exception e)
            {
                _logger.Error(e.ToString());
                if (e.InnerException != null)
                {
                    string      description    = ((System.Net.HttpWebResponse)(((System.Net.WebException)(e.InnerException)).Response)).StatusDescription;//;
                    var         jsonSerialiser = new JavaScriptSerializer();
                    CustomError json           = (CustomError)jsonSerialiser.Deserialize(description, typeof(CustomError));
                    return(Json(new { success = false, message = "[ Message Id " + json.msgId + "] - " + json.errMessage, stackTraceDescription = json.stackTraceDescription }, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    _CustomErrorLog = new CustomErrorLog();
                    _CustomError    = _CustomErrorLog.customErrorLogger(ErrorMessages.errGetUICacheInfo, e, _logger);
                    return(Json(new { success = false, message = "[ Message Id " + _CustomError.msgId + "] - " + _CustomError.errMessage, stackTraceDescription = _CustomError.stackTraceDescription }, JsonRequestBehavior.AllowGet));
                }
                //throw e;
            }
        }
コード例 #16
0
ファイル: Objects.cs プロジェクト: Neophear/ADUC
    public static CustomError Mail(string accountname, string Password, bool logging = true)
    {
        CustomError errors = new CustomError();

        if (!DoesUserExist(accountname))
        {
            errors.Add(CustomError.ErrorType.UserDoesNotExist);
        }
        else
        {
            try
            {
                ADUser user = Find(accountname);
                Utilities.SendMail(user.FullName, accountname, Password);
                if (logging)
                {
                    Logging.WriteLog(Logging.Action.Mail, Logging.ObjectType.ADUser, accountname, "", null, "Mail sendt");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        return(errors);
    }
コード例 #17
0
ファイル: BULKs.aspx.cs プロジェクト: Neophear/ADUC
    protected CustomError CreateADUser(string adusername, string firstname, string lastname, string oudn, string password, bool mustChangePassword)
    {
        CustomError errors = new CustomError();

        if (adusername == String.Empty)
        {
            errors.Add(CustomError.ErrorType.NoUsername);
        }

        if (firstname == String.Empty)
        {
            errors.Add(CustomError.ErrorType.NoFirstname);
        }

        if (lastname == String.Empty)
        {
            errors.Add(CustomError.ErrorType.NoLastname);
        }

        if (!errors.HasErrors)
        {
            ADUser user = new ADUser(adusername, firstname, lastname, password, oudn);
            errors = user.Save(mustChangePassword, true);
        }

        return(errors);
    }
コード例 #18
0
        public void Can_Return_Custom_Error_Types()
        {
            // arrange
            var error           = new CustomError(507, "title", "detail", "custom");
            var errorCollection = new ErrorCollection();

            errorCollection.Add(error);

            var expectedJson = JsonConvert.SerializeObject(new {
                errors = new dynamic[] {
                    new {
                        myCustomProperty = "custom",
                        title            = "title",
                        detail           = "detail",
                        status           = "507"
                    }
                }
            });

            // act
            var result = new JsonApiSerializer(null, null, null)
                         .Serialize(errorCollection);

            // assert
            Assert.Equal(expectedJson, result);
        }
コード例 #19
0
ファイル: HttpErrorModule.cs プロジェクト: jamestharpe/Utilla
        void context_Error(object sender, System.EventArgs e)
        {
            HttpContext   context   = ((HttpApplication)sender).Context;
            HttpException exception = context.Error as HttpException;

            if (exception != null)
            {
                // Get error information
                int statusCode = exception.GetHttpCode();
                // Update the response with the correct status code
                context.Response.ClearHeaders();
                context.Response.ClearContent();
                context.Response.StatusCode = statusCode;

                // Read configuration
                CustomErrorsSection customErrorsSection = (CustomErrorsSection)ConfigurationManager.GetSection("system.web/customErrors");
                CustomError         customError         = customErrorsSection.Errors[context.Response.StatusCode.ToString()];
                string errorPageUrl = (customError == null) ? null : customError.Redirect;
                if (string.IsNullOrEmpty(errorPageUrl))
                {
                    errorPageUrl = customErrorsSection.DefaultRedirect;
                }

                // Handle the request
                if (!string.IsNullOrEmpty(errorPageUrl))
                {
                    context.Server.Transfer(errorPageUrl);
                }
                else
                {
                    context.Response.Flush();
                }
            }
        }
コード例 #20
0
        public async Task Handle_AccountIsNotActive_SpecificErrorAnd401()
        {
            // Arrange

            LoginCommand request = new LoginCommand
            {
                Email    = ConstantsAccountsCQTest.Email,
                Password = ConstantsAccountsCQTest.Password
            };

            _accountRepositoryMock.Setup(x => x.ExistsAccount(request.Email, request.Password)).Returns(true);
            _accountRepositoryMock.Setup(x => x.GetAccount(request.Email, request.Password)).Returns(ConstantsAccountsCQTest.AccountTest);
            CustomError errorUserDisabled = new CustomError(ErrorsCodesContants.USER_DISABLED, ErrorsMessagesConstants.USER_DISABLED, 401);

            _userStatusVerificationMock.Setup(x => x.UserIsActive(ConstantsAccountsCQTest.AccountTest.Id)).Returns(Results.Fail(errorUserDisabled));

            // Act

            Result <PortalAccount> result = await _handler.Handle(request, CancellationToken.None);

            // Assert
            result.IsSuccess.Should().BeFalse();
            result.Errors.Count.Should().Be(1);
            result.Errors[0].Message.Should().Be(ErrorsMessagesConstants.USER_DISABLED);
            result.Errors[0].Metadata[ErrorKeyPropsConstants.ERROR_CODE].Should().Be(errorUserDisabled.Metadata[ErrorKeyPropsConstants.ERROR_CODE]);
            result.Errors[0].Metadata[ErrorKeyPropsConstants.ERROR_HTTP_CODE].Should().Be(errorUserDisabled.Metadata[ErrorKeyPropsConstants.ERROR_HTTP_CODE]);
        }
コード例 #21
0
ファイル: BaseBLL.cs プロジェクト: thachgiasoft/ditiecms
 /// <summary>
 /// 清除当前异常
 /// </summary>
 public void ClearError()
 {
     if (modCustomErr != null)
     {
         modCustomErr = null;
     }
 }
コード例 #22
0
        public ActionResult DBProviders()
        {
            NameValueList providers = new NameValueList();

            try
            {
                foreach (Provider provider in System.Enum.GetValues(typeof(Provider)))
                {
                    string value = provider.ToString();
                    providers.Add(new ListItem()
                    {
                        Name = value, Value = value
                    });
                }

                return(Json(providers, JsonRequestBehavior.AllowGet));
            }
            catch (Exception e)
            {
                _logger.Error(e.ToString());
                _CustomErrorLog = new CustomErrorLog();
                _CustomError    = _CustomErrorLog.customErrorLogger(ErrorMessages.errUIDBProviders, e, _logger);
                return(Json(new { success = false, message = "[ Message Id " + _CustomError.msgId + "] - " + _CustomError.errMessage, stackTraceDescription = _CustomError.stackTraceDescription }, JsonRequestBehavior.AllowGet));
            }
        }
コード例 #23
0
ファイル: AdminForm.cs プロジェクト: pjephec/Ephec-Airlines
        private void cmbVolDetails_SelectedIndexChanged(object sender, EventArgs e)
        {
            Models.Vol             oVol         = (Models.Vol)cmbVolDetails.SelectedItem;
            List <Models.Planning> planningList = BLPlannings.GetDatesByVolId(oVol.IdVol);

            try {
                if (planningList.Count == 0)
                {
                    cmbVolDetails.Text = "";                 // Pas de plannings trouvés, on n'affiche rien
                    dataGridViewPassagers.DataSource = null; // Pas de vols, pas de passagers
                }
                else
                {
                    cmbVolDetails.DataSource    = planningList;
                    cmbVolDetails.ValueMember   = "IdPlan";
                    cmbVolDetails.DisplayMember = "DateVol";
                }
            }
            catch (CustomError cEx) {
                MessageBox.Show(cEx.Message);
            }
            catch (Exception ex) {
                CustomError cEx = new CustomError(666);
                MessageBox.Show(cEx.Message);
            }
        }
コード例 #24
0
        public ActionResult SaveDBDictionary()
        {
            try
            {
                string scope = Request.Params["scope"];
                string app   = Request.Params["app"];

                var reader = new StreamReader(Request.InputStream);
                var json   = reader.ReadToEnd();

                DatabaseDictionary dictionary = Utility.FromJson <DatabaseDictionary>(json);
                Response           response   = _repository.SaveDBDictionary(scope, app, dictionary);

                if (response.Level == StatusLevel.Success)
                {
                    string dictKey = string.Format("Dictionary.{0}.{1}", scope, app);
                    Session[dictKey] = dictionary;
                    return(Json(new { success = true }, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    return(Json(new { success = false, message = response.Messages, stackTraceDescription = response.StatusText }, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception e)
            {
                //return Json(new { success = true, message = e.ToString() });
                //  return null;
                _logger.Error(e.ToString());
                _CustomErrorLog = new CustomErrorLog();
                _CustomError    = _CustomErrorLog.customErrorLogger(ErrorMessages.errUISaveDBDirectory, e, _logger);
                return(Json(new { success = false, message = "[ Message Id " + _CustomError.msgId + "] - " + _CustomError.errMessage, stackTraceDescription = _CustomError.stackTraceDescription }, JsonRequestBehavior.AllowGet));
            }
        }
コード例 #25
0
        public async Task <ActionResult> ByKeyword(Guid keywordId, int page = 1)
        {
            try
            {
                var viewModel = this.articles.GetByKeyword(keywordId)
                                .To <ArticleViewModel>().ToPagedList(page, 2);

                ViewBag.KeywordId = keywordId;

                return(this.View(viewModel));
            }
            catch (Exception ex)
            {
                var error = new CustomError()
                {
                    InnerException = "",
                    Message        = ex.Message,
                    Source         = ex.Source,
                    StackTrace     = ex.StackTrace,
                    CustomMessage  = ""
                };

                await this.customErrors.Add(error);

                return(this.View());
            }
        }
コード例 #26
0
        public static CustomError HandleException(Exception exception, string message = "")
        {
            CustomError error         = new CustomError();
            var         errorMessage  = "Error!";
            var         errorCode     = HttpStatusCode.BadRequest;
            var         exceptionType = exception.GetType();

            switch (exception)
            {
            case Exception e when exceptionType == typeof(UnauthorizedAccessException):
                errorCode = HttpStatusCode.Unauthorized;
                break;

            case ApplicationException e when exceptionType == typeof(ApplicationException):
                errorCode    = HttpStatusCode.BadRequest;
                errorMessage = (message == "")? e.Message: message;
                break;

            case SqlException e when exceptionType == typeof(SqlException):
                error.ErrorCode = e.ErrorCode;
                errorMessage    = (message == "") ? "Database Error!":message;
                break;

            default:
                errorCode    = HttpStatusCode.InternalServerError;
                errorMessage = (message == "") ? "Internal Server Error!":message;
                break;
            }
            error.ErrorCode = error.ErrorCode > 0 ? error.ErrorCode : Convert.ToInt32(errorCode);
            error.Message   = errorMessage;

            return(error);
        }
コード例 #27
0
        public async Task <ActionResult> Index(int page = 1)
        {
            try
            {
                // Keyword[] parameter
                if (!cache.TryGetValue("ArticlesCache", out ICollection <ArticleViewModel> cacheEntry))
                {
                    cacheEntry = this.articles.GetAll()
                                 .To <ArticleViewModel>().ToList();

                    cache.Set("ArticlesCache", cacheEntry);
                }
                var viewModel = cacheEntry.AsQueryable().ToPagedList(page, 5);
                return(this.View(viewModel));
            }
            catch (Exception ex)
            {
                var error = new CustomError()
                {
                    InnerException = "",
                    Message        = ex.Message,
                    Source         = ex.Source,
                    StackTrace     = ex.StackTrace,
                    CustomMessage  = ""
                };

                await this.customErrors.Add(error);

                return(this.View());
            }
        }
コード例 #28
0
        /// <summary>
        /// Generates custom error based on ValidationResult and other conditions.
        /// </summary>
        /// <param name="exception">System/Default Exception when unhandled error happens.</param>
        /// <param name="invalidInputLog">Input log that has caused the issue.</param>
        /// <param name="validationResult">ValidationResult enum received.</param>
        /// <returns></returns>
        private bool GenerateCustomError(ValidationResult validationResult, Exception exception = null, InputLog invalidInputLog = null)
        {
            var customError = new CustomError(); //let constructor build default object

            // if input log is provided, copy the ID and date
            if (invalidInputLog != null)
            {
                customError.ID        = invalidInputLog.ID;
                customError.ErrorDate = invalidInputLog.Date;
            }

            // provide the content in RawErrorData
            customError.RawErrorData = invalidInputLog.Content ?? null;

            // if exception is provided, copy the message
            if (exception != null)
            {
                customError.RawErrorData += $" Raw Exception: {exception.Message ?? null}";
            }

            customError.Severity = "HIGH";

            // refactor on next push, the complexity of method suggest moving the whole functionality to a class level
            if (validationResult == ValidationResult.DATE_MISSING || validationResult == ValidationResult.ID_MISSING)
            {
                customError.Severity = "MEDIUM";
            }

            customError.ErrorSummary    = validationResult.ToString() ?? null;
            customError.ErrorCode       = Convert.ToInt32(validationResult);
            customError.CustomErrorText = validationResult.Description();

            return(ReportException(customError).Result);
        }
コード例 #29
0
        public async Task <ActionResult> ById(Guid id)
        {
            try
            {
                var article = await this.articles.GetById(id);

                var viewModel       = this.mapper.Map <FullArticleViewModel>(article);
                var keywordArticles = article.KeywordArticles;

                foreach (var ka in keywordArticles)
                {
                    this.GetSeoHelper().AddMetaKeyword(ka.Keyword.Content);
                }

                return(this.View(viewModel));
            }
            catch (Exception ex)
            {
                var error = new CustomError()
                {
                    InnerException = "",
                    Message        = ex.Message,
                    Source         = ex.Source,
                    StackTrace     = ex.StackTrace,
                    CustomMessage  = ""
                };

                await this.customErrors.Add(error);

                return(this.View());
            }
        }
コード例 #30
0
        public async Task Handle_ErrorSavingChanges_SpecificError500()
        {
            // Arrange

            LoginCommand request = new LoginCommand
            {
                Email    = ConstantsAccountsCQTest.Email,
                Password = ConstantsAccountsCQTest.Password
            };

            _accountRepositoryMock.Setup(x => x.ExistsAccount(request.Email, request.Password)).Returns(true);
            _accountRepositoryMock.Setup(x => x.GetAccount(request.Email, request.Password)).Returns(ConstantsAccountsCQTest.AccountTest);
            _userStatusVerificationMock.Setup(x => x.UserIsActive(ConstantsAccountsCQTest.AccountTest.Id)).Returns(Results.Ok());
            _tokenCreatorMock.Setup(x => x.CreateToken(ConstantsAccountsCQTest.AccountTest)).Returns(ConstantsAccountsCQTest.Token2);
            CustomError errorSavingModifications = new CustomError(
                ErrorsCodesContants.UNABLE_TO_SAVE_CHANGES_IN_ACCOUNT_TABLE,
                ErrorsMessagesConstants.UNABLE_TO_SAVE_CHANGES_IN_ACCOUNT_TABLE, 500);

            _accountRepositoryMock.Setup(x => x.SaveModifications()).Returns(Results.Fail(errorSavingModifications));

            // Act

            Result <PortalAccount> result = await _handler.Handle(request, CancellationToken.None);

            // Assert
            result.IsSuccess.Should().BeFalse();
            result.Errors.Count.Should().Be(1);
            result.Errors[0].Message.Should().Be(ErrorsMessagesConstants.UNABLE_TO_SAVE_CHANGES_IN_ACCOUNT_TABLE);
            result.Errors[0].Metadata[ErrorKeyPropsConstants.ERROR_CODE].Should().Be(errorSavingModifications.Metadata[ErrorKeyPropsConstants.ERROR_CODE]);
            result.Errors[0].Metadata[ErrorKeyPropsConstants.ERROR_HTTP_CODE].Should().Be(errorSavingModifications.Metadata[ErrorKeyPropsConstants.ERROR_HTTP_CODE]);
        }
コード例 #31
0
ファイル: Field.cs プロジェクト: Sckorn/battleships
 public Field()
 {
     CustomError ce = new CustomError("Field", "constructor");
     this.cells = new Cell[this.byX, this.byY];
     GUITexture gt = new GUITexture();
     Jobster jb = GameObject.Find("jobster").GetComponent<Jobster>();
 }
コード例 #32
0
ファイル: Objects.cs プロジェクト: Neophear/ADUC
    /// <summary>
    /// Saves the user to AD
    /// </summary>
    /// <returns>Returns an Error object with information about eventual errors</returns>
    public CustomError Save(bool mustChangePassword, bool BULK)
    {
        CustomError errors = new CustomError();

        if (DoesUserExist(AccountName))
        {
            errors.Add(CustomError.ErrorType.UserExists);
        }
        else
        {
            try
            {
                up.SamAccountName    = AccountName;
                up.UserPrincipalName = AccountName + "@TRR-INET.local";
                up.Surname           = Lastname;
                up.GivenName         = Firstname;
                up.DisplayName       = AccountName;
                up.SetPassword(Password);
                up.AccountExpirationDate = DateExpires;
                up.Enabled = true;

                //up.HomeDrive = "P:";
                //up.HomeDirectory = (@"\\TRR-I-SRV2\Pdrev$\" + AccountName);

                if (mustChangePassword)
                {
                    up.ExpirePasswordNow();
                }

                up.Save();

                //CreatePDriveFolder();
                //DirectoryEntry entry = (DirectoryEntry)up.GetUnderlyingObject();
                //entry.InvokeSet("HomeDirectory", new object[] { (@"\\TRR-I-SRV2\Pdrev$\" + AccountName) });
                //entry.InvokeSet("HomeDrive", new object[] { "P:" });
                //entry.InvokeSet("ProfilePath", new object[] { (@"\\TRR-SRV1\UserProfiles$\" + AccountName) });
                //entry.CommitChanges();

                if (!BULK)
                {
                    Logging.WriteLog(Logging.Action.Create, Logging.ObjectType.ADUser, AccountName, (!mustChangePassword ? Password : String.Empty), mustChangePassword, String.Format("{0}{1}", FullName, (DateExpires.HasValue ? (" - " + DateExpires.Value.ToShortDateString()) : String.Empty)));
                }
            }
            catch (PrincipalExistsException)
            {
                errors.Add(CustomError.ErrorType.UserExists);
            }
            catch (PrincipalOperationException)
            {
                errors.Add(CustomError.ErrorType.OUDoesNotExist);
            }
            catch (InvalidOperationException)
            {
                errors.Add(CustomError.ErrorType.UnknownError);
            }
        }

        return(errors);
    }
コード例 #33
0
ファイル: Field.cs プロジェクト: Sckorn/battleships
 public Field(string fieldName)
 {
     CustomError ce = new CustomError("Field", "constructor");
     this.cells = new Cell[this.byX, this.byY];
     Morpher mphr = GameObject.Find("Morpher").GetComponent<Morpher>();
     mphr.InstAField(fieldName, ref this.realObjectReference);
     this.crossHair = mphr.InstACross().GetComponent<GUITexture>();
 }
コード例 #34
0
ファイル: Jobster.cs プロジェクト: Sckorn/battleships
 public void GetCrossTexture()
 {
     CustomError ce = new CustomError();
     GUITexture gt = GameObject.Find("jobster").GetComponent<GUITexture>();
     if (gt == null)
     {
         ce.description = "Texture component not found!\n";
        // ce.isSuccess = false;
     }
     else
     {
        // ce.isSuccess = true;
         this.startedGame.Human.currentField.crossHair = gt;
     }
 }
コード例 #35
0
ファイル: Jobster.cs プロジェクト: Sckorn/battleships
    public CustomError startJob(string action, string fromClass, string fromMethod)
    {
        CustomError ce = new CustomError(fromClass, fromMethod);

        ce.isSuccess = false;
        System.Type t = this.GetType();
        foreach (System.Reflection.MethodInfo mi in t.GetMethods())
        {
            if (mi.Name == action)
            {
                ce.isSuccess = true;
                mi.Invoke(this, null);
            }
        }
        if (!ce.isSuccess)
        {
            ce.description = "There is no such action!\n";
        }

        return ce;
    }
コード例 #36
0
	public void Set(CustomError customError) {}
コード例 #37
0
	// Methods
	public void Add(CustomError customError) {}