How To: Provide Save File Dialog for an Image Request in ASP.Net

It is the default behavior of the web browsers, when you click on the image link, to open the image and display it over there. There are instances when you might want your users to remain on the page and simply download and save the image after clicking on the image link.

This functionality can be achieved in ASP.Net. Here I am going to show how to:

Create a blank ASP.Net Web Application. Now you have to create a folder to store the image to be downloaded and add and image to it.

Your solution should look similar to this:

Open the Default.aspx and create a HyperLink to the image like this:

<asp:HyperLink ID="hlDownloadImage" runat="server" NavigateUrl="~/Images/image001.jpg?Action=Download">Download Image</asp:HyperLink>

Note that the image URL is having additional parameter “Action” with value “Download”. We will see the utilization of the same in a moment.

now go and add a new file of Type ASP.Net Module ImageDownload.cs to the solution and modify the code as below:

public class ImageDownload : IHttpModule
{
    #region IHttpModule Members
    public void Dispose() { }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
    }
    #endregion

    public void context_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication app = (HttpApplication)sender;
        HttpRequest req = app.Request;
        HttpResponse res = app.Response;
        if (req.Params["Action"] != null && req.Params["Action"].ToString() == "Download")
        {
            string path = req.AppRelativeCurrentExecutionFilePath;
            res.ContentType = "image/jpeg";
            res.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(path));
            res.TransmitFile(app.Server.MapPath(path));
            res.End();
        }
    }
}

Modify the web.config file to include following in <httpModules> section:

<add name="ImageDownload" type="WebUploadManager.ImageDownload"/>

You are done. Run the application and click on the Link for the image and you will see the Run/Save dialog. Try removing the Action parameter from the NavigationURL of the hyperlink; image will be displayed on screen as the default behavior of the browser.

Server.MapPath

In general whenever we need to get physical location of the file in ASP.Net Application, we use Server.MapPath. This is the most commonly adopted method. If you want the file to be located with reference to the path of the current WebPage, then the implementation holds good, but, in case you have to always refer the file from the application root, this method gives you different results. Take the following scenario, where the application directory structure is as follows:

  • Root
    • Data
      • Data.XML
    • ClassA.cs (uses Server.MapPath(“\Data\Data.XML”))
    • ClassB.cs (uses ClassA to get the XML file contents)
    • SubDir
      • ClassC.cs (uses ClassA to get the XML file contents)

In the above scenario the ClassC will fail to retrive the contents in case of the WebApplication is hosted in a virtual directory. The application will work fine if it is a website. So the implementation will not show any errors when we run the application from the Visual Studio. to make it more generic we can replace the Server.MapPath with

System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + @”Data\Data.XML”.

Great Indian Developer Summit 2009

gids-logo

Four well packed days with Information and Technology that too latest in trend and which is going to change the future is called Great Indian Developer Summit 2009. Not only that, thousands of participants, 75+ presentations on technologies, 15+ Labs driven by experts from all over the globe and all this organized by media leader Saltmarch Media in a great environment of IISC, Bangalore.
day2

DAY 2:
Rich Internet Applications

This year also as the previous years it has came to prove that whatever new in a developer’s mind comes has been achieved and has not only given satisfaction to him but to the consumer too.

As a Developer & Designer, I pulled myself in the second day of the summit because this day the experts were gonna talk about RIA (Rich Internet Application), the future of web applications. On this particular day GIDS talked about following topics:

Web 2.0 & Social Applications
Enterprise 2.0
Mashups
Social Networking
Ajax In Action
Comet
Dynamic Scripting
Browsers & Rich UI
Rich Web Security
Rich Web Stories

There were five parallel sessions going on at a time, so I was not able to attend every session. But I was able to focus myself to the session of my interest. I am a developer on Microsoft platform and having a keen interest in new Microsoft Technologies, so picked up sessions targeted on Silverlight 3.

I have attended following sessions:

Unravelling the New in Microsoft Silverlight 3
Nahas Mohammed star1star1star1star1
Deep Dive – Microsoft Silverlight Pipelines
Praveen Srivatsa star1star1star1
Building Rich UI using ASP.Net AJAX, AXAJ Control Toolkit & jQuery
Harish Ranganathan star1star1star1star1
Reusable Components for Building Killer RIAs (on Adobe Flex)
Anirudh Sasikumar star1star1star1

You might be thinking that when I am talking about Microsoft Silverlight, what I was doing in the session for the Flex. The reason is very simple, when you have the chance to learn new technologies and side by side compare them with similar technologies, why shouldn’t? So before leaving for the day I grabbed this opportunity too. I have also rated the presenters along with their contents. All over here I would like to say that I had a nice Thursday. The biggest takeaway for me was numerous seed of growth opportunities, which is a result of combined efforts of huge exposure to technology and GIDS.

To conclude this post here I would like to encourage the readers to participate in this kind of events. These events not only give you a chance to explore the new and happening world around you, but also provide a good networking environment, which in terms help you grow in your career.

Regular Expression with C#: Part 1

In this tutorial you will learn.

  1. Extract Text From The Web pages
  2. Use a special software (Expresso) to make writing Regular Expressions easier
  3. Write and Use Regular Expressions in C#

This tutorial is intended for people who know how to do some basic Regular Expressions and know the syntax of the language. Since there is a lot of material to cover I won’t go over everything.

Till a little while ago I never really thought much of Regular Expressions. I used them a couple of times just to validate an email address or web address etc. It was not till one day I thought of making a web scraping program that would deal with pages from a site and then store all the grabbed information in an xml file.

The need of grabbing the contents came across while studying the RSS technology. In RSS you need to send user a predefined output in XML format with some extra tags. In this tutorial I will not be reaching to that extent, but will give you all an idea about how to just grab the data from the site. Then its upon you, how to utilize the knowledge.

I will take the example of a google search result page, where the results are listed in a well organized manner. We will find out some text from the page for each result and display the result in my own format.

Step 1: Create a web application to host our functionality.

  1. Open Visual Studio 2005
  2. File Menu > New > Web Site
  3. Select ASP.Net Web Site from the listed project templates
  4. Select Language as Visual C# and Click Ok.

You will see the Default.aspx page in the solution explorer, if not add it.

Step 2: Write code to get the desired page source (Google Search Results).

  1. Drag n Drop a TextBox, Button and a Label Control on the Page in design mode.
  2. Rename TextBox1 to txtSearch, Button1 to btnSearch and Label1 to lblResults.
  3. On btnSearch Click event write the following code.
protected void btnGetRating_Click(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(txtSearch.Text.Trim()))
    {
        txtSearch.Text = "Google";
    }
    string URL = txtSearch.Text;
    string IMDBData = WebPage.getContents(URL);
    string fullRating = getRating(IMDBData.Replace("n", "").Replace("rn", "").Replace("nr", ""));
    lblResults.Text = fullRating;
}

Continue reading Regular Expression with C#: Part 1