"If at first you don't succeed; call it version 1.0" :-Unknown

Pages

Wednesday, September 29, 2010

filling dropdown with numbers in a range

hi frienz,
2day i'm showing filling dropdown with numbers with in a range. by using a small for loop.

for that i created a function here. u need to pass 3 parameter to here dropdown name, from limit , to limit


        Public void dropdown(DropDownList cbo, int _from, int _To)
        {
            cbo.Items.Clear();
            for (int i = _from; i <= _To; i++)
            {
                cbo.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }
                 }

Have a nice day... 'N happy Coding :)

Tuesday, September 28, 2010

Hide a Table Column with a Single line of jQuery code

today I will show you how to Hide a Column with a Single line of jQuery code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.3.2.js"
    type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#btnHide').click(function() {
                $('td:nth-child(2)').hide();
                // if your table has header(th), use this
                //$('td:nth-child(2),th:nth-child(2)').hide();
            });
        });
    </script>
</head>
<body>
<table id="tableone" border="1">
    <tr class="del">
        <td>Row 0 Column 0</td>
        <td >Row 0 Column 1</td>
        <td >Row 0 Column 2</td>
    </tr>
    <tr class="del">
        <td>Row 1 Column 0</td>
        <td>Row 1 Column 1</td>
        <td>Row 1 Column 2</td>
    </tr>
    <tr class="del">
        <td>Row 2 Column 0</td>
        <td>Row 2 Column 1</td>
        <td>Row 2 Column 2</td>
    </tr>
    <tr class="del">
        <td>Row 3 Column 0</td>
        <td>Row 3 Column 1</td>
        <td>Row 3 Column 2</td>
    </tr>
     <tr class="del">
        <td>Row 4 Column 0</td>
        <td>Row 4 Column 1</td>
        <td>Row 4 Column 2</td>
    </tr>
     <tr class="del">
        <td>Row 5 Column 0</td>
        <td>Row 5 Column 1</td>
        <td>Row 5 Column 2</td>
    </tr>
</table>
    <input id="btnHide" type="button" value="Hide Column 2"/>

</body>
</html>



Have a nice day... 'N happy Coding :)

Using jQuery to Delete a Row in a Table by just Clicking on it

Here’s a very simple way of deleting a row in a table, when a user clicks on it. With jQuery, the efforts required to achieve this requirement is just 2 lines of code.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.3.2.js"
    type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('table tr.del').click(function() {
                $(this).remove();
            });
        });
    </script>
</head>
<body>
<table border="1">
    <tr class="del">
        <td>Row 0 Column 0</td>
        <td >Row 0 Column 1</td>
    </tr>
    <tr class="del">
        <td>Row 1 Column 0</td>
        <td>Row 1 Column 1</td>
    </tr>
    <tr class="del">
        <td>Row 2 Column 0</td>
        <td>Row 2 Column 1</td>
    </tr>
    <tr class="del">
        <td>Row 3 Column 0</td>
        <td>Row 3 Column 1</td>
    </tr>
     <tr class="del">
        <td>Row 4 Column 0</td>
        <td>Row 4 Column 1</td>
    </tr>
     <tr class="del">
        <td>Row 5 Column 0</td>
        <td>Row 5 Column 1</td>
    </tr>
</table>
</body>
</html>


Have a nice day... 'N happy Coding :)

Monday, September 27, 2010

A potentially dangerous Request.Form value was detected from the client – ASP.NET 4.0

If you happen to upgrade your .NET Framework to use the .NET 4.0 CLR's version of ASP.NET, then it helps keeping the ASP.NET 4.0 breaking changes document handy.
After the upgrade, most of the users using the Rich-text editors or textboxes to submit HTML data, encounter the following error “Exception type: System.Web.HttpRequestValidationException Exception message: A potentially dangerous Request.Form value was detected from the client
Now we know about the request validation feature inASP.NET that shields cross-site scripting (XSS) attacks to a certain level. However this level of security changes inASP.NET 4.0 making it stricter in terms of request validation.
As given in the documentation “In ASP.NET 4, by default, request validation is enabled for all requests, because it is enabled before theBeginRequest phase of an HTTP request. As a result, request validation applies to requests for all ASP.NET resources, not just .aspx page requests. This includes requests such as Web service calls and custom HTTP handlers. Request validation is also active when custom HTTP modules are reading the contents of an HTTP request
To fix this error, open your web.config and add the following setting inside <system.web> as shown here
<system.web>
   <httpRuntime requestValidationMode="2.0" />
