Friday, October 23, 2009

string literal, System.String class and StringBuilder in .NET

In .NET, you can declare a string variable using string literal or System.String. The main difference between is that, string literal is mutable and System.String is immutable.

(i.e.)

string value1 = "hello";
string value2 = "hello";

Both of these variables will share the same object in memory.
But,

System.String value1 = "hello";
System.String value2 = "hello";

Two objects will be created in memory though the values are same.

The same will be case with StringBuilder and String.Concat() also;

StringBuilder stringBuilder1 = new StringBuilder();
stringBuilder1.Append("hello");

StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.Append("hello");

string sb1 = stringBuilder1.ToString();
string sb2 = stringBuilder2.ToString();

Two objects will be created in memory.

string concat1 = String.Concat("hello", " ", "world");
string concat2 = String.Concat("hello", " ", "world");

Two objects will be created in memory.

Why this behavior is that, string literal uses "string Interning" concept. .NET framework internally maintains "Intern Pool" for string values to avoid huge amount of duplicate string data.

System.String, StringBuilder and String.Concat() creates immutable string objects. Also, .NET framework has String.Intern() method which enables the identical string objects to share the same object.

string interned1 = String.Intern(String.Concat("hello", " ", "world"));
string interned2 = String.Intern(String.Concat("hello", " ", "world"));

Cryptography feature in .NET framework


What is Cryptography?

Cryptography is used to protect data. It can protect data from being viewed, modified, or to ensure the integrity from the originator. Cryptography can be used as a mechanism to provide secure communication over an unsecured network, such as the Internet, by encrypting data, sending it across the network in the encrypted state, and then the decrypting the data on the receiving end. Encryption can also be used as an additional security mechanism to further protect data such as passwords stored in a database to prevent them from being human readable or understandable.

Encryption Components in .NET

The Microsoft .NET Framework classes (System.Security.Cryptography) will manage the details of cryptography for you. The classes are implemented with the same interface; so working with the classes is the same across the cryptography namespace. Some of the classes in the Framework are mere wrappers for algorithms that exist in the Microsoft CrytpoAPI. Other classes are managed implementations of their respective algorithms

Public-Key Encryption

Public-key encryption, also known as asymmetric encryption, uses a public and private key pair to encrypt and decrypt data. The public key is made available to anyone and is used to encrypt data to be sent to the owner of the private key. The private key, as the name implies, is kept private. The private key is used to decrypt the data and will only work if the correct public key was used when encrypting the data.

The following are the various public key encryption techniques available in .NET;

    * Digital Signature Algorithm (DSA)
    * RSA

Private-Key Encryption

Private-key Encryption, also known as symmetric encryption, uses a single key to encrypt and decrypt information. The key must be kept secret from those not authorized to decrypt the data lest the data be compromised. Private-key algorithms are relatively fast and can be used to encrypt and decrypt large streams of data

The following are the various private key encryption techniques available in .NET;
    * Data Encryption Standard (DES)
    * RC2
    * TripleDES
    * Rijndael algorithm

Hashing Algorithms

Hashing refers to mapping data of any length into a fixed-length byte sequence. Regardless of if the input is the contents of the library of Congress or the typing test "The quick brown fox jumps over the lazy dog" it will result in an output of the same size. Hashing also produces unique results. Even if the input varies by a single character it will produce different output.

   The following are the various hashing techniques available in .NET;
    * HMACSHA1
    * MACTripleDES
    * MD5CryptoServiceProvider
    * SHA1Managed
    * SHA256Managed
    * SHA384Managed
    * SHA512Managed

Password Encryption in .NET

Hashing is the best technique for encrypting and decrypting passwords in .NET framework. As we have already seen, Hashing in .NET has various flavors;

    * HMACSHA1
    * MACTripleDES
    * MD5CryptoServiceProvider
    * SHA1Managed
    * SHA256Managed
    * SHA384Managed
    * SHA512Managed

