Search This Blog

Wednesday, April 28, 2010

Add FileUpload Control To Edit The Image In GridView

If you are displaying images in gridview control and you want to update the image by a fileupload control. I assume that the image path is stored in database as well as a folder named "Image" in your application.

To add a FileUpload control to your GridView, you first need to add an ItemTemplateField. To the template field you can add both an ItemTemplate, which will be displayed when the row is not in edit mode, and an EditItemTemplate, which will be displayed when the row is in edit mode. If you only want to show the FileUpload control when a row has entered edit mode, you can add the FileUpload ot the EditItemTemplate: 


    

     

    

    

       

    

   
      
As you can see in the code above, the ItemTempalte will display an Image control, where the ImageUrl attribute of the control is bound to a “Image” field (The “Image” in this case is the name of the data source’s column that will contain the path to the image that should be displayed).

To pass the filename that is uploaded by the FileUpload control to your data-source control’s UpdateCommand, you need to create a parameter for the filename. To create a parameter that will be used by your UpdateCommand, you can add the parameter to the data-source’s UpdateParameters collection. The following is an example of a SqlDataSource control where an Image parameter is added, and where the Select- and UpdateCommand are specified (The Image parameter represents the filename that will be passed to the UpdateCommnad):

 

   ID="SqlDataSource1" runat="server"

   SelectCommand="SELECT [CustomerID], [Name], [Image] FROM [Customers]"

   UpdateCommand="UPDATE [Customers] SET [Name] = @Name, [Image] = @Image WHERE   [CustomerID] = @original_CustomerID">

   

     

   

   

The FileUpload control, will not automatically save the uploaded file. To save the file you need to use the FileUpload control’s SaveAs method. Before you can use the SaveAs method you need to get the instance of the FileUpload control for the row you are editing. To get the instance of the control you can hook up to the GridView’s RowUpdating event. The following code will get the instance of the FileUpload control and save the uploaded file:

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    FileUpload fileUpload = GridView1.Rows[e.RowIndex].FindControl("FileUpload1") as FileUpload;

    fileUpload.SaveAs(System.IO.Path.Combine(Server.MapPath("Images"), fileUpload.FileName));

    SqlDataSource1.UpdateParameters["Image"].DefaultValue = "~/Images/" + fileUpload.FileName;
}

From the RowUpdating event’s GridViewUpdateEventArgs, you can get the index of GridView’s row that is going to be updated. You can use the RowIndex property to get the row you are editing from the GridView’s Rows collection. When you have the instance of the GirdView’s row, you can use the FindControl method to locate the FileUpload control. In the RowUpdating event the Image parameter added to the UpdateParamters collection will be set to the name of the uploaded file. The RowUpdating event will be trigged before the data-source control’s UpdateCommand is executed, so the RowUpdateing event is a good place to change the value of the data-source parameters that will be passed to the data-source’s UpdateCommand.

When the data-source update command is executed, the name of the uploaded file will be passed to your UpdateCommand, and the uploaded file will be saved to your disc.

Monday, April 26, 2010

Printing Reports in C Sharp Windows Forms

While working with projects we need many reports to be printed like Bills,Invoices,Management Reports,Sales Reports,Daily Reports.as whole data is displayed on Windows Forms.In this article i am going to demonstrate how to print reports by taking data from windows forms controls with a easy to understand example.
System.Drawing.Printing: -Namespace contains all print related classes,delegates and Enumerators.so let us take a deep understanding of System.Drawing.Printing namespace .
When we want to print a windows forms application first we need to create an instance of PrintDocument class.
PrintDocument:=Defines a reusable object that sends output to a printer, when printing from a Windows Forms application.

Typically, when you print from a Windows Forms application, you create a new instance of the PrintDocument class, set properties, such as DefaultPageSettings and PrinterSettings, that describe how to print, and call the Print method to actually print the document. Calling the PrintDocument.Print method raises the PrintDocument.PrintPage event, which should be handled to perform the document layout for printing.


Using the Graphics property of the PrintPageEventArgs object obtained from the PrintDocument.PrintPage event we specify the output to print. the output can be the data present in windows forms controls like textboxes,comboboxes,etc or any existing file from the hard disk.
 
In this Example I demonstrated how to generate a bill when a product is sold and the print the Bill .I taken a
















And Design of Form:
Above form is taken to select the list of products from comboBox after selecting the product name units price displayed in textbox,it needs to be enter units purchased then it calculates the total amount.after confirming it will be added to a list box one by one.
when all item purchased clicking Print button will show the PrintPreview of the Bill.



I used a PrintDocument Control and PrintPreview Control on the form.


Lets See The Code :you only need to change the connection string of the database server.

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 System.Data.SqlClient;
namespace printApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

SqlConnection con = new SqlConnection(@"Server=appin\sqlexpress;Database=Inventory_Shop;Integrated Security=True");
SqlCommand cmd;
SqlDataReader reader;
DataTable dt;
SqlDataAdapter da;
DataRow row;
private void Form1_Load(object sender, EventArgs e)
{
dt = new DataTable();
da = new SqlDataAdapter("select * from item_product", con);
da.Fill(dt);
cmd = new SqlCommand("select product_nm from item_product", con);
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
comboBox1.Items.Add(reader[0].ToString());
con.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
row = dt.Rows[comboBox1.SelectedIndex];
txtUnitPrice.Text = row["unit_price"].ToString();
}
private void txtQty_TextChanged(object sender, EventArgs e)
{

if (txtQty.Text != "")
{
txtAmt.Text =Convert.ToString( Convert.ToInt32(txtUnitPrice.Text) * Convert.ToInt32(txtQty.Text));
}
}
int slno=0;
double totAmt = 0;
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Sure To want add this product to bill?", "Confirm!", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
slno++;
listBox1.Items.Add(slno.ToString() + "\t\t" + row[1].ToString() + "\t\t" + row[4].ToString() + "\t"+txtQty.Text+"\t" + txtAmt.Text);
totAmt += Convert.ToDouble (txtAmt.Text);
txtTotAmt.Text = totAmt.ToString();
txtQty.Clear();
txtAmt.Clear();
txtUnitPrice.Clear();
}
}

