Monday, 12 October 2015

This blog has Moved!

This blog hasn't been particularly active for the last couple years also. My apologies. I have started a new blog where I will post my thoughts and opinions on various topic (mainly technical) from now on. I will also rewrite and tidy up some of my old posts from here. Thanks for reading!!!

https://kelvinbytes.wordpress.com

Thursday, 7 November 2013

Stub VS Shim VS Mock. Differences between Microsoft.Fake framework and Moq framework.

using System;
using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MicrosoftFakesFrameworkPlayClassLibrary;
using Moq;

namespace UnitTestProject
{
    [TestClass]
    public class UnitTest2
    {
        [TestMethod]
        public void TestUsingStub()
        {
            IStockFeed stockFeed =
                new MicrosoftFakesFrameworkPlayClassLibrary.Fakes.StubIStockFeed()
                {
                    GetSharePriceString = (company) => 7890
                };

            var actual = stockFeed.GetSharePrice("bbc");
        }

        [TestMethod]
        public void TestUsingShim()
        {
            using (ShimsContext.Create())
            {
                System.Fakes.ShimDateTime.NowGet = () => new DateTime(2000, 1, 1);

                var now = DateTime.Now;

                Assert.AreEqual(2000, now.Year);
            }
        }

        // To use Mock, you need to deal with Mock Wrap object. While as MS Fakes framework already generated 
        // Stub and Shim objects for you.
        [TestMethod]
        public void TestUsingMock()
        {
            var mock = new Mock();
            mock.Setup(instance => instance.GetSharePrice(It.IsAny())).Returns(1234);

            //Action
            var actual = mock.Object.GetSharePrice("myCompany");

            //Assert
            Assert.AreEqual(1234, actual);
        }
    }
}
                                                                                                                       

Saturday, 2 February 2013

Maybe class for null handling for reference types in C#

"Tony Hoare, the inventor of the null reference, called it his ‘billion dollar mistake.’ Null is a disaster because it means that every reference type has a magic value that will destroy your program. For value types, we now have ‘normal’ value types and nullable value types to express the difference between, say, ‘this function returns an integer’ and ‘this function might return an integer, or it might not.’ But we don’t have that for reference types."
For example, in C# we have int for a normal value and int? for a nullable value. But for reference type like a string, you just don't know until you check it or your program crashed on it.

Ivan Towlson has mentioned a good and compact way to handle nullable type with a Maybe class. Since I don't have his source code, I created my own. If you are interested to use it, just simply download the Maybe.cs class under the MaybeApplication folder from github and use it in your own program. Or you can download the whole project. The project is created in VS2010.

Why should you care? What does the class do?

Ok, instead of doing the null check the old fashion way
        static string DemoTheOldWayOfNullChecking()
        {
            Contact contact = new Contact();
            contact.Name = "Sean";
            contact.Phone = "12345678";
            contact.Age = 24;
            //contact.PersonalPet = new Pet()
            //{
            //    PetName = new PetName()
            //        {
            //            Name = "My Pet"
            //        }
            //};

            if (contact == null)
                return null;

            if (contact.PersonalPet == null)
                return null;

            if (contact.PersonalPet.PetName == null)
                return null;

            var petName = contact.PersonalPet.PetName.Name;
            if (petName == null)
                return null;

            return petName;
        }

Now with some Linq awesomeness, you can do something like this
        static string DemoTheNewWayOfNullChecking()
        {
            Contact contact = new Contact();
            contact.Name = "Sean";
            contact.Phone = "12345678";
            contact.Age = 24;
            //contact.PersonalPet = new Pet()
            //{
            //    PetName = new PetName()
            //        {
            //            Name = "My Pet"
            //        }
            //};

            // Maybe class allow you to do something similar to int? for the reference types.
            Maybe maybeContact = new Maybe(contact);

            var maybePetName = from c in maybeContact
                          from cp in c.PersonalPet
                          from pn in cp.PetName
                          select pn.Name;

            if (maybePetName.HasValue)
                return maybePetName.Value;

            return null;
        }


Reference:
http://www.mindscapehq.com/blog/index.php/2012/03/27/5-12-f-features-every-c-programmer-should-lust-after/

Tuesday, 11 September 2012

Copying files is extremely slow to a vmware vm

Solution 1:

After installing windows 7 64bit on my computer as the host operating system, copying files from the host windows to my linux virtual machine was painfully slow. After some research I found the fix to be :
Going to the control panel -> network and internet-> network connections-> right click on your physical interface -> click on configure-> click on the advanced tab.

In here make sure ipv4 checksum offloader, large send offload v2 ipv4, large send offload v2 ipv6 are disabled.

Solution 2:

You must disable the TCP Offload Engine features in the driver on the host.

To disable the TCP Offload Engine features:
Go to Start > Run.
Type regedit and press Enter.
Browse to:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters


Create a key named DisableTaskOffload, of type DWORD.
Set the value of the key to 1 .
Close the Registry Editor and restart the computer.

Reference:

Wednesday, 22 August 2012

