Change DocType dynamically

I have a single page(created before Master pages were available) that loaded dynamically one or another user control.Some child controls have css for quirk mode, but for new controls I want to use latest DocType
<!DOCTYPE html>
The solution is to set it dynamically in code-behind depending on current control to load(the code is copied from

<%@ Page Language=“C#” AutoEventWireup=“true” CodeFile=“Default.aspx.cs”
Inherits=“_Default” %>

<asp:literal runat=“server” id=“DocType”></asp:literal>

<html xmlns=“”>
<head runat=“server”>
==============code behind=========
protected void Page_Load(object sender, EventArgs e)
string docType;
docType= “<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0
docType= “<!DOCTYPE html>”

this.DocType.Text= docType;


Select First Row In Group using Custom Comparer

We have a requirement for a list of itineraries with multple itinerary items show only single itinerary in the list with details of one of the items  selected based on some custom sorting logic. So I needed to group by itinerary ID and sort by custom Comparison and select the first in each group.


Below is a LinqPad file that I’ve used for testing:

void Main()
var rows=new List<MyRow>()
new MyRow(1,ProductType.F,new DateTime(2012,01,01),“A”)
,new MyRow( 1,ProductType.C, new DateTime(2012,01,01),“B”)
,new MyRow(1,ProductType.H, new DateTime(2012,01,01),“C”)
,new MyRow(2,ProductType.C, new DateTime(2012,01,01),“D”)
,new MyRow(2,ProductType.Hnew DateTime(2012,01,01),“E”)
,new MyRow(3,ProductType.F, new DateTime(2012,02,01),“F”)
,new MyRow(3,ProductType.F, new DateTime(2012,03,01),“G”)
,new MyRow(3,ProductType.F, new DateTime(2012,01,05),“H”)
,new MyRow(3,ProductType.H, new DateTime(2011,01,01),“I”)
,new MyRow(4,ProductType.C, new DateTime(2012,01,01),“J”)
,new MyRow(5,ProductType.H, new DateTime(2012,01,01),“K”)
,new MyRow(6,ProductType.C, new DateTime(2012,01,01),“L”)
,new MyRow(6,ProductType.H, new DateTime(2011,01,01),“M”)

} ;

var firstsInGroups= from p in rows
//where conditions or joins with other tables to be included here
     group p by p.ID into grp
select grp.First();


var firstsByCompareInGroups= from p in rows
group p by p.ID into grp
select grp.OrderBy(a => a, new CompareRows()).First();


// Define other methods and classes here
public class  MyRow
{ public int ID;
public ProductType Type;
  public DateTime StartTime;
public string OtherData;

  public MyRow( int id,  ProductType type,   DateTime startTime,   string otherData)
  OtherData= otherData;
public enum ProductType

