forked from fordnn/usersexportimport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainControl.ascx.cs
650 lines (560 loc) · 19.1 KB
/
MainControl.ascx.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using DotNetNuke;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Entities.Users;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Profile;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.UI.UserControls;
using DotNetNuke.Security.Roles;
namespace forDNN.Modules.UsersExportImport
{
partial class MainControl : PortalModuleBase, IActionable
{
#region "Event Handlers"
private void FillProperties()
{
cblPropertiesToExport.DataSource = ProfileController.GetPropertyDefinitionsByPortal(this.PortalId);
cblPropertiesToExport.DataTextField = "PropertyName";
cblPropertiesToExport.DataValueField = "PropertyDefinitionId";
cblPropertiesToExport.DataBind();
}
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 (!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;
}
}
}
protected void Page_Load(object sender, System.EventArgs e)
{
try
{
ExtraPageLoad();
}
catch (Exception exc)
{
//Module failed to load
Exceptions.ProcessModuleLoadException(this, exc);
}
}
#endregion
#region Import
private DataTable CSV2Table(byte[] lstBytes)
{
string Separator = ",";
DataTable dt = new DataTable();
string strTable = System.Text.Encoding.UTF8.GetString(lstBytes);
string[] lstRows = strTable.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
if (lstRows.Length == 0)
{
return dt;
}
foreach (string Header in lstRows[0].Split(new char[] { ',' }))
{
dt.Columns.Add(Header);
}
for (int i = 1; (i < lstRows.Length - 1); i++)
{
ArrayList lstValues = new ArrayList();
string Value = lstRows[i];
bool WithinQuotes = false;
int k = 0;
StringBuilder SubValue = new StringBuilder();
while (k < Value.Length)
{
if (Value[k].ToString() == Separator)
{
//check is it new column
if (!WithinQuotes)
{
//yes, its new column
lstValues.Add(SubValue.ToString());
SubValue = new StringBuilder();
k++;
continue;
}
}
if (Value[k].ToString() == "\"")
{
//check is it begin/end of new string column or just quote char
if (k < Value.Length - 1)
{
if ((Value[k + 1].ToString() == "\""))
{
//this is quote char, replace it with single quote and move cursor next to it
SubValue.Append(Value[k]);
k++;
}
else
{
//this is begin/end of new string column - skip quote char and reverse WithinQuotes flag
WithinQuotes = !WithinQuotes;
}
}
}
else
{
SubValue.Append(Value[k]);
}
k++;
}
if (SubValue.ToString() != "")
{
lstValues.Add(SubValue.ToString());
}
//add new row to DataTable
DataRow dr = dt.NewRow();
for (k = 0; k < dt.Columns.Count; k++)
{
try
{
dr[k] = lstValues[k];
}
catch { }
}
dt.Rows.Add(dr);
}
return dt;
}
private DataTable XML2Table(byte[] lstBytes)
{
string strXML = System.Text.Encoding.UTF8.GetString(lstBytes);
System.Xml.XmlDocument objDoc = new System.Xml.XmlDocument();
objDoc.LoadXml(strXML);
DataTable dt = new DataTable();
bool RequireColumns = true;
foreach (System.Xml.XmlNode xmlUser in objDoc.DocumentElement.ChildNodes)
{
if (RequireColumns)
{
foreach (System.Xml.XmlAttribute xmlAttr in xmlUser.Attributes)
{
dt.Columns.Add(xmlAttr.Name);
}
RequireColumns = false;
}
DataRow dr = dt.NewRow();
foreach (System.Xml.XmlAttribute xmlAttr in xmlUser.Attributes)
{
dr[xmlAttr.Name] = xmlAttr.Value;
}
dt.Rows.Add(dr);
}
return dt;
}
private string ValidatePassword(UserInfo objUser, bool RandomPassword)
{
if (!RandomPassword)
{
objUser.Membership.Password = (objUser.Membership.Password == null) ? "" : objUser.Membership.Password;
if (UserController.ValidatePassword(objUser.Membership.Password))
{
return objUser.Membership.Password;
}
}
return UserController.GeneratePassword();
}
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());
}
private string UpdateRoles(UserInfo objUser, DataRow dr)
{
RoleController objRoleController = new RoleController();
bool ByID = false;
string Roles = "";
switch (rblImportRoles.SelectedValue)
{
case "0":
return "";
case "1":
ByID = true;
Roles = (string)dr["RoleIDs"];
break;
case "2":
Roles = (string)dr["Roles"];
break;
}
StringBuilder sb = new StringBuilder();
foreach (string Role in Roles.Split(new char[] { ',' }))
{
if (Role.Trim() == "")
{
continue;
}
RoleInfo objRole = null;
if (ByID)
{
int RoleID = -1;
if (Int32.TryParse(Role, out RoleID))
{
objRole = objRoleController.GetRole(RoleID, this.PortalId);
}
}
else
{
objRole = objRoleController.GetRoleByName(this.PortalId, Role);
}
if (objRole != null)
{
objRoleController.AddUserRole(this.PortalId, objUser.UserID, objRole.RoleID, Null.NullDate);
}
else
{
sb.AppendFormat(
ByID ? Localization.GetString("RoleIDNotFound", this.LocalResourceFile) : Localization.GetString("RoleNameNotFound", this.LocalResourceFile),
Role);
}
}
return sb.ToString();
}
protected void btnImport_Click(object sender, EventArgs e)
{
DoImport();
}
#endregion
#region Export
protected void btnExportUsers_Click(object sender, EventArgs e)
{
DoExport();
}
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;
}
}
private DataTable AddPasswordsColumn(DataTable dt)
{
dt.Columns.Add("Password", "".GetType());
foreach (DataRow dr in dt.Rows)
{
if (DotNetNuke.Security.Membership.MembershipProviderConfig.PasswordRetrievalEnabled)
{
UserInfo objUser = UserController.GetUserById(this.PortalId, (int)dr["userid"]);
dr["Password"] = UserController.GetPassword(ref objUser, objUser.Membership.PasswordAnswer);
}
else
{
dr["Password"] = "";
}
}
return dt;
}
#endregion
#region "Optional Interfaces"
/// -----------------------------------------------------------------------------
/// <summary>
/// Registers the module actions required for interfacing with the portal framework
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <history>
/// </history>
/// -----------------------------------------------------------------------------
public ModuleActionCollection ModuleActions
{
get
{
ModuleActionCollection Actions = new ModuleActionCollection();
//Actions.Add(GetNextActionID(), Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile),
// ModuleActionType.AddContent, "", "add.gif", EditUrl(), false, DotNetNuke.Security.SecurityAccessLevel.Edit,
// true, false);
return Actions;
}
}
#endregion
}
}