Cyber Security & Dot Net Security

Thursday, September 30, 2010

How to Block URLs in Firefox

Mozilla's Firefox is a highly-used Web browser that you can use on your Mac or Windows operating system to take advantage of the enhanced security that the browser provides. With Firefox, you can keep websites from loading in your browser window by installing an "add-on," which is a small application that works with Firefox to perform a specific task. Using the Firefox toolbar, you can install your own add-on to block URLs in your browser in just a few clicks.


Instructions

  1. Launch your Firefox Web browser, select "Add-ons" from the "Tools" menu and click the "Get Add-ons" tab.

  2. Type in a term like "block URLs" or "block websites" in the search box and click the search button to get a listing of all the relevant extensions, such as BlockSite and SimpleBlock, that perform this task.

  3. Read through the description of each add-on to determine the one that works best for you and click the "Add to Firefox" button next to your choice.

  4. Click the "Install Now" button and then click the "Restart Firefox" button to make sure the add-on is installed on your browser. When Firefox starts again, highlight your add-on and click the "Install" button again.

  5. Click the "Options" button and follow the prompts to enter the URL addresses that you want to block.

Why Security Can Bring You More Clients

It is an alarming fact that some businesses settle for the minimum when it comes to securing their systems. There are many ways that someone can hack into a computer system, but not every business person seems to realise this.
For many businesses, their way of coping with this aspect of safety is to assume they are safe until they discover otherwise. Unfortunately when that happens it is often too late to prevent the amount of damage it can do to the business in question.
This is where the issue of security is often not looked at in great depth. For example, someone who hasn’t done their research might think that the way to cope with a security breach is to get an expert in to solve it. This means that things can get back to normal as soon as possible.
That may be correct in principle, but in fact it does not even begin to cover the damage that has been done. Just imagine the amount of business that could have been lost in the meantime. How many customers are now doing business elsewhere because of the short-sighted approach to cyber security?
This is the main reason why you can actually benefit from taking good care of your security issues. The more you can reassure your customers that every potential problem is being combated, the more you will do business as a result. Your clients will take security very seriously, and if you cannot reassure them that you take it seriously too, they will go elsewhere.

Some companies use the best internet security consultants around to give them reason to promote this side of their business. Let’s say there are two companies that are virtually identical, and one offers better security protection for online transactions than the other one does. Which one do you think will get the most business? And if that one chooses to highlight the effort they put into their security, won’t that tip the balance towards more orders?
You can see why security is such a big issue for many companies – even if some don’t realise it. It is the degree of reassurance that it gives a person that really makes the difference. Someone who is considering whether or not to use a particular company can be swayed by that detail alone.
So how much attention do you pay to the security of your own company? Do you have an experienced company on board to check out how secure your systems are on a regular basis? If you don’t, you need to ask yourself why. How much do you value your livelihood? It could be on the line if you don’t take security seriously enough.
If you know you are lacking in this area, make a pact to do something about it now. Review your procedures, call in the experts and make sure you are doing everything you can. It is always best to cover all your bases in this way.

Why You Need To Know What The Cyber Criminals Are Doing

How aware are you of what the latest threats are to your internet security systems?

If you are looking puzzled then it is time you took positive steps to start discovering what the cyber criminals’ latest techniques are, because if you don’t you will be in a much weaker position when it comes to protecting your own website and business from their reach.

So how do you keep up with what is going on?
The first thing you can do is to keep tabs on the news – more specifically, news sources which focus on the internet and what is going on with regards to security issues. If the source is a reliable one then you will know what aspects of a business or a website the criminals are currently targeting, and you will be able to take the right steps to prevent yourself from becoming a victim before it actually happens.

The second thing that you can do is more pro-active than that however, and it involves hiring a professional company to come in and check whether your business and data is secure on a regular basis. This will obviously cost money and it is money that some businesses are not willing to pay; however when you consider what you are getting for that money you can see that it is a priceless service that could well prevent your business from losing thousands if a hacker did manage to break through.

The problem is that if you want to know what the cyber criminals are up to, you need to do the research yourself. You need to know where to look to get that information, and you need to be sure that it is correct. All of that takes up valuable time, so why not hire a service which concentrates on providing network, wireless, VoIP and application security solutions to do all the hard work for you?

