Tuesday, 24 November 2015

Fakes Mocks and Stubs

Fakes, Mocks and Stubs offer varying depth of business logic.

A Fake is a simple object that contains no business logic. It simply contains specific values (such as good or bad) that can be injected into a test to determine the result.

A Mock allows the test to replace a method call or property accessors to return a particular value. For example the test can mock a repository class to return pre-canned data when the Read() method is called. Mocks are also useful in unit tests as they can tested that particular methods were called and how many times they were called. You can assert against a mock.

A Stub is more comprehensive and at the coding level can replace an entire class. For the repository example the repository could be replaced with a StubRepository and this either returns a response based upon input data or based upon some preconfigured data.

Beyond the coding level a Stub can also be used to replace a subsystem. If a payments system is calling a third party interface, it may be necessary to stub out the 3rd party. This benefits if calling the third party costs money, if performance tests are required, if you want to avoid overloading the third party, or if the third party is unable to provide the failure scenarios when you need them.

For a stubbed interface it is often useful to return output data based upon input data. For a Fraud-checking stub, the response may vary based upon the applicant's last name, e.g. fail fraud checks if the last name is "MyLastName_Fail". You want to avoid statefulness in the stub or vary the response from the stub based upon configuration, which would require a system restart.

For performance testing it may also be useful to simulate latency based upon input data. In our Fraud Check example the response may delayed by 5 seconds if the applicant's first name was "MyFirstName_5s". This delay may help tease out scalability problems or race conditions in neighbouring parts of the system. The test driver can then issue a variety of load conditions simply by supplying varying usernames as request parameters.

Tuesday, 3 November 2015

I found my AD account being locked continuously when I had an enforced password change. This was because I had many disconnected (but not logged off) RDP sessions on many test servers across the network. So with the help of this PowerShell module, I wrote a script to detect which sessions were left open so I could manually log off.

Import-Module PSTerminalServices

$username = 'AndrewPotts'
$servers = @("serverA","serverB")

foreach ($server in $servers)
{
 Write-Host -NoNewLine $server
 
 try
 {
  $loggedOn = $False
  
  Get-TSSession -ComputerName $server | ForEach-Object { 
   if ($_.Username -eq $username) { $loggedOn = $True }
  }
  
  
  if ($loggedOn -eq $True)
  {
   Write-Host -ForegroundColor Yellow ' Logged on'
  }
  else
  {
   Write-Host
  }
 }
 catch [System.Exception]
 {
  Write-Host -ForegroundColor Red ' $_.Exception.Message'
 }
}

Debugging with WinDbg

Open a command prompt as administrator.


If you get
Cannot load "xxx"

when typing
.load clr sos

then make open a command prompt as administrator

set the path to include the .net framework 2.0 and 4.0

C:\windows\Microsoft.NET\Framework\v4.0.30319\

If it is a 32-bit process, load the 32-bit windbg and reference
the paths to the 32-bit .NET

If it is a 64-bit process, load the 32-bit windbg and reference
the paths to the 64-bit .NET, eg:
C:\windows\Microsoft.NET\Framework64\v4.0.30319\

WCF scalability settings

This article provides a good steer on the scalability settings for WCF.

IIS and Impersonation

Setting
<authentication mode="Windows" />
<identity impersonate="true"/>

on an IIS application will set the thead to run under the identity of the current user. All calls, such as file writing, writing to the event logs, will run under the identity of the current authenticated user. In this case you need to ensure that the folders and event logs allow the current user (indeed all potential users that may authenticate) to perform the task.

Note also, that if you want to pass on those credentials, for example to call another webservice or Website that requires Windows Authentication, then you need to enable delegation. By default the first Website is only allowed to impersonate, but not pass on the credentials to a 3rd party. To allow this you need to configure delegation for the Website in Active Directory. You also need to ensure the client can authenticate using Kerberos (this may involve setting the trust levels for the URL).



However, I found running the application under the context of the user at all times is troublesome. For example, Log4net fails to write to a network share, despite me setting Everyone=Full Permission.

It is probably far better to allow the Web application to run under the service account as normal, but impersonate the user only for the short call to the back-end Web service.

To do this, set
<authentication mode="Windows" />
<identity impersonate="false"/>

this ensures the application runs under the service account. Then write the code to impersonate the user.

var windowsId = (WindowsIdentity)User.Identity;
            WindowsImpersonationContext windowsContext = null;

            try
            {
                // Start impersonating
                // http://msdn.microsoft.com/en-us/library/ff647404.aspx
                windowsContext = windowsId.Impersonate();

                result = service.ValidateTrades(trades);
            }
            catch (Exception error)
            {
            }
            finally
            {
                // Revert impersonation
                if (windowsContext != null)
                {
                    windowsContext.Undo();
                }                
            }

Dell Inspiron 7537 versus the HP Touchsmart 15-j105sa

I've received both the Dell Inspiron 7537 and the HP Touchsmart 15-j105sa.

Here are my initial views on them:

HP Touchsmart 15-j105sa

Positives
It looks sturdier.
In my opinion it looks more attactive.
It outperforms the Dell in CPU performance.
The battery is removable.

Negatives
The glass is more reflective; you can see yourself in the screen.

 Dell Inspiron 7537

Positives
It outperforms the HP in the high end graphics place.

Negatives
It has a RJ45 network connector with a hinged cover. This is sure to be a pain and break in the future.

