Add

Credit Card Validation Plugin in Jquery

Introduction


It's been a long time since my last post. In the last two months I was running through a hectic schedule, so could not publish anything here.

But this time I am here with my first ever JQuery Plugin and that's on Credit Card Validation.

While working with any payment gateway its an important thing to validate the correct credit card/debit card details. You may have developed an interface where the user has to give the credit card details like card no, cvv no, expiry date, name on the card. These fields need to be validated before processing towards the payment.

In order to validate the credit card details you may use the jquery or server side coding with the help of regex expressions, which is a time taking thing. So I thought of developing an efficient plugin which can create a nice looking interface along with the user friendly validations that can be consumed in any type of application. So here it is.

In this post we will see how this plugin works and how to use it in your application. You can download the plugin from the below link.

   Download Source Code Here

  Behind The Scene








**I have used bootstrap for design purpose, you can use it or not according to your project requirement.

Before entering into the plugin details lets know some basic things about the credit card number pattens.

The first digit in your credit-card number signifies the system:

    3 - travel/entertainment cards (such as American Express and Diners Club)
    4 - Visa
    5 - MasterCard
    6 - Discover Card

The structure of the card number varies by system. For example, American Express card numbers start with 37; Carte Blanche and Diners Club with 38.
  •  American Express - Digits three and four are type and currency, digits five through 11 are the account number, digits 12 through 14 are the card number within the account and digit 15 is a check digit.

  •  Visa - Digits two through six are the bank number, digits seven through 12 or seven through 15 are the account number and digit 13 or 16 is a check digit.

  • MasterCard - Digits two and three, two through four, two through five or two through six are the bank number (depending on whether digit two is a 1, 2, 3 or other). The digits after the bank number up through digit 15 are the account number, and digit 16 is a check digit.

