PageRenderTime 80ms CodeModel.GetById 46ms RepoModel.GetById 0ms app.codeStats 1ms

/DAL/ProfileProcessor.cs

https://github.com/dbatesx/WALT
C# | 1361 lines | 927 code | 203 blank | 231 comment | 144 complexity | c465e62e90447739c9ab96c75de4ac8f MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using WALT.DTO;
  6. using System.Data.SqlClient;
  7. using System.Diagnostics;
  8. using System.DirectoryServices;
  9. using System.Configuration;
  10. using System.Data.Entity;
  11. using System.Data.Linq;
  12. namespace WALT.DAL
  13. {
  14. public class ProfileProcessor : Processor
  15. {
  16. public ProfileProcessor(Mediator mediator)
  17. : base(mediator)
  18. {
  19. }
  20. /// <summary>
  21. ///
  22. /// </summary>
  23. /// <param name="rec"></param>
  24. /// <returns></returns>
  25. public DTO.Profile CreateProfileDTO(profile rec)
  26. {
  27. return CreateProfileDTO(rec, true, true);
  28. }
  29. /// <summary>
  30. ///
  31. /// </summary>
  32. /// <param name="rec"></param>
  33. /// <param name="expand"></param>
  34. /// <returns></returns>
  35. public DTO.Profile CreateProfileDTO(profile rec, bool expand, bool loadManager)
  36. {
  37. DTO.Profile profile = null;
  38. if (rec != null)
  39. {
  40. profile = new DTO.Profile();
  41. profile.Id = rec.id;
  42. profile.Username = rec.username;
  43. profile.ExemptPlan = rec.exempt_plan;
  44. profile.ExemptTask = rec.exempt_task;
  45. profile.CanTask = rec.can_task;
  46. profile.DisplayName = rec.display_name ?? profile.Username;
  47. profile.EmployeeID = rec.employee_id ?? string.Empty;
  48. profile.Active = rec.active;
  49. profile.Roles = new List<Role>();
  50. profile.Preferences = new Dictionary<string, string>();
  51. profile.OrgCode = rec.org_code ?? string.Empty;
  52. profile.Manager = loadManager && rec.manager.HasValue ? CreateProfileDTO(rec.profile1, false, false) : null;
  53. if (string.IsNullOrEmpty(profile.DisplayName))
  54. {
  55. profile.DisplayName = profile.Username;
  56. }
  57. if (expand)
  58. {
  59. var context = _db.GetContext();
  60. var qProfileRoles = from role in context.roles
  61. join role_profile in context.role_profiles
  62. on role.id equals role_profile.role_id
  63. where role_profile.profile_id == profile.Id
  64. select role;
  65. foreach (var ProfileRole in qProfileRoles)
  66. {
  67. profile.Roles.Add(_mediator.GetAdminProcessor().CreateRoleDTO(ProfileRole));
  68. }
  69. var qProfilePreferences = from preference in context.preferences
  70. where preference.profile_id == profile.Id
  71. select preference;
  72. foreach (var ProfilePreference in qProfilePreferences)
  73. {
  74. profile.Preferences[ProfilePreference.name] = ProfilePreference.value;
  75. }
  76. }
  77. }
  78. return profile;
  79. }
  80. public Profile GetProfile(long id)
  81. {
  82. return GetProfile(id, true, true);
  83. }
  84. /// <summary>
  85. ///
  86. /// </summary>
  87. /// <param name="id"></param>
  88. /// <returns></returns>
  89. public Profile GetProfile(long id, bool expand, bool loadManager)
  90. {
  91. Profile profile = null;
  92. profile p = _db.GetContext().profiles.SingleOrDefault(x => x.id == id);
  93. if (p != null)
  94. {
  95. profile = CreateProfileDTO(p, expand, loadManager);
  96. }
  97. return profile;
  98. }
  99. /// <summary>
  100. ///
  101. /// </summary>
  102. /// <param name="username"></param>
  103. /// <returns></returns>
  104. public Profile GetProfile(string username, bool expand)
  105. {
  106. Profile profile = null;
  107. profile p = _db.GetContext().profiles.SingleOrDefault(x => x.username == username);
  108. if (p != null)
  109. {
  110. profile = CreateProfileDTO(p, expand, true);
  111. }
  112. return profile;
  113. }
  114. /// <summary>
  115. ///
  116. /// </summary>
  117. /// <returns></returns>
  118. public List<DTO.Profile> GetProfileList()
  119. {
  120. List<DTO.Profile> profiles = new List<DTO.Profile>();
  121. var query = from item in _db.GetContext().profiles
  122. orderby item.display_name
  123. select item;
  124. foreach (var rec in query)
  125. {
  126. profiles.Add(CreateProfileDTO(rec));
  127. }
  128. return profiles;
  129. }
  130. /// <summary>
  131. ///
  132. /// </summary>
  133. /// <returns></returns>
  134. public List<DTO.Profile> GetProfileList(string filter)
  135. {
  136. List<DTO.Profile> profiles = new List<DTO.Profile>();
  137. var query = from item in _db.GetContext().profiles
  138. where item.display_name.Contains(filter)
  139. orderby item.display_name
  140. select item;
  141. foreach (var rec in query)
  142. {
  143. profiles.Add(CreateProfileDTO(rec));
  144. }
  145. return profiles;
  146. }
  147. /// <summary>
  148. ///
  149. /// </summary>
  150. /// <returns></returns>
  151. public Dictionary<long, string> GetProfileDictionary(string filter)
  152. {
  153. Dictionary<long, string> profiles = new Dictionary<long, string>();
  154. var query = from item in _db.GetContext().profiles
  155. where item.display_name.Contains(filter)
  156. orderby item.display_name
  157. select item;
  158. foreach (var rec in query)
  159. {
  160. profiles.Add(rec.id, rec.display_name);
  161. }
  162. return profiles;
  163. }
  164. /// <summary>
  165. ///
  166. /// </summary>
  167. /// <returns></returns>
  168. public Dictionary<long, string> GetTeammateDictionary(long profileId)
  169. {
  170. List<KeyValuePair<long, string>> profiles = new List<KeyValuePair<long, string>>();
  171. var query = from item1 in _db.GetContext().teams
  172. join item2 in _db.GetContext().team_profiles on item1.id equals item2.team_id
  173. where item2.profile_id == profileId
  174. orderby item1.title
  175. select item1;
  176. foreach (var team in query)
  177. {
  178. if (team.owner_id != null)
  179. {
  180. var owner = _db.GetContext().profiles.SingleOrDefault(x => x.id == team.owner_id);
  181. if (!profiles.Contains(new KeyValuePair<long, string>(owner.id, owner.display_name)))
  182. {
  183. profiles.Add(new KeyValuePair<long, string>(owner.id,
  184. string.IsNullOrEmpty(owner.display_name) ? owner.username : owner.display_name));
  185. }
  186. }
  187. var members = from item in _db.GetContext().team_profiles
  188. where item.team_id == team.id
  189. select item;
  190. foreach (var user in members)
  191. {
  192. if (!profiles.Contains(new KeyValuePair<long, string>(user.profile.id, user.profile.display_name)))
  193. {
  194. profiles.Add(new KeyValuePair<long, string>(user.profile.id,
  195. string.IsNullOrEmpty(user.profile.display_name) ? user.profile.username : user.profile.display_name));
  196. }
  197. }
  198. }
  199. var teamsOwned = from item in _db.GetContext().teams
  200. where item.owner_id == profileId
  201. select item;
  202. foreach (var oteam in teamsOwned)
  203. {
  204. var members = from item in _db.GetContext().team_profiles
  205. where item.team_id == oteam.id
  206. select item;
  207. foreach (var user in members)
  208. {
  209. if (!profiles.Contains(new KeyValuePair<long, string>(user.profile.id, user.profile.display_name)))
  210. {
  211. profiles.Add(new KeyValuePair<long, string>(user.profile.id,
  212. string.IsNullOrEmpty(user.profile.display_name) ? user.profile.username : user.profile.display_name));
  213. }
  214. }
  215. }
  216. profiles.Sort(delegate(KeyValuePair<long, string> x, KeyValuePair<long, string> y) { return x.Value.CompareTo(y.Value); });
  217. return profiles.ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value);
  218. }
  219. /// <summary>
  220. ///
  221. /// </summary>
  222. /// <returns></returns>
  223. public List<DTO.Profile> GetProfileList(DTO.Action action, bool active)
  224. {
  225. List<DTO.Profile> profiles = new List<DTO.Profile>();
  226. var query1 = (from item1 in _db.GetContext().profiles
  227. join item2 in _db.GetContext().role_profiles on item1.id equals item2.profile_id
  228. join item3 in _db.GetContext().roles on item2.role_id equals item3.id
  229. join item4 in _db.GetContext().role_actions on item2.role_id equals item4.role_id
  230. join item5 in _db.GetContext().actions on item4.action_id equals item5.id
  231. where item5.title == action.ToString()
  232. select item1).Distinct();
  233. foreach (profile p in query1)
  234. {
  235. DTO.Profile profileDTO = GetProfile(p.id);
  236. if (profileDTO != null && IsAllowed(profileDTO, action))
  237. {
  238. profiles.Add(CreateProfileDTO(p, false, false));
  239. }
  240. }
  241. profiles = profiles.OrderBy(x => x.DisplayName).ToList();
  242. return profiles;
  243. }
  244. /// <summary>
  245. ///
  246. /// </summary>
  247. /// <param name="profile"></param>
  248. /// <param name="action"></param>
  249. /// <returns></returns>
  250. public bool IsAllowed(WALT.DTO.Profile profile, WALT.DTO.Action action)
  251. {
  252. bool allowed = false;
  253. if (profile != null)
  254. {
  255. foreach (DTO.Role role in profile.Roles)
  256. {
  257. if (role.Actions.Exists(x => x.ToString() == action.ToString()))
  258. {
  259. allowed = true;
  260. break;
  261. }
  262. }
  263. }
  264. return allowed;
  265. }
  266. /// <summary>
  267. ///
  268. /// </summary>
  269. /// <param name="directorateID"></param>
  270. /// <returns></returns>
  271. public bool IsDirectorateAdmin(long directorateID, DTO.Profile profile)
  272. {
  273. return _db.GetContext().team_profiles.Count(
  274. x => x.profile_id == profile.Id && x.team_id == directorateID && x.role == "ADMIN") > 0;
  275. }
  276. /// <summary>
  277. ///
  278. /// </summary>
  279. /// <param name="profile"></param>
  280. /// <returns></returns>
  281. public bool IsRogueUser(Profile profile)
  282. {
  283. return _db.GetContext().team_profiles.Count(x => x.profile_id == profile.Id && x.role == "MEMBER") == 0;
  284. }
  285. /// <summary>
  286. ///
  287. /// </summary>
  288. /// <param name="p"></param>
  289. public void SaveProfile(Profile p)
  290. {
  291. var dbContext = _db.GetContext();
  292. long id = p.Id;
  293. profile n = dbContext.profiles.SingleOrDefault(x => x.id == id);
  294. if (n == null)
  295. {
  296. n = new profile();
  297. dbContext.profiles.InsertOnSubmit(n);
  298. }
  299. n.username = p.Username;
  300. n.exempt_plan = p.ExemptPlan;
  301. n.exempt_task = p.ExemptTask;
  302. n.can_task = p.CanTask;
  303. n.active = p.Active;
  304. n.employee_id = p.EmployeeID;
  305. n.display_name = p.DisplayName;
  306. n.org_code = p.OrgCode;
  307. n.profile1 = p.Manager != null ? dbContext.profiles.SingleOrDefault(x => x.id == p.Manager.Id) : null; //p.Manager != null ? (long?)p.Manager.Id : null;
  308. if (n.display_name == null || n.display_name.Length == 0)
  309. {
  310. n.display_name = n.username;
  311. }
  312. _db.SubmitChanges();
  313. p.Id = n.id;
  314. id = p.Id;
  315. var qProfileRoles = from ProfileRole in dbContext.role_profiles
  316. where ProfileRole.profile_id == id
  317. select ProfileRole;
  318. foreach (var ProfileRole in qProfileRoles)
  319. {
  320. dbContext.role_profiles.DeleteOnSubmit(ProfileRole);
  321. }
  322. _db.SubmitChanges();
  323. foreach (DTO.Role r in p.Roles)
  324. {
  325. role_profile rp = new role_profile();
  326. rp.profile_id = id;
  327. rp.role_id = r.Id;
  328. dbContext.role_profiles.InsertOnSubmit(rp);
  329. }
  330. _db.SubmitChanges();
  331. var qProfilePreferences = from ProfilePreference in dbContext.preferences
  332. where ProfilePreference.profile_id == id
  333. select ProfilePreference;
  334. foreach (var ProfilePreference in qProfilePreferences)
  335. {
  336. dbContext.preferences.DeleteOnSubmit(ProfilePreference);
  337. }
  338. _db.SubmitChanges();
  339. foreach (var pref in p.Preferences.Keys)
  340. {
  341. preference rec = new preference();
  342. rec.profile_id = p.Id;
  343. rec.name = pref;
  344. rec.value = p.Preferences[pref];
  345. dbContext.preferences.InsertOnSubmit(rec);
  346. }
  347. //for (int i = 0; i < p.Preferences.Keys.Count; i++)
  348. //{
  349. // preference rec = new preference();
  350. // rec.profile_id = p.Id;
  351. // rec.name = p.Preferences.Keys.ElementAt(i).ToString();
  352. // rec.value = p.Preferences[rec.name];
  353. // _db.GetContext().preferences.InsertOnSubmit(rec);
  354. //}
  355. _db.SubmitChanges();
  356. }
  357. /// <summary>
  358. /// Creates a list of actions that the given profile
  359. /// is allowed to perform.
  360. /// </summary>
  361. /// <param name="profile"></param>
  362. /// <returns></returns>
  363. public List<DTO.Action> GetProfileActions(Profile profile)
  364. {
  365. List<WALT.DTO.Action> actions = new List<WALT.DTO.Action>();
  366. if (profile != null)
  367. {
  368. var query1 = from item1 in _db.GetContext().role_profiles
  369. join item2 in _db.GetContext().role_actions
  370. on item1.role_id equals item2.role_id
  371. where item1.profile_id == profile.Id
  372. select new { item2.action_id };
  373. var query2 = from item1 in _db.GetContext().actions
  374. join item2 in query1
  375. on item1.id equals item2.action_id
  376. select new { item1.title };
  377. foreach (var rec in query2)
  378. {
  379. try
  380. {
  381. actions.Add((DTO.Action)Enum.Parse(
  382. typeof(DTO.Action), rec.title, true));
  383. }
  384. catch
  385. {
  386. }
  387. }
  388. }
  389. return actions;
  390. }
  391. /// <summary>
  392. ///
  393. /// </summary>
  394. /// <param name="profile"></param>
  395. /// <param name="o"></param>
  396. /// <param name="type"></param>
  397. /// <param name="comment"></param>
  398. public void LogComment(Profile profile, DTO.Object o, string type, string comment)
  399. {
  400. log l = new log();
  401. l.profile_id = profile.Id;
  402. l.category = o.GetType().ToString();
  403. l.source_id = o.Id;
  404. l.comment = comment;
  405. l.entry_type = type;
  406. l.entry_date = DateTime.Now;
  407. _db.GetContext().logs.InsertOnSubmit(l);
  408. _db.SubmitChanges();
  409. }
  410. /// <summary>
  411. ///
  412. /// </summary>
  413. /// <param name="a"></param>
  414. /// <returns></returns>
  415. public Alert CreateAlertDTO(alert a)
  416. {
  417. Alert alert = null;
  418. if (a != null)
  419. {
  420. alert = new Alert();
  421. alert.Id = a.id;
  422. alert.Profile = CreateProfileDTO(a.profile1);
  423. alert.Creator = CreateProfileDTO(a.profile);
  424. alert.EntryDate = a.entry_date;
  425. alert.Subject = a.subject;
  426. alert.Message = a.message;
  427. alert.LinkedId = a.linked_id.GetValueOrDefault(-1);
  428. alert.Acknowledged = a.acknowledged;
  429. alert.LinkedType = a.linked_type != null && a.linked_type != string.Empty ?
  430. (Alert.AlertEnum)Enum.Parse(typeof(Alert.AlertEnum), a.linked_type) : (Alert.AlertEnum?)null;
  431. }
  432. return alert;
  433. }
  434. /// <summary>
  435. ///
  436. /// </summary>
  437. /// <param name="id"></param>
  438. /// <returns></returns>
  439. public Alert GetAlert(long id)
  440. {
  441. return CreateAlertDTO(_db.GetContext().alerts.SingleOrDefault(x => x.id == id));
  442. }
  443. /// <summary>
  444. ///
  445. /// </summary>
  446. /// <param name="profile"></param>
  447. /// <param name="acknowledged"></param>
  448. /// <returns></returns>
  449. public List<Alert> GetAlertList(Profile profile, bool acknowledged)
  450. {
  451. List<Alert> alerts = new List<Alert>();
  452. var query = from item in _db.GetContext().alerts
  453. where item.profile_id == profile.Id && item.acknowledged == acknowledged
  454. select item;
  455. foreach (alert a in query)
  456. {
  457. alerts.Add(CreateAlertDTO(a));
  458. }
  459. return alerts;
  460. }
  461. /// <summary>
  462. ///
  463. /// </summary>
  464. /// <param name="profile"></param>
  465. /// <param name="acknowledged"></param>
  466. /// <param name="sort"></param>
  467. /// <param name="order"></param>
  468. /// <param name="start"></param>
  469. /// <param name="size"></param>
  470. /// <param name="count"></param>
  471. /// <param name="filters"></param>
  472. /// <returns></returns>
  473. public List<Alert> GetAlertList(Profile profile, bool acknowledged,
  474. Alert.ColumnEnum? sort, bool order, int start, int size, ref int count,
  475. Dictionary<Alert.ColumnEnum, string> filters)
  476. {
  477. List<Alert> alerts = new List<Alert>();
  478. IQueryable<alert> query = from item in _db.GetContext().alerts
  479. where item.profile_id == profile.Id && item.acknowledged == acknowledged
  480. select item;
  481. query = FilterAlerts(query, filters);
  482. count = query.Count();
  483. query = SortAlerts(query, sort, order).Skip(start).Take(size);
  484. foreach (alert a in query)
  485. {
  486. alerts.Add(CreateAlertDTO(a));
  487. }
  488. return alerts;
  489. }
  490. /// <summary>
  491. ///
  492. /// </summary>
  493. /// <param name="profile"></param>
  494. /// <returns></returns>
  495. public List<Alert> GetAlertListByCreator(Profile profile)
  496. {
  497. List<Alert> alerts = new List<Alert>();
  498. IQueryable<alert> query = from item in _db.GetContext().alerts
  499. where item.creator_id == profile.Id
  500. select item;
  501. foreach (alert a in query)
  502. {
  503. alerts.Add(CreateAlertDTO(a));
  504. }
  505. return alerts;
  506. }
  507. /// <summary>
  508. ///
  509. /// </summary>
  510. /// <param name="profile"></param>
  511. /// <param name="sort"></param>
  512. /// <param name="order"></param>
  513. /// <param name="start"></param>
  514. /// <param name="size"></param>
  515. /// <param name="count"></param>
  516. /// <param name="filters"></param>
  517. /// <returns></returns>
  518. public List<Alert> GetAlertListByCreator(Profile profile,
  519. Alert.ColumnEnum? sort, bool order, int start, int size, ref int count,
  520. Dictionary<Alert.ColumnEnum, string> filters)
  521. {
  522. List<Alert> alerts = new List<Alert>();
  523. IQueryable<alert> query = from item in _db.GetContext().alerts
  524. where item.creator_id == profile.Id && item.linked_type != Alert.AlertEnum.SYSTEM.ToString()
  525. select item;
  526. query = FilterAlerts(query, filters);
  527. count = query.Count();
  528. query = SortAlerts(query, sort, order).Skip(start).Take(size);
  529. foreach (alert a in query)
  530. {
  531. alerts.Add(CreateAlertDTO(a));
  532. }
  533. return alerts;
  534. }
  535. /// <summary>
  536. ///
  537. /// </summary>
  538. /// <param name="alerts"></param>
  539. /// <param name="filters"></param>
  540. /// <returns></returns>
  541. private IQueryable<alert> FilterAlerts(IQueryable<alert> alerts, Dictionary<Alert.ColumnEnum, string> filters)
  542. {
  543. if (filters != null && filters.Count > 0)
  544. {
  545. long id;
  546. var predicate = PredicateBuilder.True<alert>();
  547. foreach (Alert.ColumnEnum col in filters.Keys)
  548. {
  549. string filter = filters[col];
  550. switch (col)
  551. {
  552. case Alert.ColumnEnum.ACKNOWLEDGED:
  553. predicate = predicate.And(x => x.acknowledged == Convert.ToBoolean(filter));
  554. break;
  555. case Alert.ColumnEnum.SUBJECT:
  556. predicate = predicate.And(x => x.subject.ToUpper().Contains(filter.ToUpper()));
  557. break;
  558. case Alert.ColumnEnum.MESSAGE:
  559. predicate = predicate.And(x => x.message.Contains(filter));
  560. break;
  561. case Alert.ColumnEnum.PROFILE:
  562. if (long.TryParse(filter, out id))
  563. {
  564. predicate = predicate.And(x => x.profile_id == id);
  565. }
  566. break;
  567. case Alert.ColumnEnum.CREATOR:
  568. if (long.TryParse(filter, out id))
  569. {
  570. predicate = predicate.And(x => x.creator_id == id);
  571. }
  572. break;
  573. case Alert.ColumnEnum.ENTRYDATE:
  574. string[] split = filter.Split(',');
  575. for (int i = 0; i + 1 < split.Length; i += 2)
  576. {
  577. DateTime date = Convert.ToDateTime(split[i+1]);
  578. if (split[i] == ">")
  579. {
  580. predicate = predicate.And(x => x.entry_date.CompareTo(date) > 0);
  581. }
  582. else if (split[i] == "<")
  583. {
  584. date = date.AddDays(1);
  585. predicate = predicate.And(x => x.entry_date.CompareTo(date) < 0);
  586. }
  587. }
  588. break;
  589. }
  590. }
  591. return alerts.AsQueryable().Where(predicate);
  592. }
  593. return alerts;
  594. }
  595. /// <summary>
  596. ///
  597. /// </summary>
  598. /// <param name="alerts"></param>
  599. /// <param name="sort"></param>
  600. /// <param name="order"></param>
  601. /// <returns></returns>
  602. private IQueryable<alert> SortAlerts(IQueryable<alert> alerts, Alert.ColumnEnum? sort, bool order)
  603. {
  604. if (sort.HasValue)
  605. {
  606. switch (sort.Value)
  607. {
  608. case Alert.ColumnEnum.PROFILE:
  609. if (order)
  610. {
  611. return alerts.OrderBy(x => x.profile1.display_name);
  612. }
  613. else
  614. {
  615. return alerts.OrderByDescending(x => x.profile1.display_name);
  616. }
  617. case Alert.ColumnEnum.CREATOR:
  618. if (order)
  619. {
  620. return alerts.OrderBy(x => x.profile.display_name);
  621. }
  622. else
  623. {
  624. return alerts.OrderByDescending(x => x.profile.display_name);
  625. }
  626. case Alert.ColumnEnum.SUBJECT:
  627. if (order)
  628. {
  629. return alerts.OrderBy(x => x.subject);
  630. }
  631. else
  632. {
  633. return alerts.OrderByDescending(x => x.subject);
  634. }
  635. case Alert.ColumnEnum.LINKEDTYPE:
  636. if (order)
  637. {
  638. return alerts.OrderBy(x => x.linked_type);
  639. }
  640. else
  641. {
  642. return alerts.OrderByDescending(x => x.linked_type);
  643. }
  644. case Alert.ColumnEnum.ENTRYDATE:
  645. if (order)
  646. {
  647. return alerts.OrderBy(x => x.entry_date);
  648. }
  649. else
  650. {
  651. return alerts.OrderByDescending(x => x.entry_date);
  652. }
  653. case Alert.ColumnEnum.ACKNOWLEDGED:
  654. if (order)
  655. {
  656. return alerts.OrderBy(x => x.acknowledged);
  657. }
  658. else
  659. {
  660. return alerts.OrderByDescending(x => x.acknowledged);
  661. }
  662. }
  663. }
  664. return alerts;
  665. }
  666. /// <summary>
  667. ///
  668. /// </summary>
  669. /// <param name="alert"></param>
  670. public void SaveAlert(Alert alert)
  671. {
  672. alert a = null;
  673. if (alert.Id > 0)
  674. {
  675. a = _db.GetContext().alerts.SingleOrDefault(x => x.id == alert.Id);
  676. }
  677. if (a == null)
  678. {
  679. a = new alert();
  680. _db.GetContext().alerts.InsertOnSubmit(a);
  681. }
  682. a.profile1 = _db.GetContext().profiles.Single(x => x.id == alert.Profile.Id);
  683. a.profile = _db.GetContext().profiles.Single(x => x.id == alert.Creator.Id);
  684. a.entry_date = alert.EntryDate;
  685. a.subject = alert.Subject;
  686. a.message = alert.Message;
  687. a.linked_id = alert.LinkedId != -1 ? alert.LinkedId : (long?)null;
  688. a.linked_type = alert.LinkedType.HasValue ? alert.LinkedType.Value.ToString() : string.Empty;
  689. a.acknowledged = alert.Acknowledged;
  690. _db.SubmitChanges();
  691. }
  692. /// <summary>
  693. ///
  694. /// </summary>
  695. /// <param name="alert"></param>
  696. /// <param name="sendTo"></param>
  697. public void SendAlert(Alert alert, List<Profile> sendTo)
  698. {
  699. foreach (Profile profile in sendTo)
  700. {
  701. alert a = new alert();
  702. a.profile1 = _db.GetContext().profiles.Single(x => x.id == profile.Id);
  703. a.profile = _db.GetContext().profiles.Single(x => x.id == alert.Creator.Id);
  704. a.entry_date = alert.EntryDate;
  705. a.subject = alert.Subject;
  706. a.message = alert.Message;
  707. a.linked_id = alert.LinkedId != -1 ? alert.LinkedId : (long?)null;
  708. a.linked_type = alert.LinkedType.HasValue ? alert.LinkedType.Value.ToString() : string.Empty;
  709. a.acknowledged = alert.Acknowledged;
  710. _db.GetContext().alerts.InsertOnSubmit(a);
  711. }
  712. _db.SubmitChanges();
  713. }
  714. /// <summary>
  715. ///
  716. /// </summary>
  717. /// <param name="id"></param>
  718. public void AcknowledgeAlert(long id)
  719. {
  720. alert alert = _db.GetContext().alerts.SingleOrDefault(x => x.id == id);
  721. if (alert != null)
  722. {
  723. alert.acknowledged = true;
  724. _db.SubmitChanges();
  725. }
  726. }
  727. /// <summary>
  728. ///
  729. /// </summary>
  730. /// <param name="alertIDs"></param>
  731. public void AcknowledgeAlerts(List<long> alertIDs)
  732. {
  733. var query = from item in _db.GetContext().alerts
  734. where alertIDs.Contains(item.id)
  735. select item;
  736. foreach (alert a in query)
  737. {
  738. a.acknowledged = true;
  739. }
  740. _db.SubmitChanges();
  741. }
  742. /// <summary>
  743. ///
  744. /// </summary>
  745. /// <param name="profile"></param>
  746. /// <returns></returns>
  747. public List<Profile> GetAlertCreators(Profile profile)
  748. {
  749. List<Profile> creators = new List<Profile>();
  750. var query = (from item1 in _db.GetContext().alerts
  751. join item2 in _db.GetContext().profiles on item1.creator_id equals item2.id
  752. where item1.profile_id == profile.Id
  753. orderby item2.display_name
  754. select item2).Distinct();
  755. foreach (profile p in query)
  756. {
  757. creators.Add(CreateProfileDTO(p, false, false));
  758. }
  759. return creators;
  760. }
  761. /// <summary>
  762. ///
  763. /// </summary>
  764. /// <param name="profile"></param>
  765. /// <returns></returns>
  766. public List<Profile> GetAlertProfiles(Profile profile)
  767. {
  768. List<Profile> profiles = new List<Profile>();
  769. var query = (from item1 in _db.GetContext().alerts
  770. join item2 in _db.GetContext().profiles on item1.profile_id equals item2.id
  771. where item1.creator_id == profile.Id
  772. orderby item2.display_name
  773. select item2).Distinct();
  774. foreach (profile p in query)
  775. {
  776. profiles.Add(CreateProfileDTO(p, false, false));
  777. }
  778. return profiles;
  779. }
  780. /// <summary>
  781. ///
  782. /// </summary>
  783. /// <param name="profile"></param>
  784. /// <returns></returns>
  785. public int GetUnreadAlertCount(Profile profile)
  786. {
  787. return _db.GetContext().alerts.Count(x => x.profile_id == profile.Id && !x.acknowledged);
  788. }
  789. /// <summary>
  790. ///
  791. /// </summary>
  792. /// <param name="domain"></param>
  793. /// <param name="entry"></param>
  794. /// <returns></returns>
  795. ADEntry CreateADEntryDTO(string domain, DirectoryEntry entry)
  796. {
  797. ADEntry ad = new ADEntry();
  798. try
  799. {
  800. ad.Domain = domain.ToUpper();
  801. ad.Username = entry.Properties["samaccountname"].Value.ToString().ToLower();
  802. ad.DisplayName = entry.Properties["displayname"].Value as string;
  803. ad.EmployeeID = entry.Properties["employeeid"].Value as string;
  804. ad.OrgCode = entry.Properties["department"].Value as string;
  805. string manager = entry.Properties["manager"].Value as string;
  806. if (!string.IsNullOrEmpty(manager))
  807. {
  808. string[] parts2 = entry.Properties["manager"].Value.ToString().Split(',');
  809. string[] parts3 = parts2[0].Split('=');
  810. ad.Manager = parts3[1];
  811. }
  812. }
  813. catch
  814. {
  815. return null;
  816. }
  817. return ad;
  818. }
  819. /// <summary>
  820. ///
  821. /// </summary>
  822. /// <param name="profile"></param>
  823. /// <returns></returns>
  824. public ADEntry GetADEntry(DTO.Profile profile)
  825. {
  826. ADEntry ad = null;
  827. if (profile.Username.Contains("\\") == false)
  828. {
  829. throw new Exception("Username must contain domain");
  830. }
  831. string[] parts = profile.Username.Split('\\');
  832. string dc = "LDAP://DC=" + parts[0];
  833. if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ADDomainComponents"]))
  834. {
  835. string[] split = ConfigurationManager.AppSettings["ADDomainComponents"].Split(',');
  836. foreach (string component in split)
  837. {
  838. dc += ",DC=" + component;
  839. }
  840. }
  841. DirectoryEntry de = new DirectoryEntry(dc);
  842. if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ADUsername"]))
  843. {
  844. de.Username = ConfigurationManager.AppSettings["ADUsername"];
  845. }
  846. if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ADPassword"]))
  847. {
  848. de.Password = ConfigurationManager.AppSettings["ADPassword"];
  849. }
  850. DirectorySearcher ds = new DirectorySearcher(de);
  851. if (profile.EmployeeID == null || profile.EmployeeID.Length == 0)
  852. {
  853. ds.Filter = "samaccountname=" + parts[1];
  854. }
  855. else
  856. {
  857. ds.Filter = "employeeid=" + profile.EmployeeID;
  858. }
  859. ds.PropertiesToLoad.Add("samaccountname");
  860. ds.PropertiesToLoad.Add("displayname");
  861. ds.PropertiesToLoad.Add("employeeid");
  862. ds.PropertiesToLoad.Add("department");
  863. ds.PropertiesToLoad.Add("manager");
  864. SearchResultCollection results = ds.FindAll();
  865. if (results.Count > 0)
  866. {
  867. DirectoryEntry entry = results[0].GetDirectoryEntry();
  868. var adp = new ADProcessor(_mediator);
  869. //ad = adp.CreateADEntryDTO(parts[0], entry);
  870. ad = CreateADEntryDTO(parts[0], entry);
  871. }
  872. return ad;
  873. }
  874. /// <summary>
  875. ///
  876. /// </summary>
  877. /// <param name="p"></param>
  878. /// <returns></returns>
  879. public Profile GetProfileByDisplayName(string displayName, bool expand)
  880. {
  881. Profile p = null;
  882. if (!string.IsNullOrEmpty(displayName))
  883. {
  884. profile rec = _db.GetContext().profiles.FirstOrDefault(x => x.display_name.ToUpper() == displayName.ToUpper());
  885. if (rec != null)
  886. {
  887. p = CreateProfileDTO(rec, expand, true);
  888. }
  889. }
  890. return p;
  891. }
  892. public DTO.Profile AddProfile(string Username, string DisplayName, string EmployeeID, string OrgCode)
  893. {
  894. //DTO.Profile profile = new Profile(name);
  895. DTO.Profile profile = null;
  896. {
  897. //string username = Domain + "\\" + Username;
  898. //string username = Username;
  899. if (_db.GetContext().profiles.SingleOrDefault(x => x.username.ToUpper() == Username.ToUpper()) != null)
  900. {
  901. throw new Exception("Profile for " + Username + " already exists");
  902. }
  903. profile = new Profile();
  904. profile.Username = Username;
  905. profile.DisplayName = DisplayName;
  906. profile.EmployeeID = EmployeeID;
  907. profile.OrgCode = OrgCode;
  908. //if (!string.IsNullOrEmpty(entry.Manager))
  909. //{
  910. // profile.Manager = GetProfileByDisplayName(entry.Manager, false);
  911. //}
  912. SaveProfile(profile);
  913. }
  914. return profile;
  915. }
  916. /// <summary>
  917. ///
  918. /// </summary>
  919. /// <param name="search"></param>
  920. /// <returns></returns>
  921. public DTO.Profile AddProfileByADLookup(string search)
  922. {
  923. DTO.Profile profile = null;
  924. ADEntry entry = GetADEntry(search, true);
  925. if (entry != null)
  926. {
  927. string username = entry.Domain + "\\" + entry.Username;
  928. if (_db.GetContext().profiles.SingleOrDefault(x => x.username.ToUpper() == username.ToUpper()) != null)
  929. {
  930. throw new Exception("Profile for " + entry.DisplayName + " already exists");
  931. }
  932. profile = new Profile();
  933. profile.Username = username;
  934. profile.DisplayName = entry.DisplayName;
  935. profile.EmployeeID = entry.EmployeeID;
  936. profile.OrgCode = entry.OrgCode;
  937. if (!string.IsNullOrEmpty(entry.Manager))
  938. {
  939. profile.Manager = GetProfileByDisplayName(entry.Manager, false);
  940. }
  941. SaveProfile(profile);
  942. }
  943. return profile;
  944. }
  945. /// <summary>
  946. ///
  947. /// </summary>
  948. /// <param name="search"></param>
  949. /// <returns></returns>
  950. public DTO.Profile GetProfileByADLookup(string search)
  951. {
  952. ADEntry entry = GetADEntry(search, false);
  953. if (entry != null)
  954. {
  955. return GetProfileByUsername(entry.Domain + "\\" + entry.Username, false, false);
  956. }
  957. return null;
  958. }
  959. /// <summary>
  960. ///
  961. /// </summary>
  962. /// <param name="search"></param>
  963. /// <param name="multipleError"></param>
  964. /// <returns></returns>
  965. public ADEntry GetADEntry(string search, bool multipleError)
  966. {
  967. int i = 0;
  968. bool error = false;
  969. string[] searchFields = { "name", "samaccountname", "employeeid" };
  970. string domain = string.Empty;
  971. List<ADEntry> entryList = new List<ADEntry>();
  972. search = search.Trim();
  973. if (search.Contains("\\"))
  974. {
  975. string[] split = search.Split('\\');
  976. domain = split[0];
  977. search = split[1];
  978. }
  979. while (entryList.Count != 1 && i < searchFields.Count())
  980. {
  981. entryList = GetADEntryList(searchFields[i], search, domain);
  982. if (entryList.Count > 1)
  983. {
  984. error = true;
  985. }
  986. i++;
  987. }
  988. if (entryList.Count == 1)
  989. {
  990. return entryList[0];
  991. }
  992. else if (multipleError && error)
  993. {
  994. throw new Exception("Multiple users found for " + search + ".");
  995. }
  996. return null;
  997. }
  998. /// <summary>
  999. ///
  1000. /// </summary>
  1001. /// <param name="field"></param>
  1002. /// <param name="value"></param>
  1003. /// <returns></returns>
  1004. public List<ADEntry> GetADEntryList(string field, string value)
  1005. {
  1006. return GetADEntryList(field, value, null);
  1007. }
  1008. /// <summary>
  1009. ///
  1010. /// </summary>
  1011. /// <param name="filter"></param>
  1012. /// <returns></returns>
  1013. public List<ADEntry> GetADEntryList(string field, string value, string domain)
  1014. {
  1015. List<ADEntry> entries = new List<ADEntry>();
  1016. List<string> domains = new List<string>();
  1017. string dc = string.Empty;
  1018. if (!string.IsNullOrEmpty(domain))
  1019. {
  1020. domains.Add(domain);
  1021. }
  1022. else if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ADDomains"]))
  1023. {
  1024. domains.AddRange(ConfigurationManager.AppSettings["ADDomains"].Split(','));
  1025. }
  1026. if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ADDomainComponents"]))
  1027. {
  1028. string[] split = ConfigurationManager.AppSettings["ADDomainComponents"].Split(',');
  1029. foreach (string component in split)
  1030. {
  1031. dc += ",DC=" + component;
  1032. }
  1033. }
  1034. foreach (string d in domains)
  1035. {
  1036. DirectoryEntry de = new DirectoryEntry("LDAP://DC=" + d + dc);
  1037. if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ADUsername"]))
  1038. {
  1039. de.Username = ConfigurationManager.AppSettings["ADUsername"];
  1040. }
  1041. if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ADPassword"]))
  1042. {
  1043. de.Password = ConfigurationManager.AppSettings["ADPassword"];
  1044. }
  1045. DirectorySearcher ds = new DirectorySearcher(de);
  1046. ds.Filter = field + "=" + value;
  1047. ds.PropertiesToLoad.Add("samaccountname");
  1048. ds.PropertiesToLoad.Add("displayname");
  1049. ds.PropertiesToLoad.Add("employeeid");
  1050. ds.PropertiesToLoad.Add("department");
  1051. ds.PropertiesToLoad.Add("manager");
  1052. SearchResultCollection results = ds.FindAll();
  1053. foreach (SearchResult item in results)
  1054. {
  1055. ADEntry entry = CreateADEntryDTO(d, item.GetDirectoryEntry());
  1056. if (entry != null)
  1057. {
  1058. entries.Add(entry);
  1059. }
  1060. }
  1061. }
  1062. return entries;
  1063. }
  1064. /// <summary>
  1065. ///
  1066. /// </summary>
  1067. /// <param name="username"></param>
  1068. /// <returns></returns>
  1069. public Profile GetProfileByUsername(string username)
  1070. {
  1071. return GetProfileByUsername(username, true, true);
  1072. }
  1073. /// <summary>
  1074. ///
  1075. /// </summary>
  1076. /// <param name="username"></param>
  1077. /// <returns></returns>
  1078. public Profile GetProfileByUsername(string username, bool expand, bool loadManager)
  1079. {
  1080. DTO.Profile rec = null;
  1081. profile p = _db.GetContext().profiles.SingleOrDefault(x => x.username.ToUpper() == username.ToUpper());
  1082. if (p != null)
  1083. {
  1084. rec = CreateProfileDTO(p, expand, loadManager);
  1085. }
  1086. else
  1087. {
  1088. rec = new DTO.Profile();
  1089. }
  1090. return rec;
  1091. }
  1092. /// <summary>
  1093. ///
  1094. /// </summary>
  1095. /// <param name="id"></param>
  1096. /// <returns></returns>
  1097. public Profile GetProfileByEmployeeID(string id)
  1098. {
  1099. DTO.Profile rec = null;
  1100. profile p = _db.GetContext().profiles.SingleOrDefault(x => x.employee_id == id);
  1101. if (p != null)
  1102. {
  1103. rec = CreateProfileDTO(p);
  1104. }
  1105. return rec;
  1106. }
  1107. /// <summary>
  1108. ///
  1109. /// </summary>
  1110. /// <returns></returns>
  1111. public List<string> GetProfileDisplayNameList()
  1112. {
  1113. List<string> profiles = new List<string>();
  1114. var query = from item in _db.GetContext().profiles orderby item.display_name select item;
  1115. foreach (profile p in query)
  1116. {
  1117. // HACK: For some reason, _db.GetContext().profiles is including a "null" user with no display_name
  1118. if (!string.IsNullOrEmpty( p.display_name) || !string.IsNullOrEmpty(p.username))
  1119. profiles.Add(p.display_name ?? p.username);
  1120. }
  1121. return profiles;
  1122. }
  1123. /// <summary>
  1124. ///
  1125. /// </summary>
  1126. /// <param name="profileIDs"></param>
  1127. /// <param name="exempt"></param>
  1128. public void SetProfilesPlanExempt(List<long> profileIDs, bool exempt)
  1129. {
  1130. IQueryable<profile> profiles = _db.GetContext().profiles.Where(x => profileIDs.Contains(x.id));
  1131. foreach (profile p in profiles)
  1132. {
  1133. p.exempt_plan = exempt;
  1134. }
  1135. _db.SubmitChanges();
  1136. }
  1137. }
  1138. }