Wednesday, 30 December 2009

C# load multidimensional array to datatable

[Test]
public void Test()
{
int[,] numbers = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 5 } };
DataTable dt = new DataTable();

Console.WriteLine(numbers.Rank);
Console.WriteLine(numbers.Length);

for (int dimension = 0; dimension < numbers.Rank; dimension++)
{
dt.Columns.Add("Column"+(dimension+1));
}

Console.WriteLine("Array");
for (int element = 0; element < (numbers.Length / numbers.Rank); element++)
{
DataRow row = dt.NewRow();
for (int dimension = 0; dimension < numbers.Rank; dimension++)
{
Console.Write("{0} ", numbers[element,dimension]);
row["Column" + (dimension + 1)] = numbers[element, dimension];
}
dt.Rows.Add(row);
Console.WriteLine();
}

Console.WriteLine("DataTable");
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
Console.Write("{0} ", row[column]);
}
Console.WriteLine();
}
}

Tuesday, 29 December 2009

SQL server concatenate

DECLARE @test TABLE (
FirstName varchar(50)
)
--
INSERT INTO @test
SELECT 'Jon'
UNION SELECT 'Tom'
UNION SELECT 'Mike'
--
SELECT STUFF((
SELECT DISTINCT ', ' + FirstName
FROM @test
FOR XML PATH('')
), 1, 2, '')
FOR XML does the concat, STUFF removes the first 2 characters from position 1 - i.e. the initial unwanted  ', '

List in Excel

excel-list

SQL server indexed temp table

IF (SELECT object_id('TempDB..#TempTable')) IS NOT NULL
DROP TABLE #TempTable
GO
--
CREATE TABLE #TempTable
(
id int,
name varchar(50),
primary key (id, name)
)
--
INSERT INTO #TempTable
SELECT 1,'name'
--
SELECT * FROM #TempTable

Wednesday, 11 November 2009

Move off screen window back on desktop in windows

press Alt-tab and select the window press Alt+Space press M use Arrow key, and then move your mouse.

Tuesday, 27 October 2009

C# GPG Implementation

