Friday, June 29, 2012

Google Launches Nexus 7 Tablet


With the launch of Google's Nexus 7, the $199 tablet market got even more crowded. So, is it the best?





The Kindle Fire, Nexus 7, and Nook Tablet all retail for $199.

Amazon opened a lot of eyes when it introduced the Kindle Fire last year at $199. Many people expected it to come out at $249, but Amazon surprised everybody with $199. Now Google's done the same with its Asus-made Nexus 7, which, on paper anyway, offers the best specs for a 7-inch tablet at its price point, besting its closest competitors, the Kindle Fire and the 8GB Nook Tablet (you could also include the Samsung Tab 2 7.0 in this group, but it starts at $250).

Thursday, June 28, 2012

Virtual Keyword In C#

Virtual Keyword in C#




  • When a derived class want to override  the base class member(s) then base class member(s)  need to marked as virtual members.

  • A function marked as virtual can be overridden by subclasses wishing to provide a specialized implementation.

  • Methods, properties, indexers, and events can all be declared as virtual.

  • In the derived class those members will be marked by override  keyword.


Wednesday, June 27, 2012

New Features Of .NET 4.0

Introduction


This article contains some of the new features of ASP.NET 4.0 and Visual Studio 2010 IDE.

Improvements in C# 4.0


C# in .NET Framework 4.0 has some more things to offer. These are:

  • Dynamic lookup

  • Named

  • Optional parameters


Dynamic Lookup


There is a new static type named dynamic. We can use it as object of any type. If there is any error on its usage, we would get it on runtime only. For example:
dynamic integerValue = 1;
dynamic stringValue = " a string";
dynamic Result = integerValue + stringValue;

DataSet Vs DataReader


Dataset Vs DataReader



DataReader

1. DataReader is like a forward only recordset.
2. It fetches one row at a time so very less network cost compare to DataSet(Fethces all the rows at a  time).
3. DataReader is readonly so we can't do any transaction on them.
4. DataReader will be the best choice where we need to show the data to the user which requires no transaction. 
5. As DataReader is forward only so we can't fetch data randomly. .NET Data Providers optimizes the  DataReader to handle huge amount of data.

DataSet


1. DataSet is an in memory representation of a collection of Database objects including tables of a          relational database schemas.
2. DataSet is always a bulky object that requires a lot of memory space compared to DataReader. We can say that the DataSet is a small database because it stores the schema and data in the application memory area.
3. DataSet fetches all data from the datasource at a time to its memory area.
4. We can traverse through the object to get the required data like querying database.


Thursday, June 21, 2012

Role-Based Security with Forms Authentication


Introduction


Forms Authentication in ASP.NET can be a powerful feature. With very little code and effort, you can have a simple authentication system that is platform-agnostic. If your needs are more complex, however, and require more efficient controls over assets, you need the flexibility of groups. Windows Authentication gives you this flexibility, but it is not compatible with anything but Internet Explorer since it uses NTLM, Microsoft's proprietary authentication system. Now you must choose how to manage your assets: provide multiple login pages / areas and force users to register for each, or assign groups to users and limit access to pages / areas to particular groups. Obviously, you must choose the latter.

JQuery


JQuery is a new kind of JavaScript Library.jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.


jQuery is free, open source software, dual-licensed under the MIT License or the GNU General Public License. jQuery's syntax is designed to make it easier to navigate a document, select DOM elements, create animations, handle events, and develop Ajax applications. jQuery also provides capabilities for developers to create plug-ins on top of the JavaScript library. This enables developers to create abstractions for low-level interaction and animation, advanced effects and high-level, theme-able widgets. The modular approach to the jQuery library allows the creation of powerful dynamic web pages and web applications.

SQL SERVER - ColumnStore Index - Batch Mode vs Row Mode

Ratan Tata Retirement

When long-serving employees retire, companies present them with mementos or gold watches as a form of gratitude and in recognition of services rendered.

But what should a company do when its boss, or sort-of owner, is about to hang up his boots?

Tata Consultancy Services (TCS), India’s largest infotech company, is facing just such a question. It has probably answered it the wrong way.

It’s superboss, Ratan Tata, is about to walk off into the sunset in the next six months, and TCS has decided that Rs 5 crore is a fitting reward for his “long-standing contribution to the sustained growth and success” of the company, according to a report in Business Standard.

Is the company honouring or diminishing Ratan Tata, India’s tallest businessman by far, by putting a price of Rs 5 crore on his life-long efforts to put TCS on the global map? Getty Images

Is the company honouring or diminishing Ratan Tata, India’s tallest businessman by far, by putting a price of Rs 5 crore on his life-long efforts to put TCS on the global map? This, when the formal compensation Tata will receive in 2011-12 will exceed Rs 8 crore.

There’s no question Ratan Tata, who retires this December when he turns 75 as per group policy, has rendered invaluable services to every part of the Tata group and to business, in general, both in India and abroad. If Indian business has a reputation abroad, it owes much to Ratan Tata and his group.

TCS, as the crown jewel in the Tata group, has taken in the lead in recognising Tata’s contribution to its own growth and that of the group.

But there are several reasons to think it is not doing the right thing by trying to put a monetary value to Tata’s contribution – even though this may not be the intention behind the TCS gift.

First, listed companies should not be singling out individual directors for special compensation when there are already board and AGM resolutions that specify what Tata should be paid for his work.

Second, when an exception is supposed to be made to this rule, it is the minority shareholders who should vote on it – not all shareholders. As owner of the vast majority of TCS shares (nearly 74 percent), any such resolution is going to pass, especially since Tata Sons, the main holder of TCS shares, is also run by Ratan Tata. The TCS management is thus putting Tata in the embarrassing position of being the promoter who votes on his own retirement bonus.

Third, since it is fairly certain that almost all Tata companies will also be bidding farewell to their larger-than-life promoter, they could all fall into the TCS trap of saying it not with roses, but cash. The TCS example, if followed by other Tata group companies, will be no different from the political spectacles we see where leaders are weighed in gold or garlanded with cash for services rendered.

We think a Mayawati being received with a garland of Rs 1,000 notes is gross, but a Tata being gifted a Rs 5 crore cheque is somehow sane and sensible. The difference is only in the optics: one looks gross, and the other doesn’t because it happens out of public view.

