Friday, December 24, 2010

Image Scaling without cutting image.

Some time we need to scale images in our Web or Desktop Apps. requirement could be different. but mostly we want to reduce size of image keeping the quality almost same. In my case we had collection of huge dimension images which are not need. I scaled the dimensions to 17*11 or 11*17 depending upon type of image (Portrait or Landscape.)

The main function will be like this.

string localpath = @"C:\Images\9ee5887.jpg";
Image sourceImage = Image.FromFile(localpath);

Image temp = ScalImage(sourceImage, new Size(1200, 800));

temp.Save("D:\\Images\\9ee5887-Scaled.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

sourceImage.Dispose();
temp.Dispose();


And the scale image funcion will be like this.


public Image ScalImage(Image imgToResize, Size size)
{

int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;

float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;

nPercentW = ((float)size.Width / (float)sourceWidth);
nPercentH = ((float)size.Height / (float)sourceHeight);

if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;

int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);

Bitmap b = new Bitmap(destWidth, destHeight);

using (Graphics g = Graphics.FromImage((Image)b))

{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);

}


return (Image)b;

}


I have tested both Landscap and portrait images with this. Works perfectly. :) Any Suggestion Improvement will be appreciated greatly..


Wednesday, October 20, 2010

Keeping Session Alive in Asp.Net

some time we have a requirement that we want to keep our session alive. A sudden solution that come to mind is that increase the session timeout in IIS. But this solution don't work well as we might except. It create issues like we have to increase timeout also for Application Pool. Because Application Recycles itself after 30 mins if no request hit server. I am Demonstrating two Strategies here for keeping session alive.

1. Approach No 1 Using JQuery and Handler.
Simply Add a Generic Handler to your web site like "Ping.ashx" or "KeepAlive.ashx" whatever you want. (The Reason i prefer handler over aspx pages in such scenarios is because Handler are fast as compare to aspx page which has a complete life cycle to run). In this handler simply add line of code like.
Context.Response.Write(" "); /// not necessory.
Now on your aspx page add following Code


2. Using IFrame.
Create a aspx page or Handler same as above and add the following line of code
context.Response.AddHeader("Refresh", Convert.ToString(( Session.Timeout * 60 ) -120 ));
after that Add following javascript code on you page.


I hope this will help.

Thursday, October 14, 2010

Perfect way to get Client IP Address in Asp.Net

Getting visitor IP is very frequent requirement in Web Development. There are many confusion about the method to get IP in best way. First of all be aware not to use System.Net.Dns.GetHostAddresses(strHostName) method because it will always return IP Address of the local machine on which Application is running. Use the following function to get IP Address


string clientIP;
string ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ip))
{
string[] ipRange = ip.Trim().Split(',');
int le = ipRange.Length - 1;
clientIP = ipRange[le];
}
else
clientIP = Request.ServerVariables["REMOTE_ADDR"];


First check HTTP_X_FORWARDED_FOR. It will give IP address of the client machine if client is using proxy server and if its null then read the IP address from Header.
Currently these are the only options available in Asp.Net. and they mostly work fine.

Note:Some times if NAT is enabled on Web server there are cases when It always pick local IP no matter what method you use. Check of NAT (Network Address Translation) for further information.
Hope this will help :). Any Suggestion, Correction and Updation is welcomed.

Wednesday, September 15, 2010

Uploading File with progress bar In Asp.net

Uploading file is very common task in Asp.net applications. Although asp.net evolve pretty much around time but file upload control is same from 1.0 to 3.5. Web Apps are becoming more and more interactive these days. in this scenario uploading file with progress bar and without post back give user feed back about status of task.
I find a very nice Jquery plug in called Uploadify for this. You can download it from here.
They have starting example on the site a PHP code snippet. I just want to share my Asp.net Implementation.

First of all download Jquery and Uploadify plug in the create a Asp.net website using Visual Studio or Visual Web Developer and copy the "uploadify" folder to your web site. Now Add reference of following files to your aspx page. like this



