DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Learn Web API Using WPF, WebForms, and Xamarin

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.

Thiruppathi Rengasamy user avatar by
Thiruppathi Rengasamy
CORE ·
Jun. 08, 17 · Tutorial
Like (3)
Save
Tweet
Share
19.87K Views

Join the DZone community and get the full member experience.

Join For Free

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 .

Web API Web Service mobile app Windows Presentation Foundation API xamarin

Published at DZone with permission of Thiruppathi Rengasamy, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Low-Code Development: The Future of Software Development
  • How To Use Java Event Listeners in Selenium WebDriver
  • Automated Testing With Jasmine Framework and Selenium
  • How To Create a Failover Client Using the Hazelcast Viridian Serverless

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: