Google Search

Google
 

Sunday, November 30, 2008

code to select the specified gridview row WPF

In WPF gridview when we have click on edit or delete button, the button functionality is executed but the current row is not selected by default. to select the end user selected row in wpf gridview the itemcontainerstyle should be implemented for the listview.


Below is the code for select the row when user selects the delete button in wpf gridview

Step1: create an itemcontainerstyle for listview

"ListView.ItemContainerStyle"
Style TargetType="ListViewItem"
Setter Property="HorizontalContentAlignment" Value="Stretch" /
EventSetter Event="GotFocus" Handler="Item_GotFocus"/
/Style
/ListView.ItemContainerStyle"



step2:

private void Item_GotFocus(Object sender ,RoutedEventArgs e)
{
ListViewItem item;
item = (ListViewItem) sender;
MyListView.SelectedItem = item.DataContext;
}

Friday, June 6, 2008

Sockets in c#

Writing programs that access the network used to be a relatively difficult task. With .NET, this is no longer the case. The .NET Framework class library includes two namespaces that are full of classes that help you with networking: System.Net and System.Net.Sockets. In this article, I will discuss one of the most important classes in System.Net.Sockets: the Socket class. The System.Net.Sockets.Socket class can be used as a socket in a server application as well as in a client application. It also allows both synchronous and asynchronous operations. This article shows how to use the Socket class in a client application.
A socket is an endpoint of a connection. It is a descriptor that lets an application read from and write to the network. With sockets, client and server applications can communicate by sending and receiving streams of bytes over connections. To send a message to another socket used in a software application, you need to know not only the machine's IP address that hosts the software application, but also the software's process identifier on that machine. The identification of a software process in a machine is achieved through the use of a unique number called port. Therefore, to send a message from a socket in one application to another socket at the other end of a connection, you need to know the machine's IP address and the application's port number. In the .NET Framework, a socket is represented by the System.Net.Sockets.Socket class. This class is an implementation of the Sockets API, which is also known as the Berkeley sockets interface. The Sockets API was developed in the early 80s at the University at Berkeley for the 4.1c release of Berkeley Software Distribution (BSD) Unix. This distribution contained an early version of the Internet protocols.

Bottom of Form
Constructing a Socket Object
The Socket class provides the following constructor for you to use to create a Socket object.


public Socket (AddressFamily addressFamily,
SocketType socketType,
ProtocolType protocolType );


Instantiating a Socket object requires you to pass three arguments to its constructor: AddressFamily, SocketType, and ProtocolType, all of which are enumerations that are part of the System.Net.Sockets namespace. An AddressFamily member defines the addressing scheme that a Socket object uses to resolve an address. For socket applications that will work on the Internet, you use InterNetwork.
SocketType determines the type of socket. The most popular socket type is Stream. This type of socket supports two-way connection-based byte streams. ProtocolType specifies the type of the low-level protocol that the socket uses to communicate. A stream socket must be used with the Transmission Control Protocol (TCP) protocol type and the InterNetwork address family. For example, the following code instantiates a Socket object.


Socket mySocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);



The arguments you pass to the constructor are available in the following read-only properties: AddressFamily, SocketType, and ProtocolType.
Connecting to A Remote Server
Once you have a socket instance, you can connect to a remote server using the Connect method of the Socket class. This method attempts to connect to a remote server synchronously. It waits until a connection attempt is successful or failed before releasing control to the next line in the program. Even though this method is easy to use, there is some preliminary work youneed to do before you can use this method to connect to a remote server. Consider the signature of the Connect method below.


public void Connect( EndPoint remoteEP);

It accepts an argument: an instance of System.Net.EndPoint. The abstract EndPoint represents a network address. It has a subclass: System.Net.IPEndPoint. When using the Connect method, you typically pass an IPEndPoint object containing the IP address and port number of the remote server to which you want to connect. The question will then be, "How do you construct an IPEndPoint object for your socket to connect to a remote server?" Now, look at the IPEndPoint class definition. It has two constructors.


