Recent Posts

Tuesday, September 22, 2009

How to use Json objects and Jqeury in Asp.net? Part -3

This is continuation of the tutorial how to use JSON objects and JQuery in Asp.net 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 Asp.net 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 Asp.net? 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 Asp.net? 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 Asp.net? Part -2


This is continuation of the tutorial how to use JSON objects and JQuery in Asp.net 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 Jquery.com or you can use Google API link which will be more reliable.
Lets add a aspx page in our Asp.net 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
$("#cmdDisplay").click(function(){
It calls the function
list(0);

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 Asp.net? Part 3 of this Tutorial.



Read more!

How to use Json objects and Jqeury in Asp.net? 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)
Else
dr.Close()
Return 0
End If
dr.Close()

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

Try
If PageSize > 0 Then
Top = PageSize + StartAt
strSql = "Select Top " + Top.ToString + " carriers_code,Description from Carriers"
Else
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
Airs.Add(Airline)
End If
i = i + 1
Next

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 Asp.net? 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 = _
System.Configuration.ConfigurationManager.OpenExeConfiguration(Configuration.ConfigurationUserLevel.None)
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
config.Save()
' Now force to refresh the configuration file in the application
Configuration.ConfigurationManager.RefreshSection("appSettings")

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
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
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
Next
End If
Next
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)


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()
Application.Exit()
'Waits some time for the application to exit
System.Threading.Thread.Sleep(5000)
System.Diagnostics.Process.Start(Application.ExecutablePath)
' End the current process
Process.GetCurrentProcess.Kill()

End Sub


Read more!