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
Advertisements

January 28, 2015

TFS 2010 Build Definition and Transform Files

Filed under: ASP.NET MVC,C# — Duy Nguyen @ 2:52 pm
Tags: , , ,

Here is a great blog that helped me with my build definition work with my transform files.

http://www.andygeldman.com/index.php/2011/10/web-and-app-config-transformations-with-tfs-build/

How do you specify multiple configurations like debug and release to get built by MS Build? See this answer.

http://stackoverflow.com/questions/14068750/changing-config-based-on-build-definition-tfs-2012

Some useful urls:
http://stackoverflow.com/questions/6346556/how-do-i-target-a-specific-net-project-within-a-solution-using-msbuild-from-vs2
https://msdn.microsoft.com/en-us/library/dd647547%28v=vs.110%29.aspx#projects

December 19, 2014

Web API 2 – Sample HttpClient and Sample WebClient call

Filed under: C# — Duy Nguyen @ 11:29 am
Tags: , , , ,

Here is a sample request using the old WebClient.

//GET
using (var client = new WebClient())
{
	try
	{
		client.BaseAddress = "http://localhost/endpoint";
		// HTTP GET
		client.UseDefaultCredentials = true;
		jsonResponse = client.DownloadString(endpoint);
	}
	catch (WebException ex)
	{
		// Http Error
		if (ex.Status == WebExceptionStatus.ProtocolError)
		{
			HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
			var statusCode = (int)wrsp.StatusCode;
			var msg = wrsp.StatusDescription;
			throw new HttpException(statusCode, msg);
		}
		else
		{
			throw new HttpException(500, ex.Message);
		}
	}
}

//Post
public string PostRequest(string endpoint, NameValueCollection requestParams)
{
	// Create string to hold JSON response
	string jsonResponse = string.Empty;

	using (var client = new WebClient())
	{
		try
		{
			client.UseDefaultCredentials = true;
			client.Headers.Add("Content-Type:application/x-www-form-urlencoded");
			client.Headers.Add("Accept:application/json");
			var uri = new Uri(endpoint);
			var response = client.UploadValues(uri, "POST", requestParams);
			jsonResponse = Encoding.ASCII.GetString(response);
		}
		catch (WebException ex)
		{
			// Http Error
			if (ex.Status == WebExceptionStatus.ProtocolError)
			{
				HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
				var statusCode = (int)wrsp.StatusCode;
				var msg = wrsp.StatusDescription;
				throw new HttpException(statusCode, msg);
			}
			else
			{
				throw new HttpException(500, ex.Message);
			}
		}
	}

	return jsonResponse;
}

// Post Json
public string PostRequestJson(string endpoint, string json)
{
	// Create string to hold JSON response
	string jsonResponse = string.Empty;

	using (var client = new WebClient())
	{
		try
		{
			client.UseDefaultCredentials = true;
			client.Headers.Add("Content-Type:application/json");
			client.Headers.Add("Accept:application/json");
			var uri = new Uri(endpoint);
			var response = client.UploadString(uri, "POST", json);
			jsonResponse = response;
		}
		catch (WebException ex)
		{
			// Http Error
			if (ex.Status == WebExceptionStatus.ProtocolError)
			{
				HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
				var statusCode = (int)wrsp.StatusCode;
				var msg = wrsp.StatusDescription;
				throw new HttpException(statusCode, msg);
			}
			else
			{
				throw new HttpException(500, ex.Message);
			}
		}
	}

	return jsonResponse;
}


Here is a sample request using the new HttpClient.


HttpClientHandler handler = new HttpClientHandler()
{
	PreAuthenticate = true,
	UseDefaultCredentials = true
};


string reasonPhrase = "";
using (var client = new HttpClient(handler))
{
	client.BaseAddress = new Uri("http://localhost/endpoint");
	client.DefaultRequestHeaders.Accept.Clear();
	client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
	
	// GET
	var response = client.GetAsync(endpoint).Result;
	// Post
	// var response = client.PostAsJsonAsync("http://localhost/endpoint", obj).Result;
	
	if (response.IsSuccessStatusCode)
	{
		var result = response.Content.ReadAsStringAsync().Result;
		return result;
	}
	else
	{
		reasonPhrase = response.ReasonPhrase;
		if (reasonPhrase.ToUpper() == "UNAUTHORIZED")
		{
			throw new KeyNotFoundException("Not authorized");
		}
		var apps = response.Content.ReadAsAsync<ResponseHeader>().Result;
		if (apps.ReturnCode.ToUpper() == "NOTFOUND" )
		{		
			throw new KeyNotFoundException(apps.Result);
		}
		else
		{
			throw new SystemException(apps.Result);
		}
	}
}

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

