Testing/Debugging/Logging

Unit, integration and regression testing

2 options to write tests for WCF Services

When writing Integration Tests for WCF Services, you have 2 options to access SUT(system under test)1. Inproc – Test Classes are calling methods from application DLLs directly.2. External – Tests are calling external services using client proxy with specified URL.If you own the code of the service, the Inproc method is preferred as it is allow to test units rather the whole object as black-box.If your tests are external clients of the service determined by URL, you need to have the service installed ......

Number of Unit test projects in Visual Studio solution

Some time ago I have discussion with my co-worker how to organize test projects. Should we have a single test project that does all sorts of things and references every project?It is good to have one integration test dll, but for unit tests, what is the point merging everything into one.In ideal world I agree that small independent projects are better. Unfortunately we have solution size limitations From http://stackoverflow.com/qu... ......

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 usepublic 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 ......

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/qu... These files will not be exposed to the public if kept in the right places (website\bin). ......

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? andhttp://dl.my/2013/create... found the Wizard creates quite funny default for enumerator- to use constructor.PaymentType paymentType = new PaymentType (); // TODO: Initialize to an appropriate valueI would prefer t have first/default enum value, e.g. PaymentType paymentType =PaymentType.None ;I should suggest it to ALM Rangers, who ......

EntLIb editor corrupts config files

I've tried to use Microsoft Enterprise Library(EntLIb) editor, as it was suggested in http://weblogs.asp.net/suku... 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.stackexc... is nothing wrong with static methods and they are easy to test (so long as they don't change any static data). For ......

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.EnterpriseInstrum... ......

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

Recently I've posted my experience with installation of PostSharp 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.I only want to add that the actual location of PostSharp HQ ( if it was installed from NuGet) is[solution root ]packages\PostSharp.2.1.7.1... ......

Assign multiple test categories using TestCategoryAttribute

I am using TestCategoryAttribute to filter which tests to run during builds and wandered, how to -how to assign multiple test categories.According to constructor documentation only single category can be specified. However TestCategories Property (plural!)can return multiple categories.Grouping Tests into Test Categories: You can add an automated test to one or multiple test categories using a test attribute. Each test can belong to multiple test categories.The recommended approach from MSDN How ......

What is testable code?

We are improving quality of code and trying to develop more unit tests. The question that developers asked was "How to make code testable ?" From http://openmymind.net/2010/... First and foremost, its loosely coupled, taking advantage of dependency injection (and auto-wiring), composition and interface-programming. Testable code is also readable - meaning it leverages single responsibility principle and Liskov substitution principle.A few practical ......

Dump an arbitrary object To Html String

