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

December 17, 2014

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.


December 7, 2014

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

Filed under: ASP.NET MVC,HTML — Duy Nguyen @ 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 — Duy Nguyen @ 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.


InputPropertyChange: function () {
    if (!window.addEventListener) { //IE 5-8 
        var $inputs = $("input[type!='hidden']");
        $.each($inputs, function (index, input) {
            $(index).on('paste'), function () {
                setTimeout( function() {
                }, 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 — Duy Nguyen @ 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:
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.

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.

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


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…

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

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.


Some good other reads:



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.

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. 

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

Preventing Browser Cache with a MVC Controller Filter

Filed under: ASP.NET MVC — Duy Nguyen @ 12:04 pm
public class NoCacheFilter : ActionFilterAttribute, IActionFilter
        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)


You can declarate your controller with this filter and if the user clicks on the back button, the MVC routing will attempt to (re)retrieve data from your app.

« Previous PageNext Page »

Blog at WordPress.com.