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(window.location.search);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

if following is an url.

http://www.test.com/test.html?name=bridzetech

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

function readname()
{
      var nameval = getParameterByName('name');
alert(nameval);
}

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  
PIVOT
(
SUM (SalesAmt)  
FOR State IN  
([ND],[SD],[TN],[OR],[VA])  
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(  
[NameVARCHAR(50),  
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  
FROM  
   (SELECT [Name], Subject1,Mark1, Subject2,Mark2, Subject3,Mark3  
   FROM StudentMarks) p  
UNPIVOT
   (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 (http://www.sitename.com/) to

C:\Inetpub\wwwroot
and installed your application (sub web as virtual directory in IIS, marked as application) in

D:\WebApps\shop
For example, if you call Server.MapPath in following request:

http://www.sitename.com/category/products/GetProduct.aspx?id=1
then:

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 sitename.com if called from this page

Mail seding in c# using gmail Account in asp.net


Mail seding in c# using gmail Account in asp.net.


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


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

msg.From = new MailAddress("gmailid@gmail.com");
msg.To.Add(new MailAddress("sendmailto@gmail.com"));
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 = "smtp.gmail.com";
mailobj.Port = 587;
mailobj.EnableSsl = true;
mailobj.Credentials = newSystem.Net.NetworkCredential("gmailid@gmail.com""gmailpassword");
try
{
       mailobj.Send(msg); 
       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 Asp.net...


How to prevent website from sql injection attack  in Asp.net......



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()
    {
        //no-op 
    }
    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)
        {
            CheckInput(Request.QueryString[key]);
        }
        foreach (string key in Request.Form)
        {
            CheckInput(Request.Form[key]);
        }
        foreach (string key in Request.Cookies)
        {
            CheckInput(Request.Cookies[key].Value);
        }

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

    }
    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''''''
                HttpContext.Current.Response.Redirect("~/Default.aspx");
            }
        }
    }
}



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


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

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