Abstract class implementation with asp.net

Category : Asp.Net

I’ve written one abstract class in my project. Then I realized that I have to understand clearly why we needed to use abstract class. As all we know that abstract class can not instantiate.

But we can use like standardize to inherit from all of sub-classes. My sample abstract class as follows. There is no implementation inside all of the abstract method and abstract properties, only will contain definition.

Abstract Class Sample :

All of the sub classes will override by inherit abstract class in order to implement actual logic of the methods and properties. Are you confuse now ? Please take a look at the following sample.

public abstract class AbstractClassSample
{

#region ” Abstract Properties ”

public abstract string FieldName1
{
get;
set;
}

public abstract string FieldName2
{
get;
set;

}

public abstract List<OtherObject> OtherObject
{
get;
set;

}

public abstract string TableName1
{
get;
set;
}

public abstract string TableName2
{
get;
set;
}

public virtual string Database1
{
get;
set;
}

public virtual string Database2
{
get;
set;
}

#endregion

}

When we call abstract class for subclasses, all the abstract method would be same and needed to contain in subclasses. So, Some property will same and some property will not same between abstract class and sub class, you can use virtual property in abstract class. Take a look at the following as sample.

public class diningOverviewObject : pagedataAbstract
{
private string _fieldName1         = string.Empty;
private string _fieldName2         = string.Empty;
private List<OtherObject> _bannerGroupObject = new List<OtherObject>();
private string _tableName1         = string.Empty;
private string _tableName2         = string.Empty;

#region Properties

public override string FieldName1
{
get{return _fieldName1;}
set{_fieldName1 = value;}
}

public override  string FieldName2
{
get{return _fieldName1;}
set{_fieldName1 = value;}
}

public override List<OtherObject> OtherObject
{
get{return _fieldName1;}
set{_fieldName1 = value;}
}

public override string TableName1
{
get{return _fieldName1;}
set{_fieldName1 = value;}        }

public override string TableName2
{
get{return _fieldName1;}
set{_fieldName1 = value;}        }

#endregion

}

String builder versus string concat

Category : Asp.Net

I’ve to explain that differences between string builder and string concat in order to choose when you  have to do string combination.

Let me show the right way to choose.

 

 

How to implement list property inside object

Category : Asp.Net

I’ve to consider that I need to create List collection inside one object, for example,  List<IcodersObj> _icdoers = new List<IcodersObj>() something like that . You will a bit confuse now,huh?… List collection inside have one object and that object have attribute and property itself.  You better take a look at the sample to clear.

public class HomeBlogObject
 {

private string    _Blogtitle            = string.Empty;
 private string    _categorytitle             = string.Empty;
 private List<IcodersObject> _icodersObject = new List<IcodersObject>();

public string BlogTitle
 {
 get { return _blogtitle; }
 set { _blogtitle = value; }
 }

public string CategoryTitle
 {
 get { return _categorytitle; }
 set { _categorytitle = value; }
 }

public List<IcodersObject> IcodersObject
 {
 get
 {
 return _icodersObject
 }

set
 {
 _icodersObject = value;

}
 }

}

The inside List object using object structure as follows.  You have to notice that the construct have to accept some parameter value and needed to assign those parameter value to property.

When you add the value to this object, the better way is by using  parameter value pass through from constructor.

public class icodersObj
 {

public icodersObj(string image, string imagetitle)
 {
 Image= image
 ImageTitle = imagetitle;
 }

public string Image{ get; set; }
 public string ImageTitle { get; set; }

}

List sorting by using Icomparable with two property values.

Category : Asp.Net

I just have to share you that by applying Icomparable to sort the list object as default sorting as what we would like sort.

public class IcodersObject : IComparable<IcodersObject>
{

private int         _id;
 private string      _name;

public int ID
 {
 get { return _id; }
 set { _id = value; }
 }

public string Name
 {
 get { return _name; }
 set { _name = value; }
 }

public int CompareTo(IcodersObject comparerObject)
 {

if (this.ID < comparerObject.ID)
 {
 return 1;
 }
 else if (this.ID > comparerObject.ID)
 {
 return -1;
 }
 else if (this.ID == comparerObject.ID)
 {
 return this.Name.CompareTo(comparerObject.Name);
 }
 else
 {
 return string.Compare(this.Name, comparerObject.Name);
 }

}

}

Then you can apply sort() method for List object after we had added some data after retrieve from database. Take a look at the following as sample that how I have apply for sort() method.

