a developer's notes – a semi-technical web development BLOG

February 13, 2015

The request was aborted: Could not create SSL/TLS secure channel

Filed under: ASP.NET,C# — Duy Nguyen @ 10:14 am
Tags: , , , , , ,

We had some trouble with posting data with a System.Net.WebClient request. We notice that it was sporadic and couldn’t figure it out. What we found out was that some calls had SecurityProtocolType.Ssl3 and other calls didn’t specify SecurityProtocolType.

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

SecurityProtocolType is a static class, and what ended up happening was when one call changed the SSL type, it would affect other areas of the application. We had to explicitly set the protocol type in each request.

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; // or Ssl3

December 17, 2014

Expire All Cookies in C#

Filed under: C# — Duy Nguyen @ 11:27 am
Tags: , ,
public static class CookieUtility
{
	public static void ExpireAllCookies(HttpRequestBase request, HttpResponseBase response)
	{
		// Get all cookies associated with MYA
		List<HttpCookie> cookies = new List<HttpCookie>();

		var cookieKeysArray = request.Cookies.AllKeys;

		for (int i = 0; i < cookieKeysArray.Length; i++)
		{
			HttpCookie cookie = request.Cookies[cookieKeysArray[i]];
			cookies.Add(cookie);
		}

		// Expire all cookies
		foreach (var cookie in cookies)
		{
			if (cookie != null)
				CookieUtility.ExpireCookie(response, cookie);
		}
	}
}

// From a controller
public virtual ActionResult LogOut(string logOutUrl)
{
	CookieUtility.ExpireAllCookies(Request, Response);

	return Redirect(logOutUrl);
}

// From Global.asax
var requestWrapper = new HttpRequestWrapper(Request);
var responseWrapper = new HttpResponseWrapper(Response);
CookieUtility.ExpireAllCookies(requestWrapper, responseWrapper);

September 9, 2014

MVC PartialView() VS View()

Filed under: ASP.NET MVC — Duy Nguyen @ 10:36 am
Tags: , , , , ,

Use PartialViews when you want to return a view that does that need the layout.

return PartialView()

Use Views when you need to return a view that supports the layout file.

return View()

A good blog post about it can be found here.
http://completedevelopment.blogspot.com/2014/01/is-there-really-no-difference-between.html

August 28, 2014

Custom Error Pages in MVC 4

Filed under: Uncategorized — Duy Nguyen @ 11:52 am
Tags: , , , , , ,

Default solution: Use MVC HandleErrorAttribute

 

In MVC, by default, you will have in your Global.ascx, under Application_Start()

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

And in RegisterGlobalFilters, you will have…

public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
{
      filters.Add(new HandleErrorAttribute()); 
}

In your web.config, if you turn on custom errors like this…

<system.web>
    <!--<customErrors mode="On"></customErrors>-->
    <customErrors mode="On" defaultRedirect="myCustompage.html?"></customErrors>
</system.web>

