Archive for the ‘Code and Development’ Category

How I write Equals and GetHashCode in csharp

April 25th, 2014

My code is copied with pride from the net.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
///
This is standard overridden Equals method.
/// Code is copied with pride from
/// http://msdn.microsoft.com/en-us/library/336aedhh(v=vs.85).aspx
///

//////
public override bool Equals(object obj)
{
if (null == obj || GetType() != obj.GetType())
{
return false;
}
var b = (MyType)obj;
return
this.Property1 == b.Property1 &&
...
this.PropertyN == b.PropertyN;
}

///
This is the ordinary overriden GetHashCode
/// with code proudly copied from
/// http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode
///

///
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
const int Salt = 23;
var hash = 17;
hash = hash + Salt * Property1.GetHashCode();
...
hash = hash + Salt * (null == PropertyN ? 0 : PropertyN.GetHashCode());  // Nullable values has to be taken care of.
return hash;
}
}

Unit testing private methods

March 25th, 2014

Read here instead.

I have a dirty but simple way to unit test private methods.

I create a wrapper method that I prefix with UT_ and write a comment that is only used for unit testing.
To be honest I haven’t done this on a public API but I wouldn’t hesitate for a public-within-a-company method.

1
2
3
4
5
6
7
8
9
10
11
12
</del>

<del>private int MyMethod( int myParameter ){</del>
<del> ComplexBusinessLogic...</del>
<del> }</del>

<del>///&lt;summary&gt;This helper method is only used for unit testing. Do Not call it in normal operations.&lt;/summary&gt;</del>
<del> internal int UT_MyMethod( int myParameter ){</del>
<del> return MyMethod( myParameter );</del>
<del> }</del>

<del>

I use InternalsVisibleTo to make internals visible to my unit testing project.

One can play with protected methods and inheritance too.

Compile aspnet mvc views (*.cshtml)

January 26th, 2014

To make a long story short one can compile the views in asp net mvc.

It takes considerable time though so I only activate it for release compilations.

Update the build file with


1
&lt;MvcBuildViews Condition=" '$(Configuration)' == 'Release' "&gt;true&lt;/MvcBuildViews&gt;

Like so:


1
2
&lt;TargetFrameworkVersion&gt;v4.0&lt;/TargetFrameworkVersion&gt;
&lt;MvcBuildViews Condition=" '$(Configuration)' == 'Release' "&gt;true&lt;/MvcBuildViews&gt;

I am sorry about all &gt; and &lt; but I don’t have the time right now to make everything look pretty. Just replace &gt; with < and &lt; with > and your good to go.
Or follow the links below with the awesome formatting Stack overflow provides.

Honour those who should. Especially this answer that does the only-release trick.

There are mainly 2 ways to keep a running project running – change or not

July 31st, 2013

When a project goes live it enters the maintenance phase. Further development changes.

There are mainly two ways to keep said project running.

Great wall of China

The first is to pretend the world is not (r)evolving and keep the project in a stable state.
This means one must consider present and future changes and make sure these don’t affect the system.
Unfortunately this also means changes are slow and expensive; not necessarily because of code base but of management who believes the system will work and not have to be changed because changing costs money.

What often happens is that changes are postponed until a bug or security issue surfaces in the OS, underlying framework and changes must occur. Note that I wrote “OS” and “underlying framework” and not the project specific code. The world did (r)evolve despite intentions.

Continuous change

The other method is to acknowledge that the world changes and change accordingly. The world changes continuously so allow the project to change continuously.

What comes out of this is also that every change becomes cheaper, both in money and in administration and in percieved load for management. Bugs and features are also fixed and implemented faster which benefits the business.

Testing internal classes without making them public

May 15th, 2013

…with a trick to make private methods testable too.

When doing automatic tests one often wants to get to the internal classes.

Testing internal stuff

The possibly simplest way is to use InternalsVisbleTo and write

