/// <summary>
        /// Creates a new Sitefinity profile.
        /// </summary>
        /// <param name="gigyaModel">Deserialized Gigya JSON object.</param>
        /// <param name="settings">Gigya module settings.</param>
        /// <param name="userManager">Sitefinity user manager.</param>
        /// <param name="profileManager">Sitefinity profile manager.</param>
        /// <param name="user">The user that will be associated with the new profile.</param>
        protected virtual SitefinityProfile CreateProfile(dynamic gigyaModel, IGigyaModuleSettings settings, UserManager userManager, UserProfileManager profileManager, User user, List <MappingField> mappingFields)
        {
            SitefinityProfile profile = profileManager.CreateProfile(user, Guid.NewGuid(), typeof(SitefinityProfile)) as SitefinityProfile;

            if (profile != null)
            {
                profile.Nickname = user.Email;

                userManager.SaveChanges();
                profileManager.RecompileItemUrls(profile);
                profileManager.SaveChanges();

                MapProfileFields(profile, gigyaModel, settings, mappingFields);
            }

            try
            {
                profileManager.RecompileItemUrls(profile);
                profileManager.SaveChanges();
            }
            catch (Exception e)
            {
                _logger.Error("Failed to create profile for userId: " + user.Id, e);
            }

            return(profile);
        }
Exemplo n.º 2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            UserManager userManager = UserManager.GetManager();
            List <User> users       = userManager.GetUsers().ToList();

            DataTable output = new DataTable("ASA");

            output.Columns.Add("LastName");
            output.Columns.Add("FirstName");
            output.Columns.Add("Email");
            output.Columns.Add("Username");
            output.Columns.Add("UserID");


            foreach (User user in users)
            {
                UserProfileManager profileManager = UserProfileManager.GetManager();
                SitefinityProfile  profile        = profileManager.GetUserProfile <SitefinityProfile>(user);

                DataRow dr;
                dr = output.NewRow();
                dr["FirstName"] = profile.FirstName;
                dr["Username"]  = user.UserName;
                dr["Email"]     = user.Email;
                dr["LastName"]  = profile.LastName;
                dr["UserID"]    = user.Id;

                output.Rows.Add(dr);
            }


            SitefinityUsersGridView.DataSource = output;
            //if (!IsPostBack)
            SitefinityUsersGridView.DataBind();
        }
Exemplo n.º 3
0
        private static MembershipCreateStatus CreateUser(string email)
        {
            UserManager        userManager    = UserManager.GetManager();
            UserProfileManager profileManager = UserProfileManager.GetManager();

            MembershipCreateStatus status;

            try
            {
                User user = userManager.CreateUser(email, email, email, email, true, null, out status);

                if (status == MembershipCreateStatus.Success)
                {
                    SitefinityProfile sfProfile = profileManager.CreateProfile(user, Guid.NewGuid(), typeof(SitefinityProfile)) as SitefinityProfile;

                    if (sfProfile != null)
                    {
                        sfProfile.FirstName = email;
                        sfProfile.LastName  = email;
                    }

                    userManager.SaveChanges();
                    profileManager.RecompileItemUrls(sfProfile);
                    profileManager.SaveChanges();
                }

                return(status);
            }
            catch (System.UnauthorizedAccessException ex)
            {
                return(MembershipCreateStatus.ProviderError);
            }
        }