The point is simple: if Ratan Tata’s services have been priceless and invaluable (which they demonstrably are), why try and show gratitude by trying to do precisely the opposite – by indicating a price and putting a monetary value on what is inestimable?

The Tata Group should not bring down Ratan Tata to the level of our crass political class. They should say it with roses.

Firstpost Tech Infographic: Facebook releases world’s ‘most social’ cities

We’re all addicted to Facebook. We can’t  stop checking in, F-liking, posting pictures, no matter where we are, thanks to our smartphones. Facebook has compiled a list of check-ins made on the site from 25 cities worldwide to determine the world’s most social landmarks. And  they’ve released some very cool info graphics along with the data.

According to Facebook’s data,  the Number 1 ranked landmarks across the 25 cities include:

7 sports stadiums and arenas
6 public areas such squares, parks and gardens
2 amusement parks
2 concert areas
2 shopping-related: shopping centers and malls

It seems shopping malls are the popular places for people to login worldwide. Delhi’s Hard Rock Cafe also finds a mention in the list of the most the popular places for logging in. Here’s the complete infographic. Sadly no special infographic for just Indian cities. That’s sad since India has the second highest number of Facebook users in the world, after the US.

The following infographic looks at the most social landmark in some cities across the world

Windows 8 for Android mobile

New York: As it struggles to gain a foothold against the iPhone and Android phones, Microsoft Corp is planning to issue a dramatic update to its phone software, one that won’t be available to current Windows Phones.

The new software, Windows Phone 8, will be available on new phones this fall, Microsoft said Wednesday at a presentation in San Francisco. The software will bring Windows phones closer to PCs and tablets running the company’s upcoming Windows 8, which is also scheduled to launch later this year.

With its planned software updates —and the Surface tablet computer it introduced earlier this week— Microsoft is taking dramatic steps to ensure that it plays a major role in the increasingly important mobile market.

But the company is playing catch-up in an arena dominated by Apple and Google. Microsoft launched Windows Phone 7 in 2010, making a clean break with its previous phone software, which had become outdated. Nokia Corp., until recently the world’s biggest maker of phones, has pledged to use it for all its smartphones, and launched its first Windows Phone in the US earlier this year.

[caption id="" align="alignright" width="250"]Image representing iPhone as depicted in Crunc... Image via CrunchBase[/caption]

The new software, Windows Phone 8, will be available on new phones this fall. Reuters Sales have been anemic, however. IDC estimated that 2.2 percent of the smartphones shipped worldwide in the first quarter of this year ran Microsoft’s software, compared to 23 percent for Apple and 59 percent for Android. Still, US wireless carriers support Windows Phone, seeing it as a valuable counterweight to the clout of Apple Inc’s iPhone and phones running Google Inc’s Android software.

Windows Phone is making progress in one respect. Hit games “Words With Friends” and “Draw Something” will be among the apps available for Windows 8. There are 100,000 applications available for Windows phones today, Microsoft said. That’s far less than the

number of apps available for iPhones and Android phones.

Windows Phone 8 will accept expansion memory cards, like Android phones do. It will also work on processors with more than one computing “core,” which are common in high-end smartphones. More cores boost computing power and can cut power consumption.

The new software will also work with near-field communications chips, allowing phones to be used in place of credit cards at some payment terminals. At the conference, Microsoft’s head of phone software, Joe Belfiore, demonstrated how NFC can be used to link two phones so their owners can play a Scrabble-like game. Tapping the phones together can engage NFC, and prompt the devices to establish a link over Wi-Fi.Some recent Android phones come with NFC capabilities, but they’re missing from the iPhone.

Windows Phone 8 will share the operating system “kernel,” or most basic functions, with Windows 8 RT, which will run on tablets and computers. That means manufacturers will have an easier time making hardware that can use either system. Developers will have an easier time moving applications from one platform to the other, Microsoft said.

Changing its phone software at such a basic level means that it will be difficult to install on existing Windows phones

 

Tuesday, June 19, 2012

Implementing a Data Access Layer in C#

A Data Access Layer is an important layer in the architecture of any software.  This layer is responsible for communicating with the underlying database.  Making this layer provider independent can ensure multi database support with ease.  This article discusses implementation of a provider independent Data Access Layer in C#.

ADO.NET Data Providers

The following are the major ADO.NET data providers.

  • SQL Server Data Provider

  • Oracle Data Provider

  • Odbc Data Provider

  • OleDB Data Provider

Saturday, June 16, 2012

Difference between Finalize() and Dispose()

 Some quick points on Finalize() and Dispose() in C#:



1. Finalize() is the C# equivalent of destructor   ~Object() syntax in C#. In VB.Net you implement the Finalize() by overriding it. But, in C# the compiler translates the destructor to a Finalize() method.

2. Finalize() can NOT be overridden or called in C#.

3. Since, Finalize() is called by the Garbage Collector, it is non-deterministic.

4. Dispose() has to be implemented in classes implementing IDispose interface.

5. Its the right place for freeing-up unmanaged resources like file, handles, and connections etc.

6. Dispose() method is called explicitely in the code itself.

7. Dispose() method is automatically called (for objects which implement IDispose), when used in a "using" statement.

Difference between Finalize and Dispose Method in .NET

C# Provides two special methods that are used to release the instance of a class from memory, Finalize() and Dispose().

Finalize():


The Finalize destructor is a special method that is called from the class to which it belongs or from the derived class. The Finalize() destructor is called after the last reference to an object is released from the memory. The .Net Framework automatically runs the Finalize() destructor to destroy objects in the memory. However, it is important to remember that the Finalize() destructor may not execute immediately when an object loses scope. It is called by CLR using reference-tracing garbage collection, the CLR periodically check for objects that are not used by the application. When such an object is found, the Finalize() destructor is called automatically and the garbage collector of the CLR release the object from the memory.Dispose():


The Dispose() method is called to release a resource, such as database connection, as soon as the object using such a resource is no longer in use. Unlike the Finalize() destructor, the Dispose() method is not called automatically and you must explicitly call it from a client application when an object is no longer needed. The IDisposable interface contains the Dispose() method. Therefore , to call the Dispose() method, the class must implement the IDisposable interface.

