Guest User

Untitled

a guest
Jun 21st, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.48 KB | None | 0 0
  1. Foo; // the MVC web project
  2. Foo.Models;
  3. Foo.Repositories;
  4. Foo.Services;
  5.  
  6. public class User
  7. {
  8. public string Username { get; set; }
  9.  
  10. public string Email { get; set; }
  11.  
  12. public string Password { get; set; }
  13. }
  14.  
  15. public class UserBinder : DefaultModelBinder
  16. {
  17. //...
  18. }
  19.  
  20. public string Email { get; set; }
  21.  
  22. public string Password { get; set; }
  23.  
  24. public ICollection<KeyValuePair<string, string>> ValidateErrors()
  25. {
  26. //Validate if Username, Email and Password has been passed
  27. }
  28.  
  29. // validate everything here
  30.  
  31. base.OnModelUpdated(controllerContext, bindingContext);
  32. }
  33.  
  34. public ActionResult InputAddress(InputAddressViewModel model)
  35. {
  36. if (ModelState.IsValid)
  37. {
  38. // "Front-line" validation passed; let's execute the save operation
  39. // in the our view model
  40. var result = model.Execute();
  41.  
  42. // The view model returns a status code to help the
  43. // controller decide where to redirect the user next
  44. switch (result.Status)
  45. {
  46. case InputAddressViewModelExecuteResult.Saved:
  47. return RedirectToAction("my-work-is-done-here");
  48.  
  49. case InputAddressViewModelExecuteResult.UserCorrectableError:
  50. // Something went wrong after we interacted with the
  51. // datastore, like a bogus Canadian postal code or
  52. // something. Our view model will have updated the
  53. // Error property, but we need to call TryUpdateModel()
  54. // to get these new errors to get added to
  55. // the ModelState, since they were just added and the
  56. // model binder ran before this method even got called.
  57. TryUpdateModel(model);
  58. break;
  59. }
  60.  
  61. // Redisplay the input form to the user, using that nifty
  62. // Html.ValidationMessage to convey model state errors
  63. return View(model);
  64. }
  65. }
  66.  
  67. public InputAddressViewModelExecuteResult Execute()
  68. {
  69. InputAddressViewModelExecuteResult result;
  70.  
  71. if (this.errors.Count > 0)
  72. {
  73. throw new InvalidOperationException(
  74. "Don't call me when I have errors");
  75. }
  76.  
  77. // This is just my abstraction for clearly demarcating when
  78. // I have an open connection to a highly contentious resource,
  79. // like a database connection or a network share
  80. using (ConnectionScope cs = new ConnectionScope())
  81. {
  82. var scheme = new AddressSchemeRepository().Load(this.Country);
  83. var builder = new AddressBuilder(scheme)
  84. .WithCityAs(this.City)
  85. .WithStateOrProvinceAs(this.StateOrProvince);
  86.  
  87. if (!builder.CanBuild())
  88. {
  89. this.errors.Add("Blah", builder.Error);
  90. result = new InputAddressViewModelExecuteResult()
  91. {
  92. Status = InputAddressViewModelExecuteStatus
  93. .UserCorrectableError
  94. };
  95. }
  96. else
  97. {
  98. var address = builder.Build();
  99. // save the address or something...
  100. result = new InputAddressViewModelExecuteResult()
  101. {
  102. Status = InputAddressViewModelExecuteStatus.Success,
  103. Address = address
  104. };
  105. }
  106. }
  107.  
  108. return result;
  109. }
  110.  
  111. public class UserRepository : IRepository<User>
  112. {
  113. public void Create(User user)
  114. {
  115. user.Validate();
  116.  
  117. var db = dbFooEntities();
  118.  
  119. db.AddToUsers(user);
  120. db.SaveChanges();
  121. }
  122. }
  123.  
  124. class User
  125. {
  126. string Username { get; set; }
  127. string Email { get; set; }
  128. string Password { get; set; } // hashed and salted of course :)
  129.  
  130. IEnumerable<RuleViolation> Validate()
  131. {
  132. List<RuleViolation> violations = new List<RuleViolation>();
  133. IUserService service = MyApplicationService.UserService; // MyApplicationService is a singleton class, especialy designed so that the User model can access application services
  134.  
  135. // Username is required
  136. if ( string.IsNullOrEmpty(Username) )
  137. violations.Add(new RuleViolation("Username", "Username is required"));
  138.  
  139. // Username must be unique: Should uniqueness be validated here?
  140. else if( !service.IsUsernameAvailable(Username)
  141. violations.Add(new RuleViolation("Username", "Username is already taken!"));
  142.  
  143. // Validate email etc...
  144.  
  145. return violations;
  146. }
  147. }
  148.  
  149. interface IUserRepository
  150. {
  151. void Save(User item);
  152. }
  153.  
  154. interface IUserService
  155. {
  156. IUserRepository UserRepository { get; }
  157. void Save(User item);
  158. }
  159.  
  160. class UserService : IUserService
  161. {
  162. public UserService(IUserRepository userRepository)
  163. {
  164. this.UserRepository = userRepository;
  165. }
  166.  
  167. IUserRepository UserRepository { get; private set}
  168.  
  169. public void Save(User user)
  170. {
  171. IEnumerable<RuleViolation> violations = user.Validate();
  172.  
  173. if(violations.Count() > 0)
  174. throw new RuleViolationException(violations); // this will be catched by the Controller, which will copy the violations to the ModelState errors collection. But the question is, should we validat the user here, or in the UserRepository class?
  175.  
  176. UserRepository.Save(user);
  177. }
  178. }
  179.  
  180. class UserRepository : IUserRepository
  181. {
  182. void Save(User item)
  183. {
  184. IEnumerable<RuleViolation> violations = user.Validate();
  185.  
  186. if(violations.Count() > 0)
  187. throw new RuleViolationException(violations); // this will be catched by the Controller, which will copy the violations to the ModelState errors collection. But the question is, should we validate the user here, or in the UserService class?
  188.  
  189. UserRepository.Save(user);
  190.  
  191. }
  192. }
  193.  
  194. Html.AutoForm(Model);
  195.  
  196. Html.AutoGrid(Model.Products);
Add Comment
Please, Sign In to add comment