Recent Posts

Sunday, August 24, 2008

Different Ways of Loading data in combobox in .Net Applicatons

First go to following link
Secure connection and easy transaction handling in .Net

to understand the logic for the connection
and to get the idea of what objDB means.

Just create a objDB class from the above link provided and use the following code

The follwoing are the two ways of loading the data in the combobox or drop down list in
.Net Application:



Private Sub LoadCats()

Dim objdb As New clsObjDB
Dim ds As New DataSet
Dim str As String
cboCats.Items.Clear()
str = "Select * from cat order by catID desc"

ds = objdb.getDataset(str)

Dim dt As DataTable
dt = ds.Tables(0)
For Each row As DataRow In dt.Rows

cboCats.ValueMember = row("CatID")
cboCats.Items.Add(row("CatName"))

Next

End Sub


In the above function I have used Data row to go through the each every record
of the datbase

but in the following example i have directly specified the data source to the
combo box control and determined which value to display.


Private Sub LoadCats1()

Dim objdb As New clsObjDB
Dim ds As New DataSet
Dim str As String
cboCats.Items.Clear()

str = "Select * from cat order by catID desc"

ds = objdb.getDataset(str)

cboCats.DataSource = ds.Tables(0)
cboCats.DisplayMember = "CatName"

End Sub


Read more!

How to insert record in SQL server database from VB.Net?

First go to following link
Secure connection and easy transaction handling in .Net

to understand the logic for the connection
and to get the idea of what objDB means.

Just create a objDB class from the above link provided and use the following code
to insert a record in the table named dog.

Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSingle.Click
Dim str As String
Dim objDB As clsObjDB

Try
objDB = New clsObjDB
str = "insert into Dog (DogName,Active)values('Lika',1) "


objDB.ExecuteQuery(str)
objDB = Nothing

messagebox.Show("Successfully Inserted Single row in dog!!" & vbCrLf)

Catch ex As Exception
Messagebox.show(ex.ToString())

objDB = Nothing
End Try

End Sub

In the above function I have just created a new instance of clsObjDB andpassed the sql query in the ExecuteQuery function and that's it, it does the rest of the work.


Read more!

Thursday, August 21, 2008

How to handle and log Asp.Net Error in Event Viewer ?

You can just use the following to descently handle you ASP.net error messages and log the error in the event viewer .

Also if you want to add the email function in the function.

the following code is the simplest way to handle error messages in ASP.net:


using System;
using System.Diagnostics;


void Page_Error(Object sender, EventArgs args)
{
Response.Write("Error:\n");
Exception e = Server.GetLastError();

EventLog.WriteEntry("Test Web",
"MESSAGE: " + e.Message +
"\nSOURCE: " + e.Source +
"\nFORM: " + Request.Form.ToString() +
"\nQUERYSTRING: " + Request.QueryString.ToString() +
"\nTARGETSITE: " + e.TargetSite +
"\nSTACKTRACE: " + e.StackTrace,
EventLogEntryType.Error);

Trace.Write("Message", e.Message);
Trace.Write("Source", e.Source);
Trace.Write("Stack Trace", e.StackTrace);
Response.Write("Sorry, an error was encountered.");
Context.ClearError();
}


Read more!

Wednesday, August 20, 2008

VB Split() function in C# (Stupid mistake made while converting! Solved now)

I was trying to convert the vb Split() function to C#
and while going through google it seemed pretty much easy but my function is not working or giving me errors.

I went through it more than 30 mins and later found out my mistake that I will
explain in the end of this post.

Ok here is the vb code that uses the split function to split a string line.

Dim strLine As String
strLine = "DataSource = GetDatabase"
lblMsg.Text = getTextLine(strLine)


Public Function getTextLine(ByVal strline As String) As String

Dim spChar As String
spChar = "="
Dim values() As String = Split(line, spChar)
Dim reply As String = values(1).Trim

Return reply
End Function

and the exact replica of this code in C# is :

string strLine;
strLine = "DataSource = GetDatabase";
lblMsg.Text = getTextLine(strLine);

public string getTextLine(string line)
{
char spChar = '=';


string[] arr = line.Split(spChar);
string reply = arr[1];
return reply;


}

Now where i spent my 30 mins making following mistakes:

1. The big mistake what i didn't figure out for long was i did

char spChar= "=";

2. And so I ended up declaring spChar as string. Then the problem worsened.


Read more!

Blog for Programmers (Prateek Regmi): How to get data from the Database using dataset in .Net

Blog for Programmers (Prateek Regmi): How to get data from the Database using dataset in .Net


Read more!

Monday, August 18, 2008

How to get data from the Database using dataset in .Net

First go to following link
Secure connection and easy transaction handling in .Net

to understand the logic for the connection
and to get the idea of what objDB.getDataSet means.

Then use the following function to get the values from the table named Books:


Private Function GetBooks() As Boolean
Dim strSql As String
Dim ds As DataSet

dim objBook as clsBook()

Try
strSql = "SELECT * from Books"

ds = objDB.getDataset(strSql)
If ds.Tables(0).Rows.Count > 0 Then
For Each row As DataRow In ds.Tables(0).Rows
objBook = new clsBook()

objBook.BookID = row("BookingID")
ObjBook.BookName = row ("BookName")
'etc

Next
GetBooks=true
Else

GetBooks = False
End If
Catch ex As Exception

Throw ex
End Try
End Function


Read more!

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!