Beispiel #1
0
 public ActionResult AddBlogViewer(Viewer request)
 {
     try
     {
         using (ESamhashoEntities entities = new ESamhashoEntities())
         {
             DateTime   dateTime = DateTime.Now.AddDays(-1);
             BlogViewer viewer   = entities.BlogViewers.FirstOrDefault(
                 a => a.BlogId == request.DataId && a.IpAddress.Equals(request.IpAddress) && a.DateCreated >= dateTime && a.DateCreated <= DateTime.Now);
             if (viewer != null)
             {
                 return(new ActionResult
                 {
                     Success = true,
                     Message = ""
                 });
             }
             BlogViewer blogViewer = new BlogViewer
             {
                 DateCreated = DateTime.Now,
                 BlogId      = (int)request.DataId,
                 Country     = request.Country,
                 IpAddress   = request.IpAddress,
                 Town        = request.Town
             };
             entities.BlogViewers.Add(blogViewer);
             entities.SaveChanges();
             return(new ActionResult
             {
                 Success = true,
                 Message = ""
             });
         }
     }
     catch (Exception exception)
     {
         Dictionary <string, string> dictionary = request.ToDictionary();
         ServiceHelper.LogException(exception, dictionary, ErrorSource.Blog);
         return(new ActionResult {
             Message = "Error, blog failed to confirm viewed, error."
         });
     }
 }
Beispiel #2
0
        public ActionResult SendPasswordResetEmail(string emailAddress, string passwordResetToken)
        {
            // var requestUrl = new Uri(HttpContext.Current.Request.Url, $"/#/passwordreset/{passwordResetToken}");
            // EmailPasswordReset msg = new EmailPasswordReset
            // {
            // verificationUrl = requestUrl.ToString()
            // };
            string json;// = new JavaScriptSerializer().Serialize(msg);

            using (ESamhashoEntities entities = new ESamhashoEntities())
            {
            }

            return(new ActionResult
            {
                Success = true,
                Message = "Email sent, please check your inbox to confirm"
            });
        }
Beispiel #3
0
 public List <ViewerResponse> GetBlogViews()
 {
     try
     {
         using (ESamhashoEntities entities = new ESamhashoEntities())
         {
             List <BlogViewer> blogViews = entities.BlogViewers.ToList();
             return((from blogViewer in blogViews let blog = entities.Blogs.FirstOrDefault(a => a.Id == blogViewer.BlogId) where blog != null select new ViewerResponse {
                 ViewId = blogViewer.Id, Country = blogViewer.Country, Name = blog.Name, IpAddress = blogViewer.IpAddress, Town = blogViewer.Town, DateCreated = blogViewer.DateCreated
             }).ToList());
         }
     }
     catch (Exception exception)
     {
         ServiceHelper.LogException(exception, new Dictionary <string, string>(), ErrorSource.Blog);
         return(new List <ViewerResponse> {
             new ViewerResponse()
         });
     }
 }
Beispiel #4
0
 public List <ViewerResponse> GetProductViews()
 {
     try
     {
         using (ESamhashoEntities entities = new ESamhashoEntities())
         {
             List <ProductViewer> productViews = entities.ProductViewers.ToList();
             return((from productViewer in productViews let product = entities.Products.FirstOrDefault(a => a.Id == productViewer.ProductId) where product != null select new ViewerResponse {
                 ViewId = productViewer.Id, Country = productViewer.Country, Name = product.Name, IpAddress = productViewer.IpAddress, Town = productViewer.Town, DateCreated = productViewer.DateCreated
             }).ToList());
         }
     }
     catch (Exception exception)
     {
         ServiceHelper.LogException(exception, new Dictionary <string, string>(), ErrorSource.Product);
         return(new List <ViewerResponse> {
             new ViewerResponse()
         });
     }
 }
 public List <CatergoryResponse> GetAllCatergories()
 {
     try
     {
         using (ESamhashoEntities entities = new ESamhashoEntities())
         {
             List <CatergoryResponse> responses = entities.Catergories.Where(a => !a.IsDeleted).OrderBy(a => a.Name).Select(a => new CatergoryResponse
             {
                 Name = a.Name,
                 Id   = a.Id
             }).ToList();
             return(responses);
         }
     }
     catch (Exception exception)
     {
         ServiceHelper.LogException(exception, new Dictionary <string, string>(), ErrorSource.Catergory);
         return(new List <CatergoryResponse>());
     }
 }
