Inheritance: IDisposable, IUnitOfWork
Example #1
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var uowParam = context.ActionDescriptor.Parameters.FirstOrDefault(x => x.ParameterType == typeof(IUnitOfWork));
            if (uowParam != null)
            {
                var connectionKey = this.GetType().GetCustomAttribute<ConnectionKeyAttribute>();
                if (connectionKey == null)
                    throw new ArgumentNullException("connectionKey");

                this.connection = SqlConnections.NewByKey(connectionKey.Value);
                this.unitOfWork = new UnitOfWork(connection);
                context.ActionArguments[uowParam.Name] = this.unitOfWork;
                base.OnActionExecuting(context);
                return;
            }

            var cnnParam = context.ActionDescriptor.Parameters.FirstOrDefault(x => x.ParameterType == typeof(IDbConnection));
            if (cnnParam != null)
            {
                var connectionKey = this.GetType().GetCustomAttribute<ConnectionKeyAttribute>();
                if (connectionKey == null)
                    throw new ArgumentNullException("connectionKey");

                this.connection = SqlConnections.NewByKey(connectionKey.Value);
                context.ActionArguments[cnnParam.Name] = connection;
                base.OnActionExecuting(context);
            }

            base.OnActionExecuting(context);
        }
Example #2
0
            protected override ActionResult InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary<string, object> parameters)
            {
                var uowParam = actionDescriptor.GetParameters().FirstOrDefault(x => x.ParameterType == typeof(IUnitOfWork));
                if (uowParam != null)
                {
                    var connectionKey = controllerContext.Controller.GetType().GetCustomAttribute<ConnectionKeyAttribute>();
                    if (connectionKey == null)
                        throw new ArgumentNullException("connectionKey");

                    using (var connection = SqlConnections.NewByKey(connectionKey.Value))
                    using (var uow = new UnitOfWork(connection))
                    {
                        parameters[uowParam.ParameterName] = uow;
                        var result = base.InvokeActionMethod(controllerContext, actionDescriptor, parameters);
                        uow.Commit();
                        return result;
                    }
                }

                var cnnParam = actionDescriptor.GetParameters().FirstOrDefault(x => x.ParameterType == typeof(IDbConnection));
                if (cnnParam != null)
                {
                    var connectionKey = controllerContext.Controller.GetType().GetCustomAttribute<ConnectionKeyAttribute>();
                    if (connectionKey == null)
                        throw new ArgumentNullException("connectionKey");

                    using (var cnn = SqlConnections.NewByKey(connectionKey.Value))
                    {
                        parameters[cnnParam.ParameterName] = cnn;
                        return base.InvokeActionMethod(controllerContext, actionDescriptor, parameters);
                    }
                }

                return base.InvokeActionMethod(controllerContext, actionDescriptor, parameters);
            }
Example #3
0
        protected override void Dispose(bool disposing)
        {
            if (unitOfWork != null)
            {
                unitOfWork.Dispose();
                unitOfWork = null;
            }

            if (connection != null)
            {
                connection.Dispose();
                connection = null;
            }

            base.Dispose(disposing);
        }
