How to convert numeric value in words at runtime

Code for converting numeric values in words is pretty simple. I had developed the code and using it from last few months and now to help others i am posting it here. There are 4 fucntions and each doing its on work. So i am just describing the procedure in 4 simple steps as below..

Step 1) Declare these variables in your code file

string Number;
string deciml;
string _number;
string _deciml;
string[] US = new string[1003];
string[] SNu = new string[20];
string[] SNt = new string[10];

Step 2) Call Initialize() function in your page_load event as

protected void Page_Load(object sender, EventArgs e)
{
Initialize();
}

Step 3) Call myfunction(string myNumber) function to get your number in words. You have to pass the value in the string form to this function as

string NumberInWords = myfunction("123.25");

Step 4) Copy and paste the below code in your code file

//-----------code to convert numeric value in words---------------------
//this will convert number(upto 2 decimal places like 123.15) into words
public string myfunction(string myNumber)
{
string number_in_words = "";
string currency = "Rs. ";
string _currency = " Paise Only";
if (Convert.ToDouble(myNumber) == 0)
{
number_in_words = "Null Value";
}
if (Convert.ToDouble(myNumber) < 0)
{
number_in_words = "Invalid Value";
}
if (myNumber.Split('.').Length > 1) { } else { myNumber = myNumber + ".00"; }
string[] no = myNumber.Split('.');
if ((no[0] != null) && (no[1] != "00"))
{
Number = no[0];
deciml = no[1];
_number = (NameOfNumber(Number));
_deciml = (NameOfNumber(deciml));
number_in_words = currency + _number.Trim() + " and " + _deciml.Trim() + _currency;
}
if ((no[0] != null) && (no[1] == "00"))
{
Number = no[0];
_number = (NameOfNumber(Number));
number_in_words = currency + _number + "Only";
}
if ((Convert.ToDouble(no[0]) == 0) && (no[1] != null))
{
deciml = no[1];
_deciml = (NameOfNumber(deciml));
number_in_words = _deciml + _currency;
}
return number_in_words;
}
public string NameOfNumber(string Number)
{
string GroupName = "";
string OutPut = "";

if ((Number.Length % 3) != 0)
{
Number = Number.PadLeft((Number.Length + (3 - (Number.Length % 3))), '0');
}
string[] Array = new string[Number.Length / 3];
Int16 Element = -1;
Int32 DisplayCount = -1;
bool LimitGroupsShowAll = false;
int LimitGroups = 0;
bool GroupToWords = true;
for (Int16 Count = 0; Count <= Number.Length - 3; Count += 3)
{
Element += 1;
Array[Element] = Number.Substring(Count, 3);

}
if (LimitGroups == 0)
{
LimitGroupsShowAll = true;
}
for (Int16 Count = 0; (Count <= ((Number.Length / 3) - 1)); Count++)
{
DisplayCount++;
if (((DisplayCount <>
{
if (Array[Count] == "000") continue;
{
GroupName = US[((Number.Length / 3) - 1) - Count + 1];
}


if ((GroupToWords == true))
{
OutPut += Group(Array[Count]).TrimEnd(' ') + " " + GroupName + " ";

}
else
{
OutPut += Array[Count].TrimStart('0') + " " + GroupName;

}
}

}
Array = null;
return OutPut;

}
private string Group(string Argument)
{
string Hyphen = "";
string OutPut = "";
Int16 d1 = Convert.ToInt16(Argument.Substring(0, 1));
Int16 d2 = Convert.ToInt16(Argument.Substring(1, 1));
Int16 d3 = Convert.ToInt16(Argument.Substring(2, 1));
if ((d1 >= 1))
{
OutPut += SNu[d1] + " hundred ";
}
if ((double.Parse(Argument.Substring(1, 2)) <>
{
OutPut += SNu[Convert.ToInt16(Argument.Substring(1, 2))];
}
if ((double.Parse(Argument.Substring(1, 2)) >= 20))
{
if (Convert.ToInt16(Argument.Substring(2, 1)) == 0)
{
Hyphen += " ";
}
else
{
Hyphen += " ";
}
OutPut += SNt[d2] + Hyphen + SNu[d3];
}
return OutPut;
}
private void Initialize()
{
SNu[0] = "";
SNu[1] = "One";
SNu[2] = "Two";
SNu[3] = "Three";
SNu[4] = "Four";
SNu[5] = "Five";
SNu[6] = "Six";
SNu[7] = "Seven";
SNu[8] = "Eight";
SNu[9] = "Nine";
SNu[10] = "Ten";
SNu[11] = "Eleven";
SNu[12] = "Twelve";
SNu[13] = "Thirteen";
SNu[14] = "Fourteen";
SNu[15] = "Fifteen";
SNu[16] = "Sixteen";
SNu[17] = "Seventeen";
SNu[18] = "Eighteen";
SNu[19] = "Nineteen";
SNt[2] = "Twenty";
SNt[3] = "Thirty";
SNt[4] = "Forty";
SNt[5] = "Fifty";
SNt[6] = "Sixty";
SNt[7] = "Seventy";
SNt[8] = "Eighty";
SNt[9] = "Ninety";
US[1] = "";
US[2] = "Thousand";
US[3] = "Million";
US[4] = "Billion";
US[5] = "Trillion";
US[6] = "Quadrillion";
US[7] = "Quintillion";
US[8] = "Sextillion";
US[9] = "Septillion";
US[10] = "Octillion";
}

How to Unzip a .zip file at runtime

If you are looking for the code to unzip a .zip file, then you are at the right place. The code is simple and easy. You can implement the code in your website in just 3 steps. So below are the steps.

Step 1) Create a file in App_Code folder named ZipUtil.cs and paste the below code in this ZipUtil.cs
using System;
using System.Data;
using System.Web;
using System.IO;
using System.Collections;
using ICSharpCode.SharpZipLib.Zip; //reference from ICSharpCode.SharpZipLib.dll
///
/// Summary description for ZipUtil
///
public static class ZipUtil
{
public static void UnZipFiles(string zipFile, string baseFolder)
{
if (!Directory.Exists(baseFolder))
{
Directory.CreateDirectory(baseFolder);
}
FileStream fr = File.OpenRead(zipFile);
ZipInputStream ins = new ZipInputStream(fr);
ZipEntry ze = ins.GetNextEntry();
while (ze != null)
{
if (ze.IsDirectory)
{
Directory.CreateDirectory(baseFolder + "\\" + ze.Name);
}
else if (ze.IsFile)
{
if (!Directory.Exists(baseFolder + Path.GetDirectoryName(ze.Name)))
{
Directory.CreateDirectory(baseFolder + Path.GetDirectoryName(ze.Name));
}
FileStream fs = File.Create(baseFolder + "\\" + ze.Name);
byte[] writeData = new byte[ze.Size];
int iteration = 0;
while (true)
{
int size = 2048;
size = ins.Read(writeData, (int)Math.Min(ze.Size, (iteration * 2048)), (int)Math.Min(ze.Size - (int)Math.Min(ze.Size, (iteration * 2048)), 2048));
if (size > 0)
{
fs.Write(writeData, (int)Math.Min(ze.Size, (iteration * 2048)), size);
}
else
{
break;
}
iteration++;
}
fs.Close();
}
ze = ins.GetNextEntry();
}
ins.Close();
fr.Close();
File.Delete(zipFile);// if you want to delete .zip file after conversion, otherwise don't write this line
}
}

Step 2) Add ICSharpCode.SharpZipLib.dll file in your application Bin folder.

Step 3) Use the following function in the page to unzip the .zip file

String Zipfilepath="C:\\YourFolder\\Yourzipfile.zip";
String DestinationFolder = "C:\\SomeOtherFolder\\";
ZipUtil.UnZipFiles(Zipfilepath, DestinationFolder);


and that’s it. Happy coding…

How to encrypt and decrypt Query-string

Below is the code to encrypt and decrypt whole website querystrings without doing any coding in each page of website. You have to do nothing except copying and pasting this code in your website. The procedure consists of 3 steps.
Step 1)
Create a new file in App_code folder with the name QueryStringModule.cs
Step 2)
Copy this whole code in the file named QueryStringModule.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
/// Summary description for QueryStringModule
///
public class QueryStringModule : IHttpModule
{
// private ILog m_Logger = LogManager.GetLogger(typeof(QueryStringModule));
#region IHttpModule Members
public void Dispose()
{
// Nothing to dispose
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
#endregion
private const string PARAMETER_NAME = "enc=";
private const string ENCRYPTION_KEY = "key";
void context_BeginRequest(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
string query = string.Empty;
string path = string.Empty;
try
{
if (context.Request.Url.OriginalString.Contains("aspx") && context.Request.RawUrl.Contains("?"))
{
query = ExtractQuery(context.Request.RawUrl);
path = GetVirtualPath();
if (query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase))
{
// Decrypts the query string and rewrites the path.
string rawQuery = query.Replace(PARAMETER_NAME, string.Empty);
string decryptedQuery = Decrypt(rawQuery);
context.RewritePath(path, string.Empty, decryptedQuery);
}
else if (context.Request.HttpMethod == "GET")
{
// Encrypt the query string and redirects to the encrypted URL.
// Remove if you don't want all query strings to be encrypted automatically.
string encryptedQuery = Encrypt(query);
context.Response.Redirect(path + encryptedQuery, false);
}
}
}
catch (Exception ex)
{
// m_Logger.Error("An error occurred while parsing the query string in the URL: " + path, ex);
context.Response.Redirect("~/index.aspx");
}
}
///

/// Parses the current URL and extracts the virtual path without query string.
///

///
The virtual path of the current URL.
private static string GetVirtualPath()
{
string path = HttpContext.Current.Request.RawUrl;
path = path.Substring(0, path.IndexOf("?"));
path = path.Substring(path.LastIndexOf("/") + 1);
return path;
}
///

/// Parses a URL and returns the query string.
///

///
The URL to parse.
///
The query string without the question mark.
private static string ExtractQuery(string url)
{
int index = url.IndexOf("?") + 1;
return url.Substring(index);
}
#region Encryption/decryption
///

/// The salt value used to strengthen the encryption.
///

private readonly static byte[] SALT = Encoding.ASCII.GetBytes(ENCRYPTION_KEY.Length.ToString());
///

/// Encrypts any string using the Rijndael algorithm.
///

///
The string to encrypt.
///
A Base64 encrypted string.
private static string Encrypt(string inputText)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
byte[] plainText = Encoding.Unicode.GetBytes(inputText);
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);
using (ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16)))
{
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainText, 0, plainText.Length);
cryptoStream.FlushFinalBlock();
return "?" + PARAMETER_NAME + Convert.ToBase64String(memoryStream.ToArray());
}
}
}
}
///

/// Decrypts a previously encrypted string.
///

///
The encrypted string to decrypt.
///
A decrypted string.
private static string Decrypt(string inputText)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
byte[] encryptedData = Convert.FromBase64String(inputText);
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);
using (ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
{
using (MemoryStream memoryStream = new MemoryStream(encryptedData))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
byte[] plainText = new byte[encryptedData.Length];
int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
return Encoding.Unicode.GetString(plainText, 0, decryptedCount);
}
}
}
}
#endregion
}

Step 3)
Add a line in the web.config file as below.
if your web application is running on IIS 5 or 6 then write
<system.web>
<httpModules>
<add type="QueryStringModule" name="QueryStringModule"/>
</httpModules>
</system.web>

But if your web application is running on IIS 7 then write
<system.webServer>
<modules>
<add type="QueryStringModule" name="QueryStringModule"/>
</modules>
</system.webServer>


Happy Coding…