Skip to main content


Showing posts from January, 2012 learning: Building a Reusable Data Access Library

Namespace AutoLotConnectedLayer
Public Class InventoryDAL

' This member will be used by all methods.
Private sqlCn As SqlConnection = Nothing

Public Sub OpenConnection(ByVal connectionString As String)
sqlCn = New SqlConnection()
sqlCn.ConnectionString = connectionString
End Sub
Public Sub CloseConnection()
End Sub

`Adding the Insertion Logic

Public Sub InsertAuto(ByVal id As Integer, ByVal color As String, ByVal make As String,
ByVal petName As String)
' Format and execute SQL statement.
Dim sql As String = String.Format("Insert Into Inventory " &
"(CarID, Make, Color, PetName) " &
"Values'{0}', '{1}', '{2}', '{3}')",
id, make, color, petName)
' Execute using our connection.
Using cmd As New SqlCommand(sql, Me.sqlCn)
End Using
End Sub

End Class
End Namespace learning: A Complete Data Provider Factory Example

Step 1:

insert an App.config file to the current project and define an
empty <appSettings> element. Add a new key-named provider that maps to the namespace name of the
data provider you wish to obtain (System.Data.SqlClient). Also, define a connection string that
represents a connection to the xx database.

<?xml version="1.0" encoding="utf-8" ?>
<!-- Which provider? -->
<add key="provider" value="System.Data.SqlClient" />
<!-- Which connection string? -->
<add key="cnStr" value= "Data Source=(local)\SQLEXPRESS;
Initial Catalog=AutoLot;Integrated Security=True"/>

Step 2: Read the property file

Sub Main()
Console.WriteLine("***** Fun with Data Provider Factories *****" & vbLf)
' Get Connection string/provider from *.config.
Dim dp As String = ConfigurationManager.AppSettings("provi… Learning: Projects with Multiple Modules

Module MyModule
Public Sub GreetUser()
Console.WriteLine("Hello user...")
End Sub
End Module

Sub Main()
' Show banner.
' Call the GreetUser() method in MyModule.
End Sub

Another trait of the module type is that it cannot be directly created using the VB 2010 New keyword (any
attempt to do so will result in a compiler error). Therefore, the following code is illegal:
' Nope! Error, can't allocate modules!
Dim m as New Module1()
Rather, a module simply exposes shared members Learning: Enumeration Types

Enumerations are a handy programming construct that allow you to group name/value pairs. For example, assume you are creating a video game application that allows the player to select one of the three character categories(Wizard, Fight , or Thief). Rather than keeping track of simple numerical values to represent each possibility, you could build a custom enumeration using the Enum keyword.

' A VB enumeration type.
Enum CharacterType
Wizard = 100
Fighter = 200
Thief = 300
End Enum Learning: Structure Types

Typically, structures are best suited for modeling geometric and mathematical data and
are created in VB using the Structure keyword.

' A VB structure type.
Structure Point
' Structures can contain fields.
Public xPos As Integer, yPos As Integer
' Structures can contain parameterized constructors.
Public Sub New(x As Integer, y As Integer)
xPos = x
yPos = y
End Sub
' Structures may define methods.
Public Sub PrintPosition()
Console.WriteLine("({0}, {1})", xPos, yPos)
End Sub
End Structure Learning: CTS (Commond Type System)

CTS: Common Type System, In order that two language communicate smoothly CLR has CTS 

Example :
In VB you have "Integer" and in C++ you have "long" these datatypes are not compatible so the
interfacing between them is very complicated. In order to able that two different languages can communicate Microsoft introduced Common Type System. So "Integer" datatype in VB6 and
"int" datatype in C++ will convert it to System.int32 which is datatype of CTS. CLS which is
covered in the coming question is subset of CTS. Learning: first module

Here it is.

Boss would like to involve in a project instead of C# .net. I had experience of using VB 5,6 when I was in university. It is a nice tool for rapid programming. And now, you can creating new project using some OO features like Class, Inheritance, overload, override. For me, is no difference with C# .net. Just like Java, enjoy it.

Module Module1

    Sub Main()
        Dim c As New Calc()
        Dim ans As Integer = c.Add(10, 84)
        Console.WriteLine("just kidding : {0}", ans)
    End Sub

End Module

Public Class Calc
    Public Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
        Return x + y
    End Function

End Class

C# learning: SqlCommand

case 1: return one row of data,
sqlCommand cm = new ...

int qty = (int)cm.ExecuteScalar();

case 2: return multiple rows of data
SqlDataReader dataReader = cm.ExectueReader(CommandBehavior.CloseConnection);



Case 3: no return value(e.g. insert, update, delete operations)
cm.CommandText = ...
cm.CommandType = CommandType.StoreProcedure;
cm.Connect = cn;;
int n = cm.ExecuteNonQuery();

C# Learning: LINQ to SQL(First Example)

The first step in building a LINQ to SQL application is declaring the classes we’ll
use to represent your application data: our entities.

class Contact
public int ContactID { get; set; }
public string Name { get; set; }
public string City { get; set; }

The next thing we need to prepare before being able to use language-integrated
queries is a System.Data.Linq.DataContext object. The purpose of DataContext

is to translate requests for objects into SQL queries made against the database and
then assemble objects out of the results.

The full example below,

using System;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
static class HelloLinqToSql


static void Main()
string path =
DataContext db = new DataContext(path);

var contacts =
from contact in db.GetTable<Contact>()

C# Learning: LINQ 'Hello World'

using System;
using System.Linq;

static class HelloWorld
    static void Main()

    string[] words = { "hello", "wonderful", "linq", "beautiful", "world" };

     var shortWords = from word in words where word.Length <= 5
     select word;

       foreach (var word in shortWords)

Old School Version of above hello world,

using System;
static class HelloWorld
static void Main()
string[] words = new string[] {
"hello", "wonderful", "linq", "beautiful", "world" };
foreach (string word in words)
if (word.Length <= 5)

As the requirement could be more complicated , as below,

var groups =
from word in words
orderby word ascending
group word by word.Length into lengthGroups
orderby lengthGroups.Key descending
select new {Length=lengthGroups.Key, Words=lengthGroups};

C# Learning: Design goals and origins of LINQ

It’s important to know clearly what Microsoft set out to achieve with LINQ.LINQ ships with implementations that support querying against regular object collections, databases, entities, and XML sources.
Because LINQ supports rich extensibility, developers can also easily integrate it
with other data sources and providers.

Another essential feature of LINQ is that it is strongly typed. This means the

■ We get compile-time checking for all queries. Unlike SQL statements today,
where we typically only find out at runtime if something is wrong, this
means we can check during development that our code is correct. The
direct benefit is a reduction of the number of problems discovered late in
production. Most of the time, issues come from human factors. Strongly
typed queries allow us to detect early typos and other mistakes made by the
developer in charge of the keyboard.

■ We get IntelliSense within Visual Studio when writing LINQ queries. This
not only makes typing faster, but …

C# Learning: LINQ as a toolset

LINQ offers numerous possibilities. It will significantly change some aspects of how
you handle and manipulate data with your applications and components.

There are three major flavors of LINQ, or LINQ provider s : LINQ to Objects, LINQ to SQL, and LINQ to XML.


database access:
var contacts =
from customer in db.Customers
where customer.Name.StartsWith("A") && customer.Orders.Count > 0
orderby customer.Name
select new { customer.Name, customer.Phone };

xml query:
var xml =
new XElement("contacts",
from contact in contacts
select new XElement("contact",
new XAttribute("name", contact.Name),
new XAttribute("phone", contact.Phone)

The main idea is that by using LINQ you are able to gain access to any data
source by writing queries like the one shown in listing below, directly in the programming
language that you master and use every day.

from customer in customers
where customer.Name.StartsWith("A") &&a…

C# Learning: LINQ Concept

LINQ means Language-INtegrated Query.

Before LINQ, we had to juggle different languages like SQL, XML, or XPath
along with various technologies and APIs like ADO.NET or System.Xml in every
application written using general-purpose languages such as C# or VB.NET. It goes
without saying that this approach had several drawbacks.1 LINQ glues several
worlds together. It helps us avoid the bumps we would usually find on the road
from one world to another: using XML with objects, objects with relational data,
and relational data with XML are some of the tasks that LINQ will simplify.
One of the key aspects of LINQ is that it was designed to be used against any
type of object or data source and to provide a consistent programming model for
doing so.

The syntax and concepts are the same across all of its uses: Once you
learn how to use LINQ against an array or a collection, you also know most of the
concepts needed to take advantage of LINQ with a database or an XML file.
Another important asp…

C# Learning: the common problem with using Traditional db access classes

The problem with these classes is that they force the developer to work explicitly
with tables, records, and columns, while modern languages such as C# and
VB.NET use object-oriented paradigms.

Now that the object-oriented paradigm is the prevailing model in software
development, developers incur a large amount of overhead in mapping it to other
abstractions, specifically relational databases and XML. The result is that a lot of
time is spent on writing plumbing code.3 Removing this burden would increase
productivity in data-intensive programming, which LINQ helps us do.
But it’s not only about productivity! It also impacts quality. Writing tedious
and fragile plumbing code can lead to insidious defects in software or degraded

C# learning: Traditional Database Access

The frequent use of databases in applications requires that the .NET Framework
address the need for APIs that can access the data stored within. Of course, this
has been the case since the first appearance of .NET. The .NET Framework Class
Library (FCL) includes ADO.NET, which provides an API to access relational databases
and to represent relational data in memory. This API consists of classes such
as SqlConnection, SqlCommand, SqlReader, DataSet, and DataTable, to name a
few. You can find the exmaple as below.

privatestaticvoid ReadOrderData(string connectionString) { string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;"; using (SqlConnection connection = new SqlConnection( connectionString)) { SqlCommand command = new SqlCommand( queryString, connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); try { while (reader.Read()) {…

C# Learning: Enumerations and Structs

You can use the enum keyword to define enumerations as follows:

enum <typeName>

Next, you can declare variables of this new type as follows:
<typeName> <varName>;
You can assign values using the following:
<varName> = <typeName>.<value>;

you can also do enumeration like below,

enum <typeName> : <underlyingType>
<value1> = <actualVal1>,
<value3> = <value1>,
<valueN> = <actualValN>

The struct(short for structure) is just that. That is, structs are data structures are composed of several pieces of data, possibly of different types. They enable you to fefine your own types of variables based on this structure.

Type Conversion

This is always a hard topic for myself. So, it's a good opportunity here for myself to understand well about how this work in C# or .net world.

Instead of one-to-one mapping of bits from one variable into another, you need to use type conversion on the data. Type conversion takes two forms:
Implicit conversion: Conversion from type A to type B is possible in all circumstances, and the rules for performing the conversion are simple enough for you to trust in the compiler. Implicit conversion requires no work on your part and no additional code.

Explicit conversion: Conversion from type A to type B is possible only in certain circumstances or where the rules for conversion are complicated enough to merit additional processing of some kind.

Implicit conversions
Consider the code shown here: var1 =var2; This assignment may involve an implicit conversion if the type of var2 can be implicitly converted into the type of var1, but it could just as easily involve two variables with the same…


C# enables you to label lines of code and them jump straight to them using the goto statement. This has its benefits and problems. The main benefit is that it's a simple way to control what code is executed when. The main problem is that excessive use of this technique can result in spaghetti code that is difficult to understand.


The bool type can hold one of only two values: true or false. This type is often used to record the result of some operation, so that you can act on this result. In particular, bool types are used to store the result of a comparison.

Four operators:
! (Logical NOT):
e.g. var1 = !var2.  var1 is assigned the value true if var2 is false

&(logical AND)
e.g. var1 = var2 & var3 . var1 is assigned the value true if var2 and var3 are both true, or false otherwise.

! (Logical OR)
e.g. var = var2 | var3. var1 is assigned the value true if either var2 or var3(or both) is true, or false otherwise.

^ (exclusive OR)
e.g. var1 = var2 ^ var3 : var1 is assigned the value true if either var2 or var3, but not both, is ture or false otherwise.

Two conditional Boolean operators,
&& (also call Logical AND) ,
var1 = var2 && var3;

 || (Logical OR)
var1 = var2 || var3;

The result of these operators is exactly the same as & and |, but there is an important difference in the way this…

C# Namespaces

C# code, by default, is contained in the global namespace. This means that items contained in this code are accessible from other code in the global namespace simply by referring to them by name.

A qualified name is one that contains all of its hierarchical information, which basically means that if you have code in one namespaces that needs to use a name defined in a differnet namespace, you much include a reference to this namespace. Qualified names period characters(.) between namespace levels, as shown here:

namespace LevelOne
// code in LevelOne namespace
// name "NameOne" defined
// code in global namespace

// code in LevelOne namespace
namespace LevelTwo
// code in LevelOne.LevelTwo namespace
// name "NameTwo" defined
// code in global namespace

After namespaces are set up, you can use the using statement to simplify access to the names they contain. In effect,  the using statement says, "OK, I'll be needing names fro this namespace, so …

C# Naming Conventions

Variable names are something you will use a lot, so it's worth spending a bit of time learning the sort of names you should use. Developers have realized that it is far better to name variables appropriately for their purpose.

Currently, two naming conventions are used in the .NET Framework namespaces: PascalCase and camelCase. The case used in the names indicated their usage. They both apply to names that comprise multiple words and they both specify that each word in a name should be in lowercase except for its first letter, which should be uppercase. For camelCase terms, there is an additional rule: The first world should start with a lowercase letter.

The following are camelCase variable names:

These are PascalCase:

For your simple variables, stick to camelCase. Use PacalCase fo certain more advanced naming, which is the Microsoft recommendation. Finally, note that many past name systems involved frequent use of of the unders…

VS and VCE

VS(Visual Studio) and VCE(Visual C# Express) are development tools for all of your C# programming.

When you use VS or VCE to develop applications, you do so by creating solutions. A solution, in VS and VCE terms, is more than just an application. Solutions contain projects, which might be Windows Forms projects, Web Form projects, and so on.  Because solutions can contain multiple projects, you can group together related code in one place, even if it will eventually compile to multiple assemblies in various places on your hard disk.

This is very useful because it enables you to work on shared code(which might be placed in the GA) at the same time as applications that uses this code. Debugging code is a lot easier when only one development environment is used, because you can step through instructions in multiple code modules.

What is C#?

Seriously,  C# is one of the languages you can use to create applications that will run in the .NET CLR. At times, c# code is slightly more verbose than C++. this is a consequence of C# being a type-safe language, which means that once some data has been assigned to a type, it cannot subsequently transform itself into another unrelated type. Consequently, strict rules must be adhered to when converting between types, which means you will often need to write more code to carry out the same task in C# than you might write in C++;

You can use C# to write Windows applications, Web Applications ,Web Service and other stuff.

Writing Applications Using the .NET Framework

 When you compile code that uses the .NET Framework library, you don't immediately create operating-system-specific native code. Instead, you compile your code into Common Intermediate Language(CIL) code. This code isn't specific to any operating system and isn't specific to C#.

Obviously, more work is necessary to execute an application. That is the job of a just-in-time(JIT) compiler, which compiles CIL into native code that is specific to the OS and machine architecture being targeted. Only at this point can the OS execute the applications.

When you compile an application, the CIL code created is stored in an assembly. Assemblies include both executable application files that you can run directly from Windows without the need for any other programs and libraries(which have a .dll extension) for use by other applications.

In additoin to containing CIL, assemblies also include meta information(that is, information about the information contained in t…

Be happy -Always

the jquery ajax success and error usage

Although jQuery helped to simplify the javascripts alot, it's still ugly and hard to maintain in the future. Let me know if you have any other non-ugly solution.

var myurl =  "../json/addNotes";

var varUserName = '${userName}';

  $.ajax({url:myurl,dataType: 'json', data:'comments='+comments+'&userName='+varUserName,
success: function(){
alert("Comments saved.");

  error: function(){
alert("Saving was unsuccessful, please try again.");