Tuesday, 2 January 2018

Getting The Count Of Words And Characters In A Text Using JavaScript

With the below code, when we enter some text in an textbox and click button, we will get the count of words and characters in the text entered. 

<input type="text" id="txtinput" />  
<button onclick="countwords()">  
        Check Count</button>  
<script>
    function countwords() {
        var val = document.getElementById("txtinput").value;
        var words = 0, chars = 0;
        if (val != "") {
            words = val.replace(/\s+/gi, ' ').split(' ').length; // Count words  
            chars = val.length;                                 // Count characters  
        }
        alert(chars + " Characters & " + words + " Words!");
    }  
</script>

Hope this will be helpful!

Simplest Code To Import Data From A Xml File To Dataset

Here is a Simple one line code to import xml file to dataset :-

DataSet ds = new DataSet();  
ds.ReadXml(Server.MapPath("XMLFile.xml"), XmlReadMode.InferSchema); 

Hope this will be helpful!

Updating A Table Using Inner Join In SQL

Sometimes we may need to update some columns in a table in SQL with values from columns of another table. For this purpose we can use inner join with update query as below.

UPDATE t1  
SET t1.somecol1 = t2.somecol2  
FROM table1 t1  
INNER JOIN table2 t2 ON t1.id = t2.id  

With above query, column 'somecol1' of table1 will be updated with values from 'somecol2' of table2 satisfying the inner join condition.

Hope this will be helpful!

Forcing Browsers to Fetch js/css Files From Server Instead of Cache

Sometimes we have to make some changes in our css or js files. After this we upload it to our servers. But while opening our pages in browser, it wont reflect our changes. We may have to clear our browser cache to see that changes. This is not a feasible solution for websites with thousands of visitors. So here is simple tip we can use in our websites.

First declare a global application variable in our global.asax file

