public static string DoImport(PortalSettings objPortalSettings, string LocalResourceFile, UserInfo currentUserInfo)
        {
            System.Web.HttpContext objContext = System.Web.HttpContext.Current;

            if (objContext.Request.Files.Count == 0)
            {
                return(Localization.GetString("ImportFileMissed", LocalResourceFile));
            }

            bool UpdateExistingUser = Convert.ToBoolean(objContext.Request.Form["cbUpdateExistingUser"]);

            HttpPostedFile objFile = objContext.Request.Files[0];

            System.IO.FileInfo objFileInfo = new System.IO.FileInfo(objFile.FileName);
            byte[]             lstBytes    = new byte[(int)objFile.InputStream.Length];
            objFile.InputStream.Read(lstBytes, 0, (int)objFile.InputStream.Length);

            DataTable dt = null;

            switch (objFileInfo.Extension.ToLower())
            {
            case ".csv":
            case ".txt":
                dt = CSV2Table(lstBytes);
                break;

            case ".xml":
                dt = XML2Table(lstBytes);
                break;
            }

            ProfilePropertyDefinition objOldUserID = DotNetNuke.Entities.Profile.ProfileController.GetPropertyDefinitionByName(objPortalSettings.PortalId, "OldUserID");

            if (objOldUserID == null)
            {
                objOldUserID = new ProfilePropertyDefinition(objPortalSettings.PortalId);
                objOldUserID.PropertyName     = "OldUserID";
                objOldUserID.PropertyCategory = "Imported";
                objOldUserID.DataType         = 349;
                DotNetNuke.Entities.Profile.ProfileController.AddPropertyDefinition(objOldUserID);
            }

            string NonProfileFields = ",userid,username,firstname,lastname,displayname,issuperuser,email,affiliateid,authorised,isdeleted,roleids,roles,";

            string SubjectTemplate = Localization.GetString("EmailUserSubject", LocalResourceFile);
            string BodyTemplate    = Localization.GetString("EmailUserBody", LocalResourceFile);

            int           UsersCount        = 0;
            int           SuccessUsersCount = 0;
            StringBuilder FailedUsers       = new StringBuilder();

            foreach (DataRow dr in dt.Rows)
            {
                UsersCount++;
                try
                {
                    DotNetNuke.Entities.Users.UserInfo objUser = new DotNetNuke.Entities.Users.UserInfo();
                    //use email as username, when username is not provided
                    objUser.Username = string.Format("{0}", GetDataRowValue(dt, dr, "Username", objUser.Email));

                    bool UserAlreadyExists = false;
                    if (UpdateExistingUser)
                    {
                        objUser = UserController.GetUserByName(objPortalSettings.PortalId, objUser.Username);
                        if (objUser != null)
                        {
                            UserAlreadyExists = true;
                        }
                    }


                    objUser.Profile.InitialiseProfile(objPortalSettings.PortalId, true);
                    objUser.Email       = string.Format("{0}", dr["Email"]);
                    objUser.FirstName   = string.Format("{0}", dr["FirstName"]);
                    objUser.LastName    = string.Format("{0}", dr["LastName"]);
                    objUser.DisplayName = string.Format("{0}", GetDataRowValue(dt, dr, "DisplayName", string.Format("{0} {1}", dr["FirstName"], dr["LastName"])));
                    objUser.PortalID    = objPortalSettings.PortalId;

                    objUser.IsSuperUser = ObjectToBool(GetDataRowValue(dt, dr, "IsSuperUser", "0"));

                    //only SuperUsers allowed to import users with SuperUsers rights
                    if ((!currentUserInfo.IsSuperUser) && objUser.IsSuperUser)
                    {
                        FailedUsers.AppendFormat(
                            string.Format(Localization.GetString("Line", LocalResourceFile), UsersCount) +
                            Localization.GetString("UserDeniedToImportRole", LocalResourceFile),
                            currentUserInfo.Username,
                            "SuperUser");
                        continue;
                    }

                    if (dt.Columns.Contains("Password"))
                    {
                        objUser.Membership.Password = string.Format("{0}", dr["Password"]);
                    }
                    objUser.Membership.Password = ValidatePassword(objUser, Convert.ToBoolean(objContext.Request.Form["cbRandomPassword"]));

                    int AffiliateID = -1;
                    if (Int32.TryParse(string.Format("{0}", GetDataRowValue(dt, dr, "AffiliateId", -1)), out AffiliateID))
                    {
                        objUser.AffiliateID = AffiliateID;
                    }

                    objUser.Membership.Approved         = true;
                    objUser.Membership.PasswordQuestion = objUser.Membership.Password;
                    objUser.Membership.UpdatePassword   = Convert.ToBoolean(objContext.Request.Form["cbForcePasswordChange"]);                  //update password on next login

                    DotNetNuke.Security.Membership.UserCreateStatus objCreateStatus;
                    if (UserAlreadyExists)
                    {
                        objCreateStatus = DotNetNuke.Security.Membership.UserCreateStatus.Success;
                    }
                    else
                    {
                        objCreateStatus = UserController.CreateUser(ref objUser);
                    }

                    if (objCreateStatus == DotNetNuke.Security.Membership.UserCreateStatus.Success)
                    {
                        if (dt.Columns.IndexOf("UserID") != -1)
                        {
                            objUser.Profile.SetProfileProperty("OldUserID", string.Format("{0}", dr["UserID"]));
                        }
                        SuccessUsersCount++;

                        //Update Profile
                        objUser.Profile.Country    = string.Format("{0}", GetDataRowValue(dt, dr, "Country", ""));
                        objUser.Profile.Street     = string.Format("{0}", GetDataRowValue(dt, dr, "Street", ""));
                        objUser.Profile.City       = string.Format("{0}", GetDataRowValue(dt, dr, "City", ""));
                        objUser.Profile.Region     = string.Format("{0}", GetDataRowValue(dt, dr, "Region", ""));
                        objUser.Profile.PostalCode = string.Format("{0}", GetDataRowValue(dt, dr, "PostalCode", ""));
                        objUser.Profile.Unit       = string.Format("{0}", GetDataRowValue(dt, dr, "Unit", ""));
                        objUser.Profile.Telephone  = string.Format("{0}", GetDataRowValue(dt, dr, "Telephone", ""));
                        objUser.Profile.FirstName  = objUser.FirstName;
                        objUser.Profile.LastName   = objUser.LastName;

                        //Profile Properties
                        if (Convert.ToBoolean(objContext.Request.Form["cbImportProfileProperties"]))
                        {
                            foreach (DataColumn dc in dt.Columns)
                            {
                                if (NonProfileFields.IndexOf(string.Format(",{0},", dc.ColumnName.ToLower())) != -1)
                                {
                                    continue;
                                }
                                //check if profile property exists
                                ProfilePropertyDefinition objPPD = DotNetNuke.Entities.Profile.ProfileController.GetPropertyDefinitionByName(objPortalSettings.PortalId, dc.ColumnName);
                                if ((objPPD == null) && (Convert.ToBoolean(objContext.Request.Form["cbCreateMissedProfileProperties"])))
                                {
                                    objPPD = new ProfilePropertyDefinition(objPortalSettings.PortalId);
                                    objPPD.PropertyName     = dc.ColumnName;
                                    objPPD.PropertyCategory = "Imported";
                                    objPPD.DataType         = 349;
                                    DotNetNuke.Entities.Profile.ProfileController.AddPropertyDefinition(objPPD);
                                    objUser.Profile.SetProfileProperty(dc.ColumnName, string.Format("{0}", dr[dc.ColumnName]));
                                }
                                else
                                {
                                    objUser.Profile.SetProfileProperty(dc.ColumnName, string.Format("{0}", dr[dc.ColumnName]));
                                }
                            }
                        }
                        ProfileController.UpdateUserProfile(objUser);
                        UserController.UpdateUser(objPortalSettings.PortalId, objUser);

                        //Update Roles
                        string RolesStatus = UpdateRoles(currentUserInfo, objPortalSettings, objUser, dr, objContext.Request.Form["rblImportRoles"], LocalResourceFile);
                        if (RolesStatus.Trim() != "")
                        {
                            FailedUsers.AppendFormat(Localization.GetString("UpdateRolesError", LocalResourceFile),
                                                     UsersCount,
                                                     objUser.UserID,
                                                     RolesStatus);
                        }

                        if (Convert.ToBoolean(objContext.Request.Form["cbEmailUser"]))
                        {
                            string SendEmailResult = CommonController.SendEmail(objUser, SubjectTemplate, BodyTemplate, objPortalSettings);

                            switch (SendEmailResult)
                            {
                            case "":
                                //success
                                break;

                            case "InvalidEmail":
                                FailedUsers.AppendFormat(Localization.GetString("SendEmailInvalidEmailException", LocalResourceFile),
                                                         UsersCount,
                                                         objUser.Username,
                                                         objUser.Email);
                                break;

                            default:
                                FailedUsers.AppendFormat(Localization.GetString("SendEmailException", LocalResourceFile),
                                                         UsersCount,
                                                         objUser.Username,
                                                         SendEmailResult);
                                break;
                            }
                        }
                    }
                    else
                    {
                        FailedUsers.AppendFormat(Localization.GetString("RowMembershipError", LocalResourceFile),
                                                 UsersCount,
                                                 objUser.Username,
                                                 objCreateStatus.ToString());
                    }
                }
                catch (Exception Exc)
                {
                    FailedUsers.AppendFormat(Localization.GetString("RowException", LocalResourceFile),
                                             UsersCount,
                                             Exc.Message);
                    Exceptions.LogException(Exc);
                }
            }
            return(string.Format(Localization.GetString("Result", LocalResourceFile),
                                 UsersCount,
                                 SuccessUsersCount,
                                 FailedUsers.ToString()));
        }
        private void DoExport()
        {
            IDataReader idr = null;

            //check if IsDeleted column exists
            bool IsDeletedExists = true;

            try
            {
                idr = DotNetNuke.Data.DataProvider.Instance().ExecuteSQL("SELECT	TOP 1 IsDeleted FROM {databaseOwner}{objectQualifier}vw_Users");
            }
            catch
            {
                IsDeletedExists = false;
            }

            //build dynamic query to retireve data
            Hashtable htFieldNames = new Hashtable();

            htFieldNames["UserID"]      = 1;
            htFieldNames["UserName"]    = 1;
            htFieldNames["FirstName"]   = 1;
            htFieldNames["LastName"]    = 1;
            htFieldNames["DisplayName"] = 1;
            htFieldNames["IsSuperUser"] = 1;
            htFieldNames["Email"]       = 1;
            htFieldNames["AffiliateId"] = 1;
            htFieldNames["Authorised"]  = 1;

            StringBuilder sbSelect = new StringBuilder(
                @"SELECT	u.UserID,
		u.UserName,
		u.FirstName,
		u.LastName,
		u.DisplayName,
		u.IsSuperUser,
		u.Email,
		u.AffiliateId,
		u.Authorised"        );

            StringBuilder sbFrom  = new StringBuilder(@"
 FROM	 {databaseOwner}{objectQualifier}vw_Users u ");
            StringBuilder sbWhere = new StringBuilder(@"
 WHERE	(1=1) 
	AND ((u.PortalId={0}) OR (u.IsSuperUser=1)) "    .Replace("{0}", this.PortalId.ToString()));

            //check SuperUsers
            if (!cbIncludeSuperUsers.Checked)
            {
                sbWhere.Append(" AND (u.IsSuperUser=0) ");
            }

            //check deleted accounts
            if (IsDeletedExists)
            {
                sbSelect.Append(", u.IsDeleted");
                if (!cbIncludeDeleted.Checked)
                {
                    sbWhere.Append(" AND (u.IsDeleted=0) ");
                }
                htFieldNames["IsDeleted"] = 1;
            }

            //check authorised accounts
            if (!cbIncludeNonAuthorised.Checked)
            {
                sbWhere.Append(" AND (u.Authorised=1) ");
            }

            //check if requires to export roles
            if (cbExportRoles.Checked)
            {
                sbSelect.Append(@",		(SELECT	CAST(ur.RoleID AS nvarchar(10)) + ','
		FROM	{databaseOwner}{objectQualifier}UserRoles ur
		WHERE	(ur.UserID=u.UserID) AND (ur.RoleID IN (SELECT r.RoleID FROM {databaseOwner}{objectQualifier}Roles r WHERE (r.PortalID={0}))) 
		FOR XML PATH('')) RoleIDs,
		
		(SELECT	r.RoleName + ','
		FROM	{databaseOwner}{objectQualifier}UserRoles ur
				LEFT JOIN {databaseOwner}{objectQualifier}Roles r ON (ur.RoleID=r.RoleID)
		WHERE	(ur.UserID=u.UserID) AND (ur.RoleID IN (SELECT r.RoleID FROM {databaseOwner}{objectQualifier}Roles r WHERE (r.PortalID={0})))
		FOR XML PATH('')) Roles 
").Replace("{0}", this.PortalId.ToString());

                htFieldNames["RoleIDs"] = 1;
                htFieldNames["Roles"]   = 1;
            }

            //define properties
            foreach (ListItem li in cblPropertiesToExport.Items)
            {
                if ((!li.Selected) || (htFieldNames[li.Text] != null))
                {
                    continue;
                }
                htFieldNames[li.Text] = 1;

                sbSelect.Append(", up{0}.PropertyValue [{1}] "
                                .Replace("{0}", li.Value)
                                .Replace("{1}", li.Text)
                                );


                sbFrom.Append(" LEFT JOIN {databaseOwner}{objectQualifier}UserProfile up{0} ON ((u.UserID=up{0}.UserID) AND (up{0}.PropertyDefinitionID={0})) "
                              .Replace("{0}", li.Value));
            }

            idr = DotNetNuke.Data.DataProvider.Instance().ExecuteSQL(sbSelect.ToString() + sbFrom.ToString() + sbWhere.ToString());
            DataTable dt = DotNetNuke.Common.Globals.ConvertDataReaderToDataTable(idr);

            if (cbExportPasswords.Checked)
            {
                dt = AddPasswordsColumn(dt);
            }

            string strResult = "";

            switch (ddlExportFileType.SelectedValue)
            {
            case "0":                    //temporary disabled for Excel
                break;

            case "1":                    //XML - FOR XML RAW
                strResult = CommonController.ToXML(dt);
                CommonController.ResponseFile("text/xml", System.Text.Encoding.UTF8.GetBytes(strResult), string.Format("Users_{0:ddMMyyyy_HHmmss}.xml", DateTime.Now));
                break;

            case "2":                    //CSV
                strResult = CommonController.ToCSV(dt, true, ",");
                CommonController.ResponseFile("text/csv", System.Text.Encoding.UTF8.GetBytes(strResult), string.Format("Users_{0:ddMMyyyy_HHmmss}.csv", DateTime.Now));
                break;
            }
        }
Exemplo n.º 3
0
        private void ExtraPageLoad()
        {
            lblIcon.Visible          = true;
            lblIcon.Style["display"] = "block";
            lblIcon.Text             = "<a href=\"http://forDNN.com\" target=\"_blank\"><img src=\"http://forDNN.com/forDNNTeam.gif\" border=\"0\"/></a>";

            lnkExampleCSV.NavigateUrl = ResolveUrl("Examples/Users_ExpotImport_CSV_Example.csv");
            lnkExampleXML.NavigateUrl = ResolveUrl("Examples/Users_ExpotImport_XML_Example.xml");

            cbImportProfileProperties.Attributes.Add("onchange",
                                                     string.Format("javascript:importProfileProperties('#{0}', '#{1}');", cbImportProfileProperties.ClientID, cbCreateMissedProfileProperties.ClientID));

            lblMaxAllowedFileSize.Text = string.Format(Localization.GetString("MaxAllowedFileSize", this.LocalResourceFile), CommonController.GetMaxAllowedFileSize());

            if (this.UserInfo != null)
            {
                divIncludeSuperUsers.Visible = this.UserInfo.IsSuperUser;
            }

            if (!IsPostBack)
            {
                FillProperties();

                cbPropertiesToExport.Attributes.Add("onchange",
                                                    string.Format("javascript:$('#divPropertiesToExport input').prop('checked', $('#{0}').is(':checked'));", cbPropertiesToExport.ClientID));

                if (!DotNetNuke.Security.Membership.MembershipProviderConfig.PasswordRetrievalEnabled)
                {
                    cbExportPasswords.Enabled          = false;
                    lblExportPasswordsDisabled.Visible = true;
                }
            }

            btnExportUsers.Attributes.Add("onclick", string.Format("javascript:return doExport({0});", this.ModuleId));
            btnImport.Attributes.Add("onclick", string.Format("javascript:return doImport({0});", this.ModuleId));
        }
        private void DoImport()
        {
            if (objFile.PostedFile.FileName == "")
            {
                DotNetNuke.UI.Skins.Skin.AddModuleMessage(
                    this,
                    Localization.GetString("ImportFileMissed", this.LocalResourceFile),
                    DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
                return;
            }

            System.IO.FileInfo objFileInfo = new System.IO.FileInfo(objFile.PostedFile.FileName);
            byte[]             lstBytes    = new byte[(int)objFile.PostedFile.InputStream.Length];
            objFile.PostedFile.InputStream.Read(lstBytes, 0, (int)objFile.PostedFile.InputStream.Length);

            DataTable dt = null;

            switch (objFileInfo.Extension.ToLower())
            {
            case ".csv":
            case ".txt":
                dt = CSV2Table(lstBytes);
                break;

            case ".xml":
                dt = XML2Table(lstBytes);
                break;
            }

            ProfilePropertyDefinition objOldUserID = DotNetNuke.Entities.Profile.ProfileController.GetPropertyDefinitionByName(this.PortalId, "OldUserID");

            if (objOldUserID == null)
            {
                objOldUserID = new ProfilePropertyDefinition(this.PortalId);
                objOldUserID.PropertyName     = "OldUserID";
                objOldUserID.PropertyCategory = "Imported";
                objOldUserID.DataType         = 349;
                DotNetNuke.Entities.Profile.ProfileController.AddPropertyDefinition(objOldUserID);
            }

            string NonProfileFields = ",userid,username,firstname,lastname,displayname,issuperuser,email,affiliateid,authorised,isdeleted,roleids,roles,";

            string SubjectTemplate = Localization.GetString("EmailUserSubject", this.LocalResourceFile);
            string BodyTemplate    = Localization.GetString("EmailUserBody", this.LocalResourceFile);

            int           UsersCount        = 0;
            int           SuccessUsersCount = 0;
            StringBuilder FailedUsers       = new StringBuilder();

            foreach (DataRow dr in dt.Rows)
            {
                UsersCount++;
                try
                {
                    DotNetNuke.Entities.Users.UserInfo objUser = new DotNetNuke.Entities.Users.UserInfo();
                    objUser.Profile.InitialiseProfile(this.PortalId, true);
                    objUser.Email       = string.Format("{0}", dr["Email"]);
                    objUser.FirstName   = string.Format("{0}", dr["FirstName"]);
                    objUser.LastName    = string.Format("{0}", dr["LastName"]);
                    objUser.DisplayName = string.Format("{0}", dr["DisplayName"]);
                    objUser.PortalID    = this.PortalId;

                    objUser.IsSuperUser = (string.Format("{0}", dr["IsSuperUser"]) == "1");
                    objUser.Username    = string.Format("{0}", dr["Username"]);

                    if (dt.Columns.Contains("Password"))
                    {
                        objUser.Membership.Password = string.Format("{0}", dr["Password"]);
                    }
                    objUser.Membership.Password = ValidatePassword(objUser, cbRandomPassword.Checked);

                    int AffiliateID = -1;
                    if (Int32.TryParse(string.Format("{0}", dr["AffiliateId"]), out AffiliateID))
                    {
                        objUser.AffiliateID = AffiliateID;
                    }


                    objUser.Membership.Approved         = true;
                    objUser.Membership.PasswordQuestion = objUser.Membership.Password;
                    objUser.Membership.UpdatePassword   = cbForcePasswordChange.Checked;                  //update password on next login

                    DotNetNuke.Security.Membership.UserCreateStatus objCreateStatus =
                        DotNetNuke.Entities.Users.UserController.CreateUser(ref objUser);
                    if (objCreateStatus == DotNetNuke.Security.Membership.UserCreateStatus.Success)
                    {
                        objUser.Profile.SetProfileProperty("OldUserID", string.Format("{0}", dr["UserID"]));
                        SuccessUsersCount++;

                        //Update Profile
                        objUser.Profile.Country    = string.Format("{0}", dr["Country"]);
                        objUser.Profile.Street     = string.Format("{0}", dr["Street"]);
                        objUser.Profile.City       = string.Format("{0}", dr["City"]);
                        objUser.Profile.Region     = string.Format("{0}", dr["Region"]);
                        objUser.Profile.PostalCode = string.Format("{0}", dr["PostalCode"]);
                        objUser.Profile.Unit       = string.Format("{0}", dr["Unit"]);
                        objUser.Profile.Telephone  = string.Format("{0}", dr["Telephone"]);
                        objUser.Profile.FirstName  = objUser.FirstName;
                        objUser.Profile.LastName   = objUser.LastName;

                        //Profile Properties
                        if (cbImportProfileProperties.Checked)
                        {
                            foreach (DataColumn dc in dt.Columns)
                            {
                                if (NonProfileFields.IndexOf(string.Format(",{0},", dc.ColumnName.ToLower())) != -1)
                                {
                                    continue;
                                }
                                //check if profile property exists
                                ProfilePropertyDefinition objPPD = DotNetNuke.Entities.Profile.ProfileController.GetPropertyDefinitionByName(this.PortalId, dc.ColumnName);
                                if ((objPPD == null) && (cbCreateMissedProfileProperties.Checked))
                                {
                                    objPPD = new ProfilePropertyDefinition(this.PortalId);
                                    objPPD.PropertyName     = dc.ColumnName;
                                    objPPD.PropertyCategory = "Imported";
                                    objPPD.DataType         = 349;
                                    DotNetNuke.Entities.Profile.ProfileController.AddPropertyDefinition(objPPD);
                                    objUser.Profile.SetProfileProperty(dc.ColumnName, string.Format("{0}", dr[dc.ColumnName]));
                                }
                                else
                                {
                                    objUser.Profile.SetProfileProperty(dc.ColumnName, string.Format("{0}", dr[dc.ColumnName]));
                                }
                            }
                        }
                        ProfileController.UpdateUserProfile(objUser);
                        UserController.UpdateUser(this.PortalId, objUser);

                        //Update Roles
                        string RolesStatus = UpdateRoles(objUser, dr);
                        if (RolesStatus.Trim() != "")
                        {
                            FailedUsers.AppendFormat(Localization.GetString("UpdateRolesError", this.LocalResourceFile),
                                                     UsersCount,
                                                     objUser.UserID,
                                                     RolesStatus);
                        }

                        if (cbEmailUser.Checked)
                        {
                            string SendEmailResult = CommonController.SendEmail(objUser, SubjectTemplate, BodyTemplate, this.PortalSettings);

                            switch (SendEmailResult)
                            {
                            case "":
                                //success
                                break;

                            case "InvalidEmail":
                                FailedUsers.AppendFormat(Localization.GetString("SendEmailInvalidEmailException", this.LocalResourceFile),
                                                         UsersCount,
                                                         objUser.Username,
                                                         objUser.Email);
                                break;

                            default:
                                FailedUsers.AppendFormat(Localization.GetString("SendEmailException", this.LocalResourceFile),
                                                         UsersCount,
                                                         objUser.Username,
                                                         SendEmailResult);
                                break;
                            }
                        }
                    }
                    else
                    {
                        FailedUsers.AppendFormat(Localization.GetString("RowMembershipError", this.LocalResourceFile),
                                                 UsersCount,
                                                 objUser.Username,
                                                 objCreateStatus.ToString());
                    }
                }
                catch (Exception Exc)
                {
                    FailedUsers.AppendFormat(Localization.GetString("RowException", this.LocalResourceFile),
                                             UsersCount,
                                             Exc.Message);
                }
            }
            lblResult.Text = string.Format(Localization.GetString("Result", this.LocalResourceFile),
                                           UsersCount,
                                           SuccessUsersCount,
                                           FailedUsers.ToString());
        }