Saturday, July 21, 2012

Microsoft SharePoint Server 2013 Preview is Released

This week Microsoft has unveiled SharePoint Server 2013 Preview along with 2013 Preview versions of Exchange, Lync, Office Web Apps Server, Project, Visio and Office Professional Plus. All these previews brings a Metro-like feel, as well as revamped touch tools intended to make it easier to use the desktop applications on a tablet.

According to Microsoft SharePoint Team Blog, here is a list of new features which are available in this new release.
  1. New SharePoint Experience - Metro Style User Experience
  2. Pervasive Social Networking - Yammer and SharePoint
  3. SkyDrive Pro - Sync and use documents offline in the Windows Explorer
  4. SharePoint Sites - View sites in one place
  5. Projects for Everyone - Task management
  6. FAST Search and Recommendations - Search with FAST
  7. Cloud App Model and Marketplace - build, buy, deploy and manage applications via the new Cloud App Model for the Office 2013
  8. Dynamic Publishing - Multi-device, Multi-lingual intranet and internet sites
  9. In-Place Governance and Compliance - New unified policy management

I have installed SharePoint 2013 and the user experience is some what different when comparing to SharePoint 2010, but it is great. It’s like Windows 8 user experience. I think it will take some time to get familiar with this new release and I am pretty sure it is worth it.

Central Administration
Team Site

For more information on all the new 2013 product preview releases, visit Try more products page.

Happy Coding.

Regards,
Jaliya

Friday, July 20, 2012

Writing blog posts with Windows Live Writer

For all this time, I was using Blogger post editor to write my posts. It is a nice editor, but it has some difficulties when writing source codes. Today one of my good friends, Melick told me about this Windows Live Writer which comes with Windows Live Essentials.

I have Windows Live Essentials in my laptop for sometime and the funny thing is I did not know about this nice tool until today. Just now I started using it and I must say, it is the nicest blog editor I have ever seen. The capabilities of Windows Live Writer is really amazing and it has the ability to connect to almost any kind of blog and to do all the things related to a posts without touching the browser. And there are a lot of nice free plug-ins available to make your post writing time more enjoyable.

For those who haven’t started using Windows Live Writer, why not give it a try. I am sure you will like it. And Thank you so much Melick for showing me this nice tool.

Happy Coding.

Regards,
Jaliya

Tuesday, July 10, 2012

Connecting to an Instance of SQL Server by Using SQL Server Authentication in C#

I am pretty sure that you can find many articles about how to connect to a specific database on a SQL Server instance in C#. But you won't be able to find many about how to connect to a specific SQL Server instance in C#. So thought to write a post about how to connect to a SQL Server Instance in C#.

Before starting off with the topic, I think it's better to refresh the knowledge in SQL Server instances.

Mainly there are two types of SQL Server instances. First is the Default Instance which is identified solely by the name of the computer on which the instance is running, it does not have a separate instance name. The second is the Named Instance. All instances of the database engine other than the default instance are identified by an instance name specified during installation of the instance. We can only have one default instance, but we can have many named instances and each SQL Server instance has its own copy of the server files, databases and security credentials.

Now let's move into the topic. We can connect to a SQL Server instance using SQL Server Management Objects (SMO). SMO is a collection of objects that are designed for programming all aspects of managing Microsoft SQL Server.

So this is how you can connect to the Default, Named and Remote Server Instances using SQL Server Authentication. First you need to add references to following dll's which can be found on "C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies" folder.
  1. Microsoft.SqlServer.Smo.dll
  2. Microsoft.SqlServer.ConnectionInfo.dll
  3. Microsoft.SqlServer.Management.Sdk.Sfc.dll
using System;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

