Friday, December 30, 2011

Dynamically Creating Image in C#.Net


     
        As per the requirement from one of my client, an image should be generated dynamically by taking the necessary information from the user.  When I went on a search, I came to know that, my crazy DotNet framework provided my two namespaces System.Drawing and System.Drawing.Imaging.  It’s enough to learn three classes from these namespaces - Bitmap and Graphics for generating an image dynamically related to System.Drawing Namespace and FileFormat class is for saving the created image in different file formats and is related to System.Drawing.Imaging Namespace.

            Bitmap class is useful to generate a new image and to save it different file formats.  Graphics class is useful to design the image using lines, curves, rectangles, text etc., with colors and everything.  FileFormat class is useful to save the file in a particular or in different formats like Jpeg, Png, Bmp etc.  The default format is png.
           
            Now lets jump into code.  After declaring namespaces, we need to create an image with bitmap class as follows.
Bitmap bmp = new Bitmap(200, 200);

Here bmp is the image with the height 200 and width 200.  Next we need to create a Graphics Object for our bmp Image as follows.
Graphics gr;
gr = Graphics.FromImage(bmp);


That’s it you have created image successfully with a little bit of graphics.  Now you have to go through the Graphics class for more manipulations of the image like drawing lines, rectangles, creating text etc., some examples as follows
For giving background color for image:
gr.Clear(Color.White);

For drawing line:
gr.DrawLine(new Pen(Color.Black), 0, 0, 100, 0); 

for Writing text in image:
gr.DrawString("dileepKumar", objFont, new SolidBrush(Color.Black), 0, 0);

After finishing designing the image, you have to save the image in your desired format will be as follows,
bmp.Save(Server.MapPath("img.jpg"),ImageFormat.Jpeg);

After saving the image you need to dispose the Bitmap Object and Graphics Object.
bmp.Dispose();
gr.Dispose();

Now your image is successfully generated with your graphical stuff which you have provided using the graphics object.


Any Queries or Comments are good to hear…

--Happy Programming

Wednesday, December 21, 2011

Custom Error Pages In ASP.NET



* Errors And Exceptions In ASP.NET - covers different kinds of errors, try-catch blocks, introduces Exception object, throwing an exception and page_error procedure.
* Application Level Error Handling in ASP.NET - goes a level higher and explains handling of unhandled errors by using Application_Error procedure in Global.asax file, using of custom Http modules, sending notification e-mail to administrator, show different error pages based on roles and logging errors to text files, database or EventLog.

This tutorial deals with user experience when error occurs. When error is occurred on ASP.NET web application, user will get default error page (which is not so nice looking, also known as "Yellow screen of death"). This error page confuses average visitor who don't know the meaning of "Runtime Error". Although developers like to know many details about an error, it is better to show more friendly error page to your users.

          Web.config file contains a customErrors section inside . By default, this section looks like this: <customErrorsmode="RemoteOnly" />
As you see, there is mode parameter inside customErrors tag which value is "RemoteOnly". This means that detailed messages will be shown only if site is accessed through a http://localhost. Site visitors, who access from external computers will see other, more general message, like in image bellow:



mode parameter can have three possible values:
- RemoteOnly - this is default value, detailed messages are shown if you access through a localhost, and more general (default) error message to remote visitors.
- On - default error message is shown to everyone. This could be a security problem since part of source code where error occurred is shown too.
- Off - detailed error message is shown to everyone.
Default ASP.NET error message hides details about error, but still is not user friendly. Instead of this page, ASP.NET allows you to create your own error page. After custom error page is created, you need to add a reference to it in customErrors section by using a defaultRedirect parameter, like in code snippet bellow:

<customErrors mode="RemoteOnly" defaultRedirect="~/DefaultErrorPage.htm" />

When error occured, ASP.NET runtime will redirect visitor to DefaultErrorPage.htm. On custom error page you can gently inform your visitors what happened and what they can do about it.

