public string RegisterClient(ClientRegistrationRequest request)
        {
            try
            {
                using (var scope = new TransactionScope())
                using (var db = new LomsContext())
                {
                    var email = request.Email.Trim().ToLower();

                    //check id user with such email existed already
                    var count = (from u in db.AssociationUsers
                                 where u.AssociationId == CurrentAssociationId && u.Email == email
                                 select u).Count();

                    if (count != 0)
                        return "User with such email is already registered!";

                    //create membership
                    MembershipCreateStatus status;
                    var userMembership = Membership.CreateUser(email, request.Password, email, "Am i client?", "Yes", false, out status);
                    switch (status)
                    {
                        case MembershipCreateStatus.Success:
                            break;
                        //case MembershipCreateStatus.InvalidPassword:
                        //    throw new ApplicationException("Invalid password.");
                        default:
                            throw new ApplicationException("Cannot create user account.", new ApplicationException(status.ToString()));
                    }
                    Guid aspNetUserId = (Guid)userMembership.ProviderUserKey;


                    //add role
                    if (!Roles.RoleExists(RoleName.Client))
                        Roles.CreateRole(RoleName.Client);
                    Roles.AddUserToRole(email, RoleName.Client);

                    //create user 
                    AssociationUser user = new AssociationUser();

                    user.AssociationId = CurrentAssociationId;
                    user.CountryId = request.CountryId;
                    user.Email = email;

                    //name
                    user.Prefix = NamePrefix.All.FirstOrDefault(p => p.Id == request.NamePrefixId);
                    user.FirstName = request.FirstName.ToUpper();
                    user.LastName = request.LastName.ToUpper();
                    //phone
                    user.OfficePhone = request.OfficePhone;
                    user.MobilePhone = request.MobilePhone;
                    user.HomePhone = request.HomePhone;
                    user.DefaultPhoneType = request.DefaultPhoneType;

                    user.IsTravelAgency = request.IsTravelAgency;
                    user.PositionTitle = request.Position;

                    if (user.IsTravelAgency)
                        user.IataNumber = request.IataNumber.ToUpper();

                    user.CreatedTime = user.LastUpdatedTime = DateTime.UtcNow;

                    user.AspNetUserId = aspNetUserId;

                    db.AssociationUsers.ApplyChanges(user);
                    db.SaveChanges();

                    //home address
                    AssociationUserAddress homeAddress = new AssociationUserAddress();
                    homeAddress.Nickname = user.FullName + " HOME";
                    homeAddress.AssociationUserId = user.Id;
                    homeAddress.Type = AddressType.Home;
                    homeAddress.CountryId = user.CountryId;

                    //work address
                    AssociationUserAddress workAddress = new AssociationUserAddress();
                    workAddress.Nickname = user.FullName + " WORK";
                    workAddress.AssociationUserId = user.Id;
                    workAddress.CountryId = user.CountryId;
                    workAddress.Type = AddressType.Work;

                    workAddress.BusinessName = request.BusinessName.ToUpper();
                    workAddress.BuildingName = request.BuildingName.ToUpper();
                    workAddress.Address1 = request.Address1.ToUpper();
                    workAddress.Address2 = request.Address2.ToUpper();

                    if (request.SuburbId != 0)
                    {
                        workAddress.CountryId = null;
                        workAddress.StateId = null;
                        workAddress.SuburbId = request.SuburbId;
                    }
                    else
                    {
                        if (request.StateId != 0)
                        {
                            workAddress.CountryId = null;
                            workAddress.StateId = request.StateId;
                            workAddress.SuburbId = null;
                        }

                        workAddress.SuburbName = request.SuburbName.ToUpper();
                        workAddress.SuburbCode = request.SuburbCode.ToUpper();
                    }

                    db.AssociationUserAddresses.ApplyChanges(homeAddress);
                    db.AssociationUserAddresses.ApplyChanges(workAddress);
                    db.SaveChanges();

                    AssociationUserActivation activation = new AssociationUserActivation();
                    activation.UserId = user.Id;
                    activation.Guid = Guid.NewGuid();
                    activation.ExpiryTime = DateTime.UtcNow.AddHours(2.0);  //expiry
                    db.AssociationUserActivations.ApplyChanges(activation);
                    db.SaveChanges();

                    var emailProvider = db.AssociationEmails.FirstOrDefault(e => e.AssociationId == CurrentAssociationId);
                    if (emailProvider != null)
                    {
                        var association = db.Associations.FirstOrDefault(a => a.Id == CurrentAssociationId);

                        var uri = HttpContext.Current.Request.Url;

                        string baseUrl = String.Format("{0}://{1}:{2}", uri.Scheme, uri.Host ?? "80", uri.Port);
                        string activtionLink = Path.Combine(baseUrl + string.Format("/#Activation/{0}", activation.Guid.ToString("D")));
                        string contactUsLink = Path.Combine(baseUrl + "/#Contact");

                        var emailTemplate = new EmailTemplate("OnlineRegistrationActivation");
                        emailTemplate["UserName"] = user.FullName.ToUpper();
                        emailTemplate["AssociationName"] = association.Name.ToUpper();
                        emailTemplate["ActivationLink"] = activtionLink;
                        emailTemplate["ContactUsLink"] = contactUsLink;

                        var avBody = AlternateView.CreateAlternateViewFromString(emailTemplate.Html, null, MediaTypeNames.Text.Html);
                        emailProvider.SendMail(user.Email, association.Name + " Account activation", emailTemplate.Txt, null, avBody, true);
                    }

                    scope.Complete();
                }

                return null;
            }
            catch (Exception ex)
            {
                StringBuilder builder = new StringBuilder();
                builder.AppendLine(ex.Message);
                if (ex.InnerException != null)
                {
                    builder.AppendLine(ex.InnerException.Message);
                    if (ex.InnerException.InnerException != null)
                        builder.AppendLine(ex.InnerException.InnerException.Message);
                }
                return builder.ToString();
            }
        }
        public AssociationUser SaveProfile(AssociationUser profile)
        {
            using (TransactionScope scope = new TransactionScope())
            using (var db = new LomsContext())
            {
                if (!HasUniqueEmail(profile))
                {
                    profile.AddError("Error", "The email you have entered is already in use on the system. Please use a unique email address, or call us for assistance.");
                    // TODO: Miguel. Change this based on Andrew's feedback (something like If you think this is an error, please contact)
                    return profile;
                }

                bool isManager = profile.TravelAgencyRole != null;

                if (profile.Id == 0)
                {
                    profile.AssociationId = CurrentAssociationId;
                    profile.CreatedTime = profile.LastUpdatedTime = DateTime.UtcNow;
                }
                if (profile.Email != null)
                    profile.Email = profile.Email.Trim();


                profile.LastUpdatedTime = DateTime.UtcNow;

                db.AssociationUsers.ApplyChanges(profile);
                db.SaveChanges();

                if (isManager)
                    profile = db.AssociationUsers.IncludeAll("Country", "Activation", "TravelAgencyRole", "TravelAgencyRole.TravelAgency", "TravelAgencyRole.TravelAgency.Country", "TravelAgencyRole.TravelAgency.State", "TravelAgencyRole.TravelAgency.State.Country", "TravelAgencyRole.TravelAgency.Suburb", "TravelAgencyRole.TravelAgency.Suburb.Country", "TravelAgencyRole.TravelAgency.Suburb.State", "TravelAgencyRole.TravelAgency.Suburb.State.Country").FirstOrDefault(u => u.Id == profile.Id);
                else
                    profile = db.AssociationUsers.IncludeAll("Country", "Activation").FirstOrDefault(u => u.Id == profile.Id);

                //onlie access
                if (profile != null && !string.IsNullOrWhiteSpace(profile.Email) && profile.Activation == null && !profile.HasOnlineAccess)
                {
                    //start activation process
                    AssociationUserActivation activation = new AssociationUserActivation();
                    activation.UserId = profile.Id;
                    activation.Guid = Guid.NewGuid();
                    activation.ExpiryTime = DateTime.UtcNow.AddDays(7.0);  //expiry
                    db.AssociationUserActivations.ApplyChanges(activation);
                    db.SaveChanges();

                    //send email
                    var emailProvider = db.AssociationEmails.FirstOrDefault(e => e.AssociationId == profile.AssociationId);
                    if (emailProvider != null)
                    {
                        var association = db.Associations.FirstOrDefault(a => a.Id == profile.AssociationId);

                        var request = HttpContext.Current.Request;
                        var uri = request.Url;
                        string baseUrl = String.Format("{0}://{1}:{2}", uri.Scheme, uri.Host ?? "80", uri.Port);
                        string activtionLink = Path.Combine(baseUrl + string.Format("/#Activation/{0}", activation.Guid.ToString("D")));
                        string contactUsLink = Path.Combine(baseUrl + "/#Contact");
                        string termAndConditionsLink = Path.Combine(baseUrl + "/terms");

                        var manager = db.AssociationUsers.FirstOrDefault(u => u.Id == profile.ManagerId);

                        if (profile.IataNumber != null)
                        {
                            var travelAgencyName = (from a in db.AssociationUserAddresses
                                                    where a.AssociationUserId == profile.Id && a.TypeId == (int)AddressType.Work
                                                    select a.BusinessName).SingleOrDefault();


                            var txtContent = MailTemplateHelper.GetByTravelAgentRegistrationActivationTxtContent(association.Name.ToUpper(), profile.FullName.ToUpper(), activtionLink, contactUsLink, manager.FullName, manager.Email, termAndConditionsLink, travelAgencyName);
                            var htmlContent = MailTemplateHelper.GetByTravelAgentRegistrationActivationHtmlContent(association.Name, profile.FullName, activtionLink, contactUsLink, manager.FullName, manager.Email, termAndConditionsLink, travelAgencyName);
                            var avBody = AlternateView.CreateAlternateViewFromString(htmlContent, null, MediaTypeNames.Text.Html);

                            emailProvider.SendMail(profile.Email, association.Name.ToUpper() + " Account activation", txtContent, null, avBody, true);
                        }
                        else
                        {
                            var txtContent = MailTemplateHelper.GetByGeneralUserRegistrationActivationTxtContent(association.Name.ToUpper(), profile.FullName.ToUpper(), activtionLink, contactUsLink, manager.FullName, manager.Email, termAndConditionsLink);
                            var htmlContent = MailTemplateHelper.GetByGeneralUserRegistrationActivationHtmlContent(association.Name, profile.FullName, activtionLink, contactUsLink, manager.FullName, manager.Email, termAndConditionsLink);
                            var avBody = AlternateView.CreateAlternateViewFromString(htmlContent, null, MediaTypeNames.Text.Html);

                            try
                            {
                                emailProvider.SendMail(profile.Email, association.Name.ToUpper() + " Account activation", txtContent, null, avBody, true);
                            }
                            catch
                            {
                            }
                        }
                    }
                }
                scope.Complete();
            }

            profile.AcceptChanges();
            return profile;
        }
        public AssociationUser SaveAssociationUser(AssociationUser user)
        {
            try
            {
                string email = user.Email != null ? user.Email.ToLower().Trim() : null;

                using (var db = new LomsContext())
                {
                    db.Connection.Open();

                    using (var transaction = db.Connection.BeginTransaction())
                    {
                        if (!string.IsNullOrWhiteSpace(email))
                        {
                            //check id user with such email existed already
                            var existedUser = (from u in db.AssociationUsers
                                               where u.AssociationId == CurrentAssociationId && u.Email == email && (user.Id == 0 || u.Id != user.Id)
                                               select u).SingleOrDefault();

                            if (existedUser != null)
                            {
                                user.AddError("Email", "User with such email is already registered!");
                                return user;
                            }

                            user.Email = email;
                        }
                        else
                            user.Email = null;


                        user.AssociationId = CurrentAssociationId;
                        user.CreatedTime = user.LastUpdatedTime = DateTime.UtcNow;

                        db.AssociationUsers.ApplyChanges(user);
                        db.SaveChanges();

                        if (!string.IsNullOrWhiteSpace(user.Email))
                        {
                            AssociationUserActivation activation = new AssociationUserActivation();
                            activation.UserId = user.Id;
                            activation.Guid = Guid.NewGuid();
                            activation.ExpiryTime = DateTime.UtcNow.AddDays(7.0);  //expiry
                            db.AssociationUserActivations.ApplyChanges(activation);
                            db.SaveChanges();

                            var emailProvider = db.AssociationEmails.FirstOrDefault(e => e.AssociationId == CurrentAssociationId);
                            if (emailProvider != null)
                            {
                                var association = db.Associations.FirstOrDefault(a => a.Id == CurrentAssociationId);

                                var uri = HttpContext.Current.Request.Url;
                                string baseUrl = String.Format("{0}://{1}:{2}", uri.Scheme, uri.Host ?? "80", uri.Port);
                                string activtionLink = Path.Combine(baseUrl + string.Format("/#Activation/{0}", activation.Guid.ToString("D")));
                                string contactUsLink = Path.Combine(baseUrl + "/#Contact");
                                string termAndConditionsLink = Path.Combine(baseUrl + "/terms");

                                var emailTemplate = new EmailTemplate("StaffAdminAddsNewManagedProfileWithEmail");

                                emailTemplate["UserName"] = user.FullName.ToUpper();
                                emailTemplate["AssociationName"] = association.Name.ToUpper();

                                emailTemplate["ActivationLink"] = activtionLink;
                                emailTemplate["ContactUsLink"] = contactUsLink;
                                emailTemplate["TermAndConditionLink"] = termAndConditionsLink;

                                var avBody = AlternateView.CreateAlternateViewFromString(emailTemplate.Html, null, MediaTypeNames.Text.Html);
                                emailProvider.SendMail(user.Email, association.Name + " Account activation", emailTemplate.Txt, null, avBody, true);
                            }
                        }

                        transaction.Commit();
                    }
                }
                using (var db = new LomsContext())
                {
                    var entity = db.AssociationUsers.IncludeAll("Country").Single(u => u.Id == user.Id);
                    return entity;
                }
            }
            catch (Exception ex)
            {
                StringBuilder builder = new StringBuilder();
                builder.AppendLine(ex.Message);
                if (ex.InnerException != null)
                {
                    builder.AppendLine(ex.InnerException.Message);
                    if (ex.InnerException.InnerException != null)
                        builder.AppendLine(ex.InnerException.InnerException.Message);
                }
                user.AddError("Error", builder.ToString());
                return user;
            }

        }
     public bool Equals(AssociationUserActivation other)
     {
         if (ReferenceEquals(null, other)) return false;
         if (ReferenceEquals(this, other)) return true;
 		if (other.UserId == 0 && UserId == 0)
 			return false;
 		else
 			return other.UserId == UserId;
     }
        public EntityResponse<AssociationUser> CreateManagedUser(AssociationUser user)
        {
            try
            {
                var email = user.Email.ToLower().Trim();

                using (var scope = new TransactionScope())
                using (var db = new LomsContext())
                {
                    if (!string.IsNullOrWhiteSpace(email))
                    {
                        //check id user with such email existed already
                        var existedUser = (from u in db.AssociationUsers
                                           where u.AssociationId == CurrentAssociationId && u.Email == email
                                           select u).SingleOrDefault();

                        if (existedUser != null)
                            return new EntityResponse<AssociationUser>("User with such email is already registered!");
                        user.Email = email;
                    }
                    else
                        user.Email = null;


                    user.AssociationId = CurrentAssociationId;
                    user.CreatedTime = user.LastUpdatedTime = DateTime.UtcNow;

                    var manager = db.AssociationUsers.FirstOrDefault(u => u.Id == user.ManagerId);
                    if (manager.IsTravelAgency)
                    {
                        user.IsTravelAgency = true;
                        user.IataNumber = manager.IataNumber;
                    }

                    db.AssociationUsers.ApplyChanges(user);
                    db.SaveChanges();

                    AssociationUserActivation activation = new AssociationUserActivation();
                    activation.UserId = user.Id;
                    activation.Guid = Guid.NewGuid();
                    activation.ExpiryTime = DateTime.UtcNow.AddDays(7.0);  //expiry
                    db.AssociationUserActivations.ApplyChanges(activation);
                    db.SaveChanges();

                    var emailProvider = db.AssociationEmails.FirstOrDefault(e => e.AssociationId == CurrentAssociationId);
                    if (emailProvider != null)
                    {
                        var association = db.Associations.FirstOrDefault(a => a.Id == CurrentAssociationId);

                        var uri = HttpContext.Current.Request.Url;
                        string baseUrl = String.Format("{0}://{1}:{2}", uri.Scheme, uri.Host ?? "80", uri.Port);
                        string activtionLink = Path.Combine(baseUrl + string.Format("/#Activation/{0}", activation.Guid.ToString("D")));
                        string contactUsLink = Path.Combine(baseUrl + "/#Contact");
                        string termAndConditionsLink = Path.Combine(baseUrl + "/terms");

                        EmailTemplate emailTemplate;
                        if (manager.IsTravelAgency)
                        {
                            emailTemplate = new EmailTemplate("NewProfileByTravelAgent");

                            var travelAgencyName = (from a in db.AssociationUserAddresses
                                                    where a.AssociationUserId == manager.Id && a.TypeId == (int)AddressType.Work
                                                    select a.BusinessName).SingleOrDefault();

                            emailTemplate["TravelAgencyName"] = travelAgencyName.ToUpper();
                        }
                        else
                            emailTemplate = new EmailTemplate("NewProfileByGeneralUser");

                        emailTemplate["UserName"] = user.FullName.ToUpper();
                        emailTemplate["AssociationName"] = association.Name.ToUpper();

                        emailTemplate["ManagerName"] = manager.FullName.ToUpper();
                        emailTemplate["ManagerEmail"] = manager.Email.ToLower();

                        emailTemplate["ActivationLink"] = activtionLink;
                        emailTemplate["ContactUsLink"] = contactUsLink;
                        emailTemplate["TermAndConditionLink"] = termAndConditionsLink;

                        var avBody = AlternateView.CreateAlternateViewFromString(emailTemplate.Html, null, MediaTypeNames.Text.Html);
                        emailProvider.SendMail(user.Email, association.Name + " Account activation", emailTemplate.Txt, null, avBody, true);
                    }

                    scope.Complete();

                }

                using (var db = new LomsContext())
                {
                    var entity = db.AssociationUsers.IncludeAll("Country").Single(u => u.Id == user.Id);
                    return new EntityResponse<AssociationUser>() { Entity = entity };
                }
            }
            catch (Exception ex)
            {
                StringBuilder builder = new StringBuilder();
                builder.AppendLine(ex.Message);
                if (ex.InnerException != null)
                {
                    builder.AppendLine(ex.InnerException.Message);
                    if (ex.InnerException.InnerException != null)
                        builder.AppendLine(ex.InnerException.InnerException.Message);
                }
                return new EntityResponse<AssociationUser>(builder.ToString());
            }
        }