Friday, June 15, 2012

Database Concept

What is RDBMS?
Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained across and among the data and tables. In a relational database, relationships between data items are expressed by means of tables. Interdependencies among these tables are expressed by data values rather than by pointers. This allows a high degree of data independence. An RDBMS has the capability to recombine the data items from different files, providing powerful tools for data usage.


What is normalization?
Database normalization is a data design and organization process applied to data structures based on rules that help build relational databases. In relational database design, the process of organizing data to minimize redundancy. Normalization usually involves dividing a database into two or more tables and defining relationships between the tables. The objective is to isolate data so that additions, deletions, and modifications of a field can be made in just one table and then propagated through the rest of the database via the defined relationships.

Thursday, June 14, 2012

Handler Tutorial

Handler Concept in ASP.NET


Some ASP.NET files are dynamically generated. They are generated with C# code or disk resources. These files do not require web forms. Instead, an ASHX generic handler is ideal. It can dynamically return an image from a query string, write XML, or any other data.


HTTP handlers are the .NET components that implement the System.Web.IHttpHandler interface. Any class that implements the IHttpHandler interface can act as a target for the incoming HTTP requests. HTTP handlers are somewhat similar to ISAPI extensions. One difference between HTTP handlers and ISAPI extensions is that HTTP handlers can be called directly by using their file name in the URL, similar to ISAPI extensions.

Extension Method In LINQ

Extension Methods


Extension methods are one important piece of the query architecture. Extension methods combine the flexibility of "duck typing" made popular in dynamic languages with the performance and compile-time validation of statically-typed languages. With extension methods third parties may augment the public contract of a type with new methods while still allowing individual type authors to provide their own specialized implementation of those methods.


Extension methods are defined in static classes as static methods, but are marked with the [System.Runtime.CompilerServices.Extension] attribute in CLR metadata. Languages are encouraged to provide a direct syntax for extension methods. In C#, extension methods are indicated by the this modifier which must be applied to the first parameter of the extension method.

Javascript code to check/uncheck all checkboxes from header check box

<script type="text/javascript">
var TotalChkBx;
var Counter;
window.onload = function()
{
TotalChkBx = parseInt('<%= this.GridView3.Rows.Count %>');
Counter = 0;
}
function SelectAll(CheckBox)
{
var TargetBaseControl = document.getElementById('<%= this.GridView3.ClientID %>');
var TargetChildControl = "chkselect";
var Inputs = TargetBaseControl.getElementsByTagName("input");
for(var n = 0; n < Inputs.length; ++n)
if(Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(TargetChildControl,0) >= 0)
Inputs[n].checked = CheckBox.checked;
Counter = CheckBox.checked ? TotalChkBx : 0;
}
function ChildClick(CheckBox, HCheckBox)
{
var HeaderCheckBox = document.getElementById(HCheckBox);
if(CheckBox.checked && Counter < TotalChkBx)
Counter++;
else if(Counter > 0)
Counter--;
if(Counter < TotalChkBx)
HeaderCheckBox.checked = false;
else if(Counter == TotalChkBx)
HeaderCheckBox.checked = true;
}
</script>
onclick="javascript:SelectAll(this);"

GridView Events Summary

Introduction


In this article i have tried to summarize all the  events of grid view which i came across.



What is a GridView?


The DataGrid or GridView control displays data in tabular form, and it also supports selecting, sorting, paging, and editing the data inside the grid itself. The DataGrid or GridView generates a BoundColumn for each field in the data source (AutoGenerateColumns=true). By directly assigning the data source to the GridView, the data can be rendered in separate columns, in the order it occurs in the data source. By default, the field names appear in the grid's column headers, and values are rendered in text labels. A default format is applied to non-string values and it can be changed.



GridView Fields











Column Name
Description


BoundColumn
To control the order and rendering of columns.

HyperLinkColumn
Presents the bound data in HyperLink controls

ButtonColumn
Bubbles a user command from within a row to the grid event handler

TemplateColumn
Controls which controls are rendered in the column

CommandField
Displays Edit, Update, and Cancel links in response to changes in the DataGrid control's EditItemIndex property.



Wednesday, June 13, 2012

OOPs Concept

Class




  • A class is a user defined data type that behaves like a built in data type.

  • A class acts as a blueprint for an object.

  • A class contains all the attributes and behavior of an object.

  • A class is a wrapper/container of an object.

  • A class doesn’t occupy apace in memory.


Object


Instance of Class is called object. An object is created in memory using keyword “new”.




  • An object is an instance of a class.

  • It is a run time entity.

  • Anything in this real world can be termed as object.

  • An object possesses attributes and behavior.

  • An object occupies space in memory and utilizes CPU processing.

Object Serialization in the .NET Framework

Introduction


Serialization can be defined as the process of storing the state of an object instance to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, is converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created.


When implementing a serialization mechanism in an object-oriented environment, you have to make a number of tradeoffs between ease of use and flexibility. The process can be automated to a large extent, provided you are given sufficient control over the process. For example, situations may arise where simple binary serialization is not sufficient, or there might be a specific reason to decide which fields in a class need to be serialized. The following sections examine the robust serialization mechanism provided with the .NET Framework and highlight a number of important features that allow you to customize the process to meet your needs.

JSON – Serialization and Deserialization

What is JSON?


JSON is another format of expressing data, just like XML. But, JSON is very simpler than XML, and tiny than XML. So, it is becoming popular in the web world to choose the JSON notation over XML since JSON notation are usually shorter, and less data to be transmitted if at all they were to be.


Okay, I understood a little about JSON. Give me an example!


 I know an example will get your understanding much better. Below is a simple example of how an object can be expressed in JSON notation. Let’s take a classical example of a Person object, and expressing myself as an object.


{

   “firstName”: “Rakki”,

   “lastName”:”Muthukumar”,

   “department”:”Microsoft PSS”,

   “address”: {

      “addressline1”: “Microsoft India GTSC”,

      “addressline2”: “PSS - DSI”,

      “city”: “Bangalore”,

      “state”: “Karnataka”,

      “country”: “India”,

      “pin”: 560028

   }

   “technologies”: [“IIS”, “ASP.NET”,“JavaScript”,“AJAX”]

}