Beispiel #6
0
        public ActionResult DeleteBlog(string blogId)
        {
            try
            {
                if (!int.TryParse(blogId, out int id))
                {
                    return new ActionResult {
                               Message = "Blog is invalid"
                    }
                }
                ;
                using (ESamhashoEntities entities = new ESamhashoEntities())
                {
                    Blog blog = entities.Blogs.FirstOrDefault(a => a.Id == id);

                    if (blog == null)
                    {
                        return new ActionResult {
                                   Message = "Blog does not exist"
                        }
                    }
                    ;
                    blog.IsDeleted = true;
                    entities.SaveChanges();
                    return(new ActionResult {
                        Success = true, Message = "Blog deleted successfully"
                    });
                }
            }
            catch (Exception exception)
            {
                Dictionary <string, string> dictionary = new Dictionary <string, string>
                {
                    { "blogId", blogId }
                };
                ServiceHelper.LogException(exception, dictionary, ErrorSource.Blog);
                return(new ActionResult {
                    Message = "Error, blog failed to delete, try again."
                });
            }
        }
 public List <NotificationData> GetNotificationsByProduct(string productId)
 {
     try
     {
         using (ESamhashoEntities entities = new ESamhashoEntities())
         {
             if (!long.TryParse(productId, out long id))
             {
                 return(new List <NotificationData>());
             }
             List <Notification> notifications = entities.Notifications
                                                 .Where(a => !a.IsDeleted && a.ProductId == id).OrderByDescending(a => a.DateCreated).ToList();
             List <NotificationData> notificationDatas = notifications
                                                         .Select(
                 a => new NotificationData
             {
                 Message     = a.Message,
                 IsDeleted   = a.IsDeleted,
                 Name        = a.Name,
                 ProductId   = a.ProductId,
                 IsRead      = a.IsRead,
                 Phone       = a.Phone,
                 DateCreated =
                     a.DateCreated.ToLongDateString() + " " + a.DateCreated
                     .ToLongTimeString(),
                 Email = a.Email,
                 Id    = a.Id
             }).ToList();
             return(notificationDatas);
         }
     }
     catch (Exception exception)
     {
         Dictionary <string, string> dictionary = new Dictionary <string, string>
         {
             { "productId", productId }
         };
         ServiceHelper.LogException(exception, dictionary, ErrorSource.Notification);
         return(new List <NotificationData>());
     }
 }
Beispiel #8
0
        public ProductMediaResponse AddProductMedia(Stream media)
        {
            MultipartFormDataParser dataParser = new MultipartFormDataParser(media);
            string productId = dataParser.GetParameterValue("productId");

            try
            {
                using (ESamhashoEntities entities = new ESamhashoEntities())
                {
                    string path = ServiceHelper.SaveImage(dataParser.Files[0].Data, dataParser.Files[0].FileName);
                    if (long.TryParse(productId, out long id))
                    {
                        ProductMedia productMedia = new ProductMedia
                        {
                            MediaSource = path,
                            ProductId   = id,
                            DateCreate  = DateTime.Now,
                            IsDeleted   = false,
                            IsMain      = false
                        };

                        entities.ProductMedias.Add(productMedia);
                        entities.SaveChanges();
                        return(new ProductMediaResponse {
                            MediaSource = path, Id = productMedia.Id
                        });
                    }
                    return(new ProductMediaResponse());
                }
            }
            catch (Exception exception)
            {
                Dictionary <string, string> dictionary = new Dictionary <string, string>
                {
                    { "productId", productId }
                };
                ServiceHelper.LogException(exception, dictionary, ErrorSource.Product);
                return(new ProductMediaResponse());
            }
        }