  public class CompareRows : IComparer<MyRow>
// Because the class implements IComparer, it must define a
// Compare method. The method returns a signed integer that indicates
// whether s1 > s2 (return is greater than 0), s1 < s2 (return is negative),
// or s1 equals s2 (return value is 0). This Compare method compares strings.
public int Compare(MyRow r1, MyRow r2)
return DateTime.Compare(r1.StartTime, r2.StartTime);
//F is the best type
else if (r1.Type==ProductType.F)
   return 1;
else if (r2.Type==ProductType.F)
   return 1;
else //for C and H min Date is better
{ int compareDates=DateTime.Compare(r1.StartTime.Date, r2.StartTime.Date);
return compareDates;
else//For the same date C is better
if (r1.Type==ProductType.C)
return 1;
else if (r2.Type==ProductType.C)
return 1;
Debug.Assert(false,“should not be here”);
return 0;


Serializable attribute is not related to XmlSerializer.

.Net has several methods of serialization and sometimes it causes a lot of confusion even for experienced programmers.
I believe the best article to describe the different methods is  Aaron Skonnard’s
Serialization in Windows Communication Foundation(MSDN Magazine > Issues > 2006 > August) (by some reason it’s not highly rated by Google and other articles are coming first for Serialization related requests)

There is also a brief comparison table in StackOverflow What are the differences between the XmlSerializer and BinaryFormatter.

I’ve recently read a good article XmlSerializer vs DataContractSerializer: Serialization in Wcf, but noticed that it is incorrectly describe SerializableAttribute.
[Serializable].is used by   System.Runtime.Serialization. (BinaryFormatter or obsolete SoapFormatter) and also by  DataContractSerializer/NetDataContractSerializer to be compatible with .Net Remoting.
However it is not used by XmlSerializer .XmlSerializer can operate on any public type without any special attributes.


Set Offset to not attached div doesn’t work correctly in IE

We want to dynamically show an image below a span html element. 
The javascript creates a div element, than assigns new offsets using jQuery offset() and then appends the div to document.
It worked as expected in FireFox, but moved the new element to the bottom of the page in IE.
I found, that if I will call offset after document.body.appendChild, it will assign values correctly.

In the test page below if offset is called  after document.body.appendChild,
new img assigned left: -8, top: 110
img left: -8, top: 110  -expected
If offset is called  before document.body.appendChild,
new img assigned left: -8, top: 110
img left: 0, top: 214   -wrong

The test page OffsetAfterAppend.htm: <!
DOCTYPE html> <html> <head>     <script src=""></script> </head> <body>  <p style="height:"100px">Offsets to show</p>  <p id="currentP"> Hello <span id="curr" style="background-color:Green">span to be above the image </span></p>    <p></p>   <script>       var p = $("p:first");        var s = $("span:last");        var currentOffset = s.offset();        p.html("span left: " + currentOffset.left + ", top: " +;            var currentHeight = 20;         YOffset = 40;       XOffset = -55;       sImageURL = "";                  var divMapContainer = document.createElement('div');         var imgMap = document.createElement('img');         $(imgMap).attr('src', sImageURL);         $(imgMap).attr('alt''');         $(divMapContainer).append($(imgMap));         newLeft = currentOffset.left + XOffset;         newTop = + currentHeight + YOffset;         p.html(p.html() + "<BR/>new img assigned left: " + newLeft + ", top: " + newTop);         //$(divMapContainer).offset({ top: newTop, left: newLeft });          document.body.appendChild(divMapContainer);          $(divMapContainer).offset({ top: newTop, left: newLeft });          var img = $("img:last"); var imgOffset = img.offset();          p.html(p.html() + "<BR/>img left: " + imgOffset.left + ", top: " +   </script> </body> </html>


Compiler doesn’t report missing ‘Microsoft.Practices.ServiceLocation”

I’ve upgraded Enterprise Library form 4. to 5  and replaced references to the DLLs (in particular we are using EnterpriseLibrary.Logging”)  Compiler  doesn’t report any errors about missing dependencies however at run time I’ve got
Could not load file or assembly ‘Microsoft.Practices.ServiceLocation’

I had to add the library explicitly.  
It will be good if the error will be shown during the build.

Related links “Could not load file or assembly ‘Microsoft.Practices.EnterpriseLibrary.Validation’ 


Another application reporte the same error at run-time differentlly:

Microsoft.Practices.ServiceLocation.ActivationException: Activation error occured while trying to get instance of type LogWriter, key “” —> Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency failed, type = “Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter”, name = “(none)”.

Exception occurred while: while resolving.

Exception is: InvalidOperationException – The type LogWriter cannot be constructed. You must configure the container to supply this value.


At the time of the exception, the container was:

 Resolving Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter,(none)

—> System.InvalidOperationException: The type LogWriter cannot be constructed. You must configure the container to supply this value.

  at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.GuardTypeIsNonPrimitive(IBuilderContext context, SelectedConstructor selectedConstructor)

  at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.PreBuildUp(IBuilderContext context)

  at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)

  at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlanCreatorPolicy.CreatePlan(IBuilderContext context, NamedTypeBuildKey buildKey)

  at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)

  at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)

  at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)

  — End of inner exception stack trace —

  at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)

  at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable`1 resolverOverrides)

  at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)

  at Microsoft.Practices.Unity.UnityServiceLocator.DoGetInstance(Type serviceType, String key)

  at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key)

  — End of inner exception stack trace —

  at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key)

  at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance[TService]()

  at Microsoft.Practices.EnterpriseLibrary.Logging.Logger.get_Writer()

  at Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(LogEntry log)

Changing “Trusted Sites” list affected HttpWebRequest in application running under different account

We have a webscraper ASP.Net application, that worked fine on developers and test environments, but didn’t work on some machines with more strict security settings. HttpWebRequest failed with System.Net.WebException: Unable to connect to the remote server

It start working when my colleague  added the site that application tried to access to his “Trusted Sites” zone using Internet Explorer. What we couldn’t understand, how it affected an application that ran under DIFFERENT account.
I didn’t find any references that Internet explorer security settings are shared between users.
The server affected had Windows 2003 Server and Internet Explorer 8.

Put reusable code into libraries to share between projects

I’ve recently read the post The Mooney Project » Reusable Code Is Bad.

Also I disagree with the title of the post, most of the issues in the text are valid and important.
Mike Mooney is mostly talking of creating customizable applications, that have hundreds of configuration settings.
Most close to my opinion is a comment from Geoff H

Design libraries for reuse, glue code to bind together, and logic code to call libraries through the glue.

When I am writing  an individual method, I am asking myself, how generic is the logic, is it only be useful for this feature, or to different parts of my application, or can be used as an extension of .Net framework.  Depending on this , I will move the common logic to one or another of my libraries. Sometimes, when I will looking to which class/dll should I add this new method, I will recognize, that our library already has the same or very similar method, and I don’t need to write it again.