Пример #1
0
        internal static async Task <IResponse <TOutput> > ExecuteFuncOutputAsync <TOutput>(
            Func <TOutput> func)
        {
            try
            {
                if (func == null)
                {
                    return(ResponseFactory <TOutput> .Error("The provided func is null", ErrorResponseStatus.BadRequest));
                }

                var result = await Task.Run(func);

                var taskDetail = result as Task;
                if (taskDetail != null && taskDetail.Status == TaskStatus.Canceled)
                {
                    throw new OperationCanceledException();
                }

                return(ResponseFactory <TOutput> .Ok(result));
            }
            catch (Exception ex)
            {
                return(ResponseFactory <TOutput> .Exception(ex));
            }
        }
        private IResponse ValidateReadonlyModels()
        {
            //Select all the modified entries
            var modifiedOrAddedEntities = Context.ChangeTracker.Entries()
                                          .Where(x => x.State != EntityState.Unchanged)
                                          .Select(x => x.Entity).ToList();

            //Custom Code: EFCore does not perform validation so let's do it manually
            foreach (var entity in modifiedOrAddedEntities)
            {
                var validationContext = new ValidationContext(entity);
                Validator.ValidateObject(entity, validationContext);
            }

            var readonlyErrors = modifiedOrAddedEntities.Where(x => x is IReadOnlyEntity)
                                 .Select(modifiedOrAddedEntity => modifiedOrAddedEntity.GetType().Name).ToList();

            if (!readonlyErrors.Any())
            {
                return(ResponseFactory.Ok());
            }

            //Get modification errors
            var errorsGrouped = from x in readonlyErrors
                                group x by x into g
                                let count = g.Count()
                                            select new { Value = g.Key, Count = count };

            readonlyErrors = errorsGrouped.Select(x => x.Count > 1
                    ? $"'{x.Count}' Readonly entities of type '{x.Value}' are modified."
                    : $"A Readonly entity of type '{x.Value}' is modified.")
                             .ToList();

            return(ResponseFactory.Error(readonlyErrors));
        }
Пример #3
0
        public JsonResult Login(LoginModel model)
        {
            var response = ResponseFactory.Success(ResponseCode.SuccessLoggedIn);

            if (model == null)
            {
                return(Json(ResponseFactory.Error(ResponseCode.ErrorInvalidInput), JsonRequestBehavior.AllowGet));
            }

            var user = UserCore.GetSingle(userTemp => userTemp.Email == model.Email);

            if (user == null)
            {
                return(Json(ResponseFactory.Error(ResponseCode.ErrorEmailInvalid), JsonRequestBehavior.AllowGet));
            }

            var check = Md5Helper.VerifyPassword(model.Password, user.Password);

            if (check == false)
            {
                return(Json(ResponseFactory.Error(ResponseCode.ErrorInvalidPassword), JsonRequestBehavior.AllowGet));
            }

            if (user.IsAdmin == true)
            {
                Session["isAdmin"] = true;
            }
            Session["userId"]   = user.Id;
            Session["userName"] = user.FirstName;
            return(Json(response));
        }
Пример #4
0
        /// <summary>
        /// Executes a <see cref="Func{Task}"/> which returns a <see cref="Task{TOutput}"/>
        /// </summary>
        /// <param name="processor"><see cref="Processor"/></param>
        /// <param name="func">The function to execute</param>
        /// <returns><see cref="IResponse"/></returns>
        public static IResponse <TOutput> Process <TOutput>(this Processor processor, Func <Task <TOutput> > func)
        {
            if (processor == null)
            {
                var processNullMessage = $"The provided {nameof(processor)} is null.";
                SweetAlerts.Alert(string.Empty, processNullMessage, AlertButtons.Ok, AlertType.Error);
                return(ResponseFactory <TOutput> .Error(processNullMessage, ErrorResponseStatus.BadRequest));
            }

            try
            {
                using (var form = new FuncOutputExecutorTask <TOutput>
                {
                    ParentControl = processor.ParentControl,
                    FormTitle = processor.OperationTitle,
                    CanRetry = processor.CanRetry,
                    ShowSuccessMessage = processor.ReportSuccess,
                    IgnoreResponseMessage = processor.IgnoreResponseMessage,
                    SuccessMessage = processor.SuccessMessage,
                    Func = func,
                    CancellationTokenSource = processor.CancellationTokenSource,
                    FormImage = Properties.Resources.rolling,
                    ProgressObject = processor.ProgressObject
                })
                {
                    form.ShowDialog();
                    return(form.Response as IResponse <TOutput>);
                }
            }
            catch (Exception ex)
            {
                return(ResponseFactory <TOutput> .Exception(ex));
            }
        }