(Courtesy: http://money.howstuffworks.com)

Lets get into the coding things. Ok first of all we will see the user interface and design it for enabling the user to provide his/her card details for validation and further proceedings.

I have used Bootstrap to get a UI like this, You can use it or else you can not according to your requirement.

This is how our UI is going to look like. Don't you guys like it ? please share your valuable comments below to modify it.
UI for CC Validation
Before we can start you need to download the plugin first. If you have not till now then download it from below.

Download Source Code

Once you download and extract it you will find the below javascript files in the js folder.
  • jquery-1.7.1.min.js
  • ccvalidate-tapan.min.js
We will be needing the ccvalidate-tapan.min.js file for our validation thing and you can add a latest JQuery to your project too.

 In the css folder you will find the below css files
  • bootstrap.css
  • Validation.css
Ok, Now lets jump into the coding part. Here is the HTML page how it looks like.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
    <link href="css/bootstrap.css" rel="stylesheet" />
    <link href="css/Validation.css" rel="stylesheet" />
    <script src="js/ccvalidate-tapan.min.js"></script>
    <script>
        $(document).ready(function () {
            // Initiate CC Validation
            InitiateValidation();

            // For check valid invalid details
            $("#btnValidate").click(function () {

                if (ValidateForm()) {
                    alert('You have entered valid details...');
                }
                else {
                    alert('You have entered invalid details/skipped some fields...');
                }
            });
        });

    </script>
</head>
<body>
    <div style="margin-top: 50px;" class="container">
        <div class="row">
            <div class="col-sm-5 col-xs-offset-3">
                <div class="well">

                    <div class="row">
                        <div class="col-sm-12">
                            <label class="col-sm-12 control-label">Enter Card No.</label>
                            <div class="col-sm-12">
                                <input placeholder="4587-7834-6735-1930" id="1" class="form-control" filtertype="CCNo">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-8">
                            <label class="col-sm-12 control-label">Expiry Date (MM/YY)</label>
                            <div class="col-sm-12">
                                <input placeholder="12/20" id="3" class="form-control" filtertype="Date">
                            </div>
                        </div>
                        <div class="col-sm-4">
                            <label class="col-sm-12 control-label pull-right">CVV</label>
                            <div class="col-sm-12">
                                <input placeholder="454" id="3" class="form-control" filtertype="Number">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-12">
                            <label class="col-sm-12 control-label">Name on Card</label>
                            <div class="col-sm-12">
                                <input placeholder="Tapan kumar" id="1" class="form-control" filtertype="CharacterAndSpace">
                            </div>
                        </div>
                    </div><br />
                    <div class="row">
                        <div class="col-sm-12">
                            <button id="btnValidate" class="btn btn-info col-sm-3 col-sm-offset-4 control-label">Submit</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

If you look into the above code you will find that I am using an attribute named filtertype for the input fields, which is responsible for the validation.

Here is the attribute values I have used for validating your card details.
  • Credit Card No : filtertype = "CCNo"
  • Expiry Date :  filtertype = "Date"
  • CVV No : filtertype = "Number"
  • Name on Card : filtertype = "CharacterAndSpace"

These attribute values are used into validate your card details and prevent user from inserting invalid entries in the input fields.
What you have to do is just to call 2 methods in JQuery in order to validate the card details. Find the script below.

    <script>
        $(document).ready(function () {
            // Initiate CC Validation
            InitiateValidation();

            // For check valid invalid details
            $("#btnValidate").click(function () {

                if (ValidateForm()) {
                    alert('You have entered valid details...');
                }
                else {
                    alert('You have entered invalid details/skipped some fields...');
                }
            });
        });

    </script>

The  InitiateValidation() method initiates the validation, and ValidateForm() method will return a boolean if the form is valid or not and you can perform your task accordingly. Here I am showing some alert if the details are correct or not in the click event of the submit button.

That's all for your validation to work out.

Plugin Features :

  • while inserting the card no it will automatically put a "-" in between 4 digits.
  • It will not allow you put anything except numbers in the card input field.
  • It will show your card type at the right side of the text box.
  • Max length of the CCNo field is 19(including the "-").
  • In the Date field you wont be able to put anything except numbers and the field will not accept the first two digits greater than 12 as these two digits indicates the month.
  • Max length of the Expiry Date field is 6(including the "/").
  • Now the CVV no field will accept only 3 digits.
  • Finally the Name on Card field will accept a name, which should be at least of 3-4 characters.
Happy Coding...



A Simple Example on SQL Trigger

Introduction


A trigger is a special kind of stored procedure, which is attached with a database table and gets executed automatically in response to certain action on the table like insertion, deletion or updation.
You can not invoke/call it manually, the only way to execute it is to do the required action on the table.

There are two types of Triggers
  • After Triggers (For Triggers)
  • Instead Of Triggers 

 

After Triggers 


These Triggers are fired just after insertion, deletion and updation of a table.

 

Instead Of Triggers 


These Triggers are fired when a user tries to do something like inserting/deleting/updating the table and performs what you have written inside it instead of what the user tries to do.

Example: If you have written an Instead Of Trigger for an Insertion operation on Sales table and someone is trying to insert into the Sales table then the code inside the Trigger gets executed instead of the Insertion query. Basically with the Instead Of Trigger you are overloading the actual functionality of the operators like INSERT, UPDATE, DELETE.

For more details on Triggers visit this link.

Behind The Scene


Here in this article we will see how to create a Trigger and how it works in real world.
Before we proceed we may need some basic knowledge on SQL.

Lets create a Table named Sales in our database.

CREATE TABLE Sales
  (
     id         INT IDENTITY(1, 1) PRIMARY KEY,
     totalsales VARCHAR(255) NOT NULL,
     solddate   VARCHAR(15)
  ) 

Now create another Table named TrigerResult

CREATE TABLE TrigerResult
  (
     id                 INT IDENTITY(1, 1) PRIMARY KEY,
     totalsalesoftheday INT NOT NULL,
     solddate           VARCHAR(15)
  ) 

Ok, below is what our aim to achieve with a Trigger.
  • When any row is inserted into the Sales table check TriggerResult table 
  • If it has a row with the same solddate column  value then update the row's value by adding the newly inserted totalsales column value of Sales table.
  • If no row exists with the same solddate column  value then insert a new row into the TriggerResult table.
Here is the Trigger which will do our job perfectly.

CREATE TRIGGER UpdateTriggerResult
ON Sales  

AFTER INSERT
AS
  BEGIN
      DECLARE @currentDate VARCHAR(19)
      DECLARE @CurrentSoldAmmount INT

      SET @currentDate = CONVERT(VARCHAR(19), (SELECT Cast(Getdate() AS DATE)))
      SET @CurrentSoldAmmount = (SELECT TOP 1 totalsales
                                 FROM   Sales
                                 ORDER  BY id DESC)

      IF( (SELECT TOP 1 solddate
           FROM   TrigerResult
           ORDER  BY id DESC) = @currentDate )
        BEGIN
            UPDATE TrigerResult
            SET    totalsalesoftheday = totalsalesoftheday + @CurrentSoldAmmount
            WHERE  solddate = @currentDate
        END
      ELSE
        BEGIN
            INSERT INTO TrigerResult
                        (totalsalesoftheday,
                         solddate)
            VALUES     (@CurrentSoldAmmount,
                        CONVERT(VARCHAR(19), (SELECT Cast(Getdate() AS DATE))))
        END
  END
GO

This trigger will perform as the above said constraints. And inserts/updates the TrigerResult table in response of the INSERT statement on Sales table.

Now insert into Sales table by the below statement and see what happens.

INSERT INTO sales
            (totalsales,
             solddate)
VALUES      (100,
             CONVERT(VARCHAR(19), (SELECT Cast(Getdate() + 1 AS DATE)))) 

This will give you the below result.
One row inserted in both tables.

Now run the same insert statement again and you will find the below result.
One row inserted in Sales table and TriggerResult table is updated.

Now you got to know how this Trigger actually works. You can continue with the other types for Update and Delete operations.

Find out the video tutorial on this.



Happy Coding...

Creating a Graph in ASP.NET with AJAX, HttpHandler and Morris.js Plugin

Introduction


Graphical representation is something that can make you understand every statistics without a mathematical calculation. It keeps the ability to represent the facts and figures in such a manner that you need not to give any pressure to your brain for calculations.

Lets take a simple example.

Consider yourself as an owner of a laptop selling company which sells thousands of laptops daily. As you are the owner of the company, you must have to keep track of your business if your sales volume is increasing day by day or decreasing. 

In order to keep track of your sales volume in a certain time period what you have to do ????
Yes, you will collect the facts and figure for a comparison and definitely for this comparison you need to do some calculations blah blah blah blah......

Here comes the concepts of Graph by seeing it only you will get a clear cut idea whether your business is growing or not.

Graph is the concept which will save your time, save the utilization of your brain and keeps you away from headache while analyzing a bunch of data.

So, Being a software developer it becomes an important part of development to get all the reports like user accounts, page hits, sales volumes etc. in a graphical representation, so that it will be very easy to understand what is actually happening in the background, and how the business is getting affected day by day.

Here in this article I will show you how to generate a light weight, nice looking Graph using Jquery and AJAX. If you surf in the internet you will get hundreds of plugins for generating Graphs. 
I will be using  morris.js for generating a nice looking graph. For more details about the plugin please visit their website.


   Download Source Code Here
   

Behind The Scene


In this example we will be using AJAX, JQURY along with HttpHandler in ASP.NET. So some basic idea on these topics will be highly appreciated.
You can download the above demo project for a quick demo.

Lets do this.

Front End Stuffs:


Add a new webform  to your solution (in visual studio). And add the below scripts to the header section of your page.
 <link rel="stylesheet" href="http://cdn.oesmith.co.uk/morris-0.4.3.min.css">
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
 <script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
 <script src="http://cdn.oesmith.co.uk/morris-0.4.3.min.js"></script>
Now add a div to the body of your page with an id. Here I have given it an id of  "area-example" and put it blank.
 <div id="area-example"></div>
Ok, now we need to bind that div with our data in order to produce a graph. So here you go.....

Add the below script to the header section and I will explain it line by line.
    <script type="text/javascript">
        $(document).ready(function () {

            Morris.Area({
                element: 'area-example',
                data: Graph(),
                xkey: 'label',
                ykeys: ['value'],
                labels: ['value']
            });

        });
    </script>
Here in the above script I am trying to bind the div with a graph by calling the Morris.Area function and passing it some parameters.

For more details about Morris Charts you can visit their web.

Let me explain these parameters here we are passing.
  • element (mandatory) : This is the ID of the container where the graph will be rendered.
  • data (mandatory) : Here you can provide the data to bind your graph. It accepts data in JSON format. like
    [
      { label: '2012-10-01', value: 802 },
      { label: '2012-10-02', value: 783 },
      { label: '2012-10-03', value: 820 },
      { label: '2012-10-04', value: 839 },
      { label: '2012-10-05', value: 792 },
      { label: '2012-10-06', value: 859 },
      { label: '2012-10-07', value: 790 },
    ] 

    Or you can call a function to get data from server side. Here I am using AJAX for getting data from server side through a HTTPHandler.
  • xkeys (mandatory) : A string containing the name of the attribute that contains date (X) values.The date format should be in "YYYY-MM-DD" format.
  • ykeys (mandatory) : A string containing the name of the attribute the value for (Y).
  • labels (mandatory) : A list of strings containing labels for the data series to be plotted (corresponding to the values in the ykeys option).
In our case the data attribute is calling a Javascript function named Graph(). And I am calling a HttpHandler through AJAX. Find the function below.
        function Graph() {
            var data = "";

            $.ajax({
                type: 'GET',
                url: "http://localhost:60539/GraphHandler.ashx",
                dataType: 'json',
                async: false,
                contentType: "application/json; charset=utf-8",
                data: { 'GraphName': 'line' },
                success: function (result) {
                    data = result;
                },
                error: function (xhr, status, error) {
                    alert(error);
                }
            });

            return data;
        }
I am passing the HttpHandler url in the url attribute, and I am sending some data to the server of json type. You can find the dataType : 'json' and data: {'GraphName': 'line'} which I will be using in my handler.

And as you can see I am making this AJAX call synchronous by setting async attribute to false because I need the AJAX call to wait till the data was retrieved from the back end otherwise the graph will not be loaded.

* It is not recommended usually to make the AJAX call synchronous.

Once the call is completed and it get some data then inside the success attribute I am setting a variable and then at the end of the method returning it.

You need to put this method in script block we have created just before sometime.


Back End Stuffs:



Once the call is transferred to the handler you get the flexibility to use your coding ability to fetch data from server or whatever you want to do.

Here I will be using two classes named GraphData.cs to and GraphDataList.cs. Find the two classes below.
    public class GraphData
    {
        public string label { get; set; }
        public string value { get; set; }
    }
 
    public class GraphDataList
    {
        public List<GraphData> ListOfGraphData { get; set; }
    }
Find the below function that is responsible for fetching the graph data from the server. Basically this is a DAL function.
        public GraphDataList GetGraphData(string graphName)
        {
            GraphData graphData = null;
            GraphDataList graphDataList = new GraphDataList();
            graphDataList.ListOfGraphData = new List<GraphData>();

            try
            {
                using (var con = new SqlConnection(connectionString))
                {
                    con.Open();

                    SqlCommand cmd = new SqlCommand();
                    SqlDataAdapter SqlDadp = new SqlDataAdapter();
                   
                    cmd.Parameters.Add("@ProgramID", SqlDbType.Int);
                    cmd.Parameters["@ProgramID"].Value = programID;

                    cmd.CommandType = CommandType.StoredProcedure;

                    using (IDataReader dataReader = cmd.ExecuteReader())
                    {
                        while (dataReader.Read())
                        {
                            graphData = new GraphData();

                            graphData.label = Convert.ToString(dataReader["Date"].ToString());
                            graphData.value = Convert.ToString(dataReader["AmountPaid"].ToString());

                            graphDataList.ListOfGraphData.Add(graphData);
                        }
                        dataReader.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogError(ex);
            }

            return graphDataList;
        }
As you can see in the this method I am calling a stored procedure and binding the GraphDataList with the returned values. Finally it returns the graphDataList.

Now we need to call this method from ProcessRequest method of the HttpHandler.

Here is the code for ProcessRequest method.
        public void ProcessRequest(HttpContext context)
        {
            System.Collections.Specialized.NameValueCollection forms = context.Request.Form;
            
            string chartName = context.Request["GraphName"];
           
            DataAccessLayer Dal = new DataAccessLayer();

            int programID = 1;

            if (!string.IsNullOrEmpty(chartName))
            {
                GraphDataList graphList = new GraphDataList();

                switch (chartName)
                {
                    case "line":
                        graphList = Dal.GetGraphData(chartName);
                        break;
                    case "donut":
                        graphList = Dal.GetGraphData(chartName);
                        break;
                }

                //oper = null which means its first load.
                var jsonSerializer = new JavaScriptSerializer();
                string data = jsonSerializer.Serialize(graphList.ListOfGraphData);
                context.Response.Write(data);
            }
        }
As you can see I am retrieving the parameter I have passed from AJAX, from the context.Request. Then we are almost done.

Just call the GetGraphData(chartName) with the graph name and hold the returned data in a list, we just created before 2-3 minutes ago.

We are just 1 step away from generating a nice looking graph.

Finally serialize the list with JavaScriptSerializer and parse it back. now you will get a beutiful graphical representation of your data.

Here I have plotted a graph between the time frame and the sales volume of a organization. And the graph looks like below

Graph

Hopefully you got something from this article and demonstration. If you want a complete demo then feel free to download the source code from above link.

If you like the article, a +1 will be very much appreciated, that is present at the top of the Page.

Happy Coding...

Simple Example On SQL CASE Expression

Introduction


If you are working with SQL SERVER then you are definitely going to need this article. Let me explain a bit briefly. 
You have one table named [User] where, you are storing 3 type of user's data such as
  • Clients data
  • Employee data
  • Admin data
Consider the case if you are asked to write a stored procedure that needs to fetch the respective user data. What will you do ? I can say most of the people will go for a If-Else condition to fetch the data.
But the Case expression will solve your problem in just simple way. Find it below....
   

Behind The Scene


First see if you want to fetch the client data, employee data and admin data in If-Else condition.

-- AUTHOR: Tapan kumar
-- CREATE DATE: --                                                  
-- PROJECT:          
-- CREATED BY: Tapan kumar
-- MODIFIED BY:   
-- MODIFICATION DATE: 28DEC2013  
-- Last MODIFICATIONS :                                                
-- DESCRIPTION/PURPOSE: Gets all user data according to filter type. 
-- UNIT TESTING :  [Getuseranddetailstosendexpirynotification] 
-------------------------------------------------------
CREATE PROCEDURE [dbo].[Getuseranddetailstosendexpirynotification] --1
  @FilterType INT
AS
  BEGIN
      -- @FilterType = 1 (will select clients only)
      -- @FilterType = 2 (will select employees only)
      -- @FilterType = 3 (will select admins only)
      
      SET nocount ON;

      IF @FilterType = 1 -- For selecting client data
        BEGIN
            SELECT id,
                   firstname,
                   lastname,
                   salary
            FROM   [user]
            WHERE  isclient = 1
                   AND .isdeleted = 0
        END
      ELSE IF @FilterType = 2 -- For selecting employee data
        BEGIN
            SELECT id,
                   firstname,
                   lastname,
                   salary
            FROM   [user]
            WHERE  isemployee = 1
                   AND .isdeleted = 0
        END
      ELSE IF @FilterType = 3 -- For selecting admin data
        BEGIN
            SELECT id,
                   firstname,
                   lastname,
                   salary
            FROM   [user]
            WHERE  isadmin = 1
                   AND .isdeleted = 0
        END
  END 

This is how your stored procedure will look like. You need to write the select query 3 times.

But here comes the use of CASE expression to save your time. See the below stored procedure to do the same thing..

-- AUTHOR: Tapan kumar
-- CREATE DATE: --                                                  
-- PROJECT:          
-- CREATED BY: Tapan kumar
-- MODIFIED BY:   
-- MODIFICATION DATE: 28DEC2013  
-- Last MODIFICATIONS :                                                
-- DESCRIPTION/PURPOSE: Gets all user data according to filter type. 
-- UNIT TESTING :  [Getuseranddetailstosendexpirynotification] 
-----------------------------------------------
ALTER PROCEDURE [dbo].[Getuseranddetailstosendexpirynotification] --1
  @FilterType INT
AS
  BEGIN
      -- @FilterType = 1 (will select clients only)
      -- @FilterType = 2 (will select employees only)
      -- @FilterType = 3 (will select admins only)
      
      SET nocount ON;

      SELECT id,
             firstname,
             lastname,
             salary
      FROM   [user]
      WHERE  1 = CASE
                   WHEN @FilterType = 1
                        AND isclient = 1
                        AND .isdeleted = 0 THEN 1
                   WHEN @FilterType = 2
                        AND isemployee = 1
                        AND .isdeleted = 0 THEN 1
                   WHEN @FilterType = 3
                        AND isadmin = 1
                        AND .isdeleted = 0 THEN 1
                   ELSE 0
                 END
  END 

In the above procedure you can see how I have written a single select query that behave differently depending on the @filterType .

Here is how it behaves
  • @filterType = 1, it will select the client data. 
  • @filterType = 2, it will select the employee data. 
  • @filterType = 3, it will select the admin data.
Hope this will be helpful to you.

Happy Coding...

Renaming Multiple Files Present In A Folder In Windows Form Applicaion

Introduction


Today I got scenario where I have to rename 100+ files with their names starting with XYZ_ and my task is to replace that XYZ_ with  ABC_. But I don't have that luxury to spend around 1-2 hours on renaming the files. So I find a way to rename the files through codding.

I made an application that is capable of replacing some text with your desired text.

Find the patten in the below image which thing I want to replace.


Files wth a prifix of XYZ_

This is a folder present in "E:\Test\Files" directory of my computer. As you can see the files present there in the above image you can find that all the files have a prefix of XYZ_ that needs to be changed to ABC_.

So if I go to change this by selecting all for renaming then it does not work it renames all the files with what I typed.

I tried to find out a standard solutions from the web but did not find one suitable and efficient one. So I developed a windows application to do the job. And here it is.  


   Download Source Code Here

Behind The Scene


Find the below image how I want the output.

When "XYZ_" replaced with "ABC_"


In order to do this I choose Windows application where I took two Text Boxes, those take the input from the user for replacement work. Find the below image and then I will explain what control does what ?

The Form with all the controls


* Find Text will take the text which you want to replace.
* Replace Text will take the text which will be replaced.
* Select File Type will give you to the option to select the type of file you want to rename.
* Rename Files button will open a folder selection dialog to select the respective folder you want. 


When you click on the Rename Files button with appropriate inputs then a folder selection dialog will be opened like below where you need to select the folder.

Folder selection Dialog


OK, now we are done with the design part. lets move to the codding part. Once you click on the  Rename Files button it will invoke the btnRename_Click event.

private void btnRename_Click(object sender, EventArgs e)
  {
      {
          //
          // This event handler was created by double-clicking the window in the designer.
          // It runs on the program's startup routine.
          //
          DialogResult result = folderBrowserDialog1.ShowDialog();

          if (result == DialogResult.OK)
          {
              int count = 0;
              lblError.Text = string.Empty;

              // This will get the folder you have selected.
              DirectoryInfo d = new DirectoryInfo(folderBrowserDialog1.SelectedPath);

              // Check if the Dropdown has some value or not.
              if (cmbFileType.SelectedText != "Select")
              {
                  try
                  {
                      // get only those files with an extension of the selected one.
                      FileInfo[] infos = d.GetFiles("*" + cmbFileType.SelectedItem.ToString());

                      // Make a loop to replace and rename the files.
                      foreach (FileInfo f in infos)
                      {
                          // Do the renaming here
                          File.Move(f.FullName, Path.Combine(f.DirectoryName, 
                          txtReplaceText.Text.Trim() + f.Name.Replace(txtFindText.Text.Trim(),"")));
                          count++;
                      }

                      // Show alert if no file with the selected extension is present.
                      if (infos.Count() == 0)
                      {
                          lblError.Text = "Destination folder has no " + " ' " 
                          + cmbFileType.SelectedItem.ToString() + " ' files.";
                      }
                      //Show success alert.
                      else if (count == infos.Count())
                      {
                          lblError.Text = "All ' " 
                          + cmbFileType.SelectedItem.ToString() + " ' files in '" 
                          + d +
                              " ' folder whose name contains a text of ' " + txtFindText.Text.Trim() +  
                              " ' has been replaced with ' " + txtReplaceText.Text.Trim() + " '.";
                      }
                  }
                  catch (Exception ex)
                  {
                      lblError.Text = "Some error occured";
                  }
              }
              else
              {
                  lblError.Text = "Please select a file type first.";
              }
          }
      }
  }

What I am doing in the above code ???

  1. In the above method I am getting the folder name from the the folder selection dialog and creating a DirectoryInfo .
  2. Selecting all the files with the extension selected from the combo box.
  3. Making a loop to replace the intended text with the desired text.
  4. Then show appropriate alert message to the user.
If you want to download the demo project then you can download it from the above download link.

Happy Coding...

Get The Height And Width Of Window In JQuery For Resopnsive Web Design

Introduction


Now-a-days responsive web design becomes minimum requirement while developing or designing a website. In today's market everyone wants his website to get render nicely in any type of device by keeping the reason in mind of the usage of mobile/tablet devices in business process.

Mobile devices have become an unavoidable part of our life. We are using those for almost everything like browsing, internet surfing, online shopping and also for all other important works like applying for a job, filling up any application for admission, Tax payment, for mobile recharge etc. So by keeping this vast use of mobile devices in mind it has became a must for all the website depending companies or organizations to serve their clients with the best user experience irrespective of the device they are using.

So, in order to make a website responsive you need to calculate the height, width of the browser in every step a user resizes the window.

Here is a simple way to find the width and height of a window when it got resized.
 

Behind The Scene


There is a feature in JQuery through which you can get the width and height of the window or document.

     $(document).height();
     $(document).width();

     $(window).height();
     $(
window).width(); 

But the problem with that thing is when the page loads for the first time you can get those values but lets think if the user resizes his browser then what will happen this website should render accordingly.

For doing so you need to check the height and width in every attempt user resizes the browser.

JQuery provides a method $(window).resize(), which get called when the the user is trying to resize the window. So you can get the height and width in every resolution of the window automatically.

Below I have taken two div to show the size of the window initially and after it gets resized.
  <div id="divInitial"></div>
  <div id="divResize"></div>
Then I have written the below JQuery to fetch the width and height every time user resizes his window.
 <script type="text/javascript">
        $(document).ready(function () {
            $("#divInitial").text("Initial Window width: " + $(window).width() + ", height: " + $(window).height() + ".");

            //Event to handle resizing
            $(window).resize(function () {
                var width = $(window).width();
                var height = $(window).height();
                $("#divResize").text("Window width: " + width + ", height: " + height + ".");
            });
        });
    </script>
This will write the height and width in the div when user tries to resize the window. So you can assign the CSS to the controls accordingly for making your website responsive.

Live demo


** Click on the Live Demo link above to see the example in jsfiddle and go on resizing the window and see what happens.

Happy Coding...

What is Impersonation and How to Use it in ASP.NET

Introduction


Impersonation is the process used by ASP.NET to execute code in the context of an authenticated and authorized user.

Basically when IIS gets a request it check for the authorization of the user if he/she is authorized or not, by default, all ASP.NET code is executed using a fixed machine-specific account. If you want to change it then you can do this by using Impersonation.
   

Behind The Scene


Lets go a bit dipper to understand the use of it. Each time a request goes to IIS server the ASP.NET runs a security check to find if the user is authorized or not. And mostly ASP.NET uses the machine specific user account.

Consider a senario where you are logged on to a web application through your credentials and there you are trying to access a page which has a web service, that is being called to another computer. In this case your identity will not be shown in the web service's server instead the network credential(IIS credential) will be used for authentication.

For this reason, you can use impersonation to use your credentials for authentication in the second computer instead the network credentials.

And in ASP.NET you can do this in two manners like below;
  • Use an anonymous internet user account/authenticated user account.
  • Use a specific user account.
This thing can be done by turning the impersonate attribute to "true" in the identity element of the web config file.
  <identity impersonate="true" />
In this case ASP.NET impersonates to the authenticated user or to an anonymous internet user account.
  <identity impersonate="true"  userName="domain\username" password=" password"/>
In this case ASP.NET impersonates to a specific user account.

Happy Coding...