Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Learn Web API Using WPF, WebForms, and Xamarin

DZone's Guide to

Learn Web API Using WPF, WebForms, and Xamarin

Do you love ASP.NET Core? Then read on to learn how to use its Web API to create applications for both native and web applications.

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

What Is the ASP.NET Web API?

ASP.NET Web API is a framework to build web APIs on top of the .NET framework, which makes it easy to build HTTP services that comprise of a range of clients, including mobile devices, web browsers, and desktop applications.

Web API is similar to ASP.NET MVC, so it contains all of MVC's features.

  • Model
  • Control
  • Routing
  • Model binding
  • Filter
  • Dependency injections

HTTP is not just for serving web pages. It is also a powerful platform to build RESTful (Representational state transfer) APIs that expose services and data. HTTP is simple, flexible, and ubiquitous.

Why Use the ASP.NET Web API?

Web API can be used anywhere in a wide range of client applications (Windows and Web), Mobile devices, and browsers. Web API perfectly supports HTTP verbs (GET, POST, PUT, DELETE).

Xamarin

Create a Simple Web API to Send an Email

Open Visual Studio 2015. Go to New Project-> Select Visual C# -> Web and choose the project type, ASP.NET Web Application, in the pop-up.

Xamarin

From the pop-up, given below, we will select the Web API template.

Xamarin

Once the project is created, add a new API in the controllers folder. ->Right click on controllers-> add controller. Now, add Scaffold and Create as API Controller. If you've done it properlyl, “SendMailApiController” will appear.

Xamarin

Using the Namespace

using System.Net;  
using System.Net.Http;  
using System.Net.Http.Formatting;  
using System.Web.Http;  
using System.Net.Mail;  
using System.Configuration;.  
  
If namespace are missing in your project then add to use NuGet package manager. Write the code in your method.  
   [HttpPost]  
        public HttpResponseMessage SendMail(EmailConfigDetailsVM vm)  
        {  
    bool responce = false;  
            try  
            {  
                MailMessage mail = new MailMessage();  
                SmtpClient smtpServer = new SmtpClient();  
                string password = ConfigurationManager.AppSettings["password"];  
                mail.From = new MailAddress(ConfigurationManager.AppSettings["MailFrom"]);  
                string[] toRecipients = vm.ToRecipients.Split(',');  
                foreach (string toRecipient in toRecipients)  
                {  
                    if (!string.IsNullOrEmpty(toRecipient))  
                        mail.To.Add(new MailAddress(toRecipient));  
                }  
                  
                mail.Subject = vm.Subject;  
                mail.Body = vm.Body;  
                vm.FromRecipients = ConfigurationManager.AppSettings["MailFrom"];  
                smtpServer.Host = ConfigurationManager.AppSettings["Host"];  
                smtpServer.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);  
                smtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;  
                smtpServer.EnableSsl = bool.Parse(ConfigurationManager.AppSettings["EnableSsl"]);  
                smtpServer.Timeout = 100000;  
                smtpServer.Credentials = new System.Net.NetworkCredential(vm.FromRecipients, password);  
                smtpServer.Send(mail);  
  
var Result = this.Request.CreateResponse(HttpStatusCode.OK, responce, new JsonMediaTypeFormatter());  
                 
                return Result;  
            }  
            catch (Exception ex)  
            {  
                HttpError Error = new HttpError(ex.Message) { { "IsSuccess", false } };  
                return this.Request.CreateErrorResponse(HttpStatusCode.OK, Error);  
            }  
  
    }  
public class EmailConfigDetailsVM //Create New Class file for arguments  
    {  
        public string ToRecipients { get; set; }  
        public string Body { get; set; }  
        public string Subject { get; set; }  
    }   

If namespace is missing in your project, then add the NuGet package manager. Write the code in your method.

Write Web.Config File

I am using the Gmail domain and configuring from the Mail ID in the Web.config file.