... rest of your attributes come here

The <httpRuntime requestValidationMode="2.0" /> disables validation for request data. Although this isn’t particularly a very good fix as it compromises security, I believe it’s the only quick hack available unless you want to float your own custom request validator.


Have a nice day... 'N happy Coding :)

Friday, September 24, 2010

Important: ASP.NET Security Vulnerability



Last week Microsoft find a Security Vulnerability on all version on .net. 2day i'm showing how to solve this problem.

What does the vulnerability enable?

An attacker using this vulnerability can request and download files within an ASP.NET Application like the web.config file (which often contains sensitive data).
At attacker exploiting this vulnerability can also decrypt data sent to the client in an encrypted state (like ViewState data within a page).

How the Vulnerability Works

To understand how this vulnerability works, you need to know about cryptographic oracles. An oracle in the context of cryptography is a system which provides hints as you ask it questions. In this case, there is a vulnerability in ASP.NET which acts as a padding oracle. This allows an attacker to send cipher text to the web server and learn if it was decrypted properly by examining which error code was returned by the web server.  By making many such requests (and watching what errors are returned) the attacker can learn enough to successfully decrypt the rest of the cipher text.

How to Workaround The Vulnerability

A workaround you can use to prevent this vulnerability is to enable the <customErrors> feature of ASP.NET, and explicitly configure your applications to always return the same error page - regardless of the error encountered on the server. By mapping all error pages to a single error page, you prevent a hacker from distinguishing between the different types of errors that occur on a server.
Important: It is not enough to simply turn on CustomErrors or have it set to RemoteOnly. You also need to make sure that all errors are configured to return the same error page.  This requires you to explicitly set the “defaultRedirect” attribute on the <customErrors> section and ensure that no per-status codes are set.

Enabling the Workaround on ASP.NET V1.0 to V3.5

If you are using ASP.NET 1.0, ASP.NET 1.1, ASP.NET 2.0, or ASP.NET 3.5 then you should follow the below steps to enable <customErrors> and map all errors to a single error page:
1) Edit your ASP.NET Application’s root Web.Config file.  If the file doesn’t exist, then create one in the root directory of the application.
2) Create or modify the <customErrors> section of the web.config file to have the below settings:
<configuration>        

   <system.web>

      <customErrors mode="On" defaultRedirect="~/error.html" />

   </system.web>        

</configuration>
3) You can then add an error.html file to your application that contains an appropriate error page of your choosing (containing whatever content you like).  This file will be displayed anytime an error occurs within the web application.
Notes: The important things to note above is that customErrors is set to “on”, and that all errors are handled by the defaultRedirect error page.  There are not any per-status code error pages defined – which means that there are no <error> sub-elements within the <customErrors> section.  This avoids an attacker being able to differentiate why an error occurred on the server, and prevents information disclosure.

Enabling the Workaround on ASP.NET V3.5 SP1 and ASP.NET 4.0

If you are using ASP.NET 3.5 SP1 or ASP.NET 4.0 then you should follow the below steps to enable <customErrors> and map all errors to a single error page:
1) Edit your ASP.NET Application’s root Web.Config file.  If the file doesn’t exist, then create one in the root directory of the application.
2) Create or modify the <customErrors> section of the web.config file to have the below settings.  Note the use of redirectMode=”ResponseRewrite” with .NET 3.5 SP1 and .NET 4.0:
<configuration>

   <system.web>

     <customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/error.aspx" />

   </system.web>

