using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Net;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Net.Mail;
using System.Configuration;
namespace StudyAbroadMVC.Models
{
public static class GenericFunctions
{
public static bool RedirectWithSlashMVC( string pattern )
{
bool isRedirect = false;
string pagename = GenericFunctions.GetPageRelativePath();
if( pagename != pattern )
{
isRedirect = true;
}
return isRedirect;
}
//public static string GetPageRelativePath()
//{
// string url = HttpContext.Current.Request.Url.AbsolutePath;
// return url;
//}
public static string ReturnDateFormat(DateTime dt, string Pattern)
{
string value = string.Empty;
value = dt.ToString(Pattern);
return value;
}
public static List<string> GetDateForChart()
{
DateTime dt = DateTime.Now;
string datefrom = ReturnDateFormat(dt.AddDays(-31), "yyyy-MM-dd");
string dateto = ReturnDateFormat(dt.AddDays(-1), "yyyy-MM-dd");
List<string> lst = new List<string>();
lst.Add(datefrom);
lst.Add(dateto);
return lst;
}
public static string GetPageRelativePath()
{
string url = HttpContext.Current.Request.Url.AbsolutePath;
return url;
}
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 string TrimString(string ab, int a)
{
string subab = ab;
if (subab.Length == 0) return subab;
if (subab.Length <= a) return subab;
subab = subab.Substring(0, a);
return subab;
}
public static string StripHTML(string HTMLText, bool decode = true)
{
Regex reg = new Regex("<[^>]+>", RegexOptions.IgnoreCase);
var stripped = reg.Replace(HTMLText, "");
var str1 = stripped.Replace("\r", "");
var str2 = str1.Replace("\t", "");
var strFinal = str2.Replace("\n", "");
return decode ? HttpUtility.HtmlDecode(strFinal) : strFinal;
}
public static string GiveCaptcha()
{
Random Rand = new Random();
int iNum = Rand.Next(100000, 999999);
Bitmap Bmp = new Bitmap(120, 40);
Graphics Gfx = Graphics.FromImage(Bmp);
Font Fnt = new Font("Verdana", 16, FontStyle.Regular);
Gfx.DrawString(iNum.ToString(), Fnt, Brushes.White, 15, 9);
// Create random numbers for the first line
int RandY1 = Rand.Next(0, 40);
int RandY2 = Rand.Next(0, 40);
// Draw the first line
Gfx.DrawLine(Pens.Yellow, 0, RandY1, 120, RandY2);
// Create random numbers for the second line
RandY1 = Rand.Next(0, 40);
RandY2 = Rand.Next(0, 40);
// Draw the second line
Gfx.DrawLine(Pens.Yellow, 0, RandY1, 120, RandY2);
//Bmp.Save(HttpContext.Current.Response.OutputStream, ImageFormat.Gif);
Bmp.Dispose();
Gfx.Dispose();
return iNum.ToString();
}
public static void CheckMemberLogin()
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["SALogin"];
if (cookie == null || String.IsNullOrEmpty(Convert.ToString(cookie)))
{
HttpContext.Current.Response.Redirect("/");
}
}
public static string RemoveAnchorTag(this string sample)
{
String re = @"<a [^>]+>(.*?)<\/a>";
return Regex.Replace(sample, re, "$1");
}
public static string RemoveNumberFromString(this string input)
{
return Regex.Replace(input, @"[\d]", string.Empty);
}
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 List<string> ReturnProperNumber(string Number)
{
List<string> lst = new List<string>();
if (Number != null && Number != string.Empty && Number != "-1")
{
if (Number.StartsWith("+92"))
{
Number = Number.Replace("+92", string.Empty);
}
else if (Number.StartsWith("92"))
{
Number = Number.Replace("92", string.Empty);
}
else if (Number.StartsWith("0"))
{
Number = Number.TrimStart('0');
}
Number = Number.Replace("-", string.Empty);
try
{
var arr = Number.SplitByString(string.Empty).Where(a => a != string.Empty).ToList();
string m = string.Empty;
for (int i = 0; i <= 2; i++)
{
m = m + arr[i].ToString();
}
lst.Add(m);
m = string.Empty;
for (int i = 3; i < 10; i++)
{
m = m + arr[i].ToString();
}
lst.Add(m);
}
catch
{
lst.Add("300");
lst.Add(string.Empty);
}
}
else
{
lst.Add("300");
lst.Add(string.Empty);
}
return lst;
}
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 GetHmtlContentsFromDirectory(string FileName)
{
string Result = "";
string FilePath = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath) + FileName;
System.IO.StreamReader MyFile = new System.IO.StreamReader(FilePath);
Result = MyFile.ReadToEnd();
MyFile.Close();
MyFile.Dispose();
return Result;
}
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 UppercaseFirst( string s )
{
// Check for empty string.
if( string.IsNullOrEmpty( s ) )
{
return string.Empty;
}
// Return char and concat substring.
return char.ToUpper( s[0] ) + s.Substring( 1 );
}
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 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 = "64.20.42.2"; // "64.20.42.2";//"184.107.73.104"; //"69.175.87.74";//;
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 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();
}
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);
}
}
}
}
private static System.Drawing.Imaging.ImageCodecInfo GetEncoderInfo(System.Drawing.Imaging.ImageFormat format)
{
return System.Drawing.Imaging.ImageCodecInfo.GetImageDecoders().SingleOrDefault(c => c.FormatID == format.Guid);
}
private static Random random = new Random();
public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
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 string GetYouTubeEmbedeCode(string url)
{
var a = url.SplitByString("v=").ToList();
if (a.Count > 0 && a.Count > 1)
{
return "https://www.youtube.com/embed/" + a[1];
}
else
{
return string.Empty;
}
}
}
public static class GenericExtentionFunctions
{
public static string GenrateURL(this string Input)
{
Input = (string)(Regex.Replace(Input, "[^\\w\\@-]", " ").ToLower());
Input = Regex.Replace(Input, "\\s{1,}", "-");
return Input;
}
public static string[] SplitByString(this string Input, string Pattern)
{
string[] array = Regex.Split(Input, Pattern);
return array;
}
public static T Next<T>(this IEnumerable<T> sender, T current) where T : class
{
if (sender != null)
{
var seq = sender.Select((o, i) => new { index = i, Object = o }).ToList();
var curr = seq.Where(x => x.Object == current).FirstOrDefault();
var next = seq.Where(x => x.index == curr.index + 1).FirstOrDefault();
if (next != null)
return next.Object;
}
return null;
}
public static T Previous<T>(this IEnumerable<T> sender, T current) where T : class
{
if (sender != null)
{
var seq = sender.Select((o, i) => new { index = i, Object = o }).ToList();
var curr = seq.Where(x => x.Object == current).FirstOrDefault();
var prev = seq.Where(x => x.index == curr.index - 1).FirstOrDefault();
if (prev != null)
return prev.Object;
}
return null;
}
}
public class FieldOfStudty
{
public int ID { get; set; }
public string Name { get; set; }
public string Url { get; set; }
}
public class MetaTags
{
public string MetaTitle { get; set; }
public string MetaDescription { get; set; }
public string MetaKeywords { get; set; }
public string ImageName { get; set; }
public string app_id { get; set; }
public string SiteName { get; set; }
public string Url { get; set; }
public MetaTags()
{
ImageName = "https://www.studyabroad.pk/UserEnd/Design/images/LogoForFB.gif";
app_id = "277117662711415";
SiteName = "Studyabroad.pk";
Url = HttpContext.Current.Request.Url.ToString();
}
}
public class ImageResizeBE
{
public int ImageQuality { get; set; }
public int ImageHeight { get; set; }
public int ImageWidth { get; set; }
public string FromSource { get; set; }
public string ToSource { get; set; }
}
}
No comments:
Post a Comment