Sr. Content Developer at Microsoft, working remotely in PA, TechBash conference organizer, former Microsoft MVP, Husband, Dad and Geek.
145602 stories
·
32 followers

Event Enrichment in Marten Projections

1 Share

So here’s a common scenario when building a system using Event Sourcing with Marten:

  1. Some of the data in your system is just reference data stored as plain old Marten documents. Something like user data (like I’ll use in just a bit), company data, or some other kind of static reference data that doesn’t justify the usage of Event Sourcing. Or maybe you have some data that is event sourced, but it’s very static data otherwise and you can essentially treat the projected documents as just documents.
  2. You have workflows modeled with event sourcing and you want some of the projections from those events to also include information from the reference data documents

As an example, let’s say that your application has some reference information about system users saved in this document type (from the Marten testing suite):

public class User
{
    public User()
    {
        Id = Guid.NewGuid();
    }

    public List<Friend> Friends { get; set; }

    public string[] Roles { get; set; }
    public Guid Id { get; set; }
    public string UserName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName => $"{FirstName} {LastName}";
}

And you also have events for some kind of UserTask aggregate that manages the workflow of some kind of work tracking. You might have some events like this:

public record TaskLogged(string Name);
public record TaskStarted;
public record TaskFinished;

public class UserAssigned
{
    public Guid UserId { get; set; }

    // You don't *have* to do this with a mutable
    // property, but it is *an* easy way to pull this off
    public User? User { get; set; }
}

In a “query model” view of the event data, you’d love to be able to show the full, human readable User information about the user’s full name right into the projected document:

public class UserTask
{
    public Guid Id { get; set; }
    public bool HasStarted { get; set; }
    public bool HasCompleted { get; set; }
    public Guid? UserId { get; set; }

    // This would be sourced from the User
    // documents
    public string UserFullName { get; set; }
}

In the projection for UserTask, you can always reach out to Marten in an adhoc way to grab the right User documents like this possible code in the projection definition for UserTask:

    // We're just gonna go look up the user we need right here and now!
    public async Task Apply(UserAssigned assigned, IQuerySession session, UserTask snapshot)
    {
        var user = await session.LoadAsync<User>(assigned.UserId);
        snapshot.UserFullName = user.FullName;
    }

The ability to just pull in IQuerySession and go look up whatever data you need as you need it is certainly powerful, but hold on a bit, because what if:

  1. You’re running the projection for UserTask asynchronously using Marten’s async daemon where it updates potentially hundreds of UserTask documents a the same time?
  2. You expect the UserAssigned events to be quite common, so there’s a lot of potential User lookups to process the projection
  3. You are quite aware that the code above could easily turn into an N+1 Query Problem that won’t be helpful at all for your system’s performance. And if you weren’t aware of that before, please be so now!

Instead of the N+1 Query Problem you could easily get from doing the User lookup one single event at a time, what if instead we were able to batch up the calls to lookup all the necessary User information for a batch of UserTask data being updated by the async daemon?

Enter Marten 8.11 (hopefully by the time you read this!) and our newly introduced hook for “event enrichment” and you can now do exactly that as a way of wringing more performance and scalability out of your Marten usage! Let’s build a single stream projection for the UserTask aggregate type shown up above that batches the User lookup:

public class UserTaskProjection: SingleStreamProjection<UserTask, Guid>
{
    // This is where you have a hook to "enrich" event data *after* slicing,
    // but before processing
    public override async Task EnrichEventsAsync(
        SliceGroup<UserTask, Guid> group, 
        IQuerySession querySession, 
        CancellationToken cancellation)
    {
        // First, let's find all the events that need a little bit of data lookup
        var assigned = group
            .Slices
            .SelectMany(x => x.Events().OfType<IEvent<UserAssigned>>())
            .ToArray();

        // Don't bother doing anything else if there are no matching events
        if (!assigned.Any()) return;

        var userIds = assigned.Select(x => x.Data.UserId)
            // Hey, watch this. Marten is going to helpfully sort this out for you anyway
            // but we're still going to make it a touch easier on PostgreSQL by
            // weeding out multiple ids
            .Distinct().ToArray();
        var users = await querySession.LoadManyAsync<User>(cancellation, userIds);

        // Just a convenience
        var lookups = users.ToDictionary(x => x.Id);
        foreach (var e in assigned)
        {
            if (lookups.TryGetValue(e.Data.UserId, out var user))
            {
                e.Data.User = user;
            }
        }
    }

