public virtual ServiceProcessingResult ToServiceProcessingResult(ProcessingError processingError)
        {
            var processingResult = new ServiceProcessingResult
            {
                IsSuccessful = IsSuccessful
            };

            if (!IsSuccessful)
            {
                processingResult.Error = Error.CanBeFixedByUser ? Error : processingError;
            }
            return(processingResult);
        }
 public override void OnException(HttpActionExecutedContext context)
 {
     //Log Critical errors
     Debug.WriteLine(context.Exception);
     ServiceProcessingResult<string> result = new ServiceProcessingResult<string>
     {
         Error = new ProcessingError(_message, _message, true),
         IsSuccessful = false,
         Data = ""
     };
     var settings = new JsonSerializerSettings {ContractResolver = new CamelcaseContractResolver()};
     throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.OK)
     {
         Content = new StringContent(JsonConvert.SerializeObject(result, Formatting.Indented, settings)),
         ReasonPhrase = "Critical Exception"
     });
 }
        public IHttpActionResult GetLoggedInUserRole()
        {
            var processingResult = new ServiceProcessingResult<ApplicationRole>();
            var loggedInUserRole = base.GetLoggedInUserRole();
            if (loggedInUserRole == null)
            {
                processingResult.IsSuccessful = false;
                processingResult.Error = new ProcessingError("An error occurred while getting current User's role.",
                    "An error occurred while retrieving your role. If the problem persists, contact support.", true);
                Logger.Error("An error occurred while retrieving current User's role.");
                return Ok(processingResult);
            }

            processingResult.IsSuccessful = true;
            processingResult.Data = loggedInUserRole;
            return Ok(processingResult);
        }
示例#4
0
        public async Task<IHttpActionResult> getCowForEdit(string CowID)
        {
            var processingResult = new ServiceProcessingResult<Cow> { IsSuccessful = true };

            var cowDataService = new CowDataService();
            var cowResult = await cowDataService.getCowForEdit(CowID);
            if (!cowResult.IsSuccessful)
            {
                processingResult.IsSuccessful = false;
                processingResult.Error = new ProcessingError("Unable to retrieve cow data for edit.", "Unable to retrieve cow data for edit.", true, false);
                return Ok(processingResult);
            }

            processingResult.Data = cowResult.Data;

            return Ok(processingResult);
        }
        //TODO: Look in to how this could be accomplished at the same time as the Update user call
        public async Task<ServiceProcessingResult> UpdateUserRoleIfNecessary(string newRoleName, ApplicationRole oldRole, string userId)
        {
            var processingResult = new ServiceProcessingResult { IsSuccessful = true };
            if (newRoleName == oldRole.Name)
            {
                return processingResult;
            }

            if (GetRoleWithName(newRoleName) != null && await _userManager.IsInRoleAsync(userId, newRoleName) == false)
            {
                try
                {
                    var result = await _userManager.RemoveFromRoleAsync(userId, oldRole.Name);
                    if (!result.Succeeded)
                    {
                        var identityErrors = String.Join("\n", result.Errors);
                        var logMessage = String.Format("Failed to remove user from role. Errors: {0}", identityErrors);
                        Logger.Error(logMessage);

                        processingResult.IsSuccessful = false;
                        processingResult.Error = ErrorValues.USER_ROLE_UPDATE_FAILED_ERROR;
                        return processingResult;
                    }

                    result = await _userManager.AddToRoleAsync(userId, newRoleName);
                    if (!result.Succeeded)
                    {
                        var identityErrors = String.Join("\n", result.Errors);
                        var logMessage = String.Format("Failed to add user to role. Errors: {0}", identityErrors);
                        Logger.Error(logMessage);

                        processingResult.IsSuccessful = false;
                        processingResult.Error = ErrorValues.USER_ROLE_UPDATE_FAILED_ERROR;
                    }
                }
                catch (Exception ex)
                {
                    processingResult.IsSuccessful = false;
                    processingResult.Error = ErrorValues.USER_ROLE_UPDATE_FAILED_ERROR;
                    Logger.Error("Failed to update user role.", ex);
                }
            }

            return processingResult;
        }
