Override ToString() using Json serialization or something else.

When creating a new data class, it’s a good idea to override ToString() method to output most of the data.
It will help to see details in logs.

The only exception if the class has a sensitive data like CreditCard number or password.
For DataContract classes just use

public override string ToString()
              {
                      //Use JSON as the simplest serializer
                      string sRet = this.ToExtJsJsonItem();
                      return sRet;
              }
 
Sometimes it is useful to create extensions to standard .Net classes.
E.g. In CookieHelper class I've created
  public static string ToJsonString( this HttpCookie httpCookie)
        {
            string sRet = httpCookie.ToExtJsJsonItem();
            return sRet;
        }
 
The actual extension we are using was written by Nikita Pinchuk
      public static string ToExtJsJsonItem( this object item)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType());
            using ( MemoryStream ms = new MemoryStream ())
            {
                serializer.WriteObject(ms, item);
                StringBuilder sb = new StringBuilder ();

                sb.Append( Encoding.UTF8.GetString(ms.ToArray()));

                return sb.ToString();
            }
        }
 
For non DataContract classes the extension method may not work-it could cause an error: 
A first chance exception of type 'System.Runtime.Serialization.InvalidDataContractException' occurred in System.Runtime.Serialization.dll

In this case you can try  JSON.NET or the JsonValue types (nuget package JsonValue).

Sometimes I am using
 string sRet = this.XmlSerializeSafe();
 
But it is also not working for all types, e.g. 
MyClass cannot be serialized because it does not have a parameterless constructor.

In some places we are using LinqPad's Dump an arbitrary object To Html String, but we found it is too heavy for logs, plain text is easier to read than HTML.

I haven't tried yet ServiceStack.Text  C# .NET Extension method: T.Dump();

Deploy PDB files into production to ease exception report investigation.

 

 For a long time I believed that PDB as a part of debugging information should not be included in production deployment. Recently my colleague suggested to copy them to simplify exception investigations. 

 

The following  SO discussion convinced us that it is a good idea  ( at least for web sites).

 http://stackoverflow.com/questions/933883/are-there-any-security-issues-leaving-the-pdb-debug-files-on-the-live-servers

    These files will not be exposed to the public if kept in the right places (website\bin). 

 
 So we decided to deploy the PDBs into production.
 

BTW, if you include PDBs with your deployments, you don't need to store them in a symbol server,

 as it is suggested in http://www.wintellect.com/CS/blogs/jrobbins/archive/2009/05/11/pdb-files-what-every-developer-must-know.aspx

However we found that  PDBs   were generated not for all DLLs.  After some analysis we believe that MS changed default settings starting from VS 2008 (or may be since VS 2005) and make generation of PDB-only even for release mode. This is why older projects had generation of PDBs disabled.

To change setting in Visual Studio there is an option in the "Project Properties", "Build", "Advanced...".

Change "Debug Info:" to PDB-only.

The screenshots are available in the posthttp://callicode.com/Homeltpagegt/tabid/38/EntryId/24/How-to-disable-pdb-generation-in-Visual-Studio-2008.aspx

 

Related links:
The article http://blog.vuscode.com/malovicn/archive/2007/08/05/releasing-the-build.aspx compares different options for debug and release and confirms that in 2007 pdbonly was the default for release configuration of visual studio                  

/optimize+ /debug:pdbonly (release configuration of visual studio)

The article Include .pdb files in Web Application Publish for Release mode (VS2012)  wasn't applicable for us, but may be useful for someone else.

Default Enum initialisation by MS Create Unit Tests wizard.

VS 2012 doesn't show Create Unit Tests wizard. However it can be used - see 

Where is the “Create Unit Tests” selection?  and


I've found the Wizard creates quite funny default for enumerator- to use constructor.

PaymentType paymentType = new PaymentType (); // TODO: Initialize to an appropriate value

I would prefer t have first/default enum value, e.g. 

PaymentType paymentType =PaymentType.None ;

I should suggest it to ALM Rangers, who started a new test generation project

WCF Transactions are not supported by Azure.

We have a service operation, for which it is very important to ensure that a client receives the status, that was determined at the end of operation.
If client does receive the response, the server status should be "completed". Otherwise (in case of communication error), server status should be rollback and stay as "pending". The possible technical solutions were discussed and WCF Transactions support with  2PC(two phase commit) was selected.  We implemented service operation with transaction commit/rollback support and asked our clients to use it.
Our main client is running on Azure. It was a big disappointment, when Readify consultant Himanshu Desai  adviced that WCF Transactions are not supported by Azure.

