CODEMagazine 2024 JulyAugust
CODEMagazine 2024 JulyAugust
JUL
AUG
2024
codemag.com - THE LEADING INDEPENDENT DEVELOPER MAGAZINE - US $ 8.95 Can $ 11.95
Realize 2D Interfaces
with Augmented
Reality Tools
We will send an expert to your office to meet with you. You will receive:
1. An overview presentation of the current state of Artificial Intelligence.
2. How to use AI in your business while ensuring privacy of your and your clients’ information.
3. A sample application built on your own HR documents – allowing your employees to query
those documents in English and cutting down the number of questions that you
and your HR group have to answer.
4. A roadmap for future use of AI catered to what you do.
CONTACT US TODAY FOR A FREE CONSULTATION AND DETAILS ABOUT OUR SERVICES.
codemag.com/ai-services
832-717-4445 ext. 9 • [email protected]
TABLE OF CONTENTS
Features
7 CODE: 15 Years Ago 58 S tore Application Performance
Markus continues his reflection on what the company, the magazine,
and the industry have been up to for the last decade and a half.
Metadata in a Database Using
Markus Egger AOP in ASP.NET Core
Joydip explores programming paradigms (object-oriented,
14 VS Code Tips procedural, and aspect-oriented programming) and looks at
how AOP (aspect-oriented programming) can help you optimize
Sahil looks at how Visual Studio Code, Microsoft’s free open-source
performance and store performance metadata in a database.
workhorse, lets you work on any platform, any operating system, and
Joydip Kanjilal
nearly any language.
Sahil Malik
74 Code Compilers
US subscriptions are US $29.99 for one year. Subscriptions outside the US pay
$50.99 USD. Payments should be made in US dollars drawn on a US bank. American
Express, MasterCard, Visa, and Discover credit cards are accepted. Back issues are
available. For subscription information, send e-mail to [email protected]
or contact Customer Service at 832-717-4445 ext. 9.
Subscribe online at www.codemag.com
CODE Component Developer Magazine (ISSN # 1547-5166) is published bimonthly
by EPS Software Corporation, 6605 Cypresswood Drive, Suite 425, Spring, TX
77379 U.S.A. POSTMASTER: Send address changes to CODE Component Developer
Magazine, 6605 Cypresswood Drive, Suite 425, Spring, TX 77379 U.S.A.
Adam Tepedelen’s book “Mud Ride: A Messy Trip I started building this process using simple es, disharmonies, and harmonic resolutions. We
Through the Grunge Explosion,” is a statement brute-force code. As a test of Occam’s Razor, make the music of our lives choosing what to
so powerful that it refuses to leave my head- would the simplest code work? I set about iter- play and how to play it. And occasionally, you
space. The simplicity that we may be only a ating through the 350 million records using LINQ need to change a fret or so to be more harmo-
minor change away from harmony is profound. to query the range tables that were loaded into nious.
memory. I immediately determined that this was
Early in my consulting career, I began teaching not a workable solution. My back-of-the-enve- NOTE: This editorial required a fret change or
developers for a company called ADTC. Before lope calculations figured it would take multiple two. I used my analog (walking) technique to
an instructor was allowed to teach their first hours (and maybe a day or more) to finish. figure out what fret to change to next.
public class, they had to shadow another in-
structor. As luck would have it, my instructor Time for a fret change. I looked for libraries or
was a fellow named David Anderson. David was tools that could help make this process work-
an amazing instructor (and good friend) and able. That process yielded no positive results. Rod Paddock
I borrowed (some may say stole, LOL) many
of his teaching techniques. One technique I Time for a fret change. I went into the analog
learned from David I’m still using some 30 years world (I went for a walk), thought about this
later. I learned this lesson from a question a problem, and the fret changes that I needed
student asked and how David responded. came into my head. I’d go back to the good
old algorithms I learned in college. Hmmmm….
David didn’t understand the question, so he Would a binary search work? Let’s change the
asked the student for assistance with this ques- tune…
tion: “Can you say that another way?” The stu-
dent reworded their question and, with that I went to work re-learning how to implement
fret change, student and instructor achieved a binary search algorithm using ranged tables.
harmony. With some Google-Fu and an accidental assist
from Microsoft’s Edge’s AI (I’ll talk about this
As an exercise, how many fret changes can you in a future column), I came up with the seeds
pull from that last scenario? of a workable algorithm to process this data
in fast fashion. You know what? It worked! I
• Fret Change One: Begin a teaching career was able to process the IPV4 addresses with a
• Fret Change Two: Meet David Anderson usable speed.
• Fret Change Three: Learn to ask students
“Can you ask that another way?” Then I went to classify the IPV6 addresses, and
soon realized I’d need yet another fret change.
This one experience yielded three significant This fret change was required because of the
fret changes that resonate with me to this very mathematics related to IPV6 address size. The
day. I’ll bet you didn’t think this was going to original code was written in the .NET Framework
be an SAT practice exam, but here we are. You’re (4.xx). which, I soon learned, has a limitation
welcome. <g> on the bit size of numbers it supports. IPV6 ad-
dresses are 128bit, double the 64 that the 4.xx
Programmers will understand the concept of framework supports. I changed the instrument
fret changes in their daily work. The art of pro- completely by putting the code into the newest
gramming is a constant state of fret changes version of .NET Core, which has native support
trying to achieve the harmony of working code. for 128bit numbers. My project had achieved
Earlier this year, I was tasked with geo-coding harmonic balance.
over 350,000,000 million IP4 and six addresses.
This is a huge challenge with the sheer volume These are just the highlights of the major fret
of records to process. The process is this: Take changes and chord progressions that the code
an IP address, turn it into its numerical repre- went through.
sentation, then look up that value in a range
table. The IPV4 and IPV6 have around 250,000 To conclude with a cheezie music metaphor, our
and 500,000 ranges, respectively. lives are a series of progressions, chord chang-
6 Editorial codemag.com
ONLINE QUICK ID 2408021
The “Cloud” was in its infancy (but already there). .NET Core better use of dedicated graphics hardware. As we came to
wasn’t quite a thing yet, but as we started developing Cloud find out, users didn’t want to jump through the hoops re-
apps, the early building blocks of Microsoft’s re-imagined quired to have a secure operating system. They just didn’t
.NET ecosystem were being put into place. Web development want anything bad to happen to them, while still happily
was already mainstream. Mobile development wasn’t quite running on Administrator accounts, with their machine’s
there yet but it was starting. Except for Artificial Intelli- defenses taking a back seat. As a result, Windows Vista
gence, a lot of the things we’re doing as developers today was one of the least liked Windows operating systems up
were already in place (although in different forms). But be- to that point, probably only topped by Windows 8, half a
fore I get ahead of myself, let’s survey the overall landscape decade later.
of software development and the technologies we used at Markus Egger
the time. In hindsight, Windows Vista wasn’t all bad. Yes, there [email protected]
were numerous valid points of criticism (hardware re-
quirements were high, driver compatibility was low, and Markus, the dynamic
Operating Systems all kinds of security measures made it less pleasant to founder of CODE Group and
For developers, the platform the code runs on is where it use than prior versions of Windows), but there were also CODE Magazine’s publisher,
is a celebrated Microsoft
all starts, so let’s take a look at the operating systems in a lot of good features. Utilization of GPUs is considered
RD (Regional Director) and
use 15 years ago. In the last issue’s article that looked a given in any modern operating system, but it was a
multi-award-winning MVP
20 years back, I talked about Windows XP. Surprisingly, revolutionary step in Vista. Previously, graphics hardware
(Most Valuable Profession-
Windows XP was still a very important platform in 2008. was almost exclusively used by games, which used DirectX al). A prolific coder, he’s
Admittedly, Windows XP was a very good operating system to generate high-performance output, and the “normal” influenced and advised top
for its time, but it also had serious shortcomings when Windows GUI was rendered in software through GDI (the Fortune 500 companies
it came to security. This was a problem Windows Vista Graphics Device Interface). This not only caused perfor- and has been a Microsoft
attempted to fix as one of its key themes, another being mance problems, but it also created an odd bifurcation contractor, including on
the Visual Studio team.
Globally recognized as
a speaker and author,
Markus’s expertise spans
Artificial Intelligence (AI),
.NET, client-side web, and
cloud development, focus-
ing on user interfaces,
productivity, and maintain-
able systems. Away from
work, he’s an enthusiastic
windsurfer, scuba diver,
ice hockey player, golfer,
and globetrotter, who
loves gaming on PC or
Xbox during rainy days.
Figure 1: Windows Vista used the GPU to render the user interface and thus gained features such as 3D projection and
transparency at high performance.
Overall, the world had changed a bit, right around 2008 Then again, Apple wasn’t the only player in that mar-
or so, in that it wasn’t just a Windows world anymore. ket. Previously, Microsoft had made a really good mobile
Apple had, by then, made considerable inroads and es- platform, going back to Windows CE and Microsoft Smart-
tablished Mac OS X Leopard as a serious contender and Phone. Steve Balmer (at the time, CEO of Microsoft) had
a hip client operating system. It came with a somewhat this belief that only phones with a physical keyboard
modernized user interface, better performance, and many had any chance of being successful in commercial sce-
improvements to its core features, such as Finder. It was narios. Not his finest moment, and what condemned Mi-
a genuinely good operating system on its way into the crosoft to a role where most younger developers today
mainstream, after previously serving more of a niche-ex- can’t even conceive of a world where Microsoft was a
istence. This was in no small part due to the “Hello, I am leader in Mobile tech. (Not to mention Microsoft’s once
a Mac, and I am a PC” commercials (Figure 2) that ran awesome Tablet PC initiative, which failed to claim the
from 2006 to 2009 and were, arguably, one of the most market that was—years later in 2010—claimed by Ap-
effective commercials ever run. Microsoft had little to of- ple’s iPad).
fer in response.
Then again, it wasn’t just Steve Balmer who made that
mistake. Research in Motion (RIM) was still a big player
in the mobile market with their Blackberry devices. And
just like Balmer, RIM bet on a physical keyboard on the
device. A bet that paid off for a long time, but that
time had just about run out. RIM didn’t have much to
put up against Apple’s new offerings. That, as well as
some other leadership mistakes, sunk RIM’s boat. (For
an interesting topic that is beyond the scope of this
article, and for those interested in the “make my coun-
try great again” line of politics, ask your favorite AI to
recap RIM’s adventures in building factories in Tierra del
Fuego as part of Argentina’s attempts to protect their
local markets.)
the Phoenix, The Hangover, Avatar, Up, and J.J. Abram’s (my personal favorite—boy, did I waste hours on this
reboot of Star Trek. Yup, it’s already been 15 years! Some game!), Borderlands, Metal Gear Solid 4, Halo 3, Gears of
of these are still on my “to be watched soon” list that I War 2, Forza Motorsport 3 (Figure 7), Leage of Legends,
haven’t quite gotten to yet. and Minecraft.
Watching movies and TV series was about to be com- Meanwhile, World of Warcraft was still going strong, and
pletely uprooted, even though we didn’t yet know it then. social gaming had reached a whole new level with Xbox
Netflix moved from a DVD-based video rental company to Live and other online services. Valve had, at that point,
streaming online. In 2008, they launched an auxiliary a well-established a digital sales channel with its Steam
service called “Watch Now”, which seemed super-cool, service, and they still maintain a dominant position to-
but bandwidth limitations caused many to doubt that it day.
would really work well. Today, “Watch Now” is just known
as “Netflix” and most of us don’t even remember that You’ll have to excuse me now. I have to go and re-install
Netflix used to send you DVDs in the mail not all that long some of these classics!
ago. They were the early leader in the streaming market,
and they’re still the leader today. There have been times Markus Egger
when more than half of the internet traffic was due to
people watching Netflix content.
CODE Staffing is a high-tech, career develop- and a cool workplace culture with unlimited
ment, and - for the lack of a better term - upward career development opportunities.
“staffing company,” that provides a modern
workplace with the number one goal being the Many companies think they cannot provide a work
development of talent and careers. CODE Staff- environment that rivals the “cool Silicon Valley
ing was started to disrupt the traditional staff- startups,” and many employees think they won’t
ing industry. We provide an environment that be able to find such a workplace outside “The Val-
attracts top talent. We offer unrivaled benefits ley.” We have changed that equation!
12 Title article
Career Development and Staffing reinvented! codemag.com
CODE STAFFING
VS Code Tips
I'm a huge fan of VS Code, and I suspect I'm not the only one. We’ve emerged from a world of very heavy IDEs (Integrated
Development Environments). Many of them are still around. They’re specialized IDEs that do some things very well, and a very
popular one is Visual Studio. Visual Studio has been around for quite some time. When Microsoft entered the IDE game around C++
and there were things like Microsoft Foundation Classes quick debugging, etc. It’s a really flexible application
(MFC), that’s when Visual Studio started taking off. Be- with many uses.
fore that, we had IDEs built into DOS. They would take
over your entire screen and they were text-based. IDEs
such as Turbo C++, or Turbo, by a company called Bor- VS Code Extensions
land, were the rage. Visual Studio has gone through some The first tip I have for you is that VS Code, when down-
twists and turns as well. We’ve had specialized IDEs, such loaded, is bare bones. That’s a good thing. When I’m writ-
as Visual Interdev for web-based scenarios or FrontPage ing code as a Python developer, I have zero use for Node.
Express for lightweight web page editing. There was a js-related paraphernalia loaded in memory bogging my
Sahil Malik time when a VB programmer had a different IDE than a computer down. There are some common things that are
www.winsmarts.com C++ programmer. applicable to every language, such as Git support, that are
@sahilmalik built right inside of VS Code. You can go far beyond that by
It wasn't until we had VS Code that we had an IDE that customizing VS Code further. VS Code is extremely custom-
Sahil Malik is a Microsoft
works with nearly every language, every platform, and yet izable. You can grab extensions to improve and customize
MVP, INETA speaker,
is fast, efficient, and super customizable. It runs on Mac, your dev experience from https://marketplace.visualstu-
a .NET author, consultant,
Linux, Windows—it even runs in a browser. It works on dio.com/search?target=VSCode or right within VS Code by
and trainer.
Python node.js, .NET, and anything else you can imagine. looking for the extensions button that’s shown in Figure 1.
Sahil loves interacting I'll go so far as saying that I'm hard-pressed to think of
with fellow geeks in real another application as good as VS Code. VS Code is built The process of writing your own extensions is also well
time. His talks and train- on Electron and a lot of people like to complain about documented, but 99 out of 100 times, I can find some
ings are full of humor and Electron being heavy, yet we all use VS Code. That alone really well-written extensions for my needs in the mar-
practical nuggets. is a testament to how well VS Code is built. ketplace.
His areas of expertise are In this article, I'm going to talk about some of my favorite
cross-platform Mobile app tips and tricks about my favorite IDE, VS Code. Although There Are Two VS Codes
development, Microsoft I’m writing this on a Mac, many of these concepts will Love it or hate it, in this internet-connected world, things
anything, and security port to Windows, so you may have to replace COMMAND change all the time. The application VS Code changes
and identity.
key, WIN key, etc. quite often. It has a vibrant community and dedicated
product managers who constantly look for ways to make
VS Code better. As a result, roughly once a month, VS
What Is VS Code? Code updates itself. Something I’ve found very valuable is
VS Code is a free application, built on open source by to keep up with the changes at https://code.visualstudio.
Microsoft, that you can download from https://code. com/updates/. You know that life gets busy, and the app
visualstudio.com. It’s designed to be a code editor, but updates and project deadlines mean that we can’t visit a
honestly, it’s so much more than that. It’s definitely de- website to keep up with these changes.
veloper-centric. I’ve personally used VS Code with .NET,
client- and server-side JavaScript projects, Python, and Right inside of VS Code, press COMMAND_P press the
GoLang. I wouldn’t trade it for anything else. Okay per- “greater than” sign (>) and type “Release notes”, which
haps .NET and Visual Studio are a good combination, but will show you the release notes. Ensure that you check
Visual Studio non-community edition can get expensive. the checkbox for “Show release notes after an update”
Speaking of developer-centric, although the canonical and get in the habit of periodically reading these release
use of VS Code is to fire up a code development project in notes for fun ’n’ learnin’. In fact, you can click the “gear”
your language of choice, I find myself using VS Code for icon, as shown in Figure 2, to create a shortcut for view-
Figure 1: Extensions taking quick notes as an alternative to a tabbed notepad, ing release notes. I really appreciate how the VS Code
team creates purposeful meaningful documentation that’s
easy to grok with my very limited attention span.
Keyboard Shortcuts
I’ll say one thing about creating shortcuts: VS Code is very
customizable, so don’t go nuts with shortcuts. Use it for
Figure 2: Release notes a while, see what you must have as a shortcut, see that
ul>li*5
Figure 4: Emmet in action
It should look like Figure 4.
Now when you hit enter, you get a ul with five lis inside. meeting notes. You can enable Emmet in any language
you wish.
Now, let’s say that you wish to add some text into these
five <li> elements. Carefully place your cursor in the mid- For instance, I love taking notes in markdown. I don’t
dle of the first <li></li> element, and press OPTION_COM- know why we all don’t do that. It’s simple, fast, and can
MAND_CURSORDOWN. You should now see multiple cur- be version controlled and compared. In fact, my editor
sors, as shown in Figure 5. insists that I write this article in MS Word, but you know
what? I first write it in markdown, and then copy paste it
Now any text you write will appear in all five places. You in Word. It’s just more productive.
can super charge this with text replacement and regex to
do some really amazing things. Anyway, here’s how you can enable Emmet in VS Code. Figure 5: Multiple cursors
In your settings (either user or workspace), add the fol-
What if I didn’t want to type exactly the same text in all lowing:
five places. Instead, I wanted to incrementally type 1,
2, 3, 4, 5? You can use the following Emmet expansion. {
"emmet.excludeLanguages": [],
ul>li{$}*5 "emmet.includeLanguages":
{"markdown": "html"},
I know this Emmet syntax feels a bit weird and alien. Once }
you get used to it, it’s not so bad. In fact, it feels quite
logical. So here’s a link that’s a great Emmet cheat sheet Now, open a markdown file, and try out an Emmet expan-
https://docs.emmet.io/cheat-sheet/. Of course, there’s sion. For instance, let’s say that you want to quickly cre-
an extension that makes this even easier. It’s called Text ate a list of five items. Try this:
Pastry and lets you do ranges, text etc.
{ $.}*5
Selecting Text Like a Pro You can start typing notes. For instance, Figure 7 shows
I just talked about multiple cursors. That’s very cool, but my to-dos for the weekend. Note that I have my mouse
sometimes you want to visually select a random column of cursor positioned in the left gutter. Just by indenting
text. You can see Figure 6 for what I mean. The way to do things in a certain way, I can collapse or expand sections
this is to press OPTION_SHIFT and drag your mouse cur- in my notes. Good luck doing that with Notepad. This
sor across whatever you wish to select. This can be useful collapse or expand works in any language that VS Code
when you want to cross edit or paste a vertical line of text. understands, including text.
Figure 8: The outline view Figure 9: The timeline view has my back.
Sticky Headers
A really nice feature of VS Code is sticky headers. Frequent-
The Outline View ly, as I’m scrolling through code, the methods become re-
Collapse and expand is nice, but it’s sometimes very nice ally long and I tend to lose context of where I was.
to view a top-down outline view of your code. For exam-
ple, what routes do I have configured in a long file? I’ve Sticky headers solve this problem for me. As I scroll,
found this to be especially useful in languages that tend sticky headers lock the scope I’m in at the top. If you pay
to get very verbose, such as Golang. Press COMMAND_P close attention to Figure 10, you’ll see that line #51 is
and look for “Focus on outline view”. You should see my scope, and line #52, 53, and 54 are scrolling under-
something similar to Figure 8. Please feel free to try this neath it. This also works in other scopes such as if/while,
with your incredibly complicated unwieldy long file with etc. This way, when I’m in the middle of a long method in
lots of code. line #8848, I can easily reference what the input param-
eters of my scope were.
The outline view is really useful because the overall struc-
ture of the code is now super clear. Now I can tell that I
have four routes and a few global variables. Hmm, maybe Extensions
I should restructure them into a const or something to VS Code has a vibrant extensions marketplace. Nearly ev-
clean up my code. Or maybe put them in their own scope. ery platform or language has its unique needs. VS Code
I’ll get back to refactoring later. out of the box remains fairly bare bones, but you can
add whatever you wish to it via extensions. There are UI
themes that are more suitable to HTML, for instance. But
The Timeline View it’s also true that a color picker, although incredibly use-
I mentally fought Git for many years. I felt it was over- ful in CSS, has little use in Python. This is where profiles
bearing and over-complex for simple things. I’m almost come in.
at a point now where I’ve seen the light. Even for simple
stuff, you can make Git as complex or as simple as you’d If you click on the gear icon in the activity bar, you can
create profiles. In a profile, you can capture extensions,
UI state, keyboard shortcuts, and settings. You can im-
port/export profiles, and you can create profiles unique
to dev scenarios.
oper: Show running extensions”. This gives you a clear idea This window even maintains your search history and you
of which extensions are killing your battery life. Remember, can have multiple search editors open. The red arrow al-
SPONSORED SIDEBAR
you can set up profiles to selectively load extensions. This lows you to see lines of code around the matched search Adding Copilots
little bit of homework keeps your IDE zippity fast. result. For instance, clicking on that allows me to see the
line before and after the matched search result within the
to Your Apps
search results. This can be seen in Figure 12.
Search Like a Pro The future is here now
and you don’t want to get
VS Code can search through your code. That’s not a big
deal: Just type in a search term and hit enter, right? VS Summary left behind. Unlock the
true potential of your
Code’s search is quite powerful and all these nifty things Sometimes you take things for granted. I use VS Code ev- software applications by
are right under your nose. For instance, you can do “match ery day, including weekends. I seldom realize how amaz- adding Copilots.
case” or “match whole word” in search. You can even ing this tool is and how much muscle memory I take for
make search case specific. The best part is that you can granted. When I started writing this article, I was debat- CODE Consulting can
use regex expressions to search to make it truly powerful. ing whether I had enough tips. But as I started verbal- assess your applications
izing my thoughts with VS Code open on the side, I came and provide you with
Sometimes you need to search text that spans multiple up with one tip and then another. a roadmap for adding
lines. It’s easy. You just hit SHIFT_ENTER to make your Copilot features and
optionally assist you in
search box multiline. Believe me when I say this: I’m not done. Some of the
adding them to your
super-charging tips are a bit complex and require me to
applications.
Sometimes you want to narrow your search down by file describe my workflow and OS setup. Some of them are
types. You can easily click the triple dot below the search specific to Git and certain extensions that really simplify Reach out to us today
box and pick files to exclude or include, as shown in Fig- my Git life. Some of them are all about terminals host- to get your application
ure 11. ed inside VS Code so I don’t have to leave VS Code for assessment scheduled.
common tasks. Some are around debugging and logging www.codemag.com/ai
These textboxes are deceptively powerful. They allow you tricks. And there are many more.
to use glob pattern syntax in searches. For example, you
can use an asterisk (*) to match zero or more characters What code editor do you use? Do you have any favorite
in a path segment. Or you can use a question mark (?) to tips? Give a shout out to me on X or Twitter or wherever
match against one character in a path segment. You may you feel.
use double asterisks (**) to match any number of path
segments, including none. Until next time, happy coding in VS Code, or whatever
you prefer.
You can make your combine conditions using {}. For in-
stance {**/*.html,**/*.txt} matches all HTML and text Sahil Malik
files. You can use [] to declare a range of characters to
match. For example, use .[0-9] to match on example.0,
example.1, …). You can even negate criteria using !. For
example, use [!...] to negate a range of characters to
match (example.[!0-9] to match on example.a, example.b,
but not example.0).
of articles, I’ll guide you through the process of building a and Android, the .NET runtime is implemented by Mono
complete business application from scratch, step by step. which is an implementation of the runtime designed for
those platforms. On Windows, the .NET CoreCLR provides
Starting with the fundamentals of XAML, you'll learn how to the execution environment.
create your first .NET MAUI application. From there, you’ll
dive into constructing various screens, including a detailed Instead of having to learn how each platform defines
view, and using grid, stack, and flex layouts. Witness first- their UI and how they express business logic in their
hand how effortless it is to craft screens that adapt flaw- different programming languages, .NET MAUI provides a
lessly to any screen size. Whether you're an aspiring de- single framework for building the UIs and business logic.
Paul D. Sheriff veloper or a seasoned pro, this article gets you started on .NET MAUI can create applications for either mobile or
http://www.pdsa.com building business applications using XAML and .NET MAUI. desktop. You may use a Windows computer to create ap-
If you’re a C# Windows Forms developer or a WPF developer plications that target either Windows or Android; how-
Paul has been working who wants to learn to use XAML in .NET MAUI applications, ever, to build applications for iOS or macOS does require
in the IT industry since this article is also for you. To get the most out of this ar- a Mac computer.
1985. In that time, ticle, I’m assuming that you’re very familiar with C#, .NET
he has successfully
Core, and object-oriented programming.
assisted hundreds of The Basics of XAML
companies’ architect
XAML is a declarative markup language like HTML. Unlike
software applications An Overview of .NET MAUI HTML, however, XAML is mapped directly to C# types de-
to solve their toughest
business problems. Paul .NET MAUI is a technology that helps you build native fined within the .NET API used by WPF or .NET MAUI. It’s
has been a teacher and applications on Windows, macOS, iOS, and Android, all interesting to note that you can write a WPF or .NET MAUI
mentor through various using a single C# codebase. To design the UI for your ap- application solely in C# without any XAML at all. This is
mediums such as video plications, use the XAML markup. The XAML you write is because each XAML control maps directly to a C# class in
courses, blogs, articles and translated into C# for the .NET runtime designed to run on the .NET library.
speaking engagements the target OS. XAML has been around for many years and
at user groups and was originally created for use in WPF applications to cre- Of course, it’s much simpler to use XAML because it’s more
conferences around the ate robust, resolution-independent screens. Like HTML, visual and can express controls with less code than writ-
world. Paul has multiple XAML uses a flow-layout instead of absolute positioning ing in C#. In addition, using XAML allows a designer to
courses in the www. to ensure that screens can adapt to devices of any size. create the UI for an application, and a C# programmer
pluralsight.com library focuses on the business logic. This saves time and is a
(https://bit.ly/3gvXgvj) The goal of .NET MAUI is to allow you to create multi- nice division of labor. XAML files are text files with a
and on Udemy.com platform applications using a single project and code- .xaml extension, thus making it easy to share these files
(https://bit.ly/3WOK8kX) base. You’re also allowed to add platform-specific source between the programmer and the designer.
on topics ranging from C#, code and resources if needed. Starting with .NET 6, .NET
LINQ, JavaScript, Angular, MAUI targets platform-specific frameworks (Figure 1) for
MVC, WPF, XML, jQuery,
creating apps on .NET Android, .NET iOS, .NET macOS,
and Bootstrap. Contact
and Windows UI 3 (WinUI 3). These frameworks all use
Paul at [email protected].
the same .NET Base Class Library (BCL). The BCL abstracts
the details of the underlying platform away from your
code. The BCL depends on the .NET runtime to provide
the execution environment for your code. For iOS, macOS,
XML Namespaces
An XML namespace is like a C# namespace in that it contains
a set of classes that may be used without any prefixing.
For example, in C#, you may reference a File class direct-
ly if you’ve declared a Using statement to the System.IO
namespace at the top of the C# file. In the <ContentPage>
example you just looked at, the xmlns="http://schemas.
microsoft.com/dotnet/2021/maui" attribute is like a Us-
ing statement to specify which set of element names (<But-
ton>, <Label>, etc.) may be used without any prefix.
Figure 6: .NET 8.0 Runtime (Long Term Support) is required. Figure 7: .NET MAUI SDK for Windows is required.
Console.WriteLine(firstName.Text);
XAML Is Case-Sensitive Figure 10: Search for Turn Windows features on or off.
All element and attribute names are case-sensitive when
using XAML. This is because C# is case-sensitive and, to
compile XAML into C#, the names must match exactly. The Visual Studio Installer icon, click on it to launch the VS
values contained within the properties may or may not be Installer utility.
case-sensitive and will depend on what the property will
accept. If you’re setting a Text property, for example, you When the installer utility has launched, on the Workloads
may use any case you wish. If you’re setting a Boolean tab (Figure 5), ensure that you have the following checked.
property, you may use either true or True, because the
XAML parser knows to always convert True to lower-case • ASP.NET and web development
for C#. However, if the property you are trying to set is • .NET Multi-platform App UI development (MAUI)
a C# enumeration, you must spell it exactly or the XAML • .NET desktop development
parser will give you an error message.
Click on the Individual components tab and ensure that
you have the .NET 8 Runtime (Long Term Support) se-
Installing .NET MAUI lected, as shown in Figure 6.
You need to ensure that .NET MAUI has been installed
on your machine. Detailed directions are in this link: Locate the .NET MAUI SDK for Windows and ensure that
https://learn.microsoft.com/en-us/dotnet/maui/get- it’s selected, as shown in Figure 7.
started/installation?tabs=vswin. I’ve included the follow-
ing simplified instructions to get you going quickly. If you wish to run the Android Emulator, select the Google
Android Emulator (local install), as shown in Figure 8.
Bring Up the Visual Studio Installer Tool
In the search bar on your windows computer (Figure 4), The last item to select is the Android SDK setup, as
type in Visual Studio Installer, and when you locate the shown in Figure 9.
Figure 13: Select Create a new project from the Visual Studio screen.
Figure 14: Select a .NET MAUI App from the list of templates.
Figure 16: Choose .NET 8 or later when creating a .NET MAUI application.
Activate Hyper-V on Your Computer been checked as well. These components help you have
In your Windows Search bar, type in Turn Windows fea- the best performance while developing your .NET MAUI
tures on or off to display the widget shown in Figure 10. applications.
Once you click on this widget, you should see the Windows
Features dialog appear (Figure 11). Scroll down and locate Build Your First .NET MAUI Application
the Hyper-V component and ensure that it’s checked. Now that you’ve learned a little about XAML and have
installed the necessary components for building a .NET
Scroll down a little further and locate the Windows Hy- MAUI application, let's dive right in and start building
pervisor Platform (Figure 12) and ensure that it has a .NET MAUI application. Open Visual Studio 2022 and
Try It Out
Once the application has been created, click on the Win-
dows Machine button (Figure 17) on the Visual Studio
toolbar to run this application on your windows comput-
er. The first time you try to run a .NET MAUI application,
the build process takes some time, as there are lots of
dependencies to load, and it must install the application
into your Windows operating system.
Figure 19: Choose the Android Emulators > Pixel 5 – API 34.
namespace AdventureWorks.MAUI;
CODE Consulting The second method to define rows and columns is to use
www.codemag.com/Code 75 attribute-based XAML. Each row's height and each col-
CODE Legacy umn's width is separated by a comma, as shown in the
www.codemag.com/Legacy 53 following code snippet.
Try It Out
Run the application again and you should now see that
each of the Label controls line up in the center of each of
the Entry controls they’re identifying.
Listing 5: Use a FlexLayout to allow a set of controls to wrap if not enough space is available on a page.
<Label Grid.Row="7" <CheckBox />
Text="Is Enrolled?" /> </HorizontalStackLayout>
<FlexLayout Grid.Row="7" <HorizontalStackLayout Spacing="5">
Grid.Column="1" <Label Text="Health Care?" />
Wrap="Wrap" <CheckBox IsChecked="True" />
Direction="Row"> </HorizontalStackLayout>
<HorizontalStackLayout Spacing="5"> <HorizontalStackLayout Spacing="5">
<Label Text="401k?" /> <Label Text="Health Savings Account?" />
<CheckBox IsChecked="True"/> <CheckBox IsChecked="True" />
</HorizontalStackLayout> </HorizontalStackLayout>
<HorizontalStackLayout Spacing="5"> </FlexLayout>
<Label Text="Flex Time?" />
Try It Out
Run the application and your screen should like
Figure 27.
Summary
Figure 27: Use a nested grid to add controls around other controls on a page. .NET MAUI and XAML are great for creating cross-plat-
form applications. In this article, you learned the basics
of XAML, XML namespaces, attributes, and elements. Af-
ity. Each HorizontalStackLayout control is considered the ter installing .NET MAUI from the Visual Studio Installer
child elements of the FlexLayout, thus each one of those utility, you created your first .NET MAUI application
are what is wrapped when you shrink the screen. and used label and entry controls to build a data-entry
page. The Grid control is ideal for laying out how a page
Try It Out should look to the user. With the flexibility of Auto and
Run the application and shrink the screen to see the la- Star (*) spacing, you can create pages that can easily
bels and their corresponding check boxes wrapped within respond to changes in screen size. Stack layouts help
the second column of the Grid control. you build a set of controls that can be displayed either
horizontally or vertically. In the next article in this se-
ries, you’ll create styles to keep your look consistent,
Nested Grids navigate from one page to another, create reusable UIs,
One of the most powerful features of .NET MAUI is the and use more .NET MAUI controls to build even richer
ability to nest one control within one another. Nesting UIs for your users that can run on Windows, Android, or
Grid controls can help you layout a side navigation area iOS operating systems.
on the left of the screen, a status bar area at the bottom,
and your input page within the rest of the page, as shown Paul D. Sheriff
in Figure 27.
DRONES
IN ACTION
Register at
expouav.com CURRENT REALITIES & FUTURE FRONTIERS
Use code SAVE100 for
$100 off a conference pass
or a FREE exhibit hall pass
PRE SENTED BY: OFFICIAL A SSOCIATION PAR TNER: CO - LOC ATED E V ENT S:
This article will guide you through the rising popularity immerse them in the activity being performed in the ap-
of HMDs, demonstrate how to use your existing skills for plication.
these new platforms, and explore the potential of flat ap-
plications on the Meta Quest 3. Apple, Microsoft, Meta, and have all appeared on the mar-
ket with different approaches, technologies, capabilities,
Industry Overview and vocabulary for their HMDs.
Ongoing investments in HMD technology has improved
it over earlier generations of hardware. New HMDs, like • Apple Vision Pro: Apple is the latest to enter the
Meta’s Quest 3 and Apple’s Vision Pro, have enhanced market with the Apple Vision Pro. The Vision Pro is
Ed Charbeneau the tracking, camera, and display capabilities that en- marketed as the “first spatial computer.” Apple bor-
[email protected] able seamless mixed reality or spatial computing experi- rows technology from the telescope industry by us-
@EdCharbeneau ences. Using the device’s camera, the HMD displays a live ing catadioptric lenses (that combine refraction and
view of the real world around you while positioning high- reflection) in their HMD. An opaque high-density
Ed is a Microsoft MVP and
resolution 2D and 3D graphics within the environment. screen is viewed through the lenses immersing the
an international speaker,
Although 3D graphics are used for immersive experiences, user. HD cameras and a spatial processor produce an
writer, online influencer, a
you’ll find that 2D applications have found a more tradi- immersive “Spatial Computing” environment. Even
Pr. Developer Advocate for
Progress, and expert on all tional role within HMDs. Because of the high-resolution though the Vision Pro is capable of VR applications,
things Web development. Ed displays, users have gravitated toward using 2D applica- Apple has specifically targeted the device as an im-
enjoys geeking out to cool tions within the augmented environment, freeing them- mersive operating system. The focus of the Vision
new tech, brainstorming selves from desktop monitors. It’s still early, but HMDs Pro is its visionOS operating system (OS) for either
about future technology, are already cementing their future as office workstation immersive applications or flat applications displayed
and admiring great design. replacements. within its OS environment. The Vision Pro is meant
for a consumer audience and is priced at $3500.
Ed has shared his insights • HoloLens: Microsoft first entered the market with
and experiences through the HoloLens. The HoloLens device focuses on im-
training, live streaming, Using the device’s camera, mersive “holographic” MR applications. This HMD is
and podcasting at many the HMD displays a live view of a transparent visor to project holograms on top of
industry events around the the user’s space. The user interacts with the projec-
world including Microsoft the real world around you while tions using touch and voice gestures recognized by
Build, DevReach, Oredev, positioning high-resolution 2D the headset. Because the focus of this device is a
and Codemash. He’s a com-
and 3D graphics within holographic MR, it doesn’t typically make use of VR
munity builder who regu-
or other computing modes. HoloLens is targeted at
larly live streams on Twitch the environment. enterprise applications and priced between $3500
and shares knowledge at
meetups. Ed has defined, and $5200, depending on the model.
architected, and imple- • Quest 3: Meta has introduced four generations of
mented line-of-business Immersive Applications and Devices HMDs including the: Quest, Quest 2, Quest Pro, and
solutions with a touch of If you’ve used an HMD, it’s likely that you’ve experienced the newest model, Quest 3. Although Quest was tra-
style and UX best practices. a fully immersive application. This type of app completely ditionally a VR headset, Quest Pro introduced an MR
He continues to bring this changes the user’s environment for the purpose of virtual mode that was improved in Quest 3. The Quest 3
level of detail to the Telerik reality (VR) or mixed reality (MR). The most common type HMD uses pancake lenses commonly found in pho-
UI products. of immersive applications are VR games. In a VR game, tography. Like Apple’s device, the Quest 3 uses an
the user’s entire vision is replaced with a 3D-rendered opaque high-density screen viewed through the
environment and the user is completely immersed in the lenses, immersing the user. Two HD cameras and
virtual environment. a processor produce an immersive “Mixed Reality
Passthrough” environment. Quest 3 has its roots
Immersive MR experiences are less common because they in VR and is breaking into the MR gaming market.
require more advanced hardware and software capabili- In addition, Quest 3 has an immersive-capable
ties. In an immersive MR app, the HMD either needs to be Android-based OS. Meta is focused on creating VR/
transparent or uses cameras to capture the user’s view of MR “experiences” in the consumer audience and is
the real world and display it in real time. In addition, the priced at $350.
HMD needs to analyze spatial data including the user’s
surroundings, position, and objects within the space. The In immersive applications, the software takes exclusive
spatial data is then used to augment the user’s view and control over the user’s environment to make use of spa-
The Case for Flat Applications Figure 2: The Meta Quest taskbar in Mixed Reality
A flat application denotes a conventional 2D application Passthrough floats over the real-world environment.
(originally designed for desktop monitors, mobile screens,
or the browser) that has been modified or redeployed to
function within a spatial OS. As HMDs have evolved with Office suite, including Power Point, Excel, and Word, as
better representations of the real-world environment, us- shown in Figure 1. Although Meta may have fewer native
ers are considering HMDs as replacements for other com- flat apps, its focus on affordability, visual quality, and
puting activities. Having traditional 2D applications in a developer support makes it a compelling choice for bring-
spatial context gives users the ability to run these apps ing apps to the platform.
freely in virtual 3D space versus being constrained to a
physical screen. Flat applications can run directly on the The Meta Quest 3 Platform
device’s OS in floating resizable windows. The feeling of Despite having the fewest first-party flat apps, Meta’s
openness and lack of boundaries allows users to work from platform strategically emphasizes several key advantag-
anywhere while multitasking on limitless screen sizes. es. The Meta platform offers a low price point, making it
accessible to a wide range of users. Its high-resolution
Software companies have realized the potential of flat ap- display (2064 x 2208 resolution per eye) and full color
plications and have started preparing for the emergence passthrough is suitable for productivity purposes. Quest
market. Apple and Meta have designed their operating 3’s spatial OS allows multitasking with up to three flat
systems and app stores to accommodate flat applications applications at once. In addition, Meta has intentionally
and have delivered their first-party applications. Because created a low barrier to entry for developers by choos-
Apple isn’t focused on immersive apps, it relies on flat ap- ing the ubiquitous Android OS and supporting Progressive
plications to fill out its offering by including Safari, Mail, Web Applications (PWAs).
FaceTime, Keynote, Notes, Apple TV +, and many more.
Although Meta is focused on immersive apps, it does offer You’ll enter Quest's passthrough mode through the inter-
a few of its own with Meta Quest Browser, Instagram, and face shown in Figure 2, which is activated by double tap-
Quest TV. Other big names are releasing flat apps on both ping on the headset or pressing the Enter passthrough
platforms as well. Microsoft has released the Microsoft mode button from the system's taskbar. Once in
REGISTER TODAY!
PowerPlatformConf.com @PowerPlatConf #PPCC24
Copilot • AI • ChatGPT • .NET • ASP.NET • GitHub • Visual Studios • Open AI • LLM • Azure AI Studio • and more…
ERIC BOYD SCOTT HANSELMAN SCOTT HUNTER KATHLEEN DOLLARD DAN WAHLIN
Corporate Vice Vice President, Vice President, Director Principal Program Principal Cloud
President, AI Platform, Developer Community, Product Management Manager, Microsoft Developer Advocate,
Microsoft Microsoft for Azure Developer Microsoft
Experience, Microsoft
JEFF FRITZ MADDY MONTAQUILA MARKUS EGGER ZOINER TEJADA MICHELE LEROUX
Principal Program Senior Program President and Chief CEO and Architect, BUSTAMANTE
Manager, Microsoft Manager, .NET MAUI, Software Architect, Solliance President & Architect,
Microsoft CODE Group Solliance
[email protected]
nextGenAIconf.com @ nextGenAIconf [email protected]
passthrough, you'll see the live environment displayed Meta has made the platform accessible to developers, and
in real-time with the user interface and applications dis- you can deploy and submit your own applications to the
played spatially in your surroundings. Meta Store. Most applications that you’ve written for the
Android operating system that compile to an Android Pack-
In passthrough mode, you can open three flat applica- age Kit (APK) can also deploy to the device. In addition, the
tions from the taskbar, as shown in Figure 3. Applications ecosystem is open to Progressive Web Applications (PWAs)
you use in this mode can be resized and rearranged. Using as well. The only warning with PWAs is that they must be
the Quest controllers or gestures from the device’s hand deployed through the app store as an APK, which is accom-
tracking capabilities, you grab the edges of an applica- plished with Meta's command line tool. You'll find that the
tion as if you were using a mouse on the desktop. developer toolchain used for the Quest is quite intuitive as
the developer experience integrates with the headset.
Although multitasking is built into the system's OS, there
are third-party applications that offer additional capabili-
ties such as virtual monitors, remote desktop, and collab- Developer Tools
orative experiences. Because immersive experiences take Setting up the developer environment and making sure you
control over the full user experience, multitasking only have the prerequisites installed is necessary to be successful
works with flat applications. When you launch an immer- when writing applications for the Quest. You can consider
sive experience from within an app or from the taskbar, it developing for the Quest as “mobile development” because
hides the OS and all flat applications in your current view. it follows many of the same principles and uses similar tool-
ing. In addition to the typical development tools, there are
platform-specific tools as well. There’s an extensive list of
prerequisites with each item having its own purpose. You’ll
When you launch an immersive find a list of each tool in Table 1 categorized by application
name, type, and purpose. Every tool here is used in the Soft-
experience from within an app or ware Development Life Cycle (SDLC) from unlocking devel-
from the taskbar, it hides the OS oper mode on the device, to writing code, and to publishing.
and all flat applications in your
Quest Mobile App
current view. The Quest Mobile app is required to use the device and
part of the standard installation process when you buy a
packaging tool used to wrap your PWA as an APK so it can browser is built using the open-source Chromium ren-
be delivered through the app store. The tool requires other dering engine, commonly used in popular browsers.
dependencies on Java and the Android SDK. You’ll find the It’s optimized for WebXR and WebGL, allowing fully im-
full installation instruction in the Meta developer documen- mersive 3D experiences. Specifically designed for Meta
tation under PWA tools and Packaging (https://developer. Quest hardware, it offers fast performance and improved
oculus.com/documentation/web/pwa-packaging/). battery life. It’s important to note that the Meta Quest
Browser isn’t the same browser implemented by the
Quest Remote Desktop device’s Web View. When using Blazor Hybrid on .NET
The Quest Remote Desktop application is a Quest applica- MAUI, the WebXR APIs aren’t present in the device’s
tion that runs on the device and connects to a remote PC. Web View.
You’ll need to download and install a companion app on
the PC that will be connected. Remote Desktop isn’t nec-
essary for development, but it allows you to access your Flat Applications with .NET
development PC from within the Quest. Use Remote Desk- When creating spatial computing applications, you’ll
top to access Visual Studio while using the Quest. You’ll have a variety of languages and frameworks to choose
find that the developer experience here is quite good on from. For immersive app development, it’s necessary to
the Quest 3 due to the high-resolution display. This setup use specialized 3D software development tools, such as
also enables you to write, test, and debug flat applica- the .NET-based Unity platform. In contrast, the develop-
tions while wearing the device and multitasking with its ment of flat applications is more accessible, thanks to
spatial OS, as shown in Figure 7. .NET’s robust support for cross-platform development,
sidestepping the intricacies and demands of 3D applica-
Meta Quest Browser tion development. In addition, you may be able to update
The Meta Quest Browser is the default web browser existing .NET applications, allowing them to run as flat
that runs on the Quest device, shown in Figure 8. This applications.
Figure 7: The Quest Remote Desktop (right) displaying Visual Studio on a remote PC while debugging on a .NET MAUI
app running on the Quest (left)
Table 2 is a list of .NET stacks that are compatible with Hybrid, which is part of .NET MAUI. Blazor Hybrid gives
building flat applications for the Quest. First is .NET MAUI, you the benefits of .NET MAUI with the addition of Blazor’s
a cross-platform application framework. The unified ap- component model that uses HTML and CSS to render UI
proach of .NET MAUI abstracts the platform-specific de- components. The third choice is Blazor PWA. Blazor PWA
tails, allowing you to focus on building features rather apps use browser-based technologies to build native-like
than dealing with platform complexities. Second is Blazor experiences. All these options compile to APKs and deploy
on the Quest, and each choice comes with its own benefits.
When you build your first Hello World app with each plat-
Stack UI Platform form, you’ll be able to decide which stack works for you.
.NET MAUI XAML .NET MAUI, native UI
.NET MAUI
Blazor Hybrid HTML, CSS, XAML optional Browser API, .NET MAUI .NET MAUI uses the latest technologies for building native
Blazor PWA HTML, CSS Browser API, .NET Web Assembly apps on Windows, macOS, iOS, and Android, abstracting
them into one common framework built on .NET. You use
Table 2: Quest-Compatible .NET Stacks a single C# codebase and project system for all device tar-
gets to build apps that look and feel like native platforms.
The .NET runtime is the execution environment for MAUI
applications, even though the underlying implementations
of the runtime may be different, depending on the host.
For example, on Windows, WinRT provides the environment
with optimizations for the Windows platform and on Quest,
the environment is implemented by Mono, a .NET runtime
for Android. The Android features of .NET MAUI make it
possible to target the Quest with your application.
To create your .NET MAUI app, you need the .NET Multi-
Platform App UI development workload installed, as
you can see in Figure 10. With the workload installed,
the .NET MAUI App template is available in Visual Stu-
dio. Create a new project and choose the .NET MAUI App
Figure 9: A block diagram of .NET MAUI. The highlighted items show where Android is template, as highlighted in Figure 10, then click Next to
implemented in the stack. continue through the remaining prompts.
Figure 14: The Quest Developer Hub’s Devices section with key elements highlighted: the active Quest device (1), the current user (2), and the Device menu (3)
Using (var stream = await FileSystem. skills from web development, you may be unfamiliar with
OpenAppPackageFileAsync(templateFileName)) .NET MAUI’s XAML implementation. For a web developer,
using (var reader = new StreamReader(stream)) Blazor Hybrid may be a better fit.
{
//Line 50 Blazor Hybrid with .NET MAUI
CurrentContents = await reader. Blazor Hybrid is built upon .NET MAUI’s API while add-
ReadToEndAsync(); ing in a web presentation layer powered by the Blazor
} framework. When you use Blazor Hybrid, you get platform
} API access and a rich HTML UI component model. Blazor
} Hybrid support is built into the .NET MAUI framework.
.NET MAUI includes the BlazorWebView control that per-
Now that you’re familiar with .NET MAUI, let’s explore mits rendering Razor components into an embedded Web
another UI option. If you’re a developer with technical View. By using .NET MAUI and Blazor together, you can
reuse one set of web UI components across mobile, desk-
top, and web. This approach is ideal if you’ve worked with
ASP.NET or have an existing Blazor application you want
to deploy beyond the web browser. Even third-party UI
component libraries, like Telerik UI for Blazor (https://
www.telerik.com/blazor-ui/blazor-hybrid), are supported
with Blazor Hybrid applications, giving you the ability to
use hundreds of UI components.
<BlazorWebView x:Name="blazorWebView"
HostPage="wwwroot/index.html">
<BlazorWebView.RootComponents>
<RootComponent Selector="#app"
ComponentType="{x:Type local:Components.Routes}" />
</BlazorWebView.RootComponents>
</BlazorWebView>
After reviewing the logic for the page, you’ll want to start
the application and check the functionality. To test the
application, choose Oculus Quest 3 from the start menu,
then start with debugging. When the application starts,
you’ll be greeted with the Home page and a menu con-
taining three items. Choose the Counter menu item to
view the example shown in Figure 24. The Counter exam-
ple is like the .NET MAUI project’s sample, but the Blazor
Hybrid version uses HTML and Razor instead of XAML.
Figure 20: Running the Platform integration demos for the .NET MAUI application
In the Pages folder, you’ll find the Counter.razor com-
ponent that contains the code for the Counter page. An
excerpt is shown in the snippet below. The Counter uses a
standard HTML button element. The button’s onclick event
is bound using Razor syntax to delegate the event to the
IncrementCount method in C# code. When the Increment-
Count method is triggered, the currentCount field value is
updated and displayed in the preceding p element.
@code {
private int currentCount = 0;
name to be displayed in the Remote Target heading, as form perspective, Blazor Hybrid offers the most flexibility.
shown in Figure 25. If you’d like to take a pure web approach, Blazor Progres-
sive Web Apps (PWAs) are an option.
Below the application name is the “inspect” link that
opens the debugger. Click the link to debug your app’s Blazor PWAs
rendered HTML, CSS, and JavaScript. For a seamless de- Blazor Progressive Web Apps use web standard technology
veloper experience, try using the Quest Remote Desktop to create applications that run in the browser and have
while debugging the application and running side-by-side features that parallel native platform applications. Blazor
in the Quest, as seen in Figure 26. PWAs use the .NET Runtime for WebAssembly to execute
.NET code in the browser. When a Blazor PWA runs on
Blazor Hybrid offers a balance between .NET and web de- Quest, it has complete access to the Meta Quest Browser
velopment by combining the two in a native package. and any APIs it supports. To test the Quest Browser’s API
With Blazor Hybrid, you can leverage .NET MAUI’s cross support, try visiting What PWA Can Do Today (https://
platform APIs directly from Razor code. From a cross-plat- whatpwacando.today/) using the Quest Browser.
To create your Blazor PWA app, you need the ASP.NET and
web development workload installed. To do this, refer
back to Figure 6. With the workload installed, the Blazor
Standalone App template is available in Visual Studio.
Create a new project and choose the Blazor Standalone
App template, as shown in Figure 28, and then click Next
to continue through the next prompts.
Figure 23: The file structure
of the Blazor Hybrid project On the Additional information menu, select the Progres-
with key files highlighted: sive Web Application option. Enabling this option adds
MauiProgram.cs (1), MainPage. the supporting resources required for your app to qualify
xaml (2), and Pages folder (3) Figure 24: The Blazor Hybrid application displaying the as a PWA, as shown in Figure 29. After enabling this op-
with three component samples counter page, viewed through the Quest 3 tion, click Create to generate the solution.
Figure 26: Use Edge to remotely debug the HTML of the .NET MAUI WebView via Remote Desktop.
Figure 28: The Visual Studio Create dialog with the Blazor WebAssembly Standalone App
template (highlighted)
codemag.com/legacy
832-717-4445 ext. 9 • [email protected]
three files, Home.razor, Counter.razor, and Weather.ra- With the dev tunnel created, expand the Start menu again
zor, represent the examples in the app with correspond- to choose the dev tunnel by name, as seen in Figure 34.
ing names (Home, Counter, Weather). The next notable Now start your application without debugging. When the
file is mainifest.webmainfest , which contains your ap- application starts, it opens a browser window and dis-
plication’s metadata. You set values in the manifest to plays an information message. Click Continue from the
represent your app’s name, home screen icon, and start dialog to access your app. The browser’s address bar dis-
URL. plays a generated address ending with devtunnels.ms.
Figure 31: The Blazor Progressive Web Application running in a web browser with the web address “localhost”
You use this address to connect to your application from Now that you’ve successfully launched the app from the
any device outside your network. Copy the address from Quest, you’ll want to test it as a deployable PWA that
the browser’s address bar, as shown in Figure 35. Next, can be submitted to the Quest Store. A deployable PWA
open the Quest Developer Hub with your device connect- doesn’t use the browser directly; instead it looks like a
ed and paste the address into the Open URL field under standard platform application running on the Quest’s spa-
Device Actions. After you’ve entered the URL, click Open tial OS. For the application to be deployed, you’ll need to
to launch the Meta Quest Browser on the device using package it as an Android APK using Quest’s command line
your dev tunnel address. tool. Start by prepping your manifest by opening the file
ovr-platform-util.exe create-pwa
-o blazor-pwa-outputAPK
--android-sdk C:\{androidSDK path}
--package-name com.blazorapp1.pwa
--manifest-content-file ".\path\manifest.webmanifest"
Figure 35: Opening a web app that uses dev tunnels displays a connection prompt before
accessing the app
Figure 37: A Blazor PWA running on the Quest’s spatial OS in a native shell
Conclusion using the .NET stack including: .NET MAUI, Blazor Hy-
As HMD hardware and software advance, they open new brid, and Blazor PWA. Each stack complements a certain
possibilities for developers. These days, the market is .NET developer skill set, whether it’s XAML, HTML, or web
showing interest in consumers using HMDs as desktop standards. As a .NET developer, you should look at your
replacement options. As consumers shift from gaming on current flat applications and experiment with them on the
these devices to using them for daily computing tasks, Quest 3. There just may be an opportunity to bring your
the need for flat applications will follow. Because the app into the future using spatial computing.
Meta Quest 3’s platform uses Android as its operating
system, it’s accessible to many developers. There are cur- Ed Charbeneau
rently three ways to deploy flat applications on the Quest
like logging, performance management, exception han- Procedural Programming, Object Oriented programming,
dling, configuration management, and security. Aspects and Aspect Oriented programming are typical examples of
can be used to combine similar concerns into a single unit such paradigms.
and applied to an application's core logic via weaving.
Procedural programming is a programming paradigm
This article compares AOP to OOP and Procedural Pro- that was popular worldwide before the advent of object-
graming, and provides a deep dive into AOP, explaining oriented programming. Often contrasted with object-
why it’s useful, and illustrating how you can optimize oriented programming, procedural programming is one of
performance of an ASP.NET Core application using AOP the foundational programming paradigms that thrives on
Joydip Kanjilal and then store the captured performance metadata in a writing procedures or routines to execute tasks in a pro-
[email protected] database. gram. Typical examples of procedural programming lan-
guages are C, Pascal, Fortran, etc. The major downsides
Joydip Kanjilal is an MVP If you’re to work with the code examples discussed in this of procedural programming are code tangling and that it
(2007-2012), software article, you need the following installed in your system: didn’t support reusability. Object-oriented programming
architect, author, and was invented primarily to address the pitfalls of proce-
speaker with more than
• Visual Studio 2022 dural programming.
20 years of experience.
• .NET 8.0
He has more than 16 years
• ASP.NET 8.0 Runtime
of experience in Microsoft What Is Object-Oriented
.NET and its related
technologies. Joydip has If you don’t already have Visual Studio 2022 installed on Programming (OOP)?
authored eight books, your computer, you can download it from here: https:// Object-oriented programming (OOP) helps organize an
more than 500 articles, visualstudio.microsoft.com/downloads/. application in a more structured and modular way by rep-
and has reviewed more resenting real-world entities as objects, each with its own
than a dozen books. In this article, I'll examine the following points: set of attributes (or data) and behaviors (also known as
methods). Although OOP is a programming paradigm that
• Procedural, OOP, and AOP programming styles and focuses on encapsulation of data and behavior into ob-
their benefits jects, AOP extends OOP by focusing on the separation of
• AOP and its features, benefits, and downsides concerns in an application.
• The core concepts of AOP
• How to use Autofac to create a memory cache in- Features of OOP
terceptor The key concepts of OOP include the following:
• How to use PostSharp to build an application that
stores application performance metadata in a da- • Classes: A class is defined as a blueprint based on
tabase which instances of classes or objects are created.
• How to use PostSharp to store CPU and memory us- Classes are known as the building block of OOP that
age details in a database encompasses both data and the functions (in OOP,
functions are also known as methods) that operate
on the data.
What Is a Programming Paradigm? • Objects: Objects are defined as instances of classes
The term "paradigm" is analogous to an approach or that are created based on the template or structure
style used in programming to solve a specific problem. A as defined by a class. They can interact with one
number of programming paradigms have evolved over the another through method calls.
years, including imperative, structured, procedural, func- • Encapsulation: Encapsulation (also known as in-
tional, declarative, event-driven, object-oriented, and formation hiding) is a fundamental concept in OOP
aspect-oriented. Programming has evolved into a variety that involves combining data (attributes, proper-
of paradigms since its infancy, and we've witnessed the ties) and methods (functions, operations) that op-
emergence of several programming paradigms since the erate on data inside a single unit, known as a class.
early days of programming. These paradigms have fos- • Inheritance: Inheritance is a feature of OOP that
tered the growth of several new programming languages. enables a subclass or derived class to extend or in-
58 Store Application Performance Metadata in a Database Using AOP in ASP.NET Core codemag.com
herit the attributes, properties, and methods of its
base class.
• Polymorphism: Polymorphism is a feature of OOP
that enables objects of multiple child classes to
be treated as pertaining to a common base class,
and thereby enabling the same method to behave
differently depending on the object that calls the
method.
Benefits of OOP
The key benefits of OOP include the following:
Code tangling is an example of spaghetti code that often In an application, cross-cutting concerns help implement
occurs when an application's unrelated concerns are in- separation of concerns and is a design principle that pro-
tertwined in a particular class or module. Spaghetti code, motes modularity, reusability, easier maintenance, and
an outcome of bad programming practices, is a term that reduces inconsistencies in your application's codebase.
describes code that’s difficult to understand or maintain,
because it’s tangled, complex, and difficult to compre-
hend. When the application's source code is tangled, it
What Is Aspect-Oriented
can be challenging to comprehend and manage complex Programming (AOP)?
code bases, as changes to the code in one part of the ap- In traditional Object-Oriented Programming (OOP), it of-
plication can have unexpected consequences in another. ten becomes extremely difficult to manage the applica-
tion’s cross-cutting concerns because they’re entangled
Another downside of OOP is code scattering, which oc- with the application’s core concerns. Aspect-Oriented
curs when an application's related functionality is spread Programming (AOP) is a programming approach that de-
across multiple classes, making the codebase excruciat- couples the cross-cutting concerns of an application from
ingly difficult to understand and maintain. The codebase that application's core, resulting in enhanced code reuse
of an application will become easier to manage, under- and modularity.
stand, and maintain if its related functionality is orga-
nized coherently. The reuse of code between applications Object-oriented programming (OOP) and aspect-oriented
can become difficult if functionality is spread across mul- programming (AOP) are two widely used programming
tiple classes and tied to specific implementations. paradigms that have distinct characteristics. Although
Object-Oriented Programming (OOP) is centered on the
To reduce or eliminate code scattering, you can adopt concept of objects, Aspect-Oriented Programming (AOP)
object-oriented design principles, such as the single mainly emphasizes aspects. An aspect is a modularization
codemag.com Store Application Performance Metadata in a Database Using AOP in ASP.NET Core 59
Aspects are a set of join points and pointcuts added to an
application's source code. As the name implies, join points
are specific points in the program's execution flow when
an aspect may be applied, such as method calls, object
creation, field accesses, and exception handling routines.
For example, a join point may indicate that an aspect be
applied to all method calls with a given name or class.
[Serializable]
public class
MyCustomInterceptorAspect :
Figure 2: The core concepts of AOP MethodInterceptionAspect
{
public override void
of a concern that cuts across several places in your ap- OnInvoke(MethodInterceptionArgs args)
plication's codebase. A typical example of an AOP aspect {
is a logging module. AOP doesn't replace Object-Oriented
Programming (OOP); rather, it complements OOP by add- }
ing reusable implementations. }
To implement AOP in your applications, you can take ad- You can implement weaving using several approaches,
vantage of code weaving, dynamic proxies, or bytecode ma- such as bytecode modification and dynamic proxies. By-
nipulation approaches. Each of these approaches allows you tecode modification is a technique used to modify the
to attach aspects without affecting the original program bytecode dynamically at runtime without altering the
code. Some of the widely used and most popular AOP frame- original source code. In AOP, a dynamic proxy is used
works include PostSharp, Castle Dynamic Proxy, Spring, and to create a proxy instance for a target object, thereby
AutoFac. In this article, I’ll discuss Autofac and PostSharp. enabling you to attach additional behaviors such as log-
ging, transaction management, exception handling, etc.
How Does AOP Work? There are several ways to implement weaving in AOP, in-
In this section, I’ll examine how AOP works and the re- cluding compile-time weaving, load-time weaving, and
lated concepts. Figure 2 illustrates all the bits of AOP. runtime weaving. By incorporating aspects into a pro-
gram, the AOP framework intercepts execution at the join
Note that weaving and method intersection are the two locations indicated by the pointcut and applies the advice
ways in which AOP links aspects to an application’s code. described in the aspect, as shown in Figure 3.
Weaving is a strategy adopted to untangle code by ap-
plying an aspect to an application's source code at the Implementing Cross-Cutting Concerns Using AOP
relevant join points. In AOP, method interception refers Let’s now understand how usage of AOP can help you
to the ability to intercept method calls, thereby enabling write cleaner, more manageable, and reusable code. Refer
additional behaviors to be injected either before, after, or to the following piece of code:
around the original method invocation.
public class CacheAspect:
You can isolate the cross-cutting concerns of an application OnMethodBoundaryAspect
from its code by intercepting method calls and injecting {
code at different points when the methods are in execution //Write your code here to cache data
at runtime. Method interception refers to the practice of }
altering the runtime behavior of methods. This is achieved
by splitting the methods into smaller chunks of functional- public class LogAspect:
ity known as aspects. These aspects are in turn integrated OnMethodBoundaryAspect
into the source code of a target method via proxies or deco- {
rators. An interceptor enables additional functionality to //Write your code here to log data
be added to a method call by intercepting method invoca- // to a pre-defined log target
tions and forwarding them to the target object. }
60 Store Application Performance Metadata in a Database Using AOP in ASP.NET Core codemag.com
Implementing Cross-Cutting Concerns without AOP
public class OrderRepository If you didn’t use AOP here, the OrderRepository class
{ would have looked like this:
[CacheAspect]
public Task<IEnumerable<Order>> public class OrderRepository
GetAllAsync() {
{ public Task<IEnumerable<Order>>
//Code to return all orders GetAllAsync()
//from the database {
} //Code to return all orders
//from the cache or the
[LogAspect] //underlying database
public Task SaveAsync(Order order) }
{
//Code to save an order public Task SaveAsync(Order order)
//object to the database {
} //Code to save an order object
} //to the database and cache it
}
In the preceding code snippet, the aspects Logging }
and Caching have been applied on the GetAllAsync and
SaveAsync method respectively. In this example, I've lev- So, you might have to explicitly write your code to call
eraged AOP into the OrderRepository class. You can ap- the respective methods of the LogAspect and CacheAspect
ply aspects at the method level, property level, and the classes to retrieve data from the cache or persist data into
class level as well. Although aspects applied to a par- the cache. Most importantly, you’d have had to write such
ticular method are applicable for the particular method code at several places in your application wherever these
only, those applied at the class level are applicable for aspects were used, resulting in boilerplate code, which is
all members (i.e., methods and properties) of the class. difficult to manage and maintain over a period of time.
In the following code snippet, the LogAspect has been When Should I Use AOP?
applied at the class level and the CacheAspect has been You can use AOP in for one or more of the following:
applied at the method level.
• Logging: You can eliminate boilerplate code to le-
[LogAspect] verage AOP to log data in your application.
public class OrderRepository • Caching: You can leverage AOP to cache frequently
{ used, relatively stale data.
[CacheAspect] • Validation: You can use AOP to validate input data
public Task<IEnumerable<Order>> by enforcing validation rules.
GetAllAsync() • Security: You can use AOP to enforce security poli-
{ cies in your application in a consistent manner.
//Code to return all orders • Transaction Management: You can take advantage
//from the database of AOP to implement transaction management in
} your application.
codemag.com Store Application Performance Metadata in a Database Using AOP in ASP.NET Core 61
• Performance Monitoring: You can use AOP to iden- ate a mapping between each dependency and its corre-
tify performance and scalability bottlenecks in your sponding implementation.
application.
The Autofac container resolves the dependencies based
on the provided mappings and provides the corresponding
Introducing Autofac instances when the application needs them. For example,
Autofac is a lean, open-source, Inversion of Control (IoC) if your application needs a service instance, you can de-
container used for resolving dependencies in .NET Frame- clare an interface for it and then develop a class that
work and .NET Core applications. You can use it to build implements it. You can then register this implementation
applications using .NET Framework or .NET Core, and such in the Autofac container and use one of the various injec-
applications are maintainable, manageable, adaptable, tion strategies to resolve the dependency as needed in
and loosely coupled. Autofac provides support for inter- the application.
ceptors; using them lets you inject your logic before and
after method calls, thereby enabling you to implement Benefits of Autofac over the Built-In DI Container
AOP. Autofac provides several benefits compared to the built-
in dependency injection (DI) container:
Key Features
Here are the key features of Autofac: • Flexibility: The built-in IoC container in ASP.NET
Core provides limited support for dependency injec-
• Component Registration: Autofac supports the reg- tion as you can only use constructor injection with
istration of components and their dependencies and it. However, you can leverage Autofac to implement
can resolve dependencies for registered components both constructor and property injection.
if needed. • Lifetime management: The Autofac lifetime man-
• Extensibility: Autofac supports a variety of ex- agement system lets you control the lifecycle of
tension points, including customized registration your objects and prevent memory leaks by using the
sources, middleware, and decorators. singleton instance per dependency, and instance per
• Modular Design: In Autofac, you can organize com- lifetime scope options.
ponent registrations into modules, which can be • Testing: Autofac makes making mock objects and
loaded and unloaded dynamically, thereby promot- stubs easy so that you can test your code seam-
ing the modularity and maintainability of applica- lessly.
tions. • Third-party integration: Autofac supports integra-
• Inversion of Control (IoC): Autofac adheres to the tion with popular third-party libraries, like Serilog,
IoC principle, enabling you to define how dependen- AutoMapper, and MediatR. Integrating these librar-
cies are resolved and managed in applications. ies into your application and configuring them with
• Lifetime Management: Autofac supports manag- Autofac is easy.
ing the lifetime of container objects for a particular • Performance: Autofac is fast, easily customizable,
request, including singleton, transient, and scoped and leverages lazy loading and compiled expressions
lifetimes. to optimize object creation and resolve dependen-
• Interception: Autofac supports interception, en- cies.
abling you to intercept method calls on registered
components and apply cross-cutting concerns such What Is a Dynamic Proxy?
as logging, caching, or security. A dynamic proxy is a programming approach to create a
• Integration with Frameworks: Autofac integrates proxy object at runtime, which, in turn, acts as an inter-
seamlessly with .NET and .NET Core frameworks, mediary between a real object and the client. Using this
thereby making it a preferred choice for implement- technique, you can attach aspects to objects dynamically,
ing dependency injection. such as at runtime, without altering their source code
and implement cross-cutting concerns such as transaction
What Are Interceptors? management, logging, and caching.
In Autofac, interceptors are components that enable you
to add behavior to a class, interface, or configuration
without modifying its implementation. Using Autofac,
Building a Memory Cache
you can intercept method calls and add custom behav- Interceptor Using Autofac
ior using interception frameworks such as Castle Dynam- A memory cache interceptor is a component that can in-
icProxy. In Autofac, interceptors are implemented using tercept method calls and cache the results in memory.
the Castle DynamicProxy framework, which creates a This helps you optimize the performance by decreasing
proxy object that intercepts method calls at runtime and the need to retrieve the same piece of data repeatedly. In
can modify them before passing them along to the target this section, you’ll implement a memory cache intercep-
object. tor. You’ll follow the following steps to build a memory
cache interceptor:
What Is an Autofac Container? Why Is It Needed?
An Autofac container is used to manage the lifecycle of 1. Create a model class.
objects, resolve dependencies, and ensure the creation 2. Create the data context.
and proper disposal of objects when they’re no longer 3. Prepare the seed data.
needed by your application. You can create dependen- 4. Create a memory cache interceptor.
cies by defining the required interfaces or concrete types, 5. Create and configure the Autofac container.
which are then registered in the Autofac container to cre- 6. Create the repository class.
62 Store Application Performance Metadata in a Database Using AOP in ASP.NET Core codemag.com
7. Create the controller class. PM> Install-Package Autofac
8. Leverage the cache interceptor in the control- PM> Install-Package Autofac.Extensions.DependencyInjection
ler class. PM> Install-Package Autofac.Extras.DynamicProxy
9. Run the application.
You can also install this package by executing the follow-
Create a New ASP.NET Core MVC 8 Project in Visual ing commands at the Windows Shell:
Studio 2022
You can create a project in Visual Studio 2022 in several dotnet add package Autofac
ways. When you launch Visual Studio 2022, you'll see the dotnet add package Autofac.Extensions.DependencyInjection
Start window. You can choose "Continue without code" dotnet add package Autofac.Extras.DynamicProxy
to launch the main screen of the Visual Studio 2022 IDE.
Create the Model Class
To create a new ASP.NET Core MVC 8 Project in Visual Crate a new class named Customer in a file named Cus-
Studio 2022: tomer.cs inside the Models folder of the web application
project you created earlier and write the following code
1. Start the Visual Studio 2022 IDE. in there:
2. In the “Create a new project” window, select “ASP.
NET Core Web App (Model-View-Controller)” and click namespace OrderProcessingSystem.Models
Next to move on. {
3. Specify the project name and the path where it public class Customer
should be created in the “Configure your new proj- {
ect” window. public Guid Id { get; set; }
4. If you want the solution file and project to be cre- public string FirstName
ated in the same directory, you can optionally check { get; set; } = default!;
the “Place solution and project in the same direc- public string LastName
tory” checkbox. Click Next to move on. { get; set; } = default!;
5. In the next screen, specify the target framework and public string Address
authentication type as well. Ensure that the "Con- { get; set; } = default!;
figure for HTTPS," "Enable Docker," and “Do not use public string Email
top-level statements” checkboxes are unchecked be- { get; set; } = default!;
cause you won’t use any of these in this example. public string Phone
6. Click Create to complete the process. { get; set; } = default!;
}
A new ASP.NET Core MVC project is created. You’ll use this }
project in the sections that follow.
codemag.com Store Application Performance Metadata in a Database Using AOP in ASP.NET Core 63
Listing 2: Index View of the Customer Model
@model IEnumerable <th></th>
<OrderProcessingSystem.Models.Customer> </tr>
@{ </thead>
ViewData["Title"] = "Customer View"; <tbody>
} @foreach (var item in Model)
{
<h1>Customer Details</h1> <tr>
<td>
<table class="table"> @Html.DisplayFor
<thead> (modelItem => item.FirstName)
<tr> </td>
<th> <td>
@Html.DisplayNameFor @Html.DisplayFor
(model => model.FirstName) (modelItem => item.LastName)
</th> </td>
<th> <td>
@Html.DisplayNameFor @Html.DisplayFor
(model => model.LastName) (modelItem => item.Address)
</th> </td>
<th> </tr>
@Html.DisplayNameFor }
(model => model.Address) </tbody>
</th> </table>
Create the Index View for the Customer Model namespace OrderProcessingSystem.DataAccess
In ASP.NET Core MVC, views are used to present data to {
the user in a way that’s meaningful. In this section, you'll public class CustomerRepository :
create an Index view for the Customer model. To build the ICustomerRepository
Index view for the Customer model, follow these steps: {
private readonly CustomerDbContext _context;
1. Import model data onto the view to read and extract public CustomerRepository()
data pertaining to the Customer model. {
2. Access the properties of the Customer model. var options = new
3. Iterate through the Customer data using the @ DbContextOptionsBuilder<ProductDbContext>()
foreach loop. .UseInMemoryDatabase("OrderManagementSystem")
4. Access the Customer data inside the loop and .Options;
display it in the view using @Html.DisplayFor.
_context = new CustomerDbContext(options);
The complete source code of the customer view is given _context.Database.EnsureCreated();
in Listing 2. }
public List<Customer> GetAll() =>
Note that I’ve omitted the ID column for brevity in the
preceding code of the Index view of the Customer model. Create the MemoryCacheInterceptor
To create a custom interceptor, create a class that imple-
Create the CisustomerRepository ments the IInterceptor interface, as shown in Listing 3.
The customer repository will comprised of the ICustomer-
Repository interface and the CustomerRepository class. In Listing 3, write your custom code to intercept meth-
The code snippet given below shows the ICustomerRe- ods at runtime. It should be noted that this code, that
pository interface. is, the source code you need to write inside the Intercept
64 Store Application Performance Metadata in a Database Using AOP in ASP.NET Core codemag.com
Listing 4: The complete source of MemoryCacheInterceptor class
public class MemoryCacheInterceptor : IInterceptor string? commaSeperatedArguments =
{ string.Join(", ", arguments);
private readonly IMemoryCache _memoryCache; string? cacheKey = $"
private TimeSpan cacheDuration = {declaringType}|{methodName}|
TimeSpan.FromSeconds(30); {commaSeperatedArguments}";
method, will be executed when a method is intercepted. Listing 5: The ContainerHelper class
This means that this code will be executed before and public static class ContainerHelper
after the intercepted method is invoked. {
public static WebApplication
The complete source code of the MemoryCacheInterceptor BuildContainer(WebApplicationBuilder builder)
{
is given in Listing 4.
builder.Host.UseServiceProviderFactory
Register the MemoryCacheInterceptor (new AutofacServiceProviderFactory()).
To register the MemoryCacheInterceptor, i.e., wire up the ConfigureContainer<ContainerBuilder>(builder =>
{
interceptor to the Autofac container, you can use the fol- builder.RegisterType<MemoryCacheInterceptor>();
lowing code. builder.RegisterType<CustomerRepository>()
.As<ICustomerRepository>()
builder.RegisterType<MemoryCacheInterceptor>(); .InstancePerDependency()
builder.RegisterType<CustomerRepository>() .EnableInterfaceInterceptors()
.InterceptedBy(typeof(MemoryCacheInterceptor));
.As<ICustomerRepository>() });
.InstancePerDependency()
.EnableInterfaceInterceptors() return builder.Build();
.InterceptedBy(typeof(MemoryCacheInterceptor)); }
}
codemag.com Store Application Performance Metadata in a Database Using AOP in ASP.NET Core 65
Listing 6: The CustomerController class
public class CustomerController : Controller {
{ return View();
private readonly }
ICustomerRepository _customerRepository;
public CustomerController [HttpPost]
(ICustomerRepository customerRepository, [ValidateAntiForgeryToken]
IMemoryCache memoryCache) public ActionResult Edit(int id,
{ IFormCollection collection)
_customerRepository = customerRepository; {
} try
{
public ActionResult Index() return RedirectToAction(nameof(Index));
{ }
return View(_customerRepository.GetAll()); catch
} {
public ActionResult Details(int id) return View();
{ }
return View(); }
}
public ActionResult Create() public ActionResult Delete(int id)
{ {
return View(); return View();
} }
[HttpPost] [HttpPost]
[ValidateAntiForgeryToken] [ValidateAntiForgeryToken]
public ActionResult Create public ActionResult Delete
(IFormCollection collection) (int id, IFormCollection collection)
{ {
try try
{ {
return RedirectToAction(nameof(Index)); return RedirectToAction(nameof(Index));
} }
catch catch
{ {
return View(); return View();
} }
} }
public ActionResult Edit(int id) }
tory and then call the GetAll method of it inside the Index
action method of the controller. public CustomerController
(ICustomerRepository
private readonly customerRepository,
ICustomerRepository IMemoryCache memoryCache)
_customerRepository; {
_customerRepository =
customerRepository;
Listing 7: The Program.cs file }
var builder = WebApplication.CreateBuilder(args);
// Add services to the container [LoggingAspect]
builder.Services.AddMemoryCache(); public ActionResult Index()
{
builder.Services.AddControllersWithViews();
return View(_customerRepository.
var app = ContainerHelper.BuildContainer(builder); GetAll());
}
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
The complete source code of the CustomerController class
app.UseExceptionHandler("/Home/Error"); is given in Listing 6.
}
app.UseStaticFiles(); The Program.cs File
The complete source code of the Program.cs file is given
app.UseRouting();
in Listing 7.
app.UseAuthorization();
When you execute the application and browse the /Cus-
app.MapControllerRoute( tomer endpoint, the customer records are displayed at the
name: "default",
pattern: "{controller=Home}/ web browser, as shown in Figure 4.
{action=Index}/{id?}");
Because caching has been enabled, and because you’ve al-
app.Run(); ready registered a memory cache interceptor, the customer
66 Store Application Performance Metadata in a Database Using AOP in ASP.NET Core codemag.com
data is fetched from the cache and not from the database throughout the codebase. This leads to duplicate code
for all subsequent calls to the same endpoint. Figure 5 and a lack of code modularity. For example, you might
shows how the breakpoint set in the Intercept method of require logging at several places in an application. Here's
the MemoryCacheInterceptor class is hit when you refresh where PostSharp can help, by automatically addressing
the web page. these concerns, reducing boilerplate code, and increasing
code readability and modularity.
Programming AOP Using PostSharp PostSharp works by post-processing compiler output to add
Typically, developers find it challenging to handle cross- aspects and make changes to the intermediate assembly.
cutting concerns such as logging, caching, validation, After compilation, PostSharp reads and disassembles the
and error handling because the code is often entangled intermediate assembly, applies the necessary transforma-
codemag.com Store Application Performance Metadata in a Database Using AOP in ASP.NET Core 67
Listing 8: The ProductDbContext class
public class ProductDbContext : DbContext products);
{ }
public ProductDbContext private Product[] GenerateProductData()
(DbContextOptions {
<ProductDbContext> options) var productId = 1;
: base(options)
{ var productFaker = new Faker<Product>()
} .RuleFor(x => x.Id, f => productId++)
protected override void OnConfiguring .RuleFor(x => x.Name,
(DbContextOptionsBuilder optionsBuilder) f => f.Commerce.ProductName())
{ .RuleFor(x => x.Description,
optionsBuilder. f => f.Commerce.ProductDescription())
UseInMemoryDatabase .RuleFor(x => x.Price,
(databaseName: "ProductDb"); f => Math.Round(f.Random.Decimal
} (1000, 5000), 2));
public DbSet<Product> Products { get; set; }
protected override void return productFaker.
OnModelCreating(ModelBuilder modelBuilder) Generate(count: 5).ToArray();
{ }
var products = GenerateProductData(); }
modelBuilder.Entity<Product>().HasData(
The compile-time weaving technique guarantees that Create the Data Context
the aspects are built into the assembly, resulting in re- Next, create the data context class to interact with the
duced runtime cost. This implies that when your applica- database. To do this, create a new class named Product-
tion starts, the aspects are already applied to the code, DbContext that extends the DbContext class of EF Core
eliminating the need for extra processing or overhead. In and write the code from Listing 8 in there.
runtime weaving, PostSharp enables applying aspects in
a more dynamic manner, enabling you to deploy compo- Create the ProductRepository Class
nents like application plug-ins or extensible frameworks Now, create a new class named ProductRepository in a file
at runtime. In other words, although the aspects are inte- having the same name with a .cs extension. Now write the
grated directly into the compiled code during compilation following code in there:
in compile-time weaving, in runtime-weaving, these as-
pects are applied at specified points of the application's public class ProductRepository :
code at runtime. IProductRepository
68 Store Application Performance Metadata in a Database Using AOP in ASP.NET Core codemag.com
Listing 10: The ProductController class
public class ProductController : Controller {
{ return View();
private readonly IProductRepository }
_productRepository;
public ProductController [HttpPost]
(IProductRepository productRepository, [ValidateAntiForgeryToken]
IMemoryCache memoryCache) public ActionResult Edit(int id,
{ IFormCollection collection)
_productRepository = productRepository; {
} try
public ActionResult Index() {
{ return RedirectToAction(nameof(Index));
return View(_productRepository. }
GetAll()); catch
} {
public ActionResult return View();
Details(int id) }
{ }
return View(); public ActionResult Delete(int id)
} {
public ActionResult Create() return View();
{ }
return View();
} [HttpPost]
[ValidateAntiForgeryToken]
[HttpPost] public ActionResult Delete(int id,
[ValidateAntiForgeryToken] IFormCollection collection)
public ActionResult {
Create(IFormCollection collection) try
{ {
try return RedirectToAction(nameof(Index));
{ }
return RedirectToAction(nameof(Index)); catch
} {
catch return View();
{ }
return View(); }
} }
}
public ActionResult Edit(int id)
The complete source code of the ProductRepository class //Other action methods
is given in Listing 9. }
codemag.com Store Application Performance Metadata in a Database Using AOP in ASP.NET Core 69
Listing 11: The ExecutionTimeDbContext class
public class ExecutionTimeDbContext : DbContext {
{ modelBuilder.Entity
public ExecutionTimeDbContext <ExecutionTimeMetadata>
(DbContextOptions (entity =>
<ExecutionTimeDbContext> options) {
: base(options) entity.HasKey(e => e.Id);
{ entity.Property(e =>
} e.MethodName).HasColumnType("TEXT");
protected override void OnConfiguring entity.Property(e =>
(DbContextOptionsBuilder options) e.DeclaringType).HasColumnType("TEXT");
=> options.UseSqlite entity.Property(e =>
($"Data Source=ExecutionTimeMonitor.db;"); e.ExecutionTime).HasColumnType("LONG");
public DbSet<ExecutionTimeMetadata> });
ExecutionTimeMetadatas { get; set; } }
protected override void OnModelCreating }
(ModelBuilder modelBuilder)
click on the solution and then select Manage NuGet Pack- Create the ExecutionTimeMetadata Model
ages for Solution…. Now search for the package named Create a new class named ExecutionTimeMetadata in a file
PostSharp in the search box and install it. Alternatively, named ExecutionTimeMetadata.cs and write the following
you can type the commands shown below at the NuGet code in there.
Package Manager Command Prompt:
public class ExecutionTimeMetadata
PM> Install-Package PostSharp {
[Key]
You can also install this package by executing the follow- [DatabaseGenerated
ing commands at the Windows Shell: (DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
dotnet add package PostSharp public string MethodName { get; set; }
public string DeclaringType { get; set; }
public long ExecutionTime { get; set; }
Store Performance Metadata }
into the Database
In this section, I’ll examine how to capture and store
application performance metadata in a database. You’ll You'll use this class to store method execution metadata
leverage AOP to retrieve and store performance monitor- in memory.
ing data in a database. Note that you’ll store the CPU and
memory usage details in a database as well as the method Create the ExecutionTimeDbContext Class
execution time of an action method in another database. The ExecutionTimeDbContext class is used to connect to
For the sake of simplicity, I’ll use SqlLite databases in a SqlLite database and store the method execution meta-
this example. data in it, as shown in Listing 11.
70 Store Application Performance Metadata in a Database Using AOP in ASP.NET Core codemag.com
Figure 6: Displaying the execution time of the Index action method
codemag.com Store Application Performance Metadata in a Database Using AOP in ASP.NET Core 71
Listing 15: The OnEntry and OnExit methods
public override void OnEntry _context.PerformanceMetadatas.Add
(MethodExecutionArgs args) (new PerformanceMetadata()
{ {
var options = CpuUsage = cpuUsage,
new DbContextOptionsBuilder<PerformanceDbContext>() MemoryUsage = memoryUsage
.UseSqlite($"Data Source=PerformanceMonitor.db") });
.Options;
var ctr = _context.PerformanceMetadatas.Count();
_context = new PerformanceDbContext(options); _context.SaveChanges();
_context.Database.EnsureCreated(); }
public override void OnExit(MethodExecutionArgs args)
var cpuUsage = {
float.Round(ApplicationPerformanceUtility. var typeName = args.Method.DeclaringType.Name;
GetCpuUsage(), 2); var methodName = args.Method.Name;
var memoryUsage = Console.WriteLine
float.Round(ApplicationPerformanceUtility. ($"{methodName} method of {typeName} executed.");
GetMemoryUsage(),2); }
Create the PerformanceMetadata Model WMI is an acronym for Windows Management Instrumenta-
Create a new class named PerformanceMetadata in a file tion, a COM-based Microsoft technology used to retrieve
having the same name with a .cs extension and write the hardware information. To capture application performance
following code in there. metadata, i.e., the CPU usage and memory usage in this
example, create a new class called ApplicationPerforman-
public class PerformanceMetadata ceUtility in a file named ApplicationPerformanceUtility.cs
{ and write the code given in Listing 14 in there.
[Key]
[DatabaseGenerated Create the LoggingAspect Class
(DatabaseGeneratedOption.Identity)] Create a new class named LoggingAspect in a file named
public int Id { get; set; } LoggingAspect.cs and write the following code in there.
public float CpuUsage { get; set; }
public float MemoryUsage { get; set; } [PSerializable]
} public class LoggingAspect :
OnMethodBoundaryAspect
{
Create the PerformanceDbContext public override void OnEntry
The PerformanceDbContext class connects to a SqlLite (MethodExecutionArgs args)
database named PerformanceMonitor.db to persist per- {
formance metadata. In the OnModelCreating method, you
specify the primary key and the database table columns }
you need. Listing 13 is the complete source code of the
PerformanceDbContext class. public override void OnSuccess
(MethodExecutionArgs args)
Retrieve Performance Metadata {
In this section, I’ll examine how you can take advantage
of WMI to retrieve system information from your computer. }
72 Store Application Performance Metadata in a Database Using AOP in ASP.NET Core codemag.com
Figure 7: Displaying the CPU and Memory usage details
codemag.com Store Application Performance Metadata in a Database Using AOP in ASP.NET Core 73
CODE COMPILERS
74 Store Application Performance Metadata in a Database Using AOP in ASP.NET Core codemag.com
CUSTOM SOFTWARE DEVELOPMENT
STAFFING TRAINING/MENTORING SECURITY
codemag.com/code
832-717-4445 ext. 9 • [email protected]
STAFFING
UNLOCK
STAFFING
EXCELLENCE
Top-Notch IT Talent, Contract Flexibility, Happy Teams, and a
Commitment to Customer Success Converge with CODE Staffing
Our IT staffing solutions are engineered to drive your business forward while
saving you time and money. Say goodbye to excessive overhead costs and
lengthy recruitment efforts. With CODE Staffing, you’ll benefit from contract
flexibility that caters to both project-based and permanent placements. We
optimize your workforce strategy, ensuring a perfect fit for every role and
helping you achieve continued operational excellence.
Visit our website to find out more about how we are changing
the staffing industry.
Website: codestaffing.com
Yair Alan Griver (yag)
Chief Executive Officer
Direct: +1 425 301 1590
Email: [email protected]