Monday, 1 June 2015

Automatic Page Refresh in ASP.NET

To refresh a page automatically at a time interval. Doing this is pretty simple, using META tags.

    <meta http-equiv="refresh" content="45">


    <meta http-equiv="refresh" content="45;url=home.aspx">

But if you used Master Pages, the META tag then all pages that use this master page will be refreshed, which is not desired, to accomplish this, add the following c# code in the code behind of, the particular page you want to refresh:
Response.AppendHeader("Refresh", 45 + "; URL=home.aspx");

Where, 45 is the time interval in seconds.

There are many other ways of doing auto refreshing , like using JavaScript and J Queries, but this is simplest way. 

Wednesday, 25 March 2015

SQL:- Multiple rows to a single comma-separated value

Sample Data
DECLARE @MyTable1 TABLE(ID INT, Value Varchar(50))
INSERT INTO @MyTable1 VALUES (1,'John'),(1,'Tom'),(1,'Sajan'),(1,'Ram')
Sql Query
SELECT  ID
       ,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(200)) [text()]
        FROM @MyTable1
         WHERE ID = t.ID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') Name
FROM @MyTable1 t
GROUP BY ID
Results
ID Names
1 John, Tom, Sajan, Ram

Monday, 16 March 2015

Implement Remember Me functionality using CheckBox in ASP.Net C#

HTML Markup
I have a simple HTML Form below which has two ASP.Net TextBox controls txt_UserName  and  txt_Password and a CheckBox control chk_RememberMe to allow user specify whether he wants the page to remember the UserName and Password when he visits next time, finally an ASP.Net Button  btn_Login which when clicked will save the entered UserName and Password in the Cookie.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    UserName:
    <asp:TextBox ID="txt_UserName" runat="server"></asp:TextBox><br />
    Password:
    <asp:TextBox ID="txt_Password" TextMode="Password" runat="server"></asp:TextBox><br />
    Remember me:
    <asp:CheckBox ID="chk_RememberMe" runat="server" /><br />
    <asp:Button ID="btn_Login" runat="server" Text="Login" OnClick="btn_Login_Click" />
    </form>
</body>
</html>
Saving the UserName and Password in Cookie
When the Button btn_Login is clicked the following event handler is executed which first checks whether the chk_RememberMe is checked. If it is checked then it save the UserName and Password in the Cookies and sets their expiration date to 30 days in future from the current date. And if it is not checked then it sets the expiration date to 1 day in past so that Cookie is destroyed.
C#
protected void btn_Login_Click(object sender, EventArgs e)
{
    if (chk_RememberMe.Checked)
    {
        Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(30);
        Response.Cookies["Password"].Expires = DateTime.Now.AddDays(30);
    }
    else
    {
        Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1);
        Response.Cookies["Password"].Expires = DateTime.Now.AddDays(-1);
 
    }
    Response.Cookies["UserName"].Value = txt_UserName.Text.Trim();
    Response.Cookies["Password"].Value = txt_Password.Text.Trim();
}
 Populating the UserName and Password from Cookie and setting it in TextBoxes
Now in Page_Load event we will check if the Cookie exists and if yes then we will set the TextBoxes for UserName and Password with their respective Cookie value.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
      if (Request.Cookies["UserName"] != null && Request.Cookies["Password"] != null)
        {
         txt_UserName.Text = Request.Cookies["UserName"].Value;
         txt_Password.Attributes["value"] = Request.Cookies["Password"].Value;
        }
    }
}

Wednesday, 2 July 2014

How to delete duplicate entries from table without deleting single entry in SQL

How to delete duplicate entries  from table without deleting single  entry in SQL


Suppose there are 5 duplicate  entries with same values in [MyTable] table, we have to keep only one entry in the table. 
When we  use the given code then 4 entries will be deleted


set rowcount 4
delete from MyTable where Myid =
set rowcount 0


Thursday, 29 May 2014

DateTime String Format in C#

Reference:---http://www.csharp-examples.net/string-format-datetime/

Following examples demonstrate how are the format specifiers rewritten to the output.
DateTime date = new DateTime(2004, 9, 5, 21, 3, 2, 123);
----2004-09-05 21:03:02.123---  = 05-Sep-2004 9:03:02 PM
String.Format("{0:y yy yyy yyyy}", date); // "4 04 004 2004" year String.Format("{0:M MM MMM MMMM}", date); // "9 09 Sep September" month String.Format("{0:d dd ddd dddd}", date); // "5 05 Sun Sunday" day String.Format("{0:h hh H HH}", date); // "9 09 21 21" hour 12/24 String.Format("{0:m mm}", date); // "3 03" minute String.Format("{0:s ss}", date); // "2 02" second String.Format("{0:f ff fff ffff}", date); // "1 12 123 1230" sec.fraction String.Format("{0:F FF FFF FFFF}", date); // "1 12 123 123" without zeroes String.Format("{0:t tt}", date); // "P PM" A.M. or P.M. String.Format("{0:z zz zzz}", date); // "-6 -06 -06:00" time zone
String.Format("{0:d/M/yyyy HH:mm:ss}", date); // "5/9/2004 21:03:02" 
String.Format("{0:d/M/yyyy HH:mm:ss}", date); // "5.9.2004 21:03:02" 
String.Format("{0:M/d/yyyy}", date);            // "9/5/2004"
String.Format("{0:MM/dd/yyyy}", date);          // "09/05/2004"
// day/month names
String.Format("{0:ddd, MMM d, yyyy}", date);    // "Sun, Sep 5, 2004"
String.Format("{0:dddd, MMMM d, yyyy}", date);  // "Sunday, September 5, 2004"
// two/four digit year
String.Format("{0:MM/dd/yy}", date);            // "09/05/04"
String.Format("{0:MM/dd/yyyy}", date);          // "09/05/2004"

