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.

2809 lines
103 KiB

3 months ago
10 months ago
10 months ago
10 months ago
  1. using Swift.API.Common;
  2. using Swift.DAL.BL.Remit.Transaction;
  3. using Swift.DAL.BL.Remit.Transaction.PayTransaction;
  4. using Swift.DAL.BL.System.Notification;
  5. using Swift.DAL.SwiftDAL;
  6. using Swift.web.SwiftSystem.UserManagement.ApplicationUserPool;
  7. using System;
  8. using System.Collections;
  9. using System.Collections.Generic;
  10. using System.Configuration;
  11. using System.Data;
  12. using System.Text;
  13. using System.Text.RegularExpressions;
  14. using System.Web;
  15. using System.Web.Script.Serialization;
  16. using System.Web.UI;
  17. using System.Web.UI.WebControls;
  18. using Swift.DAL.Common;
  19. using System.Net;
  20. using System.IO;
  21. using System.Xml.Serialization;
  22. using SelectPdf;
  23. using Newtonsoft.Json;
  24. using System.Linq;
  25. using System.Security.Cryptography;
  26. //using SelectPdf;
  27. namespace Swift.web.Library
  28. {
  29. public static class GetStatic
  30. {
  31. public static DbResult LogError(HttpException lastError, string page)
  32. {
  33. Exception err = lastError;
  34. if (lastError.InnerException != null)
  35. err = lastError.InnerException;
  36. RemittanceDao db = new RemittanceDao();
  37. var errPage = db.FilterString(page);
  38. var errMsg = db.FilterString(err.Message);
  39. var errDetails = db.FilterString(lastError.GetHtmlErrorMessage());
  40. var user = string.IsNullOrWhiteSpace(GetUser()) ? "'UNKNOWN'" : GetUser();
  41. string sql = string.Format(@"EXEC proc_ErrorLogs @flag = 'i', @errorPage={0}, @errorMsg={1}, @errorDetails={2}, @user = {3}", errPage, errMsg, errDetails, user);
  42. return db.ParseDbResult(sql);
  43. }
  44. internal static void AttachConfirmMsg(ref object btnApprove, string v)
  45. {
  46. throw new NotImplementedException();
  47. }
  48. public static string UploadDocument(HttpPostedFile doc, string customerId, string documentTypeName, string membershipId, string registeredDate, out string fileType)
  49. {
  50. fileType = "";
  51. string fName = "";
  52. string documentExtension = "";
  53. try
  54. {
  55. fileType = doc.ContentType;
  56. string fileExtension = new FileInfo(doc.FileName).Extension;
  57. if (documentTypeName.ToLower() == "other_document" || documentTypeName.ToLower() == "registration_form" || documentTypeName.ToLower() == "beneficiary_registration_form")
  58. {
  59. documentExtension = GetStatic.ReadWebConfig("customerDocFileExtension", "");
  60. }
  61. else
  62. {
  63. documentExtension = GetStatic.ReadWebConfig("customerDocFileExtension", "");
  64. }
  65. if (documentExtension.ToLower().Contains(fileExtension.ToLower()))
  66. {
  67. string fileName = documentTypeName + "_" + GetStatic.GetDateTimeStamp() + "_" + GetStatic.GetUser() + fileExtension;
  68. string path = GetStatic.GetCustomerFilePath() + "CustomerDocument\\" + registeredDate.Replace("-", "\\") + "\\" + membershipId;
  69. if (!Directory.Exists(path))
  70. Directory.CreateDirectory(path);
  71. doc.SaveAs(path + "/" + fileName);
  72. fName = fileName;
  73. }
  74. else
  75. {
  76. fName = "notValid";
  77. }
  78. }
  79. catch (Exception ex)
  80. {
  81. fName = "";
  82. }
  83. return fName;
  84. }
  85. public static void EmailNotificationLog(SmtpMailSetting smtpMail)
  86. {
  87. RemittanceDao db = new RemittanceDao();
  88. string sql = "";
  89. sql = "EXEC proc_emailNotes @flag = 'i'";
  90. sql += ", @sendFrom=" + db.FilterString(smtpMail.SendEmailId);
  91. sql += ", @sendTo=" + db.FilterString(smtpMail.ToEmails);
  92. sql += ", @sendCc=" + db.FilterString(smtpMail.CcEmails);
  93. sql += ", @sendBcc=" + db.FilterString(smtpMail.BccEmails);
  94. sql += ", @subject=" + db.FilterString(smtpMail.MsgSubject);
  95. sql += ", @user=''";
  96. sql += ", @sendStatus=" + db.FilterString(smtpMail.Status);
  97. sql += ", @errorMsg=" + db.FilterString(smtpMail.MsgBody);
  98. db.ExecuteDataRow(sql);
  99. }
  100. public static int ToInt(this string val)
  101. {
  102. int myval;
  103. if (int.TryParse(val.Trim(), out myval))
  104. {
  105. return myval;
  106. }
  107. else
  108. return 0;
  109. }
  110. public static decimal ToDecimal(this string val)
  111. {
  112. decimal myval;
  113. if (decimal.TryParse(val.Trim(), out myval))
  114. {
  115. return myval;
  116. }
  117. else
  118. return 0;
  119. }
  120. public static DateTime? ParseDateTime(this string val)
  121. {
  122. DateTime myval;
  123. if (DateTime.TryParse(val.Trim(), out myval))
  124. {
  125. return myval;
  126. }
  127. else
  128. return null;
  129. }
  130. public static string ToDate(this string val)
  131. {
  132. DateTime myval;
  133. if (DateTime.TryParse(val.Trim(), out myval))
  134. {
  135. return myval.ToString("yyyy-MM-dd");
  136. }
  137. else
  138. return "";
  139. }
  140. public static string RemoveComaFromMoney(string amt)
  141. {
  142. try
  143. {
  144. var Split = amt.Split('.');
  145. amt = Split[0];
  146. }
  147. catch (Exception e)
  148. {
  149. amt = "";
  150. }
  151. return amt.Replace(",", "");
  152. }
  153. public static DbResult CheckSlab(string pcnt, string minAmt, string maxAmt)
  154. {
  155. //bool PreError = false;
  156. var dbResult = new DbResult();
  157. if ((pcnt == "" ? "0" : pcnt) != "0")
  158. {
  159. if ((minAmt == "" ? "0" : minAmt) == "0" || (maxAmt == "" ? "0" : maxAmt) == "0")
  160. {
  161. dbResult.Id = "1";
  162. dbResult.Msg = "Please set Min or Max Amt ..";
  163. //PreError = true;
  164. }
  165. }
  166. else if ((pcnt == "" ? "0" : pcnt) == "0" && (minAmt == "" ? "0" : minAmt) == "0")
  167. {
  168. dbResult.Id = "1";
  169. dbResult.Msg = "Please set Min Amt ..";
  170. //PreError = true;
  171. }
  172. return dbResult;
  173. }
  174. public static void Process(ref Button ctl)
  175. {
  176. var function = "return Process();";
  177. ctl.Attributes.Add("onclick", function);
  178. }
  179. public static double GetPayAmountLimit(string controlNo)
  180. {
  181. var pay = new PayDao();
  182. var limitAmount = pay.GetPayAmountLimit(GetStatic.GetUser(), controlNo);
  183. return limitAmount;
  184. }
  185. public static string GetSendingCountryBySCurr(string sCurr)
  186. {
  187. //var db = new SwiftDao();
  188. RemittanceDao db = new RemittanceDao();
  189. var sql = "EXEC proc_transactionUtility @flag='sCountry', @user=" + db.FilterString(GetUser()) + ", @curr=" + db.FilterString(sCurr);
  190. return db.GetSingleResult(sql);
  191. }
  192. public static string GetOFACSDN()
  193. {
  194. return ReadWebConfig("OFAC_SDN");
  195. }
  196. public static string GetOFACALT()
  197. {
  198. return ReadWebConfig("OFAC_ALT");
  199. }
  200. public static string GetOFACADD()
  201. {
  202. return ReadWebConfig("OFAC_ADD");
  203. }
  204. public static string GetOFACUNSCR()
  205. {
  206. return ReadWebConfig("OFAC_UNSCR");
  207. }
  208. public static string RemoveAllTags(string html)
  209. {
  210. var loop = true;
  211. var pFrom = 0;
  212. var pTo = 0;
  213. var refined = html;
  214. while (loop)
  215. {
  216. pFrom = refined.IndexOf("<");
  217. pTo = refined.IndexOf(">");
  218. var t = refined.Substring(pFrom, pTo + 1 - pFrom);
  219. if (string.IsNullOrWhiteSpace(t))
  220. {
  221. return refined.Trim();
  222. }
  223. refined = refined.Replace(t, "");
  224. loop = refined.Contains("<") || refined.Contains(">");
  225. }
  226. return refined.Trim();
  227. }
  228. public static string RemoveHtmlTagsRegex(string input)
  229. {
  230. return Regex.Replace(input, "<.*?>", string.Empty);
  231. }
  232. public static String ShowFormatedCommaAmt(string strVal)
  233. {
  234. if (strVal != "")
  235. {
  236. var amt = double.Parse(strVal);
  237. amt = (amt < 0 ? amt * -1 : amt);
  238. return amt.ToString("C", System.Globalization.CultureInfo.CreateSpecificCulture("ko-KR"));
  239. }
  240. //return String.Format("{0:c}", double.Parse(strVal));
  241. else
  242. return strVal;
  243. }
  244. //public static string ReplaceFirst(string text, string search, string replace)
  245. //{
  246. // int pos = text.IndexOf(search);
  247. // if (pos < 0)
  248. // {
  249. // return text;
  250. // }
  251. // return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
  252. //}
  253. public static void GetPDF(string data)
  254. {
  255. //string newData = ReplaceFirst(data, "<table", "<table border='1' ");
  256. //string htmlData = newData;
  257. //SelectPdf.HtmlToPdf converter = new SelectPdf.HtmlToPdf();
  258. //converter.Options.PdfPageSize = PdfPageSize.A4;
  259. //converter.Options.PdfPageOrientation = PdfPageOrientation.Landscape;
  260. //converter.Options.WebPageWidth = 1024;
  261. //converter.Options.WebPageHeight = 0;
  262. //PdfDocument doc = converter.ConvertHtmlString(data);
  263. //doc.Save(HttpContext.Current.Response, true, "Report.pdf");
  264. //doc.Close();
  265. }
  266. public static string TXNDocumentUploadPath()
  267. {
  268. return ReadWebConfig("txnDocumentUploadPath");
  269. }
  270. public static string GetUserDateTime()
  271. {
  272. var db = new RemittanceDao();
  273. var sql = "EXEC proc_MatrixReport @flag = 'udt', @user = '" + GetUser() + "'";
  274. return db.GetSingleResult(sql);
  275. }
  276. public static string GetBranchName()
  277. {
  278. return ReadSession("branchName", "");
  279. }
  280. public static string GetAgentName()
  281. {
  282. return ReadSession("agentName", "");
  283. }
  284. public static string GetSuperAgent()
  285. {
  286. return ReadSession("superAgent", "");
  287. }
  288. public static string GetSuperAgentName()
  289. {
  290. return ReadSession("superAgentName", "");
  291. }
  292. public static string GetAgentType()
  293. {
  294. return ReadSession("agentType", "");
  295. }
  296. public static string GetSettlingAgent()
  297. {
  298. return ReadSession("settlingAgent", "");
  299. }
  300. public static string GetTranNoName()
  301. {
  302. return ReadWebConfig("tranNoName");
  303. }
  304. public static string GetAgentNameByMapCodeInt(string mapCodeInt)
  305. {
  306. var db = new SwiftDao();
  307. var sql = "SELECT agent_name FROM FastMoneyPro_account.dbo.agentTable with(nolock) where map_code = '" + mapCodeInt + "'";
  308. return db.GetSingleResult(sql);
  309. }
  310. public static string GetMapCodeInt()
  311. {
  312. return ReadSession("mapCodeInt", "");
  313. }
  314. public static string GetIsApiFlag()
  315. {
  316. return ReadWebConfig("isAPI");
  317. }
  318. public static string GetisSendPush()
  319. {
  320. return ReadWebConfig("isSendPush");
  321. }
  322. public static string GetMapCodeDom()
  323. {
  324. return ReadSession("mapCodeDom", "");
  325. }
  326. public static string GetIsActAsBranch()
  327. {
  328. return ReadSession("isActAsBranch", "");
  329. }
  330. public static string GetParentMapCodeInt()
  331. {
  332. return ReadSession("parentMapCodeInt", "");
  333. }
  334. public static string GetFundDepositVoucherPath()
  335. {
  336. return ReadWebConfig("fundDepositVoucher");
  337. }
  338. public static void AddTroubleTicket(Page page, string controlNo, string message, int successMessageType)
  339. {
  340. var obj = new TranViewDao();
  341. if (successMessageType == 1)
  342. PrintSuccessMessage(page, "Ticket Added Successfully");
  343. else if (successMessageType == 2)
  344. AlertMessage(page, "Ticket Added Successfully");
  345. ResizeFrame(page);
  346. }
  347. public static string GetFromSendTrnTime()
  348. {
  349. return ReadSession("fromSendTrnTime", "");
  350. }
  351. public static string GetToSendTrnTime()
  352. {
  353. return ReadSession("toSendTrnTime", "");
  354. }
  355. public static string GetFromPayTrnTime()
  356. {
  357. return ReadSession("fromPayTrnTime", "");
  358. }
  359. public static string GetToPayTrnTime()
  360. {
  361. return ReadSession("toPayTrnTime", "");
  362. }
  363. public static string GetCountryFlag(string countryCode)
  364. {
  365. var html = "<img src=\"" + GetUrlRoot() + "/images/countryflag/" + countryCode + ".png" + "\" border=\"0\">";
  366. return html;
  367. }
  368. public static void DataTable2ExcelDownload(ref DataTable table, string fileName)
  369. {
  370. string fileName_forSave = fileName + "_" + DateTime.Now.Year + "_" + DateTime.Now.Month + "_" + DateTime.Now.Day + "_" + DateTime.Now.ToString("hhmmss");
  371. HttpContext.Current.Response.Clear();
  372. HttpContext.Current.Response.ClearContent();
  373. HttpContext.Current.Response.ClearHeaders();
  374. HttpContext.Current.Response.Buffer = true;
  375. HttpContext.Current.Response.ContentType = "application/ms-excel";
  376. HttpContext.Current.Response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
  377. HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName_forSave + ".xls");
  378. HttpContext.Current.Response.Charset = "utf-8";
  379. HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
  380. //sets font
  381. HttpContext.Current.Response.Write("<font style='font-size:10.0pt; font-family:Calibri;'>");
  382. HttpContext.Current.Response.Write("<br/><br/><br/>");
  383. //sets the table border, cell spacing, border color, font of the text, background, foreground, font height
  384. HttpContext.Current.Response.Write("<table border='1' bgColor='#ffffff' " +
  385. "borderColor='#000000' cellSpacing='0' cellPadding='0' " +
  386. "style='font-size:10.0pt; font-family:Calibri; background:white;'> <tr>");
  387. //am getting my grid's column headers
  388. int columnscount = table.Columns.Count;
  389. for (int j = 0; j < columnscount; j++)
  390. { //write in new column
  391. HttpContext.Current.Response.Write("<td>");
  392. //Get column headers and make it as bold in excel columns
  393. HttpContext.Current.Response.Write("<strong>");
  394. HttpContext.Current.Response.Write(table.Columns[j].ColumnName.ToString());
  395. HttpContext.Current.Response.Write("</strong>");
  396. HttpContext.Current.Response.Write("</td>");
  397. }
  398. HttpContext.Current.Response.Write("</tr>");
  399. int rowNum = 0, totalBorderRows = table.Rows.Count - 5;
  400. foreach (DataRow row in table.Rows)
  401. {//write in new row
  402. HttpContext.Current.Response.Write("<tr>");
  403. for (int i = 0; i < table.Columns.Count; i++)
  404. {
  405. if (fileName == "AccountStatement" && rowNum > totalBorderRows)
  406. {
  407. HttpContext.Current.Response.Write("<td style='border:0;'>");
  408. }
  409. else
  410. {
  411. HttpContext.Current.Response.Write("<td style='textmode'>");
  412. }
  413. //HttpContext.Current.Response.Write("");
  414. HttpContext.Current.Response.Write(row[i].ToString());
  415. HttpContext.Current.Response.Write("</td>");
  416. }
  417. HttpContext.Current.Response.Write("</tr>");
  418. rowNum++;
  419. }
  420. HttpContext.Current.Response.Write("</table>");
  421. HttpContext.Current.Response.Write("</font>");
  422. HttpContext.Current.Response.Flush();
  423. HttpContext.Current.Response.End();
  424. }
  425. public static DataTable ConvertHTMLTableToDataSet(string HTML)
  426. {
  427. // Declarations
  428. DataSet ds = new DataSet();
  429. DataTable dt = null;
  430. DataRow dr = null;
  431. string TableExpression = "<table[^>]*>(.*?)</table>";
  432. string HeaderExpression = "<th[^>]*>(.*?)</th>";
  433. string RowExpression = "<tr[^>]*>(.*?)</tr>";
  434. string ColumnExpression = "<td[^>]*>(.*?)</td>";
  435. bool HeadersExist = false;
  436. int iCurrentColumn = 0;
  437. int iCurrentRow = 0;
  438. // Get a match for all the tables in the HTML
  439. MatchCollection Tables = Regex.Matches(HTML, TableExpression, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
  440. // Loop through each table element
  441. foreach (Match Table in Tables)
  442. {
  443. // Reset the current row counter and the header flag
  444. iCurrentRow = 0;
  445. HeadersExist = false;
  446. // Add a new table to the DataSet
  447. dt = new DataTable();
  448. // Create the relevant amount of columns for this table (use the headers if they
  449. // exist, otherwise use default names)
  450. if (Table.Value.Contains("<th"))
  451. {
  452. // Set the HeadersExist flag
  453. HeadersExist = true;
  454. // Get a match for all the rows in the table
  455. MatchCollection Headers = Regex.Matches(Table.Value, HeaderExpression, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
  456. // Loop through each header element
  457. foreach (Match Header in Headers)
  458. {
  459. if (!dt.Columns.Contains(Header.Groups[1].ToString()))
  460. dt.Columns.Add(Header.Groups[1].ToString().Replace("&nbsp;", ""));
  461. }
  462. }
  463. else
  464. {
  465. for (int iColumns = 1; iColumns <= Regex.Matches(Regex.Matches(Regex.Matches(Table.Value, TableExpression, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase).ToString(), RowExpression, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase).ToString(), ColumnExpression, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase).Count; iColumns++)
  466. {
  467. dt.Columns.Add("Column " + iColumns);
  468. }
  469. }
  470. // Get a match for all the rows in the table
  471. MatchCollection Rows = Regex.Matches(Table.Value, RowExpression, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
  472. // Loop through each row element
  473. foreach (Match Row in Rows)
  474. {
  475. // Only loop through the row if it isn't a header row
  476. if (!(iCurrentRow == 0 & HeadersExist == true))
  477. {
  478. // Create a new row and reset the current column counter
  479. dr = dt.NewRow();
  480. iCurrentColumn = 0;
  481. // Get a match for all the columns in the row
  482. MatchCollection Columns = Regex.Matches(Row.Value, ColumnExpression, RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);
  483. // Loop through each column element
  484. foreach (Match Column in Columns)
  485. {
  486. if (Columns.Count - 1 != iCurrentColumn)
  487. // Add the value to the DataRow
  488. dr[iCurrentColumn] = Regex.Replace(Convert.ToString(Column.Groups[1]).Replace("&nbsp;", ""), "<.*?>", string.Empty);
  489. // Increase the current column
  490. iCurrentColumn += 1;
  491. }
  492. // Add the DataRow to the DataTable
  493. dt.Rows.Add(dr);
  494. }
  495. // Increase the current row counter
  496. iCurrentRow += 1;
  497. }
  498. // Add the DataTable to the DataSet
  499. ds.Tables.Add(dt);
  500. }
  501. return ds.Tables[0];
  502. }
  503. public static string GetCSVFileInTable(string path, bool hasHeader, int numberOfObjects = 0)
  504. {
  505. var dt = new DataTable();
  506. var columnList = new ArrayList();
  507. var sb = new StringBuilder("<root>");
  508. using (CsvReader reader = new CsvReader(path))
  509. {
  510. foreach (string[] values in reader.RowEnumerator)
  511. {
  512. if (hasHeader)
  513. {
  514. dt.Columns.Clear();
  515. dt.Clear();
  516. foreach (var itm in values)
  517. {
  518. var data = itm.Replace(" ", "_").Replace("\"", "");
  519. columnList.Add(data.ToUpper());
  520. }
  521. hasHeader = false;
  522. continue;
  523. }
  524. if (values.Length > 0)
  525. {
  526. sb.Append("<row");
  527. for (int i = 0; i < ((numberOfObjects == 0) ? values.Length : numberOfObjects); i++)
  528. {
  529. sb.Append(string.Format(" {0}=\"{1}\"", columnList[i].ToString().Trim(), values[i].ToString().Trim()));
  530. }
  531. sb.Append(" />");
  532. }
  533. }
  534. }
  535. sb.Append("</root>");
  536. return sb.ToString();
  537. }
  538. public static string GetCSVFileInTableForTxnSyncInficare(string path, bool hasHeader, int numberOfObjects = 0)
  539. {
  540. var dt = new DataTable();
  541. var columnList = new ArrayList();
  542. var sb = new StringBuilder("<root>");
  543. using (CsvReader reader = new CsvReader(path))
  544. {
  545. foreach (string[] values in reader.RowEnumerator)
  546. {
  547. if (hasHeader)
  548. {
  549. dt.Columns.Clear();
  550. dt.Clear();
  551. foreach (var itm in values)
  552. {
  553. var data = itm.Replace(" ", "_").Replace("\"", "").Replace(".", "");
  554. if (string.IsNullOrEmpty(data))
  555. {
  556. data = "AgentName";
  557. }
  558. columnList.Add(data.ToUpper());
  559. }
  560. hasHeader = false;
  561. continue;
  562. }
  563. if (values.Length > 0)
  564. {
  565. sb.Append("<row");
  566. for (int i = 0; i < ((numberOfObjects == 0) ? values.Length : numberOfObjects); i++)
  567. {
  568. sb.Append(string.Format(" {0}=\"{1}\"", columnList[i].ToString().Trim(), values[i].ToString().Trim()));
  569. }
  570. sb.Append(" />");
  571. }
  572. }
  573. }
  574. sb.Append("</root>");
  575. return sb.ToString();
  576. }
  577. public static DataTable GetHistoryChangedList(string logType, string oldData, string newData)
  578. {
  579. var stringSeparators = new[] { "-:::-" };
  580. var oldDataList = oldData.Split(stringSeparators, StringSplitOptions.None);
  581. var newDataList = newData.Split(stringSeparators, StringSplitOptions.None);
  582. var dt = new DataTable();
  583. var col1 = new DataColumn("Field");
  584. var col2 = new DataColumn("Old Value");
  585. var col3 = new DataColumn("New Value");
  586. var col4 = new DataColumn("hasChanged");
  587. dt.Columns.Add(col1);
  588. dt.Columns.Add(col2);
  589. dt.Columns.Add(col3);
  590. dt.Columns.Add(col4);
  591. var colCount = newData == "" ? oldDataList.Length : newDataList.Length;
  592. for (var i = 0; i < colCount; i++)
  593. {
  594. var changeList = ParseChangesToArray(logType, (oldData == "") ? "" : oldDataList[i], (newData == "") ? "" : newDataList[i]);
  595. var row = dt.NewRow();
  596. row[col1] = changeList[0];
  597. row[col2] = changeList[1];
  598. row[col3] = changeList[2];
  599. if (changeList[1] == changeList[2])
  600. {
  601. row[col4] = "N";
  602. }
  603. else
  604. {
  605. row[col4] = "Y";
  606. }
  607. dt.Rows.Add(row);
  608. }
  609. return dt;
  610. }
  611. //
  612. //public static string ToFilterStringNativeTrim(this string strVal)
  613. //{
  614. // var db = new RemittanceDao();
  615. // var str = db.FilterQuoteNative(strVal);
  616. // if (str.ToLower() != "null") str = "'" + str + "'"; else str = "";
  617. // return str;
  618. //}
  619. private static string[] ParseChangesToArray(string logType, string oldData, string newData)
  620. {
  621. const string seperator = "=";
  622. var oldValue = "";
  623. var newValue = "";
  624. var field = "";
  625. if (logType.ToLower() == "insert" || logType.ToLower() == "i" || logType.ToLower() == "update" || logType.ToLower() == "u" || logType.ToLower() == "login fails" || logType.ToLower() == "log in")
  626. {
  627. var seperatorPos = newData.IndexOf(seperator);
  628. if (seperatorPos > -1)
  629. {
  630. field = newData.Substring(0, seperatorPos - 1).Trim();
  631. newValue = newData.Substring(seperatorPos + 1).Trim();
  632. }
  633. }
  634. if (logType.ToLower() == "delete" || logType.ToLower() == "d" || logType.ToLower() == "update" || logType.ToLower() == "u")
  635. {
  636. var seperatorPos = oldData.IndexOf(seperator);
  637. if (seperatorPos > -1)
  638. {
  639. if (field == "")
  640. field = oldData.Substring(0, seperatorPos - 1).Trim();
  641. oldValue = oldData.Substring(seperatorPos + 1).Trim();
  642. }
  643. }
  644. return new[] { field, oldValue, newValue };
  645. }
  646. internal static string ParseOfacJson(string ofacRes, string senderReceiverName)
  647. {
  648. List<OFACModel> _listOfac = JsonConvert.DeserializeObject<List<OFACModel>>(ofacRes);
  649. if (_listOfac == null || _listOfac.Count <= 0)
  650. {
  651. return "";
  652. }
  653. StringBuilder sb = new StringBuilder();
  654. sb.AppendLine("<table class='trnLog' border=\"1\" cellspacing=0 cellpadding=\"3\">");
  655. sb.Append("<tr><th align=\"left\">S. No.</th><th align=\"left\">OFAC Remarks</th></tr>");
  656. var strArr = senderReceiverName.Split(' ');
  657. int sNo = 1;
  658. foreach (var item in _listOfac)
  659. {
  660. string data = item.rmrks;
  661. sb.Append("<tr>");
  662. sb.AppendLine("<td>" + item.sno + "</td>");
  663. for (int j = 0; j < strArr.Length; j++)
  664. {
  665. if (!string.IsNullOrWhiteSpace(strArr[j]))
  666. {
  667. if (strArr[j].Length > 2)
  668. {
  669. data = data.ToUpper().Replace(strArr[j], GetStatic.PutRedBackGround(strArr[j]));
  670. }
  671. }
  672. }
  673. sb.AppendLine("<td>" + data + "</td>");
  674. sb.Append("</tr>");
  675. sNo++;
  676. }
  677. sb.Append("</table>");
  678. return sb.ToString();
  679. }
  680. internal static string ParseOfacJsonAndGetTopResult(string ofacRes)
  681. {
  682. List<OFACModel> _listOfac = JsonConvert.DeserializeObject<List<OFACModel>>(ofacRes);
  683. if (_listOfac == null || _listOfac.Count <= 0)
  684. {
  685. return "";
  686. }
  687. return _listOfac[0].rmrks.ToString();
  688. }
  689. public static DataTable GetHistoryChangedListForAgent(string oldData, string newData)
  690. {
  691. var applicationLogsDao = new ApplicationLogsDao();
  692. return applicationLogsDao.GetAuditDataForAgent(oldData, newData);
  693. }
  694. public static DataTable GetHistoryChangedListForFunction(string oldData, string newData)
  695. {
  696. var applicationLogsDao = new ApplicationLogsDao();
  697. return applicationLogsDao.GetAuditDataForFunction(oldData, newData);
  698. }
  699. public static DataTable GetHistoryChangedListForRole(string oldData, string newData)
  700. {
  701. var applicationLogsDao = new ApplicationLogsDao();
  702. return applicationLogsDao.GetAuditDataForRole(oldData, newData);
  703. }
  704. public static DataTable GetHistoryChangedListForRuleCriteria(string oldData, string newData)
  705. {
  706. var applicationLogsDao = new ApplicationLogsDao();
  707. return applicationLogsDao.GetAuditDataForRuleCriteria(oldData, newData);
  708. }
  709. public static double RoundOff(double num, int place, int currDecimal)
  710. {
  711. if (currDecimal != 0)
  712. return Math.Round(num, currDecimal);
  713. else if (place != 0)
  714. return (Math.Round(num / place)) * place;
  715. return Math.Round(num, 0);
  716. }
  717. public static Boolean IsNumeric(string stringToTest)
  718. {
  719. int result;
  720. return int.TryParse(stringToTest, out result);
  721. }
  722. #region Userpool
  723. public static string GetFullName(string firstName, string middleName, string lastName1, string lastName2)
  724. {
  725. var fullName = firstName;
  726. if (!string.IsNullOrWhiteSpace(middleName))
  727. fullName += " " + middleName;
  728. if (!string.IsNullOrWhiteSpace(lastName1))
  729. fullName += " " + lastName1;
  730. if (!string.IsNullOrEmpty(lastName2))
  731. fullName += " " + lastName2;
  732. return fullName;
  733. }
  734. public static string GetAgent()
  735. {
  736. return ReadSession("agent", "");
  737. }
  738. public static string GetAgentIdN()
  739. {
  740. return ReadSession("agentId", "");
  741. }
  742. public static string GetCountry()
  743. {
  744. return ReadSession("country", "");
  745. }
  746. public static string GetUser()
  747. {
  748. var user = ReadSession("admin", "");
  749. WriteSession("admin", user);
  750. //WriteSession("lastActiveTS", DateTime.Now.ToString());
  751. return user;
  752. }
  753. public static string GetAgentId()
  754. {
  755. var branchId = ReadSession("branchId", "");
  756. //WriteSession("lastActiveTS", DateTime.Now.ToString());
  757. return branchId;
  758. }
  759. public static string GetUserType()
  760. {
  761. var userType = ReadSession("userType", "");
  762. //WriteSession("lastActiveTS", DateTime.Now.ToString());
  763. return userType;
  764. }
  765. public static void RemoveUserSession()
  766. {
  767. WriteSession("admin", "");
  768. }
  769. #endregion Userpool
  770. public static string GetBranch()
  771. {
  772. return ReadSession("branch", "");
  773. }
  774. public static string GetDcInfo()
  775. {
  776. return GetLoggedInUser().DcInfo;
  777. return HttpContext.Current.Request.ClientCertificate["SERIALNUMBER"] + ":" + HttpContext.Current.Request.ClientCertificate["SUBJECTCN"];
  778. }
  779. public static string GetIp()
  780. {
  781. return GetLoggedInUser().IPAddress;
  782. return HttpContext.Current.Request.ClientCertificate["REMOTE_ADDR"];
  783. }
  784. public static string ToShortDate(string datetime)
  785. {
  786. try
  787. {
  788. DateTime dt;
  789. DateTime.TryParse(datetime, out dt);
  790. return dt.ToShortDateString();
  791. }
  792. catch
  793. {
  794. return "";
  795. }
  796. }
  797. public static string GetSessionId()
  798. {
  799. return HttpContext.Current.Session.SessionID;
  800. }
  801. public static string EncryptPassword(string pwd)
  802. {
  803. return pwd;
  804. }
  805. public static int GetSessionTimeOut()
  806. {
  807. return 0;
  808. }
  809. #region Read/Write Data
  810. public static string ReadCookie(string key, string defVal)
  811. {
  812. var cookie = HttpContext.Current.Request.Cookies[key];
  813. return cookie == null ? defVal : HttpContext.Current.Server.HtmlEncode(cookie.Value);
  814. }
  815. public static string ReadFormData(string key, string defVal)
  816. {
  817. return HttpContext.Current.Request.Form[key] ?? defVal;
  818. }
  819. public static string GetCountDownInSec()
  820. {
  821. return (ReadWebConfig("countDownInSec") ?? "0").ToString();
  822. }
  823. public static string ReadQueryString(string key, string defVal)
  824. {
  825. return HttpContext.Current.Request.QueryString[key] ?? defVal;
  826. }
  827. public static string ReadValue(string gridName, string key)
  828. {
  829. key = gridName + "_ck_" + key;
  830. var ck = ReadCookie(key, "");
  831. return ck;
  832. }
  833. public static void WriteValue(string gridName, ref DropDownList ddl, string key)
  834. {
  835. key = gridName + "_ck_" + key;
  836. WriteCookie(key, ddl.Text);
  837. }
  838. public static void WriteValue(string gridName, ref TextBox tb, string key)
  839. {
  840. key = gridName + "_ck_" + key;
  841. WriteCookie(key, tb.Text);
  842. }
  843. #endregion Read/Write Data
  844. public static string ReadSession(string key, string defVal)
  845. {
  846. try
  847. {
  848. return HttpContext.Current.Session[key] == null ? defVal : HttpContext.Current.Session[key].ToString();
  849. }
  850. catch (Exception ex)
  851. {
  852. return "";
  853. }
  854. }
  855. public static DataTable ReadSessionAsTable(string key)
  856. {
  857. try
  858. {
  859. return HttpContext.Current.Session[key] == null ? null : HttpContext.Current.Session[key] as DataTable;
  860. }
  861. catch (Exception ex)
  862. {
  863. return null;
  864. }
  865. }
  866. public static void WriteSessionAsDataTable(string key, DataTable dt)
  867. {
  868. HttpContext.Current.Session[key] = dt;
  869. }
  870. public static void WriteSession(string key, string value)
  871. {
  872. HttpContext.Current.Session[key] = value;
  873. }
  874. public static void RemoveSession(string key)
  875. {
  876. if (HttpContext.Current.Session[key] == null)
  877. {
  878. return;
  879. }
  880. HttpContext.Current.Session.Remove(key);
  881. }
  882. public static void DeleteCookie(string key)
  883. {
  884. if (HttpContext.Current.Request.Cookies[key] != null)
  885. {
  886. var aCookie = new HttpCookie(key);
  887. aCookie.Expires = DateTime.Now.AddDays(-1);
  888. HttpContext.Current.Response.Cookies.Add(aCookie);
  889. }
  890. }
  891. public static void AttachJSFunction(ref Button ctl, string evt, string function)
  892. {
  893. ctl.Attributes.Add(evt, function);
  894. }
  895. public static void AttachConfirmMsg(ref Button ctl)
  896. {
  897. AttachConfirmMsg(ref ctl, "Are you sure?");
  898. }
  899. public static void AttachJSFunction(ref DropDownList ctl, string evt, string function)
  900. {
  901. ctl.Attributes.Add(evt, function);
  902. }
  903. public static void AttachJSFunction(ref TextBox ctl, string evt, string function)
  904. {
  905. ctl.Attributes.Add(evt, function);
  906. }
  907. public static void AttachConfirmMsg(ref Button ctl, string confirmText)
  908. {
  909. var function = "return confirm('" + confirmText + "');";
  910. ctl.Attributes.Add("onclick", function);
  911. }
  912. public static LoggedInUser GetLoggedInUser()
  913. {
  914. var userPool = UserPool.GetInstance();
  915. return userPool.GetUser(GetUser());
  916. }
  917. public static void WriteCookie(string key, string value)
  918. {
  919. if (string.IsNullOrEmpty(value.Trim()))
  920. {
  921. DeleteCookie(key);
  922. return;
  923. }
  924. var httpCookie = new HttpCookie(key, value);
  925. httpCookie.Expires = DateTime.Now.AddDays(1);
  926. HttpContext.Current.Response.Cookies.Add(httpCookie);
  927. }
  928. public static string FormatData(string data)
  929. {
  930. if (string.IsNullOrEmpty(data))
  931. return "";
  932. decimal m;
  933. decimal.TryParse(data, out m);
  934. return m.ToString("F2");
  935. }
  936. public static string FormatData(string data, string dataType)
  937. {
  938. if (string.IsNullOrEmpty(data))
  939. return "&nbsp;";
  940. if (data == "-")
  941. return data;
  942. if (dataType == "D")
  943. {
  944. DateTime d;
  945. DateTime.TryParse(data, out d);
  946. return d.Day.ToString("00") + "/" + d.Month.ToString("00") + "/" + d.Year;
  947. }
  948. if (dataType == "DT")
  949. {
  950. DateTime t;
  951. DateTime.TryParse(data, out t);
  952. return t.Year + "/" + t.Month.ToString("00") + "/" + t.Day.ToString("00") + " " + t.Hour.ToString("00") + ":" + t.Minute.ToString("00");
  953. }
  954. if (dataType == "M")
  955. {
  956. decimal m;
  957. decimal.TryParse(data, out m);
  958. return m.ToString("N");
  959. }
  960. return data;
  961. }
  962. public static string FormatDataForForm(string data, string dataType)
  963. {
  964. if (string.IsNullOrEmpty(data))
  965. return "";
  966. if (data == "-")
  967. return data;
  968. if (dataType == "D")
  969. {
  970. DateTime d;
  971. DateTime.TryParse(data, out d);
  972. return d.Year + "/" + d.Month.ToString("00") + "/" + d.Day.ToString("00");
  973. }
  974. if (dataType == "DT")
  975. {
  976. DateTime t;
  977. DateTime.TryParse(data, out t);
  978. return t.Year + "/" + t.Month.ToString("00") + "/" + t.Day.ToString("00") + " " + t.Hour.ToString("00") + ":" + t.Minute.ToString("00");
  979. }
  980. if (dataType == "M")
  981. {
  982. decimal m;
  983. decimal.TryParse(data, out m);
  984. return m.ToString("N");
  985. }
  986. return data;
  987. }
  988. public static string NumberToWord(string data)
  989. {
  990. var str = data.Split('.');
  991. int number = Convert.ToInt32(str[0]);
  992. int dec = 0;
  993. if (str.Length > 1)
  994. dec = Convert.ToInt32(str[1].Substring(0, 2));
  995. if (number == 0) return "Zero";
  996. if (number == -2147483648)
  997. return
  998. "Minus Two Hundred and Fourteen Crore Seventy Four Lakh Eighty Three Thousand Six Hundred and Forty Eight Rupees Fifty Paisa";
  999. int[] num = new int[4];
  1000. int first = 0;
  1001. int u, h, t;
  1002. StringBuilder sb = new System.Text.StringBuilder();
  1003. if (number < 0)
  1004. {
  1005. sb.Append("Minus ");
  1006. number = -number;
  1007. }
  1008. string[] words0 = {
  1009. "", "One ", "Two ", "Three ", "Four ",
  1010. "Five ", "Six ", "Seven ", "Eight ", "Nine "
  1011. };
  1012. string[] words1 = {
  1013. "Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ",
  1014. "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen "
  1015. };
  1016. string[] words2 = {
  1017. "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ",
  1018. "Seventy ", "Eighty ", "Ninety "
  1019. };
  1020. string[] words3 = { "Thousand ", "Lakh ", "Crore " };
  1021. num[0] = number % 1000; // units
  1022. num[1] = number / 1000;
  1023. num[2] = number / 100000;
  1024. num[1] = num[1] - 100 * num[2]; // thousands
  1025. num[3] = number / 10000000; // crores
  1026. num[2] = num[2] - 100 * num[3]; // lakhs
  1027. for (int i = 3; i > 0; i--)
  1028. {
  1029. if (num[i] != 0)
  1030. {
  1031. first = i;
  1032. break;
  1033. }
  1034. }
  1035. for (int i = first; i >= 0; i--)
  1036. {
  1037. if (num[i] == 0) continue;
  1038. u = num[i] % 10; // ones
  1039. t = num[i] / 10;
  1040. h = num[i] / 100; // hundreds
  1041. t = t - 10 * h; // tens
  1042. if (h > 0) sb.Append(words0[h] + "Hundred ");
  1043. if (u > 0 || t > 0)
  1044. {
  1045. if (h > 0 && i == 0) sb.Append("and ");
  1046. if (t == 0)
  1047. sb.Append(words0[u]);
  1048. else if (t == 1)
  1049. sb.Append(words1[u]);
  1050. else
  1051. sb.Append(words2[t - 2] + words0[u]);
  1052. }
  1053. if (i != 0) sb.Append(words3[i - 1]);
  1054. }
  1055. //sb.Append(" Rupees ");
  1056. int d1 = dec / 10;
  1057. int d2 = dec % 10;
  1058. if (d1 == 0)
  1059. sb.Append(words0[d1]);
  1060. else if (d1 == 1)
  1061. sb.Append(words1[d2]);
  1062. else
  1063. sb.Append(words2[d1 - 2] + words0[d2]);
  1064. //if (dec > 0)
  1065. // sb.Append(" Paisa");
  1066. return sb.ToString().TrimEnd() + " only";
  1067. }
  1068. public static string NumberToWord(string data, string currName, string currDecimal)
  1069. {
  1070. var str = data.Split('.');
  1071. int number = Convert.ToInt32(str[0]);
  1072. int dec = 0;
  1073. if (str.Length > 1)
  1074. dec = Convert.ToInt32(str[1].Substring(0, 2));
  1075. if (number == 0) return "Zero";
  1076. if (number == -2147483648)
  1077. return
  1078. "Minus Two Hundred and Fourteen Crore Seventy Four Lakh Eighty Three Thousand Six Hundred and Forty Eight Rupees Fifty Paisa";
  1079. int[] num = new int[4];
  1080. int first = 0;
  1081. int u, h, t;
  1082. StringBuilder sb = new System.Text.StringBuilder();
  1083. if (number < 0)
  1084. {
  1085. sb.Append("Minus ");
  1086. number = -number;
  1087. }
  1088. string[] words0 = {
  1089. "", "One ", "Two ", "Three ", "Four ",
  1090. "Five ", "Six ", "Seven ", "Eight ", "Nine "
  1091. };
  1092. string[] words1 = {
  1093. "Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ",
  1094. "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen "
  1095. };
  1096. string[] words2 = {
  1097. "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ",
  1098. "Seventy ", "Eighty ", "Ninety "
  1099. };
  1100. //string[] words3 = { "Thousand ", "Lakh ", "Crore " };
  1101. string[] words3 = { "Thousand ", "Million ", "Billion " };
  1102. num[0] = number % 1000; // units
  1103. num[1] = number / 1000;
  1104. num[2] = number / 1000000;
  1105. num[1] = num[1] - 1000 * num[2]; // thousands
  1106. num[3] = number / 1000000000; // billions
  1107. num[2] = num[2] - 1000 * num[3]; // millions
  1108. for (int i = 3; i > 0; i--)
  1109. {
  1110. if (num[i] != 0)
  1111. {
  1112. first = i;
  1113. break;
  1114. }
  1115. }
  1116. //for (int i = first; i >= 0; i--)
  1117. //{
  1118. // if (num[i] == 0) continue;
  1119. // u = num[i] % 10; // ones
  1120. // t = num[i] / 10;
  1121. // h = num[i] / 100; // hundreds
  1122. // t = t - 10 * h; // tens
  1123. // if (h > 0) sb.Append(words0[h] + "Hundred ");
  1124. // if (u > 0 || t > 0)
  1125. // {
  1126. // if (h > 0 || i < first) sb.Append("and ");
  1127. // if (t == 0)
  1128. // sb.Append(words0[u]);
  1129. // else if (t == 1)
  1130. // sb.Append(words1[u]);
  1131. // else
  1132. // sb.Append(words2[t - 2] + words0[u]);
  1133. // }
  1134. // if (i != 0) sb.Append(words3[i - 1]);
  1135. //}
  1136. //num[0] = number % 1000; // units
  1137. //num[1] = number / 1000;
  1138. //num[2] = number / 100000;
  1139. //num[1] = num[1] - 100 * num[2]; // thousands
  1140. //num[3] = number / 10000000; // crores
  1141. //num[2] = num[2] - 100 * num[3]; // lakhs
  1142. //for (int i = 3; i > 0; i--)
  1143. //{
  1144. // if (num[i] != 0)
  1145. // {
  1146. // first = i;
  1147. // break;
  1148. // }
  1149. //}
  1150. for (int i = first; i >= 0; i--)
  1151. {
  1152. if (num[i] == 0) continue;
  1153. u = num[i] % 10; // ones
  1154. t = num[i] / 10;
  1155. h = num[i] / 100; // hundreds
  1156. t = t - 10 * h; // tens
  1157. if (h > 0) sb.Append(words0[h] + "Hundred ");
  1158. if (u > 0 || t > 0)
  1159. {
  1160. if (h > 0 && i == 0) sb.Append("and ");
  1161. //if (h > 0 || i < first) sb.Append("and ");
  1162. //if (h > 0) sb.Append("and ");
  1163. if (t == 0)
  1164. sb.Append(words0[u]);
  1165. else if (t == 1)
  1166. sb.Append(words1[u]);
  1167. else
  1168. sb.Append(words2[t - 2] + words0[u]);
  1169. }
  1170. if (i != 0) sb.Append(words3[i - 1]);
  1171. }
  1172. sb.Append(" " + currName + " ");
  1173. int d1 = dec / 10;
  1174. int d2 = dec % 10;
  1175. if (d1 == 0)
  1176. sb.Append(words0[d1]);
  1177. else if (d1 == 1)
  1178. sb.Append(words1[d2]);
  1179. else
  1180. sb.Append(words2[d1 - 2] + words0[d2]);
  1181. if (dec > 0 && !string.IsNullOrEmpty(currDecimal))
  1182. sb.Append(" " + currDecimal);
  1183. return sb.ToString().TrimEnd() + " only";
  1184. }
  1185. #region Read From Web Config
  1186. public static string GetAppRoot()
  1187. {
  1188. return ReadWebConfig("root");
  1189. }
  1190. public static string GetFilePath()
  1191. {
  1192. return ReadWebConfig("filePath");
  1193. }
  1194. public static string GetCustomerFilePath()
  1195. {
  1196. return ReadWebConfig("customerDocPath");
  1197. }
  1198. public static string GetUrlRoot()
  1199. {
  1200. return ReadWebConfig("urlRoot");
  1201. }
  1202. public static string GetVirtualDirName()
  1203. {
  1204. return ReadWebConfig("virtualDirName");
  1205. }
  1206. public static string GetDBUrlRoot()
  1207. {
  1208. return ReadWebConfig("dbUrlRoot");
  1209. }
  1210. public static string GetDBRoot()
  1211. {
  1212. return ReadWebConfig("dbRoot");
  1213. }
  1214. public static string GetReportPagesize()
  1215. {
  1216. return ReadWebConfig("reportPageSize");
  1217. }
  1218. public static string GetUploadFileSize()
  1219. {
  1220. return ReadWebConfig("fileSize");
  1221. }
  1222. #endregion Read From Web Config
  1223. public static DataTable GetStringToTable(string data)
  1224. {
  1225. var stringSeparators = new[] { "-:::-" };
  1226. var dataList = data.Split(stringSeparators, StringSplitOptions.None);
  1227. var dt = new DataTable();
  1228. var col1 = new DataColumn("field1");
  1229. var col2 = new DataColumn("field2");
  1230. var col3 = new DataColumn("field3");
  1231. dt.Columns.Add(col1);
  1232. dt.Columns.Add(col2);
  1233. dt.Columns.Add(col3);
  1234. var colCount = dataList.Length;
  1235. for (var i = 0; i < colCount; i++)
  1236. {
  1237. var changeList = dataList[i].Split('=');
  1238. var changeListCout = changeList.Length;
  1239. var value1 = changeListCout > 0 ? changeList[0].Trim() : "";
  1240. var value2 = changeListCout > 1 ? changeList[1].Trim() : "";
  1241. var value3 = changeListCout > 2 ? changeList[2].Trim() : "";
  1242. var row = dt.NewRow();
  1243. row[col1] = value1;
  1244. row[col2] = value2;
  1245. row[col3] = value3;
  1246. dt.Rows.Add(row);
  1247. }
  1248. return dt;
  1249. }
  1250. public static DbResult GetPasswordStatus()
  1251. {
  1252. DbResult dr = null;
  1253. if (HttpContext.Current.Session["passwordStatus"] != null)
  1254. {
  1255. dr = (DbResult)HttpContext.Current.Session["passwordStatus"];
  1256. }
  1257. return dr;
  1258. }
  1259. public static void SetPasswordStatus(DbResult dr)
  1260. {
  1261. HttpContext.Current.Session["passwordStatus"] = dr;
  1262. }
  1263. public static string GetUserName()
  1264. {
  1265. var identityArray = HttpContext.Current.User.Identity.Name.Split('\\');
  1266. return identityArray.Length > 1 ? identityArray[1] : identityArray[0];
  1267. }
  1268. public static string GetLogoutPage()
  1269. {
  1270. return GetUrlRoot() + "/Logout.aspx";
  1271. }
  1272. public static string GetErrorPage()
  1273. {
  1274. return GetUrlRoot() + "/Error.aspx";
  1275. }
  1276. public static string GetAuthenticationPage()
  1277. {
  1278. return GetUrlRoot() + "/Authentication.aspx";
  1279. }
  1280. public static string NoticeMessage
  1281. {
  1282. get { return ReadSession("message", ""); }
  1283. set { WriteSession("message", value); }
  1284. }
  1285. public static bool ToImage(this string value)
  1286. {
  1287. value = value.ToLower();
  1288. if (!value.Contains("."))
  1289. {
  1290. value = "." + value;
  1291. }
  1292. if (value == ".jpeg" || value == ".jpg" || value == ".png" || value == ".gif" || value == ".bmp")
  1293. return true;
  1294. else
  1295. {
  1296. return false;
  1297. }
  1298. }
  1299. public static string DataTable2ExcelXML(ref DataTable dt)
  1300. {
  1301. var date = DateTime.Now.Date.ToString("yyyy-MM-dd");
  1302. var header = new StringBuilder("");
  1303. header.AppendLine("<?xml version=\"1.0\"?>");
  1304. header.AppendLine("<?mso-application progid=\"Excel.Sheet\"?>");
  1305. header.AppendLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"");
  1306. header.AppendLine("xmlns:o=\"urn:schemas-microsoft-com:office:office\"");
  1307. header.AppendLine("xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
  1308. header.AppendLine("xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"");
  1309. header.AppendLine("xmlns:html=\"http://www.w3.org/TR/REC-html40\">");
  1310. header.AppendLine("<DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">");
  1311. header.AppendLine("<Created>" + date + "</Created>");
  1312. header.AppendLine("<LastSaved>" + date + "</LastSaved>");
  1313. header.AppendLine("<Version>12.00</Version>");
  1314. header.AppendLine("</DocumentProperties>");
  1315. header.AppendLine("<OfficeDocumentSettings xmlns=\"urn:schemas-microsoft-com:office:office\">");
  1316. header.AppendLine("<RemovePersonalInformation/>");
  1317. header.AppendLine("</OfficeDocumentSettings>");
  1318. header.AppendLine("<ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">");
  1319. header.AppendLine("<WindowHeight>8010</WindowHeight>");
  1320. header.AppendLine("<WindowWidth>14805</WindowWidth>");
  1321. header.AppendLine("<WindowTopX>240</WindowTopX>");
  1322. header.AppendLine("<WindowTopY>105</WindowTopY>");
  1323. header.AppendLine("<ProtectStructure>False</ProtectStructure>");
  1324. header.AppendLine("<ProtectWindows>False</ProtectWindows>");
  1325. header.AppendLine("</ExcelWorkbook>");
  1326. header.AppendLine("<Styles>");
  1327. header.AppendLine("<Style ss:ID=\"Default\" ss:Name=\"Normal\">");
  1328. header.AppendLine("<Alignment ss:Vertical=\"Bottom\"/>");
  1329. header.AppendLine("<Borders/>");
  1330. header.AppendLine("<Font ss:FontName=\"Calibri\" x:Family=\"Swiss\" ss:Size=\"11\" ss:Color=\"#000000\"/>");
  1331. header.AppendLine("<Interior/>");
  1332. header.AppendLine("<NumberFormat/>");
  1333. header.AppendLine("<Protection/>");
  1334. header.AppendLine("</Style>");
  1335. header.AppendLine("<Style ss:ID=\"s16\">");
  1336. header.AppendLine(" <NumberFormat ss:Format=\"@\"/>");
  1337. header.AppendLine("</Style>");
  1338. header.AppendLine("</Styles>");
  1339. header.AppendLine("<Worksheet ss:Name=\"Sheet1\">");
  1340. header.AppendLine("<Table ss:ExpandedColumnCount=\"{columns}\" ss:ExpandedRowCount=\"{rows}\" x:FullColumns=\"1\" x:FullRows=\"1\" ss:DefaultRowHeight=\"15\">");
  1341. var footer = new StringBuilder("");
  1342. footer.AppendLine("</Table>");
  1343. footer.AppendLine("<WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">");
  1344. footer.AppendLine("<PageSetup>");
  1345. footer.AppendLine("<Header x:Margin=\"0.3\"/>");
  1346. footer.AppendLine("<Footer x:Margin=\"0.3\"/>");
  1347. footer.AppendLine("<PageMargins x:Bottom=\"0.75\" x:Left=\"0.7\" x:Right=\"0.7\" x:Top=\"0.75\"/>");
  1348. footer.AppendLine("</PageSetup>");
  1349. footer.AppendLine("<Print>");
  1350. footer.AppendLine("<ValidPrinterInfo/>");
  1351. footer.AppendLine("<HorizontalResolution>300</HorizontalResolution>");
  1352. footer.AppendLine("<VerticalResolution>300</VerticalResolution>");
  1353. footer.AppendLine("</Print>");
  1354. footer.AppendLine("<Selected/>");
  1355. footer.AppendLine("<Panes>");
  1356. footer.AppendLine("<Pane>");
  1357. footer.AppendLine("<Number>3</Number>");
  1358. footer.AppendLine("<ActiveRow>1</ActiveRow>");
  1359. footer.AppendLine("</Pane>");
  1360. footer.AppendLine("</Panes>");
  1361. footer.AppendLine("<ProtectObjects>False</ProtectObjects>");
  1362. footer.AppendLine("<ProtectScenarios>False</ProtectScenarios>");
  1363. footer.AppendLine("</WorksheetOptions>");
  1364. footer.AppendLine("</Worksheet>");
  1365. footer.AppendLine("</Workbook>");
  1366. const string dataTemplate = "<Cell ss:StyleID=\"s16\"><Data ss:Type=\"String\">{data}</Data></Cell>";
  1367. var body = new StringBuilder("");
  1368. var columnCount = dt.Columns.Count;
  1369. body.AppendLine("<Row>");
  1370. for (var i = 0; i < columnCount; i++)
  1371. {
  1372. body.AppendLine(dataTemplate.Replace("{data}", dt.Columns[i].ColumnName));
  1373. }
  1374. body.AppendLine("</Row>");
  1375. foreach (DataRow dr in dt.Rows)
  1376. {
  1377. body.AppendLine("<Row>");
  1378. for (var i = 0; i < columnCount; i++)
  1379. {
  1380. body.AppendLine(dataTemplate.Replace("{data}", dr[i].ToString()));
  1381. }
  1382. body.AppendLine("</Row>");
  1383. }
  1384. header.AppendLine(body.ToString());
  1385. header.AppendLine(footer.ToString());
  1386. return header.ToString().Replace("{rows}", (dt.Rows.Count + 1).ToString()).Replace("{columns}",
  1387. dt.Columns.Count.ToString());
  1388. }
  1389. public static string ReadWebConfig(string key)
  1390. {
  1391. return ReadWebConfig(key, "");
  1392. }
  1393. public static string ReadWebConfig(string key, string defValue)
  1394. {
  1395. return ConfigurationManager.AppSettings[key] ?? defValue;
  1396. }
  1397. public static string PutYellowBackGround(string mes)
  1398. {
  1399. return "<span style = \"background-color : yellow\">" + mes + "</span>";
  1400. }
  1401. public static string PutRedBackGround(string mes)
  1402. {
  1403. return "<span style = \"background-color : red\">" + mes + "</span>";
  1404. }
  1405. public static string PutBlueBackGround(string mes)
  1406. {
  1407. return "<span style = \"background-color : blue\">" + mes + "</span>";
  1408. }
  1409. public static string PutHalfYellowBackGround(string mes)
  1410. {
  1411. return "<span style = \"background-color : #FFA822\">" + mes + "</span>";
  1412. }
  1413. public static long ReadNumericDataFromQueryString(string key)
  1414. {
  1415. var tmpId = ReadQueryString(key, "0");
  1416. long tmpIdLong;
  1417. long.TryParse(tmpId, out tmpIdLong);
  1418. return tmpIdLong;
  1419. }
  1420. public static decimal ReadDecimalDataFromQueryString(string key)
  1421. {
  1422. var tmpId = ReadQueryString(key, "0");
  1423. decimal tmpIdDecimal;
  1424. decimal.TryParse(tmpId, out tmpIdDecimal);
  1425. return tmpIdDecimal;
  1426. }
  1427. public static void SetActiveMenu(string menuFunctionId)
  1428. {
  1429. HttpContext.Current.Session["activeMenu"] = menuFunctionId;
  1430. }
  1431. public static void ResizeFrame(Page page)
  1432. {
  1433. // CallBackJs1(page, "Resize Iframe", "window.parent.resizeIframe();");
  1434. }
  1435. /// <summary>
  1436. /// Set DbResult in Session
  1437. /// </summary>
  1438. public static void SetMessage(DbResult value)
  1439. {
  1440. HttpContext.Current.Session["message"] = value;
  1441. }
  1442. /// <summary>
  1443. /// Set Error Code and Message in Session
  1444. /// </summary>
  1445. /// <param name="errorCode">
  1446. /// Error Code
  1447. /// </param>
  1448. /// <param name="msg">
  1449. /// Message
  1450. /// </param>
  1451. public static void SetMessage(string errorCode, string msg)
  1452. {
  1453. var dbResult = new DbResult { ErrorCode = errorCode, Msg = msg };
  1454. SetMessage(dbResult);
  1455. }
  1456. /// <summary>
  1457. /// Jquery Print Message from session
  1458. /// </summary>
  1459. public static void PrintMessage(Page page)
  1460. {
  1461. if (HttpContext.Current.Session["message"] == null)
  1462. {
  1463. //CallBackJs1(page, "Remove Message", "SetMessageBox();");
  1464. return;
  1465. }
  1466. var dbResult = GetMessage();
  1467. CallBackJs1(page, "Set Message", "window.parent.SetMessageBox(\"" + dbResult.Msg + "\",\"" + dbResult.ErrorCode + "\");");
  1468. HttpContext.Current.Session.Remove("message");
  1469. }
  1470. /// <summary>
  1471. /// Jquery Print Message from session
  1472. /// </summary>
  1473. public static void PrintMessageAPI(Page page, JsonResponse apiResponse)
  1474. {
  1475. CallBackJs1(page, "Set Message", "window.parent.SetMessageBox(\"" + apiResponse.Msg + "\",\"" + apiResponse.ResponseCode + "\");");
  1476. HttpContext.Current.Session.Remove("message");
  1477. }
  1478. /// <summary>
  1479. /// Jquery Print Message from DbResult
  1480. /// </summary>
  1481. public static void PrintMessage(Page page, DbResult dbResult)
  1482. {
  1483. CallBackJs1(page, "Set Message", "window.parent.SetMessageBox(\"" + dbResult.Msg + "\",\"" + dbResult.ErrorCode + "\");");
  1484. }
  1485. /// <summary>
  1486. /// Jquery Print Message directly passing Error Code and Message
  1487. /// </summary>
  1488. public static void PrintMessage(Page page, string errorCode, string msg)
  1489. {
  1490. CallBackJs1(page, "Set Message", "window.parent.SetMessageBox(\"" + msg + "\",\"" + errorCode + "\");");
  1491. }
  1492. public static void PrintSuccessMessage(Page page, string msg)
  1493. {
  1494. PrintMessage(page, "0", msg);
  1495. }
  1496. public static void PrintErrorMessage(Page page, string msg)
  1497. {
  1498. PrintMessage(page, "1", msg);
  1499. }
  1500. /// <summary>
  1501. /// Alert Message from session
  1502. /// </summary>
  1503. public static void AlertMessage(Page page)
  1504. {
  1505. if (HttpContext.Current.Session["message"] == null)
  1506. return;
  1507. var dbResult = GetMessage();
  1508. if (dbResult.Msg == "")
  1509. return;
  1510. CallBackJs1(page, "Alert Message", "alert(\"" + FilterMessageForJs(dbResult.Msg) + "\");");
  1511. HttpContext.Current.Session.Remove("message");
  1512. }
  1513. /// <summary>
  1514. /// Alert Message directly passing Message
  1515. /// </summary>
  1516. public static void AlertMessage(Page page, string msg)
  1517. {
  1518. CallBackJs1(page, "Alert Message", "alert(\"" + FilterMessageForJs(msg) + "\");");
  1519. }
  1520. public static void ShowSuccessMessage(string msg)
  1521. {
  1522. HttpContext.Current.Server.Transfer(GetVirtualDirName() + "/PrintMessage.aspx?errorCode=0&msg=" + msg);
  1523. }
  1524. public static void ShowErrorMessage(string msg)
  1525. {
  1526. HttpContext.Current.Server.Transfer(GetVirtualDirName() + "/PrintMessage.aspx?errorCode=1&msg=" + msg);
  1527. }
  1528. public static string GetActiveMenu()
  1529. {
  1530. return ReadSession("activeMenu", "");
  1531. }
  1532. public static string GetBoolToChar(bool chk)
  1533. {
  1534. return chk ? "Y" : "N";
  1535. }
  1536. public static bool GetCharToBool(string value)
  1537. {
  1538. return value.ToUpper() == "Y" ? true : false;
  1539. }
  1540. public static DbResult GetMessage()
  1541. {
  1542. return (DbResult)HttpContext.Current.Session["message"];
  1543. }
  1544. public static void Redirect(Page page, string url)
  1545. {
  1546. page.ClientScript.RegisterStartupScript(typeof(string), "script", "<script language = 'javascript'>Redirect('" + url + "');</script>");
  1547. }
  1548. public static void CloseDialog(Page page, string returnValue)
  1549. {
  1550. page.ClientScript.RegisterStartupScript(typeof(string), "scriptClose", "<script language = 'javascript'>CloseDialog('" + returnValue + "');</script>");
  1551. }
  1552. public static bool VerifyMode()
  1553. {
  1554. return ReadQueryString("mode", "") == "verify" ? true : false;
  1555. }
  1556. public static string GetVoucherName(string vType)
  1557. {
  1558. switch (vType.ToLower())
  1559. {
  1560. case "j":
  1561. return "Journal Voucher";
  1562. case "c":
  1563. return "Contra Voucher";
  1564. case "y":
  1565. return "Payment Voucher";
  1566. case "r":
  1567. return "Receipt Voucher";
  1568. case "s":
  1569. return "Remittance Voucher";
  1570. default:
  1571. return "";
  1572. }
  1573. }
  1574. public static String ShowWithoutDecimal(String strVal)
  1575. {
  1576. if (strVal != "")
  1577. return String.Format("{0:0}", double.Parse(strVal));
  1578. else
  1579. return strVal;
  1580. }
  1581. public static String ShowTwoDecimal(String strVal)
  1582. {
  1583. if (strVal != "")
  1584. return double.Parse(strVal).ToString("0.00");
  1585. else
  1586. return strVal;
  1587. }
  1588. public static String ShowDecimal(String strVal)
  1589. {
  1590. if (strVal != "")
  1591. return String.Format("{0:0,0.00}", double.Parse(strVal));
  1592. else
  1593. return strVal;
  1594. }
  1595. public static String ShowDecimalRate(String strVal)
  1596. {
  1597. if (strVal != "")
  1598. return String.Format("{0:0,0.0000}", double.Parse(strVal));
  1599. else
  1600. return strVal;
  1601. }
  1602. public static String ShowAbsDecimal(String strVal)
  1603. {
  1604. if (strVal != "")
  1605. {
  1606. strVal = Math.Abs(ParseDouble(strVal)).ToString();
  1607. return String.Format("{0:0,0.00}", double.Parse(strVal));
  1608. }
  1609. else
  1610. return strVal;
  1611. }
  1612. public static string GetNegativeFigureOnBrac(string Amount)
  1613. {
  1614. var FIndex = Amount[0].ToString();
  1615. if (FIndex.Equals("-"))
  1616. {
  1617. return "(" + ShowDecimal(Amount.Substring(1).ToString()) + ")";
  1618. }
  1619. else
  1620. return ShowDecimal(Amount);
  1621. }
  1622. public static string ShowDecimal_Account(string Amount)
  1623. {
  1624. var FIndex = Amount[0].ToString();
  1625. if (FIndex.Equals("-"))
  1626. {
  1627. return ShowAbsDecimal(Amount);
  1628. }
  1629. else
  1630. return "(" + ShowDecimal(Amount.ToString()) + ")";
  1631. }
  1632. public static string GetRowData(DataRow dr, string fieldName, string defValue)
  1633. {
  1634. return dr == null ? defValue : dr[fieldName].ToString();
  1635. }
  1636. public static string GetRowData(DataRow dr, string fieldName)
  1637. {
  1638. return GetRowData(dr, fieldName, "");
  1639. }
  1640. public static string GetRowDataInShortDateFormat(DataRow dr, string fieldName)
  1641. {
  1642. return dr[fieldName].ToString() == "" ? "" : Convert.ToDateTime(dr[fieldName].ToString()).ToShortDateString();
  1643. }
  1644. public static string ParseResultJsPrint(DbResult dbResult)
  1645. {
  1646. return dbResult.ErrorCode + "-:::-" + dbResult.Msg.Replace("'", "").Replace("<br/>", "").Replace(System.Environment.NewLine, "") + "-:::-" + dbResult.Id;
  1647. }
  1648. public static void CallBackJs1(Page page, String scriptName, string functionName)
  1649. {
  1650. ScriptManager.RegisterStartupScript(page, page.GetType(), scriptName, functionName, true);
  1651. }
  1652. public static void CallJSFunction(Page page, string functionName)
  1653. {
  1654. ScriptManager.RegisterStartupScript(page, page.GetType(), "cb", functionName, true);
  1655. }
  1656. public static void CallBackJs2(Page page, string scriptName, string functionName)
  1657. {
  1658. ScriptManager.RegisterStartupScript(page, page.GetType(), scriptName, functionName, true);
  1659. }
  1660. public static double ParseDouble(string value)
  1661. {
  1662. double tmp;
  1663. double.TryParse(value, out tmp);
  1664. return tmp;
  1665. }
  1666. public static decimal ParseDecimal(string value)
  1667. {
  1668. decimal tmp;
  1669. decimal.TryParse(value, out tmp);
  1670. return tmp;
  1671. }
  1672. public static int ParseInt(string value)
  1673. {
  1674. int tmp;
  1675. int.TryParse(value, out tmp);
  1676. return tmp;
  1677. }
  1678. public static string DataTableToCheckBox(DataTable dt, string name, string valueField, string textField)
  1679. {
  1680. var sb = new StringBuilder();
  1681. foreach (DataRow row in dt.Rows)
  1682. {
  1683. sb.AppendLine("<input type = \"checkbox\" name = \"" + name + "\" value = \"" + row[valueField] +
  1684. "\" />" + row[textField] + " <br />");
  1685. }
  1686. return sb.ToString();
  1687. }
  1688. public static string ParseMinusValue(double data)
  1689. {
  1690. var retVal = Math.Abs(data).ToString("N");
  1691. if (data < 0)
  1692. {
  1693. return "(" + retVal + ")";
  1694. }
  1695. return retVal;
  1696. }
  1697. public static string ParseMinusValue(string data)
  1698. {
  1699. var m = ParseDouble(data);
  1700. return ParseMinusValue(m);
  1701. }
  1702. public static DataTable GetHistoryChangedListForIdCriteria(string oldData, string newData, string id)
  1703. {
  1704. var applicationLogsDao = new ApplicationLogsDao();
  1705. return applicationLogsDao.GetAuditDataForIdCriteria(oldData, newData, id);
  1706. }
  1707. public static DataTable GetHistoryChangedListForCommissionPackage(string oldData, string newData)
  1708. {
  1709. var applicationLogsDao = new ApplicationLogsDao();
  1710. if (string.IsNullOrEmpty(oldData))
  1711. oldData = newData;
  1712. if (string.IsNullOrEmpty(newData))
  1713. newData = oldData;
  1714. return applicationLogsDao.GetAuditDataForCommissionPackage(oldData, newData);
  1715. }
  1716. public static FullName ParseName(string fullName)
  1717. {
  1718. var fn = new FullName();
  1719. var name = fullName.Split(' ');
  1720. var names = name.Length;
  1721. fn.FirstName = name[0];
  1722. fn.MiddleName = "";
  1723. fn.LastName1 = "";
  1724. fn.LastName2 = "";
  1725. if (names > 1)
  1726. {
  1727. fn.LastName1 = name[1];
  1728. if (names > 2)
  1729. {
  1730. fn.MiddleName = name[1];
  1731. fn.LastName1 = name[2];
  1732. if (names > 3)
  1733. fn.LastName2 = name[3];
  1734. if (names > 4)
  1735. fn.LastName2 += " " + name[4];
  1736. }
  1737. }
  1738. return fn;
  1739. }
  1740. //DateTime dt = GetStatic.GMTDatetime();
  1741. public static DateTime GMTDatetime()
  1742. {
  1743. System.DateTime CurrTime = System.DateTime.Now;
  1744. System.DateTime CurrUTCTime = CurrTime.ToUniversalTime();
  1745. var dt1 = CurrUTCTime.AddMinutes(345);
  1746. return dt1;
  1747. }
  1748. public static String FilterMessageForJs(string strVal)
  1749. {
  1750. if (strVal.ToLower() != "null")
  1751. {
  1752. strVal = strVal.Replace("\"", "");
  1753. }
  1754. return strVal;
  1755. }
  1756. public static void ReloadJQueryDatePicket(Page p, string textBoxName)
  1757. {
  1758. CallBackJs1(p, "ajax", "AsyncDone('#" + textBoxName + "');");
  1759. //This script handles ajax postbacks, by registering the js to run at the end of *AJAX* requests
  1760. //p.ClientScript.RegisterStartupScript(typeof(Page), "ajaxTrigger", "Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);", true);
  1761. //p.ClientScript.RegisterClientScriptBlock(typeof(Page), "EndRequest", "function EndRequestHandler(sender, args){" + callBack + ";}", true);
  1762. }
  1763. public static String GetPopupHelpmsg()
  1764. {
  1765. var sb = new StringBuilder("<!-- Start to use Help Float-->");
  1766. sb.AppendLine("<div id=\"dek\" onmouseout=\"kill()\"></div>");
  1767. sb.AppendLine("<style type=\"text/css\">");
  1768. sb.AppendLine("<!-- #dek {position:absolute;visibility:hidden;z-index:10;} //--> </style>");
  1769. sb.AppendLine("<script type=\"text/javascript\" language=\"javascript\">");
  1770. sb.AppendLine("Xoffset = -60;");
  1771. sb.AppendLine("Yoffset = 20; ");
  1772. sb.AppendLine("var old, skn, iex = (document.all), yyy = -1000;");
  1773. sb.AppendLine("var ns4 = document.layers");
  1774. sb.AppendLine("var ns6 = document.getElementById && !document.all");
  1775. sb.AppendLine("var ie4 = document.all");
  1776. sb.AppendLine("if (ns4) skn = document.dek");
  1777. sb.AppendLine("else if (ns6) skn = document.getElementById(\"dek\").style");
  1778. sb.AppendLine("else if (ie4) skn = document.all.dek.style");
  1779. sb.AppendLine("if (ns4) document.captureEvents(Event.MOUSEMOVE);");
  1780. sb.AppendLine("else {");
  1781. sb.AppendLine("skn.visibility = \"visible\"; skn.display = \"none\"; }");
  1782. sb.AppendLine("document.onmousemove = get_mouse;");
  1783. //popup
  1784. sb.AppendLine("function popup(msg, bak, control) {");
  1785. sb.AppendLine("var pos = FindPos(GetElement(control));");
  1786. sb.AppendLine("var left = pos[0] + 200;");
  1787. sb.AppendLine("var top = pos[1];");
  1788. sb.AppendLine("document.getElementById(\"dek\").style.left = left + \"px\";");
  1789. sb.AppendLine("document.getElementById(\"dek\").style.top = top + \"px\";");
  1790. sb.AppendLine("var content = \"<TABLE WIDTH=250 BORDER=1 BORDERCOLOR=black CELLPADDING=2 CELLSPACING=0 BGCOLOR=\" + bak + \"><TD ALIGN=center><FONT COLOR=black SIZE=2>\" + msg + \"</FONT></TD></TABLE>\";");
  1791. sb.AppendLine("yyy = Yoffset;");
  1792. sb.AppendLine("if (ns4) { skn.document.write(content); skn.document.close(); skn.visibility = \"visible\" }");
  1793. sb.AppendLine("if (ns6) { document.getElementById(\"dek\").innerHTML = content; skn.display = '' }");
  1794. sb.AppendLine("if (ie4) { document.all(\"dek\").innerHTML = content; skn.display = '' }");
  1795. sb.AppendLine("}");
  1796. //function kill() {
  1797. sb.AppendLine("function kill() {");
  1798. sb.AppendLine("yyy = -1000;");
  1799. sb.AppendLine("if (ns4) { skn.visibility = \"hidden\"; }");
  1800. sb.AppendLine("else if (ns6 || ie4) skn.display = \"none\"");
  1801. sb.AppendLine("}</script>");
  1802. return sb.ToString();
  1803. }
  1804. public static string ToRomanNumeral(this int value)
  1805. {
  1806. if (value < 0)
  1807. {
  1808. // throw new ArgumentOutOfRangeException("Please use a positive integer greater than zero.");
  1809. return "";
  1810. }
  1811. StringBuilder sb = new StringBuilder();
  1812. int remain = value;
  1813. while (remain > 0)
  1814. {
  1815. if (remain >= 1000) { sb.Append("M"); remain -= 1000; }
  1816. else if (remain >= 900) { sb.Append("CM"); remain -= 900; }
  1817. else if (remain >= 500) { sb.Append("D"); remain -= 500; }
  1818. else if (remain >= 400) { sb.Append("CD"); remain -= 400; }
  1819. else if (remain >= 100) { sb.Append("C"); remain -= 100; }
  1820. else if (remain >= 90) { sb.Append("XC"); remain -= 90; }
  1821. else if (remain >= 50) { sb.Append("L"); remain -= 50; }
  1822. else if (remain >= 40) { sb.Append("XL"); remain -= 40; }
  1823. else if (remain >= 10) { sb.Append("X"); remain -= 10; }
  1824. else if (remain >= 9) { sb.Append("IX"); remain -= 9; }
  1825. else if (remain >= 5) { sb.Append("V"); remain -= 5; }
  1826. else if (remain >= 4) { sb.Append("IV"); remain -= 4; }
  1827. else if (remain >= 1) { sb.Append("I"); remain -= 1; }
  1828. else
  1829. {
  1830. //throw new Exception("Unexpected error."); // <<-- shouldn't be possble to get here, but it ensures that we will never have an infinite loop (in case the computer is on crack that day).
  1831. }
  1832. }
  1833. return sb.ToString();
  1834. }
  1835. public static string getCompanyHead()
  1836. {
  1837. var headerSplit = ReadWebConfig("companyName", "").Split('|');
  1838. string header = "<strong>" + headerSplit[0].ToString() + "</strong>";
  1839. header += "<br>" + headerSplit[1].ToString();
  1840. return header;
  1841. }
  1842. public static string IntToLetter(this int value)
  1843. {
  1844. string result = string.Empty;
  1845. while (--value >= 0)
  1846. {
  1847. result = (char)('a' + value % 26) + result;
  1848. value /= 26;
  1849. }
  1850. return result + ".";
  1851. }
  1852. public static string GetVoucherType(string vType, string def)
  1853. {
  1854. string vt = "";
  1855. if (vType.ToLower() == "s")
  1856. {
  1857. vt = "Sales";
  1858. }
  1859. else if (vType.ToLower() == "p")
  1860. {
  1861. vt = "Purchase";
  1862. }
  1863. else if (vType.ToLower() == "c")
  1864. {
  1865. vt = "Contra";
  1866. }
  1867. else if (vType.ToLower() == "y")
  1868. {
  1869. vt = "Payment";
  1870. }
  1871. else if (vType.ToLower() == "r")
  1872. {
  1873. vt = "Receipt";
  1874. }
  1875. else if (vType.ToLower() == "j")
  1876. {
  1877. vt = "Journal";
  1878. }
  1879. else
  1880. {
  1881. vt = def;
  1882. }
  1883. return vt;
  1884. }
  1885. /// <summary>
  1886. /// </summary>
  1887. /// <param name="page">
  1888. /// </param>
  1889. /// <param name="controlNo">
  1890. /// </param>
  1891. /// <param name="message">
  1892. /// </param>
  1893. /// <param name="successMessageType">
  1894. /// 1 - Jquery Message, 2 - Js Alert Message
  1895. /// </param>
  1896. #region for Remittance use only
  1897. public static string GetDomesticSuperAgentId()
  1898. {
  1899. return ReadWebConfig("domesticSuperAgentId");
  1900. }
  1901. public static string GetHoAgentId()
  1902. {
  1903. return ReadWebConfig("hoAgentId");
  1904. }
  1905. #endregion for Remittance use only
  1906. public static string GetDomesticCountryId()
  1907. {
  1908. return ReadWebConfig("domesticCountryId");
  1909. }
  1910. public static string GetCountryId()
  1911. {
  1912. return ReadSession("countryId", "");
  1913. }
  1914. public static string GetDefaultPage()
  1915. {
  1916. switch (ReadCookie("loginType", "").ToUpper())
  1917. {
  1918. case "ADMIN":
  1919. return GetUrlRoot() + "/admin";
  1920. case "AGENT":
  1921. return GetUrlRoot() + "/agentlogin";
  1922. }
  1923. return GetUrlRoot();
  1924. }
  1925. internal static string GetDefaultDocPath()
  1926. {
  1927. switch (ReadCookie("loginType", "").ToUpper())
  1928. {
  1929. case "ADMIN":
  1930. return GetUrlRoot() + "/admin";
  1931. case "AGENT":
  1932. return GetUrlRoot() + "/agentlogin";
  1933. }
  1934. return GetUrlRoot();
  1935. }
  1936. public static string GetDefaultDocPathMortgage()
  1937. {
  1938. return ReadWebConfig("defaultDocPath");
  1939. }
  1940. public static string GetSendEmailId()
  1941. {
  1942. return ReadWebConfig("SendEmailId");
  1943. }
  1944. public static string GetSendEmailPwd()
  1945. {
  1946. return ReadWebConfig("SendEmailPwd");
  1947. }
  1948. public static string GetSmtpPort()
  1949. {
  1950. return ReadWebConfig("SmtpPort");
  1951. }
  1952. public static string GetSmtpServer()
  1953. {
  1954. return ReadWebConfig("SmtpServer");
  1955. }
  1956. public static void JsonResponse<T>(T obk, Page page, DataTable dt = null)
  1957. {
  1958. string jsonString = "";
  1959. if (dt == null)
  1960. {
  1961. JavaScriptSerializer jsonData = new JavaScriptSerializer();
  1962. jsonData.MaxJsonLength = Int32.MaxValue;
  1963. jsonString = jsonData.Serialize(obk);
  1964. }
  1965. else
  1966. {
  1967. jsonString = DataTableToJson(dt);
  1968. }
  1969. page.Response.ContentType = "application/json";
  1970. page.Response.Write(jsonString);
  1971. page.Response.End();
  1972. }
  1973. public static string DataTableToJson(DataTable table)
  1974. {
  1975. if (table == null)
  1976. return "";
  1977. var list = new List<Dictionary<string, object>>();
  1978. foreach (DataRow row in table.Rows)
  1979. {
  1980. var dict = new Dictionary<string, object>();
  1981. foreach (DataColumn col in table.Columns)
  1982. {
  1983. dict[col.ColumnName] = string.IsNullOrEmpty(row[col].ToString()) ? "" : row[col];
  1984. }
  1985. list.Add(dict);
  1986. }
  1987. var serializer = new JavaScriptSerializer();
  1988. string json = serializer.Serialize(list);
  1989. return json;
  1990. }
  1991. public static void DataTableToJson(DataTable table, Page page)
  1992. {
  1993. if (null == table)
  1994. {
  1995. page.Response.ContentType = "application/json";
  1996. page.Response.Write("");
  1997. page.Response.End();
  1998. }
  1999. else
  2000. {
  2001. var list = new List<Dictionary<string, object>>();
  2002. foreach (DataRow row in table.Rows)
  2003. {
  2004. var dict = new Dictionary<string, object>();
  2005. foreach (DataColumn col in table.Columns)
  2006. {
  2007. dict[col.ColumnName] = string.IsNullOrEmpty(row[col].ToString()) ? "" : row[col];
  2008. }
  2009. list.Add(dict);
  2010. }
  2011. var serializer = new JavaScriptSerializer();
  2012. string json = serializer.Serialize(list);
  2013. page.Response.ContentType = "application/json";
  2014. page.Response.Write(json);
  2015. page.Response.End();
  2016. }
  2017. }
  2018. public static string ObjectToXML(object input)
  2019. {
  2020. try
  2021. {
  2022. StringWriter stringwriter = new StringWriter();
  2023. XmlSerializer serializer = new XmlSerializer(input.GetType());
  2024. serializer.Serialize(stringwriter, input);
  2025. return stringwriter.ToString();
  2026. }
  2027. catch (Exception ex)
  2028. {
  2029. if (ex.InnerException != null)
  2030. ex = ex.InnerException;
  2031. return "Could not convert: " + ex.Message;
  2032. }
  2033. }
  2034. public static string MakeAutoCompleteControl(string uniqueKey, string category, string selectedValue = "", string selectedText = "")
  2035. {
  2036. var url = GetStatic.GetUrlRoot() + "/Component/AutoComplete/DataSource.asmx/GetList";
  2037. var usr = GetStatic.GetUser();
  2038. var sb = new StringBuilder();
  2039. //var strClientID = rowId + "_" + f.Key;
  2040. var ctlValue = uniqueKey + "_aValue";
  2041. var ctlText = uniqueKey + "_aText";
  2042. var ctlSearch = uniqueKey + "_aSearch";
  2043. //grdRole_gl_code_aText_c_admin////grdRole_gl_code_aSearch
  2044. sb.Append("<input type = 'hidden' id = '" + ctlValue + "' name = '" + ctlValue + "' value='" + selectedValue + "'/>");
  2045. sb.Append("<input type = 'text' id = '" + ctlText + "' name = '" + ctlText + "' class='form-control' value='" + selectedText + "' />");
  2046. sb.Append("<input style = 'background-color:#BBF;display:none' type = 'text' id = '" + ctlSearch + "' name = '" + ctlSearch + "' class='form-control' />");
  2047. sb.Append("<script language = 'javascript' type ='text/javascript'>");
  2048. sb.Append("$(document).ready(function () {");
  2049. sb.Append("function Auto_" + uniqueKey + "() {");
  2050. sb.Append(InitFunction(category, url, uniqueKey, "150px"));
  2051. sb.Append("} Auto_" + uniqueKey + "();");
  2052. sb.Append("});");
  2053. sb.Append("</script>");
  2054. return sb.ToString();
  2055. }
  2056. public static string MakeAutoCompleteControlNew(string uniqueKey, string category, string selectedValue = "", string selectedText = "")
  2057. {
  2058. var url = GetStatic.GetUrlRoot() + "/Component/AutoComplete/DataSource.asmx/GetList";
  2059. var usr = GetStatic.GetUser();
  2060. var sb = new StringBuilder();
  2061. //var strClientID = rowId + "_" + f.Key;
  2062. var ctlValue = uniqueKey + "_aValue";
  2063. var ctlText = uniqueKey + "_aText";
  2064. var ctlSearch = uniqueKey + "_aSearch";
  2065. //grdRole_gl_code_aText_c_admin////grdRole_gl_code_aSearch
  2066. sb.Append("<input type = 'hidden' id = '" + ctlValue + "' name = '" + ctlValue + "' value='" + selectedValue + "'/>");
  2067. sb.Append("<input type = 'text' disabled id = '" + ctlText + "' name = '" + ctlText + "' class='form-control' value='" + selectedText + "' />");
  2068. sb.Append("<input style = 'background-color:#BBF;display:none' type = 'text' id = '" + ctlSearch + "' name = '" + ctlSearch + "' class='form-control' />");
  2069. sb.Append("<script language = 'javascript' type ='text/javascript'>");
  2070. sb.Append("$(document).ready(function () {");
  2071. sb.Append("function Auto_" + uniqueKey + "() {");
  2072. sb.Append(InitFunction(category, url, uniqueKey, "150px"));
  2073. sb.Append("} Auto_" + uniqueKey + "();");
  2074. sb.Append("});");
  2075. sb.Append("</script>");
  2076. return sb.ToString();
  2077. }
  2078. public static Location GetLocation(string ipAddress)
  2079. {
  2080. if (ReadWebConfig("UseLocationAPI", "") == "N")
  2081. {
  2082. return new Location
  2083. {
  2084. errorCode = "1",
  2085. errorMsg = "Called from DEV, so no API Called!"
  2086. };
  2087. }
  2088. string apiKey = GetStatic.ReadWebConfig("GeoLocationIpInfoKey");
  2089. string url = string.Format("http://api.ipinfodb.com/v3/ip-city/?key={0}&ip={1}", apiKey, ipAddress);
  2090. JavaScriptSerializer serializer = new JavaScriptSerializer();
  2091. try
  2092. {
  2093. var HttpWReq = (HttpWebRequest)WebRequest.Create(url);
  2094. HttpWReq.Method = "GET";
  2095. var HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
  2096. System.IO.StreamReader reader = new System.IO.StreamReader(HttpWResp.GetResponseStream());
  2097. string content = reader.ReadToEnd();
  2098. var _arrLoc = content.Split(';');
  2099. if (_arrLoc[0].ToUpper() == "OK")
  2100. {
  2101. Location _loc = new Location
  2102. {
  2103. errorCode = "0",
  2104. IpAddress = _arrLoc[2],
  2105. CountryCode = _arrLoc[3],
  2106. CountryName = _arrLoc[4],
  2107. Region = _arrLoc[5],
  2108. City = _arrLoc[6],
  2109. ZipCode = _arrLoc[7],
  2110. Lat = _arrLoc[8],
  2111. Long = _arrLoc[9],
  2112. TimeZone = _arrLoc[10]
  2113. };
  2114. return _loc;
  2115. }
  2116. else
  2117. {
  2118. Location _loc = new Location
  2119. {
  2120. errorCode = "1",
  2121. errorMsg = _arrLoc[0] + " : " + _arrLoc[1]
  2122. };
  2123. return _loc;
  2124. }
  2125. }
  2126. catch (Exception ex)
  2127. {
  2128. return new Location
  2129. {
  2130. errorCode = "1",
  2131. errorMsg = ex.Message
  2132. };
  2133. }
  2134. }
  2135. public static string GetSMSTextForTxn(DataRow sRow)
  2136. {
  2137. FullName _fullNameS = GetStatic.ParseName(sRow["senderName"].ToString());
  2138. FullName _fullNameR = GetStatic.ParseName(sRow["receiverName"].ToString());
  2139. string sms = "";
  2140. if (sRow["paymentMethod"].ToString().ToLower() == "bank deposit")
  2141. {
  2142. FullName _bankName = GetStatic.ParseName(sRow["pBankName"].ToString());
  2143. sms += "Dear Mr/Ms " + _fullNameS.FirstName + ", your money sent to account of Mr/Ms " + _fullNameR.FirstName + " in ";
  2144. sms += _bankName.FirstName + "... Bank. Amt sent: JPY " + GetStatic.ShowWithoutDecimal(sRow["cAmt"].ToString());
  2145. sms += ", Deposit Amt " + sRow["payoutCurr"].ToString() + " " + GetStatic.ShowWithoutDecimal(sRow["pAmt"].ToString()) + ". Thank you-JME.";
  2146. }
  2147. else
  2148. {
  2149. sms += "Dear Mr/Ms " + _fullNameS.FirstName + ", your money sent to Mr/Ms " + _fullNameR.FirstName + ". Amt sent: JPY ";
  2150. sms += GetStatic.ShowWithoutDecimal(sRow["cAmt"].ToString()) + ", Payout Amt " + sRow["payoutCurr"].ToString() + " " + GetStatic.ShowWithoutDecimal(sRow["pAmt"].ToString()) + ". PIN NO: " + sRow["controlNo"].ToString() + ". Thank you-JME.";
  2151. }
  2152. return sms;
  2153. }
  2154. public static string SendEmail(string msgSubject, string msgBody, string toEmailId)
  2155. {
  2156. SmtpMailSetting mail = new SmtpMailSetting
  2157. {
  2158. MsgBody = msgBody,
  2159. MsgSubject = msgSubject,
  2160. ToEmails = toEmailId
  2161. };
  2162. return mail.SendSmtpMail(mail);
  2163. }
  2164. private static string InitFunction(string filter, string url, string rowId, string width)
  2165. {
  2166. var sb = new StringBuilder();
  2167. sb.Append("LoadAutoCompleteTextBox(");
  2168. sb.Append(@"""" + url + @"""");
  2169. sb.Append(@",""#" + rowId + @"""");
  2170. sb.Append(@",""" + width + @"""");
  2171. sb.Append(@",""" + filter + @""");");
  2172. return sb.ToString();
  2173. }
  2174. public static string UploadSignatureImage(string imageData, string registerDate, string membershipId, string customerId)
  2175. {
  2176. string errorCode = "1";
  2177. try
  2178. {
  2179. string fileExtension = ".png";
  2180. string fileName = customerId + "_signature_" + DateTime.Now.Hour.ToString() + DateTime.Now.Millisecond.ToString() + "_" + registerDate.Replace("-", "_") + fileExtension;
  2181. string path = GetStatic.GetCustomerFilePath() + "CustomerDocument\\" + registerDate.Replace("-", "\\") + "\\" + membershipId;
  2182. if (!Directory.Exists(path))
  2183. Directory.CreateDirectory(path);
  2184. string fName = path + "\\" + fileName;
  2185. using (FileStream fs = new FileStream(fName, FileMode.CreateNew))
  2186. {
  2187. using (BinaryWriter bw = new BinaryWriter(fs))
  2188. {
  2189. byte[] data = Convert.FromBase64String(imageData);
  2190. bw.Write(data);
  2191. bw.Close();
  2192. }
  2193. }
  2194. errorCode = fileName;
  2195. }
  2196. catch (Exception ex)
  2197. {
  2198. errorCode = "1";
  2199. }
  2200. return errorCode;
  2201. }
  2202. public static string HTMLToPDF(string htmlString, string user, string fileSaveLocation, string filePrefix = "")
  2203. {
  2204. string fileName = GetDateTimeStamp() + "_" + user + ".pdf";
  2205. if (!string.IsNullOrEmpty(filePrefix))
  2206. fileName = filePrefix + "_" + fileName;
  2207. HtmlToPdf converter = new HtmlToPdf();
  2208. if (!File.Exists(fileSaveLocation))
  2209. Directory.CreateDirectory(fileSaveLocation);
  2210. PdfDocument doc = converter.ConvertHtmlString(htmlString, ReadWebConfig("root", ""));
  2211. doc.Save(fileSaveLocation + fileName);
  2212. doc.Close();
  2213. return fileName;
  2214. }
  2215. public static string GetDateTimeStamp()
  2216. {
  2217. return DateTime.Now.ToString("yyyyMMddHHmmssffff");
  2218. }
  2219. public static string DataSetToJSON(DataSet ds)
  2220. {
  2221. ArrayList root = new ArrayList();
  2222. List<Dictionary<string, object>> table;
  2223. Dictionary<string, object> data;
  2224. foreach (DataTable dt in ds.Tables)
  2225. {
  2226. table = new List<Dictionary<string, object>>();
  2227. foreach (DataRow dr in dt.Rows)
  2228. {
  2229. data = new Dictionary<string, object>();
  2230. foreach (DataColumn col in dt.Columns)
  2231. {
  2232. data.Add(col.ColumnName, dr[col]);
  2233. }
  2234. table.Add(data);
  2235. }
  2236. root.Add(table);
  2237. }
  2238. JavaScriptSerializer serializer = new JavaScriptSerializer();
  2239. return serializer.Serialize(root);
  2240. }
  2241. #region MIME TYPE
  2242. private static IDictionary<string, string> _mappings = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase)
  2243. {
  2244. {".jpe", "image/jpeg"},
  2245. {".jpeg", "image/jpeg"},
  2246. {".jpg", "image/jpeg"},
  2247. {".png", "image/png"},
  2248. {".bmp", "image/bmp"},
  2249. {".tif", "image/tiff"},
  2250. {".tiff", "image/tiff"},
  2251. {".pdf", "application/pdf"},
  2252. {".gif", "image/gif"},
  2253. {".xls", "application/vnd.ms-excel"},
  2254. {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
  2255. {".xml", "text/xml"},
  2256. {".xps", "application/vnd.ms-xpsdocument"},
  2257. {".txt", "text/plain"},
  2258. {".csv", "text/csv"},
  2259. };
  2260. public static string GetFileExtension(this string fileName)
  2261. {
  2262. string ext = string.Empty;
  2263. int fileExtPos = fileName.LastIndexOf(".", StringComparison.Ordinal);
  2264. if (fileExtPos >= 0)
  2265. ext = fileName.Substring(fileExtPos, fileName.Length - fileExtPos);
  2266. return ext;
  2267. }
  2268. public static string GetMimeType(this string extension)
  2269. {
  2270. if (extension == null)
  2271. {
  2272. throw new ArgumentNullException("extension");
  2273. }
  2274. if (!extension.StartsWith("."))
  2275. extension = "." + extension;
  2276. string mime;
  2277. return _mappings.TryGetValue(extension, out mime) ? mime : "text/plain";
  2278. }
  2279. #endregion
  2280. public static DbResult LogError(Exception lastError, string userid = "")
  2281. {
  2282. Exception err = lastError;
  2283. if (lastError.InnerException != null)
  2284. err = lastError.InnerException;
  2285. RemittanceDao db = new RemittanceDao();
  2286. var errPage = db.FilterString(HttpContext.Current.Request.Url.ToString());
  2287. var errMsg = db.FilterString(err.Message);
  2288. var errDetails = db.FilterString(lastError.ToString());
  2289. var user = !string.IsNullOrWhiteSpace(userid) ? userid : GetUser();
  2290. string sql = string.Format(@"EXEC proc_ErrorLogs @flag = 'i', @errorPage={0}, @errorMsg={1}, @errorDetails={2}, @user = {3}", errPage, errMsg, errDetails, user);
  2291. DbResult _db = db.ParseDbResult(sql);
  2292. return _db;
  2293. }
  2294. public static String ShowDecimalWithoutZero(String strVal)
  2295. {
  2296. if (strVal != "")
  2297. return String.Format("{0:0,0}", double.Parse(strVal));
  2298. else
  2299. return "0";
  2300. }
  2301. public static string GetMIMEExtension(this string contentType)
  2302. {
  2303. return MimeTypes.MimeTypeMap.GetExtension(contentType);
  2304. }
  2305. public static string GetCSVFileInXML(string path, string[] defaultHeaders, bool hasHeader = true)
  2306. {
  2307. var columnList = new ArrayList();
  2308. var sb = new StringBuilder("<root>");
  2309. using (CsvReader reader = new CsvReader(path))
  2310. {
  2311. foreach (string[] values in reader.RowEnumerator)
  2312. {
  2313. defaultHeaders = defaultHeaders.Select(a => a.Trim()).ToArray().Select(s => s.ToLowerInvariant()).ToArray();
  2314. var fileHeaders = values.Select(a => a.Trim()).ToArray().Select(s => s.ToLowerInvariant()).ToArray();
  2315. var areEqual = Enumerable.SequenceEqual(defaultHeaders, fileHeaders);
  2316. if (hasHeader)
  2317. {
  2318. if (areEqual)
  2319. {
  2320. foreach (var item in defaultHeaders)
  2321. {
  2322. columnList.Add(item);
  2323. }
  2324. columnList.Add("trantype");
  2325. columnList.Add("invalidreason");
  2326. hasHeader = false;
  2327. continue;
  2328. }
  2329. else
  2330. break;
  2331. }
  2332. if (values.Length > 0)
  2333. {
  2334. var trimValues = values.Select(a => a.Trim()).ToArray();
  2335. bool isFirstLoop = true;
  2336. bool isInvalid = false;
  2337. string misMatchedColumn = "";
  2338. sb.Append("<row>");
  2339. for (int i = 0; i < trimValues.Length; i++)
  2340. {
  2341. //mandatory fields
  2342. if (isFirstLoop && (string.IsNullOrEmpty(trimValues[0]) || !IsValidPartner(trimValues[0]) || string.IsNullOrEmpty(trimValues[1]) || string.IsNullOrEmpty(trimValues[2]) || string.IsNullOrEmpty(trimValues[3]) ||
  2343. string.IsNullOrEmpty(trimValues[4]) || string.IsNullOrEmpty(trimValues[6]) || string.IsNullOrEmpty(trimValues[7]) || string.IsNullOrEmpty(trimValues[8]) ||
  2344. string.IsNullOrEmpty(trimValues[9]) || string.IsNullOrEmpty(trimValues[12]) || string.IsNullOrEmpty(trimValues[13]) || !IsValidDate(trimValues[13]) ||
  2345. string.IsNullOrEmpty(trimValues[15]) || !IsValidPaymentMethod(trimValues[15]) || (trimValues[15].ToLower().Equals("w") && (!IsValidNumber(trimValues[10]) || trimValues[14].ToLower() != "imepay")) ||
  2346. (trimValues[15].ToLower().Equals("b") && (string.IsNullOrEmpty(trimValues[14]) || string.IsNullOrEmpty(trimValues[16]) || string.IsNullOrEmpty(trimValues[18]) || !IsValidBankid(trimValues[14]))) ||
  2347. string.IsNullOrEmpty(trimValues[19]) || string.IsNullOrEmpty(trimValues[20]) || (IsRateRequiredPartner(trimValues[0]) && string.IsNullOrEmpty(trimValues[22])) || string.IsNullOrEmpty(trimValues[23]) || string.IsNullOrEmpty(trimValues[24]) || string.IsNullOrEmpty(trimValues[25])
  2348. || string.IsNullOrEmpty(trimValues[26])))
  2349. {
  2350. isInvalid = true;
  2351. isFirstLoop = false;
  2352. }
  2353. // to assign invalidreason for empty columns values
  2354. if (string.IsNullOrEmpty(trimValues[i]) && (i == 0 || i == 1 || i == 2 || i == 3 || i == 4 || i == 6 || i == 7 || i == 8
  2355. || i == 9 || i == 12 || i == 13 || i == 15 || i == 19 || i == 20))
  2356. misMatchedColumn += string.IsNullOrEmpty(misMatchedColumn) ? columnList[i].ToString() : ',' + columnList[i].ToString();
  2357. // to assign invalidreason for invalid columns values
  2358. else if ((i == 0 && !IsValidPartner(trimValues[0])) || (i == 10 && trimValues[15].ToLower().Equals("w") && !IsValidNumber(trimValues[10])) ||
  2359. (i == 13 && !IsValidDate(trimValues[13])) || (i == 14 && trimValues[15].ToLower().Equals("w") && trimValues[14].ToLower() != "imepay") ||
  2360. (i == 14 && trimValues[15].ToLower().Equals("b") && string.IsNullOrEmpty(trimValues[14])) || (i == 15 && !IsValidPaymentMethod(trimValues[15])) ||
  2361. (i == 16 && trimValues[15].ToLower().Equals("b") && string.IsNullOrEmpty(trimValues[16])) || (i == 18 && trimValues[15].ToLower().Equals("b") && string.IsNullOrEmpty(trimValues[18])) ||
  2362. (i == 14 && trimValues[15].ToLower().Equals("b") && !IsValidBankid(trimValues[14])) || (i == 22 && IsRateRequiredPartner(trimValues[0]) && string.IsNullOrEmpty(trimValues[22])) || string.IsNullOrEmpty(trimValues[23])
  2363. || string.IsNullOrEmpty(trimValues[24]) || string.IsNullOrEmpty(trimValues[25]) || string.IsNullOrEmpty(trimValues[26]))
  2364. {
  2365. misMatchedColumn += string.IsNullOrEmpty(misMatchedColumn) ? columnList[i].ToString() : ',' + columnList[i].ToString();
  2366. }
  2367. sb.Append(string.Format(" <{0}>{1}</{0}>", columnList[i], values[i]));
  2368. }
  2369. if (isInvalid)
  2370. sb.Append(string.Format(" <{0}>{1}</{0}>", columnList[27], "Invalid"));
  2371. else
  2372. sb.Append(string.Format(" <{0}>{1}</{0}>", columnList[27], "Valid"));
  2373. sb.Append(string.Format(" <{0}>{1}</{0}>", columnList[28], misMatchedColumn));
  2374. sb.Append(" </row>");
  2375. }
  2376. }
  2377. }
  2378. sb.Append("</root>");
  2379. return sb.ToString();
  2380. }
  2381. public static bool IsValidPaymentMethod(string name)
  2382. {
  2383. string[] nameArray = { "c", "b", "w" };
  2384. if (Array.Exists(nameArray, element => element == name.ToLower()))
  2385. return true;
  2386. return false;
  2387. }
  2388. public static bool IsValidNumber(string number)
  2389. {
  2390. if (Regex.Match(number, @"^9(61|62|74|75|80|81|82|84|85|86|88)[0-9]{7}$").Success)
  2391. return true;
  2392. return false;
  2393. }
  2394. public static bool IsValidDate(string date)
  2395. {
  2396. string[] format = { "yyyy-mm-dd" };
  2397. DateTime parsedDateTime;
  2398. if (DateTime.TryParseExact(date, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out parsedDateTime))
  2399. return true;
  2400. return false;
  2401. }
  2402. public static bool IsValidPartner(string partnerId)
  2403. {
  2404. var db = new RemittanceDao();
  2405. var sql = "EXEC proc_UploadedFileTxnHistory @flag = 'checkPartner', @partnerId = '" + partnerId + "'";
  2406. var dbResult = db.ParseDbResult(sql);
  2407. if (dbResult.ErrorCode == "0")
  2408. return true;
  2409. return false;
  2410. }
  2411. public static bool IsRateRequiredPartner(string partnerId)
  2412. {
  2413. var rateRequiredPartners = ConfigurationManager.AppSettings["rate_required_partners"];
  2414. List<string> lst = new List<string>();
  2415. if (rateRequiredPartners != null)
  2416. {
  2417. lst = rateRequiredPartners.Split('|').ToList();
  2418. if (lst.Contains(partnerId))
  2419. return true;
  2420. }
  2421. return false;
  2422. }
  2423. public static bool IsValidBankid(string bankId)
  2424. {
  2425. if (string.IsNullOrEmpty(bankId))
  2426. return false;
  2427. var db = new RemittanceDao();
  2428. var sql = "EXEC proc_UploadedFileTxnHistory @flag = 'checkbankCode', @partnerId = '" + bankId + "'";
  2429. var dbResult = db.ParseDbResult(sql);
  2430. if (dbResult.ErrorCode == "0")
  2431. return true;
  2432. return false;
  2433. }
  2434. }
  2435. }