<appSettings>  
    <add key="Port" value="587"/>  
    <add key="Host" value="smtp.gmail.com" />  
    <add key="MailFrom" value="XXXXX@gmail.com" />  
    <add key="password" value="XXXX" />  
    <add key="EnableSsl" value="True" />  
  </appSettings>  

Once you run the application, Web API REST Services are ready.

Xamarin

Calling the Web API Method

In this section, we'll call the Web API method from the following:

  • WPF (Native Application)
  • WebForm (Web Application)
  • Xamarin (Mobile Application)Xamarin

Consume Web API in WPF (Native Application)

To create a WPF Application, go to New Project, select Windows and choose WPF Application.

Xamarin

Simply design the windows, as shown below, using XAML code, and give parameters to Email Id, Email Subject, and Email Body.

Xamarin

XAML Code

<Grid>  
    <Label Content="Email Id" HorizontalAlignment="Left" Margin="55,50,0,0" VerticalAlignment="Top"/>  
    <Label Content="Email Body" HorizontalAlignment="Left" Margin="39,149,0,0" VerticalAlignment="Top"/>  
    <Label Content="Email Subject" HorizontalAlignment="Left" Margin="26,100,0,0" VerticalAlignment="Top"/>  
    <TextBox HorizontalAlignment="Left" Height="23" Margin="133,54,0,0" TextWrapping="Wrap" Text="XXXX@gmail.com" VerticalAlignment="Top" Width="298" Name="txtid"/>  
    <TextBox HorizontalAlignment="Left" Height="23" Margin="133,100,0,0" TextWrapping="Wrap" Text="WPFTestMail" VerticalAlignment="Top" Width="298" x:Name="txtSubject"/>  
    <RichTextBox HorizontalAlignment="Left" Height="81" Margin="133,149,0,0" VerticalAlignment="Top" Width="298" Name="txtBody">  
        <FlowDocument>  
            <Paragraph>  
                <Run Text="WPF"/>  
            </Paragraph>  
        </FlowDocument>  
    </RichTextBox>  
    <Button Content="Send Mail" HorizontalAlignment="Left" Margin="133,253,0,0" VerticalAlignment="Top" Width="298" Height="37" Name="btnSendMail" Click="btnSendMail_Click"/>  
  
</Grid>  


Using the Namespace Given Above

using Newtonsoft.Json;  
using System.Net.Http;  
using System.Configuration;  
using System.Net.Http.Headers;  

Base code

After inserting the namespace, create a new instance of the HttpClient, followed by setting its base URL to http://localhost:51537/api

public MainWindow()  
        {  
HttpClient client = new HttpClient();  
       string apiUrl = ConfigurationManager.AppSettings["MailApi"] + "/SendMailApi";   
    client.BaseAddress = new Uri(apiUrl);  
            client.DefaultRequestHeaders.Accept.Clear();  
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
}  

This accepts header property instruction, which is sent to the server, as a response, in JSON format.

new MediaTypeWithQualityHeaderValue("application/json") 

The URL will be set in the App.config file:

<appSettings>  
    <add key="MailApi" value="http://localhost:51537/api" />  
 </appSettings>   

Follow the code given above, and copy and paste the button click event.

private void btnSendMail_Click(object sender, RoutedEventArgs e)  
        {  
            EmailConfigDetailsVM emildetails = new EmailConfigDetailsVM();  
            emildetails.ToRecipients = txtid.Text.ToString();  
            emildetails.Body = new TextRange(txtBody.Document.ContentStart, txtBody.Document.ContentEnd).Text.ToString();   
            emildetails.Subject = txtSubject.Text.ToString();  
            var serializedProduct = JsonConvert.SerializeObject(emildetails);  
            var content = new StringContent(serializedProduct, Encoding.UTF8, "application/json");  
            HttpResponseMessage response = client.PostAsync(apiUrl + "/SendMailApi", content).Result;  
            if (response.IsSuccessStatusCode)  
            {  
                MessageBox.Show("Send Successfully");  
            }  
            else  
            {  
                MessageBox.Show("Send Failed...");  
            }  
        }  