I did a quick check on Internet and didn't find that is well known issue.
Below are a few quotes to describe the limitation:

2PC in the cloud is hard for  all sorts of reasons. 2PC as implemented by DTC effectively depends on the coordinator and its log and connectivity to the coordinator to be very highly available. It also depends on all parties cooperating on a positive outcome in an expedient fashion. To that end, you need to run DTC in a failover cluster, because it’s the Achilles heel of the whole system and any transaction depends on DTC clearing it.

The bottom line is that Service Bus, specifically with its de-duplication features for sending and with its reliable delivery support using Peek-Lock (which we didn’t discuss in the thread, but see here and also here) is a great tool to compensate for the lack of coordinator support in the cloud

The Azure storage folks implement their clusters in a very particular way to provide highly-scalable, highly-available, and strongly consistent storage – and they are using a quorum based protocol (Paxos) rather than classic atomic TX protocol to reach consensus. 

In the current release, only one top level messaging entity, such as a queue or topic can participate in a transaction, and the transaction cannot include any other transaction resource managers, making transactions spanning a messaging entity and a database not possible.

Has Windows Azure any kind of distributed transaction mechanism in order to include any remote object creation in an atomic transaction including other domain-specific operations?  
The alternative solution suggested by Himanshu Desai is to have an operation to start a process on the server and then poll in a loop on a client until final status is received from the server. 
 

2010 version of TF (TFS command tool) unable to determine the workspace that is working with Vs 2012 and TFS 2012

We upgraded to VS 2012 and TFS 2012 a month ago.
I have a backupShelve.cmd that used to work before upgrade, but when I run it yesterday caused the error

Unable to determine the workspace. You may be able to correct this by running 'tf workspaces /collection:TeamProjectCollectionUrl'

 
The backupShelve.cmd file is the following 

call "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86
tf shelve   /replace /comment:"Current backup" CurrentBackupMT01 /noprompt
pause

After some time I've noticed, that batch file refers to version 10 folder instead of "Microsoft Visual Studio 11".

After I've changed folder name, TF started to work.

EntLIb editor corrupts config files

I've tried to use Microsoft Enterprise Library(EntLIb) editor, as it was suggested in http://weblogs.asp.net/sukumarraju/archive/2011/11/07/configuring-wcf-service-to-utilise-enterprise-library-logging-application-to-log-data-to-database.aspx, but after changes all comments in config files were removed.
 
Always consider to move any Enterprise Library configurations to a separate file before editing.

Static methods not always bad for testability

Some time ago I've posted a few links about What is testable code?

Reading the links someone can feel that any static methods are bad for testability. However it is a wrong impression- static methods without external dependencies are good for testing.

 http://programmers.stackexchange.com/questions/5757/is-static-universally-evil-for-unit-testing-and-if-so-why-does-resharper-recom
There is nothing wrong with static methods and they are easy to test (so long as they don't change any static data). For instance, think of a Maths library, which is good candidate for a static class with static methods 
 
Static methods which hold no state and cause no side effects should be easily unit testable. In fact, I consider such methods a "poor-man's" form of functional programming; you hand the method an object or value, and it returns an object or value. Nothing more. I don't see how such methods would negatively affect unit testing at all.

Alternatively you can mock anything - implemented by MS Fakes, TypeMock, JustMock and Moles.  They rely on .NET'sProfiling API. It can intercept any of your CIL instructions.
 
See related links  
 

Using PostSharp.Toolkit.Diagnostics, when not all developers have Pro licenses.

We have only couple of developers who are using PostSharp.Toolkit.Diagnostics and having  PostSharp Pro license .
However ther are much more developers , who are building our solution, but do not required Toolkit.Diagnostics XmlMulticast features, that are referred in %ProjName%.psproj file.

As a workaround I've suggested to to replace locally psproj file with dummy, that doesn't have XmlMulticast(PostSharp feature that available only in Pro edition).

If a developer doesn't have PostSharp Pro license, they shoul set  Environment variable POSTSHARP_PRO=false to effectively exclude psproj from the build on their local machine.
detailed instructions iHow to Add, Remove or Edit Environment variables in Windows 7 can be found at http://www.itechtalk.com/thread3595.html.
For Each project using PostSharp.Toolkit.Diagnostics  A subfolder DEV.Config has been created.
It includes minimal 
dev.psproj , 
PreBuild.cmd
And (optionally) copy of MyProect.psproj - backup copy of real .psproj file.


For each project that uses toolkit Insert into PreBuild Event command line
cmd /c $(ProjectDir)\DEV.Config\PreBuild.cmd $(ProjectName)


 

File DEV.Config\PreBuild.cmd
rem developers without PostSharp Pro installed please set environment variable POSTSHARP_PRO=false
REM Insert into PreBuild Event command line
REM cmd /c $(ProjectDir)\DEV.Config\PreBuild.cmd $(ProjectName)
if NOT '%POSTSHARP_PRO%=='false goto end
:devPsproj
rem The current dir seems to be \bin\Debug
cd ..\..\Dev.Config
set ProjName=%1
set PSProjFile=..\%ProjName%.psproj
ATTRIB -R %PSProjFile%
copy /Y dev.psproj %PSProjFile%
:end
rem pause

See also Nuget command line

VAB ValidationResults Extensions

We've started to actively used Microsoft Enterprise Library Validation Enterprise Block ( VAB)  and I was surprised , that a few commonly used  operations are not supplied(or I haven't found them) out of the box.
See two extensions, that make use of VAB simpler

