Monday 26 November 2012

Disable back button via javascript

For disabling the back button functionality in the browser
Use this code on the master page

 <script type="text/javascript">
function noBack() {
window.history.forward()
}
noBack();
window.onload = noBack;
window.onpageshow = function (evt) { if (evt.persisted) noBack() }
window.onunload = function () { void (0) }
</script>

Friday 23 November 2012

Show Loading Image on AJAX enabled WCF Service

The below code is used to Show Loading Image on AJAX enabled WCF Service when 
the service is processing the service.
 
<span id="ajax_loading_div" style="display: inline-block;
 width: 150px;"></span>
 
<script type="text/javascript" language="javascript">
$(document).ready(function () {
                    $("#ajax_loading_div").addClass("loading");
                    $.ajax({
                        cache: false,
                        async: true,
                        type: "GET",
                        dataType: "json",
                        url: "../Services/Services.svc/DeleteList",
                        data: { name: vatid },
 
                        contentType: "application/json;charset=utf-8",
                        success: function (r) {
                            $("#ajax_loading_div").removeClass("loading");
                            if (r != null) {
                                alert("Removed Successfully");
                            }
                        },
                        error: function (e) { alert(e.statusText); }
 
                    });
                });
</script>

Friday 16 November 2012

Validating the File Format and Content in C#

If anyone change the file extension from .jpg to .doc and try to upload the file into server.
The below code will validate the file content for .doc, .xls, .txt, .pdf, .docx, .xlsx

public bool EsCabeceraPDF(string fileName)
    {
        string ext = Path.GetExtension(fileName);
        byte[] buffer = null;
        FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        long numBytes = new FileInfo(fileName).Length;
             
      // validate the pdf content
       if (ext.ToLower() == ".pdf")
        {
            //%PDF−1.0
            // If you are loading it into a long, this is (0x04034b50).
            buffer = br.ReadBytes(5);

            var enc = new ASCIIEncoding();
            var header = enc.GetString(buffer);

            if (buffer[0] == 0x25 && buffer[1] == 0x50
                && buffer[2] == 0x44 && buffer[3] == 0x46)
            {
                //return header.StartsWith("%PDF-");
                return true;
            }
        }
   
         // validate the doc and xls content
        else if (ext.ToLower() == ".doc" || ext.ToLower() == ".xls")
        {
            buffer = br.ReadBytes(8);

            var enc = new ASCIIEncoding();
            var header = enc.GetString(buffer);

            if (buffer[0] == 0xD0 && buffer[1] == 0xCF
                && buffer[2] == 0x11 && buffer[3] == 0xE0 && buffer[4] == 0xA1 && buffer[5] == 0xB1
                && buffer[6] == 0x1A && buffer[7] == 0xE1)
            {
                return true;
            }
        }


        // validate the docx and xlsx content
        else if (ext.ToLower() == ".docx" || ext.ToLower() == ".xlsx")
        {
            buffer = br.ReadBytes(8);

            var enc = new ASCIIEncoding();
            var header = enc.GetString(buffer);

            if (buffer[0] == 0x50 && buffer[1] == 0x4B
                && buffer[2] == 0x03 && buffer[3] == 0x04 && buffer[4] == 0x14 && buffer[5] == 0x00
                && buffer[6] == 0x06 && buffer[7] == 0x00)
            {
                return true;
            }
        }
       // validate the txt content
        else if (ext.ToLower() == ".txt")
        {
            bool txt=true;
             string _strnewcontent = string.Empty;
             StreamReader _objreader = new StreamReader(fileName);
            string _filetxt = string.Empty;
            _filetxt = _objreader.ReadToEnd();
            if (_filetxt != "")
            {
                _strnewcontent = _objcls.SQL_Inject(_filetxt);

                string[] BlockList = { "--", ";--", ";", "@@", "/*", "*/", "alter", "begin", "create", "cursor", "declare", "delete", "drop", "exec", "execute", "fetch", "having", "insert", "open", "from", "select", "table", "union", "update", "procedure", "proc", "function", "<", ">", "script","_SCRIP" };
                             
                string temp_str3;
                //Str1 = StrIn.Trim().ToLower();
               
                for (int i = 0; i <= BlockList.Length - 1; i++)
                {
                   
                    temp_str3 = BlockList[i].ToString().Trim().ToLower();
                    //if (Str1.ToUpper().Contains(BlockList[i].ToUpper()))
                    if (_strnewcontent.Contains(temp_str3))
                    {
                        txt= false;
                    }
                }
            }
            return txt;
        }
       return false;
    }

Wednesday 14 November 2012

Validation of Viewstate MAC failed : Error

Recently i came across the "Validation of Viewstate MAC failed".


Solution to overcome this problem:



  • <pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode ="Never" />
(or)

  •  remove action attribute in form tag.

Tuesday 13 November 2012

Drop all tables from the Database

If u want to delete all User created tables from database.
This Query will help....



DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Table: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

Explanation: 
SELECT * FROM sysobjects 







Well, here is all the type definitions you find in sysobjects table :

D - default
F - SQLJ function
L - log
P - Transact-SQL or SQLJ procedure
PR - prepare objects (created by Dynamic SQL)
R - rule
RI - referential constraint
S - system table
TR - trigger
U - user table
V - view
XP - extended stored procedure

Category 2 is system objects and 0 is user created objects...
If u want to clean the database u can use below query on the third line.

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE category = 0 ORDER BY [name])

Procedure to get Last Row for Non-Identity tables

I had an situation where i want to get the last row for Non_Identity Table.
Then i used this query to get the last row inserted into the table.




DECLARE GETLAST CURSOR DYNAMIC FOR 
SELECT [ColumnName] FROM [dbo].[TableName]

OPEN GETLAST

FETCH LAST FROM GETLAST

CLOSE GETLAST

DEALLOCATE GETLAST

Below screenshoot will explain