Thursday, December 8, 2011

Helper - class

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.Security;
using System.Web.UI.WebControls;

using System.Drawing;

namespace BusinessObjects
{
public class HelperClasses
{
private HelperClasses()
{
}

private const string ParameterName = "cwz=";
private const string EncryptionKey = "key";
private const string Digestsalt = @"H3#@*ALMLLlk31q4l1ncL#@...";

public static bool RewriteUrl
{
get { return Convert.ToBoolean(ConfigurationManager.AppSettings.Get("ReWriteUrl")); }
}
public static bool IsHtmlExt
{
get { return Convert.ToBoolean(ConfigurationManager.AppSettings.Get("IsHtmlExt")); }
}

public static bool ErrorWriteToDb
{
get { return Convert.ToBoolean(ConfigurationManager.AppSettings.Get("WriteErrorToDb")); }
}

public static bool AllowPaypal
{
get { return Convert.ToBoolean(ConfigurationManager.AppSettings.Get("AllowPaypal")); }
}
public static bool AllowCreditcardPayments
{
get { return Convert.ToBoolean(ConfigurationManager.AppSettings.Get("AllowCreditcardPayments")); }
}

///
/// To GetCheckBoxListValues
///

/// The check box list item.
///
public static string GetCheckBoxListValues(CheckBoxList checkBoxListItem)
{
var checkedValues = new StringBuilder();
try
{
foreach (var li in checkBoxListItem.Items.Cast().Where(li => li.Selected))
checkedValues.Append(li.Value + ",");
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return checkedValues.ToString().TrimEnd(',');
}

///
/// To GetCheckBoxListText
///

/// The check box list item.
///
public static string GetCheckBoxListText(CheckBoxList checkBoxListItem)
{
var checkedValues = new StringBuilder();
try
{
foreach (var li in checkBoxListItem.Items.Cast().Where(li => li.Selected))
checkedValues.Append(li.Text + ",");
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return checkedValues.ToString().TrimEnd(',');
}

//To GetListBoxListValues
public static string GetCheckBoxListValues(ListBox listBoxItem)
{
var checkedValues = new StringBuilder();
try
{
foreach (var li in listBoxItem.Items.Cast().Where(li => li.Selected))
checkedValues.Append(li.Value + ",");
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return checkedValues.ToString().TrimEnd(',');
}

//To GetListBoxListValues
public static string GetCheckBoxListText(ListBox listBoxItem)
{
var checkedValues = new StringBuilder();
try
{
foreach (var li in listBoxItem.Items.Cast().Where(li => li.Selected))
checkedValues.Append(li.Text + ",");
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return checkedValues.ToString().TrimEnd(',');
}

//To CheckCheckBoxList
public static void CheckCheckBoxList(string checkValues, CheckBoxList checkBoxListItem)
{
try
{
if (string.IsNullOrEmpty(checkValues)) return;
var splitCheckedValues = checkValues.Split(',');
checkBoxListItem.ClearSelection();
foreach (
var li in
from t in splitCheckedValues
from ListItem li in checkBoxListItem.Items
where li.Value == t
select li)
li.Selected = true;
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
}
//To CheckListBoxList
public static void CheckCheckBoxList(string checkValues, ListBox checkBoxListItem)
{
try
{
var splitCheckedValues = checkValues.Split(',');
checkBoxListItem.ClearSelection();
foreach (var li in
from t in splitCheckedValues from ListItem li in checkBoxListItem.Items where li.Text == t select li
)
li.Selected = true;
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
}

public static void CheckCheckBoxListValues(string checkValues, ListBox checkBoxListItem)
{
try
{
var splitCheckedValues = checkValues.Split(',');
checkBoxListItem.ClearSelection();
foreach (var li in
splitCheckedValues.SelectMany(
t => checkBoxListItem.Items.Cast().Where(li => li.Value == t)))
li.Selected = true;
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
}
public static void CheckCheckBoxList(CheckBoxList checkBoxListItem, out int checkedCount)
{
checkedCount = checkBoxListItem.Items.Cast().Count(li => li.Selected);
}




//To CheckCheckBoxList
public static void CheckCheckBoxList(string checkValues, CheckBoxList checkBoxListItem, out int checkedCount)
{
checkedCount = 0;
try
{
if (string.IsNullOrEmpty(checkValues)) return;

var splitCheckedValues = checkValues.Split(',');
checkedCount = 0;
checkBoxListItem.ClearSelection();
foreach (var li in
from t in splitCheckedValues
from ListItem li in checkBoxListItem.Items
where li.Value == t
select li)
{
checkedCount++;
li.Selected = true;
}

}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
}

//To CheckRadioButtonList
public static int CheckRadioButtonList(RadioButtonList radioButtonListItem)
{
var value = 2;
try
{
switch (radioButtonListItem.SelectedValue.ToLower())
{
case "yes":
value = 1;
break;
case "no":
value = 0;
break;
}
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return value;
}

//TO Check CheckBoxList
public static void CheckRadioButtonList(string checkValues, RadioButtonList radioButtonListItem)
{
try
{
radioButtonListItem.ClearSelection();
var item = radioButtonListItem.Items.FindByValue(checkValues);
if (item != null)
item.Selected = true;
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
}

//TO Check CheckBoxList
public static void CheckDropDownList(string checkValues, DropDownList dropDownList)
{
try
{
dropDownList.ClearSelection();
var item = dropDownList.Items.FindByValue(checkValues);
if (item != null)
item.Selected = true;
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
}

public static int GetIntegerValue(object obj)
{
return obj == DBNull.Value ? 0 : Convert.ToInt32(obj);
}

public static bool GetBooleanValue(object obj)
{
return obj == DBNull.Value ? false : Convert.ToBoolean(obj);
}

public static decimal GetDecimalValue(object obj)
{
return obj == DBNull.Value ? 0 : Convert.ToDecimal(obj);
}

public static DateTime? GetDateTime(object obj)
{
if (obj == DBNull.Value)
return null;
return Convert.ToDateTime(obj);

}

public static string GetStringValue(object obj)
{
return obj == DBNull.Value ? "" : obj.ToString();
}

public static int GetRadioButtonListValues(RadioButtonList radioButtonListItem)
{
var value = 2;
try
{
switch (radioButtonListItem.SelectedValue.ToLower())
{
case "yes":
value = 1;
break;
case "no":
value = 0;
break;
}
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return value;
}

public static bool IsNumeric(string value)
{
int i;
return int.TryParse(value, out i);
}

public static string ActualPreviouPath(string absolutePath)
{
var path = absolutePath.Split('/');
var returnPath = path.Where((t, i) => i > 1).Aggregate("", (current, t) => current + (t + "/"));
return returnPath.TrimEnd('/');
}

//To Generate CWDEX Authentication Cookie
public static HttpCookie GetAuthenticatedCookieBll(int userTypeId, string username, string password, string name)
{

FormsAuthentication.Initialize();
var ticket = new FormsAuthenticationTicket(1, name, DateTime.Now, DateTime.Now.AddMinutes(30), true,
userTypeId.ToString(), FormsAuthentication.FormsCookiePath);
var hash = FormsAuthentication.Encrypt(ticket);
var campNavigatorCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash) { Expires = ticket.Expiration };
return campNavigatorCookie;
}

//This To Remove Duplicates.
public static string RemoveDuplicates(string searchStrings, char delimiter)
{
var strAggregate = "";
try
{
var strData = searchStrings;
var separator = new[] { delimiter };
var values = strData.Split(separator);
var hash = new HashSet();
foreach (var val in values)
hash.Add(val);
strAggregate = hash.Aggregate(string.Empty, (current, hval) => current + (hval + delimiter));
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return strAggregate;
}

//public static ZipCityState GetZipCityState(string csvZipCityState)
//{
// try
// {
// if (!string.IsNullOrEmpty(csvZipCityState))
// {
// var values = csvZipCityState.Split(',');
// if (values.Length == 3)
// {
// var result = new ZipCityState
// {
// CityName = values[1],
// ZipCode = Convert.ToInt32(values[0]),
// StateDetails = USStateHelper.GetStateByName(values[2])
// };
// return result;
// }
// return new ZipCityState();
// }
// }
// catch (Exception ex)
// {
// CareWhizException.ReturnMessage(ex);
// }
// return new ZipCityState();
//}

#region QueryString

public static NameValueCollection GetQueryStringCollection(string query)
{
var col = new NameValueCollection();
try
{
if (!String.IsNullOrEmpty(query))
{
string[] prm = query.Split('&');
int count = prm.Length;
if (count > 1)
{
for (int i = 0; i < count; i++)
{
string[] pr = prm[i].Split('=');
if (pr.Length == 2)
col.Add(pr[0], pr[1]);
else if (pr.Length >= 2)
col.Add(pr[0], prm[i].Substring(prm[i].IndexOf('=') + 1));
}
}
else
{
string[] pr = prm[0].Split('=');
if (pr.Length == 2)
col.Add(pr[0], pr[1]);
else if (pr.Length >= 2)
col.Add(pr[0], prm[0].Substring(prm[0].IndexOf('=') + 1));
//col.Add(pr[0], pr[1]);
}
}
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return col;
}

public static string GetTamperProofQueryString(string queryString)
{
var result = string.Empty;
try
{
if (queryString.Length > 0)
{
result = Encrypt(queryString);
result += String.Concat("&dig=", GetDigest(result));
}
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return result;
}

public static string GetPlainQueryString()
{
var result = string.Empty;
try
{
if (HttpContext.Current.Request.RawUrl.IndexOf("?") >= 0)
{
string query = ExtractQuery(HttpContext.Current.Request.RawUrl);

string encryptedQuery;
string digest;
GetQueryStringAndDigest(query, out encryptedQuery, out digest);
if (!string.IsNullOrEmpty(encryptedQuery) && !string.IsNullOrEmpty(digest))
{
if (query.StartsWith(ParameterName, StringComparison.OrdinalIgnoreCase))
{

if (EnsureUrlNotTampered(encryptedQuery, digest))
{
string rawQuery = encryptedQuery.Replace(ParameterName, string.Empty);
string decryptedQuery = Decrypt(rawQuery);
result = decryptedQuery;
}
else
HttpContext.Current.Response.Redirect("~/url-tampered.aspx", true);
}
else
HttpContext.Current.Response.Redirect("~/url-tampered.aspx", true);
}
else
{
HttpContext.Current.Response.Redirect("~/url-tampered.aspx", true);
}
}
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return result;
}

public static string GetPlainQueryString(string query)
{
var result = string.Empty;
try
{
//string query = ExtractQuery(HttpContext.Current.Request.RawUrl);

string encryptedQuery;
string digest;
GetQueryStringAndDigest(query, out encryptedQuery, out digest);
if (!string.IsNullOrEmpty(encryptedQuery) && !string.IsNullOrEmpty(digest))
{
if (query.StartsWith(ParameterName, StringComparison.OrdinalIgnoreCase))
{

if (EnsureUrlNotTampered(encryptedQuery, digest))
{
string rawQuery = encryptedQuery.Replace(ParameterName, string.Empty);
string decryptedQuery = Decrypt(rawQuery);
result = decryptedQuery;
}
else
HttpContext.Current.Response.Redirect("~/url-tampered.aspx", true);
}
else
HttpContext.Current.Response.Redirect("~/url-tampered.aspx", true);
}
else
{
HttpContext.Current.Response.Redirect("~/url-tampered.aspx", true);
}
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return result;
}
private static string ExtractQuery(string url)
{

int index = url.IndexOf("?") + 1;
return url.Substring(index);

}

private static void GetQueryStringAndDigest(string query, out string encryptedQuery, out string digest)
{
encryptedQuery = "";
digest = "";
try
{
if (query.Contains("&dig="))
{
int startOfDigest = query.IndexOf("&dig=");
digest = query.Substring(startOfDigest);
encryptedQuery = query.Substring(0, query.Length - digest.Length);
digest = HttpContext.Current.Server.UrlDecode(digest);
encryptedQuery = HttpContext.Current.Server.UrlDecode(encryptedQuery).Replace(" ", "+");
}
else if (query.Contains("cwz="))
{
digest = string.Empty;
encryptedQuery = query;
}
else
{
digest = string.Empty;
encryptedQuery = string.Empty;
}
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}

}

private static string GetDigest(string tamperProofParams)
{
var digest = "";
try
{
String input = String.Concat(Digestsalt, tamperProofParams, Digestsalt);
var encoder = new UTF8Encoding();
var md5Hasher = new MD5CryptoServiceProvider();
byte[] hashedDataBytes = md5Hasher.ComputeHash(encoder.GetBytes(input));
digest = Convert.ToBase64String(hashedDataBytes).TrimEnd("=".ToCharArray());
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return digest;
}

private static bool EnsureUrlNotTampered(string tamperProofParams, string receivedDigest)
{
tamperProofParams = "?" + tamperProofParams;
string expectedDigest = GetDigest(tamperProofParams);
if (string.IsNullOrEmpty(receivedDigest))
return false;
receivedDigest = receivedDigest.Replace("&dig=", string.Empty);
receivedDigest = receivedDigest.Replace(" ", "+");
return String.Compare(expectedDigest, receivedDigest) == 0;
}

#endregion

#region Encryption/decryption

///
/// The salt value used to strengthen the encryption.
///

private readonly static byte[] Salt = Encoding.ASCII.GetBytes(EncryptionKey.Length.ToString());

///
/// Encrypts any string using the Rijndael algorithm.
///

/// The string to encrypt.
/// A Base64 encrypted string.
public static string Encrypt(string inputText)
{
var strEncrypted = "";
try
{
var rijndaelCipher = new RijndaelManaged();
var plainText = Encoding.Unicode.GetBytes(inputText);
var secretKey = new PasswordDeriveBytes(EncryptionKey, Salt);

using (
var encryptor = rijndaelCipher.CreateEncryptor(secretKey.GetBytes(32),
secretKey.GetBytes(16)))
{
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainText, 0, plainText.Length);
cryptoStream.FlushFinalBlock();
strEncrypted = "?" + ParameterName + Convert.ToBase64String(memoryStream.ToArray());
}
}
}
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return strEncrypted;
}

///
/// Decrypts a previously encrypted string.
///

/// The encrypted string to decrypt.
/// A decrypted string.
public static string Decrypt(string inputText)
{
var strDecrypted = "";
try
{
var rijndaelCipher = new RijndaelManaged();
byte[] encryptedData = Convert.FromBase64String(inputText);
var secretKey = new PasswordDeriveBytes(EncryptionKey, Salt);

using (
var decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32),
secretKey.GetBytes(16)))
{
using (var memoryStream = new MemoryStream(encryptedData))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
var plainText = new byte[encryptedData.Length];
var decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
strDecrypted = Encoding.Unicode.GetString(plainText, 0, decryptedCount);
}
}
}
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return strDecrypted;
}

#endregion

public static string GetCurrentPageName()
{
var fileName = string.Empty;
try
{
var sPath = HttpContext.Current.Request.Url.AbsolutePath;
var oInfo = new FileInfo(sPath);
fileName = oInfo.Name;
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return fileName;
}

public static string GetFullyQualifiedApplicationPath()
{
var appPath = string.Empty;
try
{
//Getting the current context of HTTP request
var context = HttpContext.Current;

//Checking the current context content
if (context != null)
{
//Formatting the fully qualified website url/name
appPath = string.Format("{0}://{1}{2}{3}",
context.Request.Url.Scheme,
context.Request.Url.Host,
context.Request.Url.Port == 80
? string.Empty
: ":" + context.Request.Url.Port,
context.Request.ApplicationPath);
}
if (!appPath.EndsWith("/"))
appPath += "/";
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return appPath;
}
public static string GetFullyQualifiedApplicationPath(string filePath)
{
return GetFullyQualifiedApplicationPath() + filePath;
}
public static List GetMonths()
{
var months = ((List)HttpContext.Current.Cache["months"]);
try
{
if (months == null)
{
var ds = new DataSet();
var path = HttpContext.Current.Server.MapPath("~/App_Data") + "\\" + "months.xml";
ds.ReadXml(path);
months = new List();
for (var i = 0; i < ds.Tables[0].Rows.Count; i++)
months.Add(new Month
{
Id = Convert.ToInt32(ds.Tables[0].Rows[i]["Id"]),
Name = ds.Tables[0].Rows[i]["Name"].ToString(),
ShortName = ds.Tables[0].Rows[i]["ShortName"].ToString()
});
var cd = new CacheDependency(path);
HttpContext.Current.Cache.Insert("months", months, cd);
}
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return months;
}

public static List GetDays()
{
var days = ((List)HttpContext.Current.Cache["days"]);
try
{
if (days == null)
{
var ds = new DataSet();
string path = HttpContext.Current.Server.MapPath("~/App_Data") + "\\" + "days.xml";
ds.ReadXml(path);
days = new List();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
days.Add(new Day
{
Id = Convert.ToInt32(ds.Tables[0].Rows[i]["Id"]),
Name = ds.Tables[0].Rows[i]["Name"].ToString()
});
}
var cd = new CacheDependency(path);
HttpContext.Current.Cache.Insert("days", days, cd);
}
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return days;
}

public static void SendMail(string from, string to, string subject, string body, string name)
{
try
{
if (string.IsNullOrEmpty(from))
from = ConfigurationManager.AppSettings["EmailFromAddr"];
if (ConfigurationManager.AppSettings["IsTesting"] == "1")
to = ConfigurationManager.AppSettings["IsTestingEmail"];

var msg = new MailMessage();
var smtp = new SmtpClient();
msg.From = new MailAddress(from, name);
msg.To.Add(new MailAddress(to));
msg.Subject = subject;
msg.IsBodyHtml = true;

msg.Body = body;
smtp.Host = ConfigurationManager.AppSettings["EmailHostAddr"]; //"smtp.gmail.com";
smtp.Port = int.Parse(ConfigurationManager.AppSettings["EmailHostPort"]); //2525
smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["EmailHostUID"],
ConfigurationManager.AppSettings["EmailHostPwd"]);
smtp.Send(msg);
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
}

public static void SendMail(string from, string to, string subject, string body)
{
try
{
if (string.IsNullOrEmpty(from))
from = ConfigurationManager.AppSettings["EmailFromAddr"];
if (ConfigurationManager.AppSettings["IsTesting"] == "1")
to = ConfigurationManager.AppSettings["IsTestingEmail"];

var msg = new MailMessage();
var smtp = new SmtpClient();
msg.From = new MailAddress(from, "CareWhiz Admin");
msg.To.Add(new MailAddress(to));
msg.Subject = subject;
msg.IsBodyHtml = true;

msg.Body = body;
smtp.Host = ConfigurationManager.AppSettings["EmailHostAddr"]; //"smtp.gmail.com";
smtp.Port = int.Parse(ConfigurationManager.AppSettings["EmailHostPort"]); //2525
smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["EmailHostUID"],
ConfigurationManager.AppSettings["EmailHostPwd"]);
smtp.Send(msg);
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
}

public static void LoadMultiLineText(TextBox txt, string text, int rowLength)
{
txt.Text = text;
txt.Rows = ((text.Length / rowLength == 0) ? 1 : text.Length / rowLength) + 2;
}

public static Int32 LoadMultiLineText(int textLength, int rowLength)
{
return ((textLength / rowLength == 0) ? 1 : textLength / rowLength) + 2;
}

//public static int IsKeyWordExists(string keyword, string fileName)
//{
// var xmlobj = new XmlObjects();
// try
// {
// if (!string.IsNullOrEmpty(keyword) && (!string.IsNullOrEmpty(fileName)))
// {
// xmlobj.FileName = fileName;
// xmlobj.Name = keyword;

// xmlobj.returnStatus = XmlBusiness.CheckKeywordAvailability(xmlobj);
// }
// }
// catch (Exception ex)
// {
// ErrorHandler.WriteError(ex);
// }
// return xmlobj.returnStatus;
//}


// For registration.

public static string BuildHtml(string content, string name, string role)
{
string htmlString = null;
try
{

var htmlStream = new StreamReader(HttpContext.Current.Server.MapPath("~/mail/messages.html"));
htmlString = htmlStream.ReadToEnd();
htmlStream.Close();
htmlStream.Dispose();
htmlString = htmlString.Replace("#heading#", "");
htmlString = htmlString.Replace("#name#", name);
htmlString = htmlString.Replace("#content#", content);
htmlString = htmlString.Replace("#role#", role);
htmlString = htmlString.Replace("#path#", GetFullyQualifiedApplicationPath());

}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return htmlString;
}

public static string BuildHtml(string content, string name, string role, string heading)
{
string htmlString = null;
try
{

var htmlStream = new StreamReader(HttpContext.Current.Server.MapPath("~/mail/messages.html"));
htmlString = htmlStream.ReadToEnd();
htmlStream.Close();
htmlStream.Dispose();
htmlString = htmlString.Replace("#heading#", heading);
htmlString = htmlString.Replace("#name#", name);
htmlString = htmlString.Replace("#content#", content);
htmlString = htmlString.Replace("#role#", role);
htmlString = htmlString.Replace("#path#", GetFullyQualifiedApplicationPath());
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return htmlString;
}
public static string BuildAddListingHtml(string content, string name)
{
string htmlString = null;
try
{

var htmlStream = new StreamReader(HttpContext.Current.Server.MapPath("~/mail/messages.html"));
htmlString = htmlStream.ReadToEnd();
htmlStream.Close();
htmlStream.Dispose();
htmlString = htmlString.Replace("#name#", name);
htmlString = htmlString.Replace("#searchcontent#", content);
htmlString = htmlString.Replace("#path#", GetFullyQualifiedApplicationPath());
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return htmlString;
}

public static string BuildHtmlforRequest(string content, string name, string role)
{
string htmlString = null;
try
{
var htmlStream = new StreamReader(HttpContext.Current.Server.MapPath("~/mail/messages.html"));
htmlString = htmlStream.ReadToEnd();
htmlStream.Close();
htmlStream.Dispose();
htmlString = htmlString.Replace("#name#", name);
htmlString = htmlString.Replace("#content#", content);
htmlString = htmlString.Replace("#ListName#", role);
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return htmlString;
}

public static void GenerateThumbImage(string path, string fname)
{

var thumbnailPath = path + fname.Split('.')[0].Split('/')[2] + "_th." + fname.Split('.')[1];

using (var img =
System.Drawing.Image.FromFile(path + fname.Split('/')[2]))
{
var thumbNailSize = NewImageSize(138, 132, 150);

using (var imgThnail =
new Bitmap(img, thumbNailSize.Width, thumbNailSize.Height))
{
imgThnail.Save(thumbnailPath, img.RawFormat);
imgThnail.Dispose();
}
img.Dispose();
}
}



public static Size NewImageSize(int originalHeight, int originalWidth, double formatSize)
{
Size newSize;

if (originalHeight > formatSize && originalWidth > formatSize)
{
double tempval;
if (originalHeight > originalWidth)
tempval = formatSize / Convert.ToDouble(originalHeight);
else
tempval = formatSize / Convert.ToDouble(originalWidth);

newSize = new Size(Convert.ToInt32(tempval * originalWidth), Convert.ToInt32(tempval * originalHeight));
}
else
newSize = new Size(originalWidth, originalHeight);
return newSize;
}
public static Bitmap ProportionallyResizeBitmap(Bitmap src, int maxWidth, int maxHeight)
{

// original dimensions
var w = src.Width;
var h = src.Height;

// Longest and shortest dimension
var longestDimension = (w > h) ? w : h;
var shortestDimension = (w < h) ? w : h;

// propotionality
var factor = ((float)longestDimension) / shortestDimension;

// default width is greater than height
double newWidth = maxWidth;
double newHeight = maxHeight / factor;

// if height greater than width recalculate
if (w < h)
{
newWidth = maxWidth / factor;
newHeight = maxHeight;
}

// Create new Bitmap at new dimensions
var result = new Bitmap(src, (int)newWidth, (int)newHeight);
//using (var g = Graphics.FromImage(result))
//{
// // g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
// // g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
// // g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
// g.DrawImage(src, 0, 0, (int)newWidth, (int)newHeight);
//}
return result;
}

///
/// Gets the state URL path.
///

/// Name of the state.
/// The state id.
///


public static string GetStateUrlPathforRent(string stateName, int stateId)
{
return RewriteUrl
? GetFullyQualifiedApplicationPath() +
string.Format("State/" + stateName.Replace(" ", "") +
(IsHtmlExt ? ".html" : ".aspx"))
: GetFullyQualifiedApplicationPath() +
string.Format("search-camp-sales.aspx?{0}",
"campstateid=" + stateId + "&campstatename=" + stateName);
}

public static string GetCityUrlPathforRent(string city)
{

return RewriteUrl
? GetFullyQualifiedApplicationPath() + string.Format("City/" + city.Replace(" ", "-") +
(IsHtmlExt ? ".html" : ".aspx"))
: GetFullyQualifiedApplicationPath() + string.Format("search-camp-sales.aspx?{0}",
"location=" + city);

}

//To GetZipcodeCityState Values
public static ZipCityState GetZipCityState(string csvZipCityState)
{
try
{
if (!string.IsNullOrEmpty(csvZipCityState))
{
var values = csvZipCityState.Split(',');
if (values.Length == 3)
{
var result = new ZipCityState
{
CityName = values[1],
ZipCode = Convert.ToInt32(values[0]),
StateDetails = USStateHelper.GetStateByName(values[2])
};
return result;
}
return new ZipCityState();
}
}
catch (Exception ex)
{
CareWhizException.ReturnMessage(ex);
}
return new ZipCityState();
}





public static string GetStateUrlPath(string stateName, int stateId)
{
return RewriteUrl
? GetFullyQualifiedApplicationPath() +
string.Format("State/" + stateName.Replace(" ", "") +
(IsHtmlExt ? ".html" : ".aspx"))
: GetFullyQualifiedApplicationPath() +
string.Format("search-camp-lists.aspx?{0}",
"campstateid=" + stateId + "&campstatename=" + stateName);
}
public static string GetCityUrlPath(string city)
{
return RewriteUrl
? GetFullyQualifiedApplicationPath() + string.Format("City/" + city.Replace(" ", "-") +
(IsHtmlExt ? ".html" : ".aspx"))
: GetFullyQualifiedApplicationPath() + string.Format("mycity/" + city + ".aspx?{0}",
"loc=" + city);
}



public static string GetCityUrlPath(string city, string statecode)
{
return RewriteUrl
? string.Format("City/" + city.Replace(" ", "-") +
(IsHtmlExt ? ".html" : ".aspx"))
: string.Format("mycity/" + city + ".aspx?{0}",
"loc=" + city);
}

public static string GetCountryUrlPath(string country)
{
return RewriteUrl
? string.Format("country/" + country.Replace(" ", "-") +
(IsHtmlExt ? ".html" : ".aspx"))
: string.Format("search-camp-lists.aspx?{0}",
"location=" + country);
}



public static int GetWidth(int logoWidth,int logoHeight, int type)
{
// original dimensions
var w = logoWidth;
var h = logoHeight;

// Longest and shortest dimension
var longestDimension = (w > h) ? w : h;
var shortestDimension = (w < h) ? w : h;

// propotionality
var factor = ((float)longestDimension) / shortestDimension;
var thumbsize = ConfigurationManager.AppSettings["thumbsizem"].Split(',');

var maxWidth = Convert.ToInt32(thumbsize[0]);// 132;
// var maxHeight = Convert.ToInt32(thumbsize[1]);// 138;
switch (type)
{
case 1:
thumbsize = ConfigurationManager.AppSettings["thumbsize"].Split(',');
maxWidth = Convert.ToInt32(thumbsize[0]);//125;
//maxHeight = Convert.ToInt32(thumbsize[1]);// 115;

break;

case 3:
thumbsize = ConfigurationManager.AppSettings["thumbsizes"].Split(',');
maxWidth = Convert.ToInt32(thumbsize[0]);//60;
//maxHeight = Convert.ToInt32(thumbsize[1]);// 65;

break;
}

// default width is greater than height
double newWidth = maxWidth;
// double newHeight = maxHeight / factor;

// if height greater than width recalculate
if (w < h)
{
newWidth = maxWidth / factor;
// newHeight = maxHeight;
}
return (int)newWidth;
}
public static int GetHeight(int logoWidth,int logoHeight, int type)
{
// original dimensions
var w = logoWidth;
var h = logoHeight;

// Longest and shortest dimension
var longestDimension = (w > h) ? w : h;
var shortestDimension = (w < h) ? w : h;

// propotionality
var factor = ((float)longestDimension) / shortestDimension;
var thumbsize = ConfigurationManager.AppSettings["thumbsizem"].Split(',');

// var maxWidth = Convert.ToInt32(thumbsize[0]);// 132;
var maxHeight = Convert.ToInt32(thumbsize[1]);// 138;
switch (type)
{
case 1:
thumbsize = ConfigurationManager.AppSettings["thumbsize"].Split(',');
//maxWidth = Convert.ToInt32(thumbsize[0]);//125;
maxHeight = Convert.ToInt32(thumbsize[1]);// 115;

break;

case 3:
thumbsize = ConfigurationManager.AppSettings["thumbsizes"].Split(',');
// maxWidth = Convert.ToInt32(thumbsize[0]);//60;
maxHeight = Convert.ToInt32(thumbsize[1]);// 65;

break;
}

// default width is greater than height
//double newWidth = maxWidth;
double newHeight = maxHeight / factor;

// if height greater than width recalculate
if (w < h)
{
// newWidth = maxWidth / factor;
newHeight = maxHeight;
}
return (int)newHeight;
}

public static int GetServiceIdByName(string serviceName)
{
switch (serviceName)
{

case "Special Needs":
return 2;
case "Tutoring":
return 3;
case "Pet Sitting":
return 4;
case "Elder Care":
return 5;
case "House Keeping":
return 6;
case "Personal Care":
return 7;
default:
return 1;
}
}

public static string GetShortRoleName(string rolename)
{
string shortname = string.Empty;
if(rolename == "careseeker")
shortname = "cr";
if(rolename == "careprovider")
shortname = "cp";
if(rolename == "careagency")
shortname = "ca";
if(rolename == "carecenter")
shortname = "cc";

return shortname;
}

public static string GetServiceNameById(int id)
{
switch (id)
{

//case 2:
// return "Special Needs";
//case 3:
// return "Tutoring";
//case 4:
// return "Pet Sitting";
//case 5:
// return "Elder Care";
//case 6:
// return "House Keeping";
//case 7:
// return "Personal Care";
default:
return "Tutoring";
}
}
}

public class Month
{
public int Id { get; set; }
public string Name { get; set; }
public string ShortName { get; set; }
}
public class Day
{
public int Id { get; set; }
public string Name { get; set; }
}





}

My Notes

retrieve emails

http://www.4shared.com/file/z1Tfg8GY/retrieve_emails.html

Ref Site

http://code.google.com/apis/contacts/docs/2.0/developers_guide_dotnet.html#Retrieving


helperclass

http://www.4shared.com/file/XbPlQ_qX/HelperClasses.html

web.config

http://www.4shared.com/file/EdymFlHU/web.html