Sunday, June 1, 2008

Patterns - Open / Close Principle

The first time I heard this principle is in DNRTV epis0de 71 Jean-Paul Boodhoo on Demystifying Design Patterns Part 4 .

This principle states:
An object should be Open for Extensions but Closed for Modifications.

Take a query scenario: The aim is to allow querying classes to query an object without have to change source code on the query class. In other words not having to add new methods for each new query.

This can be done by the Specification Pattern (out of box Dot Net Partterm) in particular the Predicate Delegate Pattern. (definition: Ask an Object if another Object meets a certain criteria)

Using the sample from DNRTV episode.

--------------------------------- Querying Class --------------------------------------

public void Should_find_all_employees_with_a_last_name_beginning_with_B()
{
IEmployeeContactBook book = CreateContactBook();
AddDefaultListOfEmployeesTo(book);
Assert.AreEqual(2,GetCountOf(book.AllContactsMatching(LastNameStartsWithB)));
}

public LastNameStartsWithB(IEmployee employee)
{
return employee.LastName.StartsWith("B");

}

----------------- Query Class ------------------------------------------------------

public IEnumerable AllContactsMatching(Predicate match)
{
foreach (IEmployee contact in contacts)
{
if (match(contact))
{
yield return contact;
}
}
}

Friday, May 23, 2008

Http Handlers

I have wanted to blog about HttpHandlers for a while now. At last I have found a reason, I have recently watched the DNRTV screencast 108 Miguel Castro on Http Handlers in .NET .

Http Handlers route file extensions to handlers. This is best illustrated by the fileC:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG\web.config . If you open this file you will see something like this (abbreviated due to space constraints



















So when you browse to an aspx page

the aspx extension is routed to System.Web.UI.PageHandlerFactory handler
The page class interits from the control class, which is where we get the event cycles such as onLoad and onInit etc; and also implement IHttpHandler and this has a method called ProcessRequest.

You can't browse to a master page, The reason is seen

In this case the request is routed to HttpForbiddenHandler. This bring up a form that says you cannot browse to a master page.

The extension ashx is browsable point handler. Thus it is a web page without a ui and without the web page lifecycle. The key point is that the ashx can accept query strings.

Web Control - Validators

I have watched many many DNRTV show but have never blogged about them. I'm not really sure why, as they a general very worthwhile to watch. Do I decided to go back over the archive and chose the show 75 Peter Blum on Web Controls Part 1

I chose this show as I remembered it had a lot of small interesting points. The show dealt with: -
  • commonly overlooked features of ASP.NET Validators
  • requiring that at least 1 textbox has text

1. commonly overlooked features of ASP.NET Validators
========================================

a) Validate a TextBox as a Date. As an aside, Personally I prefer CSLA framework concept where you can use 't' for today and 't-' for yesterday and 't+' for tomorrow etc)

Add a CompareValidor; properties;operator;change to DateTypeCheck;change type to Date



ControlToValidate="TextBox1" ErrorMessage="CompareValidator"
Operator="DataTypeCheck" Type="Date">

b) Validator Culturised (Australianised, Americanised, Ukise etc)
===============================================
Validators all follow current pages culture info object. The culture can be changed by
properties -> document -> culture

c) How to Prevent a Button from Validating
===============================
For example have a two buttons on a form (OK andCancel). You want OK to validate and Cancel not to validate.
button=>properties=>CausesValidation=>set it to false

The button will no longer provide client or server side validation.

A textbox also has a CauseValidation property. However this is part of the AutoPostBack. Thus the property name should include AutoPostBack as well as CausesValidation.

d) Server Side Validation Must be setup for it to Work
======================================
Server side validation is important to validate data against business object or database data. If you fail to do server side validation then you can be hacked. The hacked will turn off java script and then have easy access.

To setup server side validation is easy (for example):-

protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//save data
}
}


2) requiring that at least 1 textbox has text
===============================

Please see the screencast for further details - as this blog is getting too long


Wednesday, May 21, 2008

SharePoint Content Types

After blogging recently about Sql Server, I decide today to blog about SharePoint, and in particular content types. A good resource for this is Ted Pattison screencast ContentTypes.wmv.

Content types in previous version was only possible at document library level. However, it is useful to have many different content types within a library. Thus v3 allows document types to be associated at the document level.

Step 1
=====
Before creating content types, it is important to create site columns (a stand-alone definition for site columns). Site Settings --> Galleries ->Site Columns
It is good practise to put site columns into a new group.

After creating the site columns then it is time to create the content types. The good news is that content types support inheritance. All programmer know about inheritance, but sharepoint users may not know. Inheritance allows many different content types to share properties of another content type. Thus making it easier to maintain and less initial typing.

Step 2
=====
Content types are created by Site Settings --> Galleries ->Site Content Types
Base content types is another term for the content type from which the current content type inherits. It is good practise to setup base content types if there is commonality. Thus add the base content type first.

The content type (currently the base content shall require columns). You are required to add these columns from existing columns. After finishing the create of the columns for the base content type. The derived content types should be created. This follows the same procedure as above.

Step 3
=====
The final step is to configure the document library to use these created content types. If you do not do this then under new, the only option will be to create a new folder.
In the document library go
setting -> Document Library Settings ->Advanced Settings -> click yes option fo allow management types
Note a new section content types shows up under Document Library Settings

Click add from existing site content types and select the document types for this library.
Note you may want to get rid of the default "document" document type. This is done by clicking on the "document" document type and choosing delete this content type.

That's it all Done

Tuesday, May 20, 2008

Sql Server Mirroring

I have just finished DAT327 - Microsoft SQL Server 2005 Always-On Demo Fest from Teched 2007. This was a marathon screencast but very worthwhile.

This was on mirroring, which I as a developer have not been responsible for. However, it was brilliant to see a comprehensive screencast on this.

The primary severs in mirroring are the: principal (primary), mirror (secondary) and witness. The witness is extremely light weight and is used for checking to see if the principal and mirror are available. The good news is the witness can run on any edition of sql server including express (FREE).

The mirror needs to be prepared as a mirroring server. On of the steps is restore the database to the mirror server and must use Recover Completion State = No Recover. No Recover says do not bring this database online, leave it inaccessible to users but able to receive transactions.

Explicit Redirection allows changing the connection string using the following syntax:
;failover partner =

The code will now try to connect to server1 or server2, and run against whichever server is available.

Say server1 is principal, server2 is mirror and server3 is the witness.

If there is a Failover, the connections are broken, transaction are rolled back, and will have to reconnect.

Scenario1: Server1 goes down - The application will work, the principal then would be server2.

Scenario2: Mirror goes down -The application will work, the principal will remain server1. However logs will grow as log file will be needed when server2 becomes available again to ensure server can catchup.

Lots of other good stuff in this screencast.

Saturday, May 17, 2008

Sql Predicates

I recently found a good article on indxe tuning, but I misplaced the link. Not unusual for me. The article discussed query plans from first principles. I thus will document some of the points I recall from the article and hopefully bookmark the article next time.

For newbies I will give a definition of predicates:-
1. Grammar the part of a sentence in which something is said about the subject
2. Logic something that is asserted about the subject of a proposition

Thus in sql server it normally is part of the where cause: such as where city='Perth'. So when will an index be used to seek? The predicates cannot seek on a single column index if
  • the predicate contains a function such as absolute values: where ABS([xDelta]) < 5 =" 0.">
  • the predicate contains a Like expression with a wildcard in the first position
    where [city] LIKE '%erth'

In multiple column indexes the order of the keys become important. The predicate on a second column can use an index only if the first column of the index is an equality predicate. Therefore an index will be used when
where [Country]='Australia' and [City] = 'Perth'

However if the predicate is

where [Country] Like '%us%' and [City] = 'Perth' then the index will not be used.

Friday, May 16, 2008

Sql Server Data Management Views

I have recently finished watching DAT320 My Top Ten DMVs by Greg Low from Teched 2007.
The DMV are very powerful. One of the commom questions is what is the difference between DMV and a DMF. THE DMF's are DMV's with parameters.

It is important to note that additional permissions are required to run DMV. These permissions are: -
  • select permission
  • plus view server state (server scope)
  • and view database state for (database scope)