Package multiple files using Asp.Net Zip

Microsoft.Net has a very good utility for zipping aka packaging files. While there are good utilities there in open source/Code Plex for packaging files. I would still prefer to write the code using native functions and classes available in .Net. In this article I am going to use the System.IO.Packaging for showing how to attach multiple files into a zip.

Zipper class for Packaging

I have created a separate class called as Zipper for the future works as it gives great re-usability.  This class can be used for the WinForms, WPF, or ASP.Net applications. Though has to be changed as per the specific needs. It is just a starter for writing more functions into the zipper class.

Referencing required assemblies

The System.IO.Packaging library is not directly available in the default set of references. You have to add a reference to the assembly known as windowsbase.dll under Program Files. In my system it is ...

Read more here:   Asp.Net Zip Multiple Files 

ASP.Net Calendar with JavaScript as a DatePicker

Is there a DatePicker control in the ASP.Net 2.0? No, so I started writing some code which will be similar to the Win Forms DatePicker. The best approach is to build a server control or al least a user control. This article describes how to use JavaScript to get this functionality so that later on this can be ported to a user control.

Controls required for a DatePicker

I have planned to use a textbox to accept the dates, calendar to select dates, a panel to contain the calendar and a button to show, or hide the calendar control and its panel. I preferred to use the html button and div as a panel.

JavaScript Functionalities

This DatePicker is designed with the aim of improving the usability in to consideration. Still there are various functionalities can be added but for explaining the core working functionalities without making too much of confusions, I have opted only the following functionalities. ...

DataBinding GridView with Array List

DataBinding is an integral part in developing GUI intensive applications. It really eases the job of populating the data into the control from respective DataSource. The DataSource is usually being an IEnumerator. Means all the objects that implement an IEnumerator can be used to bind the controls.
GridView DataBinding
Though Binding a GridView is very simple task in VB.Net, the following is essential. Understanding
• how to use a DataSource
• Once the DataSource is given how to bind the data.
Why ArrayList over Array?
The reason behind I have chosen ArrayList over array is, because of the ease of use. The array needs to be re dim every time when the number of elements is changed. If you want to add a new item then you have to re dim the array.
But ArrayList are much easier to work with. The reason behind is, it is something like collection in Classic VB. You can ...

Recursively scan and access all TreeView nodes

TreeView nodes can be accessed from either Nodes collection from the TreeView root or ChildNodes collection for a TreeNode. But you don’t have any native functions to list all nodes to a single level list. This article explains how to get all nodes with complete source code in VB.Net.

TreeView Preparations

To distinguish the levels I have made the lines visible by the property ShowLines as visible. I have used two DIVs to show the output and the TreeView side by side. Sitemap is going to be used for the sample data to bind the TreeView, So a SiteMapDataSource to bind the Sitemap to the TreeView.

Sample Data

To explain accessing all nodes in all levels of hierarchy, we need some sample data to fill up all levels.  Here in our case we are going to deal that with a sitemap. So I have purposely created a sitemap with few levels and each level contains few items. I have named them in a way we can ide ...

Read more here:   Extract All TreeView Nodes 

ASP.Net Ajax Slider Control

I tried creating a small ASP.Net Ajax Slider Control using JavaScript and AJAX. The idea is to generate the PostBack at some predefined intervals in the marker scale. I don’t wish to raise the PostBack for every pixel the slider slides. It will actually spoil the usability of the control than helping. 

Note: some of the information discussed in this article needs the user to have some knowledge in JavaScript, Ajax, ASP.Net, Custom Server Controls, How PostBack works and CSS.

Controls used in ASP.Net Ajax Slider Control

SliderBase : A panel which contains all the following controls.
SliderHolder : It is the slider rail where the slider bar slides in.
SliderPanel : It is the slider bar.
Marker  : The marker scale sitting just above the slider holder.
SliderValue  : A hidden ...

Substitution control to bypass cache

When OutputCache is used to cache the page, the page response will be cached and the cached pages will be shown till the cache expires. This allows the web page to be rendered quickly. Wait there is a possibility that a frequently updated data is not shown to the client because of the cache. If this is what we want to accomplish, then substitution control can actually bypass the cache and display the frequently updated content to the client even thought he entire page is cached.

Display Data Using Substitution Control

To display some data using this control we need to have a static method accessible from mark-up. This function should accept a parameter with the type HttpContext, So that the control can fetch the data using this method.