Пример #5
0
        private IResponse ValidateReadonlyModels()
        {
            //Select all the modified entiries
            var modifiedOrAddedEntities = Context.ChangeTracker.Entries()
                                          .Where(x => x.State != EntityState.Unchanged)
                                          .Select(x => x.Entity).ToList();

            var readonlyErrors = modifiedOrAddedEntities.Where(x => x is IReadOnlyEntity)
                                 .Select(modifiedOrAddedEntity => modifiedOrAddedEntity.GetType().Name).ToList();

            if (!readonlyErrors.Any())
            {
                return(ResponseFactory.Ok());
            }

            //Get modification errors
            var errorsGrouped = from x in readonlyErrors
                                group x by x into g
                                let count = g.Count()
                                            select new { Value = g.Key, Count = count };

            readonlyErrors = errorsGrouped.Select(x => x.Count > 1
                    ? $"'{x.Count}' Readonly entities of type '{x.Value}' are modified."
                    : $"A Readonly entity of type '{x.Value}' is modified.")
                             .ToList();

            return(ResponseFactory.Error(readonlyErrors));
        }
        public void Response_Error_CannotSetsEmptyList_IEnumrable()
        {
            var errorResponse = ResponseFactory <IEnumerable <int> > .Error();

            Assert.IsFalse(errorResponse.Success);
            Assert.IsNull(errorResponse.Value, "Value is not null");
        }
Пример #7
0
        public static async Task <Response <AspNetUser> > CreateAspNetUserAsync(RepoUnitOfWork repoUnitOfWork, CreateUserModel model)
        {
            var response = ResponseFactory.Error <AspNetUser>();

            if (repoUnitOfWork == null)
            {
                repoUnitOfWork = RepoUnitOfWork.New();
            }
            var aspNetUserRepository = repoUnitOfWork.TrackingRepository <AspNetUserRepository>();

            if (!await IsEmailNotUsedAsync(model.Email).ConfigureAwait(false))
            {
                return(response);
            }
            var aspNetUser = new AspNetUser
            {
                Id            = Guid.NewGuid().ToString(),
                UserName      = model.Email,
                PasswordHash  = model.PasswordHash,
                SecurityStamp = Guid.NewGuid().ToString("D"),
            };

            var createdAspNetUser = await aspNetUserRepository.CreateAsync(aspNetUser, navigationProperties : new[]
            {
                nameof(AspNetRole)
            }).ConfigureAwait(false);

            if (createdAspNetUser == null)
            {
                return(response);
            }
            return(ResponseFactory.Success(createdAspNetUser));
        }
Пример #8
0
        public static async Task <Response> Register(RegisterViewModel registerModel, string passwordHash)
        {
            using (var repoUnitOfWork = RepoUnitOfWork.New())
            {
                var aspNetUser = new AspNetUser
                {
                    Id           = registerModel.Id.ToString(),
                    Email        = registerModel.Email,
                    UserName     = registerModel.Email,
                    UserType     = (int)registerModel.userType,
                    Status       = (int)UserStatus.ACTIVE,
                    PhoneNumber  = registerModel.PhoneNumber,
                    CreatedAt    = DateTime.UtcNow,
                    PasswordHash = passwordHash,
                };

                var aspNetUserRepo = repoUnitOfWork.TrackingRepository <AspNetUserRepository>();

                var createdUser = await aspNetUserRepo.CreateAsync(aspNetUser).ConfigureAwait(false);

                if (createdUser != null)
                {
                    repoUnitOfWork.CommitTransaction();
                    return(ResponseFactory.Success <AspNetUser>());
                }
                repoUnitOfWork.RollbackTransaction();
                return(ResponseFactory.Error <AspNetUser>());
            }
        }
