Syncronize IIS servers in a web farm to enable ETags


It’s known that on web Farm using  of eTags under IIS doesn’t work properly unless all servers are synchronized.
http://support.microsoft.com/?id=922733 suggests to
synchronize the ETag values on all the Web servers that are running IIS using Mdutil.exe that should be extracted from Windows CD

http://developer.yahoo.com/blogs/ydn/posts/2007/07/high_performanc_11/#comment-14835
suggests to use iiscnfg.vbs script (with the /copy switch) to keep cluster configuration synced up, this keeps the MDETAGCHANGENUMBER synced up too.
 
 
Finally I found extended recommendations how to synchronze IIS databases in
http://weblogs.asp.net/owscott/archive/2006/06/07/IISCnfg.vbs---IIS-Settings-Replication.aspx
It has customized MetabaseMerge.bat script, that seems the most appropriate for the job.
 
 
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

How to disable messages for category based on severity in EnterpriseLibrary logging configuration

Microsoft documentation article Source Schema for the Logging Application Block is very hard to follow,the set of articles http://www.education.vic.gov.au/devreskit/appdev/Application%20Blocks/Logging/logging-standards-details.htm#config3 is much better


Finally I found Log Event to Listener Routing in Enterprise Library   article, that very clear described available options , how to disable/enable logging

There are three Filters provided out of the box including a LogEnabledFilter which is a very effective way of short-circuiting the processing of all events, if you want logging turned off entirely. There's also a CategoryFilter and PriorityFilter provided, but it's easy enough to write your own.


In the example configuration
<categorySources>
<add switchValue="Critical" name="MyCategory">
<listeners>
<add name="EventLogTraceListener" />
</listeners>
</add>
I can specify switchValue   to Critical to ignore not important messages

From http://www.education.vic.gov.au/devreskit/appdev/Application%20Blocks/Logging/logging-standards-details.htm#config3
The following switchValue settings can be used:
  • Activity Tracing. Allows the Stop, Start, Suspend, Transfer, and Resume events through.
  • All. Allows all events through.
  • Critical. Allows only Critical events through. A critical event is a fatal error or application crash.
  • Error. Allows Critical and Error events through. An Error event is a recoverable error.
  • Information. Allows Critical, Error, Warning, and Information events through. An information event is an informational message.
  • Off. Does not allow any events through.
  • Verbose. Allows Critical, Error, Warning, Information, and Verbose events through. A Verbose event is a debugging trace.
  • Warning. Allows Critical, Error, and Warning events through. A Warning event is a non-critical problem.


The article  Log Event to Listener Routing in Enterprise Library  also describes notProcessed  special source.
  • notProcessed - any event not picked up by the other sources because there was no matching category will be redirected to this source (if any listeners are specified). Note that notProcessed events do not include filtered events (LogFilters) or events that matched a category but weren't processed due to the switchValue/severity.

Note that most of examples in the Internet do not specify listener element as a child of notProcessed element, but it’s critical to ensure that some categories are not missed completely.
<notProcessed switchValue="All" name="Unprocessed Category">
<listeners>
<add name="MailListener" />
</listeners>
</notProcessed>

A StackOverflow answer pointed me to the ShouldLog method of LogWriter and  Walkthrough: Checking Filter Status Before Constructing Log Messages:


If you want to check configuraton settings from the code, see
http://stackoverflow.com/questions/3485438/programmatically-access-enterprise-library-logging-configuration-object-model

Consider to create a facade class to the Logging Block as suggested in the answer to pattern for logging using enterprise library


My related previous post: Logging application block-how configure different listeners for different level of message.
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Javascript coding style recommendation: in return and throw statements use only simple variables

My collegue told me that placing the opening curly brace at the end of the line  is safer than at the beginning of the new line, because it prevents some hard-to-debug errors, related to Automatic Semicolon Insertion and  pointed me to the article Basic JavaScript Part 6: Automatic Semicolon Insertion. The article has the recommendation
 Trying to outline curly braces at the end of the line can save you some headaches in case a semicolon is forgotten somewhere in the code.
The statement  is misleading and even incorrect(the problem unrelated to forgotten semicolon).
The article has comments of Elijah Manor with link to JavaScript Semicolon Insertion, that properly explains the issue.

An Expression in a return or throw statement should start on the same line as the return or throw token. A postfix ++ or -- operator should appear on the same line as its operand. A Identifier in a break or continue statement should be on the same line as the break or continue token.


I really prefer C# style of block notation where new block starts  with curly bracket on a new line and apply it to JavaScript code as well.(You need to untick default setting for curly brackets in Visual Studio Tools->Options-Click Text Editor -> JavaScript  -> Formatting and it should be consistent for all development team).
The restriction above can be avoided by the following coding recommendation.
In return and throw statement use only simple variables and keep them on the same line as the statement:
GOOD:

var ret =

   {   

       shoeSize: 48
   };

return ret;

BAD:    
   return   //WRONG
   {         

 shoeSize: 48
   };

 
 
 
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Using CTT to modify config files for different environments

