Category Archives: Javascript

Realtime Currency Converter in C# ASP.NET using Yahoo API


In this article, Let’s see how to convert worldwide currencies in realtime using Yahoo API.

Steps:

1. Create a ASP.NET empty project, call it as “RealtimeCurrencyConverterUsingYahooAPI”.

2. Add a webpage called “Default.aspx” to the project.

3. Since we are using jQuery, include the jQuery latest library in the project. Add a reference to it on “Default.aspx” page.


<script src="jquery-1.10.2.js"></script>

4. Add the following webmethod in code behind.


using System;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Web.Services;

[WebMethod]
public static Decimal ConvertCurrency(decimal amount, string fromCurrency, string toCurrency)
{
WebClient client = new WebClient();
Stream response = client.OpenRead(string.Format("http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s={0}{1}=X", fromCurrency.ToUpper(), toCurrency.ToUpper()));
StreamReader reader = new StreamReader(response);
string yahooResponse = reader.ReadLine();
response.Close();
if (!string.IsNullOrWhiteSpace(yahooResponse))
{
string[] values = Regex.Split(yahooResponse, ",");
if (values.Length > 0)
{
decimal rate = System.Convert.ToDecimal(values[1]);
return rate * amount;
}
}
return 0;
}

The webmethod simple get response from yahoo URL. Parses it and returns the calculated result back on the screen.

5. To call this webmethod from “Default.aspx”, just add the following jQuery Code.


<script type="text/javascript">

$(document).ready(function () {
$('#submit').click(function () {
var errormsg = "";
var amount = $('#txtAmount').val();
var fromCurrency = $('#drpFromCurrency').val();
var toCurrency = $('#drpToCurrency').val();
$.ajax({
type: "POST",
url: "Default.aspx/ConvertCurrency",
data: "{amount:" + amount + ",fromCurrency:'" + fromCurrency + "',toCurrency:'" + toCurrency + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#results').html(amount + ' ' + fromCurrency + ' equals ' + data.d.toFixed(2) + ' ' + toCurrency);
},
error: function (jqXHR, exception) {
$('#results').html(jqXHR.responseText);
}
});
});
});

</script>

If you don’t know how to call a webmethod in jQuery, Please refer this.

6. To style the table, I have just added a stylesheet and referred it in the “Default.aspx” page. You can generate such styles very easily from here.

7. Now run the project and you will find the output like e.g

Source Code Download:

Github [Repository Link]

Box.com [Direct Download Link]

jQuery IP Location Plugin – jqIpLocation Example


In this post, we will see how to get location of an IP address. To achieve this, we will use jquery’s popular plugin “jqIpLocation”.

About jqIpLocation plugin:

jqIpLocation is a jQuery Plugin that returns the location of an IP address in JSON format. You can get country, country code, city name, region name, latitude and longitude information about IP address location.

Now Let’s see how it works with an Example.

1. Create a new asp.net project in Visual Studio, name it as “jqIpLocationPluginExample”.

2. Select the Empty template for web forms.

3. Once the project is created, add a webpage, call it as “Default.aspx”.

4. Download the plugin from here. Extract the rar file and copy the folder to our project.

5. Include the Javascript resources into our Default.aspx page’s <head> section.


<head>
<script src="jqIpLocation/jquery-1.6.3.min.js"></script>
 <script src="jqIpLocation/jqIpLocation.js"></script>
</head>

6. Create a table on page, consider following code snippet.


<table class="CSSTableGenerator">
 <tbody>
 <tr>
 <td>IP</td>
 <td>
 <asp:Label ID="lblIP" runat="server" ClientIDMode="Static"></asp:Label>
 </td>
 </tr>
 <tr>
 <td>Country</td>
 <td>
 <asp:Label ID="lblCountry" runat="server" ClientIDMode="Static"></asp:Label>
 </td>
 </tr>
 <tr>
 <td>Country Code</td>
 <td>
 <asp:Label ID="lblCountryCode" runat="server" ClientIDMode="Static"></asp:Label>
 </td>
 </tr>
 <tr>
 <td>City</td>
 <td>
 <asp:Label ID="lblCity" runat="server" ClientIDMode="Static"></asp:Label>
 </td>
 </tr>
 <tr>
 <td>Region</td>
 <td>
 <asp:Label ID="lblRegion" runat="server" ClientIDMode="Static"></asp:Label>
 </td>
 </tr>
 <tr>
 <td>Latitude</td>
 <td>
 <asp:Label ID="lblLatitude" runat="server" ClientIDMode="Static"></asp:Label>
 </td>
 </tr>
 <tr>
 <td>Longitude</td>
 <td>
 <asp:Label ID="lblLongitude" runat="server" ClientIDMode="Static"></asp:Label>
 </td>
 </tr>
 </tbody>
 </table>

If you observe, I have applied “CSSTableGenerator” class to table, which I have generated from here. I have added it in “StyleSheet1.css” file in the project and included the reference for the same.

7. Add the following Javascript code that will returns you IP Location information in JSON format.


<script type="text/javascript">
 $(function () {

var ipAddress = "213.243.4.20";

$.jqIpLocation({
 ip: ipAddress,
 success: function (location) {
 $("#lblIP").text(ipAddress);
 $("#lblCountry").text(location.countryName);
 $("#lblCountryCode").text(location.countryCode);
 $("#lblCity").text(location.cityName);
 $("#lblRegion").text(location.regionName);
 $("#lblLatitude").text(location.latitude);
 $("#lblLongitude").text(location.longitude);
 }
 });

});
 </script>

8. Now save everything and run the project, you will see following output.

Please note: I have hard coded IP address, you can change and try with some another IP.

Live Demo 1 | Live Demo 2

Source Code Download:

Github [Repository Link]

Box.com [Direct Download Link]

Bootbox.js – Alert, Confirm, Prompt and Dialogs for Bootstrap framework


Bootbox.js is a small JavaScript library developed on top of the Twitter’s Bootstrap which allows you to create programmatic dialog boxes like alert, confirm, prompt etc. In short, it’s a wrappers for JavaScript alert(), confirm() and other flexible dialogs using Twitter’s bootstrap framework.

Only following line of code will display a Bootstrap alert.


bootbox.alert("Hello world!");

But if you try to achieve it via Bootstrap, you need to write multiple lines of code.

See it here in action.

Core Methods of Bootbox.js

  • bootbox.alert(message, callback)
  • bootbox.prompt(message, callback)
  • bootbox.confirm(message, callback)
  • bootbox.dialog(options)

Before we look into examples, let’s see dependencies of bootbox.

Since we know that Bootbox is developed on top of Bootstrap, it is required.

Css Dependencies:


<link rel="stylesheet" type="text/css" href="bootstrap.min.css">

Javascript (JS) dependencies:


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
 <script src="bootstrap.min.js"></script>

Examples

1. Alert


$(document).ready(function () {

 bootbox.alert("Hello world!");

});

Live Demo

2. Confirm

$(document).ready(function () {

bootbox.confirm("Are you sure?", function(result) {
 alert('You clicked: ' + result);
});

});

Live Demo

3. Prompt


bootbox.prompt("What is your city?", function(result) {
 if (result === null) {
 alert("Prompt dismissed");
 } else {
 alert("Your city is " + result);
 }
});

Live Demo

4. Dialog

bootbox.dialog({
 message: "Custom dialog using Bootbox",
 title: "Bootbox Dialog",
 buttons: {
 success: {
 label: "Yes",
 className: "btn-success",
 callback: function() {
 alert("You clicked Yes");
 }
 },
 danger: {
 label: "No",
 className: "btn-danger",
 callback: function() {
 alert("You clicked No");
 }
 },
 main: {
 label: "Not Sure",
 className: "btn-primary",
 callback: function() {
 alert("You clicked Not Sure");
 }
 }
 }
});

Live Demo

Please note: It’s not necessary to call Bootbox API on document.ready, it’s for demo purpose only. You can call Bootbox API on any event.

AngularJS – A Javascript MVC Framework


What is AngularJS?

AngularJS is a Javascript MVC framework created by Google to build properly architectured and maintainable web applications. It extends HTML into a more expressive and readable format. It decreases emphasis on directly handling DOM manipulation from the application logic, allowing for easier testing. It employs efficient two-way data binding and sensible MVC implementation, reducing the server load of applications.

Why AngularJS?

AngularJS is a MVC framework that enhances HTML by attaching directives to your pages with new attributes or tags and expressions in order to define very powerful templates directly in your HTML. It allows to declare dynamic views in web-applications. It also lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop.

Now let’s have a closer look at all those features.

1. Expressions

Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by the $parse service.

For example, these are all valid expressions in angular:

2+2
7*10 | currency
user.name

2. Directives

Directives adds new tricks to HTML. During DOM compilation directives are matched against the HTML and executed. This allows directives to register behavior, or transform the DOM.

Angular comes with a built in set of directives which are useful for building web applications but can be extended such that HTML can be turned into a declarative domain specific language (DSL).

Jsfiddle Example

3. Data Binding

Data-binding in Angular web apps is the automatic synchronization of data between the model and view components. The way that Angular implements data-binding lets you treat the model as the single-source-of-truth in your application. The view is a projection of the model at all times. When the model changes, the view reflects the change, and vice versa.

ngModel Is a directive that tells Angular to do two-way data binding. It works together with input, select, textarea and even custom form controls that use NgModelController exposed by this directive.

4. Filters

In order to change the way your data are displayed in your page, AngularJS provides you with the filter mechanism.

e.g we can put the name in upper case with {{user.name | uppercase}} filter

You can also easily create your own filters.

5. Modules

In AngularJS, applications are structured in modules. A module can depend on other modules and a module can contain controllers, services, directives and filters.

jsfiddle Example

6. Scopes

Scope is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in hierarchical structure which mimic the DOM structure of the application. Scopes can watch expressions and propagate events.

7. Controller

Controllers are the behavior behind the DOM elements. AngularJS lets you express the behavior in a clean readable form without the usual boilerplate of updating the DOM, registering callbacks or watching model changes.

Related Videos

BrowserSwarm – Spend Less Time Testing Your JavaScript Project


What is BrowserSwarm?

It is a tool that automates your testing of JavaScript across browsers. Spend less time testing and more time innovating. It is a project from appendTo, Sauce Labs and the Internet Explorer team.

BrowserSwarm provides test results using top frameworks and libraries such as prototype.js and Modernizr. You receive an overall pass rate across browsers and devices, along with individual test pass rates for top browsers.

You can register an account on BrowserSwarm here.

How BrowserSwarm works?

  1. BrowserSwarm connects directly to your GitHub code repository.
  2. When your team makes updates, BrowserSwarm automatically runs your project’s Unit Test Suite and supports Frameworks, like QUnit, in the cloud using SauceLabs browser automation.
  3. You can easily view or download the results.

See test results for top libraries: (Screenshot)

Here is the sample test result for jquery.

Here is the screen for Build details and Build History for jQuery.

From the Dashboard, you can configure your BrowserSwarm projects.

There are various options through which you can configure your BrowserSwarm project.

Configuration options:

1. Collaborators

2. Github Config

3. Heroku Config

4. Webhooks

5. Deactivate

6. Custom Scripts

7. Environment

8. Saurce Config

9. Jelly-Proxy Config

10. QUnit Config

Moment.js – A javascript date library


A javascript date library for parsing, validating, manipulating, and formatting dates.

There are multiple ways to refer Moment.js, but the popular way is via Nuget package manager.

To install/refer Moment.js, run the following command in the package manager console in visual studio.

Install-Package Moment.js

Now let me run you through some of the examples using Moment.js library

1. To get the current date and time, just call moment() with no parameters.


var now = moment();

//output
//Tue Oct 01 2013 08:40:23 GMT+0550

2. You can format date by multiple ways. e.g


moment().format('MMMM Do YYYY, h:mm:ss a'); // October 1st 2013, 12:19:57 pm
moment().format('dddd'); // Tuesday
moment().format("MMM Do YY"); //Oct 1st 13
moment().format('YYYY [escaped] YYYY'); //2013 escaped 2013
moment().format(); //2013-10-01T12:20:35+05:30

3. You can validate date e.g


moment("not a real date").isValid(); //false

moment("01/01/2013").isValid(); //true

4. You can get or set hour, minutes, seconds etc.


moment().second(); // Number
moment().minute(); // Number
moment().hour(); // Number

5. You can manipulate dates/months/year by multiple ways. e.g


moment().add('days', 7).subtract('months', 1).year(2009).hours(0).minutes(0).seconds(0)

//output
//Tue Sep 08 2009 00:00:00 GMT+0550

6. You can query moment object, e.g


moment('2010-10-20').isBefore('2010-12-31', 'year'); // false
moment('2010-10-20').isBefore('2011-01-01', 'year'); // true
moment().isLeapYear(); //false
moment().isDST(); //Daylight saving time - false

Moment.js documentation can be found here.

jsFiddle example

Replace All Occurrences of a String in JavaScript


In this article, let’s discuss about how to replace all the occurrences of a string in a javascript.

To make it generic, Lets define a replaceall method in javascript.

Case sensitive replace all

Following code will replace all occurrences of a string globally using case sensitive pattern.

We are using regular expression to replace a string occurrence globally ‘g’.


String.prototype.replaceAll = function (targetString, subString) {
 var inputString = this;
 inputString = inputString.replace(new RegExp(targetString, 'g'), subString); //replace a string globally and case sensitive

return (inputString);
};

Prototype is a global property which is available with almost all JavaScript objects. It allows you to add properties and methods to an object.

JavaScript prototype Property Syntax:


object.prototype.name=value

Example:


var inputString = "This is aBc. aBC is not a bad start. This is good ABC";

inputString = inputString.replaceAll("aBc", "xyz"); //replace all case sensitive

alert(inputString); //This will print "This is xyz. aBC is not a bad start. This is good ABC"

Case insensitive replace all

We are using regular expression to replace a string occurrence globally and case insensitive which is ‘gi’.


String.prototype.replaceAllCaseInSensitive = function (targetString, subString) {
 var inputString = this;
 inputString = inputString.replace(new RegExp(targetString, 'gi'), subString); //replace a string globally and case-insensitive

return (inputString);
};

Example:


var inputString = "This is aBc. aBC is not a bad start. This is good ABC";

inputString = inputString.replaceAll("abc", "xyz"); //replace all case sensitive

alert(inputString); //This will print "This is xyz. xyz is not a bad start. This is good xyz"

jsFiddle example

Related articles