The benefits of this are obvious. An experienced company will be able to keep up with developments that the cyber criminals and hackers have made, and they will know exactly how to combat them before they happen to you. They will have far more knowledge about the situation than you could ever hope to have, purely because this is their profession and they rely on being at the cutting edge of website and business protection when it comes to this type of criminal.

So you can see that it is vital to know what this breed of criminal is up to, although you don’t have to do all the hard work yourself. The fee that you would pay for this kind of service is a very small one when you think about the peace of mind it will give you. And of course, you will be able to tell your customers just how secure your website is – which will attract more people than ever to spend money with you.
Before you know it that service will have paid for itself.

How Much Should I Expect to Spend on Web Security?

When addressing the issue of web security there are two ways to phrase the question concerning what to spend on IT security. The first question is: How much should I expect to spend on web security? The second question is: How much will it cost the company if I don’t spend enough on web security? Of course a business not only needs to spend money on system security, but it must be spent on effective security systems and reviews.
In today’s economic climate the issues of security have come to the forefront as web site hackers and computer system attacks grow globally. When looking at the issue of systems and software security, you must consider potential company losses due to online theft, the return on investment for having adequate security, and the need to stay ahead of the brilliant hackers able to manoeuvre their way through even the most sophisticated muli-leveled software systems.
In March 2009 a hacker’s group proved that hacking can reach into a customer data bases without a company even knowing. A UK newspaper, “The Telegraph”, was compromised by a hacking group and the newspaper found out when the nameless hacking group posted screen shots and other information on the internet, gleaned from their hacking of a 700,000 customer base, as proof of their success.
Upon reading the story closer it seems The Telegraph was using a 2-year old third party code that simply was outdated in the world of sophisticated hackers. When hackers obtain access to customer credit card data, personal information, or government identification numbers, it won’t take long before a company finds itself losing business because the targeted market is unwilling to take a chance on accessing their website.

Cost of Doing Nothing
There is a cost to doing nothing when it comes to securing a website. The research shows that up to 10 percent of a company’s IT budget may be dedicated to hardware and software security. In most cases it is probably closer to 3 to 6 percent of the budget. Smaller businesses tend to spend smaller percentages of their IT budget on security because of lack of resources more than anything else.
But the fact is hackers can ruin a small business as well as a large business. Deciding what to spend on a web security system is dependent on a number of factors. One of the overriding factors is the type of business itself. For example, a bank or investment business will need state-of-the-art server, router, and operating system securities in place in addition to regular security assessment and penetration testing.
Even as you read this article, hackers are devising new ways to penetrate firewalls and break into websites in order to steal information. Your business should be working just as hard to protect the system as hackers are working to break in to it. Implementing a security system without regular assessment and upgrades is the same as doing nothing. That is what The Telegraph newspaper discovered with their two-year old system.
Mitigating Risk
Mitigating risk is certainly one of the main reasons for security assessment. The underlying infrastructure and codes, employee access capabilities, and customer use of systems must be reviewed regularly for new vulnerabilities. The most common vulnerabilities include SQL injection, URL manipulation, cross-site scripting cookie poisoning and the database server.
Other factors determining how much should be spent on IT security include the following.
  • Government regulatory compliance
  • Sophistication of system including use of wireless networks, remote access to computer system, dependence
  • Need to assure customers system meets industry security standards and best practices
  • Rate of past incidences of security breaches
  • Size of the potential losses in the event a computer system is attacked
The one thing a company cannot afford to do is to do nothing. Computer data and system protection costs should be budgeted at a rate that gives a company the assurance it can provide customers safe access to its websites and no access to hackers.

How to Block Websites in Mozilla Firefox


