Thursday, December 18, 2014

Visual Studio 2012 debugger does not break after attaching to C#/.NET process

I had from time to time issue debug C#/.NET applications in Visual Studio 2012 after attaching Visual Studio 2012 debugger to a process.

Symptoms were that the debugger attached to the process but neither ‘Break All’ worked. The same applied for any preset breakpoint.

For some time I thought that Visual Studio installation for somehow corrupted on my system but since I was always able to workaround it via Debug.Assert() or Debugger.Break() calls put directly into code I had never motivation to really look for a solution nor reinstall the Visual Studio.

Today I really wanted to attach to a process to see what is going on inside and the issue happened again.

After a bit of playing I realized that in the case that debugger works after attaching correctly the ‘Attach to Process’ Visual Studio dialog looks like this (see ‘Attach to’ field):
visual_studio_debugger_does_recognize_process_type.png

For my process it didn’t work this time and ‘Attach to Process’ dialog looked like this (again see ‘Attach to’ field):
visual_studio_debugger_does_not_recognize_process_type.png

Apparently Visual Studio in some cases does not properly detect the type of the process and does not use correct debugger settings.

In order to solve my issue I finally found the ‘Select…’ button following ‘Attach to’ field where you can disable automatic detection of the process type and manually select a different one.

Zmrzka na hrázi

After selecting ‘Manager (v4.5, 4.0)’ and attaching debugger to process again everything worked well.

Wednesday, December 10, 2014

DBKeeperNet - DBKeeperNet - Automated database schema maintenance in .NET/C#

An article describing a simple .NET library which simply keeps your database schema up-to-date.

Introduction

Each project using database access solves how to distribute database schema and how to keep it up-to-date after upgrades. I was solving this problem multiple times, so I decided to write a common, easy to use, and freely available library. The result of this is the DbKeeperNet library which is pure ADO.NET framework (no dependency on Entity Framework).

This article will briefly show how to use DbKeeperNet library to fulfill this task. The library is designed as extensible and with planned support to any database engine.

Supported Features

  • Very simple usage.
  • Database commands are kept in a simple, structured XML file.
  • Each upgrade step is executed in a separate transaction (if supported by the database service). In the case of failure, all further steps are prohibited.
  • Rich set of built-in preconditions used for evaluation whether update should or shouldn’t be executed.
  • Support for unlimited and customizable list of database engines.
  • In single update, a script may be an alternative to SQL commands, for all database engine types if needed.
  • Support for custom preconditions.
  • Support for custom in-code upgrade steps (allows complex data transformations to be done in code instead of SQL).
  • DbKeeperNet provides deep logging of what is currently happening. Diagnostic output may be redirected through the standard .NET System.Diagnostics.Trace class or the System.Diagnostics.TraceSource class, or to a custom plug-in, allowing integration to an already existing application diagnostics framework.
  • XML update script structure is strictly defined by the XSD schema which can be used in any XML editor with auto-completion (intellisense).
  • Support for the Log4Net logging framework.
  • Support for MySQL Connect .NET.
  • Support for PostrgreSQL.
  • Support for SQLite.
  • Support for Oracle XE.
  • Support for Firebird.
  • Localizable log messages.
  • Support for customizable script sources (built-in are a disk file, embedded assembly).

Background

There are two basic principles on how to get your application’s database schema up-to-date:

  • Before each change, check directly in the database whether a change was already made or not (such as ask the database whether a table already exists or not).
  • Have a kind of database schema versioning table and record the current schema version.

DbKeeperNet supports both these principles; however, I suggest to use the second one.

DbKeeperNet’s design for this second principle is in a unique identifier for each update step. The database service implementation simply keeps track of these already executed steps (concrete implementation is strongly dependent on the used database service). This allows you to very simply search the database and check which steps were already executed.

Using DbKeeperNet

The code snippets below are taken from the DbKeeperNet.SimpleDemo project which is part of the source control. If you want to directly execute the demo project, you need the SQL Server 2005 Express Edition installed, or you must change the connection string in App.Config.

For more complex scenarios, you can check the DbKeeperNet.ComplexDemo project (there is an example of a custom step implementation, split XML scripts, etc.).