namespace ConnectToSQLInstance
{
class Program
{
static void Main(string[] args)
{
string username = "sa";
string password = "sa";
string instanceName = "instance_name";
string remoteSrvName = "remote_server_name";

/*----------------connect to default instance----------------*/
Server oServer = new Server();
// set to true for Windows Authentication
oServer.ConnectionContext.LoginSecure = false;
oServer.ConnectionContext.Login = username;
oServer.ConnectionContext.Password = password;
// connection is established
Console.WriteLine(oServer.Information.Version);

/*----------------connect to named instance----------------*/
ServerConnection oServerConnection = new ServerConnection();
// connects to named instance
oServerConnection.ServerInstance = @".\" + instanceName;
oServerConnection.LoginSecure = false;
oServerConnection.Login = username;
oServerConnection.Password = password;
Server oServerNamed = new Server(oServerConnection);
// connection is established
Console.WriteLine(oServerNamed.Information.Version);

/*----------------connect to default instance----------------*/
// In here remote server name / ServerInstance needs to be specified
ServerConnection oRemoteServerConnection = new ServerConnection(remoteSrvName);
oRemoteServerConnection.LoginSecure = false;
oRemoteServerConnection.Login = username;
oRemoteServerConnection.Password = password;
Server oServerRemote = new Server(oRemoteServerConnection);
// connection is established
Console.WriteLine(oServerRemote.Information.Version);
}
}
}
Hope this helps.

Happy Coding.

Regards,
Jaliya

Friday, July 6, 2012

MS SQL Server table browser and a Stored Procedure Generator

Isn't it nice to have some simple tool which will allow you to easily browse through your connected MS SQL Servers' all databases and tables? And then view the table information in design mode such as column names, column types, column sizes and primary keys etc? And finally to create "INSERT", "UPDATE", "DELETE" and "SELECT" stored procedures for a selected table in a single button click?

Since I am little bit lazy in doing things related to MS SQL, I wanted an application to make my life easier when writing Stored Procedures and all. So I have wrote this simple tool, in which it's main task is to generate Stored Procedures which ultimately ended up as a "MS SQL Server table browser and a Stored Procedure Generator".

This tool has the ability to connect to default, named or remote instances of SQL Server database engine. (Please note that, only the SQL Server Authentication is supported in this version.)  Then it can be used to browse databases and tables of connected SQL Server instance and then to view tables design in an easier manner. And finally it has the capability to generate  "INSERT", "UPDATE", "DELETE" and "SELECT" stored procedures for a selected table.


Connect To Server

Database and Table Browser

Table Design Viewer

Stored Procedure Generator


I have uploaded the installer to my skydrive, so anyone can help themselves with this tool. I have ran couple of tests with generated stored procedures and the results were very much satisfying. But if you come across with any kind of bug, please let me know as I am planning to enhance this tool further. It is really appreciated.

     Download

Happy Coding.

Regards,
Jaliya

Tuesday, July 3, 2012

How to open a new browser window from the code behind file - ASP.NET & C#

Sometimes we face this situation where we want to fill some values into some variables and we want to send those values to a web page where it will open in a new window. If you want to do all this in a single button click, there is something you should think about.

In javascript, there is window.open() method, which you  can use to open the new window in any way you prefer. But since that would be a client side event, it will run before the server side events. Which means if you write all the session variable assigning part in your server side click event which is,

OnClick
it will fire after executing client side click event which is,
OnClientClick
So as a solution to that, this is the code snippet to open a new window from the code behind file under the server side click event.
ClientScript.RegisterStartupScript(this.GetType(), "PopupWindow", "<script language='javascript'>window.open('YourPage.aspx','Title','width=600,height=300')</script>");
Happy Coding.

Regards,
Jaliya

Thursday, June 21, 2012

Web services vs WCF (Windows Communication Foundation) services

When we are talking about WCF and Web Services, are we talking about the same thing? The answer is NO. Today I will be explain the differences between these two and the advantages that WCF has over Web services.

ASP.NET provides .NET Framework class libraries and tools for building Web services, as well as facilities for hosting these services within Internet Information Services (IIS) while WCF provides .NET Framework class libraries, tools and hosting facilities for enabling software entities to communicate using any protocols, including those used by Web services.

WCF supports more protocols for transporting messages than Web services. Web services only support sending messages using the HTTP. WCF supports sending messages using HTTP, as well as the TCP, Named Pipes, and Microsoft Message Queuing (MSMQ). Most importantly, WCF can be extended to support additional transport protocols.

Since Web Services use standard XML, they are platform-independent and language-independent. They don't care about the consuming application as long as they are calling the Web services over HTTP. WCF can be hosted only under the Windows environment, but it can be consumed by clients of different languages and different platforms.