For debugging purposes me and my collegue wanted to dump details of the arbitrary object, and created function that uses LINQPad Dump functionality (thanks to http://stackoverflow.com/a/... and original http://linqpad.uservoice.co... discussion) public static string DumpToHtmlString<T>(this T objectToSerialize) { string strHTML = ""; try { var writer = LINQPad.Util.CreateXhtmlWri... ......

Extract substrings starting with known text from long lines

I’ve received a .csv report from TripWire logs, where each entry is a long text strings.I needed to extract some substring from each row, e.g “ErrorCode: ABC1234” where preceding text is constant, but actual error code could be different. In TSQL I can do someting similar using patIndex and substring, e.g.select text,substring(TEXT,PATINDEX ('%ErrorCode:%',TEXT),10)In C# I can do it using RightAfter and TrimLength from My StringHelperRightAfter(Text... But I was able to ......

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.go... is much betterFinally 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 ......

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.Servic... 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/qu... ......

DDD Melbourne -lessons learned

I've attended DDD Melbourne and want to list the interesting points, that I've learned and want to follow. To read more: * Moles-Mocking Isolation framework for .NET. Documentation is here. (See also Mocking frameworks comparison created October 4, 2009 ) * WebFormsMVP * PluralSight http://www.pluralsight-trai... * ELMAH: Error Logging Modules and Handlers Great for new sites or sites without error logging/monitoring. However if you site already have working error ......

Command prompt utility to copy files for specified time range

I've tried to find an utility that will allow to copy files from big folder for specified time range. The discussion in experts-exchange suggested to use RoboCopy (http://www.microsoft.com/d... For the specified date command e.g 2009-11-24 command should be: Robocopy FolderFrom FolderTo /MINAGE:20091125 /MAXAGE:20091124 Note that for 1 day selection MINAGE should be one day BIGGER than required date. I still wish ......

Do not check-in DEBUG specific code.

We are using .Net Remoting to interact beteeen client and back end server. I needed to call a method from services class. For debugging purposes I decided to create the class directly. It was easier to debug without starting extra back-end process. The code was like the following: IMyServices services = (IMyServices)RemotingHelper... #if DEBUG services = new MyServices(); #endif // Process the task services.ProcessItems(Items... During the development I checked ......

Windows Workflow: Concatenate all parents QualifiedNames- instead of call stack

MSDN Debugging Workflows tells that The entries in the Call Stack window are a depth-first search of executing activities. You can double-click an entry to put focus on the selected activity.-It doesn't work for me. The text on stack trace is not meaningful, when activities are described. > codeRaiseEvent_ExecuteCode(... sender = {codeRaiseEvent_CAGPNRIterate [System.Workflow.Activities... System.EventArgs e = {System.EventArgs}) Line 671 C# System.Workflow.ComponentMo... ......

Logging application block-how configure different listeners for different level of message.

I've asked on codeplex EntLib forum logging application block-how configure different listeners for different severity? and AvanadeSupport gave me the answer to use "Filter" property of the tracelistener. MSDN Source Schema for the Logging Application Block documents listeners Child Element (loggingConfiguration)/add Child Element Now I am able to make configuration like the following <loggingConfiguration name="Logging Application Block" tracingEnabled="true"> <categorySources> <add ......

Debugging Windows Services with "Edit & Continue"

I needed to debug Windows Services. But I didn't like suggested in multiple articles Debugger.Launch. Thanks to post "Debugging Windows Services is a Pain" (and article CodeProject: Debugging Windows Services under Visual Studio .NET) I was able 1. To download Service Debugging Helper (Binary) (or Service Debugging Helper (Binary + Source)) 2. Add in my service project a Reference to AndersonImes.ServiceProcess... 3. Change in the Main() function //ServiceBase.Run(ServicesT... ServicesLoader.StartService... ......

Avoid throwing exception from asynchronous delegate.

I am using delegate to invoke asyncronous call of the function. Sometimes the function can throw exception. As described in thread Re: exception handling with events , article "Handling Exceptions Thrown from an Asynchronous Delegate"(and in many other places) "You should call EndInvoke in a try/catch block to catch any exceptions your asynchronous method threw". I followed the same approach in my Asynchronous long-running tasks in ASP.NET application The code is like the following: RecalculateDelegate ......

Enterprise Library Logging Application Block and Alternatives Links

Overview of to Enterprise Library Logging Application Block and Alternatives Loren Halvorson's comparision of the Enterprise Library Logging & Instrumentation Application Block and Log4Net (Published in 2005) Comments on the EntLib/Log4Net feature and performance comparison (Published in 2005) EntLib v4 has a few performance improvements in Logging Block. Based on quick read I feel that Log4Net and NLog are simple and may be sufficient for small applications. But they seems do not support specifying ......

Use WCF Message Logging

The post based on How to enable WCF tracing article Open WCF Service Configuration Editor under VS 2008 Tools menu or directly from installation folder (typically C:\Program Files\Microsoft SDKs\Windows\v6.0\Bin\SvcCo... - subfolder v6.0 can be different depending on which version of Windows SDK has been installed) To enable WCF message logging Click the Diagnostics node, and expand it. Enable Message Logging on the right Tab To edit Message Logging settings, click the Message Logging ......

Profiling Performance of ASP.NET Code Links

Below are a few links that I found about Profiling Performance of ASP.NET Code Code performance analysis in Visual Studio 2008 and Find Application Bottlenecks with Visual Studio Profiler * Tool : VSProfiler - Analyze Performance of Managed Code How To: Use CLR Profiler and Transcript: Profiling Managed Code with the CLR Profiler are talking about CLR memory allocation profiler. - * Auto Performance Tuning in ASP.NET 2.0 process model (processModel) section of machine.config comes with default value ......

Error: control with id ... could not be located or a different control is assigned to the same ID after postback

Our application has the intermittent (not too often,but can be 10-20 per day) errors like the following: An error has occurred because a control with id 'grdComplaints$ctl04$ctl00' could not be located or a different control is assigned to the same ID after postback. If the ID is not assigned, explicitly set the ID property of controls that raise postback events to avoid this error. System.Web.UI.Page.ProcessP... postData, Boolean fBeforeLoad) +877 System.Web.UI.Page.ProcessR... ......

TypeLoadExceptionHolder object can be inserted during unsuccessful Bynary Deserialization

I am using Binary Serialization to save and then reload state ot the object. In my post Issues using binary serialization to store object state for unit tests I described why I have to use it and how I tried to avoid versioning problems. I was able to read the object and access different properties of it withowt any warnings, but later, when the object was tried to be stored in Session, I've got the following error: System.Web.HttpException: Unable to serialize the session state. In 'StateServer' ......

Validation of viewstate MAC failed when using asp.timer to trigger UpdatePanel

I have a page with UpdatePanel and ASP:Timer, that refreshs the UpdatePanel every minute. It was noticed that after new release after the first refresh any postback causes "Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster." I've searched Google and found that this error is quite common. Below there are just a few suggestions: I do ......

Watin Test Recorder helps to navigate to required for debugging page.

