Thursday 20 December 2012

Improvements in C# 4.0



1. Dynamic Lookup

There is a new static type named dynamic. We can use it as object of any type. If there is any error on its usage, we would get it on runtime only. For example:
dynamic integerValue = 1; 
dynamic stringValue = " a string"; 
dynamic Result = integerValue + stringValue;
Output of this would be: 1 a string.
But, if you change the last line to:
dynamic Result = integerValue & stringValue;
You will not get any compilation error, but the following error on runtime:
Operator '&' cannot be applied to operands of type 'int' and 'string'

2. Named Parameters

Named parameters allow you to ignore the parameter order and mention parameters with names in a different order. For example:

public void FunctionNamedParam(int x, int y , int z)
On function call, it would be:
FunctionNamedParam(x:1, z:3, y:2);
Although we are sending a value for the parameter z before its order in the function declaration, but these would be equal to x=1, y=2, z=3.

Monday 3 December 2012

Model Pop Up in MVC3


Model Pop Using Jquery UI

<!-- Model PopUp Content-->
<script type="text/javascript">
    var linkObj;
    $(function () {
        $(".authorize").button();

        $('#updateDialog').dialog({
            autoOpen: false,
            width: 950,
            resizable: false,
            modal: true,
            buttons: {
                "Post": function () {
                    $("#update-message").html(''); //make sure there is nothing on the message before we continue                        
                    $("#updateForm").submit();
                },
                "Unpost": function () {
                    var TransId = document.getElementById("hdnTransId").value;
                    var TransType = document.getElementById("hdnTransType").value;
                    if (parseInt(TransId) != 0 && parseInt(TransType) != 0) {
                        $(document).ready(function () {
                            $("#ajax_loading_div").addClass("loading");
                            $.ajax({
                                cache: false,
                                async: true,
                                type: "GET",
                                dataType: "json",
                                url: "../Services/FinTranService.svc/UnpostAuth",
                                data: { Id: TransId, Type: TransType },

                                contentType: "application/json;charset=utf-8",
                                success: function (r) {
                                    if (r != null) {
                                        $("#ajax_loading_div").removeClass("loading");
                                        $(this).dialog("close");
                                    }
                                },
                                error: function (e) {
                                    $("#ajax_loading_div").removeClass("loading");
                                    $(this).dialog("close");
                                }
                            });
                        });
                    }
                }
            }
        });
   
    $(".authorize").click(function () {
        //change the title of the dialgo
        linkObj = $(this);
        var dialogDiv = $('#updateDialog');
        var viewUrl = linkObj.attr('href');
        $.get(viewUrl, function (data) {
            dialogDiv.html(data);
            dialogDiv.dialog('open');
        });
        return false;
    });
});


In List
@Html.ActionLink("Authorize", "ViewAuthorize", new { TAid = item.TransId,mode=item.TransType}, new { @class = "authorize" })       


Pop up content page as partial view
@using (Ajax.BeginForm("ViewTransAuthorize", "FinanceTransaction", null,
        new AjaxOptions
        {
            UpdateTargetId = "update-message",
            InsertionMode = InsertionMode.Replace,
            HttpMethod = "POST",
            OnSuccess = "updateSuccess"
        }, new { @id = "updateForm" }))

    <div id="update-message" class="error invisible">
    </div>

//Your Content here

}

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