Category Archives: Jquery

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]

Advertisements

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]

FeedEk jQuery RSS, ATOM Feed Plugin in ASP.NET MVC


In this article, let’s see an example of jQuery’s one of the popular plugin – FeedEk.

About FeedEk jQuery Plugin

FeedEk is a jQuery RSS/ATOM Feed Reader/Importer/Parser. You can obtain feeds easily from any domain.

Example:

1. Create a new project, name it as “FeedEkPluginExample”.

2. Select the empty MVC template and click ok.

3. Download the FeedEk plugin here. Include the FeedEk files in the solution.

4. Now let’s add a controller and view. Right click on “Controllers” folder in the solution and select Add >> Controller, you will see following window.

Select MVC 5 Controller – Empty option and click on “Add” button.

5. Name it as “HomeController” as shown in the following screen and click “Add”.

6. Now let’s add a view for this controller. Right click on “Views” folder in the solution and select Add >> View, you will see following window and click “Add”.

7. Include the following Javascript resources into _Layout.cshtml page’s <head> section.


<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/FeedEk/js/FeedEk.js"></script>

8. Include the FeedEk css file reference in Index.cshtml file.


<link href="~/Scripts/FeedEk/css/FeedEk.css" rel="stylesheet" />

9. Add a placeholder for the widget to your page.


<div id="divRss">
</div>

10. Add the following javascript that will populate the placeholder.


<script type="text/javascript">
$(function () {
$('#divRss').FeedEk({
FeedUrl: 'http://www.asp.net/rss/spotlight',
MaxCount: 5,
ShowDesc: true,
ShowPubDate: true,
DescCharacterLimit: 150,
TitleLinkTarget: '_blank'
});
});
</script>

There are different options which you can try. Take a look here for documentation.

11. Now if you run the application, you will see following output on the page

Live Demo

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

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

Fill a Dropdownlist using jQuery in ASP.NET


In this article, let’s discuss how to fill a dropdownlist using jQuery in ASP.NET

1. Let’s start by adding a dropdownlist on page.


<asp:DropDownList ID="ddlRecords" runat="server" ClientIDMode="Static"></asp:DropDownList>

Notice that we have set ClientIDMode property to “Static” which means The ClientID value is set to the value of the ID property. So that we can directly refering this control using ID.

2. To fill a dropdownlist, using  jQuery, let’s write a webmethod, which we will call through jQuery Ajax method.


[WebMethod]
 public static string GetResultset()
 {
 DataTable dataTable = new System.Data.DataTable("Employees");
 using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
 {
 try
 {
 SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("SELECT EmployeeID, FirstName + ' ' + LastName AS Name FROM Employees", sqlConnection);
 sqlDataAdapter.Fill(dataTable);
 return JsonConvert.SerializeObject(dataTable);
 }
 catch (Exception ex)
 {
 throw ex;
 }
 }
 }

Notice that we have applied “WebMethod” attribute to this method which is defined in the namespace “using System.Web.Services;”, so we need to include it in the code.


using System.Web.Services;

Set the connection string in the config file.


<connectionStrings>
 <add name="MyConnectionString" connectionString="Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;User ID=sa;Password=123456" providerName="System.Data.SqlClient"/>
 </connectionStrings>

Webmethod Explained:

In the webmethod, we have taken a sql connection and sql adapter to fill a datatable. And the datatable object is serialized using json.net.

3. To call this webmethod, let’s write a jQuery code. Before using jQuery, we need to include the reference to it.


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

4. On document.ready, we will call our webmethod to fill dropdownlist.


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

//fill dropdownlist
 $.ajax({
 type: "POST",
 url: "Default.aspx/GetResultset",
 data: "{}",
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function (data) {
 $.each(jQuery.parseJSON(data.d), function () {
 $("#ddlRecords").append($("<option></option>").val(this['EmployeeID']).html(this['Name']));
 });
 },
 error: function (msg) {
 //error
 }
 });

});
 </script>

Here data will have number of records, so we have iterated through each record using .each() and appended a record to our dropdownlist. Since we are getting serialized data, we have parsed data using jQuery.parseJSON()

Source Code Download:

Github [Repository Link]