DefaultErrorPage.htm will display when any error occurs. Also, there is a possibility to show different custom error pages for different types of exceptions. We can do that by using sub tag. In code sample bellow, specialized pages are shown for errors 404 (File Not Found) and error 403 (Forbidden). 

<customErrors mode="On" defaultRedirect="~/DefaultErrorPage.htm" >
  <error statusCode="404" redirect="~/FileNotFound.htm"/>
  <error statusCode="403" redirect="~/Forbidden.htm"/>
customErrors>

How to set error page for every ASP.NET page
Custom pages configured in Web.config affect complete web site. It is possible also to set error page for every single ASP.NET page. We can do this by using @Page directive. Code could look like this:

< %@ Page language="C#" Codebehind="SomePage.aspx.cs" errorPage="MyCustomErrorPage.htm" AutoEventWireup="false"%>
Http Error page codes
There are different Http codes that your web application could return. Some errors are more often than others. You probably don't need to cover all cases. It is ok to place custom error pages for the most common error codes and place default error page for the rest.
400 Bad Request
Request is not recognized by server because of errors in syntax. Request should be changed with corrected syntax.
401 Not Authorized
This error happens when request doesn't contain authentication or authorization is refused because of bad credentials.
402 Payment Required
Not in use, it is just reserved for the future
403 Forbidden
Server refused to execute request, although it is in correct format. Server may or may not provide information why request is refused.
404 Not Found
Server can not find resource requested in URI. This is very common error, you should add custom error page for this code.
405 Method Not Allowed
There are different Http request methods, like POST, GET, HEAD, PUT, DELETE etc. that could be used by client. Web server can be configured to allow or disallow specific method. For example, if web site has static pages POST method could be disabled. There are many theoretical options but in reality this error usually occurs if POST method is not allowed.
406 Not Acceptable
Web client (browser or robot) could try to receive some data from web server. If that data are not acceptable web server will return this error. Error will not happen (or very rarely) when web browser request the page.
407 Proxy Authentication Required
This error could occur if web client accesses to web server through a proxy. If proxy authentication is required you must first login to proxy server and then navigate to wanted page. Because of that this error is similar to error 401 Not Authorized, except that here is problem with proxy authentication.
408 Request Timeout
If connection from web client and server is not established in some time period, which is defined on web server, then web server will drop connection and send error 408 Request Timeout. The reason could be usually temporarily problem with Internet connection or even to short time interval on web server.
409 Conflict
This error rarely occurs on web server. It means that web request from client is in conflict with some server or application rule on web server.
410 Gone
This error means that web server can't find requested URL. But, as opposed to error 404 Not Found which says: "That page is not existing", 410 says something like: "The page was here but not anymore". Depending of configuration of web server, after some time period server will change error message to 404 Not Found.
411 Length Required
This error is rare when web client is browser. Web server expects Content-Length parameter included in web request.
412 Precondition Failed
This is also rare error, especially if client is web browser. Error occurs if Precondition parameter is not valid for web server.
413 Request Entity Too Large
This error occurs when web request is to large. This is also very rare error, especially when request is sent by web browser.
414 Request URI Too Long
Similar like error 413, error occurs if URL in the web request is too long. This limit is usually 2048 to 4096 characters. If requested URL is longer than server's limit then this error is returned. 2048 characters is pretty much, so this error occurs rarely. If your web application produces this error, then it is possible that is something wrong with your URLs, especially if you build it dynamically with ASP.NET server side code.
415 Unsupported Media Type
This error occurs rarely, especially if request is sent by web browser. It could be three different reasons for this error. It is possible that requested media type doesn't match media type specified in request, or because of incapability to handle current data for the resource, or it is not compatible with requested Http method.
416 Requested Range Not Satisfied
This is very rare error. Client request can contain Range parameter. This parameter represents expected size of resource requested. For example, if client asks for an image, and range is between 0 and 2000, then image should not be larger from 2000 bytes. If image is larger, this error is returned. However, web page hyperlinks usually don't specify any Range value so this error rarely occurs.
417 Expectation Failed
This is also rare error, especially if client is web browser. There is Expect parameter of request, if this Expect is not satisfied Expectation error is returned.
500 Internal Server Error
This is very common error; client doesn't know what the problem is. Server only tells that there is some problem on server side. But, on the server side are usually more information provided. If server hosts ASP.NET application, then this often means that there is an error in ASP.NET application. More details about error could be logged to EventLog, database or plain text files. To see how to get error details take a look at Application Level Error Handling In ASP.NET tutorial.
501 Not Implemented
This is rare error. It means that web server doesn't support Http method used in request. Common Http methods are POST, GET, HEAD, TRACE etc. If some other method is used and web server can't recognize it, this error will be returned.
502 Bad Gateway
This error occurs when server is working as gateway and need to proceed request to upstream web server. If upstream web server response is not correct, then first server will return this error. The reason for this error is often bad Internet connection some problem with firewall, or problem in communication between servers.
503 Service unavailable
This error means that server is temporally down, but that is planned, usually because a maintenance. Of course, it is not completely down because it can send 503 error :), but it is not working properly. Client should expect that system administrator is working on the server and server should be up again after problem is solved.
504 Gateway Timeout
Similar to error 502 Bad Gateway, there is problem somewhere between server and upstream web server. In this case, upstream web server takes too long to respond and first server returned this error. This could happen for example if your Internet connection is slow, or it is slow or overloaded communication in your local network.
505 HTTP Version Not Supported
Web server doesn't support Http version used by web client. This should be very rare error. It could happen eventually if web client tries to access to some very old web server, which doesn't support newer Http protocol version (before v. 1.x).