VMWare Performance - vmem file cause harddisk IO busy

I am doing my project work on a vmware virtual machine. I normally will let the vm running over night. The issue is that the VM will hang for at least 15 min everyday morning when I wake it up.

After some investigation, I found there are huge read and write activities on the the *.vmem file in the virtual machine folder. It turns out the vmem file is the backup of your VM's memory. If your VM's memory is big, e.g. 8Gb, there will be a lot of writing to backup the memory to harddisk. 


You can change it by ask vmware to save the memory backup in your host machine's RAM. The catch is that there is no GUI to help you therefore you have to manually modify the vmx file. However it is a easy change. All you need to have is the following line in you vmx file.

mainmem.useNamedFile = "FALSE"



Sunday, 20 May 2012

Prevent a large textbox from getting put on the second page in SSRS

Problem:
When I render a SSRS report in PDF and the textbox is too big or long, it puts my large textbox on the second page and leave the first page with large empty space.

Solution:
In SSRS 2008 R2 and Visual Studio 2008:
Click (not-right click) a textbox and go to the properties window (lower right side of VS) -> KeepTogether = false.
The text will cleanly cut between a line and continue on the next page.

Reference:
http://stackoverflow.com/questions/3111071/dealing-with-very-tall-textboxes-and-pagination-in-ssrs-2005

Tuesday, 15 May 2012

How to disable floating tabs in Visual Studio 2010


Solution1: Ctrl+DoubleClick, it will dock back to its last position.



Solution2: The current version of Productivity Power Tools does support disabling floating tabs: it's in Options > Productivity Power Tools > Document Tab Well > Floating Docs > [ ] Enable floating tab well. Unchecking this stopped all the SSDT Juneau tabs from opening floating for me. ProductivityPower Tools



Wednesday, 28 March 2012

Uses of content-disposition in an HTTP response header

Uses of content-disposition in an HTTP response header

// Download the file
Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);

// Display the file in browser
Response.AppendHeader("content-disposition", "inline; filename=" + fileName);

Reference:
http://stackoverflow.com/questions/1012437/uses-of-content-disposition-in-an-http-response-header

Monday, 26 March 2012

Relative path with asp.net

The main part is to decide if it for the client side or server side which can be sometimes tricky.

Client side
A relative path that is resolved against the current page path.


A relative path that is resolved as a peer of the current page path.


Server side
ASP.NET includes the Web application root operator (~)



http://msdn.microsoft.com/en-us/library/ms178116(v=vs.90).aspx

Sunday, 25 March 2012

TFS Server 2010 with Business Intelligence Studio 2008

If you have upgraded to TFS Server 2010, connectivity from Visual Studio 2008 (shell for SQL Server Business Intelligence Studio 2008) has been a problem. Please follow the steps below in order to resolve this. Note that installation order is important. If you don’t have Team Explorer installed, step 3 will skip and compatibility pack will never install!

1. Install Visual Studio 2008, if it’s not already installed. If you are using BIDS studio 2008, you will have this installed already.

2. Install Team Explorer for Visual Studio 2008, if it’s not already installed http://www.microsoft.com/downloads/en/details.aspx?familyid=0ED12659-3D41-4420-BBB0-A46E51BFCA86&displaylang=en

3. Install Visual Studio 2008 Service Pack 1 http://www.microsoft.com/downloads/en/confirmation.aspx?familyId=fbee1648-7106-44a7-9649-6d9f6d58056e&displayLang=en

4. Install Visual Studio 2008 TFS 2010 Forward Compatibility pack http://www.microsoft.com/downloads/en/details.aspx?displaylang=en&FamilyID=cf13ea45-d17b-4edc-8e6c-6c5b208ec54d

If you encounter any issues, you may want to fix the registry as suggested in the blog – http://blog.jmedved.com/2009/11/visual-studio-2008-and-team-foundation.html

Ref: http://provizinc.wordpress.com/2010/10/08/tfs-server-2010-with-business-intelligence-studio-2008/

Once you install everything, you can try adding Team Foundation Server 2010 as destination, but you will be greeted with error “TF31002: Unable to connect to this Team Foundation Server …”. Reason behind this is that old Team Explorer 2008 does not know anything about collections.