public class GPG
{
private ILog log = LogManager.GetLogger(MethodInfo.GetCurrentMethod().DeclaringType);

private const string DEFAULT_GPG_PATH = @"C:\Program Files\GNU\GnuPG\";

private const string DECRYPT_ARGS = @"
--batch --output ""{0}"" --decrypt ""{1}""";
private const string ENCRYPT_ARGS = @"
--batch --output ""{0}"" --encrypt --recipient ""{2}"" ""{1}""";

private string _gpgPath;

public GPG()
{
_gpgPath = DEFAULT_GPG_PATH;
}

public string GpgPath
{
set { _gpgPath = value; }
}

public string DecryptFile(string filePath)
{
string outFile;
if (filePath.EndsWith("
.gpg"))
{
outFile = filePath.Remove(filePath.Length - 4, 4);
}else
{
outFile = string.Format("
{0}{1}", filePath, ".out");
}
return DecryptFile(filePath,outFile);
}

public string DecryptFile(string filePath, string outFile)
{
string args = string.Format(DECRYPT_ARGS, outFile, filePath);
ExecuteGPG(args);
return outFile;
}

public string EncryptFile(string filePath, string userId)
{
string outFile = string.Format("
{0}{1}", filePath, ".gpg");
return EncryptFile(filePath, outFile, userId);
}

public string EncryptFile(string filePath, string outFile, string userId)
{
string args = string.Format(ENCRYPT_ARGS, outFile, filePath, userId);
ExecuteGPG(args);
return outFile;
}

private void ExecuteGPG(string args)
{
try
{
Process process = new Process();
string programPath = string.Format(@"
""{0}""", Path.Combine(_gpgPath, "gpg.exe"));

if(!File.Exists(programPath))
{
string error = string.Format("
Invalid gpg.exe path: {0}, please set GpgPath property", programPath);
log.Error(error);
throw new Exception(error);
}

log.InfoFormat("
Executing: {0} {1}", programPath, args);

process.StartInfo.FileName = programPath;
//Open as readonly
process.StartInfo.Arguments = args;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.WorkingDirectory = _gpgPath;

process.Start();

StreamReader reader = process.StandardOutput;
string output = reader.ReadToEnd();

log.InfoFormat("
Output: {0}", output);
}
catch (Exception ex)
{
log.Error("
Failed to execute gpg.exe command",ex);
throw;
}
}
}

PGP/GPG Encryption

Public/Private keys are used to send encrypted data between clients. The receiving client generates public/private key pair and sends the public key to all contributing clients. The contributing clients are using public key to decrypt the file. Receiving client is using the private key to encrypt the file. Private key should never be send to anyone outside!

How to start?

Download latest version of GnuPG from www.gnupg.org

General Help

gpg --help

Creating public/private(secret) key

gpg --gen-key

Listing public/private keys

gpg --list-keys

Exporting public key

gpg --armor --export test@email > public.key

Exporting private key

gpg --armor –export-secret-key test@email > public.key

Importing keys

gpg -–import key.txt

Deleting secret key

gpg --delete-secret-keys test@email

Deleting public key

gpg --delete-keys test@email

Change passphrase

gpg --edit-key test@email passwd

Encrypt file

gpg --batch --output "<outfile>" --encrypt --recipient test@email "<infile>"

Encrypt file with different cipher algorithm

gpg --batch --output "<outfile>" --encrypt --cipher-algo AES --recipient test@email "<infile>"

Decrypt file

gpg --batch --output "<outfile>" --decrypt "<infile>"

Monday, 26 October 2009

Update/Insert data from one table to another

create TABLE #Load(
id int,
[name] VARCHAR(20)
)

create table #Data(
id int,
[name] VARCHAR(20)
)

SELECT * FROM #Data

INSERT INTO #Load
SELECT 1,'one'
UNION SELECT 2,'two'

UPDATE dbo.#Data SET
[name]=l.[name]
FROM #Load l JOIN #Data i ON l.id = i.id

INSERT INTO #Data
SELECT l.* FROM #Load l
LEFT JOIN #Data i ON i.id = l.id
WHERE i.id IS NULL

SELECT * FROM #Data

DELETE FROM #Load

INSERT INTO #Load
SELECT 2,'updated two'
UNION SELECT 3,'three'

UPDATE dbo.#Data SET
[name]=l.[name]
FROM #Load l JOIN #Data i ON l.id = i.id

INSERT INTO #Data
SELECT l.* FROM #Load l
LEFT JOIN #Data i ON i.id = l.id
WHERE i.id IS NULL

SELECT * FROM #Data

DROP TABLE #Load
DROP TABLE #Data

Thursday, 15 October 2009

Resolving DLL version conflict

If you’re using a third party library which was compiled with old version of some common library (like log4net) you will get a dll conflict when you try to run it.

.Net allows you to do binding redirect in App.config as long as the publicKeyToken is the same between versions.

<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="CommonLibrary" publicKeyToken="b32731d11ce58905" culture="neutral" />
<bindingRedirect oldVersion="1.0.0.1" newVersion="1.0.0.2" />
</dependentAssembly>
</assemblyBinding>
</runtime>

How to find public key for .NET dll or exe

  • Open Visual Studio Command Prompt
  • Run sn program as below

C:\>sn –T C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Accessibility.dll

Microsoft (R) .NET Framework Strong Name Utility  Version 2.0.50727.42
Copyright (c) Microsoft Corporation.  All rights reserved.

Public key token is b03f5f7f11d50a3a

Saturday, 10 October 2009

SyncToy v2.0

“SyncToy 2.0 for Windows is available as a free download from the Microsoft Download Center. The easy to use, customizable application helps you copy, move, rename, and delete files between folders and computers.”

Wednesday, 7 October 2009

Visual Studio Subversion plugin

ankhsvn

Monday, 5 October 2009

Moving ClickOnce publish directory

  • Set update location in Visual Studio to the new location in the publish/update section and publish to the old location.
  • Change publish location to new location and publish again.

Fixing Expired ClickOnce Certificate

If certificate expired:

  • Create new certificate (using Visual Studio)
  • Use Renewcert (Method 3) + This code (renewcert.cpp)
  • Create extended certificate (5years)
  • Release App

If certificate is about to expire skip first step

Monday, 28 September 2009

Asp.NET redirect

Response.Redirect("http://www.microsoft.com")

Friday, 25 September 2009

Umbraco C# Open Source CMS Installation

  • Install IIS on your windows machine if it’s not there yet 

Control Panel
Add or Remove Programs
Add/Remove Windows Components (on the left)

Make the following changes after the installation

    • SQL Server Configuration Manager
      • Go to SQL Native Client Configuration/Client Protocols and Enable TCP/IP & Named Pipes
    • SQL Server Surface Area Configuration
      • Go to Surface Configuration for Services and Connections/Database Engine/Remove Connections and set remote connections to TCP/IP and Named Pipes
    • SQL Server Management Studio
      • Right click on top node (database name) and go to Properties/Security and set Server Authentication to SQL Server and Windows Authentication mode (mixed mode)
      • Enable sa account (temporarily, only for Umbraco installation). Go to Security/Logins, right click on sa account choose Properties. On General Page set password (if not set yet) and on Status Page set Login to Enabled.

Allows to have multiple IIS websites on windows machine. Umbraco can only run on the top level websites (not in virtual directory)

  • Create new IIS website using XP PRO IIS Admin.

Set it up to run on a different port (like 8081). If you want to use default website you can skip this step.

Simplifies the whole installation process as it downloads all the dependencies like .Net framework, SQL Server etc..

  • Install Umbraco CMS using the Install Now button which is using Microsoft Web Platform

Web platform installer will download and install all necessary dependencies.

When installing Umbraco, pick Web Site name you created earlier and do not specify anything in Umbraco application name (it doesn’t work if you do)

Choose option to create database for you (rather than using existing one). Use sa account as Database Administrator. Make sure to choose secure password for your Umbraco database user as it’s failing if it’s not secure enough.

  • Start Umbraco

After successful installation click Launch Umbraco link in Web Platform Installation or go to http://localhost:8081/ (or other port you picked for your website). The Umbraco will launch Configuration Wizard for your installation.

Tuesday, 15 September 2009

Open command line from context menu

This is the x64 version of Open Command Windows Here from PowerToys for Windows XP

Create .reg file with this script and execute it.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\Command Prompt]
@="Open Command Window Here"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\Command Prompt\command]
@="Cmd.exe /k pushd %L"

Open cygwin command line from context menu

This script will add extra option to context menu to open cygwin command line. Create .reg file with this script and execute it.

Windows x86

REGEDIT4

[HKEY_CLASSES_ROOT\Directory\shell\BashHere]
@="&Open Cygwin Window Here"

[HKEY_CLASSES_ROOT\Directory\shell\BashHere\command]
@="c:\\cygwin\\bin\\bash.exe --login -c \"cd '%1' ; exec /bin/bash -rcfile ~/.bashrc\""

[HKEY_CLASSES_ROOT\Drive\shell\BashHere]
@="&Open Cygwin Window Here"

[HKEY_CLASSES_ROOT\Drive\shell\BashHere\command]
@="c:\\cygwin\\bin\\bash.exe --login -c \"cd '%1' ; exec /bin/bash -rcfile ~/.bashrc\""
Windows x64
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\BashHere]
@="&Open Cygwin Window Here"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\BashHere\command]
@="c:\\Development\\tools\\Cygwin\\bin\\bash.exe --login -c \"cd '%1' ; exec /bin/bash -rcfile ~/.bashrc\""

Monday, 14 September 2009

SQL Server Copy Table

This SQL will create another table from the select statement

SELECT *
INTO table2
FROM table1

Thursday, 10 September 2009

C# LoopFileSystemWatcher

This is another implementation of FileSystemWatcher as FileSystemWatcher doesn’t work in all cases.

public class LoopFileSystemWatcher
{
public delegate void LoopFileSystemEventHandler(object source, LoopFileSystemEvent e);
public event LoopFileSystemEventHandler created;

readonly List<string> fileCache = new List<string>();

private readonly string folderPath;
private readonly string fileFilter;
private readonly int checkFrequency;

private bool cancelled = false;

public LoopFileSystemWatcher(string folderPath, string fileFilter, int checkFrequency)
{
this.folderPath = folderPath;
this.fileFilter = fileFilter;
this.checkFrequency = checkFrequency;

DirectoryInfo dir = new DirectoryInfo(folderPath);
foreach (FileInfo file in dir.GetFiles(fileFilter))
{
fileCache.Add(file.Name);
}
}

public void Wait(int waitSeconds)
{
Thread t = new Thread(delegate() { WaitThread(waitSeconds,false); });
t.Start();
}

public FileInfo WaitOnce(int waitSeconds)
{
return WaitThread(waitSeconds,true);
}

private FileInfo WaitThread(int waitSeconds, bool waitOnce)
{
FileInfo lastFile=null;
DirectoryInfo dir = new DirectoryInfo(folderPath);

DateTime future = DateTime.Now.AddSeconds(waitSeconds);
while(DateTime.Now.CompareTo(future)<0)
{
if(cancelled)
{
return null;
}

foreach (FileInfo file in dir.GetFiles(fileFilter))
{
if(!fileCache.Contains(file.Name))
{
fireLoopFileSystemEvent(file);
fileCache.Add(file.Name);
lastFile = file;
if(waitOnce)
{
return file;
}
}
}
Thread.Sleep(checkFrequency * 1000);
}
return lastFile;
}

public void Cancel()
{
this.cancelled = true;
}

private void fireLoopFileSystemEvent(FileInfo file)
{
if (created != null)
{
created(this, new LoopFileSystemEvent(file));
}
}
}

public class LoopFileSystemEvent : EventArgs
{
private readonly FileInfo file;

public LoopFileSystemEvent(FileInfo file)
{
this.file = file;
}

public FileInfo File
{
get { return this.file; }
}
}

Tuesday, 8 September 2009

C# Pub/Sub example

public class PubSub
{
readonly Queue<string> queue = new Queue<string>();

object locker = new object();

public string Subscribe()
{
string text;
lock (locker)
{
while(queue.Count== 0)
{
Monitor.Wait(locker);
}
text = queue.Dequeue();
}
return text;
}

public void Publish(string request)
{
lock (locker)
{
queue.Enqueue(request);
Monitor.PulseAll(locker);
}
}
}

class Program
{
Random r = new Random();

public Program()
{
PubSub pubSub = new PubSub();

Thread t1 = new Thread(delegate() { Publish(pubSub); });
Thread t2 = new Thread(delegate() { Subscribe(pubSub); });

t1.Start();
t2.Start();

t1.Join();
t2.Join();

Console.WriteLine("Completed.");

Console.ReadLine();
}

void Publish(PubSub pubSub)
{
for (int i = 1; i <= 10; i++)
{
Thread.Sleep(r.Next(10, 100));
pubSub.Publish(string.Format("Publishing {0}",i));
}
pubSub.Publish(null);
}

void Subscribe(PubSub pubSub)
{
while(true)
{
string text = pubSub.Subscribe();
if(text==null) return;
Console.WriteLine(text);
}
}

static void Main(string[] args)
{
new Program();
}
}

Friday, 28 August 2009

Capturing PRINT statements from Stored Procedure in C#

public class StoredProcedure
{
private static ILog log = LogManager.GetLogger(MethodInfo.GetCurrentMethod().DeclaringType);

static public void Execute(DBSqlPath path, int connectionTimeout,
int commandTimeout, string storedProcedureName, SqlParameter[] parameters)
{
SqlInfoMessageHandler handler = new SqlInfoMessageHandler();

using (DBConn conn = new DBConn(path, connectionTimeout))
{
conn.OpenConnection();

conn.SqlConnection.InfoMessage += handler.connection_InfoMessage;

SqlCommand command = new SqlCommand(storedProcedureName, conn.SqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.CommandTimeout = commandTimeout;
foreach (SqlParameter param in parameters)
{
command.Parameters.Add(param);
}

try
{
command.ExecuteNonQuery();
}
catch (SqlException ex)
{
throw new GeneralException(string.Format("Error executing stored procedure {0}", storedProcedureName), ex);
}
finally
{
conn.SqlConnection.InfoMessage -= handler.connection_InfoMessage;
log.Debug(handler.ErrorMessages);

conn.CloseConnection();
}
}
log.DebugFormat("Completed execution of {0}", storedProcedureName);
}

internal class SqlInfoMessageHandler
{
private readonly List<string> errorMessages = new List<string>();
public void connection_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
if (e.Errors != null)
{
for (int i = 0; i < e.Errors.Count; i++)
{
errorMessages.Add(e.Errors[i].Message);
}
}
}

public string[] ErrorMessages
{
get { return errorMessages.ToArray(); }
}
}
}

Tuesday, 25 August 2009

SQL Server Performance Improvements

Update Statistics
UPDATE STATISTICS TABLE_NAME
Rebuild Indexes
ALTER INDEX ALL ON TABLE_NAME REBUILD

Friday, 17 July 2009

Visual Studio NAnt AddIn

http://www.netlogics.ch/en/nantaddin.html It works with both VS2005 and VS2008

Friday, 10 July 2009

How to filter sp_who2 information

DECLARE @sp_who2 TABLE 
(
SPID INT,
Status VARCHAR(255) NULL,
Login SYSNAME NULL,
HostName SYSNAME NULL,
BlkBy SYSNAME NULL,
DBName SYSNAME NULL,
Command VARCHAR(255) NULL,
CPUTime INT NULL,
DiskIO INT NULL,
LastBatch VARCHAR(255) NULL,
ProgramName VARCHAR(255) NULL,
SPID2 INT,
REQUESTID INT
)

INSERT @sp_who2 EXEC sp_who2

SELECT * FROM @sp_who2
WHERE Status > 'BACKGROUND'

Wednesday, 8 July 2009

How to add website to search engines

Submit to Google

Submit to Microsoft BING

Submit to Yahoo (requires registration)

Tuesday, 7 July 2009

Favicon Editor

The web editor that provides the facilities to draw favicon or convert GIF, JPEG or PNG to favicon. Favicon Editor

Open Web Tools Directory

Directory of various tools for Web Developers Open Web Tools Directory

C# How to send email

using System.Net.Mail;

public class Email
{
public static void Send(string smtpHost, string from, string to, string cc,
string subject, string body, MailPriority priority, bool isBodyHTML)
{
SmtpClient client = new SmtpClient(smtpHost);
client.UseDefaultCredentials = true;

MailMessage message = new MailMessage();
message.From = new MailAddress(from);
message.Subject = subject;
message.Body = body;
message.Priority = priority;
message.IsBodyHtml = isBodyHTML;

string[] addressesTo = to.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string address in addressesTo)
{
message.To.Add(new MailAddress(address));
}

if (cc != null)
{
string[] addressesCc = cc.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string address in addressesCc)
{
message.CC.Add(new MailAddress(address));
}
}

client.Send(message);
}
}

Monday, 29 June 2009

Free Icon Collection

FAM FAM FAM - Very good icon collection.

Friday, 19 June 2009

Case insensitive List Contains method

private static bool Contains(List<string> list, string value)
{
bool contains = null != list.Find(delegate(string str)
{
return str.ToLower().Equals(value.ToLower());
});
return contains;
}

VIM Commands

Replace first character in the line with quote (in the whole file) %s/^/’/

Replace last character in the line with quote (in the whole file) %s/$/’/ Replace more than 1 space with nothing (in the whole file) %s/ \+//

: - go to command mode % – apply to the whole file ^ – first character in the line $ – last character in the line s/x/y – substitute x with y

Tuesday, 9 June 2009

Running IronPython from C#

Download IronPython

public static void TestPython()
{
string code = @"100 * 2 + 4 / 3";

ScriptEngine engine = Python.CreateEngine();
ScriptSource source =
engine.CreateScriptSourceFromString(code, SourceCodeKind.Expression);

int res = source.Execute<int>();
Console.WriteLine(res);
}

public static void TestPython2()
{
ScriptEngine engine = Python.CreateEngine();
ScriptRuntime runtime = engine.Runtime;
ScriptScope scope = runtime.CreateScope();

string code = @"emp.Salary * 0.3";

ScriptSource source =
engine.CreateScriptSourceFromString(code, SourceCodeKind.Expression);

Employee emp = new Employee(1000,"Bernie",1000);

scope.SetVariable("emp", emp);

double res = (double)source.Execute(scope);

Console.WriteLine(res);
}

public static void TestPython3()
{
DataTable dt = new DataTable("test");
dt.Columns.Add("One", typeof(int));
dt.Columns.Add("Two", typeof(int));
dt.Columns.Add("Three", typeof(int));
for (int i = 0; i < 5; i++)
{
DataRow row = dt.NewRow();
row["One"] = 1 + 10 * i;
row["Two"] = 2 + 10 * i;
row["Three"] = 3 + 10 * i;
dt.Rows.Add(row);
}

ScriptEngine engine = Python.CreateEngine();
ScriptRuntime runtime = engine.Runtime;
ScriptScope scope = runtime.CreateScope();

string code = @"dt['One'] * 12";

ScriptSource source = engine.CreateScriptSourceFromString(code, SourceCodeKind.Expression);

scope.SetVariable("dt", dt.Rows[1]);

object res = source.Execute(scope);

Console.WriteLine(res);
}

C# Open process and capture standard output

[Test]
public void TestStartProcess()
{
System.Diagnostics.Process process = new System.Diagnostics.Process();

process.StartInfo.FileName = "echo";
//Open as readonly
process.StartInfo.Arguments = "Hello World!";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.WorkingDirectory = @"c:\temp";

process.Start();

StreamReader reader = process.StandardOutput;
string output = reader.ReadToEnd();

Console.WriteLine(output);

}

C# Read file from zip file to string

public void ReadFromZipFile()
{
string sampleZipFile = @"C:\temp\myzip.zip";
string result;
using (MemoryStream memory = new MemoryStream())
{
using (ZipFile zip = ZipFile.Read(sampleZipFile))
{
ZipEntry e = zip["myfile.txt"];
e.Extract(memory);
}

using (StreamReader reader = new StreamReader(memory))
{
memory.Seek(0, SeekOrigin.Begin);
result = reader.ReadToEnd();
}
}
Console.WriteLine(result);
}

C# Get File Name/Extension

Path.GetFileName(@"c:\temp\myfile.txt")

Path.GetFileNameWithoutExtension(@"c:\temp\myfile.txt")

Path.GetExtension(@"c:\temp\myfile.txt")

Asp.Net upload multiple files

http://www.codeproject.com/KB/aspnet/multiuploads.aspx

SQL Delete in batches

This is a sample of how to delete a large chunk of data in batches. This is to avoid putting to much data into transaction log which can cause long rollback in case of failure.

DECLARE @Table1 TABLE(
id int
)

DECLARE @Table2 TABLE(
id int
)

INSERT INTO @Table1
SELECT 1
UNION SELECT 2
UNION SELECT 3

INSERT INTO @Table2
SELECT 1
UNION SELECT 2
UNION SELECT 4

SELECT * FROM @Table1

DECLARE @BatchSize int
SET @BatchSize = 10

WHILE (Exists(SELECT 1 FROM @Table1 t1 LEFT JOIN @Table2 t2 ON t1.Id = t2.Id WHERE t2.Id IS NULL ))
BEGIN TRY
BEGIN TRAN
PRINT 'Deleting'
DELETE TOP(@BatchSize) @Table1 FROM @Table1 t1 LEFT JOIN @Table2 t2 ON t1.Id = t2.Id WHERE t2.Id IS NULL
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK
END CATCH

SELECT * FROM @Table1

Thursday, 14 May 2009

C# Indexer example

public class SampleIndexer
{
private readonly Dictionary<string,Dictionary<string, string>> list = new Dictionary<string,Dictionary<string, string>>();

public SampleIndexer()
{
list.Add("One",new Dictionary<string, string>());
list.Add("Two", new Dictionary<string, string>());
}

public void Add(string name, string key, string value)
{
list[name].Add(key,value);
}

public Dictionary<string,string> this[string name]
{
get
{
return list[name];
}
}

public string this[string name, string key]
{
get
{
return list[name][key];
}
}
}

[TestFixture]
public class TestIndexer{

[Test]
public void Test()
{
SampleIndexer indexer = new SampleIndexer();
indexer.Add("One","key1","value1");
indexer.Add("Two","key2","value2");

Console.WriteLine(indexer["One"]["key1"]);
}
}

C# String.Format("{0}", "formatting string")

Good summary of the String.Format("{0}", "formatting string")

C# Latch implementation

This is a c# Latch implementation for multithreaded applications (equivalent to java CountDownLatch).

It’s used in a situation when you have a one thread waiting for a number of other threads to finish.

The Test below also uses a Semaphore to run only a specific number of child threads at one time.

public class Latch
{
private readonly object locker = new object();
private int count;

public Latch(int noThreads)
{
lock (locker)
{
count = noThreads;
}
}

public void Await()
{
lock (locker)
{
while (count > 0)
{
Monitor.Wait(locker);
}
}
}

public void CountDown()
{
lock (locker)
{
if (--count <= 0)
{
Monitor.PulseAll(locker);
}
}
}

public int GetCount()
{
lock (locker)
{
return count;
}
}
}

[TestFixture]
public class TestLatch
{
static Latch latch = new Latch(5);
private Random random = new Random();
static Semaphore semaphore = new Semaphore(3,3);

public void Test()
{
for(int i=0;i<5;i++)
{
new Thread(RunIt).Start();
}
Console.WriteLine("Waiting for all threads to finish..");
latch.Await();
Console.WriteLine("All Threads completed.");
}

public void RunIt()
{
semaphore.WaitOne();
int waitTime = random.Next(5000);
Console.WriteLine("Running job {0}", waitTime);
Thread.Sleep(waitTime);
Console.WriteLine("Completed.");
semaphore.Release();
latch.CountDown();
}
}

Wednesday, 6 May 2009

ClickOnce Expired Certification Solution

RenewCert is a solution to Microsoft VS2005 ClickOnce deployment certification problem when it expires after one year. More info about the problem can be found on Microsoft website http://support.microsoft.com/kb/925521

Friday, 17 April 2009

Add, remove, update, query Windows Services from command line

Windows ‘sc’ command can be used to manipulate Windows Services.

More info can be found on Microsoft TechNet

Wednesday, 15 April 2009

Change current directory for Windows Service to application directory

By default current directory for Windows Service is c:\windows\System32

To change it to point to your application directory execute the following in the initialization section of your windows service

Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

Tuesday, 24 March 2009

DataTable not updating when clicked on CheckBox in DataGridView

When you have DataGridView with checkbox column and you click on the checkbox the underlying DataTable is not updated correctly. DataTable is only updated if you move to other row. Not sure why it's like that, but this is a workaround.

public void Save(){
DataTable dataTable1 = ((DataTable)dataGridView.DataSource).GetChanges();
//dataTable1 is NULL

//revalidate form (fixes the problem)
this.ValidateChildren();

DataTable dataTable2 = ((DataTable)dataGridView.DataSource).GetChanges();
//dataTable2 has correct values now
}

Open webpage from C# GUI

private void button_Click(object sender, EventArgs e)
{
try
{
string target = "http://itdevspace.blogspot.com/";
System.Diagnostics.Process.Start(target);
}
catch (Exception ex)
{
MessageBox.Show("Failed to open webpage");
}
}

Monday, 23 March 2009

Windows Live Writer and Code Snippet plugin - extra BR lines problem with Blogger

To get rid of extra BR lines when posting to blogger with Windows Live Writer and Code Snippet plugin make sure you set the Markup Type to HTML (rather then XHTML) in Advanced Setting for your blog in Windows Live Writer.

Friday, 20 March 2009

Transaction management in SQL Server 2005

This is an example of how to use try/catch functionality in SQL Server 2005 to manage transactions.

USE [MyDatabase]

PRINT 'Moving Data'
GO

BEGIN TRY
  BEGIN TRAN

    PRINT 'Inserting..'
    INSERT INTO table2(Id,ParentId,Name)
    SELECT t1.Id, t1.ParentId, t1.Name
    FROM Table1 t1
    WHERE t1.ParentId = 1

    PRINT 'Deleting..'
    DELETE FROM [Table1] i
    WHERE t1.ParentId = 1    

  COMMIT TRAN

END TRY
BEGIN CATCH
 
  ROLLBACK TRAN 
 
END CATCH 
GO

SQL Contraints in CREATE TABLE statement

CREATE TABLE [dbo].[Table1](
  [Id] [int] NOT NULL,
  [ParentId] [int] NOT NULL,
  [Name] [datetime] NULL,
  [Date] [datetime] NULL
  CONSTRAINT [DF_Table1_Date] DEFAULT getdate(), --default
  CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED  -- primary key
  (
    [Id] ASC
  ),
  CONSTRAINT [UQ_Table1_Name] UNIQUE NONCLUSTERED --unique key
  (
    [Name] ASC
  ),
  CONSTRAINT [FK_Table1_Table2_ParentId] FOREIGN KEY --foreign key
  (
    [ParentId]
  ) REFERENCES [Table2](
    [Id]
  )
)