示例#6
0
        public async Task<IHttpActionResult> GetCalvesTotal()
        {
            var result = new ServiceProcessingResult<List<Calf>>();

            var calfService = new CalfDataService();
            var calfResult = await calfService.getActiveCalves(LoggedInUser.ClientID);
            if (!calfResult.IsSuccessful)
            {
                result.Error = new ProcessingError("An error occurred while getting total calves.","Could not retrieve total calves, please try again. If the problem persists contact support.", true);
                result.IsSuccessful = false;
                return Ok(result);
            }


            result.IsSuccessful = true;
            result.Data = calfResult.Data;

            return Ok(result);
        }
示例#7
0
        public async Task<IHttpActionResult> GetActiveCows()
        {
            var cowService = new CowDataService();
            try {
                var processingResult = await cowService.getActiveCows(LoggedInUser.ClientID);
                if (!processingResult.IsSuccessful)
                {
                    processingResult.Error = new ProcessingError("An error occurred while getting all available Cows.", "Could not retrieve Cows, please try again. If the problem persists contact support.", true);
                    return Ok(processingResult);
                }
  
                processingResult.Data = processingResult.Data.OrderBy(c => c.TagNumber).ToList();
                return Ok(processingResult);
            } catch (Exception ex) {
                var processingResult =  new ServiceProcessingResult();
                ExceptionlessClient.Default.ProcessQueue();
                ex.ToExceptionless().Submit();

                return Ok(processingResult);
            }
        }
        public static ServiceProcessingResult<ValidationResult> ValidateRoleAssignmentFor(ApplicationRole roleBeingAssigned,
            ApplicationRole loggedInUserRole)
        {
            var processingResult = new ServiceProcessingResult<ValidationResult> { IsSuccessful = true };
            var validationResult = new ValidationResult
            {
                IsValid = true
            };

            if (roleBeingAssigned == null)
            {
                validationResult.IsValid = false;
                validationResult.Errors.Add("Invalid role. Please select a valid role and try again.");
            }
            else if (!loggedInUserRole.CanAssign(roleBeingAssigned))
            {
                validationResult.IsValid = false;
                validationResult.Errors.Add(CannotAssignRoleToUserUserHelp);
            }
            processingResult.Data = validationResult;

            return processingResult;
        }
示例#9
0
        public async Task<IHttpActionResult> EditCalf(CalvesUpdateBindingModel model)
        {
            var processingResult = new ServiceProcessingResult<Calf>() { IsSuccessful = true };

            if (!ModelState.IsValid)
            {
                var userHelp = GetModelStateErrorsAsString(ModelState);
                processingResult.IsSuccessful = false;
                processingResult.Error = new ProcessingError("Calf validation failed", "Calf validation failed", false, true);
                return Ok(processingResult);
            }

            var calfService = new CalfDataService();

            var updatedCalf = model.ToCalf(LoggedInUser.ClientID);
            processingResult = await calfService.UpdateCalf(updatedCalf);

            if (!processingResult.IsSuccessful)
            {
                var logMessage = String.Format("A error occurred while editing calf with Id: {0}.");
                Logger.Fatal(logMessage);
                return Ok(processingResult);
            }

            return Ok(processingResult);
        }
示例#10
0
        public async Task<IHttpActionResult> GetLoggedInUser()
        {
            var processingResult = new ServiceProcessingResult<LoggedInUserViewBindingModel>{ IsSuccessful = true };

            var loggedInUserId = LoggedInUserId;

            var appUserService = new ApplicationUserDataService();
            var loggedInUser = await appUserService.GetAsync(loggedInUserId);
            if (!loggedInUser.IsSuccessful)
            {
                processingResult.IsSuccessful = false;
                processingResult.Error = ErrorValues.GET_LOGGED_IN_USER_INFO_ERROR;
                return Ok(processingResult);
            }

            var user = loggedInUser.Data;
            processingResult.Data = user.ToLoggedInUserViewBindingModel();

            return Ok(processingResult);
        }
