Wednesday, February 07, 2007

Dynamic Gridview Generation at run time

In this example, a Gridview is generated at run time with customer list with bound field columns. It also creates a HTML table dynamically. Most of the properties can be easily controlled at run time. I am using Customer Business Object which I created for my earlier posts.

 Page: CustomerDynamicGridView.Aspx

Code Snippet
  1. <%@ Page Language="VB" AutoEventWireup="false" CodeFile="CustomerDynamicGridView.aspx.vb" Inherits="CustomerDynamicGridView" %>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <title>Dynamic Grid View</title>
  6. </head>
  7. <body>
  8. <form id="frmCustomer" runat="server">
  9. <div style="text-align:center">
  10. <asp:PlaceHolder ID="plhCustomer" runat="server">
  11. </asp:PlaceHolder>
  12. </div>
  13. </form>
  14. </body>
  15. </html>

Code Behind

Option Explicit On
 
Option Strict On
 
 
 
Imports Vishwa.Example.Business
 
 
 
''' <summary>
 
''' Author : Vishwa@VishwaMohan.com
 
''' Date : 10/14/2007
 
''' Class: CustomerDynamicGridView
 
''' Purpose : To Generate a Dynamic Gridview with Custom Bound Column
 
''' </summary>
 
''' <remarks></remarks>
 
''' 
 
 
 
Partial Class CustomerDynamicGridView
 
    Inherits System.Web.UI.Page
 
 
 
    Protected Sub Page_Load(ByVal sender AsObject, ByVal e As System.EventArgs) HandlesMe.Load
 
        IfNot Page.IsPostBack ThenCall PopulateDynamicGrid()
 
    End Sub
 
 
 
    Private Sub PopulateDynamicGrid()
 
        Dim gvwGridView AsNew GridView
 
        Dim tblMain AsNew HtmlTable
 
        Dim trRow AsNew HtmlTableRow
 
        Dim tdCell AsNew HtmlTableCell
 
        Dim lblTitleText AsNew Label
 
        Dim bizCust AsNew BIZCustomer
 
 
 
        lblTitleText.Text = "Customer List"
 
        lblTitleText.Font.Bold = True
 
        lblTitleText.BackColor = Drawing.Color.Navy
 
        lblTitleText.ForeColor = Drawing.Color.White
 
 
 
        tdCell.Controls.Add(lblTitleText)
 
        tdCell.Height = "30px"
 
        trRow.Cells.Add(tdCell)
 
        tblMain.Rows.Add(trRow)
 
 
 
        With gvwGridView
 
            .HorizontalAlign = HorizontalAlign.Left
 
            .BackColor = Drawing.Color.FromName("#ccccff")
 
            .BorderColor = Drawing.Color.Black
 
            .CellPadding = 3
 
            .CellSpacing = 0
 
            .Font.Name = "Verdana"
 
            .Font.Size = 8
 
            .HeaderStyle.Font.Size = 10
 
            .HeaderStyle.BackColor = Drawing.Color.FromName("#aaaadd")
 
            .HeaderStyle.VerticalAlign = VerticalAlign.Bottom
 
            .AlternatingRowStyle.BackColor = Drawing.Color.White
 
            .HeaderStyle.Wrap = False
 
            .AutoGenerateColumns = False
 
            .EmptyDataText = "No Record Found."
 
            CustomizeThisGrid(gvwGridView)
 
            .DataSource = bizCust.GetCustomers()
 
            .DataBind()
 
        EndWith
 
 
 
        trRow = New HtmlTableRow
 
        tdCell = New HtmlTableCell
 
        tdCell.Align = "Left"
 
        tdCell.Controls.Add(gvwGridView)
 
        trRow.Cells.Add(tdCell)
 
        tblMain.Rows.Add(trRow)
 
        plhCustomer.Controls.Add(tblMain)
 
 
 
    End Sub
 
 
 
    Private Sub CustomizeThisGrid(ByRef myGridView As GridView)
 
        myGridView.Columns.Clear()
 
        Dim col0 As BoundField = New BoundField()
 
        Dim col1 As BoundField = New BoundField()
 
        Dim col2 As BoundField = New BoundField()
 
 
 
        col0.ItemStyle.HorizontalAlign = HorizontalAlign.Left
 
        col0.HeaderStyle.HorizontalAlign = HorizontalAlign.Left
 
        col0.HeaderText = "ID#"
 
        col0.DataField = "CustID"
 
        myGridView.Columns.Add(col0)
 
 
 
        col1.ItemStyle.HorizontalAlign = HorizontalAlign.Left
 
        col1.HeaderStyle.HorizontalAlign = HorizontalAlign.Left
 
        col1.HeaderText = "Name"
 
        col1.DataField = "CustName"
 
        myGridView.Columns.Add(col1)
 
 
 
        col2.ItemStyle.HorizontalAlign = HorizontalAlign.Left
 
        col2.HeaderStyle.HorizontalAlign = HorizontalAlign.Left
 
        col2.HeaderText = "Address"
 
        col2.DataField = "CustAddress"
 
 
 
        myGridView.Columns.Add(col2)
 
 
 
    End Sub
 
 End Class
 

