Common Methods use in asp.net/mvc
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web.UI;
using System.IO;
using System.Web.Security;
using System.Collections.Specialized;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using ASPSnippets.SmsAPI;
using System.Net.Mail;
using System.Net;
public class CommonMethods
{
#region "Short Query Functions"
public static string GetTextData(string SqlStr)
{
string functionReturnValue = null;
SqlConnection OAF = default(SqlConnection);
OAF = new SqlConnection(ConfigurationManager.ConnectionStrings["SCon"].ConnectionString);
SqlCommand myCom = new SqlCommand(SqlStr, OAF);
myCom.Connection.Open();
if ((myCom.ExecuteScalar() == null))
{
functionReturnValue = string.Empty;
}
else
{
functionReturnValue = myCom.ExecuteScalar().ToString();
}
myCom.Connection.Close();
myCom.Dispose();
OAF.Close();
OAF.Dispose();
return functionReturnValue;
}
public static void Execute_Query(string SqlStr)
{
SqlConnection OAF = default(SqlConnection);
OAF = new SqlConnection(ConfigurationManager.ConnectionStrings["SCon"].ConnectionString);
SqlCommand myCom = new SqlCommand(SqlStr, OAF);
myCom.Connection.Open();
myCom.ExecuteNonQuery();
myCom.Connection.Close();
myCom.Dispose();
OAF.Close();
OAF.Dispose();
}
public static long GetIntData(string SqlStr)
{
long functionReturnValue = 0;
SqlConnection OAF = default(SqlConnection);
OAF = new SqlConnection(ConfigurationManager.ConnectionStrings["SCon"].ConnectionString);
SqlCommand myCom = new SqlCommand(SqlStr, OAF);
myCom.Connection.Open();
if (Convert.IsDBNull(myCom.ExecuteScalar()))
{
functionReturnValue = 0;
}
else
{
functionReturnValue = Convert.ToInt32(myCom.ExecuteScalar());
}
myCom.Connection.Close();
myCom.Dispose();
OAF.Close();
OAF.Dispose();
return functionReturnValue;
}
#endregion
#region "Input Data Velidation Functions"
public static Control[] MyControls(Control root)
{
List<Control> list = new List<Control>();
list.Add(root);
if (root.HasControls())
{
foreach (Control control in root.Controls)
{
list.AddRange(MyControls(control));
}
}
return list.ToArray();
}
public static string Validate_String(string Input_String)
{
Input_String = Input_String.Trim();
string[] Black_Listed = {
"--",
";",
"/*",
"*/",
"char",
"nchar",
"varchar",
"nvarchar",
"alter",
"begin",
"cast",
"create",
"cursor",
"declare",
"delete",
"drop",
"exec",
"execute",
"fetch",
"insert",
"kill",
"open",
"select",
"sys",
"sysobjects",
"syscolumns",
" table",
"update",
"|",
"&",
";",
"$",
"%",
"'",
"\"\"",
"\\'",
"\\",
"<>",
"()",
"+",
",",
"\\\""
};
string Villain = null;
foreach (string Villain_loopVariable in Black_Listed)
{
Villain = Villain_loopVariable;
if (Input_String.Contains(Villain))
{
Input_String = Input_String.Replace(Villain, "");
}
}
return Input_String;
}
public static bool IsValidString(string Input_String)
{
bool WhatToReturn = true;
Input_String = Input_String.Trim();
string[] Black_Listed = {
"--",
";",
"/*",
"*/",
"char",
"nchar",
"varchar",
"nvarchar",
"alter",
"script",
"begin",
"cast",
"create",
"cursor",
"declare",
"delete",
"drop",
"exec",
"execute",
"fetch",
"insert",
"kill",
"open",
"select",
"sys",
"sysobjects",
"syscolumns",
"table",
"update",
"<applet>",
"<body>",
"<embed>",
"<frame>",
"<script>",
"<frameset>",
"<html>",
"<iframe>",
"<img>",
"<style>",
"<layer>",
"<link>",
"<ilayer>",
"<meta>",
"<object>",
"table",
"update",
"|",
"&",
";",
"$",
"%",
"'",
"\"\"",
"\\'",
"\\",
"<>",
"()",
"+",
",",
"\\\""
};
string Villain = null;
foreach (string Villain_loopVariable in Black_Listed)
{
Villain = Villain_loopVariable;
if (Input_String.Contains(Villain))
{
WhatToReturn = false;
break; // TODO: might not be correct. Was : Exit For
}
}
return WhatToReturn;
}
#endregion
#region "Uploaded File Velidation Functions"
public static bool CheckFileType(string FileName, string CheckType)
{
string extension = Path.GetExtension(FileName).ToLower().Substring(1, Path.GetExtension(FileName).Length - 1);
switch (CheckType.ToUpper())
{
case "ALL":
switch (extension)
{
case "txt":
case "doc":
case "xls":
case "pdf":
case "gif":
case "tiff":
case "jpeg":
case "jpg":
case "ppt":
case "zip":
case "png":
case "rar": return true;
default: return false;
}
case "ONLYIMAGES":
switch (extension)
{
case "gif":
case "tiff":
case "jpeg":
case "jpg":
case "png": return true;
default: return false;
}
case "PDFONLY":
switch (extension)
{
case "pdf": return true;
default: return false;
}
case "PDF":
switch (extension)
{
case "pdf": return true;
default: return false;
}
case "JPG":
switch (extension)
{
case "jpeg":
case "jpg": return true;
default: return false;
}
case "JPEG":
switch (extension)
{
case "jpeg":
case "jpg": return true;
default: return false;
}
case "GIF":
switch (extension)
{
case "gif": return true;
default: return false;
}
case "TIFF":
switch (extension)
{
case "tiff": return true;
default: return false;
}
case "PNG":
switch (extension)
{
case "png": return true;
default: return false;
}
case "TXT":
switch (extension)
{
case "txt": return true;
default: return false;
}
case "DOC":
switch (extension)
{
case "doc": return true;
default: return false;
}
case "XLS":
switch (extension)
{
case "xls": return true;
default: return false;
}
case "PPT":
switch (extension)
{
case "ppt": return true;
default: return false;
}
case "ZIP":
switch (extension)
{
case "zip": return true;
default: return false;
}
case "RAR":
switch (extension)
{
case "rar": return true;
default: return false;
}
default:
return false;
}
}
public static string GetContentType(string extension)
{
switch (extension)
{
case "txt":
return "text/plain";
case "doc":
return "application/msword";
case "xls":
return "application/x-msexcel";
case "pdf":
return "application/pdf";
case "gif":
return "image/gif";
case "tiff":
return "image/tiff";
case "jpeg":
return "image/jpeg";
case "jpg":
return "image/jpeg";
case "png":
return "image/png";
case "pff":
return "application/ms-powerpoint";
case "zip":
return "application/zip";
default:
return "";
}
}
public bool IsFileValid(string ContentType)
{
string[] allowedImageTyps = {
"image/gif",
"image/pjpeg",
"image/bmp",
"image/x-png",
"application/pdf"
};
StringCollection imageTypes = new StringCollection();
imageTypes.AddRange(allowedImageTyps);
if (imageTypes.Contains(ContentType))
{
return true;
}
else
{
return false;
}
}
public static bool CheckFileHeader(byte[] buffer, string extension)
{
ASCIIEncoding enc = new System.Text.ASCIIEncoding();
string header = enc.GetString(buffer);
switch (extension)
{
case "pdf":
return header.StartsWith("%PDF-");
case "jpg":
return header.StartsWith("????") && !header.StartsWith("?????");
case "jpeg":
return header.StartsWith("????") && !header.StartsWith("?????");
case "txt":
return header.StartsWith("??") && !header.StartsWith("???");
case "doc":
return header.StartsWith("??_???_?");
case "xls":
return header.StartsWith("??_???_?");
case "png":
return header.StartsWith(".PNG") || header.StartsWith("?PNG");
case "tiff":
return header.StartsWith("MM*");
case "gif":
return header.StartsWith("GIF87a") || header.StartsWith("GIF89a");
case "exe":
return header.StartsWith("MZ");
case "zip":
return header.StartsWith("PK");
case "rar":
return header.StartsWith("Rar!");
case "ico":
return header.StartsWith("\\0\\0");
case "mp3":
return header.StartsWith("ID3");
case "kml":
return (header.StartsWith("<?xml") & !header.EndsWith("</kml>"));
case "kmz":
return header.StartsWith("PK");
case "OnlyImages":
if (header.StartsWith("????") && !header.StartsWith("?????"))
{
return true;
}
else if (header.StartsWith(".PNG") || header.StartsWith("?PNG"))
{
return true;
}
else if (header.StartsWith("MM*"))
{
return true;
}
else if (header.StartsWith("MM*"))
{
return true;
}
else if (header.StartsWith("GIF87a") || header.StartsWith("GIF89a"))
{
return true;
}
else if (header.StartsWith("\\0\\0"))
{
return true;
}
else
{
return false;
}
default:
return false;
}
}
#endregion
#region "Crop Image Functions"
public static byte[] CropImage(byte[] FileInBytes, int X, int Y, int W, int H)
{
using (System.IO.Stream ss = new System.IO.MemoryStream(FileInBytes))
{
using (System.Drawing.Image image = System.Drawing.Bitmap.FromStream(ss))
{
using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(W, H, image.PixelFormat))
{
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp))
{
g.DrawImage(image, new System.Drawing.Rectangle(0, 0, W, H), new System.Drawing.Rectangle(X, Y, W, H), System.Drawing.GraphicsUnit.Pixel);
}
//Save the file and reload to the control
using (System.IO.MemoryStream mm = new System.IO.MemoryStream())
{
bmp.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
FileInBytes = mm.ToArray();
}
}
}
}
return FileInBytes;
}
#endregion
#region "Membership User Functions"
public static string GetUserID()
{
MembershipUser MemUser = default(MembershipUser);
MemUser = Membership.GetUser();
return MemUser.ProviderUserKey.ToString();
}
public static string GetUserName()
{
MembershipUser MemUser = default(MembershipUser);
MemUser = Membership.GetUser();
return MemUser.UserName.ToString();
}
public static string GetErrorMessage(MembershipCreateStatus status)
{
switch (status)
{
case MembershipCreateStatus.DuplicateUserName:
return "Username already exists. Please enter a different user name.";
case MembershipCreateStatus.DuplicateEmail:
return "A username for that e-mail address already exists. Please enter a different e-mail address.";
case MembershipCreateStatus.InvalidPassword:
return "The password provided is invalid. Please enter a valid password value.";
case MembershipCreateStatus.InvalidEmail:
return "The e-mail address provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidAnswer:
return "The password retrieval answer provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidQuestion:
return "The password retrieval question provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.ProviderError:
return "The authentication provider Returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
case MembershipCreateStatus.UserRejected:
return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
default:
return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
}
}
#endregion
#region "Converter Functions"
public static string UniCode2ISCII(string S)
{
if (S == null)
{
return null;
}
try
{
Encoding encFrom = Encoding.GetEncoding(57002);
Encoding encTo = Encoding.GetEncoding(1252);
string str = S;
byte[] b = encFrom.GetBytes(str);
return encTo.GetString(b);
}
catch
{
return null;
}
}
public static byte[] HexStringToBytes(string hex)
{
int ss = 0;
string sp = "";
try
{
if (hex.Length == 0)
{
return new byte[] { 0 };
}
if (hex.Length % 2 == 1)
{
hex = "0" + hex;
}
byte[] result = new byte[hex.Length / 2];
for (int i = 0; i <= hex.Length / 2 - 1; i++)
{
ss = i;
sp = hex.Substring(2 * i, 2);
result[i] = byte.Parse(hex.Substring(2 * i, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
}
return result;
}
catch
{
return new byte[] { 0 };
}
}
public static string BytesToHexString(byte[] input)
{
StringBuilder hexString = new StringBuilder(64);
for (int i = 0; i <= input.Length - 1; i++)
{
hexString.Append(String.Format("{0:X2}", input[i]));
}
return hexString.ToString();
}
public static string BytesToDecString(byte[] input)
{
StringBuilder decString = new StringBuilder(64);
for (int i = 0; i <= input.Length - 1; i++)
{
decString.Append(String.Format((i == 0 ? "{0:D3}" : "-{0:D3}"), input[i]));
}
return decString.ToString();
}
public static string ASCIIBytesToString(byte[] input)
{
System.Text.ASCIIEncoding enc = new ASCIIEncoding();
return enc.GetString(input);
}
public static string UTF16BytesToString(byte[] input)
{
System.Text.UnicodeEncoding enc = new UnicodeEncoding();
return enc.GetString(input);
}
public static string UTF8BytesToString(byte[] input)
{
System.Text.UTF8Encoding enc = new UTF8Encoding();
return enc.GetString(input);
}
public static string ToBase64(byte[] input)
{
return Convert.ToBase64String(input);
}
public static byte[] FromBase64(string base64)
{
return Convert.FromBase64String(base64);
}
public static string DecryptString(string EncryptedString)
{
byte[] bytes = Convert.FromBase64String(EncryptedString);
return Encoding.UTF8.GetString(bytes);
}
public static string EncryptString(string PlainString)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(PlainString));
}
#endregion
#region "Genreate Password Function"
public static string GeneratePassword()
{
Random r = new Random();
string abC = "abcdefghkmnpqrstuvwxyz";
string Ints = "23456789";
string[] CharPart = new string[3];
string[] IntPart = new string[3];
string ThePassword = null;
CharPart[0] = abC.Substring(r.Next(0, 21), 1);
CharPart[1] = abC.Substring(r.Next(0, 21), 1);
CharPart[2] = abC.Substring(r.Next(0, 21), 1);
IntPart[0] = Ints.Substring(r.Next(0, 7), 1);
IntPart[1] = Ints.Substring(r.Next(0, 7), 1);
IntPart[2] = Ints.Substring(r.Next(0, 7), 1);
ThePassword = CharPart[0] + CharPart[1] + CharPart[2] + "*" + IntPart[0] + IntPart[1] + IntPart[2];
return ThePassword;
}
#endregion
#region "Send SMS/Email"
public static string SendSMS(String MobileNo, String Message)
{
Int64 MN;
if (!Int64.TryParse(MobileNo, out MN))
{
return "FAIL:Enter a proper Mobile Number.";
}
if (MobileNo.Length != 10)
{
return "FAIL:Enter a proper Mobile Number.";
}
if (String.IsNullOrEmpty(Message.Trim()))
{
return "FAIL:Message is required.";
}
string UserName, Password, MashapeKey;
UserName = ConfigurationManager.AppSettings["SMSUserName"].ToString();
Password = ConfigurationManager.AppSettings["SMSPassword"].ToString();
MashapeKey = ConfigurationManager.AppSettings["SMSMashapeKey"].ToString();
SMS.APIType = SMSGateway.Site2SMS;
SMS.MashapeKey = MashapeKey;
SMS.Username = UserName;
SMS.Password = Password;
try
{
SMS.SendSms(MobileNo.Trim(), Message.Trim());
return "SUCCESS:";
}
catch (Exception ex)
{
return "FAIL:Mobile-" + ex.Message;
}
}
public static string SendBulkSMS(List<string> MobileNos, String Message)
{
if (String.IsNullOrEmpty(Message.Trim()))
{
return "FAIL:Message is required.";
}
string UserName, Password, MashapeKey;
UserName = ConfigurationManager.AppSettings["SMSUserName"].ToString();
Password = ConfigurationManager.AppSettings["SMSPassword"].ToString();
MashapeKey = ConfigurationManager.AppSettings["SMSMashapeKey"].ToString();
SMS.APIType = SMSGateway.Site2SMS;
SMS.MashapeKey = MashapeKey;
SMS.Username = UserName;
SMS.Password = Password;
try
{
SMS.SendSms(MobileNos, Message.Trim());
return "SUCCESS:";
}
catch (Exception ex)
{
return "FAIL:" + ex.Message;
}
}
public static string SendEmail(String MsgTo, String Subject, String MsgBody, String MsgCCTo)
{
if (String.IsNullOrEmpty(MsgTo.Trim()))
{
return "FAIL:Message To is required.";
}
if (!MsgTo.Trim().Contains("@"))
{
return "FAIL:Enter a proper Email Address.";
}
if (!MsgTo.Trim().Contains("."))
{
return "FAIL:Enter a proper Email Address.";
}
if (String.IsNullOrEmpty(MsgBody.Trim()) && String.IsNullOrEmpty(Subject.Trim()))
{
return "FAIL:Subject/Message Body is required.";
}
if (String.IsNullOrEmpty(MsgCCTo.Trim()))
{
return "FAIL:CC to is required.";
}
if (!MsgCCTo.Trim().Contains("@"))
{
return "FAIL:Enter a proper CC Email Address.";
}
if (!MsgCCTo.Trim().Contains("."))
{
return "FAIL:Enter a proper CC Email Address.";
}
string MsgFrom, Password, theResule;
//MsgFrom = "momsfoodcourt.mfc@gmail.com";//ConfigurationManager.AppSettings["Email"].ToString();
//Password = "momsfoodcourt*123";//ConfigurationManager.AppSettings["EmailPassword"].ToString();
//MsgFrom = "info@momsfoodcourt.com";
//Password = "cnet*123";
MsgFrom = ConfigurationManager.AppSettings["Email"].ToString();
Password = ConfigurationManager.AppSettings["EmailPassword"].ToString();
try
{
using (MailMessage mm = new MailMessage(MsgFrom, MsgTo))
{
mm.Subject = Subject;
mm.Body = GetHeaderOnBody(MsgBody);
mm.CC.Add(MsgCCTo);
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
//smtp.Host = "smtp.gmail.com";
smtp.Host = "mail.momsfoodcourt.com";
//smtp.EnableSsl = true;
smtp.EnableSsl = false;
NetworkCredential NetworkCred = new NetworkCredential(MsgFrom, Password);
smtp.UseDefaultCredentials = false;
smtp.Credentials = NetworkCred;
//smtp.Port = 587;
smtp.Port = 25;
smtp.Send(mm);
theResule = "SUCCESS:";
}
}
catch (Exception ex)
{
theResule = "FAIL:" + ex.Message;
}
return theResule;
}
public static string SendEmail(String MsgTo, String Subject, String MsgBody)
{
if (String.IsNullOrEmpty(MsgTo.Trim()))
{
return "FAIL:Message To is required.";
}
if (!MsgTo.Trim().Contains("@"))
{
return "FAIL:Enter a proper Email Address.";
}
if (!MsgTo.Trim().Contains("."))
{
return "FAIL:Enter a proper Email Address.";
}
if (String.IsNullOrEmpty(MsgBody.Trim()) && String.IsNullOrEmpty(Subject.Trim()))
{
return "FAIL:Subject/Message Body is required.";
}
string MsgFrom, Password, theResule;
//MsgFrom = "momsfoodcourt.mfc@gmail.com";//ConfigurationManager.AppSettings["Email"].ToString();
//Password = "momsfoodcourt*123";//ConfigurationManager.AppSettings["EmailPassword"].ToString();
MsgFrom = ConfigurationManager.AppSettings["Email"].ToString();
Password = ConfigurationManager.AppSettings["EmailPassword"].ToString();
//MsgFrom = "info@momsfoodcourt.com";
//Password = "cnet*123";
try
{
using (MailMessage mm = new MailMessage(MsgFrom, MsgTo))
{
mm.Subject = Subject;
mm.Body = GetHeaderOnBody(MsgBody);
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
// smtp.Host = "smtp.gmail.com";
smtp.Host = "mail.momsfoodcourt.com";
//smtp.EnableSsl = true;
smtp.EnableSsl = false;
NetworkCredential NetworkCred = new NetworkCredential(MsgFrom, Password);
smtp.UseDefaultCredentials = false;
smtp.Credentials = NetworkCred;
//smtp.Port = 587;
smtp.Port = 25;
smtp.Send(mm);
theResule = "SUCCESS:";
}
}
catch (Exception ex)
{
theResule = "FAIL:" + ex.Message;
}
return theResule;
}
/// <summary>
/// With Attachment
/// </summary>
/// <param name="MsgTo"></param>
/// <param name="Subject"></param>
/// <param name="MsgBody"></param>
/// <param name="MsgCCTo"></param>
/// <param name="AttachedFile"></param>
/// <param name="AttachedFileName"></param>
/// <returns></returns>
public static string SendEmail(String MsgTo, String Subject, String MsgBody, String MsgCCTo, byte[] AttachedFile, string AttachedFileName)
{
if (String.IsNullOrEmpty(MsgTo.Trim()))
{
return "FAIL:Message To is required.";
}
if (!MsgTo.Trim().Contains("@"))
{
return "FAIL:Enter a proper Email Address.";
}
if (!MsgTo.Trim().Contains("."))
{
return "FAIL:Enter a proper Email Address.";
}
if (String.IsNullOrEmpty(MsgBody.Trim()) && String.IsNullOrEmpty(Subject.Trim()))
{
return "FAIL:Subject/Message Body is required.";
}
if (String.IsNullOrEmpty(MsgCCTo.Trim()))
{
return "FAIL:CC to is required.";
}
if (!MsgCCTo.Trim().Contains("@"))
{
return "FAIL:Enter a proper CC Email Address.";
}
if (!MsgCCTo.Trim().Contains("."))
{
return "FAIL:Enter a proper CC Email Address.";
}
string MsgFrom, Password, theResule;
//MsgFrom = "momsfoodcourt.mfc@gmail.com";//ConfigurationManager.AppSettings["Email"].ToString();
//Password = "momsfoodcourt*123";//ConfigurationManager.AppSettings["EmailPassword"].ToString();
//MsgFrom = "info@momsfoodcourt.com";
//Password = "cnet*123";
MsgFrom = ConfigurationManager.AppSettings["Email"].ToString();
Password = ConfigurationManager.AppSettings["EmailPassword"].ToString();
try
{
using (MailMessage mm = new MailMessage(MsgFrom, MsgTo))
{
mm.Subject = Subject;
mm.Body = GetHeaderOnBody(MsgBody);
mm.CC.Add(MsgCCTo);
mm.IsBodyHtml = true;
mm.Attachments.Add(new Attachment(new MemoryStream(AttachedFile), AttachedFileName));
SmtpClient smtp = new SmtpClient();
//smtp.Host = "smtp.gmail.com";
smtp.Host = "mail.momsfoodcourt.com";
//smtp.EnableSsl = true;
smtp.EnableSsl = false;
NetworkCredential NetworkCred = new NetworkCredential(MsgFrom, Password);
smtp.UseDefaultCredentials = false;
smtp.Credentials = NetworkCred;
//smtp.Port = 587;
smtp.Port = 25;
smtp.Send(mm);
theResule = "SUCCESS:";
}
}
catch (Exception ex)
{
theResule = "FAIL:" + ex.Message;
}
return theResule;
}
/// <summary>
/// With Attachment
/// </summary>
/// <param name="MsgTo"></param>
/// <param name="Subject"></param>
/// <param name="MsgBody"></param>
/// <param name="AttachedFile"></param>
/// <returns></returns>
public static string SendEmail(String MsgTo, String Subject, String MsgBody, byte[] AttachedFile, string AttachedFileName)
{
if (String.IsNullOrEmpty(MsgTo.Trim()))
{
return "FAIL:Message To is required.";
}
if (!MsgTo.Trim().Contains("@"))
{
return "FAIL:Enter a proper Email Address.";
}
if (!MsgTo.Trim().Contains("."))
{
return "FAIL:Enter a proper Email Address.";
}
if (String.IsNullOrEmpty(MsgBody.Trim()) && String.IsNullOrEmpty(Subject.Trim()))
{
return "FAIL:Subject/Message Body is required.";
}
string MsgFrom, Password, theResule;
//MsgFrom = "momsfoodcourt.mfc@gmail.com";//ConfigurationManager.AppSettings["Email"].ToString();
//Password = "momsfoodcourt*123";//ConfigurationManager.AppSettings["EmailPassword"].ToString();
//MsgFrom = "info@momsfoodcourt.com";
//Password = "cnet*123";
MsgFrom = ConfigurationManager.AppSettings["Email"].ToString();
Password = ConfigurationManager.AppSettings["EmailPassword"].ToString();
try
{
using (MailMessage mm = new MailMessage(MsgFrom, MsgTo))
{
mm.Subject = Subject;
mm.Body = GetHeaderOnBody(MsgBody);
mm.IsBodyHtml = true;
mm.Attachments.Add(new Attachment(new MemoryStream(AttachedFile), AttachedFileName));
SmtpClient smtp = new SmtpClient();
//smtp.Host = "smtp.gmail.com";
smtp.Host = "mail.momsfoodcourt.com";
//smtp.EnableSsl = true;
smtp.EnableSsl = false;
NetworkCredential NetworkCred = new NetworkCredential(MsgFrom, Password);
smtp.UseDefaultCredentials = false;
smtp.Credentials = NetworkCred;
//smtp.Port = 587;
smtp.Port = 25;
smtp.Send(mm);
theResule = "SUCCESS:";
}
}
catch (Exception ex)
{
theResule = "FAIL:" + ex.Message;
}
return theResule;
}
private static string GetHeaderOnBody(string Body)
{
System.Text.StringBuilder MsgBody = new System.Text.StringBuilder();
MsgBody.Append(@"<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<title>Reset Your Password</title>
<style type='text/css'>
.header{
font-family: Arial, Helvetica, sans-serif;
color: #555;
background: #e4e4e3 ;
font-size: 12px;
padding:10px;
border-radius:10px;
box-shadow:0 -4px 10px -6px #ccc inset;
}
.mtbl{background-color: #fff; border-radius:10px;padding:20px; margin-top:10px;}
.button a{
font-family: Verdana, Arial, sans-serif;
display: inline-block;
background: #32c1e4 url('http://mfc.cnet-india.net/images/shortcut-button-bg.gif') top left repeat-x !important;
border: 1px solid #32c1e4 !important;
padding:0px 7px 2px 7px !important;
font-size: 12px !important;
cursor: pointer;
font-weight:bold;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
text-decoration:none;
}
a{color:#1286cc}
a:hover {color: #000;}
.hdgtxt{ color:#8e816f; font:bold 14px arial;text-transform:uppercase }
</style>
</head>
<body style='background-color: Transparent; -moz-user-select: text;'>
<div style='overflow:visible;' class='msgBody_shell wrapped' id='MessageArea'>
<div style='margin: 5px; color: #666;'>
<div class='header'>
<div>
<a target='_blank' href='#'><img width='100px' alt='Moms Food Court' src='http://mfc.cnet-india.net/images/mfc-logo.png'></a>
</div>
<div class='mtbl'>");
MsgBody.Append(Body);
MsgBody.Append(@" <div>
copyright © 2016 <a target='_blank' href='http://mfc.cnet-india.net/'>www.momsfoodcourt.com</a></div></div>
</div>
</div>
</div>
</body>
</html>
");
return MsgBody.ToString();
}
#endregion
#region "XML Functions"
public static System.Xml.XmlWriter InitXmlWriter(out StringBuilder str)
{
System.Xml.XmlWriterSettings wsetting = new System.Xml.XmlWriterSettings();
wsetting.NewLineOnAttributes = true;
wsetting.Indent = true;
wsetting.OmitXmlDeclaration = true;
wsetting.Encoding = Encoding.UTF8;
wsetting.CloseOutput = false;
str = new StringBuilder();
return System.Xml.XmlWriter.Create(str, wsetting);
}
public static string PrepareXml(ArrayList arylst)
{
System.Xml.XmlWriterSettings wsetting = new System.Xml.XmlWriterSettings();
wsetting.NewLineOnAttributes = true;
wsetting.Indent = true;
wsetting.OmitXmlDeclaration = true;
wsetting.Encoding = Encoding.UTF8;
wsetting.CloseOutput = false;
StringBuilder str = new StringBuilder();
System.Xml.XmlWriter xx = System.Xml.XmlWriter.Create(str, wsetting);
xx.WriteStartDocument();
xx.WriteStartElement("ROOT");
xx.WriteStartElement("ROWS");
//---GetXML-------//
foreach (System.Web.UI.WebControls.ListItem li in arylst)
{
xx.WriteAttributeString(li.Text, li.Value);
}
xx.WriteEndElement();
xx.Close();
return str.ToString();
}
#endregion
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web.UI;
using System.IO;
using System.Web.Security;
using System.Collections.Specialized;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using ASPSnippets.SmsAPI;
using System.Net.Mail;
using System.Net;
public class CommonMethods
{
#region "Short Query Functions"
public static string GetTextData(string SqlStr)
{
string functionReturnValue = null;
SqlConnection OAF = default(SqlConnection);
OAF = new SqlConnection(ConfigurationManager.ConnectionStrings["SCon"].ConnectionString);
SqlCommand myCom = new SqlCommand(SqlStr, OAF);
myCom.Connection.Open();
if ((myCom.ExecuteScalar() == null))
{
functionReturnValue = string.Empty;
}
else
{
functionReturnValue = myCom.ExecuteScalar().ToString();
}
myCom.Connection.Close();
myCom.Dispose();
OAF.Close();
OAF.Dispose();
return functionReturnValue;
}
public static void Execute_Query(string SqlStr)
{
SqlConnection OAF = default(SqlConnection);
OAF = new SqlConnection(ConfigurationManager.ConnectionStrings["SCon"].ConnectionString);
SqlCommand myCom = new SqlCommand(SqlStr, OAF);
myCom.Connection.Open();
myCom.ExecuteNonQuery();
myCom.Connection.Close();
myCom.Dispose();
OAF.Close();
OAF.Dispose();
}
public static long GetIntData(string SqlStr)
{
long functionReturnValue = 0;
SqlConnection OAF = default(SqlConnection);
OAF = new SqlConnection(ConfigurationManager.ConnectionStrings["SCon"].ConnectionString);
SqlCommand myCom = new SqlCommand(SqlStr, OAF);
myCom.Connection.Open();
if (Convert.IsDBNull(myCom.ExecuteScalar()))
{
functionReturnValue = 0;
}
else
{
functionReturnValue = Convert.ToInt32(myCom.ExecuteScalar());
}
myCom.Connection.Close();
myCom.Dispose();
OAF.Close();
OAF.Dispose();
return functionReturnValue;
}
#endregion
#region "Input Data Velidation Functions"
public static Control[] MyControls(Control root)
{
List<Control> list = new List<Control>();
list.Add(root);
if (root.HasControls())
{
foreach (Control control in root.Controls)
{
list.AddRange(MyControls(control));
}
}
return list.ToArray();
}
public static string Validate_String(string Input_String)
{
Input_String = Input_String.Trim();
string[] Black_Listed = {
"--",
";",
"/*",
"*/",
"char",
"nchar",
"varchar",
"nvarchar",
"alter",
"begin",
"cast",
"create",
"cursor",
"declare",
"delete",
"drop",
"exec",
"execute",
"fetch",
"insert",
"kill",
"open",
"select",
"sys",
"sysobjects",
"syscolumns",
" table",
"update",
"|",
"&",
";",
"$",
"%",
"'",
"\"\"",
"\\'",
"\\",
"<>",
"()",
"+",
",",
"\\\""
};
string Villain = null;
foreach (string Villain_loopVariable in Black_Listed)
{
Villain = Villain_loopVariable;
if (Input_String.Contains(Villain))
{
Input_String = Input_String.Replace(Villain, "");
}
}
return Input_String;
}
public static bool IsValidString(string Input_String)
{
bool WhatToReturn = true;
Input_String = Input_String.Trim();
string[] Black_Listed = {
"--",
";",
"/*",
"*/",
"char",
"nchar",
"varchar",
"nvarchar",
"alter",
"script",
"begin",
"cast",
"create",
"cursor",
"declare",
"delete",
"drop",
"exec",
"execute",
"fetch",
"insert",
"kill",
"open",
"select",
"sys",
"sysobjects",
"syscolumns",
"table",
"update",
"<applet>",
"<body>",
"<embed>",
"<frame>",
"<script>",
"<frameset>",
"<html>",
"<iframe>",
"<img>",
"<style>",
"<layer>",
"<link>",
"<ilayer>",
"<meta>",
"<object>",
"table",
"update",
"|",
"&",
";",
"$",
"%",
"'",
"\"\"",
"\\'",
"\\",
"<>",
"()",
"+",
",",
"\\\""
};
string Villain = null;
foreach (string Villain_loopVariable in Black_Listed)
{
Villain = Villain_loopVariable;
if (Input_String.Contains(Villain))
{
WhatToReturn = false;
break; // TODO: might not be correct. Was : Exit For
}
}
return WhatToReturn;
}
#endregion
#region "Uploaded File Velidation Functions"
public static bool CheckFileType(string FileName, string CheckType)
{
string extension = Path.GetExtension(FileName).ToLower().Substring(1, Path.GetExtension(FileName).Length - 1);
switch (CheckType.ToUpper())
{
case "ALL":
switch (extension)
{
case "txt":
case "doc":
case "xls":
case "pdf":
case "gif":
case "tiff":
case "jpeg":
case "jpg":
case "ppt":
case "zip":
case "png":
case "rar": return true;
default: return false;
}
case "ONLYIMAGES":
switch (extension)
{
case "gif":
case "tiff":
case "jpeg":
case "jpg":
case "png": return true;
default: return false;
}
case "PDFONLY":
switch (extension)
{
case "pdf": return true;
default: return false;
}
case "PDF":
switch (extension)
{
case "pdf": return true;
default: return false;
}
case "JPG":
switch (extension)
{
case "jpeg":
case "jpg": return true;
default: return false;
}
case "JPEG":
switch (extension)
{
case "jpeg":
case "jpg": return true;
default: return false;
}
case "GIF":
switch (extension)
{
case "gif": return true;
default: return false;
}
case "TIFF":
switch (extension)
{
case "tiff": return true;
default: return false;
}
case "PNG":
switch (extension)
{
case "png": return true;
default: return false;
}
case "TXT":
switch (extension)
{
case "txt": return true;
default: return false;
}
case "DOC":
switch (extension)
{
case "doc": return true;
default: return false;
}
case "XLS":
switch (extension)
{
case "xls": return true;
default: return false;
}
case "PPT":
switch (extension)
{
case "ppt": return true;
default: return false;
}
case "ZIP":
switch (extension)
{
case "zip": return true;
default: return false;
}
case "RAR":
switch (extension)
{
case "rar": return true;
default: return false;
}
default:
return false;
}
}
public static string GetContentType(string extension)
{
switch (extension)
{
case "txt":
return "text/plain";
case "doc":
return "application/msword";
case "xls":
return "application/x-msexcel";
case "pdf":
return "application/pdf";
case "gif":
return "image/gif";
case "tiff":
return "image/tiff";
case "jpeg":
return "image/jpeg";
case "jpg":
return "image/jpeg";
case "png":
return "image/png";
case "pff":
return "application/ms-powerpoint";
case "zip":
return "application/zip";
default:
return "";
}
}
public bool IsFileValid(string ContentType)
{
string[] allowedImageTyps = {
"image/gif",
"image/pjpeg",
"image/bmp",
"image/x-png",
"application/pdf"
};
StringCollection imageTypes = new StringCollection();
imageTypes.AddRange(allowedImageTyps);
if (imageTypes.Contains(ContentType))
{
return true;
}
else
{
return false;
}
}
public static bool CheckFileHeader(byte[] buffer, string extension)
{
ASCIIEncoding enc = new System.Text.ASCIIEncoding();
string header = enc.GetString(buffer);
switch (extension)
{
case "pdf":
return header.StartsWith("%PDF-");
case "jpg":
return header.StartsWith("????") && !header.StartsWith("?????");
case "jpeg":
return header.StartsWith("????") && !header.StartsWith("?????");
case "txt":
return header.StartsWith("??") && !header.StartsWith("???");
case "doc":
return header.StartsWith("??_???_?");
case "xls":
return header.StartsWith("??_???_?");
case "png":
return header.StartsWith(".PNG") || header.StartsWith("?PNG");
case "tiff":
return header.StartsWith("MM*");
case "gif":
return header.StartsWith("GIF87a") || header.StartsWith("GIF89a");
case "exe":
return header.StartsWith("MZ");
case "zip":
return header.StartsWith("PK");
case "rar":
return header.StartsWith("Rar!");
case "ico":
return header.StartsWith("\\0\\0");
case "mp3":
return header.StartsWith("ID3");
case "kml":
return (header.StartsWith("<?xml") & !header.EndsWith("</kml>"));
case "kmz":
return header.StartsWith("PK");
case "OnlyImages":
if (header.StartsWith("????") && !header.StartsWith("?????"))
{
return true;
}
else if (header.StartsWith(".PNG") || header.StartsWith("?PNG"))
{
return true;
}
else if (header.StartsWith("MM*"))
{
return true;
}
else if (header.StartsWith("MM*"))
{
return true;
}
else if (header.StartsWith("GIF87a") || header.StartsWith("GIF89a"))
{
return true;
}
else if (header.StartsWith("\\0\\0"))
{
return true;
}
else
{
return false;
}
default:
return false;
}
}
#endregion
#region "Crop Image Functions"
public static byte[] CropImage(byte[] FileInBytes, int X, int Y, int W, int H)
{
using (System.IO.Stream ss = new System.IO.MemoryStream(FileInBytes))
{
using (System.Drawing.Image image = System.Drawing.Bitmap.FromStream(ss))
{
using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(W, H, image.PixelFormat))
{
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp))
{
g.DrawImage(image, new System.Drawing.Rectangle(0, 0, W, H), new System.Drawing.Rectangle(X, Y, W, H), System.Drawing.GraphicsUnit.Pixel);
}
//Save the file and reload to the control
using (System.IO.MemoryStream mm = new System.IO.MemoryStream())
{
bmp.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
FileInBytes = mm.ToArray();
}
}
}
}
return FileInBytes;
}
#endregion
#region "Membership User Functions"
public static string GetUserID()
{
MembershipUser MemUser = default(MembershipUser);
MemUser = Membership.GetUser();
return MemUser.ProviderUserKey.ToString();
}
public static string GetUserName()
{
MembershipUser MemUser = default(MembershipUser);
MemUser = Membership.GetUser();
return MemUser.UserName.ToString();
}
public static string GetErrorMessage(MembershipCreateStatus status)
{
switch (status)
{
case MembershipCreateStatus.DuplicateUserName:
return "Username already exists. Please enter a different user name.";
case MembershipCreateStatus.DuplicateEmail:
return "A username for that e-mail address already exists. Please enter a different e-mail address.";
case MembershipCreateStatus.InvalidPassword:
return "The password provided is invalid. Please enter a valid password value.";
case MembershipCreateStatus.InvalidEmail:
return "The e-mail address provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidAnswer:
return "The password retrieval answer provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidQuestion:
return "The password retrieval question provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.ProviderError:
return "The authentication provider Returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
case MembershipCreateStatus.UserRejected:
return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
default:
return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
}
}
#endregion
#region "Converter Functions"
public static string UniCode2ISCII(string S)
{
if (S == null)
{
return null;
}
try
{
Encoding encFrom = Encoding.GetEncoding(57002);
Encoding encTo = Encoding.GetEncoding(1252);
string str = S;
byte[] b = encFrom.GetBytes(str);
return encTo.GetString(b);
}
catch
{
return null;
}
}
public static byte[] HexStringToBytes(string hex)
{
int ss = 0;
string sp = "";
try
{
if (hex.Length == 0)
{
return new byte[] { 0 };
}
if (hex.Length % 2 == 1)
{
hex = "0" + hex;
}
byte[] result = new byte[hex.Length / 2];
for (int i = 0; i <= hex.Length / 2 - 1; i++)
{
ss = i;
sp = hex.Substring(2 * i, 2);
result[i] = byte.Parse(hex.Substring(2 * i, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
}
return result;
}
catch
{
return new byte[] { 0 };
}
}
public static string BytesToHexString(byte[] input)
{
StringBuilder hexString = new StringBuilder(64);
for (int i = 0; i <= input.Length - 1; i++)
{
hexString.Append(String.Format("{0:X2}", input[i]));
}
return hexString.ToString();
}
public static string BytesToDecString(byte[] input)
{
StringBuilder decString = new StringBuilder(64);
for (int i = 0; i <= input.Length - 1; i++)
{
decString.Append(String.Format((i == 0 ? "{0:D3}" : "-{0:D3}"), input[i]));
}
return decString.ToString();
}
public static string ASCIIBytesToString(byte[] input)
{
System.Text.ASCIIEncoding enc = new ASCIIEncoding();
return enc.GetString(input);
}
public static string UTF16BytesToString(byte[] input)
{
System.Text.UnicodeEncoding enc = new UnicodeEncoding();
return enc.GetString(input);
}
public static string UTF8BytesToString(byte[] input)
{
System.Text.UTF8Encoding enc = new UTF8Encoding();
return enc.GetString(input);
}
public static string ToBase64(byte[] input)
{
return Convert.ToBase64String(input);
}
public static byte[] FromBase64(string base64)
{
return Convert.FromBase64String(base64);
}
public static string DecryptString(string EncryptedString)
{
byte[] bytes = Convert.FromBase64String(EncryptedString);
return Encoding.UTF8.GetString(bytes);
}
public static string EncryptString(string PlainString)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(PlainString));
}
#endregion
#region "Genreate Password Function"
public static string GeneratePassword()
{
Random r = new Random();
string abC = "abcdefghkmnpqrstuvwxyz";
string Ints = "23456789";
string[] CharPart = new string[3];
string[] IntPart = new string[3];
string ThePassword = null;
CharPart[0] = abC.Substring(r.Next(0, 21), 1);
CharPart[1] = abC.Substring(r.Next(0, 21), 1);
CharPart[2] = abC.Substring(r.Next(0, 21), 1);
IntPart[0] = Ints.Substring(r.Next(0, 7), 1);
IntPart[1] = Ints.Substring(r.Next(0, 7), 1);
IntPart[2] = Ints.Substring(r.Next(0, 7), 1);
ThePassword = CharPart[0] + CharPart[1] + CharPart[2] + "*" + IntPart[0] + IntPart[1] + IntPart[2];
return ThePassword;
}
#endregion
#region "Send SMS/Email"
public static string SendSMS(String MobileNo, String Message)
{
Int64 MN;
if (!Int64.TryParse(MobileNo, out MN))
{
return "FAIL:Enter a proper Mobile Number.";
}
if (MobileNo.Length != 10)
{
return "FAIL:Enter a proper Mobile Number.";
}
if (String.IsNullOrEmpty(Message.Trim()))
{
return "FAIL:Message is required.";
}
string UserName, Password, MashapeKey;
UserName = ConfigurationManager.AppSettings["SMSUserName"].ToString();
Password = ConfigurationManager.AppSettings["SMSPassword"].ToString();
MashapeKey = ConfigurationManager.AppSettings["SMSMashapeKey"].ToString();
SMS.APIType = SMSGateway.Site2SMS;
SMS.MashapeKey = MashapeKey;
SMS.Username = UserName;
SMS.Password = Password;
try
{
SMS.SendSms(MobileNo.Trim(), Message.Trim());
return "SUCCESS:";
}
catch (Exception ex)
{
return "FAIL:Mobile-" + ex.Message;
}
}
public static string SendBulkSMS(List<string> MobileNos, String Message)
{
if (String.IsNullOrEmpty(Message.Trim()))
{
return "FAIL:Message is required.";
}
string UserName, Password, MashapeKey;
UserName = ConfigurationManager.AppSettings["SMSUserName"].ToString();
Password = ConfigurationManager.AppSettings["SMSPassword"].ToString();
MashapeKey = ConfigurationManager.AppSettings["SMSMashapeKey"].ToString();
SMS.APIType = SMSGateway.Site2SMS;
SMS.MashapeKey = MashapeKey;
SMS.Username = UserName;
SMS.Password = Password;
try
{
SMS.SendSms(MobileNos, Message.Trim());
return "SUCCESS:";
}
catch (Exception ex)
{
return "FAIL:" + ex.Message;
}
}
public static string SendEmail(String MsgTo, String Subject, String MsgBody, String MsgCCTo)
{
if (String.IsNullOrEmpty(MsgTo.Trim()))
{
return "FAIL:Message To is required.";
}
if (!MsgTo.Trim().Contains("@"))
{
return "FAIL:Enter a proper Email Address.";
}
if (!MsgTo.Trim().Contains("."))
{
return "FAIL:Enter a proper Email Address.";
}
if (String.IsNullOrEmpty(MsgBody.Trim()) && String.IsNullOrEmpty(Subject.Trim()))
{
return "FAIL:Subject/Message Body is required.";
}
if (String.IsNullOrEmpty(MsgCCTo.Trim()))
{
return "FAIL:CC to is required.";
}
if (!MsgCCTo.Trim().Contains("@"))
{
return "FAIL:Enter a proper CC Email Address.";
}
if (!MsgCCTo.Trim().Contains("."))
{
return "FAIL:Enter a proper CC Email Address.";
}
string MsgFrom, Password, theResule;
//MsgFrom = "momsfoodcourt.mfc@gmail.com";//ConfigurationManager.AppSettings["Email"].ToString();
//Password = "momsfoodcourt*123";//ConfigurationManager.AppSettings["EmailPassword"].ToString();
//MsgFrom = "info@momsfoodcourt.com";
//Password = "cnet*123";
MsgFrom = ConfigurationManager.AppSettings["Email"].ToString();
Password = ConfigurationManager.AppSettings["EmailPassword"].ToString();
try
{
using (MailMessage mm = new MailMessage(MsgFrom, MsgTo))
{
mm.Subject = Subject;
mm.Body = GetHeaderOnBody(MsgBody);
mm.CC.Add(MsgCCTo);
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
//smtp.Host = "smtp.gmail.com";
smtp.Host = "mail.momsfoodcourt.com";
//smtp.EnableSsl = true;
smtp.EnableSsl = false;
NetworkCredential NetworkCred = new NetworkCredential(MsgFrom, Password);
smtp.UseDefaultCredentials = false;
smtp.Credentials = NetworkCred;
//smtp.Port = 587;
smtp.Port = 25;
smtp.Send(mm);
theResule = "SUCCESS:";
}
}
catch (Exception ex)
{
theResule = "FAIL:" + ex.Message;
}
return theResule;
}
public static string SendEmail(String MsgTo, String Subject, String MsgBody)
{
if (String.IsNullOrEmpty(MsgTo.Trim()))
{
return "FAIL:Message To is required.";
}
if (!MsgTo.Trim().Contains("@"))
{
return "FAIL:Enter a proper Email Address.";
}
if (!MsgTo.Trim().Contains("."))
{
return "FAIL:Enter a proper Email Address.";
}
if (String.IsNullOrEmpty(MsgBody.Trim()) && String.IsNullOrEmpty(Subject.Trim()))
{
return "FAIL:Subject/Message Body is required.";
}
string MsgFrom, Password, theResule;
//MsgFrom = "momsfoodcourt.mfc@gmail.com";//ConfigurationManager.AppSettings["Email"].ToString();
//Password = "momsfoodcourt*123";//ConfigurationManager.AppSettings["EmailPassword"].ToString();
MsgFrom = ConfigurationManager.AppSettings["Email"].ToString();
Password = ConfigurationManager.AppSettings["EmailPassword"].ToString();
//MsgFrom = "info@momsfoodcourt.com";
//Password = "cnet*123";
try
{
using (MailMessage mm = new MailMessage(MsgFrom, MsgTo))
{
mm.Subject = Subject;
mm.Body = GetHeaderOnBody(MsgBody);
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
// smtp.Host = "smtp.gmail.com";
smtp.Host = "mail.momsfoodcourt.com";
//smtp.EnableSsl = true;
smtp.EnableSsl = false;
NetworkCredential NetworkCred = new NetworkCredential(MsgFrom, Password);
smtp.UseDefaultCredentials = false;
smtp.Credentials = NetworkCred;
//smtp.Port = 587;
smtp.Port = 25;
smtp.Send(mm);
theResule = "SUCCESS:";
}
}
catch (Exception ex)
{
theResule = "FAIL:" + ex.Message;
}
return theResule;
}
/// <summary>
/// With Attachment
/// </summary>
/// <param name="MsgTo"></param>
/// <param name="Subject"></param>
/// <param name="MsgBody"></param>
/// <param name="MsgCCTo"></param>
/// <param name="AttachedFile"></param>
/// <param name="AttachedFileName"></param>
/// <returns></returns>
public static string SendEmail(String MsgTo, String Subject, String MsgBody, String MsgCCTo, byte[] AttachedFile, string AttachedFileName)
{
if (String.IsNullOrEmpty(MsgTo.Trim()))
{
return "FAIL:Message To is required.";
}
if (!MsgTo.Trim().Contains("@"))
{
return "FAIL:Enter a proper Email Address.";
}
if (!MsgTo.Trim().Contains("."))
{
return "FAIL:Enter a proper Email Address.";
}
if (String.IsNullOrEmpty(MsgBody.Trim()) && String.IsNullOrEmpty(Subject.Trim()))
{
return "FAIL:Subject/Message Body is required.";
}
if (String.IsNullOrEmpty(MsgCCTo.Trim()))
{
return "FAIL:CC to is required.";
}
if (!MsgCCTo.Trim().Contains("@"))
{
return "FAIL:Enter a proper CC Email Address.";
}
if (!MsgCCTo.Trim().Contains("."))
{
return "FAIL:Enter a proper CC Email Address.";
}
string MsgFrom, Password, theResule;
//MsgFrom = "momsfoodcourt.mfc@gmail.com";//ConfigurationManager.AppSettings["Email"].ToString();
//Password = "momsfoodcourt*123";//ConfigurationManager.AppSettings["EmailPassword"].ToString();
//MsgFrom = "info@momsfoodcourt.com";
//Password = "cnet*123";
MsgFrom = ConfigurationManager.AppSettings["Email"].ToString();
Password = ConfigurationManager.AppSettings["EmailPassword"].ToString();
try
{
using (MailMessage mm = new MailMessage(MsgFrom, MsgTo))
{
mm.Subject = Subject;
mm.Body = GetHeaderOnBody(MsgBody);
mm.CC.Add(MsgCCTo);
mm.IsBodyHtml = true;
mm.Attachments.Add(new Attachment(new MemoryStream(AttachedFile), AttachedFileName));
SmtpClient smtp = new SmtpClient();
//smtp.Host = "smtp.gmail.com";
smtp.Host = "mail.momsfoodcourt.com";
//smtp.EnableSsl = true;
smtp.EnableSsl = false;
NetworkCredential NetworkCred = new NetworkCredential(MsgFrom, Password);
smtp.UseDefaultCredentials = false;
smtp.Credentials = NetworkCred;
//smtp.Port = 587;
smtp.Port = 25;
smtp.Send(mm);
theResule = "SUCCESS:";
}
}
catch (Exception ex)
{
theResule = "FAIL:" + ex.Message;
}
return theResule;
}
/// <summary>
/// With Attachment
/// </summary>
/// <param name="MsgTo"></param>
/// <param name="Subject"></param>
/// <param name="MsgBody"></param>
/// <param name="AttachedFile"></param>
/// <returns></returns>
public static string SendEmail(String MsgTo, String Subject, String MsgBody, byte[] AttachedFile, string AttachedFileName)
{
if (String.IsNullOrEmpty(MsgTo.Trim()))
{
return "FAIL:Message To is required.";
}
if (!MsgTo.Trim().Contains("@"))
{
return "FAIL:Enter a proper Email Address.";
}
if (!MsgTo.Trim().Contains("."))
{
return "FAIL:Enter a proper Email Address.";
}
if (String.IsNullOrEmpty(MsgBody.Trim()) && String.IsNullOrEmpty(Subject.Trim()))
{
return "FAIL:Subject/Message Body is required.";
}
string MsgFrom, Password, theResule;
//MsgFrom = "momsfoodcourt.mfc@gmail.com";//ConfigurationManager.AppSettings["Email"].ToString();
//Password = "momsfoodcourt*123";//ConfigurationManager.AppSettings["EmailPassword"].ToString();
//MsgFrom = "info@momsfoodcourt.com";
//Password = "cnet*123";
MsgFrom = ConfigurationManager.AppSettings["Email"].ToString();
Password = ConfigurationManager.AppSettings["EmailPassword"].ToString();
try
{
using (MailMessage mm = new MailMessage(MsgFrom, MsgTo))
{
mm.Subject = Subject;
mm.Body = GetHeaderOnBody(MsgBody);
mm.IsBodyHtml = true;
mm.Attachments.Add(new Attachment(new MemoryStream(AttachedFile), AttachedFileName));
SmtpClient smtp = new SmtpClient();
//smtp.Host = "smtp.gmail.com";
smtp.Host = "mail.momsfoodcourt.com";
//smtp.EnableSsl = true;
smtp.EnableSsl = false;
NetworkCredential NetworkCred = new NetworkCredential(MsgFrom, Password);
smtp.UseDefaultCredentials = false;
smtp.Credentials = NetworkCred;
//smtp.Port = 587;
smtp.Port = 25;
smtp.Send(mm);
theResule = "SUCCESS:";
}
}
catch (Exception ex)
{
theResule = "FAIL:" + ex.Message;
}
return theResule;
}
private static string GetHeaderOnBody(string Body)
{
System.Text.StringBuilder MsgBody = new System.Text.StringBuilder();
MsgBody.Append(@"<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<title>Reset Your Password</title>
<style type='text/css'>
.header{
font-family: Arial, Helvetica, sans-serif;
color: #555;
background: #e4e4e3 ;
font-size: 12px;
padding:10px;
border-radius:10px;
box-shadow:0 -4px 10px -6px #ccc inset;
}
.mtbl{background-color: #fff; border-radius:10px;padding:20px; margin-top:10px;}
.button a{
font-family: Verdana, Arial, sans-serif;
display: inline-block;
background: #32c1e4 url('http://mfc.cnet-india.net/images/shortcut-button-bg.gif') top left repeat-x !important;
border: 1px solid #32c1e4 !important;
padding:0px 7px 2px 7px !important;
font-size: 12px !important;
cursor: pointer;
font-weight:bold;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
text-decoration:none;
}
a{color:#1286cc}
a:hover {color: #000;}
.hdgtxt{ color:#8e816f; font:bold 14px arial;text-transform:uppercase }
</style>
</head>
<body style='background-color: Transparent; -moz-user-select: text;'>
<div style='overflow:visible;' class='msgBody_shell wrapped' id='MessageArea'>
<div style='margin: 5px; color: #666;'>
<div class='header'>
<div>
<a target='_blank' href='#'><img width='100px' alt='Moms Food Court' src='http://mfc.cnet-india.net/images/mfc-logo.png'></a>
</div>
<div class='mtbl'>");
MsgBody.Append(Body);
MsgBody.Append(@" <div>
copyright © 2016 <a target='_blank' href='http://mfc.cnet-india.net/'>www.momsfoodcourt.com</a></div></div>
</div>
</div>
</div>
</body>
</html>
");
return MsgBody.ToString();
}
#endregion
#region "XML Functions"
public static System.Xml.XmlWriter InitXmlWriter(out StringBuilder str)
{
System.Xml.XmlWriterSettings wsetting = new System.Xml.XmlWriterSettings();
wsetting.NewLineOnAttributes = true;
wsetting.Indent = true;
wsetting.OmitXmlDeclaration = true;
wsetting.Encoding = Encoding.UTF8;
wsetting.CloseOutput = false;
str = new StringBuilder();
return System.Xml.XmlWriter.Create(str, wsetting);
}
public static string PrepareXml(ArrayList arylst)
{
System.Xml.XmlWriterSettings wsetting = new System.Xml.XmlWriterSettings();
wsetting.NewLineOnAttributes = true;
wsetting.Indent = true;
wsetting.OmitXmlDeclaration = true;
wsetting.Encoding = Encoding.UTF8;
wsetting.CloseOutput = false;
StringBuilder str = new StringBuilder();
System.Xml.XmlWriter xx = System.Xml.XmlWriter.Create(str, wsetting);
xx.WriteStartDocument();
xx.WriteStartElement("ROOT");
xx.WriteStartElement("ROWS");
//---GetXML-------//
foreach (System.Web.UI.WebControls.ListItem li in arylst)
{
xx.WriteAttributeString(li.Text, li.Value);
}
xx.WriteEndElement();
xx.Close();
return str.ToString();
}
#endregion
}
Comments
Post a Comment