Chapter 1. Getting to Know Gradio.NET
You finish writing a C# method, and the real trouble is only just beginning: how do you get other people to use it.
This is a delivery problem. A method that runs on its own does not mean other people can actually use it. This chapter does not go into implementation; it first makes clear what problem Gradio.NET simplifies and which scenarios it suits, then sets out what this book plans to help you build.
1.1 From C# Handler Functions to an Interactive Web UI
Suppose you have written a method. It takes a piece of text, removes extra whitespace, and returns the cleaned result. The logic is not complicated, under thirty lines.
To let a colleague use it, there are three paths you can take.
The first is to send over the source code and let the other person compile it themselves. This path only holds for colleagues who have the .NET SDK installed, and they also have to know how to pass the arguments in. In most cases, they would rather just make the change by hand.
The second is to make it a console app. That is already much better than sending source code; a double-click runs it. But it is still awkward to use. Arguments have to be given in order, and if you get one wrong all you can do is read the error; there is no validation of the input, and stuffing a whole piece of text with line breaks into a single argument takes some effort; every time you change the input you have to run it again, and the previous result disappears along with the window; when there is more than one input, you also have to remember which argument corresponds to which item.
The third is to make it a web page. An input box, a button, a result area — anyone can use them, and you can change things and look again as often as you like. The cost is the amount of work. You have to write a backend interface and wrap the method as an HTTP endpoint; write a frontend page that collects the input and sends it off; handle request state and show a loading indicator while waiting; and then handle error cases. A small tool that could have been usable in an afternoon often turns into a week-long project because of this, and in the end it may still not be nicer to use than the console version.
Gradio.NET handles exactly the repetitive work on that third path.
What Gradio.NET does is not complicated. You write a C# method that takes input and returns a result, and it turns that method into a web page. Your code declares the input controls, buttons, and result area on the page, and your method decides what happens after a click; the framework takes care of the request, serialization, echoing back, and loading state in between.
Gradio.NET does not do the fine-grained interactions and animations of a frontend framework, nor the visual drag-and-drop building of a low-code platform. The UI is still written in code, just C# rather than HTML and JavaScript. What you write is still a method, only now with a clickable UI wrapped around it.
This positioning has one consequence. The UIs Gradio.NET produces all look more or less the same. It is good at putting a capability out there for people to use, and not good at turning the UI into a product differentiator. If the latter is your goal, this tool will feel constraining at every turn; if the former is your goal, it will save you a great deal of time.
1.2 Two Ways to Deliver the Same Processing Logic
This chapter’s sample is a text cleanup tool. There are only three rules. Remove the whitespace at the start and end of each line, coalesce consecutive whitespace within a line into a single space, and drop blank lines. After cleanup, count how many lines there are and how many characters.
These three rules live in a class library that does not reference Gradio.NET. Both the console version and the web version reference it, and neither writes its own copy. This is the premise for all the comparisons that follow. If the logic differed between the two sides, the comparison would be between two programs rather than between two ways of delivering one.
Figure 1-1 Two delivery forms of the same processing logic
Look at the console version first. After the build, pass the text in as an argument.
dotnet build samples-en\chapter01\console\Console.csproj --configuration Release
dotnet run --project samples-en\chapter01\console\Console.csproj --configuration Release --no-build -- " First line has extra spaces "
The output is as follows.
First line has extra spaces
-- 1 lines, 23 characters
The result is correct. But this is what using it looks like. Open a terminal, go to the directory, type the command, look at the result; to change one character, press the up arrow to recall the command, move the cursor inside the quotes to edit, then press Enter. When the text gets long, the content inside the quotes starts to become hard to read; if the text contains line breaks, it is worse, because the command line treats a line break as the end of the command.
Now look at the web version. Launch this chapter’s sample and open 127.0.0.1:7860 in a browser.
Figure 1-2 The initial UI of the sample
Paste text on the left, get the result on the right. Change one character, click again, and the result updates immediately.
Figure 1-3 After pasting a piece of text with extra whitespace and clicking “Clean up”
With the same piece of text, the differences between the two delivery forms come down to five places.
How the input is given. The console makes you remember argument order and quotes; the web version is just pasting text into a box. This one looks like a mere matter of habit, but it has a large practical effect. Spaces and line breaks inside quotes are hard to make out by eye, whereas text pasted into an input box is preserved exactly as it is — what you see is what you get.
Where the result goes. The console result is squeezed into the same window as the output of the previous command, and you have to scroll down to find it; the web result stays fixed in the area on the right, overwritten on each change, so it never piles up. The longer the task runs, the more obvious this difference becomes.
What you see when something fails. The console prints an exception stack trace to the terminal, useful to the person writing the code and useless to the person using the tool; the web version at least does not make users think they broke the terminal.
The cost of repeating an operation. The console makes you type the command again; the web version only needs one more click. If you do something twenty times a day, that difference is the difference between twenty typed commands and twenty clicks.
Who can use it. Basically only the person who wrote the code will use the console version; anyone can use the web version. This one is often underestimated. If only the author can use a tool, it saves the author’s time; if others can use it, it saves the team’s time.
What the two sides compute is exactly the same, because the processing logic is one and the same code. The difference lies in where the input comes from, where the result goes, and how much it costs to do it once more.
The web version has a cost too. It adds a launch step. A console app runs on a double-click; the web version has to start the application first and then open a browser.
So the two delivery forms are not a case of the new replacing the old. For one-off, personal use with simple input, the console is less trouble; when others need to use it, when you need to adjust repeatedly, and when the input is a long piece of text or a file, the web version fits better. This chapter spends so much space on this comparison because you will meet the same question in every later chapter. In what form should this capability be handed to other people?
When you cannot work out how a feature should be designed, start by asking where its input comes from and who sees the result. Once those two questions are clear, what remains is mostly which components to choose and how to bind the events.
This chapter does not explain the code in the sample that declares the UI. Chapter 2 starts from the smallest application and goes through it line by line.
1.3 Where Gradio.NET Fits and Its Boundaries
To decide whether to use this tool, look at whether its value lies in “what the method does” or in “how the page moves”. The former suits it; the latter does not.
By that standard, the following kinds of scenarios are a good fit.
Turn the C# logic you already have into a UI you can operate. You may already have a pile of methods that process text, parse files, or call APIs, sitting in a class library or a console app that only you use. Wrapping a UI around them costs very little, and the payoff is that others can use them too.
Small personal tools on your local machine. The cleanup, checking, and conversion you repeat every day, turned into something finished with a few clicks on a page. Tools like this need no user system, no deployment to a server, and do not even need to stay open — you close them when done. This book’s main application belongs to this category.
Internal data checks and demos. Throw in a batch of data, compare the difference before and after processing, or lay out the results of an algorithm under several sets of parameters side by side. Gradio.NET puts these UIs together quickly, and changes to them are quick too.
Teaching and experimentation. If you want students or colleagues to understand what a method does, letting them change the input and see the output themselves is far more effective than reading the code.
The other way around, the following kinds of scenarios are not a good fit.
A product UI offered to the outside world. Multiple users, permissions, state isolation, frontend interaction details — these are not its strengths. It can do them, but you will find yourself working around it the whole time, and what you end up with neither looks like a product nor enjoys the framework’s convenience.
Cases where the UI itself is the selling point. Marketing pages, showcase pages that need delicate motion effects, and pages with a design spec demanding pixel-perfect reproduction are better done with a frontend framework.
Large applications that need complex frontend state management. Dozens of interdependent interaction states, pieced together with events and session state, quickly get out of control.
This book sets three explicit limits on its scope.
First, it targets personal use on your local machine only. All the samples run on your own machine, listening on the loopback address. There is no promise of sharing with several people on an intranet, no promise of public deployment, and nothing about product-grade concerns such as multi-tenancy or identity systems. Chapter 20 covers authentication, but that is “adding a door to a local app”, not “building a user system”.
Second, it is verified only on Windows. The samples, commands, and main flows were all actually run under Windows and .NET 10. The library itself is cross-platform, but the book will not state as a conclusion anything it has not verified on Linux or in a container.
Third, it covers only the public API and observable behavior. It does not dissect the library’s internal implementation, and does not treat implementation details as promises you can rely on. Every behavioral description can be reproduced with a sample; implementation details change, behavior does not change casually.
1.4 Getting to Know the Multi-Module Workbench That Runs Through the Book
This book is not a set of unrelated examples. From this chapter to the last, it builds the same thing. A personal workbench on your local machine, gathering the repetitive text and table processing of everyday use into one UI.
It has real repetitive work. Cleaning up a piece of text copied from somewhere else, checking an exported table, running a few files through the same set of rules. These things happen every week; once or twice does not matter, but a hundred times calls for a tool.
It needs enough different capabilities. Import, rules, preview, processing, export, save — each piece needs different components and different ways of interacting, which happens to put Gradio.NET’s component families, events, state, queues, and streaming output to use. A toy example could not cover all of this.
Its boundaries are clear. Personal, on the local machine, single-user, no service, with a manageable scale. Once the scope is clear, there is a basis for what each chapter adds and what it does not.
How the modules are divided matters too. Divide by “what the input is” and “how long one operation takes”, not by feature names. Whether the input is a piece of text, a choice, a table, or a few files decides which kind of component to use; whether the operation finishes in an instant or takes tens of seconds decides whether you need a queue, whether you need progress, and whether it can be cancelled. Divided along these lines, the boundaries between modules come out fairly natural, and when the mechanisms are explained later they will not feel forced.
Its final shape is shown in Figure 1-4.
Figure 1-4 The composition of the multi-module workbench and the chapters each part belongs to
This figure has three parts. At the top are the UI modules, the things you can see and click on the page, added gradually from Chapter 1 to Chapter 13. In the middle are the runtime mechanisms; they have no UI of their own, but they decide how modules remember state, how they queue, how the process is shown, and when it can be stopped — covered in Chapters 14 to 17. At the bottom are delivery-related capabilities that turn the workbench into a finished product other code can call — covered in Chapters 18 to 22.
Figure 1-4 is the goal, not the current state. All this chapter completes is the one piece in the top-left corner, text cleanup. That is also the only thing you see in the sample. Each later chapter adds one piece, and only at the end does the figure come together.
This arrangement has one advantage. In every chapter you see “what was added”, not “a different example”. The workbench is always there, just growing more complete.
One more convention should be stated up front. Each chapter’s sample is a snapshot “as of this chapter”. It contains the modules covered earlier and nothing that only comes up later. So when you get the Chapter 9 material, what you see is a workbench that runs and already has several modules in it, not an empty shell that only demonstrates a table. Reading this way, the code will not contain patterns you have not learned yet.
1.5 The Book’s Capability Map and Reading Paths
The book has 22 chapters, divided into five parts.
Part I — Building an Application Model, four chapters. Starting from the smallest application, you work out how a method becomes a UI, how values pass between components and handler functions, and how the UI is organized with containers. After these four chapters, you can write an application with the right structure.
Part II — Interface Building Blocks, nine chapters. Event binding first, then the various components: text and numeric inputs, selection, display, tables, charts and galleries, media, files, chat. This part is the body of the book and takes up forty percent of it, because components are the most substantial part of this library. Each chapter covers one family of components, spelling out what each is suited to, which parameters matter, and what types are passed to handler functions and returned from them.
Part III — Interaction Mechanisms, four chapters. State and sessions, queues and concurrency, streaming output and progress, cancellation and errors. These four chapters introduce no new components; they cover the mechanisms that make the UI “presentable” — why data is still there after a refresh, why clicking twice does not count twice, and how long tasks can show progress and be stopped partway.
Part IV — Shaping the Interface, three chapters. Splitting a single page into multiple pages, changing the theme, adding authentication. These three chapters are about the look and the boundaries of the workbench as a finished product.
Part V — Integration and Delivery, two chapters. Hooking into ASP.NET Core, and exposing the capabilities as an interface. After these two chapters, the capabilities on the workbench are no longer usable only through the page.
There are three ways to read it; choose according to your needs.
Read in order. From Chapter 1 to Chapter 22, each chapter’s explanation continues from the previous one; this is the least effort to read and the best way to feel the workbench being filled in bit by bit. If this is your first contact with the library, this is the recommended way.
Jump around as needed. Each chapter’s sample is independent: grab a chapter’s folder and you can run that chapter, with no need to finish the earlier ones first. If you only want to solve one specific problem, such as making a UI with a table, you can turn straight to Chapter 9. The price is that the chapter will reference concepts covered earlier, and you have to accept the “not explained again here” style.
Use it as a reference. From Chapter 5 onward, every chapter is organized by capability, and the chapters on component families are especially good for lookup. If you cannot remember what a parameter does, turning to the relevant section is faster than rereading the whole chapter.
Whichever you choose, these three reading conventions should be stated up front.
A concept is explained in detail only in the chapter where it is first introduced. When it comes up again later, the chapter number is given and it is not explained a second time. So when you see a type that has not been explained, flipping back is usually faster than hunting in place.
Key methods are given a full implementation when they first appear, especially the handler functions that carry this chapter’s state transitions. Methods shown in an earlier chapter and unchanged here are not pasted again; when they change, the full implementation after the change is pasted, along with a note on what changed.
Code snippets come from samples that actually run, trimmed to make a point clear, but the trimmed code can still be dropped into that chapter’s project and compiled. For illustrative code that cannot compile, the main text says explicitly that it is illustrative.
1.6 Chapter Summary
Gradio.NET solves the problem of “the method is written, how do you get people to use it”. It does not change your processing logic; it only changes where the input comes from and where the result goes.
To decide whether to use it, look at whether the tool’s value lies in the method itself or in the page’s presentation. Small personal tools on your local machine, internal checks and demos, and wrapping a UI around existing logic are what it is good at; for external products and cases where the UI is the selling point, it is not a fit.
The whole book revolves around one multi-module workbench, advancing by capability, with each chapter adding one piece. The first piece built in this chapter is text cleanup, and the twenty-some chapters that follow will fill it out into the shape shown in Figure 1-4.
The next chapter starts from the smallest application. One method, two inputs, one output, a few lines of code, and it runs.