public IPEndPoint(long address, int port);
public IPEndPoint(IPAddress address, int port);

Of these two constructors, the second is normally used because IP addresses are often represented in dotted-quad notation (such as 129.36.129.44) and, as we soon will see, in .NET socket programming, it is easier to get an IP address in this notation than in a long address. However, the two constructors are actually very similar. It's just that the remote IP address in the first constructor is a long address, whereas in the second constructor, it is a System.Net.IPAddress object. Whichever constructor you choose, you need to have an IP address and the port number of the remote server. The port number is usually not a problem, because popular services are allocated default port numbers. For instance, HTTP uses port 80, Telnet uses port 25, and FTP uses port 21. The IP address is not normally directly available because it is easier for us to remember domain names such as microsoft.com or oreillynet.com rather than the IP addresses mapped to them. With this in mind, we need to resolve a domain name to obtain the IP address of the remote server to which we'd like to connect. In this event, to obtain an IPAddress instance that you can use to connect to a remote server, you need the following other classes: System.Net.Dns and System.Net.IPHostEntry. The Dns class is a final class that retrieves information about a specific host from the Internet Domain Name System (DNS), hence the name Dns. It is mainly used for its Resolve method, to obtain a set of IP addresses mapped to a domain name. The Resolve method returns an IPHostEntry object that contains an array of IP addresses. To obtain these IP addresses, you use the IPHostEntry class' AddressList property. For example, the following code displays all IP addresses mapped to a DNS name.


using System.Net.Sockets;
using System.Net;