Пример #9
0
        public BaseResponse SendPassword(string email)
        {
            try
            {
                if (!string.IsNullOrEmpty(email))
                {
                    var userEntity = TCSOfficeDbContext.Logins.FirstOrDefault(z => z.Email == email);
                    if (userEntity != null)
                    {
                        // Send email
                        string subject = "Reset Password for TCS Office";
                        var    body    = new StringBuilder();
                        body.AppendFormat("Hello " + userEntity.UserName);
                        body.AppendLine("Your password - ");
                        body.AppendLine(userEntity.Password);

                        string emailResult = Mail.SendMail(email, body.ToString(), subject, fromEmail, fromPassword);
                        if (emailResult == "OK")
                        {
                            return(ResponseFactory.Success(null, "Password has been sent to your registered email id."));
                        }
                    }
                    else
                    {
                        return(ResponseFactory.Error("Please enter valid email id."));
                    }
                }
                return(ResponseFactory.Error("Something went wrong."));
            }
            catch (Exception ex)
            {
                return(ResponseFactory.Error(ex.Message));
            }
        }
Пример #10
0
        /// <summary>
        /// Executes a function
        /// </summary>
        /// <param name="processor">The <see cref="Processor"/></param>
        /// <param name="func">The function to execute</param>
        /// <returns><see cref="IResponse"/></returns>
        public static IResponse Process(this Processor processor, Func <IResponse> func)
        {
            if (processor == null)
            {
                var processNullMessage = $"The provided {nameof(processor)} is null.";
                SweetAlerts.Alert(HelperMethods.GetCurrentlyActiveForm(), string.Empty, processNullMessage, AlertButtons.Ok, AlertType.Error);
                return(ResponseFactory.Error(processNullMessage, ErrorResponseStatus.BadRequest));
            }

            try
            {
                using (var form = new FuncOutputResponseExecutor
                {
                    ParentControl = HelperMethods.GetCurrentlyActiveForm(processor.ParentControl),
                    FormTitle = processor.OperationTitle,
                    CanRetry = processor.CanRetry,
                    ShowSuccessMessage = processor.ReportSuccess,
                    IgnoreResponseMessage = processor.IgnoreResponseMessage,
                    SuccessMessage = processor.SuccessMessage,
                    Func = func,
                    CancellationTokenSource = processor.CancellationTokenSource,
                    FormImage = Properties.Resources.rolling,
                    ProgressObject = processor.ProgressObject
                })
                {
                    form.ShowDialog(HelperMethods.GetCurrentlyActiveForm(processor.ParentControl));
                    return(form.Response);
                }
            }
            catch (Exception ex)
            {
                return(ResponseFactory.Exception(ex));
            }
        }
        public void Response_Error()
        {
            var errorResponse = ResponseFactory.Error();

            Assert.IsNotNull(errorResponse, "Response is null");
            Assert.IsFalse(errorResponse.Success, "Success is not false.");
            Assert.AreEqual(ResponseStatus.InternalServerError, errorResponse.Status);
        }
        public void Response_Error_SetsEmptyList()
        {
            var errorResponse = ResponseFactory <List <int> > .Error();

            Assert.IsFalse(errorResponse.Success);
            Assert.IsNotNull(errorResponse.Value, "Value is null");
            Assert.AreEqual(0, errorResponse.Value.Count, "List count is not same");
        }
        public void Response_Error_ExpectedOutput_Should_Be_NULL()
        {
            var errorResponse = ResponseFactory <int?> .Error(nameof(Response_Error));

            Assert.IsNotNull(errorResponse, "Response is null");
            Assert.IsFalse(errorResponse.Success, "Success is not false.");
            Assert.AreEqual(ResponseStatus.InternalServerError, errorResponse.Status, "Status is not valid");
            Assert.AreEqual(null, errorResponse.Value, "Values are not equal");
            Assert.IsNotNull(errorResponse.Messages, "Message list is null");
            Assert.AreEqual(1, errorResponse.Messages.Count(), "Message count is not as expected");
            Assert.AreEqual(nameof(Response_Error), errorResponse.Messages.ToList()[0], "Invalid message");
        }