Another significant thing is a WCF service can have one or more WCF endpoints, so one address for each end point. But a Web service can have only one address at one point at a time.

For more information,
   Migrating ASP.NET Web Services to WCF
   Multiple endpoints -WCF

Happy Coding.

Regards,
Jaliya

Monday, June 4, 2012

Asynchronous Programming and Callback Methods with Delegates in C#

My previous post was about Delegates in C# and today I thought of writing about one nice technique which is available with Delegates, and that is "Asynchronous Programming". In one of my previous posts, I wrote about Asynchronous Programming with C# 5.0 and that is with "async" modifier and "await" operator. 

Using Delegates we can call a synchronous method in an asynchronous manner and Callback methods are used to notify the caller, when an asynchronous work is completed. First let's get an idea on how these synchronous and asynchronous methods works.

When we call a synchronous method it will get executed on the same thread as the caller. But what happens here is, caller thread gets blocked while the called method is active. When we call a method in an asynchronous way, the .NET framework obtains a thread from the thread pool for the method invocation and delivers the in parameters passed by the calling code. The asynchronous thread can then run the method in parallel to the calling thread. Here what happens is caller thread is not blocked. The call returns immediately to the caller. If the asynchronous method returns some value, the calling thread must be able to handle it. The .NET asynchronous feature supports two mechanisms: that calling thread can either ask for the results, or the asynchronous method can deliver the results to the calling thread when the results are ready.

Delegate's do this asynchronous call invocation using delegate's BeginInvoke method.
First we have to define a delegate with the same signature as the method we want to call. The common language runtime automatically defines BeginInvoke and EndInvoke methods for this delegate, with the appropriate signatures. If a callback method has been specified in the call to the BeginInvoke method, the callback method is called when the target method ends. In the callback method, the EndInvoke method obtains the return value and any input/output or output-only parameters. If no callback method is specified when calling BeginInvoke, EndInvoke can be called from the thread that called BeginInvoke.

I think it's better if we go by examples.

Let's take the following method under the class i have created named "MyClass".
public class MyClass
{
    public string MyMethod(string s)
    {
        Thread.Sleep(5000);
        return "Hello" + s;
    }
}
I have a public method, which will return a string and accepts a string. Then I am creating a delegate for this method.
public delegate string MyDelegate(string s);
Then I am creating my delegate object.
MyClass oMyClass = new MyClass();
MyDelegate oMyDelegate = new MyDelegate(oMyClass.MyMethod);
Now I am all done for calling the method asynchronously. As I have told you, the CLR automatically defines a BeginInvoke method for this delegate object which would have a signature like this.
IAsyncResult oMyDelegate.BeginInvoke(string s, AsyncCallback callback, Object @object);
In here, the first parameter is the methods parameter. The second parameter is an AsyncCallback delegate that references a method to be called when the asynchronous call completes. The third parameter is a user-defined object that passes information into the callback method.

Let's take a complete example.
using System;
using System.Threading;

namespace MyDelegateExample
{
    public delegate string MyDelegate(string s);

    class Program
    {
        static void Main(string[] args)
        {
            MyClass oMyClass = new MyClass();
            MyDelegate oMyDelegate = new MyDelegate(oMyClass.MyMethod);
            Console.WriteLine("Going to call the method Asynchronously.");
            oMyDelegate.BeginInvoke("Jaliya", new AsyncCallback(oMyClass.MyCallbackMethod), oMyDelegate);
            Console.WriteLine("Back on Main.");
            Thread.Sleep(15000);
        }
    }

    public class MyClass
    {
        public string MyMethod(string s)
        {
            Thread.Sleep(5000);
            return "Hello " + s;
        }

        // call back method to capture results
        public void MyCallbackMethod(IAsyncResult iar)
        {
            // cast the state object back to the delegate type
            MyDelegate del = (MyDelegate)iar.AsyncState;

            // call EndInvoke on the delegate to get the results
            string result = del.EndInvoke(iar);

            // display the results
            Console.WriteLine("Delegate returned result: {0}", result);
            Console.WriteLine("Asynchronous Call Completed.");
        }
    }
}

Output :

