Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Archive for August, 2009

custom paging of the datagrid or gridview

Posted by Viral Sarvaiya on August 20, 2009

hear i demonstrate the custom paging of the datagrid or gridview.

in the client side take the datagrid or grid view

here i take the datagrid,



<asp:datagrid id="dgMake" runat="server" AutoGenerateColumns="False" Width="100%"
CellPadding="5" GridLines="None" AllowPaging="true">

<HeaderStyle HorizontalAlign="Left" Width="100"></HeaderStyle>
<ItemStyle HorizontalAlign="Left" Width="100"></ItemStyle>

<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
<ItemStyle HorizontalAlign="Left"></ItemStyle>

<PagerStyle Visible="False"></PagerStyle>


in the second raw, i add the link buttons as below,

<td valign="top" align="right" bgcolor="#e1e4e6" style="padding:10px 10px 10px 60px;text-align:right;">
<asp:linkbutton id="FirstButton" onclick="PagerButtonClick" runat="server" CssClass="contant" CommandArgument="0"> First Page</asp:linkbutton><asp:label id="lblFirstLine" runat="server">&nbsp;|&nbsp;</asp:label>
<asp:linkbutton id="PrevButton" onclick="PagerButtonClick" runat="server" CssClass="contant" CommandArgument="prev">Prev</asp:linkbutton><asp:label id="lblLine" runat="server">&nbsp;|&nbsp;</asp:label>
<asp:linkbutton id="NextButton" onclick="PagerButtonClick" runat="server" CssClass="contant" CommandArgument="next">Next</asp:linkbutton><asp:label id="lblLastLine" runat="server">&nbsp;|&nbsp;</asp:label>
<asp:linkbutton id="LastButton" onclick="PagerButtonClick" runat="server" CssClass="contant" CommandArgument="last"> Last Page</asp:linkbutton>

in the code-behind file, bind the datagrid as below,

define the page size of the datagrid in the page load

dgMake.PageSize = 50

then call this function in the postback false part of the page load.

sub bind_datagrid()

Dim ds As New DataSet

ds = classobject.fiunctionname()

If ds.Tables(0).Rows.Count > 0 Then

dgMake.DataSource = ds




dgMake.DataSource = ds

FirstButton.Visible = False
PrevButton.Visible = False
NextButton.Visible = False
LastButton.Visible = False
lblFirstLine.Visible = False
lblLastLine.Visible = False
lblLine.Visible = False

End If
End Sub

Public Sub firstprev()
If dgMake.CurrentPageIndex <> 0 Then
Call Prev_Buttons()
FirstButton.Visible = True
PrevButton.Visible = True
lblFirstLine.Visible = True
FirstButton.Visible = False
PrevButton.Visible = False
lblFirstLine.Visible = False
End If

'To Display Next/Last Page buttons

If dgMake.CurrentPageIndex <> (dgMake.PageCount - 1) Then
Call Next_Buttons()
NextButton.Visible = True
LastButton.Visible = True
lblLastLine.Visible = True
NextButton.Visible = False
LastButton.Visible = False
lblLastLine.Visible = False
End If

If dgMake.CurrentPageIndex > 0 And dgMake.CurrentPageIndex < dgMake.PageCount - 1 Then
lblLine.Visible = True
lblLine.Visible = False
End If

End Sub

Sub Prev_Buttons()
Dim PrevSet As String
If dgMake.CurrentPageIndex + 1 <> 1 Then
PrevSet = dgMake.PageSize
PrevButton.Text = ("Prev")
End If
End Sub

Sub Next_Buttons()
Dim NextSet As String
If dgMake.CurrentPageIndex + 1 < dgMake.PageCount Then
NextSet = dgMake.PageSize
NextButton.Text = ("Next")
End If
End Sub

Sub PagerButtonClick(ByVal sender As Object, ByVal e As EventArgs)
Dim arg As String = sender.CommandArgument
Select Case arg
Case "next"
'The next Button was Clicked
If (dgMake.CurrentPageIndex < (dgMake.PageCount - 1)) Then
dgMake.CurrentPageIndex += 1
End If