It is quite common, that a developer needs to do a few (sometimes time-consuming) steps to navigate to the pages that are required debugging. And if you do some non-trivial change, Edit&Continue doesn't work, and you have to start debugging again. Yes, I know, that small unit tests should cover all the code paths and make debugging redundant. Unfortunately in the real life debugging is sometimes unavoidable. Watin Test Recorder allows to record the navigation steps and save it as a console executable(or ......

Issues using binary serialization to store object state for unit tests

To save object state for unit tests we use binary serialization. The object state saved to data file and at the start of the test is loaded from the file. It works OK until the object will be changed in a new version. Fortunately There is no problem when a new field is added, but if a field is deleted or removed, it most likely will cause deserialization exception(see Version Tolerant Serialization, Net Serialization FAQ, Solving Binary serialization versioning conflicts articles for details). Also ......

Unit Testing in .Net Notes.

Some time ago I posted my Unit Testing ASP.NET Applications notes. This post is to put togeter a few links that I found useful about general Unit testing frameworks. MbUnit vs. NUnit Vs. Team System Unit Testing - Choosing a unit test framework NUnit vs Team System Unit Test In our solutions we are using both NUnit and VSTS Unit testing. I like VSTS for the ability to generate test stubs code. But our build server has only VS Professional installed, that doesn't allow to include VSTS projects to ......

Function to validate Html Fragment

My code generate some dynamic HTML fragments and I want to know does the html valid. Thanks to HtmlAgilityPack it is easy: Debug.Assert(IsValidHtmlFra... public static bool IsValidHtmlFragment(string html) { HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocumen... doc.LoadHtml(html); return (doc.ParseErrors.Count==0); } ......

Reading AppSettings to be Unit Test friendly.

My application uses a lot of AppSettings to enable/disable different function and I wanted to created unit tests for different combination. I found the simplest way is to create static class data field, that is set to null by default, and loaded from config file if it is null. This allows in unit test methods to explicitely assign values, and when you want return to reading from config file, just reset it to null. static private bool? st_bAPIEnabled; public static bool IsAPIEnabled() { st_bAPIDomesticEnabled ......

Debug.Assert vs Unit Testing Assert. class

I have quite complicated class and I wanted during debugging/testing to validate that the data in the class is consistent. So I created a method Validate and used it in unit testing class MyComplexClass oClass= MyComplexClass.CreateClass(); Assert.IsTrue(Validate(oCla... But then I understood, that it would be better to call this function in the code to ensure that validation happens in the application, not only in unit testing. So I've added Validate method to the end of my CreateClass() method ......

WatiN testing of multi-level Frames page

I wanted to use WatiN Web Application Testing In .Net, to test html page with multi-level frames: E.g TopFrame.aspx : <Frameset> <FRAME SRC="ContentFrame.aspx"> </Frameset> ContentFrame.aspx <body> <IFRAME SRC="SubFrame.aspx"> </body> When I tried to check ie.Frame("ContentFrame") it didn't show me html of ContentFrame.aspx(as expected), but showed html of parent TopFrame.aspx. I've attached debug version of WatiN and stepped through to opening page. And in debugger ......

ASP.NET Exception Handling links

There are a few articles about ASP.NET Exception Handling that I want to bookmark. User Friendly ASP.NET Exception Handling -very good library, in particular for logging Unhandled Exceptions in ASP.NET Web Services. Minor disadvantage is that it uses propriatory logging, not Enterprise Library Logging Block. Take Exception To Critical Errors With Custom Application Blocks shows how to use Enterprise Library to build an error-reporting framework and post them to remote web server. Article Rich Custom ......

Tools to debug/Trace ASP.NET applications.

I personally hate to open blogs, that just have list of links without more useful information. But as I wrote in Ways to store bookmarks/favorites post, blog is a convinient way to save favorites. So I will just save links for now, and hopefully will add more comments about them later. FIDDLER supports HTTPS, ensure that "Capture HTTPS Connects" and "Decrypting HTTPS traffic" are ticked in in "Fiddler options". However running Fiddler in "https mode" can have side effects, e.g. my connection to TFs ......

Unit Testing ASP.NET Applications

I will put a few links related to ASP.NET unit testing. WATIN Initially I saw reference to WATIR from Scott Hanselman's post Integrating Ruby and Watir with NUnit . Recently I've found WatiN Web Application Testing In .Net, including articles WatiN - Web Application Testing In .Net - The Code Project - ASP.NET and WatiN Test Recorder - The Code Project .(The home page for WatiN Test Recorder is here) There is interesting article by Jeremy D. Miller with comment from ScottGu recommending WatiN . Using ......

Calling VS 2005 tests from Windows forms test harness

I like VS 2005 Team System ability to generate test cases. Using it with TestDriven.Net “Test with Debugger” allows quickly debug and test a new or existing code. However if you do a relatively long debugger session with multiple edit changes, the test session is often interrupted. I found that “Edit and Continue” for Windows form(or console) application is more stable. So my question was: can I call TestMethod from Windows form test harness? The answer is YES, no problem. You need to add reference ......

«September»
SunMonTueWedThuFriSat
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011