Encryption and Decryption in the .NET Framework


What Is Symmetric Encryption?

 

image

Symmetric encryption uses the same key for both encryption and decryption.

Symmetric Algorithm in the .NET Framework

SymmetricAlgorithm

What Is Asymmetric Encryption?

image

Asymmetric cryptography uses separate keys for encryption and decryption

Encrypted Text with public key can be decrypted only with the private key

Asymmetric Algorithm in the .NET Framework

AsymmetricAlgorithm,

Hash Algorithm

 image

 

Has Algorithm in the .NET Framework

HashAlgorithm 

What is Digital Signature?

 

image

 

Hash + Asymmetric Encryption = Digital Signature

author: hmloo | Posted On Wednesday, May 23, 2012 2:37 PM | Feedback (0)

How to remove the last character from Stringbuilder


We usually use StringBuilder to append string in loops and make a string of each data separated by a delimiter. but you always end up with an extra delimiter at the end. This code sample shows how to remove the last delimiter from a StringBuilder.

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

class Program
{
    static void Main()
    {
        var list =Enumerable.Range(0, 10).ToArray();
        StringBuilder sb = new StringBuilder();
        foreach(var item in list)
        {
            sb.Append(item).Append(",");
        }
        sb.Length--;//Just reduce the length of StringBuilder, it's so easy
        Console.WriteLine(sb);
    }
}

//Output : 0,1,2,3,4,5,6,7,8,9

Alternatively,  we can use string.Join for the same results, please refer to blow code sample.

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

class Program
{
    static void Main()
    {
        var list = Enumerable.Range(0, 10).Select(n => n.ToString()).ToArray();
        string str = string.Join(",", list);
        Console.WriteLine(str);
    }
}

author: hmloo | Posted On Sunday, April 08, 2012 12:12 PM | Feedback (1)

How to create Checkboxes that act like Radio buttons with Jquery


I have a post here to show code examples for check/uncheck all checkbox with Jquery. This time I will implement another request that the user should only be able to check at most one of the checkboxes, it's behave like radio buttons.

There are 2 cases. Case 1 shows function that has little difference with radio button. It allows the user to deselect checkbox. Case 2 is same as radio button.

Case 1

<head id="Head1" runat="server"> 
    <title></title> 
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> 
    <style type="text/css"> 
           .cbRowItem {display:block;} 
     </style> 
    <script type="text/javascript"> 
    $(document).ready(function() 
    { 
        var $chk = $('input:checkbox .cbRowItem'); 
        $chk.click(function() 
        { 
            $chk.not(this).removeAttr('checked'); 
        }); 
    }); 
  </script> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div style="display:block;"> 
    <asp:CheckBox id="CheckBox1" runat="server" class="cbRowItem" Text = "CheckBox 1"/> 
    <asp:CheckBox id="CheckBox2" runat="server" class="cbRowItem" Text = "CheckBox 2"/> 
    <asp:CheckBox id="CheckBox3" runat="server" class="cbRowItem" Text = "CheckBox 3"/> 
    <asp:CheckBox id="CheckBox4" runat="server" class="cbRowItem" Text = "CheckBox 4"/> 
    </div> 
    </form> 
</body> 
</html>

Case 2

<head id="Head1" runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <style type="text/css">
           .cbRowItem {display:block;}
     </style>
    <script type="text/javascript">
    $(document).ready(function()
    {
        var $chk = $('input:checkbox .cbRowItem'); 
        $chk.click(function()
        {
            $chk.removeAttr('checked');
            $(this).attr('checked', 'checked');
        });
    });
  </script>
</head>
<body>
    <form id="form1" runat="server">
    <div style="display:block;">
    <asp:CheckBox id="CheckBox1" runat="server" class="cbRowItem" Text = "CheckBox 1"/>
    <asp:CheckBox id="CheckBox2" runat="server" class="cbRowItem" Text = "CheckBox 2"/>
    <asp:CheckBox id="CheckBox3" runat="server" class="cbRowItem" Text = "CheckBox 3"/>
    <asp:CheckBox id="CheckBox4" runat="server" class="cbRowItem" Text = "CheckBox 4"/>
    </div>
    </form>