try
{
String server = "microsoft.com"; // or any other domain name

IPHostEntry hostEntry = Dns.Resolve(server);
IPAddress[] ipAddresses = hostEntry.AddressList;

Console.WriteLine(server + " is mapped to:");

foreach (IPAddress ipAddress in ipAddresses)
{
Console.WriteLine(ipAddress.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}

When run, the code will display all IP addresses mapped to the DNS name microsoft.com. If a DNS name is mapped to more than one IP address, you can use any of those addresses, even though people normally use the first one. The reason for choosing the first one is because a DNS name is often mapped to one IP address only. Obtaining the first IP address mapped to a DNS name is achieved using the following code:
HostEntry.AddressList[0]
What's more important, once you get an IPAddress object, you can construct an IPEndPoint object to connect to a remote server. If the connection is successful, the Socket instance will set its Connected property to true. A programmer often checks the value of this property before performing other operations on the socket instance, because a server application can close a connection after a period of time lapses. To close a connection explicitly when you are done with a socket, you use the Close method. Normally, you need to call the Shutdown method prior to invoking Close to flush all pending data.
Sending and Receiving Streams
After your socket is connected to a remote machine, you can send and receive data. To send data in synchronous mode, you use the Send method. The data you send must be placed in an array of bytes. There are four overloads of the Send method, all of which return an Integer indicating the number of bytes sent. The first overload is the simplest and the easiest to use of the four. It has the following signature:


public int Send(byte[] buffer);

where buffer is an array of bytes containing the data you want to send. Using this overload, all data in the buffer will be sent. The second overload allows you to send all data in the buffer and specify the bitwise combination of the System.Net.Sockets.SocketFlags enumeration members. It has the following signature:


public int Send(byte[] buffer, SocketFlags socketFlags);

The third overload allows you to send all or part of the data in the buffer and specify the bitwise combination of the SocketFlags enumeration.


public int Send( byte[] buffer, int size, SocketFlags socketFlags );

In this overload, size is the number of bytes to be sent.
The last overload is similar to the third overload, but it also allows you specify an offset position in the buffer to begin sending data. Its signature is as follows:


public int Send( byte[] buffer, int offset, int size, SocketFlags socketFlags );

In this overload, offset is the offset position. To receive data synchronously, you use the Receive method. This method also has four overloads, which are similar to the Send method overloads. The signatures of the overloads are as follows:


public int Receive(byte[] buffer);
public int Receive(byte[] buffer, SocketFlags socketFlags);
public int Receive( byte[] buffer, int size, SocketFlags socketFlags );
public int Receive( byte[] buffer, int offset, int size, SocketFlags socketFlags );


When using the Receive method, you can use the Socket class' Available property, which specifies the number of bytes of data received and is available to be read.
Summary
This article introduced the System.Net.Sockets.Socket class and some other supporting classes from the System.Net namespace. Socket is used to easily access the network from your .NET application. You have also learned how to instantiate a Socket object and how to send and receive streams

Thursday, June 5, 2008

Asynchronos Calls in C#

Customers hate to wait and are turned off by poor performance. .NET addresses this issue with asynchronous communication support. Get started with C#.
Several classes in the .NET Framework Base Class Library (BCL) provide both synchronous and asynchronous method signatures. Because a synchronous method call can create a delay in program flow, an asynchronous approach may be better in certain situations, such as when a program needs to send out requests to multiple Web services. This article will show you how to use asynchronous method calls for .NET development with C#.
Synchronous vs. asynchronous A synchronous method call waits for the method to complete before continuing with program flow, whereas an asynchronous method call will return immediately so that the program can perform other operations while the called method completes its work.
The synchronous version of the Resolve method has the following signature: public static IPHostEntry Resolve( string hostName );
The IPHostEntry method accepts a single argument, the hostName, which can be either a DNS name (www.mydomain.com) or an IP address in dotted-quad notation (such as 10.10.14.2). It returns an IPHostEntry object. The IPHostEntry object members may be used to retrieve the host name, IP addresses, and other information related to this particular host.
You could use the Resolve method synchronously in your program with code such as the following: IPHostEntry host = Dns.Resolve(“10.10.14.2”); Console.WriteLine(host.HostName);
The problem here is that as soon as Dns.Resolve is called, your program will block execution until the Resolve method completes its work and returns an IPHostEntry object, which may take several seconds. Since DNS resolution involves network access, this method call can potentially be affected by factors such as network latency and other issues that can delay operation and is thus well suited to the asynchronous approach.
Asynchronous design Asynchronous communication between components requires a design pattern so that the program can determine when or if a called method has completed executing. This design pattern allows the program to obtain any results returned by the method. This capability is especially useful when using Web services because your program can send requests to multiple Web services at once and wait until each returns results before continuing with program execution.
In this scenario, the Web services used may be provided on networks with different degrees of latency and by various companies across the Internet. Consequently, the length of time required to complete a request is affected by several factors that are beyond your program’s control.
The asynchronous design pattern used in the .NET Framework is characterised by the use of BeginXXXX and EndXXXX methods, where XXXX is the name of the synchronous version of the method. Let's take a closer look at the asynchronous approach.
The BeginResolve method and IAsyncResult To avoid blocking your program’s execution (as in the first example), you can opt to use the asynchronous version of the Resolve method: BeginResolve. This method has the following signature: public static IAsyncResult BeginResolve( string hostName, AsyncCallback requestCallback, object stateObject );
The BeginResolve method accepts the same parameter as the synchronous version, hostName, but adds two more parameters that are part of the asynchronous design pattern: the requestCallback and stateObject parameters. We will discuss these shortly, but first I’d like to call your attention to the return value, an IAsyncResult interface.
When you call a method asynchronously, the call immediately returns to your program, before the method being called has a chance to finish (or sometimes even start). By definition, there is no IPHostEntry object for the BeginResolve method to return, so instead it returns a waitable object, the IAsyncResult interface, which you can use later to retrieve the results of the call. The IAsyncResult interface is defined as follows: public interface IAsyncResult { object AsyncState {get;} WaitHandle AsyncWaitHandle {get;} bool CompletedSynchronously {get;} bool IsCompleted {get;} }
The first property in this interface, AsyncState, will return the same object that was passed into the BeginResolve method's stateObject parameter. There are no restrictions on this argument value. It can be anything the program wants to use to track this particular method call. It is not used or manipulated by the called method in any way.
The second property in the IAsyncResult interface, the AsyncWaitHandle, can be used by your program to wait on the method to complete by passing it to one of the WaitHandle class’ methods, WaitAll, WaitOne, or WaitAny. This is useful if you are sending several asynchronous method calls to operate in parallel and would like to make sure they all complete before continuing your own program’s work, especially if your program’s continued operation is dependent upon the results of one or more of these calls.
The third property in the interface, CompletedSynchronously, returns a Boolean value indicating whether the method was able to be completed by the time the BeginResolve method returned.
The fourth property, IsCompleted, returns a Boolean value indicating whether the work being done by the method has completed. This is useful if you use a polling mechanism to determine whether the asynchronous call has completed.
Actually, there are four ways to make and complete .NET asynchronous calls. You can use polling (the IsCompleted property) or a callback delegate (discussed below), you can use the AsyncWaitHandle to wait on the call to complete, or can call the EndXXXX method yourself with the IAsyncResult returned from the BeginXXXX method and have it wait on the call to complete. The difference between these last two techniques is that if you perform the wait yourself (using the AsyncWaitHandle), you can “wake up” every now and then based on a timeout and decide at that point whether you really want to wait any longer.
EndResolve method and AsyncCallback delegate One of the ways to complete an asynchronous method call is to supply an AsyncCallback delegate to the BeginXXXX method. This delegate has the following signature: public delegate void AsyncCallback( IAsyncResult ar );
By providing a method in your program with this signature and creating an AsyncCallback delegate pointing to that method, you can have the asynchronous method call notify your program when it has finished processing. The following code snippet shows how you would call the Dns class BeginResolve method using a callback: AsyncCallback callback = new AsyncCallback(GetResult); IAsyncResult ar = Dns.BeginResolve("10.10.14.2", callback, null); // Do some other work while the above finishes.
When the BeginResolve method finishes executing and has an IPHostEntry object to return, it calls the delegate passed to it allowing us to obtain the result. The following code shows how the GetResult method in our program could be implemented: private void GetResult(IAsyncResult ar) { IPHostEntry host = Dns.EndResolve(ar); }
The Dns class calls the GetResult method when finished resolving the requested IP address, passing the same IAsyncResult interface that was returned from the initial call to BeginResolve. This allows us to call EndResolve using that argument to obtain the result of the call.
Summing up Although you can use either synchronous or asynchronous method calls in .NET, there are times when an asynchronous approach is more efficient. This article has shown how to use asynchronous method calls with C#. In a future article, I will show you how to use the asynchronous design pattern to create your own asynchronous methods for long-running operations.

Add a Serial No column to DataGrid

protected int i = 1;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Text = Convert.ToString(GridView1.PageIndex * GridView1.PageSize + i);
i++;
}

}