private void txtTotAmt_TextChanged(object sender, EventArgs e)
{
double tax = Convert.ToDouble (txtTotAmt.Text) * 0.12;
txtTax.Text = tax.ToString();
txtNetAmt.Text = Convert.ToString(Convert.ToDouble (txtTotAmt.Text) - tax);
}

private void button3_Click(object sender, EventArgs e)
{
printPreviewDialog1.Document = printDocument1;
printPreviewDialog1.ShowDialog();
}

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Graphics g = e.Graphics;
g.DrawString(label3.Text , new Font(FontFamily.GenericSerif, 20, FontStyle.Bold ), Brushes.Black , 300, 100);
g.DrawString("Address:- "+label4.Text, new Font(FontFamily.GenericSerif, 15, FontStyle.Regular ), Brushes.Black, 180, 130);
g.DrawString("Phone:- 000-9725889568", new Font(FontFamily.GenericSerif, 15, FontStyle.Regular), Brushes.Green , 180, 150);
g.DrawString("Customer Name: \t" + txtCustName.Text, new Font(FontFamily.GenericSerif, 15, FontStyle.Regular), Brushes.Green, 180, 200);
g.DrawString("Contact No.: \t" + txtCustName.Text, new Font(FontFamily.GenericSerif, 15, FontStyle.Regular), Brushes.Green, 180, 250);

g.DrawString("SL No.\t Product Name \t Unit Price\tQuntity\tAmount", new Font(FontFamily.GenericSerif, 15, FontStyle.Regular), Brushes.Black, 130, 300);



int j = 350;

for (int i = 0; i < listBox1.Items.Count; i++)
{
g.DrawString(listBox1.Items[i].ToString(), new Font(FontFamily.GenericSerif, 15, FontStyle.Regular), Brushes.Black, 130, j);
j += 50;
}
g.DrawString("Total Amount:\t" + txtTotAmt.Text, new Font(FontFamily.GenericSerif, 15, FontStyle.Bold), Brushes.Black, 550, j+50);

g.DrawString("Vat: \t" + txtTax.Text , new Font(FontFamily.GenericSerif, 15, FontStyle.Bold), Brushes.Black, 550, j+100);

g.DrawString("Net Amount: \t" + txtNetAmt.Text , new Font(FontFamily.GenericSerif, 15, FontStyle.Bold), Brushes.Black, 550, j + 145);
}
}
}
Hope this article will help you to print you the reports on windows forms for any queries and doubts you can contact me by clicking on Contact Me tab on the Menu bar.

Saturday, April 10, 2010

All About C Sharp Programming Language

Language Overview
C# (pronounced as "see sharp") is a multi-paradigm programming language encompassing imperative, functional, generic, object-oriented (class-based), and component-oriented programming disciplines. It was developed by Microsoft within the .NET initiative and later approved as a standard by Ecma (ECMA-334) and ISO (ISO/IEC 23270). C# is one of the programming languages designed for the Common Language Infrastructure.
C# is intended to be a simple, modern, general-purpose, object-oriented programming language. Its development team is led by Anders Hejlsberg. The most recent version is C# 3.0, which was released in conjunction with the .NET Framework 3.5 in 2007. The next proposed version, 4.0, is in development.

C# Goals
The ECMA standard lists these design goals for C#
  • C# language is intended to be a simple, modern, general-purpose, object-oriented programming language.
  • The language, and implementations thereof, should provide support for software engineering principles such as strong type checking, array bounds checking, detection of attempts to use uninitialized variables, and automatic garbage collection. Software robustness, durability, and programmer productivity are important.
  • The language is intended for use in developing software components suitable for deployment in distributed environments.
  • Source code portability is very important, as is programmer portability, especially for those programmers already familiar with C and C++.
  • Support for internationalization is very important.
  • C# is intended to be suitable for writing applications for both hosted and embedded systems, ranging from the very large that use sophisticated operating systems, down to the very small having dedicated functions.
  • Although C# applications are intended to be economical with regard to memory and processing power requirements, the language was not intended to compete directly on performance and size with C or assembly language.