Case "prev"
'The prev button was clicked
If (dgMake.CurrentPageIndex > 0) Then
dgMake.CurrentPageIndex -= 1
End If

Case "last"
'The Last Page button was clicked
dgMake.CurrentPageIndex = (dgMake.PageCount - 1)

Case Else
'The First Page button was clicked
dgMake.CurrentPageIndex = Convert.ToInt32(arg)
End Select
'Now, bind the data!
End Sub

so the page will be bind to 50 records.

enjoy coding…..


Posted in ASP.NET | Tagged: , , | Leave a Comment »

What is Rss?

Posted by Viral Sarvaiya on August 12, 2009

What is RSS?

RSS stands for “Really Simple Syndication”. It is a way to easily distribute a list of headlines, update notices, and sometimes content to a wide number of people. It is used by computer programs that organize those headlines and notices for easy reading.

What problem does RSS solve?

Most people are interested in many websites whose content changes on an unpredictable schedule. Examples of such websites are news sites, community and religious organization information pages, product information pages, medical websites, and weblogs. Repeatedly checking each website to see if there is any new content can be very tedious.

Email notification of changes was an early solution to this problem. Unfortunately, when you receive email notifications from multiple websites they are usually disorganized and can get overwhelming, and are often mistaken for spam.

RSS is a better way to be notified of new and changed content. Notifications of changes to multiple websites are handled easily, and the results are presented to you well organized and distinct from email.

How does RSS work?

RSS works by having the website author maintain a list of notifications on their website in a standard way. This list of notifications is called an “RSS Feed“. People who are interested in finding out the latest headlines or changes can check this list. Special computer programs called “RSS aggregators” have been developed that automatically access the RSS feeds of websites you care about on your behalf and organize the results for you. (RSS feeds and aggregators are also sometimes called “RSS Channels” and “RSS Readers“.)

Producing an RSS feed is very simple and hundreds of thousands of websites now provide this feature, including major news organizations like the New York Times, the BBC, and Reuters, as well as many weblogs.

What information does RSS provide?

RSS provides very basic information to do its notification. It is made up of a list of items presented in order from newest to oldest. Each item usually consists of a simple title describing the item along with a more complete description and a link to a web page with the actual information being described. Sometimes this description is the full information you want to read (such as the content of a weblog post) and sometimes it is just a summary.

For example, the RSS information for headlines on a local news website could contain the following information:

Item 1:
Title: Sidewalk contract awarded
Description: The city awarded the sidewalk contract to Smith Associates. This hotly contested deal is worth $1.2 million.
Item 2:
Title: Governor to visit
Description: The governor is scheduled to visit the city on July 1st. This is the first visit since the election two years ago. The mayor is planning a big reception.

The RSS information is placed into a single file on a website in a manner similar to normal web pages. However, the information is coded in the XML computer language for use by a program (the RSS aggregator) and not by a person like a normal web page.

RSS aggregator programs

Think of an RSS aggregator as just a web browser for RSS content. RSS aggregators automatically check a series of RSS feeds for new items on an ongoing basis, making it is possible to keep track of changes to multiple websites without needing to tediously read and re-read each of the websites yourself. They detect the additions and present them all together to you in a compact and useful manner. If the title and description of an item are of interest, the link can be used to quickly bring the related web page up for reading.

Here is a screen shot of an RSS aggregator in action. On the left is a list of the RSS feeds being monitored, along with an indication of the number of unread items in each feed in parenthesis. On the right are the details of the most recent items in a selected RSS feed (in this case, the New York Times).

Boston Globe (10), CNET, etc.

There are many RSS aggregators available. Some are accessed through a browser, some are integrated into email programs, and some run as a standalone application on your personal computer.

How do I find out if a website has an RSS feed?