There are reports of an underperforming WIFI adapter (which may now be resolved).

The battery and memory are contained within the back which you have to unscrew to get access to.

Verdict
I actually prefer the HP Touchsmart, yet the better NVidia 750M on the Dell is enough to sway it for me.

Decimal layout

I've just had a few hours debugging decimals.

decimal x1 = 256m;
decimal.GetBits(x1).Dump();
Console.WriteLine(string.Format("{0}", x1));


decimal x2 = 256m * 1.0m;
decimal.GetBits(x2).Dump();
Console.WriteLine(string.Format("{0}", x2));


http://msdn.microsoft.com/en-us/library/system.decimal.getbits(v=vs.110).aspx

Reverse Engineering Android Apps

Launch Web PC Suite
Select Apps
Select the App and select Backup
The APK is copied to SDCard\Tablet\BackupApps
Copy the APK to the local computer
At a command prompt type apktool d <apkfile.apk>

or

 Rename your APK file(e.g., rename your APK file to .zip Ex- test.apk -> test.zip) & extract resultant zip file.
Copy your .dex file in to dex2jar folder.
Run setclasspath.bat. This should be run because this data is used in the next step.
Go to Windows Command prompt, change the folder path to the path of your dex2jar folder and run the command as follows: d2j-dex2jar.bat classes.dex
Open the jar file in JD GUI.

Reformatting MPEG-2 DVD to another format

VirtualDubMod is useful for converting MPEG2 TS files to another format.

NServiceBus, DTC and MSMQ

I've spent the last week performance testing our NServiceBus solution extensively.

Our first implementation used MSDTC.
During performance testing of an NServiceBus application using MSMQ transport, we managed to kill MSDTC many times. It would go into a period of hanging for 20 minutes and everything around it; including endpoints not owned by us, stopped working.

We turned off enlistment of the databases called by the handlers by altering the connection strings. This still didn't stop MSDTC from hanging.

Analysis of the stack traces showed that NServiceBus was still engaging MSDTC through the use of TransactionScope around the handler. Although we have switched DisableDistributedTransactions = On, the handlers were still using the local transaction coordinator. We had to set DoNotWrapHandlersExecutionInATransactionScope = true.

The different settings are:
1) DisableDistributedTransactions = off, DoNotWrapHandlersExecutionInATransactionScope = off . The entire handler will be wrapped in an outer transaction scope. Any Bus.Sends will not be immediate and will wait till the outer transaction scope completes. In case of a rollback of the outer transaction scope all the Bus.Sends will be rolled back as well as any database work enlisted in the transaction scope will roll back.

2) DisableDistributedTransactions = on, DoNotWrapHandlersExecutionInATransactionScope = off. The entire handler will be wrapped in an outer transaction scope. Any Bus.Sends will be immediate and will not participate in the outer transaction scope. In the case of a rollback of the outer transaction scope the bus.sends will not roll back but any database work in the handler will roll back.
3) DisableDistributedTransactions = off, DoNotWrapHandlersExecutionInATransactionScope = on. The handler will not be wrapped in an outer transaction scope. I will explicitly have to start a transaction scope and any bus.sends will not be immediate (they completed upon outer transaction scope complete) and database work done within the manually started one will rollback together. Anything outside of my manually created transaction scope will not rollback.

4) DisableDistributedTransactions = on, DoNotWrapHandlersExecutionInATransactionScope = on. The handler will not be wrapped in an outer transaction scope. Each bus.send will be within its own transaction and if a transaction scope is created manually by me those bus sends will not enlist in it will execute immediately and will not roll back if the outer transaction scope rolls back. Any db work done within the manual transaction scope will roll back.

https://groups.google.com/forum/#!msg/particularsoftware/SoxeC4RwLlg/Kdt-gjTXYEIJ

Having changed this we were now using TransportTransactions. MSMQ still can handle a Receive and send in a transaction, without using DTC.













MSMQ uses memory-mapped files to store messages (regardless of whether they are express, recoverable, durable). It uses a 4MB file for every message and cleans them up every 6 hours. If you see the memory go very high you can initiate the cleanup by running the following PowerShell:

$MyMSMQApp = new-object  –comObject  MSMQ.MSMQApplication
$MyMSMQApp.Tidy()

NServiceBus and MSMQ Transport Transactions

If Distributed Transactions and ambient transactions are turned off, then you are reliant upon MSMQ transactions.
On a transactional queue and with the appropriate code then the Receive operation on the queue will be transactional. This allows NSB to take a message off a queue - preventing other handlers from reading it - process it and if it fails put it back on the queue.
However the MSMQ transaction will only group Receives together in a transaction, or Sends, not a mixture.
So if you have code like this:

a. Begin MSMQ transaction
b. Read Message
c. Process Message
d. Send Result Message onwards
e. Commit Transaction

then this is fine if the point D is the last action in the transaction. If anything fails before it, the MSMQ transaction will fail and the original message at B will be put on the input queue. No output message will have been sent as the processing before it will have failed.

However if you have more than one output message it will yield bad results. Take this scenario:

a. Begin MSMQ transaction
b. Read Message
c. Process some of the message
d. Send Intermediary Message onwards
e. Process some more
f. Send Result Message onwards
g. Commit Transaction

If step E fails then the transaction will be rolled back and the message at B returned to the input queue. However the MSMQ transaction will not roll back step D - the intermediary message will be sent despite the failure of the transaction.