My favorite way to implement an upgrade script is by using an XML file stored as an embedded resource in an assembly. So, let’s prepare a simple upgrade script with an alternative statement for two different database engines (you can find it in the DbKeeperNet.Demo project as the file DatabaseSetup.xml):

<?xml version="1.0" encoding="utf-8" ?>
<upd:Updates xmlns:upd="http://code.google.com/p/dbkeepernet/Updates-1.0.xsd"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation=
        "http://code.google.com/p/dbkeepernet/Updates-1.0.xsd Updates-1.0.xsd"
                AssemblyName="DbKeeperNet.SimpleDemo">
  <!-- Default way how to check whether to execute update step or not -->
  <DefaultPreconditions>
    <!-- We will use step information saving strategy -->
    <Precondition FriendlyName="Update step executed" 
                Precondition="StepNotExecuted"/>
  </DefaultPreconditions>

  <Update Version="1.00">
    <UpdateStep xsi:type="upd:UpdateDbStepType" 
    FriendlyName="Create table DbKeeperNet_SimpleDemo" Id="1">
      <!-- DbType attribute may be omitted - it will result in default value all
           which means all database types -->
      <AlternativeStatement DbType="MsSql">
        <![CDATA[
          CREATE TABLE DbKeeperNet_SimpleDemo
          (
          id int identity(1, 1) not null,
          name nvarchar(32),
          constraint PK_DbKeeperNet_SimpleDemo primary key clustered (id)
          )
        ]]>
      </AlternativeStatement>
    </UpdateStep>
    <UpdateStep xsi:type="upd:UpdateDbStepType" 
    FriendlyName="Fill table DbKeeperNet_SimpleDemo" Id="2">
      <AlternativeStatement DbType="MsSql">
        <![CDATA[
          insert into DbKeeperNet_SimpleDemo(name) values('First value');
          insert into DbKeeperNet_SimpleDemo(name) values('Second value');
        ]]>
      </AlternativeStatement>
    </UpdateStep>
  </Update>
</upd:Updates>

Now, we will implement the necessary steps for the code execution:

// Perform all configured database updates
using (UpdateContext context = new UpdateContext())
{
    context.LoadExtensions();
    context.InitializeDatabaseService("default");

    Updater updater = new Updater(context);
    updater.ExecuteXmlFromConfig();
}
// the above line is last required line for installation
// And now just print all inserted rows on console
// (just for demonstration purpose)
ConnectionStringSettings connectString = 
    ConfigurationManager.ConnectionStrings["default"];

using (SqlConnection connection = new SqlConnection(connectString.ConnectionString))
{
    connection.Open();

    SqlCommand cmd = connection.CreateCommand();
    cmd.CommandText = "select * from DbKeeperNet_SimpleDemo";
    SqlDataReader reader = cmd.ExecuteReader();
    while (reader.Read())
        Console.WriteLine("{0}: {1}", reader[0], reader[1]);
}

And finally, the setup configuration in the App.config or Web.Config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="dbkeeper.net" 
    type="DbKeeperNet.Engine.DbKeeperNetConfigurationSection,DbKeeperNet.Engine"/>
  </configSections>
  <dbkeeper.net loggingService="fx">
    <updateScripts>
      <add provider="asm" location="DbKeeperNet.SimpleDemo.DatabaseSetup.xml,DbKeeperNet.SimpleDemo" />
      <add provider="disk" location="c:\diskpath\DatabaseSetup.xml" />
    </updateScripts>
    <databaseServiceMappings>
      <add connectString="default" databaseService="MsSql" />
    </databaseServiceMappings>
  </dbkeeper.net>
  <connectionStrings>
    <add name="default" 
            connectionString="Data Source=.\SQLEXPRESS;
        AttachDbFilename='|DataDirectory|\DbKeeperNetSimpleDemo.mdf';
        Integrated Security=True;Connect Timeout=30;User Instance=True" 
            providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <system.diagnostics>
    <!-- uncomment this for TraceSource class logger (fxts)-->
    <!--
    <sources>
      <source name="DbKeeperNet" switchName="DbKeeperNet">
        <listeners>
          <add name="file" />
        </listeners>
      </source>
    </sources>
    <switches>
      <add name="DbKeeperNet" value="Verbose"/>
    </switches>
    <sharedListeners>
      <add name="file" initializeData="dbkeepernetts.log" 
        type="System.Diagnostics.TextWriterTraceListener" />
    </sharedListeners>
    -->
    <trace autoflush="true">
      <!-- uncomment this for .NET Trace class logging (fx logger)-->
      <listeners>
        <add name="file" initializeData="dbkeepernet.log" 
        type="System.Diagnostics.TextWriterTraceListener" />
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>