Пример #14
0
        internal static async Task <IResponse> PrepareResponseAsync(this HttpResponseMessage response)
        {
            try
            {
                if (response == null)
                {
                    return(ResponseFactory.Error(
                               $"Specified {nameof(HttpResponseMessage)} is null, could not create {nameof(IResponse)}.",
                               ErrorResponseStatus.BadRequest));
                }

                var status       = response.StatusCode;
                var reasonPhrase = response.ReasonPhrase;
                var contentType  = response.Content.Headers.ContentType;

                if (contentType != null && response.IsInResponsibleFormat())
                {
                    var multiContent = await response.Content.ReadAsMultipartAsync();

                    var multiMessages = await multiContent.Contents[0].ReadAsAsync <List <ServiceMessage> >();

                    return(ResponseFactory.Custom((ResponseStatus)status,
                                                  multiMessages.Select(m => m.Message).ToList()));
                }

                var responseContent = await TryToCastResponseToAString(response);

                if (!string.IsNullOrWhiteSpace(responseContent))
                {
                    return(ResponseFactory.Custom((ResponseStatus)status, new List <string>
                    {
                        $"Status: {status} - ReasonPhrase: {reasonPhrase}",
                        $"{responseContent}"
                    }));
                }

                return(ResponseFactory.Custom((ResponseStatus)status,
                                              $"Status: {status} - ReasonPhrase: {reasonPhrase}"));
            }
            catch (Exception ex)
            {
                if (ex is OperationCanceledException)
                {
                    return(ResponseFactory.Exception(ex));
                }

                return(ResponseFactory.Exception(ex,
                                                 new List <string> {
                    StaticResources.ExecutionFailureMessage, ex.Message
                }));
            }
        }
Пример #15
0
        public static IResponse <int> Add(Customer customer)
        {
            try
            {
                if (customer == null)
                {
                    return(ResponseFactory <int> .Error("Invalid customer data.", ErrorResponseStatus.BadRequest));
                }

                var customerId = new CustomersData().Add(customer);
                return(ResponseFactory <int> .Ok(customerId, "Customer has been added."));
            }
            catch (Exception ex)
            {
                return(ResponseFactory <int> .Exception(ex));
            }
        }
Пример #16
0
        public static IResponse <Customer> Get(int id)
        {
            try
            {
                var result = new CustomersData().Get(id);
                if (result == null)
                {
                    return(ResponseFactory <Customer> .Error($"Could not find a record with Id: {id}", ErrorResponseStatus.NotFound));
                }

                return(ResponseFactory <Customer> .Ok(result));
            }
            catch (Exception ex)
            {
                return(ResponseFactory <Customer> .Exception(ex));
            }
        }
Пример #17
0
        public BaseResponse RegisterCompany(LoginViewModel login)
        {
            try
            {
                var companyEntity = login.ToEntity();
                TCSOfficeDbContext.Companies.Add(companyEntity);
                TCSOfficeDbContext.SaveChanges();
                if (companyEntity != null)
                {
                    var userEntity = new Login
                    {
                        UserName = login.UserName,
                        Password = login.Password,
                        Email    = login.Email,
                        IsActive = false,
                        IsAdmin  = false,
                        Company  = companyEntity
                    };
                    TCSOfficeDbContext.Logins.Add(userEntity);
                    TCSOfficeDbContext.SaveChanges();

                    // Send email to admin
                    var getAdminEntity = TCSOfficeDbContext.Logins.FirstOrDefault(z => z.IsAdmin == true);
                    if (getAdminEntity != null)
                    {
                        string subject = "Activate Company for " + login.UserName;
                        var    body    = new StringBuilder();
                        body.AppendFormat("Hello Admin,\n");
                        body.AppendLine("Please click on below link to activate the company.");
                        body.AppendLine("<a href=" + basePath + "Account/ActivateCompanyFromEmail?userId=" + userEntity.Id + "&companyId=" + companyEntity.Id + ">Activate</a>");

                        string emailResult = Mail.SendMail(getAdminEntity.Email, body.ToString(), subject, fromEmail, fromPassword);
                        if (emailResult == "OK")
                        {
                            return(ResponseFactory.Success(null, "Congratulations! Your account has successfully created. Please ask your administrator to activate your account or wait for next 24 working hours."));
                        }
                    }
                }
                return(ResponseFactory.Error("Something went wrong."));
            }
            catch (Exception ex)
            {
                return(ResponseFactory.Error(ex.Message));
            }
        }
