Posts

Showing posts from 2009

C# load multidimensional array to datatable

[Test]
publicvoid Test()
{
int[,] numbers = newint[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[co…

SQL server concatenate

DECLARE @test TABLE (
FirstName varchar(50)
)
--
INSERT INTO @test
SELECT'Jon'
UNIONSELECT'Tom'
UNIONSELECT'Mike'
--
SELECT STUFF((
SELECTDISTINCT', ' + 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')) ISNOTNULL
DROPTABLE #TempTable
GO
--
CREATETABLE #TempTable
(
id int,
name varchar(50),
primarykey (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

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

privateconststring 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
{
ou…

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.orgGeneral Helpgpg --helpCreating public/private(secret) keygpg --gen-keyListing public/private keysgpg --list-keysExporting public keygpg --armor --export test@email > public.keyExporting private keygpg --armor –export-secret-key test@email > public.keyImporting keysgpg -–import key.txtDeleting secret keygpg --delete-secret-keys test@emailDeleting public keygpg --delete-keys test@emailChange passphrasegpg --edit-key test@email passwdEncrypt filegpg --batch --output "<outfile>" --encrypt --recipient test@email "<infile>"Encrypt file wi…

Update/Insert data from one table to another

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

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

SELECT * FROM #Data

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

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

INSERT INTO #Data
SELECT l.* FROM #Load l
LEFTJOIN #Data i ON i.id = l.id
WHERE i.id ISNULL

SELECT * FROM #Data

DELETEFROM #Load

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

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

INSERT INTO #Data
SELECT l.* FROM #Load l
LEFTJOIN #Data i ON i.id = l.id
WHERE i.id ISNULL

SELECT * FROM #Data

DROPTABLE #Load
DROPTABLE #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.dllMicrosoft (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 AppIf 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 yetControl Panel
Add or Remove Programs
Add/Remove Windows Components (on the left)Install SQL Server Express EditionMake the following changes after the installationSQL 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. Install XP PRO IIS AdminAllows to…

Open command line from context menu

This is the x64 version of Open Command Windows Here from PowerToys for Windows XPCreate .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\"&q…

SQL Server Copy Table

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

C# LoopFileSystemWatcher

This is another implementation of FileSystemWatcher as FileSystemWatcher doesn’t work in all cases.publicclass 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 filein dir.GetFiles(fileFilter))
{
fileCache.Add(file.Name);
}
}

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

C# Pub/Sub example

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

object locker = newobject();

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++)
{

Capturing PRINT statements from Stored Procedure in C#

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

staticpublic 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 inparameters)
{
command.Parameters.Add(param);
}

try
{
command.ExecuteNonQuery();
}
catch (SqlException ex)
{

SQL Server Performance Improvements

Update Statistics UPDATESTATISTICS TABLE_NAME Rebuild Indexes ALTERINDEXALLON 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 INTNULL,
DiskIO INTNULL,
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 GoogleSubmit to Microsoft BINGSubmit 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;

publicclass Email
{
publicstaticvoid 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(newchar[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string address in addressesTo)
{
message.To.Add(new MailAddress(address));
}

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

client.Send(mess…

Free Icon Collection

FAM FAM FAM - Very good icon collection.

Case insensitive List Contains method

privatestaticbool Contains(List<string> list, stringvalue)
{
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 IronPythonpublicstaticvoid 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);
}

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

publicstaticvoid TestPython3()
{
DataTable dt = new DataTable("test");
dt.Columns.Add("One", typeof(int));
dt.Columns.Add("Two", typeof(int));
dt.Columns.Add("…

C# Open process and capture standard output

[Test]
publicvoid 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

publicvoid 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

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
UNIONSELECT 2
UNIONSELECT 3

INSERT INTO @Table2
SELECT 1
UNIONSELECT 2
UNIONSELECT 4

SELECT * FROM @Table1

DECLARE @BatchSize int
SET @BatchSize = 10

WHILE (Exists(SELECT 1 FROM @Table1 t1 LEFTJOIN @Table2 t2 ON t1.Id = t2.Id WHERE t2.Id ISNULL ))
BEGIN TRY
BEGINTRAN
PRINT'Deleting'
DELETETOP(@BatchSize) @Table1 FROM @Table1 t1 LEFTJOIN @Table2 t2 ON t1.Id = t2.Id WHERE t2.Id ISNULL
COMMITTRAN
END TRY
BEGIN CATCH
ROLLBACK
END CATCH

SELECT * FROM @Table1

C# Indexer example

publicclass SampleIndexer
{
privatereadonly 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>());
}

publicvoid Add(string name, string key, stringvalue)
{
list[name].Add(key,value);
}

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

publicstringthis[string name, string key]
{
get
{
return list[name][key];
}
}
}
[TestFixture]
publicclass TestIndexer{

[Test]
publicvoid 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")

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.publicclass Latch
{
privatereadonlyobject locker = newobject();
privateint count;

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

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

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

publicint GetCount()
{
lock (locker)
{
return count;
}
}
}
[TestFixture]
publicclass TestLatch
{
static Latch latch = new Latch(5);
private Random random = new Random();
static Semaphore semaphore = new Semaphore(3,3);

publ…

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\System32To change it to point to your application directory execute the following in the initialization section of your windows serviceDirectory.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.publicvoid 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

privatevoid 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'GOBEGIN TRY BEGINTRANPRINT'Inserting..' INSERT INTO table2(Id,ParentId,Name) SELECT t1.Id, t1.ParentId, t1.Name FROM Table1 t1 WHERE t1.ParentId = 1 PRINT'Deleting..'DELETEFROM [Table1] i WHERE t1.ParentId = 1 COMMITTRANEND TRY BEGIN CATCH ROLLBACKTRANEND CATCH GO

SQL Contraints in CREATE TABLE statement

CREATETABLE [dbo].[Table1]( [Id] [int] NOTNULL, [ParentId] [int] NOTNULL, [Name] [datetime] NULL, [Date] [datetime] NULLCONSTRAINT [DF_Table1_Date] DEFAULT getdate(), --defaultCONSTRAINT [PK_Table1] PRIMARYKEYCLUSTERED-- primary key ( [Id] ASC ), CONSTRAINT [UQ_Table1_Name] UNIQUENONCLUSTERED--unique key ( [Name] ASC ), CONSTRAINT [FK_Table1_Table2_ParentId] FOREIGNKEY--foreign key ( [ParentId] ) REFERENCES [Table2]( [Id] ) )