We previously tried to use msbuild to adjust configuration files for different environments.
Recently I found C onfig Transformation Tool(CTT) on CodePlex and with addition of global replace using powershell it is enough and easier to do all required modifications

Content of ChangeConfig.cmd:
ctt s:..\web.config t:WebConfig.CTT d:..\web.config
powershell.exe -command "Get-Content ..\Remoting.config | ForEach-Object { $_ -replace '//localhost/ServicesCI/', '//ServerName01/ServicesCI/' } | Set-Content ..\remoting.temp"
powershell.exe -command "copy  ..\remoting.temp ..\remoting.config"
ctt s:..\EnterpriseLibraryLogging.config t:EnterpriseLibraryLogging.CTT d:..\EnterpriseLibraryLogging.config
@goto end
@rem some code that currently not used
:End
@pause


Content of example WebConfig.CTT :

<? xml version="1.0"?>
<
configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<
appSettings >
<
add key="ShowDeveloperExceptionInfo" value="False" xdt:Transform="Replace"  xdt:Locator="Match(key)" />
</
appSettings >
<
system.diagnostics >
<
sharedListeners >
<
add name="ServiceModelMessageLoggingListener" initializeData="C:\temp\testCIcopy2.svclog"   xdt:Locator="Match(name)" xdt:Transform="SetAttributes(initializeData)"   />
</
sharedListeners >
</
system.diagnostics >
</
configuration >

Extract from web.config - sharedListeners section

 < sharedListeners >
       <
add initializeData="C:\temp\TEST.svclog" type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="ServiceModelMessageLoggingListener" traceOutputOptions="Timestamp">
       <
filter type="" />
     </ add >
   </
sharedListeners >v
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Bookmarking for e-reading devices(Kindle and IPad)

Our family has Kindle and IPad, and periodically I had to use one or another.
Normally I prefer IPad, but Kindle has 2 advantages -
on a light sun it’s much easy to read Kindle screen,
and it also have free free wireless internet(but browser is quite limitted),when for my IPad wi-fi is required.
A few monthes ago I’ve wrote a post about Kindle and ability to transfer articles using Instapaper  add-on http://www.wordcycler.com/help.html . I beleive that it’s the most convinient way to pass html files to Kindle.
For iPhone and iPad I love ReadItLater. It saves any articles from web site or ipad Safary.
When you reading inside RIL, you can click on any link and ask to “Read it later” and continue with the main article. In Safary new link is always opened in background, which interrupt you from main article.
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Internet Explorer 9:IE 7 standards accidental change

One of our testers reported, that many pages are not working correctly in her IE9 browser.
It took me a while to find out that in development tools it was set Document Mode:IE7 standards.
The option has a shortcut -Alt-7, but it works only if development tools(F12) are opened.

I couldn't understand, how the setting was changed accidentally.If it’s possible, many IE users will have unexpected problems.
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Resharper setting to show method usage expanded.

During code analysis my favorite key is Shift-F12 to show usage of method/variable. And after this I needed to expand the list to show each line of usage.
Recently my collegue showed me that the results may be expended by default, which is very convenient.
To set it select Resharper menu->Options->Search & Navigation->Expand search Results Tree by Default.
I wourd suggest to Resharper to enable this setting by default.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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;

}

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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;
}
}
}
}

 

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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.

 

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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>

 

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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)

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

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.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Include MoreLinq Library for LINQ extensions

Last week I needed to find an object from collection with maximum value of the property and wrote the following

double maxHours = (from loc in locations select loc.TotalHours).Max();
var location = (from loc in locations where (loc.TotalHours == maxHours) select loc).FirstOrDefault();
but wasn’t happy and checked the internet.
The answer in http://stackoverflow.com/questions/914109/how-to-use-linq-to-select-object-with-minimum-or-maximum-property-value/914198#914198  referred to
http://code.google.com/p/morelinq/
I’ve  downloaded the DLL and  tried to reference 'MoreLinq'  from signed DLL,but got Error    609    Assembly generation failed -- Referenced assembly 'MoreLinq' does not have a strong name.
The issue 30 Make the assembly strong named http://code.google.com/p/morelinq/issues/detail?id=30&can=1 marked as fixed in 2010, but downloads are still old 2009

I decided to download  source code, but I do not have experience with SVN and instructions on  http://code.google.com/p/morelinq/source/checkout  were confusing for me.
It seems that  In SVN “anonymously check out” has a meaning “Get Latest” in TFS/SourceSafe terms.
Fortunately I was able to install http://www.sliksvn.com/en/download and created a batch to get source, which includes certificate key

GetSRCMoreLinq.BAT:
@rem from http://code.google.com/p/morelinq/source/checkout
@rem Use this command to anonymously check out the latest project source code:
cd C:\Program Files\SlikSvn\bin
@rem # Non-members may check out a read-only working copy anonymously over HTTP.
svn checkout http://morelinq.googlecode.com/svn/trunk/ C:\MoreLinq\Src
@pause

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
«February»
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910