    // This is the Marten 8 way of just writing explicit code in your projection
    public override UserTask Evolve(UserTask snapshot, Guid id, IEvent e)
    {
        snapshot ??= new UserTask { Id = id };
        switch (e.Data)
        {
            case UserAssigned assigned:
                snapshot.UserId = assigned?.User.Id;
                snapshot.UserFullName = assigned?.User.FullName;
                break;

            case TaskStarted:
                snapshot.HasStarted = true;
                break;

            case TaskFinished:
                snapshot.HasCompleted = true;
                break;
        }

        return snapshot;
    }
}

Focus please on the EnrichEventsAsync() method above. That’s a new hook in Marten 4.13 that lets you define a step in asynchronous projection running to potentially do batched data lookups immediately after Marten has “sliced” and grouped a batch of events by each aggregate identity that is about to be updated, but before the actual updates are made to any of the UserTask snapshot documents.

In the code above, we’re looking for all the unique user ids that are referenced by any UserAssigned events in this batch of events, and making one single call to Marten to fetch the matching User documents. Lastly, we’re looping around on the AgentAssigned objects and actually “enriching” the events by setting a User property on them with the data we just looked up.

A couple other things:

  • It might not be terribly obvious, but you could still use immutable types for your event data and “just” quietly swap out single event objects within the EventSlice groupings as well.
  • You can also do “event enrichment” in any kind of custom grouping within MultiStreamProjection types without this new hook method, but I felt like we needed this to have an easy recipe at least for SingleStreamProjection classes. You might find this hook easier to use than doing database lookups in custom grouping anyway

Summary

That EnrichEventsAsync() code is admittedly some busy code that really isn’t the most obvious thing in the world to do, but when you need better throughput, the ability to batch up queries to the database can be a hugely effective way to improve your system’s performance and we think this will be a very worthy addition to the Marten projection model. I cannot possibly stress enough how insidious N+1 Query issues can be in enterprise systems.

This work was more or less spawned by conversations with a JasperFx Software client and some of their upcoming development needs. Just saying, if you want any help being more successful with any part of the Critter Stack, drop us a line at sales@jasperfx.net.



Read the whole story
alvinashcraft
just a second ago
reply
Pennsylvania, USA
Share this story
Delete

VS Code & Friends

1 Share

Had lots of fun meeting the Visual Studio Code and GitHub Copilot teams and many cool fellow travellers. Here’s a fun little vibing session with Burke Holland on VSCode Live:


My course on AI-powered software development with Isaac Flath, Elite AI-assisted Coding, is kicking off with a first cohort on October 6th. Join us!


If you’re curious to learn how AI coding agents work, Isaac and I are going to do a free live session where we’ll build together and simple agent.

Event image


Read the whole story
alvinashcraft
15 seconds ago
reply
Pennsylvania, USA
Share this story
Delete

Americans want AI to stay out of their personal lives

1 Share

A new study from Pew suggests that Americans aren’t particularly optimistic about AI. A full 50 percent of respondents said they were more concerned than excited about the use of AI in their daily lives. That’s down ever so slightly from 52 percent in 2023, but it’s up significantly from 37 percent in 2021. 

Americans expressed a number of concerns about AI, chief among them that it will negatively impact our ability to think creatively and form meaningful relationships with other people. Just 18 percent believed that AI should play any role at all in dating and matchmaking, with just 3 percent being comfortable with it playing a “big role.” The theme in general was that Americans are okay with AI performing analysis on large data to, say, predict the weather, or find cures for disease, but they wanted it to stay out of their personal lives. Two-thirds of people want it to stay out of their love lives entirely, and 73 percent believe it has no place advising people on their religious beliefs.

A chart showing that more than half of Americans believe AI will worsen people’s ability to form meaningful relationships.

Another concern was the spread of misinformation. 18 percent of respondents rated misinformation as their number one concern, behind only its negative impact on human abilities and connections. Americans felt that it was very important to be able to identify AI-generated work, but 53 percent said they were not confident in their ability to do so.

Interestingly, in a reversal of what you’d expect with the emergence of new technologies, it’s actually younger Americans who are more concerned. 57 percent of those under 30 said they were extremely concerned that AI would erode people’s abilities, while only 46 percent of those over 65 said the same.

Broadly, though, it’s clear that Americans are taking a skeptical eye towards AI. 61 percent said they wanted more control over how AI is used in their daily lives. Unfortunately, 57 percent believe they have little or no control over that.

Read the whole story
alvinashcraft
3 hours ago
reply
Pennsylvania, USA
Share this story
Delete

Microsoft Copilot Studio Unleashed: Build Secure, Scalable AI Agents for Real Business Impact!

1 Share