Exemplo n.º 4
0
        private void CreateUser(string dataProviderName, string externalProviderName, string email, string externalId, string firstName, string lastName)
        {
            // Start transaction
            Guid   guid            = Guid.NewGuid();
            string transactionName = string.Concat("ExternalLoginCreateUserTransaction", guid.ToString());

            UserManager        userManager    = UserManager.GetManager(dataProviderName, transactionName);
            UserProfileManager profileManager = UserProfileManager.GetManager(string.Empty, transactionName);

            // Create new user
            User newUser = userManager.CreateUser(null);

            newUser.IsBackendUser        = false;
            newUser.IsApproved           = true;
            newUser.Email                = email;
            newUser.ExternalProviderName = externalProviderName;
            newUser.ExternalId           = externalId;
            newUser.SetUserName(email);

            // Update user roles
            List <string> autoAssignedRoles = (
                from s in Config.Get <AuthenticationConfig>().SecurityTokenService
                .AuthenticationProviders[externalProviderName].AutoAssignedRoles
                .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                select s.Trim()).ToList();

            RoleManager roleManager = RoleManager.GetManager(string.Empty, transactionName);
            List <Role> roles       = roleManager.GetRoles().ToList();

            foreach (string newRole in autoAssignedRoles.Distinct())
            {
                Role role = (
                    from r in roles
                    where r.Name == newRole
                    select r).FirstOrDefault();

                if (role == null)
                {
                    continue;
                }

                roleManager.AddUserToRole(newUser, role);
            }

            // Update user profile
            SitefinityProfile newProfile =
                profileManager.CreateProfile(newUser, Guid.NewGuid(), typeof(SitefinityProfile)) as SitefinityProfile;

            if (newProfile != null)
            {
                newProfile.FirstName = firstName;
                newProfile.LastName  = lastName;
            }

            // Commit transaction
            TransactionManager.FlushTransaction(transactionName);
            profileManager.RecompileItemUrls(newProfile);
            TransactionManager.CommitTransaction(transactionName);
        }
        /// <summary>
        /// Maps Gigya fields to a Sitefinity profile.
        /// </summary>
        /// <param name="profile">The profile to update.</param>
        /// <param name="gigyaModel">Deserialized Gigya JSON object.</param>
        /// <param name="settings">The Gigya module settings.</param>
        protected virtual void MapProfileFields(SitefinityProfile profile, dynamic gigyaModel, IGigyaModuleSettings settings, List <MappingField> mappingFields)
        {
            if (mappingFields == null)
            {
                return;
            }

            profile.FirstName = GetMappedFieldWithFallback(gigyaModel, Constants.SitefinityFields.FirstName, Constants.GigyaFields.FirstName, mappingFields);
            profile.LastName  = GetMappedFieldWithFallback(gigyaModel, Constants.SitefinityFields.LastName, Constants.GigyaFields.LastName, mappingFields);

            // map custom fields
            foreach (var field in mappingFields)
            {
                // check if field is a custom one
                switch (field.CmsFieldName)
                {
                case Constants.SitefinityFields.UserId:
                case Constants.SitefinityFields.FirstName:
                case Constants.SitefinityFields.LastName:
                case Constants.SitefinityFields.Email:
                    continue;
                }

                if (!string.IsNullOrEmpty(field.CmsFieldName) && profile.DoesFieldExist(field.CmsFieldName))
                {
                    object gigyaValue = GetGigyaValue(gigyaModel, field.GigyaFieldName, field.CmsFieldName);
                    if (gigyaValue != null)
                    {
                        try
                        {
                            profile.SetValue(field.CmsFieldName, gigyaValue);
                        }
                        catch (Exception e)
                        {
                            _logger.Error(string.Format("Couldn't set Sitefinity profile value for [{0}] and gigya field [{1}].", field.CmsFieldName, field.GigyaFieldName), e);
                        }

                        var profileValue = profile.GetValue(field.CmsFieldName);
                        if (profileValue == null || profileValue.ToString() != gigyaValue.ToString())
                        {
                            _logger.Error(string.Format("Sitefinity field [{0}] type doesn't match Gigya field [{1}] type. You may need to add a conversion using EventHub.Subscribe<IMapGigyaFieldEvent>", field.CmsFieldName, field.GigyaFieldName));
                        }
                    }
                    else if (settings.DebugMode)
                    {
                        _logger.DebugFormat("Gigya field \"{0}\" is null so profile field not updated.", field.GigyaFieldName);
                    }
                }
                else if (settings.DebugMode)
                {
                    _logger.DebugFormat("Sitefinity field \"{0}\" not found.", field.CmsFieldName);
                }
            }
        }
        /// <summary>
        /// Creates a new Sitefinity user from a Gigya user.
        /// </summary>
        /// <param name="username">The Id of the new user.</param>
        /// <param name="gigyaModel">Deserialized Gigya JSON object.</param>
        /// <param name="settings">Gigya module settings for the site.</param>
        /// <returns></returns>
        protected virtual MembershipCreateStatus CreateUser(string username, dynamic gigyaModel, IGigyaModuleSettings settings, List <MappingField> mappingFields)
        {
            UserManager        userManager    = UserManager.GetManager();
            UserProfileManager profileManager = UserProfileManager.GetManager();

            MembershipCreateStatus status;
            var email     = GetMappedFieldWithFallback(gigyaModel, Constants.SitefinityFields.Email, Constants.GigyaFields.Email, mappingFields);
            var firstName = GetMappedFieldWithFallback(gigyaModel, Constants.SitefinityFields.FirstName, Constants.GigyaFields.FirstName, mappingFields);
            var lastName  = GetMappedFieldWithFallback(gigyaModel, Constants.SitefinityFields.LastName, Constants.GigyaFields.LastName, mappingFields);

            User user = userManager.CreateUser(username, Guid.NewGuid().ToString(), email, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), true, null, out status);
            SitefinityProfile profile = null;

            switch (status)
            {
            case MembershipCreateStatus.Success:
                profile = CreateProfile(gigyaModel, settings, userManager, profileManager, user, mappingFields);
                break;

            case MembershipCreateStatus.DuplicateEmail:
                // insert fails if there is a duplicate email even though duplicate emails are allowed...strange huh
                var dummyEmail = string.Concat(Guid.NewGuid(), "@gigya.com");

                // try insert again with a dummy email and update it afterwards
                user = userManager.CreateUser(username, Guid.NewGuid().ToString(), dummyEmail, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), true, null, out status);
                if (status == MembershipCreateStatus.Success)
                {
                    user.Email = email;
                    profile    = CreateProfile(gigyaModel, settings, userManager, profileManager, user, mappingFields);
                }
                break;
            }

            if (user == null)
            {
                return(status);
            }

            MapProfileFields(profile, gigyaModel, settings, mappingFields);

            try
            {
                userManager.SaveChanges();
                profileManager.SaveChanges();
            }
            catch (Exception e)
            {
                _logger.Error("Failed to update profile for userId: " + username, e);
            }

            return(status);
        }
        public ActionResult Details(SitefinityProfile user)
        {
            var fullTemplateName = this.detailTemplateNamePrefix + this.DetailTemplateName;

            var viewModel = this.Model.CreateDetailsViewModel(user);

            if (SystemManager.CurrentHttpContext != null)
            {
                this.AddCacheDependencies(this.Model.GetKeysOfDependentObjects(viewModel));
            }

            return(this.View(fullTemplateName, viewModel));
        }