Output
In here what happens is in my BeginInvoke call, I have mentioned my Callback method. My main program will continue running in parallel and when the asynchronous call is completed, it will execute the "MyCallbackMethod". In that method, I have called the EndInvoke method to retrieve the results of the asynchronous call. I have put a thread sleep in my Main to keep the program running. So I can see the output from my asynchronous call.

Let's take this example.
using System;
using System.Threading;

namespace MyDelegateExample
{
    public delegate string MyDelegate(string s);

    class Program
    {
        static void Main(string[] args)
        {
            MyClass oMyClass = new MyClass();
            MyDelegate oMyDelegate = new MyDelegate(oMyClass.MyMethod);
            Console.WriteLine("Going to call the method Asynchronously.");
            IAsyncResult IAsyncResult = oMyDelegate.BeginInvoke("Jaliya", null, null);
            Console.WriteLine("Back on Main.");
            IAsyncResult.AsyncWaitHandle.WaitOne();
            string result = oMyDelegate.EndInvoke(IAsyncResult);
            Console.WriteLine(result);
            Console.ReadLine();        
        }
    }

    public class MyClass
    {
        public string MyMethod(string s)
        {
            Thread.Sleep(5000);
            return "Hello " + s;
        }
    }
}

Output :

Output

The difference here is there is no callback method.
AsyncResult.AsyncWaitHandle.WaitOne();
will hold the Main from executing further until asynchronous call completes. After that completes only it will move executing forward.

I hope you all got a good understanding in how Asynchronous Programming and Callback Methods works with Delegates.

Appreciate your feedback.

Happy Coding.

Regards,
Jaliya

Saturday, May 26, 2012

An Introduction to Delegates in C#

If you are familiar with Function Pointers in C or C++ and if you are wondering is there something similar to Function Pointers in C#, Of course there is. It's Delegates. Delegates in one of the nicest techniques in C#, but some find hard to understand the real beauty behind it. So thought to write an Introduction about delegates in C#.

Basically a delegate is a type that references a method or methods. A delegate defines a method signature, and it has the capability of referencing to a methods/methods which has the same method signature as in the delegate. When you instantiate a delegate, you can associate its instance with any method with a compatible signature. Then you can invoke the method through the delegate instance. What really happens here is delegate encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

Because of this behavior, delegates gives us many advantages. One thing is you can pass methods as arguments to other methods. Second is since we are using delegate to invoke the method, it will hide the method from the caller. Another nice advantage would be, using delegates we can call methods asynchronously.

Now let's see delegates in action. First, this is how we define delegates.
public delegate void MyDelegate(string s);
What this delegate means is, it has the capability to encapsulate any method that takes one string value and returns no value. Always remember delegates only has the capability to refer methods in which return type matches delegates return type and parameters matches delegates parameters.

Now let's take this simple but full example.
namespace MyDelegateApplication
{
    public delegate void MyDelegate(string s);

    class Program
    {
        static void Main(string[] args)
        {
            MyClass oMyClass = new MyClass();
            MyDelegate oMyDelegate = new MyDelegate(oMyClass.MyMethod);
            oMyDelegate("I am called through a Delegate.");
        }
    }

    public class MyClass
    {
        public void MyMethod(string s)
        {
            Console.WriteLine(s);
            Console.ReadLine();
        }
    }
}
Output :

calling a method through adelegate

In here I have defined a namespace level delegate, so it as accessible from all the classes in namespace. I have created two classes here to make it easy to understand. In "MyClass", I have wrote a method in which method signature is same as the delegate. Then from my Main method, I have created an instance of "MyClass", so I can access it's methods. Then I am creating an instance of "MyDelegate", and I am passing the method which I need to invoke through "MyDelegate". Then I am invoking my method through the delegate. It's simple as that.

Multicasting


Multicasting is, as I mentioned before delegates has the capability to refer more than one method at a time. A multicast delegate maintains a list of functions that will be called when the delegate is invoked. We can add or remove the pointing methods of delegate using "+" and "-" operators. To demonstrate the delegates multicasting, I will just modify the above example as follows.
namespace MyDelegateApplication
{
    public delegate void MyDelegate(string s);

