Posts

AI Agent in .NET Core

Hi All, Microsoft has released their own Agentic AI framework now (as prerelease of course) You can now connect Azure AI, Open AI or any AI framework to this Microsoft Agentic AI to get response and work on those responses as you want. I made a small AI agent as follows using Open AI to generate a speech and convert it to json format. Hope you like it using Microsoft.Agents.AI; using Microsoft.Agents.AI.Workflows; using Microsoft.Extensions.AI; using OpenAI; using System; using System.Reflection; using System.Threading.Tasks;     string apiKey = "{OPENAI_API_KEY}"; IChatClient chatClient = new OpenAIClient(apiKey)                                   .GetChatClient("gpt-4o-mini")           ...

Secure .NET Core Api Server and Client

Image
 Hi Guys, Recently I had a requirement to create a JWT token based WebApi server and a WebApi Client to consume it using .NET Core. So first I created two .NET Core Web Api projects as shown below. In the appsettings.json file of both the WebApi Server and the Client. I added the following values. "JwtConfig": { "Key": "dsadsagfaqrergsdsfdffdsfdsffdsfdsfdsfdsfdfdsfsfdsfd", //Some Secure Key longer the better "AudienceId": 7895, //Some Secure Audience Id "HostUrl": "https://somesecureurl.com" //Some Host Url } Now we will first look at implementation of the WebApi Server. 1) First we must create code to Generate the JWT token, this can be achieved by creating JWTTokenManager.cs file and adding following code public interface IJwtTokenManager { string Authenticate(string userName, string password); } public class JwtTokenManager : IJwtTokenManager { private readonly IConfiguration _c...

Windows Desktop Watermark with username

Image
 Hi Guys, I recently had a requirement from a client to implement a way to protect sensitive documents from being photographed from mobile devices and shared online. To mitigate this issue I made a windows application using C#.  When the exe runs it will read current logged in users' domain user account and display his username throughout the screen. I have given options to change the displayed text to username, hostname of the computer or any custom texts. You can get this application from the following url  Desktop watermark Note: This is works only in Windows Operating Systems

Calling ChatGPT using .NET Core

Image
  Hi Guys, With the immense hype created by ChatGPT every technology is adopting ways to integrate ChatGPT to their frameworks. Hence, a brilliant team led by Hassan Habib  has managed to give .NET Developers a way to call ChatGPT programmatically and get the responses. Remember this is still a new project you might encounter some issues, but the Standard.AI.OpenAI team is ready to help us developers in this journey. The source code can be found here. 1) First you must register yourself at https://platform.openai.com 2) Then you must generate an API Key as shown below. 3) Now you can start integrating your .NET Core applications to use openai. For this purpose I use a console application (.NET 7).  4) Install the Nuget package Standard.AI.OpenAI 5) Copy paste the below code using Microsoft.AspNetCore.Mvc; using Standard.AI.OpenAI.Brokers.DateTimes; using Standard.AI.OpenAI.Clients.OpenAIs; using Standard.AI.OpenAI.Models.Configurations; using Standard.AI.OpenAI.Model...

Security tips for hosting .NET Web Application on IIS

Image
  Hi guys, After having made multiple small/medium level web application and hosted them in IIS. I have learned certain actions we can take while hosting to make a web application secure. They are as below. 1) Prevent Clickjacking In order to prevent clickjacking add the below to configuration > system.webServer > httpProtocol > customHeaders in web.config.  <add name="X-Frame-Options" value="sameorigin" /> 2) To prevent clients knowing what options the server is serving (unless you want them to know) add the below  to configuration > system.webServer > httpProtocol > customHeaders in web.config. <add name="X-Content-Type-Options" value="nosniff" /> 3) To prevent CSS attacks add the below to configuration > system.webServer > httpProtocol > customHeaders in web.config. <add name="X-XSS-Protection" value="1" /> 4) Make sure you are using https (TLS) whenever you can. 5) Go to your we...

Calling Powershell scripts from C# to monitor IIS Application pool

