Showing posts from 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.publicvoid Save(){
DataTable dataTable1 = ((DataTable)dataGridView.DataSource).GetChanges();
//dataTable1 is NULL

//revalidate form (fixes the problem)

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

Open webpage from C# GUI

privatevoid button_Click(object sender, EventArgs e)
string 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] ) )

Define custom application configuration section in C#

App.config section configuration<configuration><configSections><sectionGroupname="section1"><sectionname="nvpconfig"type="MyCompany.NameValueConfiguration,MyCompany"/><sectionname="customconfig"type="MyCompany.CustomConfiguration,MyCompany"/></sectionGroup></configSections><section1><nvpconfig><properties><addname="id"value="1"/><addname="name"value="One"/><addname="age"value="18"/></properties></nvpconfig><customconfig><list><addid="1"name="One"age="18"/><addid="2"name="Two"age="21"/></list></customconfig></section1></configuration>Simple name value pair sectionnamespace MyCompany { publicclass NameValueConfiguration : System.Configuration.ConfigurationSection { [Configuratio…

Reading/Writing C# Application Settings in runtime

This is example how to access defined application settings in runtime publicstaticstring MyStringSetting { get { return Properties.Settings.Default.MyStringSetting; } set { Properties.Settings.Default.MyStringSetting = value; Properties.Settings.Default.Save(); } } publicstatic List<string> MyStringCollectionSetting { get { return toStringList(Properties.Settings.Default.MyStringCollectionSetting); } set { Properties.Settings.Default.MyStringCollectionSetting = fromStringList(value); Properties.Settings.Default.Save(); } } privatestatic List<string> toStringList(StringCollection sc) { List<string> list = new List<string>(); if (sc != null) { foreach (string s in sc) { list.Add(s); } } return list; } privatestatic StringCollection fromStringList(List<string> list) { StringCollection sc = new StringCollection(); if (list != null) { foreach (string s in list) { sc.Add(s.ToString()); } } return s…

Read/Write text file in C#

//read fileusing (TextReader tr = new StreamReader("sample.txt")) { string line = tr.ReadLine(); } //write fileusing (TextWriter tw = new StreamWriter("sample.txt")) { tw.WriteLine("text"); }

Using ComboBox with DataTable in C#

Define the ComboBox with DataTable//define DataTableDataTable dt = new DataTable("dataTable"); dt.Columns.Add("Id", typeof(int)); dt.Columns.Add("Name", typeof(string)); //add DataRowDataRow row = dt.NewRow(); row["Id"] = 1; row["Name"] = "One"; dt.Rows.Add(row); //assign to ComboBoxcomboBox.DataSource = dt; comboBox.DisplayMember = "Name"; comboBox.ValueMember = "Id";Get Selected data from ComboBoxDataRow row = ((DataTable)comboBox.DataSource).Rows[comboBox.SelectedIndex]; int Id = (int)row["Id"]; string Name = (string)row["Name"];

Using GridView with DataTable in C#

Define the GridView with DataTable//define DataTableDataTable dt = new DataTable("dataTable"); dt.Columns.Add("Id", typeof(int)); dt.Columns.Add("Name", typeof(string)); //add DataRowDataRow row = dt.NewRow(); row["Id"] = 1; row["Name"] = "One"; dt.Rows.Add(row); //assign to gridViewgridView.DataSource = dt;Get data from selected Row in GridView //get data from selected rowprivatevoid gridView_SelectionChanged(object sender, EventArgs e) { if (gridView.SelectedCells.Count > 0) { int seletedRow = gridView.SelectedCells[0].RowIndex; DataRow row = ((DataTable) gridView.DataSource).Rows[seletedRow]; int id = (int)row["Id"]; string name = (string)row["Name"]; } }Change Column coloursprivatevoid gridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { DataGridViewRow row = gridView.Rows[e.RowIndex]; if (e.RowIndex < ((DataTable)gridView.DataSource).Rows.Count) …

Start/Stop windows service from C#

using System.ServiceProcess; publicvoid Test() { ServiceController controller = new ServiceController(); controller.MachineName = "."; controller.ServiceName = "MyService"; controller.Stop(); //wait until stopped controller.Start(); //wait until started controller.Refresh(); Console.WriteLine(controller.Status.ToString()); }

Zip/Unzip files in C#

DotNetZip is an OpenSource Zip library for C#publicvoid ZipDir(string directoryPath, string zipFilePath) { using(ZipFile zip = new ZipFile()) { zip.AddDirectory(directoryPath); zip.Save(zipFilePath); } } publicvoid UnzipDir(string zipFilePath, string directoryPath) { using(ZipFile zip = ZipFile.Read(zipFilePath)) { zip.ExtractAll(directoryPath,true); } } publicvoid UnzipFile(string zipFilePath, string directoryPath, string fileName) { using (ZipFile zip = ZipFile.Read(zipFilePath)) { zip.Extract(fileName, directoryPath, true); } }

How to quickly compare 2 tables in SQL Server

This is the fastest way to compare 2 tables in SQL Server. Generate hash for both tables and see if it's the same.SELECT checksum_agg(checksum (*)) FROMtable1

List view/table/storedprocedure details including creation, modify date

This system tables allow you to see the list of views, tables, stored procedures in the database as well as information like creation, modify date.SELECT * FROM MyDb.sys.views SELECT * FROM MyDb.sys.tables SELECT * FROM MyDb.sys.procedures

Add/Remove privilages from Database

Grant/Revoke privileges on Tables Privilages: Select, Insert, Update, Delete, References, Alter, Index References - Ability to create contraint that refers to table Alter - Ability to alter table definition Index - Ability to create index Grant/Revoke privileges on Functions/Procedures Privilages: Execute Examples: GRANT Select, Update ON Table1 TO MyDbUser REVOKE Select, Update ON Table1 FROM MyDbUser GRANT Execute ON MyStoredProcedure TO MyDbUser REVOKE Execute ON MyStoredProcedure FROM MyDbUser

Implementing Generic method in C# to print contents of List and Dictionary

publicstaticstring ToString<T>(List<T> list) { StringBuilder builder = new StringBuilder(); if (list != null) { foreach (T t in list) { builder.Append(t.ToString()); } } return builder.ToString(); } publicstaticstring ToString<T,K>(Dictionary<T,K> dictionary) { StringBuilder builder = new StringBuilder(); if (dictionary != null) { foreach (KeyValuePair<T, K> pair in list) { builder.Append(pair.ToString()); } } return builder.ToString(); }

Add ToString() to Resharper Code/Generate menu

To autogenerate ToString() method with Resharper (Alt+Ins) download JetBrains PowerToys The installer will create directory structure in C:\Program Files\JetBrains\ReSharper\v3.0\ If you're using different version v3.x make sure to copy the contents of \v3.0\vs8.0\PowerToys and \v3.0\vs8.0\Bin\Plugins to \v3.x folder.

Load Assembly at runtime from another dll in C#

This example shows how to load a specialized version of Component implementation from from another dll during runtime. Define an interface in a Common projectnamespace MyCompany.Common { publicinterface Component { void Execute(); } }Create specialized library that will be loaded at runtime and add reference to Common project.using MyCompany.Common; namespace MyCompany.Custom { publicclass SampleComponent : Component { publicvoid Execute() { Console.WriteLine("Sample Component"); } } }Create your Console/Windows project and add a reference to Common project. Do not add reference to Custom one as this assembly will be loaded at runtime.using MyCompany.Common; namespace MyCompany.MyProgram { staticclass Program { publicstaticvoid Main() { string path = @"{}\MyCompany.Custom.dll"; Assembly a = Assembly.LoadFile(path); Component c = (Component)a.CreateInstance("MyCompany.Common.SampleComponent"); …

C# Define and execute bean from the spring configuration file

Create spring configuration file spring.xml with a sample bean definition<?xml version="1.0" encoding="utf-8" ?><objectsxmlns=""><objectid="MyClass"type="MyCompany.MyClass,MyCompany"><propertyname="name"value="John"/></object></objects>Use XmlApplicationContext to access beannamespace MyCompany { [TestFixture] publicclass Test { publicvoid Test1() { IApplicationContext context = new XmlApplicationContext("spring.xml"); IObjectFactory factory = context; MyClass obj = (MyClass)factory["MyClass"]; obj.Test(); } } publicclass MyClass { privatestring name; publicstring Name { get { return name; } set { name = value; } } publicvoid Test() { Console.WriteLine(string.Format("My name is {0}", …