How to verify the Substitution Control works?

If the sample doesn’t have a Cache directive, it is hard / impossible to notice how the control is actually bypassing the cache, so ...

Javscript Based Editor to use in ASP.Net

Please don’t get confused with Rich Text Editor in VB6 or classic VB. Those are  all working with RTF which is know as rich text format. This rich text editor I am explaining also providing rich text editing, but the format is HTML. So it has its own limitations (For e.g... unable to paste Image data directly). And it is actually a JavaScript code so it is not written but can be used along with ASP.Net applications as I am doing for this website.

Please note that, this is not a 100% working source code for Rich Text Editor. However if you are just looking for an editor which supports hyperlinks and few word formatting. This article will be helpful for you to proceed.

IFRAME Based Approach

It is basically very easy to build a simple editor using IFRAME. But the real trouble comes in when trying to build a ...

Read more here:   Asp .Net Rich Text Editor 

Asp .Net FileUpload to save image to the DataBase

I have worked in GridView for displaying different kind of data. The interesting portion is when there is a possibility to attach image, photo. This is not a very big task. But if it is done properly, the result will be very useful to the end user.

For this article I would like to extend bit further to add some image viewing capability to the GridView using HttpHandler. The following is the intention of this article.
1) ASP.Net FileUpload to upload the image to the web server
2) Read it as a byte array and don’t save it to the file system
3) Update the  byte array to save it to the database
4) Load the grid with image control and reference the image path to a HttpHandler
5) Develop the HttpHandler to read the data into a byte array
6) In HttpHandler render the data as image and set the content type as image

Asp.Net File Upload to upload file

The uploade ...

Simple Guestbook Html Code with File System

If the website is designed and developed only in plain HTML, it is nearly impossible to create a Guest Book with just plain HTML in server to track the guests. But now a days it is easier to find an ASP hosting for cheaper prices. It should be noted that, the server side execution is required for saving a GuestBook. Though the databases are the way to go. To make the article simpler I have used a flat file for GuestBook. As the target of this article is not providing a full working application for GuestBook, I am just writing some code for beginners to learn how to start with.

Guestbook Html Code To write into File System

As we discussed little earlier, the guest book is going to be saved into the file system. Since the flat file is just a text storage, we need to delimit t ...

Encrypt using RSA Key in Web.Config sections in ASP.Net 2.0

Steps to encrypt the connectionStrings section in Web.config file:

Add the below section in your web.config file under configuration section:

  <add keyContainerName="MyCustomKeys"
   description="Uses RsaCryptoServiceProvider to encrypt and decrypt"
   type="System.Configuration.RsaProtectedConfigurationProvider,System.Configuration, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" / ...

Search Control Recursively in using VB.Net

FindControl in will find the control in the current level only, it will not search in the child controls. To search for the control in child nodes, the function has to search recursively.

While i am working in GridView or any other controls which may have children, Writing code to access child controls by Control1.controls(0).controls(2).. will be longer. At the same time it may not be readable aswell. 

If some control in the same level is removed the control index may be changed. To avoid this we can use the Following code to effectively scan the control hierarchy recursively.

Source Code

