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# — adevelopersnotes @ 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

January 28, 2015

TFS 2010 Build Definition and Transform Files

Filed under: ASP.NET MVC,C# — adevelopersnotes @ 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

January 22, 2015

Cookie Tempdata Alerts with ASP.NET MVC

Filed under: ASP.NET MVC — adevelopersnotes @ 10:19 pm
Tags: , , ,

https://github.com/duyn9uyen/CookieTempDataProvideAlerts

A sample MVC Project using the CookieTempDataProvider and Bootstrap alerts. This project will illustrate how to add notifications on the serverside and client side via javascript.

Add the CookieTempDataProvider code We used the CookieTempDataProvider from:
https://github.com/KunleSmart/MvcExtensions/blob/master/src/CookieTempDataProvider.cs

Add a basecontroller that uses the CookieTempDataProvider
Added Bootstrap to project using NuGet for styling -(Added the reference to bootstrap.js and bootstrap.css in the _Layout.cshtml file.
Added notification icons (used http://www.famfamfam.com/lab/icons/silk/)
In _Layout.cshtml, moved the scripts into the tag (so that jquery will work) @Scripts.Render(“~/bundles/jquery”) @RenderSection(“scripts”, required: false)

December 19, 2014

Web API 2 – Sample HttpClient and Sample WebClient call

Filed under: C# — adevelopersnotes @ 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# — adevelopersnotes @ 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# — adevelopersnotes @ 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# — adevelopersnotes @ 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

December 7, 2014

Adding Cookies to Response, adds to the Request – Removing cookies from the Request

Filed under: ASP.NET MVC,HTML — adevelopersnotes @ 10:42 am
Tags: , , , ,

I don’t know why but when you add cookies to the RESPONSE, it seems to add the same cookie to the REQUEST. I was able to pin point this because I notice in my request, I had a bunch of cookies that I had previously expired from the response. Typically, when you expire cookies, you set the expire date time and add it back into the response.

Also, make sure you remove a cookie from the request AFTER you expire the cookie from the response. Otherwise, the cookie will still be available in the Request later in the process cycle.

November 13, 2014

Form Validation with Javascript events. Handle Input, Paste, and Keyup across all browsers

Filed under: Javascript / JQuery — adevelopersnotes @ 12:47 pm
Tags: , , , , , , , ,

While testing mobilePay in Chrome on an Android device, it was discovered that the
keyupevent was not firing for validation. Our response was to include input, an HTML5 event, to ensure that changes were firing the validation handlers.

$('form :input').on('keyup input', this.toggleSubmitBtn);

Currently, we are validating the form on every user’s input change, which would enable/ disable the submit button. The disadvantage of this is that we have to capture every single event that the user could possibly interact with the element.

The paste event is one of the events that we recently have implemented to handle. The inputevent we realize fires when the user pastes in an HTML5 browser, which means only non-HTML5 browsers actually need the pasteevent. Below is a table of support for paste validation:

$('form :input').on('keyup input paste', this.toggleSubmitBtn);

The paste event fires across all test devices, but javascript validation logic is carried out beforethe data on the clipboard gets placed into the element. Because all the browsers except for IE8 supported HTML5, however, the inputevent fired afterthe clipboard data was placed in the element. Without the inputevent, none of the browsers supported paste validation.

Solution

InputPropertyChange: function () {
    if (!window.addEventListener) { //IE 5-8 
        var $inputs = $("input[type!='hidden']");
        $.each($inputs, function (index, input) {
            $(index).on('paste'), function () {
                setTimeout( function() {
                    $(input).trigger('keyup');
                }, 250);
            }                
        });
    }
}

This was written up by my colleague Will Hanson and I.

October 31, 2014

Remote Debugging Android Devices – No Devices Detected

Filed under: General Tips — adevelopersnotes @ 2:14 pm
Tags: , , , , , ,

If you are trying to remote debug an Android phone, but Chrome Dev tools won’t detect the device, try this:

Download the Android SDK. Unzip it. The adb folder should be called something like “adt-bundle-windows-x86_64-20140702″.

Here’s how I fixed it (Windows 7).
1. Open command prompt and change directory to the adb folder. In my machine, its:
cd C:\adt-bundle-windows-x86_64-20140321\sdk\platform-tools
2. Run adb manually:
adb.exe
3. Detect the devices:
adb.exe devices
4. Check the inspect devices screen in chrome now and you should have the connected devices listed.
Hope this helps.

Next Page »

The Rubric Theme. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 26 other followers