Posterous theme by Cory Watilo

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/.

Then fill these things in the project form.


  • Name:  First
  • Package: first
  • Select your Work Folder
  • Uncheck App Engine (If you use app Engine keep it as it but you have install App engine)
  • Select Finish

 

 

“App engine” is like a web browser you can test your GWT applications. But in here i use default GWT SDK (It is easy). Now you have successfully created the GWT project “First”. Below image is your project explorer.

 


 

Step 4

Now we run the application.


  • Right click on the Project "First"
  • Select Run As
  • Select Web Application

 

 

Step 5


  • Copy the link in the bottom bar.
  • Paste it in your any browser (Firefox, Chrome, and IE)

 

 

Step 6


If you get the below error message, you have to install the GWT enabled plug-in to your browser.

 


 

 

 

You have successfully created your first project in GWT. Any problem comment here.


I hope this will be helpful.

Happy coding :)

 

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 :) 

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 = @"DirPath\9ee5887.jpg";
Image sourceImage = Image.FromFile(localpath);

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

buffer.Save("DirPath\\9ee5887-Scaled.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

/// Clear resources


sourceImage.Dispose();
buffer.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..


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

Media_http1bpblogspot_pbilm

2. Using IFrame.
Create a aspx page or Handler same as above and add the following line of code
<script language="javascript" type="text/javascript" src="jquery.min.js"></script>context.Response.AddHeader("Refresh", Convert.ToString(( Session.Timeout * 60 ) -120 ));
<script language="javascript" type="text/javascript">

function KeepAlive() {
$.post("http://YourWebSiteUrl.com/Ping.aspx");
setInterval(KeepAlive, 10000); /// Request again after 10 seconds
}
$(document).ready(KeepSessionAlive); /// To call first time
</script>

after that Add following javascript code on you page.

Media_http4bpblogspot_mspie

I hope this will help.

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.

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

<script src="Uploadify/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="Uploadify/jquery.uploadify.v2.1.0.min.js" type="text/javascript"></script>
Media_http3bpblogspot_ypajd

<script src="Uploadify/swfobject.js" type="text/javascript"></script>
Now include the reference to uploadify.css file. otherwise it will not display as you expect.
<link href="Uploadify/uploadify.css" rel="stylesheet" type="text/css">
Now add this script to you aspx page
<script type="text/javascript">

var id = "55";
var theString = "asdf";
$(document).ready(function() {
$('#fileInput').uploadify({
'uploader': 'uploadify/uploadify.swf',
'script': 'Handler.ashx',
'scriptData': { 'id': id, 'foo': theString },
'cancelImg': 'uploadify/cancel.png',
'auto': true,
'multi': true,
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.png;*.gif;*.bmp;*.jpeg',
'queueSizeLimit': 90,
'sizeLimit': 4000000,
'buttonText': 'Choose Images',
'folder': '/uploads',
'onAllComplete': function(event, queueID, fileObj, response, data) {

}
});
});
</script>

Media_http4bpblogspot_qdeeg
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.

Media_http1bpblogspot_bdebw

Happy coding :)

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.


 

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 :)

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<velocity>();
IParserContext pContext = new CSharpContext();

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

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

foreach (KeyValuePair<string,> 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);
</string,></string,></string,></velocity>

Hope this helps...


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 :)