Instructions

  1. Open Firefox, click "Tools" then "Add-ons." Click "Get Add-ons" and then "Browse All Add-ons." Type "blocksite" in the search bar after the Mozilla Firefox add-ons website opens and hit "Enter."

  2. Click the "Add to Firefox" button next to the entry for BlockSite. Allow the add-on to load (usually less than 5 seconds), then click the "Install Now" button. Restart Firefox when prompted.

  3. Go to "Tools," then "Add-ons," then click the BlockSite "Preferences" button after Firefox restarts. Make sure the "Blacklist" radio button is ticked, as well as "Enable BlockSite," "Enable warning messages," and "Enable link removal."
  4. Check "Enable authentication," then enter a password if you would like to keep other users from deleting blocked websites or changing the settings in BlockSite without your permission.

  5. Click the "Add" button, enter the URL of the website you would like to block, then click "OK." Repeat to add more sites, or click the "Clear" button to delete the list. Once the list of blocked sites is complete, click "OK" and restart Firefox.

Wednesday, September 29, 2010

Code to encrypt the Password or any string

/// <summary>
/// This method retrieve the string to encrypt from the Presentation Layer
/// And return the Encrypted String
/// </summary>
/// <param name="str">
/// <returns>
public string encryptPassword(string strText)
{
    return Encrypt(strText, "&%#@?,:*");
}

/// <summary>
/// This method retrieve the encrypted string to decrypt from the Presentation Layer
/// And return the decrypted string
/// </summary>
/// <param name="str">
/// <returns>
public string decryptPassword(string str)
{
    return Decrypt(str, "&%#@?,:*");
}

/// <summary>
/// This method has been used to get the Encrypetd string for the
/// passed string
/// </summary>
/// <param name="strText">
/// <param name="strEncrypt">
/// <returns>
private string Encrypt(string strText, string strEncrypt)
{
    byte&#91;] byKey = new byte[20];
    byte&#91;] dv ={ 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
    try
    {
        byKey = System.Text.Encoding.UTF8.GetBytes(strEncrypt.Substring(0, 8));
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        byte&#91;] inputArray = System.Text.Encoding.UTF8.GetBytes(strText);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, dv), CryptoStreamMode.Write);

        cs.Write(inputArray, 0, inputArray.Length);
        cs.FlushFinalBlock();

        return Convert.ToBase64String(ms.ToArray());
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

/// <summary>
/// This method has been used to Decrypt the Encrypted String
/// </summary>
/// <param name="strText">
/// <param name="strEncrypt">
/// <returns>
private string Decrypt(string strText, string strEncrypt)
{
    byte&#91;] bKey = new byte[20];
    byte&#91;] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

    try
    {
        bKey = System.Text.Encoding.UTF8.GetBytes(strEncrypt.Substring(0, 8));
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        Byte&#91;] inputByteArray = inputByteArray = Convert.FromBase64String(strText);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(bKey, IV), CryptoStreamMode.Write);

        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
        System.Text.Encoding encoding = System.Text.Encoding.UTF8;

        return encoding.GetString(ms.ToArray());
    }

    catch (Exception ex)
    {
        throw ex;
    }

}

Simple Navigation with CSS

 The HTML
<div id="navigation">
<ul>
    <li><a id="Links_Home" accesskey="H" title="to home page." href="/Default.aspx">Home</a></li>
    <li><a id="Links_About" title="About us." href="/about.aspx">About us</a></li>
    <li><a id="Links_Contact" title="Contact form." href="/contact.aspx">Contact me</a></li>
</ul>
</div>
you can set the class of the selected node to current to highlight it
The CSS
#navigation
{
    /*the section that holds all the links to various parts of the site
    such as archives, categories, and blogroll */
    float:right;
}
#navigation ul{
    list-style: none;
    margin: 0px;
    padding: 0px;
    display: inline;
    height:22px;
}
#navigation ul li{
    list-style: inline;
    display: inline;
}
#navigation ul li a{
    padding: 5px 15px;
    text-decoration:none;
    color:#fff;
    font-weight:bold;   
}
#navigation ul li a:visited{
}
#navigation ul li a:hover, #navigation ul li.current a{
  background-image:url(Images/underlink.jpg);
    background-position:bottom;
    background-repeat:repeat-x;
    margin:0;
    padding-bottom:5px;
    border:0;
    /*border-bottom: 4px solid #fff;*/
}

aliases in C# (and equivalent in .net)

C# Type.NET Framework type Range

bool System.Boolean  True,False  
byte System.Byte  0 to 255
 
sbyte System.SByte  -128 to 127  
char System.Char 0000h to FFFFh (unicode)
 
