Saturday, November 1, 2014

How to check stream has Image or not

No comments:
Let's suppose you have a page on which user upload there image and you want to validate that user is uploading image file only not other file format.The one easy solution is use regex and validate the extension of the file but if user rename the extension of the file and upload some executable code.Following is the simple c# code snippet that check the file type by the header value.

private bool IsImage()
    {
        bool isImage = false;
        FileStream stream = new FileStream(Server.MapPath(@"Images\a.txt"), FileMode.Open, FileAccess.Read);
        StreamReader reader = new StreamReader(stream);
        // Read the first 25 characters, we will be checking for a GIF or JPG signature.
        char[] strBuffer = new char[25];
        reader.ReadBlock(strBuffer, 0, 25);
        string stringBuffer = new string(strBuffer);
        // Is this an image?
        if (stringBuffer.IndexOf("GIF8") > -1 || stringBuffer.IndexOf("JFIF") > -1)
        {
            isImage = true;
            Response.Write("It's an image");

        }
        else
        {
            Response.Write("It's HTML or other junk.");
        }
        return isImage;
    }
Read More

How To Change your ASP.Net controls at runtime

No comments:
Lets say you are working in a fairly large asp.net application. Now because of situation (or clients request) you want to change all the textbox or button control to some server control or user control. This can be very very tedious JOB if you are using Asp.net 1.X. But if you are using Asp.net 2.0 , there is a very easy way to get this done using tagMapping
it’s a way to turn all instances of a type into another type at compile time. In human language it means that it can turn all e.g. System.Web.UI.WebControls.Textbox (in our example ) instances in the entire website into another control.That is so cool that I had to do a little example. I’ve created a very simple control that inherits from a TextBox and overrides the Text property so that it HTML encodes the text. I placed it in the App_Code folder and called it SafeTextBox.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
///
/// Summary description for SafeTextBox
///
public class SafeTextBox : System.Web.UI.WebControls.TextBox
{
    public override string Text
    {
        get
        {
            return base.Text;
        }
        set
        {
            base.Text = System.Web.HttpUtility.HtmlEncode(value);
        }
    }
}
Then I needed to hook the tag mapping up in the web.config to convert all the text boxes into SafeTextBox instances. It simply converts all TextBox instances on the entire site. Here is what’s needed in the web.config:

<pages> <tagMapping> <add tagType="System.Web.UI.WebControls.TextBox" mappedTagType="SafeTextBox"/> </tagMapping> </pages>
After we add the following line of code in the web.config file all the TextBox control will be mapped to the TextBox.
Read More

How to change some text before it is sent to the client.

No comments:

In this post,I will show you how to modify the response before it is sent to the client.The trick here is to override the Render method of the Page class and modify the response.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="InterceptHtml.aspx.cs"
Inherits="InterceptHtml" %>

<!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 runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           Hello World!
           <br />
           Hi
       </div>
   </form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;

public partial class InterceptHtml : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {

       Response.Filter = new ReplaceHTML(Response.Filter);


   }
   /// <summary>
   /// Second Method!!!!!!! overide the Render Method.
   /// </summary>
   /// <param name="writer"></param>
   protected override void Render(HtmlTextWriter writer)
   {


       StringWriter output = new StringWriter();
       base.Render(new HtmlTextWriter(output));
       writer.Write(output.ToString().Replace("Hi", "This is the replaced text!
Welcome to <a href=\"http://www.aspdotnetcodebook.blogspot.com\
">www.aspdotnetcodebook.blogspot.com</a>"));
   }
}
II nd Method
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// To intercept and get a reference to the HTML, we now need to create a
/// class to inherit System.IO.Stream. So, create a new class in
/// </summary>
public class ReplaceHTML : System.IO.Stream
{

    private System.IO.Stream Base;

    public ReplaceHTML(System.IO.Stream ResponseStream)
    {
        if (ResponseStream == null)
            throw new ArgumentNullException("ResponseStream");
        this.Base = ResponseStream;
    }






    public override int Read(byte[] buffer, int offset, int count)
    {
        return this.Base.Read(buffer, offset, count);
    }


    public override void SetLength(long value)
    {

    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        // Get HTML code 
        string HTML = System.Text.Encoding.UTF8.GetString(buffer, offset, count);

        // Replace the text with something else 
        HTML = HTML.Replace("Hello World!", "I've replaced the Hello World example!");

        // Send output 
        buffer = System.Text.Encoding.UTF8.GetBytes(HTML);
        this.Base.Write(buffer, 0, buffer.Length);
    }

    public override bool CanRead
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    public override bool CanSeek
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    public override bool CanWrite
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    public override void Flush()
    {
        HttpContext.Current.Response.Flush();

    }

    public override long Length
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    public override long Position
    {
        get
        {
            throw new Exception("The method or operation is not implemented.");
        }
        set
        {
            throw new Exception("The method or operation is not implemented.");
        }
    }

    public override long Seek(long offset, System.IO.SeekOrigin origin)
    {
        throw new Exception("The method or operation is not implemented.");
    }
}
Read More

How To - Prevent Script Attacks

No comments:
This post describes the request validation feature of ASP.NET where, by default, the application is prevented from processing unencoded HTML content submitted to the server. This request validation feature can be disabled when the application has been designed to safely process HTML data.
Applies to ASP.NET 1.1 and ASP.NET 2.0.
Check out this article
Read More

How to return data from ajax call

No comments:
In this post,I will show you how to return data from ajax request.As you know that you can not return data from ajax request but if you want to perform some action on return data of ajax.The better approach is to organize your code properly around callbacks. In the example,you can make GetUsers accept a callback and use it as success callback.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ReturnAjax.aspx.cs" Inherits="ReturnAjax" %>

<!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 runat="server">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <title></title>
    <script type="text/javascript">
        $(document).ready(function () {
            function GetUsers(name, callback) {
                $.ajax({

                    type: "POST",
                    async: true,
                    url: "ReturnAjax.aspx/GetUsers",
                    data: "{name:'" + name + "'}",
                    dataType: "json",
                    contentType: "application/json",
                    success: function (data) {
                        //Pass return data to callback function and do the operation
                        callback(data.d);
                    }
                });
            }
            $("#check").click(function () {
                GetUsers($("#txtName").val(), function (users) {
                    $('#result').empty();
                    $.each(users, function (index, user) {
                        $('#result').append('<p><strong>' + user.UserId + ' ' + user.Name + '</br>');

                    });
                });
            });
        });

      
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <input type="button" name="check" value="check " id="check" /><br />
        <div id="result">
        </div>
    </div>
    </form>
</body>
</html>
AjaxReturn.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ReturnAjax : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static UserData[] GetUsers(string name)
    {
        return UserData.Users.Where(x => x.Name.StartsWith(name)).ToArray();
    }
}
public class UserData
{
    public string UserId { get; set; }
    public string Name { get; set; }

    public static List<UserData> Users
    {
        get
        {
            return new List<UserData>()
                      {
                          new UserData(){UserId = "1",Name = "Bill"},
                          new UserData(){UserId = "2",Name = "Booler"},
                          new UserData(){UserId = "3",Name = "Scott"},
                          new UserData(){UserId = "4",Name = "Anders"},
                      };
        }
    }
}
Read More