Пример #18
0
        public static Response Create(UserViewModel model)
        {
            var response = ResponseFactory.Success(ResponseCode.SuccessEntityCreated);

            if (model == null)
            {
                return(ResponseFactory.Error(ResponseCode.ErrorInvalidInput));
            }

            var user        = model.CopyTo();
            var createdUser = Create(user);

            if (createdUser == null)
            {
                response = ResponseFactory.Error(ResponseCode.ErrorCreatingEntity);
            }
            return(response);
        }
Пример #19
0
        //public virtual async Task<ActionResult> Register(RegisterViewModel model)
        //{
        //    if (!ModelState.IsValid)
        //    {
        //        RedirectToAction("Login/Index");
        //    }

        //    var createdUserResponse = await UserCore.RegisterUser(model).ConfigureAwait(false);
        //    if (!ResponseFactory.IsSuccessful(createdUserResponse))
        //    {
        //        RedirectToAction("Login/Index");
        //    }

        //    RedirectToAction("Login/Index");
        //}

        public static Response CheckEmailCollision(string email)
        {
            var response = ResponseFactory.Error <AspNetUser>();

            if (string.IsNullOrWhiteSpace(email))
            {
                return(response);
            }

            var existingAspNetUser = AspNetUserCore.GetByEmail(email);

            if (existingAspNetUser != null)
            {
                return(ResponseFactory.ErrorReponse);
            }

            return(ResponseFactory.Success());
        }
Пример #20
0
        internal static async Task <IResponse> ExecuteActionAsync(Action action)
        {
            try
            {
                if (action == null)
                {
                    return(ResponseFactory.Error("The provided action is null", ErrorResponseStatus.BadRequest));
                }

                await Task.Run(() => action.Invoke());

                return(ResponseFactory.Ok());
            }
            catch (Exception ex)
            {
                return(ResponseFactory.Exception(ex));
            }
        }
Пример #21
0
        internal static async Task <IResponse <TOutput> > ExecuteFuncOutputResponseAsync <TOutput>(
            Func <IResponse <TOutput> > func)
        {
            try
            {
                if (func == null)
                {
                    return(ResponseFactory <TOutput> .Error("The provided func is null", ErrorResponseStatus.BadRequest));
                }

                var result = await Task.Run(func);

                return(result);
            }
            catch (Exception ex)
            {
                return(ResponseFactory <TOutput> .Exception(ex));
            }
        }
Пример #22
0
 public BaseResponse ActivateCompany(string companyId, string userId)
 {
     try
     {
         int parseCompanyId = Int32.Parse(companyId);
         var companyEntity  = TCSOfficeDbContext.Companies.FirstOrDefault(z => z.Id == parseCompanyId);
         if (companyEntity != null)
         {
             companyEntity.IsActive         = true;
             companyEntity.DateLastModified = DateTime.UtcNow;
             TCSOfficeDbContext.SaveChanges();
             return(ResponseFactory.Success(null, "Activated successfully."));
         }
         return(ResponseFactory.Error("Company doesn't exist."));
     }
     catch (Exception ex)
     {
         return(ResponseFactory.Error(ex.Message));
     }
 }