decimal System.Decimal    
double System.Double 7 digits precision ±5.0 × 10−324 to ±1.7 × 10308  
float System.Single 15-16 digits precision ±1.5 × 10−45 to ±3.4 × 1038  
int System.Int32  -2,147,483,648 to 2,147,483,647  
uint System.UInt32  0 to 4,294,967,295  
long System.Int64  -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807  
ulong System.UInt64  0 to 18,446,744,073,709,551,615  
object System.Object    
short System.Int16  -32,768 to 32,767  
ushort System.UInt16  0 to 65,535  
string System.String  

Monday, September 27, 2010

How To Encrypt configuration sections in ASp.NET



                        Developers often store confidential information in the configuration files. Database connection strings, user names and passwords are some of the examples. One of the requested feature during ASP.NET 1.x days was to provide some way to easily encrypt and decrypt such information. Thankfully ASP.NET 2.0 fulfils this request in a flexible way. This article will explain how a specific configuration section can be protected using inbuilt tool and code.

How ASP.NET encrypts configuration files?

ASP.NET 2.0 allows you to encrypt sections of your configuration file so that they are secure and protected. This feature is often called as Protected Configuration. ASP.NET provides two ways to encrypt and decrypt the configuration files:
  • Via a command line tool called ASPNET_REGIIS.EXE
  • Via configuration management classes
The encryption and decryption is done with the help of two built-in Protected Configuration Provider :
  • RsaProtectedConfigurationProvider
  • DataProtectionConfigurationProvider
If you open machine.config on your machine you will find a section that specifies these providers. The RsaProtectedConfigurationProvider is the default one. Below is the relevant markup from machine.config file.
<configProtectedData
defaultProvider="RsaProtectedConfigurationProvider">
<providers>
<add name="RsaProtectedConfigurationProvider"
type="System.Configuration.RsaProtectedConfigurationProvider,
System.Configuration, Version=2.0.0.0, Culture=neutral,
yptoServiceProvider to encrypt a
PublicKeyToken=b03f5f7f11d50a3a" description="Uses RsaC rnd decrypt" keyContainerName="NetFrameworkConfigurationKey"
/> <add name="
cspProviderName="" useMachineContainer="true" useOAEP="false
"DataProtectionConfigurationProvider"
type="System.Configuration.DpapiProtectedConfigurationProvider,
System.Configuration, Version=2.0.0.0, Culture=neutral,
ProtectData and CryptUnProtectDa
PublicKeyToken=b03f5f7f11d50a3a" description="Uses Cryp tta Windows APIs to encrypt and decrypt" useMachineProtection="true" keyEntropy="" />
</providers >
/configProtectedData>
<

Encrypting a configuration section using ASPNET_REGIIS.EXE