    class Program
    {
        static void Main(string[] args)
        {
            MyClass oMyClass = new MyClass();
            MyDelegate oMyDelegate = null;
            oMyDelegate += new MyDelegate(oMyClass.MyFirstMethod);
            oMyDelegate += new MyDelegate(oMyClass.MySecondMethod);
            oMyDelegate("I am called through a Delegate.");
        }
    }

    public class MyClass
    {
        public void MyFirstMethod(string s)
        {
            Console.WriteLine(string.Format("{0}-First Method", s));
            Console.ReadLine();
        }

        public void MySecondMethod(string s)
        {
            Console.WriteLine(string.Format("{0}-Second Method", s));
            Console.ReadLine();
        }
    }
}
Output :

Multicasting
So that's the basics of delegates in C#. Hope you all got found this post helpful.

Happy Coding.

Regards,
Jaliya

Wednesday, May 16, 2012

Accessing Report Server using Report Server Web Service - Microsoft SQL Server 2008R2

Today I am going to write about how to access SQL Server Report Server through Report Server Web service. You can access all the full functionality of the report server through this Report Server Web service. The Report Server Web service is an XML Web service with a SOAP API. It uses SOAP over HTTP and acts as a communications interface between client programs and the report server.

The Microsoft SQL Server 2008R2 Report Server Web service provides two endpoints, one is for report management and the other one is for report execution.
  1. ReportService2010
    • The ReportService2010 endpoint contains methods for managing objects in a Report Server in either native or SharePoint integrated mode. The WSDL for this endpoint is accessed through  http://server/reportserver/ReportService2010.asmx?wsdl.
  2. ReportExecution2005
    • The ReportExecution2005 endpoint allows developers to programmatically process and render reports in a Report Server. The WSDL for this endpoint is accessed through  http://server/reportserver/ReportExecution2005.asmx?wsdl.
Previous versions of Microsoft SQL Servers' has several versions of Report Server Web service endpoints. For example ReportService2005 and ReportService2006. But ReportService2005 and ReportService2006 endpoints are deprecated in SQL Server 2008 R2. The ReportService2010 endpoint includes the functionalities of both endpoints and contains additional management features.

Now, I will move into how to access Report Server using Report Server Web Service. I have created sample web site and in the Default.aspx page I have put a single button. First what I would do is, I will add a Service Reference to Report Server Web Service and the endpoint I am going to use is ReportService2010.

I will right click on my Web Site Project and will click on Add Service Reference.

Add Service Reference
In here, I have put http://server/reportserver/ReportService2010.asmx as address, I did not add ?wsdl to the end of the address, because both are valid formats.

Now if you observe the Web.config file, you will see that following part is added.
<system.serviceModel>
  <bindings>
    <basicHttpBinding>
      <binding name="ReportingService2010Soap" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
        <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
        <security mode="None">
          <transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
          <message clientCredentialType="UserName" algorithmSuite="Default"/>
        </security>
      </binding>
    </basicHttpBinding>
  </bindings>
  <client>
    <endpoint address="http://server/ReportServer/ReportService2010.asmx" binding="basicHttpBinding" bindingConfiguration="ReportingService2010Soap" contract="ReportService2010.ReportingService2010Soap" name="ReportingService2010Soap"/>
  </client>
</system.serviceModel>
Now in my button click event I am writing following code.
using System.Net;
using ReportService2010;

protected void btnListChildren_Click(object sender, EventArgs e)
{
    NetworkCredential clientCredentials = new NetworkCredential("username", "password", "domain");
    ReportService2010.ReportingService2010SoapClient client = new ReportService2010.ReportingService2010SoapClient();
    client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
    client.ClientCredentials.Windows.ClientCredential = clientCredentials;
    client.Open();
    TrustedUserHeader t = new TrustedUserHeader();
    CatalogItem[] items;
    // I need to list of children of a specified folder.
    ServerInfoHeader oServerInfoHeader = client.ListChildren(t, "/", true, out items);
    foreach (var item in items)
    {
        // I can access any properties of item
    }
}
Now again in my Web.config file I need to do some modifications. If not I might get this type of error when I am executing my button click event.
Request is unauthorized.
I am modifying the Web.config file as follows.
<security mode="TransportCredentialOnly">
  <transport clientCredentialType="Ntlm" proxyCredentialType="None" realm=""/>
  <message clientCredentialType="UserName" algorithmSuite="Default"/>