Output at Run time


 

Tuesday, January 16, 2007

Error : Internet Explorer cannot download ...

If you see Error message : Internet Explorer cannot download "filename" from "Servername"

Internet Explorer was not able to open this Internet site.

The requested site is either unavailable or cannot be found. Please try again

Then, this error usually occurs sometime while downloading a document which can be in form of PDF file, Doc file, XLS or text file. There are at least 4 possible reasons which can cause this error. I have also found their solutions. My assumption is - you are running your web site on IIS.

 

Reason 1:  You have checked Enable content expiration

Solution: 

a) Select the appropriate virtual directory on IIS, right click and select Properties then click on HTTP Headers tab.

b) Make sure that the checkbox for Enable content expiration is Unchecked.

  

Reason 2: If path for virtual directory is a shared folder and located on another computer

Solution:

a) Make sure that the Network directory is a UNC path (not mapped disks drive, because sometime you may loose mapping and it will generate an error).

b) You must provide a user name along with domain name when you click on Contact As button to provide Network Directory Security Credentials.

 

Reason 3: You are sure that you do not have issues due to above reasons but you are not able to download specific file type (e.g. .pdf, .doc etc)

Solution:

a) Select the appropriate virtual directory on IIS, right click and select Properties then click on HTTP Headers tab.

b) Click on button MIME Types and add appropriate MIME Types, if you would like to add for all types of file then click on button New, enter .* for Extension and application/text for MIME Type and then click on OK.

   

Reason 4: You checked all the above reasons and applied the solutions but you are not able to download or open a file.

Solution: Please follow the following steps

a) Internet Explorer-> Tools menu-> Internet Options-> Advanced tab

b) Go to the Security section all the way at the bottom.

c) Clear the check on the "Do not save encrypted pages to disk"

d) Close all Internet Explorer windows

e) Start IE and download the file again

  

 


Sunday, January 07, 2007

IIS 6 File Upload/Download Issue

When trying to upload files over 200KB on IIS 6 the file may never upload and you either get an error or are sent to a blank screen. By default Windows 2003 server limits file uploads to about 200KB in size. To overcome this limit you must edit the IIS metabase.xml file. 
 

Before you can edit the metabase.xml file you must tell IIS to allow you to edit the file.  In IIS, right click the name of the server and select properties.  Check "Enable Direct Metabase Edit".

  • Find the metabase.xml file located in C:\windows\sytem32\inetserv and open the file in Notepad.
  • Search for AspMaxRequestEntityAllowed and increase the value.  The default value is 204800 (200K).  Setting the value to 1000000 will allow 1 MB file uploads.
  • You may now wish to uncheck the IIS property called "Enable Direct Metabase Edit".

To increase the file download size limit, repeat all steps above but in Step 3 find the parameter called AspBufferingLimit.  The default download limit is 4MB.

In Classic ASP