As organizations accelerate their adoption of generative AI, the need for secure, scalable, and business-aligned solutions has never been greater. Microsoft 365 Copilot Studio (portal shown in the picture above), together with Azure AI Foundry, empowers enterprises to build intelligent agents that automate workflows, enhance productivity, and uphold responsible AI principles. This blog explores how technical, and business leaders can leverage these platforms to create extensible, trustworthy AI solutions, drawing on best practices from recent Microsoft Learning Paths and community feedback.

 

Why Copilot Studio Extensibility Matters

Microsoft 365 Copilot Studio lets organizations create custom agents that use enterprise data, automate tasks, and enhance experiences in Microsoft 365 apps. Its extensibility supports integration with external systems, workflow customization, and multi-step task automation, all within security and compliance standards. The image below highlights M365 Copilot Studio “Lite”. This is one of the ways to create an AI Agent. This also reminds us to use the Work tab when building agents or working with organizational data.

Key Business Benefits

  • Rapid Innovation: Declarative and custom agents can be built quickly, enabling teams to prototype and deploy solutions that address real business needs.
  • Scalability: Agents can be shared with individuals, teams, or entire organizations, supporting everything from lightweight Q&A Bots to enterprise-grade automation.
  • Security and Compliance: Copilot Studio agents operate within Microsoft’s secure ecosystem, respecting data boundaries, permissions, and compliance requirements.
  • Responsible AI: Built-in governance, content safety, and lifecycle management ensure that AI solutions are ethical and trustworthy from design to deployment.

Agentic AI: From Automation to Autonomous Intelligence

Traditional automation is limited by static rules and workflows. Agentic AI, powered by Azure AI Foundry, introduces agents that perceive, reason, and act independently adapting to dynamic business environments and complex decision-making. These agents:

  • Understand Context: Maintain thread-based memory and learn from interactions.
  • Collaborate: Work with other agents and tools to solve multifaceted challenges.
  • Act Autonomously: Respond to natural language prompts and execute goal-driven tasks.

Technical Capabilities

  • Goal-Oriented Design: Agents are configured with clear objectives and constraints, ensuring alignment with business outcomes.
  • Tool Integration: Agents connect to APIs, databases, and external services for specialized tasks.
  • Multi-Agent Collaboration: Enables coordinated strategies for complex scenarios.
  • Advanced Fine-Tuning: Techniques like Supervised Fine-Tuning (SFT), Reinforcement from Feedback Tuning (RFT), and Direct Preference Optimization (DPO) allow agents to be tailored for domain-specific needs and compliance.

Secure and Responsible AI Lifecycle

Security and responsibility are foundational to successful adoption of AI. Azure AI Foundry and Copilot Studio embed these principles throughout the agent lifecycle:

  • Protect: Implement access controls, data-loss prevention, and adversarial testing.
  • Detect: Use frameworks like MITRE ATLAS and OWASP Generative AI Risk to identify vulnerabilities.
  • Respond: Monitor agent behavior post-deployment with tracing tools and compliance integrations.
  • Govern: Align with Microsoft’s Responsible AI Standard and leverage Azure AI Content Safety for proactive risk management.

Real-World Use Cases

  • Security Agents: Detect threats, isolate incidents, and recommend policy changes.
  • Training Agents: Personalize learning paths with privacy safeguards.
  • Translation Agents: Enable safe, real-time multilingual communication.
  • Planning Agents: Support decision-making with traceable analysis.

Developer and Business Requirements

To build and deploy agentic AI solutions, organizations need:

Getting Started: Learning Paths and Resources

Microsoft provides comprehensive learning paths and documentation to guide teams through every stage of agent development:

Call to Action

As you navigate the evolving landscape of AI in the enterprise, prioritize secure, responsible, and extensible agentic solutions. Leverage Microsoft 365 Copilot Studio and Azure AI Foundry to build agents that not only automate tasks but drive meaningful business outcomes, while upholding the highest standards of security, compliance, and ethical AI.

Ready to build your first agent?

Explore the Create Agentic AI solutions by using Azure AI Foundry and Create agents in Microsoft Copilot Studio learning paths and start your journey today!

 

About the Author: Hello Jacques "Jack here!" I am a Microsoft Technical Trainer dedicated to assisting learners and organizations in implementing intelligent automation using Microsoft technologies. This blog reflects my experience guiding teams in building agentic AI solutions that are not only powerful but also secure, ethical, and scalable.

#SkilledByMTT #MicrosoftLearn

Read the whole story
alvinashcraft
3 hours ago
reply
Pennsylvania, USA
Share this story
Delete

