## středa 19. října 2016

### .NET and Windows proxy problems

Windows has two HTTP APIs, which are unfortunatelly not 100% compatible in case of proxy settings:
• WinINet, used by Internet Explorer and most of the Windows C/C++ applications. Window proxy settings dialog sets the proxy for the WinINet
• WinHTTP used by .NET.
So, when you develop a .NET application, is may happen that on a certain computer the Internet Explorer and other apps are connecting well, while your .NET app cannot connect to the Internet.
Since some proxy settings are hidden to the user by the "Automatically detect settings"checkbox, I have made a simple program WinProxyViewer, which may be run with a inexperienced user and the result sent to the application authors.

### Default Credentials

.NET does not pick up the proxy credentials entered in the Windows proxy settings, e.g. see this StackOverflow thread. One solution is to add to the application config:

<system .net="">
<defaultproxy usedefaultcredentials="true" />
</system>

But I preffer the solution in the code (at least for the desktop apps):
try
{
System.Net.IWebProxy proxy = System.Net.WebRequest.DefaultWebProxy;
PropertyInfo propInfo = proxy.GetType().GetProperty("WebProxy", BindingFlags.NonPublic | BindingFlags.Instance);
((System.Net.WebProxy)propInfo.GetValue(proxy)).UseDefaultCredentials = true;
}
catch (Exception ex)
{
// log the exception
}



### More proxies

The automatic proxy script for the WinINet may contain more proxy servers. The WinINet chooses next cycle the list until it finds the first proxy working. While the .NET (WinHTTP) use the first proxy from the list always, event when it does not work. So the .NET app may be disconnected, while the Internet Explorer is working. There is not known remedy for that. Fortunately, such situations are very rare.

### NTLM proxy

.NET (WinHTTP) cannot automatically detect NTLM proxy and use Window credentials for it like the WinINet. There is not known remedy for that. NTLM proxies are sometimes used in the enterpise environments.

### Summary

.NET app cannot be 100% compatible with all the Windows proxy settings. A possible solution for that is to have own proxy settings in the app. But the app may be used by people who cannot (security or have no knowledge) to set the proxy settings in the .NET app. So they may be situations, when .NET stays disconnected.

## čtvrtek 19. května 2016

### Atlassian Bamboo and xUnit testing

I needed to run xUnit test on the Atlassian Bamboo Cloud (OnDemand) build server. It has no runner for xUnit, but can be run from the command line by xunit.runner.console.

On the build server, just NuGet the runner:
nuget.exe xunit.runner.console
The Bamboo cannot parse xUnit output. It can handle the nUnit output nd the xUnit has an option to print results in the nUnit format. So, create a simple xunit.cmd script:
@echo off
@rem xunit runner for Bamboo

if "%2"=="" (
echo Usage: test.dll report.xml
exit /b 1
)

if not exist %~dp2 mkdir %~dp2

"c:\path\to\xunit.runner.console.2.1.0\tools\xunit.console.exe" %1 -nunit %2


### Configure Bamboo

 Capability type Executable Executable label xUnit Path c:\path\to\xunit.cmd

To add the xUnit to you plan's job, just add the Command task after the project build (e.g. MSBuild, or NAnt). I expect you have a module MyProjectTests in your solution. Then configure the xUnit task:
 Executable xUnit Argument bin\Release\MyProjectTests.dll test-reports\MyProjectTests.xml Working sub directory MyProjectTests