If you are getting this issue in Classic ASP Page then to resolve this issue, modify the value in the AspMaxRequestEntityAllowed property to set the maximum number of bytes that are permitted in the entity body of an ASP request. To do this, follow these steps:

1. At a command prompt, type the following command, and then press ENTER:
cd drive:\inetpub\adminscripts

Note In this command to change folders, drive is a placeholder for the hard disk where IIS is installed.

2. At a command prompt, type the following command, and then press ENTER:
cscript adsutil.vbs set w3svc/ASPMaxRequestEntityAllowed size

Note In this command, size is a placeholder for the largest file size upload that you want to allow. The maximum value is 1,073,741,824 bytes. Set this value to the lowest possible value that allows for the functionality that you want.

3. At a command prompt, type the following command, and then press ENTER:
iisreset

Saturday, January 06, 2007

What Are Your Priorities?

Each of us get only 24 hours of the day in our daily life, some succeed in their life and some not. Have we ever thought that what makes someone to reach at the top and some just keep struggling? I think the most important thing is – how we give priorities to certain things in our daily life, it can be career, friends, family or anything. I heard this story from friends and then read it on the web; I thought it to put it here. This story also teaches the Time Management and it has been taught in many universities around the world.
   
A time management guru was speaking to a group of type "A" personalities. He placed a wide-mouth gallon jar on the table in front of him. Next to the jar was a collection of fist-sized rocks. He carefully filled the jar with the big rocks, until he could fit no more.
   
He asked the group, "Is the jar full?"

Everyone responded, "Yes."

He then pulled a large bowl of gravel from under the table and proceeded to pour the gravel into the jar. The gravel fit into the spaces between the rocks. He again queried, "Is the jar full?"

"Probably not," was the group's reply.

He reached for another bowl, this one filled with sand. He dumped the sand into the jar. The sand filled the spaces not taken by the rocks and the gravel. Once more, he asked, "Is the jar full?"

"No," everyone agreed.

Finally, he reached for a pitcher of water and poured water into the jar until it was filled to the top. The time management guru looked at the group and asked, "What is the point of my illustration?"

One man replied, "That no matter how full your schedule is, you can always fit one more thing into it."

"No!" the guru responded.
  
The point of this illustration is, "If you don't put the big rocks in first, you'll never get them in at all!"

The moral of the story is: Get the important things figured out first, then fit everything else in around them. In other words, know what your priorities are.

In other words, this boils down to is the need to know what's important to you and to choose situations that will further your preferences.

Frequently, you end up in a job because a relative or friend thought it was a good career. You never chose. You let other people decide for you. Whether out of fear or lack of knowledge, this is a mistake.

You turn around; you're thirty or forty and hate your work. You ask yourself how you got here and how the heck to get out.

Better to do the work up front. Take the time and do the soul searching, whether on your own or with help, but do it.

At any age, it's important to know what your "big rocks" are. Then, you can start to have the balance you want in your life/career and the satisfaction of knowing you chose your goals.


Monday, January 01, 2007

Contradictions in Bhagvad Gita

Truth is contradictory; if it is not contradictory then it is not truth! Bhagvad Gita is full of contradictions. You can understand it only if you see it in totality.

At one point, Krishna tells Arjuna that action is the most important thing and without action one will be nowhere. But after that He tells him that action is all right but knowledge is better! Then Krishna says, ‘‘You must become a yogi and drop everything around you.’’ Then Krishna tells him: ‘‘He is intelligent who sees ‘action’ in ‘inaction’ and ‘inaction’ in ‘action’.’’ What does this mean? It means even if you don't do something you have acted — simply by ‘not doing’.

If you do something then too you have not acted, for in your not acting here, something else could have happened — you could have done something else. Even though you have acted, there is ‘inaction’; because you did this, you couldn't do something else. So every ‘action’ has ‘inaction’ and every ‘inaction’ has got an ‘action’ connected to it.

