PDF files play a major role in almost every industry. Whether it’s invoices, reports, onboarding forms, medical summaries, account statemen...

Building End-to-End PDF Automation in .NET Using IronPDF: A Complete Practical Guide Building End-to-End PDF Automation in .NET Using IronPDF: A Complete Practical Guide

A blog about android developement

PDF files play a major role in almost every industry. Whether it’s invoices, reports, onboarding forms, medical summaries, account statements, contracts, or audit logs, companies rely heavily on documents that must be accurate, secure, and consistent. As the volume of data grows, so does the need for a dependable way to generate and manage PDFs without manually stitching everything together.


This is where IronPDF steps in and makes a meaningful difference for .NET developers.


Instead of wrestling with low-level PDF internals or outdated libraries, IronPDF lets you work with familiar tools like HTML, CSS, and C#, while still delivering polished, professional PDFs. In this guide, we’ll walk through a full, practical setup that shows how to build a robust automation system using IronPDF —complete with rendering, merging, extracting content, securing documents, converting to PDF/A, and even generating monthly statements automatically.


1. Why IronPDF Makes PDF Work So Much Easier

IronPDF stands out because it uses a Chrome-based rendering engine behind the scenes. That means whatever you can build for a browser—layouts, styles, scripts—you can turn into a PDF with very little effort.

Highlights at a glance:

  • Convert HTML to PDF with full CSS support
  • Generate PDFs straight from URLs
  • Work with PDF merging, splitting, and page-level manipulation
  • Extract text and images from existing PDFs
  • Apply passwords and permissions
  • Convert documents into PDF/A, which is often required for compliance
  • Works seamlessly across .NET Framework, .NET 6/7/8, Azure, Linux, Docker, and more

Everything demonstrated in this guide mirrors real project requirements found in finance, SaaS, e-commerce, HR, logistics, and enterprise reporting systems.

2. Installing IronPDF

Getting started is as simple as adding the package:

NuGet Package Manager

Install-Package IronPDF

.NET CLI

dotnet add package IronPDF

3. What This Sample Project Demonstrates

Here’s everything covered inside our complete example setup:

Feature Included
Converting HTML to PDF
Rendering website URLs
Using template-driven PDF generation
Merging and splitting documents
Extracting text and images
Converting PDF pages to images
Adding passwords and permissions
Generating PDF/A compliant files
Automated monthly statement workflow

The goal is for you to have a blueprint that can fit into any production system.

📁 Full Sample Project: IronPdfDemo (.NET 8)

Below is a complete runnable project. Simply place the files in a folder, restore dependencies, and run it.


Project Structure

IronPdfDemo/
├── IronPdfDemo.csproj
├── Program.cs
├── Templates/
│ └── InvoiceTemplate.html
├── Statements/
├── Models/
│ └── User.cs
└── Services/
├── PdfService.cs
├── HtmlTemplateService.cs
├── StatementService.cs
└── EmailService.cs

1. IronPdfDemo.csproj

<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="IronPDF" Version="2024.9.2" />
</ItemGroup>
</Project>

2. Templates/InvoiceTemplate.html