Let’s see how we can encrypt the <connectionStrings> section using ASPNET_REGIIS.EXE tool.
Create a new IIS based web site in VS.NET called EncryptTest and add a web.config file to it. Then add <connectionStrings> section as shown below:
<connectionStrings>
<add name="connstr" connectionString=
"data source=.\sqlexpress;initial catalog=
northwind;integrated security=true" />
</connectionStrings>
We simply add a connection string that points to Northwind database. Next, drag and drop a GridView control on the default web form and add the following code in the Page_Load event.
protected void Page_Load(object sender, EventArgs e)
{ string strConn = ConfigurationManager.
ring; SqlDataAdapter da = new SqlDataAdapter (
ConnectionStrings["connstr"].ConnectionS t"select * from customers", strConn); DataSet ds = new DataSet(); da.Fill(ds);
GridView1.DataSource = ds; GridView1.DataBind();
}
We read the connection string from the <connectionStrings> section using ConfigurationManager class. We use this manual method instead of using SQL Data Source control deliberately just to prove that the inbuilt classes such as ConfigurationManager automatically decrypt the encrypted version of the connection string. We then populate a DataSet from all the records from Customers table and bind it with the GridView.
Now, open Visual Studio 2005 Command Prompt and issue the following command:
aspnet_regiis -pe "connectionStrings" -app "/encrypttest"
The -pe switch specifies the section from the web.config file to encrypy (connectionStrings in our case). The -app switch specifies the virtual path of the IIS application we are working on.
After executing this command if you peek into the web.config file you should see some thing like this:
<connectionStrings configProtectionProvider=
"RsaProtectedConfigurationProvider">
g/2001/04/xmlenc#Element" xmlns="http://www.w3.org/2001/04/xml
<EncryptedData Type="http://www.w3.o renc#"> <EncryptionMethod Algorithm= "http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
rg/2001/04/xmlenc#"> <EncryptionMethod Algorithm= "h
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#"> <EncryptedKey xmlns="http://www.w3. ottp://www.w3.org/2001/04/xmlenc#rsa-1_5" /> <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#"> <KeyName>Rsa Key</KeyName> </KeyInfo>
7zk2MegZmiri
<CipherData> <CipherValue>NW4gFUtlA3XkbKu42FQ3kYV8EKmwzy9r53vrI2rjV ZFqjsr00/MwS6TWqjnsguN09kWvNIrbfWu5+Gi+DLFhYnGm2NcuaCy Vic8f5e0Q8u3 E5bSELE1fZneWz4oFb+MHqA94ZO3Be XBlocou6ydtmJPXZCqLsDQ=</CipherValue> </CipherData> </EncryptedKey> </KeyInfo> <CipherData>
4Kf5zcPyWoaWwcus4LnJYNtg3oGJUvavZ0tjGXH9+5gB w/xMrtfDcY
<CipherValue>T2fswq6Rt7g7VSNUnoe4kNFGSluWCBReQf3DRbXao/ sWaWs4mrJAI6Xy0zNDHY5pKXUUF9Kep2wG84rMVx0QtLIUjBaUKCnrm Eb+53oYNPj NAIom9l/IMcO92BKrvimjn/k4Mr8VXxGpvdMkAC3+e6dtW JeUgQGpepO+RNpWymB5kWj38LjMQ=</CipherValue> </CipherData> </EncryptedData>
</connectionStrings>
The tool has encrypted the connectionStrings section using RsaProtectedConfigurationProvider (default) and stored the encrypted markup back to the configuration file. You can also specify the Protected Configuration Provider using -prov switch. Easy. Isn’t it?
Now, run your web form. The web form should correctly display the Customers table in the GridView indicating that ConfigurationManager class automatically decrypts this information while reading the connection string.

Decrypting a configuration section ASPNET_REGIIS.EXE

What if you need to make some changes to the connection string during the development? Don’t worry! The ASPNET_REGIIS.EXE tool allows you to decrypt the section also. Just issue the following command and get back your original un-encrypted version back.
aspnet_regiis -pd "connectionStrings" -app "/encrypttest"
The onlt difference between this command and the one we used previously is that we used -pd switch instead of -pa.

Encryption and decrypting via code

The task of encrypting and decrypting web.config can also be achieved via code. Let’s see how.
Add a new web form to the same web site and design it as shown below:
Add the following code in the Click event of “Encrypt Connection String” button:
protected void Button1_Click(object sender, EventArgs e)
{ Configuration config = WebConfigurationManager.
figurationSection section = config.ConnectionS
OpenWebConfiguration(Request.ApplicationPath); Co ntrings; if (!section.SectionInformation.IsProtected) {
section.SectionInformation.ProtectSection
("RsaProtectedConfigurationProvider");
section.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
}
}
If you are not familiar with how to edit web.config programmatically then you may find this article useful : Modifying Web.config file programmatically .
The code above is opening the web.config file for modification. It then retrieves the ConnectionStrings section. The most important thing happens at the line marked in bold. The ProtectSection() method accepts the Protected Configuration Provider you want  to use for encryption and then encrypts the underlying section using that provider. The code finally saves the file back to the disk.
Decrypting the configuration section works on similar lines as explained below:
protected void Button2_Click(object sender, EventArgs e)
{ Configuration config = WebConfigurationManager.
figurationSection section = config.ConnectionS
OpenWebConfiguration(Request.ApplicationPath); Co ntrings; if (section.SectionInformation.IsProtected) {
section.SectionInformation.UnprotectSection();
section.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
}
}
Here, we used UnprotectSection() method to revert back to the un-encrypted version.

How to Display Total at the bottom of the Gridview?