Пример #23
0
        public static Response Create(BookViewModel model)
        {
            var response = ResponseFactory.Success(ResponseCode.SuccessEntityCreated);

            if (model == null)
            {
                return(ResponseFactory.Error(ResponseCode.ErrorInvalidInput));
            }

            var book = model.CopyTo();

            book.Status = EntityStatus.Active;
            var createdBook = Create(book);

            if (createdBook == null)
            {
                response = ResponseFactory.Error(ResponseCode.ErrorCreatingEntity);
            }
            return(response);
        }
Пример #24
0
        public static Response Create(CommentViewModel model)
        {
            var response = ResponseFactory.Success(ResponseCode.SuccessEntityCreated);

            if (model == null)
            {
                return(ResponseFactory.Error(ResponseCode.ErrorInvalidInput));
            }

            var comment = model.CopyTo();

            comment.Status = EntityStatus.Active;
            var createdComment = Create(comment);

            if (createdComment == null)
            {
                response = ResponseFactory.Error(ResponseCode.ErrorCreatingEntity);
            }
            return(response);
        }
        public async Task <TResponse> Handle(TRequest command, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var validationResult = _validationService.ValidateCommand(command);

            if (validationResult.IsFailed)
            {
                return(validationResult as TResponse);
            }

            var handlerResult = await next();

            var result = _validationService.EvaluateResults(command.IgnoreWarnings, validationResult, handlerResult);

            if (result.IsFailed)
            {
                var requestName = typeof(TRequest).Name;
                var error       = ResponseFactory.Error(result);
                _logger.LogDebug("Request validation failure: {Name} {ErrorMessage}", requestName, error);
            }

            return(result as TResponse);
        }
Пример #26
0
        internal static async Task <IResponse <T> > PrepareResponseAsync <T>(this HttpResponseMessage response)
        {
            try
            {
                if (response == null)
                {
                    return(ResponseFactory <T> .Error(
                               $"Specified {nameof(HttpResponseMessage)} is null, could not create {nameof(IResponse<T>)}.",
                               ErrorResponseStatus.BadRequest));
                }

                var status       = response.StatusCode;
                var reasonPhrase = response.ReasonPhrase;
                var contentType  = response.Content.Headers.ContentType;

                if (contentType != null && response.IsInResponsibleFormat())
                {
                    var resultObjectFromMultiPart = await response.Content.ReadAsMultipartAsync();

                    var messagesFromMultiPart =
                        await resultObjectFromMultiPart.Contents[0].ReadAsAsync <List <ServiceMessage> >();

                    var value = default(T);
                    if (resultObjectFromMultiPart.Contents.Count > 1)
                    {
                        value = await resultObjectFromMultiPart.Contents[1].ReadAsAsync <T>();
                    }

                    return(ResponseFactory <T> .Custom((ResponseStatus)status,
                                                       messagesFromMultiPart.Select(m => m.Message).ToList(), value));
                }

                if (response.IsSuccessStatusCode)
                {
                    var resultObject = await response.Content.ReadAsAsync <T>();

                    return(ResponseFactory <T> .Custom((ResponseStatus)status, resultObject));
                }

                var responseContent = await TryToCastResponseToAString(response);

                if (!string.IsNullOrWhiteSpace(responseContent))
                {
                    return(ResponseFactory <T> .Custom((ResponseStatus)status, new List <string>
                    {
                        $"Status: {status} - ReasonPhrase: {reasonPhrase}",
                        $"{responseContent}"
                    }));
                }

                return(ResponseFactory <T> .Custom((ResponseStatus)status,
                                                   $"Status: {status} - ReasonPhrase: {reasonPhrase}"));
            }
            catch (Exception ex)
            {
                return(ResponseFactory <T> .Exception(ex,
                                                      new List <string> {
                    StaticResources.ExecutionFailureMessage, ex.Message
                }));
            }
        }
Пример #27
0
 protected virtual async Task <IResponse> ExecuteRequestAsync()
 {
     return(await Task.FromResult(
                ResponseFactory.Error($"{nameof(ExecuteRequestAsync)} is not implemented for the request.")));
 }