And that is all - all database changes are executed automatically, only in the case that they were not already executed.

Writing Database Update Scripts

  • If you are using the App.Config for the specification of executed XML scripts, all configured scripts are executed in the same order as they were defined in the configuration file. Also, the content of the XML file is processed exactly in the same order as it is written.
  • The Assembly attribute of the Updates element is in fact a namespace in which each Version and Step must be unique. If you would logically divide a single script into multiple files, you can use the same value in all the scripts.
  • The Version attribute of the Update element is intended to be used as a marker of database schema version. I suggest using a unique value for each distributed build changing the database schema (this value can be the same as the assembly version).
  • The Step attribute of the UpdateStep element should be unique inside each update version.
  • Never change the AssemblyName, Version, and Step steps after you deploy the application, unless you are absolutely sure what you are doing. 

Project location

If you have any questions, support requests, patches, your own extensions, you are looking for a binary package, documentation or if you are looking for the latest source files, the project is hosted at http://github.com/DbKeeperNet/DbKeeperNet.

Alternatively you can reference DbKeeperNet as Nuget packages.

Conclusion

This article shows only the basics from a set of supported functions. More information and examples of upgrade scripts can be find in the DbKeeperNet source files or in the unit tests.

History

  • 26th August, 2014: Update GitHub project reference
  • 17th July, 2014: Project moved to GitHub
  • 23rd September, 2012: Feature List updated, fixed App.Config example, update source package 
  • 4 June 2010: Feature list updated, new source package, updated examples according to new version.
  • 15 November, 2009: Feature list updated, new source package.
  • 4 September, 2009: Original article submitted.

Thursday, December 4, 2014

How to post markdown article on blogspot/blogger with enabled code syntax highlighting

How-to

  • Open StackEdit
  • In blogger create a new post and get postId from the URL
  • Setup post permalink to match the title
  • Using # synchronize the document with google drive
  • Using # publish the article to blogspot
  • As you keep editing simply synchronize/re-publish the article
  • In order to enable syntax highlighting for the C#/XML or any other code edit the blogspot template and insert the following script reference between <head></head> tags:
    <script src='https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js'/>
  • Use following at the top of markdown post to define whether the article is published, title and tags:
---
title: My article title
tags: tag1,tag2
published: true
---

References

Tuesday, December 2, 2014

Unity Registration Validator

Microsoft Unity Extension which verifies registrations between parent and child containers. This is mainly issue when you
accidently inject a dependency from a child container to the parent container while using ContainerControlledLifetimeManager (singleton).

Introduction

When using Microsoft Unity IoC container you may face some weird issues when dealing with ‘singletons’ (ContainerControlledLifetimeManager) and child containers. It may or may not be what you expected.
Let’s consider following classes:
public interface IServiceDependency
{
}

public interface IService
{
}

public class ServiceDependency : IServiceDependency
{
    private readonly string _dep1;

    public ServiceDependency(string dep1)
    {
        _dep1 = dep1;
    }
}

public class Service : IService
{
    private readonly IServiceDependency _dependency;