</configuration>
3) You can then add an Error.aspx to your application that contains an appropriate error page of your choosing (containing whatever content you like).  This file will be displayed anytime an error occurs within the web application.
4) We recommend adding the below code to the Page_Load() server event handler within the Error.aspx file to add a random, small sleep delay. This will help to further obfuscate errors.
VB Version
Below is a VB version of an Error.aspx file that you can use, and which has a random, small sleep delay in it.  You do notneed to compile this into an application – you can optionally just save this Error.aspx file into the application directory on your web-server:
<%@ Page Language="VB" AutoEventWireup="true" %>
<%@ Import Namespace="System.Security.Cryptography" %>
<%@ Import Namespace="System.Threading" %>

<script runat="server">
    Sub Page_Load()
        Dim delay As Byte() = New Byte(0) {}
        Dim prng As RandomNumberGenerator = New RNGCryptoServiceProvider()
        
        prng.GetBytes(delay)
        Thread.Sleep(CType(delay(0), Integer))
        
        Dim disposable As IDisposable = TryCast(prng, IDisposable)
        If Not disposable Is Nothing Then
            disposable.Dispose()
        End If
    End Sub
</script>

<html>
<head runat="server">
    <title>Error</title>
</head>
<body>
    <div>
        Sorry - an error occured
    </div>
</body>
</html>
C# Version
Below is a C# version of an Error.aspx file that you can use, and which has a random, small sleep delay in it.  You do notneed to compile this into an application – you can optionally just save it into the application directory on your web-server:
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Security.Cryptography" %>
<%@ Import Namespace="System.Threading" %>

<script runat="server">
   void Page_Load() {
      byte[] delay = new byte[1];
      RandomNumberGenerator prng = new RNGCryptoServiceProvider();

      prng.GetBytes(delay);
      Thread.Sleep((int)delay[0]);
        
      IDisposable disposable = prng as IDisposable;
      if (disposable != null) { disposable.Dispose(); }
    }
</script>

<html>
<head runat="server">
    <title>Error</title>
</head>
<body>
    <div>
        An error occurred while processing your request.
    </div>
</body>
</html>

How to Verify if the Workaround is Enabled

Once you have applied the above workaround, you can test to make sure the <customErrors> section is correctly configured by requesting a URL like this from your site: http://mysite.com/pagethatdoesnotexist.aspx
If you see the custom error page appear (because the file you requested doesn’t exist) then your configuration should be setup correctly.  If you see a standard ASP.NET error then it is likely that you missed one of the steps above.  To see more information about what might be the cause of the problem, you can try setting <customErrors mode=”remoteOnly”/> – which will enable you to see the error message if you are connecting to the site from a local browser.

How to Find Vulnerable ASP.NET Applications on Your Web Server

We have published a .vbs script that you can save and run on your web-server to determine if there are ASP.NET applications installed on it that either have <customErrors> turned off, or which differentiate error messages depending on status codes.
You can download the .vbs script here.  Simply copy/paste the script into a text file called “DetectCustomErrors.vbs” and save it to disk.  Then launch a command window that is elevated as admin and run “cscript DetectCustomErrors.vbs” to run it against your local web-server.  It will enumerate all of the applications within your web server and verify that the correct <customErrors> configuration has been specified.








HIt will flag any application where it finds that an application’s web.config file doesn’t have the <customErrors> section (in which case you need to add it), or doesn’t have it set correctly to workaround this attack (in which case you need to update it).  It will print “ok” for each application web.config file it finds that is fine.  This should hopefully make it easier to locate issues.
Note: We have developed this detection script over the last few hours, and will be refining it further in the future.  I will post an update in this section each time we make a change to it.

I got all these guidance from scottgu. 'n and thank-full to him.

Wednesday, September 22, 2010

Export list to xml

hai frienz,
2day i'm xporting content in a list to xml


using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

static void Main(string[] args)
        {
            List<Employee> empList = new List<Employee>();
            empList.Add(new Employee() { ID = 1, FName = "John", LName = "Shields", DOB = DateTime.Parse("12/11/1971"), Sex = 'M' });
            empList.Add(new Employee() { ID = 2, FName = "Mary", LName = "Jacobs", DOB = DateTime.Parse("01/17/1961"), Sex = 'F' });
            empList.Add(new Employee() { ID = 3, FName = "Amber", LName = "Agar", DOB = DateTime.Parse("12/23/1971"), Sex = 'M' });
            empList.Add(new Employee() { ID = 4, FName = "Kathy", LName = "Berry", DOB = DateTime.Parse("11/15/1976"), Sex = 'F' });
            empList.Add(new Employee() { ID = 5, FName = "Lena", LName = "Bilton", DOB = DateTime.Parse("05/11/1978"), Sex = 'F' });
            empList.Add(new Employee() { ID = 6, FName = "Susanne", LName = "Buck", DOB = DateTime.Parse("03/7/1965"), Sex = 'F' });
            empList.Add(new Employee() { ID = 7, FName = "Jim", LName = "Brown", DOB = DateTime.Parse("09/11/1972"), Sex = 'M' });
            empList.Add(new Employee() { ID = 8, FName = "Jane", LName = "Hooks", DOB = DateTime.Parse("12/11/1972"), Sex = 'F' });
            empList.Add(new Employee() { ID = 9, FName = "Robert", LName = "", DOB = DateTime.Parse("06/28/1964"), Sex = 'M' });
            empList.Add(new Employee() { ID = 10, FName = "Cindy", LName = "Fox", DOB = DateTime.Parse("01/11/1978"), Sex = 'M' });

            try
            {
                var xEle = new XElement("Employees",
                            from emp in empList
                            select new XElement("Employee",
                                         new XAttribute("ID", emp.ID),
                                           new XElement("FName", emp.FName),
                                           new XElement("LName", emp.LName),
                                           new XElement("DOB", emp.DOB),
                                           new XElement("Sex", emp.Sex)
                                       ));

                xEle.Save("D:\\employees.xml");
                Console.WriteLine("Converted to XML");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();

        }
    }

    class Employee
    {
        public int ID { get; set; }
        public string FName { get; set; }
        public string LName { get; set; }
        public DateTime DOB { get; set; }
        public char Sex { get; set; }
    }

hope it help u someway's



Have a nice day... 'N happy Coding :)

Monday, September 20, 2010

Difference between ExecuteReader,ExecuteNonQuery and ExecuteScalar.

Hi frienz,
i got a bit for ur nxt interview :). here i giving the keyhole difference b/w ExecuteReader,ExecuteNonQuery and ExecuteScalar.

* ExecuteReader : Use for accessing data. It provides a forwardonly,
read-only, connected recordset.

* ExecuteNonQuery : Use for data manipulation, such as Insert,
Update, Delete.

* ExecuteScalar : Use for retriving 1 row 1 col. value., i.e.
Single value. eg: for retriving aggregate function. It is faster
than other ways of retriving a single value from DB.

Hope it help u someways...
Have a nice day... 'N happy Coding :)

Wednesday, September 15, 2010

defining css with javascript as per criteria

 Hi,

I came across a requirement where the stylesheets referenced by a page had to be listed. The user was then given the ability to disable the stylesheet he did not want. Here’s how we can use the document.styleSheets collection to retrieve the collection of styleSheet objects that are referenced using a link; and then disable the stylesheet the user does not desire. A portion of the code is as given here:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="CSS/FloatDes.css" rel="stylesheet"
    title="Float layout" type="text/css" />
    <link href="CSS/RoundCorners.css" rel="stylesheet"
    title="Rounded Corners" type="text/css" /> 

    <script type="text/javascript">
        for (i = 0; i < document.styleSheets.length; i++) {
            alert(document.styleSheets[i].title);
            alert(document.styleSheets[i].href);
        }
    </script>
</head>
<body>

</body>
</html>



Similarly, if you have imported stylesheets using @import, you can access the style sheets using document.styleSheets[i].imports.
To disable a stylesheet programmatically, use this piece of code:
document.styleSheets[i].disabled = true;
To check if the styleSheet collection is supported on your browser, use this :
if (typeof document.styleSheets != "undefined")
 
If it is broken change the css  using javascript 
 This javascript demonstrates how you can programmatically 
