Recent Posts

Wednesday, August 13, 2008

Ajax like look and feel from Json and what is Json?

JSON what is it and how it works?

The description of JSON is "JavaScript Object notation".
According to the official website it is a lightweight data-interchange
format. It is human readable and writeable and is a subset of the Javascript
Programming Language.
It is completely language independent.
Jason Looks like this and is in easily readable format like xml.

{
"Firstname": "John",
"Lastname": "Smith",
"emailaddrs": [
{"type": "work", "value": "abc@work.com.au"},
{"type": "home", "pref": 1, "value": "abc@work.com.au"}
],
"phones": [
{"type": "work", "pref": 1, "value": "123 12321221321"},
{"type": "mobile", "value": "123 23232323"}
],
"Experience":
["2006", "2007", "2008"]

}

You can access the jason property in javaScript as follows:



var fname = jsonObject.FirstName


I found this help from Codeville.net and I have tried this out myself and found this to be interesting topic to be explored.

Also while trying this I have a test project that i will explain it to you guys that helps you to understand about it more.

This example shows how easy it is to build dynamic lists using jason and and having the ajax experience in ASP.net

1. First step is to download the following dlls from Download Jason Dlls




2. Open a web project and put those two dlls in the bin folder of your project.

3. add a web form and name it rprateekDemo.aspx and copy the following code :
(or you can add any name and modify code as per the name of the aspx)



(note: you can get the source file on the JasonDll.rar that you downloaded above

4. Then add the following code in the code behind file rprateeDemo.aspx.cs :

using System;

namespace rprateek.blogspot
{
public partial class SimpleListDemoPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TagList.Model["tags"] = new string[] { "AjaxFeel", "MVC", "JavaScript" };
}
}

protected void SubmitButton_Click(object sender, EventArgs e)
{
// Retrieve updated data model from control
string[] tags = (string[])TagList.Model["tags"];
ResultsLabel.Text = string.Format("You entered {0} tag(s): {1}", tags.Length, string.Join(", ", tags));
}
}
}

5. Add a file name it TagList.jmvc and copy the following code in the file :

(note: you can get the source file on the JasonDll.rar that you downloaded above )

6. Now save build and run the application and check out how sweetly it works.



Read more!

Thursday, August 7, 2008

How can we send cursor to catch even if there is no error in .Net

For error handling put try catch exception in your function and in the catch part you can do all your garbage collection and closing the instances.

And

If your logic doesn't match with certain cases in the function then you can send to catch with the message you want to display to the user by the following way

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim i As Integer
i = Val(Me.txtErrMsg.Text)
Try
If i = 4 Then

' If i = 4 then I want to go to catch and display the message Now throwing exception
Throw New Exception("Exception: 2 is selected")

Else
Me.txtErrMsg.Text = "Normal"

End If

Catch ex As Exception
Me.txtErrMsg.Text = ex.Message
End Try
End Sub


Read more!

How to find duplicate records in a Table (SQL Query)

Books table might have multiple bookKey. So to find out duplicate rows in a table which has thousands of rows can be tricky.

So the following query gets the duplicate records from the table and displays it and if you just want the count then you can use only the internal select statement only.

select b.* from (select bookkey, count(bookkey)as dup from Books where bookkey>0 group by bookkey) a,
books b where b.bookkey = a.bookkey and a.dup >1 order by b.bookkey

select b.* from (select bookkey from books group by bookkey having count(bookkey)>1) a,
books b where b.bookkey = a.bookkey order by b.bookkey


Read more!

Wednesday, August 6, 2008

How to check if the previous instance of the Application is already running in c#.Net

The following code illustrates how to check if previous instance of the application is running

using System.Diagnostics;


