• Shortcuts : 'n' next unread feed - 'p' previous unread feed • Styles : 1 2

» Publishers, Monetize your RSS feeds with FeedShow:  More infos  (Show/Hide Ads)


Date: Saturday, 04 May 2013 03:18

Originally posted on: http://geekswithblogs.net/mnf/archive/2013/05/04/override-tostring-using-json-serialization-or-something-else.aspx

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();
Author: "Michael Freidgeim" Tags: "Testing/Debugging/Logging"
Comments Send by mail Print  Save  Delicious 
Date: Saturday, 04 May 2013 03:03

Originally posted on: http://geekswithblogs.net/mnf/archive/2013/05/04/deploy-pdb-files-into-production-to-ease-exception-report-investigation.aspx

 

 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.
Author: "Michael Freidgeim" Tags: "Deployment, Testing/Debugging/Logging"
Comments Send by mail Print  Save  Delicious 
Date: Saturday, 16 Mar 2013 02:00

Originally posted on: http://geekswithblogs.net/mnf/archive/2013/03/16/default-enum-initialisation-by-ms-create-unit-tests-wizard.aspx

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
Author: "Michael Freidgeim" Tags: "Testing/Debugging/Logging"
Comments Send by mail Print  Save  Delicious 
Date: Saturday, 16 Mar 2013 01:43

Originally posted on: http://geekswithblogs.net/mnf/archive/2013/03/16/wcf-transactions-are-not-supported-by-azure.aspx

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. 

URLTransactions in Windows Azure (with Service Bus) – An Email Discussion 

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. 
 
Author: "Michael Freidgeim" Tags: "Web Services/WCF"
Comments Send by mail Print  Save  Delicious 
Date: Saturday, 16 Mar 2013 01:27

Originally posted on: http://geekswithblogs.net/mnf/archive/2013/03/16/2010-version-of-tf-tfs-command-tool-unable-to-determine.aspx

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.
Author: "Michael Freidgeim" Tags: "Visual Studio/TFS"
Comments Send by mail Print  Save  Delicious 
Date: Saturday, 16 Feb 2013 04:45

Originally posted on: http://geekswithblogs.net/mnf/archive/2013/02/16/entlib-editor-corrupts-config-files.aspx

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.
Author: "Michael Freidgeim" Tags: "Testing/Debugging/Logging, .Net Framewor..."
Comments Send by mail Print  Save  Delicious 
Date: Saturday, 16 Feb 2013 04:24

Originally posted on: http://geekswithblogs.net/mnf/archive/2013/02/16/static-methods-not-always-bad-for-testability.aspx

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  
 

Author: "Michael Freidgeim" Tags: "Testing/Debugging/Logging"
Comments Send by mail Print  Save  Delicious 
Date: Saturday, 16 Feb 2013 03:57

Originally posted on: http://geekswithblogs.net/mnf/archive/2013/02/16/using-postsharp.toolkit.diagnostics-when-not-all-developers-have-pro-licenses.aspx

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
Author: "Michael Freidgeim" Tags: ".Net Framework, Visual Studio/TFS"
Comments Send by mail Print  Save  Delicious 
Date: Saturday, 16 Feb 2013 03:46

Originally posted on: http://geekswithblogs.net/mnf/archive/2013/02/16/vab--validationresults-extensions.aspx

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
Author: "Michael Freidgeim" Tags: ".Net Framework"
Comments Send by mail Print  Save  Delicious 
Date: Saturday, 16 Feb 2013 03:35

Originally posted on: http://geekswithblogs.net/mnf/archive/2013/02/16/using-collectionnotemptyvalidator.aspx

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.
Author: "Michael Freidgeim" Tags: ".Net Framework, CodeProject"
Comments Send by mail Print  Save  Delicious 
Date: Saturday, 15 Dec 2012 01:54

