Tuesday, July 29, 2008

simple utility class which we need in each and every web sites

simple utility class which we need in each and every web sites
==========================================================

#region Namespaces
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Configuration;
#endregion

namespace DAL
{
public class UtilityFunctions
{
#region Variable Declaration
public static string Prefix = ConfigurationManager.AppSettings["Prefix"];
public static string Livepath = ConfigurationManager.AppSettings["Livepath"];
public static string AllCureTitleKey = ConfigurationManager.AppSettings["AllCureTitleKey"];
public static string AccessMessage = ConfigurationManager.AppSettings["AccessMessage"];
public static int TopBrandCount = int.Parse(ConfigurationManager.AppSettings["TopBrandCount"].ToString());
public static int TopSellingCount = int.Parse(ConfigurationManager.AppSettings["TopSellingCount"].ToString());
public static int HotProductCount = int.Parse(ConfigurationManager.AppSettings["HotProductCount"].ToString());
public static string FromName, FromEmail, BccEmail, CommentEmail;
public static int FrontPaging, AdminPaging;
#endregion

#region SetSEO
///
/// Method Name:-SetSEO
/// Database Table:-NULL
/// Stored Procedure:-NULL
/// Purpose:- To set the seo title and metatags on the page.
/// Created By:-Snehal
/// Created Date(dd/mm/yyyy):-25/02/2008
///

public static void SetSEO(string pagetitle, string pagemetakeywords, string metadesc, Page pg)
{
//Set page title
HtmlHead header = (HtmlHead)pg.Header;
pg.Title = pagetitle;

//Change meta description
HtmlMeta metadescription = new HtmlMeta();


/**/
metadescription = new HtmlMeta();
metadescription.Attributes.Add("Name", "rating");
metadescription.Attributes.Add("Content", "general");
header.Controls.Add(metadescription);

/**/
metadescription.HttpEquiv = "content-language";
metadescription.Content = "en-GB";
header.Controls.Add(metadescription);

/**/
metadescription = new HtmlMeta();
metadescription.Attributes.Add("Name", "robots");
metadescription.Attributes.Add("Content", "ALL, INDEX, FOLLOW");
header.Controls.Add(metadescription);

/**/
metadescription = new HtmlMeta();
metadescription.Attributes.Add("Name", "GOOGLEBOT");
metadescription.Attributes.Add("Content", "index, follow");
header.Controls.Add(metadescription);

/**/
metadescription = new HtmlMeta();
metadescription.Attributes.Add("Name", "MSNBOT");
metadescription.Attributes.Add("Content", "index, follow");
header.Controls.Add(metadescription);

/* metadescription.Attributes.Add("Content", "http://www.my-flat.co.uk");
header.Controls.Add(metadescription);

/**/
metadescription = new HtmlMeta();
metadescription.Attributes.Add("Name", "copyright");
metadescription.Attributes.Add("Content", "Copyright 2007-2008 My Flat., All Rights Reserved");
header.Controls.Add(metadescription);

/**/
metadescription = new HtmlMeta();
metadescription.HttpEquiv = "Content-Type";
metadescription.Content = "text/html; charset=iso-8859-1";
header.Controls.Add(metadescription);

/**/
metadescription = new HtmlMeta();
metadescription.HttpEquiv = "CACHE-CONTROL";
metadescription.Content = "NO-CACHE";
header.Controls.Add(metadescription);

/**/
metadescription = new HtmlMeta();
metadescription.HttpEquiv = "PRAGMA";
metadescription.Content = "NO-CACHE";
header.Controls.Add(metadescription);

if (HttpContext.Current.Request.Url != null)
{
if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("default"))
{
/**/
metadescription = new HtmlMeta();
metadescription.HttpEquiv = "verify-v1";
metadescription.Content = "hqkC6uwtjtCkxqg2+L2XEnXrs1ZCatvp5V/d9vfHfgg=";
header.Controls.Add(metadescription);

/**/
metadescription = new HtmlMeta();
metadescription.HttpEquiv = "msvalidate.01";
metadescription.Content = "B19EA352CAF84C0B88B7AF481554C07A";
header.Controls.Add(metadescription);

/**/
metadescription = new HtmlMeta();
metadescription.HttpEquiv = "y_key";
metadescription.Content = "2db3d7c920246b62";
header.Controls.Add(metadescription);
}
}
header.Controls.Add(HtmlHeaderFunctions.getMetaDescription(metadesc));

//Change meta keywords
header.Controls.Add(HtmlHeaderFunctions.getMetaKeywords(pagemetakeywords));

}
#endregion

#region SetHeaderforDynamicPages
///
/// Method Name:-SetHeaderforDynamicPages
/// Database Table:-NULL
/// Stored Procedure:-NULL
/// Purpose:- To register the css, js files on the dynamic pages[search,detail,booking] AND for SEO [title,metakeyword,metadescription] call the above SetSEO function
/// Created By:-Snehal
/// Created Date(dd/mm/yyyy):-26/02/2008
///

public static void SetHeaderforDynamicPages(string pagetitle, string pagemetakeywords, string metadesc, Page pg, string[] csspaths, string[] jspaths, string[] jsnames)
{
HtmlHead header = (HtmlHead)pg.Header;

if (csspaths != null)
{
if (csspaths.Length > 0)
{
for (int i = 0; i < csspaths.Length; i++)
{
header.Controls.Add(HtmlHeaderFunctions.getStylesheet(Livepath + csspaths[i].ToString()));
}
}
}

if (jspaths != null && jsnames != null)
{
if (jspaths.Length > 0 && jsnames.Length > 0)
{
for (int j = 0; j < jspaths.Length; j++)
{
pg.ClientScript.RegisterClientScriptInclude(jsnames[j].ToString(), Livepath + jspaths[j].ToString());
}
}
}

SetSEO(pagetitle, pagemetakeywords, metadesc, pg);

}
#endregion

#region Getrewrittenurl
///
/// Method Name:-Getrewrittenurl
/// Database Table:-NULL
/// Stored Procedure:-NULL
/// Purpose:- To set the rewritten url on the page.
/// Created By:-KUSHAN
/// Created Date(dd/mm/yyyy):-25/02/2008
///

public static string Getrewrittenurl(string PropertyType, string Pagename)
{
return Livepath + ReplacePrefix(Prefix) + Replacespace(PropertyType).ToString().ToLower() + "/" + Replacespace(Pagename).ToString().ToLower();
}
#endregion

#region Replace space
///
/// Method Name:-Replace space
/// Database Table:-NULL
/// Stored Procedure:-NULL
/// Purpose:- To set the replage space with "_".
/// Created By:-KUSHAN
/// Created Date(dd/mm/yyyy):-25/02/2008
///

public static string Replacespace(string Name)
{
Name = Name.Replace(" ", "_");
return Name;
}
#endregion

#region Replace space add
///
/// Method Name:-Replace space
/// Database Table:-NULL
/// Stored Procedure:-NULL
/// Purpose:- To set the replage space with "_".
/// Created By:-KUSHAN
/// Created Date(dd/mm/yyyy):-25/02/2008
///

public static string Replacespace_add(string Name)
{
Name = Name.Replace("_", " ");
return Name;
}
#endregion

#region GetSeoCriteria
///
/// Method Name:-GetSeoCriteria
/// Database Table:-SEO
/// Stored Procedure:-NULL
/// Purpose:- To get the title,metakeyword,metadescription for a particular page.
/// Created By:-Snehal
/// Created Date(dd/mm/yyyy):-25/02/2008
///

public static DataRow GetSeoCriteria(int pageid)
{
DataTable dt = new DataTable();
DAL.SqlHelper.FillDataTable(
CommandType.Text,
"select title,metakeyword,metadesc from seo where page_id=" + pageid,
dt
);
if (dt != null)
{
if (dt.Rows.Count > 0)
{
return dt.Rows[0];
}
else
{
return null;
}
}
else
{
return null;
}
}
#endregion

#region GetTextonly
//Get only text from html
public static string GetTextonly(string details)
{
string strtext = "";
strtext = Regex.Replace(details, @"<(.|\n)*?>", string.Empty);
return strtext;
}
#endregion

#region ReplacePrefix
///
/// Method Name:-ReplacePrefix
/// Database Table:-NULL
/// Stored Procedure:-NULL
/// Purpose:- To replace the prefix space with "-".
/// Created By:-Snehal
/// Created Date(dd/mm/yyyy):-12/03/2008
///

public static string ReplacePrefix(string Name)
{
Name = Name.Replace(" ", "-");
return Name.ToLower();
}
#endregion

#region MakeFirstUpper
///
/// Method Name:-MakeFirstUpper
/// Database Table:-NULL
/// Stored Procedure:-NULL
/// Purpose:- To replace the prefix space with "-".
/// Created By:-Snehal
/// Created Date(dd/mm/yyyy):-12/03/2008
///

public static string MakeFirstUpper(string word)
{
if (word.Length <= 1)
{
return word.ToUpper();
}
else
{
Char[] letters = word.ToCharArray();
letters[0] = Char.ToUpper(letters[0]);
return new string(letters);
}
}
#endregion

#region Set Site Config Data
///
/// To Set site config data in static variable
///

///
/// Created By : Nirav
/// Created Date(dd-mm-yyyy) : 6-5-2008
///

public static void SetSiteConfigData()
{
DataRow dr_SiteConfig = DAL.SiteConfig.GetSiteConfig();
if (dr_SiteConfig != null)
{
FromEmail = dr_SiteConfig["FromEmail"].ToString();
FromName = dr_SiteConfig["FromName"].ToString();
BccEmail = dr_SiteConfig["BccEmail"].ToString();
AdminPaging = int.Parse(dr_SiteConfig["AdminPaging"].ToString());
FrontPaging = int.Parse(dr_SiteConfig["FrontPaging"].ToString());
CommentEmail = dr_SiteConfig["CommentEmail"].ToString();
}
}
#endregion

#region GetAdminPaging
public static int GetAdminPaging()
{
if (AdminPaging != 0)
return AdminPaging;
else
{
SetSiteConfigData();
return AdminPaging;
}
}
#endregion

#region GetFrontPaging
public static int GetFrontPaging()
{
if (FrontPaging != 0)
return FrontPaging;
else
{
SetSiteConfigData();
return FrontPaging;
}
}
#endregion

#region GetFromEmail
public static string GetFromEmail()
{
if (!String.IsNullOrEmpty(FromEmail))
return FromEmail;
else
{
SetSiteConfigData();
return FromEmail;
}
}
#endregion

#region Check Admin User Access
///
/// Method Name:-Admin User Access
/// Database Table:-
/// Stored Procedure:-CheckDashboardUserRights
/// Purpose:- To Load Page By Access
/// Created By:-Kushan
/// Created Date(dd/mm/yyyy):-09/05/2008
/// ModuleType 1 for Add,2 For Edit,3 For Delete,4 For View
///

public static bool CheckAdminUserRights(int ModuleId, int ModuleType)
{
DataTable dt = AdminUserPageAccess(HttpContext.Current.User.Identity.Name);
bool Acess = false;
if (dt.Rows.Count > 0)
{
DataView dv = new DataView(dt);
dv = GetfilterDataview(dv, "Module_Id = " + ModuleId);
if (dv.Count > 0)
{
if (ModuleType == 1)
{
Acess = Convert.ToBoolean(dv[0]["Role_Add"]);
}
else if (ModuleType == 2)
{
Acess = Convert.ToBoolean(dv[0]["Role_Edit"]);
}
else if (ModuleType == 3)
{
Acess = Convert.ToBoolean(dv[0]["Role_Delete"]);
}
else if (ModuleType == 4)
{
if (Convert.ToBoolean(dv[0]["Role_Add"]) == true || Convert.ToBoolean(dv[0]["Role_Edit"]) == true || Convert.ToBoolean(dv[0]["Role_Delete"]) == true || Convert.ToBoolean(dv[0]["Role_View"]) == true)
{
Acess = true;
}
//else
//{
// Acess = Convert.ToBoolean(dv[0]["Role_View"]);
//}
}
}
dv = null;
}
dt = null;
return Acess;
}
#endregion

#region Get Admin User Page Access
public static DataTable AdminUserPageAccess(string UserEmail)
{
DataTable dt = null;
if (HttpContext.Current.Session["AllcuresPageAccess"] != null)
{
dt = (DataTable)HttpContext.Current.Session["AllcuresPageAccess"];
}
else
{
DataSet ds = new DataSet();
ds = DAL.AdminUser.GetAdminUserAccess(UserEmail);
if (ds.Tables.Count > 0)
{
if (ds.Tables[1].Rows.Count > 0)
{
dt = ds.Tables[1];
HttpContext.Current.Session["AllcuresPageAccess"] = dt;
}
}
}
return dt;
}
#endregion

#region GetfilterDataview
/*FOr Row filter of data view*/
public static DataView GetfilterDataview(DataView dv, string FilterExpression)
{
if (dv != null && dv.Count > 0)
{
dv.RowFilter = FilterExpression;
}
return dv;
}
#endregion

#region SwapList Items
public static void SwapListItems(ListBox SourceList, ListBox DestinationList)
{
DestinationList.SelectedIndex = -1;
ListItemCollection lic = new ListItemCollection();
foreach (ListItem li in SourceList.Items)
{
if (li.Selected == true)
{
lic.Add(li);
}
}
foreach (ListItem li in lic)
{
SourceList.Items.Remove(li);
}

foreach (ListItem li in lic)
{
DestinationList.Items.Add(li);
}
}
#endregion

#region Move Up in Listbox
public static void Move_Up(ListBox lst)
{
for (int i = 0; i < lst.Items.Count; i++)
{
if (lst.Items[i].Selected)//identify the selected item
{
//swap with the top item(move up)
if (i > 0 && !lst.Items[i - 1].Selected)
{
ListItem bottom = lst.Items[i];
lst.Items.Remove(bottom);
lst.Items.Insert(i - 1, bottom);
lst.Items[i - 1].Selected = true;
}
}
}
}
#endregion

#region Move Down in Listbox
public static void Move_Down(ListBox lst)
{
int startindex = lst.Items.Count - 1;
for (int i = startindex; i > -1; i--)
{
if (lst.Items[i].Selected)//identify the selected item
{
//swap with the lower item(move down)
if (i < startindex && !lst.Items[i + 1].Selected)
{
ListItem bottom = lst.Items[i];
lst.Items.Remove(bottom);
lst.Items.Insert(i + 1, bottom);
lst.Items[i + 1].Selected = true;
}
}
}
}
#endregion

#region Register Css Script
public static void RegisterCssAndScript(Page pg, string[] csspaths, string[] jspaths, string[] jsnames)
{
HtmlHead header = (HtmlHead)pg.Header;
if (header != null)
{
if (csspaths != null)
{
if (csspaths.Length > 0)
{
for (int i = 0; i < csspaths.Length; i++)
{
header.Controls.Add(getStylesheet(csspaths[i]));
}
}
}

if (jspaths != null && jsnames != null)
{
if (jspaths.Length > 0 && jsnames.Length > 0)
{
for (int j = 0; j < jspaths.Length; j++)
{
pg.ClientScript.RegisterClientScriptInclude(jsnames[j].ToString(), Livepath + jspaths[j].ToString());
}
}
}
pg.ClientScript.RegisterClientScriptBlock(typeof(string), "JsBlock", " function WebForm_OnSubmit() { if (typeof(ValidatorOnSubmit) == \"function\" && ValidatorOnSubmit() == false) return false; return true; }", true);
}
}
#endregion

#region getStylesheet

public static HtmlLink getStylesheet(string cssPath)
{
HtmlLink mylink = new HtmlLink();

mylink.Href = PageBase.AppPath + cssPath;
mylink.Attributes.Add("rel", "stylesheet");
mylink.Attributes.Add("type", "text/css");

return mylink;
}

#endregion

#region ChangeSearchStyle
public static string ChangeSearchStyle(string Description, string Keyword)
{
if (Keyword == null || Keyword == "")
{
return Description;
}
Regex re = new Regex(Keyword, RegexOptions.IgnoreCase | RegexOptions.Compiled);
MatchCollection mc_Title = re.Matches(Description);
StringBuilder sb_Description = new StringBuilder();
if (mc_Title.Count > 1)
{
int startCount = 0;
for (int i = 0; i < mc_Title.Count; i++)
{
if (i == mc_Title.Count - 1)
{
sb_Description.Append(Description.Substring(startCount));
}
else
{
sb_Description.Append(Description.Substring(startCount, mc_Title[i + 1].Index - startCount));
sb_Description.Append("" + mc_Title[i].ToString() + "");
}
startCount = mc_Title[i].Index + Keyword.Length;
}

}
else if (mc_Title.Count == 1)
{
sb_Description.Append(Regex.Replace(Description, mc_Title[0].ToString(), "" + mc_Title[0].ToString() + ""));
}
else
{
sb_Description.Append(Description);
}
//Description = Regex.Replace(Description, Keyword, "" + Keyword + "", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.ExplicitCapture);
//return Description;
return sb_Description.ToString();
}
#endregion
}
}