Now include the reference to uploadify.css file. otherwise it will not display as you expect.
Now add this script to you aspx page
Finally Add a Generic handler (see the Handler.ashx in front of 'script' property of uploadify)

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler {

public void ProcessRequest (HttpContext context) {

string path = string.Empty;

for (int j = 0; j < uploadfile =" context.Request.Files[j];" path =" context.Server.MapPath("> 0)
{
uploadFile.SaveAs(path);

}
}


}

public bool IsReusable {
get {
return false;
}
}

}
you can read detail of uploadify function and its properties from here

Now run the page and it will look like image below.


Happy coding :)

Tuesday, August 24, 2010

Silent Printing PDF File in C# and closing Adobe Popup

Printing is very common task in Desktop App. In this article i will demonstrate how to print a PDF File Silently. There are two approaches. First We can print the file using PDF Sharp ( a open source library to support PDF Related Operations) and Arobate exe. Second Approach is to intiate a process that call Acrobate now doubt both need at least acrobat installed on machine, as PDF Sharp can not render PDF It self. I will demonstrate the first way.
Add Reference to PDF Sharp. First inform PdfFilePrinter about path of Adobe reader exe on target machine.
PdfFilePrinter.AdobeReaderPath = @"C:\Program Files\Adobe\Reader 8.0\Reader\AcroRd32.exe";

///Then in next step create a instance of the class PdfFilePrinter and provide path of file to print and your default active printer.

try
{
PdfFilePrinter Pdfprinter = new PdfFilePrinter(filetoprint, printer);
Pdfprinter.Print();
}
catch(Exception ex)
{
throw ex;
}
Now get the Adobe Process and kill it if it has finished its job.

foreach (Process proc in Process.GetProcesses())
{
if (proc.ProcessName.StartsWith("Acro"))
{
if (proc.HasExited == false)
{
proc.WaitForExit(10000);
proc.Kill();
break;
}
else
{
proc.Kill();
break;
}
}
}


if you have any question please free to ask. Hope this helps.


Monday, August 16, 2010

How to Draw a shape in Silverlight 3

In Silverlight, some time we need to draw shapes. and to draw these shapes we need mouse coordinates while mouse button is down, Up and most important while mouse is moving to give illusion that shape is creating. to do this first Add a static shape (circle, rectangle etc) on canvas and set its visibility to Hidden. after this follow the following code.

Create four Global Variables to store coordinates.

double x1 = 0.0;
double y1 = 0.0;
double x2 = 0.0;
double y2 = 0.0;

Now in Canvas_ MouseLeftButtonDown Event of Mouse get the start points like this

x1 = e.GetPosition(canvas).X;
y1 = e.GetPosition(canvas).Y;
_down = true;

In Canvas_MouseMove event write this code

if ((_down)
{
double xo = e.GetPosition(canvas).X;
double yo = e.GetPosition(canvas).Y;
///// Now set position of that shape (circle, rectangle etc).

Shape.SetValue(Canvas.LeftProperty, Math.Min(xo, x1));
Shape.SetValue(Canvas.TopProperty, Math.Min(yo, y1));

//////Set Shape Size
Shape.Width = Math.Abs(xo - x1);
Shape.Height = Math.Abs(yo - y1);

if (Shape.Visibility != Visibility.Visible)
Shape.Visibility = Visibility.Visible;
}

and Finally in Canvas_MouseLeftButtonUp Event write this code
_down = false;
x2 = e.GetPosition(canvas).X;
y2 = e.GetPosition(canvas).Y;
DrawShape(x1, y1, x2, y2);

I'll explain and provide the Draw function code in my next article.

Happy Coding :)

Wednesday, August 11, 2010

Sending HTML Tempate based Email in Asp.Net

Few months ago one of our client requested a feature. They want to send HTML Template based email to their clients and staff containing some Dynamic data. I come up with following solution. I downloaded a open source parser vici.core. This is great tool and has lot of features HTML Template parser is just one on them.
First you should have HTML Template for the email. like
<blockquote>

<p>"

<strong>Creation Date:</strong>

$CreateDate

<strong>Order No:</strong>

$OrderNo

"</p>

</blockquote>
put a $ sign before your variables (that u want to provide on run time) in your html template. Then in your application add reference to vici.core. and use following code.
TemplateParser template = new TemplateParser();
IParserContext pContext = new CSharpContext();