In the above example, address is another object inside my Person, and technologies is an array or strings.

 

Using JSON with ASP.NET 3.5

Introduction


Almost any application that you write will involve exchanging data from a client application to the server. This process involves selecting a data format and exchange protocol that will be required to enable this communication. When it comes to selecting these data formats, you have a variety of open standards that you can consider and the ideal choice depends on the requirements of the application.


For example, if you use SOAP based Web services, you format the data in an XML payload that is wrapped within a SOAP envelope. Although XML works well for many application scenarios, its inherent chatty nature makes it less than ideal for certain scenarios. For example, in an AJAX style Web application, you make asynchronous lightweight out-of-band calls to the server side to get the required data without even refreshing the browser. In this scenario, you need a lightweight, open, text-based platform independent data exchange format for transferring data back and forth between the client and server. That’s exactly what the JSON (Java Script Object Notation) standard provides.

Tuesday, June 12, 2012

The Entity Framework and ASP.NET – Getting Started Part 8

Using Dynamic Data Functionality to Format and Validate Data


In the previous tutorial you implemented stored procedures. This tutorial will show you how Dynamic Data functionality can provide the following benefits:




  • Fields are automatically formatted for display based on their data type.

  • Fields are automatically validated based on their data type.

  • You can add metadata to the data model to customize formatting and validation behavior. When you do this, you can add the formatting and validation rules in just one place, and they're automatically applied everywhere you access the fields using Dynamic Data controls.


To see how this works, you'll change the controls you use to display and edit fields in the existing Students.aspx page, and you'll add formatting and validation metadata to the name and date fields of the Student entity type.

The Entity Framework and ASP.NET – Getting Started Part 7

Using Stored Procedures


In the previous tutorial you implemented a table-per-hierarchy inheritance pattern. This tutorial will show you how to use stored procedures to gain more control over database access.


The Entity Framework lets you specify that it should use stored procedures for database access. For any entity type, you can specify a stored procedure to use for creating, updating, or deleting entities of that type. Then in the data model you can add references to stored procedures that you can use to perform tasks such as retrieving sets of entities.

The Entity Framework and ASP.NET – Getting Started Part 6

Implementing Table-per-Hierarchy Inheritance


In the previous tutorial you worked with related data by adding and deleting relationships and by adding a new entity that had a relationship to an existing entity. This tutorial will show you how to implement inheritance in the data model.


In object-oriented programming, you can use inheritance to make it easier to work with related classes. For example, you could create Instructor and Student classes that derive from a Person base class. You can create the same kinds of inheritance structures among entities in the Entity Framework.

The Entity Framework and ASP.NET – Getting Started Part 5

Working with Related Data, Continued


In the previous tutorial you began to use the EntityDataSource control to work with related data. You displayed multiple levels of hierarchy and edited data in navigation properties. In this tutorial you'll continue to work with related data by adding and deleting relationships and by adding a new entity that has a relationship to an existing entity.


You'll create a page that adds courses that are assigned to departments. The departments already exist, and when you create a new course, at the same time you'll establish a relationship between it and an existing department.


Image02

The Entity Framework and ASP.NET – Getting Started Part 4

Working with Related Data


In the previous tutorial you used the EntityDataSource control to filter, sort, and group data. In this tutorial you'll display and update related data.


You'll create the Instructors page that shows a list of instructors. When you select an instructor, you see a list of courses taught by that instructor. When you select a course, you see details for the course and a list of students enrolled in the course. You can edit the instructor name, hire date, and office assignment. The office assignment is a separate entity set that you access through a navigation property.


You can link master data to detail data in markup or in code. In this part of the tutorial, you'll use both methods.

The Entity Framework and ASP.NET – Getting Started Part 3

Filtering, Ordering, and Grouping Data


In the previous tutorial you used the EntityDataSource control to display and edit data. In this tutorial you'll filter, order, and group data. When you do this by setting properties of the EntityDataSource control, the syntax is different from other data source controls. As you'll see, however, you can use the QueryExtender control to minimize these differences.


You'll change the Students.aspx page to filter for students, sort by name, and search on name. You'll also change the Courses.aspx page to display courses for the selected department and search for courses by name. Finally, you'll add student statistics to the About.aspx page.

The Entity Framework and ASP.NET – Getting Started Part 2

The EntityDataSource Control


In the previous tutorial you created a web site, a database, and a data model. In this tutorial you work with the EntityDataSource control that ASP.NET provides in order to make it easy to work with an Entity Framework data model. You'll create a GridView control for displaying and editing student data, a DetailsView control for adding new students, and a DropDownList control for selecting a department (which you'll use later for displaying associated courses).


Image20


Image09


Image18

The Entity Framework and ASP.NET – Getting Started Part 1


Introduction





The Contoso University sample web application demonstrates how to create ASP.NET Web Forms applications using the Entity Framework. The sample application is a website for a fictional Contoso University. It includes functionality such as student admission, course creation, and instructor assignments.

This tutorial series uses the ASP.NET Web Forms model and assumes you know how to work with ASP.NET Web Forms in Visual Studio. If you prefer to work with the ASP.NET MVC framework, see the Creating Model Classes with the Entity Framework tutorial or the Getting Started with the Entity Framework using ASP.NET MVC tutorial series.


Overview


The application you’ll be building in these tutorials is a simple university website.


Image03


Users can view and update student, course, and instructor information. A few of the screens you'll create are shown below.

2 Tier Vs 3 Tier Architecture

Abstract


This article i will describe you to migrate your application from 2-Tier architecture to the most advance Data Access methodology available in .Net 4.0.Please keep watching all migration articles one by one. If it really helps you out then please don't forget to put your feedback and comments.


2 Tier Architecture

If you are writing all the data access logic inside your code behind, I guess your code looks like this.




  • While Inserting Data into Database:
    SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["EmployeeConString"].ConnectionString);


SqlCommand sqlCommand = new SqlCommand(string.Format("INSERT INTO Department (DepartmentId, Name, Budget, StartDate) VALUES ({0}, '{1}', {2}, '{3}')", txtDeptId.Text, txtDeptName.Text, txtBudget.Text, txtStartDate.Text), sqlConnection);

Components of DOT.NET platform


Introduction