<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial; padding: 20px; }
h1 { color: #0077cc; }
.amount { font-size: 22px; margin-top: 20px; }
</style>
</head>
<body>
<h1>Invoice #{{InvoiceNumber}}</h1>
<p>Customer Name: <b>{{CustomerName}}</b></p>
<p>Date: {{Date}}</p>
<p class="amount">Total Amount: <b>${{Amount}}</b></p>
</body>
</html>

3. Models/User.cs

namespace IronPdfDemo.Models;
public class User
{
public int Id { get; set; }
public string CustomerName { get; set; } = "";
public double Amount { get; set; }
public string Email { get; set; } = "";
public string InvoiceNumber { get; set; } = "";
}

4. Services/HtmlTemplateService.cs

using System.IO;
namespace IronPdfDemo.Services;
public class HtmlTemplateService
{
public string RenderTemplate(string filePath, Dictionary<string, string> data)
{
var html = File.ReadAllText(filePath);
foreach (var kv in data)
html = html.Replace($"{{{{{kv.Key}}}}}", kv.Value);
return html;
}
}

5. Services/PdfService.cs — All Core IronPDF Features

using IronPDF ;
namespace IronPdfDemo.Services;
public class PdfService
{
private readonly ChromePdfRenderer renderer;
public PdfService()
{
renderer = new ChromePdfRenderer();
}
public PdfDocument RenderHtml(string html) =>
renderer.RenderHtmlAsPdf(html);
public PdfDocument RenderUrl(string url) =>
renderer.RenderUrlAsPdf(url);
public void Save(PdfDocument pdf, string path) =>
pdf.SaveAs(path);
public PdfDocument Merge(params string[] files)
{
var docs = files.Select(PdfDocument.FromFile).ToList();
var merged = docs.First();
foreach (var doc in docs.Skip(1))
merged.AppendPdf(doc);
return merged;
}
public List<PdfDocument> Split(string path)
{
var pdf = PdfDocument.FromFile(path);
return pdf.SplitToIndividualPages().ToList();
}
public string ExtractText(string path) =>
PdfDocument.FromFile(path).ExtractAllText();
public void ExtractImages(string path)
{
var pdf = PdfDocument.FromFile(path);
var images = pdf.ExtractAllImages();
int i = 1;
foreach (var img in images)
img.Save($"image-{i++}.png");
}
public void ConvertToImages(string path)
{
var pdf = PdfDocument.FromFile(path);
var pages = pdf.ToPngs();
int i = 1;
foreach (var img in pages)
img.Save($"page-{i++}.png");
}
public void SecurePdf(string path, string password)
{
var pdf = PdfDocument.FromFile(path);
pdf.Password = password;
pdf.SecuritySettings.AllowUserPrinting = false;
pdf.SaveAs("secured.pdf");
}
public void ConvertToPdfA(string path)
{
var pdf = PdfDocument.FromFile(path);
var pdfA = pdf.ConvertToPdfA(PdfAStandard.A2A);
pdfA.SaveAs("output-pdfa.pdf");
}
}

6. Services/EmailService.cs (Mock for Demo)

namespace IronPdfDemo.Services;
public class EmailService
{
public Task SendAsync(string to, string subject, string message, string attachmentPath)
{
Console.WriteLine($"(Mock Email Sent) -> {to} : {attachmentPath}");
return Task.CompletedTask;
}
}

7. Services/StatementService.cs — Automated Statement Workflow

using IronPdfDemo.Models;
namespace IronPdfDemo.Services;
public class StatementService
{
private readonly PdfService pdfService;
private readonly HtmlTemplateService templateService;
private readonly EmailService emailService;
public StatementService(PdfService pdf, HtmlTemplateService template, EmailService email)
{
pdfService = pdf;
templateService = template;
emailService = email;
}
public async Task GenerateStatementAsync(User user)
{
var data = new Dictionary<string, string>
{
{ "CustomerName", user.CustomerName },
{ "Amount", user.Amount.ToString("F2") },
{ "Date", DateTime.Now.ToShortDateString() },
{ "InvoiceNumber", user.InvoiceNumber }
};
var html = templateService.RenderTemplate("Templates/InvoiceTemplate.html", data);
var pdf = pdfService.RenderHtml(html);
var filePath = $"Statements/Statement-{user.Id}-{DateTime.Now:yyyy-MM}.pdf";
pdf.SaveAs(filePath);
pdfService.ConvertToPdfA(filePath);
await emailService.SendAsync(user.Email, "Your Monthly Statement", "Attached PDF", filePath);
}
}

8. Program.cs — Running All Features

using IronPdfDemo.Models;
using IronPdfDemo.Services;
var pdfService = new PdfService();
var templateService = new HtmlTemplateService();
var emailService = new EmailService();
var statementService = new StatementService(pdfService, templateService, emailService);
// 1. HTML → PDF
var htmlPdf = pdfService.RenderHtml("<h1>Hello from IronPDF </h1>");
pdfService.Save(htmlPdf, "hello.pdf");
// 2. URL → PDF
var urlPdf = pdfService.RenderUrl("https://example.com");
pdfService.Save(urlPdf, "webpage.pdf");
// 3. Merge
var merged = pdfService.Merge("hello.pdf", "webpage.pdf");
pdfService.Save(merged, "merged.pdf");
// 4. Split
var pages = pdfService.Split("merged.pdf");
int i = 1;
foreach (var page in pages)
page.SaveAs($"page-{i++}.pdf");
// 5. Extract Text
Console.WriteLine(pdfService.ExtractText("hello.pdf"));
// 6. Extract Images
pdfService.ExtractImages("merged.pdf");
// 7. Convert Pages to Images
pdfService.ConvertToImages("merged.pdf");
// 8. Secure PDF
pdfService.SecurePdf("hello.pdf", "mypassword123");
// 9. Convert to PDF/A
pdfService.ConvertToPdfA("hello.pdf");
// 10. Automated Monthly Statement
var user = new User
{
Id = 1,
CustomerName = "John Doe",
Amount = 349.99,
Email = "john@example.com",
InvoiceNumber = "INV-2025-001"
};
await statementService.GenerateStatementAsync(user);
Console.WriteLine("All IronPDF operations completed successfully!");

Conclusion: A Practical, Production-Ready PDF Automation Workflow

With IronPDF, .NET developers can avoid the tedious parts of PDF manipulation and instead focus on building clean, predictable workflows. The combination of HTML rendering, structured APIs, and compliance features like PDF/A support makes it suitable for everything from financial statements and HR documents to automated reporting systems in SaaS platforms.

This guide gives you:

  • A refined, publication-ready article
  • A complete example project you can integrate or expand
  • Real-world use cases covering extraction, security, automation, and conversions

You now have everything needed for a strong contest submission or for building real enterprise-grade PDF solutions.

With the release of .NET 10 , Microsoft has officially removed MessagingCenter , a long-standing feature that m...

.NET 10 Kills MessagingCenter — Here’s the Modern Replacement for Your MAUI App .NET 10 Kills MessagingCenter — Here’s the Modern Replacement for Your MAUI App

A blog about android developement

With the release of .NET 10 , Microsoft has officially removed MessagingCenter , a long-standing feature that many Xamarin.Forms and early MAUI developers relied on for lightweight communication between components. If your app still uses MessagingCenter, this change may feel disruptive — but the truth is, better, safer, and more maintainable options have already replaced it.

This article explains why MessagingCenter is gone, the recommended modern alternatives, and how you can migrate your MAUI app smoothly without breaking existing functionality.

Why MessagingCenter Was Removed

MessagingCenter was originally introduced for simple publish–subscribe messaging, but over time developers ran into repeated issues:

  • Hidden communication made debugging difficult
  • Subscriptions often caused memory leaks
  • It didn’t align with dependency injection or MVVM best practices
  • Modern .NET messaging tools are cleaner and more efficient

To encourage better architecture and avoid unpredictable behavior, Microsoft removed MessagingCenter entirely in .NET 10.

Meet the Modern Replacement: WeakReferenceMessenger

The best replacement — and Microsoft’s deliberate direction — is WeakReferenceMessenger , part of the .NET Community Toolkit.

Why it’s better

  • Strongly typed messages
  • No memory leaks thanks to weak references
  • Great for MVVM
  • Fully supported and actively updated
  • Faster and more optimized than MessagingCenter

It provides the same pub/sub workflow, but without the pitfalls.

Basic Usage Examples

Send a message

WeakReferenceMessenger.Default.Send(new UserLoggedInMessage(userId));

Receive a message

WeakReferenceMessenger.Default.Register<UserLoggedInMessage>(this, (r, m) =>
{
// Handle login message
});

Message definition

public class UserLoggedInMessage : ValueChangedMessage<string>
{
public UserLoggedInMessage(string value) : base(value) { }
}

This pattern is clean, simple, and scales beautifully as your app grows.

Migrating From MessagingCenter to WeakReferenceMessenger

Here’s a common real-world example.

Old (MessagingCenter):

MessagingCenter.Subscribe<HomePage, string>(this, "LoggedIn", (sender, value) =>
{
// handle login
});

New (WeakReferenceMessenger):

WeakReferenceMessenger.Default.Register<LoggedInMessage>(this, (r, m) =>
{
// handle login
});

Send the message

WeakReferenceMessenger.Default.Send(new LoggedInMessage("success"));

Migration Tips for Large Apps

If your MAUI app uses MessagingCenter heavily, follow this structured migration path:

  1. Search for all MessagingCenter usages
  2. Create equivalent message classes
  3. Replace subscriptions with registrations
  4. Replace publish calls with messenger sends
  5. Test navigation scenarios for memory leaks

With WeakReferenceMessenger’s weak references, cleanup becomes much easier.

Why the New Approach Is Better for Your App

Switching to modern messaging patterns gives you:

  • Cleaner, more predictable architecture
  • Faster message handling
  • Zero hidden dependencies
  • Fewer memory leaks
  • Easier debugging and testing
  • Future-proofing for new .NET MAUI updates

MessagingCenter may be gone, but the alternatives are significantly better.

Final Thoughts

The removal of MessagingCenter in .NET 10 marks the end of an old era — and the beginning of a cleaner, more modern approach to app communication. Whether you migrate to WeakReferenceMessenger , traditional events, or a DI-driven pattern, your MAUI app will benefit from improved maintainability and performance.

.NET MAUI is Coming to Linux and the Browser — Powered by Avalonia The Avalonia UI team has announced a groundbreaking upda...

.NET MAUI is Coming to Linux and the Browser like Flutter .NET MAUI is Coming to Linux and the Browser like Flutter

A blog about android developement

.NET MAUI is Coming to Linux and the Browser — Powered by Avalonia

The Avalonia UI team has announced a groundbreaking update for .NET developers — .NET MAUI applications are now coming to Linux and the browser, powered by an Avalonia-based backend. This exciting development opens the door for MAUI apps to run seamlessly across desktop Linux, embedded systems, and even WebAssembly.


Expanding MAUI’s Reach

Until now, .NET MAUI primarily supported Windows, macOS, Android, and iOS. With Avalonia’s new rendering backend, developers can extend their MAUI apps to Linux desktops (Ubuntu, Fedora, Debian) and embedded devices like Raspberry Pi. Even more impressively, early builds already demonstrate MAUI applications running inside browsers via WebAssembly — without plugins or external dependencies.


Why Avalonia?

Avalonia’s cross-platform rendering engine provides a consistent UI experience across all systems. It’s known for its performance and lightweight design, which make it ideal for embedded and browser environments. On macOS, early performance tests show more than 2× improvement compared to the native Mac Catalyst backend.


Highlights from the Avalonia Team

  • MAUI apps now run on Linux and WebAssembly using Avalonia as the rendering layer.
  • Open-source backend under the MIT license (in development).
  • Improved consistency and performance across platforms.
  • Early demo shows MAUI apps running directly in browsers.
  • Support for desktop, embedded, and browser-based deployments.

What This Means for Developers

This integration means developers can finally target a broader range of platforms without rewriting their apps. Instead of relying on multiple native toolkits, MAUI developers can use Avalonia to deliver a unified experience everywhere.

For teams maintaining large cross-platform applications, this reduces platform-specific bugs, simplifies maintenance, and significantly improves deployment flexibility.


Looking Ahead

The Avalonia backend for .NET MAUI is still in its early stages, but the future looks promising. As the feature matures, MAUI could truly achieve its original goal: “write once, run everywhere.”

The full article and official demo are available on Avalonia’s blog. Read the full announcement here .


General Analysis

This move marks a major step toward unifying the .NET ecosystem. The combination of MAUI’s developer productivity and Avalonia’s rendering flexibility could redefine how cross-platform .NET apps are built and deployed. If successful, it will bring .NET applications to devices and environments that were previously unreachable — from industrial embedded systems to browser-based user interfaces.



Source: Avalonia UI Blog — “.NET MAUI is Coming to Linux and the Browser, Powered by Avalonia” (Published Nov 11 2025)

A critical deadline is approaching for .NET MAUI developers who dist...

Getting Your .NET MAUI Applications Ready for Google Play's 16 KB Memory Page Requirement Getting Your .NET MAUI Applications Ready for Google Play's 16 KB Memory Page Requirement

A blog about android developement

A critical deadline is approaching for .NET MAUI developers who distribute applications through Google Play. Beginning November 1, 2025, Google Play will mandate that all new applications and updates designed for Android 15 and higher must be compatible with 16 KB page sizes on 64-bit devices.

Understanding the 16 KB Memory Page Requirement

Android is transitioning from its traditional 4 KB memory page architecture to a larger 16 KB format. This shift is designed to enhance performance on modern devices equipped with substantial RAM. The benefits of this architectural change extend beyond system-level improvements and directly impact individual applications:

  • Faster Application Launch: Applications experience an average 3.16% reduction in launch time, with some apps seeing improvements up to 30%
  • Enhanced Energy Efficiency: Power consumption during app launch decreases by an average of 4.56%
  • Better System Responsiveness: The overall Android operating system becomes more responsive. For example, the native camera app shows 4.48% faster hot starts and 6.60% faster cold starts

Compatibility with .NET MAUI

The positive news for developers is that .NET MAUI 9 includes native support for 16 KB page sizes. To ensure your application meets Google's requirements, simply migrate your .NET MAUI (or .NET for Android) project to .NET 9. Once upgraded, your application will automatically comply with the 16 KB page size standard.

Important Note: Keep in mind that .NET MAUI 8 reached its end-of-support date on May 14, 2025, according to the official .NET MAUI support policy.

Auditing Your Project Dependencies

Compliance isn't just about your main application—every dependency in your .NET MAUI project must also support 16 KB page sizes. During the build process, the system will alert you to any non-compliant dependencies with warnings similar to:

Android 16 will require 16 KB page sizes, shared library '{library_name}' does not have a 16 KB page size. Please inform the authors of the NuGet package '{package_name}' version '{version}' which contains '{file_path}'. See https://developer.android.com/guide/practices/page-sizes for more details.

When encountering these warnings, follow this approach:

  • Upgrade the problematic dependency to a newer version with 16 KB support
  • Reach out to package maintainers if no compatible version exists
  • Consider alternative packages if the original is no longer actively maintained

For developers who want to perform additional verification, Google provides command-line tools in their documentation that can help validate compliance for your application and its dependencies.

Your Preparation Checklist

To meet the November 2025 deadline, follow these steps:

  • Migrate to .NET 9 if you're currently on an earlier version
  • Analyze all dependencies for 16 KB page size compatibility
  • Update or substitute any dependencies that don't meet the requirements
  • Thoroughly test your application in a 16 KB environment using Android emulators or developer options on physical Android devices
Critical Reminder: Don't postpone this work until the last moment. Begin your preparation immediately to ensure smooth app submissions that comply with Google Play policies and maintain uninterrupted release schedules.

Final Thoughts

While the 16 KB page size requirement introduces a new compliance obligation, it also delivers tangible performance improvements. The .NET MAUI 9 framework is already equipped to handle this requirement—your responsibility is ensuring your dependencies are equally prepared. Upgrade to .NET 9, conduct a thorough dependency audit, and validate your application in 16 KB testing environments to be ready well before the November 2025 cutoff date.

In the fast-paced world of mobile app development, efficiency and speed are paramount. For Flutter developers, a new tool is emerging that p...

DreamFlow: Revolutionizing Flutter App Development – A No-Code Solution for the Future DreamFlow: Revolutionizing Flutter App Development – A No-Code Solution for the Future

A blog about android developement

In the fast-paced world of mobile app development, efficiency and speed are paramount. For Flutter developers, a new tool is emerging that promises to significantly accelerate the initial stages of app creation: DreamFlow


This innovative no-code AI app builder is designed to generate actual cross-platform Flutter applications, offering a unique advantage for those working within the Flutter ecosystem. Facing long development cycles and costly initial prototyping? DreamFlow transforms the game for Flutter developers.

What Makes DreamFlow Stand Out?

Unlike many other no-code platforms, DreamFlow specifically focuses on Flutter, providing a dedicated solution that understands the nuances of this popular framework. This specialization means that developers can expect outputs that are genuinely Flutter-native, rather than generic code that might require extensive modifications.

Key Features:

  • Flutter-native outputs for seamless integration.
  • AI-powered app design tailored to developer prompts.
  • Cross-platform compatibility, reducing development time.

The Simple Workflow

Getting started with DreamFlow is straightforward, simplifying the app development process into a few easy steps:

  1. Create an Account: Begin by setting up your DreamFlow account.
  2. Frame Your Prompt: Describe your desired application using a clear and concise prompt, such as: “Create a weather app with a 5-day forecast, daily temperature graphs, and location-based data.” The more detailed your prompt, the better the generated outcome will be.
  3. Generate the App: With your prompt in place, DreamFlow's AI takes over, quickly generating your Flutter application.
  4. Preview and Refine: Once generated, you can preview your app to ensure it meets your vision.



A Practical Example: Event Management App

Imagine needing a tech event management and booking application. Using a prompt generated by ChatGPT, DreamFlow can conjure a polished app within minutes. This includes:

  • A clean and modern design.
  • Intuitive navigation for seamless user experience.
  • Smooth animations.
  • Functional data modules for booking and event management.

The beauty of DreamFlow lies in its ability to provide a solid foundation. If further customization is needed, the generated app can even be edited in tools like FlutterFlow.






Current Limitations to Consider

While DreamFlow offers significant advantages, it's important to acknowledge its current limitations. It's not designed to handle:

  • Deep state management.
  • Complex custom business logic.
  • Scalable architectural patterns.
  • Intricate API integration patterns.

However, many of these limitations can be mitigated by extending the functionality of the generated app using Flutter libraries and manual coding.



The Verdict: A Time-Saving Power Tool

Despite these limitations, DreamFlow proves to be an excellent asset for swiftly building base applications, creating demos, or testing new concepts. It excels at saving substantial UI development time, allowing developers to focus on the more complex, custom aspects of their projects. DreamFlow isn’t just a tool; it’s a time-saving revolution for Flutter developers. Start your journey today!

Demo



What is Android Studio Cloud? Android Studio Cloud is Google’s experimental browser-based IDE that streams a full Linux VM running Androi...

Hands-On with Android Studio Cloud: Streamlined Development in Your Browser Hands-On with Android Studio Cloud: Streamlined Development in Your Browser

A blog about android developement

What is Android Studio Cloud?

Android Studio Cloud is Google’s experimental browser-based IDE that streams a full Linux VM running Android Studio to your web browser. Key features:

Caption: The experimental Android Studio Cloud interface accessed via Firebase Studio

  • 🌐 Access Anywhere: Develop Android apps without local installations
  • 🛠️ Pre-Configured Workspaces: Preloaded with Android SDK & IDE
  • 🧪 Experimental Tech: Tests streaming/cloud development workflows
  • 🔄 Git Integration: Import projects directly from GitHub/VCS

Caption: Creating a new cloud workspace

Getting Started

  1. Visit Android Studio Cloud via Firebase Studio
  2. Click "Try Android Studio Cloud"
  3. Name your workspace and click Create
  4. Wait ~2-5 minutes for the Linux VM to initialize


Caption: Web-based Android Studio with Gemini AI integration

Key Workflows to Test

  1. Emulator Deployment:

    • Use preconfigured Pixel 8a API 35 (slow first boot – wait 10+ mins)
    • Alternative: Stream to physical devices via Firebase Device Streaming
  2. AI Development:

    • Leverage Gemini for code completion/suggestions
  3. Version Control:

    • Import projects using Get from VCS
  4. Sample Projects:

    • Explore via Import Android Code Sample

Caption: Recommended emulator configurations for better performance

Current Limitations (July 2024)

  • 🐢 Slow Emulators: Nested virtualization causes lag
  • ⌨️ Linux Key Mapping Required
  • 🔒 2FA Restrictions: Physical security keys unsupported
  • 🚫 No Local Device Deployment
  • ⚠️ Frequent "Choose password for new keyring" popups – click Cancel

Caption: Common popups to ignore during testing

Why Try It?

  • Test cutting-edge cloud development infrastructure
  • Evaluate browser-based IDE performance
  • Provide feedback to shape future Android tools

Conclusion

While not yet production-ready, Android Studio Cloud offers a fascinating glimpse into browser-first Android development. Developers interested in cloud IDEs or remote workflows should experiment with it – but keep expectations low for now.

Try it here: Android Studio Cloud Preview

Introduction .NET MAUI (Multi-platform App UI) is a modern framework that enables developers to create cross-platform applications for And...

Consuming HTTP Calls in .NET MAUI Using HttpClient Consuming HTTP Calls in .NET MAUI Using HttpClient

A blog about android developement

Introduction

.NET MAUI (Multi-platform App UI) is a modern framework that enables developers to create cross-platform applications for Android, iOS, macOS, and Windows using a single codebase. In most applications, consuming data from REST APIs is a fundamental requirement. .NET provides the HttpClient class, a powerful and versatile way to handle HTTP requests and responses.

In this article, we will demonstrate how to use HttpClient in a .NET MAUI application to perform GET, POST, PUT, and DELETE operations. We will also display the results using a simple UI, showing responses in JSON format via alerts.

Prerequisites

Before you start, ensure you have the following:

  1. Development Environment:

    • .NET 7.0 SDK installed on your machine.
    • Visual Studio 2022 with the .NET MAUI workload installed.
  2. Basic Knowledge:

    • Familiarity with C# and .NET programming.
    • Basic understanding of REST APIs.
  3. Sample API:

    • For this tutorial, we will use the placeholder API available at JSONPlaceholder.

Steps to Implement HTTP Operations in .NET MAUI

1. Create a .NET MAUI Project

Open Visual Studio and create a new .NET MAUI App project. Name it HttpClientSample.

2. Define a Model Class

Create a Post class to represent the data structure returned by the API.

public class Post
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
    public int UserId { get; set; }
}