Originally posted on: http://geekswithblogs.net/mnf/archive/2012/12/15/i-stopped-to-use-googledrive-in-favor-to-evernote.aspx


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
Author: "Michael Freidgeim" Tags: "Blogging, iPad"
Comments Send by mail Print  Save  Delicious 
Date: Sunday, 09 Dec 2012 05:04

Originally posted on: http://geekswithblogs.net/mnf/archive/2012/12/09/enterprise-instrumentation-the-sessionname-parameter-of-value-tracesession-is.aspx

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.
Author: "Michael Freidgeim" Tags: "Testing/Debugging/Logging"
Comments Send by mail Print  Save  Delicious 
Date: Sunday, 09 Dec 2012 04:45

Originally posted on: http://geekswithblogs.net/mnf/archive/2012/12/09/eager-loading-more-than-1-table-in-linqtosql.aspx

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();

м
Author: "Michael Freidgeim" Tags: "SQL Server, LINQ"
Comments Send by mail Print  Save  Delicious 
Date: Sunday, 09 Dec 2012 02:15

Originally posted on: http://geekswithblogs.net/mnf/archive/2012/12/09/do-not-change-copy-local-project-references-to-false-unless.aspx

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. 


 
Author: "Michael Freidgeim" Tags: ".Net Framework, Visual Studio/TFS"
Comments Send by mail Print  Save  Delicious 
Date: Sunday, 04 Nov 2012 07:59

Originally posted on: http://geekswithblogs.net/mnf/archive/2012/11/04/adding-postsharp-to-new-projects-when-its-installed-for-some.aspx

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.
Author: "Michael Freidgeim" Tags: ".Net Framework, Testing/Debugging/Loggin..."
Comments Send by mail Print  Save  Delicious 
Date: Sunday, 28 Oct 2012 02:30

Originally posted on: http://geekswithblogs.net/mnf/archive/2012/10/28/helper-method-to-replaceremove-characters-that-do-not-match-the.aspx

I have a few fields, that use regEx for validation. In case if provided field has unaccepted characters, I don't want to reject the whole field, as most of validators do, but just remove invalid characters.
 I am expecting to keep only Character Classes for allowed characters and created a helper method to strip unaccepted characters.
 
The allowed pattern should be in Regex format, expect them wrapped in square brackets. function will insert a tilde after opening squere bracket , according to http://stackoverflow.com/questions/4460290/replace-chars-if-not-match.
 
[^ ] at the start of a character class negates it - it matches characters not in the class.I anticipate that it could work not for all RegEx describing valid characters sets,but it works for relatively simple sets, that we are using.         /// <summary>               /// Replaces  not expected characters.               /// </summary>               /// <param name="text"> The text.</param>               /// <param name="allowedPattern"> The allowed pattern in Regex format, expect them wrapped in brackets</param>               /// <param name="replacement"> The replacement.</param>               /// <returns></returns>               /// //        http://stackoverflow.com/questions/4460290/replace-chars-if-not-match.               //http://stackoverflow.com/questions/6154426/replace-remove-characters-that-do-not-match-the-regular-expression-net               //[^ ] at the start of a character class negates it - it matches characters not in the class.               //Replace/Remove characters that do not match the Regular Expression               static public string ReplaceNotExpectedCharacters( this string text, string allowedPattern,string replacement )              {                     allowedPattern = allowedPattern.StripBrackets( "[", "]" );                      //[^ ] at the start of a character class negates it - it matches characters not in the class.                      var result = Regex .Replace(text, @"[^" + allowedPattern + "]", replacement);                      return result;              }
static public string RemoveNonAlphanumericCharacters( this string text)
              {
                      var result = text.ReplaceNotExpectedCharacters(NonAlphaNumericCharacters, "" );
                      return result;
              }
        public const string NonAlphaNumericCharacters = "[a-zA-Z0-9]";