Solution would be to add it as full path (e.g “http://server:8080/tfs/collection”). I could not do it because every time I entered full path, I also got error “TF30335: The server name cannot contain characters ‘/’ or ‘:’ …”. Since official way would not work it was time to come up with alternative.

In order to add TFS 2010 server, you will need to exit Visual Studio 2008 and go into Registry editor. Find key “HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\TeamFoundation\Servers” and at this location just add string value. Name of this value will be what Team Explorer 2008 will use for display. It’s value is full address of your server. It should be something like “http://server:8080/tfs/collection”.

Now you can go into Visual Studio 2008 and Team Explorer will have new entry. As you work with it, you will notice that not everything is “bump-free” (e.g. tasks). However, source control it self will work perfectly and that was enough for me.

Ref: http://www.jmedved.com/2009/11/visual-studio-2008-and-team-foundation-server-2010/

Indexer - Class member

Indexers are syntactic convenience that enable you to create a class, struct or interface that client application can accessed just as an array.

Static readonly vs const

The difference is that the value of a static readonly field is set at run time, and can thus be modified by the containing class, whereas the value of a const field is set to a compile time constant.

In the static readonly case, the containing class is allowed to modify it only

in the variable declaration (through a variable initializer)
in the static constructor (instance constructors, if it's not static)

http://blogs.msdn.com/b/csharpfaq/archive/2004/12/03/274791.aspx

Const values are burned directly into the call-site; this is double edged:

it is useless if the value is fetched at runtime, perhaps from config
if you change the value of a const, you need to rebuild all the clients
but it can be faster, as it avoids a method call...
...which might sometimes have been inlined by the JIT anyway
If the value will never change, then const is fine - Zero etc make reasonable consts ;-p Other than that, static properties are more common.

http://stackoverflow.com/questions/755685/c-static-readonly-vs-const

Wednesday, 21 March 2012

SQL IDENTITY_INSERT

SQL IDENTITY_INSERT is allow values to be inserted into the identity column of a table.
Identity column creates a numeric sequence value for you automatic.

It only allow one table in a session can have the IDENTITY_INSERT property set to ON.
If you need to change the table, you need to set the existing table IDENTITY_INSERT back to OFF.

SET IDENTITY_INSERT TableName OFF

If the value inserted is larger than the current identity value for the table, SQL Server automatically uses the new inserted value as the current identity value.

SET IDENTITY_INSERT TableName ON

http://sqltutorials.blogspot.co.nz/2008/04/sql-identityinsert.html

Saturday, 17 March 2012

Misc 18/03/2012

L'Inconnue de la Seine => Death Mask => CPR doll Resusci Anne
Gaƫtan Dugas (Patient Zero of HIV of America)

Thursday, 8 March 2012

To var or not to var

When to var:
* Improve readability - where the repeated type is long and complex. For example:

When not to var:
* prime types

Resharper shortcut keys PDF

http://www.jetbrains.com/resharper/docs/ReSharper60DefaultKeymap_VS_scheme.pdf

Sunday, 4 March 2012

Crm 2011 Async Plugin timeout Issues

Plugins (both sync and async) are not supposed to be long-running processes and therefore there is a 2 minute timeout. I think you should reconsider your design to use a workflow (perhaps with a custom workflow activity) to solve your problem. Only workflows are allowed to execute for unlimited amount of time. However, because custom workflow activities are not supported in CRM Online you might have to consider using Azure.

Reference:
http://social.microsoft.com/Forums/sv-SE/crmdevelopment/thread/63430219-4262-47ae-8184-db1d82c4473e

Side track read: CRM 2011 Online: Why custom workflow assemblies are not supported

Saturday, 3 March 2012

Pivot table definition, explaination, How to do a dynamic columned pivot table?

Pivot table does two things:
1. Aggregate on the row fields' values
2. Subcategorizing on the (pivot) column values

Three key elements:
1. row field
2. column field
3. value field

The reason the Pivot table got its name is because you take some or all the values from the column field and rotate those values to become actually columns in the pivot table.

--How to do a dynamic columned pivot table:
--The following query will run on the AdventureWorks DB of the sql 2008R2 sample Database.

DECLARE @cols nvarchar(4000);

WITH CustomerIDList
AS
(
SELECT DISTINCT TOP 100
CustomerID
FROM
Sales.SalesOrderHeader
ORDER BY
CustomerID
)

SELECT @cols = STUFF(
(SELECT
'],[' + CAST(CustomerID AS varchar)
FROM
CustomerIDList
ORDER BY
CustomerID
FOR XML PATH('')), 1, 2, '') + ']'

Print(@cols)


DECLARE @query NVARCHAR(4000)
SET @query = N'SELECT OrderYear, '+
@cols +'
FROM
(SELECT CustomerID
, DATEPART(yyyy, OrderDate) as OrderYear
, TotalDue
FROM
Sales.SalesOrderHeader
) AS orgn
PIVOT
(
MAX([TotalDue])
FOR CustomerID IN
( '+
@cols +' )
) AS pvt
'

EXECUTE(@query)

Thursday, 1 March 2012

Export solution didn't export all entity properties, e.g. display in the Settings area

Question:
I have a solution that I just created a new entity in. The entity's property is set to display in the Settings area. However when I publish the solution as a managed solution to my test system, the new entity does not show up in the left menu under settings like it does on my development system. If I look at the solution properties in my test system the entity is not checked to display in the Settings area.

What would cause this property to not export/import with the solution? All my other changes appear to have imported and published OK.

Answer:
Looks like the problem was that I was not exporting the Site Map.

Ref:
http://community.dynamics.com/product/crm/f/117/p/68995/125925.aspx
https://community.dynamics.com/product/crm/crmtechnical/b/crmmitchmilam/archive/2011/12/19/developer-tip-o-the-day-solutions-and-the-sitemap.aspx