Tuesday, 2 January 2018

Custom sorting of records in SQL using Case Statement

Sometimes we may have to sort records in such a way that we need some records to be always shown at top. At that cases below query may be helpful.

SELECT *   
FROM  Tablename  
ORDER BY CASE WHEN colname = 'Somevalue1' THEN null  
              WHEN colname = 'Somevalue2' THEN '1'  
              ELSE colname END ASC  

Here sorting is based on column 'colname' .

If 'colname' has value 'Somevalue1', it will be always at top as this query treats that value as null.
Similarly 'colname' having value 'Somevalue2', it will be treated as having value '1' and will be assigned in respective position based on that value while sorting.

Hope this will be helpful!

Preview Image files before uploading using Jquery & Html5

Here is a simple script to preview the image files before saving them using jquery & html5

First create a html page and put below fiel upload button and an preview div in it :-

<input type="file" id="imageUpload3" onchange="previewimg(this)" />  
   <br />  
   <div id="dvPreview3" style="margin-top: 40px;">  
   </div>  

Now we write the Jquery function as below :- 

<script>
    function previewimg(evt) {
        var regex = /^([a-zA-Z0-9\s_\\.\-:()])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
        if (regex.test($(evt).val().toLowerCase())) {
            if ($.browser.msie && parseFloat(jQuery.browser.version) <= 9.0) {
                alert("This browser does not support FileReader.");
            }
            else {
                if (typeof (FileReader) != "undefined") {
                    $("#dvPreview3").show();
                    $("#dvPreview3").html("<img/>");
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        $("#dvPreview3 img").attr("src", e.target.result);
                    }
                    reader.readAsDataURL($(evt)[0].files[0]);
                } else {
                    alert("This browser does not support FileReader.");
                }
            }
        } else {
            alert("Please upload a valid image file.");
            $('#imageUpload3').val('');
        }
    }  
</script>  

Now, once you browse images using fileupload control, you can preview images in the bottom div.

Hope this will be helpful!

Checking For Bad/Abuse Words On Form Posting Using An XML File In C#

Here is a simple code snippet to restrict users from entering bad or abuse words on your website forms.

This is very useful in feedback forms, comments sections, etc..

Step 1: Create a aspx page “Bad-words-check.aspx” as below.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Bad-words-check.aspx.cs"  
  
Inherits="ResponsiveForms_ASP_NET_Bad_words_Bad_words_check" %>  
    <!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 id="Head1" runat="server">  
        <title></title>  
        <style>  
            body {  
                font-family: 'Arial';  
            }  
        </style>  
    </head>    
    <body>  
        <form id="form2" runat="server">  
            <div> <textarea runat="server" id="txtmsg" class="txtarea Txtbox" rows="6" cols="50" style="resize: none;  
  
width: 300px; height: 120px;"></textarea> <br /><br />  
                <asp:Button ID="btnpost" ClientIDMode="Static" runat="server" Text="SUBMIT" Width="100px" OnClick="btnpost_Click" /> <br /><br />  
                <asp:Label ID="lblmsg" runat="server" style="color:Red;font-weight:bold;"></asp:Label>  
            </div>  
        </form>  
    </body>  
</html>   


Step 2: Make cs file as below,

using System;  
using System.Collections.Generic;  
using System.Web;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.Xml;  
public partial class ResponsiveForms_ASP_NET_Bad_words_Bad_words_check: System.Web.UI.Page {  
    protected void Page_Load(object sender, EventArgs e) {}  
    protected void btnpost_Click(object sender, EventArgs e) {  
        try {  
            XmlDocument xmlDoc = new XmlDocument(); // Create an XML document object  
            xmlDoc.Load(Server.MapPath("../WordList.xml")); // Load the XML document from the specified file  
            // Get elements  
            XmlNodeList badwords = xmlDoc.GetElementsByTagName("word");  
            for (int i = 0; i < badwords.Count; i++) {  
                if (txtmsg.Value.ToUpperInvariant().Contains(badwords[i].InnerText.ToUpperInvariant())) {  
                    lblmsg.Text = "Your text contains bad/abuse words!";  
                    break;  
                } else lblmsg.Text = "Your text is clean!";  
            }  
        } catch (Exception ex) {}  
    }  
}  

Step 3: Add xml file “WordList.xml” to your project,

Now you can run the page and see the result. If you have any further words to be restricted then you can add it manually to the xml file.

For the source code of the pages and xml file, pelase visit the blog I have written in C-Sharpcorner website - Click here.

Reading Data Of A CSV File Without Saving It In C#

We can read the data of a CSV file without saving it onto a server. Given below are the steps :-

1) Create an aspx page and paste the following code into it. It will create an File upload control and an button.

<asp:FileUpload ID="txt_Upload" runat="server" />  
<asp:Button ID="btnsubmit" Text="Submit" runat="server" OnClick="btnsubmitclick"/>  


