Friday, 24 June 2016

Print option in web page

  <!--Include JQuery header file -->
 <!--prin script put it in end of the body -->
    <script type="text/javascript">
        $(document).ready()
        {
            function printData() {
                //alert(1);
                var divToPrint = document.getElementById("PrintelementID");
                newWin = window.open("");
                newWin.document.write(divToPrint.outerHTML);
                newWin.print();
                newWin.close();
            }
         //btnPrint button id
            $('#btnPrint').on('click', function () {
                               printData();
            })

        }
    </script>

Wednesday, 15 June 2016

Client Side common validation using Jquery

//class name based date
$(function () {
    $(".datepicker").datepicker({ dateFormat: "mm/dd/yyyy" });
    //$(".datepicker").datepicker({ dateFormat: "dd-mm-yy" });
    //dateFormat: 'dd-mm-yy'
});

//Common Messagebox
function commonMsgBox(msg) {
    try {
        alert(msg);
    }
    catch (exception) {
        return;
    }
    finally {
        return;
    }

}

Allow only numbers in input text
 <input type="text" onkeypress="allow_only_numbers(event);" />
function allow_only_numbers(e) {
    try {

        var kCode;
        if (e.keyCode) {
            kCode = e.keyCode;

        }
        else {
            kCode = e.charCode;
            if (kCode == 37 || kCode == 46 || kCode == 39 || kCode == 35 || kCode == 36 || kCode == 38) {
                e.preventDefault();
                return;
            }
        }
        var key_codes = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 8, 37, 39, 46, 35, 36, 9];

        if (!($.inArray(kCode, key_codes) >= 0)) {
            e.preventDefault();

        }

    }
    catch (ex) {

    }
}

Allow only float values in input text
 <input type="text" id="floattxt" onkeypress="allow_only_numbers(event,'floattxt');" />
function allow_only_Float(e, cntrl) {
    try {
        var tChkDecimal = $("#" + cntrl).val();

        var kCode;
        if (e.keyCode) {
            kCode = e.keyCode;
        }
        else {
            kCode = e.charCode;
            if (kCode == 37 || kCode == 39 || kCode == 35 || kCode == 36 || kCode == 38) {
                e.preventDefault();
                return;
            }
        }
        if (kCode == 46) { if ((tChkDecimal.split(".").length) > 1) { e.preventDefault(); return; } }
        var key_codes = [46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 8, 37, 39, 46, 35, 36, 9];
        if (!($.inArray(kCode, key_codes) >= 0)) {
            e.preventDefault();
            return;
        }

    }
    catch (ex) {

    }
}



Allow only float TAX% values <=99.9 in input text
 <input type="text" id="floatTaxttxt" onkeypress="allow_only_Float_tax(event,'floatTaxttxt');" />
function allow_only_Float_tax(e, cntrl) {
    try {
        var tChkDecimal = $("#" + cntrl).val();

        var kCode;
        if (e.keyCode) {
            kCode = e.keyCode;
        }
        else {
            kCode = e.charCode;
            if (kCode == 37 || kCode == 39 || kCode == 35 || kCode == 36 || kCode == 38) {
                e.preventDefault();
                return;
            }
        }
        if (tChkDecimal != null && tChkDecimal != "") {
            if (parseFloat(tChkDecimal) > 99 && kCode != 8 && kCode != 46 && kCode != 37 && kCode != 39)
            { e.preventDefault(); $("#" + cntrl).val(tChkDecimal.substring(0, tChkDecimal.length - 1)); return; }
        }
        if (kCode == 46) { if ((tChkDecimal.split(".").length) > 1) { e.preventDefault(); return; } }
        var key_codes = [46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 8, 37, 39, 46, 35, 36, 9];
        if (!($.inArray(kCode, key_codes) >= 0)) {
            e.preventDefault();
            return;
        }

    }
    catch (ex) {

    }
}

Allow only Alphabets in input text
 <input type="text" id="txtText" onkeypress="allow_only_Float_tax(event,'txtText');" />
function allow_only_alphabets_name(e) {
    try {
        var kCode;
        if (e.keyCode) {
            kCode = e.keyCode;

        }
        else {
            kCode = e.charCode;
            if (kCode == 37 || kCode == 46 || kCode == 39 || kCode == 35 || kCode == 36 || kCode == 38) {
                e.preventDefault();
                return;
            }
        }

        var key_codes = [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 32, 46, 8, 9, 37, 39, 40, 46, 35, 36];
        if (!($.inArray(kCode, key_codes) >= 0)) {
            e.preventDefault();
        }

    }
    catch (ex) {
        //commonMsgBox(ex.toString);
    }
}


//regular exp value based validate Mobile numbers
function validateNumbers(numbers) {
    try{
        var sum = 0;    
     
        var no = parseInt(numbers);
        while (no > 0) {
            sum = sum + no % 10;
            no = Math.floor(no / 10);
        }
        //  alert("Sum of digits  "+sum);
        if (sum == 0) {
            return false;
        }
        var filter = /^[0-9]+$/;
        return filter.test(numbers);
    }
    catch (ex)
    {
        alert(ex);
    }
}

//regular exp value based validate Email
function validateEmail(email) {
    var re = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

    return re.test(email);
}

//on change image validate
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        //reader.onload = function (e) {
        //    $('#emp_img').attr('src', e.target.result);
        //    $('#EMAddImag').attr('src', e.target.result);
        //}

        reader.readAsDataURL(input.files[0]);
    }
}

$(".imagefile").change(function () {
    readURL(this);
    var val = $(this).val();
  
    switch (val.substring(val.lastIndexOf('.') + 1).toLowerCase()) {
        case 'gif': case 'jpg': case 'png': case 'jpeg': case 'GIF' : case 'JPG': case 'PNG': case 'JPEG':
            break;
        default:
            $(this).val('');
            // error message here
            commonMsgBox("Upload only image format (jpg,jpeg,gif,png)");
            break;
    }
    //alert(this.files[0].size/1000);
    var imagesize = parseFloat(this.files[0].size) / 1000;//kb to mb
    if(imagesize>2000)
    {
        $(this).val('');
        commonMsgBox("Image Size Too Large You Can Upload Image Size Less Than 2MB only!")
    }
});

//Date validate
function checkdate(input) {
    alert(input);
    var validformat = /^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
    var returnval = false
    if (!validformat.test(input.value))
        alert("Invalid Date Format. Please correct and submit again.")
    else { //Detailed check for valid date ranges
        var monthfield = input.value.split("/")[0]
        var dayfield = input.value.split("/")[1]
        var yearfield = input.value.split("/")[2]
        var dayobj = new Date(yearfield, monthfield - 1, dayfield)
        if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield))
            alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
        else
            returnval = true
    }
    if (returnval == false) input.select()
    return returnval
}

Sunday, 12 June 2016

Sum of items from List in C#

Public Class MyList
{
Public  double Amount{get;set;}
//in controller
List<MyList>myList=new List<MyList>();
 myList.add(new List<MyList>()
{
 Amount=10, 
});
 myList.add(new List<MyList>()
 { 
   Amount=20,  }); 
double total = myList.Sum(item => item.Amount);

Wednesday, 8 June 2016

Generate 512hash in c#

 public string Generatehash512(string text)
    {

        byte[] message = Encoding.UTF8.GetBytes(text);

        UnicodeEncoding UE = new UnicodeEncoding();
        byte[] hashValue;
        SHA512Managed hashString = new SHA512Managed();
        string hex = "";
        hashValue = hashString.ComputeHash(message);
        foreach (byte x in hashValue)
        {
            hex += String.Format("{0:x2}", x);
        }
        return hex;

    }

OTP_CODE GENERATION IN C#

 public string OTP_CODE()
    {
        var nums = "123456789";
        var random = new Random();
        string otp = new string(
            Enumerable.Repeat(nums, 4)
                      .Select(s => s[random.Next(s.Length)])
                      .ToArray());
        return otp;
    }

jquery filter function for table

jquery filter function for table

  <script>

            $(":checkbox").change(function ()
            {
                busFilterJqFun();
            });
            $("input[name='radioacnonac']").change(function () {
               
                busFilterJqFun();
              
            });
            $('input[name=radiosleeper]').change(function () {
              
                busFilterJqFun();
              
            });
            function busFilterJqFun()
            {
               
                $("#grvBusDetails tr").hide();
                $('#divfilteroops').empty();
                var arrbusname = [];
             
                var rows = $("#grvBusDetails tr");
             
                $("input[name='TravelName_chkbox']").each(function ()
                {
                    if ($(this).is(":checked"))
                    {
                        arrbusname.push('.' + $(this).val());
                    }
                });
                var arrbdname = [];
                $("input[name='boardinglist_chkbox']").each(function () {

                    if ($(this).is(":checked")) {
                        arrbdname.push('.' + $(this).val());
                    }
                });
                var arrdpname = [];
                $("input[name='droppingdatalist_chkbox']").each(function () {

                    if ($(this).is(":checked")) {
                        arrdpname.push('.' + $(this).val());
                    }
                });//droppingdatalist_chkbox
               
                var AcOrNonAc = $("input[name='radioacnonac']:checked").val();
                var sleeperOrseater = $("input[name='radiosleeper']:checked").val();
            
              
               
                if (arrbusname == "" && arrbdname == "" && AcOrNonAc == "" && arrdpname=="")
                {
                    rows.show();
                }
                else
                {
                    // otherwise, hide everything...
                    $("#grvBusDetails tr").hide();

                    // then show only the matching items
                    rows = $("#grvBusDetails tr").filter(arrbusname.length ? arrbusname.join(',') : '*');
                    //rows = $("#grvBusDetails tr").filter(arrbdname.length ? arrbdname.join(',') : '*');
                    if (arrbdname != "")
                    {
                              
                                rows = $(rows).filter(arrbdname.length ? arrbdname.join(',') : '*');
                             
                    }
                    if (arrdpname != "")
                    {
                       
                        rows = $(rows).filter(arrdpname.length ? arrdpname.join(',') : '*');
                      
                    }

                    if (AcOrNonAc)
                    {
                        AcOrNonAc = '.' + AcOrNonAc;
                      
                       
                        rows = $(rows).filter(AcOrNonAc != ".1" ? AcOrNonAc : '*');
                      
                    }
                    if (sleeperOrseater)
                    {
                        sleeperOrseater = '.' + sleeperOrseater;
                       
                        rows = $(rows).filter(sleeperOrseater != ".1" ? sleeperOrseater : '*');
                      
                    }
                    if (rows.size() > 0)
                    {
                        rows.show();
                    }
                    else
                    {
                        $('#divfilteroops').empty();
                        $('#divfilteroops').append('OOps No Bus found!!!!');
                    }
                }
            }

   </script>

Amount to words conversion in c#

  public string NumberToWords(Int64 number)
    {
        if (number == 0)
            return "zero";

        if (number < 0)
            return "minus " + NumberToWords(Math.Abs(number));

        string words = "";

        if ((number / 1000000) > 0)
        {
            words += NumberToWords(number / 1000000) + " million ";
            number %= 1000000;
        }

        if ((number / 1000) > 0)
        {
            words += NumberToWords(number / 1000) + " thousand ";
            number %= 1000;
        }

        if ((number / 100) > 0)
        {
            words += NumberToWords(number / 100) + " hundred ";
            number %= 100;
        }

        if (number > 0)
        {
            if (words != "")
                words += "and ";

            var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
            var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };

            if (number < 20)
                words += unitsMap[number];
            else
            {
                words += tensMap[number / 10];
                if ((number % 10) > 0)
                    words += "-" + unitsMap[number % 10];
            }
        }

        return words;
    }