3. Create an API Service Class

Encapsulate the logic for making HTTP requests in a reusable service class.

ApiService.cs

using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

public class ApiService
{
    private readonly HttpClient _httpClient;
    private readonly JsonSerializerOptions _jsonOptions;

    public ApiService()
    {
        _httpClient = new HttpClient
        {
            BaseAddress = new Uri("https://jsonplaceholder.typicode.com/")
        };
        _jsonOptions = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true,
            DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
            WriteIndented = true
        };
    }

    public async Task<List<Post>> GetPostsAsync()
    {
        var response = await _httpClient.GetAsync("posts");
        response.EnsureSuccessStatusCode();
        var json = await response.Content.ReadAsStringAsync();
        return JsonSerializer.Deserialize<List<Post>>(json, _jsonOptions);
    }

    public async Task<Post> CreatePostAsync(Post newPost)
    {
        var jsonContent = new StringContent(JsonSerializer.Serialize(newPost, _jsonOptions), Encoding.UTF8, "application/json");
        var response = await _httpClient.PostAsync("posts", jsonContent);
        response.EnsureSuccessStatusCode();
        var json = await response.Content.ReadAsStringAsync();
        return JsonSerializer.Deserialize<Post>(json, _jsonOptions);
    }

    public async Task<Post> UpdatePostAsync(int id, Post updatedPost)
    {
        var jsonContent = new StringContent(JsonSerializer.Serialize(updatedPost, _jsonOptions), Encoding.UTF8, "application/json");
        var response = await _httpClient.PutAsync($"posts/{id}", jsonContent);
        response.EnsureSuccessStatusCode();
        var json = await response.Content.ReadAsStringAsync();
        return JsonSerializer.Deserialize<Post>(json, _jsonOptions);
    }

    public async Task<bool> DeletePostAsync(int id)
    {
        var response = await _httpClient.DeleteAsync($"posts/{id}");
        return response.IsSuccessStatusCode;
    }
}