Beispiel #9
0
        public UserProfileDetails GetUserDetails(Token token)
        {
            try
            {
                using (ESamhashoEntities entities = new ESamhashoEntities())
                {
                    UserProfile userDetails = entities.UserProfiles.FirstOrDefault();
                    if (userDetails != null)
                    {
                        ApplicationUserManager userManager = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();
                        ApplicationUser        aspUser     = userManager.FindById(userDetails.UserId);
                        UserProfileDetails     user        = new UserProfileDetails
                        {
                            DateCreated    = userDetails.DateCreated.ToLongDateString(),
                            Id             = userDetails.Id,
                            UserId         = userDetails.UserId,
                            City           = userDetails.City,
                            AboutMe        = userDetails.AboutMe,
                            Address        = userDetails.Address,
                            FirstName      = userDetails.FirstName,
                            LastName       = userDetails.LastName,
                            ProfilePicture = userDetails.ProfilePicture,
                            Country        = userDetails.Country,
                            UserName       = aspUser.UserName,
                            Email          = aspUser.Email,
                            PhoneNumber    = aspUser.PhoneNumber
                        };
                        return(user);
                    }

                    return(new UserProfileDetails());
                }
            }
            catch (Exception exception)
            {
                Dictionary <string, string> dictionary = token.ToDictionary();
                ServiceHelper.LogException(exception, dictionary, ErrorSource.User);
                return(new UserProfileDetails());
            }
        }
 public ActionResult ReadNotification(string notificationId)
 {
     try
     {
         using (ESamhashoEntities entities = new ESamhashoEntities())
         {
             if (!long.TryParse(notificationId, out long id))
             {
                 return(new ActionResult {
                     Message = "Notification is invalid"
                 });
             }
             Notification notification = entities.Notifications.FirstOrDefault(a => a.Id == id);
             if (notification == null)
             {
                 return new ActionResult {
                            Message = "Notification does not exist"
                 }
             }
             ;
             notification.IsRead = true;
             entities.SaveChanges();
             return(new ActionResult {
                 Success = true, Message = "Notification saved successfully"
             });
         }
     }
     catch (Exception exception)
     {
         Dictionary <string, string> dictionary = new Dictionary <string, string>
         {
             { "notificationId", notificationId }
         };
         ServiceHelper.LogException(exception, dictionary, ErrorSource.Notification);
         return(new ActionResult {
             Message = "Error, failed to mark notification as read"
         });
     }
 }
Beispiel #11
0
 public ActionResult DeleteCatergory(string productId)
 {
     try
     {
         using (ESamhashoEntities entities = new ESamhashoEntities())
         {
             if (!long.TryParse(productId, out long id))
             {
                 return(new ActionResult {
                     Message = "Catergory is invalid."
                 });
             }
             Catergory catergory = entities.Catergories.FirstOrDefault(a => a.Id == id);
             if (catergory == null)
             {
                 return new ActionResult {
                            Message = "Catergory does not exist."
                 }
             }
             ;
             catergory.IsDeleted = true;
             entities.SaveChanges();
             return(new ActionResult {
                 Success = true, Message = "Catergory saved successfully."
             });
         }
     }
     catch (Exception exception)
     {
         Dictionary <string, string> dictionary = new Dictionary <string, string>
         {
             { "productId", productId }
         };
         ServiceHelper.LogException(exception, dictionary, ErrorSource.Catergory);
         return(new ActionResult {
             Message = "Error, catergory failed to delete, try again."
         });
     }
 }