public void CheckForExistingInstance()
{
Process process = Process.GetCurrentProcess();

if (Process.GetProcessesByName(process.ProcessName).Length > 1)
{
MessageBox.Show("Another Instance of this process is already Running",
"Multiple Instance Forbidden", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
Application.Exit();
}

}


Read more!

Monday, August 4, 2008

Secure database connection and easy transaction handling in .Net Applications

Check out the full code for database connections, also learn steps on how to read an ini file from vb net, asp net applications  where you can store your database settings like datasource, username, password etc . 

This is very easy but very essential and convenient way of connecting the VB .net application to the SQL server database and handling the transactions.

Also simple execute and returning dataset functions are very helpful for any application development.

Required is the DBConfig.ini file where you can store your database information and keep it safe.

[DBConnection]
DataSource= 10.10.10.10
DBaseName= Data
UserID= sa
Password= sa

Please check out the following functions:

Public Const strDBConfFile = "C:\DBconfig.ini"

Imports System.Data.SqlClient

Public Class clsDBObj

Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim isTran As Boolean
Private trans As SqlTransaction
Dim connStr As String

' Just connect
Public Function Connect() As Boolean

Dim bln As Boolean
Try
If conn Is Nothing Then
bln = ReadDatabseConfig(strDBConfFile)
If bln = True Then
conn = New SqlConnection(connStr)
Else
MessageBox.Show("There is no Configuration file or Error in Config File!! Please Check")
End If
End If
If conn.State = ConnectionState.Closed Then
conn.Open()
End If

Exit Function

Catch ex As Exception
MessageBox.Show("Cannot connect to the database")

End Try

End Function

Public Sub BeginTransaction()

If isTran Then Return
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
trans = conn.BeginTransaction()
isTran = True
End Sub

Public Sub CommitTransaction()

If Not isTran Then Return
trans.Commit()
conn.close()
trans = Nothing
isTran = False
End Sub

Public Sub RollBackTransaction()
If Not isTran Then Return
trans.Rollback()
conn.close()
trans = Nothing
isTran = False
End Sub

Public Sub CloseConn()
If Not conn Is Nothing Then
If Not conn.State = ConnectionState.Closed Then

conn.Close()
End If
End If
End Sub

Public Function ExecuteQuery(ByVal strCmdTxt As String) As Boolean
Dim intRows As Integer
Try

If conn.State.Closed = ConnectionState.Closed Then
Connect()
End If

cmd = New SqlCommand
cmd.Connection = conn
cmd.CommandText = strCmdTxt
cmd.CommandType = CommandType.Text

If Not isTran Then
intRows = cmd.ExecuteNonQuery()
conn.close()
Else
cmd.Transaction = trans
intRows = cmd.ExecuteNonQuery()
End If

If intRows> 0 Then
ExecuteQuery = True
Else
ExecuteQuery = False
End If

Catch ex As Exception
Throw ex
End Try

End Function

Public Function ExecuteAndGetID(ByVal strCmdTxt As String) As String
Try
If conn.State.Closed = ConnectionState.Closed Then
Connect()
End If
strCmdTxt = strCmdTxt & " ; select scope_Identity();"
cmd = New SqlCommand
cmd.Connection = conn
cmd.CommandText = strCmdTxt
cmd.CommandType = CommandType.Text

If Not isTran Then
ExecuteAndGetID = CStr(cmd.ExecuteScalar())
conn.close()
Else
cmd.Transaction = trans
ExecuteAndGetID = CStr(cmd.ExecuteScalar())
End If

Catch ex As Exception
Throw ex
End Try
End Function

Public Function getDataset(ByVal strCmdTxt As String) As DataSet
Dim da As SqlDataAdapter = New SqlDataAdapter
Dim ds As DataSet = New DataSet

Try
If conn.State = ConnectionState.Closed Then

Connect()
End If

cmd = New SqlCommand
cmd.Connection = conn
cmd.CommandText = strCmdTxt
cmd.CommandType = CommandType.Text
If isTran Then
cmd.Transaction = trans
End If
da.SelectCommand = cmd
da.Fill(ds)

If Not isTran Then
conn.Close()
End If

Return ds

Catch ex As Exception
Throw ex

End Try

End Function

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

Public Function ReadDatabseConfig(ByVal filename As String) As Boolean

Dim result As Boolean
Dim strDataSource As String
Dim strInitialCatalog As String
Dim strUserID As String
Dim strPassword As String
Dim str
Try

Dim sr As New IO.StreamReader(filename)
Dim ln As String = sr.ReadLine
While IsNothing(ln) = False
If ln.StartsWith("DataSource") = True Then
strDataSource = getConfigValue(ln)
ElseIf ln.StartsWith("DBaseName") = True Then
strInitialCatalog = getConfigValue(ln)
ElseIf ln.StartsWith("UserID") Then
strUserID = getConfigValue(ln)
ElseIf ln.StartsWith("Password") = True Then
strPassword = getConfigValue(ln)

End If
ln = sr.ReadLine
End While
sr.Close()
connStr = "Data Source=" & strDataSource & ";" & "Initial Catalog=" & strInitialCatalog & _
";User ID=" & strUserID & ";Password=" & strPassword
result = True
ReadDatabseConfig = result
Catch ex As Exception
result = False
End Try

Return result
End Function

Public Function getConfigValue(ByVal line As String) As String
Dim values() As String = Split(line, "=")
Dim reply As String = values(1).Trim
'txtactionlog.text = WriteLine("Value = {0}", reply)
Return reply
End Function

End Class


Read more!