The basic components of .NET platform (framework) are:










                  .Net Applications

        (Win Forms,Web Applications,Web Services)


         Data(ADO.Net) and XML Library

          FrameWork Class Library(FCL)      

        (IO,Streams,Sockets,Security,Reflection,UI)


       Common Language Runtime(CLR)

             (Debugger,Type Checker,JITer,GC)


                    Operating System

(Windows,Linux,UNIX,Macintosh,etc.,)




Concept of Assembly in DOT.NET

What is a .Net Assembly?

The .NET assembly is the standard for components developed with the Microsoft.NET. Dot NET assemblies may or may not be executable, i.e., they might exist as the executable (.exe) file or dynamic link library (DLL) file. All the .NET assemblies contain the definition of types, versioning information for the type, meta-data, and manifest. The designers of .NET have worked a lot on the component (assembly) resolution.


There are two kind of assemblies in .NET;





  • Private


  • Shared/Public

Abstract Vs Interface

Introduction


In this article along with the demo project I will discuss Interfaces versus Abstract classes. The concept of Abstract classes and Interfaces is a bit confusing for beginners of Object Oriented programming. Therefore, I am trying to discuss the theoretical aspects of both the concepts and compare their usage. And finally I will demonstrate how to use them with C#.



Background


An Abstract class without any implementation just looks like an Interface; however there are lot of differences than similarities between an Abstract class and an Interface. Let's explain both concepts and compare their similarities and differences.



What is an Abstract Class?


An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

Why do we need Constructor for abstract class?

Yes we can have constructor in Abstract class (though we can’t still create object of abstract class).
Because :- this way you can instantiate the data in abstract class.
And inherited classes can call the base constructor.

public abstract class A{
private string data;
protected A(string myString){
data = myString;
}
}

public class B : A {

B(string myString) : base(mystring){}
}

NOTE:- As you can’t override constructor, so we can’t have abstract constructor.

Top 10 features of SQL Server 2008

Introduction


                      I this article i am going to describe top 10 features of SQL Server 2008 database.


Description


10.  Plug-in model for SSMS.   SSMS 2005 also had a plug-in model, but it was not published, so the few developers that braved that environment were flying blind.  Apparently for 2008, the plug-in model will be published and a thousand add-ins will bloom.


9.  Inline variable assignment.  I often wondered why, as a language, SQL languishes behind the times.  I mean, it has barely any modern syntactic sugar.  Well, in this version, they are at least scratching the the tip of the iceberg.


Instead of:




DECLARE @myVar int
SET @myVar = 5


you can do it in one line:




DECLARE @myVar int = 5


Sweet.

Temporary Table Concept In SQL Server

Introduction


This article covers the concept of temporary tables and tables variables in SQL server database.




Temporary Tables


Lets take a look at a simple CREATE TABLE statement that is going to create a temporary table:



CREATE TABLE #Yaks (
YakID int,
YakName char(30) )

You'll notice I prefixed the table with a pound sign (#). This tells SQL Server that this table is a local temporary table. This table is only visible to this session of SQL Server. When I close this session, the table will be automatically dropped. You can treat this table just like any other table with a few exceptions. The only real major one is that you can't have foreign key constraints on a temporary table.

Points to consider while designing database

SQL Server DO's and DON'Ts



DO know your tools.


Please, don't underestimate this tip. This is the best of all of those you'll see in this article. You'd be surprised of how many SQL Server programmers don't even know all T-SQL commands and all of those effective tools SQL Server has.


"What? I need to spend a month learning all those SQL commands I'll never use???" you might say. No, you don't need to. But spend a weekend at MSDN and browse through all T-SQL commands: the mission here is to learn a lot of what can and what can't be done. And, in the future, when designing a query, you'll remember "Hey, there's this command that does exactly what I need", and then you'll refer again to MSDN to see its exact syntax.


In this article I'll assume that you already know the T-SQL syntax or can find about it on MSDN.

SQL Tuning or SQL Optimization

SQL Tuning or SQL Optimization


Sql Statements are used to retrieve data from the database. We can get same results by writing different sql queries. But use of the best query is important when performance is considered. So you need to sql query tuning based on the requirement. Here is the list of queries which we use reqularly and how these sql queries can be optimized for better performance.


 Following are some of the techniques that i remember now to optimize the SQL :--


1) The sql query becomes faster if you use the actual columns names in SELECT statement instead of than '*'.


For Example: Write the query as


SELECT id, first_name, last_name, age, subject FROM student_details;


Instead of:


SELECT * FROM student_details;

Store and Retrieve Images in Sql Server ASP.NET

Intruduction

In this article i am going to write that how to store and retrieve images in our Sql Server Database.Let us start off by first creating a sample database and adding a table to it. We will call the database ‘Employee’ and the table will be called ‘EmpDetails’. This table will contain an image column along with some other columns. Run the following script in your SQL 2005 Query window (or server explorer) to construct the database and the table.
Database Script

CREATE DATABASE [Employee]

GO

USE [Employee]

GO

CREATE TABLE EmpDetails

(

empid int IDENTITY NOT NULL,

empname varchar(20),

empimg image

)


Step 1: Create a new asp.net website. In the code-behind, add the following namespace

C#

using System.Data.SqlClient;


VB.NET

Imports System.Data.SqlClient


Step 2: Drag and drop two label and one textbox control. Also drag drop a FileUpload control and a button control to upload the selected image on button click. As mentioned earlier, there are no validations performed. The source would look similar to the following:

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Save Retrieve Images</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

   

        <asp:Label ID="lblEmpName" runat="server" Text="Employee Name"></asp:Label>

&nbsp;&nbsp;&nbsp;&nbsp;

        <asp:TextBox ID="txtEName" runat="server"></asp:TextBox>

        <br />

        <asp:Label ID="lblImage" runat="server" Text="Employee Image"></asp:Label>

&nbsp;&nbsp;&nbsp;&nbsp;

        <asp:FileUpload ID="imgUpload" runat="server" />

        <br />

        <br />

        <asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click"

            Text="Submit" />

   

    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp        <asp:Label ID="lblResult" runat="server" ForeColor="#0066FF"></asp:Label>

    <br />

    <hr />

     <asp:Image ID="Image1" style="width:200px" Runat="server" />  

    </div>

    </form>