C# :-Name
C-sharp musical noteThe name "C sharp" was inspired by musical notation where a sharp indicates that the written note should be made a half-step higher in pitch. This is similar to the language name of C++, where "++" indicates that a variable should be incremented by 1.
By coincidence, the sharp symbol resembles four conjoined plus signs. This reiterates Rick Mascitti's tongue-in-cheek use of '++' when naming 'C++': where C was enhanced to create C++, C++ was enhanced to create C++++ (that is, C#).
Due to technical limitations of display (standard fonts, browsers, etc.) and the fact that the sharp symbol (♯, U+266F, MUSIC SHARP SIGN) is not present on the standard keyboard, the number sign (#, U+0023, NUMBER SIGN) was chosen to represent the sharp symbol in the written name of the programming language. This convention is reflected in the ECMA-334 C# Language Specification. However, when it is practical to do so (for example, in advertising or in box art[9]), Microsoft uses the intended musical symbol.
The "sharp" suffix has been used by a number of other .NET languages that are variants of existing languages, including J# (a .NET language also designed by Microsoft which is derived from Java 1.1), A# (from Ada), and the functional F#. The original implementation of Eiffel for .NET was called Eiffel#,a name since retired since the full Eiffel language is now supported. The suffix has also been used for libraries, such as Gtk# (a .NET wrapper for GTK+ and other GNOME libraries), Cocoa# (a wrapper for Cocoa) and Qt# (a .NET language binding for the Qt toolkit).

Features of C#
By design, C# is the programming language that most directly reflects the underlying Common Language Infrastructure (CLI). Most of its intrinsic types correspond to value-types implemented by the CLI framework. However, the language specification does not state the code generation requirements of the compiler: that is, it does not state that a C# compiler must target a Common Language Runtime, or generate Common Intermediate Language (CIL), or generate any other specific format. Theoretically, a C# compiler could generate machine code like traditional compilers of C++ or FORTRAN.

Some notable distinguishing features of C# are:
  • There are no global variables or functions. All methods and members must be declared within classes. Static members of public classes can substitute for global variables and functions.
  • Local variables cannot shadow variables of the enclosing block, unlike C and C++. Variable shadowing is often considered confusing by C++ texts.
  • C# supports a strict Boolean datatype, bool. Statements that take conditions, such as while and if, require an expression of a type that implements the true operator, such as the boolean type. While C++ also has a boolean type, it can be freely converted to and from integers, and expressions such as if(a) require only that a is convertible to bool, allowing a to be an int, or a pointer. C# disallows this "integer meaning true or false" approach on the grounds that forcing programmers to use expressions that return exactly bool can prevent certain types of common programming mistakes in C or C++ such as if (a = b) (use of assignment = instead of equality ==).
  • In C#, memory address pointers can only be used within blocks specifically marked as unsafe, and programs with unsafe code need appropriate permissions to run. Most object access is done through safe object references, which always either point to a "live" object or have the well-defined null value; it is impossible to obtain a reference to a "dead" object (one which has been garbage collected), or to a random block of memory. An unsafe pointer can point to an instance of a value-type, array, string, or a block of memory allocated on a stack. Code that is not marked as unsafe can still store and manipulate pointers through the System.IntPtr type, but it cannot dereference them.
  • Managed memory cannot be explicitly freed; instead, it is automatically garbage collected. Garbage collection addresses the problem of memory leaks by freeing the programmer of responsibility for releasing memory which is no longer needed.
  • In addition to the try...catch construct to handle exceptions, C# has a try...finally construct to guarantee execution of the code in the finally block.
  • Multiple inheritance is not supported, although a class can implement any number of interfaces. This was a design decision by the language's lead architect to avoid complication and simplify architectural requirements throughout CLI.
  • C# is more type safe than C++. The only implicit conversions by default are those which are considered safe, such as widening of integers. This is enforced at compile-time, during JIT, and, in some cases, at runtime. There are no implicit conversions between booleans and integers, nor between enumeration members and integers (except for literal 0, which can be implicitly converted to any enumerated type). Any user-defined conversion must be explicitly marked as explicit or implicit, unlike C++ copy constructors and conversion operators, which are both implicit by default.
  • Enumeration members are placed in their own scope.
  • C# provides properties as syntactic sugar for a common pattern in which a pair of methods, accessor (getter) and mutator (setter) encapsulate operations on a single attribute of a class.
  • Full type reflection and discovery is available.
  • C# currently (as of 3 June 2008) has 77 reserved words.
  • Checked exceptions are not present in C# (in contrast to Java). This has been a conscious decision based on the issues of scalability and versionability.
Common Type system (CTS)
C# has a unified type system. This unified type system is called Common Type System (CTS).
A unified type system implies that all types, including primitives such as integers, are subclasses of the System.Object class. For example, every type inherits a ToString() method. For performance reasons, primitive types (and value types in general) are internally allocated on the stack.

Datatypes Categories in C#
CTS separates datatypes into two categories:
1.Value types
2.Reference types
Value types are plain aggregations of data. Instances of value types do not have referential identity nor a referential comparison semantics - equality and inequality comparisons for value types compare the actual data values within the instances, unless the corresponding operators are overloaded. Value types are derived from System.ValueType, always have a default value, and can always be created and copied. Some other limitations on value types are that they cannot derive from each other (but can implement interfaces) and cannot have an explicit default (parameterless) constructor. Examples of value types are some primitive types, such as int (a signed 32-bit integer), float (a 32-bit IEEE floating-point number), char (a 16-bit Unicode code unit), and System.DateTime (identifies a specific point in time with nanosecond precision). Other examples are enum (enumerations) and struct(user defined structures).
In contrast, reference types have the notion of referential identity - each instance of a reference type is inherently distinct from every other instance, even if the data within both instances is the same. This is reflected in default equality and inequality comparisons for reference types, which test for referential rather than structural equality, unless the corresponding operators are overloaded (such as the case for System.String). In general, it is not always possible to create an instance of a reference type, nor to copy an existing instance, or perform a value comparison on two existing instances, though specific reference types can provide such services by exposing a public constructor or implementing a corresponding interface (such as ICloneable or IComparable). Examples of reference types are object (the ultimate base class for all other C# classes), System.String (a string of Unicode characters), and System.Array (a base class for all C# arrays).
Both type categories are extensible with user-defined types.

Boxing and unboxing
Boxing is the operation of converting a value of a value type into a value of a corresponding reference type.Boxing in C# is implicit.
Unboxing is the operation of converting a value of a reference type (previously boxed) into a value of a value type.Unboxing in C# requires an explicit type cast.

int x = 100; // Value type.

object o = x; //x is boxed to a
int y = (int)o; // Unboxed back to value type.

Wednesday, April 7, 2010

A simple .Net Remoting Example

Introduction:

Distributed computing is an integral part of almost every software development. Before .Net Remoting, DCOM was the most used method of developing distributed application on Microsoft platform. Because of object oriented architecture, .NET Remoting replaces DCOM as .Net framework replaces COM.

Benefits of Distributed Application Development:

Fault Tolerance: Fault tolerance means that a system should be resilient when failures within the system occur.
Scalability: Scalability is the ability of a system to handle increased load with only an incremental change in performance.
Administration: Managing the system from one place.

In brief, .NET remoting is an architecture which enables communication between different application domains or processes using different transportation protocols, serialization formats, object lifetime schemes, and modes of object creation. Remote means any object which executes outside the application domain. The two processes can exist on the same computer or on two computers connected by a LAN or the Internet. This is called marshalling (This is the process of passing parameters from one context to another.), and there are two basic ways to marshal an object:

Marshal by value: the server creates a copy of the object passes the copy to the client.

Marshal by reference: the client creates a proxy for the object and then uses the proxy to access the object.


Architecture:

Remote objects are accessed thro channels. Channels are Transport protocols for passing the messages between Remote objects. A channel is an object that makes communication between a client and a remote object, across app domain boundaries. The .NET Framework implements two default channel classes, as follows:
HttpChannel: Implements a channel that uses the HTTP protocol.

TcpChannel: Implements a channel that uses the TCP protocol (Transmission Control Protocol).

Channel take stream of data and creates package for a transport protocol and sends to other machine. A simple architecture of .NET remoting is as in Fig 1.







As Fig.1 shows, Remoting system creates a proxy for the server object and a reference to the proxy will be returned to the client. When client calls a method, Remoting system sends request thro the channel to the server. Then client receives the response sent by the server process thro the proxy.

Demo Example:Let us see a simple example which demonstrates .Net Remoting. In This example the Remoting object will send us the maximum of the two integer numbers sent.
Creating Remote Server and the Service classes on Machine 1:
Please note for Remoting support your service (Remote object) should be derived from MarshalByRefObject.


using System;
using System.Runtime.Remoting.Channels; //To support and handle Channel and channel sinks
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels.Http; //For HTTP channel
using System.IO;
namespace ServerApp
{
public class RemotingServer
{
public RemotingServer()
{
// TODO: Add constructor logic here
}
}
//Service class
public class Service: MarshalByRefObject
{
public void WriteMessage (int num1,int num2)
{
Console.WriteLine (Math.Max(num1,num2));
}
}
//Server Class
public class Server
{
public static void Main ()
{
HttpChannel channel = new HttpChannel(8001); //Create a new channel
ChannelServices.RegisterChannel (channel); //Register channel
RemotingConfiguration.RegisterWellKnownServiceType(typeof Service),"Service",WellKnownObjectMode.Singleton);
Console.WriteLine ("Server ON at port number:8001");
Console.WriteLine ("Please press enter to stop the server.");
Console.ReadLine ();
}
}
}



Save the above file as ServerApp.cs. Create an executable by using Visual Studio.Net command prompt by,
csc /r:system.runtime.remoting.dll /r:system.dll ServerApp.cs
A ServerApp.Exe will be generated in the Class folder.
Run the ServerApp.Exe will give below message on the console
Server ON at port number:8001

Please press enter to stop the server.
In order to check whether the HTTP channel is binded to the port, type

http://localhost:8001/Service?WSDL in the browser.You should see a XML file describing the Service class.
Please note before running above URL on the browser your server (ServerApp.Exe should be running) should be ON.



Creating Proxy and the Client application on Machine 2
SoapSuds.exe is a utility which can be used for creating a proxy dll.Type below command on Visua studio.Net command prompt.



soapsuds -url:http://< Machine Name where service is running>:8001/Service?WSDL -oa:Server.dll
This will generates a proxy dll by name Server.dll. This will be used to access remote object.
Client Code:

using System;
using System.Runtime.Remoting.Channels; //To support and handle Channel and channel sinks
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels.Http; //For HTTP channel
using System.IO;
using ServerApp;
namespace RemotingApp
{
public class ClientApp
{
public ClientApp()
{
}
public static void Main (string[] args)
{
HttpChannel channel = new HttpChannel (8002); //Create a new channel
ChannelServices.RegisterChannel (channel); //Register the channel
//Create Service class object
Service svc = (Service) Activator.GetObject (typeof (Service),"http://:8001/Service"); //Localhost can be replaced by
//Pass Message
svc.WriteMessage (10,20);
}
}
}

Save the above file as ClientApp.cs. Create an executable by using Visual Studio.Net command prompt by,

csc /r:system.runtime.remoting.dll /r:system.dll ClientrApp.cs
A ClientApp.Exe will be generated in the Class folder. Run ClientApp.Exe , we can see the result on Running ServerApp.EXE command prompt.

Tuesday, April 6, 2010

Sample 3-Tier Application

ADO.NET Architecture

Let’s look at an example where all of the pieces of code utilize the built-in ADO.NET architecture. I assume you know how to access and work with data stored in a weakly-typed dataset and data table. ADO.NET already provides a set of objects for storing data in .NET; no add-on components are necessary for this to work. In addition to that, ADO.NET has been around since .NET framework 1.x, so this approach has been available from the beginning.

Let’s start from the presentation layer, and work in reverse. The presentation layer makes use of the DataTable object, which contains several rows of customer information. This customer information is simply bound to a control in the user interface:

Listing 1: ADO.NET Use in the UI
private void BindData()
{
CustomerBAL bal = new CustomerBAL();
DataTable customerInfo = bal.GetCustomers(20);
this.gvwCustomers.DataSource = customerInfo;
this.gvwCustomers.DataBind();
}

As you can see, the data table is bound to the UI control manually; however, the ObjectDataSource control could replace this approach. To retrieve the DataTable object with the Customer data, the code makes use of a CustomerBAL class. This class provides access to CRUD operations against customer data. The makeup of the GetCustomers method is as follows:


Listing 2: ADO.NET Business Layer – GetCustomers method

public class CustomerBAL
{
public DataTable GetCustomers(int pageCount)

if (pageCount < 0)
throw new ArgumentOutOfRangeException(“pageCount”);
CustomerDAL dal = new CustomerDAL();
DataTable results = dal.GetCustomers(pageCount);
if (results.HasErrors)
throw new Exception();
}
}