Example #4
0
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            if (unitOfWork != null)
            {
                unitOfWork.Commit();
                unitOfWork = null;
            }

            if (connection != null)
            {
                connection.Dispose();
                connection = null;
            }

            context.Result = (context.Result as ActionResult) ?? new Result<object>(context.Result);

            base.OnActionExecuted(context);
        }
        public ActionResult Activate(string t)
        {
            using (var connection = SqlConnections.NewByKey("Default"))
            using (var uow = new UnitOfWork(connection))
            {
                int userId;
                try
                {
                    using (var ms = new MemoryStream(MachineKey.Unprotect(Convert.FromBase64String(t), "Activate")))
                    using (var br = new BinaryReader(ms))
                    {
                        var dt = DateTime.FromBinary(br.ReadInt64());
                        if (dt < DateTime.UtcNow)
                            return Error(Texts.Validation.InvalidActivateToken);

                        userId = br.ReadInt32();
                    }
                }
                catch (Exception)
                {
                    return Error(Texts.Validation.InvalidActivateToken);
                }

                var user = uow.Connection.TryById<UserRow>(userId);
                if (user == null || user.IsActive != 0)
                    return Error(Texts.Validation.InvalidActivateToken);

                uow.Connection.UpdateById(new UserRow
                {
                    UserId = user.UserId.Value,
                    IsActive = 1
                });

                BatchGenerationUpdater.OnCommit(uow, UserRow.Fields.GenerationKey);
                uow.Commit();

                return new RedirectResult("~/Account/Login?activated=" + Uri.EscapeDataString(user.Email));
            }
        }
        public Result<ServiceResponse> SignUp(SignUpRequest request)
        {
            return this.UseConnection("Default", connection =>
            {
                request.CheckNotNull();

                Check.NotNullOrWhiteSpace(request.Email, "email");
                Check.NotNullOrEmpty(request.Password, "password");
                UserRepository.ValidatePassword(request.Email, request.Password, true);
                Check.NotNullOrWhiteSpace(request.DisplayName, "displayName");

                if (connection.Exists<UserRow>(
                        UserRow.Fields.Username == request.Email |
                        UserRow.Fields.Email == request.Email))
                {
                    throw new ValidationError("EmailInUse", Texts.Validation.CantFindUserWithEmail);
                }

                using (var uow = new UnitOfWork(connection))
                {
                    string salt = null;
                    var hash = UserRepository.GenerateHash(request.Password, ref salt);
                    var displayName = request.DisplayName.TrimToEmpty();
                    var email = request.Email;
                    var username = request.Email;

                    var fld = UserRow.Fields;
                    var userId = (int)new SqlInsert(fld.TableName)
                        .Set(fld.Username, username)
                        .Set(fld.Source, "sign")
                        .Set(fld.DisplayName, displayName)
                        .Set(fld.Email, email)
                        .Set(fld.PasswordHash, hash)
                        .Set(fld.PasswordSalt, salt)
                        .Set(fld.IsActive, 0)
                        .Set(fld.InsertDate, DateTime.Now)
                        .Set(fld.InsertUserId, 1)
                        .Set(fld.LastDirectoryUpdate, DateTime.Now)
                        .ExecuteAndGetID(connection);

                    byte[] bytes;
                    using (var ms = new MemoryStream())
                    using (var bw = new BinaryWriter(ms))
                    {
                        bw.Write(DateTime.UtcNow.AddHours(3).ToBinary());
                        bw.Write(userId);
                        bw.Flush();
                        bytes = ms.ToArray();
                    }

                    var token = Convert.ToBase64String(MachineKey.Protect(bytes, "Activate"));

                    var externalUrl = Config.Get<EnvironmentSettings>().SiteExternalUrl ??
                        Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/");

                    var activateLink = UriHelper.Combine(externalUrl, "Account/Activate?t=");
                    activateLink = activateLink + Uri.EscapeDataString(token);

                    var emailModel = new ActivateEmailModel();
                    emailModel.Username = username;
                    emailModel.DisplayName = displayName;
                    emailModel.ActivateLink = activateLink;

                    var emailSubject = Texts.Forms.Membership.SignUp.ActivateEmailSubject.ToString();
                    var emailBody = TemplateHelper.RenderTemplate(
                        MVC.Views.Membership.Account.SignUp.AccountActivateEmail, emailModel);

                    var message = new MailMessage();
                    message.To.Add(email);
                    message.Subject = emailSubject;
                    message.Body = emailBody;
                    message.IsBodyHtml = true;

                    var client = new SmtpClient();

                    if (client.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory &&
                        string.IsNullOrEmpty(client.PickupDirectoryLocation))
                    {
                        var pickupPath = Server.MapPath("~/App_Data");
                        pickupPath = Path.Combine(pickupPath, "Mail");
                        Directory.CreateDirectory(pickupPath);
                        client.PickupDirectoryLocation = pickupPath;
                    }

                    uow.Commit();
                    UserRetrieveService.RemoveCachedUser(userId, username);
                    client.Send(message);

                    return new ServiceResponse();
                }
            });
        }