How to use Web Services with C#

How to use Web Services with C#



This article provides a walkthrough of how to call a Web API from a client application that we created in Part 1.

Let's start by creating a simple Console Application in the existing solution that we have already created.

Step 1: Right-click the Solution Explorer, select "Add New Project" and select "Console Application".

Add New Project

Step 2: Install Microsoft.AspNet.WebApi.SelfHost using the Packager Manager console as shown below. Click on "Tools" then select "Library Package Manager" --> "Package Manager Console" and enter the following command:

Package Manager Console

Install-Package Microsoft.AspNet.WebApi.SelfHost

Install-Package

Step 3: Now add a reference to the TestClient to the SelfHost1 project as in the following:

In Solution Explorer right-click the ClientApp project then select "Add Reference".

In the Reference Manager dialog, under "Solution", select "Projects". Select the SelfHost project. Click "OK" as shown below.

SelfHost project

Step 4: Now open the Program.cs file and add the following implementation. Then run the project by setting TestClient as the Start up project.
using System;  
using System.Collections.Generic;  
using System.Net.Http;  
  
namespace TestClient  
{  
    class Program  
    {  
        static HttpClient client = new HttpClient();    
        static void Main(string[] args)  
        {  
            client.BaseAddress = new Uri("http://localhost:8080");    
            ListAllBooks();  
            ListBook(1);  
            ListBooks("seventh");    
            Console.WriteLine("Press Enter to quit.");  
            Console.ReadLine();  
        }  
  
        static void ListAllBooks()  
        {  
            //Call HttpClient.GetAsync to send a GET request to the appropriate URI   
            HttpResponseMessage resp = client.GetAsync("api/books").Result;  
            //This method throws an exception if the HTTP response status is an error code.  
            resp.EnsureSuccessStatusCode();    
            var books = resp.Content.ReadAsAsync<IEnumerable<SelfHost1.book>>().Result;  
            foreach (var p in books)  
            {  
                Console.WriteLine("{0} {1} {2} ({3})", p.Id, p.Name, p.Author, p.Rating);  
            }  
        }  
        static void ListBook(int id)  
        {  
            var resp = client.GetAsync(string.Format("api/books/{0}", id)).Result;  
            resp.EnsureSuccessStatusCode();  
  
            var book1 = resp.Content.ReadAsAsync<SelfHost1.book>().Result;  
            Console.WriteLine("ID {0}: {1}", id, book1.Name);  
        }    
        static void ListBooks(string author)  
        {  
            Console.WriteLine("Books in '{0}':", author);    
            string query = string.Format("api/books?author={0}", author);    
            var resp = client.GetAsync(query).Result;  
            resp.EnsureSuccessStatusCode();    
            //This method is an extension method, defined in System.Net.Http.HttpContentExtensions    
            var books = resp.Content.ReadAsAsync<IEnumerable<SelfHost1.book>>().Result;  
            foreach (var book in books)  
            {  
                Console.WriteLine(book.Name);  
            }  
        }    
    }  
}  



How to use Geolocation in c#



Use Geolocation in C#


look at the GeoCoordinateWatcher class which is defined in the System.Deviceassembly
The GeoCoordinateWatcher class supplies coordinate-based location data from the current location provider. The current location provider is prioritized as the highest on the computer, based on a number of factors, such as the age and accuracy of the data from all providers, the accuracy requested by location applications, and the power consumption and performance impact associated with the location provider. The current location provider might change over time, for instance, when a GPS device loses its satellite signal indoors and a Wi-Fi triangulation provider becomes the most accurate provider on the computer.
Usage example : 
static void Main(string[] args)
{
    GeoCoordinateWatcher watcher = new GeoCoordinateWatcher();

    watcher.StatusChanged += (sender, e) =>
    {
        Console.WriteLine("new Status : {0}", e.Status);
    };

    watcher.PositionChanged += (sender, e) =>
    {
        Console.WriteLine("position changed. Location : {0}, Timestamp : {1}",
            e.Position.Location, e.Position.Timestamp);
    };

    if(!watcher.TryStart(false, TimeSpan.FromMilliseconds(5000)))
    {
         throw new Exception("Can't access location"); 
    }

    Console.ReadLine();
}
I think this class relies on the same mechanism than the one use by Internet Explorer. 
When you will use it, you will have an icon in your system notification tray telling that location has recently been accessed.

How to use C# for geoCode


Using GeoCode with C#





use the HttpClient class which is often used with Asp.Net Web Api or Asp.Net 5.0.
You have also a http state codes for free, asyn/await programming model and exception handling with HttpClient is easy as pie


var address = "paris, france";
var requestUri = string.Format("http://maps.googleapis.com/maps/api/geocode/xml?address={0}&sensor=false", Uri.EscapeDataString(address));

using (var client = new HttpClient())
{
    var request = await client.GetAsync(requestUri);
    var content = await request.Content.ReadAsStringAsync();
    var xmlDocument = XDocument.Parse(content);

}