    public Service(IServiceDependency dependency)
    {
        _dependency = dependency;
    }
}
Now let’s setup some test case:
[Test]
public void ServiceResolutionViaTwoDifferentChildContainersShouldFail()
{
    var rootContainer = new UnityContainer();

    rootContainer.RegisterType<IService, Service>(new ContainerControlledLifetimeManager());
    var childContainer = rootContainer.CreateChildContainer();
    var childContainer2 = rootContainer.CreateChildContainer();

    childContainer.RegisterInstance<IServiceDependency>(new ServiceDependency("Dep1"));
    childContainer2.RegisterInstance<IServiceDependency>(new ServiceDependency("Dep2"));

    var childContainerResult1 = childContainer.Resolve<IService>();
    var childContainerResult2 = childContainer.Resolve<IService>();

    var childContainer2Result1 = childContainer.Resolve<IService>();
    var childContainer2Result2 = childContainer.Resolve<IService>();

    Assert.AreEqual(childContainerResult1, childContainerResult2);
    Assert.AreEqual(childContainer2Result1, childContainer2Result2);

    Assert.AreEqual(childContainer2Result1, childContainerResult1);
}
This actually will pass all the assertions.

Let’s analyze it a bit:

  • Let’s step thru the test case in debugger.
  • Setup some watches:
    • ((ServiceDependency)((Service)childContainerResult1)._dependency)._dep1
    • ((ServiceDependency)((Service)childContainer2Result1)._dependency)._dep1
  • You can see that both of them point to Dep1.
    • Is that what you really wanted?
    • Consider the following case:
    • You disposed childContainer and your ServiceDependency is disposable registered as ContainerControlledLifetimeManager.
    • At this point you have invalid instance of IService (it has injected disposed ServiceDependency).
    • This is most likely a side effect of unwanted changes and you want to avoid it.
    • And this is exactly what is this extension trying to solve.
    • By enabling this extension the build operation will fail.

How to enable extension

  • Reference the UnityRegistrationValidator.dll in your project.
  • Call the registration below.
var rootContainer = new UnityContainer();
rootContainer.AddNewExtension<EnsureRegistrationDepthOrderExtension>();

Following rules are enforced after registering extension

  • For each registration is tracked depth in containers (starting the container in which resolve starts).
  • If you register an object which
    • has dependency resolvable only inside the child container
    • and has ContainerControlledLifetimeManager()
  • the resolve will fail.
  • If you do this without the extension the resolve will succeed but the dependencies were most likely resolved in unexpected way (unless you really know what are you doing).

Conclusion

  • This extension allows you to validate the expected behavior.
  • Since it may have performance impact (it needs to track all the registrations as well as build operations) it may have negative performance impact.
  • This extension is intended to help you ensure expected behavior - but you have to always consider your circumstanes.
  • You are using this extension on your own risk :-).

References

Letní dovolená Vranovská přehrada 2014

Letní dovolenou 2014 jsme strávili na Jižní Moravě na Vranovské přehradě v Penzionu M. Recenzetka recenze mi nařídila napsat, že to bylo hezký a že jsem zbytečný rejpal :-).

Pravda - celkově to bylo moc prima, ubytování nepočítám.

Ubytování

  • Ubytování bylo celkem prima.
  • Kupodivu s ohledem na blízkost přehrady ani příliš neobtěžoval hmyz.
  • Velice se osvědčil výběh pro divou zvěř přímo na předzahrádku.
  • Okna orientovaná na sever zajistila, že jsme se nepekli, drobnou nevýhodou bylo, že se v dobách kdy nebylo úplně slunečno těžko sušilo oblečení.
  • Celkové vybavení penzionu ušlo (hmmm, zažil už někdo, aby deklarovaná televize skutečně fungovala?)
  • Nejlepší byl asi bazén, kde se naše káčata koupala bez ohledu na počasí. Trochu komplikace se vyskytly s doplňkovou službou
  • Celkový dojem zkazila nepříliš dobře komunikativní paní majitelka, která se nás po týdnu snažila přestěhovat do lepšího pokoje kde ale bohužel chyběla jedna postel (prostě výhodná nabídka nebyla až tak výhodná).
  • Bohužel posledních několik dní vzduchotechnikou pronikal po ránu cigaretový kouř s čímž paní recepční nedokázala nic udělat.
  • Macíkovi nakonec nebylo moc dobře a tak jsme odjížděli o několik dnů dřív.
  • Znovu tam asi jet nechci…

Stravování