First add one datagridevew on a webpage.Now i am going to retrive a data from a Table named 'emp'.This emp table has 3 columns
column name          DataType
-----------------------------------------------
id                          number
empname                varchar(50)
salary                     number
In Soucrce code .aspx page
create a Template in gridvew  to display Data as follows in between the <asp:Gridview>and </asp:Gridview>
<asp:GridView ID="GridView1" runat="server" Style="z-index: 100; left: 271px; position: absolute;
top: 68px" AutoGenerateColumns="False" Height="165px" ShowFooter="True" CellPadding="4"
ForeColor="Black" GridLines="Vertical" Width="229px" BackColor="White" BorderColor="#DEDFDE"
BorderStyle="None" BorderWidth="1px">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="idlbl" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"id")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NAME">
<ItemTemplate>
<asp:Label ID="namelbl" runat="server" Text-Align="right" Text='<%#DataBinder.Eval(Container.DataItem,"empname")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SALARY">
<ItemTemplate>
<asp:Label ID="sal1" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"salary")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="Black" HorizontalAlign="Right" BackColor="#F7F7DE" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
write a code for display data in grdview:
in aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("connectionstring"); conn.Open(); SqlDataAdapter ad = new SqlDataAdapter("select * from emp", conn); DataSet ds = new DataSet(); ad.Fill(ds, "emp"); GridView1.DataSource = ds.Tables[0]; GridView1.DataBind();
}

Below is the simple output Image of a gridview:

Now we have calculate the Total Salary then have to dispaly Total Salary at the Bottom of the Gridview.By using <FooterTemplate><FooterTemplate> is used for the Last Line of our OutPut. eg:
<FooterTemplate>Last Line_outPut </FooterTemplate> 
NOTE:If we are using footer template we have to set ShowFooter Property as True by selecting the datagrid.
In this Example I am going to calculate the sum of Salary column.This sum should be displayed  in the salary column LastLine(bottom of the salary column).
I am using a method name as gettotal().here i am calculating the total salarys of employes.
public int gettotal()
{
SqlConnection conn = new SqlConnection("connectionstring"); conn.Open(); SqlCommand cmd = new SqlCommand("SELECT SUM(salary) FROM emp", conn); int totalsal = Convert.ToInt32(cmd.ExecuteScalar()); return totalsal;
}
Next we have to use this gettotal () method in <FooterTemplate> <FooterTemplate><%# gettotal()%></FooterTemplate>
here  <%# gettotal()%> will cal the gettotal() in aspx.cs page


we have to write use this FooterTemplate where we want a lastline output. Here I am using this FooterTemplate in salary column.
eg:
<asp:TemplateField HeaderText="SALARY">
<ItemTemplate>
<asp:Label ID="sal1" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"salary")%>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<%# gettotal()%>
</FooterTemplate>
</asp:TemplateField>


See the output Image


The aspx.page will look like as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" Style="z-index: 100; left: 271px; position: absolute;
top: 68px" AutoGenerateColumns="False" Height="165px" ShowFooter="True" CellPadding="4"
ForeColor="Black" GridLines="Vertical" Width="229px" BackColor="White" BorderColor="#DEDFDE"
BorderStyle="None" BorderWidth="1px">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="idlbl" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"id")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NAME">
<ItemTemplate>
<asp:Label ID="namelbl" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"empname")%>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="namelbl" runat="server" Text="Total"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SALARY">
<ItemTemplate>
<asp:Label ID="sal1" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"salary")%>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<%# gettotal()%>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="Black" HorizontalAlign="Right" BackColor="#F7F7DE" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
&nbsp;&nbsp;
</div>
</form>
</body>
</html>
the complete asp.cs page is:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("connectionstring"); conn.Open(); SqlDataAdapter ad = new SqlDataAdapter("select * from emp", conn); DataSet ds = new DataSet(); ad.Fill(ds, "emp"); GridView1.DataSource = ds.Tables[0]; GridView1.DataBind(); gettotal();
} public int gettotal() {
SqlConnection conn = new SqlConnection("connectionstring"); conn.Open(); SqlCommand cmd = new SqlCommand("SELECT SUM(salary) FROM emp", conn); int totalsal = Convert.ToInt32(cmd.ExecuteScalar()); return totalsal;
}