And then Krishna takes Arjuna towards Dhyana Yoga — meditation. In the sixth chapter of the Bhagvad Gita, he tells Arjuna that since he is confused, there is no use talking. He asks him to meditate. Finally, Krishna says, ‘‘Arjuna, he is the greatest amongst the yogis who keeps Me in his heart whether he meditates or not. He is the real yogi, because I am with him in whatever he is doing.’’

The contradictions don’t end there. At one juncture, Krishna says, ‘‘Arjuna, there is nobody dear to me, nobody whom I love.’’ And then gives a whole list of qualifications for those He really loves!

In another instance, Krishna tells Arjuna to act without looking for the fruit of action. Later He asks Arjuna to act properly, according to natural law. Then He tells him the way he ought to fight if he wants to win the war. So, at this point He is bringing Arjuna's attention to the fruit of action, but then He also tells him not to worry about the fruit of action.

Krishna was like a dear friend to Arjuna. In Bhagavat, you will see that except for Vidura and Udhava, nobody even thought he was enlightened; they all thought that he was just very smart. Of course, there were the Pandavas and the gopis who knew who Krishna was and how total He was from all angles. But many of them, including Arjuna, did not see him that way.

But then Krishna shows him, in one minute, that He is infinite. He tells Arjuna, ‘‘You can't see without the eye of knowledge; so now I will give you a special eye of knowledge, which I have haven't given anybody in ages. I am giving it to you now because it is time.’’ With that, He gives him a vision, a flash. For that one moment the universe appears as a manifestation of Krishna to Arjuna. Arjuna’s mind is shattered that moment. He sees all of creation, everything — the mountains and the rivers, the past, the present and the future — dissolving in Krishna. He sees that Krishna is that space, that infinity, into which everything is coming in and dissolving. For an instant, the whole life, the whole universe, all the memory and all that was associated with it just plays out like a movie and it frightens Arjuna.

Then Arjuna pleads, ‘‘Oh! Please show me your simple, natural and friendly face. I like your simple smile and I want to see my friend. I don't want to see anything beyond. It is too much for me.’’ This is called Vishva Roopa Darshana — the vision of the universal.

Thereafter, Krishna tells Arjuna about the yagyas and all the principles and the laws under which the society and universe works. Then He talks about sanyasa and how to be really centered.

For instance, an event or an instance should be seen as just that — an event, an instance or a happening. But it sticks to the mind and you try to get rid of it. The event assumes importance and the mind is caught up in it — ‘‘Oh! He said that, they said this, they didn't say this, etc.’’

 

Once the event goes away, then you feel a sense of great relief. You suddenly discover peace inside you.

Your very nature is peace. In the centre of you, you are peace. The moment this disturbance gets thrown out, you can actually feel it — all the brain cells, and the entire brain becomes so calm and settled the moment this garbage goes out.

And deep inside you can really smile as a flame of peace. Arjuna asks Krishna, ‘‘What you say is very magical and joyful. But it's not easy. This mind is difficult to control. It's like controlling air — can anybody control air?’’

Then Krishna says, ‘‘I agree with you. It is difficult but not impossible. Abhyasena tu Kaunteya — with practice, dispassion and by getting to the centre again, you will succeed.’’ You will see that Krishna tried everything.

Finally it was the display of the universal vision that worked on Arjuna. People cannot change just by visions also. Krishna does not really bring about the realization totally from outside — it needs something more.

That is why after Krishna led Arjuna to the infinite vision, he speaks on what is dear to him, on devotion, and then he comes on all the other things you know —about creation and even about food.

But when Arjuna says, ‘‘I give up,’’ Krishna says, ‘‘I can't do anything; you think and do whatever is best for you. First ponder on whatever I have said and then act.’’ Arjuna says, ‘‘No, now I am clear in my mind. I'll do whatever you will say.’’ So, Krishna had to speak through 18 chapters to get him to that point and interestingly gave all these knowledge in the middle of battle field. Krishna could have done it at the very first chapter. But it is beautiful the way this knowledge has flown.

Everything may appear to be all contradictory, if seen from all angles. But that is in fact reality.

 

Source: Sri Sri

 

Sunday, December 31, 2006

