Posts

Showing posts from 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 (Dat

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

Image

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

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.

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(

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 --ou

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

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

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.”

Visual Studio Subversion plugin

Image

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

Asp.NET redirect

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

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) Install SQL Server Express Edition 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 Genera

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 \S OFTWARE\Classes\Folder \s hell\Command Prompt] @="Open Command Window Here" [HKEY_LOCAL_MACHINE \S OFTWARE\Classes\Folder \s hell\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 \D irectory \s hell \B ashHere] @="&Open Cygwin Window Here" [HKEY_CLASSES_ROOT \D irectory \s hell \B ashHere\command] @="c:\\cygwin\ \b in\ \b ash . exe --login -c \"cd '%1' ; exec /bin/bash -rcfile ~/ . bashrc\"" [HKEY_CLASSES_ROOT \D rive \s hell \B ashHere] @="&Open Cygwin Window Here" [HKEY_CLASSES_ROOT \D rive \s hell \B ashHere\command] @="c:\\cygwin\ \b in\ \b ash . exe --login -c \"cd '%1' ; exec /bin/bash -rcfile ~/ . bashrc\"" Windows x64 Windows Registry Editor Version 5 . 00 [HKEY_LOCAL_MACHINE \S OFTWARE\Classes\Folder \s hell \B ashHere] @="&Open Cygwin Window Here" [HKEY_LOCAL_MACHINE \S OFTWARE\Classes\Folder \s hell \B ashHere\command] @="c:\ \D evelopment\\tools\\Cygwin\ \b in\ \b

SQL Server Copy Table

This SQL will create another table from the select statement SELECT * INTO table2 FROM table1

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 = n

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

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();

SQL Server Performance Improvements

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

Visual Studio NAnt AddIn

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

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'

How to add website to search engines

Submit to Google Submit to Microsoft BING Submit to Yahoo (requires registration)

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 (

Free Icon Collection

FAM FAM FAM - Very good icon collection.

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

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" , typeo

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

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" , &q

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;

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

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

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);

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" ); } }

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.

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].[ Table 1]( [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 [ Table 2]( [Id] ) )