void Application_BeginRequest(Object source, EventArgs e)  
{  
    Application["version"] = "1.0";  


Now while including js/css files in our aspx pages, just add a query string with them as follows.

<script src="youjsfilename.js?ver=<%= Application["version"] %>" type="text/javascript"></script>  
   <link href="youcssfilename.css?ver=<%= Application["version"] %>" rel="stylesheet"  
       type="text/css" /> 
        
Now whenever you make changes in these files, you can just change the value of "version" in global file.

void Application_BeginRequest(Object source, EventArgs e)  
{  
    Application["version"] = "1.1";  
}  

Hope this will be helpful!

Selecting Specific set of Rows using OFFSET and FETCH in SQL

We can use OFFSET and FETCH keywords to select specific number of rows in SQL Select query. 

SELECT *  
FROM Tablename  
ORDER BY colname  
OFFSET 0 ROWS  
FETCH NEXT 10 ROWS ONLY  

The above query will returns first 10 records. 

SELECT *  
FROM Tablename  
ORDER BY colname  
OFFSET 10 ROWS  
FETCH NEXT 10 ROWS ONLY  

Above query will returns records 11 to 20.

Likewise you can increase OFFSET values to get next set of records. 

Hope this will be helpful!

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!

Monday, 9 January 2017

Filtering DataSet Based On Column Values In C#

In this blog, we will learn, how to filter a DataSet, based on the value of a particular column. Suppose, we have a DataSet ‘ds’ with the records of some users, given below:





















Now, we want to filter this DataSet, based on States.

For example, we have to get the records with State as “Maharashtra” only
For that we can write the code, given below:
  1. ds.Tables[0].DefaultView.RowFilter = "State = 'Maharashtra'";  
  2. DataTable dt = (ds.Tables[0].DefaultView).ToTable();  
Now, in DataTable dt, we will get the records from DataSet ds with State=Maharashtra.






















We can also set this filtered DataSet directly as the DataSource of Gridview.
  1. ds.Tables[0].DefaultView.RowFilter = "State = 'Karnataka'";  
  2. GridView1.DataSource = ds.Tables[0].DefaultView;  
  3. GridView1.DataBind();  









We can also give multiple conditions in filtering with “and” or “or” operators. 
  1. ds.Tables[0].DefaultView.RowFilter = "State = 'Maharashtra' and City='Nagpur'";  
  2. DataTable dt = (ds.Tables[0].DefaultView).ToTable();   
Hope that this will be helpful for someone out there!

Changing The Default Values Of Select/Edit In SQL Server Management Studio

In this blog, we will learn, how to change the default values of select/edit command in SQL Server Management Studio.












Many of us have used the methods, given above, to select, insert and update the records in a table. It is much easier, compared to writing a query for the same. With these default numbers, it is not possible to edit the big tables. Thus, I searched for the options to change these numbers and found out this.
I know that this is not a big deal for most people, but for someone like me (who rarely looks at what all those menus are for!), it matters a lot and I knew many people like me complained about the same. Thus, I thought of sharing this.

Follow these steps,
Click “Tools” Menu -> “Options”.
Expand “SQL Server Object Explorer”.
Click “Commands”.
Change the values for edit & select.



Press “OK
That’s it. Now, if you right click your table you can see that your values are changed.










Hope that this will be helpful for someone out there!

Monday, 2 January 2017

Exporting HTML Table To Excel Using jQuery

In this blog, we will see how to export an HTML table to an Excel file, using the simple table2excel jQuery plugin. First we, will create the HTML table, which shows employee details and an "Export to Excel" button, as shown below.
  1. <div>  
  2.     <table id="mytable" cellpadding="5" border="1" cellspacing="0">  
  3.         <thead>  
  4.             <tr>  
  5.                 <th>  
  6.                     Employee Name  
  7.                 </th>  
  8.                 <th>  
  9.                     Age  
  10.                 </th>  
  11.                 <th>  
  12.                     Designation  
  13.                 </th>  
  14.                 <th>  
  15.                     Experience  
  16.                 </th>  
  17.             </tr>  
  18.         </thead>  
  19.         <tbody>  
  20.             <tr>  
  21.                 <td>  
  22.                     Rajeev  
  23.                 </td>  
  24.                 <td>  
  25.                     31  
  26.                 </td>  
  27.                 <td>  
  28.                     Developer  
  29.                 </td>  
  30.                 <td>  
  31.                     6  
  32.                 </td>  
  33.             </tr>  
  34.             <tr>  
  35.                 <td>  
  36.                     Sandhya  
  37.                 </td>  
  38.                 <td>  
  39.                     27  
  40.                 </td>  
  41.                 <td>  
  42.                     Tester  
  43.                 </td>  
  44.                 <td>  
  45.                     2  
  46.                 </td>  
  47.             </tr>  
  48.             <tr>  
  49.                 <td>  
  50.                     Ramesh  
  51.                 </td>  
  52.                 <td>  
  53.                     25  
  54.                 </td>  
  55.                 <td>  
  56.                     Designer  
  57.                 </td>  
  58.                 <td>  
  59.                     1  
  60.                 </td>  
  61.             </tr>  
  62.             <tr>  
  63.                 <td>  
  64.                     Sanjay  
  65.                 </td>  
  66.                 <td>  
  67.                     32  
  68.                 </td>  
  69.                 <td>  
  70.                     Developer  
  71.                 </td>  
  72.                 <td>  
  73.                     5  
  74.                 </td>  
  75.             </tr>  
  76.             <tr>  
  77.                 <td>  
  78.                     Ramya  
  79.                 </td>  
  80.                 <td>  
  81.                     23  
  82.                 </td>  
  83.                 <td>  
  84.                     Developer  
  85.                 </td>  
  86.                 <td>  
  87.                     1  
  88.                 </td>  
  89.             </tr>  
  90.         </tbody>  
  91.     </table>  
  92.     <br />  
  93.     <button onclick="exportexcel()">  
  94.         Export to Excel</button>  
  95. </div>  



Running the page will look as shown below.

















Now, we reference the jQuery file and table2excel file in our head section.
  1. <head runat="server">  
  2.     <title>Table 2 Excel</title>  
  3.     <script src="jquery.min.1.11.1.js" type="text/javascript"></script>  
  4.     <script src="jquery.table2excel.min.js" type="text/javascript"></script>  
  5. </head>  
Now, we write our exportexcel() function, as shown below.
  1. <script type="text/javascript">  
  2.         function exportexcel() {  
  3.             $("#mytable").table2excel({  
  4.                 name: "Table2Excel",  
  5.                 filename: "myFileName",  
  6.                 fileext: ".xls"  
  7.             });  
  8.         }  
  9. </script>  

In the script given above, the filename is the name of the file downloaded and fileext is the extension of the file to be downloaded, which is XLS.

Now, we will run the page and click on Export to Excel button.

Our Excel file will be downloaded. On opening the file, we can see the data of our table, as shown below.



Our Excel exporting is complete.


Summary

In this blog, we have learned how to export HTML table to an Excel file, using the table2excel jquery plugin. I hope this will be helpful.