</body>

</html>


Step 3: In the button click event, add the following code:

 C#


protected void btnSubmit_Click(object sender, EventArgs e)

    {

        SqlConnection connection = null;

        try

        {

            FileUpload img = (FileUpload)imgUpload;

            Byte[] imgByte = null;

            if (img.HasFile && img.PostedFile != null)

            {

                //To create a PostedFile

                HttpPostedFile File = imgUpload.PostedFile;

                //Create byte Array with file len

                imgByte = new Byte[File.ContentLength];

                //force the control to load data in array

                File.InputStream.Read(imgByte, 0, File.ContentLength);

            }

            // Insert the employee name and image into db

string conn = ConfigurationManager.ConnectionStrings ["EmployeeConnString"].ConnectionString;

            connection = new SqlConnection(conn);


            connection.Open();

string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY";

            SqlCommand cmd = new SqlCommand(sql, connection);

            cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());

            cmd.Parameters.AddWithValue("@eimg", imgByte);

            int id = Convert.ToInt32(cmd.ExecuteScalar());

            lblResult.Text = String.Format("Employee ID is {0}", id);

        }

        catch

        {

            lblResult.Text = "There was an error";

        }

        finally

        {

            connection.Close();

        }


    }



VB.NET


Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click

        Dim connection As SqlConnection = Nothing

        Try

            Dim img As FileUpload = CType(imgUpload, FileUpload)

            Dim imgByte As Byte() = Nothing

            If img.HasFile AndAlso Not img.PostedFile Is Nothing Then

                'To create a PostedFile

                Dim File As HttpPostedFile = imgUpload.PostedFile

                'Create byte Array with file len

                imgByte = New Byte(File.ContentLength - 1) {}

                'force the control to load data in array

                File.InputStream.Read(imgByte, 0, File.ContentLength)

            End If

            ' Insert the employee name and image into db

            Dim conn As String = ConfigurationManager.ConnectionStrings("EmployeeConnString").ConnectionString

            connection = New SqlConnection(conn)


            connection.Open()

            Dim sql As String = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY"

            Dim cmd As SqlCommand = New SqlCommand(sql, connection)

            cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim())

            cmd.Parameters.AddWithValue("@eimg", imgByte)

            Dim id As Integer = Convert.ToInt32(cmd.ExecuteScalar())

            lblResult.Text = String.Format("Employee ID is {0}", id)

        Catch

            lblResult.Text = "There was an error"

        Finally

            connection.Close()

        End Try

    End Sub


                         In the code above, i have created a byte array equal to the length of the file. The byte array will store the image. Then load the image data into the array. The record containing the Employee Name and Image is then inserted into the database using the ADO.NET code. The ID inserted is returned back using the @@Identity. We will shortly use this ID and pass it as a query string parameter to the ShowImage handler. The image will then be fetched against the EmployeeID (empid).


Step 4: In order to display the image on the page, we will create an Http handler. To do so, right click project > Add New Item > Generic Handler > ShowImage.ashx. The code shown below, uses the Request.QueryString[“id”] to retrieve the EmployeeID from it. The ID is then passed to the ‘ShowEmpImage()’ method where the image is fetched from the database and returned in a MemoryStream object. We then read the stream into a byte array. Using the OutputStream.Write(), we write the sequence of bytes to the current stream and you get to see your image.

C#


<%@ WebHandler Language="C#" Class="ShowImage" %>


using System;

using System.Configuration;

using System.Web;

using System.IO;

using System.Data;

using System.Data.SqlClient;


public class ShowImage : IHttpHandler

{

    public void ProcessRequest(HttpContext context)

    {

       Int32 empno;

       if (context.Request.QueryString["id"] != null)

            empno = Convert.ToInt32(context.Request.QueryString["id"]);

       else

            throw new ArgumentException("No parameter specified");


       context.Response.ContentType = "image/jpeg";

       Stream strm = ShowEmpImage(empno);

       byte[] buffer = new byte[4096];

       int byteSeq = strm.Read(buffer, 0, 4096);


       while (byteSeq > 0)

       {

           context.Response.OutputStream.Write(buffer, 0, byteSeq);

           byteSeq = strm.Read(buffer, 0, 4096);

       }       

       //context.Response.BinaryWrite(buffer);

    }


    public Stream ShowEmpImage(int empno)

    {

 string conn = ConfigurationManager.ConnectionStrings     ["EmployeeConnString"].ConnectionString;

        SqlConnection connection = new SqlConnection(conn);

        string sql = "SELECT empimg FROM EmpDetails WHERE empid = @ID";

        SqlCommand cmd = new SqlCommand(sql,connection);

        cmd.CommandType = CommandType.Text;

        cmd.Parameters.AddWithValue("@ID", empno);

        connection.Open();

        object img = cmd.ExecuteScalar();

        try

        {

            return new MemoryStream((byte[])img);

        }

        catch

        {

            return null;

        }

        finally

        {

            connection.Close();

        }

    }


    public bool IsReusable

    {

        get

        {

            return false;

        }

    }



}


VB.NET

<%@ WebHandler Language="vb" Class="ShowImage" %>


Imports System

Imports System.Configuration

Imports System.Web

Imports System.IO

Imports System.Data

Imports System.Data.SqlClient


Public Class ShowImage

    Implements IHttpHandler

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        Dim empno As Int32

        If Not context.Request.QueryString("id") Is Nothing Then

            empno = Convert.ToInt32(context.Request.QueryString("id"))

        Else

            Throw New ArgumentException("No parameter specified")

        End If


        context.Response.ContentType = "image/jpeg"

        Dim strm As Stream = ShowEmpImage(empno)

        Dim buffer As Byte() = New Byte(4095) {}

        Dim byteSeq As Integer = strm.Read(buffer, 0, 4096)


        Do While byteSeq > 0

            context.Response.OutputStream.Write(buffer, 0, byteSeq)

            byteSeq = strm.Read(buffer, 0, 4096)

        Loop

        'context.Response.BinaryWrite(buffer);

    End Sub


    Public Function ShowEmpImage(ByVal empno As Integer) As Stream

        Dim conn As String = ConfigurationManager.ConnectionStrings("EmployeeConnString").ConnectionString

        Dim connection As SqlConnection = New SqlConnection(conn)

        Dim sql As String = "SELECT empimg FROM EmpDetails WHERE empid = @ID"

        Dim cmd As SqlCommand = New SqlCommand(sql, connection)

        cmd.CommandType = CommandType.Text

        cmd.Parameters.AddWithValue("@ID", empno)

        connection.Open()

        Dim img As Object = cmd.ExecuteScalar()

        Try

            Return New MemoryStream(CType(img, Byte()))

        Catch

            Return Nothing

        Finally

            connection.Close()

        End Try

    End Function


    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable

        Get

            Return False

        End Get

    End Property