public List<IcodersObject> getIcodersByID(int ID)
 {
 List<IcodersObject> Icoderslist = new List<IcodersObject>();
 dalIcoders _dalIcoders = new dalIcoders();
 DataTable dt = new DataTable("IcodersTable");
 IcodersObject IcodersObj = default(IcodersObject);

try
 {
 dt = _dalIcoders.getIcodersByID(ID,langID);

if (dt != null | !object.ReferenceEquals(dt, DBNull.Value))
 {
 foreach (DataRow dr in dt.Rows)
 {
 IcodersObj                = new IcodersObject();
 IcodersObj.ID            = Convert.ToInt32(dr["ID"]);
 IcodersObj.Name       =  (dr["Name"].ToString());

Icoderslist.Add(IcodersObj);

}

 // sort method will sort by ID and name as default.
 Icoderslist.Sort();
 }
 else
 {
 Icoderslist = null;
 }
 }
 catch (Exception e)
 {
 throw new Exception(e.ToString());
 }
 finally
 {
 _dalIcoders = null;
 }

return Icoderslist;

}

Randomly Display Data from Database by Implmenting Inside User Control

Category : Asp.Net, Vb.Net

I’ve wrritend one user control for the showing the images and the abstract data randomly by applying user control.Just take a look at the following how to implement the randomly display image and data from database.

<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="FeaturedRandom.ascx.vb" Inherits="Icoder.FeaturedRandom" %>

<style type="text/css">
/* Success story Featured Listing */

.random_img{ width:82px; height:82px; float:left;padding-left:20px; padding-right:20px; text-align:left;}

.random_more
{

background: url("/images/more.png") no-repeat scroll 0 0 transparent;
display: block;
height: 22px;
margin-top: 5px;
text-indent: -9999px;
width: 88px;
padding-right:20px; text-align:left;
float:right;
}

.random_p{ line-height:13px; font-size:11px; padding-left:20px; padding-right:20px; text-align:left;}