Enter any input in the WPF Window and click the Send Mail button.


Xamarin

Consume Web API in WebForms (Web Application)

To create a web application, go to New Project ->Visual C#->Select ASP.NET Web Application. In this pop-up, choose the Web Forms template.

Xamarin

Once the project is created, you can create new Web Forms and design the forms, as shown below.

Xamarin

The same WPF code style will be used by the Web Application. If there is no HttpClient, then get it from the NuGet Package Manager.

Xamarin

After installing the interface you can alter the WPF code for Web Forms, like so: 

emildetails.ToRecipients = txtmailId.Text.ToString();  
       emildetails.Body = txtmailBody.Text.ToString();  
       emildetails.Subject = txtmailSub.Text.ToString();  
       var serializedProduct = JsonConvert.SerializeObject(emildetails);  
       var content = new StringContent(serializedProduct, Encoding.UTF8, "application/json");  
       HttpResponseMessage response = client.PostAsync(apiUrl + "/SendMailApi", content).Result;  
       if (response.IsSuccessStatusCode)  
       {  
          lblsuccess.Text="Send Successfully";  
           lblerror.Text = "";  
       }  
       else  
       {  
           lblsuccess.Text = "";  
           lblerror.Text="Send Failed...";  
       }   

Now, run the web application and the email will be received from the email id that is configured in Web API.


Xamarin

Consume Web API in Xamarin (Mobile Application)

To create a mobile application, go to New Project ->Visual C#->Cross-Platform, and choose Blank App, using the Portable class library in the pop-up.

Xamarin

Right click on App (Portable) and add new Item->Forms Xaml Page.


Xamarin

Navigate to the main page in the App.xaml.cs file

MainPage = new App1.Page1();  


Just write XML code for an Android mobile UI, as shown below.

<?xml version="1.0" encoding="utf-8" ?>  
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
             xmlns:local="clr-namespace:App1"  
             x:Class="App1.MainPage">  
<StackLayout x:Name="MasterLayout1" >  
  <Label Text="Email Id" />  
  <Entry x:Name="txtmailId" Text=" "></Entry>  
  <StackLayout x:Name="MasterLayout2">  
  
    <Label Text="Email Subject"  
            
          HorizontalOptions="Center" />  
    <Entry x:Name="txtmailSub" Text="XamarinTestMail"></Entry>  
  </StackLayout>  
    
  <StackLayout x:Name="MasterLayout3">  
    <Label Text="Email Body"  
            
            HorizontalOptions="Center" />  
    <Entry x:Name="txtmailBody" Text="Hii"></Entry>    
  </StackLayout>  
    
  <Button Clicked="MailSend_clicked" Text="Send Mail"></Button>  
</StackLayout>  
</ContentPage>   

Run the mobile application. This page appears on the mobile device or an app will open an Android Emulator Manager.

Xamarin

Follow the same HttpClient settings and alter the code based on mobile UI in the button clicked event.

HttpClient client = new HttpClient();  
        string apiUrl = "http://localhost:51537/api";       
emildetails.ToRecipients = txtmailId.Text.ToString();  
            emildetails.Body = txtmailBody.Text.ToString();  
            emildetails.Subject = txtmailSub.Text.ToString();  
            var serializedProduct = JsonConvert.SerializeObject(emildetails);  
            var content = new StringContent(serializedProduct, Encoding.UTF8, "application/json");  
            HttpResponseMessage response = client.PostAsync(apiUrl + "/SendMailApi", content).Result;  
            if (response.IsSuccessStatusCode)  
            {  
                DisplayAlert("Alert", "Send Successfully", "OK");  
            }  
            else  
            {  
                DisplayAlert("Alert", "Send Failed...", "OK");  
            }   

After clicking the button, the mail is sent to the specified Email Id.

Xamarin

Conclusion

In this article, we have learned how to use Web API, by sing WPF, WebForms, and Xamarin. If you have any queries, please tell me through the comments section.

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
web dev ,asp.net core ,web api ,web application development

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}