2) In the cs file, paste the below method.

protected void btnsubmitclick(object sender, EventArgs e)   
{  
    System.IO.StreamReader myReader = new System.IO.StreamReader(txt_Upload.PostedFile.InputStream);  
    string output = myReader.ReadToEnd();  
    Response.Write(output);  


Once you select an csv file and click on submit button, data from csv file will be read without saving the file to server and will be displayed in the page.

Hope this will be helpful!

Friday, 29 December 2017

Basic Javascript Array Methods

Understanding some of the basic built-in javascript array methods 

This blog gives a brief overview of the basic javascript methods that are related to arrays.
    
1. concat()

This methods joins two arrays and outputs a new array

<script type="text/javascript">
    //concat()
    var arr1 = [1, 2, 3];
    var arr2 = [4, 5, 6];
    var resultarr = arr1.concat(arr2);
    document.write(resultarr); //Output will be 1,2,3,4,5,6
</script>


2. filter()

This method is used to filter out an array based on some functions. The output will be an array with elements from parent array which satisfies the condition.

<script type="text/javascript">
    //filter()
    var arr1 = ["1", "a", "b", "2", "3"];
    var resultarr = arr1.filter(checkifnumber); //Here we call a function to check whether element is number or not
    document.write(resultarr); //Output will be 1,2,3

    function checkifnumber(element, index, array) {
        return (!isNaN(parseFloat(element)));
    }
</script>

    
3. indexOf()

This method returns the index of the first occurance of an particular element in an array. If element not found in the array, then returns -1.

<script type="text/javascript">
    //indexOf()
    var arr1 = ["1", "a", "b", "2", "3", "b"];
    document.write(arr1.indexOf("b")); //Output will be 2
</script>


4. lastIndexOf()

This method returns the index of the last occurance of an particular element in an array. If element not found in the array, then returns -1.

<script type="text/javascript">
    //lastIndexOf()
    var arr1 = ["1", "a", "b", "2", "3", "b"];
    document.write(arr1.lastIndexOf("b")); //Output will be 5
</script>
    

5. join()

This method joins elements of an array into a string. We can pass a separator as an parameter to join method.

<script type="text/javascript">
    //join()
    var arr1 = ["This", "is", "a", "example", "of", "array", "join"];
    document.write(arr1.join(" ")); //Output will be "This is a example of array join"
    document.write(arr1.join("-")); //Output will be "This-is-a-example-of-array-join"
</script>    


6. reverse()

This method reverses teh order of elements in the array.

<script type="text/javascript">
    //reverse()
    var arr1 = ["a", "b", "c", "d", "e", "f", "g"];
    var resultarr = arr1.reverse(); // It will be  ["g", "f", "e", "d", "c", "b", "a"]
    document.write(resultarr); //Output will be g,f,e,d,c,b,a 
</script>


7. slice()

This method extracts a given number of elements from an array and returns a new array. We can pass begin & end (not included in reulting array) index of elements to be extracted as parameters.

<script type="text/javascript">
    //slice()
    var arr1 = ["a", "b", "c", "d", "e", "f", "g"];
    var resultarr1 = arr1.slice(1, 3); // It will be  ["b", "c"]
    var resultarr2 = arr1.slice(3, 6); // It will be  ["d", "e", "f"]
</script>


8. sort()

This method sorts the elements of an array in an alphabetical order.

<script type="text/javascript">
    //sort()
    var arr1 = ["red", "blue", "white", "green"];
    var resultarr1 = arr1.sort(); // It will be  ["blue", "green", "red", "white"]

    var arr2 = [5, 27, 16, 8];
    var resultarr2 = arr2.sort(3, 6); // It will be  [16, 27, 5, 8]
</script>

Here in the above script, we can find that the numerical array is also sorted in alphabetic order. Inorder to sort it in numerical order, we can wreite a custom function and call it inside our sort function as below.

<script type="text/javascript">
    //sort()
    var arr1 = [5, 27, 16, 8];
    var resultarr1 = arr1.sort(sortNumber); // It will be  [5, 8, 16, 27]

    function sortNumber(num1, num2) {
        return num1 - num2;
    }
</script>


Hope this will be helpful!

Basic Javascript Date Methods

Understanding some of the basic built-in javascript date methods 

This blog gives a brief overview of the basic javascript methods that are related to dates.
    
1. Date()

This method returns current date with time (local date & time).

<script type="text/javascript">
        //Date()
        document.write(Date()); //Output will be current date
</script>


2. getDate()

This method returns current day from an given date.

<script type="text/javascript">
    //getDate()
    var date = new Date();
    document.write(date.getDate()); //Output will be current day

    var date = new Date("Fri Oct 21 2016 14:36:25");
    document.write(date.getDate()); //Output will be 21
</script>


3. getDay()

This method returns the day of a week. Return will be an integer corresponding to particular day. (0 for Sunday, 1 for Monday, etc..)
    
<script type="text/javascript">
    //getDay()
    var date = new Date();
    document.write(date.getDay()); //Output will be index of current day of week

    var date = new Date("Fri Oct 21 2016 14:36:25");
    document.write(date.getDay()); //Output will be 5
</script>
    

4. getFullYear()

This method returns year from a provided date.

<script type="text/javascript">
    //getFullYear()
    var date = new Date();
    document.write(date.getFullYear()); //Output will be current year

    var date = new Date("Fri Oct 23 2015 14:36:25");
    document.write(date.getFullYear()); //Output will be 2015
</script>


5. getMonth()

This method returns month as integer (0 for January, 1 for February, etc..) from a provided date.

<script type="text/javascript">
    //getMonth()
    var date = new Date();
    document.write(date.getMonth()); //Output will be current month

    var date = new Date("Fri Oct 23 2016 14:36:25");
    document.write(date.getMonth()); //Output will be 10
</script>

    
6. getHours()

This method returns hour value from given date.

<script type="text/javascript">
    //getHours()
    var date = new Date();
    document.write(date.getHours()); //Output will be current hour

    var date = new Date("Fri Oct 21 2016 14:36:25");
    document.write(date.getHours()); //Output will be 14
</script>
    

7. getMinutes()

This method returns minute value from given date.

<script type="text/javascript">
    //getMinutes()
    var date = new Date();
    document.write(date.getMinutes()); //Output will be current minute

    var date = new Date("Fri Oct 21 2016 14:36:25");
    document.write(date.getMinutes()); //Output will be 36
</script>


8. getSeconds()

This method returns seconds value from given date.

<script type="text/javascript">
    //getSeconds()
    var date = new Date();
    document.write(date.getSeconds()); //Output will be current seconds value

    var date = new Date("Fri Oct 21 2016 14:36:25");
    document.write(date.getSeconds()); //Output will be 25
</script>

Hope this will be helpful!

Basic Javascript Number Methods

    Understanding some of the basic built-in javascript number methods

    This blog gives a brief overview of the basic javascript methods that are related to numbers.

    1. isNaN()

    Check whether a value is a number and returns true if not a number (NaN stands for Not a Number)
 
 <script type="text/javascript">
        //isNaN()
        document.write(isNaN(25)); //Output is false
        document.write(isNaN("This is a string")); //Output is true
        document.write(isNaN("77")); //Output is false
        document.write(isNaN("05/10/2016")); //Output is true
    </script>


    2. parseInt()

    Converts a string to an Integer. If string doesn't start with a valid number, it returns NaN

 <script type="text/javascript">
        //parseInt()
        document.write(parseInt(25)); //Output is 25
        document.write(parseInt("This is a string")); //Output is NaN
        document.write(parseInt("77.56")); //Output is 77
        document.write(parseInt("05/10/2016")); //Output is 5
    </script>


    3. parseFloat()
 
    Converts a string to an Float value. If string doesn't start with a valid number, it returns NaN

 <script type="text/javascript">
        //parseFloat()
        document.write(parseFloat(25)); //Output is 25
        document.write(parseFloat("This is a string")); //Output is NaN
        document.write(parseFloat("77.56")); //Output is 77.56
        document.write(parseFloat("05/10/2016")); //Output is 5
    </script>

 
    4. toFixed()

    Converts a number to a decimal value with specified number of digits after the decimal point.

  <script type="text/javascript">
        //toFixed()
        document.write((25).toFixed(2)); //Output is 25.00
        document.write((25.58).toFixed(2)); //Output is 25.58
        document.write((25.52).toFixed(3)); //Output is 25.520
        document.write((25.4578).toFixed(3)); //Output is 25.458
    </script>


    5. toString()

    Converts a number to a string.

<script type="text/javascript">
        //toString()
        document.write((25).toString()); //Output is 25
        document.write((25.58).toString()); //Output is 25.58
        document.write((25 + 50).toString()); //Output is 75
        document.write((25.52 + 24.64).toString()); //Output is 50.16
    </script>


    6. isFinite()

    Checks whether if a number is a finite number and returns true or false accordingly

 <script type="text/javascript">
        //isFinite()
        document.write(isFinite(25)); //Output is true
        document.write(isFinite("This is a string")); //Output is false
        document.write(isFinite("77")); //Output is true
        document.write(isFinite("05/10/2016")); //Output is false
    </script>

 
    7. toPrecision()

    Converts a number to a decimal number string with total digits (digits on left and right of decimal point) as specified.

  <script type="text/javascript">
        //toPrecision()
        document.write((2).toPrecision(2)); //Output is 2.0
        document.write((25.58).toPrecision(2)); //Output is 26
        document.write((25.52).toPrecision(3)); //Output is 25.5
        document.write((25.4578).toPrecision(4)); //Output is 25.46
    </script>


    Hope this will be helpful!