示例#11
0
        private async Task<ServiceProcessingResult<ValidationResult>> ValidateModelForLoggedInUserEdit(EditLoggedInUserBindingModel model)
        {
            var processingResult = new ServiceProcessingResult<ValidationResult> { IsSuccessful = true };
            var validationResult = new ValidationResult
            {
                IsValid = true
            };

            if (!ModelState.IsValid)
            {
                validationResult.IsValid = false;
                validationResult.Errors =
                    ModelState.Values.SelectMany(m => m.Errors).Select(e => e.ErrorMessage).ToList();
            }
            else if (model.UserName != LoggedInUserUserName &&
                     await AuthAndUserManager.UserNameAlreadyExists(model.UserName))
            {
                validationResult.IsValid = false;
                validationResult.Errors.Add(UserNameAlreadyExistsUserHelp);
            }
            processingResult.Data = validationResult;

            return processingResult;
        }
示例#12
0
        public async Task<IHttpActionResult> ResetUsersPassword(string userId)
        {
            var processingResult = new ServiceProcessingResult();

            var appUserService = new ApplicationUserDataService();

            var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();

            var baseUrl = Request.RequestUri.Authority;
            var code = await userManager.GeneratePasswordResetTokenAsync(userId);
            var helper = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
            var callbackPath = helper.Action("ResetPassword", "Authentication", new { userId = userId, code = code });
            var callbackUrl = baseUrl + callbackPath;

            try
            {
                await
                    userManager.SendEmailAsync(userId, "Reset Password",
                        "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");

                processingResult.IsSuccessful = true;
            }
            catch (Exception ex)
            {
                processingResult.IsSuccessful = false;
                processingResult.Error = new ProcessingError("Email failed to send.", ex.Message, false);
            }

            return Ok(processingResult);
        }
示例#13
0
        public async Task<IHttpActionResult> SetCompanyId(string userid, string newclientId)
        {
            var processingResult = new ServiceProcessingResult();
            if (LoggedInUser.Role.IsSuperAdmin()) //make sure user is SA
            {
                //Set the new companyid in the database.
                var dataService = new ApplicationUserDataService();
                processingResult = await dataService.UpdateClientId(newclientId, userid);
                if (processingResult.IsFatalFailure())
                {
                    Logger.Fatal("A fatal error occurred while setting CompanyId");
                    processingResult.IsSuccessful = false;
                }
                else
                {
                    var getLoggedInUserResult = await dataService.GetAsync(LoggedInUserId);
                    if (!getLoggedInUserResult.IsSuccessful)
                    {
                        processingResult.IsSuccessful = false;
                        processingResult.Error = ErrorValues.GENERIC_COULD_NOT_FIND_USER_ERROR;
                        return Ok(processingResult);
                    }
                    var user = getLoggedInUserResult.Data;
                    LoggedInUser.ClientID = newclientId;
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    //Sign Off and back in to refresh cookie.
                    try
                    {
                        await AuthAndUserManager.RefreshAuthenticationCookie(user);
                        processingResult.IsSuccessful = true;
                    }
                    catch (Exception e)
                    {
                        Logger.Fatal("A fatal error occurred while setting CompanyId");
                        processingResult.IsSuccessful = false;
                    }
                }

            }
            return Ok(processingResult);
        }
示例#14
0
        public async Task<IHttpActionResult> CreateCow(CowsCreationBindingModel model)
        {
            var processingResult = new ServiceProcessingResult<Cow>() { IsSuccessful = true };

            if (!ModelState.IsValid)
            {
                var userHelp = GetModelStateErrorsAsString(ModelState);
                processingResult.IsSuccessful = false;
                processingResult.Error = new ProcessingError("Cow validation failed", "Cow validation failed", false, true);
                return Ok(processingResult);
            }

            var cowService = new CowDataService();

            var cowData = model.ToCow(LoggedInUser.ClientID);
            processingResult = await cowService.AddAsync(cowData);

            if (!processingResult.IsSuccessful)
            {
                var logMessage = String.Format("A error occurred while saving cow.");
                Logger.Fatal(logMessage);
                return Ok(processingResult);
            }

            return Ok(processingResult);
        }