There are a couple of functions from my StringHelper class  http://geekswithblogs.net/mnf/archive/2006/07/13/84942.aspx ,
 that are used here.
    //                           /// <summary>               /// 'StripBrackets checks that starts from sStart and ends with sEnd (case sensitive).               ///           'If yes, than removes sStart and sEnd.               ///           'Otherwise returns full string unchanges               ///           'See also MidBetween               /// </summary>               /// <param name="str"></param>               /// <param name="sStart"></param>               /// <param name="sEnd"></param>               /// <returns></returns>               public static string StripBrackets( this string str, string sStart, string sEnd)              {                      if (CheckBrackets(str, sStart, sEnd))                     {                           str = str.Substring(sStart.Length, (str.Length - sStart.Length) - sEnd.Length);                     }                      return str;              }               public static bool CheckBrackets( string str, string sStart, string sEnd)              {                      bool flag1 = (str != null ) && (str.StartsWith(sStart) && str.EndsWith(sEnd));                      return flag1;              }
               public static string WrapBrackets( string str, string sStartBracket, string sEndBracket)              {                      StringBuilder builder1 = new StringBuilder(sStartBracket);                     builder1.Append(str);                     builder1.Append(sEndBracket);                      return builder1.ToString();              }v
Author: "Michael Freidgeim" Tags: ".Net Framework, Helper Functions"
Comments Send by mail Print  Save  Delicious 
Date: Sunday, 28 Oct 2012 02:02

Originally posted on: http://geekswithblogs.net/mnf/archive/2012/10/28/maxitemsinobjectgraph-limit-required-to-be-changed-for-server-and-client.aspx

We have a wcf service, that expects to return a huge XML data. It worked ok in testing, but in production it failed with error  "Maximum number of items that can be serialized or deserialized in an object graph is '65536'. Change the object graph or increase the MaxItemsInObjectGraph quota."

The MSDN article about   dataContractSerializer xml configuration  element  correctly  describes maxItemsInObjectGraph attribute default as 65536, but documentation for of the 

DataContractSerializer.MaxItemsInObjectGraph property and DataContractJsonSerializer.MaxItemsInObjectGraph Property 

are talking about Int32.MaxValue, which causes confusion, in particular because Google shows properties articles before configuration articles.


When we changed the value in WCF service configuration, it didn't help, because the similar change must be ALSO done on client.

There are similar posts:


You need to set the MaxItemsInObjectGraph on the dataContractSerializer using a behavior on both the client and service. See  for an example.http://devlicio.us/blogs/derik_whittaker/archive/2010/05/04/setting-maxitemsinobjectgraph-for-wcf-there-has-to-be-a-better-way.aspx

 I had forgot to place this setting in my client app.config file.

It seems that DataContractJsonSerializer.MaxItemsInObjectGraph has actual default 65536, because there is no configuration for JSON serializer, but  it complains about the limit.


I believe that MS should clarify the properties documentation re default limit and make more specific error messages to distinguish server side and client side errors.

Note, that as a workaround it's possible to use commonBehaviors section which can be defined only in machine.config:
<commonBehaviors>
<behaviors>
<endpointBehaviors>
<dataContractSerializer maxItemsInObjectGraph="..." />
</endpointBehaviors>
</behaviors>
</commonBehaviors>

v
Author: "Michael Freidgeim" Tags: "Web Services/WCF"
Comments Send by mail Print  Save  Delicious 
Date: Wednesday, 17 Oct 2012 12:04

Originally posted on: http://geekswithblogs.net/mnf/archive/2012/10/17/postsharp-deployment-to-build-machine--use-setup-installation-not-nuget.aspx

PostSharp has well documented different methods of installation. I've chosen installing NuGet packages, because according to 
NuGet is the easiest way to add PostSharp to a project without installing the product on every machine.

However it didn't work well for me. I've added PostSharp NuGet package to one project in the solution.

 When I wanted to use PostSharp in other project, Visual Studio tab showed that PostSharp is not enabled for this project

