Configure ODBC Data Source Administrator with SQL Server

You might often need to connect to the SQL Server database say in your classic ASP Application using the ODBC System DSN (Data Source Name). To do this, we need to use the 32-bit application odbcad32.exe under the SysWOW64 folder. The steps are as below:
Go to the SystemDSN tab -> Click on Add

Select the SQL Server driver SQLSRV32.DLL:

Give a name and Server details:

Provide the SQL Login details. You can also use Windows Authentication if it serves the purpose.

Select the required database by checking “Change the default database to:”

Click on Finish and Test Connection.

To use this in Classic ASP, add the DSN details in your cnconst file as below:

DSNName = "testdb"
SystemDSN = "DSN=" & DSNName & "; UID=user; PWD=xxxx"

To connect, use the code below to fetch a recordset:

SET rsData = Server.CreateObject("ADODB.RecordSet")
strSQL = "SELECT LOCATION from Offices"
rsData.Open strSQL , SystemDSN
Dim OfficesArr, OfficeStr
OfficesArr = rsData.GetRows()

Support pre-flight OPTIONS requests in .Net WebAPI

A way to support the ‘OPTIONS’ pre-flight request in .net WebAPI is to by-pass this request with a default response and returning the required Headers.

Add the below code in your Global.asax.cs file under the Application_BeginRequest method:

protected void Application_BeginRequest()
{
	if (Request.HttpMethod == "OPTIONS")
	{
		HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
		HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, expiry, id, token, token-type");
		HttpContext.Current.Response.AddHeader("Access-Control-Allow‌​-Credentials", "true");
		HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
		HttpContext.Current.Response.End();
	}
}

So when you call the WebAPI with Javscript fetch/axios, the pre-flight request sent before the actual request would get the 200 status code.

The example above shows some sample custom headers and allowed methods that will be returned in Response Headers.

Delete Geckodriver temp folders using Powershell

Geckodriver is an executable that interacts with Firefox installed on the System to run automated tests by running the Firefox instance either fully or in ghost-mode.
Geckodriver creates profiles in the Windows temp folder that can be of huge size depending on the Profile created for the Firefox driver.
The folder name is of the format “rust_mozprofile*”.

The following Powershell script will delete such folders by searching for this string format under C:\windows\temp and also creates logs for the deleted folders.

$datestring = (Get-Date).ToString("s").Replace(":","-")

Start-Transcript C:\logs\Mozprofile_LogPurgeTranscript_$datestring.txt -NoClobber
get-childitem -path c:\windows\temp | where{$_.LastWriteTime -lt (get-date).AddDays(-30) -and $_.name -like "rust_mozprofile*" -and $_.psiscontainer -eq $true} |Sort-Object lastwritetime -Descending| select -last 100 |% {remove-item -Recurse $_.fullname -force -Verbose -Confirm:$false}
Stop-Transcript

This PowerShell script can also be used to generally search for folders and matching a string a delete them.

Enable CORS in .Net Core WebAPI

It is a common scenario where a React front-end SPA is calling a .Net Core WebAPI to fetch data. In this case, suppose both Applications are using their respective domains shown below:

React App => http://myfrontend.com
API=> http://myapi.com

CORS (Cross-Origin Resource Sharing) is a standard that works by adding HTTP headers that allow servers to describe the set of origins that are permitted to fetch information using a web browser and the kind of requests that are allowed.
For the API to allow the React App to fetch the data, it has to allow the Origin of the React App. This is a common CORS problem. So if you’re using, say axios or Fetch, to fetch data from the .Net Core WebAPI, it will only succeed if the API allows the domain http://myfrontend.com to call itself.

Below I’ve used the technique of CORS with named policy and middleware:

public class Startup
{
	public Startup(IConfiguration configuration)
	{
		Configuration = configuration;
	}
	readonly string MyAllowedOrigins = "_myAllowedOrigins";
	public IConfiguration Configuration { get; }
	public IContainer ApplicationContainer { get; private set; }
	// This method gets called by the runtime. Use this method to add services to the container.
	public void ConfigureServices(IServiceCollection services)
	{
		services.AddControllers();
		services.AddCors(options =>
		{
			options.AddPolicy(MyAllowedOrigins,
			builder =>
			{
				//Allowing both the localhost and hosted domains.
				builder.WithOrigins("http://localhost:3000",
									"http://www.myfrontend.com");
			});
		});
	}
	
	//Apply CORS policies to all endpoints via CORS Middleware:
	// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
	public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
	{
		//Omitted code
		app.UseCors(MyAllowedOrigins);
		app.UseEndpoints(endpoints =>
		{
			endpoints.MapControllers();
		});
		//Omitted code
	}
}

The example above is how you apply CORS policy globally to all endpoints in your API. You can also use the [EnableCors(“Policy String”)] attribute on your controllers/page-model/action method.

e.g. Applying CORS on Action method:

[EnableCors("_myAllowedOrigins")]
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
	return new string[] { "test1", "test2" };
}

