Category: .NET


Some String Extension

public static class StringExtension
{
private static readonly Regex WebUrlExpression = new Regex(@”(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?”, RegexOptions.Singleline | RegexOptions.Compiled);
private static readonly Regex EmailExpression = new Regex(@”^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$”, RegexOptions.Singleline | RegexOptions.Compiled);
private static readonly Regex StripHTMLExpression = new Regex(“<\\S[^><]*>”, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Compiled);
private static readonly Regex AlphaNumericExpression = new Regex(@”^[a-zA-Z0-9]*$”, RegexOptions.Singleline | RegexOptions.Compiled);

private static readonly char[] IllegalUrlCharacters = new[] { ‘;’, ‘/’, ‘\\’, ‘?’, ‘:’, ‘@’, ‘&’, ‘=’, ‘+’, ‘$’, ‘,’, ‘<‘, ‘>’, ‘#’, ‘%’, ‘.’, ‘!’, ‘*’, ‘\”, ‘”‘, ‘(‘, ‘)’, ‘[‘, ‘]’, ‘{‘, ‘}’, ‘|’, ‘^’, ‘`’, ‘~’, ‘–’, ‘‘’, ‘’’, ‘“’, ‘”’, ‘»’, ‘«’ };

[DebuggerStepThrough]
public static bool IsAlphaNumeric(this string target)
{
return !string.IsNullOrEmpty(target) && AlphaNumericExpression.IsMatch(target);
}

[DebuggerStepThrough]
public static bool IsPhoneNumber(this string target)
{
return !string.IsNullOrEmpty(target.Trim()) && target.Replace(” “, “”).ToCharArray().All(x => char.IsDigit(x) || x == ‘-‘ || x == ‘(‘ || x == ‘)’);
}

[DebuggerStepThrough]
public static bool IsWebUrl(this string target)
{
return !string.IsNullOrEmpty(target) && WebUrlExpression.IsMatch(target);
}

[DebuggerStepThrough]
public static bool IsEmail(this string target)
{
return !string.IsNullOrEmpty(target) && EmailExpression.IsMatch(target);
}

[DebuggerStepThrough]
public static bool IsNullOrEmpty(this string target)
{
return string.IsNullOrEmpty(target);
}

[DebuggerStepThrough]
public static bool IsNotNullOrEmpty(this string target)
{
return !string.IsNullOrEmpty(target);
}

[DebuggerStepThrough]
public static string NullSafe(this string target)
{
return (target ?? string.Empty).Trim();
}

[DebuggerStepThrough]
public static string StripHtml(this string target)
{
return StripHTMLExpression.Replace(target, string.Empty);
}

[DebuggerStepThrough]
public static Guid ToGuid(this string target)
{
Guid result = Guid.Empty;

if ((!string.IsNullOrEmpty(target)) && (target.Trim().Length == 22))
{
string encoded = string.Concat(target.Trim().Replace(“-“, “+”).Replace(“_”, “/”), “==”);

try
{
byte[] base64 = Convert.FromBase64String(encoded);

result = new Guid(base64);
}
catch (FormatException)
{
}
}

return result;
}

[DebuggerStepThrough]
public static string ToLegalUrl(this string target)
{
if (string.IsNullOrEmpty(target))
{
return target;
}

target = target.Trim();

if (target.IndexOfAny(IllegalUrlCharacters) > -1)
{
foreach (char character in IllegalUrlCharacters)
{
target = target.Replace(character.ToString(CultureInfo.CurrentCulture), string.Empty);
}
}

target = target.Replace(” “, “-“);

while (target.Contains(“–“))
{
target = target.Replace(“–“, “-“);
}

return target;
}

[DebuggerStepThrough]
public static string UrlEncode(this string target)
{
return HttpUtility.UrlEncode(target);
}

[DebuggerStepThrough]
public static string UrlDecode(this string target)
{
return HttpUtility.UrlDecode(target);
}

[DebuggerStepThrough]
public static string AttributeEncode(this string target)
{
return HttpUtility.HtmlAttributeEncode(target);
}

[DebuggerStepThrough]
public static string HtmlEncode(this string target)
{
return HttpUtility.HtmlEncode(target);
}

[DebuggerStepThrough]
public static string HtmlDecode(this string target)
{
return HttpUtility.HtmlDecode(target);
}

public static string Replace(this string target, ICollection<string> oldValues, string newValue)
{
oldValues.ForEach(oldValue => target = target.Replace(oldValue, newValue));
return target;
}

public static string SafeSubString(this string target, int startIndex, int length)
{
return startIndex + length > target.Length ? target.Substring(startIndex, target.Length) : target.Substring(startIndex, length);
}
}

Advertisements

public static string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();

// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}

public static Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}

Image Resize

public static Bitmap ReSizeBitmap(Bitmap btp, int width, int height)
{
int originalW = btp.Width;
int originalH = btp.Height;
int proportionsW = 0;
int proportionsH = 0;

if ((originalH * width) / originalW <= height)
{
proportionsW = width;
proportionsH = (originalH * width) / originalW;
}
else
{
proportionsH = height;
proportionsW = (originalW * height) / originalH;
}

Bitmap bmp = new Bitmap(width, height);

//create a new graphic from the Bitmap
Graphics graphic = Graphics.FromImage((Image)bmp);
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
//draw the newly resized image
graphic.FillRectangle(new SolidBrush(Color.White), new Rectangle(0, 0, width, height));
graphic.DrawImage(btp as Image, (width – proportionsW) / 2, (height – proportionsH) / 2, proportionsW, proportionsH);
graphic.Dispose();
//return the image
return bmp;
}

private void myProcess_Exited(object sender, System.EventArgs e)
{
while (sr.Peek() != -1)
output += sr.ReadLine() + “\n”;
eventHandled = true;
}

ExePath = “C:\a.exe”;
Process p = new Process();

ProcessStartInfo psI = new ProcessStartInfo(ExePath);
psI.UseShellExecute = false;
psI.RedirectStandardInput = true;
psI.RedirectStandardOutput = true;
psI.RedirectStandardError = true;
psI.CreateNoWindow = true;
p.StartInfo = psI;
p.EnableRaisingEvents = true;
p.Exited += new EventHandler(this.myProcess_Exited);
p.Start();

p.MaxWorkingSet = (IntPtr)(1024 * 1024 * 32); // memory set

sw = p.StandardInput;
sr = p.StandardOutput;
err = p.StandardError;

string input = “sample input”;
long limit = 5 * 1000; // 5 sec max time limit set for the exe
output = “”;

sw.Write(input);
sw.Close();

int id = p.Id;

eventHandled = false;

const int SLEEP_AMOUNT = 100;

while (!p.HasExited)
{
start += SLEEP_AMOUNT;
if (start > limit)
{
break;
}
Thread.Sleep(SLEEP_AMOUNT);
p.Refresh();
}

now we will get the output in the output variable

string a = Environment.ExpandEnvironmentVariables(@”%SystemRoot%\system32\sc.exe”);
string path = Directory.GetCurrentDirectory();
path += @”\TestWindowsService.exe”;
try
{
System.Diagnostics.ProcessStartInfo si = new System.Diagnostics.ProcessStartInfo(“cmd”);

si.RedirectStandardInput = true;

si.RedirectStandardOutput = true;

si.RedirectStandardError = true;

si.UseShellExecute = false;

si.CreateNoWindow = true;

si.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

System.Diagnostics.Process console = System.Diagnostics.Process.Start(si);
for (int i = 0; i < 100; i++)
console.StandardInput.WriteLine(“cd..”);

string command = a + ” create SycapCRMWindowsService  binPath= \”” + path + “\””;

console.StandardInput.WriteLine(command);
//Service has successfully been installed.
}
catch (Exception objException)
{
//objException.Message.ToString()
}

RegistryKey rkApp = Registry.CurrentUser.OpenSubKey(“SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run”, true);

string name = “Messanger”;  // name of the program
string pro = “C:\messanger.exe”; // program location

rkApp.SetValue(name, pro);

You have to create an .aspx file like CaptureImage.aspx, which .cs file will be like this,

protected void Page_Load(object sender, EventArgs e)
{
string Filepath = Server.MapPath(“~/Images/captcha.bmp”);
Bitmap bp = Bitmap.FromFile(Filepath) as Bitmap;

MemoryStream memStream = new MemoryStream();
Graphics g = Graphics.FromImage(bp);
g.SmoothingMode = SmoothingMode.AntiAlias;

int width = bp.Width;
int height = bp.Height;

string familyName = “Tahoma”;
string text = “”;

Random random = new Random();

for (int i = 0; i < 5; i++)
{
text += Convert.ToChar(random.Next(‘A’, ‘Z’)).ToString();
}

Rectangle rect = new Rectangle(5, 5, 168, 38);
Font font;
font = new Font(familyName, 32F, FontStyle.Bold);

StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
GraphicsPath path = new GraphicsPath();
path.AddString(text, font.FontFamily, (int)font.Style, font.Size, rect, format);

PointF[] points =
{
new PointF(rect.X – 10, rect.Y – 8),
new PointF(rect.X + rect.Width – 20, rect.Y + 4),
new PointF(rect.X – 8, rect.Y + rect.Height – 15),
new PointF(rect.X + rect.Width – 10, rect.Y + rect.Height + 4)
};

Matrix matrix = new Matrix();
matrix.Translate(0F, 0F);
path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);

HatchBrush hatchBrush = new HatchBrush(
HatchStyle.LargeConfetti,
Color.Black,
Color.Black);
g.FillPath(hatchBrush, path);

Response.Clear();
Response.ContentType = “image/jpeg”;
bp.Save(memStream, ImageFormat.Jpeg);
memStream.WriteTo(Response.OutputStream);

Session[“CaptureText”] = text;

font.Dispose();
hatchBrush.Dispose();
g.Dispose();
bp.Dispose();
}

