Using Hashtables Sep 20, 2009 C#

Here I illustrate how to create and use hash table. Each element of hash table is a combination of Key/Value pair stored in a DictionaryEntry object. A value in a hash table can be null or contains no value but a key cannot be of null reference. Key in hash table work as an identifier for the value where you can search a hash table for a value with a specified key.

First you will need to import the namespace System.Collection. We use System.Collectionnamespace because it contains various interface and classes the defines various collection of objects like list, dictionary, queues, hash tables and bit arrays.

Adding Key/Values to Hash Table

using System;
using System.Collections;
class HashtableClass
{
 public static void Main()
 {
   Hashtable htbl = new Hashtable();
   htbl.Add("AL", "Alabama");
   htbl.Add("CA", "California");
   htbl.Add("FL", "Florida");
   htbl.Add("NY", "New York");
   htbl.Add("WY", "Wyoming");
   // Get a collection of the keys.
   ICollection coll = htbl.Keys;
   foreach (string str in coll)
   {
     Console.WriteLine(str + ": " + htbl[str]);
   }
 }
}

Clear all Key/Value pairs in a hash table

To clear all the key/value pairs in a hash table use Clear() method of a hash table class:

htbl.Clear();

Remove Key/Value pairs from hash table

Just if you want to remove a particular value from a hash table use the Remove() method of hash table class and specify the Key to remove the key/value:

htbl.Remove("NY");

Adding Key/value pair to hash table by using indexer

We can use Add() method of the hash table class to add key/value pair to the hash table, but instead we can use indexer to add key/pair:

htbl["NY"] = "New York";

Use the ContainsKey() method to check if hash table contains a key

Just a simple method to use with an IF condition:

if(htbl.ContainsKey("NY"))
{
       Console.WriteLine("Hashtable contains key NY");
}

Use the ContainsValue() method to check if hash table contains a key

Just a simple method to use with an IF condition:

if(htbl.ContainsValue("New York"))
{
    Console.WriteLine("Hashtable contains value New York");
}

Copy the keys from hash table into an array using the CopyTo() method

string[] keys=new string[5];
htbl.Keys.CopyTo(keys,0);
Laws of Computer Programming Sep 13, 2009 FUNDOO
  1. Any given program, once deployed, is already obsolete.

  2. It is easier to change the specification to fit the program than vice versa.

  3. If a program is useful, it will have to be changed.

  4. If a program is useless, it will have to be documented.

  5. Only ten percent of the code in any given program will ever execute.

  6. Software expands to consume all available resources.

  7. Any non-trivial program contains at least one error.

  8. The probability of a flawless demo is inversely proportional to the number of people watching, raised to the power of the amount of money involved.

  9. Not until a program has been in production for at least six months will its most harmful error be discovered.

  10. Undetectable errors are infinite in variety, in contrast to detectable errors, which by definition are limited.

  11. The effort required to correct an error increases exponentially with time.

  12. Program complexity grows until it exceeds the capabilities of the programmer who must maintain it.

  13. Any code of your own that you haven’t looked at in months might as well have been written by someone else.

  14. Inside every small program is a large program struggling to get out.

  15. The sooner you start coding a program, the longer it will take.

  16. A carelessly planned project takes three times longer to complete than expected; a carefully planned project takes only twice as long.

  17. Adding programmers to a late project makes it later.

  18. A program is never less than 90% complete, and never more than 95% complete.

  19. If you automate a mess, you get an automated mess.

  20. Build a program that even a fool can use, and only a fool will want to use it.

  21. Users truly don’t know what they want in a program until they use it.

Import Excel to SQL Table Jul 23, 2009 T-SQL