Public Function FindControlRecursively(ByVal ParentControl As Control, _

ASP.Net Menu And CSS to format

Without a menu the web application is hard to navigate. We can even bind to a hierarchical data. Or with little additional work the database tables can be bound easily.

Format Base Menu

Base menu can be formatted using some simple format options(similar like anyother controls in shown as below). But the important item to be noted is the section where this is applied for. To format base menu use LevelMenuItemStyles section(BackColor="Silver" BorderStyle="Dashed" BorderWidth="1"). If  the menu has to be displayed horizontally, the orientation attribute has to be changed accordingly(Orientation="Horizontal") which is availabel in the <asp:Menu section itself

Sample grey background style will look like
<LevelMenuItemStyles >
<asp:MenuItemStyle BackColor="Silver" BorderStyle="Solid" Font-Bold="true" BorderColor="Gray" BorderWidth="1" HorizontalPadding="10px" />
</LevelMenuItemStyl ...

Read more here:   Formatting items in ASP.Net Menu 

Get web page response by HttpWebRequest in

How to get the Web page Source to a string which is hosted outside the application. If it is available inside the application then we can use server.execute to get it with current session. But if it is not then we can use the Http Web Request using HttpWebRequest.TimeOut can to be used when the target is a heavy page.

Configure the HttpWebRequest

To read the response of the web page we have to specify the ContentType ,Method. Method can be either Post or Get depends on the requirement. If the Post is selected then forms can be filled upa and submitted. As this article's main focus is on get posting data related information is not presented here.

StreamReader To get the response as Stream

Requester.GetResponse() can be read using  a stream reader so we can make use of the StreamReader and its ReadToEnd() method to read entire response into a string. While getting the str ...

Asp.Net Send Email with SmtpClient

Particularly for notifications emails are one of the best medium to communicate.Normally the SMTP server will be in seperate location and reachable from application server or web servers. And normally an email account is created with credentials to access the SMTP server securely. We can use MailClient.Credentials object to pass the credentials to sucessfully logon to the SMTP server. Then only the relay will be succesful.

This is a simple code to send email from Web applications using ASP.Net using SMTPClient with User Credentials.

To Pass the Email Address to From, To, CC,BCC

MailAddress object has to be used to pass the email address to specific fields such as From,To,CC,BCC. By this object the multiple email addresses can be added to their respective collections as follows

Message.CC.Add(New System.Net.Mail.MailAddress(Cc)) Send Email with A ...

Read Text File Asp.Net

In reading text file is very simple and easy using Not only reading the text file but also other file IO tasks such as open file, read file, write into a file, delete a file, rename a file, and delete a folder, rename a folder and create a folder etc...

For reading files you can simply use

Note: My.Computer namespace and objectes are specifc to Vb.Net , So dont expect the same in C-Sharp or other languages. Inaddition to that it may not be available in all versions of .Net.

Read Text File Asp.Net using stream

Reading a text file in ASP.Net using a stream is not that easy as the My.Computer namspace. But not that much tough to understand. You need to define a data transit to hold the data bytes before transfering them into string. Then we can convert the string using the proper encoding.

Source Code - Read Text File Asp.Net using stream

  & ...

Asp .Net Select Distinct on DataTable using ToTable()

Ever wondered how to do a distinct on DataTable? in When I was working on the frame work 1.0 and 1.1. I have searched the internet for a good solution. And almost of the forums,blogs advised me to go for custom function. which guided me to do the something like the following
1) Remove the rows which violates distinct( rows you don’t want to be used, and changes for each row)
2) Sort the rows for all columns you are going to issue distinct
3) Then compare the previous row with current one
4) If duplicate remove all but keep one.

I feel that the above will work. But if you are using .Net framework 2.0, then you really don’t need to do this all. Ther ...

Asp .net validate crawlers by reverse DNS lookup

If you are running a website, you may be interested in validating the visits mainly for restricting spam bots. To validate the genuine crawlers, all the known crawlers are having their urls embedded in their user agent.

We can identify the IP address range by doing Reverse and forward DNS lookup. Once we got the host of IP address, it is fairly easier to cross check the IP address of the current visit against the host.

How to get the IP address of the current visit?

Easiest way is using Request.UserHostAddress. But some times it may contain the proxy servers IP address. To get the IP address of the client, we can try Request.ServerVariables("HTTP_X_FORWARDED_FOR"). But the problem is this may not return value always. So that time we can use Request.UserHostAddress().

How to get the User Agent of the current visit?

Getting user agent is very simple as getting IP Addr ...

Search Text files recursively using

In using the files can be accessed using My.Computer.FileSystem Object easily.

  Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        SearchedFiles = New Collection
        SearchText("D:\Pons\ARAS", "FullListing")
        For Each Item Web Browser control.

This makes this task relatively easier to get the response of the given URL. Once the navigation completed, the screen shot image can be taken with the help of GDI.
Use the DocumentCompleted event to find whether the navigation of the web page has been completed. Use a Bitmap object to draw the image.

Again taking the screenshot of the given webpage is ...

Read more here:   Convert Web Page or Html to Image 

Asp .net Excel Export

When working in an application where some amount of data manipulation is required, at one point of time the export to CSV (comma-separated values), Excel or PDF etc may be require.

This article explains how to export excel from ASP.Net application. For this sample, there is no need of any third party components and no needs to install excel application or excel library in the server

Response object and Content Disposition

By just changing the Content Disposition property of the response header, the response can be exported (or downloaded). After changing the content disposition, the content type has to be given.