End Class


Step 5: One final step. Add the following code in the button click (just above the catch block) to call the handler and display the newly inserted image from the database. In the code below, we pass the EmployeeID as a query string parameter to the Http Handler.


C#

// Display the image from the database

Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;

VB.NET

' Display the image from the database

 Image1.ImageUrl = "~/ShowImage.ashx?id=" & id

That’s it. Run the code and check out the functionality. Just change the connection string in the web.config to point to your database. The code works fine for .jpg, .gif and .bmp images. I would encourage you to extend the sample and include validations in it. Some validations could be to check the size of the image uploaded, make sure that only images are uploaded, check the length of the Employee name, prevent the user from entering numeric and special characters, so on and so forth.



                   I hope this article was useful and I thank you for viewing it.If you like this post , i request you to rate this article.

3 Tier Architecture in C# .NET

Introduction


Here in this article, I would like to cover the typical three layer architecture in C# .NET. It is a very useful approach for coding due to easy code maintenance.

Overview


First let me give you a small overview about the topic I would like to cover in this article.

  1. Tier vs. Layer

  2. Three Tier/Layer Architecture Design Components

  3. Demo: Three Layer Windows Application in C#.NET


1. Tier vs. Layer


1.1 Tier: Tier indicates a physical separation of components, which may mean different assemblies such as DLL, EXE, etc. on the same server or multiple servers.



As you can see in the above figure, Data Tier have no direction with Presentation Tier, but there is an intermediate Tier called Business Tier which is mainly responsible to pass the data from Data Tier to Presentation Tier and to add defined business logic to Data.

So, if we separate each Tier by its functionality, then we come to know the below conclusion:



1.2 Layer: Layer indicates logical separation of components, such as having distinct namespaces and classes for the Database Access Layer, Business Logic Layer and User Interface Layer.


2. Three Tier/Layer Architecture Design Components


As we have already seen, tier is the sum of all the physical components. We can separate the three tiers as Data Tier, Business Tier and Presentation Tier.



  • Data Tier is basically the server which stores all the application’s data. Data tier contents Database Tables, XML Files and other means of storing Application Data.

  • Business Tier is mainly working as the bridge between Data Tier and Presentation Tier. All the Data passes through the Business Tier before passing to the presentation Tier. Business Tier is the sum of Business Logic Layer, Data Access Layer and Value Object and other components used to add business logic.

  • Presentation Tier is the tier in which the users interact with an application. Presentation Tier contents Shared UI code, Code Behind and Designers used to represent information to user.




The above figure is a mixture of Three Tier and Three Layer Architecture. Here, we can clearly see a different between Tier and Layer. Since each component is independent of each other, they are easily maintainable without changing the whole code.

This approach is really very important when several developers are working on the same project and some module needs to be re-used in another project. In a way, we can distribute work among developers and also maintain it in the future without much problems.

Testing is also a very important issue for Architecture when we are considering writing a test case for the project. Since it’s like a modular architecture, it’s very handy testing each module and to trace out bugs without going through the entire code.

3. Demo: 3 Layer Windows Application in C#.NET




Let’s go though from one module to other to have a better understanding of it.

dbConnection


This class is mainly used to do the database activity like Select, Update and Delete query to database. It also checks if the database connection is open or not. If database connection is not open, then it opens the connection and performs the database query. The database results are to be received and being passing in Data Table in this class.