reference a CSS link on a page. 
   <script type="text/javascript">
        function addCSS() {
            var headtg = document.getElementsByTagName('head')[0];
            if (!headtg) {
                return;
            }
            var linktg = document.createElement('link');
            linktg.type = 'text/css';
            linktg.rel = 'stylesheet';
            linktg.href = 'CSS/RoundCorners.css';
            linktg.title = 'Rounded Corners';
            headtg.appendChild(link);
        }
    </script>
</head>
<body onload="addCSS()"> 


Have a nice day... 'N happy Coding :)

Wednesday, September 1, 2010

64 Bit encryption in asp.net

Hi frienz,
2day i'm showing 64 bit encryption and decryption using a Key in asp.net.for that u need to import these name space's,


using System.Security.Cryptography;
using System.Text;
using System.IO;


Encryption



    private const string DEFAULT_KEY = "#kl?+@<z";



    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

        }

    }
    protected void txt_string_TextChanged(object sender, EventArgs e)
    {
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        MemoryStream MemoryStream = new MemoryStream();
        CryptoStream Cryptostream;
        string key="#kl?+@<z";
        CheckKey(ref key);
        des.Key = HashKey(key, des.KeySize / 8);
        des.IV = HashKey(key, des.KeySize / 8);

        string stringToEncrypt = txt_string.Text.Trim();

        byte[] inputBytes = Encoding.UTF8.GetBytes(stringToEncrypt);

        Cryptostream = new CryptoStream(MemoryStream, des.CreateEncryptor(), CryptoStreamMode.Write);
        Cryptostream.Write(inputBytes, 0, inputBytes.Length);
        Cryptostream.FlushFinalBlock();
        string result = Convert.ToBase64String(MemoryStream.ToArray());
        Label1.Text = result.ToString();
       
    }

    private static void CheckKey(ref string keyToCheck)
    {
        keyToCheck = keyToCheck.Length > 8 ? keyToCheck.Substring(0, 8) : keyToCheck;
        if (keyToCheck.Length < 8)
        {
            for (int i = keyToCheck.Length; i < 8; i++)
            {
                keyToCheck += DEFAULT_KEY[i];
            }
        }
    }
    private static byte[] HashKey(string key, int length)
    {
        SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();

        // Hash the key
        byte[] keyBytes = Encoding.UTF8.GetBytes(key);
        byte[] hash = sha1.ComputeHash(keyBytes);

        // Truncate hash
        byte[] truncatedHash = new byte[length];
        Array.Copy(hash, 0, truncatedHash, 0, length);
        return truncatedHash;
    }


Decryption

private const string DEFAULT_KEY = "#kl?+@<z";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

        }
    }
    protected void txt_String_TextChanged(object sender, EventArgs e)
    {

        string key = "#kl?+@<z";
        string txt = txt_String.Text.Trim();
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        MemoryStream memoryStream = new MemoryStream();
        CryptoStream cryptoStream;

        // Check whether the key is valid, otherwise make it valid
        CheckKey(ref key);

        des.Key = HashKey(key, des.KeySize / 8);
        des.IV = HashKey(key, des.KeySize / 8);
        byte[] inputBytes = Convert.FromBase64String(txt);

        cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(), CryptoStreamMode.Write);
        cryptoStream.Write(inputBytes, 0, inputBytes.Length);
        cryptoStream.FlushFinalBlock();

        Encoding encoding = Encoding.UTF8;
        lbl.Text= encoding.GetString(memoryStream.ToArray());
    }

    private static void CheckKey(ref string keyToCheck)
    {
        keyToCheck = keyToCheck.Length > 8 ? keyToCheck.Substring(0, 8) : keyToCheck;
        if (keyToCheck.Length < 8)
        {
            for (int i = keyToCheck.Length; i < 8; i++)
            {
                keyToCheck += DEFAULT_KEY[i];
            }
        }
    }
    private static byte[] HashKey(string key, int length)
    {
        SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();

        // Hash the key
        byte[] keyBytes = Encoding.UTF8.GetBytes(key);
        byte[] hash = sha1.ComputeHash(keyBytes);

        // Truncate hash
        byte[] truncatedHash = new byte[length];
        Array.Copy(hash, 0, truncatedHash, 0, length);
        return truncatedHash;
    }




Have a nice day... 'N happy Coding :)