It is recommended to enable CORS either locally or globally and not combine the two approaches.

We can also expose the allowed Headers and http methods the following way:

public void ConfigureServices(IServiceCollection services)
{
	services.AddControllers();
	services.AddCors(options =>
	{
		options.AddPolicy(MyAllowSpecificOrigins,
		builder =>
		{
			builder.WithOrigins("http://myfrontend.com", "http://localhost:3000")
			.WithHeaders("token")
			.WithMethods("OPTIONS", "GET", "POST");
		});
	});
}

You can also allow credentials to be passed to the WebAPI from the Client by chaining the .AllowCredentials method.

Pre-flight requests for OPTIONS method call fails with Windows authentication and gives 401 Unauthorized. This can be worked around by enabling both Windows and Anonymous authentication.

If you are using Windows Authentication in the case of an Intranet Application and also enabled Anonymous Authentication for allowing OPTIONS pre-flight request, then make sure to use [Authorize] and [AllowAnonymous] attributes to the respective endpoints where required. Without using [Authorize], the name of the user is returned
null with context.HttpContext.User.Identity.Name where context is the ActionExecutingContext object. These attributes can be used on Controllers or Actions as required.
Also, make sure to setup the middleware in the correct order for using with UseCors, UseAuthentication and UseAuthorization in the Startup.cs file Configuration.

How to call a Stored Procedure from Classic ASP

ASP is a program based on Microsoft Technologies that runs inside a web server.

Below is the method used for calling a Stored Procedure in MSSQLSERVER using classic ASP scripting.

The variable SystemDSN holds the value of the Data Source Name that is configured using Odbcad.exe under the SysWow64 folder on the Server. Select the required driver for SQL Server for the DSN configuration to connect to your database.

Set cn = Server.CreateObject("ADODB.Connection")
cn.Open SystemDSN
Set cmd = Server.CreateObject("ADODB.Command")
Set cmd.ActiveConnection = cn
cmd.CommandText = "usp_GetJSON"
cmd.CommandType = adCmdStoredProc

cmd.Parameters.Append(cmd.CreateParameter("@Ticket_Code",adInteger,adParamInput,100, Request.QueryString("inp_ticket_id")))
cmd.Parameters.Append(cmd.CreateParameter("@Username",adVarchar,adParamInput,100000,user))
cmd.Parameters.Append(cmd.CreateParameter("@OperatorID",adVarchar,adParamInput,100000,oprID))

cmd.Parameters.Append(cmd.CreateParameter("@ReturnJson", adVarchar, adParamOutput,100000))
cmd.Execute

'show alert in case of failure.
ReturnValue = cmd.Parameters("@ReturnJson").Value
if ReturnValue <> " " then
  jsonObject = ReturnValue
  'set the flag as 1 to ensure that JSON has been returned from SP to be used later.
  flag= "1"

end if

The above example shows the SP takes 3 input parameters and 1 output parameter. The SP returns a jsonObject assigned to the ReturnValue.

The ADO Connection Object is used to create an open connection to a data source which lets you access and manipulate a database. The ADO Command object is used to execute a single query against a database using which you can perform CRUD operations.

The json can be generated in the SP using the “FOR JSON PATH” feature for SQL Server. However, json is used just for this example. The return value can be anything as per your requirement.

Global Exception Handling and Logging in aspnet core webapi

Create a Model for your Error details as below:

public class ErrorDetails
{
	public int StatusCode { get; set; }
	public string Message { get; set; }


	public override string ToString()
	{
		return JsonConvert.SerializeObject(this); //JsonConvert is part of Newtonsoft.Json package.
	}
}

Create the Exception Factory which will handle Exceptions globally in your Api:

public static class ExceptionFactory
{ 
    public static void ConfigureExceptionHandler(this IApplicationBuilder app, int StatusCode = 0, string message = "")
    {
        app.UseExceptionHandler(appError =>
        {
            appError.Run(async context =>
            {
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                context.Response.ContentType = "application/json";
                
                var contextFeature = context.Features.Get<IExceptionHandlerFeature>();
                if (contextFeature != null)
                {
                    LogTraceFactory.LogError($"Something went wrong: {contextFeature.Error}");

                    await context.Response.WriteAsync(new ErrorDetails()
                    {
                        StatusCode = context.Response.StatusCode,
                        Message = "Internal Server Error."
                    }.ToString());
                }
            });
        });
    }
}

Register Exception handling in your Api:

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
	if (env.IsDevelopment())
	{
		app.UseDeveloperExceptionPage();
	}
	app.ConfigureExceptionHandler();
	.....
}

Also, you can return the error details in your Action Controllers as below:

[HttpGet]
[Route("product/getproductdetails")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public IActionResult GetproductDetails([FromQuery]int productId)
{
	LeadsProduct lead = null;
	if (productId == 0)
	{
		LogTraceFactory.LogError($"Incorrect parameters, productId: {productId}");
		return BadRequest(new ErrorDetails { StatusCode = Convert.ToInt32(HttpStatusCode.BadRequest), Message = $"Missing parameters, productId: {productId} for product Leads." });
	}

	lead = leadService.FetchProductDetails(productId);

	if (lead == null)
	{
		LogTraceFactory.LogError($"product Leads Not Found for productId: {productId}");
		return NotFound(new ErrorDetails { StatusCode = Convert.ToInt32(HttpStatusCode.NotFound), Message = $"product Leads not found for productId {productId}." });
	}

	return Ok(lead);
}

The example above uses the nlog package in the .net core Web Api. You can create LogTraceFactory class as below:

public static class LogTraceFactory
{
	private static ILogger logger = LogManager.GetCurrentClassLogger();

	public static void LogDebug(string message)
	{
		logger.Debug(message);
	}

	public static void LogError(string message)
	{
		logger.Error(message);
	}

	public static void LogInfo(string message)
	{
		logger.Info(message);
	}

	public static void LogWarn(string message)
	{
		logger.Warn(message);
	}
}

Configure nlog package as below in the nlog.config file:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Trace"
      internalLogFile="C:\internal_logs\internallog.txt">

  <targets>
    <target name="logfile" xsi:type="File"
            fileName="C:\ProjectLogs\${shortdate}_logfile.txt"
            layout="${longdate} ${level:uppercase=true} ${message}"/>
  </targets>

  <rules>
    <logger name="*" minlevel="Debug" writeTo="logfile" />
  </rules>
</nlog>

You can modify the above configuration as required. As part of the clean architecture, it is better to setup the ExceptionFactory and LogTraceFactory in the Common Layer of your Solution.


Omg! Now you can earn a six figure income. Click here to know how.

How to serialize data using translator C# .net core webapi

Suppose you’re trying to fetch user data from your database using ado.net in you .net core webapi. You have a SQLHelper class that calls a Stored Procedure and returns data that requires to be converted to a DTO object with pre-defined properties in C#.

The SQLHelper class will have the following method to call your Stored Procedure:

public static TData ExtecuteProcedureReturnData<TData>(string connString, string procName,
	Func<SqlDataReader, TData> translator,
	params SqlParameter[] parameters)
{
	using (var sqlConnection = new SqlConnection(connString))
	{
		using (var sqlCommand = sqlConnection.CreateCommand())
		{
			sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
			sqlCommand.CommandText = procName;
			if (parameters != null)
			{
				sqlCommand.Parameters.AddRange(parameters);
			}
			sqlConnection.Open();
			using (var reader = sqlCommand.ExecuteReader())
			{
				TData elements;
				try
				{
					elements = translator(reader);
				}
				finally
				{
					while (reader.NextResult())
					{ }
				}
				return elements;
			}
		}
	}
}

What is a Translator?

A translator is a class like a DTO in C# which will serialize your data returned from the Stored Procedure into it’s properties.
This will be returned as a json object by your WebApi to your Client front-end.

You can create a Translators folder in your .net core WebApi Project to have all such classes in one place.

An example Translator is as shown below:

public static class UserTranslator
{
	public static User TranslateAsUser(this SqlDataReader reader)
	{
		if (!reader.HasRows)
			return null;
		reader.Read();

		var item = new User();

		if (reader.IsColumnExists("Username"))
			item.Username = SqlHelper.GetNullableString(reader, "Username");

		if (reader.IsColumnExists("FullName"))
			item.FullName = SqlHelper.GetNullableString(reader, "FullName");
			
		if (reader.IsColumnExists("RoleName"))
                item.RoleName = SqlHelper.GetNullableString(reader, "RoleName");

		if (reader.IsColumnExists("Email"))
			item.Email = SqlHelper.GetNullableString(reader, "Email");

		return item;
	}
}

In the above example, you data will have the following columns as Username, FullName and Email. It only returns one row and not a list.

For returning a list:

public static List<User> TranslateAsUsersList(this SqlDataReader reader)
{
	var list = new List<User>();
	while (reader.Read())
	{
		list.Add(TranslateAsUser(reader, true));
	}
	return list;
}

Make sure your reader.Read() method is not called twice.

The DTO for user is as follows:

public class User
{
	public string Username { get; set; }
	public string FullName { get; set; }
	public string RoleName { get; set; }
	public string Email { get; set; }
}

Now, you need to call your Stored Procedure from your Repository:

public User getUserDetails(string UserName)
{
	string connString = CommonUtil.ConnectionString;
	SqlParameter[] param =
	{
		new SqlParameter("@Username", UserName)
	};

	User user = SqlHelper.ExtecuteProcedureReturnData<User>(
		connString,
		"GetUserDetailsFromDB",
		r => r.TranslateAsUser(), //call TranslateAsUsersList if List of Users is required and return List<User>
		param
		);

	return user;
}

Assuming, you’re using the Repository pattern in your WebApi Data Layer. Else, you can call the above method however your Project structure works.

I’ve written another post on multiple ways to fetch data for calling StoredProcedure in your WebApi for your SQLHelper class.