1
[assembly:InternalsVisibleTo("MyTestingProject.With.FullName)]

in the testee’s AssemblyInfo.cs

Or one can write just before the namespace declaration too

1
2
3
4
[assembly:InternalsVisibleTo("MyOtherProjectNameLikeExampleAbove")]
namespace Whatever{
class Hello{
...

<shrugging shoulders>Thats all there is to it.</shrugging>

The namespace is System.Runtime.CompilerServices.

One can decorate InternalsVisibleTo with keys and stuff to harden who gets to the internals but why bother? As long as it is dotnet some reflection can get pass the threshold anyway.

Testing private stuff

Another way I have used is to make a wrapping class “UT_Customer” or method “UT_Create” that 1) wraps the internal class/method, 2) is public and 3) is clearly marked with something conspicuous like “UT?_”. If a drive by programmer sees a method with a weird name and doesn’t bother to read the xml comments and still uses the method and fails; I consider it his fault, not mine. Not that I would use an undocumented method, no never.

1
2
3
4
5
private int AddCustomer(Customer customer){...}

internal int UT_AddCustomer(Customer customer){
return AddCustomer(customer);
}

Moq caveat

There is a caveat where interfaces are not visible for Moq as described here.

The symptom is an error message like

Message: Initialization method Base.UnitTests.Command.CommandHandlerTest thre exception.
Castle.DynamicProxy.Generators.GeneratorException:
Castle.DynamicProxy.Generators.GeneratorException: Type Base.Command.IUndoRedoStack[[Base.Command.ICommand, Base, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] is not public. Can not create proxy for types that are not accessible.

The remedy is to add

1
[assembly:InternalsVisibleTo("DynamicProxyGenAssembly2")]

Update

I see at Metzianou that one can add build variable stuff like $(AssemblyName) like so:


1
&lt;InternalsVisibleTo Include="$(AssemblyName).Tests" /&gt;

Minfied respond.js does not work in unpatched IE7

May 14th, 2013

I haven’t the full reason for the problem – exactly which implicit line ending that goes wrong – or whatever else that is broken.  But the (almost) fix is – don’t use the minified version.  At github you can get either version as (respond.min.js or respond.src.js).  Go for the latter, it is the non-minified one.

In my unlatched IE7 I get a somewhat stocastic behaviour.  When just browsing it first fails but a reload makes the page load properly.
When I debug both the debugger and IE freezes at a regular javascript row in respond.js.  “document = doc.documentElement”.  This is also where I give up.

Other browsers – including Safari/Ipad and built-in/Android seems to work alright with the minified version.

Tip when using DebuggerDisplay in Dotnet/Visual studio

March 7th, 2013

When debugging and watching an object one only sees the name of the type in the debugger.

1
MyProjectNamespace.Meeting

The quickest solution is to click the little plus sign or use the keyboard right arrow to show the properties. This is ok to do once or twice but doing this for every comparison is a waste of time at best.

Better then is to use SystemDiagnostics.DebuggerDisplay like so:

1
2
3
[DebuggerDisplay("ID:{ID}, UID:{UID}, Name:{Name}, Type:{this.GetType()}")]
public class Meeting : BaseClass {
...

to get

1
ID:1, UID:234abc, Name:XYZ, Type:MyProjectNamespace.Meeting

The Tip was to use {this.GetType()} in the argument of DebuggerDisplay.

Update

To show count of lists use something in the lines of:

1
[DebuggerDisplay("ID:{ID},Customers:{Customers==null?(int?)null:Customers.Count}")]

Update update

Since the DebuggerDisplay parameter is written as is into the assembly it might not work between languages. A solution for this is to call a method instead as most lanuguages uses the MyMethod() syntax.

It is also creates less overhead to call a method instead of having the expression in a string according to the MSDN link below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[DebuggerDisplay("{DebuggerDisplay(),nq}")]
public class ExchangeRateDto
{
public int ID { get; set; }

public string Name { get; set; }

#if DEBUG
private string DebuggerDisplay()
{
return
$"ID:{this.ID}, Name:{this.Name}, Type:{this.GetType()}";
}
}
#endif

Update update update

Use nameof. Also skip the this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[DebuggerDisplay("{DebuggerDisplay(),nq}")]
public class ExchangeRateDto
{
public int ID { get; set; }

public string Name { get; set; }

#if DEBUG
private string DebuggerDisplay()
{
return
$"{nameof(ID)}:{ID}, {nameof(Name)}:{Name}, Type:{GetType()}";
}
}
#endif

Update update update update

I have noticed that in Visual Studio 2022 (possibly earlier) one can ctrl-. on the class or record name and Visual studio writes the boilerplate code. The DebuggerDisplay is called GetDebuggerDisplay and only returns this.ToString() unfortunately. So it has to be adapted.

Praise where praise is due: https://blogs.msdn.microsoft.com/jaredpar/2011/03/18/debuggerdisplay-attribute-best-practices/.

There is more documentation at Stack overflow documentation.

Search Term: DebuggerDisplayAttribute

Visual studio snippet for an enhanced #region in csharp

March 2nd, 2013

Visual studio contains snippets.  These are “shortcuts” for writing various code.  Try writing for in the editor and text is typed in for you and you get placeholders for faster code writing.

One can write code like this oneself.  It is quite easy.  Just go to menu->Tools->Code snippets manager and work from there; copy, paste and rewrite to your will.  (The location field is the folder of the very snippets.)

Here is an example of mine.

I know that some people swear that #region is the devil’s own child but there are other, let’s call us them for pragmatists for now that say that if it fits it fits.  The standard snippet outcome for a region is

1
2
3
4
5
#region // Name of region.
//code
//code
//code
#endregion

but I prefer

1
2
3
4
5
#region // Name of region.
//code
//code
//code
#endregion // Name of region.

So I just copypasted the existing snippet to this; which you can import through above mentioned menu.<?xml version=”1.0″ encoding=”utf-8″ ?>

<CodeSnippets xmlns=”http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet”>
<CodeSnippet Format=”1.0.0″>
<Header>
<Title>#region</Title>
<Shortcut>region</Shortcut>
<Description>Code snippet for #region</Description>
<Author>Microsoft Corporation</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
<SnippetType>SurroundsWith</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>name</ID>
<ToolTip>Region name</ToolTip>
<Default>MyRegion</Default>
</Literal>
</Declarations>
<Code Language=”csharp”><![CDATA[#region $name$
$selected$ $end$
#endregion // $name$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>

Shortcuts when doing Visual studio unit test debugging

February 27th, 2013

Short story: http://msdn.microsoft.com/en-us/library/ms182470.aspx

I still miss a shortcut for “Debug the last unit test”.  There is “Repeat the last run” but that runs and doesn’t debug.  Strange since that is what I during times use the most.  I have resorted to marking the test and the alt-s-d-enter.

Also: Resharper interferes with the shortcuts but that is more a facet of life I think.

List the size of tables and stuff in a Sqlserver

February 4th, 2013

A simple solution copied from here is

1
sp_msforeachtable "sp_spaceused '?'"

an almost as simple is the one below copied from here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
SET NOCOUNT ON

CREATE TABLE #TBLSize
(Tblname VARCHAR(80),
TblRows INT,
TblReserved VARCHAR(80),
TblData VARCHAR(80),
TblIndex_Size VARCHAR(80),
TblUnused VARCHAR(80))

DECLARE @DBname VARCHAR(80)
DECLARE @tablename VARCHAR(80)

SELECT @DBname = DB_NAME(DB_ID())
PRINT 'User Table size Report for (Server / Database): ' + @@ServerName + ' / ' + @DBName
PRINT ''
PRINT 'By Size Descending'
DECLARE TblName_cursor CURSOR FOR
SELECT NAME
FROM sysobjects
WHERE xType = 'U'

OPEN TblName_cursor

FETCH NEXT FROM TblName_cursor
INTO @tablename

WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO #tblSize(Tblname, TblRows, TblReserved, TblData, TblIndex_Size, TblUnused)
EXEC Sp_SpaceUsed @tablename

-- Get the next author.
FETCH NEXT FROM TblName_cursor
INTO @tablename
END

CLOSE TblName_cursor
DEALLOCATE TblName_cursor

SELECT CAST(Tblname AS VARCHAR(30)) 'Table',
CAST(TblRows AS VARCHAR(14)) 'Row Count',
CAST(LEFT(TblReserved, CHARINDEX(' KB', TblReserved)) AS INT) 'Total Space (KB)',
CAST(TblData AS VARCHAR(14)) 'Data Space',
CAST(TblIndex_Size AS VARCHAR(14)) 'Index Space',
CAST(TblUnused AS VARCHAR(14)) 'Unused Space'
FROM #tblSize
ORDER BY 'Total Space (KB)' DESC

PRINT ''
PRINT 'By Table Name Alphabetical'

SELECT CAST(Tblname AS VARCHAR(30)) 'Table',
CAST(TblRows AS VARCHAR(14)) 'Row Count',
CAST(LEFT(TblReserved, CHARINDEX(' KB', TblReserved)) AS INT) 'Total Space (KB)',
CAST(TblData AS VARCHAR(14)) 'Data Space',
CAST(TblIndex_Size AS VARCHAR(14)) 'Index Space',
CAST(TblUnused AS VARCHAR(14)) 'Unused Space'
FROM #tblSize
ORDER BY 'Table'

DROP TABLE #TblSize