Advertisement
social1986

Untitled

Jul 26th, 2018
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.84 KB | None | 0 0
  1. namespace PhotoShare.Client.Core.Commands
  2. {
  3.     using System;
  4.     using System.Collections.Generic;
  5.     using System.ComponentModel.DataAnnotations;
  6.  
  7.     using Contracts;
  8.     using PhotoShare.Client.Core.Dtos;
  9.     using PhotoShare.Services.Contracts;
  10.  
  11.     public class RegisterUserCommand : ICommand
  12.     {
  13.         private readonly IUserService userService;
  14.  
  15.         public RegisterUserCommand(IUserService userService)
  16.         {
  17.             this.userService = userService;
  18.         }
  19.  
  20.         // RegisterUser <username> <password> <repeat-password> <email>
  21.         public string Execute(string[] data)
  22.         {
  23.             var username = data[0];
  24.             var pass = data[1];
  25.             var repeatedPass = data[2];
  26.             var email = data[3];
  27.  
  28.             var userExist = this.userService.Exists(username);
  29.  
  30.             if (userExist)
  31.             {
  32.                 throw new InvalidOperationException($"Username [{username}] is already taken!");
  33.             }
  34.  
  35.             if (!pass.Equals(repeatedPass))
  36.             {
  37.                 throw new ArgumentException("Passwords do not match!");
  38.             }
  39.  
  40.  
  41.  
  42.             var registerUserDto = new RegisterUserDto { Username = username, Password = pass, Email = email };
  43.  
  44.             if (!IsValid(registerUserDto))
  45.             {
  46.                 throw new ArgumentException("Invalid arguments inserted!");
  47.             }
  48.  
  49.             this.userService.Register(username, pass, email);
  50.  
  51.             return $"User [{username}] was registered successfully!";
  52.         }
  53.  
  54.         private bool IsValid(object obj)
  55.         {
  56.             var validationContext = new ValidationContext(obj);
  57.             var validationResults = new List<ValidationResult>();
  58.  
  59.             return Validator.TryValidateObject(obj, validationContext, validationResults, true);
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement