Thursday, April 08, 2010
If you get this helpful(!) message when setting up WCF in IIS7 for the first time:






It is likely that you need to run the following command:


servicemodelreg -i

You can find these here - http://msdn.microsoft.com/en-us/library/ms732012.aspx



Thursday, April 08, 2010 10:56:53 AM (GMT Standard Time, UTC+00:00) | Comments [0] | c# | wcf#
Wednesday, January 27, 2010
To get this, you could use an HTTP sniffing tool like Fiddler or HTTPFox, but there may be times that you have problems with this due to proxies etc being used in the company.

Thankfully there's a way to output the trace using the code below:

<system.diagnostics>
<trace autoflush="true"/>
<sources>
 
<source name="System.Net" maxdatasize="1024">
   
<listeners>
     
<add name="TraceFile"/>
   
</listeners>
 
</source>
 
<source name="System.Net.Sockets" maxdatasize="1024">
   
<listeners>
     
<add name="TraceFile"/>
   
</listeners>
 
</source>
</sources>
<sharedListeners>
 
<add name="TraceFile" type="System.Diagnostics.TextWriterTraceListener" initializeData="trace.log"/>
</sharedListeners>
<switches>
 
<add name="System.Net" value="Verbose"/>
 
<add name="System.Net.Sockets" value="Verbose"/>
</switches>
</system.diagnostics>



Acknowledgements to the following post:

http://stackoverflow.com/questions/300674/getting-raw-soap-data-from-a-web-reference-client-running-in-aspnet

Wednesday, January 27, 2010 12:20:01 PM (GMT Standard Time, UTC+00:00) | Comments [1] | ASP.NET | c##
Monday, January 25, 2010
Custom sections are created by declaring the section name in the <configsections> element, and then declaring the section, like so:

<section name="MyCustomSection" type="System.Configuration.NameValueFileSectionHandler"/>

  <MyCustomSection>
    <add key="KEY1" value="VAL1"/>
    <add key="KEY2" value="VAL2"/>
</MyCustomSection>


This is then read in as follows:


            NameValueCollection myList= (NameValueCollection)
                ConfigurationManager.GetSection("MyCustomSection");
            return myList[scenario];

Simples.

Monday, January 25, 2010 1:33:23 PM (GMT Standard Time, UTC+00:00) | Comments [0] | c##
Monday, October 26, 2009
Took me a bit of searching, but finally came across this article - http://www.satter.org/2007/10/compact-framewo.html which describes how to get LINQ goodness in you mobile apps. Add reference to System.Core and you are away. NOTE: there isn't any L2S support in there yet, you'll just get the basics.
Monday, October 26, 2009 6:37:22 PM (GMT Standard Time, UTC+00:00) | Comments [0] | c##
Thursday, October 22, 2009
Had a quick look at this today, as I wanted to see if there was a better way than doing:

try
{
doSomething();
}
finally
{
Log.LogEvent("some log");
}
catch
{
Log.LogEvent("some error");
}

Came across a library called PostSharp, which I'm going to give a go on a new project.

It's had a decent write-up in the community, so hopefully this should keep the code nice and clean.

You can find a decent tutorial here.

Thursday, October 22, 2009 9:30:50 AM (GMT Standard Time, UTC+00:00) | Comments [0] | c##
Friday, October 02, 2009
When you're creating an app that uses Linq and you want to see the SQL that is generated, you can attach to the Log property of the DataContext.

To get this to stream to the DebugWindow, use the following bit of code (credits to Kris Vandermotten - http://www.u2u.info/Blogs/Kris/Lists/Posts/Post.aspx?ID=11)

using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;

namespace Vandermotten.Diagnostics
{
    /// <summary>
    /// Implements a <see cref="TextWriter"/> for writing information to the debugger log.
    /// </summary>
    /// <seealso cref="Debugger.Log"/>
    public class DebuggerWriter : TextWriter
    {
        private bool isOpen;
        private static UnicodeEncoding encoding;
        private readonly int level;
        private readonly string category;

        /// <summary>
        /// Initializes a new instance of the <see cref="DebuggerWriter"/> class.
        /// </summary>
        public DebuggerWriter()
            : this(0, Debugger.DefaultCategory)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DebuggerWriter"/> class with the specified level and category.
        /// </summary>
        /// <param name="level">A description of the importance of the messages.</param>
        /// <param name="category">The category of the messages.</param>
        public DebuggerWriter(int level, string category)
            : this(level, category, CultureInfo.CurrentCulture)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DebuggerWriter"/> class with the specified level, category and format provider.
        /// </summary>
        /// <param name="level">A description of the importance of the messages.</param>
        /// <param name="category">The category of the messages.</param>
        /// <param name="formatProvider">An <see cref="IFormatProvider"/> object that controls formatting.</param>
        public DebuggerWriter(int level, string category, IFormatProvider formatProvider)
            : base(formatProvider)
        {
            this.level = level;
            this.category = category;
            this.isOpen = true;
        }

        protected override void Dispose(bool disposing)
        {
            isOpen = false;
            base.Dispose(disposing);
        }

        public override void Write(char value)
        {
            if (!isOpen)
            {
                throw new ObjectDisposedException(null);
            }
            Debugger.Log(level, category, value.ToString());
        }

        public override void Write(string value)
        {
            if (!isOpen)
            {
                throw new ObjectDisposedException(null);
            }
            if (value != null)
            {
                Debugger.Log(level, category, value);
            }
        }

        public override void Write(char[] buffer, int index, int count)
        {
            if (!isOpen)
            {
                throw new ObjectDisposedException(null);
            }
            if (buffer == null || index < 0 || count < 0 || buffer.Length - index < count)
            {
                base.Write(buffer, index, count); // delegate throw exception to base class
            }
            Debugger.Log(level, category, new string(buffer, index, count));
        }

        public override Encoding Encoding
        {
            get
            {
                if (encoding == null)
                {
                    encoding = new UnicodeEncoding(false, false);
                }
                return encoding;
            }
        }

        public int Level
        {
            get { return level; }
        }

        public string Category
        {
            get { return category; }
        }
    }
}

Friday, October 02, 2009 10:17:53 AM (GMT Standard Time, UTC+00:00) | Comments [0] | c# | Database#
Saturday, June 27, 2009
I've started work on a new project recently and the first thing for me to sort out is the Data Access Layer.  Because the Repository pattern served me so well in the past, I'm going to start there.

However, the previous solution used a bespoke QueryBuilder which converted an ICriteria into the appropriate SQL.  This SQL was then just passed through as CommandText on an ADO.NET connection to the appropriate database, Oracle or SQL Server. 

What we did was to mock the Repository using LINQ to Objects, and this allowed us to construct our application in a Domain-Driven fashion.

Great!

However, there was always room for improvement.  I've wanted to use LINQ as my ORM for quite some time now, and I know the purists out there will say that LINQ isn't an ORM, but for practical purposes in this project it's going to be.

Also, I've decided to use L2S rather than the Entity Framework.  My mantra is Design For Test, and right now L2E is just not persistent-ignorant in the slightest.  There are hacks as I've outlined in previous blog posts, but building hacks into the foundation of your application is a recipe for disaster.

While L2S may not be supported in future by MS, who cares?!  It works, plenty of good, solid apps have been built on it, AND IF WE GET THINGS RIGHT, there's no reason why we can't switch to L2E v2.0 next year.

We can do this because we are going to abstract out the actual DataContext, and access our data using POCO and Repository pattern.

In addition, if we can swap out the DataContext, then given that LINQ to Objects and LINQ to SQL queries are the same (or at least I hope they are, more on this later) then we can have a set of queries that we can run on both in-memory and database sources.  Truly Datasource-Agnostic.

I got the inspiration for this from http://compiledexperience.com/Blog/post/Domain-Driven-Design-Repositories-in-LINQ-to-SQL.aspx - and it works!





This diagram shows the LinqToSQL assembly, but we can also replace the SQLDataSource and SQLUnitOfWork with a MemoryDataSource and MemoryUnitOfWork.

For example, if we want to test an in-memory collection, we do the following:

            MemoryUnitOfWork context = new MemoryUnitOfWork();

            Repository<Customer> r = new Repository<Customer>(context);
            r.Save(new Customer(1, "Joe Bloggs"));
            r.Save(new Customer(2, "Joanna Bloggs"));

            IEnumerable<Customer> customers = from c in r.Fetch(null) where c.ID == 1 select c;

            List<Customer> results = customers.ToList<Customer>();

            Assert.AreEqual("Joe Bloggs", results[0].Name);


And if we want to test an actual connection to a database using L2S:

            DataContext db = new DataContext("Data Source=(local);Initial Catalog=DMGTest;Integrated Security=SSPI");

            SqlUnitOfWork context = new SqlUnitOfWork(db);

            Repository<Customer> r = new Repository<Customer>(context);

            IEnumerable<Customer> customers = from c in r.Fetch(null) where c.ID == 1 select c;

            List<Customer> results = customers.ToList<Customer>();

            Assert.AreEqual("Joe Bloggs", results[0].Name);

Note the line

IEnumerable<Customer> customers = from c in r.Fetch(null) where c.ID == 1 select c;

which is identical in both versions.

My next step is to encapsulate the queries using the Specification pattern, as Ritesh shows here.

So now we have completely isolated our domain from our DAL, and with the introduction of the Specification pattern we can look at our queries from a domain perspective also.

The code is just bashed out at the moment, but if you want it then just drop me a line and I'll send it over.



kick it on DotNetKicks.com
Saturday, June 27, 2009 9:59:11 AM (GMT Standard Time, UTC+00:00) | Comments [0] | c# | Database | Patterns | TDD#
Sunday, April 12, 2009
I must have spent the best half of a day tearing my hair out at this.


All information here - http://stackoverflow.com/questions/739859/returning-html-from-json-webservice-what-is-the-d
Sunday, April 12, 2009 10:30:27 AM (GMT Standard Time, UTC+00:00) | Comments [0] | ASP.NET | c##
Friday, February 06, 2009

Make sure you follow the pattern outlined here - http://msdn.microsoft.com/en-us/library/w369ty8x(VS.80).aspx

Friday, February 06, 2009 10:19:06 AM (GMT Standard Time, UTC+00:00) | Comments [0] | c# | Patterns#
Wednesday, February 04, 2009
I've been looking at the EF lately and while I've still not settled on how it can be tested (given the lack of persistence agnosticism), I do feel that MS has received enough stick from the community that this will be a feature of v2.

The following article by John Papa provides some good ideas as to how one would use EF as part of an n-tier architecture - http://msdn.microsoft.com/en-us/magazine/cc700340.aspx

Wednesday, February 04, 2009 7:53:45 PM (GMT Standard Time, UTC+00:00) | Comments [0] | c# | Database | Patterns | Entity Framework#
Tuesday, January 27, 2009

Making sure that your application is disposing of any unwanted resources has always been part of the ugly plumbing work of writing software.  Although .NET "helps" with this - by providing a non-deterministic Garbage Collector - it can actually muddy the waters a little.  Now, instead of having to implement a Destructor in each class, most of the time you can let the framework deal with it. 

The tricky part - and the reason I'm writing this blog - is remembering the specific scenarios when you need to, and when the framework will take over.

The general guidance is that you only need to implement IDisposable when dealing with unmanaged resources.  This is because the framework has no way of tracking this, and you need to do it yourself.  However, there are other scenarios where you might need more control.

A specific scenario would be if we had a class which had hooked into events provided by a global static or singleton class.  This singleton would likely not be disposed of until the application is shut-down (although obviously every case is different).  Because the delegate keeps a reference to our class, it would keep it alive until the singleton is disposed.  It is highly likely we want to free our class before this.  Whether we do this as part of implementing the IDisposable pattern, or use Init() and Unit() methods, is still up for debate.

In the following scenario, only ListForm and NavBarControl is required to implement IDisposable (because it is a Form):

Because this is a self-contained object graph, once we free our reference from ListForm, the GC will be able to free all the objects within this graph.

HOWEVER, if, say, ListFormController were to hook up an event handler to an object outwith this graph, then we would be in trouble - because it would not be freed and therefore keep it's referenced items alive.

You can find out more about the IDisposable pattern here.

 

Tuesday, January 27, 2009 12:24:23 PM (GMT Standard Time, UTC+00:00) | Comments [1] | c# | Patterns#
Wednesday, January 21, 2009

If you're ever having trouble with Assembly binding failures, then the Fusion log can help to resolve the problem.

Check out this blog for more information.

Wednesday, January 21, 2009 9:17:21 PM (GMT Standard Time, UTC+00:00) | Comments [0] | c##
Tuesday, January 06, 2009

It takes a while to get going after the holidays, but once I had dusted the mince pie crumbs from the thinking cap it was business time.

As you may be aware from previous posts, I'm a regular user of the various flavours of the MVC pattern (MVC, MVP, Supervising Presenter etc.  I'll just refer to it as MVC from now on, even though the exact pattern I'm using may not be that).  The software might take a little longer to construct, but this will pay back in maintainability, testability, legibility and other -bilities.  

The task for today was to apply a user-defined 'mask' over a datasource that was bound to a grid.  In this specific case, we apply the mask to the grid instead of the datasource, but the principles would be the same if our requirements were to modify the datasource in some way.

We have 3 MVC-triads involved, and the associations between which (and classes) are illustrated below:

 

The 'Super' triad, shown in green, is where it will begin.  The Window will receive the click event to show the Top N dialog, which will notify the WindowController.  The WindowController will then create the concrete TopN View (the dialog), passing this into the TopNController.

When the user clicks the 'Apply' button on the Top N dialog, this will communicate the specified values to the TopNController, which will then modify the PivotViewDef.  Note: The PivotViewDef is stored by the Document, and bound to the GridView by the GridController on instantiation.  We use a simple Observer pattern for this, which means that whenever PivotViewDef is modified, we broadcast this change to any interested parties, which can then take action.

Therefore when the PivotViewDef is modified, it will automatically refresh the GridView.

This is a clean and elegant design, as it removes any logic from the forms.  The inter-dependencies between the various components are also limited, which reduces the complexity.  And because the TopNController only communicates to the view via an interface, it is inherently unit-testable.

 

 

 

 

Tuesday, January 06, 2009 8:46:42 PM (GMT Standard Time, UTC+00:00) | Comments [0] | c# | Patterns | TDD#
Thursday, December 11, 2008

By default, the XtraPivotGrid renders the column headers horizontally.  This is fine if we only have a few columns, but chances are there will be too many columns to fit into the limited space available, without resorting to scrolling. 

It would be much better, in terms of functionality and aesthetic appeal, if we could render the text at a 45 degree angle, thereby maximizing the number of columns we can fit into a confined space.

Unfortunately the control does not support this directly, but we can work around this. 

Firstly, set the ColumnValueLineCount property of the Field being displayed in the Column Area to 2 or 3.  This will increase the header band so we have space to render our text diagonally.

Hook into the CustomDrawFieldValue event like so:

private void pivotGrid_CustomDrawFieldValue(object sender, 
            DevExpress.XtraPivotGrid.PivotCustomDrawFieldValueEventArgs e)
        {
            HeaderObjectPainter newPainter = e.Painter;

            string c = e.Info.Caption;

            e.Info.Caption = "";
            newPainter.DrawObject(e.Info);

            e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
            e.Graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
            if (IsColumnHeaderHorizontal(e.Field))
            {
                Font newFont = new Font(e.Appearance.Font.FontFamily, 8);
                e.Appearance.Font = newFont;

                StringFormat fmt = new StringFormat();
                fmt.Alignment = StringAlignment.Far;
                fmt.Trimming = StringTrimming.EllipsisCharacter;
                fmt.FormatFlags |= StringFormatFlags.NoWrap;

                e.GraphicsCache.DrawString(c, e.Appearance.Font,
                    e.Appearance.GetForeBrush(e.GraphicsCache),
                    e.Info.CaptionRect, fmt);
            }
            else
            {
                Rectangle newRect = new Rectangle();
                newRect = e.Bounds;
                newRect.X += newRect.Width;
                newRect.Y += newRect.Height;

                newRect.Width *= 7;
                newRect.Width /= 5;

                newRect.Height *= 7;
                newRect.Height /= 5;

                newRect.Y -= 8;
                newRect.Height -= 8;

                StringFormat fmt = new StringFormat();
                fmt.Alignment = StringAlignment.Far;
                fmt.Trimming = StringTrimming.EllipsisCharacter;
                fmt.FormatFlags |= StringFormatFlags.NoWrap;

                e.GraphicsCache.DrawVString(c, e.Appearance.Font, 
                    e.Appearance.GetForeBrush(e.GraphicsCache), 
                    newRect, fmt, 45);
            }

            e.Info.InnerElements.DrawObjects(e.Info, e.Info.Cache, Point.Empty);
            e.Handled = true;
        }

We also need to determine whether to render this field horizontally or not:

      private bool IsColumnHeaderHorizontal(PivotGridField field)
        {
            if (field == null)
            {
                return true;
            }
            if (field.Area == PivotArea.RowArea)
            {
                return true;
            }
            return false;
        }

 

 

 

 

 

 

 

 

 

Thursday, December 11, 2008 11:50:41 PM (GMT Standard Time, UTC+00:00) | Comments [0] | c# | DevExpress#

If your Assembly has included the

[assembly: CLSCompliantAttribute(true)]
attribute in it's AssemblyInfo, then you may encounter the above error.  It's not one of the most useful, given that you then 
have to scour the Common Language Specification rules to find out what exactly has gone wrong.
Even worse, is that it can send you in completely the wrong direction, as it did with me the other day.
If one assembly, which has the above attribute marked as true, refers to another assembly which does not include 
that attribute (or has it marked as false), then you will receive the above error message, telling you that Type such-and-such 
is not CLS-Compliant.  Even if it doesn't break any of the rules!
So, one to bear in mind for the future.
Thursday, December 11, 2008 5:36:57 PM (GMT Standard Time, UTC+00:00) | Comments [0] | c##
Monday, December 08, 2008

I love DevExpress controls.  They do so much for you.... of course, the flip side is that there are so many properties and methods that even the simplest tasks can be a bit daunting.

One of the most common tasks when dealing with grids would be to set up a Master-Detail relationship.  For my own future reference I've written down the properties and methods involved in setting this up at design-time.

  • Add Grid [Grid_Master]
  • Set up columns
  • Grid_Master.SettingsDetail.ShowDetailRow = true
  • Smart Tag -> Edit Template -> Detail Row.
  • Add Detail Grid here [Grid_Detail]
  • Grid_Detail.SettingsDetail.IsDetailGrid = true

If using custom databinding, hook up Grid_Detail.Databinding event.  In Grid_Detail.Databinding, add similar code to the following:

            //The detail data is the assets that make up each Purchase Order
            ASPxGridView detailGrid = (ASPxGridView)sender;
            detailGrid.KeyFieldName = "ID";
            int id = (int)detailGrid.GetMasterRowKeyValue();
            DataTable table = new DataTable();
            table.Columns.Add("ID", typeof(int));
            table.Columns.Add("AssetTypeName", typeof(string));
            table.Columns.Add("SerialNumber", typeof(string));
            table.Columns.Add("SalesPrice", typeof(float));
            table.Columns.Add("Location", typeof (string));
            table.Columns.Add("Discount", typeof (float));

            Invoice invoice = InvoiceModel.GetInvoiceForID(id);
            if (invoice != null)
            {
                foreach (AssetItem asset in invoice.MyInvoiceItems)
                {
                    table.Rows.Add(new object[] { asset.ID, 
                      asset.AssetTypeName, asset.SerialNumber, asset.SalesPrice, 
                    asset.Location, asset.Discount});
                }

                detailGrid.DataSource = table;
            }

 

Monday, December 08, 2008 9:52:45 PM (GMT Standard Time, UTC+00:00) | Comments [0] | c##
Monday, December 01, 2008

One of the most valuable lessons I ever learned during my time at university, was the methodology of Divide-And-Conquer.  This can be applied to anything, but in Computer Science is vital for dissecting those complex problems into their component parts.

The only problem was that, like a lot of things I did at uni, it wasn't really put into practice once the coursework and exams were over.  When you start work it's all about delivery - you don't have time to really think things through in this way, especially when you only have a couple of days until what you're working on is in the product, finished and looking shiny.

Or at least, you don't think you have the time.  But turns out the lecturers and academics are right after all.  Taking the time up-front to fully understand a component, whether it be for internal use or a UI control, saves a lot of hassle in the long-run.  Think incomplete specifications, unexpected surprises, and debugging particular scenarios during a defect cycle.

I've been thinking about this recently as I have to get to grips with a new control, and slot it into an existing application.  Whenever I start to work with a control that I'm unfamiliar with, I like to build myself a little sandbox and give it a good going overmaking sure that I know what's going on in an isolated environment, without having to worry about the rest of the codebase affecting it.   I might not get as much time on it as I'd like, but there's always that balance. 

What this lets me do is get to grips with what I'll be using the control for, how it binds to data, how it can be controlled via it's interface rather than using the 'Smart' Tags to configure it.   

I've been putting this technique through it's paces for a couple of years now, and it's clear when I look back at some older code how much of a difference it makes.  The solutions might take a little longer to develop, but the result is a cleaner implementation, for the reasons outlined above.

If I was President, I'd like to see a lot more of this sort of thing.  Whenever a new component was being developed, it should have an associated driver (prototype/sandbox - call it what you will) which configures and simulates the component in a real-world environment, but completely isolated of other parts. 

Of course, what this ultimately results in is a suite of Unit Tests for your newly developed component.  So this is hardly a revolutionary idea, but supports that we are on the right track.

 

 

 

Monday, December 01, 2008 5:59:29 PM (GMT Standard Time, UTC+00:00) | Comments [0] | c# | Patterns#
Friday, November 21, 2008

As I mentioned in a recent post, our test department submitted a defect to us regarding the XML Serializer when running under a Japanese username.

We were able to replicate using a small test application which isolated the call to the XML serializer only, but then we had to isolate the environment which led to this problem.  It worked fine under English usernames, and fine under OTHER systems which used a Japanese username, so after trying a few permutations and eliminating unneccessary steps, we reduced it to the following:

  1. Install Windows Vista (we used Ultimate edition)
  2. Change System Locale to Japanese
  3. Create User using japanese characters
  4. Change System Locale to anything other than Japanese
  5. Run Test Program - exception

What was curious about this was if we omit Step 2 then we do not get the exception, and if we include Step 2 but omit Step 4 then we also do not get the exception.

We should be hearing from Microsoft soon about this, and I'll post the results here when they are received.  Because of the nature of reproducing this exception is so contrived, I'd be surprised if we can do anything about it.

Friday, November 21, 2008 7:37:00 PM (GMT Standard Time, UTC+00:00) | Comments [0] | c##
Tuesday, November 11, 2008

Our company is submitting our product for Vista Certification at the moment, so our test department have a list of checks as long as Bao Xishun's arm.

A number of these tests check to see if the program runs correctly under various locales, especially those locales that use non-Latin based alphabets.  As internationalization was never really a design goal, even though we get unicode support by default in .NET, it fell over at this point.

However, what was a surprise was WHY it failed.  The XmlSerializer threw an exception as it could not write to the temp directory of the user, which on Vista, is <UserName>\Local\Temp

The username contained Japanese characters, but the exception report displayed these as '?' - showing that it couldn't properly resolve them.

On a hunch, I didn't really suspect our code was at fault - we weren't doing anything other than serializing a class, which worked fine for other character sets - so I quickly put together a test which just checked the XML Serialization and nothing more.

Sure enough it fell over again, so it will be interesting to see the resolution of this.  It could be that we need to set certain environment settings in the Application, but it could also be a problem with the .NET framework itself.

We're sure to find out soon.

Tuesday, November 11, 2008 10:57:03 PM (GMT Standard Time, UTC+00:00) | Comments [0] | c##
Friday, October 31, 2008
Friday, October 31, 2008 12:12:02 PM (GMT Standard Time, UTC+00:00) | Comments [0] | c##
Search
Archive
Links
Categories
Admin Login
Sign In
Blogroll