Following examples show usage of standard format specifiers in String.Format method and the resulting output.
String.Format("{0:t}", date);  // "9:03 PM"                         
String.Format("{0:d}", date);  // "9/5/2004"                        
String.Format("{0:T}", date);  // "9:03:02 PM"                      L
String.Format("{0:D}", date);  // "Sunday, September 05, 2004"      
String.Format("{0:f}", date);  // "Sunday, September 05, 2004 9:03 PM" 
String.Format("{0:F}", date);  // "Sunday, September 05, 2004 9:03:02 PM" 
String.Format("{0:g}", date);  // "9/5/2004 9:03 PM"             
String.Format("{0:G}", date);  // "9/5/2004 9:03:02 PM"          
String.Format("{0:m}", date);  // "September 05"                  
String.Format("{0:y}", date);  // "September, 2004"                  
String.Format("{0:r}", date);  // "Sun, 05 Sep 2014 21:03:02 GMT"   
String.Format("{0:s}", date);  // "2004-09-05T21:03:02"             
String.Format("{0:u}", date);  // "2004-09-05 21:03:02Z"    

Tuesday, 29 April 2014

SQL Injection Prevention & Detection Techniques


  • Database Design Best Practices
  • Defensive Coding Best Practices
  • Penetration Testing
  • Static Analysis of Code
  • Safe Development Libraries
  • Proxy Filters

  • Anomaly Based Intrusion Detection
  • Instruction Set Randomization
  • Dynamic Tainting
  • Model-based Checkers

Wednesday, 23 April 2014

Types of SQL Injection Attacks

1.Tautologies
2.Union Query
3.Piggy-backed Queries
4.Inference
5.Illegal/Logically Incorrect Queries
6.Stored Procedures

7.Alternate Encodings

Type: Tautologies
This type of attack injects SQL tokens to the conditional query statement to be evaluated always true
Example:-
"SELECT * FROM employee WHERE userid =  '112' and password ='aaa' OR '1 '='1”

As the tautology statement (1=1) has been added to the query statement so it is always true

Type: Union Queries
The result of Union Query injection attacks will be a new dataset returned by the database, containing the union of the first (developer intended) and the second (attacker-intended)

Example:-
"SELECT Name, Phone FROM Users WHERE Id= 1 UNION ALL SELECT creditCardNumber, 1 FROM Credit CardTable”

This will join the result of the original query with all the credit card

Type: Piggy-backed Queries
In this attack type, an attacker tries to inject additional queries into the original query.
In this case, attackers are not trying to modify the original intended query; instead, they are trying to include new and distinct queries that “piggy-back” on the original query.

Example:-
SELECT accounts FROM users WHERE login=‘doe’ AND pass=“0; DROP database webApp

Type: Inference
By this type of attack, intruders change the behavior of a database or application

Blind injection:- Blind SQL Injection is used when a web application is vulnerable to an SQL injection, but the results of the injection are not visible to the attacker.
Information is inferred from the behavior of the page by asking the server true/-false questions. If the injected statement evaluates to true, the site continues to function normally. If the statement valuates to false, although there is no descriptive error message, the page differs significantly from the normally-functioning page.

Timing attacks:- This type of blind SQL injection relies on the database pausing for a specified amount of time, then returning the results, indicating successful SQL query executing.
A timing attack allows an attacker to gain information from a database by observing timing delays in the response of the database. Attackers structure their injected query in the form of an if/then statement, whose branch predicate corresponds to an unknown about the contents of the database. Along one of the branches, the attacker uses a SQL construct that pause the execution for a known amount of time (e.g. the WAITFOR keyword). By measuring the response time of the database, the attacker can infer which branch was taken in his injection and therefore the answer to the injected question

Type: Illegal/Logically Incorrect Queries
This type is used to trigger syntax errors (which would be used to identify injectable parameters), type conversion errors (to deduce the data types of certain columns or extract data from them) or logical errors (which often reveal names of the tables and columns that caused the error), in order for the attacker to gather information about the type and structure of the back end database of a given Web application.
Example:-
" SELECT accounts FROM users WHERE login= AND pass=‘’ AND pin= convert (int,(select top 1 name from sysobjects where xtype=u))”

Type: Stored Procedure
This type of attack using stored procedures
Example:-
" CREATE PROCEDURE DBO.isAuthenticated
@userName varchar2, @pass varchar2, @pin int AS
EXEC("SELECT accounts FROM users WHERE login= ' “ +@userName+ “ ‘and pass=’ “+@password+” ‘and pin=”+@pin);  GO

SELECT accounts FROM users WHERE login='doe' AND pass = ' '; SHUTDOWN; -- AND pin=

Type: Alternate Encodings
This attack type is used in conjunction with other attacks. In other words, alternate encodings do not provide any unique way to attack an application; they are simply an enabling technique that allows attackers to evade detection and prevention techniques and exploit vulnerabilities that might not otherwise be exploitable

SELECT * FROM userTable WHERE” +  “login=‘” + login + “' AND pin=” + pin;

Input pin as “0; declare @a char(20)  select  @a=0x73687574646f776e exec(@a)”

SELECT * FROM userTable WHERE login=‘user' AND pin= 0;declare @a char(20) select @a=0x73687574646f776e exec(@a)”