Wednesday, 15 October 2008

Rhino mocks - partial mock calling real method not mocked expectation

Had a few occasions where a Partial mock was calling the real method even though an expectation had been defined.

The reason was that the method being called was not marked as Virtual and so not being overridden by the mock repository.

Thursday, 25 September 2008

Encrypt / Decrypt Web.Config sections

See article here to encrypt or decrypt section of web.config file.

Thursday, 18 September 2008

VS2005 XML Comments not shown

XML Method comments are not being displayed by intellisense for methods of classes other than those in the same project.

Any referenced DLL must have the XML file which contains the comments in the same directory as the DLL itself.

Tuesday, 16 September 2008

Asp.Net - Simulate a windows service

Very interesting article here: CodeProject:AspNetService detailing how to simulate a windows service running completely within Aps.Net using cache item call backs.

Tuesday, 1 July 2008

.Net Setting up Intranet as Full Trust Zone

If the PC does not have the .NET SDK installed then the configuration tool will not be available via Control Panel -> Admin. Tools. Instead a command line tool CasPol.exe must be used:

The command line tool  exists in C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\
The command for setting Intranet as full trust is:
CasPol.exe -q -m -ag All_Code -zone Intranet FullTrust

Wednesday, 28 May 2008

DataGridView - wrong row edited

When using the Edit functionality of a DataGridView it is easy to fall into the trap of selecting the wrong row to edit when running in a multi-user environment.

When user clicks row to edit you must store the ID of the row (not its index), then just prior to data-bind find the index of the selected ID in the data-source and set the EditIndex, this means if another user adds or removes rows in between the the current user clicking edit the correct row will be selected.

Tuesday, 13 May 2008

SQL Left Join with Criteria

Query to get job title of staff or null if staff not assign a job-title:

 

SELECT     CORE_Staff.ID, CORE_Staff.JobTitleID, CORE_JobTitle.Name
FROM        CORE_Staff  LEFT JOIN CORE_JobTitle
                       ON CORE_JobTitle.ID = CORE_Staff.JobTitleID
where (CORE_JobTitle.Name='Driver') or (CORE_JobTitle.Name is null)

Rhino Mocks - Partial mock not calling base method

Had a problem where I was creating a partial mock then calling a method of the partial mock which was returning 0 (zero).

The base method was not being called even though no expectations had been setup.

The reason for this was that the ReplayAll (and VerifyAll) methods of Rhino Mocks was not being called.

Original code:

            _interestBiz = _mocks.PartialMock<InterestBiz>();
int baseDay = _interestBiz.GetBaseDaysFromAccount(account);
Assert.AreEqual(365, baseDay, "Incorrect base days");


Fixed code:



            _interestBiz = _mocks.PartialMock<InterestBiz>();
using (_mocks.Record())
{

}

using (_mocks.Playback())
{
int baseDay = _interestBiz.GetBaseDaysFromAccount(account);
Assert.AreEqual(365, baseDay, "Incorrect base days");



 



So even though no expectations were set Rhino Mocks needs to no this.

Thursday, 1 May 2008

Good Rhino.Mocks introduction / tutorial

Good Rhino.Mocks introduction / tutorial here

C# Threading : Workers processing list

Using ThreadSafeQueue class as list of items to process.

Class used as a worker, takes list as parameter, creates a thread to run in.

public class MyWorker
{
private Thread _myThread;
public Thread WorkerThread
{
get { return _myThread; }
set { _myThread = value; }
}

ThreadSafeQueue<int> _listOfNumbers;
public string NumbersProcess = string.Empty;
int total=0;

public MyWorker(ThreadSafeQueue<int> listOfNumbers)
{
_listOfNumbers = listOfNumbers;
_myThread = new Thread(new ThreadStart(this.DoProcess));
}

public void DoProcess()
{
int _localInt=0;
do
{
if (_listOfNumbers.TryDequeue(out _localInt))
{
total = total + _localInt;
NumbersProcess = NumbersProcess + _localInt.ToString() + ", ";
}
} while ((!_listOfNumbers.NoMoreItems) ||
(_listOfNumbers.NoMoreItems) && (_listOfNumbers.Count > 0));
}
}



 



Calling process creates 5 workers then populates list, then waits for workers to finish processing:



//Queue to hold numbers to process
ThreadSafeQueue<int> listOfInts = new ThreadSafeQueue<int>();

//5 worker objects (threads)
MyWorker[] workers = new MyWorker[5];
for (int i = 0; i < workers.Length; i++)
{
workers[i] = new MyWorker(listOfInts);
workers[i].WorkerThread.Start();
}

//Populate list to process
for (int i = 0; i < 1000; i++)
{
listOfInts.Enqueue(i);
}

//Flag that no more items will be added to queue
listOfInts.NoMoreItems = true;

//Wait for workers to finish then display details
foreach (MyWorker worker in workers)
{
worker.WorkerThread.Join(); //Wait for worker to finish processing.
tbxDetail.Text=tbxDetail.Text+string.Format("Numbers processsed {0} \n",worker.NumbersProcess);
}
tbxDetail.Text = tbxDetail.Text + string.Format("\n\n");

Tuesday, 29 April 2008

C# Constructors

See full discussion here

Base

public myClass() : base()

Overload

class myClass
{
public myClass()
{
//No parameters
}

public myClass(string param1) : this()
{
//No parameters will be called before me!
}
}

Monday, 28 April 2008

Asp.Net : "A first chance exception"

Getting huge amount of "A first chance exception" messages when running web-site under IDE for first time (after a rebuild).

These were being reported because programmer had turned off 'Just my code' within Tools->Options->Debugging->General

Tuesday, 22 April 2008

SQL Server : Query on date and HQL

Date format is 'YYYY-MM-DD'

e.g.

select * from orders where Date='2008-04-22'



HQL (as literal)

from Activity a where a.Date between '2008-01-01' and '2008-02-29'

Thursday, 3 April 2008

Bind Dictionary to WinForm ComboBox

To bind a dictionary to a combo box:

 

            cmbTable.DisplayMember = "Key";
cmbTable.ValueMember = "Value";
cmbTable.DataSource = new BindingSource(myDictionary, null);

Friday, 7 March 2008

Validators and hidden fields

It seems that there is a strange bug with validators.

If the field that is being validated is hidden in some circumstances a Java error " 'null' is null or not a object"

This doesn't happen on all servers / clients, the problem on site was produced on the clients IIS but on our one wasn't showing, this is with the same code running.
It also didn't happen with a previous version that had one less validator.

The solution was to move the validators next to the actual fields that were being validated. The validation messages were being shown in a validator summary.

The only way I could reproduce it in the office, was to move the post buttons off the Update panel and to do a full postback. This error continued to happen on site, even if I disabled the validators for the hidden control.s

Tuesday, 12 February 2008

IIS Asp.Net (Apparently) Bizzarro (turns out) lack of understanding

Had apparently strange goings on with IIS & Asp.Net.

Delivered new mylibrary.dll. User renamed mylibrary.dll to "old mylibrary.dll", copied in new mylibrary.dll. Got error saying 'old mylibrary.dll' could not be loaded into manifest.

After deleting the 'old mylibrary.dll' files the web site loaded ok.

After a discussion we came to the conclusion that IIS loads all the DLL files in the BIN directory irrespective of references within Web.Config.

The site then throws exception when two dlls contain the same Assembly-name - this also makes sense.

So what appeared to be strange behaviour came down to not thinking logically!

Monday, 4 February 2008

Asp.Net Ajax Calendar Extender

There is a bug with the AJAX calendar extender in that the style of the popup calendar are not applied if the text-box /calendar extender are hidden when a page first loads.

e.g. Panel with Details on is only shown once valid record found; if the first calendar extender on the page is within this hidden Details panel the calendar will not be displayed correctly when Details does become visible:

image

To fix this have a hidden calendar extender at top of the page:

<!-- Workaround for Calendar not displaying correctly - if hidden when page first loads -->
<div style="display: none"><asp:TextBox runat="server" ID="textbox1" /><cc1:CalendarExtender ID="ceTextBox1" runat="server" TargetControlID="textbox1" /></div>


Calendar is then displayed correctly:



image

Monday, 28 January 2008

Crystal Reports Asp.Net issues

Deployed Crystal Reports to server by:

Run CRRedist2005_x86.msi (taken from C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\BootStrapper\Packages\CrystalReports\)

Icons did not display in CR Toolbar:

Copy C:\Inetpub\wwwroot\aspnet_client to root of website)

 

ADO provider not found (SQL Server 2000):

Report (design-time) connection was SQL-Native changed to be SQLOLEDB.

 

Change connection information at run-time

                CrystalDecisions.Shared.TableLogOnInfo tliCurrent;
                foreach (CrystalDecisions.CrystalReports.Engine.Table tbCurrent in crSource.ReportDocument.Database.Tables)
                {
                    tliCurrent = tbCurrent.LogOnInfo;
                    tliCurrent.ConnectionInfo.ServerName = server;
                    tliCurrent.ConnectionInfo.UserID = username;
                    tliCurrent.ConnectionInfo.Password = password;
                    tliCurrent.ConnectionInfo.DatabaseName = dbname;

                    tbCurrent.ApplyLogOnInfo(tliCurrent);
                }

 

Toolbar Not working

The toolbar options were not working because a post-back was being generated that performs the functionality - the assigning of the report was within a !IsPostBack block. As the report is not held in state it must be reloaded during post back.

Monday, 21 January 2008

NHibernate transaction locking oops!

Was testing catching NHibernate.StaleObjectStateException (exception where one user updates a record which another user then attempts to update without getting newer version).

Was getting 'Failed to initialise lazy..." when reloading record on associated collection due to a timeout and also appeared to be locking the server (no queries could be run on tables involved in failed update)

It came down to the transaction not being Rolled-back when exception thrown - so obviously DB still in transaction.