Beispiel #12
0
 public List <ProductResponse> SearchProduct(SearchProductRequest searchProductRequest)
 {
     try
     {
         using (ESamhashoEntities entities = new ESamhashoEntities())
         {
             List <ProductResponse> productResponses = entities.SearchProducts(searchProductRequest.Search, searchProductRequest.Catergory)
                                                       .Select(a => new ProductResponse
             {
                 IsDeleted        = a.IsDeleted,
                 CatergoryId      = a.CatergoryId,
                 Description      = a.Description,
                 Code             = a.Code,
                 ModifiedDate     = a.ModifiedDate.ToLongDateString(),
                 Name             = a.Name,
                 Manufacturer     = a.Manufacturer,
                 UserId           = a.UserId,
                 MediaSource      = a.MediaSource,
                 ProductId        = a.ProductId,
                 Price            = a.Price,
                 Per              = a.Per,
                 ShortDescription = a.ShortDescription,
                 CreatedDate      = a.CreatedDate.ToLongDateString(),
                 IsMain           = a.IsMain,
                 IsActive         = a.IsActive
             }).ToList();
             return(productResponses);
         }
     }
     catch (Exception exception)
     {
         Dictionary <string, string> dictionary = searchProductRequest.ToDictionary();
         ServiceHelper.LogException(exception, dictionary, ErrorSource.Product);
         return(new List <ProductResponse>());
     }
 }
        public ActionResult ForgotPassword(string username)
        {
            try
            {
                ActionResult actionResult = ServiceHelper.IsAnyNullOrEmpty(username);
                if (actionResult.Success)
                {
                    actionResult.Success = false;
                    return(actionResult);
                }

                ApplicationUserManager manager = new ApplicationUserManager(new UserStore <ApplicationUser>(new ApplicationDbContext()));
                ApplicationUser        user    = manager.FindByEmail(username);
                if (user == null)
                {
                    return(new ActionResult
                    {
                        Message = "User does not exist",
                        Success = false
                    });
                }

                if (!manager.IsEmailConfirmed(user.Id))
                {
                    return new ActionResult
                           {
                               Success = false,
                               Message = "You need to confirm your email."
                           }
                }
                ;
                ApplicationUserManager userManager = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();
                string resetToken  = userManager.GeneratePasswordResetToken(user.Id);
                string newPassword = PasswordService.GeneratePassword(PasswordOptions.HasCapitals |
                                                                      PasswordOptions.HasDigits |
                                                                      PasswordOptions.HasLower |
                                                                      PasswordOptions.HasSymbols |
                                                                      PasswordOptions.NoRepeating);

                IdentityResult result = userManager.ResetPassword(user.Id, resetToken, newPassword);
                if (result.Succeeded)
                {
                    using (ESamhashoEntities entities = new ESamhashoEntities())
                    {
                        EmailTemplate emailBody = entities.EmailTemplates.FirstOrDefault(a => a.EmailTemplateId == (byte)EmailTemplateId.ResetPassword);
                        if (emailBody != null)
                        {
                            string body = emailBody.Body.Replace("{password}", newPassword)
                                          .Replace("{accountname}", user.UserName);
                            string        subject       = "Esamhasho password reset";
                            OutgoingEmail outgoingEmail = new OutgoingEmail
                            {
                                Body        = body,
                                Date        = DateTime.Now,
                                Destination = user.Email,
                                Reference   = user.Id,
                                Status      = (byte)EmailStatus.Pending,
                                Subject     = subject
                            };
                            entities.OutgoingEmails.Add(outgoingEmail);
                            entities.SaveChanges();
                            manager.SendEmail(user.Id, subject, body);
                            OutgoingEmail email = entities.OutgoingEmails.FirstOrDefault(a => a.Id == outgoingEmail.Id);
                            if (email != null)
                            {
                                email.Status = (byte)EmailStatus.Success;
                            }
                            entities.SaveChanges();
                        }
                    }

                    return(new ActionResult
                    {
                        Message = "Password successfully reset. Check your email for your new password.",
                        Success = true
                    });
                }

                string error = result.Errors.Aggregate(string.Empty, (current, resultError) => current + resultError + Environment.NewLine);
                return(new ActionResult {
                    Message = error, Success = result.Succeeded
                });
            }
            catch (Exception exception)
            {
                Dictionary <string, string> dictionary = username.ToDictionary();
                ServiceHelper.LogException(exception, dictionary, ErrorSource.Authentication);
                return(new ActionResult
                {
                    Success = false,
                    Message = "Error, failed to reset password."
                });
            }
        }
        public ActionResult SignUp(SignUp signUp)
        {
            try
            {
                ActionResult actionResult = ServiceHelper.IsAnyNullOrEmpty(signUp);
                if (actionResult.Success)
                {
                    actionResult.Success = false;
                    return(actionResult);
                }

                ApplicationUserManager manager = HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>();
                string password = PasswordService.GeneratePassword(PasswordOptions.HasCapitals |
                                                                   PasswordOptions.HasDigits |
                                                                   PasswordOptions.HasLower |
                                                                   PasswordOptions.HasSymbols |
                                                                   PasswordOptions.NoRepeating);
                Guid userId = Guid.NewGuid();
                manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(10);
                manager.MaxFailedAccessAttemptsBeforeLockout = 3;
                manager.UserLockoutEnabledByDefault          = true;
                ApplicationUser applicationUser = new ApplicationUser
                {
                    UserName       = signUp.Username,
                    Email          = signUp.Email,
                    PhoneNumber    = signUp.PhoneNumber,
                    Id             = userId.ToString(),
                    LockoutEnabled = true
                };
                IdentityResult result = manager.Create(applicationUser, password);
                string         error  = result.Errors.Aggregate(string.Empty, (current, resultError) => current + resultError + Environment.NewLine);
                if (!result.Succeeded)
                {
                    return(new ActionResult
                    {
                        Success = false,
                        Message = error
                    });
                }

                string userRole = signUp.UserRole.ToString();
                result = manager.AddToRole(applicationUser.Id, userRole);
                using (ESamhashoEntities entities = new ESamhashoEntities())
                {
                    string       emailConfirmationToken = manager.GenerateEmailConfirmationToken(applicationUser.Id);
                    ActionResult guid = UserManagement.SaveVerificationDetails(applicationUser.Email, emailConfirmationToken);
                    if (!guid.Success)
                    {
                        return(new ActionResult
                        {
                            Success = false,
                            Message = "Failed to register new user."
                        });
                    }

                    Uri           requestUrl = new Uri(HttpContext.Current.Request.Url, "/Backoffice/Authentication.svc/json/VerifyEmail/" + guid.Message);
                    EmailTemplate emailBody  = entities.EmailTemplates.FirstOrDefault(a => a.EmailTemplateId == (byte)EmailTemplateId.SignUp);
                    if (emailBody != null)
                    {
                        string body = emailBody.Body.Replace("{activateaccount}", requestUrl.ToString())
                                      .Replace("{email}", applicationUser.Email)
                                      .Replace("{password}", password)
                                      .Replace("{accountname}", applicationUser.UserName);
                        string        subject       = "Esamhasho registration confirmation";
                        OutgoingEmail outgoingEmail = new OutgoingEmail
                        {
                            Body        = body,
                            Date        = DateTime.Now,
                            Destination = applicationUser.Email,
                            Reference   = applicationUser.Id,
                            Status      = (byte)EmailStatus.Pending,
                            Subject     = subject
                        };
                        entities.OutgoingEmails.Add(outgoingEmail);
                        entities.SaveChanges();
                        manager.SendEmail(applicationUser.Id, subject, body);
                        OutgoingEmail email = entities.OutgoingEmails.FirstOrDefault(a => a.Id == outgoingEmail.Id);
                        if (email != null)
                        {
                            email.Status = (byte)EmailStatus.Success;
                        }
                        entities.SaveChanges();
                    }
                }

                if (result.Succeeded)
                {
                    return(new ActionResult
                    {
                        Success = true,
                        Message = "Successfully register new user. The user should check there email to avtivate there account."
                    });
                }

                error = result.Errors.Aggregate(string.Empty, (current, resultError) => current + resultError + Environment.NewLine);
                return(new ActionResult
                {
                    Success = false,
                    Message = error
                });
            }
            catch (Exception exception)
            {
                Dictionary <string, string> dictionary = signUp.ToDictionary();
                ServiceHelper.LogException(exception, dictionary, ErrorSource.Authentication);
                return(new ActionResult
                {
                    Success = false,
                    Message = "Error, failed to register new user."
                });
            }
        }