Asp .net Excel Export Sample

This article’s scope is mainly on exporting data to export. So retrieval of data from database has been avoided. And the data store in this sample is just a DataTable with sample data.

The approach is just ...

Read more here:   Asp .Net Excel Spreadsheet Export 

ASP.NET Themes and Skins

The site may need personalization because of various requirements. However, whatever the reason personalization is the process of changing the look and feel of the entire site or some pages. When I am saying look and feel, this consists of changing background color, text color, and images, location of content, layout change etc...
These tasks can be accomplished by cascading style sheets, and JavaScript.  Then what is the use of‘s Theme and skins are introduced while CSS and JavaScript can do. Simply with Personalization is very simple to design and apply to the entire site. Even though ASP. Net’s theme and skins are used we may need to use CSS at least

What is a theme?

In, Theme is a folder which can be placed in a App_Themes folder, Which contains all Style sheets, Skins, and respective images.
For E.g
If you wish to create two themes named as Red, Blue then there should ...

Read more here:   ASP .NET Themes and Skins 

Visual Basic Code(Syntax) Highlighting by VB.Net and Regular Expressions

This walk through explains simple Syntax highlighing for Visual Basic Using and Reqular Expressions(Regex). But this code can be tweaked /modified for languages with little modifications. Mainly i have worked on this class for this site's content management control(wysiwyg editor). This site needs atleast one code segment for each page. So i started looking for free open source.Later i decided to develop myself with regular expressions and visual basic.We have implemented wysiwyg control with the source code highlighting for this article.

To highlight the code the following steps are necessary

Mainly code highlighting involves lot of text operations. so i have decided to use regular operations. So the complecated operations can be accomplished in l ...

Counting Files in a folder including subfolder in ASP .net

It is very easy to count Folders and Files in a folder including subfolder. DirectoryInfo will give you all information related to a directory. GetFiles is a function available in DirectoryInfo object. Which makes counting and accessing files much easier. This functio will return a list so we can get the number of files using the length property.

In Classic VB we have to write recursive function to iterate through all levels in a directory. But in ASP .net DirectoryInfo.GetFiles method has a parameter accepts an enumerator to specify 'AllDirectories'. Thats it it will do the rest internally to traverse the entire hierarchy.

Function CountFiles(

Load(List) all database names in GridView(DataGrid) using Asp.Net

While developing application that involves databases extensively we may need the list of databases for various reasons.

The objective of this article is to help how to load the database names into a dataset. So that the same can be used in the application later

Basically the above requirement can be done either by SQL SMO or by the ‘System Objects’ in the MS SQL server. I am using the ‘System Objects method’

How to List the databases in SQL Server?

To list we need to establish the connection to the database server
provide the connection string to the connection object

        Dim ConGrid As New SqlConnection
        Dim AdaGrid As N ...

Asp .Net Create Buttons Dynamically with events

In some specfic cases we may need to create controls at runtime. Mostly when creating controls we need to consider location, size, data validations, client events, server events, text formating, control formatting. To explain it simply i have taken button as example. To create buttons dynamically we need to declare the Button and we need to initialize the Button object

Button btnDel = new Button();

Give the caption to the button to display
btnDel.Text = "X";

Assign the event handler to the Button

btnDel.Command += new CommandEventHandler(btnDel_onDelete);

we can specify the command argument to the button in order to fetch it from the event argument. What ever the values are assigned here can be fetched from the respective event

btnDel.Comm ...

ThreadAbortException when using Response.Redirect Method

Response.Redirect Method will cause ThreadAbortException. To avoid it the over loaded version of Response.Redirect(string, Boolean) has to be used.


Read more here:   Exception with Response.Redirect 

MsgBox From ASP

To show message box from applications is not as easy as we do in Visual Basic for win forms. We have to do it in client scripting so we are using javascript to create an alert. We are using the same naming as we do in classic visual basic. the code is below.

We can do the same in the client scripting directly in the markup. But several times in an application we may need to handle this in a code behind so it is always useful to have a helper method in the serverside to show alerts

Source Code

Sub MsgBox(strMsg )
 Dim strScript
        strScript = "<script language='Javascript'>"
        strScript &= "self.alert('" & strMsg & "')" ...

Read more here:   MsgBox From ASP 

Spam Bot Trap


Select Theme