0% found this document useful (0 votes)
7 views10 pages

ADMQ4

The document discusses the importance of Web APIs in modern web applications, highlighting their role in facilitating data exchange and enhancing functionality through integration with external services. It also covers the use of HTTP Modules and Handlers in ASP.NET MVC applications for request processing, as well as providing examples of WebSocket implementation for real-time communication. Additionally, it outlines the steps for deploying an Azure Function and an MVC application that utilizes the Azure Function for weather data retrieval.

Uploaded by

kianlestino0896
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views10 pages

ADMQ4

The document discusses the importance of Web APIs in modern web applications, highlighting their role in facilitating data exchange and enhancing functionality through integration with external services. It also covers the use of HTTP Modules and Handlers in ASP.NET MVC applications for request processing, as well as providing examples of WebSocket implementation for real-time communication. Additionally, it outlines the steps for deploying an Azure Function and an MVC application that utilizes the Azure Function for weather data retrieval.

Uploaded by

kianlestino0896
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Name: Kian Lestino Q4 Week 1 - Task 1

Grade 12 - ONION

Understanding Web APIs and Their Purpose in Modern Web


Applications

A Web API (Application Programming Interface) is a set of rules and protocols


that allows different software applications to communicate with each other over the
internet. It serves as an intermediary that enables developers to access the
functionality or data of a web service without needing to understand the underlying
code. Web APIs are essential in modern web applications, as they facilitate the
integration of various services and enhance user experiences.

One of the primary purposes of a Web API is to enable data exchange


between different systems. For instance, consider a weather application that provides
real-time weather updates. Instead of building its own weather data collection
system, the application can use a Web API from a weather service provider like
OpenWeatherMap. By making a simple HTTP request to the API, the application can
retrieve current weather data and display it to users, thus saving time and resources.

Another example is social media integration. Many websites allow users to


log in using their Facebook or Google accounts. This is made possible through
OAuth, a protocol that uses Web APIs to authenticate users without requiring them to
create a new account. By leveraging these APIs, developers can enhance their
applications' functionality while providing a seamless user experience.

In summary, Web APIs are crucial in modern web applications, enabling


seamless communication between different services and enhancing functionality.
They allow developers to build more complex and feature-rich applications by
integrating external data and services, ultimately improving user engagement and
satisfaction.
Name: ELJAY XYR T. CONDE Q4 Week 1 - Task 2
Grade 12 - ONION

Reasons Developers Add a Web API to an Application

1. Access to Data: Developers add Web APIs to applications to get data from other
sources easily. For example, if an app needs weather information, it can use a
weather API to fetch the latest updates without having to create its own weather
system. This saves time and effort, allowing developers to use reliable data from
experts.

2. Improved Features: Web APIs help developers add new features to their
applications without building everything from scratch. For instance, if an app wants to
accept payments, it can use a payment API like PayPal. This way, the app can offer
secure payment options quickly and focus on other important parts of the application.

3. Easy Communication: Adding a Web API allows different applications to work


together and share information easily. This is especially useful when an app is made
up of different parts that may use different technologies. By using APIs, developers
can make sure their applications can grow and connect with other services in the
future, making them more flexible and useful.
Name: ELJAY XYR T. CONDE Q4 Week 1 - Task 4

Grade 12 - ONION

Tutorial on Using HTTP Modules and HTTP Handlers in an ASP.NET


MVC Application

Using HTTP Modules and HTTP Handlers in an ASP.NET MVC Application

Introduction

ASP.NET provides HTTP Modules and HTTP Handlers to process requests at different
stages of the request-response pipeline. They help in modifying request or response data,
implementing custom authentication, logging, or handling specific requests.

1. Understanding HTTP Modules and HTTP Handlers

HTTP Modules

• Execute during the request processing pipeline.


• Can inspect and modify incoming/outgoing requests.
• Typically used for security, logging, authentication, or response filtering.

HTTP Handlers

• Handle specific request types (e.g., images, API responses).


• Serve as an endpoint for a request, returning the response directly.

2. Creating an HTTP Module

Step 1: Create a Custom HTTP Module

Create a new class in your project (e.g., CustomHttpModule.cs):

using System; using


System.Web;

public class CustomHttpModule : IHttpModule