</body>
</html>

author: hmloo | Posted On Thursday, March 22, 2012 1:22 PM | Feedback (0)

Replace broken image with noimage icon using Jquery


Sometimes when the image isn't available on server, the web page will show a broken image. so we can display a "no image available" image for good user experience. I will implement it using Jquery.

$(document).ready(function()
{
    $("img").error(function()
    {
        $(this).hide();
    })
    .attr("src", "noimage.jpg");
});

Please note that we must first hide the broken image, or else even if we set the src to noimage, it still can not show  noimage icon.

author: hmloo | Posted On Tuesday, March 20, 2012 7:23 PM | Feedback (0)

The device is not ready


When you retrieve the drive info using the DriveInfo class, if you don't use the IsReady property to test whether a drive is ready, it will throw error as "The device is not ready". so you must use IsReady property to determines if the drive is ready to be queried, written to, or read from. The following code example demonstrates querying information for all drives on current system.

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        DriveInfo[] allDrives = DriveInfo.GetDrives();

        foreach (DriveInfo d in allDrives)
        {
            Console.WriteLine("Drive {0}", d.Name);
            Console.WriteLine("  File type: {0}", d.DriveType);
            if (d.IsReady == true)
            {
                Console.WriteLine("  Volume label: {0}", d.VolumeLabel);
                Console.WriteLine("  File system: {0}", d.DriveFormat);
                Console.WriteLine(
                    "  Available space to current user:{0, 15} bytes", 
                    d.AvailableFreeSpace);

                Console.WriteLine(
                    "  Total available space:          {0, 15} bytes",
                    d.TotalFreeSpace);

                Console.WriteLine(
                    "  Total size of drive:            {0, 15} bytes ",
                    d.TotalSize);
            }
        }
    }
}

author: hmloo | Posted On Sunday, March 18, 2012 6:16 PM | Feedback (0)

How to download files using a Generic Handler


Using a Generic Handler to download files from server has couple of advantages, I list some of them:

1. Download Statistics.

2. Download Tracking.

3. Download Protection.

4. Other business request.

So I suggest that you always use Generic Handler to download files from server.

Here I will show how to implement it.

1. Add Generic Handler and name it to “Download.ashx”.

2. Add code to the download handler

public class Download : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //add some logic to validate the user if he has access to download file
            if (context.User.Identity.IsAuthenticated)
            {
                string file = context.Request.QueryString["file"];
                if (!string.IsNullOrEmpty(file) && File.Exists(context.Server.MapPath(file)))
                {
                    context.Response.Clear();
                    context.Response.ContentType = "application/octet-stream";
                    //I have set the ContentType to "application/octet-stream" which cover any type of file
                    context.Response.AddHeader("content-disposition", "attachment;filename=" + Path.GetFileName(file));
                    context.Response.WriteFile(context.Server.MapPath(file));
                    //here you can do some statistic or tracking
                    //you can also implement other business request such as delete the file after download
                    context.Response.End();
                }
                else
                {
                    context.Response.ContentType = "text/plain";
                    context.Response.Write("File cannot be found!");
                }
            }
           
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

3. Finally we only need to add one line code to download page.

<a href="Download.ashx?file=HelloWorld.txt">Download</a>

Hope this helps!

Thanks for reading!

author: hmloo | Posted On Wednesday, March 07, 2012 8:42 PM | Feedback (0)

How to truncate string without breaking a word in half


Sometimes you need to shorten a long string to certain length without cutting the final word in half and add custom string such as 3 dots to the end, It will moves the pointer up to the previous space, if the limit finished within a word.

Here I listed 3 functions may help you.

Javascript