The business layer validated the input coming into the method, as well as the output, ensuring that the data didn’t have any erroring information. If not, the results are returned to the user. In my example, I throw an exception; but handle it anyway you want, by logging the errors, returning it to the caller, etc.

But how does the data actually get to the presentation layer? The data layer receives a request for data and actually queries the database, returning the data to the business layer, as shown below:
Listing 3: ADO.NET Data Layer – GetCustomers method

public class CustomerDAL
{
public DataTable GetCustomers(int pageCount)
{
SqlConnection connection = new SqlConnection( "your connection string");
SqlDataAdapter adapter = new SqlDataAdapter(“spSelectCustomers”,connection);
DataTable table = new DataTable();
adapter.Fill(table);
return table;
}
}

The next question is how are inserts, updates, and deletes performed? While retrieval of data is satisfied, other data manipulation topics weren’t covered. I cover the subject of data manipulation at the end of the article.
Strongly-Typed DataSets

Strongly-Typed Datasets work very similar to ADO.NET; however, with strongly-typed datasets, the designer generates custom DataTable and strongly-typed DataRow objects that match the database schema. The difference between this and the previous code is that any changes to the database require a change to the dataset, and therefore could break existing code.
To setup this approach, the examples below use a dataset named Samples.xsd, with a name of SamplesDataSet (the name property in the designer affects the dataset class name and namespace). The generated code is as follows:

Custom DataTable and DataRow that match the database system, accessible through the SamplesDataSet class.

Custom TableAdapter objects, stored in the TableAdapters namespace.


I’m not going to talk about the setup of each component; there are plenty of resources online. But, I used this as an illustration that this could be considered an equivalent to a data layer, meaning you wouldn’t have to create a physical data layer consisting of separate classes, but could rely on the strongly-typed dataset as the data layer itself.



To utilize this in the business layer, an approach is shown below:

Listing 4: Business Component for Retrieving Customer Data

public class CustomerBAL : BaseBusinessComponent
{

#region " Methods "
public SamplesDataSet.CustomersDataTable GetAll()
{
CustomersTableAdapter adapter = new CustomersTableAdapter();

SamplesDataSet.CustomersDataTable table =
 new SamplesDataSet.CustomersDataTable();
adapter.FillCustomers(table);
base.HandleErrors(table);
return table;
}
public SamplesDataSet.CustomersRow GetByAccountNumber(string accountNumber)
{
if (string.IsNullOrEmpty(accountNumber))
throw new ArgumentNullException(“accountNumber”);
CustomersTableAdapter adapter = new CustomersTableAdapter();
SamplesDataSet.CustomersDataTable table =
new SamplesDataSet.CustomersDataTable();
adapter.FillByAccountNumber(table, accountNumber);
base.HandleErrors(table);
if (table.Rows.Count == 0)
return null;
else
return (SamplesDataSet.CustomersRow)table.Rows[0];
}
#endregion
}

The code above uses the FillBX - rather than the GetX - method to retrieve the data. I do this because I can check the data for errors using the HandleErrors method (defined in the base class, which simply checks the HasErrors property), and if OK return the correct results back. Note that the input is validated in the business component.

Enterprise Library

Enterprise Library is an initiative by Microsoft to provide additional services that the .NET framework doesn’t have out-of-the-box. The Data Access Application Block provides a centralized way to access data across varying data source systems without having to specify the underlying database in your code. This works through the provider type setting for the connection string defined in the connection strings element of the configuration file; this provider type loads the correct database provider at runtime.



The key benefit is that you don’t have to rewrite your code to do work with a different provider; it works using a single approach. Also note that the Enterprise Library uses the ADO.NET mechanism to represent data. Let’s look at an example data component:



Listing 5: Enterprise Library

public class CustomerDAL : BaseDataAccessComponent
{
#region " Methods "
public DataTable GetAll()
{
Database database = DatabaseFactory.CreateDatabase();
DbCommand command = database.GetStoredProcCommand("CustomersGetAll");
DataSet dataset = new DataSet();
database.LoadDataSet(command, dataset, "Customers");
return dataset.Tables[0];
}
public DataTable GetByAccountNumber(string accountNumber)

{
Database database = DatabaseFactory.CreateDatabase();
DbCommand command = database.GetStoredProcCommand("CustomersGetByAcct");
DataSet dataset = new DataSet();
database.LoadDataSet(command, dataset, "Customers");
}

#endregion
}