public static class ValidationResultsExtensions
       {
               public static string CombinedMessage( this ValidationResults results)
              {
                      string errorMessage = ( from res in results select String.Format(" {0}:{1} ", res.Key, res.Message)).ToDelimitedString( ";");
                      return errorMessage;
              }
//Throws ValidationException if not valid
           public static void ValidateConstraints<T>( this T target)
           {
               Validator validator = ValidationFactory.CreateValidator<T>();
               var results = new ValidationResults();
               validator.Validate(target, results);
               if (results.IsValid == false)
               {
                   var errorMessage = results.CombinedMessage();
                   throw new ValidationException(errorMessage);
               }
           }
       }v

Using CollectionNotEmptyValidator

We recently started to use Microsoft Enterprise Library Validation Enterprise Block
 (VAB) to check interfaces between modules. One of the properties to validate is array  
of values, that should be not empty, and shoul include one of expected values. 
I found CollectionNotEmptyValidator at http://www.eggheadcafe.com/tutorials/xaml/9af7ac1a-d7f3-4e00-9aec-33ef1ec7d1a3/wpf-custom-validation-using-the-enterprise-library.aspx, that allows to  validate the property to satisfy part of requirements.
 
The class mostly works as is, I've only changed exception to Validation error if object to validate is not a collection.


        public override void DoValidate( object objectToValidate, object currentTarget, string key, ValidationResults validationResults)
              {

                      if (objectToValidate is ICollection)
                     {

                            if (((( ICollection)objectToValidate).Count != 0) == Negated)
                           {

                                  LogValidationResult(validationResults, MessageTemplate, currentTarget, key);

                           }

                     }

                     else
                     {

//throw new ApplicationException("Object type not supported by validator.");


                           LogValidationResult(validationResults, "Object is not a collection.", currentTarget, key);
                     }

I've also changed testing console app to a number of MSTest TestMethods.

#region Namespace Imports
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.SDC.Common.Validation;
using Microsoft.SDC.Common.Web.WCF;
using Microsoft.VisualStudio.TestTools.UnitTesting;



#endregion
namespace MSCommon.Validation
{
// I have defined an Order class
//      containing an Items property for this. There are four possible cases we can test:


//- Collection is empty, Negated property is false

//- Collection is non-empty, Negated property is false

//- Collection is non-empty, Negated property is true

//- Collection is empty, Negated property is true


       [ TestClass]
        public class CollectionNotEmptyValidatorTests
       {
              [ TestMethod(), CITest ]
               public void InvalidTest_CollectionIsEmpty()
              {
                      // Invalid test - collection is empty
                      var order = NewEmptyOrder();
                      CollectionNotEmptyValidator validator = new CollectionNotEmptyValidator ();

                      ValidationResults results = validator.Validate(order.Items);

                      Assert.IsTrue(!results.IsValid);

                      Debug.WriteLine(results.First().Message);

                      // Output: The collection must not be empty.
              }

              [ TestMethod(), CITest ]
               public void ValidTest_CollectionIsEmpty()
              {
                      // Valid test - collection has items
                      var order = NewEmptyOrder();
                     order.Items.Add( new Order. OrderItem());
                      CollectionNotEmptyValidator validator = new CollectionNotEmptyValidator ();

                      ValidationResults results = validator.Validate(order.Items);

                      Assert.IsTrue(results.IsValid);

                      Debug.WriteLine( "Valid test");
              }

              [ TestMethod(), CITest ]
               public void NegatedTest_CollectionHasItems()
              {
                      // Invalid test - collection has items (Negated)

                      var order = NewEmptyOrder();
                     order.Items.Add( new Order. OrderItem());
                      CollectionNotEmptyValidator validator = new CollectionNotEmptyValidator (true );

                      ValidationResults results = validator.Validate(order.Items);
                      Assert.IsTrue(!results.IsValid);

                      Debug.WriteLine(results.First().Message);
                      // Output: The collection must be empty.
              }


              [ TestMethod(), CITest ]
               public void NegatedTest_CollectionIsEmpty()
              {
                      // Invalid test - collection has items (Negated)

                      var order = NewEmptyOrder();
                     order.Items.Add( new Order. OrderItem());
                      CollectionNotEmptyValidator validator = new CollectionNotEmptyValidator (true );

                      ValidationResults results = validator.Validate(order.Items);
                      Assert.IsTrue(!results.IsValid);

                      Debug.WriteLine(results.First().Message);
                      // Output: The collection must be empty.
              }


               private static Order NewEmptyOrder()
              {
                      Order order = new Order();

                     order.Items = new Collection<Order .OrderItem >();
                      return order;
              }

              #region Example Classes for tests

               public class Order

              {
                     [ CollectionNotEmptyValidator()]
                      public Collection<OrderItem > Items { get; set; }

                      public bool ValidateItems()

                     {
                            return Items.Count > 0;
                     }

                      public class OrderItem

                     {
                     }
              }

              #endregion //Example Classes for tests
       }
}


I am planning to create derived ContainValidator.

I stopped to use GoogleDrive in favor to EverNote.


For a long time I've used Google Docs to write different notes, collect links for search and drafts of my posts.

Later on IPad I've started to use EverNote. The main advantage for me was that EverNote allows to create new notes when offline and even for normal account usually allow access existing notes (but sometimes telling that a note is not available). And since EverNote implemented auto save on IPad, I stopped using Google Drive. I am able to use EverNote Desktop on home and work PCs, from different browsers, from IPad and Windows Phone.

Additional very convenient tool on IPad is EverClip ( http://clip.ignition.hk/?locale=en&utm_source=homepage ), that copies text together with the URL(from Browser page) to notes. I am missing similar facility in PC browsers.

Yesterday I've copied one of my old documents to Evernote and found, that links in the document are broken and cause error like the following:


404. That’s an error.
The requested URL /http%3A%2F%2Fstackoverflow.com%2Fquestions%2F3110456%2Fpostsharp-build-targets-not-running-when-using-debug-configuration was not found on this server. That’s all we know.

So Google Drive stores URL in encoded format, which making harder to copy texts with links. It's easy to fix, but annoying. Hopefully I would not need to copy many files from Google Drive.v

Enterprise Instrumentation: The 'sessionName' parameter of value 'TraceSession' is not valid

We are still using Enterprise Instrumentation(that was created during .Net 1.1 time)
In new Server 2008 environment and IIS 7 we have the following errors:
The 'sessionName' parameter of value 'TraceSession' is not valid. A trace session of this name does not exist in the TraceSessions configuration file for Windows Trace Session Manager service. Ensure that a session of this name exists in the TraceSessions configuration file and that the Windows Trace Session Manager service is started.
   at Microsoft.EnterpriseInstrumentation.EventSinks.TraceEventSink..ctor(IDictionary parameters, EventSource eventSource)
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle._InvokeConstructor(IRuntimeMethodInfo method, Object[] args, SignatureStruct& signature, RuntimeType declaringType)
   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
   at Microsoft.EnterpriseInstrumentation.EventSinks.EventSink.CreateNewEventSinks(DataRow[] eventSinkRows, EventSource eventSource)

I’ve seen the same errors on development Win7 machines when using IIS. It seems not a problem on Cassini.

I've checked ,that Windows Trace Session Manager Service has started and 
The file C:\Program Files (x86)\Microsoft Enterprise Instrumentation\Bin\Trace Service\TraceSessions.config has corresponding entry
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns="http://www.microsoft.com/schema/EnterpriseInstrumentation/v1/TraceSessions.xsd">
                <defaultParameters minBuffers="4" maxFileSize="10" maxBuffers="25" bufferSize="20" logFileMode="sequential" flushTimer="3" />
                <sessionList>
                                 <session name="TraceSession" enabled="false" fileName="C:\Program Files (x86)\Microsoft Enterprise Instrumentation\Bin\Trace Service\Logs\TraceLog.log" />
                </sessionList>
</configuration>
The errors still continue, but I was able to disable  the parameter in  eventSink configuration

   <eventSink name=" traceSink" description=" Outputs events to the Windows Event Trace." type ="Microsoft.EnterpriseInstrumentation.EventSinks.TraceEventSink ">
                <!-- MNF disabled parameter to  avoid error "The 'sessionName' parameter of value 'TraceSession' is not valid" 
                     < parameter name ="sessionName " value ="TraceSession " />
                    -->
    </ eventSink>


One day I wish to replace all EnterpriseInstrumentation calls with NLog.

Eager Loading more than 1 table in LinqtoSql

When I've tried in Linq2Sql to load table with 2 child tables, I've noticed, that multiple SQLs are generated. I've found that  it is
a known issue, if you try to specify more than one to pre-load it just  picks which one to pre-load and which others to leave deferred (simply ignoring those LoadWith hints)
There are more explanations in 
The reason the relationship in your blog post above is generating multiple queries is that you have two (1:n) relationship (Customers->Orders) and (Orders->OrderDetails). If you just had one (1:n) relationship (Customer->Orders) or (Orders->OrderDetails) LINQ to SQL would optimize and grab it in one query (using a JOIN). 

The alternative -to use SQL and POCO classes-see http://stackoverflow.com/questions/238504/linq-to-sql-loading-child-entities-without-using-dataloadoptions?rq=1

Fortunately the problem is not applicable to Entity Framework, that we want to use in future development instead of Linq2Sql

Product firstProduct =  db.Product.Include("OrderDetail").Include("Supplier").First();

м

Do NOT Change "Copy Local” project references to false, unless understand subsequences.

To optimize performance of visual studio build I've found multiple recommendations to change CopyLocal property for dependent dlls to false,

  1. e.g. From http://stackoverflow.com/questions/690033/best-practices-for-large-solutions-in-visual-studio-2008 
  • CopyLocal? For sure turn this off

  • Always set the Copy Local property to false and enforce this via a custom msbuild step
  • My advice is to always set ‘Copy Local’ to false

Some time ago we've tried to change the setting to false, and found that it causes problem for deployment of top-level projects.

Recently I've followed the suggestion and changed the settings for middle-level projects. It didn't cause immediate issues, but I was warned by Readify Consultant Colin Savage about possible errors during deployments

I haven't undone the changes immediately and we found a few issues during testing.

There are many scenarios, when you need to have Copy Local' left to True.

The concerns are highlighted in some StackOverflow answers, but they have small number of votes.The concerns are highlighted in some StackOverflow answers, but they have small number of votes.

Top-level projects:  set copy local = true.


First of all, it doesn't work correctly for top-level projects, i.e. executables or web sites.
  • for all the references in the one at the top set copy local = true.
 
 
If you set ‘ Copy Local = false’, VS will, unless you tell it otherwise, place each assembly alone in its own .\bin\Debugdirectory. Because of this, you will need to configure VS to place assemblies together in the same directory. To do so, for each VS project, go to VS > Project Properties > Build tab > Output path, and set the Ouput path to ..\bin\Debugfor debug configuration, and ..\bin\Release for release configuration.

Second-level  dependencies:  set copy local = true.

Another example when copylocal =false fails on run-time, is when top level assembly doesn't directly referenced one of indirect dependencies.
E..g. Top-level assembly A has reference to assembly B with copylocal =true, but assembly B has reference to assembly C with copylocal =false. Most likely assembly C will be missing on runtime and will cause errors 

Copy local is important for deployment scenarios and tools. As a general rule you should use CopyLocal=True
 
and http://stackoverflow.com/questions/602765/when-should-copy-local-be-set-to-true-and-when-should-it-not?lq=1

Unfortunately there are some quirks and CopyLocal won't necessary work as expected for assembly references in secondary assemblies structured as shown below.

  • MainApp.exe
    • MyLibrary.dll
      • ThirdPartyLibrary.dll (if in the GAC CopyLocal won't copy to MainApp bin folder)

This makes xcopy deployments difficult . 

Reflection called DLLs  dependencies:  set copy local = true.
E.g user can see error "ISystem.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information."

The fix for the issue is recommended in http://stackoverflow.com/a/6200173/52277


"I solved this issue by setting the Copy Local attribute of my project's references to true."


In general, the problems with investigation of deployment issues may overweight the benefits of reduced build time.
 
Setting the Copy Local to false without considering deployment issues is not a good idea. 


 

Adding PostSharp to new projects, when it's installed for some projects in solution.

Once PostSharp  is installed in  solution's packages folder for some project(s), I often need to add PostSharp to another project in the same solutionSection "Adding PostSharp to your project using PostSharp HQ" of documentation described the process quite well.

[solution root ]packages\PostSharp.2.1.7.15\tools\Release\PostSharp.HQ.exe.
Also you need to ensure that the project is checked out,i.e. not readOnly.
«May»
SunMonTueWedThuFriSat
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678