customErrors mode=”On” = will turn on the default ~/Views/Shared/Error.cshtml view. (If you’re using IE, be sure to uncheck “Friendly Http Errors.” It works good but if you navigate to http://localhost/404, you will get the default yellow error screen unless you specify defaultRedirect=”myCustompage.htm”. Only then, will the application handle an internal application AND 404s, 500s, etc.

 Note: I’ve read lots of issues trying to preserve the error status code or the original stack trace

 

Alternative solution: Use Application_Error

 

You can also go the Application_Error route but will not have a backup error page if there is an error rendering the error page.

See this great blog post.
http://thirteendaysaweek.com/2012/09/25/custom-error-page-with-asp-net-mvc-4/

 

Some good other reads:

http://www.devcurry.com/2012/06/aspnet-mvc-handling-exceptions-and-404.html

http://colinmackay.co.uk/2011/05/02/custom-error-pages-and-error-handling-in-asp-net-mvc-3-2/

August 21, 2014

“The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.”

I keep on getting this error in Visual Studio when trying to connect to a new Secured SSL site.

“The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.”

After I installed the certificate, I was able to continue working.

Note: Also, check if Fiddler is running. It may cause issues on SSL connections.

March 8, 2014

Checkbox returning “true,false” from FormCollection.

Filed under: ASP.NET MVC — Duy Nguyen @ 10:46 am
Tags: , , , , , , , , , ,

If you try Request.Form[“checkbox0”], you’ll get the value “true,false” .

Just check this:

form[key].Contains("true"); //some said chrome returns "on"

Or

You could simplify your code doing this:

var strArray = collection["YourCheckboxName"];
char[] delimiterChars = {‘,’};
string[] checkedvalue = strArray.Split(delimiterChars);
var returnValue = checkedValue.Length > 1;

If the checkbox is checked, then the array will contain 2 values, if not, only one.

December 4, 2013

WebClient .DownloadString with Proxy Server

Filed under: ASP.NET,ASP.NET MVC,C# — Duy Nguyen @ 9:19 am
Tags: , , , , , , ,

Code to use the default proxy settings

IWebProxy defaultWebProxy = WebRequest.DefaultWebProxy;
defaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
client = new WebClient { Proxy = defaultWebProxy };
string downloadString = client.DownloadString("www.google.com");

or

WebClient client = new WebClient();
WebProxy wp = new WebProxy(" proxy server url here");
client.Proxy = wp;
string str = client.DownloadString("http://www.google.com");

If you need to set an account use this

using (WebClient webClient = new WebClient())
{
	webClient.Encoding = encoding;
	NetworkCredential netcredit = new NetworkCredential("MyNetworkUserID", "MyNetworkPassword", "corp");
	webClient.Credentials = netcredit;
	webClient.Proxy = new System.Net.WebProxy()
	{
		Credentials = new System.Net.NetworkCredential("MyNetworkUserID", "MyNetworkPassword", "corp")
	};
	// webClient.Proxy = null;//if I don't give webClient.Proxy-it returns Error "407-ProxyAuthentication Required!"
	result = webClient.DownloadString(url);
	  // result = webClient.DownloadString("http://www.google.com/");//just to check with google itself,still the same error
}

November 21, 2013

Visual Studio Performance Testing – Viewing HTTP Responses with Binary Data

When examining a response from a HTTP request, what do you do if it contains binary information?

binaryData1

You can examine the Response tab, but it will also contain binary data information.

binaryData2

What if we just want to just to view the contents on the far right column in a readable format?

binaryData3

One technique would be to copy the entire response into a text editor such as Notepad++. Then you can use the column selection (shift + alt) to remove the binary information.

binaryData5

Then you can do a Find and Replace and remove all the line breaks. In Notepad ++, replace “\r\n” with nothing. Be sure you select the Extended Search Mode.

binaryData6

Now you have the information in a readable format.

{. “object_or_array”: “object”,. “empty”: false,. “parse_time_nanoseconds”: 163674,. “validate”: true,. “size”: 6.}.

November 19, 2013

Visual Studio Performance Load Test – Only First test passes, Subsequent Tests Fails

A big “gotcha” when doing load testing is cached data and stale browser cookies. When examining a load test result, you can spot this symptom when you notice only the 1st (or first few) web tests passes before the test starts to encounter a bunch of failures. Cross check this by making sure your web test can execute many iterations without failure. So if you verified that the web test works with many (if not all) with your data inputs but the load test is producing strange errors, check the following:

1. Percentage of New Users

In your load test file, highlight the Scenario that contains your web test and view its properties. You should find the Percentage of New Users

scenarioProperties

property and set that value to 100. That will ensure all iterations in your web test will be new users.

2. Clear the Cookie Container

Create a WebTestPlugin and on the PreWebTest method, you can clear the container with the following snippet:

public override void PreWebTest(object sender, PreWebTestEventArgs e)
{
     e.WebTest.Context.CookieContainer = new System.Net.CookieContainer();
}

Add this plug-in to ensure at the beginning of each web test, there are no stale cookies from the last virtual user that executed a web test.

A Random function to generate a random number

Filed under: C# — Duy Nguyen @ 11:17 am
Tags: , , , , ,
static public void GetRandomDoubleNumber()
{
	// You can do it all on one line like this:
	//double doubleStr = Math.Truncate((new Random().NextDouble()) * 100) / 100;

	Thread.Sleep(1);
	Random autoRand = new Random((int) DateTime.Now.Ticks & 0x0000FFFF); //passing in a unique 'seed' to produce different random numbers.
	
	// Use for doubles
	double dNumber = 0.0;
	double dmin = 0.01;  //inclusive lower bound 
	double dmax = 1; //exclusive upper bound
	dNumber = GenerateRandomDoubleNumber(autoRand, dmin, dmax);

	// Use for ints
	int inumber = 0;
	int iMin = 1;
	int iMax = 10;
	inumber = GenerateRandomIntNumber(autoRand, iMax, iMin);

}

static public double GenerateRandomDoubleNumber(Random randObj, double max, double min)
{
	double randomNumber = randObj.NextDouble() * (max - min) + min;
	return Math.Truncate(randomNumber * 100) / 100;
}

static public int GenerateRandomIntNumber(Random randObj, int max, int min)
{
	int randomNumber = randObj.Next(min, max);
	return randomNumber;
}


Next Page »

Create a free website or blog at WordPress.com.