Image
  Hi All, I recently had a requirement to monitor an application pool in one of our server and if it is gets stopped for some odd reason it must be restarted automatically. I created a windows application to achieve this task. The following are two methods which I used to check the status and if it is stopped to start the application pool.    private string GetpoolStatus(string computerName,string appPoolName)         {             Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();                          PowerShell powershell = PowerShell.Create();                          PSCommand command = new PSCommand();             string result = "";             ScriptBlock scriptBlock = ScriptBlock.Cre...

Get Remote machine OS Version by querying Active Directory

Image
  Hi All, Recently I had a requirement to find out the OS Version of remote machine but RPC calling were blocked in all machines due to security reasons. So I had to find another way. I achieved this task simply by querying our organisation Active Directory by computer name. I have copied the method I used to achieve this task. public string GetOSVersion(string computername)         {             DirectoryEntry deRoot;             string RootPath;             RootPath = ConfigurationManager.AppSettings["ADPath"];             deRoot = new DirectoryEntry(ConfigurationManager.AppSettings["ADPath"],                                         ConfigurationManager.AppSettings["ADUsername"],                   ...

Azure DevOps - Notification Email not being sent

Image
 Hi Guys, Recently I encountered an issue of Notification Emails not being sent when an event occurred within my companies Azure DevOps environment. After spending hours going through log files, databases still I couldn't find any issue. Finally I went to the DevOps servers and found out the server time was wrong and once I fixed it. We started receiving Notification Emails. Hope this Helps someone    

Error while adding WCF Service Reference in .NET Core projects behind proxy

Image
  Hi All,  I faced this issue while adding WCF Service Reference to my .NET Core application. Since our environment was behind proxy I had to do the following to solve it.   Step 1 -           Go to % AppData %\NuGet\NuGet.Config -           Then add proxy details inside <configuration> < config >          < add key = "http_proxy" value = " http://192.168.21.110:8080 " /> </ config >            Step 2 run the below command in command prompt         dotnet tool install --global dotnet-svcutil          

Powershell script to enumerate Folders/Items within a TFS Project

Image
 Hi, Recently I had a requirement to enumerate folders/Items within a TFS project. The below is the powershell script I used to achieve it. $url = "http://tfsserver:8080/tfs" $folders = Invoke-RestMethod -Uri "$url/CodePortal/QuickWinProjects/_apis/tfvc/items" -Method Get -UseDefaultCredentials -ContentType application/json $folders.value.ForEach({    Write-Host $_.path })

Module to Gzip Compress dynamic aspx pages in Sharepoint

Image
Hi Guys, Recently we had a requirement to compress (gzip) all the dynamic aspx pages within our Sharepoint portal to be compressed before sent to the browser. So this was the module I created to get the task done. Enable Dynamic Page Compression in IIS then add the module in web.config public class GZipCompressionModule : IHttpModule     {         public GZipCompressionModule()         {         }         void IHttpModule.Dispose()         {         }         void IHttpModule.Init(HttpApplication context)         {             context.BeginRequest += Context_BeginRequest;             context.EndRequest += Context_EndRequest;         }         private void Context_BeginRequest(object sender, EventArgs e)     ...

Working with Hot Reload in VS 2019

Image
  Hi Guys, 1)      Please update VS 2019 to Version 16.11.11 by Clicking Help -> Check For Updates 2)       Run your project Make Code Changes Press on the Fire Icon to apply code changes without Restarting Project

Simple API using Python, Flask and pyodbc

Image
  Hi Guys, I recently learnt the fundamentals of python, one of widely used languages right now. It is super fast in executing and I recommend everyone to give it a try. So I decided to the create a Simple API which will connect to a SQL Server database to perform CRUD operations. Hope you enjoy.  1) Make sure you have installed python     Go to command prompt type " python --version ", it will return the installed version of python in your computer as shown in the image. If it throws an error, don't worry you can go   to https://www.python.org/downloads/ to download the latest version of python to your pc 2) Install pyodbc to connect to SQL Server Database      Go to command prompt type " pip install pyodbc " 3) Install flask to create the api application      Go to command prompt type " pip install flask " 4) Open Visual Studio Code and create a new file "sqlapi.py" and paste the following code import  pyodbc  impor...