TripleDes Encryption/Decryption in C#

Filed under: C# — Duy Nguyen @ 10:15 am
Tags: , , ,
public static class TripleDESUtility
{
    /// <summary>
    /// Encrypt using Triple DES.
    /// </summary>
    public static string EncryptTripleDES(string PlainText)
    {
        TripleDES des = CreateDES();
        ICryptoTransform ct = des.CreateEncryptor();
        byte[] input = Encoding.UTF8.GetBytes(PlainText);
        var output = ct.TransformFinalBlock(input, 0, input.Length);

        return Convert.ToBase64String(output);
    }

    /// <summary>
    /// Decrypt using Triple DES.
    /// </summary>
    public static string DecryptTripleDES(string CypherText)
    {
        byte[] b = Convert.FromBase64String(CypherText);
        TripleDES des = CreateDES();
        ICryptoTransform ct = des.CreateDecryptor();
        byte[] output = ct.TransformFinalBlock(b, 0, b.Length);

        return Encoding.UTF8.GetString(output);
    }

    // This is not used in the TripleDESUtility
    public static string SHA1Hash(string text)
    {
        var temp = Encoding.ASCII.GetBytes(text);
        using (SHA1Managed sha1 = new SHA1Managed())
        {
            var hash = sha1.ComputeHash(temp);

            return Convert.ToBase64String(hash);
        }
    }

    /// <summary>
    /// Create the Tripel DES encryption object instance.
    /// </summary>
    private static TripleDES CreateDES()
    {
        TripleDES des = new TripleDESCryptoServiceProvider();

        // MD5 Hashing Key
        MD5 md5 = new MD5CryptoServiceProvider();
        des.Key = md5.ComputeHash(Encoding.UTF8.GetBytes(GetKeyString()));

        des.Key = TripleDESUtility.GetKeyBytes();
        des.Mode = CipherMode.CBC;
        des.Padding = PaddingMode.PKCS7; // PKCS7 and PKCS5 algorthims are the same.

        des.IV = GetIVBytes();
        return des;
    }
    
    private static byte[] GetKeyBytes()
    {
        string encodedKey = ConfigurationManager.AppSettings["AppKeyThatContainsTheEncryptionKey"];
        
        byte[] data = Convert.FromBase64String(encodedKey);
        return data;
    }

    // Decode a base64 encoded string to a readable string
    private static string GetKeyString()
    {
        string encodedKey = ConfigurationManager.AppSettings["AppKeyThatContainsTheEncryptionKey"];

        byte[] data = Convert.FromBase64String(encodedKey);
        return Encoding.UTF8.GetString(data);
    }

    private static byte[] GetIVBytes()
    {
        string IV = ConfigurationManager.AppSettings["AppKeyThatContainsTheEncryptionKey"];

        return Convert.FromBase64String(IV);
    }
}

Simple Encryption/Decryption example in C#

Filed under: C# — Duy Nguyen @ 10:03 am
Tags: , , ,

Here are some sample code projects that I have used in the past that have worked great.

http://www.codeproject.com/Articles/33350/Encrypting-Query-Strings
http://www.codeproject.com/Tips/306620/Encryption-Decryption-Function-in-Net-using-MD-Cry
http://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt

August 5, 2014

How to Redirect user or execute Controller Action in a Custom MVC Filter

Filed under: ASP.NET MVC,C# — Duy Nguyen @ 12:41 pm
Tags: , , , , ,

MVC Filter

    public class MyFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // The controller will be the controller you add the filter to. Or some base controller
            var controller = filterContext.Controller as YourController;

            // Execute controller action from filter. 
            controller.SomeControllerMethod();

            // Redirect to controller action
            filterContext.Result = new RedirectToRouteResult( new System.Web.Routing.RouteValueDictionary
            {
                {"controller", "mycontroller"},    
                {"action", "myaction"},
                {"querystring", "?hello=true"}
            });

            // Redirect to external url
            filterContext.Result = new RedirectResult(url);
        }
    }

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 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 »

Blog at WordPress.com.