Recent Posts

Thursday, December 10, 2009

How to post data to other site via "Post" in

If you need to post data to some other website or URL via post method then this article is the perfect solution.
This article references to the article provided in

I just followed the article and did it in vb. You can click on above link to get the c# code.

As per the above article

Possible Solutions

  1. One possible solution to this problem is to Create your own form control and use it on page this will allow you to change action of form, but again what if you do not want some existing input elements in current page to go to post.
  2. There is good way to post form data using HttpWebResponse & HttpWebRequest class if you want to post data behind the scenes, but if you want to post data using user browser then you are stuck

We have solved this by following way:

Create a RemotePost class (responsible for doing the job) as below:

Public Class RemotePost
Private Inputs As System.Collections.Specialized.NameValueCollection = _
New System.Collections.Specialized.NameValueCollection

Public URL As String = ""
Public Method As String = "post"
Public FormName As String = "form1"

Public Sub Add(ByVal name As String, ByVal value As String)
Inputs.Add(name, value)
End Sub

Public Sub Post()

Dim i As Int16
'System.Web.HttpContext.Current.Response.Write(String.Format("", FormName))
'System.Web.HttpContext.Current.Response.Write(String.Format("", FormName, Method, URL))




Dim str As String
For i = 0 To Inputs.Keys.Count - 1
str = Inputs.Keys(i)
str = Inputs(Inputs.Keys(i))
str = "input name="" type="" value=""" '(Note: put the <> tags)




End Sub

End Class

Now The posting Page which has a linkbutton

asp:LinkButton id="lnkbtnSmartTickets" Runat="server" >test post< /asp:LinkButton

And the code looks like below:

Private Sub lnkbtnPostThis_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim myRemotePost As New RemotePost
myRemotePost.URL = "Receiver.aspx"
myRemotePost.Add("param1", "this is prateek 1")
myRemotePost.Add("param2", "this is regmi2")

End Sub

Now Receiver.aspx will have following code on its form load

If Not Request.Form("param1") = Nothing Then
Response.Write("param1: " & Request.Form("param1"))
End If
If Not Request.Form("param2") = Nothing Then
Response.Write("param2: " & Request.Form("param2"))
End If

Read more!

Monday, December 7, 2009

How to fix Error while trying to run project: Unable to start debugging on the web server

I'm running 2 frameworks 2.0 and 1.1. I had to do the following to switch to 1.1.In a dos prompt do the following:
cd c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
aspnet_regiis.exe -u
cd c:\WINDOWS\Microsoft.NET\Framework\v1.1.4322
aspnet_regiis.exe -i

Its hectic but its better to create a batch file to run this when ever required

thanks todymcgee

Read more!

Thursday, December 3, 2009

Problems converting string date to Date or Date time in .net

I was having issue publishing my web site in the Server its regional settings were different to mine and my Asp .net website was giving me following error

" String was not recognized as a valid DateTime "

Since it was working fine in my computer and in debugging mode.

It wasted my 2 hours and finally i changed the code to following to solve the problem

dt = New DateTime(Convert.ToInt16(strYr), Convert.ToInt16(strMon), Convert.ToInt16(strDay))

or if date and time both is required then

dt = New DateTime(Convert.ToInt16(strYear), Convert.ToInt16(strMonth), Convert.ToInt16(strDay), Convert.ToInt16(strHr), Convert.ToInt16(strMin), 0)

This would run without error no matter what regional settings is in the server so it is simpe code but pretty handy. Enjoy coding

Read more!

Monday, October 26, 2009

Simple steps listed to create a ruby on rails application

This article lists all the steps required to create a simple web site in ruby on rails.
This article a fast track approach in developing a ruby on rails website.

First download and install the ruby on rails. If you haven't yet then you can go to Ruby on rails website and then download and install and start mysql and Apache web server that can be done by starting InstantRails.exe in the Instant rails folder.

Now go to command prompt and enter use_ruby

This will take you to rails application path if ruby on rails has been installed properly in the drive.
Then follow the following steps to create a complete website:

1 . rails AppName

2. Change database.yml file to point to required database

3. rake db:create:all Creates the database
4. ruby script/generate scaffold Table1 column1:string column2:text column3:integer

5. ruby script/generate scaffold Table2 column1:string column2:text column3:integer

6. change db/migrate/ 001_create_table1.rb file specify the limit and add t.references :table2 for foreign key

7. rake db:migrate

8. Open up modals and setup Active record base for recipie and category.

9. put has_many :recipes in category ActiveRecord:: base

10. put belongs_to:category in reciepe ActiveRecord:: base

11. go to public folder and delete index.html

12. open routes.rb file from config folder and find map.root and enable that portion.

13. Set map.root :controller => "categories"

14. Now open C:\InstantRails-2.0\rails_apps\astroun\app\views\categories\new.html.erb and

15. delete the portion between <% form_for(@recipe) do |f| %>
<% end %> from recipie.

16. create a new file called _form.html.erb which is partial and it renders the form.

17. Paste the portion deleted in new.html.erb into this new file _form.html.erb and

18. Now put the render code in the deleted portion of new.html.erb :
<%= render :partial => "form", :locals => { :f => f, :button => "Create" } %>

19. And similarly in edit.html.erb put
<%= render :partial => "form", :locals => { :f => f, :button => "Update" } %>

20. Now run and see by doing ruby script/server and run http://localhost:3000/

21. Scaffold creates layouts in views that can be delted and modified as per need.

22. Lets delete these files in layout folder and create application.html.erb as application wide layout.

23. Now it works fine but with one problem if there are reciepies in category but if we destroy the category then when we try to list the recipies that throws error because category is not there.

24. To fix this make changes in categories_controller saying if it has items in it then don't destroy the category.