</security>
That's all. Now when I run the Web Site I can get the list of children in the parent folder through the Report Server Web Service. Through this Web Service we can access all the full functionality of the report server. Isn't it great.

Happy Coding.

Regards,
Jaliya

Tuesday, May 15, 2012

ASP.NET GridView Row Edit mode

It's great to have CRUD operations in a single place and ASP.NET GridView provides this feature in a nice way. Without much pre writing I will just start off with the topic.

I have a GridView in my page and I have named it "GridViewUsers". First I will load values to a DataSet and Bind my GridView's Data Source to that DataSet in Page Load event. Please note that in here I will be writing only the necessary codes.
using System;
using System.Web.UI.WebControls;
using System.Data;

dbConnection odbConnection = new dbConnection(); // calling my dbConnection class

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DataSet ds = GetAllUsers();
        gridViewUsers.DataSource = ds;
        gridViewUsers.DataBind();
    }
}

private DataSet GetAllUsers()
{
    DataSet ds = new DataSet();
    try
    {
        string selectQuery = "SELECT USER_ID,FIRST_NAME,LAST_NAME,GENDER From USERS";
        ds = odbConnection.ExecuteSelectQuery(selectQuery);
    }

    catch (Exception ex)
    {
        throw ex;
    }
    return ds;
}
Now I will  modify some properties in the GridView from the aspx file.
<asp:GridView ID="GridViewUsers" runat="server"
     AutoGenerateColumns="False"
     GridLines="None"
     AllowPaging="True">
</asp:GridView>
I have put,
AutoGenerateColumns="False"
here, because I need to write column names I want to show in the GridView. If I put,
AutoGenerateColumns="True"
I don't need to write any custom code and all the columns I have selected in my query will be appeared as it is in my GridView. Ok, Now what my target is, I will have some rows in my GridView and initially it will be read only. And in each each row, there will be a single column which will be used to modify the selected row. It will have a single button in read only mode which is "Edit", And when I click on Edit, the row will change into Edit mode. The editable fields of the row will change into edit mode and the "Edit" button will disappear. Instead of  "Edit" button, three more buttons will come to the picture which will be "Update","Delete" and "Cancel".

I hope you all got the target well, let's start achieving it.

So basically we will have two modes and some custom controls. In GridView, to define custom controls with other columns we are using "TemplateField" which is like a place holder. Under "TemplateField", I will have two properties which are "ItemTemplate" and "EditItemTemplate". "ItemTemplate" property is used to control the appearance of a data item and "EditItemTemplate" property is used to control the appearance of a data item in Edit mode. So here is my complete code for the GridView.
<asp:GridView ID="gridViewUsers" runat="server"
     AutoGenerateColumns="False"
     AllowPaging="True" Height="134px" Width="536px" 
     onrowediting="gridViewUsers_RowEditing"
     onrowcancelingedit="gridViewUsers_RowCancelingEdit"
     onrowdeleting="gridViewUsers_RowDeleting"
     onrowupdating="gridViewUsers_RowUpdating">

     <Columns>
          <asp:TemplateField HeaderText="User ID">
               <ItemTemplate>
                    <asp:Label runat="server" ID="lblUserID" Text='<%# Eval("USER_ID") %>' />
               </ItemTemplate>
          </asp:TemplateField>

          <asp:TemplateField HeaderText="First Name" >
               <ItemTemplate>
                    <asp:Label ID="lblFirstName" runat="server" Text='<%# Eval("FIRST_NAME") %>' />
               </ItemTemplate>
               <EditItemTemplate>
                    <asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FIRST_NAME") %>' />
               </EditItemTemplate>
          </asp:TemplateField>

          <asp:TemplateField HeaderText="Last Name" >
               <ItemTemplate>
                    <asp:Label ID="lblLastName" runat="server" Text='<%# Eval("LAST_NAME") %>' />
               </ItemTemplate>
               <EditItemTemplate>
                    <asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LAST_NAME") %>' />
               </EditItemTemplate>
          </asp:TemplateField>

          <asp:TemplateField HeaderText="Action">
               <ItemTemplate>
                    <asp:ImageButton ID="btnEdit" runat="server" Text="Edit" CommandName="Edit" ImageUrl="~/images/iconEdit.png" ToolTip="Edit" AutoPostBack="true" />
               </ItemTemplate>
               <EditItemTemplate>
                    <asp:ImageButton ID="btnUpdate" runat="server" Text="Update" CommandName="Update" ImageUrl="~/images/iconUpdate.png" ToolTip="Update" AutoPostBack="true" />
                    <asp:ImageButton ID="btnDelete" runat="server" Text="Delete" CommandName="Delete" ImageUrl="~/images/iconDelete.png" ToolTip="Delete" AutoPostBack="true" />
                    <asp:ImageButton ID="btnCancel" runat="server" Text="Cancel" CommandName="Cancel" ImageUrl="~/images/iconCancel.png" ToolTip="Cancel" AutoPostBack="true" />
               </EditItemTemplate>
          </asp:TemplateField>
     </Columns>