function Truncate(str, maxLength, suffix)
{
    if(str.length > maxLength)
    {
        str = str.substring(0, maxLength + 1); 
        str = str.substring(0, Math.min(str.length, str.lastIndexOf(" ")));
        str = str + suffix;
    }
    return str;
}

C#

public static string Truncate(string str, int maxLength, string suffix)
{
    if (str.Length > maxLength)
    {
        str = str.Substring(0, maxLength + 1);
        str = str.Substring(0, Math.Min(str.Length, str.LastIndexOf(" ") == -1 ? 0 : str.LastIndexOf(" ")));
        str = str + suffix;
    }
    return str.Trim();
}
public static string Truncate(string str, int maxLength, string suffix)
{
    if (str.Length > maxLength)
    {
        var words = str.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        var sb = new StringBuilder();
        for (int i = 0; sb.ToString().Length + words[i].Length <= maxLength; i++)
        {
            sb.Append(words[i]);
            sb.Append(" ");
        }
        str = sb.ToString().TrimEnd(' ') + suffix;
    }
    return str.Trim();
}

author: hmloo | Posted On Sunday, February 19, 2012 1:32 PM | Feedback (0)

Use window.onbeforeunload event to stop browser from closing or Disable Button before Page PostBack


All modern browsers support the JavaScript's  window.onbeforeunload event. It fires before the unload event when the page is unloaded. So this event always uses to stop a page from exit. The following codes illustrate how to implement this function:

window.onbeforeunload = function (e) {
   var message = 'Are you sure you want to leave?'; 
    var e = e || window.event;
    // For IE and Firefox prior to version 4
    if (e) {
        e.returnValue = message ;
    }
    // For Safari
    return message;
};

and we can also use this event to disable button before postback is done or form is submitted so that user cannot click button again. It is very simple.

window.onbeforeunload = function () { 
  document.getElementById("<%=Button1.ClientID %>").disabled = true; 
};

author: hmloo | Posted On Wednesday, February 15, 2012 9:51 PM | Feedback (2)

How to check/uncheck all checkbox with Jquery


There are a lot of solutions for this, but I found most them did not handle the case where user checked or unchecked all of the child checkboxes and it must automatically checked or unchecked the parent checkbox. so I give the following solution:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <style type="text/css">
        .cbRowItem {display:block;}
    </style>
    <script type="text/javascript">
        $(document).ready(function () {
            var cbHeader = $('.cbHeader input:checkbox');
            var cbRowItem = $('.cbRowItem input:checkbox');
            cbHeader.bind("click", function () {
                cbRowItem.attr('checked', $(this).is(':checked') ? 'checked' : '');
            });
            cbRowItem.bind("click", function () {
                cbHeader.attr('checked', cbRowItem.length == $('.cbRowItem :checked').length ? 'checked' : '');
            });

        });
    
  </script>
</head>
<body>
    <form id="form1" runat="server">
    <div style="display:block;">
    <asp:CheckBox id="CheckBoxAll" runat="server" class="cbHeader" Text="All"/>
    <asp:CheckBox id="CheckBox1" runat="server" class="cbRowItem" Text = "CheckBox 1"/>
    <asp:CheckBox id="CheckBox2" runat="server" class="cbRowItem" Text = "CheckBox 2"/>
    <asp:CheckBox id="CheckBox3" runat="server" class="cbRowItem" Text = "CheckBox 3"/>
    <asp:CheckBox id="CheckBox4" runat="server" class="cbRowItem" Text = "CheckBox 4"/>
    </div>
    </form>
</body>
</html>

author: hmloo | Posted On Wednesday, February 15, 2012 2:04 PM | Feedback (0)

Add SM (Service Mark) symbol for radeditor


Use blow javascript to add a command for radeditor

RadEditorCommandList["InsertSM"] = function (commandName, editor, oTool) { 
        editor.PasteHtml('<sup>SM</sup>'); 
    };

author: hmloo | Posted On Tuesday, February 14, 2012 7:54 PM | Feedback (0)