I've added the NuGet package to the new project, which installed a new version of the package in the new Packages subfolder.
When I wanted to refer PostSharp from the third project, I've ended up with another version of PostSharp installed.
Additionally multiple versions of Diagnostics were created. It definitely causes confusion and errors.
 
More problems we experienced on build server. According to Using PostSharp on a Build Server
"If you chose to deploy PostSharp in the source repository, it does not need to be installed specifically on the build server. "
It didn't work on our build server.
I kept getting errors "The "AddIns" parameter is not supported by the "PostSharp21" task." and "The "DisableSystemBindingPolicies" parameter is not supported by the "PostSharp21" task."
 
From my experience the only way to have the latest version of PostSharp working on the build server is to install it using Setup as described in Deploying PostSharp with the Setup Program
 
 
Gael acknowledged the issues with possible version conflicts. see http://support.sharpcrafters.com/discussions/problems/388-the-postsharp21-task-failed-unexpectedly
 
 
Author: "Michael Freidgeim" Tags: ".Net Framework"
Comments Send by mail Print  Save  Delicious 
Date: Saturday, 06 Oct 2012 02:49

Originally posted on: http://geekswithblogs.net/mnf/archive/2012/10/06/missing-error-handling-in-streaming-ajax-proxy-log.aspx

on our web site, but started to notice errors accessing log.txt file.
I found that the file is created by Log class and doesn't have ability to switch it off and error handling.
I've added reading file name from configuration and try/catch block
  public static class Log
    {
        private static StreamWriter logStream;
        private static object lockObject = new object ();
    public static void WriteLine(string msg)
        {
                      string logFileName = ConfigurationExtensions.GetAppSetting("AjaxStreamingProxy.LogFile" ,"");
                      if (logFileName.IsNullOrEmpty())
                            return;
                      try
                     {
                            if (logStream == null )
                           {
                                   lock (lockObject)
                                  {
                                          if (logStream == null )
                                         {
                           logStream = File.AppendText(Path .Combine(AppDomain.CurrentDomain.BaseDirectory, logFileName));
                                         }
                                  }
                           }
                           logStream.WriteLine(msg);
                     }
                      catch (Exception exc)
                     {
                            string ignoredMsg = String .Format("The error occured while logging {0}, but processing will continue.\n {1} ", exc);
                            LoggerHelper.LogEvent(ignoredMsg, MyCategorySource, TraceEventType .Warning, true);
                     }
        }
Author: "Michael Freidgeim" Tags: "ASP.NET"
Comments Send by mail Print  Save  Delicious 
Date: Sunday, 30 Sep 2012 01:55

Originally posted on: http://geekswithblogs.net/mnf/archive/2012/09/30/adding-asynctrue-to-the-page--no-side-effects-noticed.aspx

Recently I needed to implement PageAsyncTask  in .Net 4 web forms application.

"A PageAsyncTask object must be registered to the page through the RegisterAsyncTask method. The page itself does not have to be processed asynchronously to execute asynchronous tasks. You can set the Async attribute to either true (as shown in the following code example) or false on the page directive and the asynchronous tasks will still be processed asynchronously:

<%@ Page Async="true" %>

When the Async attribute is set to false, the thread that executes the page will be blocked until all asynchronous tasks are complete."

I was worry about any site effects if I will set  Async=true on the existing page.
The only documented restrictions, that I found are that
@Async is not compatible with @AspCompat and Transaction attributes (from @ Page directive  MSDN article). In other words, 
Asynchronous pages do not work when the AspCompat attribute is set to true or the Transactionattribute is set to a value other than Disabled in the @ Page directive

From our tests we conclude, that adding Async=true to the page is quite safe, even if you don't always call Async tasks from the page 
Author: "Michael Freidgeim" Tags: "ASP.NET"
Comments Send by mail Print  Save  Delicious 
Next page
» You can also retrieve older items : Read
» © All content and copyrights belong to their respective authors.«
» © FeedShow - Online RSS Feeds Reader