Beispiel #1
0
 public ActionResult UpdateProduct(ProductRequest product)
 {
     try
     {
         using (ESamhashoEntities entities = new ESamhashoEntities())
         {
             if (product.IsActive)
             {
                 List <Product> products = entities.Products.ToList();
                 products.ForEach(a => a.IsActive = false);
                 entities.SaveChanges();
             }
             if (product.IsMain)
             {
                 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 updateProduct = entities.Products.FirstOrDefault(a => a.Id == product.ProductId);
             if (updateProduct != null)
             {
                 updateProduct.Description      = product.Description;
                 updateProduct.ShortDescription = product.ShortDescription;
                 updateProduct.CatergoryId      = product.Catergory;
                 updateProduct.Price            = product.Price;
                 updateProduct.Per          = product.Per;
                 updateProduct.Manufacturer = product.Manufacturer;
                 updateProduct.IsActive     = product.IsActive;
                 updateProduct.IsMain       = product.IsMain;
                 updateProduct.Name         = product.Name;
             }
             entities.SaveChanges();
             return(new ActionResult {
                 Message = "Product updated successfully.", Success = true
             });
         }
     }
     catch (Exception exception)
     {
         Dictionary <string, string> dictionary = product.ToDictionary();
         ServiceHelper.LogException(exception, dictionary, ErrorSource.Product);
         return(new ActionResult {
             Message = "Error, failed to update product, try again."
         });
     }
 }
 public ActionResult AddNotification(NotificationData notificationRequest)
 {
     try
     {
         using (ESamhashoEntities entities = new ESamhashoEntities())
         {
             Notification notification = new Notification
             {
                 IsDeleted          = notificationRequest.IsDeleted,
                 DateCreated        = DateTime.Now,
                 FromCustomer       = notificationRequest.FromCustomer,
                 NotificationTypeId = notificationRequest.NotificationTypeId,
                 Email     = notificationRequest.Email,
                 IsRead    = notificationRequest.IsRead,
                 Message   = notificationRequest.Message,
                 Name      = notificationRequest.Name,
                 Phone     = notificationRequest.Phone,
                 ProductId = notificationRequest.ProductId == 0?null: notificationRequest.ProductId
             };
             entities.Notifications.Add(notification);
             entities.SaveChanges();
             return(new ActionResult {
                 Success = true, Message = "Notification saved successfully"
             });
         }
     }
     catch (Exception exception)
     {
         Dictionary <string, string> dictionary = notificationRequest.ToDictionary();
         ServiceHelper.LogException(exception, dictionary, ErrorSource.Notification);
         return(new ActionResult {
             Message = "Error, notification failed to save, try again."
         });
     }
 }
Beispiel #3
0
        public static ActionResult SaveVerificationDetails(string email, string token)
        {
            VerificationToken verification = new VerificationToken();

            try
            {
                ESamhashoEntities entities = new ESamhashoEntities();
                string            guidCode = Guid.NewGuid().ToString();
                verification = new VerificationToken
                {
                    Id         = guidCode,
                    ExpiryDate = DateTime.Now.AddDays(1),
                    UserEmail  = email,
                    UserToken  = token
                };
                entities.VerificationTokens.Add(verification);
                entities.SaveChanges();
                return(new ActionResult
                {
                    Success = true,
                    Message = verification.Id
                });
            }
            catch (Exception exception)
            {
                Dictionary <string, string> dictionary = verification.ToDictionary();
                ServiceHelper.LogException(exception, dictionary, ErrorSource.UserManagement);
                return(new ActionResult
                {
                    Success = false,
                    Message = "Error, failed to save verification details."
                });
            }
        }
 public ActionResult AddCatergory(string catergoryName)
 {
     try
     {
         using (ESamhashoEntities entities = new ESamhashoEntities())
         {
             Catergory catergory = new Catergory
             {
                 IsDeleted    = false,
                 Name         = catergoryName,
                 DateCreated  = DateTime.Now,
                 DateModified = DateTime.Now
             };
             entities.Catergories.Add(catergory);
             entities.SaveChanges();
             return(new ActionResult {
                 Success = true, Message = catergory.Id.ToString()
             });
         }
     }
     catch (Exception exception)
     {
         Dictionary <string, string> dictionary = new Dictionary <string, string>
         {
             { "catergoryName", catergoryName }
         };
         ServiceHelper.LogException(exception, dictionary, ErrorSource.Catergory);
         return(new ActionResult {
             Message = "Error, catergory failed to save, try again."
         });
     }
 }
Beispiel #5
0
        public BlogResponse AddBlog(Stream blogData)
        {
            MultipartFormDataParser dataParser = new MultipartFormDataParser(blogData);

            try
            {
                string   name             = dataParser.GetParameterValue("name");
                string   description      = dataParser.GetParameterValue("description");
                string   titleDescription = dataParser.GetParameterValue("titleDescription");
                FilePart dataParserFile   = dataParser.Files[0];
                string   path             = ServiceHelper.SaveImage(dataParserFile.Data, dataParserFile.FileName);
                using (ESamhashoEntities entities = new ESamhashoEntities())
                {
                    Blog blog = new Blog
                    {
                        Name             = name,
                        IsDeleted        = false,
                        Description      = description,
                        DateCreated      = DateTime.Now,
                        MediaUrl         = path,
                        TitleDescription = titleDescription
                    };
                    entities.Blogs.Add(blog);
                    entities.SaveChanges();
                    return(new BlogResponse
                    {
                        Name = blog.Name,
                        Description = blog.Description,
                        TitleDescription = blog.TitleDescription,
                        Id = blog.Id,
                        DateCreated = blog.DateCreated.ToLongDateString() + " " + blog.DateCreated.ToLongTimeString(),
                        MediaUrl = blog.MediaUrl
                    });
                }
            }
            catch (Exception exception)
            {
                Dictionary <string, string> dictionary = new Dictionary <string, string>
                {
                    { "name", dataParser.GetParameterValue("name") },
                    { "description", dataParser.GetParameterValue("description") },
                    { "titleDescription", dataParser.GetParameterValue("titleDescription") }
                };
                ServiceHelper.LogException(exception, dictionary, ErrorSource.Blog);
                return(new BlogResponse());
            }
        }
Beispiel #6
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 #7
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."
                });
            }
        }
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());
            }
        }
 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 #10
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 #11
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."
                });
            }
        }
        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());
            }
        }