Exemple #6
0
     private void FixupActivation(AssociationUserActivation previousValue)
     {
         // This is the principal end in an association that performs cascade deletes.
         // Update the event listener to refer to the new dependent.
         if (previousValue != null)
         {
             ChangeTracker.ObjectStateChanging -= previousValue.HandleCascadeDelete;
         }
 
         if (Activation != null)
         {
             ChangeTracker.ObjectStateChanging += Activation.HandleCascadeDelete;
         }
 
         if (IsDeserializing)
         {
             return;
         }
 
         if (Activation != null)
         {
             Activation.UserId = Id;
         }
 
         if (ChangeTracker.ChangeTrackingEnabled)
         {
             if (ChangeTracker.OriginalValues.ContainsKey("Activation")
                 && (ChangeTracker.OriginalValues["Activation"] == Activation))
             {
                 ChangeTracker.OriginalValues.Remove("Activation");
             }
             else
             {
                 ChangeTracker.RecordOriginalValue("Activation", previousValue);
                 // This is the principal end of an identifying association, so the dependent must be deleted when the relationship is removed.
                 // If the current state of the dependent is Added, the relationship can be changed without causing the dependent to be deleted.
                 if (previousValue != null && previousValue.ChangeTracker.State != ObjectState.Added)
                 {
                     previousValue.MarkAsDeleted();
                 }
             }
             if (Activation != null && !Activation.ChangeTracker.ChangeTrackingEnabled)
             {
                 Activation.StartTracking();
             }
         }
     }