The final trick is to add the NUnit Parser task, just take care to put is as the final task:
 NUnit Test Results File/Directory MyProjectTests/test-reports/*.xml

The bamboo logic is, that:
1. Any task fails, and no test result is found, it assumes the compilation error has occurred.
2. Any task fails, and a test result is found, it assumes a test has failed.
3. All tasks pass, the build is OK. If the test results are found, they are picked up.

## pátek 18. března 2016

### C# Caliburn.Micro Check Unmatched Elements

Caliburn.Micro is a great C# MVVM framework. It saves the developer's fingers with the binding by the x:Name convention:
<textbox x:name="Username" />
However, when one mistypes the x:Name or rename the property in the ViewModel then the Caliburn silently does not apply the binding. Such mistakes are hard to track. Fortunately Caliburn comes with the help of ViewModelBinder.HandleUnmatchedElements. We have a simple rule in the project: if the x:Name starts with the capital letter, then it has to be binded by the Caliburn. Then I have been able to plug in a simple method to check for unmathched elements starting with the capital:
ViewModelBinder.HandleUnmatchedElements = (elems, type) =>
{
if (!elems.Any())
return;

// elems with Name with the first letter upper case
elems = elems.Where(e => !string.IsNullOrEmpty(e.Name) && e.Name.StartsWith(e.Name.Substring(0, 1).ToUpperInvariant()));
if (!elems.Any())
return;

throw new InvalidOperationException(type + " contains Caliburn unmatched elements " + string.Join(",", elems.Select(e => e.Name)));
};


## pondělí 8. června 2015

### C# Safe Event Pattern

C# language has a very good support for event programming. However, is does not address a two common issues with event handlers:
1. An event handler is registered more times, but we want to call it just once.
2. An event handler is registered from longer living object then the event source. Then the event handler must be unregistered. Otherwise it may cause memory leaks.
First issue is usually simple to solve. The memory leaks are best avoided when using weak references. There are several solutions to .NET weak event references. e.g. see The .NET weak event pattern in C#. I have decided to go with .NET 4.5 WeakEventManager. The following pattern makes it easy for MyEvent consumer to write the code without worrying about event handler unregistering.
private event MyEventArgs _myEvent;

public event EventHandler<MyEventArgs> MyEvent
{
{
// first unregister if registered
MyEvent-= value;
// register
}
remove
{
WeakEventManager<ThisType, MyEventArgs>.RemoveHandler(_myEvent, "MyEvent", value);
}
}


## úterý 19. května 2015

### Log4net Configuration for Desktop Application

I have configured log4net for out current project, a plain Windows Desktop application. I wanted log to rolling file into the AppData\Local folder. Not the Roaming folder, since log are specific to the machine and it is waste of resources to let them roam around. Also I wanted to see logs in console, but in DEBUG mode only, not in production. First problem to find the AppData\Local\MyAppName has been solved by log4net.Util.PatternString class. It parses a special %envFolderPath and %appdomain patterns. The second problem, to configure ConsoleAppender just in DEBUG mode has several solutions. It is possible to load different configs, or to configure ConsoleAppender programatically. I have decided to create own DebugFilter, which denies all log in production mode. This way I have just one log4net config file. The cons is that it is very slightly less efficient to have configured an Appender which denies all log, but it's OK for most of applications.
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="%envFolderPath{LocalApplicationData}\%appdomain\log.txt" />
<appendToFile value="true" />
<maxSizeRollBackups value="2" />
<maximumFileSize value="10MB" />
<rollingStyle value="Size" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
<filter type="cvtBackend.Logging.DebugFilter" />
</appender>
<!-- Setup the root category, add the appenders and set the default level -->
<root>
<level value="INFO" />
<appender-ref ref="RollingLogFileAppender" />
<appender-ref ref="ConsoleAppender" />
</root>
</log4net>

And the DebugFilter:
    ///
/// log4net filter which allows logging in DEBUG mode only.
///
public class DebugFilter : FilterSkeleton
{
public override FilterDecision Decide(LoggingEvent loggingEvent)
{
#if DEBUG
return FilterDecision.Neutral;
#else
return FilterDecision.Deny;
#endif
}
}


## pátek 13. února 2015

### Java: Fast Date Formatting in Web Containers

Java SimpleDateFormat is not thread safe. When it is used in multithreaded applications, like Java web containers, it's forbidden use it as a static constant
public static final DateFormat DATE_FORMAT = new SimpleDateFormat('YYYY.MM.dd'); // DON'T!

Most developers properly constructs new SimpleDateFormat everytime they need
DateFormat dateFormat = new SimpleDateFormat('YYYY.MM.dd');
String str = dateFormat.format(date);

However, constructing new SimpleDateFormat is not so cheap operation. So, how to safe CPU and memory like in static final pattern in a multithreaded environment?

### Solution 1: clone

Fortunatelly, SimpleDateFormat implements clone() method, which is fasters than constructing a new one form a String:
private static final DateFormat DATE_FORMAT_TEMPLATE = new SimpleDateFormat('YYYY.MM.dd'); // Do not use directly

/**
* @return every time a new SimpleDateFormat.
*/
public static DateFormat getDateFormat() {
return DATE_FORMAT_TEMPLATE.clone();
}


A general solution for sharing non-thread safe objects is to have one copy for each thread. Java has a very nice ThreadLocal. Together with lazy initialization we got the proper thread safe and fast solution:
private static final ThreadLocal DATE_FORMAT_TL = new ThreadLocal() {
protected DateFormat initialValue() {
return new SimpleDateFormat('YYYY.MM.dd');
};
};

/**
* @return SimpleDateFormat, new one for every thread.
*/
public static DateFormat getDateFormat() {
return DATE_FORMAT_TL .get();
}

/**
* Simple, optimized Date formatting.
*/
public static String format(Date d) {
return format == null ? null : getDateFormat().format(d);
}

This solution has advantage over clone() method, that calling getDateFormat() multiple times in one thread (e.g. inside a loop) does not create a new object. I like to add format() to simplify usage and handle null values. Note: ThreadLocal may cause redeploy memory leaks when it's value from a WAR class. E.g. see Java Web Container: Hunting Redeploy Memory Leaks

## pátek 12. prosince 2014

### Git error: Short SHA1 is Ambiguous

Git allows using shortened SHA1 hashes. Default is to use 7 characters (see core.abbrev config option). But sooner or later, you may hit problem, that short hashes are ambiguous. E.g.
$git log 0ed98e5 ... error: short SHA1 0ed98e5 is ambiguous  To find, what Git objects are referenced by the same short has, use $git rev-parse --disambiguate=0ed98e | git cat-file --batch-check
0ed98e56dd43b172d438dba0aa6ea9ebed0554c7 commit 307
0ed98e50771521f9ec27314d49286fd54e989c87 blob 1478
0ed98e50771521f9ec27314d49286fd54e989c87 blob 1478


In this case, only the first hash (0ed98e56) refers to a commit. The second hash (0ed98e50) refers to a blob - file. So, Git does check SHA1 for all it's objects, not only for commits, although the git log command uses just commits SHA1 for it's arguments.

How to fix the error? Use longer prefix of the SHA1 hash. The bulletproof solution is to use all 40 characters. But if you still like abbreviates, then you can find the safe minimum length of SHA1 prefix for your project by Josh Stone's solution:
\$git rev-list --all --abbrev=0 --abbrev-commit | wc -L