This class takes the database setting from the app.config file so it’s really flexible to manage the database settings.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace ThreeLayerDemo.Core
{
public class dbConnection
{
private SqlDataAdapter myAdapter;
private SqlConnection conn;

/// <constructor>
/// Initialise Connection
/// </constructor>
public dbConnection()
{
myAdapter = new SqlDataAdapter();
conn = new SqlConnection(ConfigurationManager.ConnectionStrings
["dbConnectionString"].ConnectionString);
}

/// <method>
/// Open Database Connection if Closed or Broken
/// </method>
private SqlConnection openConnection()
{
if (conn.State == ConnectionState.Closed || conn.State ==
ConnectionState.Broken)
{
conn.Open();
}
return conn;
}

/// <method>
/// Select Query
/// </method>
public DataTable executeSelectQuery(String _query, SqlParameter[] sqlParameter)
{
SqlCommand myCommand = new SqlCommand();
DataTable dataTable = new DataTable();
dataTable = null;
DataSet ds = new DataSet();
try
{
myCommand.Connection = openConnection();
myCommand.CommandText = _query;
myCommand.Parameters.AddRange(sqlParameter);
myCommand.ExecuteNonQuery();
myAdapter.SelectCommand = myCommand;
myAdapter.Fill(ds);
dataTable = ds.Tables[0];
}
catch (SqlException e)
{
Console.Write("Error - Connection.executeSelectQuery - Query:
" + _query + " nException: " + e.StackTrace.ToString());
return null;
}
finally
{

}
return dataTable;
}

/// <method>
/// Insert Query
/// </method>
public bool executeInsertQuery(String _query, SqlParameter[] sqlParameter)
{
SqlCommand myCommand = new SqlCommand();
try
{
myCommand.Connection = openConnection();
myCommand.CommandText = _query;
myCommand.Parameters.AddRange(sqlParameter);
myAdapter.InsertCommand = myCommand;
myCommand.ExecuteNonQuery();
}
catch (SqlException e)
{
Console.Write("Error - Connection.executeInsertQuery - Query:
" + _query + " nException: n" + e.StackTrace.ToString());
return false;
}
finally
{
}
return true;
}

/// <method>
/// Update Query
/// </method>
public bool executeUpdateQuery(String _query, SqlParameter[] sqlParameter)
{
SqlCommand myCommand = new SqlCommand();
try
{
myCommand.Connection = openConnection();
myCommand.CommandText = _query;
myCommand.Parameters.AddRange(sqlParameter);
myAdapter.UpdateCommand = myCommand;
myCommand.ExecuteNonQuery();
}
catch (SqlException e)
{
Console.Write("Error - Connection.executeUpdateQuery - Query:
" + _query + " nException: " + e.StackTrace.ToString());
return false;
}
finally
{
}
return true;
}
}
}

Database Access Layer


Database Access Layer (DAO) builds the query based on received parameters from the Business Logic Layer and passes it the dbConnection class for execution. And simple return results from the dbConnection class to Business Logic Layer.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace ThreeLayerDemo.Core
{
public class UserDAO
{
private dbConnection conn;

/// <constructor>
/// Constructor UserDAO
/// </constructor>
public UserDAO()
{
conn = new dbConnection();
}

/// <method>
/// Get User Email By Firstname or Lastname and return DataTable
/// </method>
public DataTable searchByName(string _username)
{
string query = string.Format("select * from [t01_user]
where t01_firstname like @t01_firstname or t01_lastname
like @t01_lastname ");
SqlParameter[] sqlParameters = new SqlParameter[2];
sqlParameters[0] = new SqlParameter("@t01_firstname", SqlDbType.VarChar);
sqlParameters[0].Value = Convert.ToString(_username);
sqlParameters[1] = new SqlParameter("@t01_lastname", SqlDbType.VarChar);
sqlParameters[1].Value = Convert.ToString(_username);
return conn.executeSelectQuery(query, sqlParameters);
}

/// <method>
/// Get User Email By Id and return DataTable
/// </method>
public DataTable searchById(string _id)
{
string query = "select * from [t01_id] where t01_id = @t01_id";
SqlParameter[] sqlParameters = new SqlParameter[1];
sqlParameters[0] = new SqlParameter("@t01_id", SqlDbType.VarChar);
sqlParameters[0].Value = Convert.ToString(_id);
return conn.executeSelectQuery(query, sqlParameters);
}
}
}

Value Object


Value Object is nothing more but a class with the contents GET and SET methods. It’s mainly used to pass Data from one class to another. It’s directly connected with Business Logic Layer and Presentation Layer. As you can see in the diagram object values are being SET in Business Logic Layer and GET from Presentation Layer.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ThreeLayerDemo.Core
{
public class UserVO
{
private int _idUser;
private string _firstname;
private string _lastname;
private string _email;

/// <constructor>
/// Constructor UserVO
/// </constructor>
public UserVO()
{
//
// TODO: Add constructor logic here
//
}

public int idUser
{
get
{
return _idUser;
}

set
{
_idUser = value;
}
}

public string firstname
{
get
{
return _firstname;
}

set
{
_firstname = value;
}
}

public string lastname
{
get
{
return _lastname;
}
set
{
_lastname = value;
}
}

public string email
{
get
{
return _email;
}

set
{
_email = value;
}
}
}
}

Business Logic Layer


Business Logic Layer (BUS) works as a bridge between Presentation Layer and DAO. All the user values received from the presentation layer are being passed to BUS. The results received from the DAO are in row data in Data Table format but in BUS it’s converting into Value Objects (VO). Business Logic Layer (BUS) is the most important class in the whole architecture because it mainly contains all the business logic of the program. Whenever a user wants to update the business logic of the program only need to update this class.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace ThreeLayerDemo.Core
{
/// <summary>
/// Summary description for UserBUS
/// </summary>
public class UserBUS
{
private UserDAO _userDAO;

/// <constructor>
/// Constructor UserBUS
/// </constructor>
public UserBUS()
{
_userDAO = new UserDAO();
}

/// <method>
/// Get User Email By Firstname or Lastname and return VO
/// </method>
public UserVO getUserEmailByName(string name)
{
UserVO userVO = new UserVO();
DataTable dataTable = new DataTable();

dataTable = _userDAO.searchByName(name);

foreach (DataRow dr in dataTable.Rows)
{
userVO.idUser = Int32.Parse(dr["t01_id"].ToString());
userVO.firstname = dr["t01_firstname"].ToString();
userVO.lastname = dr["t01_lastname"].ToString();
userVO.email = dr["t01_email"].ToString();
}
return userVO;
}

/// <method>
/// Get User Email By Id and return DataTable
/// </method>
public UserVO getUserById(string _id)
{
UserVO userVO = new UserVO();
DataTable dataTable = new DataTable();
dataTable = _userDAO.searchById(_id);

foreach (DataRow dr in dataTable.Rows)
{
userVO.idUser = Int32.Parse(dr["t01_id"].ToString());
userVO.firstname = dr["t01_firstname"].ToString();
userVO.lastname = dr["t01_lastname"].ToString();
userVO.email = dr["t01_email"].ToString();
}
return userVO;
}
}
}

Presentation Layer


Presentation Layer is the only layer which is directly connected with the user. So in this matter, it’s also a really important layer for marketing purposes. Presentation Layer is mainly used for getting user data and then passing it to Business Logic Layer for further procedure, and when data is received in Value Object then it’s responsible to represent value object in the appropriate form which user can understand.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ThreeLayerDemo.Core;

namespace ThreeLayerDemo
{
public partial class frmLogin : Form
{
private UserBUS _userBUS;

public frmLogin()
{
InitializeComponent();
_userBUS = new UserBUS();
}

private void btnSearch_Click(object sender, EventArgs e)
{
UserVO _userVO = new UserVO();
_userVO = _userBUS.getUserEmailByName(txtUsername.Text);
if (_userVO.email == null)
MessageBox.Show("No Match Found!", "Not Found",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
else
MessageBox.Show(_userVO.email ,"Result",
MessageBoxButtons.OK,MessageBoxIcon.Information);
}

private void btnCancel_Click(object sender, EventArgs e)
{
Close();
}
}
}

Summary


Hope this explanation briefs the beginner specially looking for a generic approach. There are also some methods which are far better than the architecture described above, mostly with skipping Database Access Layer and Value Object Class, and making it dynamically which is really handy for maintenance in case of frequent database change. I will try to post some in the near future.