Tag 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.

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]

jQuery Advantages over Standard Javascript


Sometimes you may ask that “Why jQuery” The answer lies in the advantages of jQuery over standard Javascript.

Advantages of jQuery:

1. Large Javascript library Framework

jQuery enables you to perform hordes of functions in comparison to Javascript.

2. Amazing Documentation and Live Demos

The jQuery website has a great documentation and tutorials available along with a live demos. Even absolute beginner in programming (or jQuery) can learn it very easily.

3. Supports Ajax

jQuery provides full Ajax support where actions can be performed on pages without full postback. jquery has bunch of Ajax methods available.

4. Cross Browser Campatibility

jQuery methods provides cross browser compatibility. This means a code written in jQuery can work in different browsers like Firefox, Chrome, Internet Explorer, Opera etc. So that developer can code easily without worrying about the code output on different browsers.

5. Easy DOM manipulation

jQuery provides you methods for working with the DOM. It handles DOM the way it handles the objects!

6. Ease of use

jQuery is very more easy to use compared to standard Javascript. It uses very simple syntax, It also requires much less lines of code to achieve the same feature in comparison.

7. Strong and Large Open Source community (lots of plugins available)

jQuery is an open source project, it comes with hundreds of plugins available for download to instantly speed up your development process.

Disable Right Click on Web Page and Image in ASP.NET


Sometimes you want to prevent user from right clicking on your web pages or images from being copied. It may be because of some security reasons. You can secure your web pages or images by disabling right click.

Please note that, It is impossible to prevent webpages or images from being stolen/copied completely, since there are so many tools and utilities through which one can copy yours images.

To achieve this, Add the below event handler to the image tag.

Disable right click on images:

1. Javascript Approach:


<img src="http://i250.photobucket.com/albums/gg247/dsuraj/General/disablerightclick_zpscc89f5c6.png" oncontextmenu="return false;" />

2. jQuery Approach:


$('img').bind('contextmenu', function(e){
return false;
});

jsFiddle example

Disable right click on a web page:

1. Javascript Approach:


<html>
<head>
...
</head>
<body oncontextmenu="return false;" >
...
</body>
</html>

2. jQuery Approach:


$(document).bind("contextmenu",function(e){
return false;
});

jsFiddle example