Beispiel #15
0
        public CreateProductResponse CreateProduct(Stream data)
        {
            MultipartFormDataParser dataParser = new MultipartFormDataParser(data);
            string name             = dataParser.GetParameterValue("name");
            string description      = dataParser.GetParameterValue("description");
            string catergoryId      = dataParser.GetParameterValue("catergory");
            string price            = dataParser.GetParameterValue("price");
            string per              = dataParser.GetParameterValue("per");
            string shortDescription = dataParser.GetParameterValue("shortDescription");
            string manufacturer     = dataParser.GetParameterValue("manufacturer");
            string code             = dataParser.GetParameterValue("code");
            string userId           = dataParser.GetParameterValue("userId");
            string isMain           = dataParser.GetParameterValue("IsMain");
            string isActive         = dataParser.GetParameterValue("isActive");

            try
            {
                bool.TryParse(isMain, out bool checkMain);
                bool.TryParse(isActive, out bool checkActive);
                using (ESamhashoEntities entities = new ESamhashoEntities())
                {
                    if (checkActive)
                    {
                        List <Product> products = entities.Products.ToList();
                        products.ForEach(a => a.IsActive = false);
                        entities.SaveChanges();
                    }
                    if (checkMain)
                    {
                        List <Product> products = entities.Products.Where(a => a.IsMain).ToList();
                        if (products.Count > 3)
                        {
                            Product productMain = products.FirstOrDefault();
                            if (productMain != null)
                            {
                                productMain.IsMain = false;
                            }
                            entities.SaveChanges();
                        }
                    }
                    Product product = new Product
                    {
                        CatergoryId      = int.Parse(catergoryId),
                        Code             = code,
                        CreatedDate      = DateTime.Now,
                        Description      = description,
                        IsDeleted        = false,
                        Manufacturer     = manufacturer,
                        ModifiedDate     = DateTime.Now,
                        Name             = name,
                        Per              = per,
                        Price            = decimal.Parse(price),
                        ShortDescription = shortDescription,
                        UserId           = userId,
                        IsMain           = checkMain,
                        IsActive         = checkActive
                    };
                    entities.Products.Add(product);
                    entities.SaveChanges();
                    string       path         = ServiceHelper.SaveImage(dataParser.Files[0].Data, dataParser.Files[0].FileName);
                    ProductMedia productMedia = new ProductMedia
                    {
                        MediaSource = path,
                        ProductId   = product.Id,
                        DateCreate  = DateTime.Now,
                        IsDeleted   = false,
                        IsMain      = true
                    };
                    entities.ProductMedias.Add(productMedia);
                    entities.SaveChanges();
                    Catergory catergory = entities.Catergories.FirstOrDefault(a => a.Id == product.CatergoryId);
                    return(new CreateProductResponse
                    {
                        DateCreated = product.CreatedDate.ToLongDateString() + " " + product.CreatedDate.ToLongTimeString(),
                        ProductId = product.Id,
                        MediaSource = path,
                        Catergory = catergory == null? "":catergory.Name
                    });
                }
            }
            catch (Exception exception)
            {
                Dictionary <string, string> dictionary = new Dictionary <string, string>
                {
                    { "name", name },
                    { "description", description },
                    { "catergoryId", catergoryId },
                    { "price", price },
                    { "per", per },
                    { "shortDescription", shortDescription },
                    { "manufacturer", manufacturer },
                    { "code", code },
                    { "userId", userId },
                    { "mainImage", true.ToString() },
                };
                ServiceHelper.LogException(exception, dictionary, ErrorSource.Product);
                return(new CreateProductResponse());
            }
        }