4. Build the User Interface

Design the UI in MainPage.xaml with buttons for each HTTP operation.

MainPage.xaml

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="HttpClientSample.MainPage"
             Title="HTTP Client Demo">

    <StackLayout Padding="20" Spacing="15">
        <Label Text="HTTP Operations"
               FontSize="24"
               HorizontalOptions="Center" />

        <Button Text="GET Data"
                Clicked="OnGetClicked" />

        <Button Text="POST Data"
                Clicked="OnPostClicked" />

        <Button Text="PUT Data"
                Clicked="OnPutClicked" />

        <Button Text="DELETE Data"
                Clicked="OnDeleteClicked" />
    </StackLayout>
</ContentPage>

5. Implement Button Event Handlers

Add event handlers in the MainPage.xaml.cs to invoke the respective methods from the ApiService.

MainPage.xaml.cs

using System.Text.Json;

public partial class MainPage : ContentPage
{
    private readonly ApiService _apiService;

    public MainPage()
    {
        InitializeComponent();
        _apiService = new ApiService();
    }

    private async void OnGetClicked(object sender, EventArgs e)
    {
        try
        {
            var posts = await _apiService.GetPostsAsync();
            string json = JsonSerializer.Serialize(posts, new JsonSerializerOptions { WriteIndented = true });
            await DisplayAlert("GET Response", json, "OK");
        }
        catch (Exception ex)
        {
            await DisplayAlert("Error", ex.Message, "OK");
        }
    }

    private async void OnPostClicked(object sender, EventArgs e)
    {
        try
        {
            var newPost = new Post { Title = "New Post", Body = "This is a new post body", UserId = 1 };
            var createdPost = await _apiService.CreatePostAsync(newPost);
            string json = JsonSerializer.Serialize(createdPost, new JsonSerializerOptions { WriteIndented = true });
            await DisplayAlert("POST Response", json, "OK");
        }
        catch (Exception ex)
        {
            await DisplayAlert("Error", ex.Message, "OK");
        }
    }

    private async void OnPutClicked(object sender, EventArgs e)
    {
        try
        {
            var updatedPost = new Post { Title = "Updated Title", Body = "Updated Body", UserId = 1 };
            var updatedData = await _apiService.UpdatePostAsync(1, updatedPost);
            string json = JsonSerializer.Serialize(updatedData, new JsonSerializerOptions { WriteIndented = true });
            await DisplayAlert("PUT Response", json, "OK");
        }
        catch (Exception ex)
        {
            await DisplayAlert("Error", ex.Message, "OK");
        }
    }

    private async void OnDeleteClicked(object sender, EventArgs e)
    {
        try
        {
            var isDeleted = await _apiService.DeletePostAsync(1);
            string message = isDeleted ? "Post deleted successfully." : "Failed to delete the post.";
            await DisplayAlert("DELETE Response", message, "OK");
        }
        catch (Exception ex)
        {
            await DisplayAlert("Error", ex.Message, "OK");
        }
    }
}

Conclusion

In this article, we explored how to use HttpClient in a .NET MAUI application to perform CRUD operations on a REST API. We created a reusable service class for HTTP requests, designed a simple UI, and displayed results in JSON format using alerts. This implementation is a starting point for integrating REST APIs into your .NET MAUI applications.

Feel free to extend this example by adding features such as error handling, logging, and more advanced UI elements. Happy coding!

Android 15: Revolutionizing Mobile Experiences Android 15, codenamed Vanilla Ice Cream , was a significant leap forward in mobile OS innov...

Exploring Android 15 and the First Developer Preview of Android 16 Exploring Android 15 and the First Developer Preview of Android 16

A blog about android developement


Android 15: Revolutionizing Mobile Experiences

Android 15, codenamed Vanilla Ice Cream, was a significant leap forward in mobile OS innovation. Released earlier this year, it focused on delivering enhanced security, communication, and usability features for both everyday users and enterprise environments.

Key Features in Android 15:

  1. Private Space:
    Android 15 introduced Private Space, a virtual sandbox within the OS. This feature allows users to store sensitive files, apps, and data separately from the main environment, ensuring confidentiality. It's especially useful for professionals managing personal and work accounts on the same device.

  2. Enhanced Satellite Messaging:
    Taking connectivity to the next level, Android 15 supports satellite communication. While initially limited to premium devices, this feature ensures users remain connected even in remote or offline areas, marking a step forward in global communication capabilities.

  3. Partial Screen Recording:
    This innovative tool lets users record specific sections of their screen instead of the entire display. Ideal for sharing specific app workflows or sensitive content without revealing everything on-screen, it became a favorite among tech influencers and educators.

  4. Advanced Security Measures:
    Android 15 strengthened device security by including monthly security patches, encrypted backup improvements, and app activity transparency, ensuring user safety against modern digital threats.

  5. Performance Optimizations:
    With improved energy efficiency and reduced background process consumption, Android 15 extended battery life and boosted performance, especially on mid-range devices.