{ public void Init(HttpApplication context)
{ context.BeginRequest += new
EventHandler(OnBeginRequest); context.EndRequest += new
EventHandler(OnEndRequest);
}

private void OnBeginRequest(object sender, EventArgs e) {


HttpContext.Current.Response.Write("<p>Request
Started...</p>");
}
private void OnEndRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.Write("<p>Request
Ended...</p>"); }

public void Dispose() { }


}

Step 2: Register the Module in web.config

Open web.config and add the following inside <system.webServer>:

<configuration>
<system.webServer>
<modules>
<add name="CustomHttpModule" type="CustomHttpModule"/>
</modules>
</system.webServer>
</configuration>

3. Creating an HTTP Handler

Step 1: Create a Custom HTTP Handler

Create a new class in your project (e.g., CustomHttpHandler.cs):

using System; using


System.Web;

public class CustomHttpHandler : IHttpHandler


{ public void ProcessRequest(HttpContext context)
{ context.Response.ContentType = "text/plain";
context.Response.Write("Hello from Custom HTTP
Handler!"); }

public bool IsReusable => false;


}

Step 2: Register the Handler in web.config

Inside <system.webServer>, add:

<handlers>
<add name="CustomHttpHandler" path="customhandler" verb="*"
type="CustomHttpHandler" resourceType="Unspecified"/> </handlers>

Step 3: Access the Handler

 Run your application and navigate to http://yourdomain.com/customhandler  You


should see the text "Hello from Custom HTTP Handler!"

4. Key Differences Between HTTP Modules and Handlers


Feature HTTP Module HTTP Handler
Execution Runs for every request Handles specific requests
Purpose Global event handling Direct request handling
Use Case Logging, security, authentication Image processing, file serving

Conclusion

Now you have a working HTTP Module and HTTP Handler in your ASP.NET MVC
application! Use modules for global processing and handlers for request-specific logic.
Name: ELJAY XYR T. CONDE Q4 Week 1 - Task 5

Grade 12 – ONION

Short Script Using WebSockets


// WebSocket Server (Node.js) const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });

server.on('connection', ws => { console.log('Client connected');


ws.send('Welcome! Your connection is now active.');

ws.on('message', message => { console.log(`Received: ${message}`); ws.send(`Server


received: ${message}`);
});

ws.on('close', () => console.log('Client disconnected'));


});

// WebSocket Client (Browser Side)


const socket = new WebSocket('ws://localhost:8080');

socket.onopen = () => { console.log('Connected to WebSocket server');


socket.send('Hello, server!');
};

socket.onmessage = event => { alert(`Message from server: ${event.data}`);


}; socket.onclose = () => console.log('Connection closed');

/**
* Explanation:
* WebSockets establish a persistent, bi-directional connection between client and server,
* allowing real-time data exchange without the overhead of repeatedly making HTTP requests.
* This reduces latency and improves efficiency for applications requiring instant updates, such
as chat apps and live notifications.
*/
Name: ELJAY XYR T. CONDE Q4 Week 1 - Task 6

Grade 12 – ONION

Azure Function Code (C# HTTP Trigger)

using System.Net;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;

public static class WeatherForecastFunction


{
[Function("WeatherForecast")]
public static async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequestData req,
ILogger log)
{
var location = req.Query["location"];
var subKey =
Environment.GetEnvironmentVariable("AZURE_MAPS_KEY");

using var client = new HttpClient();


var response = await client.GetAsync(
$"https://atlas.microsoft.com/weather/forecast/daily/json?" +
$"api-version=1.0&query={location}&subscription-
key={subKey}&duration=5");

var result = await response.Content.ReadAsStringAsync();


var httpResponse = req.CreateResponse(HttpStatusCode.OK);
await httpResponse.WriteStringAsync(result);

return httpResponse;
}
}

Deployment Steps to Azure


1. Create Azure Resources:
az group create --name WeatherRG --location eastus
az functionapp create --name WeatherForecastAPI --resource-group
WeatherRG \
--runtime dotnet --functions-version 4 --storage-account <storage-name>

2. Deploy Code:
1. Use Zip Push Deployment ([Search Result 7]):
bash
az functionapp deployment source config-zip -g WeatherRG -n
WeatherForecastAPI --src ./publish.zip
2. Alternatively, deploy directly from Visual Studio using Azure Functions
Tools ([Search Result 10]).

To deploy the Azure Function for the weather forecast service to Azure, I
followed these steps:
1. Development Environment Setup: I developed the Azure Function using
Visual Studio, creating a C# class library project for Azure Functions. This
involved setting up the necessary NuGet packages and writing the function
code.
2. Publishing to Azure:
 I right-clicked the project in Visual Studio and selected Publish.
 In the Target section, I chose Azure and then Azure Function App
(Windows).
 I created a new function app by specifying a globally unique name,
selecting my Azure subscription, choosing a resource group, and
setting the plan type to Consumption.
 I enabled Run from package file to use zip deployment for better
performance.
3. Deployment:
 Visual Studio automatically created a zip package of my project files
and deployed it to Azure using zip deployment.
 The deployment process included setting up necessary Azure
resources like a storage account and Application Insights for
monitoring.
4. Configuration:
 After deployment, I managed application settings through the Azure
portal or Visual Studio to ensure that sensitive keys like the Azure
Maps API key were securely stored and accessible to the function.
This process allowed me to quickly deploy and test my Azure Function in a
serverless environment, leveraging Azure's scalability and cost-effectiveness.
Name: ELJAY XYR T. CONDE Q4 Week 1 -
Task 7

Grade 12 – ONION

using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

public class WeatherController : Controller


{
private readonly HttpClient _httpClient;

public WeatherController(IHttpClientFactory clientFactory)


{
_httpClient = clientFactory.CreateClient();
_httpClient.BaseAddress = new Uri("https://your-azure-function-
url.azurewebsites.net/api/WeatherForecast");
}

public async Task<IActionResult> Index()


{
var response = await _httpClient.GetAsync("?location=47.6,-122.3");
if (response.IsSuccessStatusCode)
{
var forecast = await response.Content.ReadAsStringAsync();
return View(forecast);
}
else
{
return StatusCode(500, "Failed to retrieve forecast");
}
}
}

Deploy the MVC Application


1. Publish the MVC Application:
 Right-click on the project and select Publish.
 Choose Microsoft Azure App Service as the target.
 Select your subscription and create a new web app or use an existing
one.
 Click Publish to deploy your application.
Step 6: Test the Application
1. Navigate to the Deployed Application:
 Open a web browser and go to the URL of your deployed MVC
application.
 Ensure that the application successfully calls your Azure Web Service
and displays the expected data.

You might also like