Friday 12 December 2008

Configuring Kerberos Authentication

Configuring Kerberos Authentication (requires registration) but a very good article

http://www.sqlservercentral.com/articles/Security/65169/#

The query to check connections on SQL server (including their authentication type) is


   1:  SELECT
   2:  s.session_id
   3:  , c.connect_time
   4:  , s.login_time
   5:  , s.login_name
   6:  , c.protocol_type
   7:  , c.auth_scheme
   8:  , s.HOST_NAME
   9:  , s.program_name
  10:  FROM sys.dm_exec_sessions s
  11:  JOIN sys.dm_exec_connections c
  12:  ON s.session_id = c.session_id


Kerberos is configured usually using an Active Directory admin account and the utility SETSPN to set the service principle names required for proper operation.

Tuesday 9 December 2008

Microsoft Application Verifier

"Application Verifier is a runtime verification tool for unmanaged code that assists in quickly finding subtle programming errors that can be extremely difficult to identify with normal application testing.

Application Verifier is designed specifically to detect and help debug memory corruptions and critical security vulnerabilities. It makes it easier to create reliable applications by monitoring an application's interaction with the Windows operating system, profiling its use of objects, the registry, the file system, and Win32 APIs (including heaps, handles, locks, and more). It also includes checks to predict how well the application will perform under Least-privileged User Account operation, compatibility tests to be used in logoing, and print tests to verify your usage of the print subsystem.

Running Application Verifier is easy; simply turn on the tool then run your project and go through your normal testing scenarios with a debugger attached. When your tests are completed, view the Application Verifier logs for any errors that may have been detected."


http://www.microsoft.com/downloads/details.aspx?FamilyID=D2DD7EE0-AAA2-402A-821D-43795D6CF139&displaylang=en

MDAC Utility: Component Checker

"The Component Checker tool is designed to help you determine installed version information and diagnose installation issues with the Microsoft Data Access Components (MDAC). MDAC is installed with numerous Microsoft products and can also be redistributed using the redistribution program (mdac_typ.exe) that you can download from the MSDN Data Access and Storage Developer Center. Windows XP SP2 or later versions of Windows also installs MDAC as an ‘out of box’ system component of the Windows operating system. Since MDAC in Windows XP SP2 or later is newer than the version (MDAC 2.8 SP1) in the last MDAC redistribution program, mdac_typ.exe no longer installs MDAC on Windows XP SP2 and later version. For more information about MDAC history and supportability please visit Data Access Technologies Road Map

Component Checker performs the following tasks:

  • Identifies the current MDAC installation on a computer.
  • Creates a series of reports about the files identified for the current MDAC installation."


http://www.microsoft.com/downloads/details.aspx?FamilyID=8F0A8DF6-4A21-4B43-BF53-14332EF092C9&displaylang=en

Tuesday 2 December 2008

.NET books list

from a poster in amazon...

My top recommended books:
1. "Accelerated C#" by Trey Nash
2. "Programming .NET Components" by Juval Lowy
3. "Test Driven Development in Microsoft .NET"
4. "Head First Design Patterns" [in Java but good]
5. "CLR Via C#" by Jeffrey Richter
6. "Code Complete" [Steve McConnell]
7. "Pro C# 2008 and the .NET 3.5 Platform" [Excellent]
8. "Framework Design Guidelines"
9. "WCF" by Juvy Lowy [Advanced stuff, but excellent]
10. "Pro LINQ Language Integrated Query in C# 2008"

Wednesday 12 November 2008

SQL Index Defrag

Looks neat http://sqlfool.com/2008/11/updated-index-defrag-script-2005-2008/

For the standard version of SQL server the script is: (all credits to the author in the link provided above):


   1:  IF EXISTS(SELECT OBJECT_ID FROM sys.tables
   2:  WHERE [name] = N'dba_indexDefragLog')
   3:  BEGIN
   4:   
   5:  DROP TABLE dbo.dba_indexDefragLog;
   6:   
   7:  PRINT 'dba_indexDefragLog table dropped!';
   8:   
   9:  END
  10:   
  11:  CREATE TABLE dbo.dba_indexDefragLog
  12:  (
  13:  indexDefrag_id    INT IDENTITY(1,1)   NOT NULL
  14:  , objectID          INT                 NOT NULL
  15:  , objectName        NVARCHAR(130)       NOT NULL
  16:  , indexID           INT                 NOT NULL
  17:  , indexName         NVARCHAR(130)       NOT NULL
  18:  , fragmentation     FLOAT               NOT NULL
  19:  , page_count        INT                 NOT NULL
  20:  , dateTimeStart     DATETIME            NOT NULL
  21:  , durationSeconds   INT                 NOT NULL
  22:  CONSTRAINT PK_indexDefragLog
  23:  PRIMARY KEY CLUSTERED (indexDefrag_id)
  24:  );
  25:   
  26:  PRINT 'dba_indexDefragLog Table Created';
  27:   
  28:  IF OBJECTPROPERTY(OBJECT_ID('dbo.dba_indexDefragStandard_sp'),
  29:  N'IsProcedure') IS Null
  30:  BEGIN
  31:  EXECUTE ('Create Procedure dbo.dba_indexDefragStandard_sp
  32:  As Print ''Hello World!''');
  33:  RAISERROR('Procedure dba_indexDefragStandard_sp created.'
  34:  , 10, 1);
  35:  END;
  36:  Go
  37:   
  38:  SET ANSI_Nulls ON;
  39:  SET Ansi_Padding ON;
  40:  SET Ansi_Warnings ON;
  41:  SET ArithAbort ON;
  42:  SET Concat_Null_Yields_Null ON;
  43:  SET NOCOUNT ON;
  44:  SET Numeric_RoundAbort OFF;
  45:  SET Quoted_Identifier ON;
  46:  Go
  47:   
  48:  ALTER PROCEDURE dbo.dba_indexDefragStandard_sp
  49:   
  50:  /* Declare Parameters */
  51:  @minFragmentation     FLOAT           = 10.0
  52:  /* in percent, will not defrag if fragmentation
  53:  less than specified */
  54:  , @rebuildThreshold     FLOAT           = 30.0
  55:  /* in percent, greater than @rebuildThreshold
  56:  will result in rebuild instead of reorg */
  57:  , @executeSQL           BIT             = 1
  58:  /* 1 = execute; 0 = print command only */
  59:  , @tableName            VARCHAR(4000)   = Null
  60:  /* Option to specify a table name */
  61:  , @printCommands        BIT             = 0
  62:  /* 1 = print commands; 0 = do not print commands */
  63:  , @printFragmentation   BIT             = 0
  64:  /* 1 = print fragmentation prior to defrag;
  65:  0 = do not print */
  66:  , @defragDelay          CHAR(8)         = '00:00:05'
  67:  /* time to wait between defrag commands */
  68:  AS
  69:  /********************************************************************
  70:  Name:       dba_indexDefragStandard_sp
  71:   
  72:  Author:     Michelle F. Ufford
  73:   
  74:  Purpose:    Defrags all indexes for the current database
  75:   
  76:  Notes:      This script was designed for SQL Server 2005
  77:  Standard edition.
  78:   
  79:  CAUTION: Monitor transaction log if executing for the first time!
  80:   
  81:  @minFragmentation     defaulted to 10%, will not defrag if
  82:  fragmentation if less than specified.
  83:   
  84:  @rebuildThreshold     defaulted to 30% as recommended by
  85:  Microsoft in BOL;
  86:  > than 30% will result in rebuild instead
  87:   
  88:  @executeSQL           1 = execute the SQL generated by this proc;
  89:  0 = print command only
  90:   
  91:  @tableName            Specify if you only want to defrag indexes
  92:  for a specific table
  93:   
  94:  @printCommands        1 = print commands to screen;
  95:  0 = do not print commands
  96:   
  97:  @printFragmentation   1 = print fragmentation to screen;
  98:  0 = do not print fragmentation
  99:   
 100:  @defragDelay          time to wait between defrag commands;
 101:  gives the server some time to catch up
 102:   
 103:  Called by:  SQL Agent Job or DBA
 104:   
 105:  Date        Initials  Description
 106:  ----------------------------------------------------------------
 107:  2008-10-27  MFU       Initial Release
 108:  2008-11-17  MFU       Added page_count to log table
 109:  , added @printFragmentation option
 110:  ********************************************************************
 111:  Exec dbo.dba_indexDefragStandard_sp
 112:  @executeSQL         = 1
 113:  , @printCommands      = 1
 114:  , @minFragmentation   = 0
 115:  , @printFragmentation = 1;
 116:  ********************************************************************/
 117:   
 118:  SET NOCOUNT ON;
 119:  SET XACT_Abort ON;
 120:   
 121:  BEGIN
 122:   
 123:  /* Declare our variables */
 124:  DECLARE   @objectID         INT
 125:  , @indexID          INT
 126:  , @schemaName       NVARCHAR(130)
 127:  , @objectName       NVARCHAR(130)
 128:  , @indexName        NVARCHAR(130)
 129:  , @fragmentation    FLOAT
 130:  , @pageCount        INT
 131:  , @sqlCommand       NVARCHAR(4000)
 132:  , @rebuildCommand   NVARCHAR(200)
 133:  , @dateTimeStart    DATETIME
 134:  , @dateTimeEnd      DATETIME
 135:  , @containsLOB      BIT;
 136:   
 137:  /* Just a little validation... */
 138:  IF @minFragmentation Not Between 0.00 And 100.0
 139:  SET @minFragmentation = 10.0;
 140:   
 141:  IF @rebuildThreshold Not Between 0.00 And 100.0
 142:  SET @rebuildThreshold = 30.0;
 143:   
 144:  IF @defragDelay Not Like '00:[0-5][0-9]:[0-5][0-9]'
 145:  SET @defragDelay = '00:00:05';
 146:   
 147:  /* Determine which indexes to defrag using our
 148:  user-defined parameters */
 149:  SELECT
 150:  OBJECT_ID AS objectID
 151:  , index_id AS indexID
 152:  , avg_fragmentation_in_percent AS fragmentation
 153:  , page_count
 154:  , 0 AS 'defragStatus'
 155:  /* 0 = unprocessed, 1 = processed */
 156:  INTO #indexDefragList
 157:  FROM sys.dm_db_index_physical_stats
 158:  (DB_ID(), OBJECT_ID(@tableName), NULL , NULL, N'Limited')
 159:  WHERE avg_fragmentation_in_percent > @minFragmentation
 160:  And index_id > 0
 161:  OPTION (MaxDop 1);
 162:   
 163:  /* Create a clustered index to boost performance a little */
 164:  CREATE CLUSTERED INDEX CIX_temp_indexDefragList
 165:  ON #indexDefragList(objectID, indexID);
 166:   
 167:  /* Begin our loop for defragging */
 168:  WHILE (SELECT COUNT(*) FROM #indexDefragList
 169:  WHERE defragStatus = 0) > 0
 170:  BEGIN
 171:   
 172:  /* Grab the most fragmented index first to defrag */
 173:  SELECT TOP 1
 174:  @objectID         = objectID
 175:  , @fragmentation    = fragmentation
 176:  , @indexID          = indexID
 177:  , @pageCount        = page_count
 178:  FROM #indexDefragList
 179:  WHERE defragStatus = 0
 180:  ORDER BY fragmentation DESC;
 181:   
 182:  /* Look up index information */
 183:  SELECT @objectName = QUOTENAME(o.name)
 184:  , @schemaName = QUOTENAME(s.name)
 185:  FROM sys.objects AS o
 186:  Inner Join sys.schemas AS s
 187:  ON s.schema_id = o.schema_id
 188:  WHERE o.OBJECT_ID = @objectID;
 189:   
 190:  SELECT @indexName = QUOTENAME(name)
 191:  FROM sys.indexes
 192:  WHERE OBJECT_ID = @objectID
 193:  And index_id = @indexID
 194:  And type > 0;
 195:   
 196:  /* Look for LOBs */
 197:  SELECT TOP 1
 198:  @containsLOB = column_id
 199:  FROM sys.columns WITH (NOLOCK)
 200:  WHERE
 201:  [OBJECT_ID] = @objectID
 202:  And (system_type_id In (34, 35, 99)
 203:  -- 34 = image, 35 = text, 99 = ntext
 204:  Or max_length = -1);
 205:  -- varbinary(max), varchar(max), nvarchar(max), xml
 206:   
 207:  /* See if we should rebuild or reorganize; handle thusly */
 208:  IF @fragmentation < @rebuildThreshold             Or IsNull(@containsLOB, 0) > 0
 209:  -- Cannot rebuild if the table has one or more LOB
 210:  SET @sqlCommand = N'Alter Index ' + @indexName + N' On '
 211:  + @schemaName + N'.' + @objectName + N' ReOrganize;'
 212:  ELSE
 213:  SET @sqlCommand = N'Alter Index ' + @indexName + N' On '
 214:  + @schemaName + N'.' + @objectName +  ' Rebuild '
 215:  + 'With (MaxDop = 1)'; -- minimize impact on server
 216:   
 217:  /* Are we executing the SQL?  If so, do it */
 218:  IF @executeSQL = 1
 219:  BEGIN
 220:   
 221:  /* Grab the time for logging purposes */
 222:  SET @dateTimeStart  = GETDATE();
 223:  EXECUTE (@sqlCommand);
 224:  SET @dateTimeEnd  = GETDATE();
 225:   
 226:  /* Log our actions */
 227:  INSERT INTO dbo.dba_indexDefragLog
 228:  (
 229:  objectID
 230:  , objectName
 231:  , indexID
 232:  , indexName
 233:  , fragmentation
 234:  , page_count
 235:  , dateTimeStart
 236:  , durationSeconds
 237:  )
 238:  SELECT
 239:  @objectID
 240:  , @objectName
 241:  , @indexID
 242:  , @indexName
 243:  , @fragmentation
 244:  , @pageCount
 245:  , @dateTimeStart
 246:  , DATEDIFF(SECOND, @dateTimeStart, @dateTimeEnd);
 247:   
 248:  /* Just a little breather for the server */
 249:  WAITFOR Delay @defragDelay;
 250:   
 251:  /* Print if specified to do so */
 252:  IF @printCommands = 1
 253:  PRINT N'Executed: ' + @sqlCommand;
 254:  END
 255:  ELSE
 256:  /* Looks like we're not executing, just print
 257:  the commands */
 258:  BEGIN
 259:  IF @printCommands = 1
 260:  PRINT @sqlCommand;
 261:  END
 262:   
 263:  /* Update our index defrag list when we've
 264:  finished with that index */
 265:  UPDATE #indexDefragList
 266:  SET defragStatus = 1
 267:  WHERE objectID  = @objectID
 268:  And indexID   = @indexID;
 269:   
 270:  END
 271:   
 272:  /* Do we want to output our fragmentation results? */
 273:  IF @printFragmentation = 1
 274:  SELECT idl.objectID
 275:  , o.name AS 'tableName'
 276:  , idl.indexID
 277:  , i.name AS 'indexName'
 278:  , idl.fragmentation
 279:  , idl.page_count
 280:  FROM #indexDefragList AS idl
 281:  JOIN sys.objects AS o
 282:  ON idl.objectID = o.OBJECT_ID
 283:  JOIN sys.indexes AS i
 284:  ON idl.objectID = i.OBJECT_ID
 285:  AND idl.indexID = i.index_id;
 286:   
 287:  /* When everything is done, make sure to get rid of
 288:  our temp table */
 289:  DROP TABLE #indexDefragList;
 290:   
 291:  SET NOCOUNT OFF;
 292:  RETURN 0
 293:  END
 294:  Go

Thursday 30 October 2008

SQL Server Language Settings

This is to solve the problem where we want to be using British English in SQL but it insists in using US English.


   1:  PRINT @@LANGUAGE

Will show you current default server language (should be British).


   1:  sp_defaultlanguage 'your-domain\your-username'

will make your username take on the default of the server. (of course replace username with the one you want to change). If the logins are done via groups and not individual users, you will need to change the group's default language (by using the group instead of the specific user as parameter to sp_defaultlanguage).

also read for more information:

sp_defaultlanguage doc:
http://doc.ddart.net/mssql/sql70/sp_da-di_7.htm

default language options:
http://msdn.microsoft.com/en-us/library/aa196707(SQL.80).aspx

sp_configure doc:
http://msdn.microsoft.com/en-us/library/aa259616(SQL.80).aspx

If all fails you can use SET DATEFORMAT eg


   1:  SET DATEFORMAT dmy

for European, inside the stored procedure you are executing, but I prefer the first solution based on user settings. On the other hand the SET DATEFORMAT command in the stored procedure makes it more robust, its up to you.

Failing all can use:


   1:  ALTER LOGIN user1 WITH DEFAULT_LANGUAGE = British

Friday 24 October 2008

Programmatically select DataGridView row

This can be useful if we are updating a row in a DataGridView and we want to refresh the DataSource, still the selected row to remain the same.


   1:  if (selectedIndex > -1 && dataGridView1.Rows.Count > selectedIndex)
   2:  {
   3:      dataGridView1.Rows[selectedIndex].Selected = true;
   4:      dataGridView1.FirstDisplayedScrollingRowIndex = selectedIndex;
   5:  }

Monday 20 October 2008

Recycling

Freecycle (www.freecycle.org) is a place to pass along no longer needed items and possibly find something you need - better passed along than in a landfill. A LaserJet III probably won't be your first choice for a business proposal or resume, but it's OK for a draft copy of anything or printing a program listing. It's a great deal if it's free and toner cartridges are still plentiful and cheap.

Craig's List (www.craigslist.org) has free, for sale, and wanted sections. You can find lawn and garden, furniture, computers, entertainment gear, kids' stuff and lots more. That 18 year old truck was sold via Craig's list and I had cash-in-hand in 24 hours from the time the ad was posted - there's no charge to post or sell on Craig's List.

Portable database VistaDB

This is an alternative to sqlite, http://vistadb.net/vistadb3/features.aspx. Although it is commercial, they also offer a free version. The database is written in .NET and seems to have all the basic features you would want. Worth considering for projects requiring a small database.

Tuesday 14 October 2008

Active directory group and member properties, DirectorySearcher PropertiesToLoad possible values

Normally you would use code like this, to retrieve values for specific properties of an Active Directory group (specified in string groupName):


   1:  DirectorySearcher search = new DirectorySearcher {Filter = String.Format("(cn={0})", groupName)};
   2:  search.PropertiesToLoad.Add("member"); 
   3:   
   4:  List<string> userNames = new List<string>();
   5:   
   6:  if (result != null)
   7:  {
   8:     for (int counter = 0; counter < result.Properties["member"].Count; counter++)  
   9:     {
  10:        string user = (string)result.Properties["member"][counter];
  11:        userNames.Add(user + Environment.NewLine);
  12:     }
  13:  }
  14:   
  15:  return userNames;

but what are the possible values of properties you can use in PropertiesToLoad.Add()? I couldnt find this information anywhere so I wrote a little snippet to retrieve them, here is the result (29 properties)

textencodedoraddress
distinguishedname
dscorepropagationdata
grouptype
objectsid
whencreated
msexchalobjectversion
mailnickname
name
usnchanged
objectcategory
samaccounttype
instancetype
reporttooriginator
cn
proxyaddresses
showinaddressbook
objectclass
mail
usncreated
member
objectguid
adspath
displayname
legacyexchangedn
samaccountname
whenchanged
memberof
msexchpoliciesincluded

The best programming fonts list... ever

http://www.codeproject.com/KB/work/FontSurvey.aspx

Thursday 9 October 2008

XML command line manipulation open source utility

This might be handy if you have to do a lot of work with XML, or even to quickly query large XML files that you want to search for specific information, although I don't know how well it can deal with large files:

http://xmlstar.sourceforge.net/

Tuesday 7 October 2008

Friday 26 September 2008

Linked server double hop

This is the best article I've found regarding the proper setup of servers for double hop in MS SQL 2005: http://blogs.msdn.com/sql_protocols/archive/2006/08/10/694657.aspx

It is the best overview and most complete and yet simple explanation of the problem and the solution.

Wednesday 24 September 2008

How to make objects available as datasources for databound controls

This attribute goes to the class:


   1:  // makes objects of this class suitable for binding to controls
   2:  [System.ComponentModel.DataObject] 

And this goes to the method:


   1:  // this attribute is so that the method will show up in the 
   2:  // ObjectDataSource wizard
   3:  [System.ComponentModel.DataObjectMethodAttribute(
   4:  System.ComponentModel.DataObjectMethodType.Select, true)]

Tuesday 16 September 2008

Finally CodePlex supports svn!!!

Now I don't know yet how good this support is, but you can read all about it here:

http://blogs.msdn.com/codeplex/archive/2008/09/14/codeplex-launches-support-for-tortoisesvn.aspx

They used to support svn in the past but it required a local installation of SvnBridge. Now it is integrated into their repository.

Typical URL format is https://projectname.svn.codeplex.com/svn

Tuesday 2 September 2008

20 tech habits to improve your life

Very good read, with some useful tips: 20 tech habits to improve your life

The .NET source code

Official site for the .NET source code, including instructions (although out of date in VS 2008 last time I checked, they were for VS 2005...)
http://referencesource.microsoft.com/serversetup.aspx

For VS 2008 SP1 there is another option which is not included in the Microsoft website at this moment:

Wizard implementation in C#

Very nice article explaining the implementation of a wizard in C#. The article skips over some details of the implementation (i.e. it is unclear at some points) but this is not a problem because clarification can be obtained by looking at the source code which is provided. On the other hand, the article has a comprehensive coverage of various events and it is definitely a worthwhile read. No doubt Microsoft will come up with some wizard component in the future, but until they do, this is a good alternative, and it any case a very educational resource.

Part 1
Part 2

Thursday 28 August 2008

Visual Studio 2008 code clone detective

Nice tool for improving code quality (removing redundancy). Free VS addon and it actually works, it’s quite cool. Currently available for C# only.

It works by identifying potential code duplication. Sadly it does not do anything resolving the issue at this stage, but it still helps to point out areas where code quality could be improved.

Article: http://www.infoworld.com/archives/emailPrint.jsp?R=printThis&A=/article/08/08/27/Cloned-code-finder-offered-for-Visual-Studio_1.html

Project : http://www.codeplex.com/CloneDetectiveVS

Monday 18 August 2008

Nice paging stored procedure in MS SQL T-SQL

This also demonstrates the use of the WITH heyword.

CREATE PROCEDURE [dbo].[Employee_Paged] ( @maximumRows int = 10, @startRowIndex int = 1 ) AS

BEGIN

SET NOCOUNT ON;

WITH [EmployeeByPage] AS

(

SELECT

row_number() OVER (ORDER BY Employee.Id ASC) AS rowid,

Employee.Id,

Employee.Name

FROM

Employee

)

SELECT

Paged.Id,

Paged.Name

FROM

[EmployeeByPage] AS Paged

WHERE

Paged.rowid BETWEEN @startRowIndex AND @startRowIndex + @maximumRows

END


Source: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3263486&SiteID=1

And some irrelevant links...

interesting reads:

8 ways to make money online

Startup Ideas

Friday 8 August 2008

Call .NET dll from MS SQL server - analyse query plan

This is a very well presented article which explains how we can obtain the query plan - estimated execution time for a query in SQL Server. It is also very useful because we can see in detail the process of registering and calling a .NET assembly from within SQL Server. Applies to: Microsoft SQL Server 2005 and Microsoft Visual C# .NET, but most likely will be possible to use a similar or even the same process in SQL Server 2008 and later.

http://technet.microsoft.com/en-us/library/ms345130.aspx

Friday 1 August 2008

C# code beautifier

I came across this interesting project for C# code beautification - Still haven't tested it. It seems in early development stage, but it does look promising for the future.

http://narrange.sourceforge.net/

Tuesday 29 July 2008

Fast row count on large tables

This statement uses Dynamic Management Views to get the row count of a table. It can be considerably faster when we want to get the row count of a very large table, since the conventional way "select count(*) from table" would require a full table scan.


   1:  SELECT
   2:  Total_Rows= SUM(st.row_count)
   3:  FROM
   4:  sys.dm_db_partition_stats st
   5:  WHERE
   6:  object_name(object_id) = 'table_name_here'

Monday 28 July 2008

Offline Browsing

Interesting open source project for offline browsing: http://www.httrack.com/

It can also be used to build HTTP Caches using archived websites copied by it.

Friday 25 July 2008

Dynamic Bulkinsert directory using server name

This command can be used to dynamically create the path for a file based on the current instance. It assumes each instance server has a directory called BulkInsert which we use to store the csv files we want to import.


   1:  select '\\' + substring(@@servername, 1, charindex('\', @@servername)) + 'BulkInsert\filename.csv'

Tuesday 22 July 2008

svn ignore list for C# / Visual Studio files

This is a list of ignore items I find useful. It includes the Ankh and Resharper addons. Note that it also includes the .dll files, which sometimes might be needed, for example if we don't have the source code or for some other reason we don't want to build the dll. In this case if the ignore is applied recursively, we need to manually allow the dll in the directory of interest.

*.suo
*.user
Ankh.*
Bin
*.exe
*.pdb
*.resharper
*.gpState
_ReSharper.*
*/bin
*/obj
*/Release
*/Debug
*.err
*.log
*.obj
*.bin
*.dll
*.LOG
[tT]emp
[tT]empPE
thumbs.db

Friday 18 July 2008

Database ANSI Padding

char , NOT NULL , ANSI PADDING (ON) : Trailing spaces to length of column created

char, NOT NULL, ANSI PADDING (OFF): Trailing spaces to length of column created

char, NULL, ANSI PADDING (ON): Trailing spaces to length of column created

char, NULL, ANSI PADDING (OFF): Variable storage, no trailing spaces created, trailing spaces present are preseverd

varchar , NOT NULL , ANSI PADDING (ON) : Variable storage, no trailing spaces created, yet trailing spaces present are preserved

varchar, NOT NULL, ANSI PADDING (OFF): Variable storage, no trailing spaces created

varchar, NULL, ANSI PADDING (ON): Variable storage, no trailing spaces created,yet trailing spaces present are preserved

varchar, NULL, ANSI PADDING (OFF): Variable storage, no trailing spaces created

source: http://channel9.msdn.com/forums/TechOff/190401-Variable-length-fields-and-fixed-length-fields-in-MSSQL/

Friday 4 July 2008

Thursday 3 July 2008

How to take over a database...

--Disconnects people from the database


   1:  alter database dbname
   2:  set single_user with rollback immediate

--Allows only db owners to connect. This step must be run because if you leave it in single user mode then the Redgate GUI cannot connect.
--If you are copying and pasting the Redgate script into the same window as the above script then you do not need to run this step.


   1:  alter database dbname
   2:  set restricted_user

Monday 23 June 2008

Executing external applications

Some interesting information about setting up an external application (command line) and executing it without a visible window. Allows for capturing the stdout, stdin and stderr streams too. This example is for launching the command line svn client with info argument about a specific file in the svn repository, and capturing the result of our query.

   1:  Process svnProcess = new Process();
   2:  svnProcess.StartInfo.FileName = "svn.exe";
   3:  svnProcess.StartInfo.Arguments = " info " + svnUri;
   4:  svnProcess.StartInfo.UseShellExecute = false;
   5:  svnProcess.StartInfo.RedirectStandardOutput = true;
   6:  svnProcess.StartInfo.RedirectStandardError = true;
   7:  svnProcess.StartInfo.RedirectStandardInput = true;
   8:  svnProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
   9:  svnProcess.StartInfo.CreateNoWindow = true;
  10:   
  11:  try
  12:  {
  13:      bool started = svnProcess.Start();
  14:      if (!started)
  15:      {
  16:          Log.WriteLog("Unable to start svn.exe process, aborting.", "svnInfoError.log", true, true);
  17:          MessageBox.Show("Unable to start svn.exe process.", "Error launching svn.exe", MessageBoxButtons.OK, MessageBoxIcon.Error);
  18:          return -1;
  19:      }
  20:  }
  21:  catch (Exception ex)
  22:  {
  23:      Log.WriteLog("Unable to start svn.exe process, aborting.", "svnInfoError.log", true, true);
  24:      MessageBox.Show("Unable to start svn.exe process.", "Error launching svn.exe", MessageBoxButtons.OK, MessageBoxIcon.Error);
  25:      return -1;
  26:  }
  27:   
  28:  StreamReader sOut = svnProcess.StandardOutput;
  29:  string output;
  30:   
  31:  while (svnProcess.HasExited == false)
  32:  {
  33:      output = sOut.ReadLine();
  34:      if (output != null)
  35:      {
  36:          if (output.StartsWith("Last Changed Rev: "))
  37:          {
  38:              string revNumberString = output.Substring("Last Changed Rev: ".Length);
  39:              int revNumber;
  40:              if (int.TryParse(revNumberString, out revNumber))
  41:              {
  42:                  sOut.Close();
  43:                  return revNumber;
  44:              }
  45:              else
  46:              {
  47:                  throw new Exception("Could not parse the svn revision number!!!");
  48:              }
  49:          }
  50:      }
  51:  }
  52:   
  53:  do
  54:  {
  55:      output = sOut.ReadLine();
  56:      if (output != null)
  57:      {
  58:          if (output.StartsWith("Last Changed Rev: "))
  59:          {
  60:              string revNumberString = output.Substring("Last Changed Rev: ".Length);
  61:              int revNumber;
  62:              if (int.TryParse(revNumberString, out revNumber))
  63:              {
  64:                  sOut.Close();
  65:                  return revNumber;
  66:              }
  67:              else
  68:              {
  69:                  throw new Exception("Could not parse the svn revision number!!!");
  70:              }
  71:          }
  72:      }
  73:  } while (output != null);
  74:   
  75:   
  76:  string error = svnProcess.StandardError.ReadToEnd();
  77:  if (string.IsNullOrEmpty(error) == false)
  78:  {
  79:      Log.WriteLog(error, "svnInfoError.log", true, true);
  80:   
  81:  }
  82:  return -1; // Error executing the svn client application!!!

Friday 20 June 2008

Ankhsvn, VS 2008 and subversion.

Today I realised that Ankhsvn, VS 2008 and subversion don't play very well together. As soon as I installed subversion my Ankhsvn VS 2008 plugin refused to work. Tried uninstalling it and installing every possible version with no success.

The final solution was to remove subversion, and just use the subversion zip file to extract the executable that I needed. It seems that the problem is some conflict between the subversion installer and Ankhsvn. In any case I am glad I managed to resolve this.

Thursday 19 June 2008

.NET events and event handlers

This is a simple description of events and handlers. Does not include custom event arguments.

Child class is the source of the events and Parent class is the sink or consumer of the events. The parent reacts to events originating at the child class.

1. In child class:

A. Declare a delegate defining the signature of event handlers. Parent class functions that handle our events need to implement this delegate. This delegate is required in order to define events in this class.

Example: child class is Car, containing the following delegate:


   1:  public delegate void CarEventHandler(string msg);

B. Declare event names and associate them to the delegate above. These are events this class can send out to subscribers.

Example:


   1:  public event CarEventHandler Exploded;
   2:  public event CarEventHandler AboutToBlow;

C. When certain conditions are met, first check event for null and fire it (with same parameters as the delegate - these will be passed on to the handler).

Example:


   1:  public void Accelerate(int delta)
   2:  {
   3:      // If the car is dead, fire Exploded event.
   4:      if (carIsDead)
   5:          if (Exploded != null)
   6:              Exploded(this, new CarEventArgs("Sorry, this car is dead..."));
   7:  }


2. In parent class:

A. Define one or more functions implementing the event delegate that will perform the action required when the event fires.

Example:


   1:  public static void CarExploded(string msg)
   2:  {
   3:      Console.WriteLine(msg);
   4:  }

B. Create an event handler, associating it with the handling function in the child class, as defined above.


   1:  Car.CarEventHandler carExplodedEventHandler = new Car.CarEventHandler(CarExploded);

C. Register the handler we created with the child class event type we want to handle (usually right after we create this object). If c1 is an object of the type in the child class,


   1:  c1.Exploded += carExplodedEventHandler ;


Now whenever the event fires in the child class, the delegate will execute the CarExploded(string msg) function in the parent class.


   1:  public void Accelerate(int delta)
   2:  {
   3:      // If the car is dead, fire Exploded event.
   4:      if (carIsDead)
   5:      if (Exploded != null)
   6:      Exploded(this,
   7:      new CarEventArgs("Sorry, this car is dead..."));
   8:  }

IMPORTANT NOTE: If you want to refer to a non static function (to fire when the event occurs i.e. function CarExploded in this example) you need to declare it at the class level, but initialise it in the parent class constructor. When declaring the event handler you can declare it readonly. I.e.:

Step 2B becomes:


   1:  readonly Car.CarEventHandler carExplodedEventHandler; // above the constructor

and inside the constructor:


   1:  carExplodedEventHandler = CarExploded;