using Microsoft.Ajax.Utilities;
using StudyAbroadMVCAdmin.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
namespace StudyAbroadMVCAdmin.Models.Function
{
public class GernalFunction
{
public static string ImageCroping(string crop, string Filepath, bool thumbnail)
{
if (!String.IsNullOrEmpty(crop))
{
var fileName = "";
var imageStr64 = crop;
var imgCode = imageStr64.Split(',');
var bytes = Convert.FromBase64String(imgCode[1]);
using (var stream = new MemoryStream(bytes))
{
using (var img = System.Drawing.Image.FromStream(stream))
{
var filename = "";
var fileext = "";
if (imgCode.Contains("png"))
{
filename = "Image" + DateTime.UtcNow;
fileext = ".png";
}
else
{
filename = "Image" + DateTime.UtcNow;
fileext = ".jpg";
}
string fileNameNew = filename;
fileNameNew = RemoveSpecialCharacters(fileNameNew);
fileNameNew = fileNameNew.Replace(" ", "");
var path = HttpContext.Current.Server.MapPath(Filepath);
var ext = Path.GetExtension(filename);
var i = 0;
while (File.Exists(path + fileNameNew + fileext))
{
i++;
fileNameNew = Path.GetFileNameWithoutExtension(filename);
fileNameNew += i;
}
fileName = fileNameNew + fileext;
var filePath = HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath + Filepath + fileName);
File.WriteAllBytes(filePath, bytes);
if (thumbnail == true)
{
string ThumbImgName = fileName.Replace("Image", "Thumb");
Resize_Image_Thumb(filePath, fileName, 63, 51, ThumbImgName);
}
}
}
return fileName;
}
else
{
return null;
}
}
public static void Resize_Image_Thumb(string filePath, string srcImgName, int newWidth, int newHeight, string ThumbImgName)
{
//Get Destinatino Path of image
string newImgName = null;
string newImagePath = null;
string imgName = null;
string imgExt = null;
string[] NameExtArray = srcImgName.Split(new char[] { '.' });
imgName = NameExtArray[0];
imgExt = NameExtArray[1];
newImgName = ThumbImgName;
newImagePath = filePath.Replace(srcImgName, ThumbImgName);
Image imgPhoto = Image.FromFile(filePath);
int sourceWidth = 0;
int sourceHeight = 0;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
double nPercent = 0;
double nPercentW = 0;
double nPercentH = 0;
sourceWidth = imgPhoto.Width;
sourceHeight = imgPhoto.Height;
sourceX = 0;
sourceY = 0;
destX = 0;
destY = 0;
nPercent = 0;
nPercentW = 0;
nPercentH = 0;
nPercentW = (Convert.ToDouble(newWidth) / Convert.ToDouble(sourceWidth));
nPercentH = (Convert.ToDouble(newHeight) / Convert.ToDouble(sourceHeight));
if ((nPercentH < nPercentW))
{
nPercent = nPercentW;
destY = Convert.ToInt32(((newHeight - (sourceHeight * nPercent)) / 2));
}
else
{
nPercent = nPercentH;
destX = Convert.ToInt32(((newWidth - (sourceWidth * nPercent)) / 2));
}
int destWidth = 0;
int destHeight = 0;
destWidth = Convert.ToInt32((sourceWidth * nPercent));
destHeight = Convert.ToInt32((sourceHeight * nPercent));
Bitmap bmPhoto = null;
bmPhoto = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
Graphics grPhoto = null;
grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto, new Rectangle(destX, destY, destWidth, destHeight), new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel);
grPhoto.Dispose();
bmPhoto.Save(newImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
bmPhoto.Dispose();
imgPhoto.Dispose();
}
public void SetCookie(EndUser user)
{
HttpCookie AdminCookie = new HttpCookie("AdminCookies");
AdminCookie.Values["UserName"] = user.user_name.ToString();
AdminCookie.Values["Password"] = user.password.ToString();
AdminCookie.Values["ID"] = user.ID.ToString();
AdminCookie.Values["IsWriter"] = "No";
HttpContext.Current.Response.SetCookie(AdminCookie);
}
public void SetCookieForWriter(EndUser user)
{
HttpCookie AdminCookie = new HttpCookie("AdminCookies");
AdminCookie.Values["UserName"] = user.user_name.ToString();
AdminCookie.Values["Password"] = user.password.ToString();
AdminCookie.Values["ID"] = user.ID.ToString();
AdminCookie.Values["IsWriter"] = "Yes";
HttpContext.Current.Response.SetCookie(AdminCookie);
}
public void CheckAdminLogin()
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["AdminCookies"];
if (cookie == null || String.IsNullOrEmpty(Convert.ToString(cookie)))
{
HttpContext.Current.Response.Redirect("/User/Login");
}
else if (cookie.Values["IsWriter"] == "Yes")
{
HttpCookie Writercookie = HttpContext.Current.Request.Cookies["WriterCookie"];
if (Writercookie != null)
{
if (Writercookie.Values["Writer"] == "Writer")
{
HttpContext.Current.Response.Cookies.Remove("WriterCookie");
Writercookie.Expires = DateTime.Now.AddDays(-10);
Writercookie.Value = null;
HttpContext.Current.Response.SetCookie(Writercookie);
}
}
else
{
HttpContext.Current.Response.Redirect("/User/Login");
}
}
else if (cookie.Values["Password"] == "-")
{
string url = "/User/LockScreen?ID=" + cookie.Values["ID"].ToString();
HttpContext.Current.Response.Redirect(url);
}
}
public void CheckAdminLoginForWriter()
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["AdminCookies"];
if (cookie == null || String.IsNullOrEmpty(Convert.ToString(cookie)) )
{
HttpContext.Current.Response.Redirect("/User/Login");
}
else if (cookie.Values["IsWriter"] == "No")
{
HttpContext.Current.Response.Redirect("/User/Login");
}
else if (cookie.Values["Password"] == "-")
{
string url = "/User/LockScreen?ID=" + cookie.Values["ID"].ToString();
HttpContext.Current.Response.Redirect(url);
}
else
{
HttpCookie CheckWriterCookie = HttpContext.Current.Request.Cookies["WriterCookie"];
if (CheckWriterCookie == null)
{
HttpCookie AdminCookie = new HttpCookie("WriterCookie");
AdminCookie.Values["Writer"] = "Writer";
HttpContext.Current.Response.SetCookie(AdminCookie);
}
}
}
public SelectList CitiesList()
{
var CategoryList = new SelectList(new CityModel().GetAll().Select(x => new { x.ID, x.cityName }).OrderBy(x => x.cityName).ToList(), "ID", "cityName");
return CategoryList;
}
public SelectList TestList()
{
var TestList = new SelectList(new TestModel().GetAllTest().Select(x => new { x.ID, x.Title }).ToList(), "ID", "Title");
return TestList;
}
//public SelectList BrandList()
//{
// var BrandLst = new SelectList(new BrandModel().GetAll().Select(x => new { x.ID, x.Name}).OrderBy(x => x.Name).ToList(), "ID", "Name");
// return BrandLst;
//}
//public SelectList AlbumList()
//{
// var Album = new SelectList(new AlbumModel().GetAllAlbum().Select(x => new { x.ID, x.Name }).OrderBy(x => x.Name).ToList(), "ID", "Name");
// return Album;
//}
public void EmailHostDetail(string toEmail, string fromEmail, string subject, string bodyHtml, string fileName)
{
//File Path
string filePath = AppDomain.CurrentDomain.BaseDirectory + "Resources\\Files\\";
//email sending code will appear here.
MailMessage message = new MailMessage();
SmtpClient client = new SmtpClient();
message.To.Add(new MailAddress(toEmail));
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = bodyHtml;
if (!String.IsNullOrEmpty(fileName))
{
//DOING ATTACHMENT:
Attachment data =
new Attachment(filePath + fileName,
MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);
}
string hostname = "smtp.sendgrid.net";// "smtp.gmail.com";
client.Host = hostname;
client.Port = 587;
client.EnableSsl = true;
string username = "alipk3";
string password = "Emailsend94";
message.From = new MailAddress(fromEmail, "NBK");
var basicCredentials = new System.Net.NetworkCredential(username, password);
client.Credentials = basicCredentials;
client.Send(message);
}
public static string GetHmtlContentsFromDirectory(string FileName)
{
string Result = "";
string FilePath = HttpContext.Current.Server.MapPath(FileName);
System.IO.StreamReader MyFile = new System.IO.StreamReader(FilePath);
Result = MyFile.ReadToEnd();
MyFile.Close();
MyFile.Dispose();
return Result;
}
//public static ServiceReference1.EmailsHtml GetHmtlContentsFromDirectoryc( string FileName )
//{
// ServiceReference1.EmailsHtml Result;
// string FilePath = HttpContext.Current.Server.MapPath( FileName );
// System.IO.StreamReader MyFile = new System.IO.StreamReader( FilePath );
// Result = MyFile.ReadToEnd();
// MyFile.Close();
// MyFile.Dispose();
// return Result;
//}
public static string RemoveSpecialCharacters(string input)
{
Regex r = new Regex("(?:[^a-zA-Z0-9 ]|(?<=['\"])s)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
return r.Replace(input, String.Empty);
}
public static void ResizePicture(int height, int width, string Filepath, string ResizePicPath)
{
Size newsize = new Size();
newsize.Width = width;
newsize.Height = height;
using (Bitmap newbmp = new Bitmap(newsize.Width, newsize.Height), oldbmp = Bitmap.FromFile(HttpContext.Current.Server.MapPath(Filepath)) as Bitmap)
{
using (Graphics newgraphics = Graphics.FromImage(newbmp))
{
newgraphics.DrawImage(oldbmp, 0, 0, newsize.Width, newsize.Height);
newgraphics.Save();
newbmp.Save(HttpContext.Current.Server.MapPath(ResizePicPath));
newbmp.Dispose();
newgraphics.Dispose();
}
}
}
public static string BuildBootstrapPagination(decimal numberOfPages, string url, int pageNo, int NumberofRecordsToBeShown)
{
string html = string.Empty;
html = Pagination(Convert.ToInt32(Math.Ceiling(numberOfPages / NumberofRecordsToBeShown)), pageNo, url);
return html;
}
public static string Pagination(int numberOfPages, int pageNo, string url)
{
string html = string.Empty;
pageNo = pageNo + 1;
int numericLinksCount = 9;
int noOfPages = numberOfPages;
int n = noOfPages;
if (noOfPages > 9)
{
n = 11;
}
int series = 0;
series = pageNo / 9;
if (pageNo < 10 || pageNo % 9 == 0)
{
series = pageNo / 10;
}
for (int i = 1; i <= n; i++)
{
int page = i + (9 * series);
if (page > noOfPages)
{
break;
}
if (page > 9 && i == 1)
{
int less = page - 1;
html += @"<li><a href='/" + url + "?pageno=" + less + "'>Previous</a></li>";
}
if (pageNo == page)
{
html += @"<li class='active'><a href='/" + url + "?pageno=" + page + "'>" + page + "</a></li>";
}
else
{
if (i == 10)
{
html += @"<li><a href='/" + url + "?pageno=" + page + "'> Next</a></li>";
}
if (i < 10)
{
html += @"<li><a href='/" + url + "?pageno=" + page + "'>" + page + "</a></li>";
}
}
}
return html;
}
public static string getLinks(string name, string id)
{
if (name == null)
{
name = "Company";
}
if (name.Length > 100)
{
name = name.Substring(0, 100);
}
string obj = "";
if (name != null)
{
obj = RemoveWhiteSpaces(name) + "-" + id;
}
return obj;
}
public static string RemoveWhiteSpaces(string ab)
{
var re = new Regex("[;\\\\ / .,+=!@%#^)(${}~:*?\"<>|&']");
ab = re.Replace(ab, "-");
ab = ab.Replace("--", "-").Replace("--", "-");
ab = ab.Replace(" ", "-").ToLower();
ab = ab.TrimEnd('-');
return ab;
}
public static string TrimData(string ab, int a)
{
string subab = ab;
if (subab.Length == 0) return subab;
if (subab.Length <= a) return subab;
subab = subab.Substring(0, a);
subab = subab + " ...";
return subab;
}
public static void SendEmailSMPT(string ToEmail, string Body, string Subject)
{
MailMessage message = new MailMessage();
SmtpClient client = new SmtpClient();
message.To.Add(new MailAddress(ToEmail));
message.Subject = Subject;
message.IsBodyHtml = true;
message.Body = Body;
message.From = new MailAddress(ConfigurationManager.AppSettings.Get("MailingAddress").ToString().Trim(), "StudyAbroad.pk");
//string hostname = ConfigurationManager.AppSettings.Get("MailServerName").ToString().Trim();
//client.Host = hostname;
client.Host = "64.20.42.2";
string username = ConfigurationManager.AppSettings.Get("MailingAddress").ToString().Trim();
string password = ConfigurationManager.AppSettings.Get("Password").ToString().Trim();
//message.From = new MailAddress(username);
System.Net.NetworkCredential basicCredentials = new System.Net.NetworkCredential(username, password);
client.Credentials = basicCredentials;
client.Port = 25;// 26;
client.Send(message);
}
public static string CheckImageNameDuplication(string directory, string ImageName)
{
var i = 0;
string filenewName = "";
string ext = Path.GetExtension(ImageName);
while (System.IO.File.Exists(HttpContext.Current.Server.MapPath(directory + ImageName)))
{
i++;
filenewName = Path.GetFileNameWithoutExtension(ImageName);
filenewName += i;
ImageName = filenewName + ext;
}
return ImageName;
}
public static void ResizePicture2(ImageResizeBE o)
{
Bitmap image = Bitmap.FromFile(HttpContext.Current.Server.MapPath(o.FromSource)) as Bitmap;
// Get the image's original width and height
//int originalWidth = image.Width;
//int originalHeight = image.Height;
//// To preserve the aspect ratio
//float ratioX = (float)maxWidth / (float)originalWidth;
//float ratioY = (float)maxHeight / (float)originalHeight;
//float ratio = Math.Min(ratioX, ratioY);
// New width and height based on aspect ratio
int newWidth = o.ImageWidth;//(int)(originalWidth * ratio);
int newHeight = o.ImageHeight;// (int)(originalHeight * ratio);
// Convert other formats (including CMYK) to RGB.
Bitmap newImage = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format64bppPArgb);
// Draws the image in the specified size with quality mode set to HighQuality
Graphics graphics = Graphics.FromImage(newImage);
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
// Get an ImageCodecInfo object that represents the JPEG codec.
System.Drawing.Imaging.ImageCodecInfo imageCodecInfo = GetEncoderInfo(System.Drawing.Imaging.ImageFormat.Jpeg);
// Create an Encoder object for the Quality parameter.
System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality;
// Create an EncoderParameters object.
System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
// Save the image as a JPEG file with quality level.
System.Drawing.Imaging.EncoderParameter encoderParameter = new System.Drawing.Imaging.EncoderParameter(encoder, o.ImageQuality);
encoderParameters.Param[0] = encoderParameter;
newImage.Save(HttpContext.Current.Server.MapPath(o.ToSource), imageCodecInfo, encoderParameters);
graphics.Dispose();
newImage.Dispose();
image.Dispose();
encoderParameter.Dispose();
encoderParameters.Dispose();
}
private static System.Drawing.Imaging.ImageCodecInfo GetEncoderInfo(System.Drawing.Imaging.ImageFormat format)
{
return System.Drawing.Imaging.ImageCodecInfo.GetImageDecoders().SingleOrDefault(c => c.FormatID == format.Guid);
}
public static void ResizePicture3(int height, int width, string path, string filename, string SavePath, double scaleFactor, Stream sourcePath)
{
Size newsize = new Size();
newsize.Width = width;
newsize.Height = height;
using (Bitmap newbmp = new Bitmap(newsize.Width, newsize.Height), oldbmp = Bitmap.FromFile(HttpContext.Current.Server.MapPath(path + filename)) as Bitmap)
{
using (Graphics newgraphics = Graphics.FromImage(newbmp))
{
using (var image = Image.FromStream(sourcePath))
{
newgraphics.DrawImage(oldbmp, 0, 0, newsize.Width, newsize.Height);
newgraphics.Save();
string newfilename = filename;
var newWidth = (int)(image.Width * scaleFactor);
var newHeight = (int)(image.Height * scaleFactor);
// var thumbnailImg = new Bitmap(newWidth, newHeight);
//var thumbGraph = Graphics.FromImage(newbmp);
//thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
//thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
//thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
//var thumbGraph = Graphics.FromImage(newbmp);
newgraphics.CompositingQuality = CompositingQuality.HighQuality;
newgraphics.SmoothingMode = SmoothingMode.HighQuality;
newgraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
//thumbGraph.DrawImage(image, imageRectangle);
var s = HttpContext.Current.Server.MapPath(SavePath + newfilename);
newbmp.Save(s, image.RawFormat);
newbmp.Dispose();
//thumbnailImg.Save(targetPath, image.RawFormat);
}
}
}
}
}
public static class FtpInformationOthers
{
//public static string FTPIP = "72.55.184.62";
//public static string ftpName = "ftpstudyabroad";
//public static string ftppassword = "mTrn#@$%^&937";
//public static string Path = "ftp://72.55.184.62/httpdocs/";
public static string FTPIP = "64.20.42.2";// "184.107.73.104";
public static string ftpName = "ftpstudyabroad";
public static string ftppassword = "2Nxpp2@7";
public static string Path = "ftp://184.107.73.104/httpdocs/";
}
public class FTPBE
{
public string HostFilePath { get; set; }
public string TransferFilePath { get; set; }
public string FileName { get; set; }
public bool DeleteFileAfterTransfer { get; set; }
public FTPBE()
{
}
}
public static class FtpUploads
{
public static bool FtpUploadUsingFileUpload(FTPBE o)
{
//string url = HttpContext.Current.Server.MapPath(o.HostFilePath );
string url = o.HostFilePath;
string domainname = o.TransferFilePath;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(domainname);
ftp.Credentials = new NetworkCredential(FtpInformationOthers.ftpName, FtpInformationOthers.ftppassword);
//userid and password for the ftp server to given
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Proxy = null;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
FileInfo fileInfo = new FileInfo(url);
FileStream fileStream = fileInfo.OpenRead();
try
{
int bufferLength = 2048;
byte[] buffer = new byte[bufferLength];
Stream uploadStream = ftp.GetRequestStream();
int contentLength = fileStream.Read(buffer, 0, bufferLength);
try
{
while (contentLength != 0)
{
uploadStream.Write(buffer, 0, contentLength);
contentLength = fileStream.Read(buffer, 0, bufferLength);
}
uploadStream.Close();
fileStream.Close();
uploadStream.Dispose();
fileStream.Dispose();
}
catch
{
uploadStream.Dispose();
fileStream.Dispose();
}
ftp = null;
#region DelFile
try
{
if (o.DeleteFileAfterTransfer == true)
{
System.IO.File.Delete(HttpContext.Current.Server.MapPath(o.HostFilePath + o.FileName));
}
}
catch
{
}
#endregion
return true;
}
catch
{
fileStream.Dispose();
return false;
}
}
}
}