Saturday, 20 April 2013

Get query string values using javascript.

Get query string values using javascript.

You can use the pure JavaScript to read query string paramemeter value,

function getParameterByName(name)
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(;
  if(results == null)
    return "";
    return decodeURIComponent(results[1].replace(/\+/g, " "));

if following is an url.

then you can following javascript method to read name value in query string.

function readname()
      var nameval = getParameterByName('name');

that's it.

How to make a first letter capital in C#

How to make a first letter capital in C#

How can the first letter in a word of sentence using c#.
as an example

it is a text.  = It is a text.

solution is use below function.

public static string ToUpperFirstLetter(this string source)
    if (string.IsNullOrEmpty(source))
        return string.Empty;
    // convert to char array of the string
    char[] letters = source.ToCharArray();
    // upper case the first char
    letters[0] = char.ToUpper(letters[0]);
    // return the array made of the new char array
    return new string(letters);
another good solution is 

String after = before.Substring(0, 1).ToUpper() + before.Substring(1);

so you can use above solution.

Sunday, 14 April 2013

Sql server - Rows to table

Sql server - Rows to table...

Using pivot ans unpivot

You can use the PIVOT and UNPIVOT relational operators to manipulate a table-valued expression into another table. PIVOT rotates a table-valued expression by turning the unique values from one column in the expression into multiple columns in the output, and performs aggregations where necessary on any remaining column values that are desired in the final output. UNPIVOT performs the opposite operation to PIVOT by rotating columns of a table-valued expression into column values. Every PIVOT query involves an aggregation of some type.

There are two ways to pivot data:
  1.     We can convert multiple rows into a single row with repeating groups of columns.
  2.     We can convert columns on a single row into multiple rows with a generic column and a row type discriminator.

Use the following scripts,

CREATE TABLE Sales (State CHAR(2), SalesAmt DECIMAL(18,2))  

Insert values,

INSERT INTO Sales VALUES ('ND',10000)  
INSERT INTO Sales VALUES ('SD',30000)  
INSERT INTO Sales VALUES ('TN',2500.50)  
INSERT INTO Sales VALUES ('OR',5500.50)  
INSERT INTO Sales VALUES ('VA',6500.50)  
INSERT INTO Sales VALUES ('SD',7000)  
INSERT INTO Sales VALUES ('ND',8000)  
  SELECT * FROM Sales  

Here is the result set,

Run the following query,

SELECT [ND],[SD],[TN],[OR],[VA]  
FROM (SELECT State,SalesAmt FROM Sales) p  
SUM (SalesAmt)  
FOR State IN  
AS pvt  

Here is the result set,

UNPIVOT performs almost the reverse operation of PIVOT, by rotating columns into rows.
Use the following scripts,

Create the following table,  
CREATE TABLE StudentMarks(  
Subject1 VARCHAR(10),  
Mark1 INT,  
Subject2 VARCHAR(10),  
Mark2 INT,  
Subject3 VARCHAR(10),  
Mark3 INT)  

Insert some data into above table ans suppose select returns following result set,

Run the following query,

SELECT  [Name], SubjectName,  
case when Subject='Subject1' then Mark1  
     when Subject='Subject2' then Mark2  
     when Subject='Subject3' then Mark3  
    else NULL end as Marks  
   (SELECT [Name], Subject1,Mark1, Subject2,Mark2, Subject3,Mark3  
   FROM StudentMarks) p  
   (SubjectName FOR Subject IN 
   (Subject1, Subject2, Subject3)
    )AS unpvt;  
Here is the result set,

Note that UNPIVOT is not the exact reverse of PIVOT. PIVOT performs an aggregation and hence merges possible multiple rows into a single row in the output. UNPIVOT does not reproduce the original table-valued expression result because rows have been merged. Besides, NULL values in the input of UNPIVOT disappear in the output, whereas there may have been original NULL values in the input before the PIVOT operation.

How to use server.mappath

How to use server.mappath

Server.MapPath specifies the relative or virtual path to map to a physical directory.

Server.MapPath(".") returns the current physical directory of the file (e.g. aspx) being executed
Server.MapPath("..") returns the parent directory
Server.MapPath("~") returns the physical path to the root of the application
Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)
An example:

Let's say you pointed a web site application ( to

and installed your application (sub web as virtual directory in IIS, marked as application) in

For example, if you call Server.MapPath in following request:

Server.MapPath(".") returns D:\WebApps\category\products
Server.MapPath("..") returns D:\WebApps\category
Server.MapPath("~") returns D:\WebApps\category
Server.MapPath("/") returns C:\Inetpub\wwwroot
Server.MapPath("/shop") returns D:\WebApps\shop

How to get the URL of the current page in C#

How to get the URL of the current page in C#

following code returns values given in comment.

string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost:1302/sitename/Default.aspx

string path = HttpContext.Current.Request.Url.AbsolutePath;
// /sitename/Default.aspx
string host = HttpContext.Current.Request.Url.Host;
// localhost 
if you just want the part between http:// and the first slash
string url = Request.Url.Host;
would return if called from this page

Mail seding in c# using gmail Account in

Mail seding in c# using gmail Account in

below is a code for sending mail using your gmail account...

MailMessage msg = new MailMessage();
SmtpClient mailobj = new SmtpClient();

msg.From = new MailAddress("");
msg.To.Add(new MailAddress(""));
msg.IsBodyHtml = true;
msg.Body = "Hi, dear <br/><br/>Your Registration completed.Thank You. ";
msg.Subject = "Email subject...";
msg.IsBodyHtml = true;
msg.Priority = MailPriority.High;
mailobj.Host = "";
mailobj.Port = 587;
mailobj.EnableSsl = true;
mailobj.Credentials = newSystem.Net.NetworkCredential("""gmailpassword");
       Response.Write("Your mail is sended");
catch (Exception ex)
        Response.Write("The error has occured during sending mail => "+ ex);

Thats it... replace your gmail account id and password in above code where its indicated,

How to stop sql injection attack in

How to prevent website from sql injection attack  in

Hi friends this is a class  to prevent from sql injectiion for c#.

First create a class named as SqlInjectionScreeningModule.cs and it's code will be like below...

using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Data.SqlClient;

public class SqlInjectionScreeningModule : IHttpModule
    ///''please remove or add the blacklist variable as per your requirement''''''''
    ///''please check(run) your application after implementing this code''''''''''''''
    public static string[] blackList = { "--", ";--", "/*", "*/", "@@", "char", "nchar", "varchar", "nvarchar", 
    "alter", "begin", "cast", "create", "cursor", "declare", "drop", "exec", 
    "execute", "fetch", "kill", "open", " sys", "sysobjects", "syscolumns", 
    "commit", "truncate", "shutdown" };
    public void Dispose()
    public void Init(HttpApplication app)
        app.BeginRequest += app_BeginRequest;
    private void app_BeginRequest(object sender, EventArgs e)
        HttpRequest Request = (sender as HttpApplication).Context.Request;

        foreach (string key in Request.QueryString)
        foreach (string key in Request.Form)
        foreach (string key in Request.Cookies)

        //For Each key As String In Request.Files
        //    CheckInput(Request.Cookies(key).Value)

    private void CheckInput(string parameter)
        for (int i = 0; i <= blackList.Length - 1; i++)
            if ((parameter.IndexOf(blackList[i], StringComparison.OrdinalIgnoreCase) >= 0))
                ///'Your Error Display Page''''''

Now in web.config add below http modules....

            <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add name="SqlInjectionScreeningModule" type="SqlInjectionScreeningModule"/>

Thats it... now for all the pages for any input it will check for sql injection code in input.