Resize Image

You may use this method to resize image and set the maximum side size in pixels when uploading.
You will need a reference to System.Drawing and System.Drawing.Imaging namespaces public void ResizeFromStream(string ImageSavePath, int MaxSideSize, Stream Buffer)
{
int intNewWidth; int intNewHeight; Image imgInput = Image.FromStream(Buffer); //Determine image format
ImageFormat fmtImageFormat = imgInput.RawFormat;
//get image original width and height
int intOldWidth = imgInput.Width; int intOldHeight = imgInput.Height;
//determine if landscape or portrait
int intMaxSide;
if (intOldWidth >= intOldHeight)
{
intMaxSide = intOldWidth;
}
else
{
intMaxSide = intOldHeight;
}
if (intMaxSide > MaxSideSize)
{ //set new width and height double dblCoef = MaxSideSize / (double)intMaxSide;
intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);
intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
}
else
{
intNewWidth = intOldWidth; intNewHeight = intOldHeight;
}
//create new bitmap Bitmap
bmpResized = new Bitmap(imgInput, intNewWidth, intNewHeight);
//save bitmap to disk
bmpResized.Save(ImageSavePath, fmtImageFormat);
//release used resources
imgInput.Dispose(); bmpResized.Dispose(); Buffer.Close();
}

Sql server And Visual Studio Editions