</asp:GridView>
So here what I have done is, UserID is the primary key. So in it there is no Edit mode. For all other columns there is a "EdiItemTemplate". And in "ItemTemplate", I have used a Label to display the value. Because it is read only. And in "EdiItemTemplate", I have used a TextBox to display value, because it should be editable. In here last "TemplateField" is the column which will contain controls for modifying the row. In "ItemTemplate", it will contain a single button which will trigger GridView EDIT command and in "EdiItemTemplate", it will contain three buttons which will trigger GridView UPDATE, DELETE and CANCEL commands. I have used image buttons here to make the UI bit nicer.

Now here is my code behind code file. First it is gridViewUsers_RowEditing event.
protected void gridViewUsers_RowEditing(object sender, GridViewEditEventArgs e)
{
    gridViewUsers.EditIndex = e.NewEditIndex;
    BindGrid();
}
In here GridViewEditEventArgs will give the row number I am editing by it's NewEditIndex property. Then I am assigning that row number to GridView's EditIndex property which will put the appropriate row into the Edit Mode. Then I am calling my custom method which I am going to write in few minutes and it will bind the GridView again.
Then it's gridViewUsers_RowUpdating event and gridViewUsers_RowDeleting event.
protected void gridViewUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    Label userID = (Label)gridViewUsers.Rows[e.RowIndex].FindControl("lblUserID");
    TextBox txtFirstName = (TextBox)gridViewUsers.Rows[e.RowIndex].FindControl("txtFirstName");
    TextBox txtLastName = (TextBox)gridViewUsers.Rows[e.RowIndex].FindControl("txtLastName");
        
    string updateQuery = "update query";

    gridViewUsers.EditIndex = -1;
    BindGrid("UPDATE", updateQuery);
}
protected void gridViewUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    Label UserID = (Label)gridViewUsers.Rows[e.RowIndex].FindControl("lblUserID");
    string deleteQuery = "delete query";

    gridViewUsers.EditIndex = -1;
    BindGrid("DELETE", deleteQuery);
}
In these two events, first line is to get the primary key's value of the current row item being modified.
protected void gridViewUsers_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    gridViewUsers.EditIndex = -1;
    BindGrid();
}
Then my BindGrid method. I have two optional parameters here which will get query type and the query. If the query type is "UPDATE" or "DELETE", it will execute the query and in the finally block it will bind the GridView.
private void BindGrid(string queryType = "default", string query = "default")
{
    DataSet ds = null;

    try
    {
        if (queryType == "UPDATE" || queryType == "DELETE")
        {
            odbConnection.ExecQuery(query);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        string selectQuery = "SELECT USER_ID,FIRST_NAME,LAST_NAME,GENDER From USERS";

        using (ds = oDBConnection.SelectQuery(selectQuery))
        {
            gridViewUsers.DataSource = ds;
            gridViewUsers.DataBind();
        }
    }
}

So that's all about ASP.NET GridView Row Edit mode. This is what you will get at the end.

gridViewUsers

gridViewUsers Edit Mode

Happy Coding.

Regards,
Jaliya