Error "System.Web.HttpException: Maximum request length exceeded"

I have come across this error multiple times at work. This problem occurs because the default value for the maxRequestLength parameter in the section of the Machine.config or Web.Config file is 4096 (4 megabytes). As a result, files that are larger than this value are not uploaded by default.

To resolve this problem, use one of the following methods:

  • In the Machine.config file, change the maxRequestLength attribute of the <httpRuntime> configuration section to a larger value. This change affects the whole computer.
  • In the Web.config file, override the value of maxRequestLength for the application. For example, the following entry in Web.config allows files that are less than or equal to 1 GB to be uploaded:
                         <httpRuntime maxRequestLength="1048576" />

Max value for maxRequestLength attribute is "1048576" (1 GB) for .NET Framework 1.0 or 1.1 and "2097151" (2 GB) for .NET Framework 2.0.

Note: During the upload process of large files, built-in ASP.NET loads the whole file in memory before the user can save the file to the disk. Therefore, the process may recycle because of the memoryLimit attribute of the processModel tag in the Machine.config file. More info you can find in Microsoft KB article: http://support.microsoft.com/default.aspx?scid=kb;EN-US;295626

Sunday, December 17, 2006

Export GridView Data in MS-Excel

In the following example, I will demonstrate how to export GridView Data into MS-Excel using VB.NET. It uses the same business object to select data from database. I have simply formatted the GridView control from previous example.

Page Name: ExportGridViewToExcel.Aspx

------------------------------------

Note: You will be required to add - EnableEventValidation = "False" at Page Directive in order to Export to work.

-------------------------------------

Code Snippet
  1. <%@ Page Language="VB" AutoEventWireup="false" EnableEventValidation = "False" CodeFile="ExportGridViewToExcel.aspx.vb"
  2.         Inherits="ExportGridViewToExcel" %>
  3.  
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  5.  
  6. <html xmlns="http://www.w3.org/1999/xhtml" >
  7. <head runat="server">
  8.     <title>Export Customers Data</title>
  9. </head>
  10. <body>
  11.     <form id="frmCustomer" runat="server">
  12.     <div  style="text-align:center">   
  13.         <asp:Button ID="btnExportToExcel" runat="server" Text="Export to Excel" /><br />  
  14.         <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label> <br />
  15.         <asp:GridView ID="gdvCustomer" DataKeyNames="CustID" runat="server" AllowPaging="True" DataSourceID="odsCustomer"  
  16.             AutoGenerateColumns="False" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None"
  17.             BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical"
  18.             RowStyle-HorizontalAlign="Left" HeaderStyle-HorizontalAlign="Left">
  19.             <Columns>                
  20.                 <asp:BoundField DataField="CustID" HeaderText="Cust ID"  />                                    
  21.                 <asp:BoundField DataField="CustName" HeaderText="Name" SortExpression="CustName" />                    
  22.                 <asp:BoundField DataField="CustAddress" HeaderText="Address" SortExpression="CustAddress"/>                
  23.             </Columns>
  24.             <EmptyDataTemplate>                
  25.                 No Customer Record Found.                
  26.             </EmptyDataTemplate>            
  27.             <FooterStyle BackColor="#CCCC99" />
  28.             <RowStyle BackColor="#F7F7DE" />
  29.             <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
  30.             <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
  31.             <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
  32.             <AlternatingRowStyle BackColor="White" />
  33.         </asp:GridView>
  34.                
  35.           <asp:ObjectDataSource ID="odsCustomer" runat="server"
  36.               SelectMethod="GetCustomers"
  37.             TypeName="Vishwa.Example.Business.CustomerFac" >
  38.          </asp:ObjectDataSource>
  39.         </div>
  40.     </form>
  41. </body>
  42. </html>
 

Code Behind : ExportGridViewToExcel.Aspx.vb

