You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1017 lines
36 KiB

1 year ago
11 months ago
1 year ago
11 months ago
1 year ago
11 months ago
1 year ago
1 year ago
1 year ago
1 year ago
11 months ago
1 year ago
  1. using Common.Model;
  2. using Common.Model.Config;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Configuration;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Net.Mail;
  11. using System.Reflection;
  12. using System.Security.Cryptography;
  13. using System.Text;
  14. using System.Text.RegularExpressions;
  15. namespace Common.Helper
  16. {
  17. public static class Utilities
  18. {
  19. private static readonly Random Random = new Random();
  20. private static readonly string MsisdnPrefix = ApplicationConfig.ReadWebConfig("MsisdnPrefix");
  21. private static readonly string MsisdnLengthSetting = ApplicationConfig.ReadWebConfig("MsisdnLength");
  22. private static EncryptionParameters _encryptionParams;
  23. private static JsonResponse response = new JsonResponse();
  24. private static List<string> lstSupportType { get; set; }
  25. private static List<string> lstTransferType { get; set; }
  26. private static List<string> lstActionType { get; set; }
  27. //private static List<string> lstScheduleType { get; set; }
  28. /// <summary>
  29. /// Private method to initialize encryption parameters
  30. /// </summary>
  31. private static void InitializeEncryptionParameters()
  32. {
  33. _encryptionParams = new EncryptionParameters()
  34. {
  35. PassPhrase = ApplicationConfig.ReadWebConfig("symmetricKey"),
  36. HashAlgorithm = "SHA1",
  37. SaltValue = "sw!ftT3ch",
  38. PasswordIterations = 2,
  39. InitVector = "@1B2c3D4e5F6g7H8",
  40. KeySize = 256
  41. };
  42. }
  43. /// <summary>
  44. /// Encrypt string
  45. /// </summary>
  46. /// <returns></returns>
  47. private static string Encrypt(EncryptionParameters encrypt)
  48. {
  49. byte[] initVectorBytes = Encoding.ASCII.GetBytes(encrypt.InitVector);
  50. byte[] saltValueBytes = Encoding.ASCII.GetBytes(encrypt.SaltValue);
  51. // Convert our plaintext into a byte array.
  52. byte[] plainTextBytes = Encoding.UTF8.GetBytes(encrypt.PlainText);
  53. PasswordDeriveBytes password = new PasswordDeriveBytes
  54. (
  55. encrypt.PassPhrase,
  56. saltValueBytes,
  57. encrypt.HashAlgorithm,
  58. encrypt.PasswordIterations
  59. );
  60. byte[] keyBytes = password.GetBytes(encrypt.KeySize / 8);
  61. // Create uninitialized Rijndael encryption object.
  62. RijndaelManaged symmetricKey = new RijndaelManaged();
  63. symmetricKey.Mode = CipherMode.CBC;
  64. ICryptoTransform encryptor = symmetricKey.CreateEncryptor
  65. (
  66. keyBytes,
  67. initVectorBytes
  68. );
  69. // Define memory stream which will be used to hold encrypted data.
  70. MemoryStream memoryStream = new MemoryStream();
  71. // Define cryptographic stream (always use Write mode for encryption).
  72. CryptoStream cryptoStream = new CryptoStream
  73. (
  74. memoryStream,
  75. encryptor,
  76. CryptoStreamMode.Write
  77. );
  78. // Start encrypting.
  79. cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
  80. // Finish encrypting.
  81. cryptoStream.FlushFinalBlock();
  82. // Convert our encrypted data from a memory stream into a byte array.
  83. byte[] cipherTextBytes = memoryStream.ToArray();
  84. // Close both streams.
  85. memoryStream.Close();
  86. cryptoStream.Close();
  87. // Convert encrypted data into a base64-encoded string.
  88. string cipherText = Convert.ToBase64String(cipherTextBytes);
  89. // Return encrypted string.
  90. return cipherText;
  91. }
  92. /// <summary>
  93. /// Generate random 5 digit OTP
  94. /// </summary>
  95. /// <returns></returns>
  96. public static string GenerateOTP()
  97. {
  98. string[] strChar = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
  99. string otpChar = strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)];
  100. return otpChar;
  101. }
  102. /// <summary>
  103. /// Decrypt string
  104. /// </summary>
  105. /// <returns></returns>
  106. private static string Decrypt(EncryptionParameters decrypt)
  107. {
  108. byte[] initVectorBytes = Encoding.ASCII.GetBytes(decrypt.InitVector);
  109. byte[] saltValueBytes = Encoding.ASCII.GetBytes(decrypt.SaltValue);
  110. // Convert our ciphertext into a byte array.
  111. byte[] cipherTextBytes = Convert.FromBase64String(decrypt.CipherText);
  112. PasswordDeriveBytes password = new PasswordDeriveBytes
  113. (
  114. decrypt.PassPhrase,
  115. saltValueBytes,
  116. decrypt.HashAlgorithm,
  117. decrypt.PasswordIterations
  118. );
  119. // Use the password to generate pseudo-random bytes for the encryption key. Specify the
  120. // size of the key in bytes (instead of bits).
  121. byte[] keyBytes = password.GetBytes(decrypt.KeySize / 8);
  122. // Create uninitialized Rijndael encryption object.
  123. RijndaelManaged symmetricKey = new RijndaelManaged();
  124. // It is reasonable to set encryption mode to Cipher Block Chaining
  125. symmetricKey.Mode = CipherMode.CBC;
  126. ICryptoTransform decryptor = symmetricKey.CreateDecryptor
  127. (
  128. keyBytes,
  129. initVectorBytes
  130. );
  131. // Define memory stream which will be used to hold encrypted data.
  132. MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
  133. // Define cryptographic stream (always use Read mode for encryption).
  134. CryptoStream cryptoStream = new CryptoStream
  135. (
  136. memoryStream,
  137. decryptor,
  138. CryptoStreamMode.Read
  139. );
  140. byte[] plainTextBytes = new byte[cipherTextBytes.Length];
  141. // Start decrypting.
  142. int decryptedByteCount = cryptoStream.Read
  143. (
  144. plainTextBytes,
  145. 0,
  146. plainTextBytes.Length
  147. );
  148. // Close both streams.
  149. memoryStream.Close();
  150. cryptoStream.Close();
  151. // Convert decrypted data into a string.
  152. string plainText = Encoding.UTF8.GetString
  153. (
  154. plainTextBytes,
  155. 0,
  156. decryptedByteCount
  157. );
  158. // Return decrypted string.
  159. return plainText;
  160. }
  161. public static string DecryptData(string key, string encrypedData)
  162. {
  163. if (string.IsNullOrEmpty(encrypedData))
  164. {
  165. return "";
  166. }
  167. string decData = null;
  168. byte[][] keys = GetHashKeys(key);
  169. try
  170. {
  171. decData = DecryptStringFromBytes_Aes(encrypedData, keys[0], keys[1]);
  172. }
  173. catch (CryptographicException) { }
  174. catch (ArgumentNullException) { }
  175. return decData;
  176. }
  177. private static byte[][] GetHashKeys(string key)
  178. {
  179. byte[][] result = new byte[2][];
  180. Encoding enc = Encoding.UTF8;
  181. SHA256 sha2 = new SHA256CryptoServiceProvider();
  182. byte[] rawKey = enc.GetBytes(key);
  183. byte[] rawIV = enc.GetBytes(key);
  184. byte[] hashKey = sha2.ComputeHash(rawKey);
  185. byte[] hashIV = sha2.ComputeHash(rawIV);
  186. Array.Resize(ref hashIV, 16);
  187. result[0] = hashKey;
  188. result[1] = hashIV;
  189. return result;
  190. }
  191. private static string DecryptStringFromBytes_Aes(string cipherTextString, byte[] Key, byte[] IV)
  192. {
  193. byte[] cipherText = Convert.FromBase64String(cipherTextString);
  194. //final byte[] plainTextBytes = (orignalText)
  195. if (cipherText == null || cipherText.Length <= 0)
  196. throw new ArgumentNullException("cipherText");
  197. if (Key == null || Key.Length <= 0)
  198. throw new ArgumentNullException("Key");
  199. if (IV == null || IV.Length <= 0)
  200. throw new ArgumentNullException("IV");
  201. string plaintext = null;
  202. using (Aes aesAlg = Aes.Create())
  203. {
  204. aesAlg.Mode = CipherMode.CBC;
  205. aesAlg.KeySize = 256;
  206. aesAlg.BlockSize = 128;
  207. aesAlg.Padding = PaddingMode.PKCS7;
  208. aesAlg.Key = Key;
  209. aesAlg.IV = new byte[16];
  210. ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
  211. using (MemoryStream msDecrypt = new MemoryStream(cipherText))
  212. {
  213. using (CryptoStream csDecrypt =
  214. new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
  215. {
  216. using (StreamReader srDecrypt = new StreamReader(csDecrypt))
  217. {
  218. plaintext = srDecrypt.ReadToEnd();
  219. }
  220. }
  221. }
  222. }
  223. return plaintext;
  224. }
  225. /// <summary>
  226. /// Generate Random 4 digit Pin
  227. /// </summary>
  228. /// <returns></returns>
  229. public static string GenerateRandomPin()
  230. {
  231. string[] strChar = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
  232. string otpChar = strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)] + strChar[Random.Next(0, 9)];
  233. return otpChar;
  234. }
  235. /// <summary>
  236. /// Encrypt plain text to cipher text.
  237. /// </summary>
  238. /// <param name="plainText"></param>
  239. /// <returns></returns>
  240. public static string EncryptString(string plainText)
  241. {
  242. InitializeEncryptionParameters();
  243. EncryptionParameters _encrypt = new EncryptionParameters()
  244. {
  245. PlainText = plainText,
  246. PassPhrase = _encryptionParams.PassPhrase,
  247. HashAlgorithm = _encryptionParams.HashAlgorithm,
  248. SaltValue = _encryptionParams.SaltValue,
  249. PasswordIterations = _encryptionParams.PasswordIterations,
  250. InitVector = _encryptionParams.InitVector,
  251. KeySize = _encryptionParams.KeySize
  252. };
  253. var s = Utilities.Encrypt(_encrypt);
  254. return s;
  255. }
  256. /// <summary>
  257. /// Decrypt encrypted/cipher text to plain text.
  258. /// </summary>
  259. /// <param name="cipherText"></param>
  260. /// <returns></returns>
  261. public static string DecryptString(string cipherText)
  262. {
  263. try
  264. {
  265. InitializeEncryptionParameters();
  266. EncryptionParameters _decrypt = new EncryptionParameters()
  267. {
  268. CipherText = cipherText,
  269. PassPhrase = _encryptionParams.PassPhrase,
  270. HashAlgorithm = _encryptionParams.HashAlgorithm,
  271. SaltValue = _encryptionParams.SaltValue,
  272. PasswordIterations = _encryptionParams.PasswordIterations,
  273. InitVector = _encryptionParams.InitVector,
  274. KeySize = _encryptionParams.KeySize
  275. };
  276. return Utilities.Decrypt(_decrypt);
  277. }
  278. catch (Exception ex)
  279. {
  280. return "";
  281. }
  282. }
  283. /// <summary>
  284. /// Check for email validity
  285. /// </summary>
  286. /// <param name="email"></param>
  287. /// <returns></returns>
  288. public static bool IsValidEmail(this string email)
  289. {
  290. return Regex.IsMatch(email ?? "", ApplicationConfig.ReadWebConfig("regex"), RegexOptions.IgnoreCase);
  291. }
  292. /// <summary>
  293. /// Check for residence card number
  294. /// </summary>
  295. /// <param name="residenceCardNo"></param>
  296. /// <returns></returns>
  297. public static bool IsValidNumber(this string residenceCardNo)
  298. {
  299. return Regex.IsMatch(residenceCardNo ?? "", ApplicationConfig.ReadWebConfig("regexResidenceCard"), RegexOptions.IgnoreCase);
  300. }
  301. public static bool IsValidMobileNumber(this string mobile)
  302. {
  303. return Regex.IsMatch(mobile ?? "", ApplicationConfig.ReadWebConfig("regexMobile"), RegexOptions.IgnoreCase);
  304. }
  305. public static bool IsValidDrivingNumber(this string drivingNo)
  306. {
  307. return Regex.IsMatch(drivingNo ?? "", ApplicationConfig.ReadWebConfig("regexDrivingLiscence"), RegexOptions.IgnoreCase);
  308. }
  309. public static bool IsCheckAdditionalId()
  310. {
  311. var additionalid = ApplicationConfig.ReadWebConfig("CheckAdditinalID");
  312. if (additionalid != null && additionalid.Equals("Y"))
  313. return true;
  314. else
  315. return false;
  316. }
  317. /// <summary>
  318. /// Check for 4 digit pin number
  319. /// </summary>
  320. /// <param name="pin"></param>
  321. /// <returns></returns>
  322. public static bool IsValidPin(this string pin)
  323. {
  324. if (!string.IsNullOrEmpty(pin))
  325. {
  326. int iPin;
  327. if (pin.Length != 4)
  328. {
  329. return false;
  330. }
  331. return int.TryParse(pin, out iPin);
  332. }
  333. else
  334. {
  335. return false;
  336. }
  337. }
  338. /// <summary>
  339. /// Check Wether the Mobile Number is Valid or not
  340. /// </summary>
  341. /// <param name="msisdn"></param>
  342. /// <returns></returns>
  343. public static bool IsValidMsisdn(this string msisdn)
  344. {
  345. int minPrefix = 2;
  346. int maxPrefix = 4;
  347. int chkFlag = 0;
  348. if (!string.IsNullOrEmpty(msisdn))
  349. {
  350. long iMsisdn;
  351. var splitMsisdnLength = MsisdnLengthSetting.Split('|').ToList();
  352. if (splitMsisdnLength.Contains(msisdn.Length.ToString()))
  353. {
  354. var splitPrefix = MsisdnPrefix.Split('|').ToList();
  355. for (int i = minPrefix; i <= maxPrefix; i++)
  356. {
  357. if (splitPrefix.Contains(msisdn.Substring(0, i))) //checking prefix
  358. {
  359. chkFlag = 1;
  360. break;
  361. }
  362. else
  363. {
  364. continue;
  365. }
  366. }
  367. if (chkFlag == 0)
  368. {
  369. return false;
  370. }
  371. }
  372. else
  373. {
  374. return false;
  375. }
  376. return long.TryParse(msisdn, out iMsisdn);
  377. }
  378. else
  379. {
  380. return false;
  381. }
  382. }
  383. public static bool IsValidARCFormat(string idType, string vin)
  384. {
  385. if (idType == ApplicationConfig.ReadWebConfig("kycVerificationIdType") || idType == ApplicationConfig.ReadWebConfig("kycNationalIdType"))
  386. {
  387. var number = vin.Split('-');
  388. if (number.Length != 2)
  389. {
  390. return false;
  391. }
  392. else if (number[0].Length != 6 || number[1].Length != 7)
  393. {
  394. return false;
  395. }
  396. else
  397. {
  398. return true;
  399. }
  400. }
  401. else
  402. {
  403. return true;
  404. }
  405. }
  406. /// <summary>
  407. /// Generate Random Password
  408. /// </summary>
  409. /// <param name="length"></param>
  410. /// <returns></returns>
  411. public static string GenerateRandomPassword(int length)
  412. {
  413. const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  414. return new string(Enumerable.Repeat(chars, length)
  415. .Select(s => s[Random.Next(s.Length)]).ToArray());
  416. }
  417. public static string GetTimestamp(DateTime value)
  418. {
  419. return value.ToString("yyyyMMddHHmmssffff");
  420. }
  421. /// <summary>
  422. /// Used to send email
  423. /// </summary>
  424. /// <param name="emailParameters"></param>
  425. /// <returns></returns>
  426. public static JsonResponse SendEmail(SendEmailParameters emailParameters)
  427. {
  428. MailMessage mail = new MailMessage();
  429. SmtpClient SmtpServer = new SmtpClient();
  430. try
  431. {
  432. SmtpServer.Host = ApplicationConfig.ReadWebConfig("smtp");
  433. SmtpServer.Port = Convert.ToInt16(ApplicationConfig.ReadWebConfig("port"));
  434. SmtpServer.Credentials = new System.Net.NetworkCredential(ApplicationConfig.ReadWebConfig("mailFrom"), ApplicationConfig.ReadWebConfig("emailPwd"));
  435. SmtpServer.EnableSsl = Convert.ToBoolean(ApplicationConfig.ReadWebConfig("enableSSL"));
  436. mail.From = new MailAddress(ApplicationConfig.ReadWebConfig("mailFrom"), ApplicationConfig.ReadWebConfig("mailSender"));
  437. mail.To.Add(emailParameters.ToEmails);
  438. if (!string.IsNullOrEmpty(emailParameters.CcEmails))
  439. mail.CC.Add(emailParameters.CcEmails);
  440. if (!string.IsNullOrEmpty(emailParameters.BccEmails))
  441. mail.Bcc.Add(emailParameters.BccEmails);
  442. mail.Subject = emailParameters.MsgSubject;
  443. mail.IsBodyHtml = true;
  444. mail.Body = emailParameters.MsgBody;
  445. SmtpServer.Send(mail);
  446. response.SetResponseMessage(HttpStatusCode.OK, "Message sent successfully");
  447. }
  448. catch (SmtpFailedRecipientsException ex)
  449. {
  450. for (int i = 0; i < ex.InnerExceptions.Length; i++)
  451. {
  452. SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
  453. if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable)
  454. {
  455. // Console.WriteLine("Delivery failed - retrying in 5 seconds.");
  456. System.Threading.Thread.Sleep(5000);
  457. SmtpServer.Send(mail);
  458. response.SetResponseMessage(HttpStatusCode.OK, "Message sent successfully");
  459. }
  460. else
  461. {
  462. response.SetResponseMessage(HttpStatusCode.BadRequest, ex.InnerExceptions[i].FailedRecipient);
  463. // Console.WriteLine("Failed to deliver message to {0}", ex.InnerExceptions[i].FailedRecipient);
  464. //throw ex;
  465. //smtpMail.Status = "N";
  466. //GetStatic.EmailNotificationLog(smtpMail);
  467. }
  468. }
  469. }
  470. catch (Exception ex)
  471. {
  472. response.SetResponseMessage(HttpStatusCode.BadRequest, ex.Message);
  473. }
  474. return response;
  475. }
  476. /// <summary>
  477. /// To check the properties of a class for Null/Empty values
  478. /// </summary>
  479. /// <param name="obj">The instance of the class</param>
  480. /// <returns>Result of the evaluation</returns>
  481. public static bool IsAnyNullOrEmpty(object obj)
  482. {
  483. //Step 1: Set the count variable to check for the count of 2.
  484. int count = 0;
  485. try
  486. {
  487. //Step 2: Check if the incoming object has values or not.
  488. if (obj != null)
  489. {
  490. //Step 3: Iterate over the properties and check for null values based on the type.
  491. foreach (PropertyInfo pi in obj.GetType().GetProperties())
  492. {
  493. if (count >= 2)
  494. {
  495. return true;
  496. }
  497. dynamic value;
  498. if (pi.PropertyType == typeof(string))
  499. {
  500. value = (string)pi.GetValue(obj);
  501. if (!string.IsNullOrEmpty(value))
  502. {
  503. count++;
  504. }
  505. }
  506. else if (pi.PropertyType == typeof(int))
  507. {
  508. value = (int)pi.GetValue(obj);
  509. if (value > 0)
  510. {
  511. count++;
  512. }
  513. }
  514. else if (pi.PropertyType == typeof(List<string>))
  515. {
  516. value = (List<string>)pi.GetValue(obj);
  517. if (value != null)
  518. {
  519. if (value.Count > 0)
  520. {
  521. count++;
  522. }
  523. }
  524. }
  525. else if (pi.PropertyType == typeof(bool))
  526. {
  527. value = pi.GetValue(obj);
  528. if (value != null)
  529. {
  530. count++;
  531. }
  532. }
  533. }
  534. //Step 4: Check if the count variable is >2 that means there is atleast one parameter passed in the body
  535. if (count >= 2)
  536. {
  537. return true;
  538. }
  539. }
  540. }
  541. catch (Exception ex)
  542. {
  543. throw ex;
  544. }
  545. return false;
  546. }
  547. public static string ConvertToUnixTimestamp(string str)
  548. {
  549. try
  550. {
  551. DateTime date = Convert.ToDateTime(str);
  552. DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
  553. TimeSpan diff = date - origin;
  554. return Math.Floor(diff.TotalSeconds).ToString();
  555. }
  556. catch (Exception)
  557. {
  558. return "";
  559. }
  560. }
  561. public static bool ConvertToGlobalFormat(string param)
  562. {
  563. try
  564. {
  565. if (string.IsNullOrEmpty(param))
  566. {
  567. return true;
  568. }
  569. DateTime dt;
  570. string[] formats = { "yyyy-MM-dd", "yyyy/MM/dd", "MM/dd/yyyy", "MM-dd-yyyy", "dd/MM/yyyy" };
  571. if (DateTime.TryParseExact(param, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt))
  572. {
  573. return true;
  574. }
  575. else
  576. {
  577. return false;
  578. }
  579. }
  580. catch (Exception ex)
  581. {
  582. return false;
  583. }
  584. }
  585. public static String ShowDecimal(String strVal)
  586. {
  587. if (strVal != "")
  588. return String.Format("{0:0,0.00}", double.Parse(strVal));
  589. else
  590. return strVal;
  591. }
  592. public static bool IsSupportTypeValid(string str)
  593. {
  594. var lstSupportType = LoadSupportType();
  595. return lstSupportType.Contains(str) ? true : false;
  596. }
  597. private static List<string> LoadSupportType()
  598. {
  599. if (lstSupportType == null)
  600. {
  601. lstSupportType = new List<string>();
  602. lstSupportType.Add("feedback");
  603. lstSupportType.Add("enquiry");
  604. }
  605. return lstSupportType;
  606. }
  607. public static bool IsTransferTypeValid(string type)
  608. {
  609. var lstTransferType = LoadTransferType();
  610. return lstTransferType.Contains(type) ? true : false;
  611. }
  612. private static List<string> LoadTransferType()
  613. {
  614. if (lstTransferType == null)
  615. {
  616. lstTransferType = new List<string>();
  617. lstTransferType.Add("offer");
  618. lstTransferType.Add("request");
  619. }
  620. return lstTransferType;
  621. }
  622. public static bool IsActionTypeValid(string type)
  623. {
  624. var lstActionType = LoadActionType();
  625. return lstActionType.Contains(type) ? true : false;
  626. }
  627. private static List<string> LoadActionType()
  628. {
  629. if (lstActionType == null)
  630. {
  631. lstActionType = new List<string>();
  632. lstActionType.Add("accept");
  633. lstActionType.Add("reject");
  634. }
  635. return lstActionType;
  636. }
  637. //public static bool IsScheduleTypeValid(string type)
  638. //{
  639. // var lstScheduleType = LoadScheduleType();
  640. // return lstScheduleType.Contains(type) ? true : false;
  641. //}
  642. //private static List<string> LoadScheduleType()
  643. //{
  644. // if (lstScheduleType == null)
  645. // {
  646. // lstScheduleType = new List<string>();
  647. // lstScheduleType.Add("0");
  648. // lstScheduleType.Add("1");
  649. // }
  650. // return lstScheduleType;
  651. //}
  652. public static int GetOriginalLengthInBytes(string base64string)
  653. {
  654. if (string.IsNullOrEmpty(base64string)) { return 0; }
  655. var characterCount = base64string.Length;
  656. var paddingCount = base64string.Substring(characterCount - 2, 2)
  657. .Count(c => c == '=');
  658. return (3 * (characterCount / 4)) - paddingCount;
  659. }
  660. public static string[] SelectDistinct(this string[] array)
  661. {
  662. return array.Distinct().ToArray();
  663. }
  664. public static string ReadWebConfig(string key, string defValue)
  665. {
  666. var Key = ConfigurationManager.AppSettings[key] ?? defValue;
  667. return Key;
  668. }
  669. public static bool CheckDateType(string date)
  670. {
  671. DateTime dt;
  672. string[] formats = { "yyyy-MM-dd" };
  673. if (!DateTime.TryParseExact(date, formats,
  674. System.Globalization.CultureInfo.InvariantCulture,
  675. DateTimeStyles.None, out dt))
  676. {
  677. return false;
  678. }
  679. else
  680. {
  681. return true;
  682. }
  683. }
  684. public static KYCConfigDto GetKYCSettings(KycRequest obj)
  685. {
  686. KYCConfigDto dt = new KYCConfigDto() { Config = new TrustDocConfig(), Options = new List<KYCOption>() };
  687. KYCConfig referenceMaps = new KYCConfig();
  688. //string mappingPath = mappingPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, obj.DeviceType.ToLower().Equals("android") ? "config\\KycConfig-uat.json" : ConfigurationManager.AppSettings["KycConfigFilePath"].ToString());
  689. string mappingPath = mappingPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["KycConfigFilePath"].ToString());
  690. using (StreamReader reader = File.OpenText(mappingPath))
  691. {
  692. var jsonS = reader.ReadToEnd();
  693. referenceMaps = Newtonsoft.Json.JsonConvert.DeserializeObject<KYCConfig>(jsonS);
  694. }
  695. if (!string.IsNullOrEmpty(obj.DeviceType))
  696. {
  697. dt.Config = referenceMaps.Config.Where(x => x.DeviceType.ToLower().Equals(obj.DeviceType.ToLower())).SingleOrDefault();
  698. }
  699. dt.Options = referenceMaps.Options;
  700. return dt;
  701. }
  702. public static List<Option> GetPaymetMethods()
  703. {
  704. List<Option> options = new List<Option>();
  705. string mappingPath = mappingPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["PaymentConfigFilePath"].ToString());
  706. using (StreamReader reader = File.OpenText(mappingPath))
  707. {
  708. var jsonS = reader.ReadToEnd();
  709. options = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Option>>(jsonS);
  710. }
  711. return options;
  712. }
  713. public static List<ReferenceMap> GetReferenceMaps()
  714. {
  715. List<ReferenceMap> referenceMaps = new List<ReferenceMap>();
  716. string mappingPath = mappingPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["MappingFilePath"].ToString());
  717. using (StreamReader reader = File.OpenText(mappingPath))
  718. {
  719. var jsonS = reader.ReadToEnd();
  720. referenceMaps = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Model.Config.ReferenceMap>>(jsonS);
  721. }
  722. return referenceMaps;
  723. }
  724. public static List<ReferenceMap> GetReferenceMaps(MappingType type)
  725. {
  726. var lstReferences = GetReferenceMaps().Where(x => x.Type.Equals(type.ToString()));
  727. return lstReferences.ToList();
  728. }
  729. public static Mapping GetMapping(MappingType type, string keyValue = "")
  730. {
  731. Mapping map = new Mapping();
  732. try
  733. {
  734. if (string.IsNullOrEmpty(keyValue))
  735. {
  736. return new Mapping();
  737. }
  738. var lstReferences = GetReferenceMaps().Where(x => x.Type.Equals(type.ToString())).SingleOrDefault();
  739. map = lstReferences.Mappings.FirstOrDefault(x => (!String.IsNullOrEmpty(x.field) ? x.field.Trim().ToUpper() : "").Equals(keyValue.ToUpper().Trim()));
  740. }
  741. catch (Exception e)
  742. {
  743. throw e;
  744. }
  745. return map != null ? map : new Mapping();
  746. }
  747. #region LANGUAGE MAPPING
  748. public static List<LanguageMap> GetReferenceLangMaps()
  749. {
  750. List<LanguageMap> referenceMaps = new List<LanguageMap>();
  751. string mappingPath = mappingPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigurationManager.AppSettings["LangFilePath"].ToString());
  752. using (StreamReader reader = File.OpenText(mappingPath))
  753. {
  754. var jsonS = reader.ReadToEnd();
  755. referenceMaps = Newtonsoft.Json.JsonConvert.DeserializeObject<List<LanguageMap>>(jsonS);
  756. }
  757. return referenceMaps;
  758. }
  759. #endregion
  760. public static LanguageMap GetLanguageMapping(string keyValue, string lang = "en")
  761. {
  762. LanguageMap map = new LanguageMap();
  763. try
  764. {
  765. if (string.IsNullOrEmpty(keyValue))
  766. {
  767. return new LanguageMap();
  768. }
  769. if (lang.Equals("np"))
  770. {
  771. lang = "ne";
  772. }
  773. else if (lang.Equals("bd"))
  774. {
  775. lang = "bn";
  776. }
  777. else if (lang.Equals("vn"))
  778. {
  779. lang = "vi";
  780. }
  781. map = GetReferenceLangMaps().FirstOrDefault(x => x.Key.ToUpper().Equals(keyValue.ToUpper())
  782. && (!String.IsNullOrEmpty(x.Lang) ? x.Lang.Trim().ToUpper() : "EN").Equals(lang.ToUpper().Trim()));
  783. if (map != null && string.IsNullOrEmpty(map.Message))
  784. {
  785. map = GetReferenceLangMaps().FirstOrDefault(x => x.Key.ToUpper().Equals(keyValue.ToUpper()) && x.Lang.Trim().ToUpper().Equals("EN"));
  786. }
  787. else if (map == null)
  788. {
  789. map = GetReferenceLangMaps().FirstOrDefault(x => x.Key.ToUpper().Equals(keyValue.ToUpper()) && x.Lang.Trim().ToUpper().Equals("EN"));
  790. }
  791. }
  792. catch (Exception e)
  793. {
  794. throw e;
  795. }
  796. return map != null ? map : new LanguageMap();
  797. }
  798. // Reflection
  799. public static List<KeyValuePair> GetPropertiesNameOfClass(this object atype)
  800. {
  801. if (atype == null) return new List<KeyValuePair>();
  802. Type t = atype.GetType();
  803. PropertyInfo[] props = t.GetProperties(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
  804. List<KeyValuePair> dict = new List<KeyValuePair>();
  805. foreach (PropertyInfo prp in props)
  806. {
  807. object propValue = prp.GetValue(atype, new object[] { });
  808. dict.Add(new KeyValuePair { Key = prp.Name, Value = propValue != null ? propValue.ToString() : "" });
  809. }
  810. var bankId = GetPropertyValue(atype, "agent.id");
  811. dict.Add(new KeyValuePair { Key = "agent.id", Value = bankId != null ? bankId.ToString() : "" });
  812. var bankname = GetPropertyValue(atype, "agent.name");
  813. dict.Add(new KeyValuePair { Key = "agent.name", Value = bankname != null ? bankname.ToString() : "" });
  814. var branch = GetPropertyValue(atype, "agent.branch.id");
  815. dict.Add(new KeyValuePair { Key = "agent.branch.id", Value = branch != null ? branch.ToString() : "" });
  816. var accountno = GetPropertyValue(atype, "agent.accountNo");
  817. dict.Add(new KeyValuePair { Key = "agent.accountNo", Value = accountno != null ? accountno.ToString() : "" });
  818. return dict;
  819. }
  820. public static object GetPropertyValue(object src, string propName)
  821. {
  822. if (src == null)
  823. return null;
  824. if (propName == null) throw new ArgumentException("Value cannot be null.", "propName");
  825. if (propName.Contains("."))//complex type nested
  826. {
  827. var temp = propName.Split(new char[] { '.' }, 2);
  828. return GetPropertyValue(GetPropertyValue(src, temp[0]), temp[1]);
  829. }
  830. else
  831. {
  832. var prop = src.GetType().GetProperty(propName);
  833. return prop != null ? prop.GetValue(src, null) : null;
  834. }
  835. }
  836. public static string GetFullName(string fname, string mname, string lname)
  837. {
  838. string fullName = string.Empty;
  839. fullName = string.Format("{0} {1}", (!string.IsNullOrEmpty(mname)) ? fname + " " + mname : fname, lname);
  840. return fullName;
  841. }
  842. public static string getUKFormattedNumber(this string number)
  843. {
  844. string finalNo = number;
  845. if (!number.Contains("+44"))
  846. {
  847. string mobileFirst = number.Substring(0, 1);
  848. if (mobileFirst == "0")
  849. {
  850. if (number.Length == 11)
  851. {
  852. finalNo = "+44" + number.Substring(1, number.Length - 1);
  853. return finalNo;
  854. }
  855. else if (number.Length < 11)
  856. {
  857. finalNo = $"+44{number}";
  858. }
  859. }
  860. else if (number.Substring(0, 1) != "0" && number.Length == 10)
  861. {
  862. finalNo = $"+44{number}";
  863. }
  864. }
  865. else if (number.Contains("+44"))
  866. {
  867. string MobN = number.Substring(4, 1);
  868. if (MobN == "0" && number.Length > 14)
  869. {
  870. finalNo = number.Remove(4, 1);
  871. }
  872. }
  873. if (!finalNo.Substring(0, 1).Contains("+"))
  874. {
  875. finalNo = $"+{finalNo}";
  876. }
  877. return finalNo;
  878. }
  879. }
  880. }