Friday, July 8, 2011

Installing and configuring Google Web Toolkit and Eclipse.

Hi every one. In this post I’ll demonstrate the steps to install and configuring Eclipse and Google web toolkit. First of all what is GWT is? GWT or Google Web Toolkit is an open source development tool kit from Google. GWT is optimized for AJAX based complex applications. To work GWT you must know basics of Java and Web Development.

Mostly user IDE for GWT based applications is Eclipse but not necessarily you can use any IDE of your choice for Java (e.g. Net beans). 

GWT has many components not just SDK. It has plug in for Eclipse, GWT Designer lets you create user interfaces in minutes with tools for intelligent layout assist, drag-and-drop, and automatic code generation.

You will need the Java SDK version 1.5 or later. If necessary, download and install the Java SE Development Kit (JDK) for your platform. Mac users, see Apple's Java developer site to download and install the latest version of the Java Developer Kit available for Mac OS X.

Then download Eclipse. I used Eclipse 3.7 Indigo. You can download it from here.

 After Installing Eclipse got menu Help -> Install New Software and in Work with text box enter this Uri http://dl.google.com/eclipse/plugin/3.7

If you are using different version of Eclipse change the 3.7 with your version. Now click Add, and in pan below it will show two Options. "Plugin" and "SDK's" Select both options and click Finish. It will take a while to install these two items.

After Installing both plug in and SDK, Restart eclipse and go to menu File -> New -> Web Application Project. A Popup will appear. Name your package carefully as it should be unique and will later be used as identity on the App store. Don't forget to select "Use Google Web Toolkit" as show in image.

 

Ss-eclipse

 

for more help visit http://code.google.com/webtoolkit/.

 

I hope this will be helpful. Comments and suggestions are welcomed. 

Happy coding :)

 

Thursday, June 30, 2011

Sending Email Using Exchange Server 2010 EWS in Asp.Net / C#

Sending email using Exchange server EWS is breeze as compare to horrible syntaxed Web Dav ( sorry to WebDav Lovers :) ) . I worked with WebDav and many times banged my head against wall figuring out the actual issue in case of error.

EWS is web service based API of exchange server and provide very managed and readable code for sending email.

Let's start writing some code to work with ESW 2010.

First of all Add reference to Microsoft.Exchange.WebServices.dll and place Microsoft.Exchange.WebServices.xml file in your bin 

Next import following namespace.

 

using Microsoft.Exchange.WebServices;


 

public static void SendExchangeEmail(string to, string from, string subject, string body, string fileattach)

 

        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);

        service.Credentials = new NetworkCredential("ExchangeUser", "UserPassword");

        service.Url = new Uri("https://YourExchangeUrl/EWS/Exchange.asmx");

        EmailMessage newMsg = new EmailMessage(service);

        foreach (string s in to.Split(new char[] { ',' }))

        {

            newMsg.ToRecipients.Add(s.Trim());

        }

        newMsg.Body = body;

        newMsg.Subject = subject;

        newMsg.From = from;        

 

        if (!string.IsNullOrEmpty(fileattach))

        {

            newMsg.Attachments.AddFileAttachment(fileattach);

        }

 

        newMsg.SendAndSaveCopy();  OR ( depending upon your requirment)

        newMsg.Send();

}

 

Note: Use Send method just to send and use "SendAndSave" to save a copy in your sent items

Cheers :) 

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.