Use this page like this,
imgCapture.ImageUrl = “CaptureImage.aspx”;
on submit check -> Session[“CaptureText”].ToString()

You have to create an .aspx file like create-water-mark-image.aspx, which .cs file will be like this,

Request[“ImageFileName”] – > image file

ConfigurationManager.AppSettings[“LOGO_IMAGE”] -> logo image

protected void Page_Load(object sender, EventArgs e)
{
if (Request[“ImageFileName”] != null)
{
string path = Request[“ImageFileName”].ToString();

CreateWaterMarkImage(path, ConfigurationManager.AppSettings[“LOGO_IMAGE”]);
}
}

private void CreateWaterMarkImage(string sourceFileName, string logoFileName)
{
string pathOfSource = Server.MapPath(sourceFileName);
string pathOfLogo = Server.MapPath(logoFileName);

System.Drawing.Image objImage = System.Drawing.Image.FromFile(pathOfSource);
System.Drawing.Image logoImage = System.Drawing.Image.FromFile(pathOfLogo);
int height = objImage.Height;
int width = objImage.Width;
int logoHeight = logoImage.Height;
int logoWidth = logoImage.Width;
int logoStartX = 0;
int logoStartY = 0;

System.Drawing.Bitmap bitmapimage = new System.Drawing.Bitmap(objImage, width, height);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmapimage);