Note the difference in the approach above; Enterprise Library uses a Database object as the central point of contact. DatabaseFactory.CreateDatabase() provides the way that Enterprise Library connects to the correct database through a provider. The CreateDatabase method uses either an empty constructor (pulls the database connection from the configuration file) or it takes the name of a connection string (using one of the connection strings in the element).



Rather than accessing this directly, the business layer connects to the data layer as below (only one of the methods is shown). Because the data is transported via a DataTable object, it uses the same approach as shown above.



Listing 6: Business Object Validating Input, Retrieving Data, Validating Output

public class CustomerBAL : BaseBusinessComponent
{
#region " Methods "

public DataRow GetByAccountNumber(string accountNumber)
{
if (string.IsNullOrEmpty(accountNumber))
throw new ArgumentNullException("accountNumber");
CustomerDAL dal = new CustomerDAL();
DataTable table = dal.GetByAccountNumber(accountNumber);
base.HandleErrors(table);
if (table.Rows.Count > 1)
throw new DataException(@"There are too many rows coming back with account number: " + accountNumber);
if (table.Rows.Count == 0)
return null;
else
return table.Rows[0];
}

#endregion
}

In the method above, the business layer validates the input and output received from the data layer. In this way, the business layer ensures the business rules of the system are intact and correct. It also improves the quality of the data.



LINQ to SQL

LINQ-to-SQL creates custom business objects through its designer, as I mentioned previously. It works very similarly to a strongly-typed dataset, but instead of custom DataRow objects, it uses business objects. LINQ to SQL business objects are intelligent enough to detect changes and track updates to its properties, inserts or deletions to records, and changes to the primary and foreign key relationships. LINQ to SQL relies upon the existence of a custom DataContext class, which is the key class for change tracking and change submission.



What this means is that a live instance of the DataContext should be passed along from the business layer to the data layer, so that only one instance of the DataContext class exists. This is because you can’t join or query data that’s created from different DataContext objects; this raises an exception. One of the key ideas is to maintain the same DataContext throughout the lifecycle of the business and data layer objects.



This means passing in a DataContext reference throughout, often passing it through a constructor, as such:



Listing 7: Data Layer Constructor

view sourceprint?1.public CustomerDAL(SamplesDataContext context) : base(context) { }

In the business layer, the DataContext needs to be passed in as well. There can be some variants to this approach, but unfortunately that’s out of scope. Getting back to the data layer, LINQ-to-SQL translates LINQ queries into SQL queries, and returns the data as a collection.



Listing 8: Data Layer LINQ queries

public IEnumerable GetAll()
{
var results = from c in this.Context.Customers
orderby c.LastName, c.FirstName
select c;
return results;
}

public Customer GetByAccountNumber(string accountNumber)
{
var results = from c in this.Context.Customers
where c.AccountNumber == accountNumber
select c;
return results.FirstOrDefault();
}

In the first method, the data returns to the caller as an enumerable list; queries are returned in IOrderedQueryable<> form; however, IEnumerable<> will work as well. In the second approach, a Customer object is returned by using the FirstOrDefault method, which returns the Customer if a match found and null if not found. The business layer calls the data layer, and returns the results. In the GetByAccountNumber method, the input is validated.



Listing 9: LINQ Data Access Layer

private CustomerDAL ConstructComponent()
{
return new CustomerDAL(this.Context);
}
public IEnumerable GetAll()
{

CustomerDAL dal = this.ConstructComponent();
return dal.GetAll();
}
public Customer GetByAccountNumber(string accountNumber)
{
if (string.IsNullOrEmpty(accountNumber))
throw new ArgumentNullException("accountNumber");
CustomerDAL dal = this.ConstructComponent();
return dal.GetByAccountNumber(accountNumber); }
Updates to Content

There are a couple of approaches for inserting, updating, and deleting new content. One of the approaches cold be to pass in all of the parameters to the method, as in the following:



Listing 10: Parameterized DML Method

Public Customer InsertNew(Guid customerKey, string customerName, string account) {
//Create new record
}

This works well in ASP.NET, where data source controls can utilize this approach. Personally, I don’t like this approach simply because future requirements or changes to the parameter list break the interface of the method. Although overloaded methods can be added, that’s not the best option.



I prefer to create a new instance of an object or record in the application, and let the business layer validate the input using a process for business rules. For instance, if creating a new customer, I prefer an approach like this:



Listing 11: Alternative DML Method Approach

Public Customer InsertNew(Customer customer)
{
//Validate properties, and submit to database
}

Using the strongly-typed dataset architecture, the newly created row in the user interface is passed in as a parameter to the Insert method (more on that in a moment). This method updates the inserted row. If there are any errors, an output string is created and is the source of the exception being thrown. Customer object references like this also work well with other validation tools like the Validation Application Block.



Listing 12: Insert Customer Row Approach

view sourceprint?01.public void Insert(SamplesDataSet.CustomersRow insertedRow)
{
CustomersTableAdapter adapter = new CustomersTableAdapter();
adapter.Update(insertedRow);
if (insertedRow.HasErrors)
{
DataColumn[] columns = insertedRow.GetColumnsInError();
string output = null;
foreach (DataColumn column in columns)
output += insertedRow.GetColumnError(column);
throw new DataException(output);
}

}

However, an exception doesn’t always have to be thrown. Instead, the alternative approach can be to store the error information in a property of the business object. This object can be a custom error object that you create, a string value containing the message, or a reference to the exception that was thrown.



Using this property, an ASP.NET page or windows form can use this to output a message to the screen. Take a look at a possible example using ASP.NET; note the code is in a custom page class:



Listing 13: Error Handling in ASP.NET

view sourceprint?01.private void InsertCustomer(Customer customer)
{
CustomerBAL bal = new CustomerBAL();
bal.InsertNew(customer);
if (bal.Error != null)
{

Label errorLabel = this.Master.FindControl(“lblError”) as Label; 

If (errorLabel != null)

errorLabel.Text = bal.Error.Message;
}

}

This may not be the most practical in your situation, but the choice is up to you how you want to handle errors that occur in your business layer.

Friday, April 2, 2010

Shutdown and Restart the CPU with C#

The Shutdown,LogOff and Restart processes can be handled through Process class
Use the namespace System.Diagonostics;
using System.Diagonostics;

Shut Down
In any event handler write this code:
Process.Start("shutdown.exe","-s");
 // By Default the Shutdown will take place after 30 Seconds if you want to change the Delay use this one
Process.Start("shutdown.exe","-s -t xx"); //Replace xx with Seconds example 10,20 etc
 
Restart
Process.Start("shutdown.exe","-r");
// By Default the Restart will take place after 30 Seconds if you want to change the Delay try this one
Process.Start("shutdown.exe","-r -t xx");
//Replace xx with Seconds example 10,20 etc
 
Log Off
Process.Start("shutdown.exe","-l");
//This Code Will Directly Log Off the System Without warnings

Delete Selected Row in GridView Control

This Example show you how to delete selected row from gridview control in your windows form application.
In this example i used Ms-Access as data base.this is devoted for how to select the row and then delete it from database;this is simple design of page containing a DataGridView And delete Button on it;
This is coding file of this form:

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 System.Data.OleDb;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OleDbConnection con=new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\WindowsFormsApplication3\WindowsFormsApplication3\db1.mdb;Persist Security Info=True");
OleDbDataAdapter da;
DataSet ds;
private void Form1_Load(object sender, EventArgs e)
{
Bind();
}
private void button1_Click(object sender, EventArgs e)
{
DataGridViewRow dr = dataGridView1.CurrentRow;
string empcode=dr.Cells[0].Value.ToString();
OleDbCommand cmd = new OleDbCommand("delete from emp where emp_code='" + empcode + "'", con);
da = new OleDbDataAdapter();
da.DeleteCommand = cmd;
ds.Tables[0].Rows[dr.Index].Delete();
da.Update(ds);
Bind();
}
void Bind()
{
ds = new DataSet();
ds.Clear();
da = new OleDbDataAdapter("select * from emp", con);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
}
}
Above i created a function named Bind() to Load the data from database bcoz after deleting the row calling this function will update the DataGridView and populate the updated database.

Your Simple dotnet Dictionary(One Line Definition)

.NET Architecture
The programming model for the .NET platform.A managed execution environment,simplified development ,deployement.supports a lot of programming languages.also called M/S next generation plateform

The .NET Framework has two key parts:
1.The .NET Framework class library is a comprehensive, object-oriented collection of reusable types that you can use to develop applications. The .NET Framework class library includes ADO.NET, ASP.NET and Windows Forms.
2.The common language runtime (CLR) is the core runtime engine for executing applications in the .NET Framework. You can think of the CLR as a safe area - a "sandbox" - inside of which your .NET code runs. Code that runs in the CLR is called managed code.
 
ADO.NET
The data access component for the .NET Framework.

ADO.NET uses the  of XML to provide disconnected access to data. ADO.NET is made of a set of classes that are used for connecting to a database, providing access to relational data, XML, application data and retrieving results.
ADO.NET is made of a set of classes that are used for connecting to a database, providing access to relational data, XML, application data, and retrieving results.

ASP.NET

The component of the Microsoft .NET Framework used for building, deploying, and running Web applications and distributed applications.

Assembly

A ompiled representation of one or more classes.
Each assembly is self-contained, that is, the assembly includes the metadata about the assembly as a whole.

Assembly Cache

A code cache used for side-by-side storage of assemblies.

Code Access Security (CAS)

The component of the Microsoft .NET Framework used for building, deploying and running Web applications and distributed applications.

Common Language Runtime (CLR)

The core runtime engine in the Microsoft .NET Framework. The CLR supplies services such as cross-language integration, code access security, object lifetime management and debugging support. Applications that run in the CLR are sometimes said to be running "in the sandbox."

Download Cache

The subdirectory in assembly cache that stores code downloaded from Internet or intranet sites, isolated to the application that caused the download. This isolation prevents code downloaded on behalf of one application from affecting other applications.

DTC (Distributed Transaction Coordinator)

In Microsoft Windows NT, Windows 2000, Windows XP and the Windows Server 2003 family, the DTC is a system service that is part of COM+ services.
COM+ components that use DTC can enlist .NET connections in distributed transactions. This makes it possible to scale transactions from one to many computers without adding special code.

Expose

To host and make available a Web service so that it can be used by other applications or services.

Garbage Collection

A process in the CLR that automatically frees allocated objects when there are no longer any outstanding references to them. The developer does not need to explicitly free memory assigned to an object.

Global Assembly Cache (GAC)

The part of the assembly cache that stores assemblies specifically installed to be shared by many applications on the computer. Applications deployed in the global assembly cache must have a strong name to handle name and version conflicts.