Přímo v penzionu není restaurace. Snídaně se podávají v přiléhající restauraci skleník - hotelová klasika typu vejce, párek, ovoce, zelenina, kakao, kafe, pečivo atd. Celkově celkem OK. Pozitivem byla cena - Macík (necelé tři) a Kryšťa jeli na jednu platbu.

Bohužel obědy a večeře byly hospodská klasika v provedení čtvrté cenové před deseti lety - podle mě jenom pro fanoušky stylu knedlo-vepřo-zelo 2x denně. Všechno zdobila podivuhodná syntetická ‘vídeňská’ cibulka. Ale aspoň, že nebyl problém si odnést pivo/kafe do penzionu.

Západ slunce nad Vranovskou přehradou

Obědy jsme typicky řešili během výletů po okolí a většinu večeří jsme proto strávili v pizzerii kousek od hráze což jsme obvykle spojili s příjemnou procházkou přes most (až na jeden exces s připálenou pizzou to tam bylo moc primo a to jak co se týče obsluhy tak i kvality jídla).

Zmrzka na hráziV okolí přehrady taky byla spousta cukráren s výbornou zmrzkou.

Okolí penzionu

Celkově jsme si hodně vystačili s blízkým okolím penzionu a tak jsme ani moc nejezdili autem.

Atrakce v kempu

Bagr v kempuV kempu na břehu přehrady je k dispozici celá řada atrakcí včetně diskotéky. Bagr vypadá celkem efektně :-).

Výlet lodí

Výlet lodíKolmo jsme se vydali na druhý konec přehrady, kde jsme se kompletně nalodili a vyrazili zpátky. Překvapivě cesta lodí se ukázala jako hoooodně dlouhá (dojížděli jsme až do nejzažšího konce a pak celou cestu zpátky) a krapet nudná. Nicméně jsme dojeli v pohodě a bez problémů jsme se vylodili hned u naší oblíbené pizzerie.

Zajímavostí výletu byla hospoda v Lančově s docela prima obědem a máčenkama :-).

Geocaching

V okolí se nám povedlo odlovit kešky a to včetně několika v dochozí vzdálenosti od penzionu. Zbývající byly zejména v okolí Vranova nad Dyjí - většinou v dojezdové vzdálenosti pro kolo :-).

Prohlídka vodní elektrárny

V rámci PR energentika nabízí prohlídku elektrárny umístěné v hrázi přehrady. Prohlídka byla zdarma a jenom škoda, že součástí nebyla také prohlídka hráze.

Vláček

Svezli jsme se také místním vláčkem, jenom škoda, že zastávky neměly jméno a tak bylo trochu těžké se orientovat v jízdních řádech (zajímavé bylo, že paní ve Vranově na informacích mi oznámila, že říkala to samé už před rokem).

Prohlídka opevnění

Opevnění Vranov nad DyjíTohle bylo moc prima. Opevnění se nachází kousek pěšky nad zámkem - součástí prohlídky jsou dva menší bunkry vybavené zbraněmi. Cestou zpátky jsme si odlovili jednu prima kešku v lese.

Restaurace a penzion Rumburak

Rumburak havranCelkem zajímavá dominanta kraje u Bítova. Součástí je pěkně přístupná vyhlídková věž a poblíž jsme si odlovili jednu kešku.

Cyklistika

  • Přehrada je v údolí, takže na kole je potřeba viceméně vždy potřeba vystoupat kopec..
  • Pro dětskou cyklistiku trochu náročnější, ale s Kryštofem na tyči jsme vše vyjeli na 42/27 :-).
  • Terka s Macíkem na sedačce nakonec pár kousků tlačila, ale celkově OK.
  • Výlety na kole jsme většinou spojili s konzumací výborné zmrzky, lovem kešek a obídkem.
    • Jednou jsme si prima pokecali s cyklozájezdem staroušků z Kanady, kteří tu byli na dovolené po Iron manovi v Německu.
  • Za mě osobně super kopce - většinou jsem si jeden nebo dva vybral a hodinu a půl jezdil nahoru a dolů
    • Až mi z toho koncem dovolené prasknul drát v zadním kole Fulcrum 5 :-(.

Odkazy