Exemplo n.º 8
0
        public static string GetUserLastNameById(Guid userId)
        {
            var  userManager = UserManager.GetManager();
            User user        = userManager.GetUser(userId);
            UserProfileManager profileManager = UserProfileManager.GetManager();
            SitefinityProfile  profile        = profileManager.GetUserProfile <SitefinityProfile>(user);
            string             lastName       = "";

            if (profile != null && profile.LastName != null)
            {
                lastName = profile.LastName;
            }

            return(lastName);
        }
Exemplo n.º 9
0
        public static MembershipCreateStatus CreateUser(string username, string password, string firstName, string lastName, string mail, string phoneNumber, string secretQuestion, string secretAnswer, bool isApproved, bool assignMemberRole = false)
        {
            UserManager        userManager    = UserManager.GetManager();
            UserProfileManager profileManager = UserProfileManager.GetManager();
            var userMangagerSecurityChek      = userManager.Provider.SuppressSecurityChecks;
            var profileMangagerSecurityChek   = profileManager.Provider.SuppressSecurityChecks;
            MembershipCreateStatus status;

            try
            {
                userManager.Provider.SuppressSecurityChecks    = true;
                profileManager.Provider.SuppressSecurityChecks = true;
                User user = userManager.CreateUser(username, password, mail, secretQuestion, secretAnswer, isApproved, null, out status);

                if (status == MembershipCreateStatus.Success)
                {
                    SitefinityProfile sfProfile = profileManager.CreateProfile(user, Guid.NewGuid(), typeof(SitefinityProfile)) as SitefinityProfile;

                    if (sfProfile != null)
                    {
                        sfProfile.FirstName = firstName;
                        sfProfile.LastName  = lastName;
                        sfProfile.SetValue("PhoneNumber", phoneNumber);
                    }

                    userManager.SaveChanges();
                    profileManager.RecompileItemUrls(sfProfile);
                    profileManager.SaveChanges();

                    if (assignMemberRole)
                    {
                        AssisgnUserRole(user, "Member");
                    }
                }
            }
            finally // Reset the security check
            {
                userManager.Provider.SuppressSecurityChecks    = userMangagerSecurityChek;
                profileManager.Provider.SuppressSecurityChecks = profileMangagerSecurityChek;
            }

            return(status);
        }
        /// <summary>
        /// Updates the users Sitefinity profile.
        /// </summary>
        /// <param name="username">Id of the user to update.</param>
        /// <param name="settings">Gigya module settings for this site.</param>
        /// <param name="gigyaModel">Deserialized Gigya JSON object.</param>
        protected virtual bool MapProfileFieldsAndUpdate(string currentUsername, string updatedUsername, IGigyaModuleSettings settings, dynamic gigyaModel, List <MappingField> mappingFields)
        {
            UserProfileManager profileManager = UserProfileManager.GetManager();
            UserManager        userManager    = UserManager.GetManager();

            using (new ElevatedModeRegion(userManager))
            {
                var user = userManager.GetUser(currentUsername);
                user.Email = GetMappedFieldWithFallback(gigyaModel, Constants.SitefinityFields.Email, Constants.GigyaFields.Email, mappingFields);

                if (user.UserName != updatedUsername)
                {
                    user.SetUserName(updatedUsername);
                }

                SitefinityProfile profile = profileManager.GetUserProfile <SitefinityProfile>(user);

                if (profile == null)
                {
                    profile = profileManager.CreateProfile(user, Guid.NewGuid(), typeof(SitefinityProfile)) as SitefinityProfile;

                    // only set this on creation as it's possible to get 2 users with the same email address
                    profile.Nickname = user.Email;
                }

                // map any custom fields
                MapProfileFields(profile, gigyaModel, settings, mappingFields);

                try
                {
                    userManager.SaveChanges();
                    profileManager.SaveChanges();
                    return(true);
                }
                catch (Exception e)
                {
                    _logger.Error("Failed to update profile for userId: " + currentUsername, e);
                }
            }

            return(false);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Changes the profile avatar.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <param name="image">The profile image.</param>
        /// <param name="userProfileManager">The user profile manager.</param>
        private void ChangeProfileAvatar(Guid userId, Image image, UserProfileManager userProfileManager)
        {
            User user = SecurityManager.GetUser(userId);

            if (user != null && image != null)
            {
                SitefinityProfile profile = userProfileManager.GetUserProfile <SitefinityProfile>(user);

                if (profile != null)
                {
                    ContentLink avatarLink = ContentLinksExtensions.CreateContentLink(profile, image);

                    profile.Avatar = avatarLink;

                    // Setting the Avatar does not modify the actual Profile persistent object and cache entries that depend on the Profile are not invalidated.
                    // By setting another property of the Profile we force all cache entries that depend ot this profile to be invalidated.
                    profile.LastModified = DateTime.UtcNow;
                }
            }
        }
Exemplo n.º 12
0
        public void UserCreating(UserCreating eventinfo)
        {
            UserProfileManager userProfileManager = UserProfileManager.GetManager();
            SitefinityProfile  profile            = userProfileManager.GetUserProfile(eventinfo.User.Id, typeof(SitefinityProfile).FullName) as SitefinityProfile;


            JXTNext_MemberRegister memberReg = new JXTNext_MemberRegister
            {
                Email     = eventinfo.Email,
                FirstName = profile.FirstName,
                LastName  = profile.LastName,
                Password  = eventinfo.User.FirstName
            };

            bool registerSuccess = _businessLogicsConnector.MemberRegister(memberReg, out string errorMessage);

            if (!registerSuccess)
            {
                //eventinfo.IsApproved = false;
            }
        }
        public void ProfileCreated(ProfileCreated eventinfo)
        {
            UserManager userManager = UserManager.GetManager();

            Telerik.Sitefinity.Security.Model.User user = userManager.GetUser(eventinfo.UserId);

            UserProfileManager userProfileManager = UserProfileManager.GetManager();
            SitefinityProfile  profile            = userProfileManager.GetUserProfile(user, eventinfo.ProfileType) as SitefinityProfile;

            // user.ExternalProviderName is null means registrating through normal registration
            // Otherwise registring through External provider like LinkedIn, Facebook, etc...
            // In case external provider, we will recieve the password as null but JXTNext Member database table requires
            // password should not be empty, so generating some random password of 8 characters length.
            JXTNext_MemberRegister memberReg = new JXTNext_MemberRegister
            {
                Email     = user.Email,
                FirstName = profile.FirstName,
                LastName  = profile.LastName,
                Password  = user.ExternalProviderName.IsNullOrEmpty() ? user.Password : GeneralHelper.GeneratePassword(8)
            };

            IEnumerable <IJobListingMapper> jobListingMappers = new List <IJobListingMapper> {
                new JXTNext_JobListingMapper()
            };
            IEnumerable <IMemberMapper> memberMappers = new List <IMemberMapper> {
                new JXTNext_MemberMapper()
            };
            IRequestSession requestSession = new SFEventRequestSession {
                UserEmail = user.Email
            };

            IBusinessLogicsConnector connector = new JXTNextBusinessLogicsConnector(jobListingMappers, memberMappers, requestSession);
            bool registerSuccess = connector.MemberRegister(memberReg, out string errorMessage);

            if (!registerSuccess)
            {
                //eventinfo.IsApproved = false;
            }
        }
Exemplo n.º 14
0
        private void UpdateUser(string dataProviderName, string externalProviderName, string email, string externalId, string firstName, string lastName)
        {
            // Start transaction
            Guid   guid            = Guid.NewGuid();
            string transactionName = string.Concat("ExternalLoginUpdateUserTransaction", guid.ToString());

            UserManager userManager = UserManager.GetManager(dataProviderName, transactionName);
            var         user        = userManager.GetUser(email);

            if (user == null)
            {
                return;
            }
            bool updateIsRequired = false;

            if (user.ExternalProviderName != externalProviderName)
            {
                user.ExternalProviderName = externalProviderName;
                updateIsRequired          = true;
            }
            if (user.ExternalId != externalId)
            {
                user.ExternalId  = externalId;
                updateIsRequired = true;
            }

            // Update user roles
            List <string> autoAssignedRoles = (
                from s in Config.Get <AuthenticationConfig>().SecurityTokenService
                .AuthenticationProviders[externalProviderName].AutoAssignedRoles
                .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                select s.Trim()).ToList();

            RoleManager roleManager = RoleManager.GetManager(string.Empty, transactionName);
            List <Role> roles       = roleManager.GetRoles().ToList();

            foreach (string newRole in autoAssignedRoles.Distinct())
            {
                Role role = (
                    from r in roles
                    where r.Name == newRole
                    select r).FirstOrDefault();

                if (role == null)
                {
                    continue;
                }
                roleManager.AddUserToRole(user, role);
                updateIsRequired = true;
            }

            // Update user profile
            UserProfileManager profileManager = UserProfileManager.GetManager(string.Empty, transactionName);
            SitefinityProfile  userProfile    = profileManager.GetUserProfile <SitefinityProfile>(user) ??
                                                profileManager.CreateProfile(user,
                                                                             "Telerik.Sitefinity.Security.Model.SitefinityProfile") as
                                                SitefinityProfile;

            if (userProfile != null)
            {
                userProfile.FirstName = firstName;
                userProfile.LastName  = lastName;
                updateIsRequired      = true;
            }

            // Commit transaction
            if (updateIsRequired)
            {
                profileManager.RecompileItemUrls(userProfile);
                TransactionManager.CommitTransaction(transactionName);
            }
        }
Exemplo n.º 15
0
        protected User GetOrCreateSitefinityUser(ImisResponse data)
        {
            UserManager uMan = UserManager.GetManager();

            uMan.Provider.SuppressSecurityChecks = true;
            UserProfileManager upMan = UserProfileManager.GetManager();

            upMan.Provider.SuppressSecurityChecks = true;

            var sfUser = uMan.GetUser(this.UserName);

            if (sfUser == null)
            {
                var randomPassword = Membership.GeneratePassword(8, 0);
                MembershipCreateStatus status;
                sfUser = uMan.CreateUser(this.UserName, randomPassword, data.Email, "", "", true, null, out status);
                if (status == MembershipCreateStatus.Success)
                {
                    SitefinityProfile sfProfile = upMan.CreateProfile(sfUser, Guid.NewGuid(), typeof(SitefinityProfile)) as SitefinityProfile;
                    if (sfProfile != null)
                    {
                        sfProfile.FirstName = data.FirstName;
                        sfProfile.LastName  = data.LastName;
                        sfProfile.SetValue("ImisId", data.ImisId);
                        sfProfile.SetValue("MiddleName", data.MiddleName);
                        sfProfile.SetValue("MemberType", data.MemberType);
                        sfProfile.SetValue("Status", data.Status);
                    }
                    uMan.SaveChanges();
                    upMan.RecompileItemUrls(sfProfile);
                    upMan.SaveChanges();

                    var roleManager = RoleManager.GetManager();
                    roleManager.Provider.SuppressSecurityChecks = true;
                    var memberRole = roleManager.GetRole("Member");
                    roleManager.AddUserToRole(sfUser, memberRole);

                    if (data.MemberType.ToLower() == "m" || data.MemberType.ToLower() == "staff")
                    {
                        var activeMemberRole = roleManager.GetRole("SSO Member");
                        roleManager.AddUserToRole(sfUser, activeMemberRole);
                    }

                    roleManager.SaveChanges();
                }
                // Log the status if the create failed
            }
            else
            {
                var sfProfile   = upMan.GetUserProfile <SitefinityProfile>(sfUser);
                var saveChanges = false;
                if (sfProfile.FirstName != data.FirstName)
                {
                    sfProfile.FirstName = data.FirstName;
                    saveChanges         = true;
                }
                if (sfProfile.LastName != data.LastName)
                {
                    sfProfile.LastName = data.LastName;
                    saveChanges        = true;
                }
                if (sfProfile.GetValue <String>("MiddleName") != data.MiddleName)
                {
                    sfProfile.SetValue("MiddleName", data.MiddleName);
                    saveChanges = true;
                }
                if (sfProfile.GetValue <String>("ImisId") != data.ImisId)
                {
                    sfProfile.SetValue("ImisId", data.ImisId);
                    saveChanges = true;
                }
                if (sfProfile.GetValue <String>("MemberType") != data.MemberType)
                {
                    sfProfile.SetValue("MemberType", data.MemberType);
                    saveChanges = true;
                }
                if (sfProfile.GetValue <String>("Status") != data.Status)
                {
                    sfProfile.SetValue("Status", data.Status);
                    saveChanges = true;
                }

                var roleManager = RoleManager.GetManager();
                roleManager.Provider.SuppressSecurityChecks = true;
                var activeMemberRole = roleManager.GetRole("SSO Member");
                if (data.MemberType.ToLower() == "m" || data.MemberType.ToLower() == "staff")
                {
                    roleManager.AddUserToRole(sfUser, activeMemberRole);
                }
                else
                {
                    roleManager.RemoveUserFromRole(sfUser, activeMemberRole);
                }
                roleManager.SaveChanges();

                if (saveChanges)
                {
                    upMan.RecompileItemUrls(sfProfile);
                    upMan.SaveChanges();
                }
            }

            return(sfUser);
        }
Exemplo n.º 16
0
        public ActionResult Details(SitefinityProfile user)
        {
            var fullTemplateName = this.detailTemplateNamePrefix + this.DetailTemplateName;

            var viewModel = this.Model.CreateDetailsViewModel(user);
            if (SystemManager.CurrentHttpContext != null)
                this.AddCacheDependencies(this.Model.GetKeysOfDependentObjects(viewModel));

            return this.View(fullTemplateName, viewModel);
        }
Exemplo n.º 17
0
        protected void ExportButton_Click(object sender, EventArgs e)
        {
            string format = ExportTypeDropDown.SelectedValue;

            DataTable selectedUsers = new DataTable("SU");

            selectedUsers.Columns.Add("UserID");
            selectedUsers.Columns.Add("DisplayName");
            selectedUsers.Columns.Add("Email");
            selectedUsers.Columns.Add("Username");

            foreach (GridViewRow row in SitefinityUsersGridView.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    CheckBox chkRow = (row.Cells[0].FindControl("SelectedCheckBox") as CheckBox);
                    if (chkRow.Checked)
                    {
                        string email   = SitefinityUsersGridView.DataKeys[row.RowIndex].Value.ToString();
                        var    userMan = UserManager.GetManager();
                        User   user    = userMan.GetUserByEmail(email);

                        UserProfileManager profileManager = UserProfileManager.GetManager();
                        SitefinityProfile  profile        = profileManager.GetUserProfile <SitefinityProfile>(user);

                        DataRow dr;
                        dr                = selectedUsers.NewRow();
                        dr["UserID"]      = user.Id;
                        dr["DisplayName"] = profile.FirstName + " " + profile.LastName;
                        dr["Email"]       = user.Email;
                        dr["Username"]    = user.UserName;
                        selectedUsers.Rows.Add(dr);
                    }
                }
            }

            if (selectedUsers.Rows.Count == 0)
            {
                NoRowSelectedErrorDiv.Visible = true;
            }
            else
            {
                // Check for license and apply if exists
                string licenseFile = Server.MapPath("~/App_Data/Aspose.Words.lic");
                if (File.Exists(licenseFile))
                {
                    License license = new License();
                    license.SetLicense(licenseFile);
                }

                string content_header_rich = "<tr><th>UserID</th><th>Display Name</th><th>Email</th><th>Username</th></tr>";
                string content_rows_rich   = "";


                foreach (DataRow user in selectedUsers.Rows)
                {
                    content_rows_rich = string.Concat(content_rows_rich, "<tr><td>" + user["UserID"].ToString() + "</td><td>" + user["DisplayName"].ToString() + "</td><td>" + user["Email"].ToString() + "</td><td>" + user["Username"].ToString() + "</td></tr>");
                }

                string content_rich = "<html><h2>Exported Users</h2><table width=\"100%\" style='border: 1px solid black; border-collapse: collapse;' >" + content_header_rich + content_rows_rich + "</table></html>";
                string fileName     = System.Guid.NewGuid().ToString() + "." + format;

                if (format != "txt")
                {
                    MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(content_rich));
                    Document     doc    = new Document(stream);
                    doc.Save(Response, fileName, ContentDisposition.Inline, null);
                    Response.End();
                }
                else
                {
                    Document        doc     = new Document();
                    DocumentBuilder builder = new DocumentBuilder(doc);

                    string delim = "\t";

                    builder.Writeln("UserID" + delim + "DisplayName" + delim + "Email" + delim + "Username");

                    foreach (DataRow user in selectedUsers.Rows)
                    {
                        string row = user["UserID"].ToString() + delim + user["DisplayName"].ToString() + delim + user["Email"].ToString() + delim + user["Username"].ToString();
                        builder.Writeln(row);
                    }


                    doc.Save(this.Response, fileName, ContentDisposition.Attachment, GetSaveFormat(format));
                    Response.End();
                }
            }
        }