Code Snippet
  1. Option Explicit On
  2. Option Strict On
  3. Imports System.IO
  4. ' Author : Vishwa Mohan
  5. ' Date : 12/15/2006
  6. ' Class : ExportCustomer
  7. ' Purpose: To Export Customers Record into Excel
  8. Partial Class ExportGridViewToExcel
  9.     Inherits System.Web.UI.Page
  10.     Protected Sub btnExportToExcel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportToExcel.Click
  11.         If gdvCustomer.Rows.Count + 1 < 65536 Then
  12.             Me.lblMessage.Text = ""
  13.             Me.gdvCustomer.AllowPaging = False
  14.             'If you are binding GridView under Code Behind
  15.             'Me.gdvCustomer.DataSource = GetCustomer
  16.  
  17.             Me.gdvCustomer.DataBind()
  18.             Dim tw As New StringWriter()
  19.             Dim hw As New System.Web.UI.HtmlTextWriter(tw)
  20.             Dim frm As HtmlForm = New HtmlForm()
  21.             Page.Response.ContentType = "application/vnd.ms-excel"
  22.             Page.Response.AddHeader("content-disposition", "attachment;Customer.xls")
  23.             Page.Response.Charset = ""
  24.             Page.EnableViewState = False
  25.             frm.Attributes("runat") = "server"
  26.             Controls.Add(frm)
  27.  
  28.             frm.Controls.Add(gdvCustomer)
  29.             frm.RenderControl(hw)
  30.             Response.Write(tw.ToString())
  31.             Response.End()
  32.             Me.gdvCustomer.AllowPaging = True
  33.  
  34.             'If you are binding GridView under Code Behind
  35.             'Me.gdvCustomer.DataBind()
  36.         Else
  37.             Me.lblMessage.Text = "Too many rows - Export to Excel not possible"
  38.         End If
  39.     End Sub
  40. End Class

 

Page at the run Time


Saturday, December 02, 2006

The Four Wives

Once upon a time, there lived a king who had four wives. He adored his fourth queen so much that he always used to gift her with loads of ornaments and other such adornments. She was inseparable from the king and a perpetual accompaniment wherever he went.
  
He also loved his third wife a lot - he guarded her richness and grandeur against the evil eyes of then neighboring kings and others.

He loved his second wife so much that he shared all his thoughts especially with her. But unfortunately he never loved his first queen - he ignored her very presence and enjoyed with the other queens.

Days passed by and one day it so happened that the king fell terribly sick and the best of the physicians in the kingdom and the world could find a cure. It was certain that he was staring at his end and he was on his final days.

He calls his fourth queen over and sadly says "Look, I am on my deathbed and will leave this world anytime now. When I was hale and hearty, I used to take you everywhere that I went. Will you accompany me when I leave to the other world?" To his utter shock, the Queen refused to do so and made it abundantly clear that it was unreasonable for the king to expect this and she would not like to give up her life for him. Though shocked, he did not lose hope; he calls his third queen and poses the same question to her. The shock was greater, she refuses to accompany him and moreover she replied that she would remarry after his death and continue to lead a happy life. The king was crestfallen at this outrageous reply from his dearest queens but again rests his hopes on the second queen. He looks at her and she pretends to be sympathetic to him and replies, "O dear, when you die, I cannot accompany you" and justifies this decision saying, "Your last rites will be performed as per the scriptures and I will take the responsibility to ensure this"

The king realized the reality at this fag end of his life. He realized the bitter truth that no one would accompany him nor would be available during his final days. While he was brooding over this fact, his first wife says, "O sweetheart, I am with you wherever you go. Don't you worry that you will have to make this last journey alone" The king was surprised and then realized that she was the true wife who loved him for what he was - not his riches not even his health. But his regret was that it was too late to make amends and shower her with his love.

Yes...like this king, we all have four wives.

The fourth wife is our body - a physical commodity that burns into ashes or disintegrates back to the earth at the end. The third wife is the wealth that we earn which would be shared and become property of others after our death. The Second wife is the relatives and friends who can only remain with us till the cemetery or crematorium. The First wife is the one which remains in our heart, the Divine or God, which remains with us in all our births and rebirths. It saves us from grief at the later stages if we adopt our spiritual practices and be devoted to the divine during our younger years.