Supercharge your workflow with real-time information from the Microsoft Learn MCP Server

1 Share

Stay focused and on track by connecting your AI agents directly to trusted Microsoft documentation.

With the shift toward more AI-powered workplaces, developers and IT teams are spending less time searching the web and more time relying on AI tools and agents for help. But AI is only as good as the knowledge it can access—and even the most advanced AI models are working with information that has knowledge cutoffs, meaning their resources can be months out of date. Outdated or incomplete information can lead to errors, inefficiencies, and compliance issues.

That’s where a new standard is emerging: Model Context Protocol (MCP) Servers. They connect AI agents directly to trusted, real-time data sources, so answers are accurate, relevant, and up to date.

With the Microsoft Learn MCP Server, your AI agents can tap directly into official Microsoft product knowledge, right inside your development environment or workflow. No browser hopping. No guesswork. Just faster, more accurate results with AI guidance that helps you streamline your workflow and grow your skills while solving real-world problems.

What is the Microsoft Learn MCP Server?

Think of the Microsoft Learn MCP Server as your direct line to official Microsoft documentation—delivered to your AI Agent, in real time, in context, without leaving the tools you already use. Whether you’re coding in Visual Studio Code, prompting GitHub Copilot, or building a custom AI assistant, the Learn MCP Server brings relevant guidance to your fingertips.

 

Faster coding within your IDE with Microsoft Learn MCP Server

There’s no need to create custom connectors or install extra components. The service uses lightweight, streamable HTTP, so it works seamlessly with almost any MCP-compatible tool.

The Learn MCP Server provides multiple ways for AI agents to surface the right information:

  • Focused excerpts: The server can search Microsoft content and return up to 10 chunks of high-quality information—each with a title, URL, and self-contained passage.
  • Full technical documentation: When broader context is needed, the Learn MCP Server can fetch complete pages, giving agents richer, more contextual information than a chunk alone could provide.

Together, these built-in tools are designed to quickly provide you with the information you need by giving AI agents the flexibility to retrieve information in the format that best fits the task at hand—whether that’s targeted excerpts or a complete page of documentation.

 

Learn how to supercharge your workflowwith theMicrosoft Learn MCP Server

If you’re a developer, that means you’ll have real-time access to definitive Microsoft resources, delivered at the right level of detail to help you solve complex problems, write high-quality code, streamline workflows, and build smarter AI agents.

If you’re a technology leader, you’ll be able to equip your teams with smarter tools that provide timely, reliable resources, opening up new ways to learn and work more efficiently and effectively.

Unlock smarter agentic experiences with the Microsoft Learn MCP Server

Here are a few ways you can start putting Learn MCP to work:

  • Create help desk agents that resolve tickets in minutes. Picture a support agent tackling a tricky issue. Instead of digging through pages of search results, their AI assistant pulls exact, up-to-date documentation from Microsoft Learn right into the workflow. The result? Faster resolution times, reduced escalations, and higher customer satisfaction.
  • Develop onboarding agents that feel like personal coaching. New hires often spend weeks finding their footing, but with AI-guided Microsoft Learn resources tailored to each role, they can quickly ramp up on the tools they'll use every day—like Microsoft 365, Azure, or Dynamics 365—and build skills and confidence faster.
  • Build more secure apps with confidence. By connecting GitHub Copilot agent mode to the Microsoft Learn MCP Server, your AI assistant can access the latest secure development practices and requirements, helping you identify vulnerabilities in open-source packages, validate configurations, and flag risky dependencies before they reach production.

 

Help Desk agents can quickly access how-to Microsoft knowledge

 

Secure coding how-to now at your fingertips

We’re continuing to expand what’s possible with the Learn MCP Server, so your AI agents can do even more, with even greater accuracy. In the coming weeks, a new capability will enable agents to access precise, ready-to-use code samples that improve the reliability and quality of AI-generated development work.

These enhancements will make it even easier for you to build intelligent, context-aware AI agents, backed by the most current Microsoft product knowledge to help teams maximize productivity, stay secure, and deliver more value.

Try it for yourself

MCP servers are rapidly gaining traction as the standard for connecting AI agents to high-value, trustworthy data sources—a critical capability as organizations race to adopt AI responsibly.

Microsoft Learn is already helping developers and technology leaders put this standard into practice, both by helping learners gain the skills needed to build AI agents and by enhancing the way those agents deliver knowledge to people in the flow of work.

By embedding official Microsoft product knowledge directly into your workflows, you can make better decisions, accelerate development cycles, streamline operations, and avoid the pitfalls of outdated information.