There are 6 SQL Server 2005 Editions:

  • Enterprise Edition
  • Standard Edition
  • Workgroup Edition
  • Express Edition
  • Developer Edition
  • Compact Edition

Visual Studio Editions

  • Visual Studio 2008 Express Editions (VWD, VB, C#, C++)
  • Visual Studio 2008 Standard
  • Visual Studio 2008 Professional
  • Visual Studio Team System 2008 Architecture Edition
  • Visual Studio Team System 2008 Database Edition
  • Visual Studio Team System 2008 Development Edition
  • Visual Studio Team System 2008 Test Edition
  • Visual Studio Team System 2008 Team Suite

The different mechanisms to persist data between user requests in ASP.NET are:

  • Application
  • Cookies
  • Form Post / Hidden Form Field
  • QueryString
  • Session
  • Cache
  • Context
  • View State
  • Control State
  • Web.config and Machine.config Files
  • Profile

Wednesday, June 4, 2008

Code Snippet in asp.net 2.0

What is a “Code Snippet”?
A: A Code Snippet is a reusable block of code. Unlike a static copy-and-paste approach, code snippets allow for dynamic instances of code
by allowing placeholders into mini templates of code. Code snippets are a new feature of Visual Studio 2005.
Q: How do I use a Code Snippet?
A: In the Visual Studio 2005 code editor, you can invoke snippets with [ctrl][k][x] keyboard shortcut. IntelliSense will then display a
context menu displaying the available code snippets to choose. However, most code snippets are available without using the keyboard
shorcut. If you know the shortcut name of the code snippet, simply type the name and press tab to invoke.
Now we will see how we can use snippets here.I will write a small snippet for disconneceted data access with dataset.


1) Open nottepad.
2) Type the code in it and save it as sample.snippet.
http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet”>

DatasetCode snippet for Disconnected data accessBharath RadhekrishnaExpansionSurroundsWith

3) After saving this. Go to visual studio 2005. Click Tools > CodeSnippets manager or ctrl+K, ctrl+B.and add this snippet to library.
4) While you are coding right click the mouse. You will see an option of “insert snippet”. when you click it will tell usto insert the snippet we like. For example if take the above snippet it will be displayed with the name as:“Disconnected Data architecture”.If we click it will display the code as:
SqlConnection cn = new SqlConnection();string selquery = ;SqlDataAdapter da = new SqlDataAdapter(selquery, cn);DataSet ds = new DataSet();da.Fill(ds);So everytime it is not necessary for us to write whole sentence or connections.It will reduce our burden of writing commonly usedcode everytime.

New Line in Tool tip

HTML Source EditorWord wrapHi Friends,This is very simple article to show the tooltip wit new lineWhen you make a new line tool tip. Just you have to write a text in title attribute, with enter key. Then you can get the new line.Here is the sample code for to do that






NameIdPlace
Mr.X001INDIA
Mr.Y002INDIA

ASP.NET Validation Controls

ASP.NET validation controls provide an easy-to-use but powerful mechanism of ensuring that data is entered correctly on the forms. There are 6 validation controls included in the ASP.NET 2.0 and ASP.NET 3.5 versions. If you are not familiar with Validation Controls in ASP.NET, here’s a recommended read for you.
Let us see some tips and tricks that can be applied to the validation controls. These tips and tricks are for beginner and intermediate users who have been using validation controls.

Tip 1: Always use Page.IsValid before submitting data. Apart from the other benefits, using it prevents submitting data from old browsers that do not support javascript.

Tip 2: To prevent validation to occur on the click of the Cancel button, set the ‘CausesValidation’ property to false


Tip 3: Use the ‘InitialValue’ property of the RequiredFieldValidator to validate controls like combobox which have a default value.
For eg: If your combobox has a default item called “--Select --“ and you want that the user should select a value other than the default value before submitting the form, then set the ‘InitialValue’ property of the RequiredFieldValidator to
“--Select--“.







Check out more validation control tips and tricks over here
http://www.dotnetcurry.com/ShowArticle.aspx?ID=121