How to pull weather info into a console app using OpenWeatherMap API

In this post, I’m going to show you how to pull weather data from a web service in a console application in easy to follow steps.

First things first, let’s sign up with Weather Map using this link.

After you have signed up, go to the API keys tab as in the image below. Here, you will see a default API key generated. If it’s not there, you can generate one by simply entering a key name in the *Name field and hitting the Generate button:

You can create however many API keys you want, although, you would only need one.

Once you have obtained a key, it takes somewhere between 10 to 60 minutes for the key to activated, so be patient!!

Next, let’s first test the API key using Postman or Fiddler, although, I’m using Postman here. If you don’t have Postman, you can install it from this link.

If you rather use your favorite browser, you can simply use the URL below in the address bar:

api.openweathermap.org/data/2.5/weather?q=london&appid={my_api_key}

Please note, I have chosen to have the web service return me JSON data. If you are comfortable with XML, you can do so by specifying mode=xml or even html in the URI. Otherwise, used mode=json like the one that is being used here. This is the beauty of RESTful services where one of its tenets is content negotiation.

Another cool trick is to have Visual Studio generate a C# POCO class from a JSON object string. To do that, simply copy the JSON raw data, then in Visual Studio IDE, go to Edit -> Past Special -> Paste JSON As Classes. See below:

Alternatively, you can use this tool to do just the same. Below is the class that would get generated using one of the above methods:

public class RootObject
    {
        public Coord coord { get; set; }
        public Weather[] weather { get; set; }
        public string _base { get; set; }
        public Main main { get; set; }
        public int visibility { get; set; }
        public Wind wind { get; set; }
        public Clouds clouds { get; set; }
        public int dt { get; set; }
        public Sys sys { get; set; }
        public int id { get; set; }
        public string name { get; set; }
        public int cod { get; set; }
    }

    public class Coord
    {
        public float lon { get; set; }
        public float lat { get; set; }
    }

    public class Main
    {
        public float temp { get; set; }
        public int pressure { get; set; }
        public int humidity { get; set; }
        public float temp_min { get; set; }
        public float temp_max { get; set; }
    }

    public class Wind
    {
        public float speed { get; set; }
        public int deg { get; set; }
        public float gust { get; set; }
    }

    public class Clouds
    {
        public int all { get; set; }
    }

    public class Sys
    {
        public int type { get; set; }
        public int id { get; set; }
        public float message { get; set; }
        public string country { get; set; }
        public int sunrise { get; set; }
        public int sunset { get; set; }
    }

    public class Weather
    {
        public int id { get; set; }
        public string main { get; set; }
        public string description { get; set; }
        public string icon { get; set; }
    }

Next, let’s write some code that will deserialize raw JSON string into a C# object that is shown above.

private async static Task GetJsonWeatherData(string location, string apikey)
        {
            string url = $"http://api.openweathermap.org/data/2.5/weather?q=" + location +
                       $"&mode=json&units=metrics&APPID=" + apikey;
            try
            {
                using (var webClient = new WebClient())
                {
                    var rawJSON = await webClient.DownloadStringTaskAsync(url);
                    RootObject root = JsonConvert.DeserializeObject(rawJSON);
                    return root;
                }
            }
            catch (AggregateException ae)
            {
                throw ae;
            }
        }

Having tested the api from inside PostSharp, it’s time to call the above method from Program Main of our console app like so:

You might also want to import the following namespaces:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization.Json;
using System.Threading.Tasks;

 

    static void Main(string[] args)
        {
            string apiKey = "hhdfda63316dfkeytrtbde96d94545454545lkl";
            var root = GetJsonWeatherData("toronto,ca", apiKey).GetAwaiter().GetResult();

            Console.WriteLine("City: " + root.name);
            Console.WriteLine("Current Temperature: " + string.Format("{0}\u00B0C", Math.Round(ConvertKelvinToCelcius(root.main.temp))));
            Console.WriteLine("Minimum: " + string.Format("{0}\u00B0C", Math.Round(ConvertKelvinToCelcius(root.main.temp_min))));
            Console.WriteLine("Maximum: " + string.Format("{0}\u00B0C", Math.Round(ConvertKelvinToCelcius(root.main.temp_max))));          
            Console.ReadLine();            
        }
        private static double ConvertKelvinToFahrenheit(float temperature)
        {
            double myTemp;
            myTemp = ((temperature - 273.15) * 9 / 5) + 32;
            return myTemp;
        }

        private static double ConvertKelvinToCelcius(float temperature)
        {
            double myTemp;
            myTemp = (temperature - 273.15);
            return myTemp;
        }

Now run the program in Visual Studio to verify the output. Here, you can see a subset of  data being pulled from a web service that is exposed by OpenWeatherMap API. Although, there’s a lot of data that you could show here such as wind, humidity etc., however, for the purposes of demonstration, I am only showing values that are relevant for this exercise.

Hope you liked it! 🙂

Posted in .NET, Web Services | Leave a comment

Migrate data from SQL Server into CosmosDB

This gallery contains 20 photos.

Those of you who are just getting into the NoSQL world and are eager to get their hands dirty, there’s good news… You’ll be glad to know that there is an open source solution called Data Migration Tool that allows … Continue reading

More Galleries | Leave a comment

How to get started with Web API in .ASP.NET Core

If you want to know what is Web API, I have an article on that which can be accessed here.

Let’s dive in and see how to create a bare-bones Web API project from inside Visual Studio 2017. To do that you can use the Community edition, Professional or the Enterprise edition.

Fire up Visual Studio. Navigate to File -> New Project

Select ASP.NET Core Web Application. There isn’t a Web API project per se, but, you’ll see that in just a moment. Next, give this project a Name and click OK.

Here, you have the option to select one of the templates. In our case, we’ll pick Web API. Notice, the item circled in red. This is the platform where we are targeting “ASP.NET Core 2.1”. Now click OK.

Visual Studio will create and add all the necessary files for you. This consists of the following:

  •  ValuesController class
  • Program.cs
  • Startup.cs

One thing to keep in mind though is the project adds ControllerBase as the base class that ValuesController derives from. This is significant because the ControllerBase does not provide a View support. In addition, it provides access to several properties and methods.

Next, I’ll modify the ActionResult methods for Get verb of the ValuesController class ever so slightly. This Get() method will return us an IEnumerable of type String or in words, it’ll give us a collection of strings without passing any parameters to it.

// GET api/values
        [HttpGet]
        public ActionResult<IEnumerable> Get()
        {
            return new string[] { "This", "is", "a", "blog", "test!" };
        }
// GET api/values/5
        [HttpGet("{id}")]
        public ActionResult Get(int id)
        {
            string retVal = string.Empty;

            switch (id)
            {
                case 1:
                    retVal = "Gather Project Requirements";
                    break;
                case 2:
                    retVal = "Design App";
                    break;
                case 3:
                    retVal = "Write Code";
                    break;
                case 4:
                    retVal = "Test App";
                    break;
                case 5:
                    retVal = "Deploy App";
                    break;
                default:
                    retVal = "Project Status!";
                    break;
            }
            return retVal;
        }

Now, build your project and run the app in your favorite browser. You can either use your browser for testing or simply copy the URL from the browser’s address bar and paste it in Postman or Fiddler.

I am using Postman for testing. Postman is a complete API development environment for API developers. You can download Postman from here. Postman also lets you save your requests for future testing.

In the image below, the Get() method returns a 200 OK response, which serializes the string as JSON.

To test the Get ActionResult by ID, simply provide the ID from 1 to 5 and see the output circled in red. Here, we are following the convention i.e. api/{controller}/{id}

In the next exercise, we will extend this solution by adding Model and Controller classes.

So stay tuned!!

Posted in .NET, Web Services | Leave a comment

An Introduction to Web API

ASP.NET Web API is a framework for building HTTP bases services on top of the .NET Framework.

These services can be consumed by a variety of clients which are the following:

  • Browsers
  • Mobile Apps
  • IoT devices
  • Desktop applications

What are RESTful Services and how do they differ from SOAP?

REST stands for Representational State Transfer. It was introduced by Roy Fielding in 2000 as part of his doctoral dissertation. REST is essentially an architectural pattern for creating services. A useful set of rule as it were.

RESTful services are fundamentally different than SOAP-based services, because they don’t attempt to achieve transport neutrality. In fact, RESTful services typically embrace HTTP as the only “Web” transport. This is because, RESTful design doesn’t say anything about which implementation technologies you use; however, in practice, HTTP is the only commonly used protocol.

With REST, you model services as resources, and you give them unique identifiers in the form of URI’s, and then you interact with those resources through a standard uniform interface, or service contract

REST architectural pattern specifies a set of constraints that a system should adhere to.

REST Architectural Goals

  • Visibility
  • Reliability
  • Scalability
  • Performance
  • Portability
  • Simplicity

REST Design Principles

  • Everything is a Resource (E.g. Departments, Employees etc.)
  • Each Resource is identifiable by Unique URI
  • Use the standard HTTP Verbs
  • Allow multiple representations for the same Resource
  • Communication should always be stateless
  • Content Negotiation (JSON, XML, Text, JPEG etc.)

REST Constraints

  • Client Server
  • Stateless (Communication between Client and Server must be stateless. In other words, nothing should be stored on the server that is related to the client)
  • Cacheable (Persisting data that is frequently accessed by the client)
  • Uniform Interface
  • Layered System
  • Code on Demand

When a user sends a request to the server, the server parses the request, builds the response to return the payload to the client. The response represents a state and HTTP response code that is typically used to inform the client of the result.

There are five types of HTTP status codes which are the following:

  • 100’s (Informational)
  • 200’s (Success)
  • 300’s (Redirection)
  • 400’s (Client Errors)
  • 500’s (Server Errors)

Below is a complete list of HTTP status codes:

What about WCF? How does it measure up to Web API?

Web API is best suited for resource-oriented services using HTTP. WCF on the other hand was created to develop SOAP-based services and bindings.

Web API is light weight, simple and fast and requires little ceremony to get up and running as compared to WCF.

As you can see in the image below, there are different nodes that are connected into one logical connected system. This is typically achieved by Services. Services expose units of functionality via messaging. This interoperability is achieved via standard protocols and message formats.

You can also go to Microsoft Docs to find out more about Web API.

Happy reading 🙂

Posted in .NET, Web Services | Leave a comment

How to create an .EXE using .NET Core Console App

In the previous exercise, we learnt how to publish and execute a .NET Core Console App! In case you want to review that exercise, you can access it from here.

In this exercise, we’ll look at a quick way to turn a .DLL to an .EXE. Please note, when you build a .NET Core console app, it compiles the app to a DLL.

Here’s I’ll show you how to create an EXE:

  • Go to the command prompt and navigate to the location where the project is stored
  • Issue the following command: dotnet build -r win10-x64

You’ll find the .EXE in the folder i.e. Win10-x64. See image below:

Hope this was helpful.

Posted in .NET | Comments Off on How to create an .EXE using .NET Core Console App

How to Publish and Execute a .NET Core Console App!

Publishing a .NET Core app is as easy as 1,2,3. Here’s how:

After you have created the console app, make sure you select Release from the Solution Configurations drop-down menu.

  Now right-click on the project node inside Solution Explorer and choose Publish from the menu item. See image below:

Hit Publish, and you are set!

In order to run the app from command prompt, the quick and easy way to navigate to the location where the .dll is stored, you can do the following:

  • Open Windows Explorer
  • Navigate to the DLL file. It’ll be your project Name with a .DLL extension

  • Point your cursor to the start of your drive (see image below) and type cmd followed by space and hit Enter. This neat shortcut will take you straight to the command prompt.

  • In order to run your program, you need to type: dotnet xxx.dll where xxx is your file name

That’s it!

Useful Links (coming soon):

Publishing .NET Core app.
Creating an .EXE in a Console App
Consuming Console App’s DLL externally (using Batch program)
Sending Email blasts using SendGrid
Using Windows Task Scheduler

Happy Consoling 🙂

Posted in .NET | Comments Off on How to Publish and Execute a .NET Core Console App!

How to use .NET Core Console app?

Console apps have been around since .NET’s inception i.e. 2002. Over the years, it has had a bit of a windows dressing with additional APIs, integration with .NET Core and the like.

Let’s look at a simple console app written in .NET Core that simply sends an email using the Net.Mail API.

using System;
using System.Net.Mail;

namespace SMTP
{
    class Program
    {
        static void Main(string[] args)
        {
            SendTestEmail();
            Console.WriteLine("The email was sent successfully!");
            Console.ReadLine();
        }

        private static void SendTestEmail()
        {
            MailMessage mail = new MailMessage("Obi@eOberoi.com", "ooberoi@hotmail.com");
            SmtpClient client = new SmtpClient
            {
                Port = 587,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = true,
                Host = "smtp.google.com",
                Credentials = new System.Net.NetworkCredential("Obi@gmail.com", "MyPassword")
            };
            
            mail.Subject = "Testing Console App!";
            mail.Body = "How is it going Obi!";
            client.Send(mail);
        }
        
    }

Links to similar blog posts (coming soon!):

Posted in .NET | Comments Off on How to use .NET Core Console app?

How to combine multiple stored procedures into a single resulset

Let’s say, you have multiple stored procedures each of which is tied to a partial view or View Component in MVC. Now, while this may seem like a logical thing to do, but what if you want the entire payload to return to a single View.

Well, how about combine all the stored procedures and return a single result set. Here’s how in three simple steps.

First, let’s take a look at the diagram below:

The Employee table has the following records:

Following are the three stored procedures that I have created for the purposes of this demo:

CREATE OR ALTER PROCEDURE [dbo].[spGetMinimumSalary]	
	@MinSalaryRange MONEY,
	@MaxSalaryRange MONEY
AS
BEGIN
	SET NOCOUNT ON;
	 
	SELECT
		FirstName, 
		LastName, 
		Gender
	FROM 
		Employee 
	WHERE
		(Salary BETWEEN @MinSalaryRange AND @MaxSalaryRange)
END
CREATE OR ALTER PROCEDURE [dbo].[spGetMedianSalary]	
	@MinSalaryRange MONEY,
	@MaxSalaryRange MONEY
AS
BEGIN	
	SET NOCOUNT ON;
  
	SELECT
		FirstName, 
		LastName, 
		Gender
	FROM 
		Employee 
	WHERE
((Salary > @MinSalaryRange) AND (Salary <= @MaxSalaryRange))
END
CREATE OR ALTER PROCEDURE [dbo].[spGetMaximumSalary]	
	@Salary MONEY	
AS
BEGIN
	SET NOCOUNT ON;
	   
	SELECT
		FirstName, 
		LastName, 
		Gender
	FROM 
		Employee 
	WHERE
		(Salary > @Salary)
END

Now, comes the interesting part. Let's create a temporary table:

CREATE TABLE #TmpSalary 
(
	FirstName NCHAR(25),
	LastName NCHAR(25),
	Gender NCHAR(10)
)

As you can see, the temporary table only has the structure, but no data:

Select * from #TmpSalary

Now, let's insert the records into the temporary table that are returned from executing the stored procedures like so:

INSERT INTO #TmpSalary
EXEC spGetMinimumSalary 0, 50000

INSERT INTO #TmpSalary
EXEC spGetMedianSalary 50000, 75000

INSERT INTO #TmpSalary
EXEC spGetMaximumSalary 75000

Let's view the records now:

Select * from #TmpSalary

There you have it! 🙂

Posted in SQL Server | Comments Off on How to combine multiple stored procedures into a single resulset

How to pass delimited list to a Stored Procedure

Let’s write a Table-valued function below. This can be created by navigating to Functions – Table-Valued Functions inside SQL Management Studio.

Just an FYI, I am using the AdventureWorks database, but this  sample can be used in any situation.

CREATE FUNCTION [dbo].[fn_SplitStateProvinceCode]
(
   @List VARCHAR(MAX),
   @Delimiter CHAR(1)
)
RETURNS TABLE 
AS 
  RETURN ( SELECT Item = CONVERT(varchar(500), Item) FROM
      ( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)')
        FROM ( SELECT [XML] = CONVERT(XML, ''
        + REPLACE(@List, @Delimiter, '') + '').query('.')
          ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y
      WHERE Item IS NOT NULL
  );

For testing, you can declare a variable and test the statement by passing the @List and delimiter like so. As you can see, in the sample below, the delimiter is ‘,’.

Caution: The delimited string is strictly delimited by a comma and has no space in between province codes.

DECLARE @List VARCHAR(MAX)
SET @List = 'AB,ON,TX,VIC,WA'
SELECT CODES = ITEM FROM dbo.[fn_SplitStateProvinceCode (@List, ',') 

If you wish to write it in a query using the Where clause and using ‘IN’ you can do the following:

DECLARE @List VARCHAR(MAX)
SET @List = 'AB,ON,TX,VIC,WA'
Select * from Person.StateProvince 
WHERE StateProvinceCode IN (Select CODES = ITEM FROM dbo.fn_SplitStateProvinceCode (@List, ','))	

Cheers,

Obi

Posted in SQL Server | Comments Off on How to pass delimited list to a Stored Procedure

Global Query Filters in EF Core 2.0

Global Query Filters are a new addition to the arsenal of features in EF Core 2.0. This also implies that EF core team spearheaded by Diego Vega who are working diligently to bring EF Core at par with its Entity Framework 6.x classic counterpart. Like it or not, its good news for us developers, right?

Well, GQF in short are LINQ query predicates. In other words they are a boolean expression that are typically passed to the LINQ “Where” query operator and applied to Entity Types in the metadata model (usually in OnModelCreating). Such filters are automatically applied to any LINQ queries involving those Entity Types, including Entity Types referenced indirectly, such as through the use of Include or direct navigation property references.

Below is a Snapshot of the database containing two tables i.e. Department & Employee respectively.

GQFContext.cs class

namespace GlobalQueryFilters 
{
    class GQFContext : DbContext
    {
        public DbSet Department { get; set; }
        public DbSet Employee { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"server=Obi-Oberoi; database=Company; Trusted_Connection=True;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity().HasQueryFilter(e => !e.IsDeleted);
        }

    }

Department & Employee POCO Classes

using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace GlobalQueryFilters
{
    public class Department
    {
        [Key]
        public int DepartmentID { get; set; }
        public string Name { get; set; }
        public List Employee { get; set; }
    }

    public class Employee
    {
        [Key]
        public int ID { get; set; }
        [ForeignKey("DepartmentID")]
        public int DepartmentID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
        public decimal Salary { get; set; }
        public bool IsDeleted { get; set; }
        public Department Department { get; set; }
    }
}

Program.cs

 
static void Main(string[] args)
        {
            using (var ctx =  new GQFContext())
            {
                var emp = ctx.Employee.ToList();

                foreach (var item in emp.Where(e => e.DepartmentID == 3))
                {
                    Console.WriteLine("Name = {0},{1}", item.FirstName, item.LastName);
                }
                Console.ReadLine();
            }
        }

Notice the two records with the DepartmentID of 3 that are being filtered using the LINQ query above.

Now, let’s try and do something different. Let’s query the records with DepartmentID of 2. In the Employee table, we have at least two records with DepartmentID of 2. See below:

Notice the record for the employee Steve Pound has one of his records marked for deletion. That’s precisely what we intended for when using Global Query Filter which as you can recall from the code snippet below. This code is defined in the GQFContext class where we have specifically filtered the record(s) that are marked for soft deletion  like so:

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity().HasQueryFilter(e => !e.IsDeleted);
        }

Notice, the record Steve Pound is filtered as a result of Global Query Filter that is defined as a predicate in the “HasQueryFilter” method.

Posted in ORM | Comments Off on Global Query Filters in EF Core 2.0