.random_h4{color:#9D0A0E; margin-bottom:5px; font-size:12px; line-height:14px;font-weight:bold;padding-left:20px; padding-right:20px; text-align:left;}
</style>
<div>
<div>
<h2>Featured Random Data</h2>
<div style="margin-left:20px;">
<div>
<asp:Literal ID="ltrFeaturedrandom" runat="server"></asp:Literal>
</div>
</div>

<h4><asp:Literal ID="ltrDescription" runat="server"></asp:Literal></h4>

<asp:Label   CssClass="random_p" ID="lblCountry" runat="server"></asp:Label><br>
<asp:Label CssClass="random_p" ID="lblJobTitle" runat="server" ></asp:Label><br>
<asp:Label CssClass="random_p" ID="lblCompanyName" runat="server" ></asp:Label><br>
<a href="/icoders/Posts?id=<%=ReadMoreID%>">Read More</a>

</div>
</div>

Public Partial Class FeaturedRandom
 Inherits System.Web.UI.UserControl

 Protected ReadMoreID As String = ""
 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

 ' Get all data
 Dim icodersList As List(Of IcodersObject) = IcodersManager.GetAllIcoders()

 Dim randomNumber As Integer = 0
 If icodersList.Count > 0 Then
 Dim myRandom As New Random()
 randomNumber = myRandom.Next(0, icodersList.Count - 1)

 If icodersList(randomNumber).ImageThumbnail <> "" Or icodersList(randomNumber).ImageThumbnail IsNot Nothing Or icodersList(randomNumber).ImageThumbnail IsNot DBNull.Value Then
 ltrFeaturedrandom.Text = "<a href=""/icoders/Posts?id=" & icodersList(randomNumber).ID & """ target=""_self""><img style=""height:110px;width:150px;border-width:0px;"" src=""" & icodersList(randomNumber).ImageThumbnail & """ ></a>"
 ltrDescription.Text = icodersList(randomNumber).Name
 lblCountry.Text = icodersList(randomNumber).Country
 lblJobTitle.Text = icodersList(randomNumber).JobTitle
 lblCompanyName.Text = icodersList(randomNumber).CompanyName
 ReadMoreID = icodersList(randomNumber).ID
 End If

 End If
 End Sub

End Class

Linq 3 tier architecture with Vb.Net & Asp.Net

Category : Asp.Net, LINQ, Vb.Net

Today I will going to explain how to implement 3 tier architecture by applying LINQ. LINQ is the one way to consider for the application architecture set up.  As all we know that LINQ can perform integrate with C# OR VB.net programming languages.That is why LINQ can integrate between programming languages and databases Query Statment, as well as providing a single querying interface for a multitude of data sources.

In this sample will contain gridvew databinding by using 3 tier architecture with LINQ. Take a look at the step by step as following.

Create new web project and add the new file. After that click and drag the gridview in the aspx file.


<asp:GridView ID="gvIcoder" runat="server" Width="100%" AutoGenerateColumns="False"
 AllowPaging="True" DataKeyNames="IcoderID" PageSize="5">
<FooterStyle CssClass="GridFooter"></FooterStyle>
<RowStyle CssClass="GridItem"></RowStyle>
<AlternatingRowStyle CssClass="GridAltItem"></AlternatingRowStyle>
<HeaderStyle CssClass="GridHeader" HorizontalAlign="Left"></HeaderStyle>
<Columns>
 <asp:BoundField DataField="IcoderID" HeaderText="Icoder Code"/>
 <asp:BoundField DataField="FullName" HeaderText="Name"/>
 <asp:BoundField DataField="post" HeaderText="Post"  />
 <asp:BoundField DataField="Date" HeaderText="Date" DataFormatString="{0:dd/MM/yyyy}" />
</Columns>
</asp:GridView>

Aspx code behind process as following.


Imports System
Imports System.Data
Imports System.Data.Linq
Imports Sample.BusinessLayer
Imports Sample.IcoderLinq

Partial Public Class Icoder
 Inherits System.Web.UI.WebPage

 Protected Overrides Sub onLoad(ByVal e As System.EventArgs)

 objIcoder = New BLIcoder

 If Not Page.IsPostBack Then
 Call BindGridView()

 End If

 End Sub

 Private Sub BindGridView()
 'Call to display all records

 Dim LocalDataTable As Table(Of tblIcoder)
 LocalDataTable = objIcoder.SelectRecordAll()

 gvIcoder.DataSource = (From tbl In LocalDataTable _
 Select tbl.IcoderID, _
 tbl.FullName, _
 tbl.post, _
 tbl.date)
 gvIcoder.DataBind()

 End Sub

End Class

Create the library project name like Linq. After that select linq to sql class and give the name like IcoderLinq.dbml. After that select the table onto that file. Create the data access layer by using the class library project.  Please give the name as dataaccesslayer. Copy and paste the follwing sample into your project.


Imports System.Data
Imports System.Data.Linq
Imports Sample.DataLinq

Public Class DALIcoder

 Private objDataContext As New IcoderLinq1DataContext

 Public Function SelectRecordAll() As Table(Of tblIcoder)
 Try
 Return objDataContext.tblIcoder
 Catch ex As Exception
 Throw ex
 End Try
 End Function
 ENd Clss

Then needed to  create the business layer project and class name as BLIcoder.

Public Class BLIcoder

 Private objDataAccess As New DALIcoder

 '------------------------------------------------------------------------------------------
 'Name    : SelectRecordAll
 'Purpose : Call Data Access method to retrieve all records from table
 'Returns : Table Collection
 '------------------------------------------------------------------------------------------
 Public Function SelectRecordAll() As Table(Of tblIcoder)
 Try
 Return objDataAccess.SelectRecordAll()
 Catch ex As Exception
 Throw ex
 End Try
 End Function
End Class

Creation of Error Log file by using Global.asax file

Category : Asp.Net, Vb.Net

I’ve created global.asax file for the dotnet project. After that I’ve written the creation of the error log file in Application_Start event into the global.asax file. I do know sometime you will have to create error tacing file in order to know when the error has been occured. I just shared the idea how to implment it. Take a look at the following.

Imports System.Web.SessionState
Imports System.Threading
Imports System.Security.Principal
Imports System.IO

Public Class Global_asax
 Inherits System.Web.HttpApplication

 Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
 ' Fires when the application is started
 SqlCacheDependencyAdmin.EnableNotifications(ConfigurationManager.ConnectionStrings("IcoderConnectionString").ConnectionString)
 SqlCacheDependencyAdmin.EnableTableForNotifications(ConfigurationManager.ConnectionStrings("IcoderConnectionString").ConnectionString, "Sites")
 SqlCacheDependencyAdmin.EnableTableForNotifications(ConfigurationManager.ConnectionStrings("IcoderConnectionString").ConnectionString, "Configs")
 SqlCacheDependencyAdmin.EnableTableForNotifications(ConfigurationManager.ConnectionStrings("IcoderConnectionString").ConnectionString, "Pages")
 SqlCacheDependencyAdmin.EnableTableForNotifications(ConfigurationManager.ConnectionStrings("IcoderConnectionString").ConnectionString, "Users")
 SqlCacheDependencyAdmin.EnableTableForNotifications(ConfigurationManager.ConnectionStrings("IcoderConnectionString").ConnectionString, "Roles")
 SqlCacheDependencyAdmin.EnableTableForNotifications(ConfigurationManager.ConnectionStrings("IcoderConnectionString").ConnectionString, "UserRole")

 End Sub

 Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
 ' Fires when the session is started
 End Sub

 Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
 ' Fires at the beginning of each request
 End Sub

 Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
 ' Fires upon attempting to authenticate the user
 End Sub

 Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
 ' Fires when an error occurs

 'Get the Error.
 Dim ex As System.Exception = Server.GetLastError()

 'Log the error
 Try

 If Request.ServerVariables("HTTP_USER_AGENT").ToString.ToLower.IndexOf("webdav") >= 0 Or _
 Request.ServerVariables("HTTP_USER_AGENT").ToString.ToLower.IndexOf("other_user_agents") >= 0 Then

 ' Do Nothing... For WEBDAV and other user agents

 Else

 'Gets folder & file information of the log file
 Dim folderName As String = Server.MapPath(ConfigurationManager.AppSettings("ErrLogFolder").ToString())
 Dim fileName As String = folderName & "error_" & Date.Now.ToString("yyMMdd") & ".log"

 Dim fs As FileStream
 Dim sw As StreamWriter

 'Check for existence of logger file
 If File.Exists(fileName) Then
 fs = New FileStream(fileName, FileMode.Append, FileAccess.Write)
 Else
 fs = File.Create(fileName)
 End If

 sw = New StreamWriter(fs)

 Try

 sw.WriteLine("")
 sw.WriteLine("[" & DateTime.Now & "] =========================================================================================")
 sw.WriteLine("")
 sw.WriteLine("SERVER NAME: " & Request.ServerVariables("SERVER_NAME"))
 sw.WriteLine("USER AGENT: " & Request.ServerVariables("HTTP_USER_AGENT"))
 sw.WriteLine("REMOTE ADDR: " & Request.ServerVariables("REMOTE_ADDR"))

 sw.WriteLine("FORM: " & Request.Form.ToString())
 sw.WriteLine("QUERYSTRING: " & Request.QueryString.ToString())

 sw.WriteLine("")
 sw.WriteLine("INNER EXCEPTION ------------------------------------------- ")
 sw.WriteLine("MESSAGE")
 sw.WriteLine(ex.InnerException.Message.ToString())
 sw.WriteLine("SOURCE")
 sw.WriteLine(ex.InnerException.Source.ToString())
 sw.WriteLine("TARGETSITE")
 sw.WriteLine(ex.InnerException.TargetSite.ToString())
 sw.WriteLine("STACKTRACE")
 sw.WriteLine(ex.InnerException.StackTrace.ToString())

 sw.WriteLine("")
 sw.WriteLine("EXCEPTION ------------------------------------------- ")
 sw.WriteLine("MESSAGE")
 sw.WriteLine(ex.Message.ToString())
 sw.WriteLine("SOURCE")
 sw.WriteLine(ex.Source.ToString())
 sw.WriteLine("TARGETSITE")
 sw.WriteLine(ex.TargetSite.ToString())
 sw.WriteLine("STACKTRACE")
 sw.WriteLine(ex.StackTrace.ToString())

 sw.Close()
 fs.Close()

 Catch miscEx As Exception

 ' Do Nothing... :(
 'Response.Write(miscEx.Message.ToString)
 'Response.End()

 End Try

 End If

 Catch ex0 As Exception

 ' Do Nothing... :(
 'Response.Write(ex0.Message.ToString)
 'Response.End()

 End Try

 'Redirect to default error page or 404 page
 If ex.GetType() Is GetType(HttpException) Then
 If CType(ex, HttpException).GetHttpCode = 404 Then
 '404
 Dim siteid As Integer = UrlRewriter.GetSiteIDFromURL(Request.RawUrl)
 Dim urlToRedirect As String = SitesManager.GetCurrentSitePath_FromDatabase(siteid) & IcoderConfigManager.GetConfigValueByKey("error_404", siteid)
 urlToRedirect &= "?errorpath=" & Request.RawUrl
 Response.Redirect(urlToRedirect)
 End If
 ElseIf ex.GetType() Is GetType(System.Web.HttpRequestValidationException) Then
 'Request validation exception
 Response.Redirect(IcoderConfigManager.GetConfigValueByKey("error_request_validation", UrlRewriter.GetSiteIDFromURL(Request.RawUrl)))
 End If
 'Response.Redirect(IcoderConfigManager.GetConfigValueByKey("error_custom", UrlRewriter.GetSiteIDFromURL(Request.RawUrl)))

 End Sub

 Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
 ' Fires when the session ends
 End Sub

 Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
 ' Fires when the application ends
 End Sub

End Class

For the Asp.net (c#) sample as following.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web.SessionState;
using System.Threading;
using System.Security.Principal;
using System.IO;

public class Global_asax : System.Web.HttpApplication
{

 public void Application_Start(object sender, EventArgs e)
 {
 // Fires when the application is started
 SqlCacheDependencyAdmin.EnableNotifications(ConfigurationManager.ConnectionStrings("IcoderConnectionString").ConnectionString);
 SqlCacheDependencyAdmin.EnableTableForNotifications(ConfigurationManager.ConnectionStrings("IcoderConnectionString").ConnectionString, "Sites");
 SqlCacheDependencyAdmin.EnableTableForNotifications(ConfigurationManager.ConnectionStrings("IcoderConnectionString").ConnectionString, "Configs");
 SqlCacheDependencyAdmin.EnableTableForNotifications(ConfigurationManager.ConnectionStrings("IcoderConnectionString").ConnectionString, "Pages");
 SqlCacheDependencyAdmin.EnableTableForNotifications(ConfigurationManager.ConnectionStrings("IcoderConnectionString").ConnectionString, "Users");
 SqlCacheDependencyAdmin.EnableTableForNotifications(ConfigurationManager.ConnectionStrings("IcoderConnectionString").ConnectionString, "Roles");
 SqlCacheDependencyAdmin.EnableTableForNotifications(ConfigurationManager.ConnectionStrings("IcoderConnectionString").ConnectionString, "UserRole");
 }

 public void Session_Start(object sender, EventArgs e)
 {
 // Fires when the session is started
 }

 public void Application_BeginRequest(object sender, EventArgs e)
 {
 // Fires at the beginning of each request
 }

 public void Application_AuthenticateRequest(object sender, EventArgs e)
 {
 // Fires upon attempting to authenticate the user
 }

 public void Application_Error(object sender, EventArgs e)
 {
 // Fires when an error occurs

 //Get the Error.
 System.Exception ex = Server.GetLastError();

 //Log the error

 try {

 if (Request.ServerVariables["HTTP_USER_AGENT"].ToString().ToLower().IndexOf("webdav") >= 0 | Request.ServerVariables["HTTP_USER_AGENT"].ToString().ToLower().IndexOf("other_user_agents") >= 0) {
 // Do Nothing... For WEBDAV and other user agents

 } else {
 //Gets folder & file information of the log file
 string folderName = Server.MapPath(ConfigurationManager.AppSettings("ErrLogFolder").ToString());
 string fileName = folderName + "error_" + System.DateTime.Now.ToString("yyMMdd") + ".log";

 FileStream fs = null;
 StreamWriter sw = null;

 //Check for existence of logger file
 if (File.Exists(fileName)) {
 fs = new FileStream(fileName, FileMode.Append, FileAccess.Write);
 } else {
 fs = File.Create(fileName);
 }

 sw = new StreamWriter(fs);

 try {
 sw.WriteLine("");
 sw.WriteLine("[" + DateTime.Now + "] =========================================================================================");
 sw.WriteLine("");
 sw.WriteLine("SERVER NAME: " + Request.ServerVariables["SERVER_NAME"]);
 sw.WriteLine("USER AGENT: " + Request.ServerVariables["HTTP_USER_AGENT"]);
 sw.WriteLine("REMOTE ADDR: " + Request.ServerVariables["REMOTE_ADDR"]);

 sw.WriteLine("FORM: " + Request.Form.ToString());
 sw.WriteLine("QUERYSTRING: " + Request.QueryString.ToString());

 sw.WriteLine("");
 sw.WriteLine("INNER EXCEPTION ------------------------------------------- ");
 sw.WriteLine("MESSAGE");
 sw.WriteLine(ex.InnerException.Message.ToString());
 sw.WriteLine("SOURCE");
 sw.WriteLine(ex.InnerException.Source.ToString());
 sw.WriteLine("TARGETSITE");
 sw.WriteLine(ex.InnerException.TargetSite.ToString());
 sw.WriteLine("STACKTRACE");
 sw.WriteLine(ex.InnerException.StackTrace.ToString());

 sw.WriteLine("");
 sw.WriteLine("EXCEPTION ------------------------------------------- ");
 sw.WriteLine("MESSAGE");
 sw.WriteLine(ex.Message.ToString());
 sw.WriteLine("SOURCE");
 sw.WriteLine(ex.Source.ToString());
 sw.WriteLine("TARGETSITE");
 sw.WriteLine(ex.TargetSite.ToString());
 sw.WriteLine("STACKTRACE");
 sw.WriteLine(ex.StackTrace.ToString());

 sw.Close();
 fs.Close();

 } catch (Exception miscEx) {
 // Do Nothing... :(
 //Response.Write(miscEx.Message.ToString)
 //Response.End()

 }

 }

 } catch (Exception ex0) {
 // Do Nothing... :(
 //Response.Write(ex0.Message.ToString)
 //Response.End()

 }

 //Redirect to default error page or 404 page
 if (object.ReferenceEquals(ex.GetType(), typeof(HttpException))) {
 if (((HttpException)ex).GetHttpCode == 404) {
 //404
 int siteid = UrlRewriter.GetSiteIDFromURL(Request.RawUrl);
 string urlToRedirect = SitesManager.GetCurrentSitePath_FromDatabase(siteid) + IcoderConfigManager.GetConfigValueByKey("error_404", siteid);
 urlToRedirect += "?errorpath=" + Request.RawUrl;
 Response.Redirect(urlToRedirect);
 }
 } else if (object.ReferenceEquals(ex.GetType(), typeof(System.Web.HttpRequestValidationException))) {
 //Request validation exception
 Response.Redirect(IcoderConfigManager.GetConfigValueByKey("error_request_validation", UrlRewriter.GetSiteIDFromURL(Request.RawUrl)));
 }
 //Response.Redirect(IcoderConfigManager.GetConfigValueByKey("error_custom", UrlRewriter.GetSiteIDFromURL(Request.RawUrl)))

 }

 public void Session_End(object sender, EventArgs e)
 {
 // Fires when the session ends
 }

 public void Application_End(object sender, EventArgs e)
 {
 // Fires when the application ends
 }

}


How to use ASHX file in Vb.Net & Asp.Net

Category : Asp.Net, Vb.Net

I will going to explain how to use ASHX Handler in Asp.net & Vb.net.At first, you have to add ASHx file in your web project.

<%@ WebHandler Language="VB" %>

Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.IO
Imports System.Collections.Generic
Imports System.Xml

Public Class FileSystemHandler
 Implements IHttpHandler
 #Region "IHttpHandler Members"

 Private pathToConfigFile As String = "~/MappingFile.mapping"
 Private _context As HttpContext
 Private Property Context() As HttpContext
 Get
 Return _context
 End Get
 Set(ByVal value As HttpContext)
 _context = value
 End Set
 End Property

 Public Sub ProcessRequest(ByVal context__1 As HttpContext) Implements IHttpHandler.ProcessRequest
 Context = context__1

 If Context.Request.QueryString("path") Is Nothing Then
 Exit Sub
 End If

 Dim virtualPathToFile As String = Context.Server.HtmlDecode(Context.Request.QueryString("path"))
 Dim physicalPathToFile As String = ""
 Dim mappedPathsInConfigFile As Dictionary(Of String, String) = Me.GetMappingsFromConfigFile()
 For Each mappedPath As KeyValuePair(Of String, String) In mappedPathsInConfigFile
 If virtualPathToFile.ToLower().StartsWith(mappedPath.Key.ToLower()) Then
 ' Build the physical path to the file ;
 physicalPathToFile = virtualPathToFile.Replace(mappedPath.Key, mappedPath.Value).Replace("/", "\")

 ' Brak the foreach loop ;
 Exit For
 End If
 Next

 ' The docx files are downloaded ;
 If Path.GetExtension(physicalPathToFile).Equals(".docx", StringComparison.CurrentCultureIgnoreCase) Then
 ' Handle .docx files ;
 Me.WriteFile(physicalPathToFile, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", Context.Response)
 End If

 If Path.GetExtension(physicalPathToFile).Equals(".jpg", StringComparison.CurrentCultureIgnoreCase) Then
 ' Handle .jpg files ;
 WriteFile(physicalPathToFile, "image/jpeg", Context.Response)
 End If

 Context.Response.WriteFile(physicalPathToFile)
 End Sub

 ''' <summary>
 ''' Forces browser to download the file
 ''' </summary>
 ''' <param name="physicalPathToFile">Physical path to the file on the server </param>
 ''' <param name="contentType">The file content type</param>
 Private Sub WriteFile(ByVal physicalPathToFile As String, ByVal contentType As String, ByVal response As HttpResponse)
 response.Buffer = True
 response.Clear()
 Dim ct As String = response.ContentType
 If Not contentType = "" Then
 response.ContentType =  contentType
 End If

 Dim extension As String = Path.GetExtension(physicalPathToFile)

 If extension <> ".htm" AndAlso extension <> ".html" AndAlso extension <> ".xml" Then
 response.AddHeader("content-disposition", "attachment; filename=" & Path.GetFileName(physicalPathToFile))
 End If
 response.WriteFile(physicalPathToFile)
 response.Flush()
 response.[End]()
 End Sub

 Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
 Get
 Return False
 End Get
 End Property

 ''' <summary>
 ''' Retrieves the mapping for view paths ;
 ''' </summary>
 ''' <param name="virtualPathToConfigFile">The fvirtual path to the config file </param>
 ''' <returns>The mappings </returns>
 Private Function GetMappingsFromConfigFile() As Dictionary(Of String, String)
 Dim configFile As New XmlDocument()
 Dim physicalPathToConfigFile As String = Context.Server.MapPath(Me.pathToConfigFile)
 configFile.Load(physicalPathToConfigFile)
 ' Load the configuration file ;
 Dim rootElement As XmlElement = configFile.DocumentElement
 Dim mappingsSection As XmlNode = rootElement.GetElementsByTagName("Mappings")(0)
 ' get all mappings ;
 Dim mappingsFromConfigFile As New Dictionary(Of String, String)()
 For Each mapping As XmlNode In mappingsSection.ChildNodes
 Dim virtualPathAsNode As XmlNode = mapping.SelectSingleNode("child::VirtualPath")
 Dim physicalPathAsNode As XmlNode = mapping.SelectSingleNode("child::PhysicalPath")
 mappingsFromConfigFile.Add(Me.AddSlashAtEndOfVirtualPath(virtualPathAsNode.InnerText), Me.AddSlashAtEndOfPhysicalPath(physicalPathAsNode.InnerText))
 Next

 Return mappingsFromConfigFile
 End Function

 ''' <summary>
 ''' Gets the path to the generic handler. It should be a virtual path
 ''' </summary>
 ''' <returns>Path to the generic handler</returns>
 Private Function GetPathTogenericHandler() As String
 Dim configFile As New XmlDocument()
 Dim physicalPathToConfigFile As String = Context.Server.MapPath(Me.pathToConfigFile)
 configFile.Load(physicalPathToConfigFile)
 ' Load the configuration file ;
 Dim rootElement As XmlElement = configFile.DocumentElement
 Dim handlerPathSection As XmlNode = rootElement.GetElementsByTagName("genericHandlerPath")(0)
 ' Get all path to the generic handler ;
 Return handlerPathSection.InnerText
 End Function

 ''' <summary>
 ''' Adds a backslash at the end of a physical path if the slash does not exist ;
 ''' </summary>
 ''' <param name="physicalPath">Physical path</param>
 ''' <returns></returns>
 Private Function AddSlashAtEndOfPhysicalPath(ByVal physicalPath As String) As String

 If Not physicalPath.EndsWith("\") Then
 Return physicalPath & "\"
 Else
 Return physicalPath
 End If
 End Function

 ''' <summary>
 ''' Adds a backslash at the end of a virtual path if the slash does not exists ;
 ''' </summary>
 ''' <param name="virtualPath">Virtual path</param>
 ''' <returns></returns>
 Private Function AddSlashAtEndOfVirtualPath(ByVal virtualPath As String) As String

 If Not virtualPath.EndsWith("/") Then
 Return virtualPath & "/"
 Else
 Return virtualPath
 End If
 End Function
 #End Region
End Class

For the Asp.Net (c#) sample as following.


<%@ WebHandler Language="c#" %>

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;

using System.Configuration;
using System.Web;
using System.IO;
using System.Xml;

public class FileSystemHandler : IHttpHandler
{
 #region "IHttpHandler Members"

 private string pathToConfigFile = "~/MappingFile.mapping";
 private HttpContext _context;
 private HttpContext Context {
 get { return _context; }
 set { _context = value; }
 }

 public void ProcessRequest(HttpContext context__1)
 {
 Context = context__1;

 if (Context.Request.QueryString["path"] == null) {
 return;
 }

 string virtualPathToFile = Context.Server.HtmlDecode(Context.Request.QueryString["path"]);
 string physicalPathToFile = "";
 Dictionary<string, string> mappedPathsInConfigFile = this.GetMappingsFromConfigFile();
 foreach (KeyValuePair<string, string> mappedPath in mappedPathsInConfigFile) {
 if (virtualPathToFile.ToLower().StartsWith(mappedPath.Key.ToLower())) {
 // Build the physical path to the file ;
 physicalPathToFile = virtualPathToFile.Replace(mappedPath.Key, mappedPath.Value).Replace("/", "\\");

 // Brak the foreach loop ;
 break; // TODO: might not be correct. Was : Exit For
 }
 }

 // The docx files are downloaded ;
 if (Path.GetExtension(physicalPathToFile).Equals(".docx", StringComparison.CurrentCultureIgnoreCase)) {
 // Handle .docx files ;
 this.WriteFile(physicalPathToFile, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", Context.Response);
 }

 if (Path.GetExtension(physicalPathToFile).Equals(".jpg", StringComparison.CurrentCultureIgnoreCase)) {
 // Handle .jpg files ;
 WriteFile(physicalPathToFile, "image/jpeg", Context.Response);
 }

 // "txt/html" is the default valuse for Response.ContentType property;
 // do not download the file. Open in the window ;
 Context.Response.WriteFile(physicalPathToFile);
 }

 /// <summary>
 /// Forces browser to download the file
 /// </summary>
 /// <param name="physicalPathToFile">Physical path to the file on the server </param>
 /// <param name="contentType">The file content type</param>
 private void WriteFile(string physicalPathToFile, string contentType, HttpResponse response)
 {
 response.Buffer = true;
 response.Clear();
 string ct = response.ContentType;
 if (!string.IsNullOrEmpty(contentType)) {
 response.ContentType = contentType;
 }

 string extension = Path.GetExtension(physicalPathToFile);

 if (extension != ".htm" && extension != ".html" && extension != ".xml") {
 response.AddHeader("content-disposition", "attachment; filename=" + Path.GetFileName(physicalPathToFile));
 }
 response.WriteFile(physicalPathToFile);
 response.Flush();
 response.End();
 }

 public bool IsReusable {
 get { return false; }
 }

 /// <summary>
 /// Retrieves the mapping for view paths ;
 /// </summary>
 /// <param name="virtualPathToConfigFile">The fvirtual path to the config file </param>
 /// <returns>The mappings </returns>
 private Dictionary<string, string> GetMappingsFromConfigFile()
 {
 XmlDocument configFile = new XmlDocument();
 string physicalPathToConfigFile = Context.Server.MapPath(this.pathToConfigFile);
 configFile.Load(physicalPathToConfigFile);
 // Load the configuration file ;
 XmlElement rootElement = configFile.DocumentElement;
 XmlNode mappingsSection = rootElement.GetElementsByTagName("Mappings")[0];
 // get all mappings ;
 Dictionary<string, string> mappingsFromConfigFile = new Dictionary<string, string>();
 foreach (XmlNode mapping in mappingsSection.ChildNodes) {
 XmlNode virtualPathAsNode = mapping.SelectSingleNode("child::VirtualPath");
 XmlNode physicalPathAsNode = mapping.SelectSingleNode("child::PhysicalPath");
 mappingsFromConfigFile.Add(this.AddSlashAtEndOfVirtualPath(virtualPathAsNode.InnerText), this.AddSlashAtEndOfPhysicalPath(physicalPathAsNode.InnerText));
 }

 return mappingsFromConfigFile;
 }

 /// <summary>
 /// Gets the path to the generic handler. It should be a virtual path
 /// </summary>
 /// <returns>Path to the generic handler</returns>
 private string GetPathTogenericHandler()
 {
 XmlDocument configFile = new XmlDocument();
 string physicalPathToConfigFile = Context.Server.MapPath(this.pathToConfigFile);
 configFile.Load(physicalPathToConfigFile);
 // Load the configuration file ;
 XmlElement rootElement = configFile.DocumentElement;
 XmlNode handlerPathSection = rootElement.GetElementsByTagName("genericHandlerPath")[0];
 // Get all path to the generic handler ;
 return handlerPathSection.InnerText;
 }

 /// <summary>
 /// Adds a backslash at the end of a physical path if the slash does not exist ;
 /// </summary>
 /// <param name="physicalPath">Physical path</param>
 /// <returns></returns>
 private string AddSlashAtEndOfPhysicalPath(string physicalPath)
 {

 if (!physicalPath.EndsWith("\\")) {
 return physicalPath + "\\";
 } else {
 return physicalPath;
 }
 }

 /// <summary>
 /// Adds a backslash at the end of a virtual path if the slash does not exists ;
 /// </summary>
 /// <param name="virtualPath">Virtual path</param>
 /// <returns></returns>
 private string AddSlashAtEndOfVirtualPath(string virtualPath)
 {

 if (!virtualPath.EndsWith("/")) {
 return virtualPath + "/";
 } else {
 return virtualPath;
 }
 }
 #endregion
}

After that you have to create mappingfile.mapping in your web project.

Then you can assign the physical path that location of your images/photo .


<?xml version="1.0" encoding="utf-8" ?>
<CustomFileBrowserProvider>
 <Paths>
 <genericHandlerPath>FileSystemHandler.ashx</genericHandlerPath>
 </Paths>
 <Mappings>
 <Mapping>
 <PhysicalPath>
 <![CDATA[C:\Inetpub\wwwroot\Icoders\Photo\Thumbnail\]]>
 </PhysicalPath>
 <VirtualPath><![CDATA[Photo1]]></VirtualPath>
 </Mapping>
 <Mapping>
 <PhysicalPath>
 <![CDATA[C:\Inetpub\wwwroot\Icoders\Photo\Thumbnail\]]>
 </PhysicalPath>
 <VirtualPath><![CDATA[Photo2]]></VirtualPath>
 </Mapping>