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 http://stackoverflow.com/questions/174916/how-do-you-specify-your-content-type-in-asp-net/6932768#6932768)

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

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

<html xmlns=“http://www.w3.org/1999/xhtml”>
<head runat=“server”>
==============code behind=========
protected void Page_Load(object sender, EventArgs e)
{
string docType;
if(PageId==”OLD”)
docType= “<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0
Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>”;
else
docType= “<!DOCTYPE html>”

this.DocType.Text= docType;

}

Advertisements

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()
{
// http://smehrozalam.wordpress.com/2009/12/29/linq-how-to-get-the-latest-last-record-with-a-group-by-clause/
// http://stackoverflow.com/questions/6963707/linq-query-group-by-and-selecting-first-items/7456167#7456167
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();

firstsInGroups.Dump();

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

}

// 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)
{
ID=id;
   Type=type;
   StartTime=startTime;
  OtherData= otherData;
}
  }
public enum ProductType
  {F,C,H}

// http://msdn.microsoft.com/en-us/library/bb549422.aspx
  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)
{
if(r1.Type==r2.Type)
{
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);
   if(compareDates!=0)
{
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="http://code.jquery.com/jquery-latest.js"></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: " + currentOffset.top);            var currentHeight = 20;         YOffset = 40;       XOffset = -55;       sImageURL = "http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif";                  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 = currentOffset.top + 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: " + imgOffset.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
http://stackoverflow.com/questions/3992072/where-does-microsoft-practices-servicelocation-come-from

http://entlib.codeplex.com/discussions/221485 “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.