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.

2680 lines
95 KiB

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