Write C# method that returns DataSet from Stored Procedure

Suppose you are writing a Helper class in your .Net Project that uses ADO.Net in the Data Layer. And you need to call Stored Procedures a lot. Writing a generic Helper method that takes in an Array of SqlParameters can be used so that you don’t have re-write the same code of calling the Stored Procedure again and again.

Below is the code that I’ve used as a general approach to call Stored Procedure and return DataSet:

public static DataSet ExecuteProcedureReturnDataSet(string connString, string procName,
            params SqlParameter[] paramters)
{
	DataSet result = null;
	using (var sqlConnection = new SqlConnection(connString))
	{
		using (var command = sqlConnection.CreateCommand())
		{
			using (SqlDataAdapter sda = new SqlDataAdapter(command))
			{
				command.CommandType = System.Data.CommandType.StoredProcedure;
				command.CommandText = procName;
				if (paramters != null)
				{
					command.Parameters.AddRange(paramters);
				}
				result = new DataSet();
				sda.Fill(result);
			}
		}
	}
	return result;
}

Another way to call Stored Procedure would be to return a single value from the Stored Procedure like a string. You can use the below method to return only a String:

public static string ExecuteProcedureReturnString(string connString, string procName,
            params SqlParameter[] paramters)
{
	string result = "";
	using (var sqlConnection = new SqlConnection(connString))
	{
		using (var command = sqlConnection.CreateCommand())
		{
			command.CommandType = System.Data.CommandType.StoredProcedure;
			command.CommandText = procName;
			if (paramters != null)
			{
				command.Parameters.AddRange(paramters);
			}
			sqlConnection.Open();
			var ret = command.ExecuteScalar();
			if (ret != null)
				result = Convert.ToString(ret);
		}
	}
	return result;
}

Example of SqlParameter array to be passed to the above methods can be as follows:

SqlParameter[] params =
{
	new SqlParameter("@name", name),
	new SqlParameter("@year", year)
};

Change Javascript attribute for asp.net textbox using c#

Suppose we have the following asp.net textbox in a UserControl with the onfocusout javascript method that passes validation as 50000 characters.

<telerik:RadTextBox TextMode="MultiLine" ID="txtComments" onfocusout="return CheckLength(this, 50000);" Height="100px"  runat="server" CssClass="TextMulti" Width="99%" EnableSingleInputRendering="False">
</telerik:RadTextBox>

For a particular scenario, you may need to change the number of characters to say 6000.

This can be done dynamincally in the UserControl C# code as below:

txtComments.Attributes["onfocusout"] = "return CheckLength(this, 6000);";

Authorize WebAPI request with ActionFilterAttribute

Action filters let you use pre and post processing logic which can be applied globally, to an action method or Controller class. These are generally used for applying logic for logging, caching, authorization etc. which can be shared across Controllers.

For adding Authorization to a WebAPI, we can use ActionFilterAttributes to enable strict access for a particular role or user. The ActionFilterAttribute class below implements the authorization logic.

The base ActionFilterAttribute class has the following methods that you can override as per the MS documentation:

  • OnActionExecuting – This method is called before a controller action is executed.
  • OnActionExecuted – This method is called after a controller action is executed.
  • OnResultExecuting – This method is called before a controller action result is executed.
  • OnResultExecuted – This method is called after a controller action result is executed.

As an example, you have a class called TokenFilter that inherits from ActionFilterAttribute. This class overrides the following methods OnActionExecuting and OnActionExecuted as below:

public class TokenFilter : ActionFilterAttribute
{


	public override void OnActionExecuting(HttpActionContext actionContext)
	{
		try
		{
			if (CheckValidHeaders(actionContext))
			{
				var auth_token = actionContext.Request.Headers.GetValues("access-token").FirstOrDefault();
				
				var ValidateObj = MyUtils.ValidateToken(auth_token);
				if (!ValidateObj.IsAuthenticated)
				{
					var error = MyUtils.GetNotSignedInErrorMessage();
					var response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized, error);
					actionContext.Response = response;
				}
				else
				{
					if (!ValidateObj.IsDurationValid)
					{
						auth_token = MyUtils.GenerateToken(email);
						actionContext.Request.Headers.Remove("access-token");
						actionContext.Request.Headers.Add("access-token", auth_token);
					}

					HttpContext.Current.Items.Add("access-token", auth_token);
					
				}
			}
			else
			{
				var response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized, "error message");
				actionContext.Response = response;
			}
		}
		catch (Exception ex)
		{
			var response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized, "error message");
			actionContext.Response = response;
		}
	}

The above code OnActionExecuting will check for valid Headers in the request, Validates the auth token and also generates the token if required. The new auth token is again injected into the Request Headers.

The OnActionExecuted method is as below:

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
    var auth_token = HttpContext.Current.Items["access-token"].ToString();
    actionExecutedContext.Response.Headers.Add("access-token", auth_token);
    var email = HttpContext.Current.Items["emailid"].ToString();
    actionExecutedContext.Response.Headers.Add("emailid", email);
}

Similary, other custom headers can be used to Authorize the request.

The below Authorize Filter class will authorize the user based on email id:

public class AuthorizeUserAttribute : ActionFilterAttribute
{
	bool IsinRole = false;
	public override void OnActionExecuting(HttpActionContext actionContext)
	{
		if (HttpContext.Current.Request.Headers["emailid"] != null)
		{
			var email = HttpContext.Current.Request.Headers["emailid"].ToString();
			 IsinRole = MyUtils.Checkroles(email, "admin");
			if(!IsinRole)
			{
				var response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized, "error message");
				actionContext.Response = response;
			}
		}

	}
}

The below controller will use the TokenFilter and AuthorizeUser attributes to use the Filter out Unauthorized users as below:

[TokenFilter]
[AuthorizeUser]
public class ValuesController : ApiController
{

}

So any Action method that gets called for this Controller, has to have a valid token and a valid role Authorized to access this Controller.


Get great detals on Mobile Phones at Alibaba.

Set Project Build Order in Visual Studio

In order to set the Build order for your Solution, right-click on the Solution in Solution Explorer and Select Project Build Order:

Your Project Dependencies should be set correctly which is used to determine the Build order by Visual Studio.

The image below shows the Project references added in the Business layer to determine that the DTO and Persistence Projects should be built first before the Business layer Project.

The Project Build order will make sure the required dlls are available for the Api to compile correctly.

Now give your car batteries a good re-conditioning they need. Click here to know more.

Handle WebDriver browser prompt for ADFS credentials Selenium C#

While working on Automating the UI using Selenium C#, you might encounter a scenario where a website requires to be authenticated with ADFS. The browser would prompt the user to provide the AD domain credentials to authorize for accessing the website. So automating this scenario with the Selenium C# API, would require you to provide the domain credentials programatically.

The WebDriver used is Firefox with Geckodriver. Another post explains the working of the automation and initialization of the WebDriver in detail here.

Code sample is as shown below:

public static IWebDriver driverWeb;
driverWeb.Navigate().GoToUrl(link);
try
{
	driverWeb.SwitchTo().Alert().SendKeys("Username" + Keys.Tab + "Password");
	driverWeb.SwitchTo().Alert().Accept();
}
catch { }

try
{
	driverWeb.FindElement(By.Id("acknowledgeCookieId")).Click();
}
catch { }