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]

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]

Entity Framework – Database First Approach Example


In this article, Let’s see an example of Entity Framework – Database First approach

If you don’t know about Entity Framework, please go through this article.

Database First allows you to reverse engineer a model from an existing database. The model is stored in an EDMX file (.edmx extension) and can be viewed and edited in the Entity Framework Designer. The poco classes are automatically generated from the EDMX file.

Entity Framework – Database First Approach Example

1. Let’s create a console application. Name it as “EFDatabaseFirstExample”.

2. We will create a model by using Entity Framework Designer for our existing database. Let’s add a new item to our project “ADO.NET Entity Data Model”.

3. It will start a wizard, now as we have existing database, we will select “Generate from Database”.

4. Choose the connection string, pick a connection to our existing database and click on “Next” button.

5. Wizard will ask you to pick the Entity Framework version to use. Just select the latest version and click “Next”.

6. Now choose the database objects like tables, views, stored procedures etc from the screen.

7. Model is created now and you can see the entities.

8. During the process when you select Entity Framework version, the reference to Entity Framework Assembly is automatically added.

So after step 7, you will see following things in the project.

9. Since everything is in place, let’s code to add a employee for a company and display all the employees for a company.


Console.WriteLine("Please enter employee name");
using (var db = new EFDatabaseFirstExample.EFDatabaseFirstDBEntities())
{
Employee employee = new Employee();
employee.Name = Console.ReadLine();
employee.CompanyId = 1; //hard coded for demo purpose
employee.Age = 27;
db.Employees.Add(employee);
db.SaveChanges();
}

Console.WriteLine("List of employees for company 1");
using (var db = new EFDatabaseFirstExample.EFDatabaseFirstDBEntities())
{
//get the company with ID = 1
var company = (from c in db.Companies
where c.Id == 1
select c).SingleOrDefault();

//get the employee list for a company with a id = 1
List<Employee> employees = company.Employees.ToList();

//display each item.
foreach (var emp in employees)
{
Console.WriteLine(emp.Name);
}
Console.ReadKey();
}

Hope this helps. Please comment below the post if you have any doubts or questions.

Source Code Download:

Github [Repository Link]

Box.com [Direct Download Link]

Entity Framework – Model First Approach Example


In this article, Let’s see an example of Entity Framework – Model First approach

If you don’t know about Entity Framework, please go through this article.

Model First allows you to create a new model using the Entity Framework Designer and then generate a database schema from the model.

Entity Framework – Model First Approach Example

1. Let’s create a console application. Name it as “EFModelFirstExample”.

Add a reference to the “Entity Framework” using nuget package manager. If you don’t know how to add a reference using Nuget, please refer this post.

2. We will create a model by using Entity Framework Designer. Let’s add a new item to our project “ADO.NET Entity Data Model”.

3. Once you click on “Add”, there are 2 options, either you can create a model using existing database or you can start it by creating empty model. In this project, we will create an empty model.

4. Once you “Finish” it, you will see that an empty file called “Model1.edmx” is added into your project. Open it and right click on it and select Add New and click on Entity to create a new entity.

5. For this example, we will consider a simple Company-employee relationship and create entities for them.

6. Right click on it and Add new scalar property called “Name” and “Address”.

7. Now follow the same procedure for “Employee” entity. Add “Name” and “Age” scalar properties to it.

Once it’s done, we need to set the association between those 2 entities. Right click the “Company” entity and click “Add New” – “Association”.

8. Check the “Multiplicity” option and set it for our entities. In our case, it’s one to many. (a company – many employees)

9. Entities and their relationship will look like as show in the screenshot below. Just right click on the “edmx” file anywhere on the screen and click on “Generate Database from Modal” to generate database for our defined entities.

10. Once you click on “Generate Database from Modal”, you will be asked to set connection string for your database.

11. Then from the following screen, select “Microsoft SQL Server” and click “Continue”.

12. Enter the Server Name, credentials and Database name.

13. If you are creating a new database, you will see following screen. Just click “Ok” as it will create a new database only.

14. Once done, select “Yes” or “No” (include or exclude sensitive data in connection string) and Click “Next” button.

15. Finally review “Summary and Settings” and click on “Finish” button.

16. You may see following screen once you finish the wizard. Just ignore it and click “Ok”.

17. A file called “Model1.edmx.sql” will be created and added to the project. Open it and right click, then select “Execute”. It will create tables and constraints in the database.

18. Since entities are automatically created, we can directly use it in the code.

If you just expand the “Model1.tt”, you can see the classes “Company.cs” and “Employee.cs” are auto created during the process.

19. Now let’s write a sample code which will add a company record and display it on the screen.


Console.WriteLine("Please enter a company name.");
string companyName = Console.ReadLine();

Console.WriteLine("Please enter a company address");
string companyAddress = Console.ReadLine();

EFModelFirstExample.Company company = new Company();
company.Name = companyName;
company.Address = companyAddress;
using (var db = new DBContext())
{
db.Companies.Add(company);
db.SaveChanges();
}

Console.WriteLine("List of companies in the DB");
using (var db = new DBContext())
{
var companies = (from c in db.Companies
select c.Name).ToList();
foreach (var name in companies)
{
Console.WriteLine(name);
}
Console.ReadKey();
}

Hope this helps. Please comment below the post if you have any doubts or questions.

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.

Peek Definition in Visual Studio 2013


In this article, let’s review a new handy feature in Visual Studio 2013 called Peek Definition .

Generally when you want to view a method, you point a mouse cursor on a method name and right click on it and click “Go To Definition” (F12 shortcut key).

Once you do that, you will go to the file where method is declared or defined.

Using Peek Definition

This feature is similar to “Go To Definition” except in-file editing (which we can describe it as view or edit in a same file without losing your place) as explained below.

When you right click on a method by placing a cursor over it and clicking on “Peek Definition” (ALT + F12 shortcut key), you won’t leave your current file/location instead a small window will appear over there.

This makes it very easy to view as well as edit a method definition without losing your place in the current file.