Show different error pages based on roles
By using of RemoteOnly value for customErrors mode parameter in Web.config you can get detailed messages when you access through a localhost and custom messages if you access remotely. This could be a problem, because sometime you need to access remotely to web application and still see detailed messages. If you have shared hosting than this is only option. Of course, you still don't want to show error details to end users.
If you use some role based security architecture you can show detailed message to single logged user (you) or to all users that belong to some role, for example "Developers". On this way, developers logged in to web application will see detailed error messages and your users will still see just friendly custom notification.
To implement this idea we need to add some code to Application_Error procedure in Global.asax file. Code could look like this:
[ C# ]
void Application_Error(object sender, EventArgs e) 
{
 
if(Context != null)
{
// Of course, you don't need to use both conditions bellow
// If you want, you can use only your user name or only role name
if(Context.User.IsInRole("Developers") || 
(Context.User.Identity.Name ==
 "YourUserName") )
{
// Use Server.GetLastError to recieve current exception object
Exception CurrentException = Server.GetLastError();

// We need this line to avoid real error page
Server.ClearError();

// Clear current output
Response.Clear();

// Show error message as a title
Response.Write(
"

Error message: " + CurrentException.Message + "

");
// Show error details
Response.Write(
"Error details:
"
);
Response.Write(CurrentException.ToString());
}
}
}

[ VB.NET ]
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
If Context IsNot Nothing Then
' Of course, you don't need to use both conditions bellow
' If you want, you can use only your user name or only role name
If Context.User.IsInRole("Developers") Or _
(Context.User.Identity.Name =
 "YourUserName") Then

' Use Server.GetLastError to recieve current exception object
Dim CurrentException As Exception = Server.GetLastError()

' We need this line to avoid real error page
Server.ClearError()

' Clear current output
Response.Clear()

' Show error message as a title
Response.Write(
"

Error message: " & _
CurrentException.Message &
 "

")
' Show error details
Response.Write(
"Error details:
"
)
Response.Write(CurrentException.ToString())
End If
End If
End Sub
ASP.NET Custom Error Pages Remarks
By using custom error pages you can achieve more professional look for your ASP.NET web application. Although your visitors will not be happy if something is not working, it will be much better if you told them that something is wrong, but you are aware of that and you will correct it as soon as possible. That will connect you closer to your users. Errors are almost unavoidable, but your competence to deal with them makes difference.
I hope that you find this tutorial helpful. Happy programming!

Saturday, November 12, 2011

SENDING MAIL USING OUTLOOK IN VB.NET


INTRODUCTION:-
                One of my clients required a desk top application that maintains contacts in a database and sends emails to the contacts in the database.  They have not provided the credentials and the details of mail server.  So I created an application that uses outlook for sending mails by using the credentials preconfigured by the outlook account.  This application can send email for multiple email accounts and with or without attachments.
FEATURES:-
·         Sending mails to multiple email accounts at a time.
·         Using configured outlook credentials.
·         No need of configuring credentials every time.
·         Sending mails with attachments.
CODE EXPLANATION:-
                Create new project and add references as follows.  These files can be downloaded or can be achieved by the sample project which is attached with this article.
  • Interop.Microsoft.Office.Core.dll
  • Interop.Outlook.dll
Let’s go to code part.  Import the following libraries apart from default
Imports Microsoft.Office.Interop.Outlook
Imports Microsoft.Office.Interop
Imports Microsoft.Office
Imports Microsoft

Here we need to create instances for outlook application; namespace and the namespace should be configured with the instance of the outlook application.  We need to configure the outbox i.e.,  the place where the sent mail will be saved in our mail folder.  Then we need to add credentials for this account.  Here we are not going to give any credentials because we need to obtain the credentials from the native outlook application using the code.  The code for this process will be as follows.

  Dim ol As New Outlook.Application()
        Dim ns As Outlook.NameSpace
        Dim fdMail As Outlook.MAPIFolder
        ns = ol.GetNamespace("MAPI")
  ns.Logon(, , True, True)

Now create a new outlook mail item and necessary fields like subject, body, destination folder for saving the message and the priority as follows,
Dim newMail As Outlook.MailItem

        'gets defaultfolder for my Outlook Outbox
        fdMail = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderOutbox)

        'assing values to the new mail mailitem
        newMail = fdMail.Items.Add(Outlook.OlItemType.olMailItem)


        With newMail
            .Subject = txtSubject.Text
            .Body = txtBody.Text
            .SaveSentMessageFolder = fdMail
            .Importance = Outlook.OlImportance.olImportanceHigh
        End With

Add Mail recipients to the mail item.  You can add more than one recipient for sending the same mail to many recipients as follows.
For Each checkedindex In chklstboxEmails.CheckedItems
            newMail.Recipients.Add(checkedindex.ToString())
            'MessageBox.Show(checkedindex.ToString())
        Next
Add attachments as follows.
If (lblAttachmentFile.Text <> "No File Selected..") Then
            Dim attachments As Outlook.Attachments = newMail.Attachments
            Dim attachment As Outlook.Attachment
            Dim sourcefile As String = lblAttachmentFile.Text
            Dim displaytext As String = sourcefile.Substring(sourcefile.LastIndexOf("\") + 1)
            Dim bodylength As String = newMail.Body.Length
            attachment = attachments.Add(sourcefile, , bodylength + 1, displaytext)
        End If
After that you can send the mail using the send() method.
newMail.Send()

This is how we can send mails by using the outlook and outlook preconfigured credentials.

Your comments are valuable for me,Thanking you,
Happy Programming

Friday, September 16, 2011

Visual Studio 11


    Today in the BUILD keynote I had the opportunity to show some of the new functionality in Microsoft® Visual Studio® 11 Developer Preview and Microsoft® Team Foundation Server Preview.  MSDN subscribers can download the previews today as well as the new release of .NET Framework 4.5 Developer Preview; general availability is on Friday, September 16.
Some exciting announcements are being made here at BUILD.  Visual Studio 11 provides anintegrated development experience that spans the entire lifecycle of software creation from architecture to code creation, testing and beyond. This release adds support for Windows 8 and HTML 5, enabling you to target platforms across devices, services and the cloud.  Integration with Team Foundation Server enables the entire team to collaborate throughout the development cycle to create quality applications.
.NET 4.5 has focused on top developer requests across all our key technologies, and includes new features for Asynchronous programming in C# and Visual Basic, support for state machines in Windows Workflow, and increased investments in HTML5 and CSS3 in ASP.NET.
We’ve shared a lot at BUILD already, for more on the future of Windows development I suggest you take a look at Steven Sinofsky and S. Somasegar’s blogs. More details on Team Foundation Server including the new service announced at BUILD and how we’re helping teams be more productive can be found on Brian Harry’s blog.

Tuesday, September 6, 2011

Image Thumbnail Creation using C#.Net




Introduction:-
            This tutorial will show you how to generate image thumbnails dynamically from an original big image.

Background:-

            Many of the web developers will show the big images as small by giving the attribute values for the image tag.  This will slow down the webpage loading.  For better performance the best method is creating the small thumbnail images for showing small size image on the web pages.  But for every upload of the images by the user we cannot create a thumbnail image, it’s a tedious process.  I planed to create a method which will create a thumbnail automatically while the image upload and saves in a separate path.  This is a light weight process and easy to use.  The only thing is you have to add one more filed for saving the thumbnail image path while dealing with databases.

Following are the features of this technique.
  • Good Quality.
  • Desired thumbnail size.

Using the code:-

            Below is the method which will generates the thumbnail and saves to the destination folder.

public void GenerateThumbNail(string sourcefile, string destinationfile,int width)
    {
        System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath(sourcefile));
        int srcWidth = image.Width;
        int srcHeight = image.Height;
        int thumbWidth = width;
        int thumbHeight;
        Bitmap bmp;
        if (srcHeight > srcWidth)
        {
            thumbHeight = (srcHeight / srcWidth) * thumbWidth;
            bmp = new Bitmap(thumbWidth, thumbHeight);
        }
        else
        {
            thumbHeight = thumbWidth;
            thumbWidth = (srcWidth / srcHeight) * thumbHeight;
            bmp = new Bitmap(thumbWidth, thumbHeight);
        }

        System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
        gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
        System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);
        gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);
        bmp.Save(Server.MapPath(destinationfile));
        bmp.Dispose();
        image.Dispose();
    }

      In the above method we are passing three parameters first one is the soruce location of the image and the second one is the destination location of the image and the third parameter is the width.  At first we need to include two namespaces

using System.Drawing;
using System.Drawing.Drawing2D;

Then create an instance image from the source file as follows

System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath(sourcefile));

After getting the image height and width using the instance of the image we need to set the targetted thumbnail image’s height and width. Create and instance for the bitmap.  By using the below logic we can get the width and height of the targetted thumbnail.  Set the thumbnails’s width and height to the bitmap.

Bitmap bmp;
        if (srcHeight > srcWidth)
        {
            thumbHeight = (srcHeight / srcWidth) * thumbWidth;
            bmp = new Bitmap(thumbWidth, thumbHeight);
        }
        else
        {
            thumbHeight = thumbWidth;
            thumbWidth = (srcWidth / srcHeight) * thumbHeight;
            bmp = new Bitmap(thumbWidth, thumbHeight);
        }

After this for creating the high quality thumbnails create an instance for the Graphics class with the bitmap.  Set the SmoothingMode and CompositingQuality to HighQuality and InterpolationMode to Hign.  Then draw a rectangle with the thumbnail’s height and width using the rectangle class and place the image inside the rectangle using the DrawImage class.  Now the bitmap image i.e., thumbnail image is ready.  Now save the thumbnail the the destination location using bmp.save(/*destination location*/) method.

            I think mostly this example will help in website development for loading webpages fast with small images instead of loading large image with small sizes.