Beispiel #16
0
        public ActionResult UpdateUserDetails(Stream userData)
        {
            MultipartFormDataParser dataParser = new MultipartFormDataParser(userData);

            try
            {
                string aboutMe     = dataParser.GetParameterValue("aboutMe");
                string address     = dataParser.GetParameterValue("address");
                string city        = dataParser.GetParameterValue("city");
                string country     = dataParser.GetParameterValue("country");
                string firstName   = dataParser.GetParameterValue("firstName");
                string lastName    = dataParser.GetParameterValue("lastName");
                string token       = dataParser.GetParameterValue("token");
                string phoneNumber = dataParser.GetParameterValue("phonenumber");
                string email       = dataParser.GetParameterValue("email");

                AuthenticationService authenticationService = new AuthenticationService();
                IPrincipal            jwtToken = authenticationService.AuthenticateJwtToken(token);
                string userId = jwtToken.Identity.GetUserId();
                string path   = null;
                if (dataParser.Files.Any())
                {
                    FilePart dataParserFile = dataParser.Files[0];
                    path = ServiceHelper.SaveImage(dataParserFile.Data, dataParserFile.FileName);
                }

                using (ESamhashoEntities entities = new ESamhashoEntities())
                {
                    AspNetUser netUser = entities.AspNetUsers.FirstOrDefault(a => a.Id.Equals(userId));
                    if (netUser != null)
                    {
                        netUser.Email       = String.IsNullOrEmpty(email) ? netUser.Email : email;
                        netUser.PhoneNumber = String.IsNullOrEmpty(phoneNumber) ? netUser.PhoneNumber : phoneNumber;
                    }
                    UserProfile userProfile = entities.UserProfiles.FirstOrDefault(a => a.UserId.Equals(userId));
                    if (userProfile != null)
                    {
                        userProfile.AboutMe        = String.IsNullOrEmpty(aboutMe) ? userProfile.AboutMe : aboutMe;
                        userProfile.Address        = String.IsNullOrEmpty(address) ? userProfile.Address : address;
                        userProfile.City           = String.IsNullOrEmpty(city) ? userProfile.City : city;
                        userProfile.Country        = String.IsNullOrEmpty(country) ? userProfile.Country : country;
                        userProfile.FirstName      = String.IsNullOrEmpty(firstName) ? userProfile.FirstName : firstName;
                        userProfile.LastName       = String.IsNullOrEmpty(lastName) ? userProfile.LastName : lastName;
                        userProfile.ProfilePicture = String.IsNullOrEmpty(path)?userProfile.ProfilePicture:path;
                        userProfile.UserId         = userId;
                    }
                    else
                    {
                        UserProfile addUserProfile = new UserProfile
                        {
                            DateCreated    = DateTime.Now,
                            AboutMe        = aboutMe,
                            Address        = address,
                            City           = city,
                            Country        = country,
                            FirstName      = firstName,
                            LastName       = lastName,
                            ProfilePicture = path,
                            UserId         = userId
                        };
                        entities.UserProfiles.Add(addUserProfile);
                    }
                    entities.SaveChanges();
                    return(new ActionResult
                    {
                        Message = path,
                        Success = true
                    });
                }
            }
            catch (Exception exception)
            {
                Dictionary <string, string> dictionary = new Dictionary <string, string>
                {
                    { "aboutMe", dataParser.GetParameterValue("aboutMe") },
                    { "address", dataParser.GetParameterValue("address") },
                    { "city", dataParser.GetParameterValue("city") },
                    { "country", dataParser.GetParameterValue("country") },
                    { "firstName", dataParser.GetParameterValue("firstName") },
                    { "lastName", dataParser.GetParameterValue("lastName") },
                    { "userId", dataParser.GetParameterValue("userId") }
                };
                ServiceHelper.LogException(exception, dictionary, ErrorSource.User);
                return(new ActionResult
                {
                    Message = "Failed to save profile, try again.",
                    Success = true
                });
            }
        }
        public ActionResult ChangePassword(ChangePassword changePassword)
        {
            try
            {
                string token = HttpContext.Current.Request.Headers["Token"];
                if (!Security.ValidateToken(token, out List <Claim> claims))
                {
                    return(new ActionResult
                    {
                        Message = "Please login",
                        Success = false
                    });
                }
                ActionResult actionResult = ServiceHelper.IsAnyNullOrEmpty(changePassword);
                if (actionResult.Success)
                {
                    actionResult.Success = false;
                    return(actionResult);
                }

                ApplicationUserManager manager = new ApplicationUserManager(new UserStore <ApplicationUser>(new ApplicationDbContext()));
                ApplicationUser        user    = manager.FindByName(changePassword.Username);
                if (user == null)
                {
                    return(new ActionResult
                    {
                        Message = "User does not exist",
                        Success = false
                    });
                }

                IdentityResult result = manager.ChangePassword(user.Id, changePassword.OldPassword, changePassword.NewPassword);
                if (result.Succeeded)
                {
                    using (ESamhashoEntities entities = new ESamhashoEntities())
                    {
                        EmailTemplate emailBody = entities.EmailTemplates.FirstOrDefault(a => a.EmailTemplateId == (byte)EmailTemplateId.ResetPassword);
                        if (emailBody != null)
                        {
                            string body = emailBody.Body.Replace("{password}", changePassword.NewPassword)
                                          .Replace("{accountname}", user.UserName);
                            string        subject       = "Esamhasho password reset";
                            OutgoingEmail outgoingEmail = new OutgoingEmail
                            {
                                Body        = body,
                                Date        = DateTime.Now,
                                Destination = user.Email,
                                Reference   = user.Id,
                                Status      = (byte)EmailStatus.Pending,
                                Subject     = subject
                            };
                            entities.OutgoingEmails.Add(outgoingEmail);
                            entities.SaveChanges();
                            manager.SendEmail(user.Id, subject, body);
                            OutgoingEmail email = entities.OutgoingEmails.FirstOrDefault(a => a.Id == outgoingEmail.Id);
                            if (email != null)
                            {
                                email.Status = (byte)EmailStatus.Success;
                            }
                            entities.SaveChanges();
                        }
                    }

                    return(new ActionResult
                    {
                        Message = "Password successfully changed",
                        Success = true
                    });
                }

                string error = result.Errors.Aggregate(string.Empty, (current, resultError) => current + resultError + Environment.NewLine);
                return(new ActionResult
                {
                    Message = error
                });
            }
            catch (Exception exception)
            {
                Dictionary <string, string> dictionary = changePassword.ToDictionary();
                ServiceHelper.LogException(exception, dictionary, ErrorSource.Authentication);
                return(new ActionResult
                {
                    Success = false,
                    Message = "Error, failed to change password."
                });
            }
        }