Now in first value add name of your variable in html template. without $ sign

Dictionary emailData = new Dictionary();
emailData.Add("CreateDate", dpCDate.Text);
emailData.Add("OrderNo", txtOrderNo.Text);
emailData.Add("CDate", txtCompDate.Text);

foreach (KeyValuePair pair in eData)
{
pContext.Set(pair.Key, pair.Value);
}
string tempStr = File.ReadAllText("EmailTemplate.html");

MailMessage msg = new MailMessage();
msg.Subject = "Order Confirmation ";
msg.From = new MailAddress("from@yourdomain.com");
msg.Body = template.Render(tempStr, pContext);
msg.IsBodyHtml = true;

for (int i = 0; i < toAddrArray.Length; i++)
{
msg.To.Add(toAddrArray[i]);
}

///////////Define your smtp setting in web.config
var mailclient = new SmtpClient();
mailclient.Send(msg);


Hope this helps...


Tuesday, August 10, 2010

Converting WPF Control to Image

In one of my application I need to convert my WPF Form to Image. I Googled around and find RenderTargetBitmap is solution to my Problem. The Code is given below.

public static PngBitmapEncoder ImageFromControl(Control myControl)
{
Transform transform =
myControl.LayoutTransform;

System.Windows.Size sizeOfControl = new System.Windows.Size(
myControl.ActualWidth, controlToConvert.ActualHeight);
myControl.Measure(sizeOfControl);
myControl.Arrange(new Rect(sizeOfControl));

RenderTargetBitmap renderBitmap = new RenderTargetBitmap((Int32)sizeOfControl.Width, (Int32)sizeOfControl.Height, 96d, 96d, PixelFormats.Pbgra32);
renderBitmap.Render(
myControl);

PngBitmapEncoder pngEncoder = new PngBitmapEncoder();
pngEncoder.Frames.Add(BitmapFrame.Create(renderBitmap));

return pngEncoder;
}
and in my Main function is use it like,,,
stream = File.Create("Control.jpg");
ImageFromControl(myControl).Save(stream);
stream.Close();
I hope this will Help..... Happy Coding :)

Wednesday, March 17, 2010

ReSetting Form Fields

function ClearAll()

{

for (i=0; i0].length; i++)

{

doc = document.forms[0].elements[i];

switch (doc.type)

{

case "text" :

doc.value = "";

break;

case "checkbox" :

doc.checked = false;

break;

case "radio" :

doc.checked = false;

break;

case "select-one" :

doc.options[doc.selectedIndex].selected = false;

break;

case "select-multiple" :

while (doc.selectedIndex != -1)

{

indx = doc.selectedIndex;

doc.options[indx].selected = false;

}

doc.selected = false;

break;

default :

break;

}

}

}

}

Sunday, March 14, 2010

New Features in .Net 4.0

.Net 4 has introduced some exciting new features. Here are some of them listed below. I will take an overview of these (which i have used) features as c# develope
r

Dynamic Lookup (New to C#)

C# added a new static type named dynamic. Although there is a lot that goes into making this new type work, but using it is eady. You can think of the dynamic type as an object that supports late binding

dynamic Car = GetCar();               //Get a reference to the dynamic object
Car.Model = "Mondeo"; //Assign a value to a property (also works for fields)
Car.StartEngine(); //Calling a method
Car.Accelerate(100); //Call a methods with parameters
dynamic Person = Car["Driver"]; //Getting with an indexer
Car["Passenger"] = CreatePassenger(); //Setting with an indexer

Named and Optional Parameters (New to C#)

Named parameters were in VB only, and now are finally being incorporated into C#. As the name suggests, optional parameters are parameters that you can (have option) to pass into a method or constructor. If you opt not to pass a parameter, the method simply uses the default value defined for the parameter. To make a method parameter optional in C#, you just give it a default value

public void CreateBook(string title="No Title", int pageCount=0, string isbn = "0-00000-000-0")
{
this.Title = title;
this.PageCount = pageCount;
this.ISBN = isbn;
}