It is getting more and more common for websites to have RSS feeds. They usually indicate the existence of the feed on the home page or main news page with a link to “RSS”, or sometimes by displaying an orange button with the letters “XML” or “RSS”. RSS feeds are also often found via a “Syndicate This” link. Text “RSS” links sometimes (there are lots of variations) point to a web page explaining the nature of the RSS feeds provided and how to find them. The buttons are often linked directly to the RSS feed file itself.

Once you know the URL of an RSS feed, you can provide that address to an RSS aggregator program and have the aggregator monitor the feed for you. Many RSS aggregators come preconfigured with a list to choose from of RSS feed URLs for popular news websites.

How is the RSS feed file produced?

Unless you are maintaining a website or want to create your own RSS feed for some other purpose, how the RSS feed is produced should not be of concern and you may skip this section.

The special XML-format file that makes up an RSS feed is usually created in one of a variety of ways.

Most large news websites and most weblogs are maintained using special “content management” programs. Authors add their stories and postings to the website by interacting with those programs and then use the program’s “publish” facility to create the HTML files that make up the website. Those programs often also can update the RSS feed XML file at the same time, adding an item referring to the new story or post, and removing less recent items. Blog creation tools like Blogger, LiveJournal, Movable Type, and Radio automatically create feeds.

Websites that are produced in a more custom manner, such as with Macromedia Dreamweaver or a simple text editor, usually do not automatically create RSS feeds. Authors of such websites either maintain the XML files by hand, just as they do the website itself, or use a tool such as Software Garden, Inc.’s ListGarden program to maintain it. There are also services that periodically read requested websites themselves and try to automatically determine changes (this is most reliable for websites with a somewhat regular news-like format), or that let you create RSS feed XML files that are hosted by that service provider.

Tying it all together

Here is a diagram showing how the websites, the RSS feed XML files, and your personal computer are connected:

Two web servers each with an RSS file being checked by an aggregator

The diagram shows a web browser being used to read first Web Site 1 over the Internet and then Web Site 2. It also shows the RSS feed XML files for both websites being monitored simultaneously by an RSS Feed Aggregator.

Other uses

In addition to notifying you about news headlines and changes to websites, RSS can be used for many other purposes. There does not even have to be a web page associated with the items listed — sometimes all the information you need may be in the titles and descriptions themselves.

Some commonly mentioned uses are:

  • Notification of the arrival of new products in a store
  • Listing and notifying you of newsletter issues, including email newsletters
  • Weather and other alerts of changing conditions
  • Notification of additions of new items to a database, or new members to a group

One RSS aggregator is all that you need to read all of the RSS feeds, be they headlines, alerts, changes, or other notifications. RSS is shaping up to be a very popular and useful means for communicating.

RSS Toolkit

The RSS toolkit includes support for consuming as well as publishing RSS feeds in ASP.NET applications. Features include:

  • RSS Data Source control to consume feeds in ASP.NET applications
    • Works with ASP.NET data bound controls
    • Implements schema to generate columns at design time
    • Supports auto-generation of columns at runtime (via ICustomTypeDescriptor implementation)
  • Caching of downloaded feeds both in-memory and on-disk (persisted across process restarts)
  • Generation of strongly typed classes for RSS feeds (including strongly typed channel, items, image, handler) based on a RSS URL (the toolkit recognizes RSS and RDF feeds) or a file containing RSS definition. Allows programmatically download (and create) RSS channels using strongly-typed classes. The toolkit includes:
    • Stand-alone command line RSS compiler
    • Build provider for .rssdl file (containing the list of feed URLs)
    • Build provider for .rss file (containing RSS XML)
  • Support for generation of RSS feeds in ASP.NET application including:
    • RSS HTTP handler (strongly typed HTTP handlers are generated automatically by the build providers) to generate the feed.
    • RSS Hyper Link control (that can point to RSS HTTP handler) to create RSS links
    • Optional secure encoding of user name into query string to allow generation of personalized feeds
  • Set of classes for programmatic consumption and generation of RSS feed in a late-bound way, without using strongly typed generated classes