Read more!

Tuesday, September 22, 2009

How to use Json objects and Jqeury in Part -3

This is continuation of the tutorial how to use JSON objects and JQuery in part -2
which explains the aspx page and how to use JQuery to render the data into the aspx page. This part of the tutorial explains how to use a handler to communicate between the Java script and the business logic layer and return back the json objects data. If you want to go to the starting of this article then it can be found in How to use JSON objects and JQuery in part -1.

Lets add the handler in the Asp .net web project and name it jqAirlines.ashx.
My whole code for jqAirlines.ascx can be found here:

Now in sub ProcessRequest check the parameters received (action).

I have declared the business layer as bll and lstAir as list of my TarrifAirlines

and similarly set the contextType = "application/json" that means we will be returning json format data back

Similarly get the pageSize and startRecord and put them in variables.

Then it calls the function bll.CountAirlinesJQ that gives the count of the records and then calls the function bll.GetAirlinesJQ that gets the list of TariffAirlines which is explained in How to use Json objects and Jqeury in Part -1.

Now the lstAir is the list of TariffAirlines and we need to convert it to json format, so we can get stuck here and try to find the ways or even plan to write the function to convert it. It is a lengthy process so why not use opensource dll (Newtonsoft.Json.dll) by Newtonsoft which can be downloaded from Json.Net
strJsonAir = Newtonsoft.Json.JavaScriptConvert.SerializeObject(lstAir)

Now strJsonAir would have list of TariffAirlines as a serilized string in json format.

We now declare a stringBuilder named writer and lets append with count, pagesize, startRecord and data that contains the collection of TarrifAirlines ie strJsonAir in the JSON format and write it back which is then used by our javascript explained in How to use Json objects and Jqeury in Part -2

Now hope you understand the now how to use JQuery, and render the JSON objects in three tier ASP. net web applications. If any confusion or suggestions please feel free to comment or directly email me.

Read more!

How to use Json objects and Jqeury in Part -2

This is continuation of the tutorial how to use JSON objects and JQuery in part -1 which explains how to retrieve the data and return it back to the presentation layer from data access layer and then from business layer. Now in this part i will explain aspx page where we will prepare a basic structure of the page and also learn how to use jquery in it.

- Download latest version of Jquery from or you can use Google API link which will be more reliable.
Lets add a aspx page in our web project named jqAirlines.aspx
and add the javaScript link to jquery and format your aspx page. I have done mine as below:

Now lets analyse this code:

I have div id="pageBody" that lies inside the form. and I have 3 more divs namely "dvLoading" where loading image is displayed, "tableArea" where main grid loads but this table has structure only and finally "btnArea" where my buttons will be located, now i only have Display button.

Now we are done with our aspx page now we need main files where we do our code rendering. Lets add a javacript file called jqAirlines.js , You might have noticed link to jqAirlines.js in the aspx page. Here we write all our JQuery code from where we will render the aspx page.

Lets see the JQuery code from the link provided below and i will try to explain how this javascript functions:

