using System;
using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessObjects;
using System.Xml;
using System.Net;
using System.Net.NetworkInformation;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.ComponentModel;
using System.Reflection;
using System.Globalization;
using System.Threading;
/// <summary>
/// Common helper class for HVMCore, contains helper functions
/// </summary>
public class CommonHelper
{
#region Variables
// Name of the Attribute in DropDownLists specifying whether to add blank item or not(Its value is "1" if blank item is to be added,else it is "0")
public const string AddBlankCaption = "AddBlank";
// Name of the Attribute in DropDownLists specifying whether to replace underscore with the space
public const string ReplaceUnderScoreFromEnumCaption = "ReplaceUnderscore";
public const char Separator = ';';
//public const string minSQLDate = "01/01/1753";
//public const string maxSQLDate = "12/31/9999";
public const string comboValueField = "ID";
public const string comboTextField = "TEXT";
public const string NoAccess = "'*****'";
public const string dateFormat = "MM/dd/yy";
// EditText for Grid
public const string GridEditText = "<img src='https://www.prudentcorporate.com/branchdesk/images/edit.gif' alt='{0}' border='0'/>";
// UpdateText for Grid
public const string GridUpdateText = "<img src='https://www.prudentcorporate.com/branchdesk/images/save.gif' alt='{0}' border='0'/>";
// DeleteText for Grid
public const string GridDeleteText = "<img src='https://www.prudentcorporate.com/branchdesk/images/del.gif' alt='{0}' border='0' onclick='return confirmDelete(event);'/>";
// CancelText for Grid
public const string GridCancelText = "<img src='https://www.prudentcorporate.com/branchdesk/images/cancel.gif' alt='{0}' border='0'/>";
public const short commandFieldIndex = 1, checkBoxFieldIndex = 0, changePwdField = 12,
activateUserFieldIndex = 14, assignUserToPocPCFieldIndex = 15, assignPocPCToUserFieldIndex = 13, activatePocPCFieldIndex = 16;
public const string minCharsRegx = @"\w{{{0},}}";
#endregion //Variables
public static void MessageBox(Page p, string msg)
{
//System.Web.UI.Page p = new Page();
ClientScriptManager cm = p.ClientScript;
cm.RegisterStartupScript(p.GetType(), "alert", "<script>alert('" + msg + "');</script>");
}
//Clear Values Controls
/// <summary>
/// Function to Clear value of Controls
/// </summary>
/// <param name="controls">Controls to be manipulated</param>
public static void Clear(Control[] controls)
{
foreach (Control ctrSource in controls)
{
switch (ctrSource.GetType().Name)
{
case "TextBox":
((TextBox)(ctrSource)).Text = "";
break;
case "CheckBox":
((CheckBox)(ctrSource)).Checked = false;
break;
case "ListBox":
((ListBox)(ctrSource)).Items.Clear();
break;
case "RadioButton":
((RadioButton)(ctrSource)).Checked = false;
break;
case "RadioButtonList":
((RadioButtonList)(ctrSource)).SelectedIndex = 0;
break;
case "DropDownList":
if (((DropDownList)(ctrSource)).Items.Count > 0)
((DropDownList)(ctrSource)).SelectedIndex = 0;
break;
}
}
}
public static string[] getRowValues(GridView gv)
{
if (gv.EditIndex < 0)
return new string[0];
string[] values = new string[gv.Rows[gv.EditIndex].Controls.Count];
int i = 0;
int ctrlPos = 0;
foreach (Control ctrl in gv.Rows[gv.EditIndex].Controls)
{
//Necessary for combobox in an edit item template
ctrlPos = ctrl.Controls.Count == 1 ? 0 : 1;
switch (ctrl.Controls[ctrlPos].GetType().Name)
{
case "DataBoundLiteralControl":
values[i] =
((DataBoundLiteralControl)ctrl.Controls[ctrlPos]).Text.Trim().Replace("'", "''");
break;
case "TextBox":
values[i] = ((TextBox)ctrl.Controls[ctrlPos]).Text.Trim().Replace("'", "''");
break;
case "CheckBox":
values[i] = ((CheckBox)ctrl.Controls[ctrlPos]).Checked ? "1" : "0";
break;
case "DropDownList":
values[i] = ((DropDownList)ctrl.Controls[ctrlPos]).SelectedValue;
break;
}
i++;
}
return values;
}
// Bind Data To Combo
/// <summary>
/// function to bind data to DropDownList
/// </summary>
/// <param name="ddlCombo">DropDownList</param>
/// <param name="dtSource">Data source</param>
/// <param name="dataTextField">data text field</param>
/// <param name="dataValueField">data value field</param>
public static void bindCombo(DropDownList ddlCombo,
DataTable dtSource, string dataTextField, string dataValueField)
{
ddlCombo.Items.Clear();
ddlCombo.Items.Add(new ListItem("---Select---", "-1"));
if (dtSource != null)
{
ddlCombo.DataSource = dtSource;
ddlCombo.DataTextField = dataTextField;
ddlCombo.DataValueField = dataValueField;
ddlCombo.DataBind();
}
}
public static void FillCheckBoxListFromEnums(CheckBoxList[] chkArray, Type[] enumType)
{
for (int chkCounter = 0; chkCounter < chkArray.Length; chkCounter++)
{
// clear the all item before adding
chkArray[chkCounter].Items.Clear();
// Fill the each item in Enum to Combo
if (chkArray[chkCounter].Attributes[ReplaceUnderScoreFromEnumCaption] != null)
{
foreach (string str in Enum.GetNames(enumType[chkCounter]))
{
chkArray[chkCounter].Items.Add(new ListItem(str.Replace("_", " "), (Convert.ToInt32(Enum.Parse(enumType[chkCounter], str))).ToString()));
}
}
else
{
foreach (string str in Enum.GetNames(enumType[chkCounter]))
{
chkArray[chkCounter].Items.Add(new ListItem(str, (Convert.ToInt32(Enum.Parse(enumType[chkCounter], str))).ToString()));
}
}
// If "AddBlank" attribute is present, then add a Blank item"
if (chkArray[chkCounter].Attributes[AddBlankCaption] != null)
chkArray[chkCounter].Items.Insert(0, new ListItem("", ""));
}
}
//Bind a Data To ListBox
/// <summary>
/// function to bind data to ListBox
/// </summary>
/// <param name="lstListBox">ListBox</param>
/// <param name="dtSource">Data source</param>
/// <param name="dataTextField">data text field</param>
/// <param name="dataValueField">data value field</param>
public static void bindListBox(ListBox lstListBox,
DataTable dtSource, string dataTextField, string dataValueField)
{
if (dtSource != null)
{
lstListBox.DataSource = dtSource;
lstListBox.DataTextField = dataTextField;
lstListBox.DataValueField = dataValueField;
lstListBox.DataBind();
}
}
public static void bindCheckBoxList(CheckBoxList ddlCheck,
DataTable dtSource, string dataTextField, string dataValueField)
{
if (dtSource != null)
{
ddlCheck.DataSource = dtSource;
ddlCheck.DataTextField = dataTextField;
ddlCheck.DataValueField = dataValueField;
ddlCheck.DataBind();
}
}
// Populate combo from DataTable
/// <summary>
/// populate comboxes using the data tables
/// NOTE: datatable must have two columns 'lTEXT' and 'lVALUE'
/// </summary>
/// <param name="dtSourceArr">Source DataTables</param>
/// <param name="ddlComboArr">Comboboxes to be populated</param>
/// <param name="addBlankArr">Array of flags whether to add blank item</param>
//public static void FillCombosFromDataTables(DataTable[] dtSourceArr, DropDownList[] ddlComboArr)
//{
// // Counter used to track no of DataTable
// int comboCounter = 0;
// foreach (DropDownList ddlDestCombo in ddlComboArr)
// {
// // If table has no data then do nothing
// if (dtSourceArr[comboCounter] == null || dtSourceArr[comboCounter].Rows.Count == 0)
// continue;
// ddlDestCombo.Items.Clear();
// // Fill the DropDownLists with Tables Given
// ddlDestCombo.DataSource = dtSourceArr[comboCounter];
// ddlDestCombo.DataTextField = comboTextField;
// ddlDestCombo.DataValueField = comboValueField;
// ddlDestCombo.DataBind();
// // If AddBlank attribute is specified in the control,then add a Blank item
// if (ddlDestCombo.Attributes[AddBlankCaption] != null)
// {
// ddlDestCombo.Items.Insert(0, new ListItem("Select All", ""));
// }
// comboCounter++;
// }
//}
/// <summary>
/// function to update the 'DataValueField' to that of the 'SelectedValue' attribute
/// </summary>
/// <param name="ddls">array of dropdownlist</param>
public static void UpdateNewValues(DropDownList[] ddls, IOrderedDictionary newVals)
{
foreach (DropDownList ddl in ddls)
newVals[ddl.DataTextField] = ddl.SelectedValue;
}
public static string SQLFix(string str)
{
return str.Replace("'", "''");
}
public static string SQLFixDouble(string str)
{
return str.Replace("''", "");
}
//public static void FillComboFromDataset(DataTable dtSource, DropDownList ddlCombo)
//{
// // If table has no data then do nothing
// if (dtSource == null || dtSource.Rows.Count == 0)
// {
// ddlCombo.Items.Clear();
// return;
// }
// // Fill the DropDownList with Table Given
// ddlCombo.Items.Clear();
// ddlCombo.DataSource = dtSource;
// ddlCombo.DataTextField = comboTextField;
// ddlCombo.DataValueField = comboValueField;
// ddlCombo.DataBind();
// //if ((ddlCombo.Attributes[AddBlankCaption] != null))
// //{
// // ddlCombo.Items.Insert(0, new ListItem("Select All", ""));
// //}
//}
// Fill destination combos from source combos
/// <summary>
/// Fill destination combos from source combos
/// </summary>
/// <param name="ddlSource">Array of source combos</param>
/// <param name="ddlDestination">Array of destination combos</param>
/// <param name="addBlankArr">Array of flags whether to add blank item</param>
/// <param name="selectItem">Flag specifying whether to select the item in combo from its DataValueField(Used to select item in combos of grid in edit mode)</param>
public static void FillDestCombosFromSrcCombos(DropDownList[] ddlSourceArr,
DropDownList[] ddlDestinationArr,
bool selectItemFromDataValueField
)
{
#region Note:
// Note: This function is used to fill destiantion combos from source combos
// -> It is used on page to fill combos of e.g. search from combos of Add
// -> It is used to fill combos of Grid while grid is in edit-mode.
// It will be called from grid's RowBound event.
// Here it will select the combo-item whose value match with the
// DataValueField passed in combo
#endregion
// Counter used to track no of source DropDownList
int comboCounter = 0;
foreach (DropDownList ddlDestination in ddlDestinationArr)
{
bool srcHasBlankItem = (ddlSourceArr[comboCounter].Attributes[AddBlankCaption] != null);
bool destiHasBlankItem = (ddlDestination.Attributes[AddBlankCaption] != null);
// If source combo has no data,then do nothing
if (ddlSourceArr[comboCounter].Items.Count > 0)
{
// Clear the destination combo
ddlDestination.Items.Clear();
// Copy the data from source combo to destination combo
foreach (ListItem li in ddlSourceArr[comboCounter].Items)
{
if (!string.IsNullOrEmpty(li.Text) || destiHasBlankItem)
ddlDestination.Items.Add(new ListItem(li.Text, li.Value));
// If item is to be selected, from the DataValueField then
//select item from list whose value match with DataValueField
if (selectItemFromDataValueField)
{
// If this item's value is same as DataValueField,then select this item
if (li.Value == ddlDestination.DataValueField &&
ddlDestinationArr[comboCounter].DataValueField != "")
ddlDestination.SelectedValue = li.Value;
}
}
#region Impt Note
// If "AddBlank" attribute is specified in the destinaion combo and not
// specified in source combo then add a blank item
// If source combo has "AddBlank" means it has already added the blank item.
//So,if it does not comtain "AddBlank: attribute,then add blank item
// Note:-Case:1. Here we check only one case,that source has attr.
// and destination has not attr.
// -Case:2. We don't have the case that source has added blank and
// destination has not blank
// -Case:3/4. If source and destination both have attr. and both
// don't have attr. then we don't need to do anything
#endregion
if ((ddlDestination.Attributes[AddBlankCaption] != null)
&& (ddlSourceArr[comboCounter].Attributes[AddBlankCaption] == null))
ddlDestination.Items.Insert(0, new ListItem("", ""));
}
comboCounter++;
}
}
// Fill the Combos From Enum
/// <summary>
/// Method to Fill the Combos from Enum
/// </summary>
/// <param name="ddlArray">Array Of Combos to be Filled</param>
/// <param name="enumType">Array Of Enum Types</param>
/// <param name="addBlankArr">Array Of Boolen (true values add the blank)</param>
public static void FillCombosFromEnums(DropDownList[] ddlArray, Type[] enumType)
{
for (int comboCounter = 0; comboCounter < ddlArray.Length; comboCounter++)
{
// clear the all item before adding
ddlArray[comboCounter].Items.Clear();
// Fill the each item in Enum to Combo
if (ddlArray[comboCounter].Attributes[ReplaceUnderScoreFromEnumCaption] != null)
{
foreach (string str in Enum.GetNames(enumType[comboCounter]))
{
ddlArray[comboCounter].Items.Add(new ListItem(str.Replace("_", " "), (Convert.ToInt32(Enum.Parse(enumType[comboCounter], str))).ToString()));
}
}
else
{
foreach (string str in Enum.GetNames(enumType[comboCounter]))
{
ddlArray[comboCounter].Items.Add(new ListItem(str, (Convert.ToInt32(Enum.Parse(enumType[comboCounter], str))).ToString()));
}
}
// If "AddBlank" attribute is present, then add a Blank item"
if (ddlArray[comboCounter].Attributes[AddBlankCaption] != null)
ddlArray[comboCounter].Items.Insert(0, new ListItem("", ""));
}
}
public static DateTime setYearFrom(string YearFrom)
{
//char[] arr = { };
string[] fromYear = YearFrom.Split();
return (YearFrom.ToUpper() == "SELECT ALL" ? Convert.ToDateTime("04/01/1999")
: Convert.ToDateTime("04/01/" + fromYear[1].ToString()));
}
public static DateTime setYearTo(string YearTo)
{
string[] fromYear = YearTo.Split();
return (YearTo.ToUpper() == "SELECT ALL" ? DateTime.Now
: Convert.ToDateTime("03/31/" + fromYear[4].ToString()));
}
public static void FillListBoxFromEnums(ListBox[] ddlArray, Type[] enumType)
{
for (int ListCounter = 0; ListCounter < ddlArray.Length; ListCounter++)
{
// clear the all item before adding
ddlArray[ListCounter].Items.Clear();
// Fill the each item in Enum to Combo
if (ddlArray[ListCounter].Attributes[ReplaceUnderScoreFromEnumCaption] != null)
{
foreach (string str in Enum.GetNames(enumType[ListCounter]))
{
ddlArray[ListCounter].Items.Add(new ListItem(str.Replace("_", " "), (Convert.ToInt32(Enum.Parse(enumType[ListCounter], str))).ToString()));
}
}
else
{
foreach (string str in Enum.GetNames(enumType[ListCounter]))
{
ddlArray[ListCounter].Items.Add(new ListItem(str, (Convert.ToInt32(Enum.Parse(enumType[ListCounter], str))).ToString()));
}
}
}
}
// Map look-up values to their values in DataTable
/// <summary>
/// Function to map look-up values to their values in DataTable
/// </summary>
/// <param name="dtSource">Data Source</param>
/// <param name="ddlarrLookedSource">DropDownList array to be used as lookup</param>
/// <param name="strarrLookupFields">string array of fields to lookup</param>
public static void GetLookupValues(DataTable dtSource, DropDownList[] ddlarrLookedSource, string[] strarrLookupFields)
{
foreach (DataRow drItem in dtSource.Rows)
{
int intIndex = -1;
foreach (DropDownList ddlSource in ddlarrLookedSource)
{
intIndex++;
if (dtSource.Columns.IndexOf(strarrLookupFields[intIndex]) < 0)
continue;
object objVal = drItem[strarrLookupFields[intIndex]];
if (objVal == null || objVal.ToString().Length == 0)
continue;
if (objVal.ToString().CompareTo(NoAccess.Replace("'", "")) != 0)
{
ListItem li = ddlSource.Items.FindByValue(objVal.ToString());
if (li != null)
drItem[strarrLookupFields[intIndex]] = li.Text;
}
}
}
}
// Get regular expression for minimum length(Used for min length in User-ID and Password)
/// <summary>
/// Get regular expression for minimum length(Used for min length in User-ID and Password)
/// </summary>
/// <param name="len">length to be set in regular expression</param>
//public static string getMinLengthRegx(int len)
//{
// // Return regular expression "\w{6,}"
// return @"\w{" + len + ",}";
//}
/// <summary>
/// populate combobox using the data source
/// NOTE: datatable must have two columns 'TEXT' and 'ID'
/// </summary>
/// <param name="source">source DataTable</param>
/// <param name="combo">combobox to be populated</param>
public static void FillComboFromDataset(DataTable dtSource, DropDownList ddlCombo)
{
ddlCombo.Items.Clear();
// If table has no data then do nothing
if (dtSource == null || dtSource.Rows.Count == 0)
{
return;
}
// Fill the DropDownList with Table Given
ddlCombo.DataSource = dtSource;
ddlCombo.DataTextField = comboTextField;
ddlCombo.DataValueField = comboValueField;
ddlCombo.DataBind();
if ((ddlCombo.Attributes[AddBlankCaption] != null))
{
ddlCombo.Items.Insert(0, new ListItem("Select", ""));
}
}
public static void FillComboFromDatasetNew(DataTable dtSource, DropDownList ddlCombo, string textField, string ValueField)
{
ddlCombo.Items.Clear();
// If table has no data then do nothing
if (dtSource == null || dtSource.Rows.Count == 0)
{
return;
}
// Fill the DropDownList with Table Given
ddlCombo.DataSource = dtSource;
ddlCombo.DataTextField = textField;
ddlCombo.DataValueField = ValueField;
ddlCombo.DataBind();
if ((ddlCombo.Attributes[AddBlankCaption] != null))
{
ddlCombo.Items.Insert(0, new ListItem("-- Select --", "0"));
}
}
//public static void DownloadFile()
//{
// string fname = Config.DownloadFile;
// string path = Config.DownloadFilePath + Config.directorySeparator + fname;
// string name = Path.GetFileName(path);
// string ext = Path.GetExtension(path);
// string type = "";
// // set known types based on file extension
// if (ext != null)
// {
// switch (ext.ToLower())
// {
// case ".htm":
// case ".html":
// type = "text/HTML";
// break;
// case ".txt":
// type = "text/plain";
// break;
// case ".xls":
// type = "application/excel";
// break;
// case ".pdf":
// type = "application/pdf";
// break;
// case ".doc":
// case ".rtf":
// type = "Application/msword";
// break;
// case ".zip":
// type = "application/x-zip";
// break;
// }
// }
// HttpContext.Current.Response.AppendHeader("content-disposition",
// "attachment; filename=" + name);
// if (type != "")
// HttpContext.Current.Response.ContentType = type;
// HttpContext.Current.Response.WriteFile(path);
// HttpContext.Current.Response.End();
//}
public static DateTime setDateFrom(string txtdateFrom)
{
DateTime dateFrom = DateTime.Parse("01/01/1753");
if (!String.IsNullOrEmpty(txtdateFrom))
{
dateFrom = Convert.ToDateTime(txtdateFrom);
}
return dateFrom;
}
public static DateTime setDateTo(string txtdateTo)
{
DateTime dateTo = DateTime.Now;
if (!String.IsNullOrEmpty(txtdateTo))
{
dateTo = Convert.ToDateTime(txtdateTo);
}
return dateTo;
}
public static string GetListBoxValue(ListBox list)
{
if (list != null)
{
string value = string.Empty;
foreach (ListItem li in list.Items)
{
if (li.Selected)
{
value += li.Value.Trim() + ",";
}
}
if (value.Length != 0)
{
value = value.Remove(value.Length - 1, 1);
}
return value;
}
else
return "";
}
// With comma
public static string GetListBoxValueWC(ListBox list)
{
string value = "";
foreach (ListItem li in list.Items)
{
if (li.Selected)
{
value += li.Value.Trim() + ",";
}
}
return value;
}
public static void InsertErorLog(int ModuleId, Int64 ModulePrimaryKey, string ReportName, string Error)
{
if (ConfigurationManager.AppSettings.Get("ErrorVal") != "1")
{
string cn = ConfigurationManager.ConnectionStrings["ConnectionStringIns"].ConnectionString;
SqlConnection con = new SqlConnection(cn);
con.Open();
string strQuery = "Execute PW_ErorLogInsert 'PW'," + ModuleId + "," + ModulePrimaryKey + ",'" + ReportName + "','" + CommonHelper.FmtSQLString(Error) + "'";
SqlCommand cmderrorlog = new SqlCommand(strQuery, con);
cmderrorlog.ExecuteNonQuery();
con.Close();
}
}
//public static string GetListBoxValueWithFormatString(ListBox list)
//{
// string value = string.Empty;
// foreach (ListItem li in list.Items)
// {
// if (li.Selected)
// {
// value += li.Value.Trim() + ",";
// }
// }
// if (value != "")
// return string.Concat("'" + value.Substring(0, (value.Length - 1)) + "'").Replace(",", "','");
// else
// return string.Empty;
//}
public static string GetCheckListValueWithoutComma(CheckBoxList list)
{
int itemCount = list.Items.Count;
string str = string.Empty;
for (int i = 0; i < (itemCount); i++)
{
if (list.Items[i].Selected)
{
str += list.Items[i].Value.Trim() + ",";
}
}
if (str.Length != 0)
{
str = str.Remove(str.Length - 1, 1);
}
return str;
}
public static string GetCheckListBoxValue(CheckBoxList list)
{
int itemCount = list.Items.Count;
string str = string.Empty;
for (int i = 0; i < (itemCount); i++)
{
if (list.Items[i].Selected)
{
str += list.Items[i].Value.Trim() + ",";
}
}
return str;
}
public static string FmtSQLString(string textData)
{
return textData.Trim().Replace("'", "''");
}
public static string FmtSQLNumber(string textData)
{
return textData.Trim().Replace("'", "");
}
public static string CheckListBoxValue(ListBox list)
{
if (list.GetSelectedIndices().Length != 0)
{
if (list.Items.Count == list.GetSelectedIndices().Length)
return "";
else
return CommonHelper.GetListBoxValue(list);
}
else
return "";
}
public static bool IsLongNumber(string value)
{
Double numb;
return Double.TryParse(value.Trim(), out numb);
}
public static string SetDate(string date)
{
String[] ch = date.Split(new char[] { '/' });
int mn = int.Parse(ch[0]);
int dt = int.Parse(ch[1]);
int yr = int.Parse(ch[2]);
if (mn < 9)
{
string mn1 = (Convert.ToString(ch[0]));
string newdate = dt + "/" + mn1 + "/" + yr;
return newdate;
}
else
{
string newdate = dt + "/" + mn + "/" + yr;
return newdate;
}
}
//Read XML value from CommonSettings.xml file
public static string GetXmlValuefromSetting(string xmltagName)
{
XmlDocument XD = new XmlDocument();
XD.Load(HttpContext.Current.Server.MapPath("..") + "/App_Data/CommonSettings.xml");
return XD.GetElementsByTagName(xmltagName).Item(0).InnerText;
}
// ------------------------- Form Automation ---------------------
public static void FillComboFromDatasetBD(DataTable dtSource, DropDownList ddlCombo, string FirstItemText, string FirstItemValue)
{
ddlCombo.Items.Clear();
// If table has no data then do nothing
if (dtSource == null || dtSource.Rows.Count == 0)
{
if ((ddlCombo.Attributes[AddBlankCaption] != null))
{
ddlCombo.Items.Insert(0, new ListItem(FirstItemText, FirstItemValue));
}
return;
}
// Fill the DropDownList with Table Given
ddlCombo.DataSource = dtSource;
ddlCombo.DataTextField = comboTextField;
ddlCombo.DataValueField = comboValueField;
ddlCombo.DataBind();
if ((ddlCombo.Attributes[AddBlankCaption] != null))
{
ddlCombo.Items.Insert(0, new ListItem(FirstItemText, FirstItemValue));
}
}
//Start For Export To PDf/////
//public static void SetColumnNumeric(int RepVal, object MissVal, Microsoft.Office.Interop.Excel.Worksheet WS, string[] ArStr)
//{
// for (int ir = 1; ir <= WS.UsedRange.Columns.Count; ir++)
// {
// if (WS.get_Range(N2S(ir) + RepVal, MissVal).Value2 != null && ((System.Collections.IList)ArStr).Contains(WS.get_Range(N2S(ir) + RepVal, MissVal).Value2.ToString().ToUpper().Trim()))
// {
// WS.Cells.get_Range(N2S(ir) + "1", N2S(ir) + WS.Rows.Count).NumberFormat = "#";
// WS.Cells.get_Range(N2S(ir) + "1", N2S(ir) + WS.Rows.Count).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
// }
// }
//}
public static void ChkFile(string EXLPath, string PDFPath, string Epath)
{
if (!System.IO.Directory.Exists(Epath))
System.IO.Directory.CreateDirectory(Epath);
if (File.Exists(EXLPath))
File.Delete(EXLPath);
if (File.Exists(PDFPath))
File.Delete(PDFPath);
}
//public static String N2S(int number)
//{
// int number1 = number / 27;
// int number2 = number - (number1 * 26);
// if (number2 > 26)
// {
// number1 = number1 + 1;
// number2 = number - (number1 * 26);
// }
// Char a = (Char)(65 + (number1 - 1));
// Char b = (Char)(65 + (number2 - 1));
// Char c = (Char)(65 + (number - 1));
// string d = String.Concat(a, b);
// if (number <= 26)
// return c.ToString();
// else
// return d;
//}
//End For Export To PDf/////
//For Get IP Address/////
public static string GetForwadedIP(System.Web.UI.Page page)
{
return page.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
}
public static string GetIPAddress(System.Web.UI.Page page)
{
string IP = string.Empty;
IP = HttpContext.Current.Request.UserHostAddress;
if (string.IsNullOrEmpty(IP))
IP = page.Request.ServerVariables["REMOTE_ADDR"];
return IP;
}
public static string GetMacAddress()
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
String sMacAddress = string.Empty;
foreach (NetworkInterface adapter in nics)
{
if (sMacAddress == String.Empty)// only return MAC Address from first card
{
IPInterfaceProperties properties = adapter.GetIPProperties();
sMacAddress = adapter.GetPhysicalAddress().ToString();
}
}
return sMacAddress;
}
public static string GetListBoxValueWithComma(ListBox list)
{
string value = "";
foreach (ListItem li in list.Items)
{
if (li.Selected)
{
value += li.Value.Trim() + ",";
}
}
return value;
}
public static string CheckListBoxValueWithoutcomma(ListBox list)
{
if (list.GetSelectedIndices().Length != 0)
{
if (list.Items.Count == list.GetSelectedIndices().Length)
return "";
else
return CommonHelper.GetListBoxValueWithoutComma(list);
}
else
return "";
}
public static string GetListBoxValueWithoutComma(ListBox list)
{
string value = string.Empty;
foreach (ListItem li in list.Items)
{
if (li.Selected)
{
value += li.Value + ",";
}
}
if (value.Length != 0)
{
value = value.Remove(value.Length - 1, 1);
}
return value;
}
public static string GetRadioButtonListValue(RadioButtonList Chk)
{
string Str = "";
foreach (ListItem li in Chk.Items)
{
if (li.Selected)
Str = Str + li.Value + ",";
}
return Str.Substring(0, Str.LastIndexOf(",")); ;
}
// Save Html To Excel - 97-2003
// StrHTML = Only Html Text like htmlWrite.InnerWriter.ToString();
// saveAsPath = File Name like "TransactionReport"
//public static void saveAsExcelMail(string StrHTML, string FileName)
//{
// Random ran = new Random();
// int RanNo = ran.Next(100, 10000);
// string FilePath = Config.PcUpload + @"ExpToPdf\" + RanNo + ".xls";
// string saveAsPath = Config.PcUpload + @"ExpToPdf\" + FileName + ".xls";
// FileIO.DeleteFile(saveAsPath);
// File.WriteAllText(FilePath, StrHTML);
// Microsoft.Office.Interop.Excel.ApplicationClass ExlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
// Microsoft.Office.Interop.Excel.Workbook WB = null;
// object MissVal = System.Reflection.Missing.Value;
// try
// {
// ExlApp.DisplayAlerts = false;
// WB = ExlApp.Workbooks.Open(FilePath, MissVal, MissVal, MissVal, MissVal, MissVal, MissVal, MissVal, MissVal, MissVal, MissVal, MissVal, MissVal, MissVal, MissVal);
// WB.Activate();
// WB.SaveAs(saveAsPath, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel8, MissVal, MissVal, MissVal, MissVal, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, MissVal, MissVal, MissVal, MissVal, MissVal);
// }
// catch (Exception)
// {
// FileIO.DeleteFile(FilePath);
// }
// finally
// {
// if (WB != null)
// {
// WB.Close(false, MissVal, MissVal);
// WB = null;
// }
// if (ExlApp != null)
// {
// ExlApp.DisplayAlerts = true;
// ExlApp.Quit();
// ExlApp = null;
// }
// GC.Collect();
// GC.WaitForPendingFinalizers();
// GC.Collect();
// GC.WaitForPendingFinalizers();
// FileIO.DeleteFile(FilePath);
// }
//}
public static string GetExcelPath(string filename)
{
return System.Web.HttpContext.Current.Server.MapPath("~") + "/PC_Upload/ExpToPdf/" + filename + ".xls";
}
public static bool SendSMS(string MobileNo, string Msg, int oSMSFlag)
{
try
{
ConnectionDB connectionDB = new ConnectionDB();
string newMSG = Msg.Replace("&", "%26").Replace("'", "%27%27");
string smsurl = "http://mobi1.blogdns.com/MSGID/SMSSenders.aspx?UserID=prudentcasahm&UserPass=pr123&Message=" + newMSG + "&MobileNo=" + MobileNo + "&GSMID=Prudnt";
string sHtml = "";
HttpWebRequest request;
HttpWebResponse response = null;
Stream stream = null;
request = (HttpWebRequest)WebRequest.Create(smsurl);
request.Timeout = System.Threading.Timeout.Infinite;
request.AllowAutoRedirect = false;
response = (HttpWebResponse)request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream, System.Text.Encoding.Default);
sHtml = sr.ReadToEnd();
SqlParameter[] spSMS = new SqlParameter[4];
spSMS[0] = new SqlParameter("@MobileNo", MobileNo);
spSMS[1] = new SqlParameter("@SMSResponse", sHtml.Remove(sHtml.Length - 1, 1).Replace("100=", ""));
spSMS[2] = new SqlParameter("@SMSText", Msg);
spSMS[3] = new SqlParameter("@SMSFlag", oSMSFlag);
connectionDB.Execute_NonQuery("WP_SMSLogInsert", spSMS);
return true;
}
catch (Exception)
{
throw;
}
}
public static string GetZipFileName(string filepath, string panno)
{
string[] ZipfilePath = Directory.GetFiles(filepath, "*" + panno + "*", SearchOption.TopDirectoryOnly);
if (ZipfilePath.Length > 0)
{
return ZipfilePath[0].ToString();
}
else
{
return string.Empty;
}
}
public static string SerielizseDataset(DataSet ds)
{
System.Web.Script.Serialization.JavaScriptSerializer Serielizse = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> Rows = new List<Dictionary<string, object>>();
Dictionary<string, object> Row;
string str1 = "{";
for (int i = 0; i < ds.Tables.Count; i++)
{
Rows.Clear();
foreach (DataRow dr in ds.Tables[i].Rows)
{
Row = new Dictionary<string, object>();
foreach (DataColumn col in ds.Tables[i].Columns)
{
Row.Add(col.ColumnName, dr[col]);
}
Rows.Add(Row);
}
str1 = str1 + @"""T" + i + @""":" + Serielizse.Serialize(Rows) + ",";
}
return str1.Remove(str1.LastIndexOf(","), 1) + "}";
}
public static string[] GetDescritpString(string URL)
{
string QStr = URL;
string DS = QStr.Substring(QStr.IndexOf("?") + 1);
string str = CommonHelper.DecryptURL(DS);
string[] SplitChar = { "&" };
return str.Substring(str.IndexOf("?") + 1).Split(SplitChar, StringSplitOptions.None);
}
public static string EncryptURL(string inputValue)
{
//byte[] keyArray;
//byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(Text);
//string key = "";
//MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
//keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
//hashmd5.Clear();
//TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
//tdes.Key = keyArray;
//tdes.Mode = CipherMode.ECB;
//tdes.Padding = PaddingMode.PKCS7;
//ICryptoTransform cTransform = tdes.CreateEncryptor();
//byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
//tdes.Clear();
//return Convert.ToBase64String(resultArray, 0, resultArray.Length);
string input = inputValue.Replace("0", "!q=").Replace("1", "|w#").Replace("2", "/a*").Replace("3", "?c&").Replace("4", "#d%").Replace("5", "$l<").Replace("6", "&k|").Replace("7", "*t%").Replace("8", "-g!").Replace("9", "^m:");
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
Byte[] stringBytes = encoding.GetBytes(input);
StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
foreach (byte b in stringBytes)
{
sbBytes.AppendFormat("{0:X2}", b);
}
return sbBytes.ToString();
}
public static string DecryptURL(string hexInput)
{
//byte[] keyArray;
//byte[] toEncryptArray = Convert.FromBase64String(cipherText);
//string key = "";
//MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
//keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
//hashmd5.Clear();
//TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
//tdes.Key = keyArray;
//tdes.Mode = CipherMode.ECB;
//tdes.Padding = PaddingMode.PKCS7;
//ICryptoTransform cTransform = tdes.CreateDecryptor();
//byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
//tdes.Clear();
//return UTF8Encoding.UTF8.GetString(resultArray);
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
int numberChars = hexInput.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(hexInput.Substring(i, 2), 16);
}
string input = encoding.GetString(bytes);
string outPut = input.Replace("!q=", "0").Replace("|w#", "1").Replace("/a*", "2").Replace("?c&", "3").Replace("#d%", "4").Replace("$l<", "5").Replace("&k|", "6").Replace("*t%", "7").Replace("-g!", "8").Replace("^m:", "9");
return outPut;
}
public static string SerielizseDatatbale(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer Serielizse = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> Rows = new List<Dictionary<string, object>>();
Dictionary<string, object> Row;
foreach (DataRow dr in dt.Rows)
{
Row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
Row.Add(col.ColumnName, dr[col]);
Rows.Add(Row);
}
return Serielizse.Serialize(Rows);
}
//To get enum property description
public static string GetEnumDescription(Enum enumValue)
{
string enumValueAsString = enumValue.ToString();
var type = enumValue.GetType();
FieldInfo fieldInfo = type.GetField(enumValueAsString);
object[] attributes = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
var attribute = (DescriptionAttribute)attributes[0];
return attribute.Description;
}
return enumValueAsString;
}
//public static string AmountToINRFormat(string val)
//{
// // set currency format
// string curCulture = Thread.CurrentThread.CurrentCulture.ToString();
// System.Globalization.NumberFormatInfo currencyFormat = new
// System.Globalization.CultureInfo(curCulture).NumberFormat;
// currencyFormat.CurrencyNegativePattern = 1;
// string s = Convert.ToDouble(val).ToString("c", currencyFormat);
// s = s.Substring(1, s.Length - 1);
// return s;
//}
public static string AmountToINRFormat(string val)
{
if (!string.IsNullOrWhiteSpace(val))
{
var prm = String.Format(new CultureInfo("en-IN", false), "{0:n}", Convert.ToDouble(val));
prm = prm.Substring(0, prm.Length - 3);
return prm;
}
return "";
}
public static void setUserId(string ID, string Module)
{
ConnectionDB connectionDB = new ConnectionDB();
SqlParameter[] pa = new SqlParameter[2];
pa[0] = new SqlParameter("@ID", ID);
pa[1] = new SqlParameter("@Modual", Module);
string sp = "GNA_GetUserId";
object res = connectionDB.Execute_Scaler(sp, pa);
if (!string.IsNullOrEmpty(Convert.ToString(res)))
_Session.UserId = Convert.ToString(res);
}
public static DataTable checkBMI(string CompId, string HeightFeet, string HeightInch, string Weight)
{
ConnectionDB con = new ConnectionDB();
DataTable dt = new DataTable();
try
{
SqlParameter[] pa = new SqlParameter[3];
pa[0] = new SqlParameter("@CompId", Convert.ToInt32(CompId));
pa[1] = new SqlParameter("@Height", Convert.ToDecimal(Convert.ToString(HeightFeet + "." + HeightInch)));
pa[2] = new SqlParameter("@Weight", Convert.ToInt32(Weight));
string sp = "PW_Check_BMI";
dt = con.GetDataTable(sp, pa);
}
catch (Exception ex)
{
CommonHelper.InsertErorLog(0, 0, "CommonHelper : checkBMI()", ex.ToString());
}
return dt;
}
}