Using bulk operations using code with sql can be complex, time consuming and tedious for most of the programmers. I just used a stored procedure in one of my projects instead of traversing from cell to cell and save the value in the database, so I search the net and found this SQL Stored Procedure achieve this. I have just copied and paste the code as it is.

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
--drop procedure sp_excel_Convert_Excel_To_Table
--go
Create procedure [dbo].[sp_excel_Convert_Excel_To_Table]
(
@excel_full_file_name varchar(666)
,@convert_to_table_name varchar(50)
,@transfer_to_table bit=1
,@clear_existing_records_first bit=1
,@good int =null output
,@error_code int =null
,@error_description varchar(255) = null output
)
as
set nocount on
declare @command varchar(8000)
-- copy excel file under temp and change worksheet name
set @good=0
set @error_description = ''
set @error_code=0
declare @object int
,@hr int
,@src varchar(255)
exec @hr = master.dbo.sp_OACreate 'Excel.Application', @object out
if @hr <> 0
begin
exec master.dbo.sp_OAGetErrorInfo @object, @src out, @error_description out
set @error_description = '1. ' + isnull(@error_description,'N/A')
select hr=convert(varbinary(4),@hr), source=@src, description=@error_description
set @error_code=1
set @good=0
goto error
end
exec @hr = master.dbo.sp_OASetProperty @object, 'DisplayAlerts', 'false'
if @hr <> 0
begin
exec master.dbo.sp_OAGetErrorInfo @object, @src out, @error_description out
set @error_description = '2. ' + isnull(@error_description,'N/A')
select hr=convert(varbinary(4),@hr), source=@src, description=@error_description
set @error_code=2
set @good=0
goto error
end
declare @workbook int
,@workbook_path_save_as varchar(666)
set @workbook_path_save_as = 'c:\test.xls'
exec @hr = master.dbo.sp_oaMethod @Object,'WorkBooks.Open',@workbook out,@excel_full_file_name
if @hr <> 0
begin
exec master.dbo.sp_OAGetErrorInfo @object, @src out, @error_description out
set @error_description = '3. ' + isnull(@error_description,'N/A')
select hr=convert(varbinary(4),@hr), source=@src, description=@error_description
set @error_code=3
set @good=0
goto error
end
exec @hr = master.dbo.sp_OASetProperty @object, 'Workbooks(1).Worksheets(1).Name','excel_data'
if @hr <> 0
begin
exec master.dbo.sp_OAGetErrorInfo @object, @src out, @error_description out
set @error_description = '4. ' + isnull(@error_description,'N/A')
select hr=convert(varbinary(4),@hr), source=@src, description=@error_description
set @error_code=4
set @good=0
goto error
end
exec @hr = master.dbo.sp_oaMethod @workbook ,'SaveAs',null,@workbook_path_save_as
if @hr <> 0
begin
exec master.dbo.sp_OAGetErrorInfo @object, @src out, @error_description out
set @error_description = '5. ' + isnull(@error_description,'N/A')
select hr=convert(varbinary(4),@hr), source=@src, description=@error_description
set @error_code=5
set @good=0
goto error
end
-- get full file name
exec @hr = master.dbo.sp_OAGetProperty @object, 'Workbooks(1).FullName',
@workbook_path_save_as output
if @hr <> 0
begin
exec master.dbo.sp_OAGetErrorInfo @object, @src out, @error_description out
set @error_description = '6. ' + isnull(@error_description,'N/A')
select hr=convert(varbinary(4),@hr), source=@src, description=@error_description
set @error_code=6
set @good=0
goto error
end
exec @hr = master.dbo.sp_oaMethod @Object,'Application.Quit'--,@workbook out,@workbook_path
if @hr <> 0
begin
exec master.dbo.sp_OAGetErrorInfo @object, @src out, @error_description out
set @error_description = '7. ' + isnull(@error_description,'N/A')
select hr=convert(varbinary(4),@hr), source=@src, description=@error_description
set @error_code=7
set @good=0
goto error
end
if @transfer_to_table = 1
begin
if @clear_existing_records_first=1
begin
set @command = 'delete from ' + @convert_to_table_name
exec (@command)
end
-- copy records from excel into table:
set @command = 'insert into ' + @convert_to_table_name +
' select * from ' +
' OpenRowSet(''MSDASQL'' '+
', ''Driver={Microsoft Excel Driver (*.xls)};'+
'DBQ=' + @workbook_path_save_as + ''''+
',''SELECT * FROM [excel_data$]'')'
print @command
exec (@command)
set @command = 'select * from ' + @convert_to_table_name
exec (@command)
end
error:
select @error_description as 'Error', @error_code as 'Error Code'
exec @hr = master.dbo.sp_OADestroy @workbook
if @hr <> 0
begin
set @error_description = '7. ' + isnull(@error_description,'N/A')
select hr=convert(varbinary(4),@hr), source=@src, description=@error_description
set @error_code=7
set @good=0
end
exec @hr = master.dbo.sp_OADestroy @object
if @hr <> 0
begin
set @error_description = '8. ' + isnull(@error_description,'N/A')
select hr=convert(varbinary(4),@hr), source=@src, description=@error_description
set @error_code=8
set @good=0
end
C# Method: Encrypting a string using MD5 algorithm Jul 20, 2009 C#   CODE SNIPPETS

Encrypting a string using the MD5 algorithm

This C# method will encrypt any string using MD5 algorithm. It generates the same hash as the PHP MD5() function.

using System;using System.Collections.Generic;
using System.Linq;using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
namespace EncryptString
{
    class Program
    {
        public static string EncodePassword(string originalPassword)
        {
            Byte[] originalBytes;
            Byte[] encodedBytes;
            MD5 md5;
            md5 = new MD5CryptoServiceProvider();
            originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword);
            encodedBytes = md5.ComputeHash(originalBytes);
            return Regex.Replace(BitConverter.ToString(encodedBytes), "-", "").ToLower();
         }
         static void Main(string[] args)
         {
            Console.WriteLine("Enter a string to Encrypt");
            string strEnc = Console.ReadLine();
            Console.WriteLine(EncodePassword(strEnc));
            Console.ReadLine();
         }
    }
}
Insert binary files to SQL server using BULK operation Jul 11, 2009 T-SQL

Performing BULK operations with SQL can be useful when you are trying to insert any type of file. Don’t mess up with the complex code, just use a simple SQL query to insert any file type in SQL table.

To perform this operation first you need to have a column with datatype as varbinary(max). See below example:

Create a table with an ID and Data as columns with INT and VARBINARY(MAX) as their Datatypes respectively.

Create table tblData
(
FileId int,
FileData varbinary(max)
)

Perform INSERT to Save a file. Here just change the location of the file you want to insert.

Insert into tblData
(FileId, FileData)
SELECT 1, BulkColumn
FROM OPENROWSET(BULK N'D:\Software\siw.exe', SINGLE_BLOB) AS Document

Display table data after INSERT

Select * from tblData