ASP.NET Core
191 Topics[ASP.NET CORE] Exchange Web Services Throw HTTP 401 When Called from IIS
Hi, Currently, I can't get Microsoft.Exchange.WebServices to work with Exchange 2019 On-Premise. Send Email feature is working OK on Development but as soon I deployed it to IIS, it stopped working with following error: Microsoft.Exchange.WebServices.Data.ServiceRequestException: The request failed. The remote server returned an error: (401) Unauthorized. ---> System.Net.WebException: The remote server returned an error: (401) Unauthorized. at System.Net.HttpWebRequest.GetResponse() at Microsoft.Exchange.WebServices.Data.EwsHttpWebRequest.Microsoft.Exchange.WebServices.Data.IEwsHttpWebRequest.GetResponse() at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.GetEwsHttpWebResponse(IEwsHttpWebRequest request) --- End of inner exception stack trace --- at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.GetEwsHttpWebResponse(IEwsHttpWebRequest request) at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ValidateAndEmitRequest(IEwsHttpWebRequest& request) at Microsoft.Exchange.WebServices.Data.SimpleServiceRequestBase.InternalExecute() at Microsoft.Exchange.WebServices.Data.MultiResponseServiceRequest`1.Execute() at Microsoft.Exchange.WebServices.Data.ExchangeService.InternalCreateItems(IEnumerable`1 items, FolderId parentFolderId, Nullable`1 messageDisposition, Nullable`1 sendInvitationsMode, ServiceErrorHandling errorHandling) at Microsoft.Exchange.WebServices.Data.ExchangeService.CreateItem(Item item, FolderId parentFolderId, Nullable`1 messageDisposition, Nullable`1 sendInvitationsMode) at Microsoft.Exchange.WebServices.Data.Item.InternalCreate(FolderId parentFolderId, Nullable`1 messageDisposition, Nullable`1 sendInvitationsMode) at Microsoft.Exchange.WebServices.Data.EmailMessage.InternalSend(FolderId parentFolderId, MessageDisposition messageDisposition) I'm using same Exchange Settings (URL, Credentials, etc.) for both instance but it is only worked on Development. My Site is using App Pool User which is registered on Exchange Mailbox Users. How to fix this issue? Thanks in advance. Best Regards, Henoch32Views0likes0CommentsDeploy your ASP.NET Core Web API with the help of GitHub Copilot for Azure in Visual Studio Code.
Introducing GitHub Copilot for Azure, your personal assistant to streamline the deployment process. It provides you with clear, step-by-step instructions to deploy your applications and assists with troubleshooting, making your development journey smoother and more efficient. In this blog, we’ll explore how to deploy an ASP.NET Core API to Azure using GitHub Copilot for Azure in Visual Studio Code. By leveraging Copilot’s AI capabilities, I’ll guide it with prompts to streamline the deployment process. Together, we’ll learn how to transform a locally developed API into a cloud-hosted solution with ease. Prerequisites An Azure account and a subscription. Create Azure for free or pay as you go A GitHub account and GitHub Copilot Subscription. creating-an-account-on-GitHub and quick start on copilots Visual Studio code. See more info on setting up vs code GitHub Copilot and GitHub Copilot Chat Extension. Set up GitHub Copilot in VS Code and Getting started with Copilot Chat in VS Code .NET SDK. Download it here, C# Dev-kit Extension in VS Code. More on C# Dev-kit Prepare I will be deploying the TodoApi developed with ASP.NET Core. The source code is available on GitHub. Follow these steps to have the project on your local machine. Head to the GitHub repo: Github-Copilot-for-Azure-TodoApi-Sample Clone the Repository on your terminal or download as Zip: git clone https://github.com/kemboi590/Github-Copilot-for-Azure-TodoApi-Sample-.git Change directory to the cloned folder: cd Github-Copilot-for-Azure-TodoApi-Sample- Install required Packages: dotnet restore Open with Visual Studio Code: code . Here is an illustration of the steps: Run the application - Open the inbuilt terminal on Visual Studio Code and type the following: dotnet run The API is now running and we can test it using REST Client. Calling REST APIs From the IDE Install the rest client extension. - Open the extension and search for Rest Client and install it. Open TodoApi.http file and start testing the routes: GitHub Copilot Set up When you install GitHub Copilot Extension, you also get GitHub Copilot Chat, a conversational extension that provides conversational AI assistance Go to extensions Search for GitHub Copilot Install GitHub Copilot for Azure GitHub Copilot for Azure extension is designed to help streamline the process of developing for Azure. On extensions, search for GitHub Copilot for Azure Install the extension Start your Conversation with GitHub Copilot for Azure extension Open the chat, use the shortcut keys: ctr + shift + I or open chat by clicking on the chat Icon. To use GitHub Copilot for Azure use azure then describe what you want it to help you with. I will share with you my prompts that I am using so that you can use them as well. Note: Your GitHub Copilot for Azure may not give the same output as mine. Here are the steps to Deploy our WebApp. Describe what you want GitHub Copilot for Azure to help you with. - Give a clear information so that the copilot will get to respond better. - Try this prompt: @Azure I have developed an ASP.NET Core web API using Visual Studio Code, which is a simple TodoAPI with CRUD Functionalities with no database, I would like to deploy it on azure with your help because I have no experience. Which services should I use and which options do I have to have it on azure - GitHub Copilot for Azure Suggest that for an API, we should use Azure App Services Let’s ask for more details @Azure to deploy Azure App services on Visual Studio Code, which are the available options? We now have three options, o Using Visual Studio Code Extension – App Service Extension o Manual Process – On Azure Portal o Automated CI/CD Pipeline on GitHub App Service Extension - I will go with the first Option (Using Visual Studio Code– App Service Extension) Asking for more steps I will ask GitHub Copilot to give me some steps I will use to deploy using App Service Extension @Azure Guide me on the steps using App Service Extension - Open the extensions and install App Service Extension - You will be requested to sign in to your azure account. Ensure you have azure subscription so that you can be able to deploy your API. Working with Azure tools - You will note that Azure icon is available is the side bar - Click on it and you will see the App Services under your subscription. Create an App Service Web App from the available options - Click on App Service and click on Create button (+) to create an App Service Web App. Web App Name - Give a unique name of your new web app and click Enter - I will name mine azure-copilot-demo Choose Runtime Stack - If you are following along with TodoApi project, select .NET 9 and click Enter. Select Pricing Tier Let’s ask copilot of these pricing tiers: @Azure While selecting the pricing tiers, i see three options. Free F1 Basic B1 Premium P1V2 Which one do I select I will select Basic (B1) because I consider my project small-to-medium applications and low-traffic production workloads. Web App created on the Terminal for Azure - It will take some few seconds for the web app to be created Publish your App - Want to know why should you publish your project? - Let’s ask GitHub copilot for Azure for clarification: @Azure what does this command do? - Open the terminal on the folder with the project and type the following command: dotnet publish -c Release -o ./bin/Publish New bin/publish Folder has been created - The folder contains our project which is now ready to deploy Deploy - Right Click on the new web app (azure-copilot-demo) on the list and choose deploy to web app - Browse the /bin/publish folder and select it: Deployment success - It will take some few mins for the Web App to be deployed. Check on your terminal for Azure. - Wait for some time then your web pp will be running on Azure. Working with deployed Web App - I will also use REST Client to test the deployed web App on Visual Studio Code. - The end pot I will be using will be: https://azure-copilot-demo.azurewebsites.net/ - Without starting the server this time, replace the Host Address with the one you got after deploying the web App. POST Request: - Test the other routes and they should all be working just fine. Conclusion We have been able to deploy our TodoApi with the help of GitHub Copilot for Azure. I hope you had a great time following a long and were able to deploy your application as well. You are not limited to deploying the Web Apps alone with the help of GitHub Copilot for Azure. Feel free to explore other services and remember to share feedback. Resources Get started with GitHub Copilot for Azure Preview Get started with GitHub Copilot Training Module on Microsoft Learn Example prompts for learning about Azure and your application with GitHub Copilot for Azure Preview368Views2likes0CommentsSeamless File Management in ASP.NET Core: Azure Blob Storage with Configurable Local Mode
Setting up the Project Before we dive into the implementation, let’s set up the basic structure: Create an ASP.NET Core Web API project. Add the Azure.Storage.BlobsNuGet Package for Azure Blob Storage integration. Update appsettings.json to include storage configurations: "Storage": { "Mode": "Local", "BlobStorage": { "ConnectionString": "YourAzureBlobStorageConnectionString", "ContainerName": "YourContainerName" } } Mode: Determines whether to use Local or Azure Blob Storage. ConnectionString and ContainerName: Azure Blob Storage details. Implementing the Storage Service Here is a custom StorageService that handles file uploads, deletions, and downloads. It dynamically decides the storage location based on the configuration mode. public class StorageService : IStorageService { private readonly IConfiguration _configuration; private readonly IHttpContextAccessor _httpContextAccessor; private readonly string _storageMode; public StorageService(IConfiguration configuration, IHttpContextAccessor httpContextAccessor) { _configuration = configuration; _httpContextAccessor = httpContextAccessor; _storageMode = _configuration["Storage:Mode"]; } public async Task<string> UploadFile(IFormFile file) { try { if (_storageMode == "Local") { var uploads = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads"); var fileName = $"{DateTime.Now:MMddss}-{file.FileName}"; var filePath = Path.Combine(uploads, fileName); if (!Directory.Exists(uploads)) Directory.CreateDirectory(uploads); using (var fileStream = new FileStream(filePath, FileMode.Create)) { await file.CopyToAsync(fileStream); } var host = string.Format("{0}{1}", _httpContextAccessor.HttpContext!.Request.IsHttps ? "https://" : "http://", _httpContextAccessor.HttpContext.Request.Host); return $"{host}/uploads/{fileName}"; } else { var container = new BlobContainerClient(_configuration["Storage:BlobStorage:ConnectionString"], _configuration["Storage:BlobStorage:ContainerName"]); await container.CreateIfNotExistsAsync(PublicAccessType.Blob); var blob = container.GetBlobClient(file.FileName); using (var fileStream = file.OpenReadStream()) { await blob.UploadAsync(fileStream, new BlobHttpHeaders { ContentType = file.ContentType }); } return blob.Uri.ToString(); } } catch (Exception ex) { throw; } } public async Task<bool> DeleteFile(string fileName) { try { if (_storageMode == "Local") { var uploads = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads"); var filePath = Path.Combine(uploads, fileName); if (File.Exists(filePath)) { File.Delete(filePath); return true; } } else { var container = new BlobContainerClient(_configuration["Storage:BlobStorage:ConnectionString"],_configuration["Storage:BlobStorage:ContainerName"]); var blob = container.GetBlobClient(fileName); await blob.DeleteIfExistsAsync(); return true; } } catch (Exception ex) { return false; } } public byte[] DownloadFile(string fileName) { var blobServiceClient = new BlobServiceClient(_configuration["Storage:BlobStorage:ConnectionString"]); var container = blobServiceClient.GetBlobContainerClient(_configuration["Storage:BlobStorage:ContainerName"]); var blobClient = container.GetBlobClient(fileName); using (var memoryStream = new MemoryStream()) { blobClient.DownloadTo(memoryStream); return memoryStream.ToArray(); } } } Static File Middleware Add app.UseStaticFiles(); in Program.cs to serve local files. Usage Example Here’s how to use the UploadFile method in a Web API: public async Task<ServiceResponse<List<ProductPicture>>> UploadImages(List<IFormFile> images) { ServiceResponse<List<ProductPicture>> response = new(); try { List<ProductPicture> pictures = new(); foreach (var file in images) { var imageUrl = await _storageService.UploadFile(file); pictures.Add(new ProductPicture { Url = imageUrl, FileName = Path.GetFileName(imageUrl) }); } response.Data = pictures; } catch (Exception ex) { response.Success = false; response.Message = ex.Message; } return response; } Conclusion By integrating Azure Blob Storage and providing a configurable local storage mode, this approach ensures flexibility for both development and production environments. It reduces development friction while leveraging Azure’s scalability when deployed. For further details, explore the Azure Blob Storage Documentation and Quickstart: Azure Blob Storage.150Views0likes0CommentsExcelDataReader and Date Field
I am looping through the Excel document saved withing my project (wwwroot) and I cannot get the date to work. I have searched and found a reference to call GetDateTime as opposed to GetValue and also attempted to use ToString() and ToShortDateString(); Cannot implicitly convert type 'string' to 'System.DateOnly' What am I missing? using (var stream = System.IO.File.Open(filePath, FileMode.Open, FileAccess.Read)) { // Auto-detect format, supports: // - Binary Excel files (2.0-2003 format; *.xls) // - OpenXml Excel files (2007 format; *.xlsx, *.xlsb) using (var reader = ExcelReaderFactory.CreateReader(stream)) { do { while (reader.Read()) { BirthModel birth = new BirthModel(); birth.LastName = reader.GetValue(1).ToString(); birth.FirstName = reader.GetValue(2).ToString(); birth.MiddleName = reader.GetValue(3).ToString(); birth.BirthDate = reader.GetDateTime(4).ToShortDateString(); birth.County = reader.GetValue(5).ToString(); birth.Maiden_FirstName = reader.GetValue(6).ToString(); birth.Maiden_MiddleName = reader.GetValue(7).ToString(); birth.Maiden_LastName = reader.GetValue(8).ToString(); } } while (reader.NextResult());37Views0likes1CommentLet's Learn .NET - AI
Learn about AI, how to get started, and using ChatGPT to improve text completions. Come to learn something new and leave with something that we all built, together, live with experts! Community Links: https://aka.ms/letslearn/dotnet/ai Featuring: Luis Quintanilla (luquinta@microsoft.com) #AI #dotNET #ChatGPT4KViews0likes3CommentsASP.NET Community Standup - Implementation of the .NET WebAssembly Jiterpreter
A technical talk by Katelyn Gadd about the design and implementation of the .NET WebAssembly Jiterpreter. Community Links: https://www.theurlist.com/blazor-standup-2023-07 Featuring: Katelyn Gadd, Jon Galloway (@jongalloway), Mackinnon Buck (@MackinnonBuck) #Blazor #WebAssembly #dotnet955Views0likes0CommentsOn .NET Live - Building full stack applications using gRPC-Web in ASP.NET Core
gRPC is a modern, high-performance framework that streamlines messaging between clients and back-end services. In this week's episode, community MVP Swamy Viswanatha stops by to show us how to build a full-stack application using gRPC-Web in ASP.NET Core. Featuring: Swamy Viswanatha (@vishipayyallore) #grpc #webapi #dotnet #aspnetcore1.5KViews0likes1CommentLive in 21 hours June 29 at 11:00 AM Notify me Let's Learn .NET - Web Development
Learn the basics of web development by writing HTML and CSS code to create an accessible webpage using the browser-based version of Visual Studio Code. Then build your first webpage using Razor with ASP.NET Core. Come to learn something new and leave with something that we all built, together, live with experts! Resource links: https://aka.ms/letslearndotnet-webdev https://github.com/dotnet/intro-to-dotnet-web-dev Web Dev Around the World Series https://aka.ms/letslearndotnet Featuring: Cam Soper (@camsoper), Jayme Singleton (@jaymesingleton1) #VSCode #AspNetCore #Razor #dotnet298Views0likes0CommentsASP.NET Community Standup | Implementation of the .NET WebAssembly Jiterpreter
A technical talk by Katelyn Gadd about the design and implementation of the .NET WebAssembly Jiterpreter. Community Links: https://www.theurlist.com/blazor-standup-2023-07 Featuring: Katelyn Gadd, Jon Galloway (@jongalloway), Mackinnon Buck (@MackinnonBuck) #Blazor #WebAssembly #dotnet2KViews0likes0Comments