-
Notifications
You must be signed in to change notification settings - Fork 5
/
ImportExportService.cs
688 lines (633 loc) · 32.6 KB
/
ImportExportService.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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
using ExpressBase.Common;
using ExpressBase.Common.Data;
using ExpressBase.Common.LocationNSolution;
using ExpressBase.Common.Objects;
using ExpressBase.Common.ServerEvents_Artifacts;
using ExpressBase.Common.ServiceClients;
using ExpressBase.Objects;
using ExpressBase.Objects.Services;
using ExpressBase.Objects.ServiceStack_Artifacts;
using ExpressBase.Security.Core;
using ExpressBase.ServiceStack.Services;
using Newtonsoft.Json;
using ServiceStack;
using ServiceStack.Messaging;
using ServiceStack.Redis;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExpressBase.ServiceStack.Services
{
[Authenticate]
public class ImportExportService : EbMqBaseService
{
public ImportExportService(IMessageProducer _mqp, IMessageQueueClient _mqc, IEbServerEventClient _sec) : base(_mqp, _mqc, _sec)
{
}
public ExportApplicationResponse Post(ExportApplicationMqRequest request)
{
ExportApplicationResponse resp = new ExportApplicationResponse();
MessageProducer3.Publish(new ExportApplicationRequest
{
AppCollection = request.AppCollection,
PackageName = request.PackageName,
PackageDescription = request.PackageDescription,
PackageIcon = request.PackageIcon,
BToken = this.ServerEventClient.BearerToken,
RToken = this.ServerEventClient.RefreshToken,
SolnId = request.SolnId,
UserId = request.UserId,
UserAuthId = request.UserAuthId,
WhichConsole = request.WhichConsole,
MasterSoln = request.MasterSoln,
SubscriptionId = (!String.IsNullOrEmpty(this.ServerEventClient.Headers[Common.Constants.TokenConstants.SSE_SUBSCRIP_ID])) ? this.ServerEventClient.Headers[Common.Constants.TokenConstants.SSE_SUBSCRIP_ID] : String.Empty
});
Log.Info("ExportApplicationRequest published to Mq");
return resp;
}
public ImportApplicationResponse Post(ImportApplicationMqRequest request)
{
ImportApplicationResponse resp = new ImportApplicationResponse();
this.MessageProducer3.Publish(new ImportApplicationRequest
{
Id = request.Id,
Package = request.Package,
BToken = this.ServerEventClient.BearerToken,
RToken = this.ServerEventClient.RefreshToken,
SolnId = request.SolnId,
UserId = request.UserId,
UserAuthId = request.UserAuthId,
WhichConsole = request.WhichConsole,
IsDemoApp = request.IsDemoApp,
SelectedSolutionId = request.SelectedSolutionId,
SubscriptionId = (!String.IsNullOrEmpty(this.ServerEventClient.Headers[Common.Constants.TokenConstants.SSE_SUBSCRIP_ID])) ? this.ServerEventClient.Headers[Common.Constants.TokenConstants.SSE_SUBSCRIP_ID] : String.Empty
});
Log.Info("ImportApplicationRequest published to Mq");
return resp;
}
}
[Restrict(InternalOnly = true)]
public class ImportExportInternalService : EbMqBaseService
{
public DevRelatedServices Devservice;
public AppStoreService AppstoreService;
public EbObjectService Objservice;
public SecurityServices SecurityServices;
public NotificationService NotificationService;
private int counter = 0;
public ImportExportInternalService(IEbServerEventClient _sec) : base(_sec)
{
Devservice = base.ResolveService<DevRelatedServices>();
AppstoreService = base.ResolveService<AppStoreService>();
Objservice = base.ResolveService<EbObjectService>();
SecurityServices = base.ResolveService<SecurityServices>();
NotificationService = base.ResolveService<NotificationService>();
}
public void SetConnectionFactory(string solutionId, IRedisClient redis)
{
EbConnectionFactory _ebConnectionFactory = new EbConnectionFactory(solutionId, redis);
this.EbConnectionFactory = _ebConnectionFactory;
AppstoreService.EbConnectionFactory = _ebConnectionFactory;
Devservice.EbConnectionFactory = _ebConnectionFactory;
Objservice.EbConnectionFactory = _ebConnectionFactory;
SecurityServices.EbConnectionFactory = _ebConnectionFactory;
NotificationService.EbConnectionFactory = _ebConnectionFactory;
}
public string Post(ExportApplicationRequest request)
{
Log.Info("ExportApplicationRequest inside Mq");
ExportPackage package = new ExportPackage();
List<int> AppIdCollection = new List<int>();
List<string> ObjectIdCollection = new List<string>();
try
{
SetConnectionFactory(request.SolnId, this.Redis);
foreach (KeyValuePair<int, List<string>> _app in request.AppCollection)
{
AppIdCollection.Add(_app.Key);
OrderedDictionary ObjDictionary = new OrderedDictionary();
AppWrapper Appwrp = Devservice.Get(new GetApplicationRequest { Id = _app.Key }).AppInfo;
Appwrp.ObjCollection = new List<EbObject>();
foreach (string _refid in _app.Value)
GetRelated(_refid, ObjDictionary, request.SolnId);
ICollection ObjectList = ObjDictionary.Values;
foreach (object item in ObjectList)
{
Appwrp.ObjCollection.Add(item as EbObject);
ObjectIdCollection.Add((item as EbObject).RefId.Split("-")[3]);
}
package.Apps.Add(Appwrp);
}
Log.Info("Calling FillExportData");
SolutionType s_type = this.Redis.Get<Eb_Solution>(String.Format("solution_{0}", request.SolnId)).SolutionType;
if (s_type == SolutionType.REPLICA)
package.DataSet = ExportTablesToPkg(request.SolnId, ObjectIdCollection, AppIdCollection);
string packageJson = EbSerializers.Json_Serialize4AppWraper(package);
Log.Info("Serialized packageJson. Saving to appstore");
SaveToAppStoreResponse p = AppstoreService.Post(new SaveToAppStoreRequest
{
Store = new AppStore
{
Name = request.PackageName,
Cost = 10.00m,
Currency = "USD",
Json = packageJson,
Status = 1,
AppType = 1,
Description = request.PackageDescription,
Icon = request.PackageIcon,
MasterSoln = request.MasterSoln
},
SolnId = request.SolnId,
UserId = request.UserId,
UserAuthId = request.UserAuthId,
WhichConsole = request.WhichConsole
});
this.ServerEventClient.BearerToken = request.BToken;
this.ServerEventClient.RefreshToken = request.RToken;
this.ServerEventClient.RefreshTokenUri = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_GET_ACCESS_TOKEN_URL);
this.ServerEventClient.Post<NotifyResponse>(new NotifySingleSubscriptionRequest
{
//ToChannel = new string[] {"file-upload" },
Msg = "ExportApplication success",
Selector = "cmd.exportApplication",
ToSubscriptionId = request.SubscriptionId
});
try
{
NotifyByUserIDResponse NF = NotificationService.Post(new NotifyByUserIDRequest
{
Link = "/AppStore",
Title = $"Your application({request.PackageName}) export was successful",
UsersID = request.UserId,
User_AuthId = request.UserAuthId
});
}
catch (Exception ex)
{
Console.WriteLine("ExportApplication send notification" + ex.Message + ex.StackTrace);
}
Console.WriteLine("ExportApplication success");
}
catch (Exception e)
{
Console.WriteLine("ExportApplication" + e.Message + e.StackTrace);
}
return null;
}
public string Post(ImportApplicationRequest request)
{
Log.Info("ImportApplicationRequest inside Mq");
Dictionary<string, string> RefidMap = new Dictionary<string, string>();
GetOneFromAppstoreResponse packageresponse;
try
{
SetConnectionFactory(request.SelectedSolutionId, this.Redis);
if (request.Package is null)
{
packageresponse = AppstoreService.Get(new GetOneFromAppStoreRequest
{
Id = request.Id,
SolnId = request.SelectedSolutionId,
UserAuthId = request.UserAuthId,
UserId = request.UserId,
WhichConsole = request.WhichConsole
});
}
else
{
packageresponse = new GetOneFromAppstoreResponse { IsPublic = false, Package = request.Package };
}
if (packageresponse.Package?.Apps != null)
{
Dictionary<int, int> AppIdMAp = new Dictionary<int, int>();
Dictionary<int, KeyValuePair<int, int>> ObjectIdMAp = new Dictionary<int, KeyValuePair<int, int>>();
foreach (AppWrapper Application in packageresponse.Package.Apps)
{
if (Application.ObjCollection.Count > 0)
{
string ApplicationName = packageresponse.IsPublic ? packageresponse.Title : Application.Name;
int _currentAppId = CreateOrGetAppId(ApplicationName, Application);
if (!AppIdMAp.ContainsKey(Application.Id))
AppIdMAp.Add(Application.Id, _currentAppId);
else
Console.WriteLine("Duplication of appid in packge" + Application.Id + " - " + _currentAppId);
for (int i = Application.ObjCollection.Count - 1; i >= 0; i--)
{
EbObject obj = Application.ObjCollection[i];
if (!RefidMap.ContainsKey(obj.RefId))
{
obj.DisplayName = GetUniqDisplayName(obj.DisplayName);
obj.Name = GetProcessedName(obj.Name);
if (obj is EbWebForm)
(obj as EbWebForm).EbSid = obj.Name;
ObjectLifeCycleStatus _status = (request.IsDemoApp || !IsVersioned(request.SelectedSolutionId, request.UserId)) ? ObjectLifeCycleStatus.Live : ObjectLifeCycleStatus.Dev;
EbObject_Create_New_ObjectRequest ds = new EbObject_Create_New_ObjectRequest
{
Name = obj.Name,
DisplayName = obj.DisplayName,
Description = obj.Description,
Json = EbSerializers.Json_Serialize(obj),
Status = _status,
Relations = "import",
IsSave = false,
Tags = "_tags",
Apps = _currentAppId.ToString(),
SourceSolutionId = (obj.RefId.Split("-"))[0],
SourceObjId = (obj.RefId.Split("-"))[3],
SourceVerID = (obj.RefId.Split("-"))[4],
SolnId = request.SelectedSolutionId,
UserId = request.UserId,
UserAuthId = request.UserAuthId,
WhichConsole = request.WhichConsole,
IsImport = true
};
EbObject_Create_New_ObjectResponse res = Objservice.Post(ds);
RefidMap[obj.RefId] = res.RefId;
ObjectIdMAp.Add(Convert.ToInt32(obj.RefId.Split("-")[3]), new KeyValuePair<int, int>(Convert.ToInt32(res.RefId.Split("-")[3]), Convert.ToInt32(res.RefId.Split("-")[2])));
}
}
//Updating Refid
for (int i = Application.ObjCollection.Count - 1; i >= 0; i--)
{
EbObject obj = Application.ObjCollection[i];
string _mapRefid = obj.RefId;
obj.RefId = RefidMap[obj.RefId];
obj.ReplaceRefid(RefidMap);
string _rel_obj_tmp = string.Empty;
List<string> temp = obj.DiscoverRelatedRefids();
if (temp?.Count > 0)
_rel_obj_tmp = string.Join(",", temp);
EbObject_SaveRequest ss = new EbObject_SaveRequest
{
RefId = RefidMap[_mapRefid],
Name = obj.Name,
DisplayName = obj.DisplayName,
Description = obj.Description,
Json = EbSerializers.Json_Serialize(obj),
Apps = _currentAppId.ToString(),
SolnId = request.SelectedSolutionId,
UserId = request.UserId,
UserAuthId = request.UserAuthId,
WhichConsole = request.WhichConsole,
Relations = _rel_obj_tmp,
Tags = "_tags",
IsImport = true
};
EbObject_SaveResponse saveRes = Objservice.Post(ss);
}
Console.WriteLine("App & Object Creation Success.");
}
else
Console.WriteLine("Import - ObjectCollection is null. appid: " + request.Id);
}
SolutionType s_type = this.Redis.Get<Eb_Solution>(String.Format("solution_{0}", request.SolnId)).SolutionType;
if (s_type == SolutionType.REPLICA)
{
try
{
ImportFullTablesFromPkg(packageresponse.Package.DataSet.FullExportTables, request.SelectedSolutionId);
}
catch (Exception e)
{
Console.WriteLine("Error at Import.ImportFullTablesFromPkg " + e.Message + e.StackTrace);
}
try
{
ImportConditionalTablesFromPkg(packageresponse.Package.DataSet.ConditionalExportTables, request.SelectedSolutionId, AppIdMAp, ObjectIdMAp, request.UserId);
}
catch (Exception e)
{
Console.WriteLine("Error at Import.ImportConditionalTablesFromPkg " + e.Message + e.StackTrace);
}
try
{
UpdateSequencetoMax();
}
catch (Exception e)
{
Console.WriteLine("Error at Import.UpdateSequencetoMax " + e.Message + e.StackTrace);
}
}
this.ServerEventClient.BearerToken = request.BToken;
this.ServerEventClient.RefreshToken = request.RToken;
this.ServerEventClient.RefreshTokenUri = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_GET_ACCESS_TOKEN_URL);
this.ServerEventClient.Post<NotifyResponse>(new NotifySingleSubscriptionRequest
{
//ToChannel = new string[] {"file-upload" },
Msg = "ImportApplication success",
Selector = "cmd.importApplication",
ToSubscriptionId = request.SubscriptionId
});
//try
//{
// NotifyByUserIDResponse NF = NotificationService.Post(new NotifyByUserIDRequest
// {
// Link = "/MySolutions",
// Title = "ImportApplication success",
// UsersID = request.UserId,
// User_AuthId = request.UserAuthId
// });
//}
//catch (Exception ex)
//{
// Console.WriteLine("ImportApplication send notification" + ex.Message + ex.StackTrace);
//}
Console.WriteLine("ImportApplication success.");
}
else
{
Console.WriteLine(" Failed to load from appstore appid: " + request.Id);
}
}
catch (Exception e)
{
Console.WriteLine("ImportApplication" + e.Message + e.StackTrace);
}
return null;
}
public void GetRelated(string _refid, OrderedDictionary ObjDictionary, string solid)
{
EbObject obj = null;
if (!ObjDictionary.Contains(_refid))
{
obj = GetObjfromDB(_refid, solid);
if (obj == null)
Console.WriteLine("Object not in db : reference error " + _refid);
else
{
ObjDictionary.Add(_refid, obj);
List<string> _refCollection = obj.DiscoverRelatedRefids();
foreach (string _ref in _refCollection)
if (_ref.Trim() != string.Empty)
GetRelated(_ref, ObjDictionary, solid);
}
}
}
public EbObject GetObjfromDB(string _refid, string solid)
{
EbConnectionFactory ebConnectionFactory = new EbConnectionFactory(solid, this.Redis);
EbObjectService objservice = base.ResolveService<EbObjectService>();
objservice.EbConnectionFactory = ebConnectionFactory;
EbObject obj = null;
EbObjectParticularVersionResponse res = (EbObjectParticularVersionResponse)objservice.Get(new EbObjectParticularVersionRequest { RefId = _refid });
if (res.Data.Count > 0)
{
obj = EbSerializers.Json_Deserialize(res.Data[0].Json);
obj.RefId = _refid;
}
return obj;
}
public bool IsVersioned(string selectedSolnId, int uid)
{
Eb_Solution soln = this.Redis.Get<Eb_Solution>(String.Format("solution_{0}", selectedSolnId));
if (soln == null)
{
base.ResolveService<TenantUserServices>().Post(new UpdateSolutionObjectRequest { SolnId = selectedSolnId, UserId = uid });
soln = this.Redis.Get<Eb_Solution>(String.Format("solution_{0}", selectedSolnId));
}
return soln.IsVersioningEnabled;
}
public PackageDataSets ExportTablesToPkg(string solnId, List<string> ObjectIdCollection, List<int> AppIdCollection)
{
PackageDataSets Sets = new PackageDataSets();
try
{
string fullexport = @"SELECT id,name FROM
eb_user_types
WHERE eb_del ='F' ORDER BY id;
SELECT id, type FROM
eb_location_types
WHERE eb_del ='F' ORDER BY id;
SELECT id, name, description FROM
eb_usergroup
WHERE eb_del ='F' ORDER BY id;";
Sets.FullExportTables = this.EbConnectionFactory.DataDB.DoQueries(fullexport);
string conditionalexport = string.Format(@"SELECT id, role_name, applicationid, description, is_anonymous FROM
eb_roles
WHERE eb_del = 'F' AND applicationid IN({0})
AND id IN (SELECT distinct role_id FROM eb_role2permission WHERE eb_del ='F' AND obj_id IN ({1}))
ORDER BY applicationid;", string.Join<int>(",", AppIdCollection), string.Join(",", ObjectIdCollection));
conditionalexport += string.Format(@"SELECT id, role1_id, role2_id FROM
eb_role2role
WHERE eb_del ='F'
AND role1_id IN (SELECT id FROM eb_roles WHERE eb_del ='F' AND applicationid IN({0}) AND id IN (SELECT distinct role_id FROM eb_role2permission WHERE eb_del ='F' AND obj_id IN ({1})))
ORDER BY id;", string.Join<int>(",", AppIdCollection), string.Join(",", ObjectIdCollection));
conditionalexport += string.Format(@"SELECT id, role_id, obj_id, op_id FROM
eb_role2permission
WHERE eb_del ='F'
AND role_id IN (SELECT id FROM eb_roles WHERE eb_del ='F' AND applicationid IN({0}))
AND obj_id IN ({1})
ORDER BY id;", string.Join<int>(",", AppIdCollection), string.Join(",", ObjectIdCollection));
Sets.ConditionalExportTables = this.EbConnectionFactory.DataDB.DoQueries(conditionalexport);
}
catch (Exception e)
{
Console.WriteLine("Error in ExportInternalservice.FillExportData : " + e.Message + e.StackTrace);
}
return Sets;
}
public void ImportFullTablesFromPkg(EbDataSet dataSet, string solnId)
{
try
{
if (dataSet != null)
{
string query = string.Empty;
EbDataTable T0 = dataSet.Tables[0];
if (T0.Rows.Count > 0)
{
foreach (EbDataRow dr in T0.Rows)
{
query += string.Format(@"INSERT INTO eb_user_types(id, name, eb_created_by, eb_created_at, eb_del) VALUES
({0}, '{1}', 1, NOW(), 'F');", dr[0], dr[1]);
}
}
EbDataTable T1 = dataSet.Tables[1];
if (T1.Rows.Count > 0)
{
foreach (EbDataRow dr in T1.Rows)
{
query += string.Format(@"INSERT INTO eb_location_types(id, type, eb_created_by, eb_created_at, eb_del) VALUES
({0}, '{1}', 1, NOW(), 'F');", dr[0], dr[1]);
}
}
EbDataTable T2 = dataSet.Tables[2];
if (T2.Rows.Count > 0)
{
foreach (EbDataRow dr in T2.Rows)
{
query += string.Format(@"INSERT INTO eb_usergroup(id, name, description, eb_del) VALUES
({0}, '{1}', '{2}', 'F');", dr[0], dr[1], dr[2]);
}
}
this.EbConnectionFactory = new EbConnectionFactory(solnId, this.Redis);
this.EbConnectionFactory.DataDB.DoQueries(query);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message + e.StackTrace);
}
}
public void ImportConditionalTablesFromPkg(EbDataSet dataSet, string solnId, Dictionary<int, int> AppIdMap, Dictionary<int, KeyValuePair<int, int>> ObjectIdMap, int userid)
{
Dictionary<int, ExportRole> RolesCollection = new Dictionary<int, ExportRole>();
EbDataTable T0 = dataSet.Tables[0];
if (T0.Rows.Count > 0)
{
foreach (EbDataRow dr in T0.Rows)
{
int appid = Convert.ToInt32(dr[2]);
int oldRoleid = Convert.ToInt32(dr[0]);
RolesCollection.Add(oldRoleid, new ExportRole
{
AppId = AppIdMap[appid],
Role = new EbRole { Id = Convert.ToInt32(dr[0]), Name = dr[1].ToString(), Description = dr[3].ToString(), },
IsAnonymous = dr[4].ToString(),
Permissions = new List<EbPermissions>(),
LocationIds = new List<int> { { 1 } }
});
}
}
EbDataTable T1 = dataSet.Tables[1];
if (T1.Rows.Count > 0)
{
foreach (EbDataRow dr in T1.Rows)
{
int oldRoleid = Convert.ToInt32(dr[1]);
int roleid2 = Convert.ToInt32(dr[2]);
if (roleid2 > 0)
{
if (RolesCollection[oldRoleid].DependantRoles == null)
RolesCollection[oldRoleid].DependantRoles = new List<int>();
RolesCollection[oldRoleid].DependantRoles.Add(roleid2);
}
}
}
EbDataTable T2 = dataSet.Tables[2];
if (T2.Rows.Count > 0)
{
foreach (EbDataRow dr in T2.Rows)
{
int oldRoleid = Convert.ToInt32(dr[1]);
KeyValuePair<int, int> pair = ObjectIdMap[Convert.ToInt32(dr[2])];//<objectid,objtype>
RolesCollection[oldRoleid].Permissions.Add(new EbPermissions(pair.Value /*type*/, pair.Key, Convert.ToInt32(dr[3])));
}
}
foreach (KeyValuePair<int, ExportRole> role in RolesCollection)
{
ExportRole exp_role = role.Value;
string query = string.Format(@"INSERT INTO eb_roles(id, role_name) VALUES
({0},'{1}');", exp_role.Role.Id, exp_role.Role.Name);
int c = this.EbConnectionFactory.DataDB.DoNonQuery(query);
if (c > 0)
{
Dictionary<string, object> Dict = new Dictionary<string, object>();
Dict["roleid"] = exp_role.Role.Id;
Dict["applicationid"] = exp_role.AppId;
Dict["role_name"] = exp_role.Role.Name;
Dict["Description"] = exp_role.Role.Description;
Dict["IsAnonymous"] = exp_role.IsAnonymous;
Dict["users"] = string.Empty;
Dict["permission"] = string.Empty;
if (exp_role.Permissions.Count > 0)
{
List<string> permissionString = new List<string>();
foreach (EbPermissions permission in exp_role.Permissions)
{
permissionString.Add(exp_role.AppId.ToString().PadLeft(3, '0') + "-" + /*this is obj type*/permission._id.ToString().PadLeft(2, '0') + "-" + permission._object_id.ToString().PadLeft(5, '0') + "-" + permission._operation_id.ToString().PadLeft(2, '0'));
}
Dict["permission"] = string.Join(',', permissionString);
}
if (exp_role.DependantRoles != null)
{
}
Dict["dependants"] = (exp_role.DependantRoles == null) ? string.Empty : string.Join<int>(",", exp_role.DependantRoles);
Dict["locations"] = (exp_role.LocationIds == null) ? string.Empty : string.Join<int>(",", exp_role.LocationIds);
SaveRoleResponse res = (SaveRoleResponse)SecurityServices.Post(new SaveRoleRequest { Colvalues = Dict, UserId = userid, SolnId = solnId });//if res.id = 0 success
}
}
}
public void UpdateSequencetoMax()
{
string sequenceUpdateQ = @"SELECT setval('eb_roles_id_seq', (SELECT MAX(id) FROM eb_roles)+1);
SELECT setval('eb_location_types_id_seq', (SELECT MAX(id) FROM eb_location_types)+1);
SELECT setval('eb_user_types_id_seq', (SELECT MAX(id) FROM eb_user_types)+1);
SELECT setval('eb_usergroup_id_seq', (SELECT MAX(id) FROM eb_usergroup)+1);";
this.EbConnectionFactory.DataDB.DoQueries(sequenceUpdateQ);
}
public int CreateOrGetAppId(string ApplicationName, AppWrapper AppObj)
{
int _currentAppId = 0;
try
{
UniqueApplicationNameCheckResponse uniq_appnameresp = Devservice.Get(new UniqueApplicationNameCheckRequest { AppName = ApplicationName });
if (uniq_appnameresp.IsUnique)
{
CreateApplicationResponse appres = Devservice.Post(new CreateApplicationRequest
{
AppName = ApplicationName,
AppType = AppObj.AppType,
Description = AppObj.Description,
AppIcon = AppObj.Icon,
AppSettings = AppObj.AppSettings,
});
_currentAppId = appres.Id;
}
else
_currentAppId = uniq_appnameresp.AppId;
Console.WriteLine("Import.CreateOrGetAppId success : " + ApplicationName);
}
catch (Exception e)
{
Console.WriteLine(e.Message + e.StackTrace);
}
return _currentAppId;
}
public string GetUniqDisplayName(string name)
{
UniqueObjectNameCheckResponse uniqnameresp;
int o = 1;
string dispname = name;
do
{
uniqnameresp = Objservice.Get(new UniqueObjectNameCheckRequest
{
ObjName = dispname
});
if (!uniqnameresp.IsUnique)
dispname = name + "(" + o++ + ")";
}
while (!uniqnameresp.IsUnique);
return dispname;
}
public string GetProcessedName(string name)
{
counter++;
string oldts = string.Empty;
if (name.Contains('_'))
oldts = name.Substring(name.LastIndexOf('_'));
string newts = DateTime.UtcNow.ToString("MMMydHms").ToLower();
if (oldts != string.Empty)
name = name.Replace(oldts, "_" + newts);
else
name += "_" + newts;
return name + counter.ToString();
}
}
public class ExportRole
{
public EbRole Role { get; set; }
public int AppId { get; set; }
public string IsAnonymous { get; set; }
public List<int> LocationIds { get; set; }
public List<EbPermissions> Permissions { get; set; }
public List<int> DependantRoles { get; set; }
}
}