The toolkit is packaged as an assembly (DLL) that can be either placed in GAC or in ‘bin’ directory of a web application. It is also usable from client (including WinForms) applications.

RSS Toolkit works in Medium Trust (RssToolkit.dll Assembly either in GAC or in ‘bin’) with the following caveats:

  • If the ASP.NET application consumes RSS feeds, the trust level must be configured to allow outbound HTTP requests.
  • To take advantage of disk caching, there must be a directory (configurable via AppSettings[“rssTempDir”]) where the trust level policy would allow write access. However, disk caching is optional.

Click here to Download & more info…..

Posted in General | Tagged: , , , , | Leave a Comment »

Set maxlength of textarea with javascript

Posted by Viral Sarvaiya on August 11, 2009

Here i demonstrate, how to set maximum length of the textarea or multiline textbox with javascript.

copy this code in the head section of the page.

<script language="javascript" type="text/javascript">
function CheckFieldLength1(fn, mc) {
var len = fn.value.length;
if (len > mc) {
fn.value = fn.value.substring(0, mc);
len = mc;
document.getElementById("charcount").innerHTML = len;
document.getElementById("remaining").innerHTML = mc - len;


now in the body section,

<asp:TextBox ID="txtDesc" runat="server" Width="500" Height="200" TextMode="MultiLine" MaxLength="250"></asp:TextBox><br />
<span><span id="charcount" runat="server">0</span> Characters entered.   |   <span id="remaining"  runat="server">250</span> </span>

in the server side coding, set the 3 attributes as below.

txtDesc.Attributes.Add("onkeyup", "javascript:return CheckFieldLength(" & txtDesc.ClientID & ",250);")
txtDesc.Attributes.Add("onkeydown", "javascript:return CheckFieldLength(" & txtDesc.ClientID & ",250);")
txtDesc.Attributes.Add("onmouseout", "javascript:return CheckFieldLength(" & txtDesc.ClientID & ",250);")

this will allow you to enter only 250 character in the textarea.

enjoy coding…….

Posted in Javascript | Tagged: , , , , | 3 Comments »

Display Hierarchical Data with TreeView in ASP.NET 2.0

Posted by Viral Sarvaiya on August 4, 2009

I’m going to provide a simple example how to display hierarchical data from SQL Server database in the TreeView. A requirement is that the implementation should not be dependant on the hierarchy level in the database. It means that the TreeView implementation should be capable of displaying data from any level, no matter how deep.

Listing #1 : TreeviewEx.aspx

<asp:TreeView ID=”tvCategoryList” runat=”server” ImageSet=”BulletedList3″ Width=”100%”
ShowExpandCollapse=”True” NodeWrap=”True”
ExpandDepth=”2″ PopulateNodesFromClient=”False” >
<ParentNodeStyle Font-Bold=”True” />
<RootNodeStyle Font-Bold=”True” CssClass=”Table_Title_Label_Black12″ />
<HoverNodeStyle Font-Underline=”True” ForeColor=”#5555DD” />
<SelectedNodeStyle Font-Underline=”True” HorizontalPadding=”0px” VerticalPadding=”0px”
ForeColor=”#5555DD” />
<NodeStyle Font-Names=”Verdana” Font-Size=”8pt” ForeColor=”Black” HorizontalPadding=”0px”
NodeSpacing=”0px” VerticalPadding=”0px” />

Next, we start looking at the code in the TreeviewEx.aspx,cs file. We want to populate the root level. Here’s the code.

Listing #2

protected void Page_Load(object sender, EventArgs e)

if (!IsPostBack)


This happens by connecting to the database, querying the first set of nodes (having null as the parent id), and creating TreeNode objects with the PopulateNodes routine, which follows next.

Listing #3

private void PopulateRootLevel()
DataTable dt = BAL_Category.GetParentCategory();// Get Parent CategoryList From Database
PopulateNodes(dt, tvCategoryList.Nodes);

Next, we want to create the routine to populate the child nodes of a given node. This happens with the PopulateSubLevel method.

Listing #4

private void PopulateSubLevel(int parentid, TreeNode parentNode)
DataTable dt = BAL_Category.GetChildCategory(parentid);       // Get CategoryList by ParentID From Database
PopulateNodes(dt, parentNode.ChildNodes);

Here, the idea is the same as with the root level, but with the distinction that only child nodes of the given node are queried and populated with the PopulateNodes method (described earlier). The trick to triggering the populating of the child nodes is as follows.

Listing #5


protected void tvCategoryList_TreeNodePopulate(object sender, TreeNodeEventArgs e)
PopulateSubLevel(Int32.Parse(e.Node.Value), e.Node);

TreeNodePopulate is raised for a TreeNode which is expanded by the user for the first time. Due to PopulateNodesFromClient (TreeView) and PopulateOnDemand (TreeNode) settings, this happens with the client-side callback mechanism which is handled by the ASP.NET Page framework. This means that populating does not involve a postback. And, due to better cross-browser support in ASP.NET 2.0, this also works for other browsers such as Firefox. Note that clicking on the node does cause a postback because I haven’t modified the select action of the populated tree nodes from the defaults.

Listing #6

private void PopulateNodes(DataTable dt, TreeNodeCollection nodes)
foreach (DataRow dr in dt.Rows)
TreeNode tn = new TreeNode();
tn.Text = dr["Category"].ToString();
tn.Value = dr["CategoryID"].ToString();

int NoofChild = Convert.ToInt32(dr["childnodecount"].ToString());

if (NoofChild != 0 )
tn.PopulateOnDemand = true;
tn.SelectAction = TreeNodeSelectAction.None;
tn.PopulateOnDemand = false;
if (dr["TotalDoc"].ToString().Equals(”0″) == false)
tn.NavigateUrl = “~/CategoryWiseProductList.aspx?ID=” + dr["CategoryID"].ToString();
tn.Text = tn.Text + ” (” + dr["TotalProduct"].ToString() + “)”;
tn.NavigateUrl = “javascript:alert(’Product is not Available Under this Category.’)”;

Posted in ASP.NET | Tagged: , , , , | 3 Comments »

Image Resize or create thumb image

Posted by Viral Sarvaiya on August 4, 2009

The project shows the resizing of the image, means create the thumb file of the actual image, here i show how to create the thumb as well as Medium sized file.

first create the class file named “GeneralMethods.vb”

Public Class GeneralMethods
Public Shared Function CreateThumbImage(ByVal imgPhoto As Image, ByVal Width As Integer, ByVal Height As Integer) As Image
Dim bmpOut As Bitmap = Nothing
Dim oBMP As New Bitmap(imgPhoto)
Dim oFormat As Imaging.ImageFormat = oBMP.RawFormat
Dim NewWidth As Integer = 0
Dim NewHeight As Integer = 0

'*** If the image is smaller than a thumbnail just return it

If oBMP.Width <= Width AndAlso oBMP.Height <= Height Then
Return imgPhoto
End If

Dim per As Double
If oBMP.Width > Width Or oBMP.Height > Height Then
If oBMP.Width > oBMP.Height Then
per = (100 * Width) / oBMP.Width
NewWidth = (oBMP.Width * per) / 100
NewHeight = (oBMP.Height * per) / 100
per = (100 * Height) / oBMP.Height
NewWidth = (oBMP.Width * per) / 100
NewHeight = (oBMP.Height * per) / 100
End If

If NewHeight > Height Or NewWidth > Width Then
If NewWidth > NewHeight Then
per = (100 * Width) / NewWidth
per = (100 * Height) / NewHeight
End If
NewWidth = (NewWidth * per) / 100
NewHeight = (NewHeight * per) / 100
End If

End If

bmpOut = New Bitmap(NewWidth, NewHeight)

Dim g As Graphics = Graphics.FromImage(bmpOut)

g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
g.InterpolationMode = Drawing2D.InterpolationMode.High
g.CompositingQuality = Drawing2D.CompositingQuality.HighQuality

Dim codec As Drawing.Imaging.ImageCodecInfo = Drawing.Imaging.ImageCodecInfo.GetImageEncoders(1)
Dim eParams As Drawing.Imaging.EncoderParameter = New System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 1)

g.FillRectangle(Brushes.White, 0, 0, NewWidth, NewHeight)

g.DrawImage(oBMP, 0, 0, NewWidth, NewHeight)


Return Nothing
End Try
Return bmpOut
End Function

Imports this 2 namesapces,
Imports System.IO
Imports System.Drawing

in the html side, take a fileupload control named “file1” and one button.
on the click of the button write the following code

If file1.HasFile Then
extension = Path.GetExtension(file1.PostedFile.FileName).ToLower()
SyncLock (objLock)
'get the max id from the database
maxId = (objclass.GetMaxId())
filename = maxId & extension

strImagePath = rootPath & ConfigurationManager.AppSettings("ACTUAL_PATH") & filename
End SyncLock
If Not Directory.Exists(rootPath & ConfigurationManager.AppSettings("ACTUAL_PATH")) Then
Directory.CreateDirectory(rootPath & ConfigurationManager.AppSettings("ACTUAL_PATH"))
End If

objprice.photograph = filename


If File.Exists(strImagePath) Then
Dim actualImage As Drawing.Image
Dim mediumImage As Drawing.Image = Nothing
Dim thumbImage As Drawing.Image = Nothing

actualImage = Drawing.Image.FromFile(strImagePath)

'------------- Medium Image --------------------
Dim mediumWidth As Integer = ConfigurationManager.AppSettings("MEDIUM_WIDTH")
Dim mediumHeight As Integer = ConfigurationManager.AppSettings("MEDIUM_HEIGHT")
mediumImage = GeneralMethods.CreateThumbImage(actualImage, mediumWidth, mediumHeight)

If mediumImage.Width > mediumWidth Then
mediumImage = mediumImage.GetThumbnailImage(mediumWidth, mediumImage.Height, New Drawing.Image.GetThumbnailImageAbort(AddressOf ThumbnailCallback), IntPtr.Zero)
End If

If mediumImage.Height > mediumHeight Then
mediumImage = mediumImage.GetThumbnailImage(mediumImage.Width, mediumHeight, New Drawing.Image.GetThumbnailImageAbort(AddressOf ThumbnailCallback), IntPtr.Zero)
End If

If mediumImage IsNot Nothing Then
mediumImage.Save(rootPath & ConfigurationManager.AppSettings("MEDIUM_PATH") & filename)
End If
'-------------  End Medium  --------------------

actualImage = Drawing.Image.FromFile(strImagePath)
'--------------- Thumb Image -----------------
Dim thumbWidth As Integer = ConfigurationManager.AppSettings("THUMB_WIDTH")
Dim thumbHeight As Integer = ConfigurationManager.AppSettings("THUMB_HEIGHT")
thumbImage = GeneralMethods.CreateThumbImage(actualImage, thumbWidth, thumbHeight)

If thumbImage.Width > thumbWidth Then
thumbImage = thumbImage.GetThumbnailImage(thumbWidth, thumbImage.Height, New Drawing.Image.GetThumbnailImageAbort(AddressOf ThumbnailCallback), IntPtr.Zero)
End If

If thumbImage.Height > thumbHeight Then
thumbImage = thumbImage.GetThumbnailImage(thumbImage.Width, thumbHeight, New Drawing.Image.GetThumbnailImageAbort(AddressOf ThumbnailCallback), IntPtr.Zero)
End If

If thumbImage IsNot Nothing Then
thumbImage.Save(rootPath & ConfigurationManager.AppSettings("THUMB_PATH") & filename)
End If
'------------- End Thumb Image -----------------

End If

End If
Private Function ThumbnailCallback() As Boolean
Return False
End Function

according to the requirements set the application setting of the web.config.

hope this will help you

enjoy coding…..

Posted in ASP.NET | Tagged: , , , | Leave a Comment »

%d bloggers like this: