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);

}

HOW TO TAKE SCEEN SHOT IN C# WINDOWS FORM

How take screenshot of desktop using Windows Application.
 
 
Step 1: Add the following namespaces which helps for generating image:
  1. using System.Windows.Forms;
  2. using System.Drawing.Imaging;
Step 2: Add the following code to capture the screenshot and save it to drive:
  1. Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);  
  2. Graphics graphics = Graphics.FromImage(bitmap as System.Drawing.Image);  
  3. graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);  
  4. bitmap.Save(@"D:\MyDemo\Reports\ScreenShot.bmp", ImageFormat.Jpeg);  
In preceding code: 
 
Line 1: It is fetching computer screen height and width. 
Line 2: Creating graphics object to draw/generate image.
Line 3: CopyFromScreen() method is copying background image and generate image through graphics object.
Line 4: It is saving the image to physical folder. 
 
Output:
 
 
                           Figure 1: Captured screenshot in Drive

HOW TO SEND MAIL USING C# WINDOWS FORM

SENDING EMAIL


Step 1: Open Your Visual Studio 2010, Go to File, New, Projects, then under Visual C# select Windows.

windows application

You can change the name of the project and browse your project to different location too. And then press OK.

Design chamber

Step 2: Now open your Form1.cs file, where we will create our design for sending email to gmail. We will drag 3 labels, 3 textboxes and one button from toolbox to Form1.cs. You will see your Form look like this.

Design

Code chamber

Right click on the blank part of Form1.cs, then click View Code. You will enter in the code part of the form. Write the following code and then Press F5 to run the project. 

For GmailSend.dll file - -> https://gmailsend.codeplex.com/

Add some of the namespaces for sending Gmail.

namespaces

If you can’t find these namespaces in the intellisense, then in the Solution Explorer - Right Click, Add References. In Add References, Browse and Find GmaiSend.dll that you had downloaded from the above link.

Add References:

Add References

Code chamber

Open your Form1.cs file where you have to write the code for sending Gmail.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using GmailSend;  
  10.   
  11.   
  12. namespace WindowsFormsApplication2  
  13. {  
  14.     public partial class Form1 : Form  
  15.     {  
  16.         public Form1()  
  17.         {  
  18.             InitializeComponent();  
  19.         }  
  20.   
  21.         private void button1_Click(object sender, EventArgs e)  
  22.         {  
  23.             try  
  24.             {  
  25.                 gmail gmlsnd = new gmail();  
  26.                 gmlsnd.auth("your emailid""your password");  
  27.                 gmlsnd.To = textBox1.Text;  
  28.   
  29.   
  30.                 gmlsnd.Subject = textBox2.Text;  
  31.                 gmlsnd.Message = textBox3.Text;  
  32.   
  33.                 gmlsnd.Priority = 1;  
  34.                 gmlsnd.send();  
  35.   
  36.                 MessageBox.Show("Your Mail is sended");  
  37.             }  
  38.             catch (Exception ex)  
  39.             {  
  40.                 MessageBox.Show(ex.Message);  
  41.             }  
  42.              
  43.              
  44.         }  
  45.   
  46.           
  47.     }  
Output chamber

Output


HOW TO READ EXCEL DATA WITH C# WINDOWS FORM

READ EXCEL DATA 
  1. Open Visual Studio. Select New Project, then Windows Form Application.
  2. Name it as you want. My applications name is ReadExcelFileApp.

    window form application
  3. First of all add Reference of Excel library. Right click on the Reference in the solution explorer. 

    Assemblies, Extensions, then Microsoft.Office.Interop.Excel.

    If you are using Visual Studio 2010, then you can add Reference using two ways:

    Right click on References then select Add Reference. After that a dialog appears,

    1. Browse, C drive, Microsoft Office, Office12, then open EXCEL.EXE.
    2. Select .NET tab then choose Microsoft.Office.Interop.Excel.


  4. After adding Reference add namespace using Excel = Microsoft.Office.Interop.Excel; and other namespaces as shown in the figure.
  5. Add two buttons Choose and Read File and Close.
  6. Add a DataGridView to see the result (excel data).

    DataGridView
  7. Create a method ReadExcel who returns a datatable using the following logic.
    1. public DataTable ReadExcel(string fileName, string fileExt) {  
    2.     string conn = string.Empty;  
    3.     DataTable dtexcel = new DataTable();  
    4.     if (fileExt.CompareTo(".xls") == 0)  
    5.         conn = @"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';"//for below excel 2007  
    6.     else  
    7.         conn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=NO';"//for above excel 2007  
    8.     using(OleDbConnection con = new OleDbConnection(conn)) {  
    9.         try {  
    10.             OleDbDataAdapter oleAdpt = new OleDbDataAdapter("select * from [Sheet1$]", con); //here we read data from sheet1  
    11.             oleAdpt.Fill(dtexcel); //fill excel data into dataTable  
    12.         } catch {}  
    13.     }  
    14.     return dtexcel;  
    15. }  
    Let's discuss something about ReadExcel() method.

    Firstly, we will decide whether the file has extension .xls or .xlsx because there is a difference between the connection strings of both the files.

    If the file has extension .xls, then the connection string will be the following:

    provider=Microsoft.Jet.OLEDB.4.0;Data Source='fileName';Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';

    Otherwise

    Provider=Microsoft.ACE.OLEDB.12.0;Data Source='FileName';Extended Properties='Excel 12.0;HDR=NO';"

    Here HDR is the header field ,depend upon you,whether you want to add or not,

    IMEX=1 is used to retrieve the mixed data from the columns.

    Now by using the OleDbConnection define an OleDbDataAdapter.
    1. OleDbDataAdapter oleAdpt = new OleDbDataAdapter("select * from [Sheet1$]", con);  
    Here Sheet1 is the sheet number that you want to select, you can select any sheet e.g. Sheet2, Sheet3, etc. If you want to choose some specific columns,   then you can. For example, you want to read just 2 columns say Name and Salary from the excel file then your query be like the following:

    Select Name,Salary from [Sheet1$]

    If there are no headers in complex excel files then you can select columns like F1, F20 etc. In that case the query be like the following:

    Select F11,F41,F70 from [Sheet1$]
  8. Add the following logic in button click events.
    1. private void btnChooseFile_Click(object sender, EventArgs e) {  
    2.     string filePath = string.Empty;  
    3.     string fileExt = string.Empty;  
    4.     OpenFileDialog file = new OpenFileDialog(); //open dialog to choose file  
    5.     if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK) //if there is a file choosen by the user  
    6.     {  
    7.         filePath = file.FileName; //get the path of the file  
    8.         fileExt = Path.GetExtension(filePath); //get the file extension  
    9.         if (fileExt.CompareTo(".xls") == 0 || fileExt.CompareTo(".xlsx") == 0) {  
    10.             try {  
    11.                 DataTable dtExcel = new DataTable();  
    12.                 dtExcel = ReadExcel(filePath, fileExt); //read excel file  
    13.                 dataGridView1.Visible = true;  
    14.                 dataGridView1.DataSource = dtExcel;  
    15.             } catch (Exception ex) {  
    16.                 MessageBox.Show(ex.Message.ToString());  
    17.             }  
    18.         } else {  
    19.             MessageBox.Show("Please choose .xls or .xlsx file only.""Warning", MessageBoxButtons.OK, MessageBoxIcon.Error); //custom messageBox to show error  
    20.         }  
    21.     }  
    22. }  
    23.   
    24. private void btnClose_Click(object sender, EventArgs e) {  
    25.     this.Close(); //to close the window(Form1)  
    26. }  
After choosing the file Result will be like the following whether you upload .xls or .xlsx file.

Choose and read file