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);";
Advertisements

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.

Preserve newline characters in xml asp.net

While using a telerik text box in asp.net in multiline mode, I faced a weird issue where pressing enter was adding spaces and not new line. So, to fix that, I had to use the below css to add new line characters:

div.divTxtBox .txtBoxNewLineFix {
    width: 100% !important;
    white-space: pre !important;
}

RadTextBox aspx code:

<telerik:RadTextBox ID="txtDev"
	Wrap="true" TextMode="MultiLine" runat="server" Width="98%" CssClass="txtBoxNewLineFix" Rows="8">
</telerik:RadTextBox>

Also, while saving the text to the SQL Server database, since I was creating the XML in a C# string, the new line characters were getting replaced with new lines in the XML but it did not replicate in the saved text, so I had to preserve the \r\n characters as below:

private string preserveNewLine(string str)
{
	string sReturnValue;
	sReturnValue = str.Replace("\r\n", "
");

	return sReturnValue;
}

The below xml sample is prepared using StringBuilder in C#:

StringBuilder PlanData = new StringBuilder();
PlanData.AppendLine("<?xml version=\"1.0\" standalone=\"yes\" ?>");
PlanData.Append("<XMLInfo ");
PlanData.Append(" UserDataId=" + "\"" + UserDataId + "\"");
PlanData.Append(" UpdatedBy=" + "\"" + objUser.UserID + "\"");
PlanData.Append(" UpdatedOn=" + "\"" + DateTime.Now.ToString() + "\"");
PlanData.AppendLine(">");
PlanData.AppendLine("<Plans>");

//TO DO loop through data with following lines to add multiple Plan child elements:
Comments = preserveNewLine(Comments);
PlanData.AppendLine("<Plan ID=" + "\"" + ID + "\"" + " Comment=" + "\"" + Comments + "\"" + "/>");

PlanData.AppendLine("</Plans>");
PlanData.AppendLine("</XMLInfo>");

C# sample debug output with new lines converted:

{<?xml version="1.0" standalone="yes" ?>
<XMLInfo  UserDataId="7180" UpdatedBy="1898" UpdatedOn="10/10/2019 6:14:00 PM">
<Plans>
<Plan ID="38685" Comment="1 1111 11111 111111 1111111 11111111 1111   111111

test new line"/>
<Plan ID="38686" Comment="11  2222  2222222    222222      444"/>
}

C# sample debug output with new lines characters preserved:

{<?xml version="1.0" standalone="yes" ?>
<XMLInfo  UserDataId="7180" UpdatedBy="1898" UpdatedOn="10/10/2019 6:39:55 PM">
<Plans>
<Plan ID="38685" Comment="1 1111 11111 111111 1111111 11111111 1111   111111    

test new line"/>
}

So when this xml is saved to SQL Server and pulled back in the Text Box, the new lines will show up correctly.

CSS Media queries adjust to screen width in asp.net

I have two html tables in my Asp.net project, first one has normal html and 2nd one has a Repeater control. Due to some recent changes, it was difficult to align the width of the two tables. Also, I was facing issue on 2 different resolutions as below:

  1. 1920×1080 on my laptop.
  2. 1366×768 on my Desktop.

To solve this, I used the css media queries to cater to minimum width resolution of 1400px for MyTable and for above 1400px width resolution for OthersTable as shown below:

@media only screen and (max-width: 1400px) {
    .MyTable {
        width: 92%;
    }

    .OthersTable {
        width: 90%;
    }
}

@media only screen and (min-width: 1400px) {
    .MyTable {
        width: 90%;
    }

    .OthersTable {
        width: 90%;
    }
}

Media queries introduced in CSS3 let you include some properties only if certain condition is met. In the above case, I’m using screen-width as the condition. Below I’m using the class in my html tables as defined in the media queries in the aspx code.

<table id="divMyTable" visible="false" style="border-collapse: collapse;" class="MyTable" runat="server">
	<tr><td></td></tr>
</table/>			

<table id="divOthersTable" visible="false" style="border-collapse: collapse;" class="OthersTable" runat="server">
	<tr>
		<td></td>
	</tr>
</table>

Asp.net how to escape double quotes in text property aspx file

I recently had a facepalm moment when I experienced an issue with a text property of a user control in my aspx file that had a custom property that included double quotes. Double quotes confused the compiler and made it believe that the ID property of my user control used in cs file didn’t exist.

After wasting some time on the wrong problem, it came down to escaping the double quotes. Aspx files are like XML and need to be treated like one in the text property of attributes used in the form controls.

To escape a double quote you need to use quot; e.g.

HeaderText="This is a &quot;double quote&quot;"

will show up as below:

This is a “double quote”

Similarly for other such characters, use below ones:
 ampersand &   =>   &amp;
 single quotes '   =>   &apos;
 less than <   =>   &lt;
 greater than >   =>   &gt;

App Pool set idle time out IIS Server

When it comes to managing your website traffic, one of the things to consider is the availability of your website.

IIS has a idle time-out property that is by default set to 20 minutes. This means that if no request comes for your site for 20 minutes of inactivity, IIS would kill the worker process to free-up resources. This means the memory utilised by loading of classes, session etc. This can be helpful when multiple websites may be hosted on the Server and is resource crunched.

You’ll find the below settings under the AppPool advanced settings:

So, when the next request comes to your site to access something e.g. Login page, IIS Server would again need to initialize the Worker process and load the required resources to serve that request. The first request will be slow to respond to the user because of all the initialization time required. You need to think in these terms that how much traffic usually comes to your site. If your website requires high availability, then you should consider setting the idle time-out to 0 in the App Pool settings. Or if high availability isn’t a concern, you can think for how many minutes you’d usually require your application to be available depending on the traffic.

There have been studies regarding the make or break for websites because of their initial load time. So, please be careful about this setting. Internet facing websites usually require high availability. For Intranet websites, you can think of some number of minutes based on the usage.