c#
6 TopicsC# MIP SDK v1.17.x - AccessViolationException on creation of MIPContext in 64-bit console app
I first logged this on https://stackoverflow.com/questions/79746967/accessviolationexception-when-creating-mipcontext-after-upgrade-to-v1-17 and the responses there have indicated I should raise with Microsoft a a likely bug, but I don't see a clear route to reporting other than here so any response would be appreciated, even if just to direct me to the appropriate reporting location. I've built a simple console app that demonstrates this issue that I'm happy to provide but we're seeing an issue with the 1.17.x version of the C# MIP SDK where an AccessViolationException is being thrown when trying to create an MIP context object. This is for a .Net Framework 4.8 console app built in 64-bit configuration, deployed to a Windows Server 2016 with the latest VC++ redistributable (14.44.35211) installed (both x86 and x64 versions), though we've seen the same on Windows Server 2019 and 2022. When the same app is built in 32-bit and deployed to the same environment the exception doesn't occur. The following code is what I've used to repro the issue: MIP.Initialize(MipComponent.File); var appInfo = new ApplicationInfo { ApplicationId = string.Empty, ApplicationName = string.Empty, ApplicationVersion = string.Empty }; var diagnosticConfiguration = new DiagnosticConfiguration { IsMinimalTelemetryEnabled = true }; var mipConfiguration = new MipConfiguration(appInfo, "mip_data", LogLevel.Info, false, CacheStorageType.InMemory) { DiagnosticOverride = diagnosticConfiguration }; //Expect BadInputException here due to empty properties of appInfo //When built as part of a 64-bit console app this causes AccessViolationException instead MIP.CreateMipContext(mipConfiguration); The AccessViolationException crashes the console app, with the following logged in the Windows Event Log: Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: System.AccessViolationException at Microsoft.InformationProtection.Internal.SdkWrapperPINVOKE.MipContext_Create__SWIG_1(System.Runtime.InteropServices.HandleRef) at Microsoft.InformationProtection.Internal.MipContext.Create(Microsoft.InformationProtection.Internal.MipConfiguration) at Microsoft.InformationProtection.Utils.MIPHelper.CreateMipContext(Microsoft.InformationProtection.MipConfiguration) The issue doesn't occur with the latest 1.16 version (1.16.149) of the SDK but does appear to be in all versions of the 1.17 release. Library: C# MIP SDK v1.17.x Target App: .Net Framework 4.8 console app Deployed OS: Windows Server 2016, 2019 and 2022 (With .Net Framework 4.8 and latest VC++ redist installed)26Views0likes0CommentsIntroducing AzureImageSDK — A Unified .NET SDK for Azure Image Generation And Captioning
Hello 👋 I'm excited to share something I've been working on — AzureImageSDK — a modern, open-source .NET SDK that brings together Azure AI Foundry's image models (like Stable Image Ultra, Stable Image Core), along with Azure Vision and content moderation APIs and Image Utilities, all in one clean, extensible library. While working with Azure’s image services, I kept hitting the same wall: Each model had its own input structure, parameters, and output format — and there was no unified, async-friendly SDK to handle image generation, visual analysis, and moderation under one roof. So... I built one. AzureImageSDK wraps Azure's powerful image capabilities into a single, async-first C# interface that makes it dead simple to: 🎨 Inferencing Image Models 🧠 Analyze visual content (Image to text) 🚦 Image Utilities — with just a few lines of code. It's fully open-source, designed for extensibility, and ready to support new models the moment they launch. 🔗 GitHub Repo: https://github.com/DrHazemAli/AzureImageSDK Also, I've posted the release announcement on the https://github.com/orgs/azure-ai-foundry/discussions/47 👉🏻 feel free to join the conversation there too. The SDK is available on NuGet too. Would love to hear your thoughts, use cases, or feedback!106Views1like0CommentsIntroducing AzureSoraSDK: A Community C# SDK for Azure OpenAI Sora Video Generation
Hello everyone! I’m excited to share the first community release of AzureSoraSDK, a fully-featured .NET 6+ class library that makes it incredibly easy to generate AI-driven videos using Azure’s OpenAI Sora model and even improve your prompts on the fly. 🔗 Repository: https://github.com/DrHazemAli/AzureSoraSDK210Views0likes2CommentsSetting up Code Coverage data in Azure DevOps Pipeline, C# .NET 9
Hello everyone, I would like some assistance with my Azure DevOps pipeline. I am trying to set up Tasks in my Azure DevOps pipeline to collect Code Coverage results, after running UTs using the VsTest Task, to then have a Powershell Task in the Pipeline write to a SQL db the contents of those metrics. The main issue I am encountering is actually finding the published results after the UTs successfully run. I have set up Tasks to publish the results, then find them & then insert, but the publish doesn't seem to actually publish to the directory I specify, or if it does publish, I cannot see where to. Here are the Tasks I currently have set-up. Task to run UTs: steps: - task: VSTest@2 displayName: 'VsTest - testAssemblies' inputs: testAssemblyVer2: | **\$(BuildConfiguration)\*\*test*.dll !**\obj\** runSettingsFile: '$/B3API/Main/B3API.Tests/codecoverage.runsettings' runInParallel: true runTestsInIsolation: false codeCoverageEnabled: true platform: '$(BuildPlatform)' configuration: '$(BuildConfiguration)' failOnMinTestsNotRun: true codecoverage.runsettings file: <?xml version="1.0" encoding="utf-8"?> <RunSettings> <DataCollectionRunSettings> <DataCollectors> <DataCollector friendlyName="Code Coverage"> <Configuration> <Format>cobertura</Format> </Configuration> </DataCollector> </DataCollectors> </DataCollectionRunSettings> </RunSettings> Task to publish results: steps: - task: PublishCodeCoverageResults@2 displayName: 'Publish code coverage results' inputs: summaryFileLocation: '$(System.DefaultWorkingDirectory)/**/coverage.cobertura.xml' pathToSources: '$(System.DefaultWorkingDirectory)/**/coverage' Task to find published file & store into variable: steps: - powershell: | $coverageFile = "$(System.DefaultWorkingDirectory)/**/coverage.cobertura.xml" [xml]$coverageData = Get-Content $coverageFile $coveragePercentage = $coverageData.coverage.@line-rate # Store the coverage data in a variable Write-Host "##vso[task.setvariable variable=coveragePercentage]$coveragePercentage" displayName: 'Store Coverage in variable' The main issue it the Task to publish, it does not publish the results, I think it is due to not finding them in the first place. Thank you for taking the time to read my post, any help would be greatly appreciated, thanks!162Views0likes3CommentsPet project on SQL Server 2022 platform
Hello, world! I would like to share my pet project on SQL Server 2022 platform. I have created a DWH solution that includes many MS's best practices and interesting features such us: ETL process with data cleansing and MDM that easy expand Documentation CI/CD Functional ETL test Ready analytical templates Time intelligence New & returning customers Cluster customers based on spending volume Product ABC classification Basket analysis Events in progress https://dev.azure.com/zinykov/NorthwindBI Unfortunately in SQL Server 2025 will be no DQS & MDS...25Views0likes0CommentsFire-and-Forget Methods in C# — Best Practices & Pitfalls
When building modern applications, there are often situations where you want to perform tasks in the background without holding up the main flow of your application. This is where “fire-and-forget” methods come into play. In C#, a fire-and-forget method allows you to run a task without awaiting its completion. A common use case is sending a confirmation email after creating a user, but this also brings some limitations, particularly when dealing with scoped services. In this blog, we’ll walk through an example and explain why scoped services, like database contexts or HTTP clients, cannot be accessed in fire-and-forget methods. Why Fire-and-Forget? Fire-and-forget is useful in situations where you don’t need the result of an operation immediately, and it can happen in the background, for example: Sending emails Logging Notification sending Here’s a common scenario where fire-and-forget comes in handy: sending a welcome email after a user is created in the system. public async Task<ServiceResponse<User?>> AddUser(User user) { var response = new ServiceResponse<User?>(); try { // User creation logic (password hashing, saving to DB, etc.) _context.Users.Add(user); await _context.SaveChangesAsync(); // Fire-and-forget task to send an email _ = Task.Run(() => SendUserCreationMail(user)); response.Data = user; response.Message = user.FirstName + " added successfully"; } catch (Exception ex) { // Error handling } return response; } The method SendUserCreationMail sends an email after a user is created, ensuring that the main user creation logic isn’t blocked by the email-sending process. private async Task SendUserCreationMail(int id) { // This will throw an exception be _context is an scoped service var user = await _context.Users.FindAsync(id); var applicationUrl = "https://blogs.shahriyarali.com" string body = $@" <body> <p>Dear {user.FirstName},</p> <p>A new user has been created in the system:</p> <p>Username: {user.Username}</p> <p>Email: {user.Email}</p> <p>Welcome to the system! Please use the provided username and email to log in. You can access the system by clicking on the following link:</p> <p><a href='{applicationUrl}'>{applicationUrl}</a></p> <p>Best regards,</p> <p>Code With Shahri</p> </body>"; var mailParameters = new MailParameters { Subject = $"New User Created - {user.Username}", Body = body, UserEmails = new List<UserEmail> { new() { Name = user.FirstName, Email = user.Email } } }; await _mailSender.SendEmail(mailParameters); } In the code above, the SendUserCreationMail method is executed using Task.Run(). Since it's a fire-and-forget task, we don’t await it, allowing the user creation process to complete without waiting for the email to be sent. The Problem with Scoped Services A major pitfall with fire-and-forget tasks is that you cannot reliably access scoped services (such as DbContext or ILogger) within the task. This is because fire-and-forget tasks continue to run after the HTTP request has been completed, and by that point, scoped services will be disposed of. For example, if _mailSender was scoped services, they could be disposed of before the SendUserCreationMail task completes, leading to exceptions. Why Can’t We Access Scoped Services? Scoped services have a lifecycle tied to the HTTP request in web applications. Once the request ends, these services are disposed of, meaning they are no longer available in any background task that wasn’t awaited within the request lifecycle. In the example above, since the fire-and-forget email sending isn’t awaited, attempting to use scoped services will throw an ObjectDisposedException. To safely access scoped services in a fire-and-forget method, you can leverage IServiceScopeFactory to manually create a service scope, ensuring that the services are available for the task. private async Task SendUserCreationMail(int id) { // Create a service scope. using var scope = _serviceScopeFactory.CreateScope(); var _context = scope.ServiceProvider.GetRequiredService<DataContext>(); var user = await _context.Users.FindAsync(id); var applicationUrl = "https://blogs.shahriyarali.com" string body = $@" <body> <p>Dear {user.FirstName},</p> <p>A new user has been created in the system:</p> <p>Username: {user.Username}</p> <p>Email: {user.Email}</p> <p>Welcome to the system! Please use the provided username and email to log in. You can access the system by clicking on the following link:</p> <p><a href='{applicationUrl}'>{applicationUrl}</a></p> <p>Best regards,</p> <p>Code With Shahri</p> </body>"; var mailParameters = new MailParameters { Subject = $"New User Created - {user.Username}", Body = body, UserEmails = new List<UserEmail> { new() { Name = user.FirstName, Email = user.Email } } }; await _mailSender.SendEmail(mailParameters); } Conclusion Fire-and-forget methods in C# are useful for executing background tasks without blocking the main application flow, but they come with their own set of challenges, particularly when working with scoped services. By leveraging techniques like IServiceScopeFactory, you can safely access scoped services in fire-and-forget tasks without risking lifecycle management issues. Whether you're sending emails, logging, or processing notifications, ensuring proper resource management is crucial to prevent errors like ObjectDisposedException. Always weigh the pros and cons of fire-and-forget and consider alternative approaches like background services or message queuing for more robust solutions in larger systems. To explore more on this topic, you can check out the following resources on Microsoft Learn: Task.Run Method Task asynchronous programming model9.9KViews2likes2Comments