Now in the above js code $(function(){ is the main jquery function that is called first when page loads and that does all the job.

Now lets look step by step to this function
$("#dvLoading").hide(); --> hides the div named dvLoading
$("#airTable").hide(); --> hide the table first
Then when display is clicked
It calls the function

Now Lets go to the function list(startRecord, pageSize)
if the page size is not given then make it 10

Now main function $.getJSON gets the json data back after rendering the handler jqAirlines.ashx (or web service)

Analyzing the $.getJSON function it calls jqairlines.ashx and sends the parameters called action, pagesize and startRecord and gets json data "data" back which then passed to function ShowAirlineList(data) for further processing.

Now lets see the function showAirlineList(data)

This function starts assigning the value of data in an array called currentAirList
then hide and empty the table if it is already filled. Then Append the header row in #airTable thead .
Now from the data we loop through a collection inside it called Data that has been returned by jqAirlines.ashx page and append the data to tbody other seem pretty straight forward where page items are shown or hidden.

Now We have completed our .js file as well but the main portion where it calls the business layer function and converts back to json object and returns back for this .js to render is handler jqAirlines.ashx Further explanation of this handler is done in How to use Json objects and Jqeury in Part 3 of this Tutorial.

Read more!

How to use Json objects and Jqeury in Part -1

This is a very cruital article for all programmers wanting to learn jquery and apply it to their Asp .net web applications. This jquery, json and asp .net 2.0 tutorial explains step by step on how to retrieve the data from the database and render it back as json objects and display it on the web page using jquery.
When I was learning jquery, I actually was looking for similar tutorial where it can be explained using .net platform but i couldn't find exact solution and i spent so much time to get to this. Therefore i am writing this tutorial for all the .net programmers who want to learn jquery and apply it to their .Net web applications.

This tutorial assumes that the reader know basics of jquery and json objects and able to program dynamic websites in .net and knows the concept of three - tier architecture. I am not providing the full source code for this but i will try to explain the best i can with the help of code screenshots. You can definately ask questions and write comments and i will try to answer them as i get time off my work.

Ok lets begin here now:

In this tutorial I am using a table called Carriers that has carriers_code and Description Field containing 30 records and i will just show you how to retrieve these records and display in the grid with paging. I am pretty sure if you can retrieve and display records then you can easily insert, update or delete records.

Ok now lets see database layer code below ( Now if you don't know about Data access layer, business layer and presentation layer then you can learh how to develop three tier web application in .net )

Below function gets the count of the number of records:

Public Function CountTAirlinesJQ() As Integer
Dim count As Integer
Dim strSql As String
Dim dr As OleDb.OleDbDataReader

strSql = "Select Count(*) from Carriers"
db = New DBHelper("SFIA")

dr = db.ExecuteAndGetRowOLEDB(strSql)
If dr.Read() Then
count = dr(0)
Return 0
End If

Return count
End Function

Below function retrieves the data and return as the list of TariffAirlines object.

Public Function GetTAirlinesJQ(ByVal PageSize As Integer, _
ByVal StartAt As Integer, _
ByRef ErrMsg As String) As List(Of TarrifAirlines)

Dim ds As DataSet
Dim Airs As New List(Of TarrifAirlines)
Dim strSql As String
Dim Top As Integer

If PageSize > 0 Then
Top = PageSize + StartAt
strSql = "Select Top " + Top.ToString + " carriers_code,Description from Carriers"
strSql = "Select carriers_code,Description from Carriers "
End If

db = New DBHelper("SFIA")
ds = New DataSet

ds = db.getDataset(strSql)

Dim dt As DataTable = ds.Tables(0)
Dim row As DataRow

Dim Airline As TarrifAirlines

Dim i As Integer
For Each row In dt.Rows
Airline = New TarrifAirlines
Airline.AirlineCode = row.Item("carriers_code").ToString()
Airline.AirlineName = row.Item("Description").ToString()

' PAGING here...............................>
'' frist get select top 10 from the table
' net time it will be top 20 and so you will pick up last 10
' because you will start at 10 now...

If i >= StartAt Then
End If
i = i + 1

Return Airs
Catch ex As Exception
ErrMsg = ex.ToString()
Return Nothing
End Try

End Function

Similarly following business layer function return values to the presentation layer:

This returns the count from AirlinesDB containing above code

Public Function CountAirlinesJQ() As Integer

Dim db As New AirlinesDB
Return db.CountTAirlinesJQ()
End Function

Below function returns the list of TAirlines object retrieving from the AirlinesDB to the presentation layer:

Public Function GetAirlinesJQ(ByVal PageSize As Integer, _
ByVal StartAt As Integer, _
ByRef ErrMsg As String) As List(Of TarrifAirlines)

Dim db As New AirlinesDB
Return db.GetTAirlinesJQ(PageSize, StartAt, ErrMsg)

End Function

Ok now we have retrieved the data from the database and returned the count of the tables and list of Tairlines object. This tutorial will get longer therefore i am dividing this to different parts. Ok now Lets go to Second part of learn how to use json objects and jquery in Part 2.

Read more!

Wednesday, September 2, 2009

How to Update App.config during runtime from .net 1.0 or .net 2.0 application?

If you want your .net 1.0 or .net 2.0 application to update app.config file during runtime then below code solves your problem. If you want to change certain settings after user logs in to your system like for eg. last login username then this code will be very helpful.

Lets look visual basic code to update app.config file in .net 2.0

Private Sub UpdateAppConfig()
Dim config As System.Configuration.Configuration = _
Dim oldValue As String
Dim newValue As String

oldValue = config.AppSettings.Settings("LastUserID").Value

If oldValue = "" Then
'do anything you like
End If

newValue = "NewUser"

'You can add a new value or remove like below just play around
config.AppSettings.Settings.Add("NewKey", "1234")
' enter new values to the config file
config.AppSettings.Settings("LastUserID").Value = newValue
' save the config file
' Now force to refresh the configuration file in the application

End Sub

Similarly lets look visual basic code to update app.config file in .net 1.0

Since .net 1.0 does not have the facility to directly save the config files as done above we have to individually go through the xml nodes of the config file and update it See below for the full function that updates the file:

Private Sub UpdateAppSetting()
Dim xmlDoc As New Xml.XmlDocument
Dim strkey As String = "LastUserID"
Dim strValue As String = "234324"
' load the file from the system where it is located
Dim element As Xml.XmlElement

For Each element In xmlDoc.DocumentElement
'check if it is appsettings or not
If element.Name.Equals("appSettings") Then
Dim node As Xml.XmlNode
For Each node In element.ChildNodes
' update the key with the value provided above
If node.Attributes(0).Value.Equals(strkey) Then
node.Attributes(1).Value = strValue
End If
End If

End Sub

Read more!

How to restart .net 1.0 application automatically?

If you want your .net 1.0 application restart automatically then this article has the solution. Also it sloves the problem like waiting until the previous instance of the .net application is killed and restarting itself.

Private Sub RestartApp()
'Waits some time for the application to exit
' End the current process

End Sub

Read more!

Monday, August 17, 2009

How to login as different windows user from application

I was just doing a vb net application that talks to a third party application that runs under a windows service domain user account.

So now my application need to login as the service account from the vb net code and then talk to the third party application and then log off from the service account.

I have solved this using the below visual basic code

Imports System.Security.Principal

Module Common
Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As String, _
ByVal lpszDomain As String, _
ByVal lpszPassword As String, _
ByVal dwLogonType As Integer, _
ByVal dwLogonProvider As Integer, _
ByRef phToken As IntPtr) As Integer

Declare Auto Function DuplicateToken Lib "advapi32.dll" _
(ByVal ExistingTokenHandle As IntPtr, _
ByVal ImpersonationLevel As Integer, _
ByRef DuplicateTokenHandle As IntPtr) As Integer

Dim impersonationContext As WindowsImpersonationContext

Public Function impersonateValidUser(ByVal userName As String, _
ByVal domain As String, ByVal password As String) As Boolean

Dim tempWindowsIdentity As WindowsIdentity
Dim token As IntPtr
Dim tokenDuplicate As IntPtr

If LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, _
LOGON32_PROVIDER_DEFAULT, token) <> 0 Then
If DuplicateToken(token, 2, tokenDuplicate) <> 0 Then
tempWindowsIdentity = New WindowsIdentity(tokenDuplicate)
impersonationContext = tempWindowsIdentity.Impersonate()
If impersonationContext Is Nothing Then
impersonateValidUser = False
impersonateValidUser = True
End If
impersonateValidUser = False
End If
impersonateValidUser = False
End If
End Function

Public Sub undoImpersonation()
End Sub

End Module

Now call the function as below to Sign ON

Private Sub SignOn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SignOn.Click

If impersonateValidUser("test", "", "test") Then
' do talking to the third party application here

MsgBox("The user is not validated")
End If

End Sub

Now call the function as below to Sign OFF

Private Sub SignOff_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SignOff.Click

End Sub

Read more!

Tuesday, July 7, 2009

Connection attempt Failed for Ruby gem update --system (Solved for windows users)

I encountered while trying to update ruby gem and took my more than 1 hour to search for the solution and have to go through lots of blogs and scroll through the comments to finally get the right answer.

When i did gem update --system then i got the following error:

ERROR: While executing gem ... (Gem::RemoteFetcher::FetchError)
A connection attempt failed because the connected party did not properly res
pond after a period of time, or established connection failed because connected
host has failed to respond. - connect(2) (Errno::ETIMEDOUT)
getting size of


So this might be due to the connection to the site or the proxy problem

1 Go to your IE Internet options/connections/Lan Settings/

2. Check your proxy and its port

3. go to Command prompt and do

set http_proxy=http://proxy:port

Now do gem update --system

Should work now.....

Read more!

Monday, July 6, 2009

How to export data from an Asp net website to an Excel File?

In web sites it is pretty good to have a export button for the users to get the data in excel displayed in grid or gridview insted of printing them.

Those can be very useful for many reporting issues in an organisation.

Here i am explaining the function that will help to export data from the website to an excel or csv file and it is pretty easy.

Private Sub ExportData()

Dim dt As Data.DataTable
Dim Bl As New BLL
' Here I get all the data required to fill data table from my business layer
dt = Bl.GetDataForExport()
'Create a dummy GridView
Dim GridView1 As New GridView()
GridView1.AllowPaging = False
GridView1.DataSource = dt
Response.Buffer = True
Response.AddHeader("content-disposition", _
Response.Charset = ""
Response.ContentType = "application/"
Dim sw As New IO.StringWriter()
Dim hw As New HtmlTextWriter(sw)

For i As Integer = 0 To GridView1.Rows.Count - 1
'Apply text style to each Row
GridView1.Rows(i).Attributes.Add("class", "textmode")

'style to format numbers to string
Dim style As String = ""

Catch ex As Exception
strErr = ex.ToString()
dvMsg.InnerHtml = strErr
dvMsg.Visible = True
End Try
End Sub

Just fetch the data from your business layer and use the above function on click event of the control, it will work for you.

Read more!

Monday, June 15, 2009

Sys Not defined even after you fix the web config " Solved "

I fixed this problem long time back by fixing the web.config and launched my website,
See the Web.config fix for 'Sys' is undefined
But to my surprise after few days i got complaints about my site crashing and the crashes were only for few Internet Explorer users.

I tested it again in my computer and saw the same old stupid bug "Sys Not Defined" !!!

Now what? I thought I have already fixed it, and i noticed its happening in only one page all other pages seem to be working normal. Then that kept me thinking if the fix of "Sys Not Defined " was in web.config modification then why I am getting error in only one page.

Did some investigation and found out the fix by declaring Scripts after ContentTemplate

script type="text/javascript" src="../Scripts/smartFare.js">/script>

This should fix the problem, for now, lets not hope it comes back again....

Read more!

Monday, June 1, 2009

Solve undefined method `render_text' in Ruby on rails

I have just started to work on Ruby on Rails and was going through step by step Ruby on rails tutorial. 

As i went through I got on to undefined method `render_text' .... Now what ???

so looking into various web sites I Finally got it

You can use

render :text =>"Hello World" Instead of render_text

Enjoy learning ruby

Read more!

Thursday, April 30, 2009

How to open a child window on row command, pass value to child window and return values to parent form in 2.0?

This is a very good asp net tutorial to address the issues of passing the values "to and from" a parent and child window in asp net 2.0.

In this asp net tutorial i have passed values from parent window to child window to tick check boxes and get values back from checkboxes from child and
pass it back in the text box in asp net gird view.
I got this working getting help from different websites and was hassle doing it.

So I thought of putting it together in one article so that it helps other programmers to save their time programming asp net 2.0 web sites.

I will explain my case:
I have a asp net 2.0 gridview where I bind the data from microsoft sql server 2005 database. In the grid I have a text box in one column and I have a button on column next to the text box column.
Now when I press the button then it has to pick the values from the textboxes delimited by some character, and open a new child window which has a grid populated from the database and has the check box. Now those check box has to be ticked reading the values passed from the textbox from the grid of the parent form.
Also when the user unticks the checkboxes or ticks additional checkboxes and closes the child form then it should pass back the checked values to the appropriate textbox on the grid of the parent form.

Ok Now lets Start the tutorial.

Here for this asp net 2.0 tutorial i have created two tables in my sql server database
Table Customers
ID int
Name varchar(50)
Cars varchar(100)

Table Cars
CD varchar(10)
CarName varchar(100)

Now in this application I will have a customer who has different cars and car CDs are recorded in column cars delemitated by "/".

This has to be done in some situations where you have no access to cars table.

Ok Now lests start a website in asp net 2.0 containing master and detail pages
(Learn how to design Master Detail pages in asp net 2.0)

Add two web forms in the website, first is Default.aspx (parent form) and link it to the Master page. Similarly add another web form cars.aspx but don't link it to the master page as it will act as child window.

Now add the database classes to connect to the database
(Learn how to connect to the database from asp net web site) and write the classes to retrieve the data from the customers table and Cars table from the database.
(Learn how to retrieve data from the database)

In my case I have class DBObj for connection to the database and I have a class RetrieveData for retrieving the data where I have three functions
I am planning to use object as a datasource in this tutorial so I am returning objects from the functions below:

(No clue about object data source in asp net 2.0 then Learn how to use object as data source in asp .net applications )

1. Public Function GetCars(ByVal strCars As String) As List(Of Cars) (returns list of cars)
2. Public Function GetCustomers(ByVal strCars As String) As List(Of Customer) (returns list of customers)
3. Public Function CheckCars(ByVal CD As String, ByVal strCars As String) As Boolean (checks if the car has to be ticked or not)

In Cars object I have a property called checked that determines if the car is in the customer list or not. So this function determines if this property has to be set true or not by getting stringCars as input.

I have added a Java script file in the Default.aspx page called Test.js
Now Lets bind a asp net 2.0 grid view named gvCustomers in Default.aspx page and grid view named gvCars in Cars page.

My Default.aspx page has a asp net 2.0 gridview with following columns :
Customer Name,
Customer Cars (Text Box Field which is bound to CustCars field),
cmdCar (Command button to open up the Cars Window),

Note: And on cmdCar Under OnClientClick I have called a Java Script Function called openPage(this);

My default.aspx code looks like below:

And my Test.js has the following code:

Similarly my CarsFrm.aspx has a asp net 2.0 gridview with following columns:
chkOk (Check box which can be selected by user)

And it has a command button called cmdOk

My CarsFrm.aspx code looks like the following:

Now when you run the application then you are able to see the gridview with data and command button and when the command button is pressed a new window for cars opens up. Now lets transfer data "to and from" Cars page.

Now here I will explain step by step which makes it easier to understand:

Step 1 .
On Default.aspx in grid gvCustomers cmdCar put the following code:
OnClientClick="openpage(this);return false;"

Step 2.
openpage(obj) on the java script will be called where it will open up cars.aspx page.
Also sends the data from adjacent text box to the cars page.

step 3.
put a hidden field "hdTest" in cars.aspx
asp:HiddenField ID="hdTest" runat="server"

and one label to test the hidden field is working or not and name it "lblTest"

Step 4.
in cars page load retrieve the data arrived with following code
strCars = Request.QueryString("target")
and bind the grid
gvCars.DataSource = obj.GetCars(strCars)

GetCars retrives all the cars from the table and checks the ones that are on the string strCars

Step 5.
Now in cars.aspx page you need to set the databinder for checked as follows
asp:CheckBox ID="chkOK" checked=''

and on gvCars_DataBound put the following code to see if the code is passed ok :
For Each gvr As GridViewRow In gvCars.Rows

Dim cb As CheckBox = CType(gvr.FindControl("chkOK"), CheckBox)

If cb.Checked = True Then
strCarCode = strCarCode.Trim() & "/" & gvr.Cells(0).Text.Trim()

End If

If strCarCode.Length > 0 Then
hdTest.Value = strCarCode.Substring(1, strCarCode.Length - 1)
lblTest.Text = strCarCode.Substring(1, strCarCode.Length - 1)

End If

(Now try to run the application and enter the car code in the text box now you can see the checkbox checked in cars Grid)

Step 6.

Now in Default.aspx register a javascript function called update to update the textbox in the grid.
like folows
scr = ""

' register the javascript into the Page
ClientScript.RegisterClientScriptBlock(Me.GetType, "update", scr)

Step 7.
similarly in cars.aspx page register a function to send it to Default.aspx page
like follows:

strTextId = Request.QueryString(1)
scr = ""

ClientScript.RegisterClientScriptBlock(Me.GetType, "done(fName,strId)", scr)

cmdOk.OnClientClick = "Done('" & str & "','" & strTextId & "')"

Step 8.
Now we are ready to send the data to the main form from the child form in asp .net website.
Now we have to get the data and put it in correct format and send it to the main form:

in cars.aspx page just assign the event to check box as OnCheckedChanged="chkOk_CheckedChanged"
and write the following code to get the value of the checkbox and format the data:
Dim chkbox As CheckBox
       Dim strText As String = ""

       chkbox = CType(sender, CheckBox)

       Dim row As GridViewRow = CType(chkbox.NamingContainer, GridViewRow)

       strText = hdTest.Value

       If chkbox.Checked = True Then
           If strText = "" Then
               strText = strText & row.Cells(0).Text.Trim

               strText = strText & "/" & row.Cells(0).Text.Trim

           End If

           If InStr(strText, "/") > 0 Then
               strText = strText.Replace("/" & row.Cells(0).Text.Trim, "")
               strText = strText.Replace(row.Cells(0).Text.Trim & "/", "")
               strText = strText.Replace(row.Cells(0).Text.Trim, "")
           End If
       End If

       hdTest.Value = strText
       lblTest.Text = hdTest.Value
   End Sub

Note : remember to do AutoPostBack="true" for checkbox so that the hidden field is written at the time when we check the box
The checkbox in Cars page will look like follows:
asp:CheckBox ID="chkOK"
OnCheckedChanged="chkOk_CheckedChanged" /

Now run the website it should be passing data to and from the parent and child forms.

Download Full surce code for "How to open a child window on row command, pass value to child window and return values to parent form in 2.0?"

Read more!

Tuesday, March 31, 2009

How to merge columns of a gridview in Asp net 2.0?

I was playing around gridview to find out the ways to merge the cells in asp net 2.0 gridview as we do in Microsoft excel. After working few hours on it with the help of google i got a function ready for the new programmers to learn how to merge cells in asp net 2.0 gridview which has got identical data.
You can just use the following function to merge the cells of asp net 2.0 gridview as in Microsoft excel:

Public Shared Sub MergeCells(ByVal gridView As GridView)
        For rowIndex As Integer = gridView.Rows.Count - 2 To 0 Step -1
            Dim row As GridViewRow = gridView.Rows(rowIndex)
            Dim previousRow As GridViewRow = gridView.Rows(rowIndex + 1)

            For cellIndex As Integer = 0 To row.Cells.Count - 1
                If row.Cells(cellIndex).Text = previousRow.Cells(cellIndex).Text Then
                    If previousRow.Cells(cellIndex).RowSpan < 2 Then
                        row.Cells(cellIndex).RowSpan = 2
                        row.Cells(cellIndex).RowSpan = previousRow.Cells(cellIndex).RowSpan + 1
                    End If
                    previousRow.Cells(cellIndex).Visible = False
                End If
            Next cellIndex
        Next rowIndex
    End Sub

Read more!

Monday, March 23, 2009

How to find the week number for a date of a month .net?

If you want to show the report in .net or asp .net application for a month and divide the data in weekly basis then you need to identify the week number to show the data accordingly. The following .net code allows you to find the week number for the given date of a month.

Dim userDate As DateTime
       Dim remain As Integer
       Dim noOfWeek As Integer

       userDate = DateTime.Parse("01/02/2010")

       noOfWeek = Math.DivRem(userDate.Day, 7, remain)

       If remain > 0 Then
           noOfWeek = noOfWeek + 1

       End If
       MessageBox.Show("The week no is :" & noOfWeek.ToString())

Enjoy coding

Read more!

Sunday, March 15, 2009

How to use Session in 2.0 web site design?

This article can also be defined as " How pass an object from one page to another using Session in 1.0 or 2.0 application?"
This tutorial shows how to use session for passing data from one page to other page using session.
This article is very helpful for validating the user name and password while asp net 2.0 login or 1.0 login using session. This process validates the user on every page of 2.0 or 1.0 website.
The data passed is only valid till the asp net session has not timed out. If the asp net session is timed out then the website redirects it to the asp net login page where the user has to enter the username and password again. The asp net session timeout information can be set as per required by the business.
Ok Lets go to the actual process on how to use asp net session in asp.Net web site development?

First open the web site or Learn how to develop an web site in .Net

Click on Ok or Submit button on Login.aspx page and include the following code:

Protected Sub cmdOk_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdOk.Click
       Dim strUser As String = Me.txtUserName.Text.Trim()
       Dim strPass As String = Me.txtPassword.Text.Trim()
       If strUser = "" Or strPass = "" Then Exit Sub

       Dim usr As User

           usr = BUser.AuthenticateUser(strUser, strPass)

           If usr Is Nothing Then
               lblMsg.Text = "Login failed"
           ElseIf usr.SecurityLevel = 0 Then
               lblMsg.Text = "You are not allowed in this site"
               Session("SFUser") = usr
           End If
       Catch ex As Exception
           lblMsg.Text = ex.ToString()
       End Try
   End Sub

In the above code you can see I have picked up username, password from the text box and declared a User Class and got the user information from BUser.AuthenticateUser function. BUser is my Business Layer and Authenticate user function returns me the user information.
If you didn't get the clue about Business Layer then you can Learn How to Develop three tier Application

Then I have said if the user is nothing then that means the user has failed the login or security level is 0 then the user is prohibited.
Now if the login is successfull then I have put the user in session named "User"

Now lets go to the default.aspx page where the user will be retrieved from the session and check if it is valid.
Declare user on the top if you want to use the user details on this page.
Protected usr As User

On Page_Load event of Default.aspx write the following code:

usr = Session("SFUser")
      If usr Is Nothing Then Response.Redirect("~/login.aspx")

      Me.lblUser.Text = "Logged in as " & usr.UserID

Here I retrieved the user from the session and checked if it is nothing or not if it is nothing that means the user's session has timed out or the user is not coming from the login page, the user is redirected to the login page.

If the user is valid then I have included user name a Label control.

Enjoy the code and do not forget to comment.

Read more!

Wednesday, February 25, 2009

How to show modal Dialog panel in (In normal pages or in Master Child web applications)

Show only a dialog panel disabling the other part of the page by pressing a button.
In this article i will show how can we use this feature for displaying a image and set background disabled.
This will be a very good tutorial for learning one more feature of Ajax.
Even grid and different other data can be shown on the modal dialog where then user can do some work and close the dialog box.

First you have to download Ajax control toolkit for 2.0

Now add the reference AjaxControlToolKit.dll to your web project. Learn how to develop a web application with Asp Master Pages

Please look at the image below and I will explain on how this works:

In the image I have done the following:

First of all i have registered AjaxControlToolKit and prefix it by cc1

%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

I have added Script manager in between the content template of the detail page.

asp:ScriptManager ID="ScriptManager1" runat="server">

I have added two button because btnShowPopup will run for ModalPopupExtender as a client side control. Therefore i have disabled it. The other button btnTest is our control where we write the code to show the modal dialog panel or load any required data in the modal dialog panel and show the dialog.

asp:Button ID="btnTest" runat="server" Text="TestPopup" OnClick="btnTest_Click" />

asp:Button id="btnShowPopup" runat="server" style="display:none" />

Now I have added ModalPopupExtender from ajax tool kit and named it mdlPopup and it has targetcontrolID as btnshowpopup and popupcontrolID which it will show is pnlImage. Finally btnClose will close the modal

cc1:ModalPopupExtender ID="mdlPopup" runat="server"
TargetControlID="btnShowPopup" PopupControlID="pnlImage"

Now put the Panel where we want to display the modal and make it invisible at the beginning.

asp:Panel ID="pnlImage" runat="server" style="display:none;">
asp:UpdatePanel ID="upCities" runat="server" UpdateMode="Conditional">

Now put the label for Image name and the image and close the content template and update panel

asp:Label ID="lblImg" runat="server" Text="This is My Image">/asp:Label>
asp:Image ID="Image1" ImageUrl="~/images/logo.gif" runat="server" />


Now put the button that closes the dialog

asp:Button ID="btnClose" runat="server" Text="Close" Width="50px" />

Now close the panel tag

Now try running your application should work sweetly. Enjoy coding

Read more!

Tuesday, February 24, 2009

How to overload Constructor in

Constructors are the initialisation code of the classes or the objects that we use in Visual Basic .NET or in Visual Studio C#.NET or in Visual Basic.
In this short explanation I have used VB .NET code to explain how we can overload the constructor or have multiple constructors that can accept different parameters. Overloading helps to pass multiple paramaters to a method without using optional keyword in the method. If you overload the constructor of a class in visual basic or in c# .NET, you can initialize values for the properties of the class and which can later used in the class for performing various tasks.

Please look below where I have used the ConnectMe class where I have two constructors one has got string passed to it the other one doesn't have any parameter passed to it.

Here I have used the external connection string in one constructor to instantiate the connection string but in other constructor, if I don't get the connection string then I call the function ReadDatabaseConfig which in turn gets me the connection String.

By below example we can easily explain the use of overloading the constructor.

Public Class ConnectMe

    Public connStr As String = "" 

    Public Sub New(ByVal strConn As String)
        connStr = strConn
        If Not Connect() Then
            Exit Sub
        End If
    End Sub

    Public Sub New()

        If Not Connect() Then
            Exit Sub
        End If
    End Sub

End Class

Read more!

Sunday, January 18, 2009

How to bind an object in Grid View in visual studio .Net 2005 and handle Paging?

This article will be very helpful for the beginners and intermediate asp net programmer. This will show the easiest possible way of binding the asp net gridview in Asp net 2.0. This also explains how easily we can use the paging gridview feature of the asp net grid view without including any additional statements in the sql select query because sometimes there can be instances where the programmer is not allowed to change the sql query but they can be responsible for displaying data on the web application . So this technique will solve all the questions that are not solved by other postings seen on the web.

While doing this and prior to this post i have noted all the problems I faced and I will explain some of the related problems in this article.

This article will try to answer following questions:

How to use ASP Net Required field validator control?

How to display loading image in Asp Net 2.0 using AJAX ?

How to use ajax extensions in master and detail pages in Asp net 2.0 ?

How to solve "Element 'ScriptManager' is not a known element" error in Asp net 2.0 ?

How to handle "sys" is undefined error while using scriptmanager in Asp net 2.0 ?

Learn asp net "How to develop asp net 2.0 ajax web application with gridview?" with asp net 2.0 free source code.

Ok Now Lets Start................

Step 1

(Note: This article assumes you have installed Microsoft visual studio .net 2005 if not you can go to Microsoft express editions download page )

First open Microsoft Visual Studio 2005 and go to File --> New -->Website

Now select Asp.Net Web Site and give the path of your development site to be and
choose the language on which you want to code.

(Note: This article is written in c# so this will be talking about C# code samples in this article)

Step 2 (Adding Master and child pages)

Add one master page and name it main.Master and one child page and name it Default.aspx

(note you will see current default.aspx so just delete the current one and add the new one and select master page while adding it)

You can see How to work with 2.0 Master pages? for more detail information on how to work with master pages.

Step 3 (Adding gridview)

Now add a gridview in your default.aspx in "asp:content" or just drag and drop in design view and name appropriately. 
In this example i have given ID="grdData" and set AllowPaging="true".
see code below:

(The style of the grid can be changed from the design view by right clicking on the grid view and AutoFormat and then select the desired style for the gridview.)

Now we have got a detail page consisting of a gridview with id "grdData".
Now we need to get the data from the database to feed in the grid. For this reason i have used two classes clsDBobj.cs and DBClass.cs which is responsible for getting the data from the database.

You can write your data access classes yourself of if you want to get full detail on how to retrieve data from database you can see my post "How to retrieve data from sql server database from .net application?"

Step 4 (clsPerson)

Now lets add a class in the project and name it clsPerson and save it. This will be the object of person and includes all the getters and setters for the person class.

Lets assume Person has ID, Name, Address, Phone No fields.
And you need to write the following code in this class :

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// Summary description for clsPerson

public class clsPerson
public clsPerson()
// TODO: Add constructor logic here

    private int _id ;
    private string _name;
    private string _address;
    private string _phoneNo;

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

    public string Name
            return _name;  
            _name = value;

    public string Address
        { return _address; }
        { _address = value; }

    public string PhoneNo
        { return _phoneNo; }
        { _phoneNo = value; }

In the above code these are just the getters and setters of the clsPerson.
Getter and setter in normal language are the properties of the class.

Step 5 (DBClass)

Similarly add a new class and name it DBClass. This will be the class where we will be writing the data retrieval query and this class will be mainly responsible for returning collection of clsPerson which in turn can be used as data source in grid view.

Now just paste the following two functions in code in this class:

public List clsperson> GetPerson1(int maximumRows, int startRowIndex)
        DataSet ds;
        string str = "";
        clsDBObj objDB = new clsDBObj();
        clsPerson obj;

        str = "Select * from Suppliers";

        ds = objDB.getDataSet(str);
        DataTable dt = ds.Tables[0];

        int currentIndex = startRowIndex;
        int itemsRead = 0;
        int totalRecords = dt.Rows.Count;
        List clsperson> persons = new List clsperson>();

        while (itemsRead < maximumRows && currentIndex < totalRecords)         {             obj = new clsPerson();             obj.ID = Convert.ToInt32(dt.Rows[currentIndex]["SupplierID"].ToString());             obj.Name = dt.Rows[currentIndex]["ContactName"].ToString();             obj.Address = dt.Rows[currentIndex]["Address"].ToString();             obj.PhoneNo = dt.Rows[currentIndex]["Phone"].ToString();             persons.Add(obj);             itemsRead++;             currentIndex++;         }         return persons;              }

public static clsPerson[] GetPerson(int maximumRows, int startRowIndex)
      ArrayList ar = new ArrayList();
      DataSet ds;
      string str = "";
      clsDBObj objDB = new clsDBObj();
      clsPerson obj;

      str = "Select * from Suppliers";

      ds = objDB.getDataSet(str);

      DataTable dt = ds.Tables[0];

      int currentIndex = startRowIndex;
      int itemsRead = 0;
      int totalRecords = dt.Rows.Count;
      while (itemsRead < maximumRows &&               currentIndex < totalRecords)       {           obj = new clsPerson();           obj.ID = Convert.ToInt32(dt.Rows[currentIndex]["SupplierID"].ToString());           obj.Name = dt.Rows[currentIndex]["ContactName"].ToString();           obj.Address = dt.Rows[currentIndex]["Address"].ToString();           obj.PhoneNo = dt.Rows[currentIndex]["Phone"].ToString();                                          ar.Add(obj);           itemsRead++;           currentIndex++;       }       obj = new clsPerson();       return (clsPerson[])ar.ToArray(obj.GetType());         }  

Now in above code you can see I am using the class clsDBObj to connect to the sql server database and to get dataset of records. Get more detail about this class and know about secure database connection and easy transaction handling in .net Applications.

Similarly in above code we can notice that there are two functions GetPerson which returns the collection of clsPerson and GetPerson1 that returns the list of clsPerson. We can use any of the functions. I am just showing this to explain clearly on how we can return the object collection in different ways in .net.
But in my example I will be using GetPerson and the query will extract the supplier information from Northwind SQL Server sample database.

Step 6 (Bind Grid View)

Now lets go to code behind of default.aspx page ie: "default.aspx.cs" and bind the grid with the data.

Just paste the following code in your default.aspx.cs and call the function BindGridonLoad() on page load and run the application.

clsPerson[] prns;
   private void BindGridonLoad()
       prns = DBClass.GetPerson(int.MaxValue, 0);        
       // we are calling GetPerson class straight from 
       // the class because GetPerson is a static function

       grdData.DataSource = prns;

Now at this stage your application should run with data in the grid if it doesn't just go back and check your steps.
And now when you press the paging on the grid it would give error saying "The GridView 'grdData' fired event PageIndexChanging which wasn't handled." That means we haven't written our code for the paging of our grid so for that lets go to the next step.

Step 7 (Page Index Changing code)

Lets go to Default.aspx Design page and select the gridview and open the properties of the gridview or press F4 to see the properties and press the events button to see all the events of gridview see below image:

Then double click on PageIndexChanging event and paste the follwoing code in the code behind default.aspx.vb:

protected void grdData_PageIndexChanging(object sender, GridViewPageEventArgs e)
        prns = DBClass.GetPerson(int.MaxValue, 0);       

        grdData.PageIndex = e.NewPageIndex;
        grdData.DataSource = prns;

In the above code you can just find the difference is griddata.pageindex =
e.newpageIndex. I have included the max value and startRow in the GetPerson function but haven't used it here because i am just showing that there are both ways of doing this.

Now we can run the application and see our grid loads data and its paging is working properly. But we can see that columns are not in the right order and even header text is not what we desired so in next step we will try to bind the individual column of the grid and display the desired header text of each column.

Step 8 (Bind individual Column of grid view)

Lets go to the Default.aspx source page and in the gridview set

Also bind the individual columns in the gridview as shown in the image below and
try running the application and you can see the formatted gridvew as desired.

Now we have completed binding the data in grid view now in next steps i would show how to use ajax (Asynchronous JavaScript and XML) while loading the grid and show loading image.

Step 9 (Use Ajax in application)

First add a loading.gif image in the project to show the application is loading.
"Download the animated loading images from AJAX Load Image"

Frist download AJAX 1.0 and install it into your pc else .net will show error if we try to use its controls.

Lets go to the Default.aspx page and just place the scriptManger and Updatepanel
add contenttemplate inside update panel and close contenttemplate and updatepanel just before the asp:content tag as shown in the figure below:

Now in the image you can see there is red underline in most of the Ajax components that means visual studio 2005 is not understanding the ajax component. And we can see the following error message : "Element 'ScriptManager' is not a known element. This can occur if there is a compilation error in the Web Site"

I googled it and found an article on Ajax Error post.

And the above post explains this might be because i have not installed Visual Studio 2005 Service Pack 1 . Download Visual Studio 2005 Service Pack 1

After Visual studio 2005 service pack 1 is installed all the errors are removed from the code and it seems now visual studio 2005 understands all the Ajax components.

Then below asp:Gridview just put the updateprogress code as below to show loading progress image:

Ok now run the application and see the ajax effect ... " opps " we can see no ajax effect but there we see error on the page and the error is " 'Sys' is undefined ". Now see the next step to solve this error:

Step 10 ( How to solve 'Sys' is undefined error? )

This is explained clearly in the post 'Sys' is undefined - ASP.NET AJAX Error solved

Now after changing the web.config file now your site is Ajax enabled and has grid view with paging.

You can download How to bind an object in Grid View in visual studio .Net 2005 Tutorial file here.

Please feel free to comment

Read more!