Android 16 Developer Preview: A Glimpse into the Future

Android 16 aims to build on Android 15’s solid foundation with groundbreaking improvements and cutting-edge technology. The first developer preview teases several enhancements that cater to developers and end-users alike.

What’s New in Android 16?

  1. AI-Enhanced Personalization:
    Android 16 integrates artificial intelligence deeply into the OS to adapt to individual usage patterns. From predictive app suggestions to dynamic interface adjustments, AI creates a more intuitive user experience.

  2. Cross-Device Harmony:
    Google is focusing on seamless cross-device operations, making it easier to transition between Android-powered smartphones, tablets, and wearable devices. Developers can leverage new APIs to build apps that offer consistent experiences across device ecosystems.

  3. Sustainability and Efficiency:
    The latest version takes sustainability seriously by introducing features that optimize energy consumption. Enhanced battery management tools and smarter resource allocation extend device life and reduce carbon footprints.

  4. Advanced Accessibility Features:
    Accessibility tools are getting a major upgrade, ensuring inclusivity for all users. Enhanced voice control, real-time transcription, and assistive gesture navigation are some of the highlights aimed at supporting diverse user needs.

  5. Developer-Centric Updates:
    Android 16 offers new tools to developers, including improvements to Jetpack Compose for creating responsive UI designs, updated debugging tools, and extended support for foldable and large-screen devices.

Why Developers Should Explore the Preview:

The first developer preview is a goldmine for app creators, allowing them to adapt their apps early to leverage Android 16's new capabilities. From API testing to performance benchmarking, this is a pivotal moment for the developer community to innovate alongside the OS.


Conclusion

Android 15 and Android 16 demonstrate Google’s unwavering commitment to enhancing the mobile experience. While Android 15 brought essential upgrades in security, connectivity, and usability, Android 16 pushes boundaries with AI-driven innovation and sustainability. Developers and users can look forward to a transformative era in mobile technology as these advancements become mainstream.

For developers, now is the time to dive into the Android 16 Developer Preview and explore its offerings to craft the next generation of apps that define the Android experience.


References

Android 15 Features

Android 16 Features

Image Generated using Chat GPT & DALL-E