if (logoWidth < width)
logoStartX = (width – logoWidth) / 2;

if (logoHeight < height)
logoStartY = (height – logoHeight) / 2;

g.DrawImage(logoImage, new System.Drawing.Rectangle(logoStartX, logoStartY, logoWidth, logoHeight), 0, 0, logoWidth, logoHeight, System.Drawing.GraphicsUnit.Pixel, SetImageAttributes());

System.Drawing.Image newImage = bitmapimage;

this.Response.Clear();
this.Response.ContentType = “image/jpeg”;
newImage.Save(this.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}

private System.Drawing.Imaging.ImageAttributes SetImageAttributes()
{
System.Drawing.Imaging.ImageAttributes imageAttributes = new System.Drawing.Imaging.ImageAttributes();
System.Drawing.Imaging.ColorMap colorMap = new System.Drawing.Imaging.ColorMap();

colorMap.OldColor = System.Drawing.Color.FromArgb(255, 0, 255, 0);
colorMap.NewColor = System.Drawing.Color.FromArgb(0, 0, 0, 0);

System.Drawing.Imaging.ColorMap[] remapTable = { colorMap };

imageAttributes.SetRemapTable(remapTable, System.Drawing.Imaging.ColorAdjustType.Bitmap);

float[][] colorMatrixElements = {
new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
new float[] {0.0f,  0.0f,  0.0f,  1.0f, 0.0f},
new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
};

System.Drawing.Imaging.ColorMatrix wmColorMatrix = new System.Drawing.Imaging.ColorMatrix(colorMatrixElements);

imageAttributes.SetColorMatrix(wmColorMatrix,
System.Drawing.Imaging.ColorMatrixFlag.Default,
System.Drawing.Imaging.ColorAdjustType.Bitmap);

return imageAttributes;
}

This page can be called like

aImageLink.HRef = “create-water-mark-image.aspx?ImageFileName=” + productImage;

For playing .flv file mediaplayer.swf is needed.

<asp:Literal ID=”litVideo” runat=”server”></asp:Literal>
C# code :
string filename = “Media/test.wmv”;
string code = string.Empty;
string browserType = Request.Browser.Type;
int height = 0;
int width = 0;
int marginUp = 0;
int marginRight = 0;
int marginDown = 0;
int marginLeft = 0;

if (filename.ToLower().EndsWith(“.wmv”))
{
int start = HttpContext.Current.Request.Url.AbsoluteUri.IndexOf(HttpContext.Current.Request.Url.AbsolutePath);
string hostName = HttpContext.Current.Request.Url.AbsoluteUri.Remove(start);

if (!hostName.EndsWith(“/”))
hostName += “/”;

string appPath = HttpContext.Current.Request.ApplicationPath;
if (appPath.StartsWith(“/”))
appPath = appPath.Remove(0, 1);

hostName += appPath;

if (!hostName.EndsWith(“/”))
hostName += “/”;

if (browserType.StartsWith(“IE”))
{
height = 307;
width = 545;
marginUp = 30;
marginRight = 0;
marginDown = 0;
marginLeft = 30;
}
else if (browserType.ToLower().StartsWith(“firefox”))
{
height = 420;
width = 610;
marginUp = 10;
marginRight = 3;
marginDown = 10;
marginLeft = 3;
}
else
{
height = 307;
width = 545;
marginUp = 65;
marginRight = 0;
marginDown = 0;
marginLeft = 38;
}

code = string.Format(@”<div style=””margin: {0}px {1}px {2}px {3}px; overflow:hidden””>http://”4”<div>”, marginUp, marginRight, marginDown, marginLeft, hostName + filename, width, height);
}

else if (filename.ToLower().EndsWith(“.mov”))
{
if (browserType.StartsWith(“IE”))
{
height = 407;
width = 602;
marginUp = 3;
marginRight = 3;
marginDown = 3;
marginLeft = 3;
}
else if (browserType.ToLower().StartsWith(“firefox”))
{
height = 420;
width = 610;
marginUp = 10;
marginRight = 3;
marginDown = 10;
marginLeft = 3;
}
else
{
height = 416;
width = 610;
marginUp = 10;
marginRight = 3;
marginDown = 10;
marginLeft = 3;
}

int start = HttpContext.Current.Request.Url.AbsoluteUri.IndexOf(HttpContext.Current.Request.Url.AbsolutePath);
string hostName = HttpContext.Current.Request.Url.AbsoluteUri.Remove(start);

if (!hostName.EndsWith(“/”))
hostName += “/”;

string appPath = HttpContext.Current.Request.ApplicationPath;
if (appPath.StartsWith(“/”))
appPath = appPath.Remove(0, 1);

hostName += appPath;

if (!hostName.EndsWith(“/”))
hostName += “/”;

code = string.Format(@”<object classid=””clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B”” codebase=””http://www.apple.com/qtactivex/qtplugin.cab”&#8221; height=””{5}”” width=””{4}””>
<param name=””src”” value=””{6}”” />
<param name=””autoplay”” value=””true”” />
<param name=””controller”” value=””true”” />
<PARAM NAME=””ShowStatusBar”” VALUE=””true”” />
http://”6”
</object>”, marginUp, marginRight, marginDown, marginLeft, width, height, hostName + filename);

}
else if (filename.ToLower().EndsWith(“.flv”))
{
if (browserType.StartsWith(“IE”))
{
height = 407;
width = 602;
marginUp = 3;
marginRight = 3;
marginDown = 3;
marginLeft = 3;
}
else if (browserType.ToLower().StartsWith(“firefox”))
{
height = 420;
width = 610;
marginUp = 10;
marginRight = 3;
marginDown = 10;
marginLeft = 3;
}
else
{
height = 416;
width = 610;
marginUp = 10;
marginRight = 3;
marginDown = 10;
marginLeft = 3;
}

code = string.Format(@”<div id=””container”” style=””margin: {0}px {1}px {2}px {3}px; overflow:hidden;””>
<a href=””http://www.macromedia.com/go/getflashplayer””>Get the Flash Player</a> to see this player.
</div>

<script type=””text/javascript””>
var s1 = new SWFObject(“”../mediaplayer.swf””, “”mediaplayer””, “”{4}””, “”{5}””, “”8″”);
s1.addParam(“”allowfullscreen””, “”true””);
s1.addParam(“”autostart””, “”true””);
s1.addVariable(“”width””, “”{4}””);
s1.addVariable(“”height””, “”{5}””);
s1.addVariable(“”file””, “”{6}””);
s1.write(“”container””);
</script>”, marginUp, marginRight, marginDown, marginLeft, width, height, filename);
}
else
{
code = “Video format is not supported!”;
}

litVideo.Text = code;

public string ChangeFieldValue(string value,string filed,string newValue)
{
int length = value.Length;
int fieldLength = filed.Length;
int i = 0;

while(i+fieldLength<=length)
{
string str = value.Substring(i, fieldLength);
if (str.ToLower() == filed.ToLower())
{
int start = -1;
int end = -1;
int j = i+fieldLength;

while (j < length)
{
if (value[j].ToString() == “\””)
{
start = j + 1;
j++;
break;
}
j++;
}

while (j < length)
{
if (value[j].ToString() == “\””)
{
end = j – 1;
j++;
break;
}
j++;
}

if (start != -1 && end != -1)
{
value = value.Remove(start, end – start + 1);
value = value.Insert(start, newValue);
length = value.Length;
}
}
i++;
}
return value;
}
}

embedCode = ChangeFieldValue(embedCode, “height”, “200″);

embedCode = ChangeFieldValue(embedCode, “width”, “200″);