All hashes have the same purpose: to digitally fingerprint code. However, there are different speed and security tradeoffs for each Hash.Provider:

Provider
Length (bits)
Security
Speed
Hash.Provider.CRC32
32
low
fast
Hash.Provider.SHA1
160
moderate
medium
Hash.Provider.SHA256
256
high
slow
Hash.Provider.SHA384
384
high
slow
Hash.Provider.SHA512
512
extreme
slow
Hash.Provider.MD5
128
moderate
medium

Considering the speed and security tradeoffs, the best to use for encrypting and decrypting password will be using the SHA1 hashing provider.

SHA1 is also called Secure Hashing Algorithm. It is said to be irreversible, you can’t decrypt it. They are said to be secure since it computationally infeasible to reverse the process to discover the original message from the digest. They are therefore frequently used to produce a unique one-way hash representation of a sensitive message.
This algorithm is able to take a very large message and produce a 160-bit message digest.

Thursday, October 22, 2009

Connecting to Windows Internal Database in Windows Server 2008

Here is how you can connect to Windows Internal Database ("\MICROSOFT##SSME") using the SQL Server Management Studio


\\.\pipe\MSSQL$MICROSOFT##SSEE\sql\query

Exporting unicode characters to Excel in ASP.NET

Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=Export.xls");
            Response.ContentType = "application/octet-stream";
            Response.ContentEncoding = System.Text.Encoding.Unicode;
           Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
            byte[] bytes = System.Text.Encoding.Unicode.GetBytes("ส่วนของโค้ด โปรแกรมที่ใช้ประมวลผล ภาษา");              Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();

Creating Custom List from List Template through feature in sharepoint

Elements.xml file:


<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="KM" Url="_catalogs/lt" RootWebOnly="TRUE">
    <File Url="Knowledge Management.stp" Type="GhostableInLibrary" >
      <Property Name="Name" Value="Knowledge Management"/>
      <Property Name="Title" Value="Knowledge Management"/>
    </File>
    <File Url="Team Details.stp" Type="GhostableInLibrary" >
      <Property Name="Name" Value="Team Details"/>
      <Property Name="Title" Value="Team Details"/>
    </File>
    <File Url="Team Leave.stp" Type="GhostableInLibrary" >
      <Property Name="Name" Value="Team Leave"/>
      <Property Name="Title" Value="Team Leave"/>
    </File>
    <File Url="Training Plan.stp" Type="GhostableInLibrary" >
      <Property Name="Name" Value="Training Plan"/>
      <Property Name="Title" Value="Training Plan"/>
    </File>
  </Module>
</Elements>



Feature Activation code:


 public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            //System.Diagnostics.Debugger.Launch();
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(properties.Feature.Definition.RootDirectory + "/ListInstance.xml");
            XmlElement xmlElement = xmlDocument.DocumentElement;
            XmlNodeList node = xmlElement.ChildNodes;
            using (SPWeb web = (SPWeb)properties.Feature.Parent)
                {
                    //SPWeb web = site.OpenWeb();
                    foreach (XmlNode node1 in node)
                    {
                        SPListTemplate template;
                        SPListTemplateCollection templateList = web.Site.GetCustomListTemplates(web);
                        if (templateList != null && templateList.Count > 0)
                        {
                            template = templateList[node1.Attributes[0].Value];
                        }
                        else
                        {
                            throw new Exception(string.Format("No custom lists found for {0}", web));
                        }

                        if (template != null)
                        {
                            web.Lists.Add(node1.Attributes[0].Value, node1.Attributes[0].Value, template);
                            //web.Lists.Add("Teams TSL", "Teams TSL", template);
                            //web.Lists.Add("Teams Toezicht", "Teams Toezicht", template);
                            web.Update();
                            SPList list=web.Lists[node1.Attributes[0].Value];
                            list.OnQuickLaunch=true;
                            list.Update();
                        }
                        else
                        {
                            throw new Exception("No template to add");
                        }
                    }
                }
           
            //throw new NotImplementedException();
        }