Exemplo n.º 18
0
        protected void ExportButton_Click(object sender, EventArgs e)
        {
            string format = ExportTypeDropDown.SelectedValue;

            DataTable selectedUsers = new DataTable("SU");

            selectedUsers.Columns.Add("UserID");
            selectedUsers.Columns.Add("DisplayName");
            selectedUsers.Columns.Add("Email");
            selectedUsers.Columns.Add("Username");

            foreach (GridViewRow row in SitefinityUsersGridView.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    CheckBox chkRow = (row.Cells[0].FindControl("SelectedCheckBox") as CheckBox);
                    if (chkRow.Checked)
                    {
                        string email   = SitefinityUsersGridView.DataKeys[row.RowIndex].Value.ToString();
                        var    userMan = UserManager.GetManager();
                        User   user    = userMan.GetUserByEmail(email);

                        UserProfileManager profileManager = UserProfileManager.GetManager();
                        SitefinityProfile  profile        = profileManager.GetUserProfile <SitefinityProfile>(user);

                        DataRow dr;
                        dr                = selectedUsers.NewRow();
                        dr["UserID"]      = user.Id;
                        dr["DisplayName"] = profile.FirstName + " " + profile.LastName;
                        dr["Email"]       = user.Email;
                        dr["Username"]    = user.UserName;
                        selectedUsers.Rows.Add(dr);
                    }
                }
            }

            if (selectedUsers.Rows.Count == 0)
            {
                NoRowSelectedErrorDiv.Visible = true;
            }
            else
            {
                // Check for license and apply if exists
                string licenseFile = Server.MapPath("~/App_Data/Aspose.Cells.lic");
                if (File.Exists(licenseFile))
                {
                    License license = new License();
                    license.SetLicense(licenseFile);
                }

                //Instantiate a new Workbook
                Workbook book = new Workbook();
                //Clear all the worksheets
                book.Worksheets.Clear();
                //Add a new Sheet "Data";
                Worksheet sheet = book.Worksheets.Add("Sitefinity Users");

                //We pick a few columns not all to import to the worksheet
                sheet.Cells.ImportDataTable(selectedUsers, true, "A1");

                Worksheet worksheet = book.Worksheets[0];

                ApplyCellStyle(ref worksheet, "A1");
                ApplyCellStyle(ref worksheet, "B1");
                ApplyCellStyle(ref worksheet, "C1");
                ApplyCellStyle(ref worksheet, "D1");

                worksheet.Cells.InsertRow(0);
                worksheet.Cells.InsertColumn(0);

                worksheet.AutoFitColumns();

                string fileName = System.Guid.NewGuid().ToString() + "." + format;

                book.Save(this.Response, fileName, ContentDisposition.Attachment, GetSaveFormat(format));
                Response.End();
            }
        }