Async Code Execution in XAF Actions

Async Code Execution in XAF Actions

Lately, I’ve been working extensively on interacting with LLMs using the Semantic Kernel framework. My experiments usually start as NUnit test projects, where I prototype my ideas.

Once an experiment is successful, I move it to XAF. Recently, I faced challenges with executing asynchronous code and updating the XAF UI. This process is tricky because some solutions might appear to work but fail under certain conditions.

Goals

Here’s what I aim to achieve:

  1. Execute asynchronous code within the execute handler of an action.
  2. Notify the UI and access the current view, object, and object space.
  3. Run multiple operations on a background thread.

For more background, check out these links on async executions within XAF actions:

WebForms

Blazor

Complete source code for this test can be found on GitHub.

Common Cases

1. Blocking the UI Thread (this will not work)

If you don’t make your action async, attempting to get the awaiter will block the UI thread, freezing your application.


ActionBlockUIThread = new SimpleAction(this, nameof(ActionBlockUIThread), "View");
ActionBlockUIThread.Execute += ActionBlockUIThread_Execute;

protected virtual void ActionBlockUIThread_Execute(object sender, SimpleActionExecuteEventArgs e) {
    var Tasks = GetTaskList();
    StringBuilder Results = new StringBuilder();
    foreach (var item in Tasks) {
        Results.AppendLine(item.Invoke().GetAwaiter().GetResult().ToString());
    }
    MessageOptions options = new MessageOptions { Duration = 2000, Message = Results.ToString(), Type = InformationType.Success };
    Application.ShowViewStrategy.ShowMessage(options);
}

2. Using Async Modifier (somehow works)

Marking your handler as async prevents blocking but keeps the UI responsive, which can allow the user to modify or navigate away from the current view, causing exceptions.


protected virtual async void ActionWithAsyncModifier_Execute(object sender, SimpleActionExecuteEventArgs e) {
    var Tasks = GetTaskList();
    StringBuilder Results = new StringBuilder();
    foreach (var item in Tasks) {
        var CurrentResult = await item.Invoke();
        Results.AppendLine(CurrentResult.ToString());
    }
    MessageOptions options = new MessageOptions { Duration = 2000, Message = Results.ToString(), Type = InformationType.Success };
    Application.ShowViewStrategy.ShowMessage(options);
}

A slightly modified Blazor version of this code also illustrates similar issues.

Executing Object Space Operations Inside Async Action, things that can happen

This approach still leaves the UI responsive, risking disposal of object space if the user navigates away, if that happens you will end up with an exception


protected virtual async void ActionWithAsyncModifierAndOsOperations_Execute(object sender, SimpleActionExecuteEventArgs e) {
    var Instance = GetInstance();
    var Tasks = GetTaskList();
    StringBuilder Results = new StringBuilder();
    foreach (var item in Tasks) {
        var CurrentResult = await item.Invoke();
        Results.AppendLine(CurrentResult.ToString());
    }
    Instance.Result = Results.ToString();
    ViewCommit();
    MessageOptions options = new MessageOptions { Duration = 3000, Message = Instance.Result, Type = InformationType.Success };
    Application.ShowViewStrategy.ShowMessage(options);
}

Proposed Solution

My solution utilizes a background worker to handle async operations while locking the UI thread with a loading indicator. This allows us to react to progress on the UI thread.

Async Background Worker Example

Here’s how the AsyncBackgroundWorker is set up and used:


protected virtual void AsyncActionWithAsyncBackgroundWorker_Execute(object sender, SimpleActionExecuteEventArgs e) {
    var tasks = GetTaskList();
    var worker = new AsyncBackgroundWorker

Handling Background Worker Events


protected virtual void ProcessingDone(Dictionary<int, object> results) {
    // Interact with UI and object space
}

protected virtual void OnReportProgress(int progress, string status, object result) {
    MessageOptions options = new MessageOptions { Duration = 2000, Message = status, Type = InformationType.Success };
    Application.ShowViewStrategy.ShowMessage(options);
}

Blazor Implementation

The Blazor version manages UI locking by showing a loading indicator and reporting progress through the UI thread:

source here: https://github.com/egarim/XafAsyncActions/blob/master/XafAsyncActions.Blazor.Server/Controllers/MyViewControllerBlazor.cs


protected async override void AsyncActionWithAsyncBackgroundWorker_Execute(object sender, SimpleActionExecuteEventArgs e) {
    loading.Hold("Loading");
    base.AsyncActionWithAsyncBackgroundWorker_Execute(sender, e);
}

protected async override void ProcessingDone(Dictionary<int, object> results) {
    base.ProcessingDone(results);
    loading.Release("Loading");
}

When you run this implementation, it will look like this

As you can see the task are being run on the background worker and every time a task is finish is reported back to the U.I thread where we can execute a notification (this is actually optional)

When all the tasks are finished, I hide the loading indicator, and the user can interact with the view again

I hope this article clarifies async execution in XAF. I will update the repository as new scenarios arise.

The Critical Need for AI Legislation in El Salvador: Ensuring Ethical and Innovative Growth

The Critical Need for AI Legislation in El Salvador: Ensuring Ethical and Innovative Growth

AI Integration and Future Plans

El Salvador has embarked on a remarkable journey of technological transformation under the leadership of President Nayib Bukele. Building on the momentum from its pioneering adoption of Bitcoin as legal tender, the nation is now setting its sights on integrating Artificial Intelligence (AI) into various sectors to foster innovation and growth. This article explores President Bukele’s vision for AI, the potential benefits and challenges, and the critical need for establishing robust AI legislation.

Government Vision for AI

President Bukele envisions a future where AI plays a central role in El Salvador’s development. In recent developments, he appointed Brian Roemmele, a renowned expert in voice technology and AI, as an AI advisor. Roemmele’s appointment highlights the government’s commitment to integrating AI to drive economic growth and educational opportunities, positioning El Salvador as a leader in the digital age[7][8][9].

Economic Growth: By fostering an environment conducive to AI innovation, El Salvador aims to attract tech companies and startups, thereby boosting economic growth and creating high-tech job opportunities.

Smart Governance: The integration of AI in government operations promises to enhance efficiency, transparency, and responsiveness, making public administration more effective and citizen-centric[28][30].

Global Competitiveness: Bukele’s vision includes positioning El Salvador as a leader in AI within Latin America, much like its pioneering role with Bitcoin. This involves not only adopting AI technologies but also setting standards that other countries can follow.

Potential Benefits and Challenges

The potential benefits of AI integration are immense:

Economic Benefits: AI can drive significant economic growth by improving productivity, fostering innovation, and creating new job sectors[28][30].

Social Benefits: AI can enhance the quality of life by improving healthcare, education, and public services, leading to a more inclusive and equitable society[27][29].

However, the challenges cannot be overlooked:

Ethical Concerns: Ensuring that AI systems are fair, transparent, and free from bias is crucial to prevent societal harm.

Data Privacy: Protecting the personal data of citizens is essential to maintain trust and prevent misuse.

Workforce Displacement: The transition to an AI-driven economy must be managed carefully to support workers displaced by automation through reskilling and education initiatives.

The Need for AI Legislation

To harness the full potential of AI while addressing its challenges, it is imperative to establish a comprehensive AI legal framework. This framework should cover several key areas:

1. Ethical Standards

  • Transparency: AI developers must disclose methodologies and data sources to ensure clarity and trust.
  • Accountability: Clear accountability mechanisms for AI decisions, especially in critical sectors like healthcare and finance.
  • Fairness: Measures to prevent bias and ensure equitable treatment for all users of AI systems.

2. Data Protection

  • Privacy Laws: Strengthened data privacy laws to safeguard citizens’ information.
  • Consent: Ensuring individuals have control over their data, including the ability to opt-out of AI data processing.

3. Innovation Incentives

  • Research Grants: Funding for AI research and development projects.
  • Tax Breaks: Tax incentives for companies investing in AI technologies and infrastructure.

4. Workforce Transition

  • Reskilling Programs: Programs to help workers displaced by AI acquire new skills and transition to new job opportunities in the AI sector.
  • Education Initiatives: Integrating AI and digital literacy into the national education curriculum.

5. International Cooperation

  • Standards Collaboration: Working with international bodies to adopt global AI standards and best practices.
  • Regional Partnerships: Fostering regional cooperation in AI research and development.

Conclusion

El Salvador’s journey towards technological transformation continues with the integration of AI. By setting the rules for AI through robust legislation, El Salvador can ensure that it remains at the forefront of innovation in Latin America. The proposed AI legal framework not only addresses the ethical and practical challenges of AI but also positions the country as a leader in the digital future. As El Salvador charts this new course, the commitment to innovation and responsible governance will be key to its success.

This article outlines the government’s vision for AI in El Salvador, the potential benefits and challenges, and the critical need for AI legislation. It aims to inform and engage readers, encouraging them to support and contribute to the country’s digital future.

 

Related Articles

El Salvador: Digital Transformation Initiatives

El Salvador: The Implementation of Bitcoin as Legal Tender

El Salvador’s Technological Revolution

 

El Salvador: Digital Transformation Initiatives

El Salvador: Digital Transformation Initiatives

Partnerships with Tech Giants

 

El Salvador has embarked on an ambitious journey of digital transformation, significantly bolstered by strategic partnerships with leading technology companies. These collaborations have been pivotal in advancing the country’s technological landscape across various sectors.

One notable partnership is with Google, focusing on enhancing healthcare, education, and digital government services. Google’s involvement includes the deployment of cloud services to streamline government operations and the integration of AI tools to improve healthcare delivery. Through these initiatives, El Salvador aims to enhance the efficiency and accessibility of public services, ensuring that technology benefits all citizens.

In the education sector, partnerships with tech giants are transforming learning environments. Google Classroom and other digital platforms are being integrated into schools, enabling remote learning and enhancing the quality of education. These tools not only facilitate learning during crises like the COVID-19 pandemic but also prepare students for a digital future.

 

Development of Digital Infrastructure

 

Central to El Salvador’s digital transformation is the robust development of digital infrastructure. The government has made significant investments to ensure widespread internet access, recognizing it as a cornerstone for digital inclusion. Efforts include expanding broadband coverage to rural areas and implementing 5G technology in urban centers.

Digital payment systems have also seen substantial growth. The introduction of the Chivo Wallet, a government-backed digital wallet, marked a significant step in promoting cashless transactions. This initiative aligns with the broader goal of fostering a digital economy and reducing the reliance on traditional banking systems. Moreover, the Chivo Wallet’s integration with Bitcoin and other cryptocurrencies opens new avenues for financial inclusion and innovation.

E-government platforms are another critical component of this transformation. The government has launched various online portals to streamline public services, from tax filing to business registrations. These platforms not only enhance efficiency but also reduce bureaucratic hurdles, making it easier for citizens and businesses to interact with the government.

 

Efforts to Improve Digital Literacy

 

Recognizing that technological advancements are only as effective as the population’s ability to use them, El Salvador has prioritized digital literacy. The government, in collaboration with educational institutions and private sector partners, has launched comprehensive programs aimed at improving digital skills across the population.

For the general public, initiatives include community training programs and digital literacy campaigns. These efforts focus on teaching basic computer skills, internet navigation, and the safe use of digital tools. By equipping citizens with these skills, the government aims to ensure that everyone can participate in the digital economy and access online services.

In the education sector, digital literacy is being integrated into the national curriculum. Schools are now equipped with modern technology, and teachers receive training on digital teaching methods. This approach not only prepares students for future job markets but also fosters a culture of innovation and technological proficiency from a young age.

Government employees are also a focus of digital literacy efforts. Specialized training programs have been developed to enhance the digital skills of public sector workers. These programs aim to improve the efficiency of government operations and ensure that public servants can effectively use new technologies in their daily tasks.

 

Conclusion

 

El Salvador’s digital transformation under President Nayib Bukele is a multifaceted effort encompassing strategic partnerships, infrastructure development, and comprehensive digital literacy programs. By working with tech giants like Google, investing in digital infrastructure, and prioritizing digital education, the country is laying a strong foundation for a technologically advanced future. These initiatives not only improve the quality of life for Salvadorans but also position the country as a leader in digital innovation within Latin America. As El Salvador continues to embrace digital transformation, it serves as a compelling case study for other nations seeking to navigate the complexities of the digital age.

 

Related Articles

El Salvador: The Implementation of Bitcoin as Legal Tender

El Salvador’s Technological Revolution

Embrace the Dogfood: How Dogfooding Can Transform Your Software Development Process

Embrace the Dogfood: How Dogfooding Can Transform Your Software Development Process

Hey there, fellow developers! Today, let’s talk about a practice that can revolutionize the way we create, test, and perfect our software: dogfooding. If you’re wondering what dogfooding means, don’t worry, it’s not about what you feed your pets. In the tech world, “eating your own dog food” means using the software you develop in your day-to-day operations. Let’s dive into how this can be a game-changer for us.

Why Should We Dogfood?

  • Catch Bugs Early: By using our own software, we become our first line of defense against bugs and glitches. Real-world usage uncovers issues that might slip through traditional testing. We get to identify and fix these problems before they ever reach our users.
  • Enhance Quality Assurance: There’s no better way to ensure our software meets high standards than by relying on it ourselves. When our own work depends on our product, we naturally aim for higher quality and reliability.
  • Improve User Experience: When we step into the shoes of our users, we experience firsthand what works well and what doesn’t. This unique perspective allows us to design more intuitive and user-friendly software.
  • Create a Rapid Feedback Loop: Using our software internally means continuous and immediate feedback. This quick loop helps us iterate faster, refining features and squashing bugs swiftly.
  • Build Credibility and Trust: When we show confidence in our software by using it ourselves, it sends a strong message to our users. It demonstrates that we believe in what we’ve created, enhancing our credibility and trustworthiness.

Real-World Examples

  • Microsoft: They’re known for using early versions of Windows and Office within their own teams. This practice helps them catch issues early and improve their products before public release.
  • Google: Googlers use beta versions of products like Gmail and Chrome. This internal testing helps them refine their offerings based on real-world use.
  • Slack: Slack’s team relies on Slack for communication, constantly testing and improving the platform from the inside.

How to Start Dogfooding

  • Integrate it Into Daily Work: Start by using your software for internal tasks. Whether it’s a project management tool, a communication app, or a new feature, make it part of your team’s daily routine.
  • Encourage Team Participation: Get everyone on board. The more diverse the users, the more varied the feedback. Encourage your team to report bugs, suggest improvements, and share their experiences.
  • Set Up Feedback Channels: Create dedicated channels for feedback. This could be as simple as a Slack channel or a more structured feedback form. Ensure that the feedback loop is easy and accessible.
  • Iterate Quickly: Use the feedback to make quick improvements. Prioritize issues that affect usability and functionality. Show your team that their feedback is valued and acted upon.

Overcoming Challenges

  • Avoid Bias: While familiarity is great, it can also lead to bias. Pair internal testing with external beta testers to get a well-rounded perspective.
  • Manage Resources: Smaller teams might find it challenging to allocate resources for internal use. Start small and gradually integrate more aspects of your software into daily use.
  • Consider Diverse Use Cases: Remember, your internal environment might not replicate all the conditions your users face. Keep an eye on diverse scenarios and edge cases.

Conclusion

Dogfooding is more than just a quirky industry term. It’s a powerful practice that can elevate the quality of our software, speed up our development cycles, and build stronger trust with our users. By using our software as our customers do, we gain invaluable insights that can lead to better, more reliable products. So, let’s embrace the dogfood, turn our critical eye inward, and create software that we’re not just proud of but genuinely rely on. Happy coding, and happy dogfooding! 🐶💻

Feel free to share your dogfooding experiences in the comments below. Let’s learn from each other and continue to improve our craft together!

Getting Started with Stratis Blockchain Development Quest: Running Your First Stratis Node

Getting Started with Stratis Blockchain Development Quest: Running Your First Stratis Node

Getting Started with Stratis Blockchain Development: Running Your First Stratis Node

Stratis is a powerful and flexible blockchain development platform designed to enable businesses and developers to build, test, and deploy blockchain applications with ease. If you’re looking to start developing for the Stratis blockchain, the first crucial step is to run a Stratis node. This article will guide you through the process, providing a clear and concise roadmap to get your development journey underway.

Introduction to Stratis Blockchain

Stratis offers a blockchain-as-a-service (BaaS) platform, which simplifies the development, deployment, and maintenance of blockchain solutions. Built on a foundation of the C# programming language and the .NET framework, Stratis provides an accessible environment for developers familiar with these technologies. Key features of Stratis include smart contracts, sidechains, and full node capabilities, all designed to streamline blockchain development and integration.

Why Run a Stratis Node?

Running a Stratis node is essential for several reasons:

  • Network Participation: Nodes form the backbone of the blockchain network, validating and relaying transactions.
  • Development and Testing: A local node provides a controlled environment for testing and debugging blockchain applications.
  • Decentralization: By running a node, you contribute to the decentralization and security of the Stratis network.

Prerequisites

Before setting up a Stratis node, ensure you have the following:

  • A computer with a modern operating system (Windows, macOS, or Linux).
  • .NET Core SDK installed.
  • Sufficient disk space (at least 10 GB) for the blockchain data.
  • A stable internet connection.

Step-by-Step Guide to Running a Stratis Node

1. Install .NET Core SDK

First, install the .NET Core SDK, which is necessary to run the Stratis Full Node. You can download it from the official .NET Core website. Follow the installation instructions for your specific operating system. I recommend having all DotNetCore SDKs because the source code for most of the Stratis solutions target really an old framework version like.NET Core 2.1 so it’s better to have multiple choices of framework in case you need to re-target for compatibility

.NET Core Versions

  • .NET Core 3.1 (LTS)
  • .NET Core 3.0
  • .NET Core 2.2
  • .NET Core 2.1 (LTS)
  • .NET Core 2.0
  • .NET Core 1.1
  • .NET Core 1.0

Installation Links

Download .NET Core SDKs

2. Clone the Stratis Full Node Repository

Next, clone the Stratis Full Node repository from GitHub. Open a terminal or command prompt and run the following command:

git clone https://github.com/stratisproject/StratisFullNode.git

This command will download the latest version of the Stratis Full Node source code to your local machine.

3. Build the Stratis Full Node

Navigate to the directory where you cloned the repository:

cd StratisFullNode

Now, build the Stratis Full Node using the .NET Core SDK:

dotnet build

This command compiles the source code and prepares it for execution.

4. Run the Stratis Full Node

Once the build process is complete, you can start the Stratis Full Node. Use the following command to run the node:

cd Stratis.StraxD
dotnet run -testnet

This will initiate the Stratis node, which will start synchronizing with the Stratis blockchain network.

5. Verify Node Synchronization

After starting the node, you need to ensure it is synchronizing correctly with the network. You can check the node’s status by visiting the Stratis Full Node’s API endpoint in your web browser:

http://localhost:37221/api

here is more information about the possible ports for the API depending on which network you want to use (test or main) and which command did you use to start up the API

Swagger
To run the API in a specific port you can use the following code

StraxTest (dotnet run -testnet -apiport=38221)

http://localhost:38221/Swagger/index.html

StraxTest

http://localhost:27103/Swagger

StraxMain

http://localhost:17103/Swagger

You should see a JSON response indicating the node’s current status, including its synchronization progress.

Conclusion

Congratulations! You have successfully set up and run your first Stratis node. This node forms the foundation for your development activities on the Stratis blockchain. With your node up and running, you can now explore the various features and capabilities of the Stratis platform, including deploying smart contracts, interacting with sidechains, and building blockchain applications.

As you continue your journey, remember that the Stratis community and its comprehensive documentation are valuable resources. Engage with other developers, seek guidance, and contribute to the growing ecosystem of Stratis-based solutions. Happy coding!

 

Previous articles

Discovering the Simplicity of C# in Blockchain Development with Stratis | Joche Ojeda

 

An Introduction to Dynamic Proxies and Their Application in ORM Libraries with Castle.Core

An Introduction to Dynamic Proxies and Their Application in ORM Libraries with Castle.Core

Castle.Core: A Favourite Among C# Developers

Castle.Core, a component of the Castle Project, is an open-source project that provides common abstractions, including logging services. It has garnered popularity in the .NET community, boasting over 88 million downloads.

Dynamic Proxies: Acting as Stand-Ins

In the realm of programming, a dynamic proxy is a stand-in or surrogate for another object, controlling access to it. This proxy object can introduce additional behaviours such as logging, caching, or thread-safety before delegating the call to the original object.

The Impact of Dynamic Proxies

Dynamic proxies are instrumental in intercepting method calls and implementing aspect-oriented programming. This aids in managing cross-cutting concerns like logging and transaction management.

Castle DynamicProxy: Generating Proxies at Runtime

Castle DynamicProxy, a feature of Castle.Core, is a library that generates lightweight .NET proxies dynamically at runtime. It enables operations to be performed before and/or after the method execution on the actual object, without altering the class code.

Dynamic Proxies in the Realm of ORM Libraries

Dynamic proxies find significant application in Object-Relational Mapping (ORM) Libraries. ORM allows you to interact with your database, such as SQL Server, Oracle, or MySQL, in an object-oriented manner. Dynamic proxies are employed in ORM libraries to create lightweight objects that mirror database records, facilitating efficient data manipulation and retrieval.

Here’s a simple example of how to create a dynamic proxy using Castle.Core:


using Castle.DynamicProxy;

public class SimpleInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        Console.WriteLine("Before target call");
        try
        {
            invocation.Proceed(); //Calls the decorated instance.
        }
        catch (Exception)
        {
            Console.WriteLine("Target threw an exception!");
            throw;
        }
        finally
        {
            Console.WriteLine("After target call");
        }
    }
}

public class SomeClass
{
    public virtual void SomeMethod()
    {
        Console.WriteLine("SomeMethod in SomeClass called");
    }
}

public class Program
{
    public static void Main()
    {
        ProxyGenerator generator = new ProxyGenerator();
        SimpleInterceptor interceptor = new SimpleInterceptor();
        SomeClass proxy = generator.CreateClassProxy(interceptor);
        proxy.SomeMethod();
    }
}

Conclusion

Castle.Core and its DynamicProxy feature are invaluable tools for C# programmers, enabling efficient handling of cross-cutting concerns through the creation of dynamic proxies. With over 825.5 million downloads, Castle.Core’s widespread use in the .NET community underscores its utility. Whether you’re a novice or an experienced C# programmer, understanding and utilizing dynamic proxies, particularly in ORM libraries, can significantly boost your programming skills. Dive into Castle.Core and dynamic proxies in your C# projects and take your programming skills to the next level. Happy coding!