Windows Forms
68 TopicsUsing Entra ID Authentication with Arc-Enabled SQL Server in a .NET Windows Forms Application
Introduction: This guide demonstrates how to securely connect a .NET Framework Windows Forms application to an Arc-enabled SQL Server 2022 instance using Entra ID (Azure AD) authentication. It covers user authentication, token management, and secure connection practices, with code samples and screenshots. In many modern applications, it is common practice to use an application web service to mediate access to SQL Server. This approach can offer several advantages, such as improved security, scalability, and centralized management of database connections. However, there are scenarios where directly connecting to SQL Server is more appropriate. This guide focuses on such scenarios, providing a solution for applications that need direct access to SQL Server. This model is particularly useful for applications like SQL Server Management Studio (SSMS), which require direct database connections to perform their functions. By using Entra ID authentication, we can ensure that these direct connections are secure and that user credentials are managed efficiently. By following the steps outlined in this guide, developers can ensure secure and efficient connections between their .NET Windows Forms applications and Arc-enabled SQL Server instances using Entra ID authentication. This approach not only enhances security but also simplifies the management of user credentials and access tokens, providing a robust solution for modern application development. SAMPLE CODE: GitHub Repository Prerequisites Arc-enabled SQL Server 2022/2025 configured for Entra ID authentication Entra ID (Azure AD) tenant and app registration .NET Framework 4.6.2 Windows Forms application (Not required .NET version, only what the solution is based on) Microsoft.Identity.Client, Microsoft.Data.SqlClient NuGet packages Application Overview User authenticates with Entra ID Token is acquired and used to connect to SQL Server Option to persist token cache or keep it in memory Data is retrieved and displayed in a DataGridView Similar setup to use SSMS with Entra ID in articles below. Windows Form Sample Check User Button shows the current user The Connect to Entra ID at Login button will verify if you are logged in and try to connect to SQL Server. If the user is not logged in, an Entra ID authentication window will be displayed or ask you to log in. Once logged in it shows a Connection successful message box stating the connection to the database was completed. The Load Data button queries the Adventure Works database Person table and loads the names into the datagridview. The Cache Token to Disk checkbox option either caches to memory when unchecked and would require reauthentication after the application closes, or the option to cache to disk the token to be read on future application usage. If the file is cached to disk, the location of the cached file is (C:\Users\[useraccount]\AppData\Local). This sample does not encrypt the file which is something that would be recommended for production use. This code uses MSAL (Microsoft Authentication Library) to authenticate users in a .NET application using their Microsoft Entra ID (Azure AD) credentials. It configures the app with its client ID, tenant ID, redirect URI, and logging settings to enable secure token-based authentication. //Application registration ClientID, and TenantID are required for MSAL authentication private static IPublicClientApplication app = PublicClientApplicationBuilder.Create("YourApplicationClientID") .WithAuthority(AzureCloudInstance.AzurePublic, "YourTenantID") .WithRedirectUri("http://localhost") .WithLogging((level, message, containsPii) => Debug.WriteLine($"MSAL: {message}"), LogLevel.Verbose, true, true) .Build(); This method handles user login by either enabling persistent token caching or setting up temporary in-memory caching, depending on the input. It then attempts to silently acquire an access token for Azure SQL Database using cached credentials, falling back to interactive login if no account is found. private async Task<AuthenticationResult> LoginAsync(bool persistCache) { if (persistCache) TokenCacheHelper.EnablePersistence(app.UserTokenCache); else { app.UserTokenCache.SetBeforeAccess(args => { }); app.UserTokenCache.SetAfterAccess(args => { }); } string[] scopes = new[] { "https://database.windows.net//.default" }; var accounts = await app.GetAccountsAsync(); if (accounts == null || !accounts.Any()) return await app.AcquireTokenInteractive(scopes).ExecuteAsync(); var account = accounts.FirstOrDefault(); return await app.AcquireTokenSilent(scopes, account).ExecuteAsync(); } Connecting to SQL Server with Access Token This code connects to an Azure SQL Database using a connection string and an access token obtained through MSAL authentication. It securely opens the database connection by assigning the token to the SqlConnection object, enabling authenticated access without storing credentials in the connection string. This sample uses a self-signed certificate, in production always configure SQL Server protocols with a certificate issued by a trusted Certificate Authority (CA). TrustServerCertificate=True bypasses certificate validation and can allow MITM attacks. For production, use a trusted Certificate Authority and change TrustServerCertificate=True to TrustServerCertificate=False. Configure Client Computer and Application for Encryption - SQL Server | Microsoft Learn string connectionString = $"Server={txtSqlServer.Text};Database=AdventureWorks2019;Encrypt=True;TrustServerCertificate=True;"; var result = await LoginAsync(checkBox1.Checked); using (var conn = new SqlConnection(connectionString)) { conn.AccessToken = result.AccessToken; conn.Open(); // ... use connection ... } Fetching Data into DataGridView This method authenticates the user and connects to an Azure SQL Database using an access token, and runs a SQL query to retrieve the top 1,000 names from the Person table. It loads the results into a DataTable, which can then be used for display or further processing in the application. private async Task<DataTable> FetchDataAsync() { var dataTable = new DataTable(); var result = await LoginAsync(checkBox1.Checked); using (var conn = new SqlConnection(connectionString)) { conn.AccessToken = result.AccessToken; await conn.OpenAsync(); using (var cmd = new SqlCommand("SELECT TOP (1000) [FirstName], [MiddleName], [LastName] FROM [AdventureWorks2019].[Person].[Person]", conn)) using (var reader = await cmd.ExecuteReaderAsync()) { dataTable.Load(reader); } } return dataTable; } Configure Azure Arc SQL Server to use Entra ID authentication Using SQL Server 2022 follow the instructions here to setup the key vault and certificate when configuring. This article can also be used to configure SSMS to use Entra ID authentication. Detailed steps located here: Set up Microsoft Entra authentication for SQL Server - SQL Server | Microsoft Learn Using SQL Server 2025 the setup is much easier as you do not need to configure a Key Vault, or certificates as it is relying on using the managed identity for the authentication. Entra ID App Registration Steps Register a new app in Azure AD Add a redirect URI (http://localhost) Add API permissions for https://database.windows.net/.default On the Entra ID app registration, click on API Permissions. Add the API’s for Microsoft Graph: User.Read.All Application.Read.All Group.Read.All Add a permission for Azure SQL Database. If Azure SQL database is not shown in the list ensure that the Resource Provider is registered for Microsoft.Sql. Choose Delegated permissions and select user_impersonation, Click Add permission for the Azure SQL Database. NOTE: Once the permissions are added ensure that you grant admin consent on the items. Security Considerations Never store client secrets in client apps Use in-memory token cache for higher security, or encrypted disk cache for convenience Use user tokens for auditing and least privilege References Microsoft Docs: Azure AD Authentication for SQL Server MSAL.NET Documentation Arc-enabled SQL Server Documentation Conclusion: By following the steps outlined in this guide, developers can ensure secure and efficient connections between their .NET Windows Forms applications and Arc-enabled SQL Server instances using Entra ID authentication. This approach not only enhances security but also simplifies the management of user credentials and access tokens, providing a robust solution for modern application development. *** Disclaimer *** The sample scripts are not supported under any Microsoft standard support program or service. The sample scripts are provided AS IS without warranty of any kind. Microsoft further disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you. In no event shall Microsoft, its authors, or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts or documentation, even if Microsoft has been advised of the possibility of such damages.Versioning my Maui Android App
Previously the way to define version code for Android in Maui .csproj file was like this: <!-- Versions --> <ApplicationVersion>3.1.2</ApplicationVersion> <AndroidVersionCode>3</AndroidVersionCode> With the new release of Visual Studio Preview, this has changed to: <ApplicationVersion>3</ApplicationVersion> It works, from Visual Studio, I can bundle a new .aab package (see image below). We see the version code is defined to 3. Unfortunately the version is defined to 1.0.0 and I don't know how to change this. ...when imported on the Google Play Console, it look like this: Unfortunately, when imported I only see the versionCode 3 (which is defined in the .csproj file as ApplicationVersion). What about the versionName (in parentheses) ? Nothing is planned in the .csproj file ? When imported on the Google Play Console, I don't want to have 3 (1.0.0) but I want 3 (3.1.2)... https://developer.android.com/studio/publish/versioning versionCode — A positive integer used as an internal version number. versionName — A string used as the version number shown to users.27KViews0likes8CommentsGraph API getAsync() in C#
This is cross posted in Azure as well. If I use graph in a console application I get the information that I request. Such as test = await graphClient.Users.GetAsync(); If I try this in a WebMethod in the code behind of a page or in an .asmx, it never returns with the data. I know this has been mentioned before in many forums, but I did not have issues in V1.0 of the SDK. When I try to use V5+ I can't seem to get the information back. Any ideas on overcoming the issue? Any help would be great.67Views0likes0CommentsA strange run issue
I encountered a strange operational issue. After packaging my software in. msixbundle format, I installed and tested it locally. When clicking on the program icon in the start menu, an error occurred and a DLL could not be found. However, after confirmation, the main interface of the program can be opened. In fact, this DLL and the program's exe are in the same directory. But in the program files \ windows app \ myapp directory, clicking on this exe will allow the program to execute normally. My program is a. NET 8 winform program. How should I do?38Views0likes0CommentsHow can I find CPE of dll in .NET?
For example, System.IO.Packaging 8.0.0 hav weakness. https://www.nuget.org/packages/System.IO.Packaging/8.0.0 I have Vulnerability Management tool, I can receive notice of the weakness by registering CPE. I want to obtain CPE of System.IO.Packaging, but where is it available from? Thanks65Views0likes0CommentsEnviar archivo PDF a contacto de WhattsApp con C Sharp.
Hola, una consulta, tengo desarrollada una aplicación de escritorio Windows Forms con C Sharp y me están requiriendo que desde la misma se pueda enviar documentos PDF a contactos de WhttsApp. Estuve buscando información en la web, pero no encontré información certera. Desde ya muchas gracias. Saludos.100Views0likes0CommentsMAUI APP does not run, android-API34 issue ?
Hi everyone, i'm facing a problem using dotnet 8.0 and Maui. I read that an android api is automatically associated to a dotnet version. So for .Net 8.0 the android api is 34.0 I installed the Maui workload and created a new project, then i ran(build) it without any modifications and all the necessay packages installed without issues But when i go to the generated bin folder and run windows app it does'nt even show up, For android part i installed the signed-apk in virtual device and here is what i get : I found somewhere that this was the api 34 issue, i tried to install .Net 7.0-API 33 and .Net 9.0-API 35.0 but facing the same problem. What should i do now... please help me THNKS!!!587Views0likes2CommentsChanging TCP Receive Window in C#
Hi, I have an embedded board with limited RAM (25 KB) and have defined two TCP sockets on it. I can communicate effectively with my Windows application, which I developed in C#. However, I encounter a problem when the Ethernet cable is abruptly disconnected. In this situation, due to the TCP timeout and retry procedure, the embedded board runs out of memory and stops functioning. After consulting with an expert from the company, I learned that this issue is related to the TCP receive window on the PC side (since the receive window on my embedded board is already reduced). They suggested that if I can decrease the TCP receive window for my socket in C#, it may help prevent my board from becoming unresponsive. And they are correct, because when I replaced the PC with another embedded board, this problem did not occur. I would greatly appreciate any guidance you can provide on how to reduce the TCP receive window just for the connected socket in C# not all adapters window size. Thank you!196Views0likes0CommentsForm borders appearing different in visual studio and when the application is running
Good morning I can't understand why in my application that I made some time ago in VB.NET the edges of the forms are seen differently, in visual studio they are one way and when I start the application they are seen in another way. I attach two screenshots to better understand what I mean. If anyone knows what may have happened and can give me some advice on how to resolve it. Thank you Fabrizio443Views0likes1Comment