It’s all part of Microsoft Learn’s commitment to helping people use AI more effectively and with confidence.

Explore the Learn MCP Server:

Read the whole story
alvinashcraft
3 hours ago
reply
Pennsylvania, USA
Share this story
Delete

Copilot-powered file previews coming to Microsoft 365 Copilot app for iOS

1 Share

Hi, Insiders! We’re Samer Sawaya and Jeet Mukeshkumar Patel, Product Managers on the Apple Experiences and Microsoft 365 Copilot app team. We’re excited to share some changes we’re making to the Microsoft 365 Copilot app for iOS that will give you easier access to start your work with the power of Copilot Chat.

Copilot-powered file previews coming to Microsoft 365 Copilot app for iOS

The Microsoft 365 Copilot mobile app on iPhone and iPad is getting an experience update that puts key AI-driven capabilities and experiences front and center. (NOTE: These features are available to Microsoft 365 Copilot app users with access to Copilot Chat.)

With this update, anyone using the Microsoft 365 Copilot app can:

  • Create any Word, Excel, or PowerPoint file in no time by simply sharing their thoughts or text from other files or webpages with Copilot Chat.
  • Get answers to questions, understand more about a topic, or review a full file summary with a seamless previewing experience and intelligent suggestions.
  • Share any file with the Microsoft 365 Copilot app to get instant summaries or answers through an interactive chat, perfect for quickly understanding key points.
  • Find what they need fast by searching for any of their content using natural, conversational language. (NOTE: This feature is only available to Enterprise customers with a Premium Copilot license.)

Consumption of all your files, including Word, Excel, and PowerPoint files, in the Microsoft 365 Copilot app will be powered by an in-context preview, with the ability to ask Copilot for assistance on the file. To edit the contents in a document, you will now be prompted to switch to the Word, Excel, and PowerPoint apps.

We’re making these changes to evolve the Microsoft 365 Copilot app as your go-to AI productivity app, and to bring AI-first, chat-driven scenarios front and center in the experience. Since Word, Excel, and PowerPoint have dedicated apps with a first-rate editing experience, app-specific Copilot capabilities, and fast performance, with this change, we will direct users who would like to edit documents to the standalone Word, Excel, and PowerPoint mobile apps. 

Users can search to find files and content they care about, but file browsing actions and OneDrive library management will be moved into the OneDrive app.

As part of this change, the Outlook, OneDrive, and Teams apps for both iPhone and iPad will no longer open Word, Excel, and PowerPoint files in Microsoft 365 Copilot. Those apps will provide optimized previews of documents but launch Word, Excel, or PowerPoint, or ask you to download those apps from the App Store if they are not installed, when you try to open those file types.

How it works

A series of updates will automatically go into effect for Microsoft 365 Copilot for iOS users when they update the app. To download the app on your iOS device:

NOTE: We recommend you also download the Word, Excel, and PowerPoint for iOS apps to edit files, and the OneDrive for iOS app to browse folders.

Availability

This update is slowly rolling out to Microsoft 365 Copilot app users on iOS.

The first phase of this change is in-product notifications in the Microsoft 365 Copilot app shown to users who are editing documents to notify them that Word, PowerPoint, Excel, and OneDrive apps are available. Users will still be able to work with documents and dismiss the notification without taking action during this time. This in-app notification rolled out to TestFlight users at the end of August, and is becoming generally available mid-September for iPad and iPhone users.

The second phase of this change updates the Word, PowerPoint, and Excel functionality in the Microsoft 365 Copilot app with previewers that will be made available to TestFlight users only in October, and progress to general availability later in the month, starting with iPhone. With this part of the change, users will no longer be able to edit files in the Microsoft 365 Copilot app. Teams, OneDrive, and Outlook apps will stop opening these files in the Microsoft 365 Copilot app and instead prompt users to install the respective standalone apps. While we are starting with iPhone, the iPad will see similar changes rolling out before the end of the calendar year. 

Our team is working diligently to ensure a smooth and seamless experience for all users, and we thank you for your patience!

A similar change will be coming to Android devices in the future, so stay tuned!

Feedback

We’d love to hear what you think of the updated Microsoft 365 Copilot app! To provide feedback, select the Settings gear in the app, then navigate to Help & Feedback.

Thank you for being a valued member of the Microsoft 365 community!

 

Learn about the Microsoft 365 Insider program and sign up for the Microsoft 365 Insider newsletter to get the latest information about Insider features in your inbox once a month!

Read the whole story
alvinashcraft
3 hours ago
reply
Pennsylvania, USA
Share this story
Delete
Next Page of Stories