Isolation Level

An isolation level represents a particular locking strategy employed in the database system to improve data consistency. The higher the isolation level, the more complex the locking strategy behind it.
The isolation level provided by the database determines whether a transaction will encounter defined behaviors in data consistency.
The American National Standards Institute (ANSI) defines four isolation levels:
  • Read uncommitted (0)
  • Read committed (1)
  • Repeatable read (2)
  • Serializable (3)
JIT Compiler

The "just-in-time" compilation that converts Microsoft intermediate language (MSIL) into machine code at the point when the code is required at run time.

Unmanaged Code

Code that is executed directly by the operating system, outside of the CLR.
Unmanaged code includes all code written before the .NET Framework was introduced. This includes code written to use COM, native Win32 and Visual Basic 6. Because it does not run inside the .NET environment, unmanaged code cannot make use of any .NET managed facilities.

UnicodeA standard that software can use to support multi-lingual character sets.
The .NET Framework uses UTF-16 Unicode encoding to represent characters. .NET applications use encoding and decoding to map character representations between Unicode and non-Unicode formats. The .NET Framework also provides UTF-8, ASCII, and ANSI/ISO encodings.


Locking Level

Locking is a database operation that restricts a user from accessing a table or record. Locking is used in situations when more than one user might try to use the same table at the same time. By locking the table or record, only one user at a time can affect the data.

Managed Code

 Code executed and managed by the .NET Framework, specifically by the CLR. Managed code must supply the information necessary for the CLR to provide services such as memory management and code access security.

Microsoft Intermediate Language (MSIL)

A CPU-independent set of instructions that can be converted to native code. MSIL includes instructions for loading, storing, initializing and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling and other operations.

Namespace

A logical naming scheme for grouping related types.
In the .NET Framework, a namespace is a logical design-time naming convenience, whereas an assembly establishes the name scope for types at run time.

No-touch Deployment

A feature of the .NET Framework, similar to browser-based application deployment, that lets clients download the assemblies they need from a remote web server.

The first time an assembly is referenced, it is downloaded to the download cache on the client and executed. After that, when the client accesses the application, the application checks the server to find out whether any assemblies have been updated. Any new assemblies are downloaded to the download cache on the client, refreshing the application without any interaction with the end user.

Side-by-side Execution

The ability to install and use multiple versions of the same assembly in isolation at the same time. Allowing different versions of assemblies to coexist and to execute simultaneously on the same computer enables robust versioning.
Web Forms

An ASP.NET feature that can be used to create the user interface for Web applications.
The Web Forms page works as a container for the static text and controls you want to display. The programming logic for the Web Forms page resides in a separate file from the user interface file. This file is referred to as the "code-behind" file and has an ".aspx.vb" or ".aspx.cs" extension, depending on whether the code-behind file was written in Visual Basic or Visual C#.

Web Services

A set of modular applications or "services" that can be accessed within a network (e.g., the Internet, an intranet, or extranet) through a standard interface, typically XML.

Universal Description, Discover, and Integration (UDDI)

A platform-independent framework that provides a way to locate and register Web services on the Internet.
The UDDI specification calls for three elements, similar to a telephone book:
1.White pages; which provide business contact information
2.Yellow pages; which organize Web services into categories (for example, credit card authorization services)
3.Green pages; which provide detailed technical information about individual services.
The UDDI specification also contains an operational registry.

Simple Object Access Protocol (SOAP)

A simple, XML-based protocol for exchanging structured data and type information over the Internet. SOAP is currently the de facto standard for XML messaging.
SOAP consists of:
•An envelope that defines a framework for describing message structure.
•A set of encoding rules for expressing instances of application-defined data types.
•A convention for using SOAP with HTTP.








 





Store image in Sql Server from Windows Forms

To Store the Image in Sql Server database from Windows forms.


This concept can be used,to store the image as image data we need a column that has datatype image which stores pictures as binary data .then from Windows Form we create a byte array using the BinaryWriter then in SqlCommand object we pass the byte array created by BinaryWriter to column. I am giving an example here which stores an image follow these steps in your example-

first create a table with following structure:

CREATE TABLE imageTable
(
imgId int IDENTITY(1,1),
imgSrc VARCHAR(100),
imgData IMAGE
)

Then design a windows form having these controls and with following properties:
1.TextBox Name:-textBox1
2.Button-Name=button1,Text:=Browse
3.Button-Name=button2,Text=Save

use the Namespace System.Io to use the class Stream and BinaryReader
using System.Io;

On the Click Event of Browse button write this code

void button1_click(object sender,EventArgs e)
{
OpenFileDialog dlg=new OpenFieDialog();
if(dlg.ShowDialog()!=DialogResult.Cancel)
{
textBox.Text=dlg.FileName;
}
}

On the Save Button Click Event Write the code to create byte array and insert it to database

void button2_Click(object sender,EventArgs e)
{
byte []data=null;
FileStream stream=new FileStream(textBox1.Text);
int length=(int)stream.Length;
data=new byte[length];
BinaryWriter bw=new BinaryWriter(stream);
data=(byte[])bw.WriteBytes(length);
Sqlconnection con=new SqlConnection("your connecion string");
con.Open();
SqlCommand cmd=new SqlCommand("insert into imageTable values(@source,@pic)",con);
cmd.Parameters.AddWithValue("source",textBox1.Text);
cmd.Parameters.AddWithValue("pic",data);
cmd.ExecuteNonQuery();
MessageBox.Show("Your Image Saved ","save");
}
Hope this example will help.