==================================

#region Namespaces
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Web;
#endregion

namespace DAL
{
public class ControlBase:System.Web.UI.UserControl
{
#region OnError
///
/// Method Name:-OnError
/// Purpose:- To catch the errors of the .aspx pages and register them in the Errors table
/// Created By:-Snehal
/// Created Date(dd/mm/yyyy):-31/07/2007
///

protected override void OnError(EventArgs e)
{
string strmessage = "";
string strclientip = "";
string strsource = "";

HttpContext ctx = HttpContext.Current;
Exception exception = ctx.Server.GetLastError();

string errorInfo =
"
Offending URL: " + ctx.Request.Url.ToString() +
"
Source: " + exception.Source +
"
Message: " + exception.Message +
"
Stack trace: " + exception.StackTrace;
strmessage = errorInfo;

strclientip = Request.UserHostAddress.ToString();
strsource = ctx.Request.Url.ToString();

//To add the error to the database
int retValue = DAL.Error.AddErrors(strmessage, strclientip, strsource);

//For redirection to the errorpage
string strpath = Server.MapPath("~").ToString() + "/ErrorPage.aspx";
Response.Redirect(strpath);
}
#endregion

#region ReadXmlFile
///
/// Method Name:-ReadXmlFile
/// Purpose:- To read the xml file from a given path and return it in the form of dataset.
/// Created By:-Snehal
/// Created Date(dd/mm/yyyy):-31/07/2007
///

public DataSet ReadXmlFile(string xmlfilepath)
{
DataSet ds = new DataSet();
ds.ReadXml(xmlfilepath, XmlReadMode.ReadSchema);
return ds;
}
#endregion

#region CheckRole
public static bool CheckRole(string role)
{
bool Rolevalue = false;
string str_role = ((System.Web.Security.FormsIdentity)(HttpContext.Current.User.Identity)).Ticket.UserData.ToString();
if (str_role == role)
{
Rolevalue = true;
}
return Rolevalue;
}
#endregion

#region ChangeFileName
///
/// Method Name:-ChangeFileName
/// Purpose:- To change the filename of the uploaded image file
/// Created By:-Snehal
/// Created Date(dd/mm/yyyy):-17/04/2007
///

public static string ChangeFileName(string filename)
{
string newFileName;
string[] Substring;
char[] delimitdot = { '.' };
char[] delimitspace = { ' ' };
Substring = filename.Split(delimitdot, 2);
string dateTimenew = System.DateTime.Now.ToString().Replace('/', ' ');
string dateTime = dateTimenew.Replace(':', ' ');
string[] substring1 = dateTime.Split(delimitspace);
string appenddatetime = "";
int i;
for (i = 0; i < substring1.Length - 1; i++)
{
appenddatetime += substring1[i];
}
return newFileName = Substring[0] + appenddatetime + '.' + Substring[1];
}
#endregion
}
}

No comments: