<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>tpodolak.com</title><description>No description</description><link>https://tpodolak.com/</link><language>en</language><item><title>ASP.NET Core - adding controllers directly from integration tests</title><link>https://tpodolak.com/blog/asp-net-core-adding-controllers-directly-integration-tests/</link><guid isPermaLink="true">https://tpodolak.com/blog/asp-net-core-adding-controllers-directly-integration-tests/</guid><pubDate>Mon, 22 Jun 2020 08:00:12 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;From time to time it might happen, that you need to test certain parts of your &lt;code&gt;ASP.NET Core&lt;/code&gt; configuration without hitting publicly visible business-related controllers. For instance, in my case, I wanted to make sure that my &lt;code&gt;ASP.NET Core API&lt;/code&gt; behavior is consistent with the original &lt;code&gt;API&lt;/code&gt; written in &lt;code&gt;Nancy&lt;/code&gt;. As you might expect there are quite a lot of differences between both of the frameworks, so let&apos;s focus on testing one thing, namely non-nullable reference type handling. Long story short, in order to have the same behavior in &lt;code&gt;ASP.NET Core&lt;/code&gt; as in &lt;code&gt;Nancy&lt;/code&gt; I had to add the following line of configuration&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers(opts =&amp;gt; opts.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true)
        .AddNewtonsoftJson();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This one prevents &lt;code&gt;ASP.NET Core&lt;/code&gt; from marking non-nullable reference type properties in request as required.
Having that configuration ready, I wanted to test it with an end to end test.
Because there was no business-related logic yet, I needed to figure out the way of adding &lt;code&gt;API&lt;/code&gt; controllers to my application directly from the integration tests.
Here is how you can achieve that.&lt;/p&gt;
&lt;h3&gt;2. Accessing ApplicationPartManager from integration tests&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;ASP.NET Core&lt;/code&gt; is able to compose your &lt;code&gt;API&lt;/code&gt; from different parts thanks to &lt;code&gt;ApplicationPartManager&lt;/code&gt;.
By default, you don&apos;t use it directly but rather with &lt;code&gt;IMvcBuilder AddApplicationPart&lt;/code&gt; extension method while setting up your application&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers()
        .AddApplicationPart(typeof(SomeClass).Assembly)
        .AddNewtonsoftJson();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;However, there is no easy way of getting &lt;code&gt;IMvcBuidler&lt;/code&gt; from the integration tests(at least I didn&apos;t find a proper way of doing that without tampering too much with the original application pipeline) so we need to access &lt;code&gt;ApplicationPartManager&lt;/code&gt; directly.
Inspecting the source code of the framework you will find that &lt;code&gt;ApplicationPartManager&lt;/code&gt; can be retrieved directly from &lt;code&gt;IServiceCollection&lt;/code&gt; with following &lt;a href=&quot;https://github.com/dotnet/aspnetcore/blob/3.0/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreServiceCollectionExtensions.cs#L74&quot;&gt;code&lt;/a&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;private static ApplicationPartManager GetApplicationPartManager(IServiceCollection services)
{
    var manager = GetServiceFromCollection&amp;lt;ApplicationPartManager&amp;gt;(services);
    if (manager == null)
    {
        manager = new ApplicationPartManager();

        var environment = GetServiceFromCollection&amp;lt;IWebHostEnvironment&amp;gt;(services);
        var entryAssemblyName = environment?.ApplicationName;
        if (string.IsNullOrEmpty(entryAssemblyName))
        {
            return manager;
        }

        manager.PopulateDefaultParts(entryAssemblyName);
    }

    return manager;
}

private static T GetServiceFromCollection&amp;lt;T&amp;gt;(IServiceCollection services)
{
    return (T)services
        .LastOrDefault(d =&amp;gt; d.ServiceType == typeof(T))
        ?.ImplementationInstance;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Applying similar code to the &lt;code&gt;WebApplicationFactory&lt;/code&gt; will allow us to add controllers directly from tests&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Fact]
public async Task DoesNotReturnBadRequest_WhenNonNullableTypeHasNoValue_FirstAttempt()
{
    var webApplicationFactory = new WebApplicationFactory&amp;lt;Startup&amp;gt;()
        .WithWebHostBuilder(
            builder =&amp;gt; builder.ConfigureServices(services =&amp;gt;
            {
                var partManager = (ApplicationPartManager) services
                    .Last(descriptor =&amp;gt; descriptor.ServiceType == typeof(ApplicationPartManager))
                    .ImplementationInstance;

                partManager.ApplicationParts.Add(new AssemblyPart(GetType().Assembly));
            }));

    var expectedResponse = new Request
    {
        Id = &quot;1&quot;
    };

    var httpClient = webApplicationFactory.CreateClient();
    var httpResponseMessage = await httpClient.GetAsync(&quot;test?id=1&quot;);

    httpResponseMessage.IsSuccessStatusCode.Should().BeTrue();
    var rawContent = await httpResponseMessage.Content.ReadAsStringAsync();
    var result = JsonConvert.DeserializeObject&amp;lt;Request&amp;gt;(rawContent);

    result.Should().BeEquivalentTo(expectedResponse);
}

[ApiController]
public class MvcOptionsTestController : ControllerBase
{
    [HttpGet(&quot;test&quot;)]
    public object Get([FromQuery] Request request)
    {
        return request;
    }
}

public class Request
{
    public string Id { get; set; }

    public string OtherId { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;3. Handling private controllers&lt;/h3&gt;
&lt;p&gt;The solution presented below works nice, however it has couple of drawbacks.
First of all, it only discovers public non-nested controllers.
Second of all, it will always add all controllers from given assembly - which potentially might affect other integration tests.
In order to get rid of these drawbacks, we need to tell &lt;code&gt;ApplicationPartManager&lt;/code&gt; to include only selected controllers.
We can achieve that by adding additional &lt;code&gt;IApplicationFeatureProvider&amp;lt;ControllerFeature&amp;gt;&lt;/code&gt; to the list of &lt;code&gt;FeatureProviders&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class ExternalControllersFeatureProvider : IApplicationFeatureProvider&amp;lt;ControllerFeature&amp;gt;
{
    private readonly Type[] _controllers;

    public ExternalControllersFeatureProvider(params Type[] controllers)
    {
        _controllers = controllers ?? Array.Empty&amp;lt;Type&amp;gt;();
    }

    public void PopulateFeature(IEnumerable&amp;lt;ApplicationPart&amp;gt; parts, ControllerFeature feature)
    {
        foreach (var controller in _controllers)
        {
            feature.Controllers.Add(controller.GetTypeInfo());
        }
    }
}

[Fact]
public async Task DoesNotReturnBadRequest_WhenNonNullableTypeHasNoValue()
{
    var webApplicationFactory = new WebApplicationFactory&amp;lt;Startup&amp;gt;()
        .WithWebHostBuilder(
            builder =&amp;gt; builder.ConfigureServices(services =&amp;gt;
            {
                var partManager = (ApplicationPartManager) services
                    .Last(descriptor =&amp;gt; descriptor.ServiceType == typeof(ApplicationPartManager))
                    .ImplementationInstance;

                partManager.FeatureProviders.Add(new ExternalControllersFeatureProvider(typeof(MvcOptionsTestController)));
            }));
// rest of the code omitted for brevity
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Putting it all together and applying some refactoring we will end up with following code&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;internal static class WebHostBuilderExtensions
{
    public static IWebHostBuilder WithAdditionalControllers(this IWebHostBuilder builder, params Type[] controllers)
    {
        return builder.ConfigureTestServices(
            services =&amp;gt;
            {
                var partManager = GetApplicationPartManager(services);

                partManager.FeatureProviders.Add(new ExternalControllersFeatureProvider(controllers));
            });
    }

    private static ApplicationPartManager GetApplicationPartManager(IServiceCollection services)
    {
        var partManager = (ApplicationPartManager)services
            .Last(descriptor =&amp;gt; descriptor.ServiceType == typeof(ApplicationPartManager))
            .ImplementationInstance;
        return partManager;
    }

    private class ExternalControllersFeatureProvider : IApplicationFeatureProvider&amp;lt;ControllerFeature&amp;gt;
    {
        private readonly Type[] _controllers;

        public ExternalControllersFeatureProvider(params Type[] controllers)
        {
            _controllers = controllers ?? Array.Empty&amp;lt;Type&amp;gt;();
        }

        public void PopulateFeature(IEnumerable&amp;lt;ApplicationPart&amp;gt; parts, ControllerFeature feature)
        {
            foreach (var controller in _controllers)
            {
                feature.Controllers.Add(controller.GetTypeInfo());
            }
        }
    }
}

public class MvcOptionsConfigurationTests
{
    [Fact]
    public async Task DoesNotReturnBadRequest_WhenNonNullableTypeHasNoValue()
    {
        var webApplicationFactory = new WebApplicationFactory&amp;lt;Startup&amp;gt;()
            .WithWebHostBuilder(
                builder =&amp;gt; builder.WithAdditionalControllers(typeof(MvcOptionsTestController)));

        var httpClient = webApplicationFactory.CreateClient();
        var expectedResponse = new Request
        {
            Id = &quot;1&quot;
        };

        var httpResponseMessage = await httpClient.GetAsync(&quot;test?id=1&quot;);

        httpResponseMessage.IsSuccessStatusCode.Should().BeTrue();
        var rawContent = await httpResponseMessage.Content.ReadAsStringAsync();
        var result = JsonConvert.DeserializeObject&amp;lt;Request&amp;gt;(rawContent);

        result.Should().BeEquivalentTo(expectedResponse);
    }

    [ApiController]
    private class MvcOptionsTestController: ControllerBase
    {
        [HttpGet(&quot;test&quot;)]
        public object Get([FromQuery] Request request)
        {
            return request;
        }
    }

    private class Request
    {
        public string Id { get; set; }

        public string OtherId { get; set; }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/AspNetCoreAddingControllersInIntegrationTests&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Running ASP.NET Core together with Nancy</title><link>https://tpodolak.com/blog/running-asp-net-core-together-nancy/</link><guid isPermaLink="true">https://tpodolak.com/blog/running-asp-net-core-together-nancy/</guid><pubDate>Mon, 20 Apr 2020 08:00:44 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;Our current &lt;code&gt;API&lt;/code&gt; runs on &lt;a href=&quot;https://github.com/NancyFx/Nancy&quot;&gt;Nancy&lt;/a&gt; which in my opinion is past its prime. Recent news from the &lt;a href=&quot;https://github.com/NancyFx/Nancy/issues/3010&quot;&gt;GitHub&lt;/a&gt; issue tracker seems to confirm that thesis, that is why we started looking for a migration path from Nancy based &lt;code&gt;API&lt;/code&gt; to &lt;code&gt;ASP.NET Core&lt;/code&gt;. Because the codebase is quite large we didn&apos;t want to do a &lt;code&gt;Big Bang Rewrite&lt;/code&gt; but instead of that, we wanted to gradually replace old &lt;code&gt;API&lt;/code&gt; with a new one, so both of them can coexist next to each other.&lt;/p&gt;
&lt;h3&gt;2. Legacy API&lt;/h3&gt;
&lt;p&gt;Before I jump into implementation, here is a sample &lt;code&gt;Nancy API&lt;/code&gt; with two endpoints - &lt;code&gt;products&lt;/code&gt; and &lt;code&gt;variants&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // nancy has its own container
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseOwin(owin =&amp;gt; owin.UseNancy());
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;public sealed class ProductsNancyModule : NancyModule
{
    public ProductsNancyModule()
    {
        Get(&quot;products&quot;, args =&amp;gt; Response.AsJson(new List&amp;lt;Product&amp;gt;
        {
            new Product(Guid.NewGuid().ToString(), &quot;First product from nancy&quot;),
            new Product(Guid.NewGuid().ToString(), &quot;Second product from nancy&quot;)
        }));
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;public sealed class VariantsNancyModule : NancyModule
{
    public VariantsNancyModule()
    {
        Get(&quot;variants&quot;, args =&amp;gt; Response.AsJson(new List&amp;lt;Variant&amp;gt;
        {
            new Variant(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), &quot;first variant from nancy&quot;),
            new Variant(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), &quot;second variant from nancy&quot;)
        }));
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The goal is to replace &lt;code&gt;products&lt;/code&gt; endpoint with &lt;code&gt;ASP.NET Core&lt;/code&gt; implementation while &lt;code&gt;variants&lt;/code&gt; endpoint should still be served by &lt;code&gt;Nancy&lt;/code&gt;&lt;/p&gt;
&lt;h3&gt;3. Combining Nancy with &lt;code&gt;ASP.NET Core&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;The solution is based on &lt;a href=&quot;https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1#branch-the-middleware-pipeline&quot;&gt;branching&lt;/a&gt; the pipeline feature which is available starting from &lt;code&gt;ASP.NET Core&lt;/code&gt; 2.1. Long story short - it is possible to configure different pipelines for different route paths thanks to&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static IApplicationBuilder Map(this IApplicationBuilder app, PathString pathMatch, Action&amp;lt;IApplicationBuilder&amp;gt; configuration)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;method. Having that in mind we can `Map` &lt;code&gt;products&lt;/code&gt; path to run through &lt;code&gt;ASP.NET Core&lt;/code&gt; pipeline whereas the rest would go through &lt;code&gt;Nancy&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // register mvc services
    services.AddControllers();
    services.AddMvc(options =&amp;gt; options.EnableEndpointRouting = false);
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // run everything with products prefix through mvc
    app.Map(&quot;/products&quot;, appBuilder =&amp;gt;
    {
        appBuilder.UseMvc();
    });

    // run the rest through Nancy
    app.Map(string.Empty, appBuilder =&amp;gt;
    {
        appBuilder.UseOwin(options =&amp;gt; options.UseNancy());
    });
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;[ApiController]
public class ProductsController : ControllerBase
{
    [HttpGet(&quot;/products&quot;)]
    public List&amp;lt;Product&amp;gt; Get()
    {
        return new List&amp;lt;Product&amp;gt;
        {
            new Product(Guid.NewGuid().ToString(), &quot;First product from asp net core&quot;),
            new Product(Guid.NewGuid().ToString(), &quot;Second product from asp net core&quot;)
        };
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;At this point we are almost there, however running request through &lt;code&gt;Map&lt;/code&gt; pipeline will remove the path prefix, meaning that our controller would be accessible under &lt;code&gt;/&lt;/code&gt; path instead of &lt;code&gt;products&lt;/code&gt;.
In order to bypass this limitation we have to restore original prefix with &lt;code&gt;RewriteMiddleware&lt;/code&gt;.
Once we put it all together, now we are able to replace multiple &lt;code&gt;Nancy&lt;/code&gt; endpoints with &lt;code&gt;ASP.NET Core&lt;/code&gt; ones using following piece of code&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    var aspNetCorePaths = new PathString[] {&quot;/products&quot;};
    foreach (var path in aspNetCorePaths)
    {
        app.Map(path, appBuilder =&amp;gt;
        {
            // we still want to access the resource under old url, so we need to add the branch path back to the route
            var rewriteOptions = new RewriteOptions().AddRewrite(
                &quot;(?&amp;lt;Path&amp;gt;.*)&quot;,
                $&quot;{path}/${{Path}}&quot;,
                skipRemainingRules: true);
            appBuilder.UseRewriter(rewriteOptions);
            appBuilder.UseMvc();
        });
    }

    app.Map(string.Empty, appBuilder =&amp;gt;
    {
        appBuilder.UseOwin(options =&amp;gt; options.UseNancy());
    });
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;images/NancyCore.gif&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/RunningAspNetCoreTogetherWithNancy&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Introduce substitute refactoring comes to NSubstitute.Analyzers</title><link>https://tpodolak.com/blog/introduce-substitute-refactoring-comes-nsubstitute-analyzers/</link><guid isPermaLink="true">https://tpodolak.com/blog/introduce-substitute-refactoring-comes-nsubstitute-analyzers/</guid><pubDate>Thu, 09 Apr 2020 08:00:03 GMT</pubDate><content:encoded>&lt;p&gt;I am glad to announce the newest version of &lt;a href=&quot;https://www.nuget.org/packages/NSubstitute.Analyzers.CSharp/1.0.13&quot;&gt;NSubstitute.Analyzers&lt;/a&gt; comes with &quot;introduce substitute&quot; refactoring, which allows you to automatically create substitutes for constructor arguments as fields or local variables.
As an image is worth a thousand words here is a quick demo of &lt;code&gt;C#&lt;/code&gt; version&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;images/77374918-54832d80-6d6c-11ea-965a-eb96080bf8cd.gif&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
&lt;p&gt;and VisualBasic one&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;images/77374922-564cf100-6d6c-11ea-8fca-96d8a9724b36.gif&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;
</content:encoded></item><item><title>.NET Core - missing currency symbol in docker alpine image</title><link>https://tpodolak.com/blog/net-core-missing-currency-symbol-docker-alpine-image/</link><guid isPermaLink="true">https://tpodolak.com/blog/net-core-missing-currency-symbol-docker-alpine-image/</guid><pubDate>Mon, 18 Nov 2019 13:54:32 GMT</pubDate><content:encoded>&lt;p&gt;During the process of moving a Scala-based &lt;code&gt;API&lt;/code&gt; to &lt;code&gt;.NET Core&lt;/code&gt;, we encountered an interesting localization issue when running our code in a docker container based on an alpine image.
The code itself was doing a currency formatting based on some culture. It looked more or less as below&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Route(&quot;api/[controller]&quot;)]
[ApiController]
public class PriceController : ControllerBase
{
    [HttpGet]
    public ActionResult&amp;lt;object&amp;gt; Get(string cultureCode = &quot;de-DE&quot;)
    {
        var cultureInfo = CultureInfo.CreateSpecificCulture(cultureCode);
        var price = 10m;
        
        return new
        {
            price,
            formattedPrice = price.ToString(&quot;C&quot;, cultureInfo),
            currencySymbol = cultureInfo.NumberFormat.CurrencySymbol
        };
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We also had some integration tests for that piece of logic&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class PriceTests : IClassFixture&amp;lt;WebApplicationFactory&amp;lt;Startup&amp;gt;&amp;gt;
{
    private readonly WebApplicationFactory&amp;lt;Startup&amp;gt; _factory;

    public PriceTests(WebApplicationFactory&amp;lt;Startup&amp;gt; factory)
    {
        _factory = factory;
    }
        
    [Fact]
    public async Task GetPrice_ReturnsCorrectCurrency()
    {
        var httpClient = _factory.CreateClient();
        var httpResponseMessage = await httpClient.GetAsync(&quot;api/Price&quot;);
            
        httpResponseMessage.EnsureSuccessStatusCode();
        var content = await httpResponseMessage.Content.ReadAsStringAsync();
        var jObject = JObject.Parse(content);

        jObject[&quot;currencySymbol&quot;].ToObject&amp;lt;string&amp;gt;().Should().Be(&quot;€&quot;);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The tests were run during a &lt;code&gt;CI&lt;/code&gt; build in a container with an image defined as below&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Builder image
FROM mcr.microsoft.com/dotnet/core/sdk:2.1.700-alpine AS builder
WORKDIR /sln

COPY ./*.sln ./

# Copy the main source project files
COPY src/*/*.csproj ./
RUN for file in $(ls *.csproj); do mkdir -p src/${file%.*}/ &amp;amp;&amp;amp; mv $file src/${file%.*}/; done

# Copy the test project files
COPY test/*/*.csproj ./
RUN for file in $(ls *.csproj); do mkdir -p test/${file%.*}/ &amp;amp;&amp;amp; mv $file test/${file%.*}/; done

RUN dotnet restore

# Copy across the rest of the source files
COPY ./test ./test
COPY ./src ./src

RUN dotnet build -c Release

RUN dotnet test &quot;./test/AlpineMissingCurrencySymbol.Tests/AlpineMissingCurrencySymbol.Tests.csproj&quot; \
    -c Release --no-build --no-restore

RUN dotnet publish &quot;./src/AlpineMissingCurrencySymbol/AlpineMissingCurrencySymbol.csproj&quot; \
    -c Release -o &quot;../../dist&quot; --no-restore

# App image
FROM mcr.microsoft.com/dotnet/core/aspnet:2.1.11-alpine
WORKDIR /app
ENTRYPOINT [&quot;dotnet&quot;, &quot;AlpineMissingCurrencySymbol.dll&quot;]
COPY --from=builder /sln/dist .
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;At this point, we were sure that everything works fine, as the tests were green and everything was also working correctly on our local machines.
However, after deployment to a testing environment, we started getting invalid currency symbols&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;curl localhost:8080/api/price 
{ 
  &quot;price&quot;: 10, 
  &quot;formattedPrice&quot;: &quot;¤10.00&quot;, 
  &quot;currencySymbol&quot;: &quot;¤&quot; 
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see the response contains &lt;code&gt;¤&lt;/code&gt; (invariant currency symbol) instead of expected &lt;code&gt;€&lt;/code&gt;.
It took us some time to figure this out but finally, it turned out that &lt;code&gt;aspnet:2.1.11-alpine&lt;/code&gt; image(the one we used for running the application) contrary to the &lt;code&gt;SDK&lt;/code&gt; image(used for building and running tests) is missing &lt;code&gt;icu-libs&lt;/code&gt; package.
In default conditions, the application should throw the following exception during the startup&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;FailFast:
Couldn&apos;t find a valid ICU package installed on the system. Set the configuration flag System.Globalization.Invariant to true if you want to run with no globalization support.

   at System.Environment.FailFast(System.String)
   at System.Globalization.GlobalizationMode.GetGlobalizationInvariantMode()
   at System.Globalization.GlobalizationMode..cctor()
   at System.Globalization.CultureData.CreateCultureWithInvariantData()
   at System.Globalization.CultureData.get_Invariant()
   at System.Globalization.CultureInfo..cctor()
   at System.StringComparer..cctor()
   at System.AppDomain.InitializeCompatibilityFlags()
   at System.AppDomain.Setup(System.Object)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;However, &lt;code&gt;aspnet:2.1.11-alpine&lt;/code&gt; image has the &lt;code&gt;DOTNET_SYSTEM_GLOBALIZATION_INVARIANT&lt;/code&gt; flag set to &lt;code&gt;true&lt;/code&gt; by default, so the missing package was not validated during a startup.
After all, in order to fix the issue, we had to install the icu-libs package and also set the &lt;code&gt;DOTNET_SYSTEM_GLOBALIZATION_INVARIANT&lt;/code&gt; back to &lt;code&gt;false&lt;/code&gt;.
This was done by these two lines in &lt;code&gt;Dockerfile&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false 
RUN apk add --no-cache icu-libs 
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Once the lines were added the application started working as expected&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;curl localhost:8080/api/price 
{ 
  &quot;price&quot;: 10, 
  &quot;formattedPrice&quot;: &quot;10,00 €&quot;, 
  &quot;currencySymbol&quot;: &quot;€&quot; 
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/AlpineMissingCurrencySymbol&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>MongoDB.Driver - class-based server side projection</title><link>https://tpodolak.com/blog/mongodb-driver-class-based-server-side-projection/</link><guid isPermaLink="true">https://tpodolak.com/blog/mongodb-driver-class-based-server-side-projection/</guid><pubDate>Tue, 22 Oct 2019 08:00:31 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;When working with &lt;code&gt;NoSQL&lt;/code&gt; databases, your documents might be quite heavy and in some cases, you would like to get only a slice of original data.
For instance, let&apos;s assume we have an &lt;code&gt;Account&lt;/code&gt; document which among other things contains a list of transactions&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Account : IAccountDefinition
{
    public ObjectId Id { get; set; }

    public string Name { get; set; }

    public List&amp;lt;Transaction&amp;gt; Transactions { get; set; }
}

public class Transaction
{
    public ObjectId Id { get; set; }
        
    public decimal Amount { get; set; }
        
    public DateTime CreatedAt { get; set; }
        
    public DateTime ModifiedAt { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As there might be hundreds of transaction in the account object, you might want to occasionally work on a subset of original data, say for instance &lt;code&gt;AccountSlim&lt;/code&gt; object to improve the performance&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class AccountSlim : IAccountDefinition
{
    public ObjectId Id { get; set; }
        
    public string Name { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;2.Exploring existing options&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;MongoDB.Driver&lt;/code&gt; has a couple of ways of defining projections so as you can operate on a slimmer object instead of a default one.
For instance&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;List&amp;lt;AccountSlim&amp;gt; accountSlims = await accountsCollection.Find(defaultAccountFilterDefinition)
                .Project(Builders&amp;lt;Account&amp;gt;.Projection.As&amp;lt;AccountSlim&amp;gt;())
                .ToListAsync();
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;
IAsyncCursor&amp;lt;AccountSlim&amp;gt; asyncCursor = await accountsCollection.FindAsync(defaultAccountFilterDefinition,
                new FindOptions&amp;lt;Account, AccountSlim&amp;gt;());
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Unfortunately, those are a client-side projection.
This means that the entire object is returned from the database and we just serialized it to a different class.
You can check it on your own by examining request and result commands sent to &lt;code&gt;Mongo&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var clientSettings = MongoClientSettings.FromUrl(new MongoUrl(&quot;mongodb://localhost:27017&quot;)); 
clientSettings.ClusterConfigurator += builder =&amp;gt; 
{ 
    builder.Subscribe&amp;lt;CommandStartedEvent&amp;gt;(OnCommandStarted); 
    builder.Subscribe&amp;lt;CommandSucceededEvent&amp;gt;(OnCommandSucceeded); 
}; 
var client = new MongoClient(clientSettings); 

private static void OnCommandSucceeded(CommandSucceededEvent @event) 
{ 
    if (@event.CommandName == FindCommandName) 
    { 
        Console.WriteLine(&quot;Returned document:&quot;); 
        PrintDocument(@event.Reply); 
    } 
} 
 
private static void OnCommandStarted(CommandStartedEvent @event) 
{ 
    if (@event.CommandName == FindCommandName) 
    { 
        Console.WriteLine(&quot;Requested document:&quot;); 
        PrintDocument(@event.Command); 
    } 
} 
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In both cases requested query doesn&apos;t contain &lt;code&gt;projection&lt;/code&gt; section, so entire document is returned&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// query 
{ 
  &quot;find&quot; : &quot;Accounts&quot;, 
  &quot;filter&quot; : { 
    &quot;_id&quot; : ObjectId(&quot;5dac6ab1ea342a254e1b7748&quot;) 
  }, 
  &quot;$db&quot; : &quot;Accounting&quot;, 
  &quot;lsid&quot; : { 
    &quot;id&quot; : CSUUID(&quot;c6b40361-c47f-4fe6-99bd-6a9ec1702576&quot;) 
  } 
} 

// returned document 
{ 
  &quot;cursor&quot; : { 
    &quot;firstBatch&quot; : [{ 
        &quot;_id&quot; : ObjectId(&quot;5dac6ab1ea342a254e1b7748&quot;), 
        &quot;AccountName&quot; : &quot;WRKYDWKKJY&quot;, 
        &quot;Transactions&quot; : [{ 
            &quot;_id&quot; : ObjectId(&quot;5dac6ab1ea342a254e1b7749&quot;), 
            &quot;Amount&quot; : &quot;413648280&quot;, 
            &quot;CreatedAt&quot; : ISODate(&quot;2019-10-20T14:09:53.635Z&quot;), 
            &quot;ModifiedAt&quot; : ISODate(&quot;2019-10-20T14:09:53.635Z&quot;) 
          }] 
      }], 
    &quot;id&quot; : NumberLong(0), 
    &quot;ns&quot; : &quot;Accounting.Accounts&quot; 
  }, 
  &quot;ok&quot; : 1.0 
} 
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Of course, there is a possibility to manually create a server-side projection, for instance&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var accountSlims = await accountsCollection.Find(defaultAccountFilterDefinition)
                .Project(new ObjectProjectionDefinition&amp;lt;Account, AccountSlim&amp;gt;(new { id = 1, name = 1 }))
                .ToListAsync();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or with a strongly typed version&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var bsonDocument = Builders&amp;lt;Account&amp;gt;.Projection.Exclude(x =&amp;gt; x.Transactions)
                .Render(accountsCollection.DocumentSerializer, accountsCollection.Settings.SerializerRegistry);

List&amp;lt;AccountSlim&amp;gt; accountSlim = await accountsCollection.Find(defaultAccountFilterDefinition)
                .Project(new BsonDocumentProjectionDefinition&amp;lt;Account, AccountSlim&amp;gt;(bsonDocument))
                .ToListAsync();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;However, in my opinion, this is error-prone and it would be better to generate server-side projection automatically based on properties in a slim object.
As I didn&apos;t find anything like that in the official driver, here is my approach for handling this&lt;/p&gt;
&lt;h3&gt;3. Class-based server-side projection&lt;/h3&gt;
&lt;p&gt;In order to create a custom projection, all we have to do is to extend &lt;code&gt;ProjectionDefinition&amp;lt;TSource, TResult&amp;gt;&lt;/code&gt; class and provide a &lt;code&gt;RenderedProjectionDefinition&lt;/code&gt; with all properties which are in both &quot;heavy&quot; and &quot;slim&quot; object&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;

namespace MongoDBServerSideProjection.Projections
{
    public class ServerSideProjectionDefinition&amp;lt;TSource, TResult&amp;gt; : ProjectionDefinition&amp;lt;TSource, TResult&amp;gt;
    {
        private readonly ProjectionDefinition&amp;lt;TSource&amp;gt; _projectionDefinition;

        public ServerSideProjectionDefinition()
        {
            _projectionDefinition = BuildProjectionDefinition();
        }

        public override RenderedProjectionDefinition&amp;lt;TResult&amp;gt; Render(IBsonSerializer&amp;lt;TSource&amp;gt; sourceSerializer, IBsonSerializerRegistry serializerRegistry)
        {
            var bsonDocument = _projectionDefinition.Render(sourceSerializer, serializerRegistry);

            return new RenderedProjectionDefinition&amp;lt;TResult&amp;gt;(bsonDocument, serializerRegistry.GetSerializer&amp;lt;TResult&amp;gt;());
        }

        private static ProjectionDefinition&amp;lt;TSource&amp;gt; BuildProjectionDefinition()
        {
            var sourceProperties = ProjectionPropertyCache&amp;lt;TSource&amp;gt;.PropertyNames;
            var resultProperties = ProjectionPropertyCache&amp;lt;TResult&amp;gt;.PropertyNames;

            var projectionDefinitionBuilder = Builders&amp;lt;TSource&amp;gt;.Projection;

            var projectionDefinitions = resultProperties.Intersect(sourceProperties).Select(
                name =&amp;gt; projectionDefinitionBuilder.Include(new StringFieldDefinition&amp;lt;TSource&amp;gt;(name)));

            return projectionDefinitionBuilder.Combine(projectionDefinitions);
        }

        private class ProjectionPropertyCache&amp;lt;T&amp;gt;
        {
            static ProjectionPropertyCache()
            {
                PropertyNames = GetProperties();
            }

            public static IReadOnlyCollection&amp;lt;string&amp;gt; PropertyNames { get; }

            private static ReadOnlyCollection&amp;lt;string&amp;gt; GetProperties()
            {
                return typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
                    .Where(prop =&amp;gt; !prop.IsSpecialName).Select(prop =&amp;gt; prop.Name).ToList().AsReadOnly();
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see we use &lt;code&gt;MongoDB.Driver&lt;/code&gt; build-in projections to render our custom projection consisting of necessary properties.
Note, that as we are using &lt;code&gt;StringFieldDefinition&lt;/code&gt; instead of defining &lt;code&gt;Bson&lt;/code&gt; document manually, the projection will take into account potential class mappings or attribute mappings applied to your object&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;BsonClassMap.RegisterClassMap&amp;lt;Account&amp;gt;(cm =&amp;gt;
            {
                cm.AutoMap();
                cm.MapProperty(account =&amp;gt; account.Name).SetElementName(&quot;AccountName&quot;);
            });
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Having the projection ready we can make it a bit easier to use by introducing some extensions. The first one looks as follows&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using MongoDB.Driver;
using MongoDBServerSideProjection.Projections;

namespace MongoDBServerSideProjection.Extensions
{
    public static class ProjectionDefinitionBuilderExtensions
    {
        public static ServerSideProjectionDefinition&amp;lt;TSource, TResult&amp;gt; ServerSide&amp;lt;TSource, TResult&amp;gt;(this ProjectionDefinitionBuilder&amp;lt;TSource&amp;gt; builder)
        {
            return new ServerSideProjectionDefinition&amp;lt;TSource, TResult&amp;gt;();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;which allows you to use this projection similarly like others – so by accessing &lt;code&gt;Builders&lt;/code&gt; class&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var projection = Builders&amp;lt;Account&amp;gt;.Projection.ServerSide&amp;lt;Account, AccountSlim&amp;gt;();
List&amp;lt;AccountSlim&amp;gt; slims = await accountsCollection.Find(defaultAccountFilterDefinition)
                .Project(projection)
                .ToListAsync();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The second method will extend &lt;code&gt;IFindFluent&amp;lt;TDocument, TProjection&amp;gt;&lt;/code&gt; interface&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using MongoDB.Driver;

namespace MongoDBServerSideProjection.Extensions
{
    public static class FindFluentExtensions
    {
        public static IFindFluent&amp;lt;TSource, TResult&amp;gt; ProjectTo&amp;lt;TSource, TResult&amp;gt;(this IFindFluent&amp;lt;TSource, TSource&amp;gt; findFluent)
        {
            var serverSideProjectionDefinition = Builders&amp;lt;TSource&amp;gt;.Projection.ServerSide&amp;lt;TSource, TResult&amp;gt;();
            return findFluent.Project(serverSideProjectionDefinition);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and thanks to it we will end up with an even better syntax&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;List&amp;lt;AccountSlim&amp;gt; list = await accountsCollection.Find(defaultAccountFilterDefinition)
                .ProjectTo&amp;lt;Account, AccountSlim&amp;gt;()
                .ToListAsync();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;One way or another we will end up with proper projection definition which will result in a smaller document returned from the database&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// query
{ 
  &quot;find&quot; : &quot;Accounts&quot;, 
  &quot;filter&quot; : { 
    &quot;_id&quot; : ObjectId(&quot;5dac846eea29403cb83f99bb&quot;) 
  }, 
  &quot;projection&quot; : { 
    &quot;_id&quot; : 1, 
    &quot;AccountName&quot; : 1 
  }, 
  &quot;$db&quot; : &quot;Accounting&quot;, 
  &quot;lsid&quot; : { 
    &quot;id&quot; : CSUUID(&quot;cf5d5a88-2598-4110-9295-6417d1a5f7dd&quot;) 
  } 
} 

// returned document
{ 
  &quot;cursor&quot; : { 
    &quot;firstBatch&quot; : [{ 
        &quot;_id&quot; : ObjectId(&quot;5dac846eea29403cb83f99bb&quot;), 
        &quot;AccountName&quot; : &quot;CBBRRWQVKJ&quot; 
      }], 
    &quot;id&quot; : NumberLong(0), 
    &quot;ns&quot; : &quot;Accounting.Accounts&quot; 
  }, 
  &quot;ok&quot; : 1.0 
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/MongoDBServerSideProjection&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Performance improvements in NSubstitute.Analyzers 1.0.11</title><link>https://tpodolak.com/blog/performance-improvements-nsubstitute-analyzers-1-0-11/</link><guid isPermaLink="true">https://tpodolak.com/blog/performance-improvements-nsubstitute-analyzers-1-0-11/</guid><pubDate>Mon, 21 Oct 2019 12:57:05 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;I am glad to announce that the latest release of &lt;a href=&quot;https://www.nuget.org/packages/NSubstitute.Analyzers.CSharp/1.0.11&quot;&gt;NSubstitute.Analyzers&lt;/a&gt; (apart from some bugfixes) brings a lot of performance and memory usage improvements for most of the analyzers. The benchmark results shown below should give you enough information about the speed and memory consumption of the newest version of the library. If you are interested in actual changes behind these results please take a look at this &lt;a href=&quot;https://github.com/nsubstitute/NSubstitute.Analyzers/pull/111&quot;&gt;pull request&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;2. Benchmark comparision of NSubstitute.Analyzers.CSharp&lt;/h3&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Analyzer&lt;/th&gt;
&lt;th&gt;Mean (us)&lt;/th&gt;
&lt;th&gt;Error (us)&lt;/th&gt;
&lt;th&gt;StdDev (us)&lt;/th&gt;
&lt;th&gt;Gen 0&lt;/th&gt;
&lt;th&gt;Gen 1&lt;/th&gt;
&lt;th&gt;Allocated (KB)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;CallInfoAnalyzer&lt;/td&gt;
&lt;td&gt;1,897.0&lt;/td&gt;
&lt;td&gt;5.646&lt;/td&gt;
&lt;td&gt;5.2814&lt;/td&gt;
&lt;td&gt;136.7188&lt;/td&gt;
&lt;td&gt;11.7188&lt;/td&gt;
&lt;td&gt;424.54&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ConflictingArgumentAssignmentsAnalyzer&lt;/td&gt;
&lt;td&gt;554.2&lt;/td&gt;
&lt;td&gt;1.018&lt;/td&gt;
&lt;td&gt;0.9524&lt;/td&gt;
&lt;td&gt;33.2031&lt;/td&gt;
&lt;td&gt;1.9531&lt;/td&gt;
&lt;td&gt;103.47&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;NonSubstitutableMemberAnalyzer&lt;/td&gt;
&lt;td&gt;2,466.9&lt;/td&gt;
&lt;td&gt;9.317&lt;/td&gt;
&lt;td&gt;8.2596&lt;/td&gt;
&lt;td&gt;179.6875&lt;/td&gt;
&lt;td&gt;15.6250&lt;/td&gt;
&lt;td&gt;560.33&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;NonSubstitutableMemberReceivedAnalyzer&lt;/td&gt;
&lt;td&gt;644.4&lt;/td&gt;
&lt;td&gt;2.280&lt;/td&gt;
&lt;td&gt;1.9039&lt;/td&gt;
&lt;td&gt;31.2500&lt;/td&gt;
&lt;td&gt;6.8359&lt;/td&gt;
&lt;td&gt;96.27&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;NonSubstitutableMemberWhenAnalyzer&lt;/td&gt;
&lt;td&gt;995.9&lt;/td&gt;
&lt;td&gt;2.320&lt;/td&gt;
&lt;td&gt;1.9370&lt;/td&gt;
&lt;td&gt;37.1094&lt;/td&gt;
&lt;td&gt;7.8125&lt;/td&gt;
&lt;td&gt;116.74&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ReEntrantSetupAnalyzer&lt;/td&gt;
&lt;td&gt;57,979.0&lt;/td&gt;
&lt;td&gt;196.824&lt;/td&gt;
&lt;td&gt;174.4794&lt;/td&gt;
&lt;td&gt;2333.3333&lt;/td&gt;
&lt;td&gt;-&lt;/td&gt;
&lt;td&gt;7175.61&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;SubstituteAnalyzer&lt;/td&gt;
&lt;td&gt;1,960.4&lt;/td&gt;
&lt;td&gt;8.197&lt;/td&gt;
&lt;td&gt;7.2666&lt;/td&gt;
&lt;td&gt;89.8438&lt;/td&gt;
&lt;td&gt;19.5313&lt;/td&gt;
&lt;td&gt;343.67&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;UnusedReceivedAnalyzer&lt;/td&gt;
&lt;td&gt;524.0&lt;/td&gt;
&lt;td&gt;1.671&lt;/td&gt;
&lt;td&gt;1.5630&lt;/td&gt;
&lt;td&gt;29.2969&lt;/td&gt;
&lt;td&gt;1.9531&lt;/td&gt;
&lt;td&gt;92.45&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Analyzer&lt;/th&gt;
&lt;th&gt;Mean (us)&lt;/th&gt;
&lt;th&gt;Error (us)&lt;/th&gt;
&lt;th&gt;StdDev (us)&lt;/th&gt;
&lt;th&gt;Gen 0&lt;/th&gt;
&lt;th&gt;Gen 1&lt;/th&gt;
&lt;th&gt;Allocated (KB)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;CallInfoAnalyzer&lt;/td&gt;
&lt;td&gt;1,828.8&lt;/td&gt;
&lt;td&gt;5.599&lt;/td&gt;
&lt;td&gt;4.963&lt;/td&gt;
&lt;td&gt;123.0469&lt;/td&gt;
&lt;td&gt;11.7188&lt;/td&gt;
&lt;td&gt;379.78&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ConflictingArgumentAssignmentsAnalyzer&lt;/td&gt;
&lt;td&gt;510.3&lt;/td&gt;
&lt;td&gt;1.973&lt;/td&gt;
&lt;td&gt;1.846&lt;/td&gt;
&lt;td&gt;33.2031&lt;/td&gt;
&lt;td&gt;1.9531&lt;/td&gt;
&lt;td&gt;102.76&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;NonSubstitutableMemberAnalyzer&lt;/td&gt;
&lt;td&gt;766.0&lt;/td&gt;
&lt;td&gt;2.798&lt;/td&gt;
&lt;td&gt;2.336&lt;/td&gt;
&lt;td&gt;39.0625&lt;/td&gt;
&lt;td&gt;8.7891&lt;/td&gt;
&lt;td&gt;122.27&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;NonSubstitutableMemberReceivedAnalyzer&lt;/td&gt;
&lt;td&gt;600.6&lt;/td&gt;
&lt;td&gt;3.411&lt;/td&gt;
&lt;td&gt;3.191&lt;/td&gt;
&lt;td&gt;27.3438&lt;/td&gt;
&lt;td&gt;5.8594&lt;/td&gt;
&lt;td&gt;85.82&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;NonSubstitutableMemberWhenAnalyzer&lt;/td&gt;
&lt;td&gt;866.0&lt;/td&gt;
&lt;td&gt;3.144&lt;/td&gt;
&lt;td&gt;2.941&lt;/td&gt;
&lt;td&gt;34.1797&lt;/td&gt;
&lt;td&gt;9.7656&lt;/td&gt;
&lt;td&gt;107.87&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ReEntrantSetupAnalyzer&lt;/td&gt;
&lt;td&gt;7,442.0&lt;/td&gt;
&lt;td&gt;34.067&lt;/td&gt;
&lt;td&gt;31.866&lt;/td&gt;
&lt;td&gt;281.2500&lt;/td&gt;
&lt;td&gt;15.6250&lt;/td&gt;
&lt;td&gt;870.18&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;SubstituteAnalyzer&lt;/td&gt;
&lt;td&gt;1,870.2&lt;/td&gt;
&lt;td&gt;29.787&lt;/td&gt;
&lt;td&gt;27.863&lt;/td&gt;
&lt;td&gt;87.8906&lt;/td&gt;
&lt;td&gt;23.4375&lt;/td&gt;
&lt;td&gt;346.09&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;UnusedReceivedAnalyzer&lt;/td&gt;
&lt;td&gt;482.1&lt;/td&gt;
&lt;td&gt;1.705&lt;/td&gt;
&lt;td&gt;1.511&lt;/td&gt;
&lt;td&gt;25.8789&lt;/td&gt;
&lt;td&gt;1.9531&lt;/td&gt;
&lt;td&gt;80.96&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h3&gt;3. Benchmark comparision of NSubstitute.Analyzers.VisualBasic&lt;/h3&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Method&lt;/th&gt;
&lt;th&gt;Mean (ms)&lt;/th&gt;
&lt;th&gt;Error (ms)&lt;/th&gt;
&lt;th&gt;StdDev (ms)&lt;/th&gt;
&lt;th&gt;Gen 0&lt;/th&gt;
&lt;th&gt;Gen 1&lt;/th&gt;
&lt;th&gt;Allocated (KB)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;CallInfoAnalyzer&lt;/td&gt;
&lt;td&gt;3.459&lt;/td&gt;
&lt;td&gt;0.0137&lt;/td&gt;
&lt;td&gt;0.0121&lt;/td&gt;
&lt;td&gt;156.2500&lt;/td&gt;
&lt;td&gt;11.7188&lt;/td&gt;
&lt;td&gt;484.15&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ConflictingArgumentAssignmentsAnalyzer&lt;/td&gt;
&lt;td&gt;1.279&lt;/td&gt;
&lt;td&gt;0.0103&lt;/td&gt;
&lt;td&gt;0.0086&lt;/td&gt;
&lt;td&gt;21.4844&lt;/td&gt;
&lt;td&gt;1.9531&lt;/td&gt;
&lt;td&gt;69.15&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;NonSubstitutableMemberAnalyzer&lt;/td&gt;
&lt;td&gt;1.975&lt;/td&gt;
&lt;td&gt;0.0108&lt;/td&gt;
&lt;td&gt;0.0090&lt;/td&gt;
&lt;td&gt;35.1563&lt;/td&gt;
&lt;td&gt;7.8125&lt;/td&gt;
&lt;td&gt;108&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;NonSubstitutableMemberReceivedAnalyzer&lt;/td&gt;
&lt;td&gt;1.287&lt;/td&gt;
&lt;td&gt;0.0070&lt;/td&gt;
&lt;td&gt;0.0065&lt;/td&gt;
&lt;td&gt;13.6719&lt;/td&gt;
&lt;td&gt;1.9531&lt;/td&gt;
&lt;td&gt;47.46&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;NonSubstitutableMemberWhenAnalyzer&lt;/td&gt;
&lt;td&gt;1.589&lt;/td&gt;
&lt;td&gt;0.0103&lt;/td&gt;
&lt;td&gt;0.0092&lt;/td&gt;
&lt;td&gt;25.3906&lt;/td&gt;
&lt;td&gt;5.8594&lt;/td&gt;
&lt;td&gt;82.72&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ReEntrantSetupAnalyzer&lt;/td&gt;
&lt;td&gt;54.131&lt;/td&gt;
&lt;td&gt;0.2320&lt;/td&gt;
&lt;td&gt;0.1937&lt;/td&gt;
&lt;td&gt;3600.0000&lt;/td&gt;
&lt;td&gt;-&lt;/td&gt;
&lt;td&gt;11139.45&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;SubstituteAnalyzer&lt;/td&gt;
&lt;td&gt;3.615&lt;/td&gt;
&lt;td&gt;0.0168&lt;/td&gt;
&lt;td&gt;0.0149&lt;/td&gt;
&lt;td&gt;105.4688&lt;/td&gt;
&lt;td&gt;23.4375&lt;/td&gt;
&lt;td&gt;393.13&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;UnusedReceivedAnalyzer&lt;/td&gt;
&lt;td&gt;1.306&lt;/td&gt;
&lt;td&gt;0.0258&lt;/td&gt;
&lt;td&gt;0.0528&lt;/td&gt;
&lt;td&gt;13.6719&lt;/td&gt;
&lt;td&gt;1.9531&lt;/td&gt;
&lt;td&gt;43.3&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Analyzer&lt;/th&gt;
&lt;th&gt;Mean (ms)&lt;/th&gt;
&lt;th&gt;Error (ms)&lt;/th&gt;
&lt;th&gt;StdDev (ms)&lt;/th&gt;
&lt;th&gt;Gen 0&lt;/th&gt;
&lt;th&gt;Gen 1&lt;/th&gt;
&lt;th&gt;Allocated (KB)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;CallInfoAnalyzer&lt;/td&gt;
&lt;td&gt;3.737&lt;/td&gt;
&lt;td&gt;0.0878&lt;/td&gt;
&lt;td&gt;0.1110&lt;/td&gt;
&lt;td&gt;152.3438&lt;/td&gt;
&lt;td&gt;11.7188&lt;/td&gt;
&lt;td&gt;471.79&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ConflictingArgumentAssignmentsAnalyzer&lt;/td&gt;
&lt;td&gt;1.402&lt;/td&gt;
&lt;td&gt;0.0266&lt;/td&gt;
&lt;td&gt;0.0285&lt;/td&gt;
&lt;td&gt;21.4844&lt;/td&gt;
&lt;td&gt;1.9531&lt;/td&gt;
&lt;td&gt;68.36&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;NonSubstitutableMemberAnalyzer&lt;/td&gt;
&lt;td&gt;1.543&lt;/td&gt;
&lt;td&gt;0.0264&lt;/td&gt;
&lt;td&gt;0.0247&lt;/td&gt;
&lt;td&gt;25.3906&lt;/td&gt;
&lt;td&gt;5.8594&lt;/td&gt;
&lt;td&gt;81&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;NonSubstitutableMemberReceivedAnalyzer&lt;/td&gt;
&lt;td&gt;1.213&lt;/td&gt;
&lt;td&gt;0.0051&lt;/td&gt;
&lt;td&gt;0.0048&lt;/td&gt;
&lt;td&gt;13.6719&lt;/td&gt;
&lt;td&gt;1.9531&lt;/td&gt;
&lt;td&gt;45.43&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;NonSubstitutableMemberWhenAnalyzer&lt;/td&gt;
&lt;td&gt;1.475&lt;/td&gt;
&lt;td&gt;0.0055&lt;/td&gt;
&lt;td&gt;0.0051&lt;/td&gt;
&lt;td&gt;27.3438&lt;/td&gt;
&lt;td&gt;7.8125&lt;/td&gt;
&lt;td&gt;85.25&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;ReEntrantSetupAnalyzer&lt;/td&gt;
&lt;td&gt;7.044&lt;/td&gt;
&lt;td&gt;0.0236&lt;/td&gt;
&lt;td&gt;0.0209&lt;/td&gt;
&lt;td&gt;265.6250&lt;/td&gt;
&lt;td&gt;7.8125&lt;/td&gt;
&lt;td&gt;837.14&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;SubstituteAnalyzer&lt;/td&gt;
&lt;td&gt;3.333&lt;/td&gt;
&lt;td&gt;0.0912&lt;/td&gt;
&lt;td&gt;0.1186&lt;/td&gt;
&lt;td&gt;101.5625&lt;/td&gt;
&lt;td&gt;23.4375&lt;/td&gt;
&lt;td&gt;377.16&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;UnusedReceivedAnalyzer&lt;/td&gt;
&lt;td&gt;1.102&lt;/td&gt;
&lt;td&gt;0.0067&lt;/td&gt;
&lt;td&gt;0.0062&lt;/td&gt;
&lt;td&gt;11.7188&lt;/td&gt;
&lt;td&gt;-&lt;/td&gt;
&lt;td&gt;40.24&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
</content:encoded></item><item><title>NSubstitute.Analyzers 1.0.0 released</title><link>https://tpodolak.com/blog/nsubstitute-analyzers-1-0-0-released/</link><guid isPermaLink="true">https://tpodolak.com/blog/nsubstitute-analyzers-1-0-0-released/</guid><pubDate>Wed, 24 Oct 2018 09:00:51 GMT</pubDate><content:encoded>&lt;p&gt;A while ago I&apos;ve &lt;a href=&quot;//tpodolak.com/blog/2018/06/11/announcing-nsubstitute-analyzers-beta/&quot;&gt;announced&lt;/a&gt; a release of the first beta package of &lt;code&gt;NSubstitute.Analyzers&lt;/code&gt;.
Now, 4 months later I am happy to say that the first stable version is available for download.
As usual, analyzers comes with two flavors:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://www.nuget.org/packages/NSubstitute.Analyzers.CSharp/&quot;&gt;NSubstitute.Analyzers.CSharp&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://www.nuget.org/packages/NSubstitute.Analyzers.VisualBasic/&quot;&gt;NSubstitute.Analyzers.VisualBasic&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Both of them come together with 19 &lt;a href=&quot;https://github.com/nsubstitute/NSubstitute.Analyzers/tree/dev/documentation/rules&quot;&gt;diagnostics&lt;/a&gt;, which will warn you against common misusages of &lt;code&gt;NSubstitue API&lt;/code&gt;.
Feel free to grab them from &lt;code&gt;NuGet&lt;/code&gt; and try them in your project.
In case of any issues don&apos;t hestitate to report a bug via GitHub &lt;a href=&quot;https://github.com/nsubstitute/NSubstitute.Analyzers/issues&quot;&gt;issue tracker&lt;/a&gt;.&lt;/p&gt;
</content:encoded></item><item><title>Announcing NSubstitute.Analyzers (beta)</title><link>https://tpodolak.com/blog/announcing-nsubstitute-analyzers-beta/</link><guid isPermaLink="true">https://tpodolak.com/blog/announcing-nsubstitute-analyzers-beta/</guid><pubDate>Mon, 11 Jun 2018 08:06:20 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;I am glad to announce that yesterday, together with &lt;code&gt;NSubstitute&lt;/code&gt; team we released first beta version of &lt;code&gt;Roslyn&lt;/code&gt; analyzers for &lt;code&gt;NSubstitute&lt;/code&gt; - &lt;a href=&quot;https://github.com/nsubstitute/NSubstitute.Analyzers&quot;&gt;NSubstitute.Analyzers&lt;/a&gt;.
The analyzers come in two flavors: &lt;a href=&quot;https://www.nuget.org/packages/NSubstitute.Analyzers.CSharp&quot;&gt;NSubstitute.Analyzers.CSharp&lt;/a&gt; and &lt;a href=&quot;https://www.nuget.org/packages/NSubstitute.Analyzers.VisualBasic&quot;&gt;NSubstitute.Analyzers.VisualBasic&lt;/a&gt;. Feel free to grab them from NuGet and try them in your project.&lt;/p&gt;
&lt;h3&gt;2. Diagnostics&lt;/h3&gt;
&lt;p&gt;As for today analyzers can detect two most common misusages of &lt;code&gt;NSubstitute&lt;/code&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;non-virtual call setup
&lt;img src=&quot;images/NonVirtualSetup.png&quot; alt=&quot;&quot; /&gt;&lt;/li&gt;
&lt;li&gt;Received used without following method call
&lt;img src=&quot;images/UnusedReceived.png&quot; alt=&quot;&quot; /&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Feels free to &lt;a href=&quot;https://github.com/nsubstitute/NSubstitute.Analyzers/issues&quot;&gt;suggest&lt;/a&gt; additional diagnostic you would like to have in the package.&lt;/p&gt;
</content:encoded></item><item><title>ASP.NET Web API 2 - missing swagger query parameters</title><link>https://tpodolak.com/blog/asp-net-web-api-2-missing-swagger-query-parameters/</link><guid isPermaLink="true">https://tpodolak.com/blog/asp-net-web-api-2-missing-swagger-query-parameters/</guid><pubDate>Mon, 23 Apr 2018 08:00:27 GMT</pubDate><content:encoded>&lt;p&gt;Last week I&apos;ve encountered an interesting bug in swagger documentation of our API. For some reason couple of &lt;em&gt;Get&lt;/em&gt; operations were missing some of the query parameters. The issue itself was only visible in a couple of controllers, simplified version of one of them is shown below&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable&amp;lt;string&amp;gt; Get([FromUri] FullAvailabilityRequest request)
    {
        return new string[] {&quot;value1&quot;, &quot;value2&quot;};
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see the controller has a Get method which takes as an argument following class&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class FullAvailabilityRequest : AvailabilityRequest
{
    public string TermsOfService { get; set; }
}

[DataContract]
public class AvailabilityRequest
{
    [DataMember]
    public string Origin { get; set; }

    [DataMember]
    public string Destination { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you run swagger for &lt;code&gt;Get&lt;/code&gt; operation you will see that only two parameters are listed in a parameter list&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2018/04/asp-net-web-api-2-missing-swagger-query-parameters/MissingParameter.png&quot;&gt;&lt;img src=&quot;images/MissingParameter.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;After some digging I found the actual problem were basically &lt;code&gt;[DataMember]&lt;/code&gt; and &lt;code&gt;[DataContract]&lt;/code&gt; attributes randomly scattered in the models used in &lt;code&gt;Get&lt;/code&gt; methods arguments.
Even though these attributes are not used for model binding from the query string, swagger takes them into account either way.
It happens basically because swagger under the hood uses &lt;code&gt;JsonObjectContract&lt;/code&gt; (even for &lt;code&gt;[FromUri]&lt;/code&gt; request classes) and by default it respects &lt;code&gt;[DataContract]&lt;/code&gt; attribute - more info can be found &lt;a href=&quot;http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size&quot;&gt;here&lt;/a&gt;.
Removing redundant &lt;code&gt;[DataContract]&lt;/code&gt; and &lt;code&gt;[DataMember]&lt;/code&gt; attributes from respective models solved the issue.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2018/04/asp-net-web-api-2-missing-swagger-query-parameters/FixedMissingParameter.png&quot;&gt;&lt;img src=&quot;images/FixedMissingParameter.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;PS. This particular corner case is not an issue for &lt;em&gt;ASP.NET Core&lt;/em&gt; swagger implementation.&lt;/p&gt;
</content:encoded></item><item><title>Solution-wide project properties with Directory.Build.props</title><link>https://tpodolak.com/blog/solution-wide-project-properties-directory-build-props/</link><guid isPermaLink="true">https://tpodolak.com/blog/solution-wide-project-properties-directory-build-props/</guid><pubDate>Tue, 03 Apr 2018 08:00:14 GMT</pubDate><content:encoded>&lt;h3&gt;1. Problem&lt;/h3&gt;
&lt;p&gt;When you work with a solution which contains multiple projects, you usually have some kind of convention which is applied to all of the projects.
For instance, in my case, I always make sure that &lt;code&gt;Stylecop.Analyzers&lt;/code&gt; package is installed and properly configured in every project.
In this particular case, this boils down to adding these lines into the &lt;code&gt;csproj&lt;/code&gt; file&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;PropertyGroup&amp;gt;
  &amp;lt;TreatWarningsAsErrors&amp;gt;True&amp;lt;/TreatWarningsAsErrors&amp;gt;
&amp;lt;/PropertyGroup&amp;gt;
&amp;lt;ItemGroup&amp;gt;
  &amp;lt;AdditionalFiles Include=&quot;..\StyleCop.json&quot; /&amp;gt;
&amp;lt;/ItemGroup&amp;gt;
&amp;lt;ItemGroup&amp;gt;
  &amp;lt;PackageReference Include=&quot;StyleCop.Analyzers&quot; Version=&quot;1.0.2&quot; /&amp;gt;
&amp;lt;/ItemGroup&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Unfortunately, you have to add these lines to every project in a solution in order to make the &lt;code&gt;Stylecop.Analyzers&lt;/code&gt; work for given project.
This might be fine if you create all of them up front, but in real life scenario sooner or later you will add a new project to the solution.
In that case, you might forget about adding those magic lines, so you will end up with inconsistent coding style in your repository.
An additional problem with this approach is a code duplication so in case you rename &lt;code&gt;StyleCop.json&lt;/code&gt; file you will have to make sure you update it everywhere.
A partial solution for that problem is a manual import of custom made &lt;code&gt;.props&lt;/code&gt; file, however, this approach is not perfect as well.
The import part is not automatic, that is why you still have to remember about adding import directive to all of your projects.&lt;/p&gt;
&lt;h3&gt;2. Solution&lt;/h3&gt;
&lt;p&gt;Fortunately starting form &lt;code&gt;MSBuild 15&lt;/code&gt; you can bypass the limitations mentioned above thanks to automatic imports of properties from &lt;code&gt;Directory.Build.props&lt;/code&gt; file.
All you have to do is to create a beforementioned file in the root folder of your solution and you are good to go. The properties defined in the &lt;code&gt;Directory.Build.props&lt;/code&gt; file will be automatically propagated to all of the child projects.
In my case, this file looks as follows&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Project&amp;gt;
  &amp;lt;PropertyGroup&amp;gt;
    &amp;lt;TreatWarningsAsErrors&amp;gt;True&amp;lt;/TreatWarningsAsErrors&amp;gt;
  &amp;lt;/PropertyGroup&amp;gt;
  &amp;lt;ItemGroup&amp;gt;
    &amp;lt;AdditionalFiles Include=&quot;..\StyleCop.json&quot; /&amp;gt;
  &amp;lt;/ItemGroup&amp;gt;
  &amp;lt;ItemGroup&amp;gt;
    &amp;lt;PackageReference Include=&quot;StyleCop.Analyzers&quot; Version=&quot;1.0.2&quot; /&amp;gt;
  &amp;lt;/ItemGroup&amp;gt;
&amp;lt;/Project&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The sample application which leverages this feature can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/SolutionWideProjectPropertiesWithDirectoryBuildProps&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>ASP.NET Core – custom ILogger&lt;T&gt; and Nlog callsite layout renderer issue</title><link>https://tpodolak.com/blog/asp-net-core-custom-iloggert-nlog-callsite-layout-renderer-issue/</link><guid isPermaLink="true">https://tpodolak.com/blog/asp-net-core-custom-iloggert-nlog-callsite-layout-renderer-issue/</guid><pubDate>Thu, 01 Mar 2018 08:00:34 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;In my current project, we use &lt;code&gt;Microsoft.Extensions.Logging.ILogger&amp;lt;T&amp;gt;&lt;/code&gt; default implementation as our logging mechanism.
This basically comes with the &lt;code&gt;ASP.NET Core 2.0&lt;/code&gt; package and it was working fine so far.
However recently we decided to switch the default implementation with a custom one, due to the fact that we wanted to have some additional logic applied for all of the logging providers.&lt;/p&gt;
&lt;h3&gt;2. Implementation&lt;/h3&gt;
&lt;p&gt;The custom implementation itself is very similar to the original one, we came up with something like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Logger&amp;lt;T&amp;gt; : ILogger&amp;lt;T&amp;gt;
{
    private readonly ILogger _logger;

    public Logger(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger&amp;lt;T&amp;gt;();
    }

    public void Log&amp;lt;TState&amp;gt;(LogLevel, EventId, TState state, Exception, Func&amp;lt;TState, Exception, string&amp;gt; formatter)
    {
        string Formatter(TState innserState, Exception innerException)
        {
            // additional logic goes here, in my case that was extracting additional information from custom exceptions
            var message = formatter(innserState, innerException) ?? string.Empty;
            return message + &quot; additional stuff in here&quot;;
        }

        _logger.Log(logLevel, eventId, state, exception, Formatter);
    }

    public bool IsEnabled(LogLevel logLevel)
    {
        return _logger.IsEnabled(logLevel);
    }

    public IDisposable BeginScope&amp;lt;TState&amp;gt;(TState state)
    {
        return _logger.BeginScope(state);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and we replaced the default logger with this code&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;services.Replace(new ServiceDescriptor(typeof(ILogger&amp;lt;&amp;gt;), typeof(Logger.Logger&amp;lt;&amp;gt;), ServiceLifetime.Singleton));
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see we basically wanted to add information from custom exceptions to the message.
Due to the fact that this is added in here, we don’t have to modify all of our existing logging providers.&lt;/p&gt;
&lt;h3&gt;3. &lt;code&gt;NLog&lt;/code&gt; call site renderer issue&lt;/h3&gt;
&lt;p&gt;Once we run the application all of the providers were working fine and were producing expected output apart from &lt;code&gt;NLog&lt;/code&gt; provider.
Originally &lt;code&gt;NLog&lt;/code&gt; provider for the following code&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Route(&quot;api/[controller]&quot;)]
public class ValuesController : Controller
{
    private readonly ILogger&amp;lt;ValuesController&amp;gt; _logger;

    public ValuesController(ILogger&amp;lt;ValuesController&amp;gt; logger)
    {
        _logger = logger;
    }

    [HttpGet]
    public IEnumerable&amp;lt;string&amp;gt; Get()
    {
        _logger.LogTrace(&quot;Get method called trace&quot;);
        _logger.LogWarning(&quot;Get method called warning&quot;);
        _logger.LogError(&quot;Get method called error&quot;);
        _logger.LogInformation(&quot;Get method called information&quot;);

        return new string[] {&quot;value1&quot;, &quot;value2&quot;};
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;was producing this output&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;TimeStamp=2018-02-28 20:14:37.2711 Callsite=AspNetCoreCustomLoggerAndNLogCallsiteIssue.Controllers.ValuesController.Get Level=TRACE Message=Get method called trace 
TimeStamp=2018-02-28 20:14:37.3261 Callsite=AspNetCoreCustomLoggerAndNLogCallsiteIssue.Controllers.ValuesController.Get Level=WARN Message=Get method called warning 
TimeStamp=2018-02-28 20:14:37.3261 Callsite=AspNetCoreCustomLoggerAndNLogCallsiteIssue.Controllers.ValuesController.Get Level=ERROR Message=Get method called error 
TimeStamp=2018-02-28 20:14:37.3261 Callsite=AspNetCoreCustomLoggerAndNLogCallsiteIssue.Controllers.ValuesController.Get Level=INFO Message=Get method called information 

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;However, after introducing new implementation of &lt;code&gt;ILogger&amp;lt;T&amp;gt;&lt;/code&gt;, it started appending wrong caller member name&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;TimeStamp=2018-02-28 20:17:27.4044 Callsite=AspNetCoreCustomLoggerAndNLogCallsiteIssue.Logger`1.Log Level=TRACE Message=Get method called trace additional stuff in here 
TimeStamp=2018-02-28 20:17:27.5117 Callsite=AspNetCoreCustomLoggerAndNLogCallsiteIssue.Logger`1.Log Level=WARN Message=Get method called warning additional stuff in here 
TimeStamp=2018-02-28 20:17:27.5117 Callsite=AspNetCoreCustomLoggerAndNLogCallsiteIssue.Logger`1.Log Level=ERROR Message=Get method called error additional stuff in here 
TimeStamp=2018-02-28 20:17:27.5202 Callsite=AspNetCoreCustomLoggerAndNLogCallsiteIssue.Logger`1.Log Level=INFO Message=Get method called information additional stuff in here 

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After some digging, it turned out that the issue lies in the (indirect)configuration of &lt;code&gt;NLog&apos;s&lt;/code&gt; &lt;a href=&quot;https://github.com/NLog/NLog/wiki/Callsite-layout-renderer&quot;&gt;callsite layout renderer&lt;/a&gt;.
Long story short, when you add &lt;code&gt;NLog&lt;/code&gt; provider to your logger providers, under the hood it adds &lt;code&gt;Microsoft.Extensions.Logging.Abstractions&lt;/code&gt; assembly(among others) to something called hidden assembly collection.
Once the &lt;code&gt;NLog&lt;/code&gt; tries to figure out what is the caller member name, it crawls the stack trace to find a method name.
If the method in current frame comes from a hidden assembly, logger skips it and continues iteration.
As we changed the &lt;code&gt;Logger&amp;lt;T&amp;gt;&lt;/code&gt; to our custom one, it is no longer part of &lt;code&gt;Microsoft.Extensions.Logging.Abstractions&lt;/code&gt; assembly, so the &lt;code&gt;NLog&lt;/code&gt; reports &lt;code&gt;Log&lt;/code&gt; method from our custom logger as a caller member name.&lt;/p&gt;
&lt;h3&gt;4. The fix&lt;/h3&gt;
&lt;p&gt;In order to restore previous behavior you have to add custom logger assembly to the hidden assembly collection. You can do it via&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;LogManager.AddHiddenAssembly(typeof(Logger.Logger&amp;lt;&amp;gt;).Assembly);

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Of course, if the logger is located in the same assembly as rest of your code, this might not be the perfect solution - as this will impact the way the callsite is rendered for other parts of your code in this assembly. In that case, you might consider moving the logging piece to separate assembly or resign from using callsite layout renderer at all. We decided to replace it with &lt;a href=&quot;https://github.com/NLog/NLog/wiki/Logger-Layout-Renderer&quot;&gt;logger layout renderer&lt;/a&gt; as callsite layout renderer, either way, wouldn’t be used in production environments.&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/AspNetCoreCustomLoggerAndNLogCallsiteIssue&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>ASP.NET Core - make sure IOptions&lt;T&gt; is initialized</title><link>https://tpodolak.com/blog/asp-net-core-make-sure-ioptionst-initialized/</link><guid isPermaLink="true">https://tpodolak.com/blog/asp-net-core-make-sure-ioptionst-initialized/</guid><pubDate>Mon, 29 Jan 2018 08:00:06 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;As most people know &lt;code&gt;IOptions&amp;lt;T&amp;gt;&lt;/code&gt; is a convenient way of handling configuration options in your application.
Even though I&apos;ve been using it for quite some time, last week I was unpleasantly surprised by a production bug caused by wrong usage of this mechanism.&lt;/p&gt;
&lt;h3&gt;2. Problem&lt;/h3&gt;
&lt;p&gt;Let&apos;s say we have a simple controller which depends on two instances of &lt;code&gt;IOptions&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Route(&quot;api/[controller]&quot;)]
public class ValuesController : Controller
{
    private readonly IOptions&amp;lt;PaymentOptions&amp;gt; _paymentOptions;
    private readonly IOptions&amp;lt;NotificationOptions&amp;gt; _notificationOptions;

    public ValuesController(IOptions&amp;lt;PaymentOptions&amp;gt; paymentOptions, IOptions&amp;lt;NotificationOptions&amp;gt; notificationOptions)
    {
        _paymentOptions = paymentOptions ?? throw new ArgumentNullException(nameof(paymentOptions));
        _notificationOptions = notificationOptions ?? throw new ArgumentNullException(nameof(notificationOptions));
    }

    // GET api/values
    [HttpGet]
    public IEnumerable&amp;lt;string&amp;gt; Get()
    {
        var notificationOptions = _notificationOptions.Value;
        var paymentOptions = _paymentOptions.Value;
            
        return new string[] {&quot;value1&quot;, &quot;value2&quot;};
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then we add only &lt;code&gt;IOptions&lt;/code&gt; in Startup class - &lt;code&gt;IOptions&amp;lt;PaymentOptoins&amp;gt;&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Startup
{
    // Rest of the code omitted for brevity
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddOptions();
        services.AddMvc();
        services.Configure&amp;lt;PaymentOptions&amp;gt;(Configuration.GetSection(&quot;PaymentOptions&quot;));
    }
      // Rest of the code omitted for brevity
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, when we run the app and hit one of the endpoints in &lt;code&gt;ValuesController&lt;/code&gt; I was expecting to get an exception, as I didn&apos;t register &lt;code&gt;IOptions&amp;lt;NotificationOptions&amp;gt;&lt;/code&gt;.
Surprisingly for me, the application was running normally and &lt;code&gt;IOptions&amp;lt;NotificationOptions&amp;gt;&lt;/code&gt; was created with the new instance of &lt;code&gt;NotificationOptions&lt;/code&gt; class(with all the properties defaulted).&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2018/01/asp-net-core-make-sure-your-ioptions-is-initialized/NotInitialized.png&quot;&gt;&lt;img src=&quot;images/NotInitialized.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In order to find out why it behaves like that we have to take a look how services responsible for handling &lt;code&gt;IOptions&amp;lt;T&amp;gt;&lt;/code&gt; are registered in the container.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static IServiceCollection AddOptions(this IServiceCollection services)
{
    if (services == null)
        throw new ArgumentNullException(nameof (services));

    services.TryAdd(ServiceDescriptor.Singleton(typeof (IOptions&amp;lt;&amp;gt;), typeof (OptionsManager&amp;lt;&amp;gt;)));
    services.TryAdd(ServiceDescriptor.Scoped(typeof (IOptionsSnapshot&amp;lt;&amp;gt;), typeof (OptionsManager&amp;lt;&amp;gt;)));
    services.TryAdd(ServiceDescriptor.Singleton(typeof (IOptionsMonitor&amp;lt;&amp;gt;), typeof (OptionsMonitor&amp;lt;&amp;gt;)));
    services.TryAdd(ServiceDescriptor.Transient(typeof (IOptionsFactory&amp;lt;&amp;gt;), typeof (OptionsFactory&amp;lt;&amp;gt;)));
    services.TryAdd(ServiceDescriptor.Singleton(typeof (IOptionsMonitorCache&amp;lt;&amp;gt;), typeof (OptionsCache&amp;lt;&amp;gt;)));
    return services;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see &lt;code&gt;AddOptions&lt;/code&gt; method registers open generics for (among others) &lt;code&gt;IOptions&amp;lt;&amp;gt;&lt;/code&gt; which means that you don’t have to register specific types of &lt;code&gt;IOptions&amp;lt;T&amp;gt;&lt;/code&gt;, however, you are responsible for its configuration with&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;services.Configure&amp;lt;T&amp;gt;(Configuration.GetSection(&quot;Section&quot;));
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I was always convinced that &lt;code&gt;services.Configure&lt;/code&gt; registers and configure &lt;code&gt;IOptions&amp;lt;T&amp;gt;&lt;/code&gt; but apparently, I was wrong.&lt;/p&gt;
&lt;h3&gt;3. Ensuring initialization&lt;/h3&gt;
&lt;p&gt;As these kind of errors are rather difficult to catch(at least in case of our application) I wanted to minimize the risk of doing the same bug again.
The idea was to make sure that at least one &lt;code&gt;IConfigureOptions&amp;lt;T&amp;gt;&lt;/code&gt; or &lt;code&gt;IPostConfigureOptions&amp;lt;T&amp;gt;&lt;/code&gt; service is registered in the container (as these are the services which are responsible for setting the values of &lt;code&gt;T&lt;/code&gt; class).
My first approach was to replace default &lt;code&gt;OptionsFactory&amp;lt;T&amp;gt;&lt;/code&gt; with a custom one&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class ValidatableOptionsFactory&amp;lt;TOptions&amp;gt; : OptionsFactory&amp;lt;TOptions&amp;gt; where TOptions : class, new()
{
    private static readonly string NamespacePrefix = typeof(Program).Namespace.Split(&apos;.&apos;).First();

    public ValidatableOptionsFactory(IEnumerable&amp;lt;IConfigureOptions&amp;lt;TOptions&amp;gt;&amp;gt; setups, IEnumerable&amp;lt;IPostConfigureOptions&amp;lt;TOptions&amp;gt;&amp;gt; postConfigures)
            : base(setups, postConfigures)
    {
        if (typeof(TOptions).Namespace.StartsWith(NamespacePrefix) &amp;amp;&amp;amp; setups.Any() == false &amp;amp;&amp;amp; postConfigures.Any() == false)
        {
            throw new InvalidOperationException($&quot;No configuration options or post configuration options was found to configure {typeof(TOptions)}&quot;);
        }
    }
}

public class Startup
{      
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient(typeof(IOptionsFactory&amp;lt;&amp;gt;), typeof(ValidatableOptionsFactory&amp;lt;&amp;gt;));
        services.AddOptions();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This method works fine (although probably needs smarter &lt;code&gt;TOptions&lt;/code&gt; filter)&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2018/01/asp-net-core-make-sure-your-ioptions-is-initialized/ValidatableOptionsFactory.png&quot;&gt;&lt;img src=&quot;images/ValidatableOptionsFactory.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;however I got to conclusion that there is no point to do validation in a runtime, and the integration test might be a better choice.
I came up with following code (I am assuming that all configuration options are stored in the same assembly, as this is convention in my project)&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class OptionsTests
{
    private readonly Lazy&amp;lt;IWebHost&amp;gt; _webHost = new Lazy&amp;lt;IWebHost&amp;gt;(Program.BuildWebHost(null));

    // this test will fail as not every option in assembly is configured
    [Fact]
    public void AllConfigurationOptions_HasConfigurationServicesDefined()
    {
        var optionsType = typeof(IOptions&amp;lt;&amp;gt;);
        var constructorParameterTypes = typeof(Program).Assembly.GetExportedTypes()
                .SelectMany(type =&amp;gt; type.GetConstructors().SelectMany(ctor =&amp;gt; ctor.GetParameters()))
                .Select(parameter =&amp;gt; parameter.ParameterType);

        var optionValueTypes = constructorParameterTypes.Where(parameterType =&amp;gt; IsAssignableToGenericType(parameterType, optionsType))
                .Select(options =&amp;gt; options.GetGenericArguments().Single())
                .Distinct();
            
        var postConfigureOptionsType = typeof(IPostConfigureOptions&amp;lt;&amp;gt;);
        var configureOptionsType = typeof(IConfigureOptions&amp;lt;&amp;gt;);

        var postConfiguration = optionValueTypes.Select(type =&amp;gt; new
        {
            optionsType = type,
            configureOptionsType = _webHost.Value.Services.GetServices(configureOptionsType.MakeGenericType(type)),
            postConfigureServices = _webHost.Value.Services.GetServices(postConfigureOptionsType.MakeGenericType(type))
        });

        var emptyConfigurations =
                postConfiguration.Where(item =&amp;gt; item.configureOptionsType.Any() == false &amp;amp;&amp;amp; item.postConfigureServices.Any() == false)
                    .Select(item =&amp;gt; item.optionsType);

        emptyConfigurations.Should().BeEmpty(&quot;All options should be configured&quot;);
    }

    // https://stackoverflow.com/questions/74616/how-to-detect-if-type-is-another-generic-type/1075059#1075059
    public static bool IsAssignableToGenericType(Type givenType, Type genericType)
    {
        var interfaceTypes = givenType.GetInterfaces();

        if (interfaceTypes.Any(it =&amp;gt; it.IsGenericType &amp;amp;&amp;amp; it.GetGenericTypeDefinition() == genericType))
        {
            return true;
        }

        if (givenType.IsGenericType &amp;amp;&amp;amp; givenType.GetGenericTypeDefinition() == genericType)
            return true;

        var baseType = givenType.BaseType;
        if (baseType == null) return false;

        return IsAssignableToGenericType(baseType, genericType);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Running the test shows that &lt;code&gt;NotificationOptions&lt;/code&gt; was not configured&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2018/01/asp-net-core-make-sure-your-ioptions-is-initialized/Test.png&quot;&gt;&lt;img src=&quot;images/Test.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/AspNetCoreMakeSureYouInitializedYourIOptionsOfT&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>ASP.NET Core - passing command-line arguments to Startup class</title><link>https://tpodolak.com/blog/asp-net-core-passing-command-line-arguments-startup-class/</link><guid isPermaLink="true">https://tpodolak.com/blog/asp-net-core-passing-command-line-arguments-startup-class/</guid><pubDate>Tue, 16 Jan 2018 09:00:24 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;I usually pass configuration to my web &lt;code&gt;API&lt;/code&gt; via &lt;code&gt;JSON&lt;/code&gt; files, but recently I needed to pass them also via command-line arguments.
As the solution for &lt;code&gt;ASP.NET Core 2.x&lt;/code&gt; is quite different than for &lt;code&gt;ASP.NET Core 1.x&lt;/code&gt; I decided to describe both methods in here.&lt;/p&gt;
&lt;h3&gt;2. ASP.NET Core 2.x&lt;/h3&gt;
&lt;p&gt;For the newest version of &lt;code&gt;ASP.NET Core&lt;/code&gt;, the solution is pretty straightforward as &lt;code&gt;IConfiguration&lt;/code&gt; is injected by default to the &lt;code&gt;Startup&lt;/code&gt; class.
All we have to do is to add &lt;code&gt;CommandLineConfigurationSource&lt;/code&gt; to &lt;code&gt;IConfigurationBuilder&lt;/code&gt; when configuring &lt;code&gt;IWebHost&lt;/code&gt;.
&lt;code&gt;CommandLineConfigurationSource&lt;/code&gt; is part of the &lt;code&gt;Microsoft.Extensions.Configuration.CommandLine&lt;/code&gt; package and can be easily used by &lt;code&gt;AddCommandLine&lt;/code&gt; extension method&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }
	
    public static IWebHost BuildWebHost(string[] args)
    {
        var webHost = new WebHostBuilder()
	     .UseKestrel()
	     .UseContentRoot(Directory.GetCurrentDirectory())
	     .ConfigureAppConfiguration((hostingContext, config) =&amp;gt;
	     {
	         var env = hostingContext.HostingEnvironment;
	         config.AddJsonFile(&quot;appsettings.json&quot;, optional: true, reloadOnChange: true)
	               .AddJsonFile($&quot;appsettings.{env.EnvironmentName}.json&quot;, optional: true, reloadOnChange: true);
	         config.AddEnvironmentVariables();
	         config.AddCommandLine(args);
	     }).UseStartup&amp;lt;Startup&amp;gt;()
	       .Build();
        return webHost;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we can access our command-line arguments just like any other configuration&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Startup
{
    private readonly IConfiguration _configuration;

    public Startup(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime)
    {
        loggerFactory.AddConsole();
        loggerFactory.AddDebug();
        applicationLifetime.ApplicationStarted.Register(() =&amp;gt; loggerFactory.CreateLogger&amp;lt;Startup&amp;gt;().LogInformation(&quot;CommandLine argument {0}: &quot;, _configuration[&quot;usecustomschema&quot;]));
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2018/01/asp-net-core-passing-command-line-arguments-to-startup-class/AspNetCore2CommandLineArgument-1.png&quot;&gt;&lt;img src=&quot;images/AspNetCore2CommandLineArgument-1.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;3. ASP.NET Core 1.x&lt;/h3&gt;
&lt;p&gt;The solution for &lt;code&gt;ASP.NET Core 1.x&lt;/code&gt; requires a bit more work but it is possible to achieve the same result. We still will be using &lt;code&gt;CommandLineConfigurationSource&lt;/code&gt; from &lt;code&gt;Microsoft.Extensions.Configuration.CommandLine&lt;/code&gt; package, however this time we have to manually create &lt;code&gt;IConfiguration&lt;/code&gt; object and register it in the container before the &lt;code&gt;Startup&lt;/code&gt; class is created. This is possible because the &lt;code&gt;WebHostBuilder&lt;/code&gt; exposes &lt;code&gt;ConfigureServices&lt;/code&gt; method.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
             .UseKestrel()
             .UseContentRoot(Directory.GetCurrentDirectory())
             UseIISIntegration()
             .ConfigureServices(serviceCollection =&amp;gt;
                 serviceCollection.AddSingleton&amp;lt;IConfiguration&amp;gt;(new ConfigurationBuilder().AddCommandLine(args).Build()))
             .UseStartup&amp;lt;Startup&amp;gt;()
             .Build();

          host.Run();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Having our service registered now we can easily access &lt;code&gt;IConfiguration&lt;/code&gt; object in our application&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment hostingEnvironment, IConfiguration configuration, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime)
    {
        loggerFactory.AddConsole();
        loggerFactory.AddDebug();
        applicationLifetime.ApplicationStarted.Register(() =&amp;gt;
                loggerFactory.CreateLogger&amp;lt;Startup&amp;gt;().LogInformation(&quot;CommandLine argument {0}: &quot;, configuration[&quot;usecustomschema&quot;]));

        if (hostingEnvironment.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2018/01/asp-net-core-passing-command-line-arguments-to-startup-class/AspNetCoreCommandLineArgument-1.png&quot;&gt;&lt;img src=&quot;images/AspNetCoreCommandLineArgument-1.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/AspNetCorePassingCommandLineArgumentsToStartupClass&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>ASP.NET Core - retrieving swagger specification without hosting API</title><link>https://tpodolak.com/blog/asp-net-core-retrieving-swagger-specification-without-hosting-api/</link><guid isPermaLink="true">https://tpodolak.com/blog/asp-net-core-retrieving-swagger-specification-without-hosting-api/</guid><pubDate>Mon, 08 Jan 2018 08:00:19 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;I am currently exploring possible ways of removing a repetitive work when it comes to creating integration tests for our &lt;code&gt;API&lt;/code&gt;.
The one thing which usually takes some time when testing a new endpoint is a process of creating response and request classes (as we don&apos;t share the models between API project and integration test project).
That is why I would like to have some kind of a tool (&lt;code&gt;AutoRest&lt;/code&gt; or &lt;code&gt;NSwag&lt;/code&gt;) which would do it for us (possibly, in a prebuild step).
As those tools generate &lt;code&gt;API&lt;/code&gt; clients based on swagger specification and I wanted this process to be as fast as possible I decided to figure out the way how to retrieve swagger specs without hosting the &lt;code&gt;API&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;2. Implementation&lt;/h3&gt;
&lt;p&gt;After taking a look at &lt;code&gt;Swashbuckle.AspNetCore.Swagger&lt;/code&gt; source code it turned out that &lt;code&gt;Swashbuckle.AspNetCore.Swagger.ISwaggerProvider&lt;/code&gt; is responsible for creating a &lt;code&gt;SwaggerDocument&lt;/code&gt; class.
&lt;code&gt;JSON&lt;/code&gt; representation of that class is a swagger specification.
Having all of that in mind I wrote following piece of code.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class SchemaRetriever
{
    private readonly Lazy&amp;lt;IWebHost&amp;gt; _webHostProxy = new Lazy&amp;lt;IWebHost&amp;gt;(() =&amp;gt; Program.BuildWebHost(new string[0]));

    private IWebHost WebHost =&amp;gt; _webHostProxy.Value;
        
    public string RetrieveSchema(string swaggerDocument)
    {
        using (var scope = WebHost.Services.CreateScope())
        {
            var serviceProvider = scope.ServiceProvider;
            var swaggerProvider = serviceProvider.GetRequiredService&amp;lt;ISwaggerProvider&amp;gt;();
            var mvcJsonOptions = serviceProvider.GetRequiredService&amp;lt;IOptions&amp;lt;MvcJsonOptions&amp;gt;&amp;gt;();
            var document = swaggerProvider.GetSwagger(swaggerDocument, null, &quot;/&quot;);

            var serializer = new JsonSerializer
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    Formatting = mvcJsonOptions.Value.SerializerSettings.Formatting,
                    ContractResolver = new SwaggerContractResolver(mvcJsonOptions.Value.SerializerSettings)
                };

            using (var stringWriter = new StringWriter())
            {
                serializer.Serialize(stringWriter, document);
                return stringWriter.ToString();
            }   
        }
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =&amp;gt;
            WebHost.CreateDefaultBuilder(args)
                .UseStartup&amp;lt;Startup&amp;gt;()
                .Build();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;Program&lt;/code&gt; class is an entry point of the &lt;code&gt;API&lt;/code&gt;. The only one difference compared to default &lt;code&gt;ASP.NET Core&lt;/code&gt; template is the fact that I made the &lt;code&gt;BuildWebHost&lt;/code&gt; method public.
Thanks to that we can build the host (but without running) and get our hands on the &lt;code&gt;DI&lt;/code&gt; container of our application.
From that point the rest is easy, I retrieve the &lt;code&gt;ISwaggerProvider&lt;/code&gt; from the container so I can get the swagger document for given id.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2018/01/asp-net-core-retrieving-swagger-specification-without-hosting-api/TestWithoutHosting.png&quot;&gt;&lt;img src=&quot;images/TestWithoutHosting.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In order to make sure that the &lt;code&gt;SchemaRetriever&lt;/code&gt; works as expected I wrote simple integration test which makes sure that swagger specs from hosted &lt;code&gt;API&lt;/code&gt; is the same as the one retrieved without hosting.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Fact]
public async Task RetrieveSchema_RetrievesSwaggerSchema_SameAsDeployedSchema()
{
    var swaggerSchemaWithoutHosting = _subject.RetrieveSchema(_swaggerDocumentName);
    using (var testServer = new TestServer(new WebHostBuilder().UseStartup&amp;lt;Startup&amp;gt;()))
    {
        using (var httpClient = testServer.CreateClient())
        {
            var response = await httpClient.GetAsync($&quot;swagger/{EscapeDataString(_swaggerDocumentName)}/swagger.json&quot;);
            response.EnsureSuccessStatusCode();
            var content = await response.Content.ReadAsStringAsync();

            swaggerSchemaWithoutHosting.Should().Be(content);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2018/01/asp-net-core-retrieving-swagger-specification-without-hosting-api/IntegrationTest.png&quot;&gt;&lt;img src=&quot;images/IntegrationTest.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/AspNetCoreManuallyRetrieveSwaggerSchema&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Null-propagation operator and conditional statements</title><link>https://tpodolak.com/blog/null-propagation-operator-conditional-statements/</link><guid isPermaLink="true">https://tpodolak.com/blog/null-propagation-operator-conditional-statements/</guid><pubDate>Sun, 17 Dec 2017 15:23:23 GMT</pubDate><content:encoded>&lt;p&gt;This post is just a quick reminder for me to put a bit more attention to conditional statements combined with a null-propagation operator. Nothing too fancy but I tend to overlook this when doing code review. Starting from C# 6 we can simplify accessing members of an object which might be &lt;code&gt;null&lt;/code&gt; thanks to &lt;code&gt;?.&lt;/code&gt; operator. For my perspective it is particularly useful within &lt;code&gt;if&lt;/code&gt; statements, however, you have to be aware of how compiler rewrites the code under the hood otherwise, it is easy to introduce a bug. Consider following scenario&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public Flight GetFirstPossibleFlight(Availability availability)
{
    if (availability.Flights?.Any() == false)
    {
       return null;
    }
            
    // more magic in here
     return availability.Flights.First();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;At a glance everything seems to be ok, we make sure that &lt;code&gt;Flight&lt;/code&gt; collection is not accessed if it is &lt;code&gt;null&lt;/code&gt;, however simple test shows that this method has a bug.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Fact]
public void GetFirstPossibleFlight_ReturnsNull_WhenFlightsCollectionIsEmpty()
{
    var availability = new Availability
    {
        Flights = null
    };
            
    var subject = new AvailabilityScanner();

    var result = subject.GetFirstPossibleFlight(availability);

    result.Should().BeNull();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-2/debugger.jpg&quot;&gt;&lt;img src=&quot;images/FailedTest.png&quot; alt=&quot;debugger&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;We protected the code from &lt;code&gt;NullReferenceException&lt;/code&gt; in if statement, however we failed on the return statement.
This happens because our original code is rewritten by compiler as &lt;a href=&quot;https://sharplab.io/#v2:CYLg1APgAgDABFAjAFgNwFgBQsGIHQAyAlgHYCOG2AzAgExwCCAbgIZEA2LARh0QC4BPAMoBjFiRIBTAE5YA3ljhKENAGLsiAcwAWfOAHFJfVUWkBnPgAUA9mbNEu7Seq26AFMzaceGwXBasHNy8ggCUisoKmMoxcEQAZnBuAV7BvgJ4Ljp8ZgD8eAwkAm6hcAC8ZXDxLOxmkuHRsUpRTU1QAOxwJACu7OyUrXAAvhGDSqNjAPSTcAC21tKScyyaRCJxJHDaMpITMR3+gd4hGVm6ZpmmFiUDyiOY91hQNFD0Z3zyWI/UdIxHafwBJ9GkpnnBiBYADzvAB8cHeZjgcjgmiMqDgdT46PuQyAA=&quot;&gt;follows&lt;/a&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public Flight GetFirstPossibleFlight(Availability availability)
{
    List&amp;lt;Flight&amp;gt; expr_07 = availability.Flights;
    bool flag = expr_07 != null &amp;amp;&amp;amp; !expr_07.Any&amp;lt;Flight&amp;gt;();
    Flight result;
    if (flag)
    {
        result = null;
    }
    else
    {
        result = availability.Flights.First&amp;lt;Flight&amp;gt;();
    }
    return result;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now it is clearly visible that we have to satisfy both of the conditions in order to return &lt;code&gt;null&lt;/code&gt;.
Fortunately, you still can use one-liner and have a bug-free code, the one thing which is needed is an additional null-coalescing operator in the if statement.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public Flight GetFirstPossibleFlight(Availability availability)
{            
    if ((availability.Flights?.Any() ?? false) == false)
    {
        return null;
    }
            
    // more magic in here
    return availability.Flights.First();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now the compiler will rewrite the code in a &lt;a href=&quot;https://sharplab.io/#v2:CYLg1APgAgDABFAjAFgNwFgBQsGIHQAyAlgHYCOG2AzAgExwCCAbgIZEA2LARh0QC4BPAMoBjFiRIBTAE5YA3ljhKENAGLsiAcwAWfOAHFJfVUWkBnPgAUA9mbNEu7Seq26AFMzaceGwXBasHNy8ggCUisoKmMoxcEQAZnBubgFewb4CeC46fGYA/HgMJAJuoXB5eXDxLOxmkmUAvA1VNXXh0bGdUZ09ylAA7HAkAK7s7JS9MQC+EZNws5MA9ItwALbW0pJrLJpEInEkcNoykgu9A/6B3iGZ2bpmWaYWpRPKM5jvWFA0UPR3fPIsJ9qHRGFd0vwBICOkpvnBiBYADz/AB8cH+ZjgcjgmiMqDgdT4+PeUyAA=&quot;&gt;following way&lt;/a&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public Flight GetFirstPossibleFlight(Availability availability)
{
    List&amp;lt;Flight&amp;gt; expr_07 = availability.Flights;
    bool flag = expr_07 == null || !expr_07.Any&amp;lt;Flight&amp;gt;();
    Flight result;
    if (flag)
    {
        result = null;
    }
    else
    {
        result = availability.Flights.First&amp;lt;Flight&amp;gt;();
    }
    return result;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Notice that &lt;code&gt;AND&lt;/code&gt; operator was replaced with &lt;code&gt;OR&lt;/code&gt; operator, resulting in code safe from &lt;code&gt;NullReferenceException&lt;/code&gt;.
Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/NullPropagationOperatorAndIfStatements&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>ASP.NET Core MemoryCache - GetOrCreate calls factory method multiple times</title><link>https://tpodolak.com/blog/asp-net-core-memorycache-getorcreate-calls-factory-method-multiple-times/</link><guid isPermaLink="true">https://tpodolak.com/blog/asp-net-core-memorycache-getorcreate-calls-factory-method-multiple-times/</guid><pubDate>Wed, 13 Dec 2017 21:57:20 GMT</pubDate><content:encoded>&lt;p&gt;Recently I&apos;ve been trying to locate a performance issue in our application.
Stress tests have shown an excessive usage of memory combined with too many external server requests.
As usual in such cases, I&apos;ve run the profiler and after a bit of searching, I&apos;ve noticed that issue is connected with our caching mechanism.
The problematic part was a factory delegate (responsible for populating cache, if the cache for given key is empty) which was called multiple times when concurrent requests were sent.
That was a bit surprising to me as we basically were using a very naïve wrapper over &lt;code&gt;ASP.NET Core MemoryCache&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class CacheService : ICacheService
{
    private readonly IMemoryCache _memoryCache;

    public CacheService(IMemoryCache memoryCache)
    {
        _memoryCache = memoryCache ?? throw new ArgumentNullException(nameof(memoryCache));
    }

    public T GetOrAdd&amp;lt;T&amp;gt;(string cacheKey, Func&amp;lt;T&amp;gt; factory, DateTime absoluteExpiration)
    {
        return _memoryCache.GetOrCreate(cacheKey, entry =&amp;gt;
        {
            entry.AbsoluteExpiration = absoluteExpiration;
            return factory();
        });
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;However simple test proved that this was an actual issue&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Fact]
public void GetOrAdd_CallsFactoryMethodOnce()
{
    var factoryMock = Substitute.For&amp;lt;Func&amp;lt;string&amp;gt;&amp;gt;();
    var optionsMock = Substitute.For&amp;lt;IOptions&amp;lt;MemoryCacheOptions&amp;gt;&amp;gt;();
    optionsMock.Value.Returns(callInfo =&amp;gt; new MemoryCacheOptions());
    var memoryCache = new MemoryCache(optionsMock);

    var subject = new CacheService(memoryCache);

    var threads = Enumerable.Range(0, 10).Select(_ =&amp;gt; new Thread(() =&amp;gt; subject.GetOrAdd(&quot;key&quot;, factoryMock, DateTime.MaxValue))).ToList();
            
    threads.ForEach(thread =&amp;gt; thread.Start());
    threads.ForEach(thread =&amp;gt; thread.Join());

    factoryMock.Received(1)();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/12/asp-net-core-memorycache-getorcreate-calls-factory-method-multiple-times/FailedTest.png&quot;&gt;&lt;img src=&quot;images/FailedTest.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;After doing a bit of a digging it turned out that this was by-design behavior, which is documented in the very end of official &lt;a&gt;documentation&lt;/a&gt; . However, as this behavior wasn&apos;t the one we were expecting, we decided to reduce amount of factory calls by applying custom logic. We had couple of ideas when it comes to implementation, including:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Exclusive lock over factory method&lt;/li&gt;
&lt;li&gt;Lock per key&lt;/li&gt;
&lt;li&gt;Lock per type&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;After discussion we decided to go with third option, mainly because we didn&apos;t want to over-complicate the design, plus we wanted to allow concurrent factory method calls for different types of objects. Once &lt;code&gt;CacheService&lt;/code&gt; was updated with following code&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class CacheService: ICacheService
{
    private readonly IMemoryCache _memoryCache;

    public CacheService(IMemoryCache memoryCache)
    {
        _memoryCache = memoryCache ?? throw new ArgumentNullException(nameof(memoryCache));
    }

    public T GetOrAdd&amp;lt;T&amp;gt;(string cacheKey, Func&amp;lt;T&amp;gt; factory, DateTime absoluteExpiration)
    {
        // locks get and set internally
        if (_memoryCache.TryGetValue&amp;lt;T&amp;gt;(cacheKey, out var result))
        {
            return result;
        }

        lock (TypeLock&amp;lt;T&amp;gt;.Lock)
        {
            if (_memoryCache.TryGetValue(cacheKey, out result))
            {
                return result;
            }

            result = factory();
            _memoryCache.Set(cacheKey, result, absoluteExpiration);

            return result;
         }
    }    

    private static class TypeLock&amp;lt;T&amp;gt;
    {
        public static object Lock { get; } = new object();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;we stoped experiencing excessive memory usage.&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/AspNetCoreMemoryCacheIsPopulatedMultipleTimes&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Finding typos with ReSharper Command Line Tools, ReSpeller and Cake</title><link>https://tpodolak.com/blog/finding-typos-resharper-command-line-tools-respeller-cake/</link><guid isPermaLink="true">https://tpodolak.com/blog/finding-typos-resharper-command-line-tools-respeller-cake/</guid><pubDate>Fri, 27 Oct 2017 08:06:04 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;I tend to do a lot of typos when I write a code and I mean a lot.
This is quite annoying for me so I decided to somehow automate the process of finding the spelling errors during the build.
My first thought was to use some kind of Roslyn analyzer, however, I failed to find any working one.
This is why I decided to give a try to &lt;a href=&quot;https://www.jetbrains.com/help/resharper/ReSharper%60Command%60Line%60Tools.html&quot;&gt;ReSharper Command Line Tools&lt;/a&gt; (also known as &lt;code&gt;CLIT&lt;/code&gt;) combined with &lt;code&gt;ReSpeller&lt;/code&gt; plugin.
For those who don&apos;t know, &lt;code&gt;ReSharper Command Line Tools&lt;/code&gt; is set of tools which allow you to use &lt;code&gt;ReSharper&lt;/code&gt; inspections without &lt;code&gt;Visual Studio&lt;/code&gt;&lt;/p&gt;
&lt;h3&gt;2. First attempt&lt;/h3&gt;
&lt;p&gt;This was supposed to be a rather straightforward task because according to &lt;a href=&quot;https://www.jetbrains.com/help/resharper/InspectCode.html&quot;&gt;documentation&lt;/a&gt; command line inspections support extensions out of the box. The example presented in the help page was supposed to be the perfect one for me&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;InspectCode.exe --project=Documents -o=&quot;OutputFile.xml&quot; --no-swea -x=EtherealCode.ReSpeller &quot;SolutionFile.sln&quot;

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Unfortunately, it turned out that extensions support is broken for &lt;a href=&quot;https://youtrack.jetbrains.com/issue/RSRP-436208#comment=27-1078217&quot;&gt;some time&lt;/a&gt; and it wasn&apos;t working for me either (tested on &lt;code&gt;Command Line Tools&lt;/code&gt; version &lt;code&gt;2017.2&lt;/code&gt;).&lt;/p&gt;
&lt;h3&gt;3. The workaround&lt;/h3&gt;
&lt;p&gt;Even though extension support is not working as expected I was able to make it work with some workaround.
The workaround itself is a combination of helpful tips taken from this &lt;a href=&quot;https://youtrack.jetbrains.com/issue/RSRP-436208#comment=27-1078217&quot;&gt;YouTrack&lt;/a&gt; issue.
Long story short, we have to manually install the plugin and then force &lt;code&gt;ReSharper&lt;/code&gt; to use it.
Assuming that you have command line tools installed this can be achieved in following way.
First of all we have to get our hands on &lt;code&gt;ReSpeller&lt;/code&gt; plugin. We can install it using &lt;code&gt;NuGet&lt;/code&gt; but before you do it, remember to add additional feed to &lt;code&gt;nuget.config&lt;/code&gt; file.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;nuget sources add -name JetBrains-Feed -source https://resharper-plugins.jetbrains.com/api/v2/curated-feeds/Wave_v9.0/

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The feed url can be found in the &lt;code&gt;ReSharper&apos;s&lt;/code&gt; option page and for version 2017.2 it is&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/10/finding-typos-with-resharper-command-line-tools-respeller-and-cake/ReSharperNuGetFeed.png&quot;&gt;&lt;img src=&quot;images/ReSharperNuGetFeed.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Having our &lt;code&gt;NuGet&lt;/code&gt; sources updated we can retrieve the package using following command&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;nuget install &quot;EtherealCode.ReSpeller&quot; -Version &quot;4.6.9.2&quot;

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The next step is to copy &lt;code&gt;ReSpeller&apos;s&lt;/code&gt; &lt;code&gt;DLLs&lt;/code&gt; from following folders&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;etherealcode.respeller.4.6.9.2\EtherealCode.ReSpeller\lib\net45\
etherealcode.respeller.4.6.9.2\Extended.Wpf.Toolkit\lib\net40\
etherealcode.respeller.4.6.9.2\NHunspell\lib\net\

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;directly to &lt;code&gt;CLIT&lt;/code&gt; tools folder - &lt;code&gt;JetBrains.ReSharper.CommandLineTools\tools&lt;/code&gt;. What is more, &lt;code&gt;ReSpeller&lt;/code&gt; comes together with dictionary files which also have to be copied to the tools folder.
This time, however, we have to copy entire &lt;code&gt;etherealcode.respeller.4.6.9.2\EtherealCode.ReSpeller\lib\net45\dic&lt;/code&gt; directory, not only its content.
The very last thing is to make &lt;code&gt;ReSharper&lt;/code&gt; aware of the plugin, in order to do that we have to find &lt;code&gt;EtherealCode.ReSpeller.JetMetadata.sstg&lt;/code&gt; file.
The file itself doesn’t come together with the package but it is generated by &lt;code&gt;ReSharper&lt;/code&gt; during plugin installation.
So the easiest way of getting that file is to install &lt;code&gt;ReSpeller&lt;/code&gt; as a &lt;code&gt;ReSharper&lt;/code&gt; plugin in &lt;code&gt;Visual Studio&lt;/code&gt; and then copy the &lt;code&gt;sstg&lt;/code&gt; file to tools folder.
After all that work now if you run&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;InspectCode.exe --project=Documents -o=&quot;OutputFile.xml&quot; --no-swea -x=EtherealCode.ReSpeller &quot;SolutionFile.sln&quot;

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;(note lack of &lt;code&gt;\-x&lt;/code&gt; switch) you will see spellcheck inspections in output file.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/10/finding-typos-with-resharper-command-line-tools-respeller-and-cake/OutputXml.png&quot;&gt;&lt;img src=&quot;images/OutputXml.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;4. Cake integration&lt;/h3&gt;
&lt;p&gt;Doing all that stuff manually is error-prone and time-consuming and of course, I wanted to have the spellcheck up and running on the CI server, that is why I&apos;ve also automated all above steps with &lt;code&gt;Cake&lt;/code&gt; build script. The core concept is to use &lt;code&gt;ReSpeller&lt;/code&gt; and &lt;code&gt;ReSharper Command Line Tools&lt;/code&gt; as so-called &quot;Cake tools&quot; to run the inspections and &lt;code&gt;Cake.Issues&lt;/code&gt; and &lt;code&gt;Cake.Issues.InspectCode&lt;/code&gt; plugins for analyzing the output file. Adding tools and add-ins is straightforward we just have to add following lines on top of the build file.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#tool &quot;nuget:?package=EtherealCode.ReSpeller&amp;amp;version=4.6.9.2&quot;
#tool &quot;nuget:?package=JetBrains.ReSharper.CommandLineTools&amp;amp;version=2017.2.2&quot;
#addin &quot;Cake.Issues&quot;
#addin &quot;Cake.Issues.InspectCode&quot;

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We also have to add &lt;code&gt;nuget.config&lt;/code&gt; file to our build directory in order to point &lt;code&gt;Cake&lt;/code&gt; to &lt;code&gt;ReSharper&lt;/code&gt; feed (you could also modify the global &lt;code&gt;nuget.config&lt;/code&gt; but I don’t want a build process to change the behavior of entire system)&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;configuration&amp;gt;
    &amp;lt;packageSources&amp;gt;
      &amp;lt;add key=&quot;nuget.org&quot; value=&quot;https://api.nuget.org/v3/index.json&quot; protocolVersion=&quot;3&quot; /&amp;gt;
      &amp;lt;add key=&quot;resharper-plugins&quot; value=&quot;https://resharper-plugins.jetbrains.com/api/v2/curated-feeds/Wave_v9.0/&quot; protocolVersion=&quot;2&quot; /&amp;gt;
    &amp;lt;/packageSources&amp;gt;
&amp;lt;/configuration&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Before calling &lt;code&gt;InspectCode.exe&lt;/code&gt; we have to make sure that all of the files and folders exist&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var destinationPath = &quot;tools/jetbrains.resharper.commandlinetools.2017.2.2/JetBrains.ReSharper.CommandLineTools/tools&quot;;
Setup(context =&amp;gt;
{
    if(!DirectoryExists(&quot;.artifacts&quot;))
    {
        CreateDirectory(&quot;.artifacts&quot;);
    }

    if(!DirectoryExists(destinationPath + &quot;/dic&quot;))
    {
        CreateDirectory(destinationPath + &quot;/dic&quot;);
    }
});
	
Task(&quot;Prepare-Respeller&quot;)
.Does(()=&amp;gt;
{
    // works for pinned version of ReSpeller
    var destinationPath = &quot;tools/jetbrains.resharper.commandlinetools.2017.2.2/JetBrains.ReSharper.CommandLineTools/tools&quot;;
    CopyFiles(&quot;tools/etherealcode.respeller.4.6.9.2/EtherealCode.ReSpeller/lib/net45/*.dll&quot;, destinationPath);
    CopyFiles(&quot;tools/etherealcode.respeller.4.6.9.2/Extended.Wpf.Toolkit/lib/net40/*.dll&quot;, destinationPath);
    CopyFiles(&quot;tools/etherealcode.respeller.4.6.9.2/NHunspell/lib/net/*.dll&quot;, destinationPath);
    CopyFiles(&quot;../Spelling/*.dic&quot;,  destinationPath + &quot;/dic&quot;);
    CopyFiles(&quot;../Spelling/*.aff&quot;,  destinationPath + &quot;/dic&quot;); // using shared dictionaries not the ReSpeller ones
    CopyFiles(&quot;EtherealCode.ReSpeller.JetMetadata.sstg&quot;, destinationPath);
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Having all of the items in place now we are ready to run the actual spellcheck and verify the results&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Task(&quot;Run-SpellCheck&quot;)
.IsDependentOn(&quot;Prepare-Respeller&quot;)
.Does(() =&amp;gt;
{
    var processArgumentBuilder = new ProcessArgumentBuilder().AppendSwitch(&quot;--profile&quot;,&quot;=&quot;,&quot;../Spelling/Resharper.ReSpeller.DotSettings&quot;)
                                          .AppendSwitch(&quot;--caches-home&quot;,&quot;=&quot;,&quot;tools&quot;)
                                          .AppendSwitch(&quot;-o&quot;,&quot;=&quot;,&quot;../.artifacts/inspectcode.xml&quot;)
                                          .Append(&quot;../ResharperCommandLineInspections.sln&quot;);

    var processSettings = new ProcessSettings 
    {
        Arguments = processArgumentBuilder,
        Silent = true,
        RedirectStandardOutput = true
    };

    IEnumerable&amp;lt;string&amp;gt; redirectedOutput, redirectedErrors;

    var exitCode = StartProcess(Context.Tools.Resolve(&quot;inspectcode.exe&quot;), processSettings, out redirectedOutput, out redirectedErrors);
    if(exitCode !=0)
    {
        throw new CakeException($&quot;InspectCode exited with unexpected error code: {exitCode}&quot;);
    }

    var issues = ReadIssues(InspectCodeIssuesFromFilePath(&quot;../.artifacts/inspectcode.xml&quot;), &quot;../&quot;);
    var spellingIssues = issues.Where(issue =&amp;gt; issue.Rule.Contains(&quot;Typo&quot;)).ToList();

    if(spellingIssues.Any())
    {
        var errorMessage = spellingIssues.Aggregate(new StringBuilder(), (stringBuilder, issue) =&amp;gt; stringBuilder.AppendFormat(&quot;FileName: {0} Line: {1} Message: {2}{3}&quot;, issue.AffectedFileRelativePath, issue.Line, issue.Message, Environment.NewLine));
        throw new CakeException($&quot;{spellingIssues.Count} spelling errors detected: {Environment.NewLine}{errorMessage}please fix them or add missing words to the dictionary.&quot;);
    }
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see I start &lt;code&gt;InspectCode.exe&lt;/code&gt; process with a bunch of parameters.
Once the process returns successful exit code I can go ahead and process the results thanks to &lt;code&gt;ReadIssues&lt;/code&gt; and &lt;code&gt;InspectCodeIssuesFromFilePath&lt;/code&gt; methods provided by the add-ins.
Because of the fact that &lt;code&gt;ReSharper&lt;/code&gt; can produce a ton of inspections I only care about the ones which are typos.
Simple and very naïve &lt;code&gt;LINQ&lt;/code&gt; query can do it for me&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var spellingIssues = issues.Where(issue =&amp;gt; issue.Rule.Contains(&quot;Typo&quot;)).ToList();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If any typos were found I just throw exception with a listing of all the issues.
Note that I aggregate all the issues into one big message because if you have lots of typos (just like I do) rendering them can take some time&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/10/finding-typos-with-resharper-command-line-tools-respeller-and-cake/Errors.png&quot;&gt;&lt;img src=&quot;images/Errors.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The source code for slightly enhanced version of that script can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/R%23CLIInspections&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>ASP.NET Core 1.x - curios case of missing IOptions&lt;T&gt; array item</title><link>https://tpodolak.com/blog/asp-net-core-1-x-curios-case-missing-ioptionst-array-item/</link><guid isPermaLink="true">https://tpodolak.com/blog/asp-net-core-1-x-curios-case-missing-ioptionst-array-item/</guid><pubDate>Tue, 17 Oct 2017 08:00:08 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;Last week while I was working on one of the features for my current project, I noticed quite surprising behavior of &lt;code&gt;IOptions&amp;lt;T&amp;gt;&lt;/code&gt; object.
Long story short, for some reasons there were missing array elements in my parsed application settings class.&lt;/p&gt;
&lt;h3&gt;2. Problem&lt;/h3&gt;
&lt;p&gt;Just like everyone else, we store our application settings in &lt;code&gt;JSON&lt;/code&gt; file.
The settings are pretty straightforward, just a bunch of properties with some nested objects&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
    &quot;PaymentMethods&quot;: [
        {
            &quot;Name&quot;: &quot;MasterCard&quot;,
            &quot;ExcludedCurrencies&quot;: []
        },
        {
            &quot;Name&quot;: &quot;Visa&quot;,
            &quot;ExcludedCurrencies&quot;: null
        },
        {
            &quot;Name&quot;: &quot;Apple Pay&quot;
        },
        {
            &quot;Name&quot;: &quot;PayPal&quot;,
            &quot;ExcludedCurrencies&quot;: [
                &quot;MAD&quot;
            ]
        }
    ]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;which are bound to the &lt;code&gt;AppSetting&lt;/code&gt; class thanks to these couple of lines of code&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{            
    services.Configure&amp;lt;AppSettings&amp;gt;(Configuration);
    // Add framework services.
    services.AddMvc();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;where &lt;code&gt;AppSettings&lt;/code&gt; class looks as follows&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class AppSettings
{
    public List&amp;lt;PaymentMethod&amp;gt; PaymentMethods { get; set; }
}

public class PaymentMethod
{
    public string Name { get; set; }

    public List&amp;lt;string&amp;gt; ExcludedCurrencies { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see nothing too fancy in here, standard &lt;code&gt;ASP.NET Core&lt;/code&gt; approach for handling configuration files.
However, if you access the &lt;code&gt;PaymentMethods&lt;/code&gt; property of &lt;code&gt;IOptions&amp;lt;AppSettings&amp;gt;&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Route(&quot;api/[controller]&quot;)]
public class ValuesController : Controller
{
    private readonly IOptions&amp;lt;AppSettings&amp;gt; _appSettings;

    public ValuesController(IOptions&amp;lt;AppSettings&amp;gt; appSettings)
    {
        _appSettings = appSettings;
    }
        
    // GET api/values
    [HttpGet]
    public List&amp;lt;PaymentMethod&amp;gt; Get()
    {
        return _appSettings.Value.PaymentMethods;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;you will see that instead of four elements we ended up having 3 items&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/10/asp-net-core-1-x-curios-case-of-missing-ioptions-array-item/MissingItem.png&quot;&gt;&lt;img src=&quot;images/MissingItem.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;as the &lt;code&gt;Visa&lt;/code&gt; element is missing.&lt;/p&gt;
&lt;h3&gt;3. Solution&lt;/h3&gt;
&lt;p&gt;If you look closely at the &lt;code&gt;appsettings.json&lt;/code&gt; file you will notice that a &lt;code&gt;Visa&lt;/code&gt; item configuration is a bit different than the ones which are parsed just fine.
Namely &lt;code&gt;null&lt;/code&gt; is assigned to &lt;code&gt;excludedCurrencies&lt;/code&gt; property, whereas in other items an empty array or no property at all is used.
So the first fix is just to use the same approach as in the other items&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
    &quot;Name&quot;: &quot;Visa&quot;,
    &quot;ExcludedCurrencies&quot;: []
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This approach works fine, however, it is not a silver bullet as someone still might use null and introduce a bug.
Another fix might be upgrading to &lt;code&gt;ASP.NET Core 2.0&lt;/code&gt; as the problem doesn’t seem to exist in there.
Of course, this is rather a huge change so not everyone will be willing to do it.
The last option is a manual installation of &lt;code&gt;Microsoft.Extensions.Configuration.Binder 2.0&lt;/code&gt; along with &lt;code&gt;Microsoft.Extensions.Configuration.Json 2.0&lt;/code&gt; package.
However, this approach requires you to retarget your application to &lt;code&gt;netcoreapp2.0&lt;/code&gt;.
One way or another every solution in here works fine, so once you apply the fix you will see all items in the array&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/10/asp-net-core-1-x-curios-case-of-missing-ioptions-array-item/AllItems.png&quot;&gt;&lt;img src=&quot;images/AllItems.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/ASP.NETCoreCuriousCaseOfMissingIOptionsOfTArrayItem&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>.NET Core - calculating code coverage with OpenCover (on Windows)</title><link>https://tpodolak.com/blog/net-core-calculating-code-coverage-opencover-windows/</link><guid isPermaLink="true">https://tpodolak.com/blog/net-core-calculating-code-coverage-opencover-windows/</guid><pubDate>Thu, 12 Oct 2017 08:00:27 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction.&lt;/h3&gt;
&lt;p&gt;I&apos;ve been struggling for some time to make &lt;code&gt;OpenCover&lt;/code&gt; work with &lt;code&gt;.NET Core&lt;/code&gt; projects, so I&apos;ve decided to document a working example.
This is basically an aggregation of hints and answers I found on the &lt;code&gt;Web&lt;/code&gt; (especially in &lt;a href=&quot;https://github.com/OpenCover/opencover/issues/601&quot;&gt;here&lt;/a&gt;)&lt;/p&gt;
&lt;h3&gt;2. Working example.&lt;/h3&gt;
&lt;p&gt;If you run an &lt;code&gt;OpenCover&lt;/code&gt; with the same arguments you were running it for a classic framework, you will end up with something like this&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/10/net-core-calculating-code-coverage-on-windows/MissingPdbs.png&quot;&gt;&lt;img src=&quot;images/MissingPdbs.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;As you can see the coverage was not calculated and &lt;code&gt;OpenCover&lt;/code&gt; is complaining about a missing &lt;code&gt;PDBs&lt;/code&gt;.
In order to fix that we have to do two things. First of all, we have to build the project with a full &lt;code&gt;PDBs&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;dotnet build &quot;PathToYourSolution.sln&quot; /p:DebugType=Full

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And then run &lt;code&gt;OpenCover&lt;/code&gt; with and &lt;code&gt;-oldStyle&lt;/code&gt; switch&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
OpenCover.Console.exe -target:&quot;C:/Program Files/dotnet/dotnet.exe&quot; -targetargs:&quot;test \&quot;PathToTestProject.csproj\&quot; --configuration Debug --no-build&quot; -filter:&quot;+[*]* -[*.Tests*]*&quot; -oldStyle -register:user -output:&quot;OpenCover.xml&quot;

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From now on, &lt;code&gt;OpenCover&lt;/code&gt; recognizes &lt;code&gt;PDB&lt;/code&gt; files and the code coverage is calculated correctly&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/10/net-core-calculating-code-coverage-on-windows/OkPdbs.png&quot;&gt;&lt;img src=&quot;images/OkPdbs.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;3. Cake script.&lt;/h3&gt;
&lt;p&gt;As we use a &lt;code&gt;Cake&lt;/code&gt; as our build automation tool I&apos;ve also prepared a sample script for generating a code coverage.
The core part of the script looks as follows&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// rest of the code omitted for brevity

Task(&quot;Build&quot;)
    .IsDependentOn(&quot;Restore-NuGet-Packages&quot;)
    .Does(() =&amp;gt;
{
    DotNetCoreBuild(paths.Files.Solution.ToString(), new DotNetCoreBuildSettings
    {
        Configuration = parameters.Configuration,
        ArgumentCustomization = arg =&amp;gt; arg.AppendSwitch(&quot;/p:DebugType&quot;,&quot;=&quot;,&quot;Full&quot;)
    });
});

Task(&quot;Run-Tests&quot;)
    .IsDependentOn(&quot;Build&quot;)
    .Does(() =&amp;gt;
{
    var success = true;
    var openCoverSettings = new OpenCoverSettings
    {
        OldStyle = true,
        MergeOutput = true
    }
    .WithFilter(&quot;+[*]* -[*.Tests*]*&quot;);

    foreach(var project in paths.Files.TestProjects)
    {
        try 
        {
            var projectFile = MakeAbsolute(project).ToString();
            var dotNetTestSettings = new DotNetCoreTestSettings
            {
                Configuration = parameters.Configuration,
                NoBuild = true
            };

            OpenCover(context =&amp;gt; context.DotNetCoreTest(projectFile, dotNetTestSettings), paths.Files.TestCoverageOutput, openCoverSettings);
        }
        catch(Exception ex)
        {
            success = false;
            Error(&quot;There was an error while running the tests&quot;, ex);
        }
    }

    ReportGenerator(paths.Files.TestCoverageOutput, paths.Directories.TestResults);

    if(success == false)
    {
        throw new CakeException(&quot;There was an error while running the tests&quot;);
    }

});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Notice that script is able to merge code coverage results from multiple test projects thanks to &lt;code&gt;MergeOutput&lt;/code&gt; flag passed to &lt;code&gt;OpenCover&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/10/net-core-calculating-code-coverage-on-windows/Report.png&quot;&gt;&lt;img src=&quot;images/Report.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Full sources of that script (along with a &lt;code&gt;dotnet vstest&lt;/code&gt; alternative approach) can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/NETCoreCodeCoverage/Build&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
</content:encoded></item><item><title>ASP.NET Core – request serialization issues after migration from classic WebApi</title><link>https://tpodolak.com/blog/asp-net-core-request-serialization-issues-migration-classic-webapi/</link><guid isPermaLink="true">https://tpodolak.com/blog/asp-net-core-request-serialization-issues-migration-classic-webapi/</guid><pubDate>Mon, 21 Aug 2017 10:00:49 GMT</pubDate><content:encoded>&lt;p&gt;We&apos;ve been migrating a classic &lt;code&gt;WebApi&lt;/code&gt; application into the &lt;code&gt;ASP.NET Core API&lt;/code&gt; for quite a while now, and last week we decided to deploy it on the test environment and try to run a website against it.
We were pretty confident about the quality of a migration because all of the integration tests from old &lt;code&gt;API&lt;/code&gt; were green when running against a new one.
We were expecting maybe some business logic bugs but from our perspective, the infrastructure part was good to go.
Unfortunately, when the &lt;code&gt;QA&apos;s&lt;/code&gt; run the selenium test suite they quickly found a major issue in our codebase.
They basically were getting &lt;code&gt;HTTP 500&lt;/code&gt; errors indicating a &lt;code&gt;NullReferenceException&lt;/code&gt;.
That was pretty surprising to us and after a bit of a digging we found following lines in the logs&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;TimeStamp=2017-08-20 00:43:49.4383 TraceId=0HL77AF0N305P Level=DEBUG Message=JSON input formatter threw an exception. Newtonsoft.Json.JsonSerializationException: Error converting value {null} to type &apos;System.Int32&apos;. Path &apos;PassengerNumber&apos;, line 2, position 26. ---&amp;gt; System.InvalidCastException: Null object cannot be converted to a value type.
   at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)
   --- End of inner exception stack trace ---
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;this was resulting in a null request in controller&apos;s application&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/08/asp-net-core-request-serialization-issues-after-migration-from-classic-webapi/NullRequest.png&quot;&gt;&lt;img src=&quot;images/NullRequest.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;As you can see &lt;code&gt;JSON&lt;/code&gt; serializer was not able to convert null into the int.
We double checked the requests coming from front-end and this is how one of them looked like&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
   &quot;PassengerNumber&quot;: null,
   &quot;PassengerType&quot;: &quot;2&quot;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;whereas corresponding request class on the server side was written in following way&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class CreatePassengerRequest
{
    public int PassengerNumber { get; set; }
        
    public int PassengerType { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Clearly front-end shouldn&apos;t be sending a null as a &lt;code&gt;PassengerNumber&lt;/code&gt; however the same request was serialized just fine when running against classic &lt;code&gt;WebApi&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/08/asp-net-core-request-serialization-issues-after-migration-from-classic-webapi/NotNullAspWebApi.png&quot;&gt;&lt;img src=&quot;images/NotNullAspWebApi.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Fortunately the fix for that was pretty straightforward. All we had to do was to configure &lt;code&gt;JSON&lt;/code&gt; serializer to ignore null values.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddJsonOptions(options =&amp;gt;
    {
        options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
    });
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From now on we were able to properly serialize the request&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/08/asp-net-core-request-serialization-issues-after-migration-from-classic-webapi/NotNullAfterChange.png&quot;&gt;&lt;img src=&quot;images/NotNullAfterChange.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/AspNetCoreRequestPropertyNullParsing&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>NLog.Web.AspNetCore - make sure you add error message for logging exception</title><link>https://tpodolak.com/blog/nlog-web-aspnetcore-make-sure-add-error-message-logging-exception/</link><guid isPermaLink="true">https://tpodolak.com/blog/nlog-web-aspnetcore-make-sure-add-error-message-logging-exception/</guid><pubDate>Sun, 09 Jul 2017 10:10:34 GMT</pubDate><content:encoded>&lt;p&gt;I&apos;ve been using &lt;code&gt;NLog&lt;/code&gt; for quite some time already, and it was a natural choice to use it in the &lt;code&gt;ASP.NET Core&lt;/code&gt; projects as well.
I&apos;ve configured the logger using &lt;a href=&quot;https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-(csproj---vs2017)&quot;&gt;this&lt;/a&gt; tutorial and everything seemed to be working fine.
Unfortunately, after some time we&apos;ve noticed that for some reasons some of the errors are not logged.
We&apos;ve taken a deeper look at our code base and we&apos;ve found couple logs being written as follows&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;_logger.LogError(exception.HResult, exception, string.Empty); 
_logger.LogCritical(exception.HResult, exception, string.Empty);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This piece of code works perfectly fine with &lt;code&gt;ASP.NET Core&lt;/code&gt; console logger but it seems it doesn’t for &lt;code&gt;NLog&lt;/code&gt;.
We double checked that with following piece of code&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Route(&quot;api/[controller]&quot;)]
public class ValuesController : Controller
{
    private readonly ILogger&amp;lt;ValuesController&amp;gt; _logger;
        
    public ValuesController(ILogger&amp;lt;ValuesController&amp;gt; logger)
    {
        _logger = logger;
    }

    // GET api/values
    [HttpGet]
    public IEnumerable&amp;lt;string&amp;gt; Get()
    {
        var exception = new Exception();
        _logger.LogTrace(&quot;Log trace&quot;);
        _logger.LogDebug(&quot;Log debug&quot;);
        _logger.LogInformation(&quot;Log information&quot;);
        _logger.LogWarning(&quot;Log warning&quot;);
        _logger.LogError(exception.HResult, exception, string.Empty); // this one will not be logged
        _logger.LogCritical(exception.HResult, exception, string.Empty); // this one will not be logged as well            

        return new string[] {&quot;value1&quot;, &quot;value2&quot;};
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And as you can see in the picture below, no errors have been reported&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/07/auto-draft/NoErrorsLogged.png&quot;&gt;&lt;img src=&quot;images/NoErrorsLogged.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Changing the error message to any message (even the one containing only white spaces)&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; _logger.LogError(exception.HResult, exception, &quot; &quot;); 
 _logger.LogCritical(exception.HResult, exception, &quot; &quot; ); 
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;fixed the problem.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/07/auto-draft/ErrorsLoggedWithMessage.png&quot;&gt;&lt;img src=&quot;images/ErrorsLoggedWithMessage.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;That looks like a bug for me, so I will create a PR with the fix and see if that will make its way to the &lt;code&gt;master&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;As usual, the source code for this post can be found on my &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/NLogWebAspNetCoreExceptionLoggingWithoutMessage&quot;&gt;GitHub&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>XUnit - MemberDataAttribute and generic type inheritance</title><link>https://tpodolak.com/blog/xunit-memberdataattribute-generic-type-inheritance/</link><guid isPermaLink="true">https://tpodolak.com/blog/xunit-memberdataattribute-generic-type-inheritance/</guid><pubDate>Mon, 19 Jun 2017 20:21:14 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction.&lt;/h3&gt;
&lt;p&gt;When I was writing &lt;a href=&quot;https://github.com/tpodolak/Cake.Intellisense&quot;&gt;Cake.Intellisense&lt;/a&gt; I was playing a lot with &lt;code&gt;Roslyn&lt;/code&gt; syntax rewriters.
The one thing which was pretty important for me at this time was a reliable set of tests which can quickly show if rewritten code is valid &lt;code&gt;C#&lt;/code&gt; code and if it matches my expectations.
As I don’t like to repeat my code I wanted to have a base test class which can be provided with different test cases from inherited classes.
The initial implementation looked as follows&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public abstract class CSharpSyntaxRewriterTest&amp;lt;T&amp;gt; where T : CSharpSyntaxRewriter
{
    public static IEnumerable&amp;lt;object[]&amp;gt; TestCases { get; set; }
    protected T Subject { get; }

    private readonly NSubstituteAutoMocker&amp;lt;T&amp;gt; _autoMock;
    
    protected CSharpSyntaxRewriterTest()
    {
        _autoMock = new NSubstituteAutoMocker&amp;lt;T&amp;gt;();
        Subject = _autoMock.ClassUnderTest;
    }

    [Theory]
    [MemberData(nameof(TestCases))]
    public void Verify(SyntaxRewriterTestCase testCase)
    {
        var inputTree = SyntaxFactory.ParseSyntaxTree(testCase.Input);
        var result = Subject.Visit(inputTree.GetRoot());

        inputTree.GetDiagnostics().Should().BeEmpty();
        result.GetDiagnostics().Should().BeEmpty();
        result.ToFullString().Should().Be(testCase.ExpectedResult);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see I have a generic base test class which holds test cases in a static field &lt;code&gt;TestCases&lt;/code&gt;.
The field is static as it is required by &lt;code&gt;XUnit&lt;/code&gt;, this solution is perfectly valid because a static field is shared across &lt;a href=&quot;https://stackoverflow.com/a/3037259&quot;&gt;all instances of the same type&lt;/a&gt;.
Having a base test class ready I wanted to write a set of unit tests for following syntax rewriter&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class InternalToPublicClassModifierSyntaxRewriter : CSharpSyntaxRewriter
{ 
    public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
    {
        var internalModifierIndex = node.Modifiers.IndexOf(SyntaxKind.InternalKeyword);
            
        if (internalModifierIndex &amp;gt; -1)
        {
            var tokenInList = node.Modifiers[internalModifierIndex];
            var updatedModifiers = node.Modifiers.Replace(tokenInList,
                   SyntaxFactory.Token(SyntaxKind.PublicKeyword).WithLeadingTrivia(tokenInList.LeadingTrivia)
                        .WithTrailingTrivia(tokenInList.TrailingTrivia));

            node = node.WithModifiers(updatedModifiers);
         }

         return base.VisitClassDeclaration(node);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The rewriter shown above is a very simple piece of code which replaces internal class modifier with a public one. Writing the tests for that class was supposed to be very easy, I just had to provide test cases with input code and expected result.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class InternalToPublicClassModifierSyntaxRewriterTests
        : CSharpSyntaxRewriterTest&amp;lt;InternalToPublicClassModifierSyntaxRewriter&amp;gt;
{
    static InternalToPublicClassModifierSyntaxRewriterTests()
    {
        TestCases = new[]
        {
            new[] { ReplacesInternalModifierWithPublic() },
            new[] { LeavesModifiersIntactWhenClassModifierPublic() },
            new[] { LeavesModifiersIntactWhenClassModifierProtected() }
        };
    }

    private static SyntaxRewriterTestCase ReplacesInternalModifierWithPublic()
    {
        return new SyntaxRewriterTestCase(nameof(ReplacesInternalModifierWithPublic), 
                &quot;internal class Foo { }&quot;, &quot;public class Foo { }&quot;);
    }

    private static SyntaxRewriterTestCase LeavesModifiersIntactWhenClassModifierPublic()
    {
        return new SyntaxRewriterTestCase(nameof(LeavesModifiersIntactWhenClassModifierPublic),
                &quot;public class Foo { }&quot;, &quot;public class Foo { }&quot;);
    }

    private static SyntaxRewriterTestCase LeavesModifiersIntactWhenClassModifierProtected()
    {
        return new SyntaxRewriterTestCase(nameof(LeavesModifiersIntactWhenClassModifierProtected),
                &quot;protected class Foo { }&quot;, &quot;protected class Foo { }&quot;);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Unfortunately running the tests resulted in &lt;code&gt;InvalidOperationException&lt;/code&gt; being thrown from &lt;code&gt;XUnit&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/06/xunit-memberdataattribute-and-generic-type-inheritance/FailedTest.png&quot;&gt;&lt;img src=&quot;images/FailedTest.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;If you look closely at the message you will notice that the &lt;code&gt;TestCases&lt;/code&gt; field used for providing data was not initialized, which means that the static constructor of class &lt;code&gt;InternalToPublicClassModifierSyntaxRewriterTests&lt;/code&gt; was not run.
That was pretty surprising for me that is why I wanted to investigated the issue a bit more.&lt;/p&gt;
&lt;h3&gt;2. Investigation.&lt;/h3&gt;
&lt;p&gt;I started from going back to the basics. As we probably all know, the static constructor is triggered when one of the following events occur:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;An instance of the class type is created.&lt;/li&gt;
&lt;li&gt;Any of the static members of the class type are referenced&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The first condition is not met because instance of the test class is created after test cases are enumerated. That is why member data fields have to be a static fields/properties etc. When it comes to second condition the situation in here is a bit more complicated but if you take a look at the &lt;a href=&quot;https://github.com/xunit/xunit/blob/bccfcccf26b2c63c90573fe1a17e6572882ef39c/src/xunit.core/MemberDataAttributeBase.cs&quot;&gt;MemberDataAttributeBase&lt;/a&gt; class&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public override IEnumerable&amp;lt;object[]&amp;gt; GetData(MethodInfo testMethod)
{
    Guard.ArgumentNotNull(&quot;testMethod&quot;, testMethod);

    var type = MemberType ?? testMethod.DeclaringType;
    var accessor = GetPropertyAccessor(type) ?? GetFieldAccessor(type) ?? GetMethodAccessor(type);
    // implementation omitted for brevity  
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;you will notice that member data looks for properties in &lt;code&gt;DeclaringType&lt;/code&gt; of method. In my case declaring type is&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;XUnitMemberDataAndInheritance.CSharpSyntaxRewriterTest`1[[XUnitMemberDataAndInheritance.InternalToPublicClassModifierSyntaxRewriter]]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;not&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;InternalToPublicClassModifierSyntaxRewriterTests
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So when &lt;code&gt;XUnit&lt;/code&gt; accesses &lt;code&gt;TestCase&lt;/code&gt; property the static constructor from &lt;code&gt;InternalToPublicClassModifierSyntaxRewriterTests&lt;/code&gt; class will not be called either as the types does not match.&lt;/p&gt;
&lt;h3&gt;3. Solution.&lt;/h3&gt;
&lt;p&gt;In order to bend the behavior of &lt;code&gt;XUnit&lt;/code&gt; to my needs, I had to ensure that the static constructor from inherited class is called.
Fortunately, workaround is pretty straightforward - I had to introduce a custom &lt;code&gt;MemberDataAttribute&lt;/code&gt; which calls static constructor from &lt;code&gt;ReflectedType&lt;/code&gt; manually&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[DataDiscoverer(&quot;Xunit.Sdk.MemberDataDiscoverer&quot;, &quot;xunit.core&quot;)]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class CustomMemberDataAttribute : MemberDataAttributeBase
{
    public CustomMemberDataAttribute(string memberName, params object[] parameters)
            : base(memberName, parameters)
    {
    }

    public override IEnumerable&amp;lt;object[]&amp;gt; GetData(MethodInfo testMethod)
    {
        var type = MemberType ?? testMethod.ReflectedType;
        System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);
        return base.GetData(testMethod);
    }

    protected override object[] ConvertDataItem(MethodInfo testMethod, object item)
    {
        if (item == null)
        {
            return null;
        }

        var array = item as object[];
        if (array == null)
        {
            throw new ArgumentException(
                    $&quot;Property {MemberName} on {MemberType ?? testMethod.ReflectedType} yielded an item that is not an object[]&quot;);
        }
            return array;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now all I have to do is use newly created attribute in &lt;code&gt;CSharpSyntaxRewriterTest&lt;/code&gt; test class&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Theory]
[CustomMemberData(nameof(TestCases))]
public void Verify(SyntaxRewriterTestCase testCase)
{
    // implementation omitted for brevity        
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From now on all of the test cases will be run correctly&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/06/xunit-memberdataattribute-and-generic-type-inheritance/GreenTest.png&quot;&gt;&lt;img src=&quot;images/GreenTest.png&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/XUnitMemberDataAndInheritance&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>NSubstitute - returning value from IEnumerable</title><link>https://tpodolak.com/blog/nsubstitute-returning-ienumerable/</link><guid isPermaLink="true">https://tpodolak.com/blog/nsubstitute-returning-ienumerable/</guid><pubDate>Mon, 12 Jun 2017 11:35:02 GMT</pubDate><content:encoded>&lt;p&gt;I&apos;ve been using &lt;code&gt;NSubstitute&lt;/code&gt; combined with automocks for quite some time already, but recently I&apos;ve encountered quite interesting situation.
Let&apos;s assume that we have the following class we need to write tests for&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class PriceValidator : IValidator&amp;lt;Price&amp;gt;
{
    private readonly IEnumerable&amp;lt;IValidator&amp;lt;Price&amp;gt;&amp;gt; _innerValidators;

    public PriceValidator(IEnumerable&amp;lt;IValidator&amp;lt;Price&amp;gt;&amp;gt; innerValidators)
    {
         _innerValidators = innerValidators;
    }

    public bool IsValid(Price input)
    {
        return _innerValidators.Any() &amp;amp;&amp;amp; _innerValidators.All(validator =&amp;gt; validator.IsValid(input));
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As mentioned before I wanted to test that class leveraging the concept of automocks.
If you have never used them before, no worries, the idea is pretty simple.
Instead of providing mock dependencies manually, you just generate them automatically.
Once the dependencies are mocked you can retrieve and set them up if necessary.
So in my case, I have to setup &lt;code&gt;IEnumerable&amp;lt;IValidator&amp;lt;Price&amp;gt;&amp;gt;&lt;/code&gt; mock so that it yields some values.
It can be achieved by mocking return values of &lt;code&gt;GetEnumerator()&lt;/code&gt; method.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var automock = new NSubstituteAutoMocker&amp;lt;PriceValidator&amp;gt;();
var innerValidators = new List&amp;lt;IValidator&amp;lt;Price&amp;gt;&amp;gt;
{
    Substitute.For&amp;lt;IValidator&amp;lt;Price&amp;gt;&amp;gt;(),
};            
automock.Get&amp;lt;IEnumerable&amp;lt;IValidator&amp;lt;Price&amp;gt;&amp;gt;&amp;gt;().GetEnumerator().Returns(innerValidators.GetEnumerator());
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The entire test then can be written as&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Fact]
public void IsValid_ReturnsTrue_WhenAllInnerValidatorsAreValid()
{
    var automock = new NSubstituteAutoMocker&amp;lt;PriceValidator&amp;gt;();
    var innerValidators = new List&amp;lt;IValidator&amp;lt;Price&amp;gt;&amp;gt;
    {
        Substitute.For&amp;lt;IValidator&amp;lt;Price&amp;gt;&amp;gt;(),
    };
    innerValidators.ForEach(validator =&amp;gt; validator.IsValid(Arg.Any&amp;lt;Price&amp;gt;()).Returns(true));
    automock.Get&amp;lt;IEnumerable&amp;lt;IValidator&amp;lt;Price&amp;gt;&amp;gt;&amp;gt;().GetEnumerator().Returns(innerValidators.GetEnumerator());
            
    var result = automock.ClassUnderTest.IsValid(new Price());

    innerValidators.ForEach(validator =&amp;gt; validator.Received(1).IsValid(Arg.Any&amp;lt;Price&amp;gt;()));
    result.Should().BeTrue();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Everything looks good at that point, however if you run the tests, it will FailedTest&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/06/nsubstitute-returning-from-ienumerable/FailedTest.png&quot;&gt;&lt;img src=&quot;images/FailedTest.png&quot; alt=&quot;FailedTest&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;That was quite surprising for me and I have to admit that at the beginning I thought it was a bug in &lt;code&gt;NSubstitute&lt;/code&gt;.
However, if you looks closely at the implementation of the test, you will see that every time validator collection is enumerated, the same instance of the enumerator is used.
As the enumerator keeps its state, the first enumeration (&lt;code&gt;innerValidators.Any()&lt;/code&gt;) will move a current element to the first position (which is the last position at the same time) so when I try to enumerate again (&lt;code&gt;innerValidators.All(validator =&amp;gt; validator.IsValid(input)&lt;/code&gt;) enumeration will continue from the previous position and the iteration will end yielding no results.
Fortunately, with &lt;code&gt;NSubstitute&lt;/code&gt; you can configure the call so that it always returns a new value.
The relevant code changes are shown below&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;automock.Get&amp;lt;IEnumerable&amp;lt;IValidator&amp;lt;Price&amp;gt;&amp;gt;&amp;gt;().GetEnumerator().Returns(callInfo =&amp;gt; innerValidators.GetEnumerator());
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Running the tests again will give us &quot;green&quot; result&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/06/nsubstitute-returning-from-ienumerable/Green.png&quot;&gt;&lt;img src=&quot;images/Green.png&quot; alt=&quot;Green&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/NSubstiuteReturningFromIEnumerable&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Dotnet CLI - running tests from multiple assemblies</title><link>https://tpodolak.com/blog/dotnet-cli-running-tests-from-multiple-assemblies/</link><guid isPermaLink="true">https://tpodolak.com/blog/dotnet-cli-running-tests-from-multiple-assemblies/</guid><pubDate>Wed, 07 Jun 2017 19:33:16 GMT</pubDate><content:encoded>&lt;p&gt;When you start looking for information how to run unit tests for &lt;code&gt;.NET Core&lt;/code&gt; based projects in the command line, you will most probably stumble upon &lt;code&gt;dotnet CLI&lt;/code&gt; and its &lt;a href=&quot;https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-test&quot;&gt;dotnet test&lt;/a&gt; command.
The command works really great when you have just one test project in your solution, however, it doesn’t allow you to run tests from multiple projects at once.
Of course, you can write little &lt;code&gt;PowerShell&lt;/code&gt; which will run the command in the loop e.g.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Get-ChildItem | ? { $_.Name.Contains(&quot;.Tests.&quot;) } | ForEach-Object { Push-Location; Set-Location $_.Name; dotnet test; Pop-Location}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Unfortunately, in this case, you won&apos;t get an aggregated summary of tests results, instead, you will get a summary per test project.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/06/dotnet-cli-running-tests-from-multiple-assemblies/dotnettest.png&quot;&gt;&lt;img src=&quot;images/dotnettest.png&quot; alt=&quot;dotnettest&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Luckily &lt;code&gt;dotnet CLI&lt;/code&gt; have another command for running tests - namely &lt;a href=&quot;https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-vstest&quot;&gt;dotnet vstest&lt;/a&gt;.
In this case, we do not operate on projects but we provide a location for assemblies with tests.
So if you, for instance, would like to run unit and integration tests at once, you can write something like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;dotnet vstest .\DotnetCLIRunningTestsFromMultipleAssemblies.Tests.Integration\bin\Debug\netcoreapp1.1\DotnetCLIRunningTestsFromMultipleAssemblies.Tests.Integration.dll .\DotnetCLIRunningTestsFromMultipleAssemblies.Tests.Unit\bin\Debug\netcoreapp1.1\DotnetCLIRunningTestsFromMultipleAssemblies.Tests.Unit.dll
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you want a bit more flexible solution this simple &lt;code&gt;PowerShell&lt;/code&gt; script will scan files and based on naming convention retrieve tests assemblies.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;dotnet vstest (Get-ChildItem -recurse -File *.Tests.*dll | ? { $_.FullName -notmatch &quot;\\obj\\?&quot; })
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;One way or another, the &lt;code&gt;dotnet vstest&lt;/code&gt; command will aggregate all of the test results and will present them as one summary.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/06/dotnet-cli-running-tests-from-multiple-assemblies/dotnetvstest.png&quot;&gt;&lt;img src=&quot;images/dotnetvstest.png&quot; alt=&quot;dotnetvstest&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;One thing to note, &lt;code&gt;dotnet vstest&lt;/code&gt; won&apos;t build the solution, you have to run the build manually with &lt;code&gt;dotnet build&lt;/code&gt; command.&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/DotnetCLIRunningTestsFromMultipleAssemblies&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>ASP.NET Core - API versioning by convention</title><link>https://tpodolak.com/blog/asp-net-core-api-versioning-convention/</link><guid isPermaLink="true">https://tpodolak.com/blog/asp-net-core-api-versioning-convention/</guid><pubDate>Thu, 04 May 2017 13:02:47 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;If you were looking for information about &lt;code&gt;API&lt;/code&gt; versioning support for &lt;code&gt;ASP.NET Core&lt;/code&gt; you&apos;ve probably come across &lt;a href=&quot;https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.Versioning&quot;&gt;Microsoft.AspNetCore.Mvc.Versioning&lt;/a&gt; library. The library itself allows you to set up versioning in a couple of different ways, for instance, via &lt;a href=&quot;https://github.com/Microsoft/aspnet-api-versioning/wiki/How-to-Version-Your-Service&quot;&gt;attributes&lt;/a&gt; or via &lt;a href=&quot;https://github.com/Microsoft/aspnet-api-versioning/wiki/API-Version-Conventions&quot;&gt;manual convention setup&lt;/a&gt;. All of this options are really nice but unfortunately, they have one significant drawback, namely, you have to set them up manually. As I tend to forget about this kind of things I wanted to automate that process as much as possible. Thankfully &lt;code&gt;ASP.NET Core&lt;/code&gt; has a very nice feature called &lt;code&gt;ApplicationModelConventions&lt;/code&gt; which allows you to add some metadata(like routing information, &lt;code&gt;API&lt;/code&gt; versioning ) to your controller, actions etc.&lt;/p&gt;
&lt;h3&gt;2. Convention&lt;/h3&gt;
&lt;p&gt;I&apos;ve decided to implement versioning by routing which means the &lt;code&gt;API&lt;/code&gt; will be accessible via this template&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&quot;v{version:apiVersion}/[controller]&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The template itself doesn’t give you much, as you also have to add information to the controllers which version of &lt;code&gt;API&lt;/code&gt; they support.
In my case, I decided to go with a version by namespace convention, which means that supported version will be deduced from namespace in which given controller resides.
So, in fact, there will be two conventions, one for applying routing and a second one for applying versioning&lt;/p&gt;
&lt;h3&gt;3. Creating conventions.&lt;/h3&gt;
&lt;p&gt;In order to write an &lt;code&gt;ASP.NET Core&lt;/code&gt; convention, we have to implement &lt;code&gt;IApplicationModelConvention&lt;/code&gt; interface. This interface has a single method &lt;code&gt;Apply&lt;/code&gt; which takes &lt;code&gt;ApplicationModel&lt;/code&gt; class as an argument. This class gives us access to all of our controllers, actions and other parts of the application. So if we want to apply a routing with versioning for all of the controllers, we can do it in following way&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class ApiVersionRoutePrefixConvention : IApplicationModelConvention
{
    private readonly string _versionConstraintTemplate;
    private readonly string _versionedControllerTemplate;

    public ApiVersionRoutePrefixConvention()
    {
        _versionConstraintTemplate = &quot;v{version:apiVersion}&quot;;
        _versionedControllerTemplate = $&quot;{_versionConstraintTemplate}/[controller]&quot;;
    }

    public void Apply(ApplicationModel application)
    {
        foreach (var applicationController in application.Controllers)
        {
            foreach (var applicationControllerSelector in applicationController.Selectors)
            {
                if (applicationControllerSelector.AttributeRouteModel != null)
                {
                    var versionedConstraintRouteModel = new AttributeRouteModel
                    {
                        Template = _versionConstraintTemplate
                    };

                    applicationControllerSelector.AttributeRouteModel =
                            AttributeRouteModel.CombineAttributeRouteModel(versionedConstraintRouteModel,
                                applicationControllerSelector.AttributeRouteModel);
                }
                else
                {
                    applicationControllerSelector.AttributeRouteModel = new AttributeRouteModel
                    {
                        Template = _versionedControllerTemplate
                    };
                }
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see we iterate through all of the &lt;code&gt;Selectors&lt;/code&gt; and then apply new route model to them.
If selector already had a route attribute applied we combine two attributes together. Once our convention is applied our actions will be accessible with following routing prefix&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&quot;v{version:apiVersion}/[controller]&quot; 
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or via&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&quot;v{version:apiVersion}/previous_route_for_controller&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Having our routing ready now it is time to add versioning information to our controllers.
Once again it will be done via application model convention.
The version of the controller will be deduced from the namespace given controller is located in.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class ApiVersionByNamespaceConvention : IApplicationModelConvention
{
    public void Apply(ApplicationModel application)
    {
        foreach (var controllerModel in application.Controllers)
        {
            var version = DeduceControllerVersion(controllerModel);
            var builder = new ControllerApiVersionConventionBuilder&amp;lt;ControllerModel&amp;gt;();
            builder.HasApiVersion(new ApiVersion(version, 0));
            builder.ApplyTo(controllerModel);
        }
    }

    private int DeduceControllerVersion(ControllerModel model)
    {
        // super trivial way of retrieving version number from namespace
        if (!int.TryParse(model.ControllerType.Namespace.Last().ToString(), out var version))
        {
            throw new InvalidOperationException(&quot;Unable to retrieve version information from namespace&quot;);
        }
        
        return version;
     }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see I iterate through all of the controller models of our application, then check the version of controller based on its namespace and finally with&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var builder = new ControllerApiVersionConventionBuilder&amp;lt;ControllerModel&amp;gt;();
builder.HasApiVersion(new ApiVersion(version, 0));
builder.ApplyTo(controllerModel);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I am able to inform the framework which version of &lt;code&gt;API&lt;/code&gt; given controller supports.&lt;/p&gt;
&lt;h3&gt;4. Adding convention to application&lt;/h3&gt;
&lt;p&gt;Having all of our conventions prepared now we can enable versioning support&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Add framework services.
services.AddApiVersioning(options =&amp;gt;
{
    options.ReportApiVersions = true;
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And of course, we have to add newly created conventions to list of application conventions&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;services.AddMvc(options =&amp;gt;
{
    options.Conventions.Remove&amp;lt;ApiVersionConvention&amp;gt;();
    options.Conventions.Remove&amp;lt;ImplicitControllerVersionConvention&amp;gt;();
    options.Conventions.Add(new ApiVersionRoutePrefixConvention());
    options.Conventions.Add(new ApiVersionByNamespaceConvention());
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that I removed &lt;code&gt;ApiVersionConvention&lt;/code&gt; and &lt;code&gt;ImplicitControllerVersionConvention&lt;/code&gt; with simple extension method &lt;code&gt;Remove&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static class CollectionExtensions
{
    public static void Remove&amp;lt;T&amp;gt;(this IList&amp;lt;IApplicationModelConvention&amp;gt; conventionsCollection)
            where T : IApplicationModelConvention
    {
        var conventions = conventionsCollection.OfType&amp;lt;T&amp;gt;().ToList();

        foreach (var convention in conventions)
        {
            conventionsCollection.Remove(convention);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;to make sure that only my convention is responsible for API versioning.&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/AspNetCoreDefaultApiVersionWithUrlPathVersioning&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>ASP.NET Core - default API version with url path versioning</title><link>https://tpodolak.com/blog/asp-net-core-default-api-version-with-url-path-versioning/</link><guid isPermaLink="true">https://tpodolak.com/blog/asp-net-core-default-api-version-with-url-path-versioning/</guid><pubDate>Wed, 03 May 2017 20:50:32 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction.&lt;/h3&gt;
&lt;p&gt;When you start versioning your &lt;code&gt;API&lt;/code&gt; sometimes you want to have access to your endpoints without specifying version explicitly.
Thanks to &lt;a href=&quot;https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.Versioning&quot;&gt;Microsoft.AspNetCore.Mvc.Versioning&lt;/a&gt; library this can be easily achieved with proper setup of configuration action.
However, it turns out that in order to enable default &lt;code&gt;API&lt;/code&gt; version for url path versioning, there are a couple additional steps to do.&lt;/p&gt;
&lt;h3&gt;2. Default &lt;code&gt;API&lt;/code&gt; version without url path versioning&lt;/h3&gt;
&lt;p&gt;Let&apos;s start with the initial setup of &lt;code&gt;API&lt;/code&gt; versioning which will work for every type of versioning apart from url path versioning.
All you have to do is to assign an &lt;code&gt;ApiVersionSelector&lt;/code&gt; and set the &lt;code&gt;AssumeDefaultVersionWhenUnspecified&lt;/code&gt; property to true.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApiVersioning(options =&amp;gt;
    {
        options.ApiVersionReader = new QueryStringApiVersionReader();
        options.AssumeDefaultVersionWhenUnspecified = true;
        options.ApiVersionSelector = new CurrentImplementationApiVersionSelector(options);
    });
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now when the user will try to access the endpoint without specifying version explicitly the &lt;code&gt;ApiVersionSelector&lt;/code&gt; will select proper version - in this case highest available version.&lt;/p&gt;
&lt;h3&gt;3. Default Api version with URL path versioning&lt;/h3&gt;
&lt;p&gt;Running the same configuration against controllers which are versioned via url path (not query string)&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;namespace AspNetCoreDefaultApiVersionAndRoutePrefix.Controllers.V1
{
    [Route(&quot;v{version:apiVersion}/[controller]&quot;)]
    [ApiVersion(&quot;1&quot;)]
    public class ValuesController : Controller
    {
        // GET api/values
        [HttpGet]
        public IEnumerable&amp;lt;string&amp;gt; Get()
        {
            return new string[] {&quot;V1&quot;};
        }
    }
}

namespace AspNetCoreDefaultApiVersionAndRoutePrefix.Controllers.V2
{
    [Route(&quot;v{version:apiVersion}/[controller]&quot;)]
    [ApiVersion(&quot;2&quot;)]
    public class ValuesController : Controller
    {
        // GET api/values
        [HttpGet]
        public IEnumerable&amp;lt;string&amp;gt; Get()
        {
            return new string[] {&quot;V2&quot;};
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;will result with &lt;code&gt;404&lt;/code&gt; status code, as routing is not able to match the url.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/05/asp-net-core-default-api-version-with-url-path-versioning/404.png&quot;&gt;&lt;img src=&quot;images/404.png&quot; alt=&quot;404&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Fortunately, unlike the &lt;code&gt;ASP.NET Web API&lt;/code&gt;, &lt;code&gt;ASP.NET Core&lt;/code&gt; allows us to have multiple route attributes applied to given controller, so in order to fix the issue we just have to add&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Route(&quot;[controller]&quot;)]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;attribute to versioned controllers. From now on we can access our &lt;code&gt;API&lt;/code&gt; without specifying version as well as with version specified.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/05/asp-net-core-default-api-version-with-url-path-versioning/after.png&quot;&gt;&lt;img src=&quot;images/after.png&quot; alt=&quot;after&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;4. Adding default route with convention&lt;/h3&gt;
&lt;p&gt;If you don’t want to specify default route manually for every controller, you can do it via application model convention.
The interesting thing about it is the fact that apart from changing existing values of application model we can also add new items to it.
This means that we can add additional &lt;code&gt;SelectorModel&lt;/code&gt; with our default route to &lt;code&gt;Selectors&apos;&lt;/code&gt; collection&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class DefaultRoutePrefixConvention : IApplicationModelConvention
{
    public void Apply(ApplicationModel application)
    {
        foreach (var applicationController in application.Controllers)
        {
            applicationController.Selectors.Add(new SelectorModel
            {
                AttributeRouteModel = new AttributeRouteModel
                {
                    Template = &quot;[controller]&quot;
                }
            });
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we can get rid of &lt;code&gt;[Route(&quot;[controller]&quot;)]&lt;/code&gt; attribute from our versioned controllers and just rely on convention which can be added as follows&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public void ConfigureServices(IServiceCollection services)
{
    // rest of the code omitted for brevity 
    services.AddMvc(mvc =&amp;gt;
    {
        mvc.Conventions.Add(new DefaultRoutePrefixConvention());
    });
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/AspNetCoreDefaultApiVersionWithUrlPathVersioning&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>VS Code - forcing partial IntelliSense support for Cake scripts</title><link>https://tpodolak.com/blog/vs-code-forcing-partial-intellisense-support-cake-scripts/</link><guid isPermaLink="true">https://tpodolak.com/blog/vs-code-forcing-partial-intellisense-support-cake-scripts/</guid><pubDate>Wed, 12 Apr 2017 22:39:44 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;I&apos;ve been using &lt;code&gt;Cake&lt;/code&gt; for quite some time now, and I really like this tool, however the more complex my build scripts are, the more painful lack of &lt;code&gt;IntelliSense&lt;/code&gt; is.
Inspired a bit by this &lt;a href=&quot;http://www.strathweb.com/2016/12/writing-c-build-scripts-with-fake-omnisharp-and-vs-code/&quot;&gt;post&lt;/a&gt;, I decided to see what it takes to enable at least partial &lt;code&gt;IntelliSense&lt;/code&gt; for &lt;code&gt;Cake&lt;/code&gt; scripts in Visual Studio Code.&lt;/p&gt;
&lt;h3&gt;2. Investigation&lt;/h3&gt;
&lt;p&gt;The proper way of providing the code completion for &lt;code&gt;Cake&lt;/code&gt; scripts would probably be a plugin to &lt;code&gt;Omnisharp-Roslyn&lt;/code&gt;, as &lt;code&gt;Cake&lt;/code&gt; script is basically a valid c# snippet.
Unfortunately, at this moment &lt;code&gt;Omnisharp-Roslyn&lt;/code&gt; doesn’t have plugin infrastructure &lt;a href=&quot;https://github.com/OmniSharp/omnisharp-roslyn/issues/208&quot;&gt;ready&lt;/a&gt;, that is why I decided to go with a bit different path.
As you might or might not be aware, &lt;code&gt;VS Code&lt;/code&gt; already supports &lt;code&gt;csx&lt;/code&gt; files, so if you add an empty &lt;code&gt;project.json&lt;/code&gt; file (by empty I mean file with empty &lt;code&gt;JSON&lt;/code&gt; object) to your build directory and change extension of your scripts to &lt;code&gt;csx&lt;/code&gt;, you will immediately get a &lt;code&gt;C#&lt;/code&gt; syntax highlighting and some &lt;code&gt;IntelliSense&lt;/code&gt; support.
Sadly this will not provide code completion for &lt;code&gt;Cake&lt;/code&gt; method aliases. The reason why it fails on that is the fact that the &lt;code&gt;Cake&lt;/code&gt; alias is &lt;code&gt;ICakeContext&lt;/code&gt; extension method&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[CakeMethodAlias]
public static T Argument&amp;lt;T&amp;gt;(this ICakeContext context, string name)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;but you use it as it was written as&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[CakeMethodAlias]
public static T Argument&amp;lt;T&amp;gt;(string name)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;Cake&lt;/code&gt; engine generates additional alias overloads during script compilation, and as these overloads exist only on runtime, &lt;code&gt;VS Code&lt;/code&gt; just can&apos;t &quot;see&quot; them.&lt;/p&gt;
&lt;h3&gt;3. My approach&lt;/h3&gt;
&lt;p&gt;Having in mind the way &lt;code&gt;Cake&lt;/code&gt; works I decided to write an application which would be able to take any &lt;code&gt;Cake&lt;/code&gt; or &lt;code&gt;Cake add-in&lt;/code&gt; and produce a library containing proper alias overloads.
For instance, if original &lt;code&gt;Cake&lt;/code&gt; method looks as follows&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/// &amp;lt;summary&amp;gt;
/// Contains functionality related to arguments.
/// &amp;lt;/summary&amp;gt;
[CakeAliasCategory(&quot;Arguments&quot;)]
public static class ArgumentAliases
{
    /// &amp;lt;summary&amp;gt;
    /// Determines whether or not the specified argument exist.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&quot;context&quot;&amp;gt;The context.&amp;lt;/param&amp;gt;
    /// &amp;lt;param name=&quot;name&quot;&amp;gt;The argument name.&amp;lt;/param&amp;gt;
    /// &amp;lt;returns&amp;gt;Whether or not the specified argument exist.&amp;lt;/returns&amp;gt;
    /// &amp;lt;example&amp;gt;
    /// This sample shows how to call the &amp;lt;see cref=&quot;HasArgument&quot;/&amp;gt; method.
    /// &amp;lt;code&amp;gt;
    /// var argumentName = &quot;myArgument&quot;;
    /// //Cake.exe .\hasargument.cake -myArgument=&quot;is specified&quot;
    /// if (HasArgument(argumentName))
    /// {
    ///     Information(&quot;{0} is specified&quot;, argumentName);
    /// }
    /// //Cake.exe .\hasargument.cake
    /// else
    /// {
    ///     Warning(&quot;{0} not specified&quot;, argumentName);
    /// }
    /// 
    /// &amp;lt;/example&amp;gt;
    [CakeMethodAlias]
    public static bool HasArgument(this ICakeContext context, string name)
    {
        // rest of the code omitted for brevity
    }
}```

the application will rewrite it into

```csharp
/// &amp;lt;summary&amp;gt;
/// Contains functionality related to arguments.
/// &amp;lt;/summary&amp;gt;
[CakeAliasCategory(&quot;Arguments&quot;)]
public static class ArgumentAliasesMetadata
{
    /// &amp;lt;summary&amp;gt;
    /// Determines whether or not the specified argument exist.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;param name=&quot;name&quot;&amp;gt;The argument name.&amp;lt;/param&amp;gt;
    /// &amp;lt;returns&amp;gt;Whether or not the specified argument exist.&amp;lt;/returns&amp;gt;
    /// &amp;lt;example&amp;gt;
    /// This sample shows how to call the &amp;lt;see cref=&quot;HasArgument&quot;/&amp;gt; method.
    /// &amp;lt;code&amp;gt;
    /// var argumentName = &quot;myArgument&quot;;
    /// //Cake.exe .\hasargument.cake -myArgument=&quot;is specified&quot;
    /// if (HasArgument(argumentName))
    /// {
    ///     Information(&quot;{0} is specified&quot;, argumentName);
    /// }
    /// //Cake.exe .\hasargument.cake
    /// else
    /// {
    ///     Warning(&quot;{0} not specified&quot;, argumentName);
    /// }
    /// 
    /// &amp;lt;/example&amp;gt;
    public static bool HasArgument(string name)
    {
        return default(bool);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The algorithm looks more or less like that&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Retrieve &lt;code&gt;Cake&lt;/code&gt; or &lt;code&gt;Cake&lt;/code&gt; add-in via &lt;code&gt;NuGet&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Scan an assembly and find all classes containing alias methods&lt;/li&gt;
&lt;li&gt;Use &lt;a href=&quot;http://source.roslyn.io/#Microsoft.CodeAnalysis.CSharp.Workspaces/CodeGeneration/CSharpCodeGenerationService.cs,20912a440e5cda03&quot;&gt;CSharpCodeGenerationService&lt;/a&gt; to generate metadata for Cake alias methods&lt;/li&gt;
&lt;li&gt;Parse generated code with &lt;code&gt;Roslyn&lt;/code&gt; and produce &lt;code&gt;SyntaxTree&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Append Metadata suffix to classes containing alias method&lt;/li&gt;
&lt;li&gt;Remove &lt;code&gt;ICakeContext&lt;/code&gt; parameter from alias method&lt;/li&gt;
&lt;li&gt;Generate dummy body for methods which require that (methods which have return type or which have out parameters)&lt;/li&gt;
&lt;li&gt;Update xml documentation&lt;/li&gt;
&lt;li&gt;Compile generated code and produce dll&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;There is no point of doing more detailed description in here so if you want to take a closer look here is &lt;a href=&quot;https://github.com/tpodolak/Cake.Intellisense&quot;&gt;source code&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;4. Generating metadata libraries&lt;/h3&gt;
&lt;p&gt;Before we start &quot;hacking&quot; &lt;code&gt;VS Code&lt;/code&gt; to have &lt;code&gt;IntelliSense&lt;/code&gt;, we have to prepare metadata libraries which will contain all necessary &lt;code&gt;Cake&lt;/code&gt; alias overloads.
In order to do that grab the application from &lt;a href=&quot;https://www.nuget.org/packages/Cake.Intellisense/&quot;&gt;NuGet&lt;/a&gt; and generate &lt;code&gt;Cake.Common&lt;/code&gt; and &lt;code&gt;Cake.Core&lt;/code&gt; metadata libraries.
The simplest way of doing it is to run these commands&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Cake.Intellisense.exe --Package Cake.Common --PackageVersion 0.19.2 --TargetFramework .NETFramework,Version=v4.5 --OutputFolder C:\Output
	
Cake.Intellisense.exe --Package Cake.Core --PackageVersion 0.19.2 --TargetFramework .NETFramework,Version=v4.5 --OutputFolder C:\Output
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As a result, the application will produce following files:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Cake.CommonMetadata.dll&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Cake.CommonMetadata.xml&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Cake.CoreMetadata.dll&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Cake.CoreMetadata.xml&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;5. Enabling &lt;code&gt;IntelliSense&lt;/code&gt; in &lt;code&gt;VS Code&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;Having our metadata libraries prepared now we can adjust our build scripts to have code completion in &lt;code&gt;VS Code&lt;/code&gt;. Here are the steps:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Add &lt;code&gt;project.json&lt;/code&gt; file with empty &lt;code&gt;JSON&lt;/code&gt; object into your build directory.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Change extension of all your build scripts to &lt;code&gt;csx&lt;/code&gt;.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Copy metadata libraries into your &lt;code&gt;Build&lt;/code&gt; directory.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Create &lt;code&gt;imports.csx&lt;/code&gt; file. This is the file which contains all original namespace imports. It may look as follows&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#load &quot;./metadataImports.csx&quot;
using Cake.Core;
using Cake.Core.IO;
// rest of imports
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Create &lt;code&gt;metadataimports.csx&lt;/code&gt; file. This is the file which contains metadata namespaces imports and loads &lt;code&gt;Cake&lt;/code&gt; and metadata references.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#r &quot;./tools/Cake/Cake.Core.dll&quot;
#r &quot;./tools/Cake/Cake.Common.dll&quot;
#r &quot;./tools/Cake.Metadata/Cake.Core.Metadata.dll&quot;
#r &quot;./tools/Cake.Metadata/Cake.Common.Metadata.dll&quot;
using static Cake.Common.ArgumentAliasesMetadata;
using static Cake.Common.EnvironmentAliasesMetadata;
// rest of imports 
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Each original &lt;code&gt;Cake&lt;/code&gt; alias class has corresponding metadata class with Metadata suffix, for instance &lt;code&gt;Cake.Common.ArgumentAliases -&amp;gt; Cake.Common.ArgumentAliasesMetadata&lt;/code&gt; &lt;code&gt;Cake.Common.EnvironmentAliases -&amp;gt; Cake.Common.EnvironmentAliasesMetadata&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Load &lt;code&gt;imports.csx&lt;/code&gt; to your &lt;code&gt;build.csx&lt;/code&gt; file via&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#load &quot;./imports.csx&quot;    
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Run &lt;code&gt;VS Code&lt;/code&gt; install &lt;a href=&quot;//tpodolak.com/blog/2017/04/09/downgrading-visual-studio-code-extension/&quot;&gt;ms-vscode.csharp 1.7.0&lt;/a&gt;, open &lt;code&gt;Build&lt;/code&gt; directory and write your build script with &lt;code&gt;IntelliSense&lt;/code&gt; support&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;a&gt;&lt;img src=&quot;images/ButIXBW.gif&quot; alt=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Before running the script remember to comment out&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#load &quot;./metadataImports.csx&quot;

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;from &lt;code&gt;imports.csx&lt;/code&gt; file&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Run the build&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;build.ps1 -script build.csx -target Your-Target

&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I do realize this is quite convoluted explanation so in case of any troubles take a look at my &lt;a href=&quot;https://github.com/tpodolak/Cake.Intellisense/tree/master/Build&quot;&gt;build&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;6. Known issues&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Cake.Intellisense&lt;/code&gt; can only generate metadata libraries for a standard .NET frameworks, it will fail if you try to create metadata targeting &lt;code&gt;.NETStandard&lt;/code&gt; or &lt;code&gt;.NET Core&lt;/code&gt; framework&lt;/li&gt;
&lt;li&gt;Due to some &lt;a href=&quot;https://github.com/OmniSharp/omnisharp-roslyn/issues/811&quot;&gt;breaking changes&lt;/a&gt; in &lt;code&gt;Omnisharp-Roslyn&lt;/code&gt; scripting support, &lt;code&gt;IntelliSense&lt;/code&gt; will only work with &lt;code&gt;Omnisharp 1.7.0&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;7. Summary&lt;/h3&gt;
&lt;p&gt;This approach is just a temporary solution. As you can see, it requires significant amount of work to have a code completion in &lt;code&gt;VS Code&lt;/code&gt;. I believe that once &lt;code&gt;Omnisharp-Roslyn&lt;/code&gt; has proper plugin support it should be possible to write some kind of custom &lt;code&gt;IntelliSense&lt;/code&gt; provider for &lt;code&gt;Cake&lt;/code&gt; scripts. There are already people who forked &lt;code&gt;Omnisharp-Roslyn&lt;/code&gt; and play around with &lt;a href=&quot;https://github.com/mholo65/omnisharp-roslyn/tree/wip/new-cake-plugin&quot;&gt;that&lt;/a&gt;, so we just have to wait for something better than this solution.&lt;/p&gt;
</content:encoded></item><item><title>Downgrading Visual Studio Code extension</title><link>https://tpodolak.com/blog/downgrading-visual-studio-code-extension/</link><guid isPermaLink="true">https://tpodolak.com/blog/downgrading-visual-studio-code-extension/</guid><pubDate>Sun, 09 Apr 2017 17:56:34 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;For time to time when you update Visual Studio Code&apos;s extension you realize that there were some breaking changes you don’t like or the extension has a bug which prevents you from using it.
Usually, in this kind of situations, you would like to just go back to the version you were using previously rather than stop using the extension at all.
Unfortunately, &lt;code&gt;VSCode&lt;/code&gt; doesn’t give us an option to install a specific version of the extension for &lt;a href=&quot;https://github.com/Microsoft/vscode/issues/12764&quot;&gt;now&lt;/a&gt;.
Luckily there is an easy way of doing that manually.&lt;/p&gt;
&lt;h3&gt;2. Installation&lt;/h3&gt;
&lt;p&gt;Let&apos;s assume that I would like to downgrade &lt;code&gt;C#&lt;/code&gt; plugin from newest version (&lt;code&gt;1.8.1&lt;/code&gt; at the moment) to &lt;code&gt;1.7.0&lt;/code&gt;.
First of all, we have to uninstall current extension. As there as some issues of doing that via command line, just do it from &lt;code&gt;VSCode&lt;/code&gt; by clicking on uninstall button in extension screen.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/04/downgrading-visual-studio-code-extension/Initial.png&quot;&gt;&lt;img src=&quot;images/Initial.png&quot; alt=&quot;Initial&quot; /&gt;&lt;/a&gt;
In the next step we have to download proper extension&apos;s version using &lt;code&gt;vsassets&lt;/code&gt; &lt;code&gt;api&lt;/code&gt;. The url pattern looks as follows&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;https://${publisher}.gallery.vsassets.io/_apis/public/gallery/publisher/${publisher}/extension/${extension_name}/${version}/assetbyname/Microsoft.VisualStudio.Services.VSIXPackage
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In my case, the variables looks as follow&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;${publisher}&lt;/code&gt; - ms-vscode&lt;/li&gt;
&lt;li&gt;&lt;code&gt;${extension_name}&lt;/code&gt; - csharp&lt;/li&gt;
&lt;li&gt;&lt;code&gt;${version}&lt;/code&gt; - 1.7.0&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;and entire url can be rewritten as&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;https://ms-vscode.gallery.vsassets.io/_apis/public/gallery/publisher/ms-vscode/extension/csharp/1.7.0/assetbyname/Microsoft.VisualStudio.Services.VSIXPackage

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Having the link prepared we can paste it into browser address bar and download the extension.
Once the file is downloaded, run &lt;code&gt;VSCode&lt;/code&gt;, hit &lt;code&gt;CTRL+SHIFT+P&lt;/code&gt;, type &lt;code&gt;vsix&lt;/code&gt; in command line and choose&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Extensions: Install from VSIX...

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/04/downgrading-visual-studio-code-extension/vsix.png&quot;&gt;&lt;img src=&quot;images/vsix.png&quot; alt=&quot;vsix&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Select the file you&apos;ve just downloaded and restart editor after installation.
From now on you can use older version of your favorite extension.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/04/downgrading-visual-studio-code-extension/after.png&quot;&gt;&lt;img src=&quot;images/after.png&quot; alt=&quot;after&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Asp.NET Core - populating IOptions&lt;T&gt; from external data source</title><link>https://tpodolak.com/blog/asp-net-core-populating-ioptions-external-data-source/</link><guid isPermaLink="true">https://tpodolak.com/blog/asp-net-core-populating-ioptions-external-data-source/</guid><pubDate>Sun, 26 Feb 2017 22:56:52 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;In &lt;code&gt;ASP.NET Core&lt;/code&gt; &lt;code&gt;web.config&lt;/code&gt; is no longer a proper place for storing application settings.
New framework introduces the concept of a json based configuration and the default file which stores the settings now is &lt;code&gt;appsettings.json&lt;/code&gt;.
Here is a quick tutorial how to use new features.&lt;/p&gt;
&lt;h3&gt;2. Reading configuration&lt;/h3&gt;
&lt;p&gt;Let&apos;s assume that our &lt;code&gt;appsettings.json&lt;/code&gt; file looks as follows.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
    &quot;Logging&quot;: {
        &quot;IncludeScopes&quot;: false,
        &quot;LogLevel&quot;: {
            &quot;Default&quot;: &quot;Debug&quot;,
            &quot;System&quot;: &quot;Information&quot;,
            &quot;Microsoft&quot;: &quot;Information&quot;
        }
    },
    &quot;AvailabilitySearchOptions&quot;: {
        &quot;FlexDaysIn&quot;: 2,
        &quot;FlexDaysOut&quot;: 3
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Thanks to &lt;code&gt;ConfigurationBuilder&lt;/code&gt; we can parse this config and later on materialize sections or entire file into strongly typed configuration classes.
Let&apos;s say we want to parse &lt;code&gt;AvailabilitySearchOptions&lt;/code&gt; node to following class&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class AvailabilitySearchOptions
{
    public int FlexDaysIn { get; set; }

    public int FlexDaysOut { get; set; }

    public TimeSpan MinimumConnectionTime { get; set; }

    public TimeSpan MinimumDepartureTime { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can achieve that with following steps. First of all, we need to read entire configuration&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public IConfigurationRoot Configuration { get; }

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
                        .SetBasePath(env.ContentRootPath)
                        .AddJsonFile(&quot;appsettings.json&quot;, optional: true, reloadOnChange: true)
                        .AddJsonFile($&quot;appsettings.{env.EnvironmentName}.json&quot;, optional: true)
                        .AddEnvironmentVariables();
    Configuration = builder.Build();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And in the next step we have to register &lt;code&gt;IOptions&amp;lt;AvailabilitySearchOptions&amp;gt;&lt;/code&gt; in the container using &lt;code&gt;services.Configure&amp;lt;TOptions&amp;gt;(IConfiguration section)&lt;/code&gt; method&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    services.Configure&amp;lt;AvailabilitySearchOptions&amp;gt;(Configuration.GetSection(&quot;AvailabilitySearchOptions&quot;));  
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note &lt;code&gt;Configuration.GetSection(&quot;AvailabilitySearchOptions&quot;)&lt;/code&gt; passed as argument to &lt;code&gt;services.Configure&lt;/code&gt; method.
From now on we can access &lt;code&gt;AvailabilitySearchOptions&lt;/code&gt; settings via &lt;code&gt;IOptions&amp;lt;AvailabilitySearchOptions&amp;gt;&lt;/code&gt; interface, which you can easily inject into your classes.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
[Route(&quot;api/[controller]&quot;)]
public class OptionsController : Controller
{
    private readonly IOptions&amp;lt;AvailabilitySearchOptions&amp;gt; availabilitySearchOptions;

    public OptionsController(IOptions&amp;lt;AvailabilitySearchOptions&amp;gt; availabilitySearchOptions)
    {
        this.availabilitySearchOptions = availabilitySearchOptions;
    }

    public AvailabilitySearchOptions Get()
    {
        return availabilitySearchOptions.Value;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;3. Populating &lt;code&gt;IOptions&amp;lt;T&amp;gt;&lt;/code&gt; from external data source&lt;/h3&gt;
&lt;p&gt;From time to time, reading configuration just from &lt;code&gt;JSON&lt;/code&gt; file might not be enough and for instance you would like to add additional configuration read from some external data source.
Fortunately you don&apos;t have to resign from the &lt;code&gt;IOptions&amp;lt;T&amp;gt;&lt;/code&gt; class as it is possible to read additional data for literally any other source thanks to &lt;code&gt;IConfigureOptions&amp;lt;T&amp;gt;&lt;/code&gt; class.
All we have to do is to create a setup class which implements &lt;code&gt;IConfigureOptions&amp;lt;T&amp;gt;&lt;/code&gt; interface&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
public class AvailabilitySearchOptionsSetupService : IConfigureOptions&amp;lt;AvailabilitySearchOptions&amp;gt;
{
    private readonly ILogger&amp;lt;AvailabilitySearchOptionsSetupService&amp;gt; logger;
    private readonly IReservationSettingsService reservationSettingsService;
	
    public AvailabilitySearchOptionsSetupService(ILogger&amp;lt;AvailabilitySearchOptionsSetupService&amp;gt; logger ,IReservationSettingsService reservationSettingsService)
    {
        this.logger = logger;
        this.reservationSettingsService = reservationSettingsService;
    }
	
    public void Configure(AvailabilitySearchOptions options)
    {
        this.logger.LogInformation($&quot;Calling first {typeof(IConfigureOptions&amp;lt;AvailabilitySearchOptions&amp;gt;)} service&quot;);
        options.MinimumConnectionTime = reservationSettingsService.GetMinimumConnectionTime();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And then registering this class in our container&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    services.Configure&amp;lt;AvailabilitySearchOptions&amp;gt;(Configuration.GetSection(&quot;AvailabilitySearchOptions&quot;));
    services.AddSingleton&amp;lt;IConfigureOptions&amp;lt;AvailabilitySearchOptions&amp;gt;, AvailabilitySearchOptionsSetupService&amp;gt;();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From now on, when value of &lt;code&gt;IOptions&amp;lt;AvailabilitySearchOptions&amp;gt;&lt;/code&gt; is accessed for very first time, &lt;code&gt;Configure&lt;/code&gt; method from &lt;code&gt;AvailabilitySearchOptionsSetupService&lt;/code&gt; will be called and you will be able to set additional values for your settings. Note that values from &lt;code&gt;appsettings.json&lt;/code&gt; will already be there. In addition, it is possible to have multiple implementations of &lt;code&gt;IConfigureOptions&amp;lt;T&amp;gt;&lt;/code&gt; so if you want your setup to be split into multiple classes you are good to go.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/02/asp-net-core-populating-ioptions-external-data-source/multiple.png&quot;&gt;&lt;img src=&quot;images/multiple.png&quot; alt=&quot;multiple&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/AspNetCoreInitializingOptions&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>XUnit - sharing test data across assembly</title><link>https://tpodolak.com/blog/xunit-sharing-test-data-across-assembly/</link><guid isPermaLink="true">https://tpodolak.com/blog/xunit-sharing-test-data-across-assembly/</guid><pubDate>Sun, 19 Feb 2017 14:02:19 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;XUnit&lt;/code&gt; provides two ways of sharing data between tests - &lt;code&gt;ICollectionFixture&lt;/code&gt; and &lt;code&gt;IClassFixture&lt;/code&gt;.
The first one allows you to shared context across collections and the second one across test classes.
I&apos;ve already had a couple of cases in which these fixtures were not enough.
Basically, I wanted to share data between all tests in given assembly - without worrying in which test class or test collection given test is.
In these circumstances, I&apos;ve usually used some kind of old fashioned singleton or custom &lt;code&gt;TestFrameworkExecutor&lt;/code&gt;.
I&apos;ve never liked those solutions, fortunately recently I&apos;ve come across a nice little library - &lt;code&gt;xunit.assemblyfixture&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;2. Usage&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;Xunit.assemblyfixture&lt;/code&gt; allows you to share data between tests in given assembly via &lt;code&gt;IAssemblyFixture&lt;/code&gt; interface. The usage is basically the same as in other &lt;code&gt;XUnit&apos;s&lt;/code&gt; fixtures. All we have to do is to create a class which instance we want to share with other tests&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class TestFixture : IDisposable
{
    public static int InitializationCounter { get; private set; }

    public TestFixture()
    {
        InitializationCounter++;
    }

    public void Dispose()
    {
        // free resources if necessary
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And then create test classes which implement &lt;code&gt;IAssemblyFixture&lt;/code&gt; interface.
If we want to have access to the fixture from the tests, we can inject instance of &lt;code&gt;TFixture&lt;/code&gt; via constructor&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class TestBase : IAssemblyFixture&amp;lt;TestFixture&amp;gt;
{
    protected readonly ITestOutputHelper TestOutputHelper;
    protected readonly TestFixture Fixture;

    protected TestBase(ITestOutputHelper testOutputHelper, TestFixture fixture)
    {
        this.TestOutputHelper = testOutputHelper;
        this.Fixture = fixture;
    }

    protected void DisplayInitializationCount()
    {
        TestOutputHelper.WriteLine($&quot;Initialization count: {TestFixture.InitializationCounter}&quot;);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;Xunit.assemblyfixture&lt;/code&gt; fixture will ensure that given test class is shared via all the tests and is initialized only once.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2017/02/xunit-sharing-test-data-across-assembly/Shared.png&quot;&gt;&lt;img src=&quot;images/Shared.png&quot; alt=&quot;Shared&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;If you want to share multiple classes across the assembly, you can, of course, use &lt;code&gt;IAssemblyFixture&lt;/code&gt; multiple times.&lt;/p&gt;
&lt;h3&gt;3. Visual Studio 2017 - XUnit beta tests runners&lt;/h3&gt;
&lt;p&gt;As for now &lt;code&gt;VS 2017 RC&lt;/code&gt; requires beta runners of &lt;code&gt;XUnit&lt;/code&gt; in order to run our unit tests.
&lt;code&gt;xunit.assemblyfixture&lt;/code&gt; seems not to cooperate with them smoothly.
However, there is a simple workaround to fix that. All we have to do is to add the following attribute to our test project&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[assembly: TestFramework(&quot;Xunit.TestFramework&quot;, &quot;xunit.assemblyfixture&quot;)]

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And from now on, &lt;code&gt;XUnit&lt;/code&gt; correctly can inject assembly fixtures into our test classes&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/XunitSharingFixtureDataAcrossAssembly&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>ASP.NET Core - tracking flow of requests with NLog</title><link>https://tpodolak.com/blog/asp-net-core-tracking-flow-requests-nlog/</link><guid isPermaLink="true">https://tpodolak.com/blog/asp-net-core-tracking-flow-requests-nlog/</guid><pubDate>Sat, 18 Feb 2017 14:11:18 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;A while ago I wrote an &lt;a href=&quot;//tpodolak.com/blog/2016/07/05/nlog-tracking-flow-of-requests-using-mappeddiagnosticslogicalcontext/&quot;&gt;article&lt;/a&gt; about using &lt;code&gt;MappedDiagnosticsLogicalContext&lt;/code&gt; for tracking request flow in your application.
As we are moving our project to &lt;code&gt;ASP.NET Core&lt;/code&gt;, I wanted to keep that functionality in place.
Unfortunately, &lt;code&gt;MDLC&lt;/code&gt; layout renderer is not available in that framework anymore(when targeting &lt;code&gt;.NET Core&lt;/code&gt;).
Luckily, there are two other renderers which can be used as a replacement:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;aspnet-traceidentifier&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;aspnet-item&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;2. Configuring NLog&lt;/h3&gt;
&lt;p&gt;Before I dig into details of layout renderers mentioned above, we have to configure &lt;code&gt;ASP.NET Core&lt;/code&gt; to use &lt;code&gt;NLog&lt;/code&gt; as a logger.
First of all, we need to grab &lt;code&gt;NLog.Web.AspNetCore&lt;/code&gt; &lt;code&gt;NuGet&lt;/code&gt; package. Once the package is installed we have to manually add &lt;code&gt;NLog.config&lt;/code&gt; to the project (the file won&apos;t be added automatically by &lt;code&gt;NuGet&lt;/code&gt; installer).
The next step is to configure &lt;code&gt;NLog&lt;/code&gt; with our config, then configure &lt;code&gt;NLogWeb&lt;/code&gt; and finally register &lt;code&gt;NLog&lt;/code&gt; in &lt;code&gt;LoggingFactory&lt;/code&gt;.
All of these steps should be done in &lt;code&gt;Startup&lt;/code&gt; class.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        // rest of the code omitted for brevity
        env.ConfigureNLog(&quot;NLog.config&quot;);
        // rest of the code omitted for brevity
    }
	
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        // rest of the code omitted for brevity
        loggerFactory.AddNLog();
        app.AddNLogWeb();
        // rest of the code omitted for brevity
    }
}	
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The final step required for &lt;code&gt;NLog&lt;/code&gt; to work is to register &lt;code&gt;HttpContextAccessor&lt;/code&gt; in &lt;code&gt;IoC&lt;/code&gt; container of your choice.
If you use the build one, you can do it like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Startup
{
    // rest of the code omitted for brevity
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton&amp;lt;IHttpContextAccessor, HttpContextAccessor&amp;gt;();
    }
    // rest of the code omitted for brevity
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;3. Using aspnet-traceidentifier renderer&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;Aspnet-traceidentifier&lt;/code&gt; layout renderer allows you to obtain value of &lt;code&gt;TraceIdentifier&lt;/code&gt; property from current &lt;code&gt;HttpContext&lt;/code&gt;.
&lt;code&gt;TraceIdentifier&lt;/code&gt; is basically unique id which identifies the request. The renderer can be used as follows&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&amp;gt;
	&amp;lt;nlog xmlns=&quot;http://www.nlog-project.org/schemas/NLog.xsd&quot;
	      xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	      autoReload=&quot;true&quot;&amp;gt;
	
	  &amp;lt;extensions&amp;gt;
	    &amp;lt;add assembly=&quot;NLog.Web.AspNetCore&quot;/&amp;gt;
	  &amp;lt;/extensions&amp;gt;
	  
	  &amp;lt;targets&amp;gt;
	    &amp;lt;target xsi:type=&quot;File&quot; name=&quot;File&quot; fileName=&quot;${basedir}/logs/${shortdate}.log&quot;
	            layout=&quot;TimeStamp=${longdate} Level=${uppercase:${level}} TraceId=${aspnet-traceidentifier} Message=${message}&quot; /&amp;gt;
	  &amp;lt;/targets&amp;gt;
	   
	  &amp;lt;rules&amp;gt;
	    &amp;lt;logger name=&quot;*&quot; minlevel=&quot;Debug&quot; writeTo=&quot;File&quot; /&amp;gt;
	  &amp;lt;/rules&amp;gt;
&amp;lt;/nlog&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From now on (without any additional configuration) every log entry logged (once &lt;code&gt;HttpContext&lt;/code&gt; is created), will contain &lt;code&gt;TraceIdentifier&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;TimeStamp=2017-02-15 23:10:52.1901 Level=INFO TraceId=0HL2LTTU3JVBI Message=Request starting HTTP/1.1 GET http://localhost:50334/api/values  
TimeStamp=2017-02-15 23:10:52.1941 Level=DEBUG TraceId=0HL2LTTU3JVBI Message=Request successfully matched the route with name &apos;&apos; and template &apos;api/Values&apos;.
TimeStamp=2017-02-15 23:10:52.1941 Level=DEBUG TraceId=0HL2LTTU3JVBI Message=Action &apos;AspNetCoreLoggingWithCorrelationId.Controllers.ValuesController.Post (AspNetCoreLoggingWithCorrelationId)&apos; with id &apos;a133346a-a8f9-4182-ac10-efa1afb18c4d&apos; did not match the constraint &apos;Microsoft.AspNetCore.Mvc.Internal.HttpMethodActionConstraint&apos;
TimeStamp=2017-02-15 23:10:52.1941 Level=DEBUG TraceId=0HL2LTTU3JVBI Message=Executing action AspNetCoreLoggingWithCorrelationId.Controllers.ValuesController.Get (AspNetCoreLoggingWithCorrelationId)
TimeStamp=2017-02-15 23:10:52.2091 Level=INFO TraceId=0HL2LTTU3JVBI Message=Executing action method AspNetCoreLoggingWithCorrelationId.Controllers.ValuesController.Get (AspNetCoreLoggingWithCorrelationId) with arguments () - ModelState is Valid
TimeStamp=2017-02-15 23:10:52.2091 Level=INFO TraceId=0HL2LTTU3JVBI Message=Get method requested
TimeStamp=2017-02-15 23:10:52.2091 Level=INFO TraceId=0HL2LTTU3JVBI Message=Log from Get action, from thread=4
TimeStamp=2017-02-15 23:10:52.2271 Level=INFO TraceId=0HL2LTTU3JVBI Message=Log from Get, from thread 3 assigned by scheduler
TimeStamp=2017-02-15 23:10:52.2271 Level=INFO TraceId=0HL2LTTU3JVBI Message=Log from Get action, from async continuation, from thread 3
TimeStamp=2017-02-15 23:10:52.2422 Level=INFO TraceId=0HL2LTTU3JVBI Message=Log from Get action, from explicitly created thread 15
TimeStamp=2017-02-15 23:10:52.3212 Level=DEBUG TraceId=0HL2LTTU3JVBI Message=Executed action method AspNetCoreLoggingWithCorrelationId.Controllers.ValuesController.Get (AspNetCoreLoggingWithCorrelationId), returned result Microsoft.AspNetCore.Mvc.ObjectResult.
TimeStamp=2017-02-15 23:10:52.3212 Level=DEBUG TraceId=0HL2LTTU3JVBI Message=No information found on request to perform content negotiation.
TimeStamp=2017-02-15 23:10:52.3322 Level=DEBUG TraceId=0HL2LTTU3JVBI Message=Selected output formatter &apos;Microsoft.AspNetCore.Mvc.Formatters.JsonOutputFormatter&apos; and content type &apos;application/json&apos; to write the response.
TimeStamp=2017-02-15 23:10:52.3322 Level=INFO TraceId=0HL2LTTU3JVBI Message=Executing ObjectResult, writing value Microsoft.AspNetCore.Mvc.ControllerContext.
TimeStamp=2017-02-15 23:10:52.3492 Level=INFO TraceId=0HL2LTTU3JVBI Message=Executed action AspNetCoreLoggingWithCorrelationId.Controllers.ValuesController.Get (AspNetCoreLoggingWithCorrelationId) in 140.4884ms
TimeStamp=2017-02-15 23:10:52.3492 Level=INFO TraceId=0HL2LTTU3JVBI Message=Request finished in 170.7178ms 200 application/json; charset=utf-8
TimeStamp=2017-02-15 23:10:52.3672 Level=DEBUG TraceId= Message=Connection id &quot;0HL2LTTU1ONI7&quot; completed keep alive response.

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;4. Using aspnet-item renderer&lt;/h3&gt;
&lt;p&gt;If for some reasons we don’t like to use &lt;code&gt;TraceIdentifier&lt;/code&gt; as our CorrelationId, we can leverage &lt;code&gt;aspnet-item&lt;/code&gt; renderer, which basically allows you to read data from &lt;code&gt;HttpContext.Items&lt;/code&gt; collection.
However in that case, we are responsible for providing and storing unique identifier of request in &lt;code&gt;HttpContext.Items&lt;/code&gt;.
Fortunately it is pretty straightforward to do with custom middleware.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class LoggingMiddleware
{
    private readonly ILogger&amp;lt;LoggingMiddleware&amp;gt; logger;
    private readonly RequestDelegate next;
	
    public LoggingMiddleware(ILogger&amp;lt;LoggingMiddleware&amp;gt; logger, RequestDelegate next)
    {
        this.logger = logger;
        this.next = next;
    }
	
    public async Task Invoke(HttpContext context)
    {
        context.Items[&quot;CorrelationId&quot;] = Guid.NewGuid().ToString();
        logger.LogInformation($&quot;About to start {context.Request.Method} {context.Request.GetDisplayUrl()} request&quot;);
	
        await next(context);

        logger.LogInformation($&quot;Request completed with status code: {context.Response.StatusCode} &quot;);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Of course we have to also use this middleware in our application so we have to add following line&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;app.UseMiddleware&amp;lt;LoggingMiddleware&amp;gt;();

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;in configure method of our &lt;code&gt;Startup&lt;/code&gt; class. Having all the pieces in place, now we can append &lt;code&gt;CorrelationId&lt;/code&gt; read from &lt;code&gt;HttpContext.Items&lt;/code&gt; to our log entries with following configuration&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&amp;gt;
&amp;lt;nlog xmlns=&quot;http://www.nlog-project.org/schemas/NLog.xsd&quot;
      xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
      autoReload=&quot;true&quot;&amp;gt;

  &amp;lt;extensions&amp;gt;
    &amp;lt;add assembly=&quot;NLog.Web.AspNetCore&quot;/&amp;gt;
  &amp;lt;/extensions&amp;gt;
  
  &amp;lt;targets&amp;gt;
    &amp;lt;target xsi:type=&quot;File&quot; name=&quot;File&quot; fileName=&quot;${basedir}/logs/${shortdate}.log&quot;
            layout=&quot;TimeStamp=${longdate} Level=${uppercase:${level}} CorrelationId=${aspnet-item:variable=CorrelationId} Message=${message}&quot; /&amp;gt;
  &amp;lt;/targets&amp;gt;
   
  &amp;lt;rules&amp;gt;
    &amp;lt;logger name=&quot;*&quot; minlevel=&quot;Debug&quot; writeTo=&quot;File&quot; /&amp;gt;
  &amp;lt;/rules&amp;gt;
&amp;lt;/nlog&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From now on, &lt;code&gt;CorrelationId&lt;/code&gt; will be automatically added to our log entries&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;TimeStamp=2017-02-15 23:35:56.8333 Level=INFO CorrelationId= Message=Request starting HTTP/1.1 GET http://localhost:50334/api/values  
TimeStamp=2017-02-15 23:35:56.8333 Level=INFO CorrelationId=15989892-9f27-49d0-88b5-ced61b6851ac Message=About to start GET http://localhost:50334/api/values request
TimeStamp=2017-02-15 23:35:56.8333 Level=DEBUG CorrelationId=15989892-9f27-49d0-88b5-ced61b6851ac Message=Request successfully matched the route with name &apos;&apos; and template &apos;api/Values&apos;.
TimeStamp=2017-02-15 23:35:56.8513 Level=DEBUG CorrelationId=15989892-9f27-49d0-88b5-ced61b6851ac Message=Action &apos;AspNetCoreLoggingWithCorrelationId.Controllers.ValuesController.Post (AspNetCoreLoggingWithCorrelationId)&apos; with id &apos;5d60d23c-ddef-4d20-98eb-a0c03885bea5&apos; did not match the constraint &apos;Microsoft.AspNetCore.Mvc.Internal.HttpMethodActionConstraint&apos;
TimeStamp=2017-02-15 23:35:56.8513 Level=DEBUG CorrelationId=15989892-9f27-49d0-88b5-ced61b6851ac Message=Executing action AspNetCoreLoggingWithCorrelationId.Controllers.ValuesController.Get (AspNetCoreLoggingWithCorrelationId)
TimeStamp=2017-02-15 23:35:56.8513 Level=INFO CorrelationId=15989892-9f27-49d0-88b5-ced61b6851ac Message=Executing action method AspNetCoreLoggingWithCorrelationId.Controllers.ValuesController.Get (AspNetCoreLoggingWithCorrelationId) with arguments () - ModelState is Valid
TimeStamp=2017-02-15 23:35:56.8673 Level=INFO CorrelationId=15989892-9f27-49d0-88b5-ced61b6851ac Message=Get method requested
TimeStamp=2017-02-15 23:35:56.8673 Level=INFO CorrelationId=15989892-9f27-49d0-88b5-ced61b6851ac Message=Log from Get action, from thread=3
TimeStamp=2017-02-15 23:35:56.8923 Level=INFO CorrelationId=15989892-9f27-49d0-88b5-ced61b6851ac Message=Log from Get, from thread 4 assigned by scheduler
TimeStamp=2017-02-15 23:35:56.8993 Level=INFO CorrelationId=15989892-9f27-49d0-88b5-ced61b6851ac Message=Log from Get action, from async continuation, from thread 4
TimeStamp=2017-02-15 23:35:56.8993 Level=INFO CorrelationId=15989892-9f27-49d0-88b5-ced61b6851ac Message=Log from Get action, from explicitly created thread 16
TimeStamp=2017-02-15 23:35:56.9163 Level=DEBUG CorrelationId=15989892-9f27-49d0-88b5-ced61b6851ac Message=Executed action method AspNetCoreLoggingWithCorrelationId.Controllers.ValuesController.Get (AspNetCoreLoggingWithCorrelationId), returned result Microsoft.AspNetCore.Mvc.ObjectResult.
TimeStamp=2017-02-15 23:35:56.9163 Level=DEBUG CorrelationId=15989892-9f27-49d0-88b5-ced61b6851ac Message=No information found on request to perform content negotiation.
TimeStamp=2017-02-15 23:35:56.9274 Level=DEBUG CorrelationId=15989892-9f27-49d0-88b5-ced61b6851ac Message=Selected output formatter &apos;Microsoft.AspNetCore.Mvc.Formatters.JsonOutputFormatter&apos; and content type &apos;application/json&apos; to write the response.
TimeStamp=2017-02-15 23:35:56.9274 Level=INFO CorrelationId=15989892-9f27-49d0-88b5-ced61b6851ac Message=Executing ObjectResult, writing value Microsoft.AspNetCore.Mvc.ControllerContext.
TimeStamp=2017-02-15 23:35:56.9444 Level=INFO CorrelationId=15989892-9f27-49d0-88b5-ced61b6851ac Message=Executed action AspNetCoreLoggingWithCorrelationId.Controllers.ValuesController.Get (AspNetCoreLoggingWithCorrelationId) in 83.2831ms
TimeStamp=2017-02-15 23:35:56.9444 Level=INFO CorrelationId=15989892-9f27-49d0-88b5-ced61b6851ac Message=Request completed with status code: 200 
TimeStamp=2017-02-15 23:35:56.9674 Level=INFO CorrelationId=15989892-9f27-49d0-88b5-ced61b6851ac Message=Request finished in 134.3253ms 200 application/json; charset=utf-8
TimeStamp=2017-02-15 23:35:56.9764 Level=DEBUG CorrelationId= Message=Connection id &quot;0HL2LUBSKVM2T&quot; completed keep alive response.

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;6. It works in multithreading scenarios&lt;/h3&gt;
&lt;p&gt;If you take a closer look at logs presented above, you will see that both of the renderers can log proper &lt;code&gt;CorrelationId&lt;/code&gt;/&lt;code&gt;TraceId&lt;/code&gt; regardless of the thread from which the logger was called. This is possible thanks to implementation of &lt;code&gt;HttpContextAccessor&lt;/code&gt; which uses &lt;code&gt;AsyncLocal&lt;/code&gt; under the hood, which allows you to persist data across threads.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// decompiled code
namespace Microsoft.AspNetCore.Http
{
    public class HttpContextAccessor : IHttpContextAccessor
    {
        private AsyncLocal&amp;lt;HttpContext&amp;gt; _httpContextCurrent = new AsyncLocal&amp;lt;HttpContext&amp;gt;();
	
        public HttpContext HttpContext
        {
            get
            {
                return this._httpContextCurrent.Value;
            }
            set
            {
                this._httpContextCurrent.Value = value;
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/AspNetCoreLoggingWithCorrelationId&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Boxstarter - breaking infinite reboot loop</title><link>https://tpodolak.com/blog/boxstarter-breaking-infinite-reboot-loop/</link><guid isPermaLink="true">https://tpodolak.com/blog/boxstarter-breaking-infinite-reboot-loop/</guid><pubDate>Mon, 19 Dec 2016 23:20:40 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;http://boxstarter.org/&quot;&gt;Boxstarter&lt;/a&gt; is a great tool for configuring your machine without any user interaction.
I&apos;ve been using it for a while now, however recently I&apos;ve noticed that for no apparent reason it wasn&apos;t able to finish the execution of provisioning script as it stuck in infinite reboot loop.
Is was quite frustrating for me, that is why I&apos;ve decided to investigate the problem. Here are my findings.&lt;/p&gt;
&lt;h3&gt;2. Detecting pending reboots&lt;/h3&gt;
&lt;p&gt;If you dive into &lt;code&gt;Boxstarter&lt;/code&gt; source code you will notice that script responsible for checking if reboot is necessary uses &lt;a href=&quot;https://github.com/mwrock/boxstarter/blob/master/Boxstarter.Bootstrapper/Get-PendingReboot.ps1&quot;&gt;Get-PendingReboot&lt;/a&gt; cmdlet.
By default &lt;code&gt;Boxstarter&lt;/code&gt; doesn’t export it, so if you want to see what it does you have to add following line in your &lt;code&gt;Boxstarer&lt;/code&gt; script&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Import-Module (Join-Path $Boxstarter.BaseDir Boxstarter.Bootstrapper\Get-PendingReboot.ps1) -global -DisableNameChecking

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Calling the &lt;code&gt;Get-PendingReboot&lt;/code&gt; cmdlet will give you an information about mandatory reboots. In my case, the output looked as following&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;/tpodolak.com/blog/wp-content/uploads/2016/12/boxstarter-breaking-infinite-reboot-loop/GetPendingReboot.png&quot;&gt;&lt;img src=&quot;images/GetPendingReboot.png&quot; alt=&quot;getpendingreboot&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;As you can see &lt;code&gt;RebootPending&lt;/code&gt; flag is set to true and the reason is that the value of &lt;code&gt;PendingFileRenVal&lt;/code&gt; property is not null. Basically, in most of the cases, a restart is indeed required however, some applications leave information about pending reboot in the registry (&lt;code&gt;HKEY\LOCAL\MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\PendingFileRenameOperations&lt;/code&gt;) and operating system (in some cases) never cleans this up. As a result &lt;code&gt;Get-PendingReboot&lt;/code&gt; indicates that reboot is required and &lt;code&gt;Boxstarter&lt;/code&gt; falls into infinite restart loop.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2016/12/boxstarter-breaking-infinite-reboot-loop/PendingFileRenameOperationsFrame.png&quot;&gt;&lt;img src=&quot;images/PendingFileRenameOperationsFrame.png&quot; alt=&quot;pendingfilerenameoperationsframe&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;3. Fixing the problem&lt;/h3&gt;
&lt;p&gt;The obvious solution is to remove that value from the registry key manually. However this approach didn’t work for me, basically because the registry value somehow was added at the beginning of execution of my script. That is why, I&apos;ve decided to modify my script and add a function which clears undesirable pending file renames of my choice.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function Clear-Known-Pending-Renames($ignoredRenames){
    $regKey = &quot;HKLM:SYSTEM\CurrentControlSet\Control\Session Manager\&quot;
    $regProperty = &quot;PendingFileRenameOperations&quot;
    $pendingReboot = Get-PendingReboot

    Write-BoxstarterMessage &quot;Current pending reboot $($pendingReboot | Out-String)&quot;
    
    if($pendingReboot.PendFileRename){

        $output = $pendingReboot.PendFileRenVal | %{$_ -split [Environment]::NewLine} | ? { 
            $current = $_
            ![string]::IsNullOrWhiteSpace($current) -and ($ignoredRenames | ? { $current.StartsWith($_)  } ).Length -eq 0 } | Get-Unique

        if($output -eq $null){
            $output = @()
        }
        
        Set-ItemProperty -Path $regKey -Name $regProperty -Value ([string]::Join([Environment]::NewLine, $output))
        Write-BoxstarterMessage &quot;Updated pending reboot $(Get-PendingReboot | Out-String)&quot;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see I am taking current value of &lt;code&gt;PendingFileRenameOperations&lt;/code&gt; and remove the entries which I know that will stay there forever. Calling that function as the very first step of my installation script solved the problem and I was able to successfully restore my machine from &lt;code&gt;Boxstarter&lt;/code&gt; script&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2016/12/boxstarter-breaking-infinite-reboot-loop/FullScrtipt.png&quot;&gt;&lt;img src=&quot;images/FullScrtipt.png&quot; alt=&quot;fullscrtipt&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2016/12/boxstarter-breaking-infinite-reboot-loop/PendingFileRenameOperationsClearedFrame.png&quot;&gt;&lt;img src=&quot;images/PendingFileRenameOperationsClearedFrame.png&quot; alt=&quot;pendingfilerenameoperationsclearedframe&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Entire Boxstarter script can be found &lt;a href=&quot;https://github.com/tpodolak/InstallBox&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
</content:encoded></item><item><title>Logstash - reading logs from RabbitMQ</title><link>https://tpodolak.com/blog/elastic-stack-reading-logs-queue/</link><guid isPermaLink="true">https://tpodolak.com/blog/elastic-stack-reading-logs-queue/</guid><pubDate>Thu, 17 Nov 2016 13:53:07 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;In my previous post, I&apos;ve shown how to configure &lt;code&gt;Logstash&lt;/code&gt; to parse logs from files. This is pretty useful however if your application is deployed on multiple servers, you usually log to some kind of central log storage - in my case to queue, &lt;code&gt;RabbitMQ&lt;/code&gt; to be more specific.
In this post, I will show how to configure &lt;code&gt;Logstash&lt;/code&gt; so it reads the logs from that queue.&lt;/p&gt;
&lt;h3&gt;2. Preparing queue&lt;/h3&gt;
&lt;p&gt;Before we move to &lt;code&gt;Logstash&lt;/code&gt; configuration, first of all, we have to prepare &lt;code&gt;RabbitMQ&lt;/code&gt; test instance.
If you don&apos;t have &lt;code&gt;RabbitMQ&lt;/code&gt; yet, go to &lt;a href=&quot;https://www.rabbitmq.com/download.html&quot;&gt;this&lt;/a&gt; website and install the queue.
Once installation is done, go to the installation folder (&lt;code&gt;C:\Program Files\RabbitMQ Server\rabbitmq\server-3.6.5\sbin&lt;/code&gt; in my case) and run in console&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;rabbitmq-plugins.bat enable rabbitmq_management

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This command will prepare &lt;code&gt;RabbitMQ&lt;/code&gt; management website, so it will be easier for us to see what is going on in given queue. In the next step, we have to prepare the queue, the logs will be sent to. You can do it via the website we&apos;ve just enabled (&lt;code&gt;http://localhost:15672/&lt;/code&gt;) or via &lt;code&gt;RabbitMQ&lt;/code&gt; admin console. As I prefer to automate things as much as possible I will do it via command line. What is quite unusual when it comes &lt;code&gt;RabbitMQ CLI&lt;/code&gt; is the fact that it is a python script you have to download and run locally (this is not an executable). The script can be found on management site under this &lt;a href=&quot;http://localhost:15672/cli/rabbitmqadmin&quot;&gt;address&lt;/a&gt;. Once the script is downloaded (in my case it is saved as &lt;code&gt;rabbitmqadmin.py&lt;/code&gt;) you can start preparing necessary elements: exchange, queue and the binding.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;python rabbitmqadmin.py declare exchange name=logger type=topic -u username -p password

python rabbitmqadmin.py declare queue  name=MyAppLogginQueue auto_delete=false durable=true -u username -p password

python rabbitmqadmin.py  declare binding source=logger destination=MyAppLogginQueue routing_key=MyApp -u username -p password

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see I&apos;ve created exchange called &lt;code&gt;logger&lt;/code&gt; which is bound to &lt;code&gt;MyAppLogginQueue&lt;/code&gt; queue using &lt;code&gt;MyApp&lt;/code&gt; route. This means that every message with topic &lt;code&gt;MyApp&lt;/code&gt; sent to &lt;code&gt;logger&lt;/code&gt; exchange will be pushed to &lt;code&gt;MyAppLogginQueue&lt;/code&gt; .&lt;/p&gt;
&lt;h3&gt;3. Preparing Logstash&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;Logstash&lt;/code&gt; configuration will be modified version of my &lt;a href=&quot;http://tpodolak.com/blog/2016/11/03/logstash-parsing-multiline-log-entries/&quot;&gt;previous&lt;/a&gt; config. I will just add another input source. Here is a basic usage&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;input {	
	rabbitmq {
        host =&amp;gt; &quot;localhost&quot;
        queue =&amp;gt; &quot;MyAppLogginQueue&quot;
        heartbeat =&amp;gt; 30
        durable =&amp;gt; true
        password =&amp;gt; &quot;password&quot;
        user =&amp;gt; &quot;username&quot;
    }
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see we will be consuming messages from &lt;code&gt;MyAppLogginQueue&lt;/code&gt; which is deployed on &lt;code&gt;localhost&lt;/code&gt;.
For &lt;code&gt;password&lt;/code&gt; and &lt;code&gt;user&lt;/code&gt; properties use your own credentials. That is basically it, so now it is time to see if everything is working.&lt;/p&gt;
&lt;h3&gt;4. Testing coniguration&lt;/h3&gt;
&lt;p&gt;In order to test the configuration you have to run the &lt;code&gt;Elasticsearch&lt;/code&gt;, &lt;code&gt;Kibana&lt;/code&gt; and use new config for &lt;code&gt;Logstash&lt;/code&gt;.
I&apos;ve shown how to do it in one of my &lt;a href=&quot;http://tpodolak.com/blog/2016/11/02/getting-started-elastic-stack/&quot;&gt;recent post&lt;/a&gt;.
For sending messages to the queue I will just use &lt;code&gt;RabbitMQ&lt;/code&gt; management website &lt;code&gt;API&lt;/code&gt;. The &lt;code&gt;API&lt;/code&gt; exposes&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;api/exchanges/%2F/{exchange_name}/publish

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;endpoint accepting &lt;code&gt;POST&lt;/code&gt; verbs which can be used for publishing messages to given exchange. In my case &lt;code&gt;POST&lt;/code&gt; body will look as follows&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;vhost&quot;: &quot;/&quot;,
  &quot;name&quot;: &quot;logger&quot;,
  &quot;properties&quot;: {
    &quot;delivery_mode&quot;: 2,
    &quot;headers&quot;: {}
  },
  &quot;routing_key&quot;: &quot;MyApp&quot;,
  &quot;delivery_mode&quot;: &quot;2&quot;,
  &quot;payload&quot;: &quot;TimeStamp=2016-11-01 00:13:01.1669 CorrelationId=77530786-8e6b-45c2-bbc1-31837d911c14 Level=INFO Message=Request completed with status code: 200&quot;,
  &quot;headers&quot;: {},
  &quot;props&quot;: {},
  &quot;payload_encoding&quot;: &quot;string&quot;
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and I will be sending it to&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;http://localhost:15672/api/exchanges/%2F/logger/publish

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that I will be sending messages to the exchange, not to the queue itself. The exchange&apos;s responsibility is to route the message to all bound queues. Here is how it looks in practice&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/11/elastic-stack-reading-logs-queue/ezgif.com-gif-maker.gif&quot;&gt;&lt;img src=&quot;images/ezgif.com-gif-maker.gif&quot; alt=&quot;ezgif-com-gif-maker&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;As you can see our configuration is valid and messages are shown on &lt;code&gt;Kibana&apos;s&lt;/code&gt; dashboard almost in real time.&lt;/p&gt;
&lt;p&gt;Full &lt;code&gt;Logstash&lt;/code&gt; config can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/ElasticStackReadingFromRabbitMQ&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Logstash - parsing multiline log entries</title><link>https://tpodolak.com/blog/logstash-parsing-multiline-log-entries/</link><guid isPermaLink="true">https://tpodolak.com/blog/logstash-parsing-multiline-log-entries/</guid><pubDate>Thu, 03 Nov 2016 20:26:28 GMT</pubDate><content:encoded>&lt;p&gt;In my previous &lt;a href=&quot;http://tpodolak.com/blog/2016/11/02/getting-started-elastic-stack/&quot;&gt;post&lt;/a&gt; I&apos;ve shown how to configure &lt;code&gt;Logstash&lt;/code&gt; so that, it would be able to parse the logs in custom format.
Configuration presented in that post had one significant drawback - it wasn&apos;t able to parse multiline log entries.
This is a rather common scenario, especially when you log exceptions with a stack trace. Log entry, in that case may look as follows&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;TimeStamp=2016-11-01 02:08:02.9086 CorrelationId=69dd69bb-3457-4440-8f77-88b1fd39255a Level=ERROR Message=System.InvalidOperationException: Operation is not valid due to the current state of the object.
   at AspNetMvcLoggingWithCorrelationId.Controllers.HomeController.&amp;lt;About&amp;gt;d__2.MoveNext() in E:\Tomek\Programowanie\BlogSrc\AspNetMvcLoggingWithCorrelationId\AspNetMvcLoggingWithCorrelationId\Controllers\HomeController.cs:line 24
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.&amp;lt;&amp;gt;c__DisplayClass37.&amp;lt;BeginInvokeAsynchronousActionMethod&amp;gt;b__36(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.&amp;lt;InvokeActionMethodFilterAsynchronouslyRecursive&amp;gt;b__3d()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.&amp;lt;&amp;gt;c__DisplayClass46.&amp;lt;InvokeActionMethodFilterAsynchronouslyRecursive&amp;gt;b__3f()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.&amp;lt;&amp;gt;c__DisplayClass33.&amp;lt;BeginInvokeActionMethodWithFilters&amp;gt;b__32(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.&amp;lt;&amp;gt;c__DisplayClass21.&amp;lt;&amp;gt;c__DisplayClass2b.&amp;lt;BeginInvokeAction&amp;gt;b__1c()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.&amp;lt;&amp;gt;c__DisplayClass21.&amp;lt;BeginInvokeAction&amp;gt;b__1e(IAsyncResult asyncResult)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Parsing these kind of messages using current configuration will result in grok parsing error&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/11/elastic-stack-parsing-multiline-log-entries/GrokFailure.png&quot;&gt;&lt;img src=&quot;images/GrokFailure.png&quot; alt=&quot;grokfailure&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;and we won&apos;t be able to search against predefined fields.
Fortunately &lt;code&gt;Logstash&lt;/code&gt; allows you to configure something called &lt;code&gt;input codecs&lt;/code&gt; which basically allows you to transform input data into some other form.
One of those codes is &lt;code&gt;multiline codec&lt;/code&gt;, which is responsible for &quot;merging&quot; multiline logs into one entry.
Here is example of codec configuration&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;codec =&amp;gt; multiline {
                       pattern =&amp;gt; &quot;^TimeStamp=%{TIMESTAMP_ISO8601}&quot;
                       negate =&amp;gt; true
                       what =&amp;gt; &quot;
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The code above says that any line not starting with a &lt;code&gt;TimeStamp=timestamp value&lt;/code&gt; should be merged with the previous line. Multiline coded can be added to a variety of inputs. Here is how you can apply it to &lt;code&gt;file&lt;/code&gt; input&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;input {
    file {
        path =&amp;gt; [&quot;E:/Tomek/Programowanie/BlogSrc/ElasticStackParsingMultilineEntries/logs/*.log&quot;]
        start_position =&amp;gt; beginning
        ignore_older =&amp;gt; 0
        sincedb_path =&amp;gt; &quot;NUL&quot;
        codec =&amp;gt; multiline {
                               pattern =&amp;gt; &quot;^TimeStamp=%{TIMESTAMP_ISO8601}&quot;
                               negate =&amp;gt; true
                               what =&amp;gt; &quot;previous&quot;
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Thanks to that change, &lt;code&gt;Logstash&lt;/code&gt; is now able to correctly parse exceptions from our logs.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/11/logstash-parsing-multiline-log-entries/Fixed2.png&quot;&gt;&lt;img src=&quot;images/Fixed2.png&quot; alt=&quot;fixed2&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/ElasticStackParsingMultilineEntries&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Getting started with Elastic Stack</title><link>https://tpodolak.com/blog/getting-started-elastic-stack/</link><guid isPermaLink="true">https://tpodolak.com/blog/getting-started-elastic-stack/</guid><pubDate>Wed, 02 Nov 2016 19:38:24 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;In one of my previous post I&apos;ve shown how to improve logging in an application by tracking the flow of incoming requests.
Now it is time to show the basics of &lt;code&gt;Elastic stack&lt;/code&gt; to make searching across multiple log files/sources a piece of cake.
&lt;code&gt;Elastic stack&lt;/code&gt; (previously called &lt;code&gt;ELK stack&lt;/code&gt;) is set of three tools which allows you to parse (&lt;code&gt;Logstash&lt;/code&gt;), query (&lt;code&gt;Elasticsearch&lt;/code&gt;) and visualize (&lt;code&gt;Kibana&lt;/code&gt;) logs with ease.&lt;/p&gt;
&lt;h3&gt;2. Installation&lt;/h3&gt;
&lt;p&gt;First of all (as usual) we have to get the tools, so go to &lt;a href=&quot;https://www.elastic.co/downloads&quot;&gt;elastic.co&lt;/a&gt; and download apps mentioned before.
These are stand-alone applications so no installation is required.
The only requirement is to have &lt;code&gt;JAVA\&lt;/code&gt;HOME_ system variable pointing to your java directory. In my case, this looks as follows&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;C:\Program Files\Java\jre1.8.0_91\

&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;3. Elasticsearch&lt;/h3&gt;
&lt;p&gt;Once all three applications are downloaded we can run &lt;code&gt;Elasticsearch&lt;/code&gt; (as there is not additional configuration needed for basic usage) instance via an &lt;code&gt;elasticsearch.bat&lt;/code&gt; file.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/10/getting-started-elastic-stack/ElasticSearchWeb-1.png&quot;&gt;&lt;img src=&quot;images/ElasticSearchWeb-1.png&quot; alt=&quot;elasticsearchweb&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;4. Logstash&lt;/h3&gt;
&lt;p&gt;Having our &lt;code&gt;Elasticsearch&lt;/code&gt; instance up and running, now it is time configure &lt;code&gt;Logstash&lt;/code&gt; so that it will be able to parse logs.
Configuration provided in next sections will be able to parse logs with the following format&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;TimeStamp=2016-07-20 21:22:46.0079 CorrelationId=dc665fe7-9734-456a-92ba-3e1b522f5fd4 Level=INFO Message=About to start GET / request

&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;4.1. Configuration&lt;/h4&gt;
&lt;p&gt;&lt;code&gt;Logstash&lt;/code&gt; configuration is done via config file in specific format.
You can read about that &lt;a href=&quot;https://www.elastic.co/guide/en/logstash/current/configuration-file-structure.html&quot;&gt;here&lt;/a&gt;.
The very first step is to define input and output sections&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;input {
    file {
        path =&amp;gt; [&quot;C:/logs/*.log&quot;]
        start_position =&amp;gt; beginning
    }
}
output {
    elasticsearch {
        hosts =&amp;gt; &quot;localhost:9200&quot;
    }
    stdout {}
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see the logs will be read from &lt;code&gt;C:\logs&lt;/code&gt; directory and parsed content will be pushed to &lt;code&gt;Elasticsearch&lt;/code&gt; instance and to the console output.
We can verify correctness of configuration calling&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;logstash.bat -f  &quot;Path\To\Config\File.conf&quot; -t

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/10/getting-started-elastic-stack/ConfigurationTest.png&quot;&gt;&lt;img src=&quot;images/ConfigurationTest.png&quot; alt=&quot;configurationtest&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;If you are making your config file for the first time it is good idea to add additional properties to the &lt;code&gt;file&lt;/code&gt; section&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ignore_older =&amp;gt; 0
sincedb_path =&amp;gt; &quot;NUL&quot;

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This will force &lt;code&gt;Logstash&lt;/code&gt; to reparse entire file when restarted and will also make sure that older files are not ignored (by default files modified more than 24 hours ago are ignored).&lt;/p&gt;
&lt;p&gt;At this point, &lt;code&gt;Logstash&lt;/code&gt; can read the log file but it doesn’t do anything special with it.
Next step is to configure a pattern which will be used for log parsing. &lt;code&gt;Logstash&lt;/code&gt; uses &lt;code&gt;grok&lt;/code&gt; for defining the patterns.
Long story short it is kind of a regex which can use predefined patterns.
The easiest way to play around with it is to use &lt;a href=&quot;http://grokconstructor.appspot.com/&quot;&gt;grokconstructor&lt;/a&gt;, for list of ready to use patterns take a look at &lt;a href=&quot;https://www.elastic.co/guide/en/logstash/current/plugins-filters-grok.html&quot;&gt;this&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;For parsing logs shown in previous section I&apos;ve ended up with this grok pattern&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;TimeStamp=%{TIMESTAMP_ISO8601:logdate} CorrelationId=%{UUID:correlationId} Level=%{LOGLEVEL:logLevel} Message=%{GREEDYDATA:logMessage}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Notice that you are able to give aliases for particular fields, for instance&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;TimeStamp=%{TIMESTAMP_ISO8601:logdate} 

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;means that everything that matches &lt;code&gt;TimeStamp=%{TIMESTAMP\ISO8601}&lt;/code&gt; will be stored in &lt;code&gt;logdate&lt;/code&gt; field.
Having defined our pattern, now we can add it to the config file. After modifications, it looks as follows&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;input {
    file {
        path =&amp;gt; [&quot;C:/logs/*.log&quot;]
        start_position =&amp;gt; beginning
    }
}
filter {
    grok {
        match =&amp;gt; { &quot;message&quot; =&amp;gt; &quot;TimeStamp=%{TIMESTAMP_ISO8601:logdate} CorrelationId=%{UUID:correlationId} Level=%{LOGLEVEL:logLevel} Message=%{GREEDYDATA:logMessage}&quot; }
    }
}
output {
    elasticsearch {
        hosts =&amp;gt; &quot;localhost:9200&quot;
    }
    stdout {}
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Once we run this config and start querying elastic search for list of all indices via&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;http://localhost:9200/_cat/indices?v

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;we will see that our logs were parsed and stored in index called &lt;code&gt;logstash-2016.10.30&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/10/getting-started-elastic-stack/indices.png&quot;&gt;&lt;img src=&quot;images/indices.png&quot; alt=&quot;indices&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;If we now go to&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;http://localhost:9200/logstash-2016.10.30

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;we will be able to see index information&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/10/getting-started-elastic-stack/IndexInfo-1.png&quot;&gt;&lt;img src=&quot;images/IndexInfo-1.png&quot; alt=&quot;indexinfo&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h4&gt;4.2. Fixing the date fields&lt;/h4&gt;
&lt;p&gt;At this moment there are two main problems with our configuration.
First of all, the indices are created based on read time from file. Second of all our &lt;code&gt;logdate&lt;/code&gt; field is treated as string.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/10/getting-started-elastic-stack/logdateasstring.png&quot;&gt;&lt;img src=&quot;images/logdateasstring.png&quot; alt=&quot;logdateasstring&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;By default &lt;code&gt;Logstash&lt;/code&gt; creates indices based on read time of the source.
However in my opinion it is better to create index names based on time given event occurred.
In order to do that, we have to tell the &lt;code&gt;Logstash&lt;/code&gt; which field is responsible for holding timestamp.
In my case, this field is called &lt;code&gt;logdate&lt;/code&gt;. All we have to do is to map this field into field via date filter&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;date {
        match =&amp;gt; [ &quot;logdate&quot;, &quot;yyyy-MM-dd HH:mm:ss.SSSS&quot; ]
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see first argument is a filed name and rest of the arguments (you can specify more) are just date time formats.
By default date filter maps a field from the &lt;code&gt;match&lt;/code&gt; property into &lt;code&gt;@timestamp&lt;/code&gt; field. So the config above equals this one&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;date {
        match =&amp;gt; [ &quot;logdate&quot;, &quot;yyyy-MM-dd HH:mm:ss.SSSS&quot; ]
        target =&amp;gt; &quot;@timestamp&quot;
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If we restart &lt;code&gt;Logstash&lt;/code&gt; and get the indices, we will see something similar to that&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/10/getting-started-elastic-stack/multipleindices.png&quot;&gt;&lt;img src=&quot;images/multipleindices.png&quot; alt=&quot;multipleindices&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Second problem can be handled in very similar way. We have to add second date filter and select as target &lt;code&gt;longdate&lt;/code&gt; field&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;date {
        match =&amp;gt; [ &quot;logdate&quot;, &quot;yyyy-MM-dd HH:mm:ss.SSSS&quot; ]
        target =&amp;gt; &quot;logdate&quot;
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From now on &lt;code&gt;logdate&lt;/code&gt; field will be treated as date so we will be able to filter the logs easily with &lt;code&gt;Kibana&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/10/getting-started-elastic-stack/logdateasdate.png&quot;&gt;&lt;img src=&quot;images/logdateasdate.png&quot; alt=&quot;logdateasdate&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;5. Running Kibana&lt;/h3&gt;
&lt;p&gt;Having all the configuration in place now we are ready to run &lt;code&gt;Kibana&lt;/code&gt;.
As in previous steps, no installation is needed so just run the &lt;code&gt;Kibana.bat&lt;/code&gt; file&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/10/getting-started-elastic-stack/kibanastarted.png&quot;&gt;&lt;img src=&quot;images/kibanastarted.png&quot; alt=&quot;kibanastarted&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;and go to&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;http://localhost:5601/

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you run the app for the first time you will be asked to configure the indices.
You can use the default parameters and just click &lt;code&gt;Create&lt;/code&gt; button.
Once the indices are setup you can start writing queries against the logs.
By default entire message is searched for the search terms, however the real power comes with queries written against specific fields.
For example, you can search for any errors in the application with this simple query&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;logLevel: (FATAL OR ERROR)

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Thanks to date type fields, you can combine this query with date range selector and narrow down time to specific values, just like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;logdate:[2016-07-20 TO 2016-10-31] AND logLevel: (FATAL OR ERROR)

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/10/getting-started-elastic-stack/kibanasearchresults-1.png&quot;&gt;&lt;img src=&quot;images/kibanasearchresults-1.png&quot; alt=&quot;kibanasearchresults&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;These are just the basic queries you can run in Kibana, for more advanced scenarios please visit &lt;a href=&quot;https://www.elastic.co/guide/en/elasticsearch/reference/5.0/query-dsl-query-string-query.html#query-string-syntax&quot;&gt;website&lt;/a&gt;.
I also strongly encourage you guys to take a look at other feature &lt;code&gt;Elastic stack&lt;/code&gt; provides.
Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/GettingStartedWithElasticStack&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;PS Configuration presented in this post will not be able to parse multiline log entries e.g. exceptions. I will show you how to do it in the next post.&lt;/p&gt;
</content:encoded></item><item><title>RedisSessionStateProvider - unknown command &apos;EVAL&apos;</title><link>https://tpodolak.com/blog/redissessionstateprovider-unknown-command-eval/</link><guid isPermaLink="true">https://tpodolak.com/blog/redissessionstateprovider-unknown-command-eval/</guid><pubDate>Sat, 29 Oct 2016 18:33:27 GMT</pubDate><content:encoded>&lt;p&gt;A couple of days ago I was trying to use &lt;code&gt;Redis&lt;/code&gt; as session storage for one of my ASP .NET websites. Even though it seemed to be a rather straightforward task (Scott Hanselman wrote about that a &lt;a href=&quot;http://www.hanselman.com/blog/UsingRedisAsAServiceInAzureToSpeedUpASPNETApplications.aspx&quot;&gt;while ago&lt;/a&gt;), I ended up with some weird exception while running the app: &lt;code&gt;ERR unknown command &apos;EVAL&apos;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/10/redissessionstateprovider-unknown-command-eval/UnknownCommandEval.png&quot;&gt;&lt;img src=&quot;images/UnknownCommandEval.png&quot; alt=&quot;unknown command &apos;EVAL&apos;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;This wasn’t for sure a connectivity issue, as I was able to connect to &lt;code&gt;Redis&lt;/code&gt; server from &lt;code&gt;Redis Client&lt;/code&gt; - &lt;code&gt;redis-cli&lt;/code&gt;. For me it looked like my server is not able to &quot;understand&quot; &lt;code&gt;EVAL&lt;/code&gt; command. I started digging around and it turned out that this command has been introduced in version &lt;a href=&quot;http://redis.io/commands/EVAL&quot;&gt;2.6.0&lt;/a&gt; I&apos;ve connected to the server using &lt;code&gt;redis-cli&lt;/code&gt; and checked the version with
&lt;code&gt;info&lt;/code&gt; command and basically that revealed the problem.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/10/redissessionstateprovider-unknown-command-eval/RedisCli.png&quot;&gt;&lt;img src=&quot;images/RedisCli.png&quot; alt=&quot;rediscli&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;As you can see I&apos;ve accidentally installed version 2.4.6 (I have no idea how I ended up with so old version). After upgrading to the newest one, my problem was gone and I was able to successfully store session in &lt;code&gt;Redis&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/10/redissessionstateprovider-unknown-command-eval/Working.png&quot;&gt;&lt;img src=&quot;images/Working.png&quot; alt=&quot;working&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Visual Studio - restoring default exception window</title><link>https://tpodolak.com/blog/visual-studio-restoring-default-exception-window/</link><guid isPermaLink="true">https://tpodolak.com/blog/visual-studio-restoring-default-exception-window/</guid><pubDate>Tue, 25 Oct 2016 19:22:33 GMT</pubDate><content:encoded>&lt;p&gt;I think everyone is familiar with this nice exception window we see once exception is thrown.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/10/visual-studio-restoring-default-exception-window/DefaultException.png&quot;&gt;&lt;img src=&quot;images/DefaultException.png&quot; alt=&quot;exceptionwindow&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;However today for some reasons my &lt;code&gt;VisualStudio&lt;/code&gt; started showing some weird dialog.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/10/visual-studio-restoring-default-exception-window/ExceptionWindow.png&quot;&gt;&lt;img src=&quot;images/ExceptionWindow.png&quot; alt=&quot;exceptionwindow&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;This was pretty frustrating as I wasn’t able to see which line has thrown exception and basically after clicking &lt;code&gt;Break&lt;/code&gt; or &lt;code&gt;Continue&lt;/code&gt; application was terminated.
After a while I found out that the default window is called &lt;code&gt;Exception assistant&lt;/code&gt; and you can enable it in &lt;code&gt;Visual Studio&apos;s&lt;/code&gt; options.
So in order to restore default behavior, just go to &lt;code&gt;Tools -&amp;gt; Options -&amp;gt; Debugging -&amp;gt; General&lt;/code&gt; and select &lt;code&gt;Enable the exception assistant&lt;/code&gt; checkbox.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/10/visual-studio-restoring-default-exception-window/EnableExceptionAssistant.png&quot;&gt;&lt;img src=&quot;images/EnableExceptionAssistant.png&quot; alt=&quot;enableexceptionassistant&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Fiddler - request redirection</title><link>https://tpodolak.com/blog/fiddler-redirecting-outgoing-calls-local-server/</link><guid isPermaLink="true">https://tpodolak.com/blog/fiddler-redirecting-outgoing-calls-local-server/</guid><pubDate>Wed, 28 Sep 2016 20:25:12 GMT</pubDate><content:encoded>&lt;p&gt;As a back-end developer I am quite often contacted by front-end devs to take a look why certain &lt;code&gt;UI&lt;/code&gt; calls to the server results in wrong data being returned by &lt;code&gt;API&lt;/code&gt;.
Usually I am provided with request payload so it is quite straightforward to reply it with &lt;code&gt;Postman&lt;/code&gt; or &lt;code&gt;Fiddler&lt;/code&gt; and see what is going on the backend.
However for time to time, replying single request is not enough to reproduce the problem.
In that case it is easier to just recreate the scenario on the &lt;code&gt;UI&lt;/code&gt; and debug the &lt;code&gt;API&lt;/code&gt; during that process.
Unfortunately this approach requires backend devs to have &lt;code&gt;UI&lt;/code&gt; up and running on their local machines and that is not always possible (e.g. you might not get access to &lt;code&gt;UI&lt;/code&gt; repository).
Fortunately with &lt;code&gt;Fiddler&lt;/code&gt; it is quite easy to intercept outgoing front-end calls to the &lt;code&gt;API&lt;/code&gt; and redirect them to your locally deployed version (so you can easily debug the &lt;code&gt;API&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;Let&apos;s assume we would like to redirect all &lt;code&gt;simpletestspa.azurewebsites.net&lt;/code&gt; calls &lt;code&gt;to localhost:50277&lt;/code&gt;. In order to do that run &lt;code&gt;Fiddler&lt;/code&gt; and go to &lt;code&gt;Tools -&amp;gt; Hosts…&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/09/fiddler-redirecting-outgoing-calls-to-local-server/Toolsv2.png&quot;&gt;&lt;img src=&quot;images/Toolsv2.png&quot; alt=&quot;Fiddler - tools&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Select &quot;&lt;code&gt;Enable remapping of requests for one host to a different host or IP, overriding DNS&lt;/code&gt;&quot; checkbox&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/09/fiddler-redirecting-outgoing-calls-to-local-server/HostsWindow.png&quot;&gt;&lt;img src=&quot;images/HostsWindow.png&quot; alt=&quot;Fiddler - hosts window&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;and enter following values in the editor&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;localhost:50277 simpletestspa.azurewebsites.net

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From now every outgoing request to &lt;code&gt;simpletestspa.azurewebsites.net&lt;/code&gt; will be redirected to your local instance of the server on &lt;code&gt;localhost:50277&lt;/code&gt;.&lt;/p&gt;
</content:encoded></item><item><title>Cake - Data at the root level is invalid</title><link>https://tpodolak.com/blog/cake-data-root-level-invalid/</link><guid isPermaLink="true">https://tpodolak.com/blog/cake-data-root-level-invalid/</guid><pubDate>Thu, 08 Sep 2016 20:55:01 GMT</pubDate><content:encoded>&lt;p&gt;Couple of weeks &lt;a href=&quot;http://tpodolak.com/blog/2016/07/10/debugging-cake-scripts/&quot;&gt;ago&lt;/a&gt; I mentioned that in my current project we use &lt;code&gt;Cake&lt;/code&gt; as a build mechanism.
Recently we wanted to add simple functionality to our build script, which would allow us to modify one of the &lt;code&gt;App.config&lt;/code&gt;&apos;s properties.
According to the documentation it should be a straightforward tasks, as all the heavy lifting can be done via &lt;code&gt;XmlPeek&lt;/code&gt; and &lt;code&gt;XmlPoke&lt;/code&gt; aliases.&lt;/p&gt;
&lt;p&gt;Our initial script looked as follows&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Task(&quot;Update-Version&quot;)
.Does(()=&amp;gt;
{
    var appConfigPath = paths.Directories.Project + &quot;/&quot; + Context.File(&quot;App.config&quot;);
    var version = GetVersion(appConfigPath);
    Information(&quot;Current version: {0}&quot;, version);
    XmlPokeString(File(appConfigPath), xPathVersionSelector, (++version).ToString());
    version = GetVersion(appConfigPath);
    Information(&quot;Updated version: {0}&quot;, version);
});

private int GetVersion(string appConfigPath)
{
    return int.Parse(XmlPeek(appConfigPath, xPathVersionSelector));
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And what was surprising for us, it didn&apos;t work.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/09/cake-data-at-the-root-level-is-invalid/DataAtTheRootLevel.png&quot;&gt;&lt;img src=&quot;images/DataAtTheRootLevel.png&quot; alt=&quot;dataattherootlevel&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;We got a bit weird error &lt;code&gt;&quot;Data at the root level is invalid. Line 1, position 1&quot;&lt;/code&gt;.
The exception suggested that there was something wrong with our &lt;code&gt;App.config&lt;/code&gt; file. However if you look at the picture presented above, you will see that we were able to successfully read the file and retrieve value of &lt;code&gt;Version&lt;/code&gt; with &lt;code&gt;XmlPeek&lt;/code&gt; method.
After a bit of digging it turned out that &lt;code&gt;XmlPoke&lt;/code&gt; and &lt;code&gt;XmlPokeString&lt;/code&gt; are not able to work with relative paths and we have to use absolute one in order to make it work.
Fortunately there is an easy way to do that, namely &lt;code&gt;MakeAbsolute&lt;/code&gt; method. Out script after modifications looks that way&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Task(&quot;Update-Version&quot;)
.Does(()=&amp;gt;
{
    var appConfigPath = paths.Directories.Project + &quot;/&quot; + Context.File(&quot;App.config&quot;);
    var version = GetVersion(appConfigPath);
    Information(&quot;Current version: {0}&quot;, version);
    XmlPoke(MakeAbsolute(File(appConfigPath)), xPathVersionSelector, (++version).ToString());
    version = GetVersion(appConfigPath);
    Information(&quot;Updated version: {0}&quot;, version);
});

private int GetVersion(string appConfigPath)
{
    return int.Parse(XmlPeek(appConfigPath, xPathVersionSelector));
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And now everything works fine&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/09/cake-data-at-the-root-level-is-invalid/after.png&quot;&gt;&lt;img src=&quot;images/after.png&quot; alt=&quot;after&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/CakeDataAtTheRootLevelIsInvalid&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Intercepting browser requests with Postman</title><link>https://tpodolak.com/blog/intercepting-browser-requests-postman/</link><guid isPermaLink="true">https://tpodolak.com/blog/intercepting-browser-requests-postman/</guid><pubDate>Sun, 24 Jul 2016 22:39:19 GMT</pubDate><content:encoded>&lt;p&gt;If you are doing any kind of rest api development you probably have heard of &lt;code&gt;Postman&lt;/code&gt;.
Long story short, it is a &lt;code&gt;Chrome&lt;/code&gt; extension which allows you to send http requests in a very easy and intuitive way.
Apart from that (and many other features), it also allows you to intercept browser request.
As this feature is very easy to overlook, here is a simple guide how to use it.&lt;/p&gt;
&lt;p&gt;In the &lt;code&gt;Postman&lt;/code&gt; window, click little satellite look-like button and toggle the &lt;code&gt;Interceptor&lt;/code&gt; switch&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/07/intercepting-browser-requests-postman/SwitchRed.png&quot;&gt;&lt;img src=&quot;images/SwitchRed.png&quot; alt=&quot;Postman switch interceptor&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;Postman&lt;/code&gt; will ask you to install additional plugin called &lt;code&gt;Postman Interceptor&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/07/intercepting-browser-requests-postman/Install.png&quot;&gt;&lt;img src=&quot;images/Install.png&quot; alt=&quot;Install&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Once you click &lt;code&gt;Install&lt;/code&gt; you will be redirected to &lt;code&gt;Chrome Web Store&lt;/code&gt; where you can add the plugin to the browser.
After successful installation you will see additional icon in &lt;code&gt;Chrome&lt;/code&gt; menu bar.
Click it and toggle &lt;code&gt;Request capture&lt;/code&gt; switch&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/07/intercepting-browser-requests-postman/CaptureEnabled.png&quot;&gt;&lt;img src=&quot;images/CaptureEnabled.png&quot; alt=&quot;CaptureEnabled&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;When you go back to &lt;code&gt;Postman&lt;/code&gt; and toggle again &quot;Interceptor&quot; button, it will be synchronized with &lt;code&gt;Postman Interceptor&lt;/code&gt; plugin&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/07/intercepting-browser-requests-postman/InSync.png&quot;&gt;&lt;img src=&quot;images/InSync.png&quot; alt=&quot;InSync&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;and from now on, requests sent by browser will be visible in requests history&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/07/intercepting-browser-requests-postman/Interception.gif&quot;&gt;&lt;img src=&quot;images/Interception.gif&quot; alt=&quot;Interception&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;where you will be able to modify and resend them.&lt;/p&gt;
</content:encoded></item><item><title>Generating PDB files with Resharper</title><link>https://tpodolak.com/blog/generating-pdb-files-resharper/</link><guid isPermaLink="true">https://tpodolak.com/blog/generating-pdb-files-resharper/</guid><pubDate>Sun, 17 Jul 2016 10:40:59 GMT</pubDate><content:encoded>&lt;p&gt;The majority of the libraries developers use in their projects these days are open source.
So in case something crashes inside third party library or you just want to know how it works, it is possible to get the &lt;code&gt;PDB&lt;/code&gt; files from &lt;code&gt;Microsoft Symbols Servers&lt;/code&gt; and debug it.
If for some reasons &lt;code&gt;PDB&lt;/code&gt; cannot be found on the servers, you can always grab the source code from &lt;code&gt;GitHub&lt;/code&gt; and add to your project manually.
Unfortunately when you use commercial libraries, it is impossible to do any of the previous steps.
Luckily with &lt;code&gt;Resharper&lt;/code&gt; you are able to generate &lt;code&gt;PDB&lt;/code&gt; files from assembly and use it later in &lt;code&gt;Visual Studio&lt;/code&gt; to debug it.
Let&apos;s assume we would like to generate &lt;code&gt;PDB&lt;/code&gt; files for &lt;code&gt;EntityFramework&lt;/code&gt;.
First of all, we have to locate &lt;code&gt;EntityFramework&lt;/code&gt; assembly in &lt;code&gt;Assembly Explorer&lt;/code&gt;.
Go to &lt;code&gt;Solution Explorer&lt;/code&gt;, &lt;code&gt;RMB&lt;/code&gt; click on assembly you are interested in and select &lt;code&gt;View in Assembly Explorer&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/07/generating-pdb-files-with-resharper/ViewInAssemblyExplorer.png&quot;&gt;&lt;img src=&quot;images/ViewInAssemblyExplorer.png&quot; alt=&quot;ViewInAssemblyExplorer&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In &lt;code&gt;Assembly Explorer&lt;/code&gt; once again &lt;code&gt;RMB&lt;/code&gt; click on &lt;code&gt;EntityFramework&lt;/code&gt; and select &quot;&lt;code&gt;Generate Pdb…&lt;/code&gt;&quot;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/07/generating-pdb-files-with-resharper/GeneratePdbFileMenu.png&quot;&gt;&lt;img src=&quot;images/GeneratePdbFileMenu.png&quot; alt=&quot;GeneratePdbFileMenu&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In the opened window, select the destination folder for the files.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/07/generating-pdb-files-with-resharper/GeneratedPdbsOption.png&quot;&gt;&lt;img src=&quot;images/GeneratedPdbsOption.png&quot; alt=&quot;GeneratedPdbsOption&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Once you click &quot;&lt;code&gt;Generate&lt;/code&gt;&quot;, &lt;code&gt;Resharper&lt;/code&gt; will process the assembly and generate &lt;code&gt;PDBs&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/07/generating-pdb-files-with-resharper/PdbGenerated.png&quot;&gt;&lt;img src=&quot;images/PdbGenerated.png&quot; alt=&quot;PdbGenerated&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Once the files are generated we have to tell &lt;code&gt;Visual Studio&lt;/code&gt; to use them.
In order to do that, run the app and stop the execution with some breakpoint, then go to &lt;code&gt;Debug-&amp;gt;Windows-&amp;gt; Modules&lt;/code&gt;, locate &lt;code&gt;EntityFramework.dll&lt;/code&gt;, click it with &lt;code&gt;RMB&lt;/code&gt;, select &lt;code&gt;Load Symbols&lt;/code&gt; and choose file(s) generated by &lt;code&gt;Resharper&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/07/generating-pdb-files-with-resharper/LoadSymbols.png&quot;&gt;&lt;img src=&quot;images/LoadSymbols.png&quot; alt=&quot;LoadSymbols&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;At this point we have &lt;code&gt;PDB&lt;/code&gt; files ready but we are not able to set any breakpoint as we don&apos;t have source code of &lt;code&gt;EntityFramework&lt;/code&gt;.
Fortunately &lt;code&gt;Resharper&lt;/code&gt; once again saves the day as it is able to navigate to decompiled sources.
Just make sure that your settings (&lt;code&gt;Resharper-&amp;gt;Options-&amp;gt;External Sources&lt;/code&gt;) are the same as in the picture below&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/07/generating-pdb-files-with-resharper/decompile.png&quot;&gt;&lt;img src=&quot;images/decompile.png&quot; alt=&quot;decompile&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;and you can navigate to external libraries&apos; source code just like they were in your project.
The very last step is to disable &lt;code&gt;Enable Just My Code&lt;/code&gt; option in &lt;code&gt;Tools-&amp;gt;Options-&amp;gt;Debugging-&amp;gt;General&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/07/generating-pdb-files-with-resharper/JustMyCode.png&quot;&gt;&lt;img src=&quot;images/JustMyCode.png&quot; alt=&quot;JustMyCode&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;and from now on you can debug the external library&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/07/generating-pdb-files-with-resharper/DbContextDebugging.png&quot;&gt;&lt;img src=&quot;images/DbContextDebugging.png&quot; alt=&quot;DbContextDebugging&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Debugging cake scripts</title><link>https://tpodolak.com/blog/debugging-cake-scripts/</link><guid isPermaLink="true">https://tpodolak.com/blog/debugging-cake-scripts/</guid><pubDate>Sun, 10 Jul 2016 09:03:08 GMT</pubDate><content:encoded>&lt;p&gt;We&apos;ve been using &lt;a href=&quot;http://cakebuild.net/&quot;&gt;Cake&lt;/a&gt; in our project for quite some time and it has been working great.
However for time to time lack of debugging support was really annoying for me.
Fortunately it seems that these times are gone now.
During &lt;a href=&quot;https://vimeo.com/171704581&quot;&gt;NDC Oslo 2016&lt;/a&gt; &lt;a href=&quot;https://github.com/gep13&quot;&gt;Gary Ewan Park&lt;/a&gt; showed that it is possible to attach debugger to the build process.
Here are the steps to achieve that.&lt;/p&gt;
&lt;p&gt;Let&apos;s assume that we have following simple cake script.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var target = Argument(&quot;target&quot;, &quot;Default&quot;);
Task(&quot;Default&quot;)
    .Does(() =&amp;gt;
{
    MSBuild(Directory(&quot;../&quot;) + File(&quot;DebuggingCakeScript.sln&quot;));
});

RunTarget(target);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In order to make the debugging possible it is necessary to add &lt;code&gt;#break&lt;/code&gt; preprocessor directive to the task we want the debugger to stop.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var target = Argument(&quot;target&quot;, &quot;Default&quot;);
Task(&quot;Default&quot;)
    .Does(() =&amp;gt;
{
    #break
    MSBuild(Directory(&quot;../&quot;) + File(&quot;DebuggingCakeScript.sln&quot;));
});

RunTarget(target);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This operation doesn&apos;t affect the default build process, so if you run in console&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;.\build.ps1 -target Default

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;the build will run as usual. In order to be able to attach the debugger we have to call &lt;code&gt;Cake&lt;/code&gt; with &lt;code&gt;--debug&lt;/code&gt; flag. You can&apos;t do it directly via &lt;code&gt;\build.ps1&lt;/code&gt;
script so assuming that you didn&apos;t change directory structure created by bootstrapper, go to &lt;code&gt;Tools\Cake&lt;/code&gt; folder and run from &lt;code&gt;PowerShell&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;.\Cake.exe ..\..\build.cake -target=Default --debug

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;where &lt;code&gt;..\..\build.cake&lt;/code&gt; is path to your cake script and &lt;code&gt;Default&lt;/code&gt; is task you want to start.
Once you run the command, cake will wait for attaching the debugger&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/07/debugging-cake-scripts/WaitingForDebugger.png&quot;&gt;&lt;img src=&quot;images/WaitingForDebugger.png&quot; alt=&quot;WaitingForDebugger&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Now launch &lt;code&gt;Visual Studio&lt;/code&gt;, go to &lt;code&gt;Debug-&amp;gt; Attach to Process…&lt;/code&gt;, find process id listed in console&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/07/debugging-cake-scripts/Attach.png&quot;&gt;&lt;img src=&quot;images/Attach.png&quot; alt=&quot;Attach&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;and click &lt;code&gt;Attach&lt;/code&gt;. After couple of seconds &lt;code&gt;Visual Studio&lt;/code&gt; will load your cake script and you will be able to debug it like normal application.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/07/debugging-cake-scripts/attached.png&quot;&gt;&lt;img src=&quot;images/attached.png&quot; alt=&quot;attached&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>NLog - tracking flow of requests using MappedDiagnosticsLogicalContext</title><link>https://tpodolak.com/blog/nlog-tracking-flow-of-requests-using-mappeddiagnosticslogicalcontext/</link><guid isPermaLink="true">https://tpodolak.com/blog/nlog-tracking-flow-of-requests-using-mappeddiagnosticslogicalcontext/</guid><pubDate>Tue, 05 Jul 2016 20:38:53 GMT</pubDate><content:encoded>&lt;h3&gt;1. Problem&lt;/h3&gt;
&lt;p&gt;Everyone who has ever had to analyze logs from production environment knows, that quite often it is not an easy task.
Usually application flow is deduced by log entries matched by thread id, which is problematic when you deal with multithreading scenarios.
Say for example we have following piece of code&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class HomeController : Controller
{
    private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
    
    public async Task&amp;lt;ActionResult&amp;gt; Index()
    {
        await PreprocessRequest(nameof(Index));
        return View();
    }
    
    private static async Task PreprocessRequest(string actionName)
    {
        Logger.Info($&quot;Log from {actionName} action, from thread={Thread.CurrentThread.ManagedThreadId}&quot;);
        
        await Task.Run(() =&amp;gt; Logger.Info($&quot;Log from {actionName}, from thread {Thread.CurrentThread.ManagedThreadId} assigned by scheduler&quot;))
                  .ConfigureAwait(continueOnCapturedContext: false);
        Logger.Info($&quot;Log from {actionName} action, from async continuation, from thread {Thread.CurrentThread.ManagedThreadId}&quot;);
               
        var thread =
            new Thread(() =&amp;gt; Logger.Info($&quot;Log from {actionName} action, from explicitly created thread {Thread.CurrentThread.ManagedThreadId}&quot;));
        thread.Start();
        thread.Join();
    }
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Default log file usually looks like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;TimeStamp=2016-07-03 11:56:02.2327 ThreadId=5 Level=INFO Message=About to start GET / request
TimeStamp=2016-07-03 11:56:02.3797 ThreadId=5 Level=INFO Message=Log from Index action, from thread=5
TimeStamp=2016-07-03 11:56:02.3797 ThreadId=6 Level=INFO Message=Log from Index, from thread 6 assigned by scheduler
TimeStamp=2016-07-03 11:56:02.3797 ThreadId=6 Level=INFO Message=Log from Index action, from async continuation, from thread 6
TimeStamp=2016-07-03 11:56:02.3917 ThreadId=14 Level=INFO Message=Log from Index action, from explicitly created thread 14
TimeStamp=2016-07-03 11:56:04.8250 ThreadId=8 Level=INFO Message=Request completed with status code: 200 

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Having multiple simultaneous &lt;code&gt;Index&lt;/code&gt; requests, makes it almost impossible to figure out which log entry is part of which call. Fortunately with &lt;code&gt;NLog&lt;/code&gt; it is possible to solve this problem without too much of a hassle.&lt;/p&gt;
&lt;h3&gt;2. Proposed solution&lt;/h3&gt;
&lt;p&gt;The whole idea is to leverage &lt;code&gt;MappedDiagnosticsLogicalContext&lt;/code&gt; &quot;storage&quot; to keep some unique identifier of request for entire call. Note, that this identifier will be accessible also from other threads created from within given call. In order to set unique request id (also known as correlation id) I will use custom &lt;code&gt;HttpModule&lt;/code&gt;. The very first implementation looks like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class LoggingHttpModule : IHttpModule
{
    private const string CorrelationIdKey = &quot;correlationid&quot;;

    private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

    public void Init(HttpApplication context)
    {
        context.BeginRequest += HandleBeginRequest;
        context.EndRequest += HandleEndRequest;
    }

    public void Dispose()
    {
    }

    private void HandleBeginRequest(object sender, EventArgs e)
    {
        var value = Guid.NewGuid().ToString();
        var httpApplication = (HttpApplication) sender;
        var httpContext = httpApplication.Context;
        MappedDiagnosticsLogicalContext.Set(CorrelationIdKey, value);
        Logger.Info($&quot;About to start {httpContext.Request.HttpMethod} {httpContext.Request.RawUrl} request&quot;);
    }

    private void HandleEndRequest(object sender, EventArgs e)
    {
        var httpApplication = (HttpApplication) sender;
        var httpContext = httpApplication.Context;
        Logger.Info($&quot;Request completed with status code: {httpContext.Response.StatusCode} &quot;);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Once the &lt;code&gt;HttpModule&lt;/code&gt; is ready it is necessary to register it in &lt;code&gt;web.config&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;!--rest of the code omitted --&amp;gt;
&amp;lt;system.webServer&amp;gt;
  &amp;lt;modules&amp;gt;
  &amp;lt;!--rest of the code omitted --&amp;gt;
    &amp;lt;add name=&quot;LoggingHttpModule&quot; type=&quot;AspNetMvcLoggingWithCorrelationId.HttpModules.LoggingHttpModule&quot;/&amp;gt;
  &amp;lt;/modules&amp;gt;
&amp;lt;/system.webServer&amp;gt;
&amp;lt;!--rest of the code omitted --&amp;gt;
&amp;lt;system.web&amp;gt;
&amp;lt;!--rest of the code omitted --&amp;gt;
  &amp;lt;httpModules&amp;gt;
  &amp;lt;!--rest of the code omitted --&amp;gt;
    &amp;lt;add name=&quot;ApplicationInsightsWebTracking&quot; type=&quot;Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule,Microsoft.AI.Web&quot;/&amp;gt;
  &amp;lt;/httpModules&amp;gt;
&amp;lt;/system.web&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From now on, every request goes through &lt;code&gt;LogginHttpModule&lt;/code&gt; and proper &lt;code&gt;correlationId&lt;/code&gt; is set in &lt;code&gt;MappedDiagnosticsLogicalContext&lt;/code&gt;. As we want to have &lt;code&gt;correlationId&lt;/code&gt; included in log files it is necessary to modify &lt;code&gt;Nlog.config&lt;/code&gt;. In my case it looks like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&amp;gt;
&amp;lt;nlog xmlns=&quot;http://www.nlog-project.org/schemas/NLog.xsd&quot;
      xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
      xsi:schemaLocation=&quot;http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd&quot;
      autoReload=&quot;true&quot;
      throwExceptions=&quot;false&quot;
      internalLogLevel=&quot;Off&quot; internalLogFile=&quot;c:\temp\nlog-internal.log&quot; &amp;gt;

  &amp;lt;variable name=&quot;myvar&quot; value=&quot;myvalue&quot;/&amp;gt;
  &amp;lt;targets&amp;gt;
    &amp;lt;target xsi:type=&quot;File&quot; name=&quot;f&quot; fileName=&quot;${basedir}/logs/${shortdate}.log&quot;
            layout=&quot;TimeStamp=${longdate} CorrelationId=${mdlc:item=correlationid} Level=${uppercase:${level}} Message=${message}&quot; /&amp;gt;
  &amp;lt;/targets&amp;gt;

  &amp;lt;rules&amp;gt;
    &amp;lt;logger name=&quot;*&quot; minlevel=&quot;Debug&quot; writeTo=&quot;f&quot; /&amp;gt;
  &amp;lt;/rules&amp;gt;
&amp;lt;/nlog&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that we can access our &lt;code&gt;correlationId&lt;/code&gt; variable via &lt;code&gt;${mdlc:item=correlationid}&lt;/code&gt; Log file after the changes looks like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;TimeStamp=2016-07-03 12:41:35.7292 CorrelationId=b322d1fa-47b2-4582-b7a9-c9463b7c0a47 Level=INFO Message=About to start GET / request
TimeStamp=2016-07-03 12:41:35.8752 CorrelationId=b322d1fa-47b2-4582-b7a9-c9463b7c0a47 Level=INFO Message=Log from Index action, from thread=6
TimeStamp=2016-07-03 12:41:35.8752 CorrelationId=b322d1fa-47b2-4582-b7a9-c9463b7c0a47 Level=INFO Message=Log from Index, from thread 7 assigned by scheduler
TimeStamp=2016-07-03 12:41:35.8752 CorrelationId=b322d1fa-47b2-4582-b7a9-c9463b7c0a47 Level=INFO Message=Log from Index action, from async continuation, from thread 7
TimeStamp=2016-07-03 12:41:35.8752 CorrelationId=b322d1fa-47b2-4582-b7a9-c9463b7c0a47 Level=INFO Message=Log from Index action, from explicitly created thread 9
TimeStamp=2016-07-03 12:41:38.4454 CorrelationId= Level=INFO Message=Request completed with status code: 200

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is almost perfect, however for some reasons &lt;code&gt;correlationId&lt;/code&gt; is lost in &lt;code&gt;EndRequest&lt;/code&gt; event handler. I am not sure if this is bug in &lt;code&gt;NLog&lt;/code&gt; (I&apos;ve posted question in &lt;code&gt;Nlog&apos;s&lt;/code&gt; github) or it is by design, however there is easy workaround for that. We can store our &lt;code&gt;correlationId&lt;/code&gt; in &lt;code&gt;HttpContext.Items&lt;/code&gt; collection and reassign it to &lt;code&gt;MappedDiagnosticsLogicalContext&lt;/code&gt; in &lt;code&gt;EndRequest&lt;/code&gt; event handler.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;private void HandleBeginRequest(object sender, EventArgs e)
{
    var value = Guid.NewGuid().ToString();
    var httpApplication = (HttpApplication) sender;
    var httpContext = httpApplication.Context;
    MappedDiagnosticsLogicalContext.Set(CorrelationIdKey, value);

    httpContext.Items[CorrelationIdKey] = value;
    Logger.Info($&quot;About to start {httpContext.Request.HttpMethod} {httpContext.Request.RawUrl} request&quot;);
}

private void HandleEndRequest(object sender, EventArgs e)
{
    var httpApplication = (HttpApplication) sender;
    var httpContext = httpApplication.Context;

    var correlationId = httpContext.Items[CorrelationIdKey].ToString();
    MappedDiagnosticsLogicalContext.Set(CorrelationIdKey, correlationId);

    Logger.Info($&quot;Request completed with status code: {httpContext.Response.StatusCode} &quot;);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After these changes our log file finally looks &lt;code&gt;OK&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;TimeStamp=2016-07-03 12:41:35.7292 CorrelationId=b322d1fa-47b2-4582-b7a9-c9463b7c0a47 Level=INFO Message=About to start GET / request
TimeStamp=2016-07-03 12:41:35.8752 CorrelationId=b322d1fa-47b2-4582-b7a9-c9463b7c0a47 Level=INFO Message=Log from Index action, from thread=6
TimeStamp=2016-07-03 12:41:35.8752 CorrelationId=b322d1fa-47b2-4582-b7a9-c9463b7c0a47 Level=INFO Message=Log from Index, from thread 7 assigned by scheduler
TimeStamp=2016-07-03 12:41:35.8752 CorrelationId=b322d1fa-47b2-4582-b7a9-c9463b7c0a47 Level=INFO Message=Log from Index action, from async continuation, from thread 7
TimeStamp=2016-07-03 12:41:35.8752 CorrelationId=b322d1fa-47b2-4582-b7a9-c9463b7c0a47 Level=INFO Message=Log from Index action, from explicitly created thread 9
TimeStamp=2016-07-03 12:41:38.4454 CorrelationId=b322d1fa-47b2-4582-b7a9-c9463b7c0a47 Level=INFO Message=Request completed with status code: 200 

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/AspNetMvcLoggingWithCorrelationId&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Console2 - multiple tabs on startup</title><link>https://tpodolak.com/blog/console2-multiple-tabs-startup/</link><guid isPermaLink="true">https://tpodolak.com/blog/console2-multiple-tabs-startup/</guid><pubDate>Sun, 24 Apr 2016 12:26:04 GMT</pubDate><content:encoded>&lt;p&gt;I&apos;ve been using &lt;code&gt;Console2&lt;/code&gt; for quite some time and as for now it is my favorite command line terminal.
The one thing I like the most is availability to use multiple tabs you can easily switch between.
By default &lt;code&gt;Console2&lt;/code&gt; starts with only one tab opened, which was a bit of a pain for me.
Mainly because I work a lot with Git and I also like to have a Visual Studio command prompt opened.
So basically every time I launched command line I had to open one or two additional tabs.
Fortunately it is quite easy to launch multiple tabs on startup.
All you have to do is to create a shortcut to the &lt;code&gt;Console2&lt;/code&gt; with proper flags. Say for example I have following tabs defined&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/04/console2-multiple-tabs-startup/Settings.png&quot;&gt;&lt;img src=&quot;images/Settings.png&quot; alt=&quot;Settings&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;I can start &lt;code&gt;Console2&lt;/code&gt; with all these tabs opened on startup using following command.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;PATH_TO_CONSOLE\Console.exe -t Git -t Cmd -t Powershell

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Of course it is easier to define a shortcut to &lt;code&gt;Console2&lt;/code&gt; rather than remembering command above. My configuration looks like that&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/04/console2-multiple-tabs-startup/Properties.png&quot;&gt;&lt;img src=&quot;images/Properties.png&quot; alt=&quot;Properties&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Mocking downstream services with Mountebank</title><link>https://tpodolak.com/blog/mocking-downstream-services-mountebank/</link><guid isPermaLink="true">https://tpodolak.com/blog/mocking-downstream-services-mountebank/</guid><pubDate>Thu, 25 Feb 2016 20:44:35 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;I&apos;m a part of a team which creates large enterprise platform for the banking sector.
Due to the fact that we operate in the financial area, our application consumes a high amount of downstream services.
One of the major problems we are facing at the moment is the inaccessibility of those services on &lt;code&gt;DEV&lt;/code&gt; and &lt;code&gt;UAT&lt;/code&gt; environments.
It often happens that one of those services is down for quite some time, so our development speed is impaired.
The bigger problem, however, is the fact that our end-to-end tests are red.
Having a red test on &lt;code&gt;TeamCity&lt;/code&gt; for a long time is a really annoying thing because basically at this point, we just automatically assume that all of the failures are caused by issues with downstream systems.
Fortunately, we finally decided to get rid of this problem and this is the solution we came up with.&lt;/p&gt;
&lt;h3&gt;2. Background&lt;/h3&gt;
&lt;p&gt;Before I go to the implementation details, take a look at a sample implementation of situation I described at the very beginning.
Let&apos;s assume that we have &lt;code&gt;WCF&lt;/code&gt; service which contains business logic of our application and it is consumed by the &lt;code&gt;UI&lt;/code&gt; side&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class BookingFacade :  IBookingFacade
{
    public Response&amp;lt;Price&amp;gt; Price(Models.GetPriceRequest request)
    {
        // in real life scenario Pricer should be injected
        var pricerService = new Pricer();
        var response = new Response&amp;lt;Price&amp;gt;();
        try
        {
            var tradingDates = pricerService.GetTradingDates();
            var price = pricerService.GetPrice(new GetPriceRequest
            {
                IsAdvised = request.IsAdvised
            });

            // rest of the code omitted for brevity
            response.Result = new Price
            {
                TradingDates = new TradingDates
                {
                    MaturityDate = tradingDates.MaturityDate,
                    SettlementDate = tradingDates.SettlementDate
                }
            };
            // rest of the code omitted for brevity
        }
        catch (Exception ex)
        {
            // rest of the code omitted for brevity
        }
        return response;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;BookingFacade&lt;/code&gt; uses &lt;code&gt;Pricer&lt;/code&gt; service which basically is just a wrapper for external/downstream service we have to use in order to retrieve some data (and we do not have an ownership of that service).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Pricer : IPricer
{
    public TradingDates GetTradingDates()
    {
        using (var webClient = new WebClient())
        {
            var result = webClient.DownloadString(ConfigurationManager.AppSettings[&quot;MockingDownstreamServices.Externals.Pricer.GetTradingDates&quot;]);
            return JsonConvert.DeserializeObject&amp;lt;TradingDates&amp;gt;(result);
        }

    }

    public Price GetPrice(GetPriceRequest request)
    {
        using (var webClient = new WebClient())
        {
            var result = webClient.UploadString(ConfigurationManager.AppSettings[&quot;MockingDownstreamServices.Externals.Pricer.GetPrice&quot;], JsonConvert.SerializeObject(request));
            return JsonConvert.DeserializeObject&amp;lt;Price&amp;gt;(result);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Very simple end-to-end test for &lt;code&gt;BookingFacade&lt;/code&gt; can look like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[TestFixture]
public class BookingFacadeTests
{
    [Test]
    public void CanSuccessfullyPriceTest()
    {
        var response = this.Price(new GetPriceRequest());
        Assert.IsNotNull(response);
        Assert.IsNotNull(response.Result);
        Assert.IsFalse(string.IsNullOrWhiteSpace(response.Result.Id));
        CollectionAssert.IsEmpty(response.Messages.Where(val =&amp;gt; val.StatusCode == StatusCodes.Error));
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As I mentioned before, everything is fine as long as all of the downstream systems are working.
The moment one of them is down, our tests start failing.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2016/02/mocking-downstream-services-with-mountebank-part-one/FailingTests.png&quot;&gt;&lt;img src=&quot;images/FailingTests.png&quot; alt=&quot;FailingTests&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;3. Implementation&lt;/h3&gt;
&lt;p&gt;General idea to fix this problem is to use fake downstream systems during end-to-end testing.
In order to do that we use combination of custom compilation profile, &lt;code&gt;app.config&lt;/code&gt; transformations and &lt;a href=&quot;http://www.mbtest.org/&quot;&gt;mountebank&lt;/a&gt; test doubles.&lt;/p&gt;
&lt;h4&gt;3.1 Setting up transformations&lt;/h4&gt;
&lt;p&gt;First of all we will create a custom compilation profile called &lt;code&gt;test.integration&lt;/code&gt; which will be used for running tests with mocked downstream systems (we want to preserve the normal use of downstreams for &lt;code&gt;Debug&lt;/code&gt; and &lt;code&gt;Release&lt;/code&gt; mode).
In order to do that, go to &lt;code&gt;ConfigurationManager&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2016/02/mocking-downstream-services-with-mountebank-part-one/ConfigurationManager.png&quot;&gt;&lt;img src=&quot;images/ConfigurationManager.png&quot; alt=&quot;ConfigurationManager&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;and follow the steps presented in the pictures below&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2016/02/mocking-downstream-services-with-mountebank-part-one/ConfigurationManager2.png&quot;&gt;&lt;img src=&quot;images/ConfigurationManager2.png&quot; alt=&quot;ConfigurationManager2&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2016/02/mocking-downstream-services-with-mountebank-part-one/ConfigurationManager3.png&quot;&gt;&lt;img src=&quot;images/ConfigurationManager3.png&quot; alt=&quot;ConfigurationManager3&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Now it is time to prepare our &lt;code&gt;app.config&lt;/code&gt; for transformations. We can do it manually but for sake of simplicity I will use &lt;code&gt;SlowCheetah&lt;/code&gt; extension.
Go to &lt;code&gt;Tools-&amp;gt;Extensions and Updates&lt;/code&gt; and install &lt;a href=&quot;https://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5&quot;&gt;SlowCheetah - XML Transforms&lt;/a&gt;.
Once extension is installed you will see a &lt;code&gt;Add Transform&lt;/code&gt; item in a config files&apos; context menu.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2016/02/mocking-downstream-services-with-mountebank-part-one/AddTransform.png&quot;&gt;&lt;img src=&quot;images/AddTransform.png&quot; alt=&quot;AddTransform&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Clicking &lt;code&gt;Add Transform&lt;/code&gt; will create three files: &lt;code&gt;App.Debug.config&lt;/code&gt;, &lt;code&gt;App.Release.config&lt;/code&gt; and &lt;code&gt;App.Test.Integration.config&lt;/code&gt;.
What is more, some additional changes will be added to your &lt;code&gt;csproj&lt;/code&gt; file, which will be responsible for applying transformations during a build process.
These three additional files hold information about config transformations. The default &lt;code&gt;App.config&lt;/code&gt; file looks like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&amp;gt;
&amp;lt;configuration&amp;gt;
  &amp;lt;appSettings file=&quot;&quot;&amp;gt;
    &amp;lt;add key=&quot;commonKey&quot; value=&quot;commonValue&quot;/&amp;gt;
  &amp;lt;/appSettings&amp;gt;
&amp;lt;/configuration&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Nothing special in here but note the empty &lt;code&gt;file&lt;/code&gt; attribute in &lt;code&gt;appSettings&lt;/code&gt; node.
The value of this attribute will be replaced with proper filename during transformation process.
In order to do that let&apos;s implement tramsforms for every of three config files we use&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&amp;gt;
&amp;lt;!-- For more information on using transformations 
     see the web.config examples at http://go.microsoft.com/fwlink/?LinkId=214134. --&amp;gt;
&amp;lt;configuration xmlns:xdt=&quot;http://schemas.microsoft.com/XML-Document-Transform&quot;&amp;gt;
  &amp;lt;appSettings file=&quot;app.settings.debug&quot; xdt:Transform=&quot;SetAttributes&quot;&amp;gt;
  &amp;lt;/appSettings&amp;gt;
&amp;lt;/configuration&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&amp;gt;
&amp;lt;!-- For more information on using transformations 
     see the web.config examples at http://go.microsoft.com/fwlink/?LinkId=214134. --&amp;gt;
&amp;lt;configuration xmlns:xdt=&quot;http://schemas.microsoft.com/XML-Document-Transform&quot;&amp;gt;
  &amp;lt;appSettings file=&quot;app.settings.release&quot; xdt:Transform=&quot;SetAttributes&quot;&amp;gt;
  &amp;lt;/appSettings&amp;gt;
&amp;lt;/configuration&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;``&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&amp;gt;
&amp;lt;!-- For more information on using transformations 
     see the web.config examples at http://go.microsoft.com/fwlink/?LinkId=214134. --&amp;gt;
&amp;lt;configuration xmlns:xdt=&quot;http://schemas.microsoft.com/XML-Document-Transform&quot;&amp;gt;
  &amp;lt;appSettings file=&quot;app.settings.tests.integration&quot; xdt:Transform=&quot;SetAttributes&quot;&amp;gt;
  &amp;lt;/appSettings&amp;gt;
&amp;lt;/configuration&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see I apply &lt;code&gt;SetAttributes&lt;/code&gt; transform for &lt;code&gt;appSettings&lt;/code&gt; node, which means that the transformation will replace &lt;code&gt;appSettings&lt;/code&gt; node attributes from &lt;code&gt;app.config&lt;/code&gt; file with &lt;code&gt;appSettings&lt;/code&gt; node attributes from transform file.
You can preview results of transformation by clicking &lt;code&gt;Preview Transform&lt;/code&gt; context menu option available for every of our transform files&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2016/02/mocking-downstream-services-with-mountebank-part-one/Preview.png&quot;&gt;&lt;img src=&quot;images/Preview.png&quot; alt=&quot;Preview&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;As you&apos;ve probably already figured it out &lt;code&gt;app.settings.debug&lt;/code&gt; and &lt;code&gt;app.settings.release&lt;/code&gt; fileses contain real downstream endpoints and &lt;code&gt;app.settings.tests.integration&lt;/code&gt; contains addresses of fake endpoints. Of course you have to create those files and copy them to output directory during the build (for instance by using &lt;code&gt;Copy to Output directory&lt;/code&gt; option).&lt;/p&gt;
&lt;h4&gt;3.2. Creating fake downstreams with mountebank&lt;/h4&gt;
&lt;p&gt;Setting up fake downstream systems completely from scratch would be a very painful and time consuming process.
Fortunately there are tools which can make this task easier. The tool I use is called &lt;a href=&quot;http://www.mbtest.org/&quot;&gt;mountebank&lt;/a&gt; - you can easily install it via &lt;code&gt;npm&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install -g mountebank

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Having &lt;code&gt;mountebank&lt;/code&gt; on board it is time to configure it, so that it acts as fake &lt;code&gt;Pricer&lt;/code&gt; service. It can be done in couple of ways but I will go with file based configuration.
You can run the tool using following command&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;mb --configfile impostors.ejs --allowInjection

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2016/02/mocking-downstream-services-with-mountebank/ImpostorsListening.png&quot;&gt;&lt;img src=&quot;images/ImpostorsListening.png&quot; alt=&quot;ImpostorsListening&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Where &lt;code&gt;impostors.ejs&lt;/code&gt; is a configuration file with following structure&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;imposters&quot;: [
    &amp;lt;% include pricer.json %&amp;gt;
  ]
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;&amp;lt;% include pricer.json %&amp;gt;&lt;/code&gt; is &lt;a href=&quot;http://www.embeddedjs.com/&quot;&gt;EJS&lt;/a&gt; syntax which (in this case) allows you to split configuration into multiple files.
As you&apos;ve probably already figured it out, &lt;code&gt;Pricer.json&lt;/code&gt; contains the actual mock configuration for &lt;code&gt;Pricer&lt;/code&gt; service.
The initial mock object consists of couple of properties which setup the name, port and protocol for given mock.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;port&quot;: 4545,
  &quot;protocol&quot;: &quot;http&quot;,
  &quot;name&quot;: &quot;pricer stub&quot;,
  &quot;stubs&quot;: []
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that we do not specify the address of mock but just a port. &lt;code&gt;Mountebank&lt;/code&gt; by default runs on &lt;code&gt;http://localhost:2525&lt;/code&gt; and mocks listen on &lt;code&gt;http://localhost:{port}&lt;/code&gt;.
The actual magic happens in &lt;code&gt;stubs&lt;/code&gt; property. Here is an example of stub/mock for &lt;code&gt;GetTradingDates&lt;/code&gt; method.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
    &quot;responses&quot;: [
      {
        &quot;is&quot;: {
          &quot;body&quot;: {
            &quot;MaturityDate&quot;: &quot;2016-02-17&quot;,
            &quot;SettlementDate&quot;: &quot;2012-02-23&quot;
          }
        }
      }
    ],
    &quot;predicates&quot;: [
      {
        &quot;equals&quot;: {
          &quot;path&quot;: &quot;/GetTradingDates&quot;,
          &quot;method&quot;: &quot;GET&quot;
        },
      }
    ]
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see stub object consists of two properties&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;responses&lt;/li&gt;
&lt;li&gt;predicates&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;responses&lt;/code&gt;&lt;/strong&gt; property is an array of objects &lt;code&gt;mountebank&lt;/code&gt; will be using to create a response.
If you insert multiple items into array, they will be utilized using round robin algorithm.
Note that you don&apos;t have to create a full response (with all the headers etc.) just use &quot;is&quot; property which will fill the default values for you.
More about that topic can be found &lt;a href=&quot;http://www.mbtest.org/docs/api/stubs&quot;&gt;here&lt;/a&gt; but in most of the cases setting value for &quot;body&quot; property will be enough for you.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;code&gt;predicates&lt;/code&gt;&lt;/strong&gt; property is an array of predicates which will be used during matching process.
Predicate object can be quite complex, it supports lots of different matching techniques.
In this case, for simple &lt;code&gt;GET&lt;/code&gt; method I just use &lt;code&gt;equals&lt;/code&gt; operator to match &lt;code&gt;HTTP&lt;/code&gt; verb and &lt;code&gt;HTTP&lt;/code&gt; method.
The same technique can be used for stubbing &lt;code&gt;POST&lt;/code&gt; methods. However, in this case, you can also perform matching against the body of the request.
The one thing you have to remember is that &lt;code&gt;body&lt;/code&gt; property is not an object but string. So in my case, if I want to make a stub for &lt;code&gt;GetPrice&lt;/code&gt; which takes as params following request object&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class GetPriceRequest
{
    public bool IsAdvised { get; set; }
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I can write for instance this stub&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
    &quot;responses&quot;: [
      {
        &quot;is&quot;: {
          &quot;body&quot;: {
            &quot;Id&quot;: &quot;1&quot;,
            &quot;Strike&quot;: &quot;1&quot;
          }
        }
      }
    ],
    &quot;predicates&quot;: [
      {
        &quot;equals&quot;: {
          &quot;path&quot;: &quot;/GetPrice&quot;,
          &quot;method&quot;: &quot;POST&quot;,
          &quot;body&quot;: &quot;{\&quot;IsAdvised\&quot;:false}&quot;
        }
      }
    ]
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Of course for more complex request it is pointless to write every possible combination of params. Fortunately you can create fallback/default stub which will match everything&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
    &quot;responses&quot;: [
      {
        &quot;is&quot;: {
          &quot;body&quot;: {
            &quot;Id&quot;: &quot;default&quot;,
            &quot;Strike&quot;: &quot;1&quot;
          }
        }
      }
    ],
    &quot;predicates&quot;: [
      {
        &quot;equals&quot;: {
          &quot;path&quot;: &quot;/GetPrice&quot;,
          &quot;method&quot;: &quot;POST&quot;
        }
      }
    ]
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you put this at the very end of stubs array it will not interfere with other stubs. This is of course just a tip of the iceberg when it comes to predicate matching. Explanation of all possible matching options can be found &lt;a href=&quot;http://www.mbtest.org/docs/api/predicates&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;4. Results&lt;/h3&gt;
&lt;p&gt;From now on running tests against &lt;code&gt;test.integration&lt;/code&gt; compilation profile and having &lt;code&gt;mountebank&lt;/code&gt; working in the background, our tests will be green.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;//tpodolak.com/blog/wp-content/uploads/2016/02/mocking-downstream-services-with-mountebank/SuccessfulTests.png&quot;&gt;&lt;img src=&quot;images/SuccessfulTests.png&quot; alt=&quot;SuccessfulTests&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/MockingDownstreamServicesWithMountebank&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Using async/await with IAsyncResult pattern</title><link>https://tpodolak.com/blog/using-asyncawait-iasyncresult-pattern/</link><guid isPermaLink="true">https://tpodolak.com/blog/using-asyncawait-iasyncresult-pattern/</guid><pubDate>Fri, 12 Feb 2016 17:45:14 GMT</pubDate><content:encoded>&lt;p&gt;Even though in my current project we use &lt;code&gt;.NET 4.5&lt;/code&gt; we still have lots of references to internal libraries targeting &lt;code&gt;.NET 4.0&lt;/code&gt;.
Usually it is not a problem, however some of these libraries follow &lt;a href=&quot;https://msdn.microsoft.com/pl-pl/library/jj152938(v=vs.110).aspx&quot;&gt;Asynchronous Programming Model&lt;/a&gt; pattern.
This approach makes the code quite ugly because we end up with lots of nested callbacks.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// rest of the code omitted for brevity
private static void GetHostEntryIAsyncResultPattern()
{
    DnsService dnsService = new DnsService();
    dnsService.BeginGetHostEntry(GoogleHost, googleAsyncResult =&amp;gt;
    {
        var googleHostResult = dnsService.EndGetHostEntry(googleAsyncResult);
        Console.WriteLine($&quot;Result from IAsyncResultPattern: {GoogleHost} - {FormatHostEntry(googleHostResult)}&quot;);
        dnsService.BeginGetHostEntry(YahooHost, yahooAsyncResult =&amp;gt;
        {
            var yahooHostResult = dnsService.EndGetHostEntry(yahooAsyncResult);
            Console.WriteLine($&quot;Result from IAsyncResultPattern: {YahooHost} - {FormatHostEntry(yahooHostResult)}&quot;);
        }, null);
    }, null);
}
// rest of the code omitted for brevity
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Fortunately thanks to &lt;code&gt;Task.Factory.FromAsync&lt;/code&gt; method it is possible to quite easily make &lt;code&gt;Begin&lt;/code&gt;/&lt;code&gt;End&lt;/code&gt; methods work with &lt;code&gt;async&lt;/code&gt;/&lt;code&gt;await&lt;/code&gt; pattern.
All you have to do is to pass &lt;code&gt;Begin&lt;/code&gt;/&lt;code&gt;End&lt;/code&gt; methods as an arguments to &lt;a href=&quot;https://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.fromasync(v=vs.110).aspx&quot;&gt;Task.Factory.FromAsync&lt;/a&gt; and you are good to go.
The original code after refactoring looks like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// rest of the code omitted for brevity
var dnsService = new DnsService();
var googleHostResult = await Task.Factory.FromAsync((callback, stateObject) =&amp;gt; dnsService.BeginGetHostEntry(GoogleHost, callback, stateObject), dnsService.EndGetHostEntry, null);
Console.WriteLine($&quot;Result from async/await: {GoogleHost} - {FormatHostEntry(googleHostResult)}&quot;);

var yahooHostResult = await Task.Factory.FromAsync((callback, stateObject) =&amp;gt; dnsService.BeginGetHostEntry(YahooHost, callback, stateObject), dnsService.EndGetHostEntry, null);
Console.WriteLine($&quot;Result from async/await: {YahooHost} - {FormatHostEntry(yahooHostResult)}&quot;);
// rest of the code omitted for brevity
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I think everyone will agree with me that refactored version is much better than original one.&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/BeginInvokeEndInvokeAsyncAwait&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>EntityFramework - SQLException during database migration</title><link>https://tpodolak.com/blog/entityframework-sqlexception-during-database-migration/</link><guid isPermaLink="true">https://tpodolak.com/blog/entityframework-sqlexception-during-database-migration/</guid><pubDate>Sun, 07 Feb 2016 13:10:54 GMT</pubDate><content:encoded>&lt;p&gt;Recently I&apos;ve been doing some small refactoring of my pet project. Nothing too fancy - just namespace adjustment, variables and class renaming etc.
However it turned out that even these minor changes can in fact be major ones.
All of the sudden most of my integration tests started failing due to &lt;code&gt;SQLException&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/02/entityframework-sqlexception-during-database-migration/Exception.png&quot;&gt;&lt;img src=&quot;images/Exception.png&quot; alt=&quot;Exception&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;I am using &lt;code&gt;Code First&lt;/code&gt; approach so I didn&apos;t take me too much time to realize that for some reasons &lt;code&gt;EntityFramework&lt;/code&gt; wanted to create already existing tables.
I started looking into the way &lt;code&gt;EF&lt;/code&gt; keeps track of the changes in the model and it turned out that it creates special table called &lt;code&gt;__MigratoinHistory&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2016/02/entityframework-sqlexception-during-database-migration/ContextKey.png&quot;&gt;&lt;img src=&quot;images/ContextKey.png&quot; alt=&quot;ContextKey&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;One of the most important columns in there is column called &lt;code&gt;ContextKey&lt;/code&gt;, which identifies the class which describes migration policy.
In my case this class originally looked that way&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;namespace EFAutoupgradeException.Data
{
    public class AutoupgradeExceptionMigrationConfiguration : DbMigrationsConfiguration&amp;lt;AutoupgradeExceptionDbContext&amp;gt;
    {
        public AutoupgradeExceptionMigrationConfiguration()
        {
            this.AutomaticMigrationsEnabled = true;
            this.AutomaticMigrationDataLossAllowed = true;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In that case value of the &lt;code&gt;ContextKey&lt;/code&gt; column matches the full name of the class&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;EFAutoupgradeException.Data.AutoupgradeExceptionMigrationConfiguration

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The class after refactoring was slightly changed and now it looks that way&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;namespace EFAutoupgradeExceptions.Data
{
    public class AutoupgradeExceptionMigrationConfiguration : DbMigrationsConfiguration&amp;lt;AutoupgradeExceptionDbContext&amp;gt;
    {
        public AutoupgradeExceptionMigrationConfiguration()
        {
            this.AutomaticMigrationsEnabled = true;
            this.AutomaticMigrationDataLossAllowed = true;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is easy to overlook the change but now, full name of the class is&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Exceptions as in plural compared to singular previously
EFAutoupgradeExceptions.Data.AutoupgradeExceptionMigrationConfiguration
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;so &lt;code&gt;EF&lt;/code&gt; loses the information about the migration and tries to migrate once again from the scratch.
Fortunately there is an easy fix for that which doesn&apos;t require dropping the database.
All you have to do is to write simple update statement which set the proper &lt;code&gt;ContextKey&lt;/code&gt; value.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;USE EFAutoupgradeException
UPDATE [__MigrationHistory]
SET
[ContextKey] = &apos;EFAutoupgradeExceptions.Data.AutoupgradeExceptionMigrationConfiguration&apos;
WHERE [ContextKey] LIKE &apos;%AutoupgradeExceptionMigrationConfiguration&apos;

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/EntityFrameworkAutoupgradeException&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Abusing collection initializers</title><link>https://tpodolak.com/blog/abusing-collection-initializers/</link><guid isPermaLink="true">https://tpodolak.com/blog/abusing-collection-initializers/</guid><pubDate>Mon, 01 Feb 2016 18:03:10 GMT</pubDate><content:encoded>&lt;p&gt;Most of &lt;code&gt;.NET&lt;/code&gt; developers are familiar with collection initializers syntax. Long story short, this language feature allows you to replace this ugly syntax&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var numbers = new List&amp;lt;int&amp;gt;();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
numbers.Add(4);

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;with much shorter and cleaner one&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var numbers = new List&amp;lt;int&amp;gt; { 1, 2, 3, 4 };
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The more interesting thing is the fact that you can leverage this syntax not only for build-in collections but also for your custom classes.
In order to do that your class must implement &lt;code&gt;IEnumerable&lt;/code&gt; interface and expose public &lt;code&gt;Add&lt;/code&gt; method.
Let&apos;s assume that we have some real case scenario and we have class which looks like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class StatusMessages : IEnumerable&amp;lt;StatusMessage&amp;gt;
{
    private List&amp;lt;StatusMessage&amp;gt; messages = new List&amp;lt;StatusMessage&amp;gt;();

    public IEnumerator&amp;lt;StatusMessage&amp;gt; GetEnumerator()
    {
        return this.messages.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.messages.GetEnumerator();
    }
}

public class StatusMessage
{
    public string Text { get; set; } = string.Empty;
    public string SourceSystem { get; set; } = string.Empty;
    public int StatusCode { get; set; }

    public StatusMessage()
    {
    }

    public StatusMessage(string text)
    {
        this.Text = text;
    }

    public override string ToString()
    {
        return $&quot;Text: {this.Text} StatusCode: {this.StatusCode} SourceSystem: {this.SourceSystem}&quot;;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is a simple wrapper over the List. At this moment we can&apos;t use collection initializer when constructing objects of this classs.
However by adding method &lt;code&gt;Add&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class StatusMessages : IEnumerable&amp;lt;StatusMessage&amp;gt;
{
    // rest of the code omitted for brevity
    public void Add(StatusMessage message)
    {
        this.messages.Add(message);
    }
    // rest of the code omitted for brevity
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;we can create a new instance of that class just like we would do with &lt;code&gt;List&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var messagesAddInitializer = new StatusMessages
            {
                new StatusMessage(&quot;y&quot;),
                new StatusMessage(&quot;x&quot;),
            };

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;What is more, it is possible to have multiple overloads of &lt;code&gt;Add&lt;/code&gt; method in our class, so for instance if we add&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class StatusMessages : IEnumerable&amp;lt;StatusMessage&amp;gt;
{
    // rest of the code omitted for brevity
    public void Add(string text)
    {
         this.Add(new StatusMessage(text));
    }
    // rest of the code omitted for brevity
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;we are able to use this syntax&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var messagesAddStringInitializer = new StatusMessages
            {
                &quot;y&quot;,
                &quot;x&quot;
            };
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In addition it is even possible to use a mix of &lt;code&gt;Add&lt;/code&gt; overloads&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var messagesAddAndTextInitializers = new StatusMessages
            {
                new StatusMessage(&quot;y&quot;),
                &quot;x&quot;
            };

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;Add&lt;/code&gt; method can also have multiple arguments&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class StatusMessages : IEnumerable&amp;lt;StatusMessage&amp;gt;
{
    // rest of the code omitted for brevity
    public void Add(int statusCode, string text)
    {
        this.Add(new StatusMessage(text) { StatusCode = statusCode });
    }
    
    public void Add(int statusCode, string text, string sourceSystem)
    {
        this.Add(new StatusMessage(text) { StatusCode = statusCode,SourceSystem = sourceSystem });
    }
    // rest of the code omitted for brevity
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;in that case we are able to use this syntax&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var messagesMultipleArgumentsInitializers = new StatusMessages
            {
                { 1, &quot;x&quot; },
                {1,&quot;x&quot;,&quot;source&quot; }
            };

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The last thing I would like to point out is that &lt;code&gt;Add&lt;/code&gt; function doesn&apos;t have to be an instance method, we can easily implement it as an extension method and still leverage the collection initializer syntax.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;namespace AbusingCollectionInitializers
{
    public static class StatusMessagesExtensions
    {
        public static void Add(this StatusMessages statusMessages, int statusCode)
        {
            statusMessages.Add(new StatusMessage() { StatusCode = statusCode });
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now with proper namespace import we can write this code&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using AbusingCollectionInitializers;
// rest of the code omitted for brevity
var messagesExtensionInitializers = new StatusMessages { 1,2,3 };

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/AbusingCollectionInitializers&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Easy way to suppress code analysis warnings</title><link>https://tpodolak.com/blog/easy-way-to-suppress-code-analysis-warnings/</link><guid isPermaLink="true">https://tpodolak.com/blog/easy-way-to-suppress-code-analysis-warnings/</guid><pubDate>Mon, 10 Aug 2015 19:12:00 GMT</pubDate><content:encoded>&lt;p&gt;Everyone who has ever been using a code analysis knows that sometimes it is hard to follow the &lt;code&gt;Microsoft&lt;/code&gt; coding guidelines and it is necessary to suppress some warnings.
For me it always was a painful operation because I didn&apos;t know any automated way of doing that.
So basically I had to find the warning in the &lt;code&gt;MSDN&lt;/code&gt;, copy category, code and other necessary stuff and then manually add appropriate attribute in code.
Fortunately a friend of mine yesterday showed me a simple trick to generate this attribute with couple of mouse clicks.
All you have to do is to right-click on warning message and choose &lt;code&gt;Suppress Message&lt;/code&gt; context menu ...&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2015/08/easy-way-to-suppress-code-analysis-warnings/ContextMenu.png&quot;&gt;&lt;img src=&quot;images/ContextMenu.png&quot; alt=&quot;code analysis&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;There are two options in there. The first option - &lt;code&gt;In Source&lt;/code&gt;, will add attribute directly in the code&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2015/08/easy-way-to-suppress-code-analysis-warnings/SuppressInSource.gif&quot;&gt;&lt;img src=&quot;images/SuppressInSource.gif&quot; alt=&quot;code analysis&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;and the second one - &lt;code&gt;In Suppression&lt;/code&gt; File, will create &lt;code&gt;GlobalSuppressoins.cs&lt;/code&gt; file with assembly attribute which suppresses given warning in entire assembly&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2015/08/easy-way-to-suppress-code-analysis-warnings/SuppresionGlobal.gif&quot;&gt;&lt;img src=&quot;images/SuppresionGlobal.gif&quot; alt=&quot;code analysis&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>TPL - exception handling and UnobservedTaskException issue</title><link>https://tpodolak.com/blog/tpl-exception-handling-and-unobservedtaskexception-issue/</link><guid isPermaLink="true">https://tpodolak.com/blog/tpl-exception-handling-and-unobservedtaskexception-issue/</guid><pubDate>Mon, 10 Aug 2015 19:12:00 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;Working with &lt;code&gt;Tasks&lt;/code&gt; is a modern way of writing asynchronous code in an easy and flexible manner.
It is quite straightforward to start using them, so usually developers do not investigate thoroughly the topic.
Unfortunately this often leads to unpleasant surprises - especially when it comes to exception handling.
Having this in mind let&apos;s take a look how to handle exceptions in &lt;code&gt;Task&lt;/code&gt; and what can happen if we do it wrong.&lt;/p&gt;
&lt;h3&gt;2. Exception handling&lt;/h3&gt;
&lt;p&gt;Because of the fact that &lt;code&gt;Tasks&lt;/code&gt; are run asynchronously we can&apos;t just use a standard &lt;code&gt;try catch&lt;/code&gt; block surrounding &lt;code&gt;Task&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static void TryCatchBlockWrongWay()
{
    try
    {
        Task.Factory.StartNew(() =&amp;gt; { throw new Exception(&quot;From method TryCatchBlockWrongWay&quot;); });
    }
    catch (Exception ex)
    {
        // this will never be hit
        Console.WriteLine(&quot;Exception handled {0}&quot;, ex);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In that case catch block is unreachable (I will describe later what happens with that exception), of course we could use &lt;code&gt;try catch&lt;/code&gt; inside &lt;code&gt;Task.Factory.StartNew&lt;/code&gt; lambda expression but this is not always the case.
Usually we want to handle exception in the caller of the &lt;code&gt;Task&lt;/code&gt;, not inside the &lt;code&gt;Task&lt;/code&gt; itself.
There are couple of ways of achieving that - depending on the situation you can use one of the following ways.
Exception are propagated to caller once you start waiting for the result of &lt;code&gt;Task&lt;/code&gt;.
So basically you can use &lt;code&gt;try catch&lt;/code&gt; block if you wait for a &lt;code&gt;Task&lt;/code&gt; to finish - either by accessing &lt;code&gt;Result&lt;/code&gt; property or using &lt;code&gt;Wait&lt;/code&gt; method&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static void HandleExceptionTryCatchResult()
{
    try
    {
        var task = Task.Factory.StartNew(() =&amp;gt;
        {
            throw new Exception(&quot;From method HandleExceptionTryCatchResult&quot;);
            return 1;
        });
        // do more stuff while task is running
        // do more stuff while task is running
        // do more stuff while task is running
        var result = task.Result;
    }
    catch (Exception ex)
    {
        Console.WriteLine(&quot;HandleExceptionTryCatchResult: exception handled in try catch block. Exception is {0}&quot;, ex);
    }
}

public static void HandleExceptionTryCatchWait()
{
    try
    {
        var task = Task.Factory.StartNew(() =&amp;gt; { throw new Exception(&quot;From method HandleExceptionTryCatchWait&quot;); });
        // do more stuff while task is running
        // do more stuff while task is running
        // do more stuff while task is running
        task.Wait();
    }
    catch (Exception ex)
    {
        Console.WriteLine(&quot;HandleExceptionTryCatchWait: exception handled in try catch block. Exception is {0}&quot;, ex);
    }
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;However accessing &lt;code&gt;Result&lt;/code&gt; or calling &lt;code&gt;Wait&lt;/code&gt; method are blocking calls, so this might not be a perfect solution for every scenario.
Fortunately we can also leverage &lt;code&gt;ContinueWith&lt;/code&gt; method which gives you an ability to specify what should be done once &lt;code&gt;Task&lt;/code&gt; finishes processing the operation.
What is more important you can configure this method to only be called if exception occurs.
Nonetheless there is one crucial thing you have to remember - in order to make exception handled or observed you have to access &lt;code&gt;Exception&lt;/code&gt; property of &lt;code&gt;Task&lt;/code&gt;...&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static void HandleExceptionContinueWith()
{
    Task.Factory.StartNew(() =&amp;gt; { throw new Exception(&quot;From method HandleExceptionContinueWith&quot;); })
                .ContinueWith(val =&amp;gt;
                {
                    // we need to access val.Exception property otherwise unobserved exception will be thrown
                    // ReSharper disable once PossibleNullReferenceException
                    foreach (var ex in val.Exception.Flatten().InnerExceptions)
                    {
                        Console.WriteLine(&quot;HandleExceptionContinueWith: exception handled in ContinueWith. Exception is {0}&quot;, ex);
                    }
                }, TaskContinuationOptions.OnlyOnFaulted);
}

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;or call &lt;code&gt;Handle&lt;/code&gt; method from &lt;code&gt;AggregateException&lt;/code&gt; object&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static void HandleExceptionContinueWithAndHandleMethod()
{
    Task.Factory.StartNew(() =&amp;gt; { throw new Exception(&quot;From method HandleExceptionContinueWith&quot;); })
                .ContinueWith(val =&amp;gt;
                {
                    val.Exception.Handle(ex =&amp;gt;
                    {
                        Console.WriteLine(&quot;HandleExceptionContinueWith: exception handled in AggregateException.Handle. Exception is {0}&quot;, ex);
                        return true;
                    });
                }, TaskContinuationOptions.OnlyOnFaulted);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Otherwise exception will not be handled which may cause a lot of troubles described in section 3 of this post.
Lastly if you use &lt;code&gt;.NET 4.5&lt;/code&gt; you can also just use &lt;code&gt;async await&lt;/code&gt; and &lt;code&gt;try catch&lt;/code&gt; block&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// called from Main
public static async void HandleExceptionTryCatchAwait()
{
    try
    {
        await HandleExceptionTryCatchAwaitInternal();
    }
    catch (Exception ex)
    {
        Console.WriteLine(&quot;HandleExceptionTryCatchAwait: exception handled in try catch block&quot;);
    }
}

private static async Task&amp;lt;int&amp;gt; HandleExceptionTryCatchAwaitInternal()
{
    return await Task.Factory.StartNew(() =&amp;gt;
    {
        throw new Exception();
        return 1;
    }, TaskCreationOptions.LongRunning);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;3. Handling UnobservedTaskException&lt;/h3&gt;
&lt;p&gt;If it happens that exception thrown by &lt;code&gt;Task&lt;/code&gt; is not handled, once the &lt;code&gt;Task&lt;/code&gt; is garbage-collected, finalizer thread will throw &lt;code&gt;UnobservedTaskException&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Task.Factory.StartNew(() =&amp;gt; { throw new Exception(&quot;fire-and-forget no exception handling&quot;); });
using (var autoresetEvent = new AutoResetEvent(false))
{
    //wait for task to run
    autoresetEvent.WaitOne(TimeSpan.FromSeconds(2));
}

Console.WriteLine(&quot;GC: Collecting&quot;);
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine(&quot;GC: Collected&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The implication of this depends on framework we are running our application on. If you run your app on &lt;code&gt;.NET 4.5&lt;/code&gt; or later version, with default escalation policy, &lt;code&gt;TaskScheduler.UnobservedTaskException&lt;/code&gt; event will be raised and basically that is all.
No more further problems, so basically you may not even realize that there is something like &lt;code&gt;UnobservedTaskException&lt;/code&gt;.
However if we add this entry&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;runtime&amp;gt;
    &amp;lt;ThrowUnobservedTaskExceptions enabled=&quot;true&quot;/&amp;gt;
&amp;lt;/runtime&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;to &lt;code&gt;app.config&lt;/code&gt; our process will be killed once &lt;code&gt;UnobservedTaskExceptionis&lt;/code&gt; is thrown.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2015/08/tpl-exception-handling-and-unobservedtaskexception-issue/ProcessKilled.png&quot;&gt;&lt;img src=&quot;images/ProcessKilled.png&quot; alt=&quot;UnobservedTaskExceptionis&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The problem arises in &lt;code&gt;.NET 4.0&lt;/code&gt; (if you run your app on &lt;code&gt;.NET 4.0&lt;/code&gt; not only compile it against this framework version), in this version of framework default escalation policy is very strict and will kill our process once the &lt;code&gt;UnobservedTaskException&lt;/code&gt; is thrown by finalizer thread.
Furthermore you cannot change this policy using &lt;code&gt;app.config&lt;/code&gt;. Fortunately there is a one last chance to handle UnobservedExceptions and prevent our process from being killed.
All you have to do is to wire up &lt;code&gt;TaskScheduler.UnobservedTaskException&lt;/code&gt; static event handler and then set exception to observed state&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
    e.SetObserved();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There is one more thing to clarify. You can compile your library against &lt;code&gt;.NET 4.0&lt;/code&gt; but if you have &lt;code&gt;.NET 4.5&lt;/code&gt; installed on your machine, your application is launched and run on &lt;code&gt;.NET 4.5&lt;/code&gt;.
This means that escalation policy from &lt;code&gt;.NET 4.5&lt;/code&gt; will be used - so by default process will not be killed.
In order to simulate pure &lt;code&gt;.NET 4.0&lt;/code&gt; behavior while having &lt;code&gt;.NET 4.5&lt;/code&gt; installed you have to add&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;runtime&amp;gt;
    &amp;lt;ThrowUnobservedTaskExceptions enabled=&quot;true&quot;/&amp;gt;
&amp;lt;/runtime&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;in your &lt;code&gt;app.config&lt;/code&gt; as it was mentioned before. Otherwise you would have to uninstall &lt;code&gt;.NET 4.5&lt;/code&gt; in order to, for example reproduce production issue.&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/HandlingUnobservedTaskExceptions&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>C# - testing internal classes</title><link>https://tpodolak.com/blog/c-testing-internal-classes/</link><guid isPermaLink="true">https://tpodolak.com/blog/c-testing-internal-classes/</guid><pubDate>Sun, 26 Jul 2015 09:23:00 GMT</pubDate><content:encoded>&lt;p&gt;I am currently involved in writing library which will be used by couple of external teams.
In that library we have a quite a lot classes which are only used internally and won&apos;t be a part of public &lt;code&gt;API&lt;/code&gt;.
The natural way of keeping that code inaccessible for other assemblies is to use internal access modifier.
However this makes the code also inaccessible directly for testing.
Of course you can still test your internal code through public &lt;code&gt;API&lt;/code&gt; but usually this is inconvenient and forces you to write a lot of additional code in test.
This is particularly painful for me, because our build process requires 100% test coverage.
Fortunately there is an easy way to make internal classes visible for certain assemblies without making them public.
All you have to do is to use &lt;code&gt;InternalsVisibleToAttribute&lt;/code&gt; and specify assembly name which is allowed to use code with internal access modifier.
This attribute is most commonly added to &lt;code&gt;AssemblyInfo.cs&lt;/code&gt; file. For example, assuming that my library is in &lt;code&gt;TestingInternalClasses.Lib&lt;/code&gt; assembly and my tests are in &lt;code&gt;TestingInternalClasses.Tests&lt;/code&gt; I should add&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[assembly: InternalsVisibleTo(&quot;TestingInternalClasses.Tests&quot;)]

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;to &lt;code&gt;AssemblyInfo.cs&lt;/code&gt; located in &lt;code&gt;TestingInternalClasses.Lib&lt;/code&gt; project. However you can also use this attribute in a class definition file - just like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using System;
using System.IO;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(&quot;TestingInternalClasses.Tests&quot;)]

namespace TestingInternalClasses.Lib
{
    internal class VanillaSerializer : ISerializer
    {
        public Stream Serialize(object obj)
        {
            if (obj == null)
                throw new ArgumentNullException(nameof(obj));

            // rest of the code
            // ...
            // ...
        }

        public T Deserialize&amp;lt;T&amp;gt;(Stream stream)
        {
            if (stream == null)
                throw new ArgumentNullException(nameof(stream));

            // rest of the code
            // ...
            // ...
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From now on I can easily test internal classes from &lt;code&gt;TestingInternalClasses.Lib&lt;/code&gt; project in &lt;code&gt;TestingInternalClasses.Tests&lt;/code&gt;. Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/TestingInternalClasses&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>WCF - exposing metadata over TCP</title><link>https://tpodolak.com/blog/wcf-exposing-metadata-over-tcp/</link><guid isPermaLink="true">https://tpodolak.com/blog/wcf-exposing-metadata-over-tcp/</guid><pubDate>Sun, 28 Jun 2015 15:10:00 GMT</pubDate><content:encoded>&lt;p&gt;I think that everyone who has ever been working with &lt;code&gt;WCF&lt;/code&gt; knows that we can enable metadata exchange by adding &lt;code&gt;ServiceMetadataBehavior&lt;/code&gt; to &lt;code&gt;App.config&lt;/code&gt; file&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;behaviors&amp;gt;
     &amp;lt;serviceBehaviors&amp;gt;
       &amp;lt;behavior&amp;gt;
         &amp;lt;serviceMetadata httpGetEnabled=&quot;true&quot;&amp;gt;&amp;lt;/serviceMetadata&amp;gt;
       &amp;lt;/behavior&amp;gt;
     &amp;lt;/serviceBehaviors&amp;gt;
&amp;lt;/behaviors&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Up until yesterday the build in solution works fine for me. However recently I&apos;ve had to expose metadata over &lt;code&gt;TCP&lt;/code&gt; protocol.
&lt;code&gt;ServiceMetadataBehavior&lt;/code&gt; doesn&apos;t have something like &lt;code&gt;TcpGetEnabled&lt;/code&gt; property so in order to expose metadata over other protocols (in my case &lt;code&gt;TCP&lt;/code&gt;) it is necessary to add custom &lt;code&gt;MEX&lt;/code&gt; endpoint.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;system.serviceModel&amp;gt;
    &amp;lt;services&amp;gt;
          &amp;lt;service name=&quot;AudioLib.Services.AudioService&quot;&amp;gt;
            &amp;lt;endpoint address=&quot;AudioService/MEX&quot; binding=&quot;mexTcpBinding&quot; contract=&quot;IMetadataExchange&quot;&amp;gt;
    &amp;lt;!-- application endpoints --&amp;gt;
            &amp;lt;host&amp;gt;
              &amp;lt;baseAddresses&amp;gt;
                &amp;lt;add baseAddress=&quot;net.tcp://localhost:8080&quot;&amp;gt;&amp;lt;/add&amp;gt;
              &amp;lt;/baseAddresses&amp;gt;
            &amp;lt;/host&amp;gt;
          &amp;lt;/endpoint&amp;gt;
        &amp;lt;/service&amp;gt;
    &amp;lt;/services&amp;gt; 
    &amp;lt;!-- rest of the config --&amp;gt;
&amp;lt;/system.serviceModel&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The endpoint configuration has to have a specific binding - in my case &lt;code&gt;mexTcpBinding&lt;/code&gt; (there are of course &lt;code&gt;MEX&lt;/code&gt; bindings available for other protocols).
What is more, the contract has to be set to &lt;code&gt;IMetadataExchange&lt;/code&gt;. The address value is up to us, we can use full blown address as well as leverage base address.
At this point if we run service we will get the exception&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2015/06/wcf-exposing-metadata-over-tcp/Exception.png&quot;&gt;&lt;img src=&quot;images/Exception.png&quot; alt=&quot;Exception&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Even though we added custom endpoint for metadata exchange we still have to use &lt;code&gt;ServiceMetadataBehavior&lt;/code&gt;.
This time however we can skip &lt;code&gt;httpGetEnabled&lt;/code&gt; property&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;!-- rest of the config --&amp;gt;
&amp;lt;serviceBehaviors&amp;gt;
        &amp;lt;behavior&amp;gt;
          &amp;lt;serviceMetadata httpgetenabled=&quot;true&quot;&amp;gt;&amp;lt;/serviceMetadata&amp;gt;
        &amp;lt;/behavior&amp;gt;
&amp;lt;/serviceBehaviors&amp;gt;
&amp;lt;!-- rest of the config --&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From now on we can access metadata over &lt;code&gt;TCP&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2015/06/wcf-exposing-metadata-over-tcp/audioservicetcpmex.png&quot;&gt;&lt;img src=&quot;images/audioservicetcpmex.png&quot; alt=&quot;metadata over TCP&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/WCFExposingServiceMetadataOverTCP&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Gulp - exluding type definitions files from TypeScript linting</title><link>https://tpodolak.com/blog/gulp-exluding-type-definitions-files-from-typescript-linting/</link><guid isPermaLink="true">https://tpodolak.com/blog/gulp-exluding-type-definitions-files-from-typescript-linting/</guid><pubDate>Sat, 13 Jun 2015 16:35:00 GMT</pubDate><content:encoded>&lt;p&gt;I wanted to improve a code quality of my &lt;code&gt;TypeScript&lt;/code&gt; project, so I decided to add linting to my gulp build process.
My original build task looked pretty straightforward&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function buildTypeScript() {
    return gulp.src([&apos;app/**/*.ts&apos;,&apos;typings/**/*.ts&apos;])
               .pipe(sourcemaps.init())
               .pipe(ts({
                   sortOutput: true,
                   noExternalResolve: true,
                   noEmitOnError: true,
                   target: &apos;ES5&apos;
               }))
               .pipe(concat(constants.appall))
               .pipe(sourcemaps.write())
               .pipe(gulp.dest(paths.app));
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and according to &lt;code&gt;gulp-tslint&lt;/code&gt; &lt;a href=&quot;https://www.npmjs.com/package/gulp-tslint&quot;&gt;manual&lt;/a&gt; adding linting requires including only two additional lines of code&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;.pipe(tslint())
.pipe(tslint.report(&apos;verbose&apos;));

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This works fine until you start using type definitions (d.ts files) from external resources (which is the usual way of combining &lt;code&gt;TypeScript&lt;/code&gt; with existing &lt;code&gt;JavaScript&lt;/code&gt; libraries).
Usually these files have different code styling rules than our own, which means that our build will fail.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2015/06/gulp-exluding-type-definitions-files-from-typescript-linting/buildfail.png&quot;&gt;&lt;img src=&quot;images/buildfail.png&quot; alt=&quot;buildfail&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;There are couple of ways of solving this problem. The obvious one is to split the task into two separate tasks, one for linting and one for building, but in my opinion a much cleaner way is to use &lt;a href=&quot;https://www.npmjs.com/package/gulp-filter&quot;&gt;&lt;code&gt;gulp-filter&lt;/code&gt;&lt;/a&gt;.
&lt;code&gt;Gulp-filter&lt;/code&gt; has an ability to filter the stream on the fly, but what is more interesting it can also restore it to previous unfiltered state.
Using these two features we can filter the stream from d.ts files before linting process begins and then restore the stream and pass it to &lt;code&gt;TypeScript&lt;/code&gt; compiler.
We can do it with two additional lines of code. Improved build script is presented below&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;function buildTypeScript() {
    // include all typescript files but exclude definitions
    var filter = gulpFilter([&apos;**/*.ts&apos;, &apos;!**/*d.ts&apos;]);

    return gulp.src([&apos;app/**/*.ts&apos;,&apos;typings/**/*.ts&apos;])
               .pipe(filter)    // use the filter
               .pipe(tslint())
               .pipe(tslint.report(&apos;prose&apos;, {
                   emitError: true
               }))
               .pipe(filter.restore()) // clear filter
               .pipe(sourcemaps.init())
               .pipe(ts({
                   sortOutput: true,
                   noExternalResolve: true,
                   noEmitOnError: true,
                   target: &apos;ES5&apos;
               }))
               .pipe(concat(constants.appall))
               .pipe(sourcemaps.write())
               .pipe(gulp.dest(paths.app));
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2015/06/gulp-exluding-type-definitions-files-from-typescript-linting/buildfilter.png&quot;&gt;&lt;img src=&quot;images/buildfilter.png&quot; alt=&quot;exluding type definitions&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/ExcludingDefinitelytypedFromTsLint&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>C# - dynamic type can be useful</title><link>https://tpodolak.com/blog/c-dynamic-type-can-be-useful/</link><guid isPermaLink="true">https://tpodolak.com/blog/c-dynamic-type-can-be-useful/</guid><pubDate>Sat, 16 May 2015 09:29:00 GMT</pubDate><content:encoded>&lt;p&gt;I am not a big fan of &lt;code&gt;dynamic&lt;/code&gt; type in C#, however there are certain situations in which it can be handy.
Let&apos;s assume that we have following piece of code (which I encounter quite often at my work)&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public abstract class Weapon
{
    //some properties
}

public class Gun : Weapon
{
     //some properties
}

// more derived types

var weaponService = new WeaponService();
IList&amp;lt;TransferObjects.Weapon&amp;gt; data = weaponService.GetWeapons();
List&amp;lt;Models.Weapon&amp;gt; weapons = data.Select(WeaponConverter.Convert).ToList();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see we have to convert &lt;code&gt;DTO&lt;/code&gt; objects into &lt;code&gt;normal&lt;/code&gt; objects using some kind of converter.
This is not a problematic when you can use some auto-mappings libraries (&lt;code&gt;Automapper&lt;/code&gt;,&lt;code&gt;FastMapper&lt;/code&gt;) however I am not allowed to do that in a company I work for.
So the question is how to write &lt;code&gt;WeaponConverter.Convert&lt;/code&gt; method in some elegant way. The obvious way (but definitely not elegant) is just to use lots of &lt;code&gt;if&lt;/code&gt; statements&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static Models.Weapon ConvertOld(TransferObjects.Weapon weapon)
{
    if (weapon == null)
        return null;
        
    if (weapon is TransferObjects.Gun)
        return ConvertInternal((TransferObjects.Gun) weapon);
        
    if (weapon is TransferObjects.Sword)
        return ConvertInternal((TransferObjects.Sword) weapon);
        
    throw new ArgumentException(&quot;Unknown weapon&quot;, nameof(weapon));
}
// ConvertInternal implementation goes here for every derived type

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;But this is really ugly, much better idea (at least from my point of view) is to leverage &lt;code&gt;dynamic&lt;/code&gt; keyword introduced in &lt;code&gt;.NET 4&lt;/code&gt;.
Thanks to it our &lt;code&gt;Convert&lt;/code&gt; method can be reduced to this&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static Models.Weapon Convert(TransferObjects.Weapon weapon)
{
    return weapon != null ? ConvertInternal((dynamic)weapon) : null;
}

// ConvertInternal implementation goes here for every derived type
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/DynamicCanBeUseful&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Nested properties initialization - syntactic sugar</title><link>https://tpodolak.com/blog/nested-properties-initialization-syntactic-sugar/</link><guid isPermaLink="true">https://tpodolak.com/blog/nested-properties-initialization-syntactic-sugar/</guid><pubDate>Sat, 18 Apr 2015 19:11:00 GMT</pubDate><content:encoded>&lt;p&gt;I think most of developers are familiar with the object syntax initializer, which basically allows you to set up values of properties just like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var webClient = new CustomWebClient
            {
                Settings = new CustomWebClientSettings
                {
                    Encoding = &quot;UTF-8&quot;,
                    Method = &quot;POST&quot;
                }
            };
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this example the &lt;code&gt;Settings&lt;/code&gt; property is assigned with new instance of &lt;code&gt;CustomWebClientSettings&lt;/code&gt; class.
However for time to time we only want to change particular property of given nested property and leave rest of the object intact.
Of course we can write it usual way&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// we assume that CustomWebClient initialized Settings property in constructor
var webClient = new CustomWebClient();
webClient.Settings.Encoding = &quot;UTF-8&quot;;
webClient.Settings.Method = &quot;POST&quot;;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;but there is a much cooler syntax for that. The code above can be rewritten to&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var webClient = new CustomWebClient
            {
                 Settings = {Encoding = &quot;UTF-8&quot;, Method = &quot;POST&quot;}
            };
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that there is no &lt;code&gt;new&lt;/code&gt; keyword in the assignment of &lt;code&gt;Settings&lt;/code&gt; property, which means that the &lt;code&gt;Settings&lt;/code&gt; object is updated with the values of properties in braces.
Of course this syntax can be safely used only if the nested property(in this case &lt;code&gt;Settings&lt;/code&gt;) is initialized up front in constructor, otherwise you will get &lt;code&gt;NullReferenceException&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/NestedPropertiesInitialization&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Using ECMAScript6 today</title><link>https://tpodolak.com/blog/using-ecmascript6-today/</link><guid isPermaLink="true">https://tpodolak.com/blog/using-ecmascript6-today/</guid><pubDate>Sun, 12 Apr 2015 10:48:00 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;Although &lt;code&gt;ECMAScript6&lt;/code&gt; has not been officially released yet, we can play around with new language features today.
There are tools such as &lt;code&gt;Traceur&lt;/code&gt; or &lt;code&gt;Babel&lt;/code&gt; which are able to convert &lt;code&gt;ECMAScript6&lt;/code&gt; into &lt;code&gt;ECMASciprt5&lt;/code&gt;, thus we are able to run the code in every browser.
So let&apos;s try to run the snippet below, which leverages &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment&quot;&gt;destructuring assignment&lt;/a&gt; using those tools&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(function () {
    var obj = {
        firstProp: 1,
        secondProp: 2
    }, array = [1, 2, 3];

    //Destructuring array
    var [x,y,z] = array;

    console.log(&apos;Destructuring array&apos;);
    console.log(&apos;Value of x = &apos; + x);
    console.log(&apos;Value of y = &apos; + y);
    console.log(&apos;Value of z = &apos; + z);

    console.log(&apos;Destructuring object&apos;);
    var { secondProp: b,firstProp: a } = obj;
    console.log(&apos;Value of firstProp = &apos; + a);
    console.log(&apos;Value of secondProp = &apos; + b);

}());
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;2. Using &lt;code&gt;Traceur&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;I&apos;ll start from &lt;code&gt;Traceur&lt;/code&gt; first. First of all we have to install it, so run in console (I am using gulp as my build system)&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install gulp-traceur --save-dev

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then we have to write simple gulp task which:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;grabs all of our js files&lt;/li&gt;
&lt;li&gt;runs the code analysis using &lt;code&gt;JsHint&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;transpiles source files into valid &lt;code&gt;ECMAScript5&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;concatenates the result into single file&lt;/li&gt;
&lt;li&gt;generates source maps (for debugging proposes)&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;var gulp = require(&apos;gulp&apos;);
var sourcemaps = require(&apos;gulp-sourcemaps&apos;);
var traceur = require(&apos;gulp-traceur&apos;);
var concat = require(&apos;gulp-concat&apos;);
var jshint = require(&apos;gulp-jshint&apos;);

return gulp.src(&apos;app/*.js&apos;)
           .pipe(jshint())
           .pipe(jshint.reporter(&apos;jshint-stylish&apos;))
           .pipe(jshint.reporter(&apos;fail&apos;))
           .pipe(sourcemaps.init())
           .pipe(traceur())
           .pipe(concat(&apos;app.all.js&apos;))
           .pipe(sourcemaps.write(&apos;.&apos;))
           .pipe(gulp.dest(&apos;dest&apos;));
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Having our result file ready, now we can add a script tag in html pointing to &lt;code&gt;app.all.js&lt;/code&gt;.
However at this point in the runtime we will get an error.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$traceurRuntime is not defined

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2015/04/using-ecmascript6-today/runtimeerror.png&quot;&gt;&lt;img src=&quot;images/runtimeerror.png&quot; alt=&quot;ECMAScript6 today&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Quick look at the generated &lt;code&gt;app.all.js&lt;/code&gt; file reveals the problem&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&quot;use strict&quot;;
(function() {
  var $__1,
      $__2;
  var obj = {
    firstProp: 1,
    secondProp: 2
  },
      array = [1, 2, 3];
  var $__0 = array,
      x = ($__1 = $__0[$traceurRuntime.toProperty(Symbol.iterator)](), ($__2 = $__1.next()).done ? void 0 : $__2.value),
      y = ($__2 = $__1.next()).done ? void 0 : $__2.value,
      z = ($__2 = $__1.next()).done ? void 0 : $__2.value;
  console.log(&apos;Destructuring array&apos;);
  console.log(&apos;Value of x = &apos; + x);
  console.log(&apos;Value of y = &apos; + y);
  console.log(&apos;Value of z = &apos; + z);
  console.log(&apos;Destructuring object&apos;);
  var $__3 = obj,
      b = $__3.secondProp,
      a = $__3.firstProp;
  console.log(&apos;Value of firstProp = &apos; + a);
  console.log(&apos;Value of secondProp = &apos; + b);
}());

//# sourceMappingURL=app.all.js.map

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Transpiled code has references to &lt;code&gt;$traceurRuntime&lt;/code&gt; objects, so in order to make our code work, we have to add additional script tag pointing to &lt;code&gt;traceur-runtime.js&lt;/code&gt;.
You can easily get the sources with &lt;code&gt;bower&lt;/code&gt;, just run in console&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install bower --save-dev
bower install  traceur-runtime

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now everything should work and in console we&apos;ll get expected result&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2015/04/using-ecmascript6-today/result.png&quot;&gt;&lt;img src=&quot;images/result.png&quot; alt=&quot;ECMAScript6 today&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;As you could see in example above &lt;code&gt;Traceur&lt;/code&gt; generates overcomplicated code which makes debugging of the original sources (using source maps) a painful process.
Just take a look at the following screenshot&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2015/04/using-ecmascript6-today/SourceMapTraceur.png&quot;&gt;&lt;img src=&quot;images/SourceMapTraceur.png&quot; alt=&quot;ECMAScript6 today&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;fortunately &lt;code&gt;Babel&lt;/code&gt; doesn&apos;t seem to have these drawbacks.&lt;/p&gt;
&lt;h3&gt;3. Using &lt;code&gt;Babel&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;Let&apos;s modify our gulp build script to use &lt;code&gt;Babel&lt;/code&gt; instead of &lt;code&gt;Traceur&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install gulp-babel --save-dev

&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;var gulp = require(&apos;gulp&apos;);
var sourcemaps = require(&apos;gulp-sourcemaps&apos;);
var babel= require(&apos;gulp-babel&apos;);
var concat = require(&apos;gulp-concat&apos;);
var jshint = require(&apos;gulp-jshint&apos;);

return gulp.src(&apos;app/*.js&apos;)
           .pipe(jshint())
           .pipe(jshint.reporter(&apos;jshint-stylish&apos;))
           .pipe(jshint.reporter(&apos;fail&apos;))
           .pipe(sourcemaps.init())
           .pipe(babel())
           .pipe(concat(&apos;app.all.js&apos;))
           .pipe(sourcemaps.write(&apos;.&apos;))
           .pipe(gulp.dest(&apos;dest&apos;));

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And basically that all, we are ready to go. &lt;code&gt;Babel&lt;/code&gt; doesn&apos;t require any runtime dependencies, generated code is simple&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&apos;use strict&apos;;

(function () {
    var obj = {
        firstProp: 1,
        secondProp: 2
    },
        array = [1, 2, 3];

    //Destructuring array
    var x = array[0];
    var y = array[1];
    var z = array[2];

    console.log(&apos;Destructuring array&apos;);
    console.log(&apos;Value of x = &apos; + x);
    console.log(&apos;Value of y = &apos; + y);
    console.log(&apos;Value of z = &apos; + z);

    console.log(&apos;Destructuring object&apos;);
    var b = obj.secondProp;
    var a = obj.firstProp;

    console.log(&apos;Value of firstProp = &apos; + a);
    console.log(&apos;Value of secondProp = &apos; + b);
})();
//# sourceMappingURL=app.all.js.map
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and even source maps seem to work correctly.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2015/04/using-ecmascript6-today/SourceMapBabel.png&quot;&gt;&lt;img src=&quot;images/SourceMapBabel.png&quot; alt=&quot;ECMAScript6 today&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;So when it comes to me I choose &lt;code&gt;Babel&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/UsingEcmaScript6Today&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Azure - connecting to Windows 10 virtual machine</title><link>https://tpodolak.com/blog/azure-connecting-to-windows-10-virtual-machine/</link><guid isPermaLink="true">https://tpodolak.com/blog/azure-connecting-to-windows-10-virtual-machine/</guid><pubDate>Wed, 11 Mar 2015 19:15:00 GMT</pubDate><content:encoded>&lt;p&gt;Today just a quick tip, which may save you some time. If you want to connect to virtual machine with &lt;code&gt;Windows 10 Technical Preview&lt;/code&gt;, make sure that you include &lt;code&gt;DNS&lt;/code&gt; name in user name field.
So instead of default combination of username and password&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2015/03/azure-connecting-to-windows-10-virtual-machine/failed.png&quot;&gt;&lt;img src=&quot;images/failed.png&quot; alt=&quot;Azure&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;which worked for me for every virtual machine (except for the one with Windows 10). You should use something like that&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2015/03/azure-connecting-to-windows-10-virtual-machine/dns.png&quot;&gt;&lt;img src=&quot;images/dns.png&quot; alt=&quot;Azure&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;If You don&apos;t know the &lt;code&gt;DNS&lt;/code&gt; name for virtual machine, you can easily check it in &lt;code&gt;Virtual Machines&lt;/code&gt; pane&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2015/03/azure-connecting-to-windows-10-virtual-machine/VirtualMachineList.png&quot;&gt;&lt;img src=&quot;images/VirtualMachineList.png&quot; alt=&quot;Azure&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>AngularJS - extending existing services using decorator</title><link>https://tpodolak.com/blog/angularjs-extending-existing-services-using-decorator/</link><guid isPermaLink="true">https://tpodolak.com/blog/angularjs-extending-existing-services-using-decorator/</guid><pubDate>Wed, 25 Feb 2015 23:24:00 GMT</pubDate><content:encoded>&lt;p&gt;One of the features I miss the most in &lt;code&gt;AngularJS&lt;/code&gt; is ability to easy unsubscribe event handlers.
There is no convenience function opposed to &lt;code&gt;$on&lt;/code&gt;, so in order to unsubscribe event, we have to call method returned by &lt;code&gt;$on&lt;/code&gt; function&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(function () {
    angular.module(&apos;app.download&apos;, [])
        .controller(&apos;downloadCtrl&apos;, downloadController);

    function downloadController($scope) {
        // keep the unsubscribe function in local variable
        var afterRenderUnsubscribe = $scope.$on(&apos;afterRender&apos;, onAfterRender);

        function onAfterRender() {
            console.log(&apos;CallingonAfterRender&apos;);
            // unsubscribe form event
            afterRenderUnsubscribe();
        }
    }
}());
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;However in my opinion this approach fails in real life scenarios, because usually we are subscribed to more than one event - thus we have to have multiple local variables for detaching listeners.
Fortunately &lt;code&gt;AngularJS&lt;/code&gt; provides an easy way to extend existing services with some new functionalities - we can achieve that by using &lt;code&gt;$provide&lt;/code&gt; service.
This service exposes &lt;a href=&quot;https://docs.angularjs.org/api/auto/service/$provide#decorator&quot;&gt;&lt;code&gt;decorator&lt;/code&gt;&lt;/a&gt; method, which is able to intercept creation of any service, so we are able to augment it with some new functions.
The best moment to call &lt;code&gt;$provide.decorator&lt;/code&gt; method is during module configuration, thanks to this approach we are sure that our custom logic is invoked before module is started.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;angular.module(&apos;app.common&apos;, [])
       .config(extendServices);

/*ngInject*/
function extendServices($provide) {
    $provide.decorator(&apos;serviceName&apos;, function ($delegate) {
     /*some interception logic*/
    });
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In my case I wanted to extend &lt;code&gt;$rootScope&lt;/code&gt; with new method &lt;code&gt;$un&lt;/code&gt; for unsubscribing events, so I called method &lt;code&gt;decorator&lt;/code&gt; with parameter &lt;code&gt;&apos;$rootScope&apos;&lt;/code&gt; (note single quotation marks) - this tells &lt;code&gt;Angular&lt;/code&gt; that I will be modifying &lt;code&gt;$rootScope&lt;/code&gt; service&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;angular.module(&apos;app.common&apos;, [])
    .config(extendServices);

/*ngInject*/
function extendServices($provide) {
    $provide.decorator(&apos;$rootScope&apos;, extendRootScope);
}

/*ngInject*/
function extendRootScope($delegate) {
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Because I passed &lt;code&gt;&apos;$rootScope&apos;&lt;/code&gt; as a first argument of &lt;code&gt;$provide.decorator&lt;/code&gt; method, the &lt;code&gt;$delegate&lt;/code&gt; parameter in &lt;code&gt;extendRootScope&lt;/code&gt; function is actually a &lt;code&gt;$rootScope&lt;/code&gt; service.
Now having access to the service I can augment it with my custom logic for detaching event handlers.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;/*ngInject*/
function extendRootScope($delegate){
    $delegate.$un=function(name,listener){
        var namedListeners=this.$$listeners[name],
            idx;
        if(namedListeners&amp;amp;&amp;amp;(idx=namedListeners.indexOf(listener))&amp;gt;-1){
            namedListeners.splice(idx,1);
        }
    };
    return $delegate;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Entire code listing looks then as follows&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(function () {
    angular.module(&apos;app.common&apos;, [])
           .config(extendServices);

    /*ngInject*/
    function extendServices($provide)
    {
        $provide.decorator(&apos;$rootScope&apos;, extendRootScope);
    }

    /*ngInject*/
    function extendRootScope($delegate)
    {
        $delegate.$un = function (name, listener) {
            var namedListeners = this.$$listeners[name],
                idx;
            if (namedListeners &amp;amp;&amp;amp; (idx = namedListeners.indexOf(listener)) &amp;gt; -1) {
                namedListeners.splice(idx, 1);
            }
        };
        return $delegate;
    }
}());
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From now on, you can unsubscribe events handlers simply by calling &lt;code&gt;$un&lt;/code&gt; method&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(function () {
    angular.module(&apos;app.download&apos;, [&apos;app.common&apos;])
        .controller(&apos;downloadCtrl&apos;, downloadController);

    function downloadController($scope) {
        $scope.$on(&apos;afterRender&apos;, onAfterRender);

        function onAfterRender() {
            console.log(&apos;Calling afterRender handler&apos;);
            $scope.$un(&apos;afterRender&apos;, onAfterRender);
        }
    }
}());
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and our listener will react only once&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;console.log(&apos;Broadcasting afterRender event for the first time&apos;);
$rootScope.$broadcast(&apos;afterRender&apos;);
console.log(&apos;Broadcasting afterRender event for the second time&apos;);
$rootScope.$broadcast(&apos;afterRender&apos;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2015/02/angularjs-extending-existing-services-using-decorator/InvokeEvents.png&quot;&gt;&lt;img src=&quot;images/InvokeEvents.png&quot; alt=&quot;AngularJS&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/AngularJSDecorator&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>WinJS - AuthenticateAndContinue and &quot;remote procedure call failed&quot; exception</title><link>https://tpodolak.com/blog/winjs-authenticateandcontinue-and-remote-procedure-call-failed-exception/</link><guid isPermaLink="true">https://tpodolak.com/blog/winjs-authenticateandcontinue-and-remote-procedure-call-failed-exception/</guid><pubDate>Thu, 19 Feb 2015 22:11:00 GMT</pubDate><content:encoded>&lt;p&gt;A while ago I started playing around a bit with &lt;code&gt;JavaScript&lt;/code&gt; on &lt;code&gt;Windows Phone&lt;/code&gt;. I wanted to create very simple app using AngularJS but of course I also had to use some &lt;code&gt;WinJS&lt;/code&gt; features (for integration with device ).
One of the things I needed to implement was authentication/authorization using &lt;code&gt;OAuth&lt;/code&gt;.
According to &lt;code&gt;WinJS&lt;/code&gt; &lt;a href=&quot;https://msdn.microsoft.com/pl-pl/library/dn608114.aspx&quot;&gt;documentation&lt;/a&gt; it should be pretty straightforward - just use &lt;code&gt;Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAndContinue&lt;/code&gt; method with appropriate URLs.
Of course I wanted authentication/authorization to be called before navigating to any screen, so I slightly modified default &lt;code&gt;WinJS&lt;/code&gt; template and my code looked like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// rest of code omitted for brevity
var activation = Windows.ApplicationModel.Activation,
    app = WinJS.Application,
    nav = WinJS.Navigation,
    sched = WinJS.Utilities.Scheduler,
    ui = WinJS.UI;

 app.addEventListener(&quot;activated&quot;, function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }

            nav.history = app.sessionState.history || {};
            nav.history.current.initialPlaceholder = true;

            var p = ui.processAll().then(function() {
                Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAndContinue(
                        requestUrl, // for instance facebook auth url
                        callbackUrl // for instance facebook auth callback url
                    );
            });
            args.setPromise(p);
        }
    });
// rest of code omitted for brevity
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Unfortunately all I got was this strange exception&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2015/02/angularjs-extending-existing-services-using-decorator/RemoteProcedureCallsFailed.png&quot;&gt;&lt;img src=&quot;images/RemoteProcedureCallsFailed.png&quot; alt=&quot;remote procedure call failed&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The exception itself originated somewhere from &lt;code&gt;WinJS&lt;/code&gt; framework so I wasn&apos;t able to debug it at all.
It took me a while to figure this out but after all it turned out, that all you have to do, to make it work is to &lt;code&gt;schedule&lt;/code&gt; call of &lt;code&gt;AuthenticateAndContinue&lt;/code&gt; method using &lt;code&gt;WinJS.Utilities.Scheduler&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;WinJS.Utilities.Scheduler.schedule(function(){ //your code in here});

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After this change entire code listing looks like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// rest of code omitted for brevity
var activation = Windows.ApplicationModel.Activation,
   app = WinJS.Application,
   nav = WinJS.Navigation,
   sched = WinJS.Utilities.Scheduler,
   ui = WinJS.UI;

app.addEventListener(&quot;activated&quot;, function (args) {
       if (args.detail.kind === activation.ActivationKind.launch) {
           if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
               // TODO: This application has been newly launched. Initialize
               // your application here.
           } else {
               // TODO: This application has been reactivated from suspension.
               // Restore application state here.
           }
           
           nav.history = app.sessionState.history || {};
           nav.history.current.initialPlaceholder = true;
           
           var p = ui.processAll().then(function() {
               return sched.schedule(function() {
                   Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAndContinue(
                       requestUrl, // for instance facebook auth url,
                       callbackUrl // for instance facebook auth callback url
                   );
               });
           });
           
           args.setPromise(p);
       }
   });
// rest of code omitted for brevity
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After this procedure we should be successfully redirected to the &lt;code&gt;requestUrl&lt;/code&gt;, in my case to &lt;code&gt;Facebook&lt;/code&gt; login page&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2015/02/angularjs-extending-existing-services-using-decorator/Succesfull.png&quot;&gt;&lt;img src=&quot;images/Succesfull.png&quot; alt=&quot;Succesfull&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>AngularJS - dependency injection</title><link>https://tpodolak.com/blog/angularjs-dependency-injection/</link><guid isPermaLink="true">https://tpodolak.com/blog/angularjs-dependency-injection/</guid><pubDate>Mon, 16 Feb 2015 19:39:00 GMT</pubDate><content:encoded>&lt;p&gt;There are couple of ways of injecting dependencies into &lt;code&gt;AngularJS&lt;/code&gt; components. The most common one is just to specify the dependency name in the function&apos;s argument list&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(function() {
    angular
        .module(&apos;app&apos;)
        .controller(&apos;shellCtrl&apos;, function ($scope, $http) {
            $scope.title = &quot;Title&quot;;
        });
})();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;However this technique fails in real life scenarios, because for production we usually (or rather always) minify and uglify javascript files.
Uglify proces renames our variables and due to the fact that dependencies are resolved by name, AngularJS is not able to find appropriate services, directives etc.
To overcome this limitation, we can enclose our function definition into an array, and specify dependencies as a string literals.
Our original code becomes then&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(function () {
    angular.module(&apos;app&apos;)
           .controller(&apos;shellCtrl&apos;, [&apos;$scope&apos;, &apos;$http&apos;, function ($scope, $http) {
               $scope.title = &quot;Title&quot;;
           }]);
})();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Although this works fine even after minifying and uglifiyng js files, for me this code is hard to read.
That is why I like to use yet another technique. This technique leverages variable hoisting and &lt;code&gt;$inject&lt;/code&gt; property&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(function(){
    angular.module(&apos;app&apos;)
           .controller(&apos;shellCtrl&apos;,shellController);

    shellController.$inject=[&apos;$scope&apos;,&apos;$http&apos;];

    function shellController($scope,$http){
        $scope.title=&apos;title&apos;;
    }
})();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As You can see I extracted controller function into separate variable &lt;code&gt;shellController&lt;/code&gt; and listed all necessary dependencies in &lt;code&gt;$inject&lt;/code&gt; array&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;shellController.$inject= [&apos;$scope&apos;,&apos;$http&apos;]

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It is even possible to enhance a bit this example and make it a little less error prone.
With the current implementation we have to make sure that order of properties in &lt;code&gt;$inject&lt;/code&gt; array is the same as in function declaration.
It is easy to keep track of that if we have just a couple of dependencies, but it might be a bit of a pain if we start to add, remove or edit them.
Fortunately we can automate this task and basically autogenerate &lt;code&gt;$inject&lt;/code&gt; array. In order to do that I like to use &lt;code&gt;Gulp&lt;/code&gt; (although it is also possible to use &lt;code&gt;Grunt&lt;/code&gt;).
First of all we have to install &lt;code&gt;Gulp&lt;/code&gt;. There is great tutorial how to do that in &lt;a href=&quot;https://github.com/gulpjs/gulp/blob/master/docs/getting-started.md&quot;&gt;here&lt;/a&gt;.
Having &lt;code&gt;Gulp&lt;/code&gt; on board we have to install additional packages: &lt;code&gt;gulp-rename&lt;/code&gt; and &lt;code&gt;gulp-ng-annotate&lt;/code&gt;.
In order to do that type into command line&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install gulp-ng-annotate --save-dev
npm install gulp-rename --save-dev

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we can create &lt;code&gt;gulp.js&lt;/code&gt; file which should look more or less like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var rename = require(&apos;gulp-rename&apos;),
    ngAnnotate = require(&apos;gulp-ng-annotate&apos;);

gulp.task(&apos;annotate&apos;, function () { //create new task &apos;annotate&apos;
    return gulp.src(&apos;app/layout/controllers/shellController.js&apos;) //select files to process
        .pipe(ngAnnotate()) // add angularjs dependeny injection annotation
        .pipe(rename(&apos;app.all.js&apos;)) //rename in-memory stream to app.all.js
        .pipe(gulp.dest(&apos;.build&apos;));//save stream to new location
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can run this task typing into command line&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;gulp annotate

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2015/02/angularjs-extending-existing-services-using-decorator/gulp.png&quot;&gt;&lt;img src=&quot;images/gulp-1024x213.png&quot; alt=&quot;gulp dependency injection&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;And as a result our original code (notice lack of dependeny annotations - no &lt;code&gt;$inject&lt;/code&gt; arrray)&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(function() {
    angular.module(&apos;app&apos;)
           .controller(&apos;shellCtrl&apos;, shellController);

    function shellController($scope, $http) {
        $scope.title = &apos;title&apos;;
    }
})();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Will be transformed into&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(function(){
    angular.module(&apos;app&apos;)
           .controller(&apos;shellCtrl&apos;,shellController);

    function shellController($scope,$http){
    }
    
shellController.$inject=[&quot;$scope&quot;,&quot;$http&quot;];
})();
&lt;/code&gt;&lt;/pre&gt;
</content:encoded></item><item><title>Fixing empty SQL server list in &quot;Entity Data Model Wizard&quot;</title><link>https://tpodolak.com/blog/fixing-empty-sql-server-list-in-entity-data-model-wizard/</link><guid isPermaLink="true">https://tpodolak.com/blog/fixing-empty-sql-server-list-in-entity-data-model-wizard/</guid><pubDate>Mon, 10 Nov 2014 15:23:00 GMT</pubDate><content:encoded>&lt;p&gt;I consider myself as a quite experienced user of &lt;code&gt;Nhibernate&lt;/code&gt;, that is why I decided to check what is going on on the other side of barricade and started playing with &lt;code&gt;Entity Framework&lt;/code&gt;.
I followed the steps of some tutorial and I stuck at the very beginning of it.
I was about to generate model classes using &lt;code&gt;Entity Data Model Wizard&lt;/code&gt; but it turned out that the wizard could not find my SQL server (despite the fact that server itself was up and running).&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/11/fixing-empty-sql-server-list-in-entity-data-model-wizard/EmptyServerList.png&quot;&gt;&lt;img src=&quot;images/EmptyServerList.png&quot; alt=&quot;empty SQL server list&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;I remember having similar issue a while back, but at that time I wasn&apos;t able to solve it (I ended up creating connections string manually).
This time I wanted to give this issue a closer look. After a bit of digging I found the problem - the SQL server wasn&apos;t broadcasting information about itself.
In order to fix it and make the server visible to other computers and applications it is necessary to start &lt;code&gt;SQL Server Browser&lt;/code&gt; service.
To do that go to &lt;code&gt;Start -&amp;gt; Run&lt;/code&gt; and type &lt;code&gt;Services.msc&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/11/fixing-empty-sql-server-list-in-entity-data-model-wizard/runservices.png&quot;&gt;&lt;img src=&quot;images/runservices.png&quot; alt=&quot;runservices&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Then in newly opened window find &lt;code&gt;SQL Server Browser&lt;/code&gt; service&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/11/fixing-empty-sql-server-list-in-entity-data-model-wizard/SqlServerBrowser.png&quot;&gt;&lt;img src=&quot;images/SqlServerBrowser.png&quot; alt=&quot;SqlServerBrowser&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Double click it and set up startup type to &lt;code&gt;Automatic&lt;/code&gt;. You can also click &lt;code&gt;Start&lt;/code&gt; button to make sure that service starts immediately&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/11/fixing-empty-sql-server-list-in-entity-data-model-wizard/automaticserverbrowser.png&quot;&gt;&lt;img src=&quot;images/automaticserverbrowser.png&quot; alt=&quot;automaticserverbrowser&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;From now on SQL servers should be visible in &lt;code&gt;Entity Data Model Wizard&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/11/fixing-empty-sql-server-list-in-entity-data-model-wizard/filledserverlist.png&quot;&gt;&lt;img src=&quot;images/filledserverlist.png&quot; alt=&quot;filledserverlist&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>T-SQL - syntactic sugar for updating current row in cursor</title><link>https://tpodolak.com/blog/t-sql-syntactic-sugar-for-updating-current-row-in-cursor/</link><guid isPermaLink="true">https://tpodolak.com/blog/t-sql-syntactic-sugar-for-updating-current-row-in-cursor/</guid><pubDate>Sat, 01 Nov 2014 20:05:00 GMT</pubDate><content:encoded>&lt;p&gt;I am not a big fan of cursors, however for time to time I have to write one. In my case cursor usually is responsible for some complicated updates.
Until yesterday I&apos;ve been writing my update statements within the cursor the standard way&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;-- cursor code omitted for brevity
-- some complicated update
UPDATE Person.Person set FirstName = &apos;some logic goes here&apos; where Person.BusinessEntityID = @Id
where @Id variable is set by cursor. 
-- cursor code omitted for brevity
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There is nothing wrong with that, however we can do the same thing using specialized syntax - &lt;code&gt;current of&lt;/code&gt; keyword(s)&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;UPDATE Person.Person set FirstName = &apos;some logic goes here&apos; where current of personCursor
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The entire cursor statement then looks that way&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;DECLARE personCursor CURSOR FOR SELECT top 1000 * FROM Person.Person
OPEN personCursor
FETCH NEXT FROM personCursor
WHILE @@FETCH_STATUS = 0
BEGIN
   -- some complicated update goes here
   UPDATE Person.Person set FirstName = &apos;some logic goes here&apos; where current of personCursor
   FETCH NEXT FROM personCursor
END
CLOSE personCursor
DEALLOCATE personCursor
&lt;/code&gt;&lt;/pre&gt;
</content:encoded></item><item><title>T-SQL - executing query multiple times</title><link>https://tpodolak.com/blog/t-sql-executing-query-multiple-times/</link><guid isPermaLink="true">https://tpodolak.com/blog/t-sql-executing-query-multiple-times/</guid><pubDate>Mon, 27 Oct 2014 21:56:00 GMT</pubDate><content:encoded>&lt;p&gt;For time to time during my everyday work I have to do some &lt;code&gt;SQL&lt;/code&gt; query optimization.
The simplest way of measuring whether my changes improved the performance or not, is simply measure the execution time of given query (I know that this is not the best way of doing that, but let&apos;s leave aside execution plans for now).
However measuring time of single executin is not very meaningfull. Thats why I like execute query multiple times by using this simple trick&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;GO 100
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/10/t-sql-executing-query-multiple-times/GO1000.png&quot;&gt;&lt;img src=&quot;images/GO1000.png&quot; alt=&quot;executing query multiple times&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;and then calculate an average time of execution by dividing the total time by execution count.
As You can see, all You have to do is to specify execution count after the &lt;code&gt;GO&lt;/code&gt; statment.
Despite the fact that &lt;code&gt;Management Studio&lt;/code&gt; indicates that there is an error in the &lt;code&gt;SQL&lt;/code&gt;, this is perfectly valid code.
Of course You should hide execution results in order to measure only the time of execution, not the time of rendering data.
To do that, right click on query window and choose &lt;code&gt;Query Options...&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/10/t-sql-executing-query-multiple-times/queryoptions.png&quot;&gt;&lt;img src=&quot;images/queryoptions.png&quot; alt=&quot;queryoptions&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;then select &lt;code&gt;Results&lt;/code&gt; node and check &lt;code&gt;Discard results after execution&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/10/t-sql-executing-query-multiple-times/queryoptionshighlighted.png&quot;&gt;&lt;img src=&quot;images/queryoptionshighlighted.png&quot; alt=&quot;queryoptionshighlighted&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>INotifyPropertyChange - notifying about change of all properties at once</title><link>https://tpodolak.com/blog/inotifypropertychange-notifying-about-change-of-all-properties-at-once/</link><guid isPermaLink="true">https://tpodolak.com/blog/inotifypropertychange-notifying-about-change-of-all-properties-at-once/</guid><pubDate>Sun, 24 Aug 2014 09:40:00 GMT</pubDate><content:encoded>&lt;p&gt;Today, working on a new feature for my pet project, I realized that I have to notify the view, that all properties in view model have changed.
The most obvious way to achieve that would, of course be to rise &lt;code&gt;PropertyChange&lt;/code&gt; event a bunch of times.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;protected virtual void OnPropertyChanged(Expression&amp;lt;Func&amp;lt;object&amp;gt;&amp;gt; propertyExpression)
{
   //..
   //implementation
   //..
}

protected virtual void OnPropertyChanged(string propertyName)
{
   //..
   //implementation
   //..
}

public void Refresh()
{
   OnPropertyChanged(() =&amp;gt; FirstProperty);
   OnPropertyChanged(() =&amp;gt; SecondProperty);
   OnPropertyChanged(() =&amp;gt; ThirdProperty);
   //and so on ...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is good solution for one time usage, however I was interested in something more general, something which could be extracted to base view model.
Fortunately, it turns out that there is a simple trick to do that. All You have to do is use an empty string or null as a property name.
So in my case this comes down to this one-liner&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public void Refresh()
{
   OnPropertyChanged(string.Empty);
}
&lt;/code&gt;&lt;/pre&gt;
</content:encoded></item><item><title>NHibernate - generating WHERE IN … OR … queries</title><link>https://tpodolak.com/blog/nhibernate-generating-where-in-or-queries/</link><guid isPermaLink="true">https://tpodolak.com/blog/nhibernate-generating-where-in-or-queries/</guid><pubDate>Mon, 18 Aug 2014 10:08:00 GMT</pubDate><content:encoded>&lt;p&gt;Let&apos;s assume that we have a simple table &lt;code&gt;GL_Task&lt;/code&gt; which looks like this&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/08/nhibernate-generating-where-in-or-queries/Table.png&quot;&gt;&lt;img src=&quot;images/Table.png&quot; alt=&quot;Table&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;I was asked to rewrite simple &lt;code&gt;SQL&lt;/code&gt; query&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;SELECT Id,Name,IdProject FROM GL_Task WHERE Name = &apos;First task&apos; OR Id IN (3,4 /*more id&apos;s to come*/)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;using NHibernate&apos;s &lt;code&gt;QueryOver API&lt;/code&gt;. As simple as it may seem, solution for this particular problem is not straightforward.
My first (not so clever) attempt was simply combining &lt;code&gt;WhereRestrictionOn&lt;/code&gt; and &lt;code&gt;Where&lt;/code&gt; clause&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var result = session.QueryOver&amp;lt;Task&amp;gt;().Where(val=&amp;gt; val.Name == &quot;First task&quot;)
                                      .WhereRestrictionOn(val=&amp;gt; val.Id)
                                      .IsIn(new []{3,4})
                                      .List();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Of course this query returns wrong data because of the fact, that &lt;code&gt;NHiberante&lt;/code&gt; by default &quot;joins&quot; queries using &lt;code&gt;AND&lt;/code&gt; operator.
So above query will result in generating something like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;SELECT Id,Name,IdProject FROM GL_Task WHERE Name = &apos;First task&apos; AND Id IN (3,4 /*more id&apos;s to come*/)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After a little digging I managed to write appropriate query&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var orRestriction = Restrictions.Or(
                         Restrictions.Where&amp;lt;Task&amp;gt;(val =&amp;gt; val.Name == &quot;First task&quot;),
                         Restrictions.On&amp;lt;Task&amp;gt;(val =&amp;gt; val.Id).IsIn(new[] { 3,4 }));

var result = session.QueryOver&amp;lt;Task&amp;gt;()
                    .Where(orRestriction)
                    .List();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Although this code generates correct &lt;code&gt;SQL&lt;/code&gt;, it is hard to use it in case of many &lt;code&gt;OR&lt;/code&gt; statements.
For example, adding one more &lt;code&gt;OR&lt;/code&gt; force us to write&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var orRestriction = Restrictions.Or(
      Restrictions.Or(
            Restrictions.Where&amp;lt;Task&amp;gt;(val =&amp;gt; val.Name == &quot;First task&quot;),
            Restrictions.On&amp;lt;Task&amp;gt;(val =&amp;gt; val.Id).IsIn(new[] {3, 4}) 
       ),
       Restrictions.On&amp;lt;Task&amp;gt;(val =&amp;gt; val.Name).IsIn(new[] {&quot;FirstTask&quot;, &quot;SecondTask&quot;})
);

var result = session.QueryOver&amp;lt;Task&amp;gt;()
                    .Where(orRestriction)
                    .List();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In my opinion this is a little bit hard to read, so I continued my searching to find more elegant solution.
My third attempt was based on &lt;code&gt;Restrictions.Disjunction&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var disjunctinos = Restrictions.Disjunction()
                           .Add(Restrictions.Where&amp;lt;Task&amp;gt;(val =&amp;gt; val.Name == &quot;First task&quot;))
                           .Add(Restrictions.On&amp;lt;Task&amp;gt;(val =&amp;gt; val.Id).IsIn(new[] { 3,4 }));
                           
var result = session.QueryOver&amp;lt;Task&amp;gt;()                    
                    .Where(disjunctinos)                    
                    .List();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This was almost perfect solution. Adding new &lt;code&gt;OR&lt;/code&gt; statements do not require us to do function nesting&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var disjunctinos = Restrictions.Disjunction()
                          .Add(Restrictions.Where&amp;lt;Task&amp;gt;(val =&amp;gt; val.Name == &quot;First task&quot;))
                          .Add(Restrictions.On&amp;lt;Task&amp;gt;(val =&amp;gt; val.Id).IsIn(new[] { 3,4 }))
                          .Add(Restrictions.On&amp;lt;Task&amp;gt;(val =&amp;gt; val.Name).IsIn(new[] { &quot;FirstTask&quot;, &quot;SecondTask&quot; }));

var result = session.QueryOver&amp;lt;Task&amp;gt;()
                    .Where(disjunctinos)
                    .List();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;However the ultimate solution is to just add &lt;code&gt;NHibernate.Criterion&lt;/code&gt; namespace and use &lt;code&gt;IsIn&lt;/code&gt; extension method.
This operation simplify our query into single lambda expression&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var result = session.QueryOver&amp;lt;Task&amp;gt;()
                    .Where(val =&amp;gt; val.Name == &quot;First task&quot; || val.Id.IsIn(new[] { 3,4 }))
                    .List();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/NHibernateDisjunction&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Resharper - localizable string literals</title><link>https://tpodolak.com/blog/resharper-localizable-string-literals/</link><guid isPermaLink="true">https://tpodolak.com/blog/resharper-localizable-string-literals/</guid><pubDate>Sun, 17 Aug 2014 13:17:00 GMT</pubDate><content:encoded>&lt;p&gt;Everyone who has ever tried to create multilingual application knows, that this is very tedious task. The most repetitive work is usually moving hard-coded strings to resource files. Fortunately with Resharper this is definitelly less painfull than usuall.
In order to point out localizable parts of application , it is necessary to decorate classes with &lt;code&gt;System.ComponentModel.LocalizableAttribute&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/08/resharper-localizable-string-literals/LocalizableAttribute.png&quot;&gt;&lt;img src=&quot;images/LocalizableAttribute.png&quot; alt=&quot;LocalizableAttribute&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;However, usually we want to localize an entire program, so more universal solution is to set appropriate project configuration in properties window. To bring up this window, select project file and then press &lt;code&gt;F4&lt;/code&gt; button.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/08/resharper-localizable-string-literals/PropertiesWindow.png&quot;&gt;&lt;img src=&quot;images/PropertiesWindow.png&quot; alt=&quot;PropertiesWindow&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;From now on, Resharper shows warnings indicating that our hard-coded strings might be moved to resource file. Pressing &lt;code&gt;ALT+ENTER&lt;/code&gt; on these strings will bring up the context menu action, where new option - &lt;code&gt;Move to resource&lt;/code&gt; is available.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/08/resharper-localizable-string-literals/MoveToResourceContextAction.png&quot;&gt;&lt;img src=&quot;images/MoveToResourceContextAction.png&quot; alt=&quot;MoveToResourceContextAction&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Choosing this option will bring up the &lt;code&gt;Move to Resource&lt;/code&gt; window. However if we do not have any resource files in our project, we will get this message.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/08/resharper-localizable-string-literals/NoResourcesFound.png&quot;&gt;&lt;img src=&quot;images/NoResourcesFound.png&quot; alt=&quot;NoResourcesFound&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In order to create these files, right click on project and choose &lt;code&gt;Add-&amp;gt;New Item&lt;/code&gt;. Now, select &lt;code&gt;Resource.resx&lt;/code&gt; file and name it for example &lt;code&gt;LocalizableStrings.resx&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/08/resharper-localizable-string-literals/AddingsResource.png&quot;&gt;&lt;img src=&quot;images/AddingsResource.png&quot; alt=&quot;AddingsResource&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In this resource file we will store values for our &lt;code&gt;default language&lt;/code&gt;. Supporting more languages require us to create additional &lt;code&gt;LocalizableString&lt;/code&gt; files with appropriate &lt;code&gt;LETF&lt;/code&gt; tags suffixes.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/08/resharper-localizable-string-literals/Allfiles.png&quot;&gt;&lt;img src=&quot;images/Allfiles.png&quot; alt=&quot;Allfiles&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Now, we are able to move our hard-coded string to resource files.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/08/resharper-localizable-string-literals/MoveToResource.png&quot;&gt;&lt;img src=&quot;images/MoveToResource.png&quot; alt=&quot;MoveToResource&quot; /&gt;&lt;/a&gt;
&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/08/resharper-localizable-string-literals/aftermove.png&quot;&gt;&lt;img src=&quot;images/aftermove.png&quot; alt=&quot;aftermove&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;By default Resharper adds hard-coded strings to default resource file, so we have to specify values for localizable string for other languages. In order to do that, first navigate to resource entry in &lt;code&gt;LocalizableStrings.resx&lt;/code&gt; file by holding &lt;code&gt;CTRL&lt;/code&gt; and clicking property &lt;code&gt;Program_Main_This_is_localizable_string&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/08/resharper-localizable-string-literals/GoToProperty.png&quot;&gt;&lt;img src=&quot;images/GoToProperty.png&quot; alt=&quot;GoToProperty&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/08/resharper-localizable-string-literals/overriden.png&quot;&gt;&lt;img src=&quot;images/overriden.png&quot; alt=&quot;overriden&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;and then press &lt;code&gt;ALT+ENTER&lt;/code&gt; and choose &lt;code&gt;Override &apos;PropertyName…&apos;&lt;/code&gt;. This operation brings up &lt;code&gt;Edit Resource&lt;/code&gt; window where You can easily navigate between resource files and update given resource property&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/08/resharper-localizable-string-literals/EditResourceDialog.png&quot;&gt;&lt;img src=&quot;images/EditResourceDialog.png&quot; alt=&quot;EditResourceDialog&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Resharper not only is able to move strings to resource files but also can use existing ones. This basically means that if we use hard-coded string which already has been added to resource file, Resharper will suggest to use predefined resource&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/08/resharper-localizable-string-literals/useproperty.png&quot;&gt;&lt;img src=&quot;images/useproperty.png&quot; alt=&quot;localizable string&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>NHhibernate - multiple queries in one roundtrip to server</title><link>https://tpodolak.com/blog/nhhibernate-multiple-queries-in-one-roundtrip-to-server/</link><guid isPermaLink="true">https://tpodolak.com/blog/nhhibernate-multiple-queries-in-one-roundtrip-to-server/</guid><pubDate>Sun, 27 Apr 2014 22:14:00 GMT</pubDate><content:encoded>&lt;p&gt;Usually when we need to retrieve data from database server, we write code which looks like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using (var session = DataAccesLayer.Instance.OpenSession())
{
    using (var transaction = session.BeginTransaction())
    {
        var projects = session.QueryOver&amp;lt;Project&amp;gt;().Where(val =&amp;gt; val.Name == &quot;Project&quot;).List();
        var tasks = session.QueryOver&amp;lt;Task&amp;gt;().Where(val =&amp;gt; val.Name == &quot;First task&quot;).List();
        //more queries           
        //more queries             
        //exception handling etc.
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This code will execute two queries,each of them in separate roundtrip to the server.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/04/nhhibernate-multiple-queries-in-one-roundtrip-to-server/SeveralRoundtrips.png&quot;&gt;&lt;img src=&quot;images/SeveralRoundtrips.png&quot; alt=&quot;SeveralRoundtrips&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;This is the most popular way of getting data for multiple tables etc. However it is possible to enhance the code above and execute several queries in only one roundtrip to the database server.
NHibernate provides us with three different mechanisms to accomplish this goal:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;MultiQuery&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;First way to execute several queries at once is &lt;code&gt;MultiQuery&lt;/code&gt;. In my opinion this is not very handy mechanism because of the fact, that we must use &lt;code&gt;HQL&lt;/code&gt;.
Here is an example of usage&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var projectQuery = session.CreateQuery(&quot;FROM Project as prj where prj.Name= :projectName&quot;)
                          .SetParameter(&quot;projectName&quot;, &quot;Project&quot;);

var taskQuery = session.CreateQuery( &quot;FROM Task as tsk where tsk.Name=:taskName&quot; )
                       .SetParameter(&quot;taskName&quot;,&quot;First task&quot;);
 
var multiQueryByIndex = session.CreateMultiQuery( )
                               .Add&amp;lt;Project&amp;gt;( projectQuery )
                               .Add&amp;lt;Task&amp;gt;( taskQuery );
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As You can see thanks to &lt;code&gt;CreateMultiQuery&lt;/code&gt; method we are able to aggregate multiple queries.
In order to get access to results, we have to execute code below&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var result = multiQueryByIndex.List();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we can get result of specific query using indexer&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var projects = result[0] as List&amp;lt;Project&amp;gt;;
var tasks = result[1] as List&amp;lt;Task&amp;gt;;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If we don&apos;t like this approach, the &lt;code&gt;CreateMultiQuery&lt;/code&gt; method has an overload which allows to give &quot;names&quot; to queries.
Thanks to this we can get result of query by its name.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var multiQueryByKey = session.CreateMultiQuery( )
                             .Add&amp;lt;Project&amp;gt;( &quot;project&quot;, projectQuery )
                             .Add&amp;lt;Task&amp;gt;( &quot;task&quot;, taskQuery );
 
var projects = multiQueryByKey.GetResult( &quot;project&quot; ) as List&amp;lt;Project&amp;gt;;
var tasks = multiQueryByKey.GetResult( &quot;task&quot; ) as List&amp;lt;Task&amp;gt;;
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;MultiCriteria&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Much better way of creating multiple queries is MultiCriteria. In this case we can use &lt;code&gt;QueryOver&lt;/code&gt; API, so we don&apos;t have to rely on &lt;code&gt;HQL&lt;/code&gt; query strings.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var projectQuery = session.QueryOver&amp;lt;Project&amp;gt;().Where(val =&amp;gt; val.Name == &quot;Project&quot;);
var taskQuery = session.QueryOver&amp;lt;Task&amp;gt;( ).Where(val =&amp;gt; val.Name == &quot;First task&quot;);
var multiCriteriaByIndex = session.CreateMultiCriteria( )
                                  .Add( projectQuery )
                                  .Add( taskQuery );

var multiCriteriaByKey = session.CreateMultiCriteria( )
                                .Add( &quot;project&quot;, projectQuery )
                                .Add( &quot;task&quot;, taskQuery );

IList result = multiCriteriaByIndex.List( );
var projects = result[0] as List&amp;lt;Project&amp;gt;;
var tasks = result[1] as List&amp;lt;Task&amp;gt;;

projects = multiCriteriaByKey.GetResult( &quot;project&quot; ) as List&amp;lt;Project&amp;gt;;
tasks = multiCriteriaByKey.GetResult( &quot;task&quot; ) as List&amp;lt;Task&amp;gt;;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As You can see the usage of &lt;code&gt;CreateMultiCriteria&lt;/code&gt; method is pretty consistent with &lt;code&gt;CreateMultiQuery&lt;/code&gt;.
Unfortunately we still have to retrieve data from specific query by index or by query name.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Future&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;My personal favorite for creating multi queries is &lt;code&gt;Future&lt;/code&gt;. The usage is pretty straightforward&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var projects = session.QueryOver&amp;lt;Project&amp;gt;().Where(val =&amp;gt; val.Name == &quot;Project&quot;).Future&amp;lt;Project&amp;gt;();
var tasks = session.QueryOver&amp;lt;Task&amp;gt;().Where(val =&amp;gt; val.Name == &quot;First task&quot;).Future&amp;lt;Task&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As You can see, we can leverage &lt;code&gt;QueryOver&lt;/code&gt; API and instead of calling &lt;code&gt;List&lt;/code&gt; we call &lt;code&gt;Future&lt;/code&gt;.
&lt;code&gt;NHibernate&lt;/code&gt; will aggregate our queries and will execute them once we start to iterate over one of them.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/04/nhhibernate-multiple-queries-in-one-roundtrip-to-server/delayedenumerator.png&quot;&gt;&lt;img src=&quot;images/delayedenumerator.png&quot; alt=&quot;delayedenumerator&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Despite the fact that all three mechanism has completely different syntax ,SQL created by all of them is the same and looks like that&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/04/nhhibernate-multiple-queries-in-one-roundtrip-to-server/intheend.png&quot;&gt;&lt;img src=&quot;images/intheend.png&quot; alt=&quot;multiple queries&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Resharper - &quot;Go to Everything&quot;</title><link>https://tpodolak.com/blog/resharper-go-to-everything/</link><guid isPermaLink="true">https://tpodolak.com/blog/resharper-go-to-everything/</guid><pubDate>Thu, 17 Apr 2014 19:50:00 GMT</pubDate><content:encoded>&lt;p&gt;In &lt;code&gt;Resharper 8&lt;/code&gt; &lt;code&gt;JetBrains&lt;/code&gt; introduced new command called &lt;code&gt;Go to Everything&lt;/code&gt;. You can use it by hitting the &lt;code&gt;CTRL + N&lt;/code&gt; keys (&lt;code&gt;CTRL + T&lt;/code&gt; with &lt;code&gt;Visual Studio&lt;/code&gt; keyboard shortcuts layout) This command is basically combination of three features known from previous versions of Resharper, namely: &lt;code&gt;Go to Class&lt;/code&gt;, &lt;code&gt;Go to Type&lt;/code&gt; and &lt;code&gt;Go to Symbol&lt;/code&gt;.
Most common usage of this functionality is just to search classes, properties or functions.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/04/resharper-go-to-everything/GoToType.png&quot;&gt;&lt;img src=&quot;images/GoToType.png&quot; alt=&quot;Go to Everything&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;However not everyone knows, that we can narrow down search criteria and find methods or properties in given class&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/04/resharper-go-to-everything/GoToFunctionInType.png&quot;&gt;&lt;img src=&quot;images/GoToFunctionInType.png&quot; alt=&quot;Go to Everything&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;What is even more interesting, is the fact that it is possible to go to specific line in searched type&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/04/resharper-go-to-everything/GoToLine.png&quot;&gt;&lt;img src=&quot;images/GoToLine.png&quot; alt=&quot;Go to Everything&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Resharper - annotation attributes</title><link>https://tpodolak.com/blog/resharper-annotation-attributes/</link><guid isPermaLink="true">https://tpodolak.com/blog/resharper-annotation-attributes/</guid><pubDate>Sun, 02 Mar 2014 16:39:00 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;I think one of the most important features of Resharper is on-the-fly code quality analysis.
Basically, every time Resharper finds possible pitfall in code, it indicates this with appropriate warning.
The most common warning is &lt;code&gt;&quot;Possible System.NullReferenceException&quot;&lt;/code&gt;.
You can easily reproduce it by writing this code&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;List&amp;lt;object&amp;gt; objlList = new List&amp;lt;object&amp;gt;( );
var result = objlList.SingleOrDefault( );
Console.WriteLine( result.GetHashCode( ) );
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a&gt;&lt;img src=&quot;images/singledefaultwarning.png&quot; alt=&quot;Warning&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;As you can see &lt;code&gt;R#&lt;/code&gt; is able to figure out, that &lt;code&gt;LINQ&lt;/code&gt; &lt;code&gt;SingleOrDefault&lt;/code&gt; function can return null.
However there is no warning if we try to do something like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;private static void DisplayHashCode()
{
    var result = Foo();
    Console.WriteLine( result.GetHashCode( ) );
}

private static object Foo()
{
    return null;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So it got me thinking, how &lt;code&gt;Resharper&lt;/code&gt; recognizes whether or whether not to show warnings.
It turned out, that it uses annotation attributes, which describe behavior of functions, properties, classes and interfaces.&lt;/p&gt;
&lt;h3&gt;2. Source code annotations&lt;/h3&gt;
&lt;p&gt;In order to use these attributes we have to place them in our project.
First of all, let&apos;s create &lt;code&gt;Annotation.cs&lt;/code&gt; file and then copy default implementation of annotations into this file.
The default implementation can be found in Code annotation option (&lt;code&gt;Resharper-&amp;gt;Options-&amp;gt;Code Inspections-&amp;gt;Code Annotations&lt;/code&gt;) under the button &lt;code&gt;Copy default implementation to clipboard&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a&gt;&lt;img src=&quot;images/resharperOptions.png&quot; alt=&quot;ResharperOptions&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a&gt;&lt;img src=&quot;images/annotationoptions.png&quot; alt=&quot;AnnotationOptions&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;From now on we can decorate our functions with e.g. &lt;code&gt;CanBeNull&lt;/code&gt; attribute&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;private static void DisplayHashCode()
{
    var result = Foo();
    Console.WriteLine( result.GetHashCode( ) );
}
       
[CanBeNull]
private static object Foo()
{
    return null;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and we will get warning if necessary&lt;/p&gt;
&lt;p&gt;&lt;a&gt;&lt;img src=&quot;images/after.png&quot; alt=&quot;After&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Of course there are a lot more of attributes to use. My favorites are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;StringFormatMethodAttribute&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;a&gt;&lt;img src=&quot;images/format.png&quot; alt=&quot;Format&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;PathReferenceAttribute&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;a&gt;&lt;img src=&quot;images/path.png&quot; alt=&quot;Path&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;NotifyPropertyChangedInvocatorAttribute&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;a&gt;&lt;img src=&quot;images/notify.png&quot; alt=&quot;Notify&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;3. External code annotations&lt;/h3&gt;
&lt;p&gt;In case we do not have access to source code, we still are able to use annotation attributes.
However we have to define annotations in &lt;code&gt;xml&lt;/code&gt; configuration file.
Let&apos;s say we want to decorate &lt;code&gt;NHibernte&apos;s&lt;/code&gt; &lt;code&gt;SaveOrUpdate&lt;/code&gt; function with NotNullAttribute.
First of all we have to create xml file with appropriate declaration (This is standard XML Document Comment file.
You can read specification &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/aa288481(v=vs.71).aspx&quot;&gt;here&lt;/a&gt; and &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/fsbx0t7x.aspx&quot;&gt;here&lt;/a&gt;)&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;assembly name=&quot;NHibernate&quot;&amp;gt;
    &amp;lt;member name=&quot;M:NHibernate.ISession.SaveOrUpdate(System.Object)&quot;&amp;gt;
        &amp;lt;parameter name=&quot;obj&quot;&amp;gt;
            &amp;lt;attribute ctor=&quot;M:JetBrains.Annotations.NotNullAttribute.#ctor&quot; /&amp;gt;
        &amp;lt;/parameter&amp;gt;
    &amp;lt;/member&amp;gt;
&amp;lt;/assembly&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Having prepared configuration file, we need to place it in appropriate location in order for Resharper to use it. It can be stored in&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[ReSharper install directory]\Bin\ExternalAnnotations\[Assembly name].xml
[ReSharper install directory]\Bin\ExternalAnnotations\[Assembly name][Any name].xml.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So in my case the location is
&lt;code&gt;C:\Program Files (x86)\JetBrains\ReSharper\v8.1\Bin\ExternalAnnotations\NHibernateNHibernate.xml&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;After restarting &lt;code&gt;Visual Studio&lt;/code&gt;, &lt;code&gt;Resharper&lt;/code&gt; should load the file and show warning messages.&lt;/p&gt;
&lt;p&gt;&lt;a&gt;&lt;img src=&quot;images/nhibernate.png&quot; alt=&quot;NHibernate&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;4. Generating initial XML annotation files&lt;/h3&gt;
&lt;p&gt;Creating &lt;code&gt;xml&lt;/code&gt; annotation file for large library is very tedious task, fortunately &lt;code&gt;Resharper&lt;/code&gt; have a hidden feature which can help us with generating initial xml file.
First of all we have to run &lt;code&gt;Visual Studio&lt;/code&gt; with &lt;code&gt;/ReSharper.Internal&lt;/code&gt; parameter. In this mode we have an access to undocumented/hidden features of &lt;code&gt;Resharper&lt;/code&gt;.
Now, in the &lt;code&gt;Resharper&lt;/code&gt; menu there is one additional menu item - &lt;code&gt;Internal&lt;/code&gt;, where You can find &lt;code&gt;Annotator&lt;/code&gt; submenu in which resides &lt;code&gt;Annotate&lt;/code&gt; item.&lt;/p&gt;
&lt;p&gt;&lt;a&gt;&lt;img src=&quot;images/annotator.png&quot; alt=&quot;Annotator&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Now You can specify for which dll &lt;code&gt;Resharper&lt;/code&gt; should generate xml annotation file.&lt;/p&gt;
&lt;p&gt;&lt;a&gt;&lt;img src=&quot;images/annotatorwindow.png&quot; alt=&quot;AnnotatorWindow&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;and after a while You should get complete &lt;code&gt;xml&lt;/code&gt; declaration.&lt;/p&gt;
&lt;p&gt;&lt;a&gt;&lt;img src=&quot;images/annotatorprogress.png&quot; alt=&quot;AnnotatorProgress&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;[!WARNING]
Please bear in mind, that Annotator is not official &lt;code&gt;R#&lt;/code&gt; feature, so there is no guarantee that generating annotation files will succeed.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/ResharperAnnotations&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Implementing INotifyPropertyChanged without lambda expressions and &quot;magic&quot; strings</title><link>https://tpodolak.com/blog/implementing-inotifypropertychanged-without-lambda-expressions-and-magic-strings/</link><guid isPermaLink="true">https://tpodolak.com/blog/implementing-inotifypropertychanged-without-lambda-expressions-and-magic-strings/</guid><pubDate>Sun, 19 Jan 2014 20:31:00 GMT</pubDate><content:encoded>&lt;p&gt;I think almost every &lt;code&gt;.NET&lt;/code&gt; developer is familiar with &lt;code&gt;INotifyPropertyChanged&lt;/code&gt; interface.
Typical implementation of this interface looks more or less like that:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class NotifyPropertyBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged( Expression&amp;lt;Func&amp;lt;object&amp;gt;&amp;gt; propertyExpression )
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler( this, new PropertyChangedEventArgs( GetPropertyName( propertyExpression ) ) );
    }

    private string GetPropertyName( Expression&amp;lt;Func&amp;lt;object&amp;gt;&amp;gt; propertyExpression )
    {
        var unaryExpression = propertyExpression.Body as UnaryExpression;
        var memberExpression = unaryExpression == null ? (MemberExpression)propertyExpression.Body : (MemberExpression)unaryExpression.Operand;
        var propertyName = memberExpression.Member.Name;
        return propertyName;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Thanks to lambda expressions we can get rid of so called &quot;magic&quot; strings when rising &lt;code&gt;PorpertyChange&lt;/code&gt; event.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;private int _myProperty;
public int MyProperty
{
    get { return _myProperty; }
    set
    {
        if (_myProperty == value) return;
        _myProperty = value;
        OnPropertyChanged( ( ) =&amp;gt; MyProperty );
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;However, with &lt;code&gt;.NET 4.5&lt;/code&gt; we can even get rid of lambda expressions itself.
Everything thanks to &lt;a href=&quot;http://msdn.microsoft.com/pl-pl/library/system.runtime.compilerservices.callermembernameattribute(v=vs.110).aspx&quot;&gt;CallerMemberNameAttribute&lt;/a&gt;, which provides us information about caller of given method.
Now we can rewrite &lt;code&gt;NotifyPropertyBase&lt;/code&gt; class as follows&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class NotifyPropertyBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged( [CallerMemberName] string propertyName = null )
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler( this, new PropertyChangedEventArgs( propertyName));
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From this moment we can call &lt;code&gt;OnPropertyChanged&lt;/code&gt; method without any arguments&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;private int _myProperty;
public int MyProperty
{
    get { return _myProperty; }
    set 
    {
      if (_myProperty == value) return;
      _myProperty = value;
      OnPropertyChanged();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and thanks to &lt;code&gt;CallerMemberName&lt;/code&gt; attribute, argument &lt;code&gt;propertyName&lt;/code&gt; will be filled with appropriate value.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2014/01/implementing-inotifypropertychanged-without-lambda-expressions-and-magic-strings/callermembername.png&quot;&gt;&lt;img src=&quot;images/callermembername.png&quot; alt=&quot;callermembername&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/NotifyPropertyChangedCallerMemberName&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>How to check if one function calls another function</title><link>https://tpodolak.com/blog/how-to-check-if-one-function-calls-another-function/</link><guid isPermaLink="true">https://tpodolak.com/blog/how-to-check-if-one-function-calls-another-function/</guid><pubDate>Sun, 01 Dec 2013 18:12:00 GMT</pubDate><content:encoded>&lt;p&gt;An application which I&apos;m currently developing has quite complicated authorization system.
That is why, we can not use role based authorization, and basically every developer is obliged to call appropriate security check method in every controller action he or she writes.
As You probably know it is quite easy to forget about that, therefore I decided to write a test which would check whether all controller&apos;s action invokes this security critical function.
After hours of searching for some anchor point, I came across this &lt;a href=&quot;https://devblogs.microsoft.com/haibo_luo/system-reflection-based-ilreader.aspx&quot;&gt;article&lt;/a&gt; in which author creates so called &quot;reflection based ILReader&quot;.
&lt;code&gt;ILReader&lt;/code&gt; is a class which allows You to iterate over IL instructions of every object of type &lt;code&gt;RuntimeMethodInfo&lt;/code&gt; or &lt;code&gt;RuntimeConstructorInfo&lt;/code&gt;.
One of these instructions is &lt;code&gt;InlineMethodInstruction&lt;/code&gt; which indicates method call.
That is why, in order to get all methods which are called by given method, we have to simply select all instructions of type &lt;code&gt;InlineMethodInstruction&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static class MethodInvokerCrawler
{
    public static IEnumerable&amp;lt;MethodBase&amp;gt; GetMethods(MethodBase caller)
    {
        ILReader reader = new ILReader(caller);
        return reader.OfType&amp;lt;InlineMethodInstruction&amp;gt;().Select(method =&amp;gt; method.Method);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can go a bit further and create a recursive version of this function to iterate over entire function execution chain&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static class MethodInvokerCrawler
{
    public const string DefaultPrefix = &quot;GeneralLearning&quot;;
    public static IEnumerable&amp;lt;MethodBase&amp;gt; GetMethods(MethodBase caller, bool recursive = false, string namespacePrefix = DefaultPrefix)
    {
        ILReader reader = new ILReader(caller);
        foreach (InlineMethodInstruction method in
            reader.OfType&amp;lt;InlineMethodInstruction&amp;gt;())
        {
            yield return method.Method;
            if (recursive &amp;amp;&amp;amp; method.Method.DeclaringType != null &amp;amp;&amp;amp; method.Method.DeclaringType.FullName.StartsWith(namespacePrefix, StringComparison.InvariantCultureIgnoreCase))
            {
                foreach (var innerMethod in GetMethods(method.Method))
                {
                    yield return innerMethod;
                }
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Please notice, that I limited recursion depth to methods from user defined namespace, otherwise we would end up iterating over &lt;code&gt;.NET&apos;s&lt;/code&gt; native functions.&lt;/p&gt;
&lt;p&gt;Now it is time to show some results. Here is a sample program which demonstrate possibilities of &lt;code&gt;MethodInvokerCrawler&lt;/code&gt; class&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;internal class Program
{
    public class FooClass
    {
        public FooClass()
        {
            this.X();
            this.Foo();
            this.Bar();
        }

        public void Foo(){}

        public void Bar()
        {
            this.Z();
            this.Foo();
        }

        public string X()
        {
            return null;
        }

        public void Y(){ }

        public void Z()
        {
            this.Y();
        }
    }

    public static void Main(string[] args)
    {
        Console.WriteLine(&quot;=== execution chain of Bar function no recursion ===&quot;);
        foreach (var s in MethodInvokerCrawler.GetMethods(typeof(FooClass).GetMethod(&quot;Bar&quot;)))
        {
            Console.WriteLine(&quot;{0}.{1}&quot;, s.DeclaringType.FullName, s.Name);
        }

        Console.WriteLine();
        Console.WriteLine(&quot;=== execution chain of Bar function with recursion ===&quot;);
        foreach (var s in MethodInvokerCrawler.GetMethods(typeof(FooClass).GetMethod(&quot;Bar&quot;), true))
        {
            Console.WriteLine(&quot;{0}.{1}&quot;, s.DeclaringType.FullName, s.Name);
        }

        Console.WriteLine();
        Console.WriteLine(&quot;execution chain of FooClass default constructor no recursion&quot;);
        foreach (var s in MethodInvokerCrawler.GetMethods(typeof(FooClass).GetConstructors().Single()))
        {
            Console.WriteLine(&quot;{0}.{1}&quot;, s.DeclaringType.FullName, s.Name);
        }

        Console.WriteLine();
        Console.WriteLine(&quot;execution chain of FooClass default constructor with recursion&quot;);
        foreach (var s in MethodInvokerCrawler.GetMethods(typeof(FooClass).GetConstructors().Single(), true))
        {
            Console.WriteLine(&quot;{0}.{1}&quot;, s.DeclaringType.FullName, s.Name);
        }
        Console.ReadKey();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/12/how-to-check-if-one-function-calls-another-function/result.png&quot;&gt;&lt;img src=&quot;images/result.png&quot; alt=&quot;calls another function&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;At this point checking whether function or constructor calls another function is limited to simple &lt;code&gt;LINQ&lt;/code&gt; query&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;MethodInvokerCrawler.GetMethods(typeof(FooClass).GetMethod(&quot;Bar&quot;)).Any(val =&amp;gt; val.Name == &quot;Foo&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/MethodCrawler&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Extjs - vertical header in grid and locked columns</title><link>https://tpodolak.com/blog/extjs-vertical-header-in-grid-and-locked-columns/</link><guid isPermaLink="true">https://tpodolak.com/blog/extjs-vertical-header-in-grid-and-locked-columns/</guid><pubDate>Sun, 10 Nov 2013 21:09:00 GMT</pubDate><content:encoded>&lt;p&gt;A while ago I wrote an article where I described how to create a plugin, which can flip header of &lt;code&gt;Ext.panel.Grid&lt;/code&gt; vertically.
I&apos;ve been using this plugin for a couple of months in a company I work for, however in the last week it turned out that this extension does not work for grid with &lt;a href=&quot;http://dev.sencha.com/deploy/ext-4.0.0/examples/grid/locking-grid.html&quot;&gt;locked columns&lt;/a&gt;.
After digging into &lt;code&gt;Extjs&lt;/code&gt; source code I found out that when You use locked columns, the grid is created as a combination of two grids: &lt;code&gt;normalGrid&lt;/code&gt; and &lt;code&gt;lockedGrid&lt;/code&gt;.
Therefore it is necessary to apply vertical-header plugin to these two grids separately. In order to do that, I improved this extension to detect if grid has locked columns or not.
The main change is in &lt;code&gt;init&lt;/code&gt; function which now looks that way&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;init: function (grid) {
      var me = this;
      me.grid = grid;
      me.grid.addCls(&apos;v-vertical-header-grid&apos;);
      me.textMetric = new Ext.util.TextMetrics();

      if (me.isLocked()){
          var normalGridPlugin = Ext.create(&apos;GeneralLearning.ux.VerticalHeader&apos;,me.extraCfg),
              lockedGridPlugin = Ext.create(&apos;GeneralLearning.ux.VerticalHeader&apos;,me.extraCfg);
              normalGridPlugin.init(me.grid.normalGrid);
              lockedGridPlugin.init(me.grid.lockedGrid);
              me.grid.normalGrid.plugins.push(normalGridPlugin);
              me.grid.lockedGrid.plugins.push(lockedGridPlugin);
      } else {
          me.grid.on({
              afterlayout: {
                  scope: me,
                  fn: me.handleAfterLayout
              }
          });
      }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the first step I check if columns are locked. The method for do that is pretty straightforward&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;isLocked: function () {
          var me = this;
          return me.grid.normalGrid &amp;amp;&amp;amp; me.grid.lockedGrid;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Afterward I do create two instances of vertical-header plugin and initialize them with appropriate partial grid (&lt;code&gt;lockedGrid&lt;/code&gt; or &lt;code&gt;normalGrid&lt;/code&gt;).
Entire code listing is presented below&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Ext.define(&apos;GeneralLearning.ux.VerticalHeader&apos;, {
    alias: &apos;plugin.verticalheader&apos;,
    grid: null,
    extraCfg:null,
    textMetric: null,
    init: function (grid) {
        var me = this;
        me.grid = grid;
        me.grid.addCls(&apos;v-vertical-header-grid&apos;);
        me.textMetric = new Ext.util.TextMetrics();

        if (me.isLocked()) {
            var normalGridPlugin = Ext.create(&apos;GeneralLearning.ux.VerticalHeader&apos;,me.extraCfg),
                lockedGridPlugin = Ext.create(&apos;GeneralLearning.ux.VerticalHeader&apos;,me.extraCfg);
                normalGridPlugin.init(me.grid.normalGrid);
                lockedGridPlugin.init(me.grid.lockedGrid);
                me.grid.normalGrid.plugins.push(normalGridPlugin);
                me.grid.lockedGrid.plugins.push(lockedGridPlugin);

        } else {
            me.grid.on({
                afterlayout: {
                    scope: me,
                    fn: me.handleAfterLayout
                }
            });
        }
    },

    constructor: function (cfg) {
        var me = this;
        me.extraCfg = cfg;
        Ext.apply(this, cfg);
        me.callParent(arguments);
    },

    handleAfterLayout: function (cmp) {
        var me = this,
            maxWidth = 0,
            headerItems = cmp.headerCt.items,
            curremtWidth;

        headerItems.each(function (item) {
            if ((curremtWidth = me.textMetric.getWidth(item.text)) &amp;gt; maxWidth) {
                maxWidth = curremtWidth + 10;
            }
        });

        cmp.headerCt.el.select(&apos;.x-column-header-text&apos;).each(function (el) {
            el.setSize(maxWidth, maxWidth);
        });
    },

    isLocked: function () {
        var me = this;
        return me.grid.normalGrid &amp;amp;&amp;amp; me.grid.lockedGrid;
    }

});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/11/extjs-vertical-header-in-grid-and-locked-columns/lockedColumns.png&quot;&gt;&lt;img src=&quot;images/lockedColumns.png&quot; alt=&quot;vertical header&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/ExtjsVerticalGridHeaderLockedColumns&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Generating string consisting of the same character</title><link>https://tpodolak.com/blog/generating-string-consisting-of-the-same-character/</link><guid isPermaLink="true">https://tpodolak.com/blog/generating-string-consisting-of-the-same-character/</guid><pubDate>Sun, 03 Nov 2013 14:45:00 GMT</pubDate><content:encoded>&lt;p&gt;Recently I&apos;ve been asked by friend of mine, how to generate string consisting of 50 commas.
I came up with these three code snippets:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var repeat = string.Join(string.Empty, Enumerable.Repeat(&quot;,&quot;, 50));
var aggregate = Enumerable.Range(1, 50).Aggregate(new StringBuilder(), 
                                                 (acc, seed) =&amp;gt; acc.Append(&quot;,&quot;)).ToString();
var usingArray = string.Join(&quot;,&quot;, new string[51]);//must be 51, separator is not inserted after last index
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Although all of these lines produce appropriate outcome, it&apos;s seemed to me that there is some simpler way to accomplish this task.
After a little bit of searching, it turned out, that it is possible to generate string consisting of same characters using one of string&apos;s constructors&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var usingConstructor = new string(&apos;,&apos;, 50);
&lt;/code&gt;&lt;/pre&gt;
</content:encoded></item><item><title>NHibarnate - using event listeners to set entity modification date</title><link>https://tpodolak.com/blog/nhibarnate-using-event-listeners-to-set-entity-modification-date/</link><guid isPermaLink="true">https://tpodolak.com/blog/nhibarnate-using-event-listeners-to-set-entity-modification-date/</guid><pubDate>Sat, 24 Aug 2013 23:04:00 GMT</pubDate><content:encoded>&lt;p&gt;I think, that it is a common practice to store information about creation and modification date of entities.
However keeping appropriate columns up to date manually is error prone. We must remember that every time we modify entity, we also have to change its modification date.
Fortunately thanks to event listeners, &lt;code&gt;NHibernate&lt;/code&gt; can do all of this boring stuff for us.
Let&apos;s start from creating class which implements two interfaces:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;IPreInsertEventListener&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;IPreUpdateEventListener&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;public class NHListener : IPreInsertEventListener, IPreUpdateEventListener
{
    public bool OnPreInsert(PreInsertEvent @event)
    {
        throw new NotImplementedException();
    }

    public bool OnPreUpdate(PreUpdateEvent @event)
    {
        throw new NotImplementedException();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As You probably guessed &lt;code&gt;OnPreInsert&lt;/code&gt; method is invoked before insert, and &lt;code&gt;OnPreUpdate&lt;/code&gt; is called before update of entity.
Having prepared the basic skeleton of class, it is time to configure &lt;code&gt;NHibernate&lt;/code&gt; to use our event listeners.
The basic configuration is taken from my previous post about &lt;code&gt;NHibernate&lt;/code&gt; &lt;a href=&quot;http://tpodolak.com/blog/2013/03/25/fluent-nhibernate-automappings&quot;&gt;automappings&lt;/a&gt;, so I will only extend it by appending event listeners&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Fluently.Configure().Database(
                    MsSqlConfiguration.MsSql2008.ConnectionString(
                        @&quot;YourConnectionString&quot;))
                    .Mappings(val =&amp;gt; val.AutoMappings.Add(CreateAutomappings))
                    .ExposeConfiguration(val =&amp;gt;
                    {
                        val.AppendListeners(ListenerType.PreUpdate, new IPreUpdateEventListener[] { new NHListener() });
                        val.AppendListeners(ListenerType.PreInsert, new IPreInsertEventListener[] { new NHListener() });
                    })
                    .BuildSessionFactory();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now we can put some logic into &lt;code&gt;OnPreInsert&lt;/code&gt; and &lt;code&gt;OnPreUpdate&lt;/code&gt; functions.
First of all we have to somehow identify entities which hold information about creation and modification time.
In order to do that I created simple interface &lt;code&gt;IDateInfo&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public interface IDateInfo
{
    DateTime ModificationDate { get; set; }
    DateTime CreationDate { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the next step we have to modify &lt;code&gt;OnPreInsert&lt;/code&gt; and &lt;code&gt;OnPreUpdate&lt;/code&gt; methods, so that they can set creation and modification date of entities which implement &lt;code&gt;IDateInfo&lt;/code&gt; interface.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class NHListener : IPreInsertEventListener, IPreUpdateEventListener
{
    public bool OnPreInsert(PreInsertEvent @event)
    {
        IDateInfo dateInfo;
        if ((dateInfo = @event.Entity as IDateInfo) != null)
        {
            var currentDate = DateTime.Now;
            dateInfo.CreationDate = dateInfo.ModificationDate = currentDate;
        }
        return false;
    }

    public bool OnPreUpdate(PreUpdateEvent @event)
    {
        IDateInfo dateInfo;
        if ((dateInfo = @event.Entity as IDateInfo) != null)
        {
            var currentDate = DateTime.Now;
            dateInfo.ModificationDate = currentDate;
        }
        return false;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Unfortunately at this moment saving entity (which implements &lt;code&gt;IDateInfo&lt;/code&gt; interface) will throw exception&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/08/nhibarnate-using-event-listeners-to-set-entity-modification-date/Exception.png&quot;&gt;&lt;img src=&quot;images/Exception.png&quot; alt=&quot;Exception&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Despite the fact that we set values of &lt;code&gt;ModificationDate&lt;/code&gt; and &lt;code&gt;CreationDate&lt;/code&gt; properties , &lt;code&gt;NHiberante&lt;/code&gt; seems not to notice that.
That is why we have to manually update values of &lt;code&gt;State&lt;/code&gt; object from &lt;code&gt;PreInsertEvent&lt;/code&gt; and &lt;code&gt;PreUpdateEvent&lt;/code&gt;.
According to the documentation &lt;code&gt;State&lt;/code&gt; object from class &lt;code&gt;PreInsertEvent&lt;/code&gt; holds values which should be inserted and &lt;code&gt;State&lt;/code&gt; object from class &lt;code&gt;PreUpdateEvent&lt;/code&gt; holds values which should be updated.
Function which update values of state object might look like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;private void SetState(IEntityPersister persister, object[] state, string propertyName, object value)
{
    var index = Array.IndexOf(persister.PropertyNames, propertyName);
    if (index == -1)
        return;
    state[index] = value;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Updated &lt;code&gt;NHListener&lt;/code&gt; class now looks like that&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using System;
using System.Linq.Expressions;
using NHibernate.Event;
using NHibernate.Impl;
using NHibernate.Persister.Entity;

namespace DataAccessLayer
{
    public class NHListener : IPreInsertEventListener, IPreUpdateEventListener
    {
        private static readonly string ModificationDatePropertyName = GetPropertyName&amp;lt;IDateInfo&amp;gt;(val =&amp;gt; val.ModificationDate),
                                       CreationDatePropertyName = GetPropertyName&amp;lt;IDateInfo&amp;gt;(val =&amp;gt; val.CreationDate);

        public bool OnPreInsert(PreInsertEvent @event)
        {
            IDateInfo dateInfo;
            if ((dateInfo = @event.Entity as IDateInfo) != null)
            {
                var currentDate = DateTime.Now;
                dateInfo.CreationDate = dateInfo.ModificationDate = currentDate;
                SetState(@event.Persister, @event.State, ModificationDatePropertyName, currentDate);
                SetState(@event.Persister, @event.State, CreationDatePropertyName , currentDate);
            }
    
            return false;
        }
    
        public bool OnPreUpdate(PreUpdateEvent @event)
        {
            IDateInfo dateInfo;
            if ((dateInfo = @event.Entity as IDateInfo) != null)
            {
                var currentDate = DateTime.Now;
                dateInfo.ModificationDate = currentDate;
                SetState(@event.Persister, @event.State, ModificationDatePropertyName, currentDate);
            }
            return false;
        }
        
        private void SetState(IEntityPersister persister, object[] state, string propertyName, object value)
        {
            var index = Array.IndexOf(persister.PropertyNames, propertyName);
            if (index == -1)
                return;
            state[index] = value;
        }
    
        private static string GetPropertyName&amp;lt;TType&amp;gt;(Expression&amp;lt;Func&amp;lt;TType, object&amp;gt;&amp;gt; expression)
        {
            return ExpressionProcessor.FindPropertyExpression(expression.Body);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As You can see, after setting values of &lt;code&gt;IDateInfo&lt;/code&gt; I also call function &lt;code&gt;SetState&lt;/code&gt; and update state of appropriate properties.
From now everything works fine and our entities can be saved without problems.&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/NHibernateEventListener&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Extjs - vertical header in grid</title><link>https://tpodolak.com/blog/extjs-vertical-header-in-grid/</link><guid isPermaLink="true">https://tpodolak.com/blog/extjs-vertical-header-in-grid/</guid><pubDate>Sun, 30 Jun 2013 10:55:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;code&gt;Extjs&lt;/code&gt; doesn&apos;t provide us with any build-in mechanism for flipping text vertically in grid&apos;s header.
Fortunately we can achieve this effect by using a mixture of &lt;code&gt;CSS&lt;/code&gt; rules and some javascript code.
In order to make code more reusable, I&apos;ll write it as a plugin for grid.
Let&apos;s start from creating &lt;code&gt;CSS&lt;/code&gt; rules responsible for text rotation&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;.v-vertical-header-grid .x-column-header  .x-column-header-text {
   display:block;
   margin-left:auto;
   margin-right:auto;
   text-align: left;
   -webkit-transform: rotate(-90deg);     
   -moz-transform: rotate(-90deg);     
   -o-transform: rotate(-90deg);    
   -ms-transform: rotate(-90deg); /* IE  */                             
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;.x-column-header .x-column-header-text&lt;/code&gt; is a selector for header text in every &lt;code&gt;Extjs&lt;/code&gt; grid.
It is obvious that we want only certain grids to have vertical headers, that is why I extended selector with additional custom class &lt;code&gt;.v-vertical-header-grid&lt;/code&gt;.
Having &lt;code&gt;CSS&lt;/code&gt; class prepared, now we can write actual plugin.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Ext.define(&apos;GeneralLearning.ux.VerticalHeader&apos;, {
    alias: &apos;plugin.verticalheader&apos;,
    grid: null,
    textMetric: null,
    init: function (grid) {
        var me = this;
        me.grid = grid;
        me.grid.addCls(&apos;v-vertical-header-grid&apos;);
        me.textMetric = new Ext.util.TextMetrics();
        me.grid.on({
            afterlayout: {
                scope: me,
                fn: me.handleAfterLayout
            }
        });
    },

    constructor: function (cfg) {
        Ext.apply(this, cfg);
    },

    handleAfterLayout: function (cmp) {
        var me = this,
            maxWidth = 0,
            headerItems = cmp.headerCt.items,
            curremtWidth;

        headerItems.each(function (item) {
            if ((curremtWidth = me.textMetric.getWidth(item.text)) &amp;gt; maxWidth) {
                maxWidth = curremtWidth + 10;
            }
        });

        cmp.headerCt.el.select(&apos;.x-column-header-text&apos;).each(function (el) {
            el.setSize(maxWidth, maxWidth);
        });
    }
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;At the very beginning &lt;code&gt;.v-vertical-header-grid&lt;/code&gt; class is added to the grid.
Thanks to this, &lt;code&gt;CSS&lt;/code&gt; selector created in the first step is able to select text in header.
At this point text is rotated, however it can&apos;t fit into header - its size didn&apos;t change.
That is why in function &lt;code&gt;handleAfterLayout&lt;/code&gt; I manually measure text height using &lt;code&gt;Ext.util.TextMetrics&lt;/code&gt; and change height of header.
Solution presented above works fine in &lt;code&gt;IE10&lt;/code&gt;, &lt;code&gt;Opera&lt;/code&gt;, &lt;code&gt;Firefox&lt;/code&gt; and &lt;code&gt;Chrome&lt;/code&gt;.
There were some problems in &lt;code&gt;IE9&lt;/code&gt;, however extending &lt;code&gt;CSS&lt;/code&gt; class with these rules&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;.v-vertical-header-grid .x-column-header {
    background-image: -ms-linear-gradient(rgb(249, 249, 249), rgb(227, 228, 230)) !important;
    filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr=&apos;#F9F9F9&apos;, endColorstr=&apos;#E3E4E6&apos;);

}
  
.v-vertical-header-grid .x-grid-header-ct {
    background-image: -ms-linear-gradient(rgb(249, 249, 249), rgb(227, 228, 230)) !important;
    filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr=&apos;#F9F9F9&apos;, endColorstr=&apos;#E3E4E6&apos;);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;did the trick. Here is the result&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/06/extjs-vertical-header-in-grid/result.png&quot;&gt;&lt;img src=&quot;images/result.png&quot; alt=&quot;vertical header&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/ExtjsVerticalGridHeader&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;[!WARNING]
There is a problem with this plugin and locked columns, please see the updated version of this plugin &lt;a href=&quot;http://tpodolak.com/blog/2013/11/10/extjs-vertical-header-in-grid-and-locked-columns&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
</content:encoded></item><item><title>Extjs - drag-and-drop between tables</title><link>https://tpodolak.com/blog/extjs-drag-and-drop-between-tables/</link><guid isPermaLink="true">https://tpodolak.com/blog/extjs-drag-and-drop-between-tables/</guid><pubDate>Wed, 22 May 2013 22:08:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;code&gt;Extjs&lt;/code&gt; framework provides us with two helper classes responsible for performing &lt;code&gt;drag-drop&lt;/code&gt; operation:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;Ext.dd.DragZone&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;The most important element of this class is &lt;code&gt;getDragData&lt;/code&gt; function, which provides data for drag operation.
It is necessary for this method to return object with &lt;code&gt;ddel&lt;/code&gt; property containing DOM element, from which draging operation was originated.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;Ext.dd.DropZone&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;This class has two important methods. The first one is &lt;code&gt;getTargetFromEvent&lt;/code&gt; which informs if drop operation should be performed.
The other one is &lt;code&gt;onNodeDrop&lt;/code&gt; which is responsible for actual drop operation.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Having covered the basics, let&apos;s try to implement drag-drop operation. Let&apos;s start from creating simple container with two tables.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Ext.define(&apos;GeneralLearning.views.DragAndDropView&apos;, {
    extend:&apos;Ext.container.Container&apos;,
    renderTpl:Ext.create(&apos;Ext.Template&apos;,
     &apos;&amp;lt;div id=&quot;table_container&quot;&amp;gt;&apos;,
        &apos;&amp;lt;table id=&quot;leftTable&quot; style=&quot;margin: 20px 20px&quot;&amp;gt;&apos;,
             &apos;&amp;lt;tr&amp;gt;&apos;,
                &apos;&amp;lt;th&amp;gt;a&amp;lt;/th&amp;gt;&apos;,
                &apos;&amp;lt;th&amp;gt;b&amp;lt;/th&amp;gt;&apos;,
             &apos;&amp;lt;/tr&amp;gt;&apos;,
            &apos;&amp;lt;tr&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;1&amp;lt;/td&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;2&amp;lt;/td&amp;gt;&apos;,
            &apos;&amp;lt;/tr&amp;gt;&apos;,
            &apos;&amp;lt;tr&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;4&amp;lt;/td&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;9&amp;lt;/td&amp;gt;&apos;,
            &apos;&amp;lt;/tr&amp;gt;&apos;,
            &apos;&amp;lt;tr&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;16&amp;lt;/td&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;25&amp;lt;/td&amp;gt;&apos;,
            &apos;&amp;lt;/tr&amp;gt;&apos;,
        &apos;&amp;lt;/table&amp;gt;&apos;,
        &apos;&amp;lt;table id=&quot;rightTable&quot; style=&quot;margin: 20px 20px&quot;&amp;gt;&apos;,
             &apos;&amp;lt;tr&amp;gt;&apos;,
                &apos;&amp;lt;th&amp;gt;a&amp;lt;/th&amp;gt;&apos;,
                &apos;&amp;lt;th&amp;gt;b&amp;lt;/th&amp;gt;&apos;,
             &apos;&amp;lt;/tr&amp;gt;&apos;,
             &apos;&amp;lt;tr&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;1&amp;lt;/td&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;2&amp;lt;/td&amp;gt;&apos;,
            &apos;&amp;lt;/tr&amp;gt;&apos;,
            &apos;&amp;lt;tr&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;4&amp;lt;/td&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;9&amp;lt;/td&amp;gt;&apos;,
            &apos;&amp;lt;/tr&amp;gt;&apos;,
            &apos;&amp;lt;tr&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;16&amp;lt;/td&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;25&amp;lt;/td&amp;gt;&apos;,
            &apos;&amp;lt;/tr&amp;gt;&apos;,
        &apos;&amp;lt;/table&amp;gt;&apos;,
    &apos;&amp;lt;/div&amp;gt;&apos;)
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the next step we will create &lt;code&gt;DragZone&lt;/code&gt; and &lt;code&gt;DropZone&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;createDragDropZones:function () {
    var me = this,
        rightTable = me.el.select(&apos;#rightTable&apos;).first(),
        leftTable = me.el.select(&apos;#leftTable&apos;).first();
    Ext.create(&apos;Ext.dd.DragZone&apos;, rightTable, {
        getDragData:function (e) {
            if (e.target.nodeName == &apos;TD&apos;) {
                var sourceEl = e.target;
                var d = sourceEl.cloneNode(true);
                d.id = Ext.id();
                return {
                    ddel:d,
                    sourceEl:sourceEl,
                    repairXY:Ext.fly(sourceEl).getXY()
                }
            }

        },
        getRepairXY:function () {
            return this.dragData.repairXY;
        }
    });

    Ext.create(&apos;Ext.dd.DropZone&apos;, leftTable, {
        getTargetFromEvent:function (e) {
            if (e.target.nodeName == &apos;TD&apos;)
                return e.target;
        },
        onNodeEnter:function (target, dd, e, data) {
            Ext.fly(target).addCls(&apos;drop-target-hover&apos;);
        },
        onNodeOut:function (target, dd, e, data) {
            Ext.fly(target).removeCls(&apos;drop-target-hover&apos;);
        },
        onNodeOver:function (target, dd, e, data) {
            return Ext.dd.DropZone.prototype.dropAllowed;
        },
        onNodeDrop:function (target, dd, e, data) {
            target.parentNode.replaceChild(dd.dragData.ddel, target)
            return true;
        }
    })
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As You cas see &lt;code&gt;DragZone&lt;/code&gt; was created on the right table.
I want to be able to drag only &lt;code&gt;td&lt;/code&gt; elements, that is why function &lt;code&gt;getDragData&lt;/code&gt; returns null, if drag operation was originated from other HTML element.
Extjs will take care of showing approperiate animation, if drag-drop is available.
I also overrode &lt;code&gt;getRepairXY&lt;/code&gt; method, which is responsible for providing &lt;code&gt;X&lt;/code&gt; and &lt;code&gt;Y&lt;/code&gt; coordinates for animation, which is fired in case of invalid drop off.
The code responsible for handling drop operation is a little bit more complicated.
After creating a &lt;code&gt;DropZone&lt;/code&gt; from left table, I ovverode &lt;code&gt;getTargetFromEvent&lt;/code&gt; method, so as to drop could be performed only to &lt;code&gt;td&lt;/code&gt; elements of table.
What is more, using &lt;code&gt;onNodeEnter&lt;/code&gt; and &lt;code&gt;onNodeOut&lt;/code&gt; methods I changed target elements of the drop, to show user where given element will be placed.
Actual drop is performed in &lt;code&gt;onNodeDrop&lt;/code&gt; method, in my case I just replace HTML node form original one to dropped.
Here is a result:&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/05/extjs-drag-and-drop-between-tables/dragdrop.gif&quot;&gt;&lt;img src=&quot;images/dragdrop.gif&quot; alt=&quot;drag-and-drop&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Entire code listing looks like that:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; #table_container table { border: 1px solid black;float:left;width:400px;}
 #table_container td, #table_container th   { border: 1px solid black;}
 
 td.drop-target-hover {
     border-color: yellow !important;
     border-width: 3px !important;
 }
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;Ext.define(&apos;GeneralLearning.views.DragAndDropView&apos;, {
    extend:&apos;Ext.container.Container&apos;,
    renderTpl:Ext.create(&apos;Ext.Template&apos;,
     &apos;&amp;lt;div id=&quot;table_container&quot;&amp;gt;&apos;,
        &apos;&amp;lt;table id=&quot;leftTable&quot; style=&quot;margin: 20px 20px&quot;&amp;gt;&apos;,
             &apos;&amp;lt;tr&amp;gt;&apos;,
                &apos;&amp;lt;th&amp;gt;a&amp;lt;/th&amp;gt;&apos;,
                &apos;&amp;lt;th&amp;gt;b&amp;lt;/th&amp;gt;&apos;,
             &apos;&amp;lt;/tr&amp;gt;&apos;,
            &apos;&amp;lt;tr&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;1&amp;lt;/td&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;2&amp;lt;/td&amp;gt;&apos;,
            &apos;&amp;lt;/tr&amp;gt;&apos;,
            &apos;&amp;lt;tr&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;4&amp;lt;/td&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;9&amp;lt;/td&amp;gt;&apos;,
            &apos;&amp;lt;/tr&amp;gt;&apos;,
            &apos;&amp;lt;tr&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;16&amp;lt;/td&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;25&amp;lt;/td&amp;gt;&apos;,
            &apos;&amp;lt;/tr&amp;gt;&apos;,
        &apos;&amp;lt;/table&amp;gt;&apos;,
        &apos;&amp;lt;table id=&quot;rightTable&quot; style=&quot;margin: 20px 20px&quot;&amp;gt;&apos;,
             &apos;&amp;lt;tr&amp;gt;&apos;,
                &apos;&amp;lt;th&amp;gt;a&amp;lt;/th&amp;gt;&apos;,
                &apos;&amp;lt;th&amp;gt;b&amp;lt;/th&amp;gt;&apos;,
             &apos;&amp;lt;/tr&amp;gt;&apos;,
             &apos;&amp;lt;tr&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;1&amp;lt;/td&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;2&amp;lt;/td&amp;gt;&apos;,
            &apos;&amp;lt;/tr&amp;gt;&apos;,
            &apos;&amp;lt;tr&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;4&amp;lt;/td&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;9&amp;lt;/td&amp;gt;&apos;,
            &apos;&amp;lt;/tr&amp;gt;&apos;,
            &apos;&amp;lt;tr&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;16&amp;lt;/td&amp;gt;&apos;,
                &apos;&amp;lt;td&amp;gt;25&amp;lt;/td&amp;gt;&apos;,
            &apos;&amp;lt;/tr&amp;gt;&apos;,
        &apos;&amp;lt;/table&amp;gt;&apos;,
    &apos;&amp;lt;/div&amp;gt;&apos;),

    initComponent:function () {
        var me = this;
        me.callParent(arguments);
        me.on(&apos;afterrender&apos;, me.createDragDropZones, me);
    },

    createDragDropZones:function () {
        var me = this,
            rightTable = me.el.select(&apos;#rightTable&apos;).first(),
            leftTable = me.el.select(&apos;#leftTable&apos;).first();
        Ext.create(&apos;Ext.dd.DragZone&apos;, rightTable, {
            getDragData:function (e) {
                if (e.target.nodeName == &apos;TD&apos;) {
                    var sourceEl = e.target;
                    var d = sourceEl.cloneNode(true);
                    d.id = Ext.id();
                    return {
                        ddel:d,
                        sourceEl:sourceEl,
                        repairXY:Ext.fly(sourceEl).getXY()
                    }
                }
            },
            getRepairXY:function () {
                return this.dragData.repairXY;
            }
        });

        Ext.create(&apos;Ext.dd.DropZone&apos;, leftTable, {
            getTargetFromEvent:function (e) {
                if (e.target.nodeName == &apos;TD&apos;)
                    return e.target;
            },
            onNodeEnter:function (target, dd, e, data) {
                Ext.fly(target).addCls(&apos;drop-target-hover&apos;);
            },
            onNodeOut:function (target, dd, e, data) {
                Ext.fly(target).removeCls(&apos;drop-target-hover&apos;);
            },
            onNodeOver:function (target, dd, e, data) {
                return Ext.dd.DropZone.prototype.dropAllowed;
            },
            onNodeDrop:function (target, dd, e, data) {
                target.parentNode.replaceChild(dd.dragData.ddel, target)
                return true;
            }
        })
    }
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/ExtjsDragDrop&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Fixing missing semicolon issue using WebStorm</title><link>https://tpodolak.com/blog/fixing-missing-semicolon-issue-using-webstorm/</link><guid isPermaLink="true">https://tpodolak.com/blog/fixing-missing-semicolon-issue-using-webstorm/</guid><pubDate>Sun, 14 Apr 2013 11:44:00 GMT</pubDate><content:encoded>&lt;p&gt;Recently in the company I work for, we&apos;ve been trying to improve Javascript code quality.
After hooking up JSlint into our build script, it turned out that the most common issue with our code is missing semicolon at the end of statements.
Fixing all warnings manually would be very boring task, that is why I started searching for alternative solution.
Fortunatelly once again, &lt;code&gt;WebStorm&lt;/code&gt; came for the rescue.
As you probably know &lt;code&gt;WebStorm&lt;/code&gt; has it&apos;s own code inspection tool which indicates problems with code.
However except that, this tool can also fix these problems automatically.
Here is a little demonstration. Let us start with simple code.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Ext.define(&apos;GeneralLearning.controllers.ImageCachingController&apos;,{
    extend:&apos;Ext.app.Controller&apos;,
    viewInstance:null,
    launch:function(){
        var me = this;
        me.viewInstance = Ext.create(&apos;GeneralLearning.views.ImageCachingView&apos;);
    },

    getView:function(){
        var me = this
        return me.viewInstance
    }
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the listing above, there are two lines with missing semicolon (in function &lt;code&gt;getView&lt;/code&gt;).
Let fix them using &lt;code&gt;Webstorm&lt;/code&gt; code inspection tool. First of all, we have to make sure that appropriate inspection options are selected.
In order to do that, let&apos;s choose &lt;code&gt;Settings&lt;/code&gt; from menu &lt;code&gt;File&lt;/code&gt;.
In the opened window, go to &lt;code&gt;Settings&lt;/code&gt; and select options presented in the picture below.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/04/fixing-missing-semicolon-issue-using-webstorm/options.png&quot;&gt;&lt;img src=&quot;images/options.png&quot; alt=&quot;options&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In the next step, from menu &lt;code&gt;Code&lt;/code&gt; choose &lt;code&gt;Inspect code&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/04/fixing-missing-semicolon-issue-using-webstorm/InspectCode.png&quot;&gt;&lt;img src=&quot;images/InspectCode.png&quot; alt=&quot;InspectCode&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In the opened window, we can change inspection profile or inspection scope, but usually we can go with default settings&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/04/fixing-missing-semicolon-issue-using-webstorm/InspectCodeWindow.png&quot;&gt;&lt;img src=&quot;images/InspectCodeWindow.png&quot; alt=&quot;InspectCodeWindow&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;After inspection is done, at the bottom of the screen you will see results&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/04/fixing-missing-semicolon-issue-using-webstorm/InspectionResult.png&quot;&gt;&lt;img src=&quot;images/InspectionResult.png&quot; alt=&quot;InspectionResult&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Now, we can quickly fix them by using context menu and clicking &lt;code&gt;Terminate statement&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/04/fixing-missing-semicolon-issue-using-webstorm/InspectionResultMenu.png&quot;&gt;&lt;img src=&quot;images/InspectionResultMenu.png&quot; alt=&quot;InspectionResultMenu&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Here is the result of fixing operation&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/04/fixing-missing-semicolon-issue-using-webstorm/result.png&quot;&gt;&lt;img src=&quot;images/result.png&quot; alt=&quot;missing semicolon&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Fluent Nhibernate - automappings</title><link>https://tpodolak.com/blog/fluent-nhibernate-automappings/</link><guid isPermaLink="true">https://tpodolak.com/blog/fluent-nhibernate-automappings/</guid><pubDate>Mon, 25 Mar 2013 18:38:00 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;Writing mappings for models in large application is quite boring task.
Fortunatelly, &lt;code&gt;Fluent NHibernate&lt;/code&gt; provides possibility for automatic mapping creation - so called automappings.&lt;/p&gt;
&lt;h3&gt;2. Creating database and model&lt;/h3&gt;
&lt;p&gt;In order to show you, how to configure automappings in &lt;code&gt;Fluent NHibernate&lt;/code&gt;, let&apos;s create simple database along with model classes.
The database structure is presented in the picture below.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/03/fluent-nhibernate-automappings/DBDiagram.png&quot;&gt;&lt;img src=&quot;images/DBDiagram.png&quot; alt=&quot;DBDiagram&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Model classes which represent database tables look this way&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public abstract class ModelBase
{
    public virtual int Id { get; set; }
}

public class Project : ModelBase
{
    public virtual string Name { get; set; }
    public virtual User User { get; set; }
    public virtual IList&amp;lt;Task&amp;gt; Tasks { get; set; }
}

public class Task : ModelBase
{
    public virtual string Name { get; set; }
    public virtual Project Project { get; set; }
}

public class User : ModelBase
{
    public virtual string Name { get; set; }
    public virtual string Surname { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;3. Automappings configuration&lt;/h3&gt;
&lt;p&gt;Having our database and models prepared, now we can create and configure &lt;code&gt;SessionFactory&lt;/code&gt; to use automappings.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var factory = Fluently.Configure().Database(MsSqlConfiguration.MsSql2008.ConnectionString(&quot;YourConnectionString&quot;))
                      .Mappings(val =&amp;gt; val.AutoMappings.Add(AutoMap.AssemblyOf&amp;lt;Project&amp;gt;))
                      .BuildSessionFactory();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As You can see I used the static &lt;code&gt;AutoMap.AssemblyOf&lt;/code&gt; method.
This method takes a generic type parameter from which &lt;code&gt;Fluent NHibernate&lt;/code&gt; can deduce which assembly to look in for mappable entities.
From now all classes defined in the assemlby of &lt;code&gt;Project&lt;/code&gt; are mapped using build-in convention.&lt;/p&gt;
&lt;h3&gt;4. Mapping only specified classes&lt;/h3&gt;
&lt;p&gt;Mapping all classes from specyfic assembly may not be very useful.
That is why, we need to &quot;tell&quot; &lt;code&gt;Automapper&lt;/code&gt; which classes should be mapped.
It can be achieved by creating custom configuration class which implements &lt;code&gt;IAutomappingConfiguration&lt;/code&gt; interface or which is subclass of &lt;code&gt;DefaultAutomappingConfiguration&lt;/code&gt;.
&lt;code&gt;IAutomappingConfiguration&lt;/code&gt; interface has quite a lot of functions, that is why I decided to craete class which inherits from &lt;code&gt;DefaultAutomappingConfiguration&lt;/code&gt; and override only one method - &lt;code&gt;ShouldMap&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class AutomappingConfiguration : DefaultAutomappingConfiguration
{
    public override bool ShouldMap(Type type)
    {
        return type.IsSubclassOf(typeof (ModelBase));
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As You can see by overriding &lt;code&gt;ShouldMap&lt;/code&gt; function,I specified that only classes which inherit from &lt;code&gt;ModelBase&lt;/code&gt; class should be mapped.
To use our new configuration, we need to pass an instance of it to &lt;code&gt;AutoMap&lt;/code&gt; setup&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var factory = Fluently.Configure().Database(MsSqlConfiguration.MsSql2008.ConnectionString(&quot;YourConnectionString&quot;))
                      .Mappings(val =&amp;gt; val.AutoMappings.Add(AutoMap.AssemblyOf&amp;lt;Project&amp;gt;(new  DefaultAutomappingConfiguration())))
                      .BuildSessionFactory();
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;5. Defining custom conventions&lt;/h3&gt;
&lt;p&gt;It is rather obvious that default automapping conventions may not come along with our database naming conventions.
Fortunately we can create custom conventions(which override default ones), and pass them to AutoMap configuration.
Here are examples of conventions I use &lt;code&gt;IClassConvention&lt;/code&gt; - gives us access to properties and functions which allow us to change a default table name format for our entities.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class DefaultTableNameConvention : IClassConvention
{
    public void Apply(IClassInstance instance)
    {
        instance.Table(string.Format(&quot;{0}{1}&quot;, &quot;GL_&quot;, instance.EntityType.Name));
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;IIdConvention&lt;/code&gt; is used for altering default identity conventions.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class DefaultPrimaryKeyConvention : IIdConvention
{
    public void Apply(IIdentityInstance instance)
    {
        instance.Column(&quot;Id&quot;);
        instance.GeneratedBy.Native();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;IPropertyConvention&lt;/code&gt; - allows us to modify properties mappings (lazy load, nullability,length etc)&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class DefaultStringLengthConvention : IPropertyConvention
{
    public void Apply(IPropertyInstance instance)
    {
        instance.Length(50);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;IReferenceConvention&lt;/code&gt; - allows us to modify entities relationship convention&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class DefaultReferenceConvention : IReferenceConvention
{
    public void Apply(IManyToOneInstance instance)
    {
        instance.Column(string.Format(instance.Class.Name.StartsWith(&quot;Id&quot;) ? &quot;{1}&quot; : &quot;{0}{1}&quot;, &quot;Id&quot;,
                                      instance.Class.Name));
        instance.LazyLoad();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;IHasManyConvention&lt;/code&gt; - allow us to modify default has-many relationship convention&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class DefaultHasManyConvention : IHasManyConvention
{
    public void Apply(IOneToManyCollectionInstance instance)
    {
        instance.Key.Column(string.Format(&quot;{0}{1}&quot;, &quot;Id&quot;, instance.EntityType.Name));
        instance.LazyLoad();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In order to use new conventions we need to pass them into &lt;code&gt;AutoMap&lt;/code&gt; configuration.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Fluently.Configure()
                .Database(
                    MsSqlConfiguration.MsSql2008.ConnectionString(&quot;YourConnectionString&quot;))
                .Mappings(val =&amp;gt; val.AutoMappings.Add(AutoMap.AssemblyOf&amp;lt;Project&amp;gt;(new DefaultAutomappingConfiguration()).Conventions.Setup(con =&amp;gt;
                                                                           {
                                                                               con.Add&amp;lt;DefaultTableNameConvention&amp;gt;();
                                                                               con.Add&amp;lt;DefaultPrimaryKeyConvention&amp;gt;();
                                                                               con.Add&amp;lt;DefaultStringLengthConvention&amp;gt;();
                                                                               con.Add&amp;lt;DefaultReferenceConvention&amp;gt;();
                                                                               con.Add&amp;lt;DefaultHasManyConvention&amp;gt;();
                                                                           })))
                .BuildSessionFactory();
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;6. Overriding mappings&lt;/h3&gt;
&lt;p&gt;Sometimes it is necessary to slightly modify entity mapping.
It can be achieved by creating class which implements &lt;code&gt;IAutoMappingOverride&lt;/code&gt; interface&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class ProjectMapping: IAutoMappingOverride&amp;lt;Project&amp;gt;
{
    public void Override(AutoMapping&amp;lt;Project&amp;gt; mapping)
    {
        mapping.IgnoreProperty(val=&amp;gt;val.SomeIgnoredProperty);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;Override&lt;/code&gt; method gives us access to all actions known from fluent mappings.
After creating class map, we have to call function &lt;code&gt;UseOverridesFromAssemblyOf&lt;/code&gt; in our automapping configuration&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var factory = Fluently.Configure()
                      .Database(MsSqlConfiguration.MsSql2008.ConnectionString(&quot;YourConnectionString&quot;))
                      .Mappings(val =&amp;gt; val.AutoMappings.Add(AutoMap.AssemblyOf&amp;lt;Project&amp;gt;(new DefaultAutomappingConfiguration()).UseOverridesFromAssemblyOf&amp;lt;Project&amp;gt;()
                                  .Conventions.Setup(con =&amp;gt; 
                                  {
                                       con.Add&amp;lt;DefaultTableNameConvention&amp;gt;();
                                       con.Add&amp;lt;DefaultPrimaryKeyConvention&amp;gt;();
                                       con.Add&amp;lt;DefaultStringLengthConvention&amp;gt;();
                                       con.Add&amp;lt;DefaultReferenceConvention&amp;gt;();
                                       con.Add&amp;lt;DefaultHasManyConvention&amp;gt;();
                                  }))).BuildSessionFactory();
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;7. It works&lt;/h3&gt;
&lt;p&gt;Here just couple of screens from &lt;code&gt;NHibernateProfiler&lt;/code&gt; with basic queries&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/03/fluent-nhibernate-automappings/InsertIntoTask.png&quot;&gt;&lt;img src=&quot;images/InsertIntoTask.png&quot; alt=&quot;InsertIntoTask&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/03/fluent-nhibernate-automappings/InsertIntoUser.png&quot;&gt;&lt;img src=&quot;images/InsertIntoUser.png&quot; alt=&quot;InsertIntoUser&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/03/fluent-nhibernate-automappings/InsertIntoProject.png&quot;&gt;&lt;img src=&quot;images/InsertIntoProject.png&quot; alt=&quot;InsertIntoProject&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/03/fluent-nhibernate-automappings/SelectFromTask.png&quot;&gt;&lt;img src=&quot;images/SelectFromTask.png&quot; alt=&quot;SelectFromTask&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/NHibernateAutomappings&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Extjs - Changing style of items in dropdownlist</title><link>https://tpodolak.com/blog/extjs-changing-style-of-items-in-dropdownlist/</link><guid isPermaLink="true">https://tpodolak.com/blog/extjs-changing-style-of-items-in-dropdownlist/</guid><pubDate>Tue, 19 Mar 2013 18:58:00 GMT</pubDate><content:encoded>&lt;p&gt;I&apos;ve recently been asked to create &lt;code&gt;ComboBox&lt;/code&gt; with custom styled &lt;code&gt;drop-down&lt;/code&gt; list.
Colors of items of drop-dow list should be picked based on values of record bounded to given item.
After reading some post on Extjs forum, I decided to overwrite default template of &lt;code&gt;drop-down&lt;/code&gt; list.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Ext.create(&apos;Ext.XTemplate&apos;,
                     &apos;&amp;lt;tpl for=&quot;.&quot;&amp;gt;&apos;,
                       &apos;&amp;lt;div class=&quot;{[this.getClass(values)]}&quot;&amp;gt;{abbr} - {name}&amp;lt;/div&amp;gt;&apos;,
                     &apos;&amp;lt;/tpl&amp;gt;&apos;,{
                            getClass: function (rec) {
                                return rec.name == &apos;Arizona&apos; ? &apos;x-boundlist-item x-highlighted-item&apos; : &apos;x-boundlist-item&apos;;
                        }
                    }
    )
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As You can see I decided to use &lt;code&gt;XTemplate&lt;/code&gt;, which (to the contrary to &lt;code&gt;Template&lt;/code&gt;) allows to call user defined function.
Function &lt;code&gt;getClass&lt;/code&gt; from &lt;code&gt;XTemplate&lt;/code&gt; will be called for each element in ComboBox&apos;s store.
The result of this function will be inserted into class attribute of &lt;code&gt;div&lt;/code&gt; element, which is resposible for displaying single item in drop-down list.
Please notice, that in order to maintain ability to select items from &lt;code&gt;drop-down&lt;/code&gt; list, it is necessary to specify &lt;code&gt;x-boundlist-item&lt;/code&gt; class in template.
Here is example of usage&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;div.x-highlighted-item {
    background: blue !important; 
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;
var states = Ext.create(&apos;Ext.data.Store&apos;, {
            fields: [&apos;id&apos;, &apos;abbr&apos;, &apos;name&apos;],
            data: [
                { id: 1, abbr: &quot;AL&quot;, name: &quot;Alabama&quot; },
                { id: 2, abbr: &quot;AK&quot;, name: &quot;Alaska&quot; },
                { id: 3, abbr: &quot;AZ&quot;, name: &quot;Arizona&quot; },
                { id: 4, abbr: &quot;AZ&quot;, name: &quot;Arizona&quot; },
                { id: 5, abbr: &quot;AZ&quot;, name: &quot;Arizona&quot; }
            ]
        });

  Ext.create(&apos;Ext.form.ComboBox&apos;, {
       fieldLabel: &apos;Choose State&apos;,
       store: states,
       queryMode: &apos;local&apos;,
       valueField: &apos;abbr&apos;,
       displayField: &apos;name&apos;,
       renderTo: Ext.getBody(),
       tpl: Ext.create(&apos;Ext.XTemplate&apos;,
                &apos;&amp;lt;tpl for=&quot;.&quot;&amp;gt;&apos;,
                  &apos;&amp;lt;div class=&quot;{[this.getClass(values)]}&quot;&amp;gt;{abbr} - {name}&amp;lt;/div&amp;gt;&apos;,
                 &apos;&amp;lt;/tpl&amp;gt;&apos;,
                    {
                        getClass: function (rec) {
                            return rec.name == &apos;Arizona&apos; ? &apos;x-boundlist-item x-highlighted-item&apos; : &apos;x-boundlist-item&apos;;
                        }
                    }
    )
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and the result&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/03/extjs-changing-style-of-items-in-dropdownlist/Result.png&quot;&gt;&lt;img src=&quot;images/Result.png&quot; alt=&quot;dropdownlist&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/ExtjsChangeStyleInDropDown&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>StringBuilder - removing trailing characters</title><link>https://tpodolak.com/blog/stringbuilder-removing-trailing-characters/</link><guid isPermaLink="true">https://tpodolak.com/blog/stringbuilder-removing-trailing-characters/</guid><pubDate>Sun, 17 Mar 2013 00:03:00 GMT</pubDate><content:encoded>&lt;p&gt;Today just quick tip about &lt;code&gt;StringBuilder&lt;/code&gt; I used to remove last character(s) from &lt;code&gt;StringBuilder&lt;/code&gt; using &lt;code&gt;Remove&lt;/code&gt; method.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; StringBuilder builder = new StringBuilder(&quot;some long text with comma,&quot;);
 builder.Remove(builder.Length - 1, 1);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;However, recently I&apos;ve came accross even simpler solution.
You just need to lessen the &lt;code&gt;Length&lt;/code&gt; property of StringBuilder, in order to get rid of last characters&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;StringBuilder builder = new StringBuilder(&quot;some long text with comma,&quot;);
builder.Length--;
&lt;/code&gt;&lt;/pre&gt;
</content:encoded></item><item><title>Resharper - custom snippet</title><link>https://tpodolak.com/blog/resharper-custom-snippet/</link><guid isPermaLink="true">https://tpodolak.com/blog/resharper-custom-snippet/</guid><pubDate>Sat, 05 Jan 2013 10:28:00 GMT</pubDate><content:encoded>&lt;p&gt;I think all &lt;code&gt;Resharper&lt;/code&gt; users are familiar with snippets. &lt;code&gt;Resharper&apos;s&lt;/code&gt; snippet basically generates a piece of code, which can be easily customised on the fly.
All you have to do is to press &lt;code&gt;TAB&lt;/code&gt;, and you can change names of auto-generated variables etc.
Today, I decided to write my own snippet, which would make writing unit tests easier.
In general, all my unit test methods looks like this&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Test]
public void MethodName_Scenario_ExpectedResult_Test()
{
    // test logic goes in here            
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So let&apos;s write a snippet which will generate a method with this signature.
In order to do this, let&apos;s choose a &lt;code&gt;Templates Explorer...&lt;/code&gt; from the &lt;code&gt;Resharper’s&lt;/code&gt; menu.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/01/resharper-custom-snippet/TemplateExplorerFirstWindow.png&quot;&gt;&lt;img src=&quot;images/TemplateExplorerFirstWindow.png&quot; alt=&quot;TemplateExplorerFirstWindow&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In the opened window, click on the plus sign and a new tab should appear.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/01/resharper-custom-snippet/TemplateExplorerFullView.png&quot;&gt;&lt;img src=&quot;images/TemplateExplorerFullView.png&quot; alt=&quot;TemplateExplorerFullView&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Let&apos;s name our snippet &lt;code&gt;test&lt;/code&gt; and paste the following code into the main editor.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Test]
public void MethodName_Scenario_ExpectedResult_Test()
{
           
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, we&apos;ve created a simplified snippet for generating our test function signature.
However, this snippet is not really useful as its user cannot navigate through the underscored chunks.
In order to employ the &lt;code&gt;Resharper’s&lt;/code&gt; navigation features, we have to slightly modify our snippet.
Let&apos;s replace the previous code with this one:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Test]
public void $MethodName$_$Scenario$_$ExpectedResult$_Test()
{
    $END$
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Please notice that now some parts of the method’s name are written between dollar signs.
Thanks to this syntax, the &lt;code&gt;Resharper&lt;/code&gt; is able to iterate over these parts and lets us change their names on the fly.
&lt;code&gt;$END$&lt;/code&gt; is a special control sequence which tells the &lt;code&gt;Resharper&lt;/code&gt; where to stop iteration over variables.
At this moment, our snippet is fully functional and we can use it by typing the word test and hitting the &lt;code&gt;TAB&lt;/code&gt; button.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/01/resharper-custom-snippet/CustomSnippetIntellisense.png&quot;&gt;&lt;img src=&quot;images/CustomSnippetIntellisense.png&quot; alt=&quot;custom snippet&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2013/01/resharper-custom-snippet/SnippetFirstChunk.png&quot;&gt;&lt;img src=&quot;images/SnippetFirstChunk.png&quot; alt=&quot;SnippetFirstChunk&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>ASP.NET MVC - Custom ActionResult - PDFResult</title><link>https://tpodolak.com/blog/asp-net-mvc-custom-actionresult-pdfresult/</link><guid isPermaLink="true">https://tpodolak.com/blog/asp-net-mvc-custom-actionresult-pdfresult/</guid><pubDate>Wed, 26 Dec 2012 15:01:00 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;In the company I&apos;m currently working for, it is a common practice to use &lt;code&gt;Devexpress&lt;/code&gt; &lt;code&gt;XtraReports&lt;/code&gt; to create all kind of reports.
Usually these reports are embedded into html page and used along with &lt;code&gt;DevexpressReportViewer&lt;/code&gt;.
However, lately I have been asked to open a report as a &lt;code&gt;PDF&lt;/code&gt; file, without putting a viewer into a html page.&lt;/p&gt;
&lt;h3&gt;2. First approach&lt;/h3&gt;
&lt;p&gt;After some digging, I created an action in controller which looks like this&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public void ExportToPdf()
{
    using (MemoryStream stream = new MemoryStream())
    {
        var testReport = new TestReport();
        testReport.CreateDocument();
        testReport.ExportToPdf(stream);
        Response.Clear();
        Response.ContentType = &quot;application/pdf&quot;
        Response.BinaryWrite(stream.ToArray());
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the first step I made a new instance of a devexpress report(&lt;code&gt;TestReport&lt;/code&gt;), then I called a method &lt;code&gt;CreateDocument&lt;/code&gt; which is responsible for creating a content of report.
Having prepared the report, I could use the &lt;code&gt;ExportToPdf&lt;/code&gt; function which creates a stream in a &lt;code&gt;PDF&lt;/code&gt; format.
In the last step, I cleared Response property and added an array of bytes into it.
I also had to change &lt;code&gt;Response.ContentType&lt;/code&gt; to &lt;code&gt;application/pdf&lt;/code&gt; in order to inform a browser that I&apos;m sending a &lt;code&gt;PDF&lt;/code&gt; file.&lt;/p&gt;
&lt;h3&gt;3. Second approach - custom ActionResult&lt;/h3&gt;
&lt;p&gt;The solution presented above works fine, however, I wanted to create something more reusable, that is why I decided to create a custom &lt;code&gt;ActionResult&lt;/code&gt; -  &lt;code&gt;PDFActionResult&lt;/code&gt;.
In order to create my own &lt;code&gt;ActionResult&lt;/code&gt;, I created a &lt;code&gt;PDFActionResult&lt;/code&gt; class which inherits from an abstract ActionResult class.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class PDFActionResult : ActionResult
{
    private readonly byte[] _byteArray;
    private const string ContentType = &quot;application/pdf&quot;;
    
    public PDFActionResult(byte[] byteArray)
    {
        _byteArray = byteArray;
    }
    
    public PDFActionResult(XtraReport report)
    {
        using(MemoryStream stream = new MemoryStream())
        {
            report.CreateDocument();
            report.ExportToPdf(stream);
            _byteArray = stream.ToArray();
        }
    }
    
    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;
        response.Clear();
        response.ContentType = ContentType;
        response.BinaryWrite(_byteArray);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see, all logic from the &lt;code&gt;ExportToPdf&lt;/code&gt; action was transferred to the &lt;code&gt;PDFActionResult&lt;/code&gt; class.
Now, all you have to do to return &lt;code&gt;PDF&lt;/code&gt; from &lt;code&gt;DevexpressReport&lt;/code&gt; is to return the &lt;code&gt;PDFActionResult&lt;/code&gt; from your controller action.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public PDFActionResult ExportToPdfUsingCustomResult()
{
    var testReport = new TestReport();
    return new PDFActionResult(testReport);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a&gt;&lt;img src=&quot;images/ResultPDF.png&quot; alt=&quot;ResultPDF&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/AspCustomActionResult&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Argument validation with attributes and Ninject interceptor</title><link>https://tpodolak.com/blog/argument-validation-with-attributes-and-ninject-interceptor/</link><guid isPermaLink="true">https://tpodolak.com/blog/argument-validation-with-attributes-and-ninject-interceptor/</guid><pubDate>Sun, 21 Oct 2012 15:13:00 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;It is a common practice to validate function arguments before running actual code.
Usually validation looks like that:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public  void Update(Car entity)
{
    if(entity ==null)
        throw new ArgumentNullException(&quot;entity&quot;);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There is nothing wrong with this code, however we have to repeat this piece of code in every function.
Of course we could create some helper class for argument validation and call approperiate validation function before launching rest of the code&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static class ValidationHelper
{
    public static void CheckNotNull(object entity, string argumentName)
    {
        if (entity == null)
            throw new ArgumentNullException(argumentName);
    }
}

public  void Update(Car entity)
{
    ValidationHelper.CheckNotNull(entity, &quot;entity&quot;);
    //rest of the code
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;However I was searching for more universal way for argument validation.
That is why, I decided to try function interceptors and attributes.&lt;/p&gt;
&lt;h3&gt;2. Creating validation attributes&lt;/h3&gt;
&lt;p&gt;Let&apos;s start for creating base attribute&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[AttributeUsage(AttributeTargets.Parameter)]
public abstract class ArgumentValidationAttribute : Attribute
{
    public abstract void ValidateArgument(object value, string argumentName);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the next step let&apos;s create specialized attribute for &quot;not null&quot; validation. This argument may look this way:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class NotNullAttribute : ArgumentValidationAttribute
{
    public override void ValidateArgument(object value,string argumentName)
    {
        if (value == null)
            throw new ArgumentNullException(argumentName, string.Format(&quot;Value {0} can not be null&quot;, argumentName));
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;3. Using IInterceptor interface&lt;/h3&gt;
&lt;p&gt;That was an easy part, now it&apos;s necessary to somehow intercept function execution and run attribute validation.
In &lt;code&gt;.NET&lt;/code&gt; there is no build-in mechanism to do that,that is why I&apos;ll use extension for &lt;code&gt;Ninject&lt;/code&gt; - &lt;code&gt;Ninject Interception&lt;/code&gt;.
First of all we have to add to our project three dll&apos;s&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Ninject&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Ninject.Extensions.Interception&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Ninject.Extensions.Interception.LinFu&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You can easily add them using &lt;code&gt;NuGet&lt;/code&gt;. Having all necessary files added to solution,let&apos;s create function interceptor - &lt;code&gt;ValidaitionInterceptor&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class ValidationInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        var parameters = invocation.Request.Method.GetParameters();
        for (int index = 0; index &amp;lt; parameters.Length; index++)
        {
            foreach (ArgumentValidationAttribute attr in parameters[index].GetCustomAttributes(typeof(ArgumentValidationAttribute), true))
                attr.ValidateArgument(invocation.Request.Arguments[index], parameters[index].Name);
        }
        invocation.Proceed();       
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As You can see &lt;code&gt;ValidationInterceptor&lt;/code&gt; implements interface &lt;code&gt;IInterceptor&lt;/code&gt;which belongs to &lt;code&gt;Ninject.Extensions.Interception&lt;/code&gt;.
This interface has one method &lt;code&gt;Intercept&lt;/code&gt; which is called before function from registered component is called.
In this function I iterate over all function attributes of type ArgumentValidationAttribute and call &lt;code&gt;ValidateArgument&lt;/code&gt; function.
If validation passess function &lt;code&gt;invocation.Proceed()&lt;/code&gt; is called, which continues execution of original function.&lt;/p&gt;
&lt;h3&gt;4. Example of usage&lt;/h3&gt;
&lt;p&gt;In order to take advantage of benefits of function interceptors, we have to resolve objects from &lt;code&gt;Ninject&lt;/code&gt; container.
First of all I&apos;ll create some examplorary classes&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public interface IRepository&amp;lt;T&amp;gt; where T:class
{
    List&amp;lt;T&amp;gt; GetAll();
    void Update([NotNull] T entity);
}

public class Car
{
    public int Id { get; set; }
    public string Model { get; set; }
}

public class CarRepository : IRepository&amp;lt;Car&amp;gt;
{
    public  List&amp;lt;Car&amp;gt; GetAll()
    {
        return null;
    }

    public  void Update(Car entity)
    {
            
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the next step I&apos;ll create simple wrapper for &lt;code&gt;Ninject&lt;/code&gt; container and register &lt;code&gt;CarRepository&lt;/code&gt; in &lt;code&gt;Kernel&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static class IOCContainer
{
    private static readonly IKernel Kernel;
    static IOCContainer()
    {
        Kernel = new StandardKernel();
    }

    public static void Configure()
    {
        Kernel.Bind(typeof(IRepository&amp;lt;Car&amp;gt;)).To(typeof(CarRepository)).Intercept().With&amp;lt;ValidaitionInterceptor&amp;gt;();
    }

    public static T Get&amp;lt;T&amp;gt;()
    {
        return Kernel.Get&amp;lt;T&amp;gt;();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Please, notice that registration of &lt;code&gt;CarRepository&lt;/code&gt; was used with option &lt;code&gt;Intercept().With()&lt;/code&gt;.
Thanks to this configuration, everytime we call method from &lt;code&gt;CarRepository&lt;/code&gt;, &lt;code&gt;Intercept&lt;/code&gt; method from &lt;code&gt;ValidaitionInterceptor&lt;/code&gt; will be called first.
Now, it is time to use our repository,we could do that this way&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class Program
{
    static void Main(string[] args)
    {
        IOCContainer.Configure();
        var carRepository = IOCContainer.Get&amp;lt;IRepository&amp;lt;Car&amp;gt;&amp;gt;();
        carRepository.Update(null);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Argument &lt;code&gt;entity&lt;/code&gt; in method &lt;code&gt;Update&lt;/code&gt; from interface &lt;code&gt;IRepository&lt;/code&gt; was decorated with &lt;code&gt;NotNull&lt;/code&gt;, that is why our validation mechanism should throw exception.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/10/argument-validation-with-attributes-and-ninject-interceptor/CallingValidationInInterceptor.png&quot;&gt;&lt;img src=&quot;images/CallingValidationInInterceptor.png&quot; alt=&quot;CallingValidationInInterceptor&quot; /&gt;&lt;/a&gt;
&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/10/argument-validation-with-attributes-and-ninject-interceptor/Throw.png&quot;&gt;&lt;img src=&quot;images/Throw.png&quot; alt=&quot;Argument validation&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;5. Validation of return value&lt;/h3&gt;
&lt;p&gt;Using &lt;code&gt;IInterceptor&lt;/code&gt; we could go one step further and also validate return value of method.
In order to do that, we have to slightly modify &lt;code&gt;Intercept&lt;/code&gt; method in &lt;code&gt;ValidaitionInterceptor&lt;/code&gt; class.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class ValidaitionInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        var parameters = invocation.Request.Method.GetParameters();
        for (int index = 0; index &amp;lt; parameters.Length; index++)
        {
            foreach (ArgumentValidationAttribute attr in parameters[index].GetCustomAttributes(typeof(ArgumentValidationAttribute), true))
                attr.ValidateArgument(invocation.Request.Arguments[index], parameters[index].Name);
        }

        invocation.Proceed();

        foreach (ArgumentValidationAttribute attr in invocation.Request.Method.ReturnTypeCustomAttributes.GetCustomAttributes(typeof(ArgumentValidationAttribute), true))
        {
            attr.ValidateArgument(invocation.ReturnValue, &quot;return value&quot;);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We also have to change attribute usage of &lt;code&gt;ArgumentValidationAttribute&lt;/code&gt; to&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.ReturnValue)]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, we can decorate function &lt;code&gt;GetAll&lt;/code&gt; with &lt;code&gt;NotNull&lt;/code&gt;attribute&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[return: NotNull]
List&amp;lt;T&amp;gt; GetAll();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Since this moment, everytime function &lt;code&gt;GetAll&lt;/code&gt; returns null, the &lt;code&gt;ArgumentNullException&lt;/code&gt; will be thrown.&lt;/p&gt;
&lt;h3&gt;6. Drawbacks&lt;/h3&gt;
&lt;p&gt;Unfortunately using attributes for argument validation have some drawbacks.
First of all, argument validation is based on function interceptors, and as I mentioned before only function, which are in objects, which are resolved from IoC container can be intercepted.
What is more, interceptors allow us to intercept only functions marked as virtual or inhirited from interface.&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/NInjectInterceptors&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>ASP.NET MVC javascript debugging using WebStorm</title><link>https://tpodolak.com/blog/asp-net-mvc-javascript-debugging-using-webstorm/</link><guid isPermaLink="true">https://tpodolak.com/blog/asp-net-mvc-javascript-debugging-using-webstorm/</guid><pubDate>Mon, 17 Sep 2012 08:26:00 GMT</pubDate><content:encoded>&lt;p&gt;I&apos;ve been working with &lt;code&gt;ASP .NET&lt;/code&gt; combined with &lt;code&gt;Extjs&lt;/code&gt; for about half a year.
All this time for debugging I&apos;ve been using &lt;code&gt;Firebug&lt;/code&gt; in &lt;code&gt;Firefox&lt;/code&gt;, or &lt;code&gt;Developer Tools&lt;/code&gt; in &lt;code&gt;Chrome&lt;/code&gt;.
Although both of these tools are great, I decided to try to use build in &lt;code&gt;WebStorm&lt;/code&gt; debugger.
According to documentation this debugger should work with &lt;code&gt;Firefox&lt;/code&gt; as well as with &lt;code&gt;Chrome&lt;/code&gt;.
However I&apos;ve only managed to run it correctly with &lt;code&gt;Firefox&lt;/code&gt;.
In order to start debugging session, we have to make some preparation.
Let&apos;s choose option &lt;code&gt;Debug...&lt;/code&gt; from &lt;code&gt;Run&lt;/code&gt; menu&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/09/asp-net-mvc-javascript-debugging-using-webstorm/rundebug.png&quot;&gt;&lt;img src=&quot;images/rundebug.png&quot; alt=&quot;rundebug&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In opened small window, we have to choose first option - &lt;code&gt;Edit configurations...&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/09/asp-net-mvc-javascript-debugging-using-webstorm/editconfigurationsmall.png&quot;&gt;&lt;img src=&quot;images/editconfigurationsmall.png&quot; alt=&quot;editconfigurationsmall&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In the next window we can create new debugging profile.
In order to do that, click on &lt;code&gt;+&lt;/code&gt; sign in the left upper corner of window, then choose &lt;code&gt;JavascriptDebug&lt;/code&gt; and &lt;code&gt;Remote&lt;/code&gt; option&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/09/asp-net-mvc-javascript-debugging-using-webstorm/runremotedebug.png&quot;&gt;&lt;img src=&quot;images/runremotedebug.png&quot; alt=&quot;runremotedebug&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;This is the final step of the configuration. The most important fields in configuration window is &lt;code&gt;URL to open&lt;/code&gt; field, in which we specify adress of our site.
In my case it is localhost on port &lt;code&gt;8142&lt;/code&gt;. We also have to specify mapping from remote host direcotry structure to our directory structure.
Sample configuration is presented below&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/09/asp-net-mvc-javascript-debugging-using-webstorm/sampleconfig.png&quot;&gt;&lt;img src=&quot;images/sampleconfig.png&quot; alt=&quot;sampleconfig&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;We also have a possibility to choose browser in which our site will be displayed.
I decided to choose &lt;code&gt;Firefox&lt;/code&gt; because of the fact, that &lt;code&gt;WebStorm&lt;/code&gt; debugger had some problems with &lt;code&gt;Chrome&lt;/code&gt;.
Now we can try to run debugging session by pressing &lt;code&gt;ALT+F9&lt;/code&gt;.
If we choose &lt;code&gt;Firefox&lt;/code&gt;, in the very first time we run debugger, we will see this window&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/09/asp-net-mvc-javascript-debugging-using-webstorm/installExtension.png&quot;&gt;&lt;img src=&quot;images/installExtension.png&quot; alt=&quot;installExtension&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;which informs us that &lt;code&gt;WebStorm&lt;/code&gt; must install extension to &lt;code&gt;Firefox&lt;/code&gt;. Clicking &lt;code&gt;OK&lt;/code&gt; button starts &lt;code&gt;Firefox&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/09/asp-net-mvc-javascript-debugging-using-webstorm/AddOnInstalation.jpg&quot;&gt;&lt;img src=&quot;images/AddOnInstalation.jpg&quot; alt=&quot;AddOnInstalation&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;which warns us that external program is trying to install extension.
Clicking &lt;code&gt;continue&lt;/code&gt; button will finish configuration process, and &lt;code&gt;WebStorm&lt;/code&gt; will successfully attach debugger.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/09/asp-net-mvc-javascript-debugging-using-webstorm/debuggerattached.png&quot;&gt;&lt;img src=&quot;images/debuggerattached.png&quot; alt=&quot;debugging&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Extjs 4.1.1 - how to fix row resize phenomena</title><link>https://tpodolak.com/blog/extjs-4-1-1-how-to-fix-row-resize-phenomena/</link><guid isPermaLink="true">https://tpodolak.com/blog/extjs-4-1-1-how-to-fix-row-resize-phenomena/</guid><pubDate>Sat, 15 Sep 2012 23:17:00 GMT</pubDate><content:encoded>&lt;p&gt;Recently I&apos;ve encountered annoying problem with &lt;code&gt;Extjs&lt;/code&gt; grid.
After hiding columns with long wrapped text, height of rows was dramatically increased.
Here are some screens presenting this particular situation. Grid with all columns shown&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/09/extjs-4-1-1-how-to-fix-row-resize-phenomena/problembeforeshow.jpg&quot;&gt;&lt;img src=&quot;images/problembeforeshow.jpg&quot; alt=&quot;problembeforeshow&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;and grid with one column hidden&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/09/extjs-4-1-1-how-to-fix-row-resize-phenomena/problemaftershow.png&quot;&gt;&lt;img src=&quot;images/problemaftershow.png&quot; alt=&quot;row resize&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The code responsible for rendering this grid is shown below&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;.x-grid-cell-inner { white-space: normal; }
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;Ext.onReady(function () {
        Ext.QuickTips.init();
        var store = Ext.create(&apos;Ext.data.Store&apos;, {
            fields: [&apos;Id&apos;, &apos;firstname&apos;, &apos;lastname&apos;],
            data: {
                items: [{
                    Id: 1,
                    firstname: &apos;some long text some long text some long text some long text some long text some long text some long text some long text some long textareasome long textareasome long textarea&apos;,
                    lastname: &apos;Smith&apos;
                },{
                    Id: 1,
                    firstname: &apos;Mat&apos;
                },{
                    Id: 1,
                    firstname: &apos;Kate&apos;,
                    lastname: &apos;Smith&apos;
                },{
                    Id: 1,
                    firstname: &apos;Richard&apos;,
                    lastname: &apos;Smith&apos;
                }]
            },
            proxy: {
                type: &apos;memory&apos;,
                reader: {
                    type: &apos;json&apos;,
                    root: &apos;items&apos;
                }
            }
        });

       var visible = true;
       var grid = Ext.create(&apos;Ext.grid.Panel&apos;, {
            store: store,
            renderTo: Ext.getBody(),
            columns: [
                      { text: &apos;Id&apos;, dataIndex: &apos;Id&apos; },
                      { text: &apos;First name&apos;, dataIndex: &apos;firstname&apos; },
                      { text: &apos;Last name&apos;, dataIndex: &apos;lastname&apos; }]});

        Ext.create(&apos;Ext.button.Button&apos;, {
            text: &apos;click&apos;,
            renderTo: Ext.getBody(),
            handler: function() {
                visible = !visible;
                grid.columns[1].setVisible(visible);
                grid.validate();
            }
        });
    });
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After some digging, it turned out that &lt;code&gt;Extjs&lt;/code&gt; hides columns by setting their width to &lt;code&gt;0px&lt;/code&gt;.
In order to solve this problem and preverse text wrap in cells, I implemented small workaround.
Let&apos;s start from creating &lt;code&gt;CSS&lt;/code&gt; class which disables word wrapping in grid cells.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;.noWrap .x-grid-cell-inner {white-space: nowrap;}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Next, we have to start listening for two events&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;columnhide&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;columnshow&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In handlers of these events, we have to modify &lt;code&gt;tdCls&lt;/code&gt; property of hidden column - add &lt;code&gt;noWrap&lt;/code&gt; class, if column is hidden and delete this class otherwise.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;grid.headerCt.on({
            columnhide: function (headerCt, column) {
                column.tdCls = &quot;noWrap&quot;;
                this.getView().refresh();
            },
            columnshow: function (headerCt, column) {
                column.tdCls = &quot;&quot;;
                this.getView().refresh();
            },
            scope: grid
        });
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From now hiding and showing columns works fine&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/09/extjs-4-1-1-how-to-fix-row-resize-phenomena/fixedAfterHide.png&quot;&gt;&lt;img src=&quot;images/fixedAfterHide.png&quot; alt=&quot;fixedAfterHide&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Entire code listing is presented below&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;``Ext.onReady(function () {
        Ext.QuickTips.init();
        var store = Ext.create(&apos;Ext.data.Store&apos;, {
            fields: [&apos;Id&apos;, &apos;firstname&apos;, &apos;lastname&apos;],
            data: {
                items: [{
                    Id: 1,
                    firstname: &apos;some long text some long text some long text some long text some long text some long text some long text some long text some long textareasome long textareasome long textarea&apos;,
                    lastname: &apos;Smith&apos;
                },{
                    Id: 1,
                    firstname: &apos;Mat&apos;
                },{
                    Id: 1,
                    firstname: &apos;Kate&apos;,
                    lastname: &apos;Smith&apos;
                },{
                    Id: 1,
                    firstname: &apos;Richard&apos;,
                    lastname: &apos;Smith&apos;
                }]
            },
            proxy: {
                type: &apos;memory&apos;,
                reader: {
                    type: &apos;json&apos;,
                    root: &apos;items&apos;
                }
            }
        });

       var visible = true;
       var grid = Ext.create(&apos;Ext.grid.Panel&apos;, {
            store: store,
            renderTo: Ext.getBody(),
            columns: [
        { text: &apos;Id&apos;, dataIndex: &apos;Id&apos; },
        { text: &apos;First name&apos;, dataIndex: &apos;firstname&apos; },
        { text: &apos;Last name&apos;, dataIndex: &apos;lastname&apos; }]});

        grid.headerCt.on({
            columnhide: function (headerCt, column) {
                column.tdCls = &quot;noWrap&quot;;
                this.getView().refresh();
            },
            columnshow: function (headerCt, column) {
                column.tdCls = &quot;&quot;;
                this.getView().refresh();
            },
            scope: grid
        });

        Ext.create(&apos;Ext.button.Button&apos;, {
            text: &apos;click&apos;,
            renderTo: Ext.getBody(),
            handler: function() {
                visible = !visible;
                grid.columns[1].setVisible(visible);
                grid.validate();
            }
        });
    });
&lt;/code&gt;&lt;/pre&gt;
</content:encoded></item><item><title>Extjs 4.1.1 - validatable grid</title><link>https://tpodolak.com/blog/extjs-4-1-1-validatable-grid/</link><guid isPermaLink="true">https://tpodolak.com/blog/extjs-4-1-1-validatable-grid/</guid><pubDate>Sun, 02 Sep 2012 14:08:00 GMT</pubDate><content:encoded>&lt;p&gt;In this post I will present a simple plugin to &lt;code&gt;Ext.panel.Grid&lt;/code&gt; which displays validation errors on a grid.
The validation mechanism is based on the model validation - useful feature of &lt;code&gt;Extjs&lt;/code&gt; framework.
Let&apos;s start from creating a simple model:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Ext.define(&apos;CustomerModel&apos;, {
    extend: &apos;Ext.data.Model&apos;,
    fields: [
        {name: &apos;id&apos;,  type: &apos;int&apos;},
        { name: &apos;lastname&apos;, type: &apos;string&apos; },
        {name: &apos;firstname&apos;,type:&apos;string&apos;}
    ],
    validations: [{type: &apos;presence&apos;, field: &apos;lastname&apos;, message:&apos;Required field&apos;}]
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As we can see, this model has a &lt;code&gt;validation&lt;/code&gt; field where we can define a validation mechanism for every field in our model.
In this example the &lt;code&gt;lastname&lt;/code&gt; field is required, I use build in Extjs validator of the &lt;code&gt;presence&lt;/code&gt; type.
More build-in validation types might be found &lt;a href=&quot;http://www.sencha.com/learn/using-validations-and-associations-in-sencha-touch&quot;&gt;here&lt;/a&gt;.
Of course, it is possible to define custom validation types, simple example can be found on &lt;a href=&quot;http://stackoverflow.com/questions/7414115/how-to-add-a-custom-validation-rule-to-a-model-in-sencha-touch&quot;&gt;Stackoverflow&lt;/a&gt;.
Having defined model validation, let&apos;s create &lt;code&gt;ValidatableGrid&lt;/code&gt;plugin.
The main function of &lt;code&gt;ValidatableGrid&lt;/code&gt; plugin is function called &lt;code&gt;validate&lt;/code&gt; which is attached to grid component.
This function looks this way:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;validate: function(){
       var me = this, view = this.getView(),isValid = true;
       var columnLength = me.columns.length;
       me.getStore().each(function(record,idx){
           // remove existing validation errors
           for (var j = 0; j &amp;lt; columnLength; j++) {
               var cell = view.getCellByPosition({row: idx, column: j});
               cell.removeCls(me.clsInvalidField);
           }
           var validationResult = record.validate();
           if(!validationResult.isValid()){
               isValid= false;
               for(var i =0;i &amp;lt; validationResult.items.length;i++){
                   for (var j = 0; j &amp;lt; columnLength; j++) {
                       var cell = view.getCellByPosition({row: idx, column: j});
                       if(validationResult.items[i].field == me.columns[j].dataIndex){
                           cell.addCls(&quot;x-form-invalid-field&quot;);
                           cell.set({&apos;data-errorqtip&apos;: validationResult.items[i].message});
                       }
                   }
               }
           }
       })
       return isValid;
   }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This function iterates through every model in grid&apos;s store and runs validation method.
As a result, we get a &lt;code&gt;validationResult&lt;/code&gt; object which holds information about errors of model.
This object has a function &lt;code&gt;isValid&lt;/code&gt; which returns true if there is no errors or false otherwise.
Having checked the model, we have to show errors on the grid.
In order to do that, we have to find a cell, in which invalid field is displayed using &lt;code&gt;getCellByPosition&lt;/code&gt; function.
In the last step, we only have to modify &lt;code&gt;CSS&lt;/code&gt; classes of cell.
That is why, I added &lt;code&gt;x-form-invalid-field&lt;/code&gt; class to show red line in cell and also &lt;code&gt;data-errorqtip&lt;/code&gt; class to show validation error tooltip.
The entire listing looks this way:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Ext.define(&apos;ValidatableGrid&apos;, {
    grid:null,
    init: function (grid) {
        var me = this;
        me.grid = grid;
        me.grid.validate = me.validate;
    },

   validate: function(){
        var me = this, view = this.getView(),isValid = true;
        var columnLength = me.columns.length;
        me.getStore().each(function(record,idx){
            //remove existing validation errors
            for (var j = 0; j &amp;lt; columnLength; j++) {
                var cell = view.getCellByPosition({row: idx, column: j});
                cell.removeCls(me.clsInvalidField);
            }
            var validationResult = record.validate();
            if(!validationResult.isValid()){
                isValid= false;
                for(var i =0;i &amp;lt; validationResult.items.length;i++){
                    for (var j = 0; j &amp;lt; columnLength; j++) {
                        var cell = view.getCellByPosition({row: idx, column: j});
                        if(validationResult.items[i].field == me.columns[j].dataIndex){
                            cell.addCls(&quot;x-form-invalid-field&quot;);
                            cell.set({&apos;data-errorqtip&apos;: validationResult.items[i].message});
                        }
                    }
                }
            }
        })
        return isValid;
    }
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;here is example of usage;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Ext.QuickTips.init();

var store = Ext.create(&apos;Ext.data.Store&apos;, {
    model: &apos;CustomerModel&apos;
});
store.add([{
    id: 1,
    firstname: &apos;John&apos;
}, {
    id: 1,
    firstname: &apos;Mat&apos;
}, {
    id: 1,
    firstname: &apos;Kate&apos;,
    lastname:  &apos;Smith&apos;
}, {
    id: 1,
    firstname: &apos;Richard&apos;,
    lastname:  &apos;Smith&apos;
}, {
    id: 1,
    firstname: &apos;Nick&apos;
}]);

vGrid = Ext.create(&apos;Ext.grid.Panel&apos;, {
    store: store,
    plugins: [Ext.create(&apos;ValidatableGrid&apos;)],
    columns: [ { text: &apos;Id&apos;, dataIndex: &apos;id&apos; },
               { text: &apos;First name&apos;, dataIndex: &apos;firstname&apos; },
               { text: &apos;Last name&apos;, dataIndex: &apos;lastname&apos; }]});

vGrid.validate();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and the result&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/09/extjs-4-1-1-validatable-grid/ValidatableGridWithTooltip.jpg&quot;&gt;&lt;img src=&quot;images/ValidatableGridWithTooltip.jpg&quot; alt=&quot;validatable grid&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/ExtjsValidatableGrid&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Extjs 4.1.1 - multiselectable datepicker as plugin</title><link>https://tpodolak.com/blog/extjs-4-1-1-multiselectable-datepicker-as-plugin/</link><guid isPermaLink="true">https://tpodolak.com/blog/extjs-4-1-1-multiselectable-datepicker-as-plugin/</guid><pubDate>Sun, 02 Sep 2012 12:32:00 GMT</pubDate><content:encoded>&lt;p&gt;A couple of weeks ago I wrote a post about creating a mutiselectable datepicker.
The idea of creating this component was to use the object inheritance.
Today, I would like to show how to create a multiselectable datepicker as a plugin to &lt;code&gt;Ext.date.Picker&lt;/code&gt;.
The code responsible for selecting dates is almost the same, the only thing which must be changed is the component initialization and access to the datepicker component.
In order to make a plugin to any &lt;code&gt;Ext.Component&lt;/code&gt; class, you must implement the &lt;code&gt;init&lt;/code&gt; method which takes as argument a reference to the component - so let&apos;s change the existing code to meet this requirement.
We need to rename &lt;code&gt;initComponent&lt;/code&gt; function to &lt;code&gt;init&lt;/code&gt;.
In addition to, we should delete the &lt;code&gt;extend&lt;/code&gt; property from our code. After these changes the &lt;code&gt;init&lt;/code&gt; function looks like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;init:function(datePicker){
        var me = this;
        me.datePicker = datePicker;
        // me.callParent(arguments);
        me.datePicker.on(&apos;select&apos;,me.handleSelectionChanged,me);
        me.datePicker.on(&apos;afterrender&apos;,me.higlighDates,me);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Please notice, that the &lt;code&gt;init&lt;/code&gt; function takes as an argument the datepicker component - and from now on this is our only way to access this component.
The rest of the code also requires some modifications - it&apos;s necessary to change all references to the &lt;code&gt;datepicker&lt;/code&gt; (from the variable &lt;code&gt;me&lt;/code&gt; to &lt;code&gt;me.datePicker&lt;/code&gt;).
The entire code listing is presented below.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Ext.define(&apos;Multiselect&apos;, {
    selectedDates : {},
    clsHigligthClass :&apos;x-datepicker-selected&apos;,
    datePicker:null,
    init:function(datePicker){
        var me = this;
        me.datePicker = datePicker;
       // me.callParent(arguments);
        me.datePicker.on(&apos;select&apos;,me.handleSelectionChanged,me);
        me.datePicker.on(&apos;afterrender&apos;,me.higlighDates,me);
    },
    
    higlighDates: function(){
        var me = this;
        if(!me.datePicker.cells)
            return;
        me.datePicker.cells.each(function(item){
            var date = new Date(item.dom.firstChild.dateValue).toDateString();
            if(me.selectedDates[date]){
                if(item.getAttribute(&apos;class&apos;).indexOf(me.clsHigligthClass)=== -1){
                    item.addCls(me.clsHigligthClass)
                }
            }else{
                item.removeCls(me.clsHigligthClass);
            }
        })
    },

    handleSelectionChanged:function(cmp,date){
        var me = this;
        if(me.selectedDates[date.toDateString()])
            delete me.selectedDates[date.toDateString()]
        else
            me.selectedDates[date.toDateString()] = date;
        me.higlighDates();
    }
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here is example of usage;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var picker = Ext.create(&apos;Ext.picker.Date&apos;, {
                    plugins: [Ext.create(&apos;Multiselect&apos;)]
                });
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and the result&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/09/extjs-4-1-1-multiselectable-datepicker-as-plugin/datepicker.jpg&quot;&gt;&lt;img src=&quot;images/datepicker.jpg&quot; alt=&quot;multiselectable datepicker&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/ExtjsMultiselectableDatePickerAsPlugin&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Windows Phone - skinnable application</title><link>https://tpodolak.com/blog/windows-phone-skinnable-application/</link><guid isPermaLink="true">https://tpodolak.com/blog/windows-phone-skinnable-application/</guid><pubDate>Fri, 20 Jul 2012 08:38:00 GMT</pubDate><content:encoded>&lt;h3&gt;1. Introduction&lt;/h3&gt;
&lt;p&gt;Today, I would like to present my concept of making skinnable application in &lt;code&gt;Windows Phone 7.1&lt;/code&gt;.
Making a skinnable application in &lt;code&gt;Windows Phone&lt;/code&gt; might be a little bit tricky.
Unfortunately, &lt;code&gt;WP7&lt;/code&gt; doesn&apos;t support &lt;code&gt;DynamicResource&lt;/code&gt; keyword which is a basic tool for making skins in &lt;code&gt;WPF&lt;/code&gt;.
In order to overcome this inconvenience I decided to write a &lt;code&gt;SkinManager&lt;/code&gt; for WindowsPhone.&lt;/p&gt;
&lt;h3&gt;2. Base view&lt;/h3&gt;
&lt;p&gt;As I mentioned before, there is no support for using dynamic resources in &lt;code&gt;WP7&lt;/code&gt;, therefore, in order to force a control to change style, we have to assign this style in code behind.
It is rather obvious that in a single window/control there might be quite a lot of other controls whose style also should be changed.
That is why, I decided to write controls iterator first.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class ViewsEnumerator : IEnumerator&amp;lt;FrameworkElement&amp;gt;
{
    private Stack&amp;lt;FrameworkElement&amp;gt; _frameworkElementsStack = new Stack&amp;lt;FrameworkElement&amp;gt;();
    private FrameworkElement _current;
    private readonly FrameworkElement _startingElement;
    
    public ViewsEnumerator(FrameworkElement stargingElement)
    {
        _startingElement = stargingElement;
    }
    
    public void Dispose()
    {
        _current = null;
        _frameworkElementsStack.Clear();
        _frameworkElementsStack = null;
    }
 
    #region Implementation of IEnumerator

    public bool MoveNext()
    {
        if (_current == null)
        {
            _current = _startingElement;
            for (int i = 0; i &amp;lt; VisualTreeHelper.GetChildrenCount(_current); i++)
                _frameworkElementsStack.Push((FrameworkElement)VisualTreeHelper.GetChild(_current, i));
        }
        else
        {
            if (_frameworkElementsStack.Count == 0) return false;
            _current = _frameworkElementsStack.Pop();

            for (int i = 0; i &amp;lt; VisualTreeHelper.GetChildrenCount(_current); i++)
                _frameworkElementsStack.Push((FrameworkElement)VisualTreeHelper.GetChild(_current, i));
            return true;
        }
        return true;
    }

    public void Reset()
    {
        _current = null;
        _frameworkElementsStack.Clear();
        _frameworkElementsStack = null;
    }

    public FrameworkElement Current
    {
        get { return _current; }
    }

    object IEnumerator.Current
    {
        get { return Current; }
    }

    #endregion
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this iterator I used &lt;code&gt;DFS&lt;/code&gt; algorithm for searching elements in a tree.
Thanks to this piece of code I can take advantage of &lt;code&gt;LINQ&apos;s&lt;/code&gt; benefits.
In the next step I created base classes for views.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public interface IViewBase : IEnumerable&amp;lt;FrameworkElement&amp;gt;
{
}

public class ViewBase : UserControl, IViewBase
{
   #region Implementation of IEnumerable

    /// &amp;lt;summary&amp;gt;
    /// Returns an enumerator that iterates through the collection.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;returns&amp;gt;
    /// A &amp;lt;see cref=&quot;T:System.Collections.Generic.IEnumerator`1&quot;/&amp;gt; that can be used to iterate through the collection.
    /// &amp;lt;/returns&amp;gt;
    public IEnumerator&amp;lt;FrameworkElement&amp;gt; GetEnumerator()
    {
        return new ViewsEnumerator(this);
    }

    /// &amp;lt;summary&amp;gt;
    /// Returns an enumerator that iterates through a collection.
    /// &amp;lt;/summary&amp;gt;
    /// &amp;lt;returns&amp;gt;
    /// An &amp;lt;see cref=&quot;T:System.Collections.IEnumerator&quot;/&amp;gt; object that can be used to iterate through the collection.
    /// &amp;lt;/returns&amp;gt;
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    #endregion
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;3. SkinManager class&lt;/h3&gt;
&lt;p&gt;Having prepared basis for skinnable control, let me introduce a custom attribute called the &lt;code&gt;SkinnablePartAttribute&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[AttributeUsage(AttributeTargets.Class)]
public class SkinnablePartAttribute : Attribute
{
    public string ThemePartName { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This attribute should decorate custom controls which should have an ability to change theme/skin.
As you can see, the &lt;code&gt;SkinnablePartAttribute&lt;/code&gt; has a &lt;code&gt;ThemePartName&lt;/code&gt; property which holds information about a name of &lt;code&gt;ResourceDictionary&lt;/code&gt; where styles for the given control ought to be searched.
Now, it is time to take a look at a &lt;code&gt;SkinManager&lt;/code&gt; class.
The &lt;code&gt;SkinManager&lt;/code&gt; class has one public function - &lt;code&gt;ApplySkin&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static void ApplySkin&amp;lt;TView&amp;gt;(TView view, string skinName)
           where TView : FrameworkElement, IViewBase
{
    foreach (IViewBase control in view.Where(val =&amp;gt; val.ImplementsInterfaceOf&amp;lt;IViewBase&amp;gt;()))
    {
        var assemblyName = control.GetType().Assembly.FullName;
        Uri parsedUri;
        var attribute = control.GetType().GetCustomAttributes(typeof(SkinnablePartAttribute), true).SingleOrDefault();
        if (attribute != null &amp;amp;&amp;amp; Uri.TryCreate(string.Format(&quot;/{0};component/Themes/{1}/{2}.xaml&quot;,assemblyName.Substring(0, assemblyName.IndexOf(&quot;,&quot;, StringComparison.Ordinal)), skinName,(attribute as SkinnablePartAttribute).ThemePartName), UriKind.Relative, out parsedUri))
            ApplySkin(control, parsedUri);
        else
            Debug.WriteLine(string.Format(&quot;Could not find {0}/{1}&quot;, skinName,(attribute as SkinnablePartAttribute).ThemePartName));
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This function iterates through all controls which implement a &lt;code&gt;IViewBase&lt;/code&gt; interface - in other words, the function iterates through our custom controls.
If a control is decorated with the &lt;code&gt;SkinnablePartAttribue&lt;/code&gt;, a new &lt;code&gt;Uri&lt;/code&gt; is created based on the information from the &lt;code&gt;ThemePartName&lt;/code&gt; property and from the skinName parameter(I assumed that all dictionaries are located in the &lt;code&gt;Themes&lt;/code&gt; directory).
In the final step, private function also known as the &lt;code&gt;AppySkin&lt;/code&gt; function is called. This function looks this way:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;private static void ApplySkin&amp;lt;TView&amp;gt;(TView view, Uri uri, int mergedDictionaryIndex = 0)
            where TView :  IViewBase
{
    var castedView = view as FrameworkElement;
    if(castedView == null) return;

    var resourceMergedDictionary = castedView.Resources.MergedDictionaries[mergedDictionaryIndex];
    var beforeClearDictionary = resourceMergedDictionary.ToDictionary(key =&amp;gt; key.Value, val =&amp;gt; new { key = val.Key, value = val.Value });
    castedView.Resources.MergedDictionaries.Remove(resourceMergedDictionary);
    resourceMergedDictionary.Clear();

    var newStyleDictionary = new ResourceDictionary
    {
        Source = uri
    };

    castedView.Resources.MergedDictionaries.Insert(mergedDictionaryIndex, newStyleDictionary);
    foreach (var control in view.Where(val =&amp;gt; val.Style != null &amp;amp;&amp;amp; !val.ImplementsInterfaceOf&amp;lt;IViewBase&amp;gt;()).Where(control =&amp;gt;
        beforeClearDictionary.ContainsKey(control.Style) &amp;amp;&amp;amp; newStyleDictionary[beforeClearDictionary[control.Style].key] != null))
        control.Style = newStyleDictionary[beforeClearDictionary[control.Style].key] as Style;

    beforeClearDictionary.Clear();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here, all the magic begins. In the first step, current &lt;code&gt;ResourceDictionary&lt;/code&gt; is transformed into the standard dictionary.
The key of this dictionary is a value of style – a reference to the style object.
In the next step, I created a new &lt;code&gt;ResourceDictionary&lt;/code&gt; based on the Uri parameter passed to this function.
In the last step, another loop over controls is performed.
However, this time only controls with the assigned &lt;code&gt;Style&lt;/code&gt; property are taken into consideration.
Then, if the &lt;code&gt;newStyleDictionary&lt;/code&gt; contains a key of given control style we are ready to swap styles.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;control.Style = newStyleDictionary[beforeClearDictionary[control.Style].key] as Style;

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Entire listing of &lt;code&gt;SkinManager&lt;/code&gt; is presented below&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static class SkinManager
{
    private static void ApplySkin&amp;lt;TView&amp;gt;(TView view, Uri uri, int mergedDictionaryIndex = 0)
        where TView :  IViewBase
    {
        var castedView = view as FrameworkElement;
        if(castedView == null) return;

        var resourceMergedDictionary = castedView.Resources.MergedDictionaries[mergedDictionaryIndex];
        var beforeClearDictionary = resourceMergedDictionary.ToDictionary(key =&amp;gt; key.Value, val =&amp;gt; new { key = val.Key, value = val.Value });
        castedView.Resources.MergedDictionaries.Remove(resourceMergedDictionary);
        resourceMergedDictionary.Clear();

        var newStyleDictionary = new ResourceDictionary
        {
            Source = uri
        };

        castedView.Resources.MergedDictionaries.Insert(mergedDictionaryIndex, newStyleDictionary);
        foreach (var control in view.Where(val =&amp;gt; val.Style != null &amp;amp;&amp;amp; !val.ImplementsInterfaceOf&amp;lt;IViewBase&amp;gt;()).Where(control =&amp;gt;
            beforeClearDictionary.ContainsKey(control.Style) &amp;amp;&amp;amp; newStyleDictionary[beforeClearDictionary[control.Style].key] != null))
            control.Style = newStyleDictionary[beforeClearDictionary[control.Style].key] as Style;

        beforeClearDictionary.Clear();

    }
    
    public static void ApplySkin&amp;lt;TView&amp;gt;(TView view, string skinName)
       where TView : FrameworkElement, IViewBase
    {

        foreach (IViewBase control in view.Where(val =&amp;gt; val.ImplementsInterfaceOf&amp;lt;IViewBase&amp;gt;()))
        {
            var assemblyName = control.GetType().Assembly.FullName;
            Uri parsedUri;
            var attribute = control.GetType().GetCustomAttributes(typeof(SkinnablePartAttribute), true).SingleOrDefault();
            if (attribute != null &amp;amp;&amp;amp; Uri.TryCreate(string.Format(&quot;/{0};component/Themes/{1}/{2}.xaml&quot;,assemblyName.Substring(0, assemblyName.IndexOf(&quot;,&quot;, StringComparison.Ordinal)), skinName,(attribute as SkinnablePartAttribute).ThemePartName), UriKind.Relative, out parsedUri))
                ApplySkin(control, parsedUri);
            else
                Debug.WriteLine(string.Format(&quot;Could not find {0}/{1}&quot;, skinName,(attribute as SkinnablePartAttribute).ThemePartName));
            
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;4. Example of usage&lt;/h3&gt;
&lt;p&gt;In order to use the &lt;code&gt;SkinManager&lt;/code&gt; it is essential to make some preparation.
First of all, you have to create &lt;code&gt;Themes&lt;/code&gt; directory in a project.
In this directory there must be separate subdirectories for every skin you would like to use.
What is more, in these subdirectories you should place all &lt;code&gt;ResourceDictionaries&lt;/code&gt; specified in the &lt;code&gt;SkinnablePartAttribute&lt;/code&gt;.
A sample directory structure is shown in the picture below:&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/07/windows-phone-skinnable-application/DirectoryStructure.png&quot;&gt;&lt;img src=&quot;images/DirectoryStructure.png&quot; alt=&quot;DirectoryStructure&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The very last step is to make controls (which should be skinnable) inherit from &lt;code&gt;ViewBase&lt;/code&gt;. Here is example of usage&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;namespace Joomanji.Chat.Client.Views
{
    [SkinnablePart(ThemePartName = &quot;ChatWindowSkin&quot;)]
    public partial class ChatWindowView : ViewBase
    {
        public ChatWindowView()
        {
            SkinManager.ApplySkin(this, &quot;Red&quot;); // change skin
        }
    }   
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and screenshots of the same view with different skin&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/07/windows-phone-skinnable-application/right.jpg&quot;&gt;&lt;img src=&quot;images/right-159x300.jpg&quot; alt=&quot;skinnable application&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/07/windows-phone-skinnable-application/left.jpg&quot;&gt;&lt;img src=&quot;images/left-158x300.jpg&quot; alt=&quot;skinnable application&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;5. Controls with dynamically changing content&lt;/h3&gt;
&lt;p&gt;After some test, it turned out that the mechanism presented above has problems with controls which change their content dynamically.
Let me clarify - styling grids, list boxes etc. work fine, however changing row styles and listboxitem styles are not working properly.
In order to overcome this problem you must define a style for a specific target type.
Here is an example of usage with the listbox:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Style TargetType=&quot;ListBox&quot;&amp;gt;
    &amp;lt;Setter Property=&quot;HorizontalContentAlignment&quot; Value=&quot;Stretch&quot;/&amp;gt;
    &amp;lt;Setter Property=&quot;VerticalAlignment&quot; Value=&quot;Stretch&quot;/&amp;gt;
    &amp;lt;Setter Property=&quot;ItemTemplate&quot; Value=&quot;{StaticResource GeneralChatMessageTemplate}&quot;/&amp;gt;
&amp;lt;/Style&amp;gt;`&lt;/code&gt;&lt;/pre&gt;
</content:encoded></item><item><title>Extjs 4.1.1 - multiselectable datepicker</title><link>https://tpodolak.com/blog/extjs-4-1-1-multiselectable-datepicker/</link><guid isPermaLink="true">https://tpodolak.com/blog/extjs-4-1-1-multiselectable-datepicker/</guid><pubDate>Thu, 19 Jul 2012 21:31:00 GMT</pubDate><content:encoded>&lt;p&gt;Recently, I have been given a task to make extjs datepicker allowing for selection of multiple dates.
Unfortunately afters hours of searching for some build-in function, it turned out that this kind of functionality is not supported by default.
Finaly, I decided to extend datepicker by creating component called &lt;code&gt;highlightableDatePicker&lt;/code&gt;.
I started from creating a class which inhierits from &lt;code&gt;Ext.picker.Date&lt;/code&gt;.
First draft of class looked this way&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Ext.define(&apos;HighlightableDatePicker&apos;, {
    extend: &apos;Ext.picker.Date&apos;,
    selectedDates:{},
    clsHighlightClass:&apos;x-datepicker-selected&apos;,
    initComponent: function(){
        var me = this;
        me.callParent(arguments);
    },

    highlightDates: function(){
        var me = this;
    }
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this class I created additional function &lt;code&gt;highlightDates&lt;/code&gt; which is responsible for highlighting dates.
Moreover, I added some additional config elements:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;selectedDates&lt;/code&gt; - object keeping track of dates which should be selected&lt;/li&gt;
&lt;li&gt;&lt;code&gt;clsHighlightClass&lt;/code&gt; - &lt;code&gt;CSS&lt;/code&gt; class defining selected cell style&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The most important part of &lt;code&gt;HighlightableDatepicker&lt;/code&gt; class is function &lt;code&gt;highlightDates&lt;/code&gt; which is responsible for highlighting dates.
The body of this method looks like this&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;highlightDates: function(){
      var me = this;
       if(!me.cells)
           return;
       me.cells.each(function(item){
           var date = new Date(item.dom.firstChild.dateValue).toDateString();
           if(me.selectedDates[date]){
               if(item.getAttribute(&apos;class&apos;).indexOf(me.clsHighlightClass)=== -1){
                   item.addCls(me.clsHighlightClass)
               }
           }else{
               item.removeCls(me.clsHighlightClass);
           }
       })
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As You can see, this function simply compares date in cell with dates stored in selectedDates.
If there is a match, cell style is modified by adding extra &lt;code&gt;CSS&lt;/code&gt; class into &lt;code&gt;class&lt;/code&gt; attribute of cell (see addCls function of Extjs), otherwise &lt;code&gt;CSS&lt;/code&gt; class responsible for highlighting is removed.
Having defind &lt;code&gt;highlightDates&lt;/code&gt; function,I also had to attach an event handler to &lt;code&gt;select&lt;/code&gt; event, in order to modify collection of selected dates.
This handler looks this way&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;handleSelectionChanged: function(cmp, date){
   var me = this;
       if(me.selectedDates[date.toDateString()])
           delete me.selectedDates[date.toDateString()]
       else
           me.selectedDates[date.toDateString()] = date;
       me.highlightDates();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The final step to make this control work is to attach event handlers and call &lt;code&gt;highlightDates&lt;/code&gt; function during initialization of component.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;initComponent: function() {
        var me = this;
        me.callParent(arguments);
        me.on(&apos;select&apos;,me.handleSelectionChanged,me);
        me.on(&apos;afterrender&apos;,me.highlightDates,me);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Please, notice that &lt;code&gt;highlightDates&lt;/code&gt; is called after component is rendered, because there is no rendered cells before that moment.
Entire code listing is presented below&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Ext.define(&apos;HighlightableDatePicker&apos;, {
    extend: &apos;Ext.picker.Date&apos;,
    selectedDates : {},
    clsHighlightClass :&apos;x-datepicker-selected&apos;,
    
    initComponent: function(){
        var me = this;
        me.callParent(arguments);
        me.on(&apos;select&apos;,me.handleSelectionChanged,me);
        me.on(&apos;afterrender&apos;,me.highlightDates,me);

    },
    
    highlightDates: function(){
        var me = this;
        if(!me.cells)
            return;
        me.cells.each(function(item){
            var date = new Date(item.dom.firstChild.dateValue).toDateString();
            if(me.selectedDates[date]){
                if(item.getAttribute(&apos;class&apos;).indexOf(me.clsHighlightClass)=== -1){
                    item.addCls(me.clsHighlightClass)
                }
            }else{
                item.removeCls(me.clsHighlightClass);
            }
        })
    },

    handleSelectionChanged: function(cmp, date){
        var me = this;
        if(me.selectedDates[date.toDateString()])
            delete me.selectedDates[date.toDateString()]
        else
            me.selectedDates[date.toDateString()] = date;
        me.highlightDates();
    }
})
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and the result&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/09/extjs-4-1-1-multiselectable-datepicker-as-plugin/datepicker.jpg&quot;&gt;&lt;img src=&quot;images/datepicker.jpg&quot; alt=&quot;multiselectable datepicker&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Source code for this post can be found &lt;a href=&quot;https://github.com/tpodolak/Blog/tree/master/ExtjsMultiselectableDatePicker&quot;&gt;here&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Extjs 4.1 - zmiana stylu konkretnej komórki w gridzie</title><link>https://tpodolak.com/blog/extjs-4-1-zmiana-stylu-konkretnej-komorki-w-gridzie/</link><guid isPermaLink="true">https://tpodolak.com/blog/extjs-4-1-zmiana-stylu-konkretnej-komorki-w-gridzie/</guid><pubDate>Fri, 13 Jul 2012 20:42:00 GMT</pubDate><content:encoded>&lt;p&gt;Witam Dzisiejszy post nie będzie związany z platformą &lt;code&gt;.NET&lt;/code&gt;, lecz z javascriptowym frameworkiem &lt;code&gt;Extjs&lt;/code&gt; w wersji &lt;code&gt;4.1&lt;/code&gt;.
Jako, że ostatnio w pracy poświęcam dużo czasu na pisanie w wyżej wymienionej technologii postanowiłem zaprezentować, w jaki sposób zmienić styl konkretnej komórki w gridzie.
Zacznijmy od przygotowania danych do wyświetlenia - zdefiniujmy zatem stora, który będzie przechowywał informacje mające zostać zaprezentowane na gridzie.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Ext.create(&apos;Ext.data.Store&apos;, {
    storeId:&apos;itemsStore&apos;,
    fields:[&apos;name&apos;, &apos;email&apos;, &apos;change&apos;],
    data:{&apos;items&apos;:[
        { &apos;name&apos;: &apos;LCD PLAYER&apos;,    &quot;change&quot;:100  },
        { &apos;name&apos;: &apos;DVD PLAYER&apos;, &quot;change&quot;:-20  },
        { &apos;name&apos;: &apos;CD PLAYER&apos;,   &quot;change&quot;:23   },
        
    ]},
    proxy: {
        type: &apos;memory&apos;,
        reader: {
            type: &apos;json&apos;,
            root: &apos;items&apos;
        }
    }
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Następnie podepnijmy stora pod grida w wersji podstawowej - bez zmiany stylu konkretnych komórek.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Ext.create(&apos;Ext.grid.Panel&apos;, {
    store: Ext.data.StoreManager.lookup(&apos;itemsStore&apos;),
    columns: [
        { header: &apos;Name&apos;,  dataIndex: &apos;name&apos; },
        { header: &apos;Change&apos;, dataIndex: &apos;change&apos;}
    ],
    height: 200,
    width: 400,
    forceFit:true,
    renderTo: Ext.getBody()
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W celu zmiany parametrów poszczególnych komórek grida posłużymy się tzw. rendererem.
&lt;code&gt;Renderer&lt;/code&gt; jest to funkcja, której zadaniem jest modyfikacją komórek w danej kolumnie grida.
Dzięki rendererowi możemy nie tyko zmienić zawartość komórki, ale również przypisać jej osobny styl lub klasę &lt;code&gt;CSS&lt;/code&gt;.
Myślę, że renderer można porównać do conwertera znanego z technologii &lt;code&gt;WPF&lt;/code&gt;.
Funkcję renderera podłączymy pod ostatnią kolumnę. Kod po modyfikacjach będzie wyglądał w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Ext.create(&apos;Ext.grid.Panel&apos;, {
    store: Ext.data.StoreManager.lookup(&apos;itemsStore&apos;),
    columns: [
        { header: &apos;Name&apos;,  dataIndex: &apos;name&apos; },
        { header: &apos;Change&apos;, dataIndex: &apos;change&apos;, renderer: function(value, metaData, record, row, col, store, gridView){
            if(value&amp;gt;0)
              metaData.tdCls = &apos;price-rise&apos;
            else
              metaData.tdCls = &apos;price-fall&apos;
                  
             return value;
        }}
    ],
    height: 200,
    width: 400,
    
    renderTo: Ext.getBody()
});
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;.price-fall  {
    background-color: red !important;
    
}
.price-rise {
    background-color: #B0FFC5;
    color:green;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Zauważmy, że funkcja renderer przyjmuje kilka parametrów. Najważniejsze z nich to&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;value&lt;/code&gt; - wartość wyświetlona w komórce grida&lt;/li&gt;
&lt;li&gt;&lt;code&gt;metaData&lt;/code&gt;- obiekt dający nam dostęp do parametrów komórki (np. tdCls)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;record&lt;/code&gt; - record grida&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;W moim przypadku na podstawie wartości wyświetlanej w komórkach kolumny &lt;code&gt;Change&lt;/code&gt;, określam czy dana komórka powinna być czerwona czy zielona.
Wygląd grida przed oraz po zastosowaniu renderera przedstawiają poniższe screeny&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/07/extjs-4-1-zmiana-stylu-konkretnej-komorki-w-gridzie/Before.jpg&quot;&gt;&lt;img src=&quot;images/Before.jpg&quot; alt=&quot;Before&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/07/extjs-4-1-zmiana-stylu-konkretnej-komorki-w-gridzie/After.jpg&quot;&gt;&lt;img src=&quot;images/After.jpg&quot; alt=&quot;zmiana stylu&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Windows Phone - własny DataTemplateSelector</title><link>https://tpodolak.com/blog/windows-phone-wlasny-datatemplateselector/</link><guid isPermaLink="true">https://tpodolak.com/blog/windows-phone-wlasny-datatemplateselector/</guid><pubDate>Sat, 09 Jun 2012 22:55:00 GMT</pubDate><content:encoded>&lt;p&gt;Pisząc moją małą aplikację pod &lt;code&gt;Windows Phone&lt;/code&gt; po raz kolejny natknąłem się na problem.
Pod &lt;code&gt;WP7&lt;/code&gt; nie ma tak przydatnej rzeczy jaką jest &lt;code&gt;DataTemplateSelector&lt;/code&gt; znany nam bardziej, lub mniej z Silverlighta oraz &lt;code&gt;WPF-a&lt;/code&gt;.
Na szczęście napisane własnego &lt;code&gt;DataTemplateSelector-a&lt;/code&gt; nie jest specjalnie skomplikowane.
Nasz customowy &lt;code&gt;DataTemplateSelector&lt;/code&gt; zostanie oparty o kontrolkę &lt;code&gt;ContentControl&lt;/code&gt;.
Po pierwsze stwórzmy klasę bazową &lt;code&gt;DataTemplateSelectora&lt;/code&gt; dziedziczącą po &lt;code&gt;ContentControl&lt;/code&gt;, w której przeciążamy funkcję &lt;code&gt;OnContentChanged&lt;/code&gt;,&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public abstract class AbstractDataTemplateSelector : ContentControl
{
    public abstract DataTemplate SelectTemplate(object item, DependencyObject container);
    
    protected override void OnContentChanged(object oldContent, object newContent)
    {
        base.OnContentChanged(oldContent, newContent);
        ContentTemplate = SelectTemplate(newContent, this);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Klasa ta będzie klasą z której będą wywodzić się wszystkie nasze &lt;code&gt;TemplateSelectory&lt;/code&gt;.
Załóżmy, że chcemy zbudować &lt;code&gt;DataTemplateSelector&lt;/code&gt;, który będzie obsługiwał aplikację chata.
Powinien on zatem reagować na dwa typy elementów:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;wiadomości przychodzące&lt;/li&gt;
&lt;li&gt;wiadomości wychodzące&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Stwórzmy zatem &quot;wyspecjalizowany&quot; &lt;code&gt;DataTemplateSelector&lt;/code&gt;, który w zależności od typu wiadomości zwróci odpowiedni &lt;code&gt;DataTemplate&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class ChatMessageTemplateSelector : AbstractDataTemplateSelector
{
    public DataTemplate Out { get; set; }
    public DataTemplate In { get; set; }

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        ChatMessage message = item as ChatMessage;
        if (message != null)
        {
            switch (message.MessageDirection)
            {
                case MessageDirection.In:
                    return In;
                case MessageDirection.Out:
                    return Out;
                default:
                    return Out;
            }
        }
        return In;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W klasie &lt;code&gt;ChatMessageTemplateSelector&lt;/code&gt; przeciążyliśmy metodę &lt;code&gt;SelectTemplate&lt;/code&gt;.
W metodzie tej, na podstawie zbindowanego obiektu (parametr item) określamy jaki template powinniśmy zwrócić.
Templaty do wiadomości przychodzących oraz wychodzących zostały zdefiniowane jako propertisy.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Out&lt;/code&gt; - template wiadomości wychodzącej&lt;/li&gt;
&lt;li&gt;&lt;code&gt;In&lt;/code&gt; - template wiadomości przychodzącej&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Pozostaje nam tylko zdefiniować wymienione wyżej templaty. Nie będziemy robić tego w kodzie, ale w &lt;code&gt;XAML-u&lt;/code&gt;.
Nasz nowo stworzony &lt;code&gt;DataTemplateSelector&lt;/code&gt; wykorzytamy w &lt;code&gt;ListBox-ie&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;ListBox  ItemsSource=&quot;{Binding MessageList,Mode=TwoWay}&quot; Grid.ColumnSpan=&quot;2&quot; HorizontalContentAlignment=&quot;Stretch&quot; VerticalAlignment=&quot;Stretch&quot;
                     ItemTemplate=&quot;{StaticResource GeneralChatMessageTemplate}&quot; /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Jako, że nasz &lt;code&gt;ChatMessageTemplateSelector&lt;/code&gt; jest tak naprawdę obiektem typu &lt;code&gt;ContentControl&lt;/code&gt;, zatem możemy go zbindować do właściwości &lt;code&gt;ItemTemplate&lt;/code&gt; &lt;code&gt;ListBox-a&lt;/code&gt;.
Zasób &lt;code&gt;GeneralChatMessageTemplate&lt;/code&gt; wygląda w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;DataTemplate x:Key=&quot;GeneralChatMessageTemplate&quot;&amp;gt;
            &amp;lt;Client:ChatMessageTemplateSelector HorizontalContentAlignment=&quot;Stretch&quot; Content=&quot;{Binding}&quot; In=&quot;{StaticResource IncomingChatMessageTemplate}&quot; Out=&quot;{StaticResource OutcomingChatMessageTemplate}&quot;&amp;gt;
            &amp;lt;/Client:ChatMessageTemplateSelector&amp;gt;
&amp;lt;/DataTemplate&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Jak widać jest to obiekt typu &lt;code&gt;ChatMessageTemplateSelector&lt;/code&gt;, którego właściwość &lt;code&gt;Content&lt;/code&gt; jest zbindowana do aktualnego kontekstu (pojedyncze słowo kluczowe &lt;code&gt;Binding&lt;/code&gt;).
Widzimy również, że ustawiliśmy wartości właściwości odpowiadających za templaty poszczególnych wiadomości (&lt;code&gt;In=&quot;{StaticResource IncomingChatMessageTemplate}&quot; Out=&quot;{StaticResource OutcomingChatMessageTemplate}&quot;&lt;/code&gt;).
Wspomniane templaty wyglądają w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;DataTemplate x:Key=&quot;IncomingChatMessageTemplate&quot;&amp;gt;
            &amp;lt;Border BorderThickness=&quot;0,0,0,1&quot; BorderBrush=&quot;#2d3550&quot; &amp;gt;
                &amp;lt;Grid Background=&quot;#181c2a&quot; HorizontalAlignment=&quot;Stretch&quot;&amp;gt;
                    &amp;lt;Grid.ColumnDefinitions&amp;gt;
                        &amp;lt;ColumnDefinition /&amp;gt;
                        &amp;lt;ColumnDefinition /&amp;gt;
                    &amp;lt;/Grid.ColumnDefinitions&amp;gt;
                    &amp;lt;Grid.RowDefinitions&amp;gt;
                        &amp;lt;RowDefinition&amp;gt;&amp;lt;/RowDefinition&amp;gt;
                        &amp;lt;RowDefinition&amp;gt;&amp;lt;/RowDefinition&amp;gt;
                    &amp;lt;/Grid.RowDefinitions&amp;gt;
                    &amp;lt;StackPanel Orientation=&quot;Horizontal&quot;&amp;gt;
                        &amp;lt;Border BorderThickness=&quot;1&quot; BorderBrush=&quot;White&quot; Margin=&quot;5,5,0,0&quot;&amp;gt;
                            &amp;lt;Image Stretch=&quot;None&quot;  Width=&quot;30&quot; Height=&quot;30&quot; MaxWidth=&quot;30&quot; MinHeight=&quot;30&quot; MaxHeight=&quot;30&quot;  Source=&quot;..avatar_4934.bmp&quot;&amp;gt;&amp;lt;/Image&amp;gt;
                        &amp;lt;/Border&amp;gt;
                        &amp;lt;TextBlock Padding=&quot;5,5,5,0&quot; Foreground=&quot;White&quot; FontFamily=&quot;Segoe UI, Tahoma&quot; FontSize=&quot;12&quot; FontWeight=&quot;Bold&quot; TextTrimming=&quot;WordEllipsis&quot;  TextAlignment=&quot;Left&quot; VerticalAlignment=&quot;Center&quot; HorizontalAlignment=&quot;Left&quot;  Text=&quot;{Binding Sender.UserName,Mode=TwoWay}&quot;&amp;gt;&amp;lt;/TextBlock&amp;gt;
                    &amp;lt;/StackPanel&amp;gt;
                    &amp;lt;TextBlock FontFamily=&quot;Segoe UI, Tahoma&quot; FontSize=&quot;10&quot; Padding=&quot;5,5,5,0&quot; Foreground=&quot;#8e929f&quot; TextTrimming=&quot;WordEllipsis&quot;  Grid.Column=&quot;1&quot; TextAlignment=&quot;Right&quot; VerticalAlignment=&quot;Center&quot; HorizontalAlignment=&quot;Right&quot; Text=&quot;{Binding SendTime, Mode=TwoWay, StringFormat=&apos;{0:dd.MM HH:mm:ss}&apos;}&quot;&amp;gt;&amp;lt;/TextBlock&amp;gt;
                    &amp;lt;TextBlock FontFamily=&quot;Segoe UI, Tahoma&quot; FontSize=&quot;12&quot; Margin=&quot;5,0,0,0&quot; TextWrapping=&quot;Wrap&quot; Grid.ColumnSpan=&quot;2&quot; Grid.Row=&quot;1&quot; Text=&quot;{Binding Message,Mode=TwoWay}&quot; &amp;gt;&amp;lt;/TextBlock&amp;gt;
                &amp;lt;/Grid&amp;gt;
            &amp;lt;/Border&amp;gt;
&amp;lt;/DataTemplate&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;DataTemplate x:Key=&quot;OutcomingChatMessageTemplate&quot;&amp;gt;
            &amp;lt;Border BorderThickness=&quot;0,0,0,1&quot; BorderBrush=&quot;#2d3550&quot;&amp;gt;
                &amp;lt;Grid HorizontalAlignment=&quot;Stretch&quot;&amp;gt;
                    &amp;lt;Grid.ColumnDefinitions&amp;gt;
                        &amp;lt;ColumnDefinition /&amp;gt;
                        &amp;lt;ColumnDefinition /&amp;gt;
                    &amp;lt;/Grid.ColumnDefinitions&amp;gt;
                    &amp;lt;Grid.RowDefinitions&amp;gt;
                        &amp;lt;RowDefinition&amp;gt;&amp;lt;/RowDefinition&amp;gt;
                        &amp;lt;RowDefinition&amp;gt;&amp;lt;/RowDefinition&amp;gt;
                    &amp;lt;/Grid.RowDefinitions&amp;gt;
                    &amp;lt;StackPanel Orientation=&quot;Horizontal&quot;&amp;gt;
                        &amp;lt;Border BorderThickness=&quot;1&quot; BorderBrush=&quot;White&quot; Margin=&quot;5,5,0,0&quot;&amp;gt;
                            &amp;lt;Image Stretch=&quot;None&quot;  Width=&quot;30&quot; Height=&quot;30&quot; MaxWidth=&quot;30&quot; MinHeight=&quot;30&quot; MaxHeight=&quot;30&quot;  &amp;gt;&amp;lt;/Image&amp;gt;
                        &amp;lt;/Border&amp;gt;
                        &amp;lt;TextBlock Padding=&quot;5,5,5,0&quot; Foreground=&quot;#8e929f&quot; FontFamily=&quot;Segoe UI, Tahoma&quot; FontSize=&quot;12&quot; FontWeight=&quot;Bold&quot; TextTrimming=&quot;WordEllipsis&quot;  TextAlignment=&quot;Left&quot; VerticalAlignment=&quot;Center&quot; HorizontalAlignment=&quot;Left&quot;  Text=&quot;{Binding Sender.UserName,Mode=TwoWay}&quot;&amp;gt;&amp;lt;/TextBlock&amp;gt;
                    &amp;lt;/StackPanel&amp;gt;
                    &amp;lt;TextBlock FontFamily=&quot;Segoe UI, Tahoma&quot; FontSize=&quot;10&quot; Padding=&quot;5,5,5,0&quot; Foreground=&quot;#8e929f&quot; TextTrimming=&quot;WordEllipsis&quot;  Grid.Column=&quot;1&quot; TextAlignment=&quot;Right&quot; VerticalAlignment=&quot;Center&quot; HorizontalAlignment=&quot;Right&quot; Text=&quot;{Binding SendTime, Mode=TwoWay, StringFormat=&apos;{0:dd.MM HH:mm:ss}&apos;}&quot;&amp;gt;&amp;lt;/TextBlock&amp;gt;
                    &amp;lt;TextBlock FontFamily=&quot;Segoe UI, Tahoma&quot; FontSize=&quot;12&quot; Margin=&quot;5,0,0,0&quot; TextWrapping=&quot;Wrap&quot; Grid.ColumnSpan=&quot;2&quot; Grid.Row=&quot;1&quot; Text=&quot;{Binding Message,Mode=TwoWay}&quot; &amp;gt;&amp;lt;/TextBlock&amp;gt;
                &amp;lt;/Grid&amp;gt;
            &amp;lt;/Border&amp;gt;
&amp;lt;/DataTemplate&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Od teraz gdy do &lt;code&gt;ListBox-a&lt;/code&gt; zostanie dodany nowy item, pierwszą rzeczą jaka się odpali będzie funkcja &lt;code&gt;OnContentChanged&lt;/code&gt;.
W funkcji tej &lt;code&gt;AbstractDataTemplateSelector&lt;/code&gt; na podstawie nowo przybyłego itemu ustawi właściwość &lt;code&gt;ContentTemplate&lt;/code&gt;, na taki template jaki zwróci mu funkcja &lt;code&gt;SelectTemplate&lt;/code&gt;.
Wynik działania &lt;code&gt;ChatMessageTemplateSelector&lt;/code&gt; wygląda w następujący sposób&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/06/windows-phone-wlasny-datatemplateselector/Result.jpg&quot;&gt;&lt;img src=&quot;images/Result.jpg&quot; alt=&quot;DataTemplateSelector&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Windows Phone - wyświetlanie błędów walidacji</title><link>https://tpodolak.com/blog/windows-phone-wyswietlanie-bledow-walidacji/</link><guid isPermaLink="true">https://tpodolak.com/blog/windows-phone-wyswietlanie-bledow-walidacji/</guid><pubDate>Sat, 09 Jun 2012 22:55:00 GMT</pubDate><content:encoded>&lt;p&gt;Kilka miesięcy temu w &lt;a href=&quot;http://tpodolak.com/blog/2011/11/28/walidacja&quot;&gt;tym&lt;/a&gt; poście przedstawiałem różne sposoby walidacji jakie są dostępne na platformie &lt;code&gt;Silverlight&lt;/code&gt;.
Jako, że ostatnio mam więcej czasu aby pisać jakieś proste aplikacje pod &lt;code&gt;Windows Phonem&lt;/code&gt; potrzebowałem mechanizmu walidacji działającego pod tą platformą.
Według &lt;code&gt;MSDN-a&lt;/code&gt; wszystkie metody walidacji przedstawione we wspomnianym wcześniej poście powinny działać.
Niestety po przerzuceniu mechanizmu z &lt;code&gt;Silverlighta&lt;/code&gt; na &lt;code&gt;Windows Phona&lt;/code&gt; okazało się, że błędy walidacji nie zostają wyświetlone na interfejsie.
Po przeszukaniu kilku for oraz blogów dowiedziałem się, że przyczyną takiego stanu rzeczy jest brak obsługi reakcji na błędy w templacie &lt;code&gt;TextBoxów&lt;/code&gt; (i innych elementów typu input).
Zatem aby wyświetlić błędy walidacji, pozostaje nam zmodyfikować istniejący template &lt;code&gt;TextBox-a&lt;/code&gt;.
Zacznijmy od wyciągnięcia standardowego templatu TextBox-a z Windows Phona.
W tym celu możemy użyć aplikacji &lt;code&gt;Expression Blend&lt;/code&gt;. Otwórzmy w niej jakikolwiek projekt typu &lt;code&gt;Windows Phone Application&lt;/code&gt;, w którym na kontrolce mamy naniesionego Textboxa.
W moim przypadku, po wczytaniu projektu do &lt;code&gt;Blenda&lt;/code&gt; ekran wygląda w następujący sposób&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/06/windows-phone-wyswietlanie-bledow-walidacji/blend.jpg&quot;&gt;&lt;img src=&quot;images/blend.jpg&quot; alt=&quot;blend&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Następnie zaznaczamy w &lt;code&gt;Blendzie&lt;/code&gt; &lt;code&gt;TextBox-a&lt;/code&gt; i z opcji znajdujących się w lewym górnym rogu aktualnej zakładki wybieramy &lt;code&gt;TextBox-&amp;gt;Edit Template-&amp;gt; Edit Copy&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/06/windows-phone-wyswietlanie-bledow-walidacji/BlendTemplateExtraction.png&quot;&gt;&lt;img src=&quot;images/BlendTemplateExtraction.png&quot; alt=&quot;BlendTemplateExtraction&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;W oknie, które się pojawi klikamy &lt;code&gt;OK&lt;/code&gt;.
Następnie możemy przejść do widoku &lt;code&gt;XAML-a&lt;/code&gt;, w sekcji &lt;code&gt;phone:PhoneApplicationPage.Resources&lt;/code&gt; powinien pojawić się nam nowy styl wyglądający w ten sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;ControlTemplate x:Key=&quot;PhoneDisabledTextBoxTemplate&quot; TargetType=&quot;TextBox&quot;&amp;gt;
   &amp;lt;ContentControl x:Name=&quot;ContentElement&quot; BorderThickness=&quot;0&quot; HorizontalContentAlignment=&quot;Stretch&quot; Margin=&quot;{StaticResource PhoneTextBoxInnerMargin}&quot; Padding=&quot;{TemplateBinding Padding}&quot; VerticalContentAlignment=&quot;Stretch&quot;/&amp;gt;
   &amp;lt;/ControlTemplate&amp;gt;
   &amp;lt;Style x:Key=&quot;TextBoxStyle1&quot; TargetType=&quot;TextBox&quot;&amp;gt;
      &amp;lt;Setter Property=&quot;FontFamily&quot; Value=&quot;{StaticResource PhoneFontFamilyNormal}&quot;/&amp;gt;
      &amp;lt;Setter Property=&quot;FontSize&quot; Value=&quot;{StaticResource PhoneFontSizeMediumLarge}&quot;/&amp;gt;
      &amp;lt;Setter Property=&quot;Background&quot; Value=&quot;{StaticResource PhoneTextBoxBrush}&quot;/&amp;gt;
      &amp;lt;Setter Property=&quot;Foreground&quot; Value=&quot;{StaticResource PhoneTextBoxForegroundBrush}&quot;/&amp;gt;
      &amp;lt;Setter Property=&quot;BorderBrush&quot; Value=&quot;{StaticResource PhoneTextBoxBrush}&quot;/&amp;gt;
      &amp;lt;Setter Property=&quot;SelectionBackground&quot; Value=&quot;{StaticResource PhoneAccentBrush}&quot;/&amp;gt;
      &amp;lt;Setter Property=&quot;SelectionForeground&quot; Value=&quot;{StaticResource PhoneTextBoxSelectionForegroundBrush}&quot;/&amp;gt;
      &amp;lt;Setter Property=&quot;BorderThickness&quot; Value=&quot;{StaticResource PhoneBorderThickness}&quot;/&amp;gt;
      &amp;lt;Setter Property=&quot;Padding&quot; Value=&quot;2&quot;/&amp;gt;
      &amp;lt;Setter Property=&quot;Template&quot;&amp;gt;
       &amp;lt;Setter.Value&amp;gt;
        &amp;lt;ControlTemplate TargetType=&quot;TextBox&quot;&amp;gt;
         &amp;lt;Grid Background=&quot;Transparent&quot;&amp;gt;
          &amp;lt;VisualStateManager.VisualStateGroups&amp;gt;
           &amp;lt;VisualStateGroup x:Name=&quot;CommonStates&quot;&amp;gt;
            &amp;lt;VisualState x:Name=&quot;Normal&quot;/&amp;gt;
            &amp;lt;VisualState x:Name=&quot;MouseOver&quot;/&amp;gt;
            &amp;lt;VisualState x:Name=&quot;Disabled&quot;&amp;gt;
             &amp;lt;Storyboard&amp;gt;
              &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Visibility&quot; Storyboard.TargetName=&quot;EnabledBorder&quot;&amp;gt;
               &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot;&amp;gt;
                &amp;lt;DiscreteObjectKeyFrame.Value&amp;gt;
                 &amp;lt;Visibility&amp;gt;Collapsed&amp;lt;/Visibility&amp;gt;
                &amp;lt;/DiscreteObjectKeyFrame.Value&amp;gt;
               &amp;lt;/DiscreteObjectKeyFrame&amp;gt;
              &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
              &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Visibility&quot; Storyboard.TargetName=&quot;DisabledOrReadonlyBorder&quot;&amp;gt;
               &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot;&amp;gt;
                &amp;lt;DiscreteObjectKeyFrame.Value&amp;gt;
                 &amp;lt;Visibility&amp;gt;Visible&amp;lt;/Visibility&amp;gt;
                &amp;lt;/DiscreteObjectKeyFrame.Value&amp;gt;
               &amp;lt;/DiscreteObjectKeyFrame&amp;gt;
              &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
             &amp;lt;/Storyboard&amp;gt;
            &amp;lt;/VisualState&amp;gt;
            &amp;lt;VisualState x:Name=&quot;ReadOnly&quot;&amp;gt;
             &amp;lt;Storyboard&amp;gt;
              &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Visibility&quot; Storyboard.TargetName=&quot;EnabledBorder&quot;&amp;gt;
               &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot;&amp;gt;
                &amp;lt;DiscreteObjectKeyFrame.Value&amp;gt;
                 &amp;lt;Visibility&amp;gt;Collapsed&amp;lt;/Visibility&amp;gt;
                &amp;lt;/DiscreteObjectKeyFrame.Value&amp;gt;
               &amp;lt;/DiscreteObjectKeyFrame&amp;gt;
              &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
              &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Visibility&quot; Storyboard.TargetName=&quot;DisabledOrReadonlyBorder&quot;&amp;gt;
               &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot;&amp;gt;
                &amp;lt;DiscreteObjectKeyFrame.Value&amp;gt;
                 &amp;lt;Visibility&amp;gt;Visible&amp;lt;/Visibility&amp;gt;
                &amp;lt;/DiscreteObjectKeyFrame.Value&amp;gt;
               &amp;lt;/DiscreteObjectKeyFrame&amp;gt;
              &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
              &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Background&quot; Storyboard.TargetName=&quot;DisabledOrReadonlyBorder&quot;&amp;gt;
               &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;{StaticResource PhoneTextBoxBrush}&quot;/&amp;gt;
              &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
              &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;BorderBrush&quot; Storyboard.TargetName=&quot;DisabledOrReadonlyBorder&quot;&amp;gt;
               &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;{StaticResource PhoneTextBoxBrush}&quot;/&amp;gt;
              &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
              &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Foreground&quot; Storyboard.TargetName=&quot;DisabledOrReadonlyContent&quot;&amp;gt;
               &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;{StaticResource PhoneTextBoxReadOnlyBrush}&quot;/&amp;gt;
              &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
             &amp;lt;/Storyboard&amp;gt;
            &amp;lt;/VisualState&amp;gt;
           &amp;lt;/VisualStateGroup&amp;gt;
           &amp;lt;VisualStateGroup x:Name=&quot;FocusStates&quot;&amp;gt;
            &amp;lt;VisualState x:Name=&quot;Focused&quot;&amp;gt;
             &amp;lt;Storyboard&amp;gt;
              &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Background&quot; Storyboard.TargetName=&quot;EnabledBorder&quot;&amp;gt;
               &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;{StaticResource PhoneTextBoxEditBackgroundBrush}&quot;/&amp;gt;
              &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
              &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;BorderBrush&quot; Storyboard.TargetName=&quot;EnabledBorder&quot;&amp;gt;
               &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;{StaticResource PhoneTextBoxEditBorderBrush}&quot;/&amp;gt;
              &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
             &amp;lt;/Storyboard&amp;gt;
            &amp;lt;/VisualState&amp;gt;
            &amp;lt;VisualState x:Name=&quot;Unfocused&quot;/&amp;gt;
           &amp;lt;/VisualStateGroup&amp;gt;
          &amp;lt;/VisualStateManager.VisualStateGroups&amp;gt;
          &amp;lt;Border x:Name=&quot;EnabledBorder&quot; BorderBrush=&quot;{TemplateBinding BorderBrush}&quot; BorderThickness=&quot;{TemplateBinding BorderThickness}&quot; Background=&quot;{TemplateBinding Background}&quot; Margin=&quot;{StaticResource PhoneTouchTargetOverhang}&quot;&amp;gt;
           &amp;lt;ContentControl x:Name=&quot;ContentElement&quot; BorderThickness=&quot;0&quot; HorizontalContentAlignment=&quot;Stretch&quot; Margin=&quot;{StaticResource PhoneTextBoxInnerMargin}&quot; Padding=&quot;{TemplateBinding Padding}&quot; VerticalContentAlignment=&quot;Stretch&quot;/&amp;gt;
          &amp;lt;/Border&amp;gt;
          &amp;lt;Border x:Name=&quot;DisabledOrReadonlyBorder&quot; BorderBrush=&quot;{StaticResource PhoneDisabledBrush}&quot; BorderThickness=&quot;{TemplateBinding BorderThickness}&quot; Background=&quot;Transparent&quot; Margin=&quot;{StaticResource PhoneTouchTargetOverhang}&quot; Visibility=&quot;Collapsed&quot;&amp;gt;
           &amp;lt;TextBox x:Name=&quot;DisabledOrReadonlyContent&quot; Background=&quot;Transparent&quot; Foreground=&quot;{StaticResource PhoneDisabledBrush}&quot; FontWeight=&quot;{TemplateBinding FontWeight}&quot; FontStyle=&quot;{TemplateBinding FontStyle}&quot; FontSize=&quot;{TemplateBinding FontSize}&quot; FontFamily=&quot;{TemplateBinding FontFamily}&quot; IsReadOnly=&quot;True&quot; SelectionForeground=&quot;{TemplateBinding SelectionForeground}&quot; SelectionBackground=&quot;{TemplateBinding SelectionBackground}&quot; TextAlignment=&quot;{TemplateBinding TextAlignment}&quot; TextWrapping=&quot;{TemplateBinding TextWrapping}&quot; Text=&quot;{TemplateBinding Text}&quot; Template=&quot;{StaticResource PhoneDisabledTextBoxTemplate}&quot;/&amp;gt;
          &amp;lt;/Border&amp;gt;
         &amp;lt;/Grid&amp;gt;
        &amp;lt;/ControlTemplate&amp;gt;
       &amp;lt;/Setter.Value&amp;gt;
      &amp;lt;/Setter&amp;gt;
   &amp;lt;/Style&amp;gt;
&amp;lt;/ControlTemplate&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W ten oto sposób udało nam się wydobyć domyślny styl oraz template &lt;code&gt;TextBoxa&lt;/code&gt; w &lt;code&gt;Windows Phonie&lt;/code&gt;.
W kolejnym kroku musimy zmodyfikować ten template w taki sposób, aby zaczął reagować na zmiany stanu walidacji.
Zacznijmy od sprawdzenia jakie stany wizualne może obsługiwać &lt;code&gt;TextBox&lt;/code&gt;.
W tym celu musimy przeglądnąć metadane &lt;code&gt;TextBoxa&lt;/code&gt; - możemy to zrobić klikając &lt;code&gt;PPM&lt;/code&gt; na klasie &lt;code&gt;TextBox-a&lt;/code&gt; i wybierając &lt;code&gt;Go To Definition&lt;/code&gt;.
Naszym oczom powinno ukazać się coś takiego.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/06/windows-phone-wyswietlanie-bledow-walidacji/validationstates.png&quot;&gt;&lt;img src=&quot;images/validationstates.png&quot; alt=&quot;validationstates&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Widzimy, że klasa &lt;code&gt;TextBox&lt;/code&gt; jest opatrzona atrybutami &lt;code&gt;TemplateVisualState&lt;/code&gt;, nas interesują najbardziej trzy z tych atrybutów:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[TemplateVisualState(GroupName = &quot;ValidationStates&quot;, Name = &quot;Valid&quot;)\]
[TemplateVisualState(GroupName = &quot;ValidationStates&quot;, Name = &quot;InvalidFocused&quot;)\]
[TemplateVisualState(GroupName = &quot;ValidationStates&quot;, Name = &quot;InvalidUnfocused&quot;)\]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Mówią nam one, że w przypadku gdy wystąpią błędy walidacji nasza kontrolka przechodzi w stan &lt;code&gt;InvalidFocused&lt;/code&gt; lub &lt;code&gt;InvalidUnfocused&lt;/code&gt;.
Natomiast, w przypadku gdy nie ma błędów znajduje się ona w stanie &lt;code&gt;Valid&lt;/code&gt;.
Analizując kod domyślnego templatu &lt;code&gt;TextBoxa&lt;/code&gt; widzimy, że stany z grupy &lt;code&gt;ValidationStates&lt;/code&gt; nie są obsługiwane - czas zatem to zmienić.
Po pierwsze do templatu musimy dorzucić elementy, które będą wyświetlały błędy walidacji.
Zmieńmy zatem opakowujący wszystko element &lt;code&gt;Grid&lt;/code&gt; na &lt;code&gt;StackPanel&lt;/code&gt;, a następnie dodajmy element typu &lt;code&gt;TextBlock&lt;/code&gt; oraz &lt;code&gt;Border&lt;/code&gt;.
Elementy wyświetlające błędy walidacji musimy umieścić w jednym kontenerze z elementami odpowiadającymi za wyświetlanie tekstu.
Zatem musimy je opakować w &lt;code&gt;Grida&lt;/code&gt;. Po zastosowaniu powyższych wskazówek nasz template będzie wyglądał w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;StackPanel&amp;gt;
...
...
...
    &amp;lt;Grid&amp;gt;
       &amp;lt;Grid.RowDefinitions&amp;gt;
           &amp;lt;RowDefinition Height=&quot;Auto&quot;&amp;gt;&amp;lt;/RowDefinition&amp;gt;
           &amp;lt;RowDefinition Height=&quot;Auto&quot;&amp;gt;&amp;lt;/RowDefinition&amp;gt;
       &amp;lt;/Grid.RowDefinitions&amp;gt;
       &amp;lt;Border x:Name=&quot;EnabledBorder&quot; BorderBrush=&quot;{TemplateBinding BorderBrush}&quot; BorderThickness=&quot;{TemplateBinding BorderThickness}&quot; Background=&quot;{TemplateBinding Background}&quot; Margin=&quot;{StaticResource PhoneTouchTargetOverhang}&quot;&amp;gt;
             &amp;lt;ContentControl x:Name=&quot;ContentElement&quot; BorderThickness=&quot;0&quot; HorizontalContentAlignment=&quot;Stretch&quot;   Padding=&quot;{TemplateBinding Padding}&quot; VerticalContentAlignment=&quot;Stretch&quot;/&amp;gt;
       &amp;lt;/Border&amp;gt;
       &amp;lt;Border x:Name=&quot;DisabledOrReadonlyBorder&quot; BorderBrush=&quot;{StaticResource PhoneDisabledBrush}&quot; BorderThickness=&quot;{TemplateBinding BorderThickness}&quot; Background=&quot;Transparent&quot; Margin=&quot;{StaticResource PhoneTouchTargetOverhang}&quot; Visibility=&quot;Collapsed&quot;&amp;gt;
          &amp;lt;TextBox x:Name=&quot;DisabledOrReadonlyContent&quot; Background=&quot;Transparent&quot; Foreground=&quot;{StaticResource PhoneDisabledBrush}&quot; FontWeight=&quot;{TemplateBinding FontWeight}&quot; FontStyle=&quot;{TemplateBinding FontStyle}&quot; FontSize=&quot;{TemplateBinding FontSize}&quot; FontFamily=&quot;{TemplateBinding FontFamily}&quot; IsReadOnly=&quot;True&quot; SelectionForeground=&quot;{TemplateBinding SelectionForeground}&quot; SelectionBackground=&quot;{TemplateBinding SelectionBackground}&quot; TextAlignment=&quot;{TemplateBinding TextAlignment}&quot; TextWrapping=&quot;{TemplateBinding TextWrapping}&quot; Text=&quot;{TemplateBinding Text}&quot; Template=&quot;{StaticResource PhoneDisabledTextBoxTemplate}&quot;/&amp;gt;
       &amp;lt;/Border&amp;gt;
       &amp;lt;Border x:Name=&quot;ValidationBorder&quot; Grid.RowSpan=&quot;2&quot; BorderBrush=&quot;Red&quot; BorderThickness=&quot;2&quot; Visibility=&quot;Collapsed&quot;  &amp;gt;
       &amp;lt;/Border&amp;gt;
       &amp;lt;TextBlock x:Name=&quot;ValidationMessage&quot; Foreground=&quot;Red&quot; FontSize=&quot;16&quot; Visibility=&quot;Collapsed&quot; Grid.Row=&quot;1&quot; Text=&quot;{Binding (Validation.Errors)[0].ErrorContent, RelativeSource={RelativeSource TemplatedParent}}&quot;  Padding=&quot;0,0,0,2&quot; Margin=&quot;10,-14,0,0&quot;  /&amp;gt;
    &amp;lt;/Grid&amp;gt;
&amp;lt;/StackPanel&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Dodanie elementów wyświetlających błędy to nie wszystko, musimy jeszcze określić kiedy nasze elementy mają być widoczne.
W chwili obecnej ich właściwość &lt;code&gt;Visibility&lt;/code&gt; jest ustawiona na &lt;code&gt;Collapsed&lt;/code&gt;.
Zatem elementy te nie będą widoczne, jak również nie będą zajmowały miejsca na interfejsie.
Jak już wcześniej wspomniałem kontrolka &lt;code&gt;TextBoxa&lt;/code&gt; w przypadku wystąpienia błędów walidacji przejdzie do stanów &lt;code&gt;InvalidFocused&lt;/code&gt; lub &lt;code&gt;InvalidUnfocused&lt;/code&gt;.
Pozostaje nam zatem zareagować na przejście kontrolki w te stany i odpowiednio zmodyfikować właściwość &lt;code&gt;Visibility&lt;/code&gt; bordera oraz textblocka.
W tym celu posłużymy się &lt;code&gt;VisualStateManagerem&lt;/code&gt; oraz animacjami. Do naszego templatu dodajmy następujący wpis&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;VisualStateGroup x:Name=&quot;ValidationStates&quot;&amp;gt;
                                &amp;lt;VisualState x:Name=&quot;Valid&quot; &amp;gt;
                                    &amp;lt;Storyboard&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Visibility&quot; Storyboard.TargetName=&quot;ValidationBorder&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;Collapsed&quot; /&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Visibility&quot; Storyboard.TargetName=&quot;ValidationMessage&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;Collapsed&quot; /&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                    &amp;lt;/Storyboard&amp;gt;
                                &amp;lt;/VisualState&amp;gt;
                                &amp;lt;VisualState x:Name=&quot;InvalidFocused&quot; &amp;gt;
                                    &amp;lt;Storyboard&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Visibility&quot; Storyboard.TargetName=&quot;ValidationBorder&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;Visible&quot; /&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Visibility&quot; Storyboard.TargetName=&quot;ValidationMessage&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;Visible&quot; /&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                    &amp;lt;/Storyboard&amp;gt;
                                &amp;lt;/VisualState&amp;gt;
                                &amp;lt;VisualState x:Name=&quot;InvalidUnfocused&quot; &amp;gt;
                                    &amp;lt;Storyboard&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Visibility&quot; Storyboard.TargetName=&quot;ValidationBorder&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;Visible&quot; /&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Visibility&quot; Storyboard.TargetName=&quot;ValidationMessage&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;Visible&quot; /&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                    &amp;lt;/Storyboard&amp;gt;
                                &amp;lt;/VisualState&amp;gt;
&amp;lt;/VisualStateGroup&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W ten oto sposób zdefiniwaliśmy w &lt;code&gt;XAML-u&lt;/code&gt; grupę (&lt;code&gt;VisualStateGroup&lt;/code&gt;) o nazwie &lt;code&gt;ValidationStates&lt;/code&gt; - zauważmy, że nazwa grupy jest taka sama jak nazwa grupy z atrybutów klasy &lt;code&gt;TextBox&lt;/code&gt;.
Dodaliśmy również trzy stany wizualne (&lt;code&gt;VisualState&lt;/code&gt;), których nazwy również odpowiadają nazwą zdefiniowanym w atrubytach klasy &lt;code&gt;TextBox&lt;/code&gt;.
Od tej chwili gdy kontrolka TextBoxa będzie posiadała błędy walidacji, zostanie odpalona animacja zmieniająca właściwość &lt;code&gt;Visibility&lt;/code&gt; bordera &lt;code&gt;ValidationBorder&lt;/code&gt; oraz &lt;code&gt;TextBlocka&lt;/code&gt; &lt;code&gt;ValidationMessage&lt;/code&gt; na &lt;code&gt;Visible&lt;/code&gt;.
Ostatecznie cały gotowy template będzie wyglądał w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;ControlTemplate x:Key=&quot;PhoneDisabledTextBoxTemplate&quot; TargetType=&quot;TextBox&quot;&amp;gt;
    &amp;lt;ContentControl x:Name=&quot;ContentElement&quot; BorderThickness=&quot;0&quot; HorizontalContentAlignment=&quot;Stretch&quot; Margin=&quot;{StaticResource PhoneTextBoxInnerMargin}&quot; Padding=&quot;{TemplateBinding Padding}&quot; VerticalContentAlignment=&quot;Stretch&quot;/&amp;gt;
    &amp;lt;/ControlTemplate&amp;gt;
    &amp;lt;Style TargetType=&quot;TextBox&quot;&amp;gt;
        &amp;lt;Setter Property=&quot;FontFamily&quot; Value=&quot;{StaticResource PhoneFontFamilyNormal}&quot;/&amp;gt;
        &amp;lt;Setter Property=&quot;FontSize&quot; Value=&quot;{StaticResource PhoneFontSizeMediumLarge}&quot;/&amp;gt;
        &amp;lt;Setter Property=&quot;Background&quot; Value=&quot;{StaticResource PhoneTextBoxBrush}&quot;/&amp;gt;
        &amp;lt;Setter Property=&quot;Foreground&quot; Value=&quot;{StaticResource PhoneTextBoxForegroundBrush}&quot;/&amp;gt;
        &amp;lt;Setter Property=&quot;BorderBrush&quot; Value=&quot;{StaticResource PhoneTextBoxBrush}&quot;/&amp;gt;
        &amp;lt;Setter Property=&quot;SelectionBackground&quot; Value=&quot;{StaticResource PhoneAccentBrush}&quot;/&amp;gt;
        &amp;lt;Setter Property=&quot;SelectionForeground&quot; Value=&quot;{StaticResource PhoneTextBoxSelectionForegroundBrush}&quot;/&amp;gt;
        &amp;lt;Setter Property=&quot;BorderThickness&quot; Value=&quot;{StaticResource PhoneBorderThickness}&quot;/&amp;gt;
        &amp;lt;Setter Property=&quot;Padding&quot; Value=&quot;2&quot;/&amp;gt;
        &amp;lt;Setter Property=&quot;Template&quot;&amp;gt;
            &amp;lt;Setter.Value&amp;gt;
                &amp;lt;ControlTemplate TargetType=&quot;TextBox&quot;&amp;gt;
                    &amp;lt;StackPanel Background=&quot;Transparent&quot;&amp;gt;
                        &amp;lt;VisualStateManager.VisualStateGroups&amp;gt;
                            &amp;lt;VisualStateGroup x:Name=&quot;CommonStates&quot;&amp;gt;
                                &amp;lt;VisualState x:Name=&quot;Normal&quot;/&amp;gt;
                                &amp;lt;VisualState x:Name=&quot;MouseOver&quot;/&amp;gt;
                                &amp;lt;VisualState x:Name=&quot;Disabled&quot;&amp;gt;
                                    &amp;lt;Storyboard&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Visibility&quot; Storyboard.TargetName=&quot;EnabledBorder&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot;&amp;gt;
                                                &amp;lt;DiscreteObjectKeyFrame.Value&amp;gt;
                                                    &amp;lt;Visibility&amp;gt;Collapsed&amp;lt;/Visibility&amp;gt;
                                                &amp;lt;/DiscreteObjectKeyFrame.Value&amp;gt;
                                            &amp;lt;/DiscreteObjectKeyFrame&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Visibility&quot; Storyboard.TargetName=&quot;DisabledOrReadonlyBorder&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot;&amp;gt;
                                                &amp;lt;DiscreteObjectKeyFrame.Value&amp;gt;
                                                    &amp;lt;Visibility&amp;gt;Visible&amp;lt;/Visibility&amp;gt;
                                                &amp;lt;/DiscreteObjectKeyFrame.Value&amp;gt;
                                            &amp;lt;/DiscreteObjectKeyFrame&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                    &amp;lt;/Storyboard&amp;gt;
                                &amp;lt;/VisualState&amp;gt;
                                &amp;lt;VisualState x:Name=&quot;ReadOnly&quot;&amp;gt;
                                    &amp;lt;Storyboard&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Visibility&quot; Storyboard.TargetName=&quot;EnabledBorder&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot;&amp;gt;
                                                &amp;lt;DiscreteObjectKeyFrame.Value&amp;gt;
                                                    &amp;lt;Visibility&amp;gt;Collapsed&amp;lt;/Visibility&amp;gt;
                                                &amp;lt;/DiscreteObjectKeyFrame.Value&amp;gt;
                                            &amp;lt;/DiscreteObjectKeyFrame&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Visibility&quot; Storyboard.TargetName=&quot;DisabledOrReadonlyBorder&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot;&amp;gt;
                                                &amp;lt;DiscreteObjectKeyFrame.Value&amp;gt;
                                                    &amp;lt;Visibility&amp;gt;Visible&amp;lt;/Visibility&amp;gt;
                                                &amp;lt;/DiscreteObjectKeyFrame.Value&amp;gt;
                                            &amp;lt;/DiscreteObjectKeyFrame&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Background&quot; Storyboard.TargetName=&quot;DisabledOrReadonlyBorder&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;{StaticResource PhoneTextBoxBrush}&quot;/&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;BorderBrush&quot; Storyboard.TargetName=&quot;DisabledOrReadonlyBorder&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;{StaticResource PhoneTextBoxBrush}&quot;/&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Foreground&quot; Storyboard.TargetName=&quot;DisabledOrReadonlyContent&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;{StaticResource PhoneTextBoxReadOnlyBrush}&quot;/&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                    &amp;lt;/Storyboard&amp;gt;
                                &amp;lt;/VisualState&amp;gt;
                            &amp;lt;/VisualStateGroup&amp;gt;
                            &amp;lt;VisualStateGroup x:Name=&quot;FocusStates&quot;&amp;gt;
                                &amp;lt;VisualState x:Name=&quot;Focused&quot;&amp;gt;
                                    &amp;lt;Storyboard&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Background&quot; Storyboard.TargetName=&quot;EnabledBorder&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;{StaticResource PhoneTextBoxEditBackgroundBrush}&quot;/&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;BorderBrush&quot; Storyboard.TargetName=&quot;EnabledBorder&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;{StaticResource PhoneTextBoxEditBorderBrush}&quot;/&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                    &amp;lt;/Storyboard&amp;gt;
                                &amp;lt;/VisualState&amp;gt;
                                &amp;lt;VisualState x:Name=&quot;Unfocused&quot;/&amp;gt;
                            &amp;lt;/VisualStateGroup&amp;gt;
                            &amp;lt;VisualStateGroup x:Name=&quot;ValidationStates&quot;&amp;gt;
                                &amp;lt;VisualState x:Name=&quot;Valid&quot; &amp;gt;
                                    &amp;lt;Storyboard&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Visibility&quot; Storyboard.TargetName=&quot;ValidationBorder&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;Collapsed&quot; /&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Visibility&quot; Storyboard.TargetName=&quot;ValidationMessage&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;Collapsed&quot; /&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                    &amp;lt;/Storyboard&amp;gt;
                                &amp;lt;/VisualState&amp;gt;
                                &amp;lt;VisualState x:Name=&quot;InvalidFocused&quot; &amp;gt;
                                    &amp;lt;Storyboard&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Visibility&quot; Storyboard.TargetName=&quot;ValidationBorder&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;Visible&quot; /&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Visibility&quot; Storyboard.TargetName=&quot;ValidationMessage&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;Visible&quot; /&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                    &amp;lt;/Storyboard&amp;gt;
                                &amp;lt;/VisualState&amp;gt;
                                &amp;lt;VisualState x:Name=&quot;InvalidUnfocused&quot; &amp;gt;
                                    &amp;lt;Storyboard&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Visibility&quot; Storyboard.TargetName=&quot;ValidationBorder&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;Visible&quot; /&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                        &amp;lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty=&quot;Visibility&quot; Storyboard.TargetName=&quot;ValidationMessage&quot;&amp;gt;
                                            &amp;lt;DiscreteObjectKeyFrame KeyTime=&quot;0&quot; Value=&quot;Visible&quot; /&amp;gt;
                                        &amp;lt;/ObjectAnimationUsingKeyFrames&amp;gt;
                                    &amp;lt;/Storyboard&amp;gt;
                                &amp;lt;/VisualState&amp;gt;
                            &amp;lt;/VisualStateGroup&amp;gt;
                        &amp;lt;/VisualStateManager.VisualStateGroups&amp;gt;
                        &amp;lt;Grid&amp;gt;
                            &amp;lt;Grid.RowDefinitions&amp;gt;
                                &amp;lt;RowDefinition Height=&quot;Auto&quot;&amp;gt;&amp;lt;/RowDefinition&amp;gt;
                                &amp;lt;RowDefinition Height=&quot;Auto&quot;&amp;gt;&amp;lt;/RowDefinition&amp;gt;
                            &amp;lt;/Grid.RowDefinitions&amp;gt;
                            &amp;lt;Border x:Name=&quot;EnabledBorder&quot; BorderBrush=&quot;{TemplateBinding BorderBrush}&quot; BorderThickness=&quot;{TemplateBinding BorderThickness}&quot; Background=&quot;{TemplateBinding Background}&quot; Margin=&quot;{StaticResource PhoneTouchTargetOverhang}&quot;&amp;gt;
                                &amp;lt;ContentControl x:Name=&quot;ContentElement&quot; BorderThickness=&quot;0&quot; HorizontalContentAlignment=&quot;Stretch&quot;   Padding=&quot;{TemplateBinding Padding}&quot; VerticalContentAlignment=&quot;Stretch&quot;/&amp;gt;
                            &amp;lt;/Border&amp;gt;
                            &amp;lt;Border x:Name=&quot;DisabledOrReadonlyBorder&quot; BorderBrush=&quot;{StaticResource PhoneDisabledBrush}&quot; BorderThickness=&quot;{TemplateBinding BorderThickness}&quot; Background=&quot;Transparent&quot; Margin=&quot;{StaticResource PhoneTouchTargetOverhang}&quot; Visibility=&quot;Collapsed&quot;&amp;gt;
                                &amp;lt;TextBox x:Name=&quot;DisabledOrReadonlyContent&quot; Background=&quot;Transparent&quot; Foreground=&quot;{StaticResource PhoneDisabledBrush}&quot; FontWeight=&quot;{TemplateBinding FontWeight}&quot; FontStyle=&quot;{TemplateBinding FontStyle}&quot; FontSize=&quot;{TemplateBinding FontSize}&quot; FontFamily=&quot;{TemplateBinding FontFamily}&quot; IsReadOnly=&quot;True&quot; SelectionForeground=&quot;{TemplateBinding SelectionForeground}&quot; SelectionBackground=&quot;{TemplateBinding SelectionBackground}&quot; TextAlignment=&quot;{TemplateBinding TextAlignment}&quot; TextWrapping=&quot;{TemplateBinding TextWrapping}&quot; Text=&quot;{TemplateBinding Text}&quot; Template=&quot;{StaticResource PhoneDisabledTextBoxTemplate}&quot;/&amp;gt;
                            &amp;lt;/Border&amp;gt;
                            &amp;lt;Border x:Name=&quot;ValidationBorder&quot; Grid.RowSpan=&quot;2&quot; BorderBrush=&quot;Red&quot; BorderThickness=&quot;2&quot; Visibility=&quot;Collapsed&quot;  &amp;gt;
                            &amp;lt;/Border&amp;gt;
                            &amp;lt;TextBlock x:Name=&quot;ValidationMessage&quot; Foreground=&quot;Red&quot; FontSize=&quot;16&quot; Visibility=&quot;Collapsed&quot; Grid.Row=&quot;1&quot; Text=&quot;{Binding (Validation.Errors)[0].ErrorContent, RelativeSource={RelativeSource TemplatedParent}}&quot;  Padding=&quot;0,0,0,2&quot; Margin=&quot;10,-14,0,0&quot;  /&amp;gt;

                        &amp;lt;/Grid&amp;gt;

                    &amp;lt;/StackPanel&amp;gt;
                &amp;lt;/ControlTemplate&amp;gt;
            &amp;lt;/Setter.Value&amp;gt;
        &amp;lt;/Setter&amp;gt;
    &amp;lt;/Style&amp;gt;
&amp;lt;/ControlTemplate&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Tak natomiast przedstawiają się błędy walidacji wyświetlone na &lt;code&gt;TextBoxach&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/06/windows-phone-wyswietlanie-bledow-walidacji/result.jpg&quot;&gt;&lt;img src=&quot;images/result.jpg&quot; alt=&quot;wyświetlanie błędów walidacji&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Tworzenie bootstrappera aplikacji przy użyciu CaliburnMicro</title><link>https://tpodolak.com/blog/tworzenie-bootstrappera-aplikacji-przy-uzyciu-caliburnmicro/</link><guid isPermaLink="true">https://tpodolak.com/blog/tworzenie-bootstrappera-aplikacji-przy-uzyciu-caliburnmicro/</guid><pubDate>Mon, 07 May 2012 19:24:00 GMT</pubDate><content:encoded>&lt;p&gt;Witam po długiej przerwie. W dzisiejszym wpisie postaram się krótko opisać w jaki sposób stworzyć bootstrapper aplikacji przy użyciu &lt;code&gt;CaliburnMicro&lt;/code&gt;.
Ponadto przedstawię w jaki sposób skonfigurować bootstrapper w taki sposób, aby &lt;code&gt;Caliburn&lt;/code&gt; wykorzystywał nasz własny kontener &lt;code&gt;IOC&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;1. Wstęp&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;CaliburnMicro&lt;/code&gt; jest to framework &lt;code&gt;MVVM&lt;/code&gt;, który w znacznym stopniu ułatwia i przyśpiesza pisanie aplikacji pod &lt;code&gt;WPF&lt;/code&gt;,&lt;code&gt;Silverlight&lt;/code&gt;,&lt;code&gt;WindowsPhone&lt;/code&gt; oraz &lt;code&gt;WinRT&lt;/code&gt;.
Zdecydowałem się poznać ten framework z uwagi na jego przenośność na różne platformy.
Wcześniej całkiem sporo czasu poświęciłem &lt;code&gt;Prismowi&lt;/code&gt;, jednakże z powodu licznych problemów z jego działaniem pod &lt;code&gt;WindowsPhonem&lt;/code&gt; chciałem spróbować czegoś nowego.&lt;/p&gt;
&lt;h3&gt;2. Bootstrapper - Silverlight&lt;/h3&gt;
&lt;p&gt;Bootstrapper jest to ogólnie rzecz biorąc klasa inicjalizująca całą aplikację.
W trakcie odpalania bootstrappera na ogół konfiguruje się kontener &lt;code&gt;IOC&lt;/code&gt;(rejestruje wszystkie potrzebne typu), inicjalizuje się połączenie z serverem, oraz odpala się główne okno aplikacji - tzw. &lt;code&gt;Shella&lt;/code&gt;.
Dlatego też musimy odchudzić plik &lt;code&gt;App.xaml.cs&lt;/code&gt; i zostawić w nim jedynie konstruktor wraz z wywołaniem funkcji &lt;code&gt;InitializeComponents&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public partial class App : Application
{
    public App()
    {          
        InitializeComponent();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Zacznijmy od utworzenia nowego projektu typu &lt;code&gt;SilverlightApplication&lt;/code&gt;, do którego dodajemy referencje do dll-ek &lt;code&gt;Cliburna&lt;/code&gt;.
Możemy to zrobić poprzez &lt;code&gt;NuGetta&lt;/code&gt; (niestety u mnie one nie działały :D), jak również możemy je ściągnąć z oficjalnej strony &lt;a href=&quot;http://caliburnmicro.codeplex.com/releases/view/81466&quot;&gt;projektu&lt;/a&gt;.
Następnie stwórzmy główne okno aplikacji(wspomnianego wcześniej &lt;code&gt;Shella&lt;/code&gt;) oraz jego &lt;code&gt;viewmodel&lt;/code&gt;.
W tym celu dodajemy do projektu &lt;code&gt;Silverlight User Control&lt;/code&gt; o nazwie &lt;code&gt;ShellView&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/05/tworzenie-bootstrappera-aplikacji-przy-uzyciu-caliburnmicro/ShellView.jpg&quot;&gt;&lt;img src=&quot;images/ShellView.jpg&quot; alt=&quot;ShellView&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;oraz nową klasę &lt;code&gt;ShellViewModel&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/05/tworzenie-bootstrappera-aplikacji-przy-uzyciu-caliburnmicro/ShellViewModel.jpg&quot;&gt;&lt;img src=&quot;images/ShellViewModel.jpg&quot; alt=&quot;ShellViewModel&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Dorzućmy jeszcze jakiegoś &lt;code&gt;TextBox-a&lt;/code&gt; do naszego &lt;code&gt;ShellView&lt;/code&gt;, tak aby mieć pewność, że rzeczywiście odpowiednie okno jest widoczne przy starcie aplikacji&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;UserControl x:Class=&quot;Loginv2.ShellView&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
    xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
             xmlns:cal=&quot;clr-namespace:Caliburn.Micro;assembly=Caliburn.Micro&quot; mc:Ignorable=&quot;d&quot; Height=&quot;516&quot; Width=&quot;792&quot;&amp;gt;

    &amp;lt;Grid x:Name=&quot;LayoutRoot&quot;  &amp;gt;
        &amp;lt;TextBox Text=&quot;oto jest shell&quot;/&amp;gt;
    &amp;lt;/Grid&amp;gt;
&amp;lt;/UserControl&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W kolejnym kroku musimy stworzyć właściwy bootstrapper - dodajmy nową klasę o nazwie &lt;code&gt;SilverlightBootstrapper&lt;/code&gt;, która dziedziczyć będzie po klasie &lt;code&gt;Bootstrapper&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;namespace Client.Silverlight
{
    public class SilverlightBootstrapper : Bootstrapper&amp;lt;ShellViewModel&amp;gt;
    {
    
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Klasa &lt;code&gt;Bootstrapper&lt;/code&gt; jest to klasa dostarczona przez &lt;code&gt;CaliburnMicro&lt;/code&gt;, generyczny parametr &lt;code&gt;T&lt;/code&gt; określa nam &lt;code&gt;viewmodel&lt;/code&gt; na podstawie którego framework będzie wyszukiwał odpowiedni widok &lt;code&gt;shella&lt;/code&gt; ze swojego wbudowanego kontenera &lt;code&gt;IOC&lt;/code&gt; (&lt;code&gt;Caliburn&lt;/code&gt; podczas uruchomienia aplikacji rejestruje dostępne typu w kontenerze).
Zgodnie z domyślną konwencją, &lt;code&gt;CaliburnMicro&lt;/code&gt; jako główne okno aplikacji ustawi widok, który nazywać się będzie &lt;code&gt;ShellView&lt;/code&gt;.
W celu odpalenia naszego &lt;code&gt;bootstrappera&lt;/code&gt; musimy jeszcze umieścić go w zasobach aplikacji.
Zmodyfikujmy zatem plik &lt;code&gt;App.xaml&lt;/code&gt; aby wyglądał w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Application xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
             xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
             xmlns:Silverlight=&quot;clr-namespace:Client.Silverlight&quot; x:Class=&quot;Client.Silverlight.App&quot;&amp;gt;
    &amp;lt;Application.Resources&amp;gt;
        &amp;lt;Silverlight:SilverlightBootstrapper x:Key=&quot;Bootstrapper&quot;&amp;gt;&amp;lt;/Silverlight:SilverlightBootstrapper&amp;gt;
    &amp;lt;/Application.Resources&amp;gt;
&amp;lt;/Application&amp;gt;

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Kompilując, a następnie uruchamiając nasz projekt naszym oczom powinien ukazać się następujący widok&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/05/tworzenie-bootstrappera-aplikacji-przy-uzyciu-caliburnmicro/Client.Silverlight.jpg&quot;&gt;&lt;img src=&quot;images/Client.Silverlight.jpg&quot; alt=&quot;Client.Silverlight&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Powyżej przedstawiłem w jaki sposób stworzyć najprostszą wersję bootstrapera z wykorzystaniem &lt;code&gt;CaliburnMicro&lt;/code&gt; oraz jego domyślnego kontenera &lt;code&gt;IOC&lt;/code&gt;.
Jednakże najczęściej jest tak, że w aplikacji wykorzystujemy już jakiś bardziej zaawansowany kontener i po prostu nie chcemy wykorzystywać jednego kontenera do &quot;rozwiązywania&quot; widoków, a drugiego do pozostałych rzeczy.
Dlatego też pokaże teraz w jaki sposób skonfigurować napisany wcześniej bootstrapper tak aby widoki były wyciągane z naszego kontenera &lt;code&gt;IOC&lt;/code&gt;.
Zacznijmy do dodania do naszego projektu referencji do &lt;code&gt;NInjecta&lt;/code&gt;, a następnie utwórzmy klasę &lt;code&gt;IOCContainer&lt;/code&gt; (będącą naszym customowym kontenerem), wyglądającą w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class IOCContainer
{
    private static readonly IKernel Kernel = new StandardKernel();

    protected IOCContainer()
    {

    }

    public static void Dispose()
    {
        Kernel.Dispose();
    }

    public static object Get(Type type)
    {
        return Kernel.Get(type);
    }

    public static object Get(Type type,string key)
    {
        return Kernel.Get(type, key);
    }
  
    public static IEnumerable&amp;lt;object&amp;gt;  GetAll(Type instanceType)
    {
        return Kernel.GetAll(instanceType);
    }
  
    public static void Bind&amp;lt;T, TS&amp;gt;() where TS : T
    {
        Kernel.Bind&amp;lt;T&amp;gt;().To&amp;lt;TS&amp;gt;();
    } 
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Następnie w klasie &lt;code&gt;SilverlightBootstraper&lt;/code&gt; musimy przeciążyć funkcję &lt;code&gt;Configure&lt;/code&gt;, &lt;code&gt;GetAllInstances&lt;/code&gt; oraz &lt;code&gt;GetInstance&lt;/code&gt;.
Jako, że będziemy korzystali z naszego własnego kontenera w funkcji &lt;code&gt;Configure&lt;/code&gt; rejestrujemy wszystkie potrzebne nam &lt;code&gt;viewmodele&lt;/code&gt; oraz widoki.
Zatem funkcja &lt;code&gt;Configure&lt;/code&gt; powinna od teraz wyglądać tak&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;protected override void Configure()
{
    IOCContainer.Bind&amp;lt;ShellView, ShellView&amp;gt;();
    IOCContainer.Bind&amp;lt;ShellViewModel, ShellViewModel&amp;gt;();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Następnie musimy &quot;pokazać&quot; &lt;code&gt;Caliburn-owi&lt;/code&gt; gdzie powinien szukać widoków.
Dlatego też przeciążamy funkcje &lt;code&gt;GetInstance&lt;/code&gt; oraz &lt;code&gt;GetAllInstances&lt;/code&gt; i zmieniamy ich postać na następującą&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;protected override object GetInstance(Type serviceType, string key)
{
    return IOCContainer.Get(serviceType, key);
}

protected override IEnumerable&amp;lt;object&amp;gt; GetAllInstances(Type serviceType)
{
    return IOCContainer.GetAll(serviceType);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Od tej pory, za każdym razem gdy użyjemy mechanizmów &lt;code&gt;Caliburna&lt;/code&gt; do bindowania viewmodelu z widokiem itp., &lt;code&gt;Caliburm&lt;/code&gt; będzie szukał widoków oraz viewmodeli w naszym kontenerze &lt;code&gt;IOC&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;2.2 Własna konwencja wyszukiwania widoków&lt;/h3&gt;
&lt;p&gt;W przedstawionym powyżej przykładzie bootstrappera, nasz bootstrapper korzystał z domyślnej konwencji rozwiązywania widoków na podstawie viewmodeli (do &lt;code&gt;ShellViewModel&lt;/code&gt; został dopasowany widok &lt;code&gt;ShellView&lt;/code&gt;).
Czasem jednak konwencja ta, nie pasuje do konwencji przyjętej w danym projekcie.
Sam biorę udział w projekcie, w którym widoki w kontenerze są rejestrowane następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;IOCContainer.Bind&amp;lt;IView&amp;lt;ViewModel&amp;gt;, View&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Czy zatem oznacza to, że nie mogę korzystać już mechanizmów &lt;code&gt;Caliburna&lt;/code&gt; i musze zrezygnować chociażby z bootstrappera? Oczywiście, że nie.
Framework dostarcza nam możliwość zdefiniowania własnej konwencji wyszukiwania widoków na podstawie viewmodeli.
W celu zastąpienia domyślnej konwencji musimy podpiąć się pod propercję &lt;code&gt;LocateForModelType&lt;/code&gt; znajdującą się w klasie &lt;code&gt;ViewLocator&lt;/code&gt; i zdefiniować własną funkcję wyszukującą widok na podstawie viewmodelu.
W moim przypadku wygląda to w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ViewLocator.LocateForModelType = (modelType, displayLocation, context) =&amp;gt;
                                                 {
                                                     string viewTypeName = string.Format(&quot;{0}[[{1}]],{2}&quot;, typeof(IView&amp;lt;&amp;gt;).FullName, modelType.AssemblyQualifiedName, typeof(IView&amp;lt;&amp;gt;).Assembly.FullName);
                                                     Type viewType = Type.GetType(viewTypeName);
                                                     if (viewType == null)
                                                         throw new ArgumentNullException(string.Format(&quot;Nie odnaleziono typu widoku dla viewModelu&quot;), modelType.FullName);

                                                     return ViewLocator.GetOrCreateViewType(viewType);
                                                 };
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Funkcja &lt;code&gt;ViewLocator.LocateForModelType&lt;/code&gt; odpalana jest za każdym razem, gdy &lt;code&gt;CaliburnMicro&lt;/code&gt; chce wyszukać widok na podstawie viewmodleu.
Najważniejszym argumentem funkcji &lt;code&gt;LocateForModelType&lt;/code&gt; jest &lt;code&gt;modelType&lt;/code&gt; - czyli typ viewmodelu, który posłuży nam do znalezienia widoku - a właściwie jego typu.
Po odnalezieniu typu widoku, wywołujemy funkcję &lt;code&gt;ViewLocator.GetOrCreateViewType(viewType);&lt;/code&gt; (które z kolei znajdzie nam w kontenerze pożądanym przez nas typ widoku) i zwracamy jej rezultat.&lt;/p&gt;
&lt;h3&gt;3. Bootstrapper - Windows Phone&lt;/h3&gt;
&lt;p&gt;W przypadku bootstrappera dla &lt;code&gt;Windows Phona&lt;/code&gt; sytuacja wygląda odrobinę inaczej.
W celu utworzenia własnego bootstrappera musimy rozszerzyć klasę &lt;code&gt;PhoneBootstrapper&lt;/code&gt;.
Utwórzmy zatem nowy projekt typu &lt;code&gt;Windows Phone Application&lt;/code&gt;, oraz dodajmy do niego nową kontrolkę typu &lt;code&gt;Windows Phone Portrait Page&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a&gt;&lt;img src=&quot;images/ShellViewPortrait.jpg&quot; alt=&quot;ShellViewPortrait&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Podobnie jak w przypadku projektu &lt;code&gt;Silverlightowego&lt;/code&gt; dodajemy referencję do &lt;code&gt;CaliburnMicro&lt;/code&gt;, dorzucamy klasę viewmodelu (którą nazywamy &lt;code&gt;ShellViewModel&lt;/code&gt;) oraz dodajemy jakiegoś textboxa do &lt;code&gt;ShellView&lt;/code&gt;.
Następnie musimy utworzyć nasz bootstrapper, dodajmy zatem klasę &lt;code&gt;WindowsPhoneBootstrapper&lt;/code&gt; rozszerzającą klasę &lt;code&gt;PhoneBootstrapper&lt;/code&gt;.
Podobnie jak w przypadku bootstrappera silverlightowego przeciążamy funkcje odpowiedzialne za konfigurację kontenera &lt;code&gt;IOC&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class WindowsPhoneBootstrapper : PhoneBootstrapper
{
    protected override void Configure()
    {
      
       IOCContainer.BindToConstant&amp;lt;INavigationService&amp;gt;(new FrameAdapter(RootFrame));
       IOCContainer.BindToConstant&amp;lt;IPhoneService&amp;gt;(new PhoneApplicationServiceAdapter(RootFrame));
       IOCContainer.BindAsSingleton&amp;lt;ShellViewModel, ShellViewModel&amp;gt;();
    }

    protected override void OnExit(object sender, EventArgs e)
    {
        IOCContainer.Dispose();
        base.OnExit(sender, e);
    }

    protected override object GetInstance(Type serviceType, string key)
    {
        return IOCContainer.Get(serviceType, key);
    }

    protected override IEnumerable&amp;lt;object&amp;gt; GetAllInstances(Type serviceType)
    {
        return IOCContainer.GetAll(serviceType);
    }

    protected override void BuildUp(object instance)
    {
        IOCContainer.Inject(instance);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Zwróćmy uwagę, że w kontenerze &lt;code&gt;IOC&lt;/code&gt; zostały zarejestrowane usługi nawigacji &lt;code&gt;Windows Phona&lt;/code&gt;, do których został przekazany &lt;code&gt;RootFrame&lt;/code&gt;.
&lt;code&gt;RootFrame&lt;/code&gt; jest to główne okno aplikacji, zostaje ono utworzone przez &lt;code&gt;CliburnMicro&lt;/code&gt;.
Tak samo jak w przypadku projektu &lt;code&gt;Silverlightowego&lt;/code&gt; w pliku &lt;code&gt;App.xaml.cs&lt;/code&gt; zostawiamy jedynie konstruktor z wywołaniem funkcji &lt;code&gt;InitializeComponents&lt;/code&gt;.
W celu ustawienia &lt;code&gt;ShellView&lt;/code&gt; jako &lt;code&gt;RootFram-a&lt;/code&gt; musimy zmodyfikować plik &lt;code&gt;WMAppManifest.xml&lt;/code&gt; (znajdujący się w katalogu &lt;code&gt;Properties&lt;/code&gt;).
Odnajdujemy tam wpis&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;DefaultTask  Name =&quot;_default&quot; NavigationPage=&quot;MainPage.xaml&quot;/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;i zamieniamy go na&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;DefaultTask  Name =&quot;_default&quot; NavigationPage=&quot;ShellView.xaml&quot;/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Jak widać &lt;code&gt;WindowsPhone&lt;/code&gt; wymusza tutaj podejście &lt;code&gt;ViewFirst&lt;/code&gt;.
Przy uruchomieniu aplikacji mechanizm nawigacji &lt;code&gt;WindowsPhona&lt;/code&gt; odpali widok &lt;code&gt;ShellView&lt;/code&gt; (bez wiedzy Caliburn&apos;a), natomiast &lt;code&gt;CaliburnMicro&lt;/code&gt; dopasuje odpowiedni &lt;code&gt;ViewModel&lt;/code&gt;
do naszego widoku - na podstawie domyślnej konwencji.
Jeżeli chcielibyśmy zmodyfikować sposób wyszukiwania &lt;code&gt;ViewModeli&lt;/code&gt; do widoków musimy podpiąć się do propertisa &lt;code&gt;LocateForViewType&lt;/code&gt; znajdującego się w klasie &lt;code&gt;ViewModelLocator&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ViewModelLocator.LocateForViewType = type =&amp;gt; { return //tutaj zwroc odpowiedni viewmodel na podstawie parametru type; };
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W ostatnim kroku musimy jeszcze tylko dodać nasz bootstrapper do zasobów aplikacji&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Application.Resources&amp;gt;
        &amp;lt;Bootstrapper:WindowsPhoneBootstrapper x:Key=&quot;Bootstrapper&quot;&amp;gt;&amp;lt;/Bootstrapper:WindowsPhoneBootstrapper&amp;gt;
&amp;lt;/Application.Resources&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;odpalając teraz program naszym oczom powinien ukazać się taki oto widok&lt;/p&gt;
&lt;p&gt;&lt;a&gt;&lt;img src=&quot;images/ShellViewEmulator.jpg&quot; alt=&quot;ShellViewEmulator&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>FluentNhibernate - mapowanie kolumn typu time</title><link>https://tpodolak.com/blog/fluentnhibernate-mapowanie-kolumn-typu-time/</link><guid isPermaLink="true">https://tpodolak.com/blog/fluentnhibernate-mapowanie-kolumn-typu-time/</guid><pubDate>Tue, 13 Mar 2012 21:36:00 GMT</pubDate><content:encoded>&lt;p&gt;Ostatnio napotkałem na dość ciekawy wyjątek podczas wykonywania &lt;code&gt;NHibernatowego&lt;/code&gt; inserta. W bazie danych mam prostą tabelę&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/03/fluentnhibernate-mapowanie-kolumn-typu-time/Table.jpg&quot;&gt;&lt;img src=&quot;images/Table.jpg&quot; alt=&quot;Table&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Do takiej tabeli został stworzony model&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;namespace Model
{
    public class Appointment
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual DateTime StartDate { get; set; }
        public virtual TimeSpan Duration { get; set; }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;oraz mapping&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;namespace Model.Mappings
{
    public class AppointmentMapping : ClassMap&amp;lt;Appointment&amp;gt;
    {
        public AppointmentMapping()
        {
            Id(val =&amp;gt; val.Id).GeneratedBy.Native();
            Map(val =&amp;gt; val.Name).Not.Nullable();
            Map(val =&amp;gt; val.StartDate).Not.Nullable();
            Map(val =&amp;gt; val.Duration).Not.Nullable();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Niestety ku mojemu zaskoczeniu próbując zapisać do bazy obiekt typu &lt;code&gt;Appointment&lt;/code&gt; dostałem następujący wyjątek &lt;code&gt;SqlException: Operand type clash: bigint is incompatible with time&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/03/fluentnhibernate-mapowanie-kolumn-typu-time/Exception.jpg&quot;&gt;&lt;img src=&quot;images/Exception-1024x358.jpg&quot; alt=&quot;Exception&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Mówiąc szczerze wyjątek ten niewiele mi powiedział, zwłaszcza, że zapytanie wygenerowane przez &lt;code&gt;NHibernata&lt;/code&gt; (przechwycone w &lt;code&gt;NHibernateProfilerze&lt;/code&gt;) wyglądało jak najbardziej poprawnie.
Jednakże zapytanie przechwycone przez &lt;code&gt;SqlProfilera&lt;/code&gt; wyglądało w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;exec sp_executesql N&apos;INSERT INTO [Appointment] (Name,StartDate,Duration) VALUES (@p0,@p1,@p2); 
select SCOPE_IDENTITY()&apos;,
N&apos;@p0 nvarchar(4000),
@p1 datetime,
@p2 bigint&apos;,
@p0=N&apos;appoitnemt&apos;,
@p1=&apos;2012-03-13 00:00:00&apos;,
@p2=439320000000
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Widać tutaj, że drugi parametr &lt;code&gt;(@p2)&lt;/code&gt; został oznaczony jako &lt;code&gt;bigint&lt;/code&gt;, a nie &lt;code&gt;time&lt;/code&gt; (tak jak jest to oznaczone w bazie).
Przyczyną takiego stanu rzeczy jest zły mapping. Z tego co wyczytałem, jeżeli chcemy aby poprawnie zmapować &lt;code&gt;TimeSpana&lt;/code&gt; na kolumnę typu &lt;code&gt;time&lt;/code&gt;,
musimy zmodyfikować interesujący nas mapping na następujący.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Map(val =&amp;gt; val.Duration).Not.Nullable().CustomType(&quot;TimeAsTimeSpan&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Mając taki mapping nasze zapytanie zostanie wygenerowane poprawnie i operacja insertu zakończy się powodzeniem&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/03/fluentnhibernate-mapowanie-kolumn-typu-time/Result.jpg&quot;&gt;&lt;img src=&quot;images/Result.jpg&quot; alt=&quot;FluentNhibernate&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Definiowanie własnego operatora rzutowania</title><link>https://tpodolak.com/blog/definiowanie-wlasnego-operatora-rzutowania/</link><guid isPermaLink="true">https://tpodolak.com/blog/definiowanie-wlasnego-operatora-rzutowania/</guid><pubDate>Sun, 26 Feb 2012 21:54:00 GMT</pubDate><content:encoded>&lt;p&gt;Ostatnio modyfikując mój kod stanąłem przed problemem rzutowania obiektu typu &lt;code&gt;MembershipUser&lt;/code&gt;(z namespaca &lt;code&gt;System.Web.Security&lt;/code&gt;) na mój własny typ &lt;code&gt;UserDTO&lt;/code&gt;.
Klasa UserDTO nie wyróżnia się niczym specjalnym i wygląda następująco&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class UserDTO : UserBase
{
    public string Id { get; set; }

    public string Email { get; set; }

    public string DisplayName { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Podejściem dość oczywistym w takim przypadku jest utworzenie odpowiedniego konstruktora w klasie &lt;code&gt;UserDTO&lt;/code&gt;, przyjmującego jako parametr obiekt typu &lt;code&gt;MembershipUser&lt;/code&gt;.
Jednakże można również utworzyć własny operator rzutowania, dzięki któremu zapis&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; 
MembershipUser user = new MembershipUser(/*jakies parametry*/);
UserDTO dtoUser = (UserDTO) user;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;będzie poprawny. Wszystko sprowadza się do użycia dwóch słów kluczowych:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;operator&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;explicit&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;W klasie &lt;code&gt;UserDTO&lt;/code&gt; musimy dopisać następujący kod&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static explicit operator UserDTO(MembershipUser user)
{
    if (user == null)
        throw new ApplicationException(&quot;Parametr user nie może być null-em&quot;);

    return new UserDTO {   
                          Id = user.ProviderUserKey is Guid ? ((Guid)user.ProviderUserKey).ToString() : user.ProviderUserKey.ToString(),
                          Name = user.UserName,
                          Email = user.Email,
                       };
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Jak widać tworzymy nowy operator konwersji, w którym po prawej stronie wyrażenia musi stać obiekt typu &lt;code&gt;MembershipUser&lt;/code&gt;.
Od teraz za każdym razem gdy będziemy chcieli rzutować obiekt &lt;code&gt;MembershipUser&lt;/code&gt; na &lt;code&gt;UserDTO&lt;/code&gt; będziemy mogli posłużyć się następującą konstrukcją.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;UserDTO dtoUser = (UserDTO) membershipUser;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Rzutowanie z &lt;code&gt;UserDTO&lt;/code&gt; na &lt;code&gt;MembershipUser&lt;/code&gt; nie jest dozwolone (przy wykorzystaniu wyżej wymienionego kodu), ale nic nie stoi na przeszkodzie aby zdefiniować drugi operator rzutowania&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static explicit operator MembershipUser(UserDTO userDto)
{
    //tutaj odpowiedni kod
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;który zapewni nam konwersję odwrotną&lt;/p&gt;
</content:encoded></item><item><title>ASP.NET MVC - okna modalne z wykorzystaniem Kendo UI</title><link>https://tpodolak.com/blog/asp-net-mvc-okna-modalne-z-wykorzystaniem-kendo-ui/</link><guid isPermaLink="true">https://tpodolak.com/blog/asp-net-mvc-okna-modalne-z-wykorzystaniem-kendo-ui/</guid><pubDate>Sat, 04 Feb 2012 22:39:00 GMT</pubDate><content:encoded>&lt;p&gt;Ostatnimi czasy w pracy eksperymentujemy z &lt;code&gt;ASP.NET MVC&lt;/code&gt;. Jednym z problemów na jakie natknąłem się poznając tą technologię było utworzenie okien modalnych.
Po niezbyt owocnej walce z kontrolkami ze stajni Devexpressa postanowiliśmy, że skorzystamy z darmowej biblioteki &lt;code&gt;Kendo UI&lt;/code&gt; napisanej w &lt;code&gt;jQuery&lt;/code&gt;.
Wspomnianą wcześniej bibliotekę możemy znaleźć pod adresem http://www.kendoui.com/get-kendo-ui.aspx.
Aby uzyskać dostęp do plików należy zarejestrować się w systemie - oczywiście rejestracja jest darmowa.
Po zassaniu wszystkich plików kopiujemy zawartość katalogu &quot;source&quot; do naszego projektu &lt;code&gt;MVC&lt;/code&gt;.
W moim przypadku utworzyłem katalog &lt;code&gt;Kendo&lt;/code&gt; w katalogu &lt;code&gt;Content&lt;/code&gt; i tam umieściłem zawartość katalogu &lt;code&gt;source&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/02/asp-net-mvc-okna-modalne-z-wykorzystaniem-kendo-ui/Structure.jpg&quot;&gt;&lt;img src=&quot;images/Structure.jpg&quot; alt=&quot;Structure&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Mając wszystkie pliki w komplecie musimy wskazać naszej aplikacji aby zaczęła z nich korzystać.
Dodajmy zatem w pliku &lt;code&gt;_Layout.cshtml&lt;/code&gt; następujące elementy&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;script src=&quot;@Url.Content(&quot;~/Content/Kendo/js/jquery.min.js&quot;)&quot; type=&quot;text/javascript&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;link href=&quot;@Url.Content(&quot;~/Content/Site.css&quot;)&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&amp;gt;
&amp;lt;link href=&quot;@Url.Content(&quot;~/Content/Kendo/styles/kendo.common.css&quot;)&quot; rel=&quot;stylesheet&quot;/&amp;gt;
&amp;lt;link href=&quot;@Url.Content(&quot;~/Content/Kendo/styles/kendo.default.css&quot;)&quot; rel=&quot;stylesheet&quot;/&amp;gt;
&amp;lt;script src=&quot;@Url.Content(&quot;~/Scripts/jquery-1.5.1.min.js&quot;)&quot; type=&quot;text/javascript&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src=&quot;@Url.Content(&quot;~/Content/Kendo/js/jquery.min.js&quot;)&quot; type=&quot;text/javascript&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src=&quot;@Url.Content(&quot;~/Content/Kendo/js/kendo.core.js&quot;)&quot; type=&quot;text/javascript&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src=&quot;@Url.Content(&quot;~/Content/Kendo/js/kendo.data.js&quot;)&quot; type=&quot;text/javascript&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src=&quot;@Url.Content(&quot;~/Content/Kendo/js/kendo.pager.js&quot;)&quot; type=&quot;text/javascript&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src=&quot;@Url.Content(&quot;~/Content/Kendo/js/kendo.selectable.js&quot;)&quot; type=&quot;text/javascript&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src=&quot;@Url.Content(&quot;~/Content/Kendo/js/kendo.draganddrop.js&quot;)&quot; type=&quot;text/javascript&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src=&quot;@Url.Content(&quot;~/Content/Kendo/js/kendo.groupable.js&quot;)&quot; type=&quot;text/javascript&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src=&quot;@Url.Content(&quot;~/Content/Kendo/js/kendo.grid.js&quot;)&quot; type=&quot;text/javascript&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src=&quot;@Url.Content(&quot;~/Content/Kendo/js/kendo.fx.js&quot;)&quot; type=&quot;text/javascript&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src=&quot;@Url.Content(&quot;~/Content/Kendo/js/kendo.resizable.js&quot;)&quot; type=&quot;text/javascript&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src=&quot;@Url.Content(&quot;~/Content/Kendo/js/kendo.window.js&quot;)&quot; type=&quot;text/javascript&quot;&amp;gt;&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Przejdźmy teraz do najważniejszej części, a mianowicie do tworzenia okna modalnego.
Biblioteka &lt;code&gt;Kendo UI&lt;/code&gt; udostępnia nam funkcję &lt;code&gt;kendoWindow&lt;/code&gt;, dzięki której jesteśmy w stanie utworzyć okno modalne.
Okno to jednak nie ma w sobie żadnej zawartości - nie posiada nawet przycisków typu &lt;code&gt;Zapisz&lt;/code&gt; oraz &lt;code&gt;Anuluj&lt;/code&gt;.
Utworzenie i załadowanie zawartości okna oraz reakcja na kliknięcia w potencjalne przyciski musi zostać obsłużona przez nas.
Zacznijmy zatem od utworzenia zawartości okna.
Załóżmy, że okno, które za chwilę stworzymy będzie służyło do dodawania nowego produktu do bazy danych.
Klasa produkt jest bardzo prostą klasą prezentującą się w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Product
{
    public string Id { get; set; }
    public string Name { get; set; }
    public int Quantity { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Stwórzmy zatem strongly-typed partial view, który będzie zawartością naszego okna modalnego.
Widok ten będzie posiadał dwa textboxy do wypełniania propertisów obiektu, oraz przyciski &lt;code&gt;Zapisz&lt;/code&gt; oraz &lt;code&gt;Anuluj&lt;/code&gt;.
Zacznijmy od dodania odpowiednich funkcji w kontrolerze. Pierwszą z nich będzie akcja &lt;code&gt;AddProduct()&lt;/code&gt;;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public PartialViewResult AddProduct()
{
    return PartialView(&quot;AddProduct&quot;, new Product());
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W celu dodania widoku klikamy &lt;code&gt;PPM&lt;/code&gt; na nazwę funkcji i wybieramy opcję &lt;code&gt;Add View&lt;/code&gt;.
W otwartym oknie zaznaczmy opcję &lt;code&gt;Create Strongly Typed View&lt;/code&gt;, a w comboboxie wpisujemy &lt;code&gt;Product&lt;/code&gt;.
Ponadto zaznaczamy checkboxa &lt;code&gt;Create as a partial view&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/02/asp-net-mvc-okna-modalne-z-wykorzystaniem-kendo-ui/addcontroller.jpg&quot;&gt;&lt;img src=&quot;images/addcontroller.jpg&quot; alt=&quot;addcontroller&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;W katalogu &lt;code&gt;Home&lt;/code&gt; pojawił się nowy plik &lt;code&gt;AddProduct.cshtml&lt;/code&gt;. W pliku tym zdefiniujemy wygląd zawartości naszego okna modalnego.
Jako, że nasze dane będą musiały zostać wysłane na serwer do zapisu, skorzystamy z funkcji pomocniczej &lt;code&gt;Html.BeginForm&lt;/code&gt;, w której to umieścimy wszystkie potrzebne elementy do edycji produktu.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;@model ModalDialogs.Models.Product
&amp;lt;div id=&quot;windowContent&quot;&amp;gt;
    @using (Html.BeginForm(&quot;AddProduct&quot;, &quot;Home&quot;, FormMethod.Post, new { id = &quot;fmAddProduct&quot; }))
    {
        @Html.ValidationSummary(true)
        &amp;lt;div&amp;gt;
            @Html.Label(&quot;lblName&quot;, &quot;Nazwa&quot;)
            @Html.TextBoxFor(val =&amp;gt; val.Name)
            @Html.ValidationMessageFor(val =&amp;gt; val.Name)
        &amp;lt;/div&amp;gt;
        &amp;lt;div&amp;gt;
            @Html.Label(&quot;lblQuantity&quot;, &quot;Ilość&quot;)
            @Html.TextBoxFor(val =&amp;gt; val.Quantity)
            @Html.ValidationMessageFor(val =&amp;gt; val.Quantity)
        &amp;lt;/div&amp;gt;
        &amp;lt;input type=&quot;button&quot; value=&quot;Zapisz&quot; id=&quot;btnSave&quot; /&amp;gt;
        &amp;lt;input type=&quot;button&quot; value=&quot;Anuluj&quot; id=&quot;btnCancel&quot; /&amp;gt;
    }
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Dodajmy teraz na naszej stronie głównej linka, który wywoła nasze okno modalne.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;@Html.ActionLink(&quot;Dodaj produkt&quot;, &quot;AddProduct&quot;, &quot;Home&quot;, null, new { id = &quot;addProduct&quot; })
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Przyszedł teraz czas na najważniejszą część wpisu, a mianowicie na wykorzystaniu &lt;code&gt;jQuery&lt;/code&gt; oraz &lt;code&gt;kendoWindow&lt;/code&gt; do pokazania okna edycji/dodawania produktu.
Najpierw podpinamy się do zdarzenia(dodajemy handler) &lt;code&gt;click&lt;/code&gt; utworzonego przed chwilą odnośnika.
W funkcji obsługującej zdarzenie click musimy utworzyć okno, wypełnić jego zawartość oraz pokazać okno.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$(document).ready(function () {
        var $kendoWindow;
        $(&quot;#addProduct&quot;).click(function (event) {
            debugger;
            event.preventDefault(); // anulujemy domyślną akcję
            var $dialog = $(&apos;&amp;lt;div&amp;gt;&amp;lt;/div&amp;gt;&apos;);
            var $url = $(this).attr(&apos;href&apos;); //wyciągamy  url-a
            $dialog.empty();
            $kendoWindow = $dialog.kendoWindow({ //tworzmy okno
                height: &quot;200px&quot;, //o wysokosci 200px
                title: &quot;Dodaj&quot;, // z tytulem &quot;Dodaj&quot;
                width: &quot;200px&quot;, // o szerokosci 200px
                actions: [&quot;Close&quot;], // ktore mozna jedynie zamknac - nie mozna przesuwac, odswiezac itp
                content: $url // ktorego zawartosc pobieramy z urla przechwyconego z clica

            }).data(&quot;kendoWindow&quot;);
            $kendoWindow.center(); //centrujemy okno
            $kendoWindow.open(); // otwieramy
        });
...
...
...
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Korzystając z selektora &lt;code&gt;jQuery&lt;/code&gt; znajdujemy link opisany id-kiem &lt;code&gt;addProduct&lt;/code&gt;, a następnie podłączamy się do zdarzenia &lt;code&gt;click&lt;/code&gt;.
W funkcji obsługującej zdarzenie musimy najpierw zapobiec wywołaniu się domyślnej akcji wykonującej się po naciśnięciu na link.
Robimy to przy pomocy funkcji &lt;code&gt;prefentDefault()&lt;/code&gt;.
W kolejnych krokach tworzymy okno modalne zgodnie ze wskazówkami znajdującymi się w dokumentacji &lt;a href=&quot;http://demos.kendoui.com/web/window/index.html&quot;&gt;Kendo UI&lt;/a&gt;.
Najważniejszym elementem przy tworzeniu okna jest dynamiczne załadowanie jego zawartości poprzez podanie linka do akcji w kontrolerze.
Linka tego jesteśmy w stanie wyciągnąć wykorzystując kolejną użyteczną funkcję &lt;code&gt;jQuery&lt;/code&gt; - &lt;code&gt;attr(&apos;nazwaAtrybutu&apos;)&lt;/code&gt;.
Od tej chwili po naciśnięciu odnośnika &lt;code&gt;Dodaj produkt&lt;/code&gt; zawsze będzie odpalane okno modalne dodawania nowego produktu.
Teraz musimy jeszcze obsłużyć zdarzenia &lt;code&gt;click&lt;/code&gt; na przyciskach &lt;code&gt;Zapisz&lt;/code&gt; oraz &lt;code&gt;Anuluj&lt;/code&gt;.
Do funkcji przedstawionej powyżej dopisujemy następujące linijki&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;$(&quot;#btnSave&quot;).live(&quot;click&quot;, function (event) {
            event.preventDefault(); // anulujemy domyślną akcję
            var $url = $(&quot;#fmAddProduct&quot;).attr(&quot;action&quot;); //wyciągamy  url-a
           // odpalamy ajaxa w celu wywołania akcji kontrolera
            $.ajax(
                {
                    url: $url,  // podajemy url z akcja kontrolera
                    type: &quot;POST&quot;, // okreslamy metode 
                    data: $(&quot;#fmAddProduct&quot;).serialize(), // przekazujemy dane 
                    success: function (response) {       //w przypadku gdy wszystko OK
                        $(&quot;#btnSave&quot;).unbind(); // odpinamy zdarzenia
                        $(&quot;btnCancel&quot;).unbind();
                        $kendoWindow.close(); //zamykamy i 
                        $kendoWindow.destroy(); // niszczymy okno
                    },
                    error: function (response) {
                        $(&quot;#btnSave&quot;).unbind(); //odpinamy zarzenia
                        $(&quot;btnCancel&quot;).unbind();
                        $kendoWindow.content(response.responseText); //odswiezamy zawartosc okna
                    }
                });
        });

        $(&quot;#btnCancel&quot;).live(&quot;click&quot;, function (event) {
            event.preventDefault();// anulujemy domyślną akcję
            $(&quot;#btnSave&quot;).unbind(); //odpinamy zdarzenia
            $(&quot;btnCancel&quot;).unbind();
            $kendoWindow.close(); //zamykamy i
            $kendoWindow.destroy(); // niszczymy okno
        });
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Tutaj sytuacja odrobinę się komplikuje gdyż musimy wysłać wprowadzone dane do kontrolera oraz obsłużyć ewentualne błędy walidacji.
Zaczynamy od znalezienia przycisku opisanego id-kiem &lt;code&gt;btnSave&lt;/code&gt; oraz podpięcia się do zdarzenia &lt;code&gt;click&lt;/code&gt;.
Ponownie anulujemy domyślną akcję wywołując funkcję &lt;code&gt;preventDefault&lt;/code&gt;.
W kolejnym kroku wyciągamy url-a, który miał zostać wywołany po naciśnięciu przycisku.
Robimy to, ponownie wykorzystując funkcję &lt;code&gt;attr(&apos;nazwaAtrybutu&apos;)&lt;/code&gt;.
Jednakże teraz wyszukujemy tego atrybutu na obiekcie o &lt;code&gt;id =&quot;fmAddProduct&quot;&lt;/code&gt; (taki id nadaliśmy &quot;formie&quot; na której są pola edycyjne produktu).
Ostatnim elementem jest wykonanie asynchronicznego zapytania &lt;code&gt;AJAX&lt;/code&gt;.
Do tego zapytania przekazujemy wcześniej uzyskany url,określamy typ zapytania jako &lt;code&gt;POST&lt;/code&gt; oraz przesyłamy dane wykorzystując funkcję serialize z biblioteki &lt;code&gt;jQuery&lt;/code&gt;.
Na samym końcu musimy sprecyzować co ma się stać w przypadku gdy wszystko pójdzie ok - parametr &lt;code&gt;success&lt;/code&gt;, a co w przypadku gdy coś będzie nie tak - parametr &lt;code&gt;error&lt;/code&gt;.
Musimy oczywiście dodać do kontrolera jeszcze jedną akcję. Tym razem będzie to również akcja &lt;code&gt;AddProduct&lt;/code&gt;, jednakże będzie to akcja &lt;code&gt;HttpPost&lt;/code&gt; posiadająca jeden parametr typu &lt;code&gt;Product&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[HttpPost]
public ActionResult AddProduct(Product product)
{
    if (ModelState.IsValid)
        return new EmptyResult();
    Response.StatusCode = (int)HttpStatusCode.BadRequest;
    return PartialView(&quot;AddProduct&quot;, product);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/02/asp-net-mvc-okna-modalne-z-wykorzystaniem-kendo-ui/save.jpg&quot;&gt;&lt;img src=&quot;images/save.jpg&quot; alt=&quot;okna modalne&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Ostatnią rzeczą jaką musimy zrobić jest wyłączenie cachowania widoków, które są pokazywane w oknie modalnym - można to zrobić wykorzystując atrybut &lt;code&gt;OutputCaching&lt;/code&gt;.
W przypadku gdy nie wyłączymy cachowania, okna modalne, które raz nie przeszły walidacji nie będą mogły zostać zapisane.
W celu wyłączenia cachowania dla poszczególnych widoków najpierw musimy stworzyć profil cachowania.
Dodajemy taki oto wpis do pliku &lt;code&gt;Web.config&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;caching&amp;gt;
      &amp;lt;outputCacheSettings&amp;gt;
        &amp;lt;outputCacheProfiles&amp;gt;
          &amp;lt;add name=&quot;DisableCaching&quot;
               duration=&quot;0&quot;
               varyByParam=&quot;None&quot;
               location=&quot;None&quot; /&amp;gt;
        &amp;lt;/outputCacheProfiles&amp;gt;
      &amp;lt;/outputCacheSettings&amp;gt;
&amp;lt;/caching&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;a następnie dekorujemy atrybutem&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[OutputCache(CacheProfile = &quot;DisableCaching&quot;)]

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;akcje &lt;code&gt;AddProduct()&lt;/code&gt; oraz &lt;code&gt;AddProduct(Product product)&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;To by było na tyle, projekt można zassać z tego &lt;a href=&quot;http://www.4shared.com/rar/F4pNi3VH/ModalDialogs.html&quot;&gt;linka&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Lokalizowanie aplikacji Silverlight i Windows Phone z wykorzystaniem Portable Shared Library</title><link>https://tpodolak.com/blog/lokalizowanie-aplikacji-silverlight-i-windows-phone-z-wykorzystaniem-portable-shared-library/</link><guid isPermaLink="true">https://tpodolak.com/blog/lokalizowanie-aplikacji-silverlight-i-windows-phone-z-wykorzystaniem-portable-shared-library/</guid><pubDate>Sat, 21 Jan 2012 11:32:00 GMT</pubDate><content:encoded>&lt;p&gt;W dzisiejszym wpisie postaram się przedstawić w jaki sposób lokalizować treści aplikacji typu &lt;code&gt;Silverlight&lt;/code&gt; oraz &lt;code&gt;WindowsPhone&lt;/code&gt;.
Założenie jest takie, że chcemy zbudować multiplatformową aplikację, która będzie obsługiwała platformę &lt;code&gt;Silverlight&lt;/code&gt; oraz &lt;code&gt;Windows Phone&lt;/code&gt;.
Rozsądnym zatem podejściem jest trzymanie wszystkich tłumaczeń w jednym miejscu - najlepiej aby mechanizm tłumaczenia był obsługiwany zarówno przez &lt;code&gt;Windows Phona&lt;/code&gt; jak i &lt;code&gt;Silverlighta&lt;/code&gt;.
W pierwszym kroku musimy doinstalować do środowiska &lt;code&gt;Visual Studio&lt;/code&gt; projekt typu &lt;code&gt;Portable Class Library&lt;/code&gt;.
Referencje do tego typu projektów możemy dodawać zarówno do projektów &lt;code&gt;Silverlightowych&lt;/code&gt;, &lt;code&gt;WindowsPhonowych&lt;/code&gt; - zatem idealnie nadaje się na przetrzymywanie w nim mechanizmu tłumaczenia aplikacji.
W celu zainstalowania wyżej wspomnianego typu projektu musimy odwiedzić następującą &lt;a href=&quot;http://visualstudiogallery.msdn.microsoft.com/b0e0b5e9-e138-410b-ad10-00cb3caf4981&quot;&gt;stronę&lt;/a&gt;, a następnie zassać plik instalacyjny.
Mając już przygotowane środowisko, stwórzmy nową solucję i dodajmy do niej projekt typu &lt;code&gt;Portable Class Library&lt;/code&gt; - nazwijmy go &lt;code&gt;SharedPortableClasses&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/01/lokalizowanie-aplikacji-silverlight-i-windows-phone-z-wykorzystaniem-portable-shared-library/Create.jpg&quot;&gt;&lt;img src=&quot;images/Create.jpg&quot; alt=&quot;Create&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Następnie dodajmy do tego projektu nowy folder &lt;code&gt;Localization&lt;/code&gt;, w którym to umieścimy pliki typu &lt;code&gt;*.resx&lt;/code&gt;.
Pierwszy plik nazywamy po prostu &lt;code&gt;Localization.resx&lt;/code&gt; natomiast następne nazywamy według wzorca &lt;code&gt;Localization.&amp;lt;culture&amp;gt;.resx&lt;/code&gt;, gdzie: &lt;code&gt;&amp;lt;culture&amp;gt;&lt;/code&gt;  oznacza kulturę/język komunikatów jaki dany plik będzie przechowywać.
Dla przykładu aby mechanizm tłumaczący obsługiwał język polski oraz angielski, powinniśmy stworzyć następującą strukturę plików&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Localization.resx&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Localization.pl-PL.resx&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Localization.en-US.resx&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;W kolejnym kroku musimy zmienić modyfikator dostępu do naszych plików zasobów na publiczny.
W tym celu klikamy podwójnie na każdy plik &lt;code&gt;*.resx&lt;/code&gt; i z comboboxa wybieramy public&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/01/lokalizowanie-aplikacji-silverlight-i-windows-phone-z-wykorzystaniem-portable-shared-library/Public.jpg&quot;&gt;&lt;img src=&quot;images/Public.jpg&quot; alt=&quot;Public&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Mając przygotowane pliki zasobów, możemy teraz umieszczać w nich tłumaczone elementy interfejsów oraz komunikatów.
Robimy to w następujący sposób:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;W pliku &lt;code&gt;Localization.resx&lt;/code&gt; wypełniamy pole w kolumnie &lt;code&gt;Name&lt;/code&gt; jakąś wartością(kluczem), która identyfikuje nasz tekst (w moim przypadku będzie to &lt;code&gt;Title&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;W plikach &lt;code&gt;Localization.pl-PL.resx&lt;/code&gt; oraz &lt;code&gt;Localization.en-US&lt;/code&gt; powtarzamy tę czynność (uzupełniamy pola w kolumnie &lt;code&gt;Name&lt;/code&gt; tymi samymi wartościami co w pliku &lt;code&gt;Localization.resx&lt;/code&gt;) oraz wypełniamy pole w kolumnie &lt;code&gt;Value&lt;/code&gt; tekstem w odpowiednim języku.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Mając już prawie gotowy mechanizm tłumaczący stwórzmy teraz projekt typu &lt;code&gt;Silverlight Application&lt;/code&gt; oraz dodajmy mu referencję do projektu &lt;code&gt;SharedPortableClasses&lt;/code&gt;.
Dodajmy teraz do zasobów naszej aplikacji obiekt typu &lt;code&gt;Localization&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Application.Resources&amp;gt;
        &amp;lt;Localization:Localization x:Key=&quot;LocalizationProxy&quot; /&amp;gt;
&amp;lt;/Application.Resources&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Niestety z powodu tego, że klasa &lt;code&gt;Localization&lt;/code&gt; nie posiada publicznego konstruktora bezparametrowego, nie uda nam się odpalić naszej aplikacji.
&lt;code&gt;Resharper&lt;/code&gt; od razu wyrzuci ostrzeżenie następującej treści&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/01/lokalizowanie-aplikacji-silverlight-i-windows-phone-z-wykorzystaniem-portable-shared-library/ConstructorWarning.jpg&quot;&gt;&lt;img src=&quot;images/ConstructorWarning.jpg&quot; alt=&quot;ConstructorWarning&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Zatem w jaki sposób wykorzystać nasz mechanizm tłumaczący? Rozwiązania są dwa&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Zmodyfikować plik &lt;code&gt;Localization.Designer.cs&lt;/code&gt; i ustawić konstruktor domyślny na publiczny. Takie rozwiązanie jednak nie jest eleganckie, gdyż za każdym razem gdy dodamy nowy wpis do pliku &lt;code&gt;Localization.resx&lt;/code&gt; kod w pliku &lt;code&gt;Localization.Designer.cs&lt;/code&gt; zostanie przegenerowany.&lt;/li&gt;
&lt;li&gt;Drugim sposobem jest stworzenie klasy pośredniczącej, która będzie w sobie trzymała instancję obiektu &lt;code&gt;Localization&lt;/code&gt;, oraz dodanie obiektu tej klasy pośredniczącej do zasobów aplikacji&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Jako, że podejście drugi jest według mnie dużo lepsze to postaram się je teraz przedstawić.
Do projektu &lt;code&gt;SharedPortableClasses&lt;/code&gt; dodajmy klasę &lt;code&gt;LocalizationProxy.cs&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class LocalizationProxy : INotifyPropertyChanged
{
    public Localization LocalizationManager { get; private set; }

    public LocalizationProxy()
    {
        LocalizationManager = new Localization();
    }

    public void ResetResources()
    {
        OnPropertyChanged(&quot;LocalizationManager&quot;);
    }

    #region INotifyPropertyChanged region
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Teraz stwórzmy instancję tej klasy w zasobach aplikacji&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Application xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
             xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
             xmlns:Localization=&quot;clr-namespace:SharedPortableLibrary.Localization;assembly=SharedPortableLibrary&quot;
             x:Class=&quot;LocalizationSolution.App&quot;&amp;gt;
    &amp;lt;Application.Resources&amp;gt;
        &amp;lt;Localization:LocalizationProxy x:Key=&quot;LocalizationProxy&quot; /&amp;gt;
    &amp;lt;/Application.Resources&amp;gt;
&amp;lt;/Application&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Zanim przystąpimy do tłumaczenia samego interfejsu musimy jeszcze zmodyfikować plik projekty &lt;code&gt;*.csproj&lt;/code&gt;.
Otwieramy nasz plik projektu w dowolnym edytorze tekstowym, a następnie w sekcji &lt;code&gt;SupportedCultures&lt;/code&gt; dorzucamy kultury w jakich nasza aplikacja ma pracować.
W moim przypadku będzie to wyglądać w następujący sposób:&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/01/lokalizowanie-aplikacji-silverlight-i-windows-phone-z-wykorzystaniem-portable-shared-library/CSProjCultures.jpg&quot;&gt;&lt;img src=&quot;images/CSProjCultures.jpg&quot; alt=&quot;CSProjCultures&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Jak widać moja aplikacja będzie wspierała język angielski oraz język polski.
Mając już wszystko gotowe przystąpmy do tworzenia interfejsu.
Zmodyfikujmy plik &lt;code&gt;MainPage.xaml&lt;/code&gt; tak aby wyglądał w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;UserControl x:Class=&quot;LocalizationSolution.MainPage&quot;
    xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;
    xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
    mc:Ignorable=&quot;d&quot;
    d:DesignHeight=&quot;300&quot; d:DesignWidth=&quot;400&quot;&amp;gt;

    &amp;lt;Grid x:Name=&quot;LayoutRoot&quot; Background=&quot;White&quot;&amp;gt;
        &amp;lt;!--TitlePanel contains the name of the application and page title--&amp;gt;
        &amp;lt;StackPanel x:Name=&quot;TitlePanel&quot; Grid.Row=&quot;0&quot; Margin=&quot;12,17,0,28&quot;&amp;gt;
            &amp;lt;TextBlock TextWrapping=&quot;Wrap&quot; x:Name=&quot;PageTitle&quot; Text=&quot;{Binding Source={StaticResource LocalizationProxy},Path=LocalizationManager.Title,Mode=TwoWay}&quot; Margin=&quot;9,-7,0,0&quot; /&amp;gt;
            &amp;lt;Button Content=&quot;Polski&quot; Command=&quot;{Binding PolisLanguageCommand}&quot;  Height=&quot;72&quot; HorizontalAlignment=&quot;Left&quot;   VerticalAlignment=&quot;Top&quot; Width=&quot;160&quot;   /&amp;gt;
            &amp;lt;Button Content=&quot;English&quot; Command=&quot;{Binding EnglishLanguageCommand}&quot; Height=&quot;72&quot; HorizontalAlignment=&quot;Left&quot;  VerticalAlignment=&quot;Top&quot; Width=&quot;160&quot;  /&amp;gt;
        &amp;lt;/StackPanel&amp;gt;
    &amp;lt;/Grid&amp;gt;
&amp;lt;/UserControl&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Widok ten jest bardzo prosty.
Posada on dwa przyciski służące do zmiany aktualnego języka oraz labelkę, na której dany tekst będzie się pojawiać.
Najciekawszą rzeczą w tym kodzie jest sposób wyświetlania tłumaczonego tekstu.
Jak widać do właściwości &lt;code&gt;Text&lt;/code&gt; elementu typu &lt;code&gt;TextBlok&lt;/code&gt; nie jest przypisywana wartość stała, ale używany jest binding&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Text=&quot;{Binding Source={StaticResource LocalizationProxy},Path=LocalizationManager.Title,Mode=TwoWay}&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To co wyświetli się w danym &lt;code&gt;TextBloku&lt;/code&gt; zależne jest od tego co zwróci nam nasz mechanizm tłumaczący.
Odnosimy się do niego poprzez wskazanie zasobu, który nazwaliśmy &lt;code&gt;LocalizationProxy&lt;/code&gt; (taki klucz nadaliśmy mu w zasobach aplikacji).
Następnie do konkretnego tekstu odnosimy się podając odpowiednią ścieżkę - w tym przypadku jest to &lt;code&gt;LocalizationManager.Title&lt;/code&gt;.
&lt;code&gt;LocalizationManager&lt;/code&gt; jest to właściwość, którą stworzyliśmy w klasie &lt;code&gt;LocalizationProxy&lt;/code&gt;, natomiast &lt;code&gt;Title&lt;/code&gt; jest to klucz jaki wpisaliśmy w pliku zasobów &lt;code&gt;Localization.resx&lt;/code&gt;.
Przeglądając plik &lt;code&gt;Localization.Designer.cs&lt;/code&gt; można zauważyć, że została tam wygenerowana właściwość &lt;code&gt;Title&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static string Title 
{
    get { return ResourceManager.GetString(&quot;Title&quot;, resourceCulture); }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Właściwość tak zwraca nam tekst w odpowiednim języku.
Sam mechanizm zwracania tekstu dla wybranego przez nas języka jest już dostarczony z &lt;code&gt;Frameworkiem&lt;/code&gt;.
Tekst wyświetlany w aplikacji będzie w takim języku/kulturze jaka zostania przypisana do właściwości &lt;code&gt;Thread.CurrentThread.CurrentUICulture&lt;/code&gt;.
Możemy to w łatwy sposób sprawdzić zmieniając dynamicznie kulture wątku. Stwórzmy nową klasę i nazwijmy ją &lt;code&gt;MainPageViewModel&lt;/code&gt;.
Wygląda ona w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class MainPageViewModel
{
    public DelegateCommand PolisLanguageCommand { get; set; }
    public DelegateCommand EnglishLanguageCommand { get; set; }
    public MainPageViewModel()
    {
        PolisLanguageCommand = new DelegateCommand(() =&amp;gt;
        {
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(&quot;pl-PL&quot;);
            Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(&quot;pl-PL&quot;);
            ResetResources();

        });

        EnglishLanguageCommand = new DelegateCommand(() =&amp;gt;
        {
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(&quot;en-US&quot;);
            Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(&quot;en-US&quot;);
            ResetResources();
        });
    }

    private void ResetResources()
    {
        ((LocalizationProxy)Application.Current.Resources[&quot;LocalizationProxy&quot;]).ResetResources();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Następnie stwórzmy obiekt tej klasy i przypiszmy go do &lt;code&gt;DataContext-u&lt;/code&gt; okna &lt;code&gt;MainPage&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();
        DataContext = new MainPageViewModel();
    }         
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Dzięki wykorzystaniu komend po naciśnięciu przycisku &lt;code&gt;Polski&lt;/code&gt; zostanie odpalana komenda &lt;code&gt;PolishLangugeCommand&lt;/code&gt;, która z kolei odpali anonimową funkcję do niej przypisaną.
W funkcji tej zmienimy kulturę wątku na &lt;code&gt;pl-PL&lt;/code&gt;.
Ważnym elementem jest tutaj funkcja &lt;code&gt;ResetResources&lt;/code&gt;, która znajduje się w klasie &lt;code&gt;LocalizationProxy&lt;/code&gt;.
Funkcja ta informuje widok (poprzez zdarzenie &lt;code&gt;NotifyPropertyChanged&lt;/code&gt;), że należy odświeżyć wszystkie elementy, które zostały zbindowane do właściwości &lt;code&gt;LocalizationManager&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Postępując w analogiczny sposób możemy stworzyć aplikację &lt;code&gt;WindowsPhone&lt;/code&gt;, która będzie wykorzystywałą nasz mechanizm tłumaczący.
Co więcej dzięki temu, że dwie aplikacje będą korzystały z tego samego mechanizmu oraz z tych samych resourców, nie musimy podwójnie wpisywać tłumaczonych tekstów.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/01/lokalizowanie-aplikacji-silverlight-i-windows-phone-z-wykorzystaniem-portable-shared-library/PhoneResults.jpg&quot;&gt;&lt;img src=&quot;images/PhoneResults.jpg&quot; alt=&quot;Lokalizowanie&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Projekt można znaleźć pod tym &lt;a href=&quot;http://www.4shared.com/rar/i9cd3EGD/LocalizationSolution.html&quot;&gt;linkiem&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Lokalizowanie aplikacji WPF oraz Silverlight 5 przy użyciu MarkupExtension</title><link>https://tpodolak.com/blog/lokalizowanie-aplikacji-wpf-oraz-silverlight-5-przy-uzyciu-markupextension/</link><guid isPermaLink="true">https://tpodolak.com/blog/lokalizowanie-aplikacji-wpf-oraz-silverlight-5-przy-uzyciu-markupextension/</guid><pubDate>Sat, 21 Jan 2012 11:24:00 GMT</pubDate><content:encoded>&lt;p&gt;W poprzednim wpisie przedstawiłem w jaki sposób można lokalizować aplikację napisaną w &lt;code&gt;Silverlight 4&lt;/code&gt; oraz &lt;code&gt;Windows Phone&lt;/code&gt;, wykorzystując do tego ten sam mechanizm.
Tym razem zademonstruje w jaki sposób można nieco uprościć składnie tłumaczenia wykorzystując do tego &lt;code&gt;MarkupExtension&lt;/code&gt;.
Jeżeli kiedykolwiek pisałeś coś w &lt;code&gt;Silverlighcie&lt;/code&gt;, &lt;code&gt;Windows Phonie&lt;/code&gt; lub &lt;code&gt;WPF-ie&lt;/code&gt; istnieje duża szansa, że używałeś już &lt;code&gt;MarkupExtension&lt;/code&gt;.
Do najpopularniejszych &lt;code&gt;MarkupExtensions&lt;/code&gt; należą takie słowa kluczowe (używane w &lt;code&gt;XAML-u&lt;/code&gt;) jak:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Binding&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;StaticResource&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;DynamicResource&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;TemplateBinding&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Na potrzeby mechanizmu lokalizowania aplikacji &lt;code&gt;WPF&lt;/code&gt; (ewentualnie &lt;code&gt;Silverlight 5&lt;/code&gt;) stworzymy customowe &lt;code&gt;MarkupExtenssion&lt;/code&gt;, które będzie odpowiedzialne za tłumaczenie elementów &lt;code&gt;UI&lt;/code&gt; naszej aplikacji.
Zacznijmy od przygotowania plików zasobów. Podobnie jak w poprzednim wpisie utwórzmy trzy pliki:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Localization.resx&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Localization.pl-PL.resx&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Localization.en-US.resx&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;W plikach tych będziemy przechowywać nasze tłumaczenia.
Następnie stwórzmy klasę Translator, która będzie dziedziczyła po klasie MarkupExtension.
Do klasy tej dodajmy właściwość&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public string Key { get; set; }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;, która będzie przechowywać klucz dzięki któremu z pliku zasobów wyciągniemy tekst w odpowiednim języku.
W kolejnym kroku musimy przeciążyć funkcję&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public abstract object ProvideValue(IServiceProvider serviceProvider)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;tak aby dostarczyła nam ona przetłumaczony tekst.
W moim pierwszym podejściu funkcja ta wyglądała w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public override object ProvideValue(IServiceProvider serviceProvider)
{
    Binding binding = new Binding(Key) { Source = new Localization(),Mode = BindingMode.OneWay};
    return binding.ProvideValue(serviceProvider);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Wadami takiego rozwiązania było:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;duża liczba tworzonych obiektów - przy każdym tłumaczeniu tworzyłem nowy obiekt Localization(), który prawdopodobnie może być dość ciężkim obiektem (zwłaszcza gdy będzie przechowywał dużo tłumaczonego tekstu)&lt;/li&gt;
&lt;li&gt;brak możliwości dynamicznej zmiany języka&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Ostatecznie zatem zrezygnowałem z przedstawionej wyżej opcji i zdecydowałem się na metodę odrobinę bardziej zaawansowaną.
Po pierwsze utworzyłem klasę &lt;code&gt;TranslationManager&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class TranslationManager
{
    public event Action&amp;lt;CultureInfo&amp;gt; LanguageChanged = val =&amp;gt; { };
    private static TranslationManager _instance;
    private static readonly object LockInstance = new object();
    public static TranslationManager Instance
    {
        get
        {
            lock (LockInstance)
            {
                return _instance = _instance ?? new TranslationManager();
            }
        }
    }
    
    private CultureInfo _currentCulture;
    public CultureInfo CurrentCulture
    {
        get { return _currentCulture ?? (CurrentCulture = Thread.CurrentThread.CurrentUICulture); }
        set
        {
            _currentCulture = value;
            OnLanguageChanged(CurrentCulture);
        }
    }
    
    protected void OnLanguageChanged(CultureInfo culture)
    {
        LanguageChanged(culture);
    }
    
    private TranslationManager()
    {
    }
    
    public string Translate(string key)
    {
        return Localization.ResourceManager.GetString(key, CurrentCulture);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;która będzie zarządzała tłumaczeniami. Najważniejszą metodą tej klasy jest oczywiście funkcja&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public string Translate(string key)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;która to zwraca tekst w odpowiednim języku - w zależności od kultury, która zostanie ustawiona w &lt;code&gt;TranslationManagerze&lt;/code&gt;.
Ponadto &lt;code&gt;TranslationManager&lt;/code&gt; posiada jedno zdarzenie&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public event Action&amp;lt;CultureInfo&amp;gt; LanguageChanged
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;które ma za zadanie poinformować &lt;code&gt;UI&lt;/code&gt; o potrzebie odświeżenia zbindowanych elementów. W jaki sposób się to odbywa?
Wszystko zawdzięczamy interfejsowi &lt;code&gt;INotifyPropertyChanged&lt;/code&gt; oraz bindingom.
Funkcja &lt;code&gt;ProvideValue&lt;/code&gt; została zmodyfikowana w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public override object ProvideValue(IServiceProvider serviceProvider)
{
    Binding binding = new Binding(&quot;Value&quot;) { Source = new TranslationItem(Key), Mode = BindingMode.OneWay };
    return binding.ProvideValue(serviceProvider);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W funkcji tej tworze binding, który binduje się do właściwości &lt;code&gt;Value&lt;/code&gt; obiektu &lt;code&gt;TranslationItem&lt;/code&gt;.
&lt;code&gt;TranslationItem&lt;/code&gt; jest to prosty obiekt który udostępnia właściwość &lt;code&gt;Value&lt;/code&gt; zwracającą przetłumaczony tekst.
Dodatkowo obiekt ten podpina się do zdarzenia &lt;code&gt;LanguageChanged&lt;/code&gt; z klasy &lt;code&gt;TranslationManager&lt;/code&gt;.
W przypadku gdy ktoś zmieni język aplikacji, odpalone zostanie zdarzenie &lt;code&gt;NotifyPropertyChanged&lt;/code&gt;, które poinformuje widok o potrzebie odświeżenia odpowiednich elementów.
Klasa TranslationItem wygląda zatem w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public sealed class TranslationItem : INotifyPropertyChanged, IDisposable
{
    public event PropertyChangedEventHandler PropertyChanged = delegate { };
    private readonly string _key;
    public TranslationItem(string key)
    {
        _key = key;
        TranslationManager.Instance.LanguageChanged += Instance_LanguageChanged;
    }

    ~TranslationItem()
    {
        Dispose();
    }

    void Instance_LanguageChanged(System.Globalization.CultureInfo obj)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(&quot;Value&quot;));
    }

    public string Value
    {
        get { return TranslationManager.Instance.Translate(_key); }
    }

    public  void Dispose()
    {
        TranslationManager.Instance.LanguageChanged -= Instance_LanguageChanged;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Mając gotowy mechanizm tłumaczący możemy wykorzystać go w następujący sposób w &lt;code&gt;XAML-u&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Label Content=&quot;{WPFMarkupExtension:Translator Key=Title}&quot;/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Zauważmy, że tekst do labelki jest przypisywany z wykorzystywaniem naszego customoweog &lt;code&gt;MarkupExtension&lt;/code&gt; - &lt;code&gt;WPFMarkupExtension:Translator&lt;/code&gt; (&lt;code&gt;WPFMarkupExtension&lt;/code&gt; - jest to alias na namespace, w którym znajduje się nasza klasa &lt;code&gt;Translator&lt;/code&gt;).
W składni przekazujemy do właściwości &lt;code&gt;Key&lt;/code&gt; klucz do tekstu (znajdującego się w resourcach), który chcemy tłumaczyć.
W celu zmiany języka wystarczy, że ustawimy interesującą nas kulturę w klasie &lt;code&gt;TranslationManager&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;TranslationManager.Instance.CurrentCulture = new CultureInfo(&quot;en-US&quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Przykładowy widok wykorzystujący napisany translator, oraz pokazujący dynamiczną zmianę języka może wyglądać w następujący sposób (dorzucamy następujące linijki do &lt;code&gt;MainWindow.xaml&lt;/code&gt;)&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;StackPanel&amp;gt;
    &amp;lt;Label Content=&quot;{WPFMarkupExtension:Translator Key=Key}&quot;/&amp;gt;
    &amp;lt;Button Command=&quot;{Binding PolishCommand}&quot;&amp;gt;Polski&amp;lt;/Button&amp;gt;
    &amp;lt;Button Command=&quot;{Binding EnglishCommand}&quot;&amp;gt;English&amp;lt;/Button&amp;gt;
&amp;lt;/StackPanel&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Następnie tworzymy &lt;code&gt;ViewModel&lt;/code&gt; do naszego okna&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class MainPageViewModel
{
        public DelegateCommand PolishCommand { get; set; }
        public DelegateCommand EnglishCommand { get; set; }
        
        public MainPageViewModel()
        {
            PolishCommand = new DelegateCommand(()=&amp;gt; TranslationManager.Instance.CurrentCulture = new CultureInfo(&quot;pl-PL&quot;));
            EnglishCommand = new DelegateCommand(()=&amp;gt;TranslationManager.Instance.CurrentCulture = new CultureInfo(&quot;en-US&quot;));
        }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Ostatecznie przypisujemy obiekt klasy &lt;code&gt;MainPageViewModel&lt;/code&gt; do &lt;code&gt;DataContextu&lt;/code&gt; &lt;code&gt;MainWindow.xaml&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public MainWindow()
{
    InitializeComponent();
    DataContext = new MainPageViewModel();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/01/lokalizowanie-aplikacji-wpf-oraz-silverlight-5-przy-uzyciu-markupextension/result.jpg&quot;&gt;&lt;img src=&quot;images/result.jpg&quot; alt=&quot;MarkupExtension&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Kod do projektu można znaleźć pod tym &lt;a href=&quot;http://www.4shared.com/rar/SwDXay7V/WPFMarkupExtension.html&quot;&gt;linkiem&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>Silverlight - koncepcja logowania z użyciem MembershipProviders oraz WCF RIA cz.3 - Microsoft Enterprise Library Security Block</title><link>https://tpodolak.com/blog/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-3-microsoft-enterprise-library-security-block/</link><guid isPermaLink="true">https://tpodolak.com/blog/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-3-microsoft-enterprise-library-security-block/</guid><pubDate>Fri, 06 Jan 2012 13:47:00 GMT</pubDate><content:encoded>&lt;p&gt;W tym wpisie postaram się krótko przedstawić blok bezpieczeństwa (&lt;code&gt;Security Block&lt;/code&gt;) z biblioteki &lt;code&gt;Microsoft Enterprise Library&lt;/code&gt;.
Biblioteki tej użyjemy do sprawdzania rol i reguł dostępu do funkcji serwisu &lt;code&gt;WCF&lt;/code&gt;.
Najpierw oczywiście musimy pobrać bibliotekę &lt;code&gt;Microsoft Enterprise Library&lt;/code&gt;, znajduje się ona pod tym &lt;a href=&quot;http://www.microsoft.com/download/en/details.aspx?id=15104&quot;&gt;adresem&lt;/a&gt;.
Biblioteka ta jest również dostępna z poziomu &lt;code&gt;NuGeta&lt;/code&gt;, jednakże instalacja poprzez ten plugin dorzuca do projektu tylko dll-ki.
W pierwszym przypadku natomiast oprócz dll-ek zostaje również zainstalowane bardzo wygodne narzędzie ułatwiające konfigurację różnych modułów biblioteki.
Mając zainstalowane wszystkie potrzebne komponenty możemy przystąpić do działania.
Zacznijmy od zmodyfikowania pliku &lt;code&gt;Web.config&lt;/code&gt;, tak aby umożliwić naszemu systemowi korzystanie z ról - a tak właściwie aby umożliwić edycję, tworzenie, usuwanie oraz przypisywanie ról użytkownikom.
W sekcji &lt;code&gt;&amp;lt;system.web&amp;gt;&lt;/code&gt; dorzucamy następujące wpisy&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;roleManager enabled=&quot;true&quot; defaultProvider=&quot;SqlProvider&quot;&amp;gt;
      &amp;lt;providers&amp;gt;
        &amp;lt;clear /&amp;gt;
        &amp;lt;add connectionStringName=&quot;aspnetdbConnectionString&quot; name=&quot;SqlProvider&quot;
          type=&quot;System.Web.Security.SqlRoleProvider&quot; /&amp;gt;
      &amp;lt;/providers&amp;gt;
&amp;lt;/roleManager&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W tym momencie dodaliśmy do kolekcji menadżerów ról (&lt;code&gt;Role managers&lt;/code&gt;) nowy provider - nie jest to jednak &lt;code&gt;MembershipProvider&lt;/code&gt; lecz &lt;code&gt;RoleProvider&lt;/code&gt;, a dokładniej dostarczony przez framework &lt;code&gt;SqlRoleProvider&lt;/code&gt;.
Provider ten jest przystosowany do działania na bazie danych o takiej strukturze, jak baza, którą stworzyliśmy w części pierwszej.
Po konfiguracji providera przyszedł czas na dodanie przykładowego użytkownika oraz przypisanie mu jakiejś roli.
Wybieramy opcję &lt;code&gt;ASP.NET Configuration&lt;/code&gt; z menu &lt;code&gt;Project&lt;/code&gt;, następnie na stronie na którą zostaniemy przeniesieni, przechodzimy na zakładkę &lt;code&gt;Security&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/01/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-3-microsoft-enterprise-library-security-block/Configuration.jpg&quot;&gt;&lt;img src=&quot;images/Configuration.jpg&quot; alt=&quot;Configuration&quot; /&gt;&lt;/a&gt;
&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/01/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-3-microsoft-enterprise-library-security-block/admintool.jpg&quot;&gt;&lt;img src=&quot;images/admintool.jpg&quot; alt=&quot;admintool&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;W kolejnym kroku dodajemy role - klikamy w &lt;code&gt;Create or Manage roles&lt;/code&gt;, a w stronie, która się otworzy wpisujemy nazwę roli np. &lt;code&gt;Developer&lt;/code&gt;.
Postępując w podobny sposób dodajmy jeszcze role &lt;code&gt;Admin&lt;/code&gt;.
Następnie tworzymy użytkownika - klikamy w &lt;code&gt;Create user&lt;/code&gt;, a następnie wypełniamy pola podobnie jak na załączonym poniżej screenie&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/01/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-3-microsoft-enterprise-library-security-block/admintoolpass.jpg&quot;&gt;&lt;img src=&quot;images/admintoolpass.jpg&quot; alt=&quot;admintoolpass&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Mając stworzonego przykładowego użytkownika możemy przystąpić do ograniczenia dostępu do niektórych funkcji naszego serwisu.
W tym celu, po pierwsze modyfikujemy funkcję logowania.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; protected UserDTO ValidateCredentials(string name, string password, string customData, out string userData)
 {
     UserDTO user = null;
     userData = null;
     if (Membership.Providers[customData].ValidateUser(name, password))
     {
         userData = name;
         user = new UserDTO { DisplayName = name, Name = name, Email = name, Roles = Roles.GetRolesForUser(name) };
     }
     
     if (user != null) userData = name;
     
     return user;
 }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Jak widać, przy tworzeniu użytkownika dodatkowo pobieramy z bazy danych jego wszystkie role.
Statyczna funkcja &lt;code&gt;GetRolesForUser&lt;/code&gt; pobiera role przy pomocy domyślnego &lt;code&gt;RoleProvidera&lt;/code&gt;.
Dodajmy teraz do naszego &lt;code&gt;DataAccesService-u&lt;/code&gt; dwie funkcje.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;OnlyAdminCanDownloadThis&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;DevelopersCanDownloadThis&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Dane pobierane przez pierwszą funkcję mogą być odczytane jedynie przez użytkowników, którzy są administratorami systemu.
Natomiast dane z funkcji drugiej mogą być odczytane przez developerów (oczywiście admin również może pobrać te dane).
Zastanówmy się teraz w jaki sposób sprawdzić czy dany użytkownik ma dostęp do danych.
Możemy sprawdzać role ręcznie (niewygodne), użyć znanego z &lt;code&gt;ASP.NET&lt;/code&gt; atrybutu &lt;code&gt;PrincipalPermission&lt;/code&gt; (mało elastyczne) lub skorzystać z &lt;code&gt;Microsoft Enterprise Library&lt;/code&gt; (całkiem dobra opcja).
&lt;code&gt;Security Block&lt;/code&gt; z biblioteki &lt;code&gt;Microsoft Enterprise Library&lt;/code&gt; ma tę przewagę nad wcześniej wspomnianymi rozwiązaniami, że wprowadza on tzw. reguły(&lt;code&gt;Rules&lt;/code&gt;).
Dzięki nim możemy w łatwy sposób zdefiniować warunki jakie musi spełnić użytkownik aby zezwolić mu na dostęp w jakieś miejsce systemu.
Skonfigurujmy zatem prostą regułę - regułą ta pozwoli na dostęp do danych jedynie tym użytkownikom, którzy mają prawo administratora.
Klikamy &lt;code&gt;PPM&lt;/code&gt; na plik &lt;code&gt;Web.config&lt;/code&gt; i wybieramy z niego opcję &lt;code&gt;Edit Enterprise Library V5 Configuration&lt;/code&gt; - opcja ta została dodana po instalacji biblioteki &lt;code&gt;Microsoft Enterprise Library&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/01/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-3-microsoft-enterprise-library-security-block/editenterprise.png&quot;&gt;&lt;img src=&quot;images/editenterprise.png&quot; alt=&quot;editenterprise&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;W oknie które się otworzy wybieramy &lt;code&gt;Add Security Settings&lt;/code&gt; z menu &lt;code&gt;Blocks&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/01/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-3-microsoft-enterprise-library-security-block/addsecurity.jpg&quot;&gt;&lt;img src=&quot;images/addsecurity.jpg&quot; alt=&quot;addsecurity&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;W głównym oknie aplikacji pojawi się nowy element - &lt;code&gt;Security Settings&lt;/code&gt;.
Klikamy na znak &lt;code&gt;+&lt;/code&gt; obok &lt;code&gt;Authorization Providers&lt;/code&gt;, następnie z rozwiniętego menu przechodzimy na &lt;code&gt;Add Authorization Providers&lt;/code&gt; i ostatecznie klikamy na &lt;code&gt;Add Authorization Rule Provider&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/01/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-3-microsoft-enterprise-library-security-block/authorization.jpg&quot;&gt;&lt;img src=&quot;images/authorization.jpg&quot; alt=&quot;authorization&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;W ten sposób dodaliśmy domyślny &lt;code&gt;Rule Provider&lt;/code&gt;, teraz możemy stworzyć reguły dostępu do naszej aplikacji.
W tym celu musimy kliknąć w lewy dolny róg pola &lt;code&gt;Authorization Rule Provider&lt;/code&gt;, a następnie z menu, które się pojawi wybrać &lt;code&gt;Add Authorization Rule&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/01/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-3-microsoft-enterprise-library-security-block/rule.jpg&quot;&gt;&lt;img src=&quot;images/rule.jpg&quot; alt=&quot;rule&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;W oknie aplikacji pojawi się nowy element - &lt;code&gt;Authorization Rule&lt;/code&gt;, nadajmy mu nazwę &lt;code&gt;DevelopersOnly&lt;/code&gt;, a następnie zdefiniujmy tzw. &lt;code&gt;Rule expression&lt;/code&gt;.
&lt;code&gt;Rule expression&lt;/code&gt; jest warunek jaki musi zostać spełniony, aby użytkownik uzyskał dostęp do części aplikacji chronionej przez regułę &lt;code&gt;DevelopersOnly&lt;/code&gt;.
Wyrażenie to możemy wpisać ręcznie, lub poprzez prosty kreator - dostępny jest on pod przyciskiem &lt;code&gt;...&lt;/code&gt;.
Stwórzmy więc regułę, która pozwoli tylko użytkownikom typu Developer oraz oczywiście adminowi mieć dostęp do jakieś części aplikacji.
Otwórzmy zatem &lt;code&gt;Rule Expression Editor&lt;/code&gt; (dostępny on jest pod przyciskiem &lt;code&gt;...&lt;/code&gt;), kliknijmy na przycisk &lt;code&gt;Role&lt;/code&gt;, wpiszmy &lt;code&gt;Developer&lt;/code&gt;, następnie kliknijmy w przycisk &lt;code&gt;OR&lt;/code&gt;, wpiszmy &lt;code&gt;Admin&lt;/code&gt;.
Możemy również wpisać następujące wyrażenie ręcznie&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;R:Developer OR R:Admin

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2012/01/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-3-microsoft-enterprise-library-security-block/ruleeditor.jpg&quot;&gt;&lt;img src=&quot;images/ruleeditor.jpg&quot; alt=&quot;ruleeditor&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Stworzyliśmy zatem regułę pozwalającą na dostęp użytkownikom typu &lt;code&gt;Developer&lt;/code&gt; (&lt;code&gt;R:Developer&lt;/code&gt;) oraz administratorom (&lt;code&gt;R:Admin&lt;/code&gt;).
Aby zatwierdzić zmiany wybieramy &lt;code&gt;Save&lt;/code&gt; z menu &lt;code&gt;File&lt;/code&gt;. W pliku &lt;code&gt;Web.config&lt;/code&gt; pojawiły się teraz następujące linijki&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;securityConfiguration&amp;gt;
    &amp;lt;authorizationProviders&amp;gt;
      &amp;lt;add type=&quot;Microsoft.Practices.EnterpriseLibrary.Security.AuthorizationRuleProvider, Microsoft.Practices.EnterpriseLibrary.Security, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&quot;
        name=&quot;Authorization Rule Provider&quot;&amp;gt;
        &amp;lt;rules&amp;gt;
          &amp;lt;add expression=&quot;R:Developer OR R:Admin&quot; name=&quot;DevelopersOnly&quot; /&amp;gt;
        &amp;lt;/rules&amp;gt;
      &amp;lt;/add&amp;gt;
    &amp;lt;/authorizationProviders&amp;gt;
&amp;lt;/securityConfiguration&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Do powyżej konfiguracji musimy jeszcze dorzucić wybór domyślnego providera - dodajmy zatem następujący wpis do linii&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;XHTML
defaultAuthorizationInstance=&quot;Authorization Rule Provider&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Wykorzystajmy teraz stworzoną właśnie regułę aby zabezpieczyć wspomnianą wcześniej funkcję &lt;code&gt;DevelopersCanDownloadThis&lt;/code&gt;.
Po pierwsze stwórzmy pomocniczą klasę pomocniczą &lt;code&gt;SecurityHelper&lt;/code&gt; i dodajmy do niej metodę &lt;code&gt;IsAuthorized&lt;/code&gt;, która wygląda w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static bool IsAuthorized(this IPrincipal principal, string rule)
{
    IAuthorizationProvider ruleProvider = EnterpriseLibraryContainer.Current.GetInstance&amp;lt;IAuthorizationProvider&amp;gt;();
    return ruleProvider.Authorize(principal, rule);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Następnie w funkcji &lt;code&gt;DevelopersCanDownloadThis&lt;/code&gt; musimy sprawdzić czy użytkownik może wykorzystać tą funkcję - w tym celu wykorzystujemy funkcję &lt;code&gt;IsAuthorized&lt;/code&gt;.
Może wyglądać to w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public string DevelopersCanDownloadThis()
{
    if (ServiceContext.User.IsAuthorized(&quot;DevelopersOnly&quot;))
        return &quot;very secure data&quot;;
    throw new PermisionDeniedException(&quot;Brak dostępu&quot;);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Logując się na użytkownika, który posiada prawo/rolę &lt;code&gt;Developer&lt;/code&gt; będziemy mogli pobrać dane wykorzystując funkcję &lt;code&gt;DevelopersCanDownloadThis&lt;/code&gt; w przeciwnym razie do klienta zostanie rzucony wyjątek z odpowiednim komunikatem.
Niestety &lt;code&gt;Security Block&lt;/code&gt; nie został jeszcze przeniesiony na platformę &lt;code&gt;Silverlightową&lt;/code&gt;, zatem przedstawionych powyżej sposobów sprawdzania praw dostępu(np. do jakiejś funkcjonalności) nie możemy zastosować po stronie klienta.&lt;/p&gt;
</content:encoded></item><item><title>Silverlight - koncepcja logowania z użyciem MembershipProviders oraz WCF RIA cz.2</title><link>https://tpodolak.com/blog/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-2/</link><guid isPermaLink="true">https://tpodolak.com/blog/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-2/</guid><pubDate>Sun, 25 Dec 2011 13:17:00 GMT</pubDate><content:encoded>&lt;p&gt;W poprzednim wpisie przedstawiłem w jaki sposób zaimplementować mechanizm logowania po stronie serwera.
Wykorzystałem do tego celu &lt;code&gt;WCF RIA&lt;/code&gt; oraz znane z &lt;code&gt;ASP&lt;/code&gt; &lt;code&gt;MembershipProvidery&lt;/code&gt;.
Tym razem przedstawię jak wymusić logowanie po stronie klienta, oraz w jaki sposób można dynamicznie zmieniać providerów, którzy walidują usera.
Poprzednim razem stworzyliśmy już szkielet aplikacji, zatem mamy projekt klienta oraz projekt serwera.
Zacznijmy od &quot;włączenia&quot; &lt;code&gt;FormsAuthentication&lt;/code&gt; po stronie klienta.
W pliku &lt;code&gt;App.xaml.cs&lt;/code&gt; , w konstruktorze dorzućmy następujące linijki&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;WebContext context = new WebContext {Authentication = new FormsAuthentication()};
ApplicationLifetimeObjects.Add(context);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Następnie zanim pokażemy treść naszej strony, musimy sprawdzić czy użytkownik jest zalogowany.
Jeżeli nie, należy pokazać okno logowania. Możemy to zrobić w następujący sposób.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;if (!WebContext.Current.User.IsAuthenticated)
{
    ModalDialogService.ShowDialog(_unityContainer.Resolve&amp;lt;IModalView&amp;lt;LoginViewModel&amp;gt;&amp;gt;(),
                                  val =&amp;gt; { InitializeView();GetSecureData(); });
}
else
{
    InitializeView();
    GetSecureData();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;WebContext&lt;/code&gt; jest to klasa generowana automatycznie przy buildowaniu solucji.
Jej kod powinniśmy odnaleźć w katalogu &lt;code&gt;Generated_Code&lt;/code&gt; po stronie klienta.
Klasa ta posiada właściwość Current, która zwraca obecny context zarejestrowany w kolekcji &lt;code&gt;ApplicationLifetimeObjects&lt;/code&gt;.
Okno logowania zostało zaimplementowane jako &lt;code&gt;ChildWindow&lt;/code&gt;. Jego kod może wyglądać w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Grid x:Name=&quot;LayoutRoot&quot; Margin=&quot;2&quot;&amp;gt;
        &amp;lt;Grid.RowDefinitions&amp;gt;
            &amp;lt;RowDefinition /&amp;gt;
            &amp;lt;RowDefinition Height=&quot;Auto&quot; /&amp;gt;
        &amp;lt;/Grid.RowDefinitions&amp;gt;
        &amp;lt;StackPanel VerticalAlignment=&quot;Center&quot;&amp;gt;
            &amp;lt;sdk:Label Content=&quot;Login&quot;&amp;gt;&amp;lt;/sdk:Label&amp;gt;
            &amp;lt;TextBox Text=&quot;{Binding Login,NotifyOnValidationError=True,Mode=TwoWay}&quot; &amp;gt;
               
            &amp;lt;/TextBox&amp;gt;
            &amp;lt;sdk:Label Content=&quot;Hasło&quot;&amp;lt;/sdk:Label&amp;gt;
            &amp;lt;PasswordBox  Password=&quot;{Binding Password,NotifyOnValidationError=True,Mode=TwoWay}&quot; &amp;gt;
            &amp;lt;/PasswordBox&amp;gt;
        &amp;lt;/StackPanel&amp;gt;
        &amp;lt;Button x:Name=&quot;CancelButton&quot; Content=&quot;Cancel&quot; Click=&quot;CancelButton_Click&quot;  Width=&quot;75&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Right&quot; Margin=&quot;0,12,0,0&quot; Grid.Row=&quot;1&quot; /&amp;gt;
        &amp;lt;Button x:Name=&quot;OKButton&quot; Content=&quot;OK&quot; Command=&quot;{Binding OkCommand}&quot; Width=&quot;75&quot; Height=&quot;23&quot; HorizontalAlignment=&quot;Right&quot; Margin=&quot;0,12,79,0&quot; Grid.Row=&quot;1&quot; /&amp;gt;
&amp;lt;/Grid&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Kontrolka logowania jest bardzo prosta, składa się ona z dwóch labelek, textboxa oraz passwordBoxa.
Powyższy kod powinien wygenerować mniej więcej takie oto okno&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-2/login.jpg&quot;&gt;&lt;img src=&quot;images/login.jpg&quot; alt=&quot;WCF RIA&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Mechanizm wywoływania operacji logowania znajduje się natomiast w &lt;code&gt;ViewModelu&lt;/code&gt; kontrolki logowania.
Po naciśnięciu przycisku &lt;code&gt;OK&lt;/code&gt;, dzięki zastosowaniu &lt;code&gt;DelegateCommand&lt;/code&gt; uruchamiany następującą funkcję&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;private void OkCommandExecuted()
{
    if (Validate())
    {
        PerfomrLoginOperation();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W funkcji tej najpierw sprawdzamy, czy użytkownik podał dane do logowania, a następnie wywołujemy kolejną funkcję &lt;code&gt;PerfomrLoginOperation&lt;/code&gt;.
Przedstawia się w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;private void PerfomrLoginOperation()
{      
    WebContext.Current.Authentication.Login(new LoginParameters(Login, Password, false,string.Empty, CompleteLoginOperation, Guid);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Widzimy zatem, że wywołujemy funkcję logowania z serwisu &lt;code&gt;WCF&lt;/code&gt;, w parametrach natomiast podajemy login oraz hasło przechwycone z okna.
Dodatkowo w parametrze podajemy delegata do funkcji, która zostanie wykonana po zakończeniu operacji logowania.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;private void CompleteLoginOperation(LoginOperation loginOperation)
{
    if (loginOperation.Error == null)
        OnOperationCompleted();
    else
    {
        if (loginOperation.Error is FormsAuthenticationLogonException)
            MessageBoxService.ShowMessageBox(&quot;Nieprawidłowy login lub hasło&quot;, MessageBoxButton.OK);
        else
            MessageBoxService.ShowMessageBox(&quot;Wystąpił problem podczas operacji logowania&quot;,
                                             MessageBoxButton.OK);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Jeżeli odpowiedź z serwisu &lt;code&gt;WCF&lt;/code&gt; zawiera błędy to wiemy, że operacja logowania się nie powiodła.
Wyświetlamy zatem stosowny komunikat. Jeżeli natomiast wszystko jest &lt;code&gt;OK&lt;/code&gt;, pole &lt;code&gt;loginOperation.Error&lt;/code&gt; będzie miało wartość &lt;code&gt;null&lt;/code&gt;.
Możemy wtedy pokazać naszą wiadomość dostępną jedynie dla zalogowanych użytkowników.&lt;/p&gt;
&lt;p&gt;Mamy zatem ochronę przeciwko nieautoryzowanemu dostępowi do klienta.
Jednak co w przypadku gdy nasz klient musi w calach np. zassania danych pobrać je przy wykorzystaniu jakiegoś &lt;code&gt;WebServicu&lt;/code&gt;.
Na ogól wystawiany jest wtedy drugi &lt;code&gt;WebService&lt;/code&gt; do pobierania danych z jakiejś bazy.
Do takiego &lt;code&gt;WebServicu&lt;/code&gt; w teorii może dostać się każdy - my natomiast chcemy żeby dane można było pobierać jedynie po zalogowaniu się do aplikacji.
Na szczęście nasz dodatkowy &lt;code&gt;WebServise&lt;/code&gt; można w prosty sposób zabezpieczyć przed dostępem osób trzecich.
Stwórzmy zatem sobie nowy &lt;code&gt;WebService&lt;/code&gt; służący do pobierania danych.
Do projektu &lt;code&gt;Webowego&lt;/code&gt; dodajmy nową klasę typu &lt;code&gt;Domain Service&lt;/code&gt; oraz dopiszmy do nie jedną metodę symulującą pobieranie danych.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[EnableClientAccess()]
public class DataAccesService : DomainService
{
    public string GetSecureData()
    {
        return &quot;very secure data&quot;;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Do takiego &lt;code&gt;Servicu&lt;/code&gt; może dostać się każdy.
Jeżeli natomiast naszą klasę udekorujemy atrybutem &lt;code&gt;[RequiresAuthentication]&lt;/code&gt; tylko użytkownicy, którzy pomyślnie przeszli autentykację przez nasz &lt;code&gt;CustomAuthenticationService&lt;/code&gt; będą w stanie pobrać dane. W przeciwnym wypadku zostanie rzucony wyjątek.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-2/debugger.jpg&quot;&gt;&lt;img src=&quot;images/debugger.jpg&quot; alt=&quot;debugger&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Zastanówmy się teraz w jaki sposób można byłoby logować się do naszej aplikacji np. przy pomocy konta &lt;code&gt;Google&lt;/code&gt;.
Zacznijmy od tego, że musimy stworzyć własny &lt;code&gt;MembershipProvider&lt;/code&gt;.
W tym celu dodajmy do projektu &lt;code&gt;Webowego&lt;/code&gt; nową klasę &lt;code&gt;GoogleMembershipProvider&lt;/code&gt;, która będzie rozszerzać klasę &lt;code&gt;MembershipProvider&lt;/code&gt;.
Klasa &lt;code&gt;MembershipProvider&lt;/code&gt; jest klasą abstrakcyjną zatem musimy zoverridować wszystkie jej funkcje (nie musimy wrzucać tam logiki, narazie po prostu wpiszmy tam cokolwiek aby przeszła kompilacja).
Mając stworzony szkielet providera musimy go dorzucić do listy wszystkich providerów (tak jak to zrobiliśmy z &lt;code&gt;SqlMembershipProvider-em&lt;/code&gt;).
Modyfikujemy zatem sekcję podsekcję providers z sekcji membership na następującą.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;membership
            defaultProvider=&quot;PremiumHandsMembershipProvider&quot;
            userIsOnlineTimeWindow=&quot;20&quot;&amp;gt;
      &amp;lt;providers&amp;gt;
        &amp;lt;clear/&amp;gt;
        &amp;lt;add name=&quot;PremiumHandsMembershipProvider&quot;
             connectionStringName=&quot;aspnetdbConnectionString&quot;
            type=&quot;System.Web.Security.SqlMembershipProvider&quot;
            enablePasswordRetrieval=&quot;false&quot;
            enablePasswordReset=&quot;false&quot;
            requiresQuestionAndAnswer=&quot;true&quot;
            passwordFormat=&quot;Hashed&quot;
            applicationName=&quot;/&quot; /&amp;gt;
        &amp;lt;add name=&quot;GoogleMembershipProvider&quot;
             type=&quot;MainModule.Web.Providers.GoogleMembershipProvider&quot;
             enablePasswordRetrieval=&quot;false&quot;
            enablePasswordReset=&quot;false&quot;
            requiresQuestionAndAnswer=&quot;true&quot;
            passwordFormat=&quot;Hashed&quot;
            applicationName=&quot;/&quot;
             /&amp;gt;
      &amp;lt;/providers&amp;gt;
&amp;lt;/membership&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Mając w kolekcji wszystkie nasze providery pozostaje nam się zastanowić, w jaki sposób raz używać &lt;code&gt;GoogleMembershpProvidera&lt;/code&gt;, a innym razem &lt;code&gt;SqlMembershipProvidera&lt;/code&gt;.
Ja zrobiłem to w następujący sposób.
Najpierw utworzyłem enuma, w którym przechowuje &quot;nazwy&quot; moich providerów&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public enum AccountType
{
    PremiumHandsMembershipProvider,
    GoogleMembershipProvider,
    Facebook
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Następnie wykorzystałem parametr customData interfejsu &lt;code&gt;IAuthentication&lt;/code&gt;.
Po stronie klienta w funkcji logowania po prostu przesyłam typ konta do którego się loguję.
Wygląda to w ten sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt; WebContext.Current.Authentication.Login(new LoginParameters(Login, Password, false,AccountType.GoogleMembershipProvider.ToString(&quot;g&quot;)), CompleteLoginOperation, Guid);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Następnie po stronie serwera wybieram tego providera, przez którego loguje się użytkownik.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;protected UserDTO ValidateCredentials(string name, string password, string customData, out string userData)
{
    UserDTO user = null;
    userData = null;
    if (Membership.Providers[customData].ValidateUser(name, password))
    //if (Membership.Provider.ValidateUser(name, password))
    {
        userData = name;
        user = new UserDTO { DisplayName = name, Name = name, Email = name};
    }
    if (user != null) userData = name;
    return user;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Zauważmy, że linijka&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;if (Membership.Provider.ValidateUser(name, password))

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;została zastąpiona przez&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;if (Membership.Providers[customData].ValidateUser(name, password))

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;zatem teraz mamy wpływ na to, którego &lt;code&gt;MembershipProvidera&lt;/code&gt; użyjemy.
Jeżeli chodzi o samo sprawdzenie czy dany użytkownik podał poprawne dane do konta google, to sprawa jest trochę kłopotliwa(tak mi się wydaje :D).
Nie udało mi się użyć biblioteki &lt;code&gt;dotNetOpenAuth&lt;/code&gt;, gdyż z tego co widzę logowanie poprzez tą bibliotekę wymaga przekierowania na stronę &lt;code&gt;Googla&lt;/code&gt;.
Niestety taka operacja nie jest dozwolona w &lt;code&gt;Silverlighcie&lt;/code&gt; (&lt;code&gt;Silverlight&lt;/code&gt; nie wspiera cross-domain policy).
Ponadto wykorzystanie tej biblioteki po stronie serwera również nie przyniosło oczekiwanych rezultatów.
Ostatecznie zatem skorzystałem z opisu znajdującego się na stronie &lt;a href=&quot;http://code.google.com/intl/pl-PL/apis/accounts/docs/AuthForInstalledApps.html#Using&quot;&gt;Googla&lt;/a&gt;.
Czyli po prostu spreparowałem odpowiedni &lt;code&gt;HTTPS Post Request&lt;/code&gt;.
Funkcja &lt;code&gt;ValidateUser&lt;/code&gt; z &lt;code&gt;GoogleMembershipProvidera&lt;/code&gt; wygląda zatem następująco&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public override bool ValidateUser(string username, string password)
{
    string requestUrl = string.Format(&quot;https://www.google.com/accounts/ClientLogin?service=mail&amp;amp;Email={0}&amp;amp;Passwd={1}&quot;, username, password);
    byte[] data = Encoding.ASCII.GetBytes(requestUrl);
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(requestUrl);
    req.ProtocolVersion = HttpVersion.Version10;
    req.ContentLength = data.Length;
    req.ContentType = &quot;application/x-www-form-urlencoded&quot;;
    req.Method = &quot;POST&quot;;
    var stream = req.GetRequestStream();
    stream.Write(data,0,data.Length);
    stream.Close();
    
    try
    {
        HttpWebResponse response = (HttpWebResponse)req.GetResponse();
        return response.StatusCode == HttpStatusCode.OK;
    }
    catch (WebException e)
    {
        return false;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Ciężko mi jednak stwierdzić czy takie logowanie jest bezpieczne.
Co prawda nie udało mi się wyłapać nic konkretnego poprzez &lt;code&gt;Wiresharka&lt;/code&gt; lub &lt;code&gt;Fiddlera&lt;/code&gt;, jednakże ekspertem od zabezpieczeń niestety nie jestem.
W następnym wpisie postaram się króciutko przedstawić bibliotekę &lt;code&gt;Microsoft Enterprise Library&lt;/code&gt;, a właściwie jeden z jej bloków - &lt;code&gt;Security Block&lt;/code&gt;.
Wykorzystam go do zezwalania użytkownikom do dostępu do funkcji serwisu, w zależności od ich roli w systemie.&lt;/p&gt;
</content:encoded></item><item><title>Silverlight - koncepcja logowania z użyciem MembershipProviders oraz WCF RIA cz.1</title><link>https://tpodolak.com/blog/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-1/</link><guid isPermaLink="true">https://tpodolak.com/blog/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-1/</guid><pubDate>Sat, 24 Dec 2011 13:12:00 GMT</pubDate><content:encoded>&lt;p&gt;W dzisiejszym wpisie postaram się przedstawić moją koncepcję logowania do aplikacji &lt;code&gt;Silverlightowej&lt;/code&gt; z wykorzystaniem &lt;code&gt;MembershipProviders&lt;/code&gt; oraz własnego &lt;code&gt;AuthenticationService&lt;/code&gt;.
Zacznijmy od stworzenia bazy danych, w której będziemy przetrzymywać informacje o użytkownikach - hasła, role itp.
Bazę danych stworzymy przy użyciu narzędzia &lt;code&gt;aspnet_regsql.exe&lt;/code&gt;, które to wygeneruje schemat bazy danych dostosowany do możliwości &lt;code&gt;SqlMembershipProvider-a&lt;/code&gt;.
&lt;code&gt;aspnet_regsq.exe&lt;/code&gt; znajduje się w katalogu &lt;code&gt;C:WINDOWS\Microsoft.NET\Framework\wersjaFrameworka\aspnet_regsql.exe&lt;/code&gt;.
Czyli w moim przypadku jest to &lt;code&gt;C:WINDOWS\Microsoft.NET\Frameworkv\4.0.30319\aspnet_regsql.exe&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-1/regsql.jpg&quot;&gt;&lt;img src=&quot;images/regsql.jpg&quot; alt=&quot;regsql&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Klikając podwójnie na ikonę aplikacji pojawia nam się następujące okno&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-1/wizzard.jpg&quot;&gt;&lt;img src=&quot;images/wizzard.jpg&quot; alt=&quot;wizzard&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Klikamy w przycisk &lt;code&gt;Dalej&lt;/code&gt;. W kolejnym oknie mamy do wyboru dwie opcje&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Configure SQL Server for application services&lt;/li&gt;
&lt;li&gt;Remove application services from an existing database&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Pierwsza opcja odpowiedzialna jest za stworzenie struktury danych do naszego sytemu logowania, natomiast druga usuwa z bazy danych tabele służące do logowania itp.
Wybieramy opcję bramkę nr 1. W kolejnym oknie musimy podać connection string do naszego serwera bazy danych oraz login i hasło.
W moim przypadku wygląda to w następujący sposób:&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-1/wizzard2.jpg&quot;&gt;&lt;img src=&quot;images/wizzard2.jpg&quot; alt=&quot;wizzard2&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Jeżeli wszystko pójdzie &lt;code&gt;OK&lt;/code&gt; pokaże się nam następujące okno, w którym to możemy zobaczyć, że została stworzona baz danych &lt;code&gt;aspnetdb&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-1/wizzard3.jpg&quot;&gt;&lt;img src=&quot;images/wizzard3.jpg&quot; alt=&quot;wizzard3&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Ostatecznie klikamy na przycisk &lt;code&gt;Next&lt;/code&gt;, a następnie w &lt;code&gt;Finish&lt;/code&gt; aby dokończyć działanie kreatora&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-1/wizzard4.jpg&quot;&gt;&lt;img src=&quot;images/wizzard4.jpg&quot; alt=&quot;wizzard4&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Mając gotową bazę danych możemy przystąpić do właściwego kodowania.
Zacznijmy od stworzenia nowego projektu typu &lt;code&gt;Silverlight Application&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-1/silverlightapp.jpg&quot;&gt;&lt;img src=&quot;images/silverlightapp.jpg&quot; alt=&quot;silverlightapp&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;po kliknięciu przycisku &lt;code&gt;OK&lt;/code&gt; włączamy &lt;code&gt;WCF RIA Service&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-1/EnableWCF.jpg&quot;&gt;&lt;img src=&quot;images/EnableWCF.jpg&quot; alt=&quot;EnableWCF&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Mając stworzony szkielet aplikacji możemy zabrać się za napisanie własnego &lt;code&gt;AuthenticationService&lt;/code&gt;.
Do projektu webowego (&lt;code&gt;nazwaprojektu.Web&lt;/code&gt;) dodajmy nowy element typu &lt;code&gt;Domain Service&lt;/code&gt;.
&lt;code&gt;PPM&lt;/code&gt; na projekt, następnie &lt;code&gt;Add new item&lt;/code&gt;, w oknie które się otworzy wybieramy &lt;code&gt;Domain Service&lt;/code&gt;.
Nadajemu mu nazwę &lt;code&gt;CustomAuthenticationService.cs&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-1/AddItemSmall.jpg&quot;&gt;&lt;img src=&quot;images/AddItemSmall.jpg&quot; alt=&quot;AddItemSmall&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-1/DomainServiceClass.jpg&quot;&gt;&lt;img src=&quot;images/DomainServiceClass.jpg&quot; alt=&quot;DomainServiceClass&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Nasza właśnie dodana klasa powinna wyglądać mniej więcej w taki sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;namespace MainModule.Web
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.ServiceModel.DomainServices.Hosting;
    using System.ServiceModel.DomainServices.Server;

    // TODO: Create methods containing your application logic.
    [EnableClientAccess()]
    public class CustomAuthenticationService: DomainService
    {
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W następnym kroku zaimplementujmy w klasie &lt;code&gt;CustomAuthenticationService&lt;/code&gt; interfejs &lt;code&gt;IAuthentication where T: IUser&lt;/code&gt;.
Interfejs ten wygląda w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public interface IAuthentication&amp;lt;T&amp;gt; where T: IUser
{
    T GetUser();
    T Login(string userName, string password, bool isPersistent, string customData);
    T Logout();
    void UpdateUser(UserDTO user);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Widzimy zatem, że zanim go zaimplementujemy musimy posiadać obiekt implementujący inny interfejs - &lt;code&gt;IUser&lt;/code&gt;.
Przystąpmy zatem do stworzenia naszej klasy modelującej użytkownika - nazwijmy ją &lt;code&gt;UserDTO&lt;/code&gt;.
Stwórzmy nowy projekt typu &lt;code&gt;Class library&lt;/code&gt;.
W projekcie tym stwórzmy klasę &lt;code&gt;UserDTO&lt;/code&gt;, która będzie dziedziczyła po klasie &lt;code&gt;UserBase&lt;/code&gt; znajdującej się w przestrzeni nazw &lt;code&gt;System.ServiceModel.DomainServices.Server.ApplicationServices&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class UserDTO : UserBase
{
    public string Email { get; set; }
    public string DisplayName { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Mając gotową klasę reprezentującą użytkownika zaimplementujmy w końcu w klasie &lt;code&gt;CustomAuthenticationService&lt;/code&gt; interfejs &lt;code&gt;IAuthentication&lt;/code&gt;.
Po implementacji interfejsu nasz serwis wygląda w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[EnableClientAccess]
public class CustomAuthenticationService: DomainService, IAuthentication
{
    public UserDTO GetUser()
    {
        throw new NotImplementedException();
    }
    
    public UserDTO Login(string userName, string password, bool isPersistent, string customData)
    {
        throw new NotImplementedException();
    }
    
    public UserDTO Logout()
    {
        throw new NotImplementedException();
    }
    
    public void UpdateUser(UserDTO user)
    {
        throw new NotImplementedException();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Pozostaje nam &quot;tylko&quot; zaimplementować odpowiednie metody. Funkcja która nas najbardziej interesuje to oczywiście funkcja logowania.
Przy jej implementacji posłuży się mechanizmem znanym z &lt;code&gt;ASP&lt;/code&gt; mianowicie z &lt;code&gt;MembershipProviders&lt;/code&gt;.
Klasa &lt;code&gt;MembershipProvider&lt;/code&gt; jest to abstrakcyjna klasa posiadająca szereg funkcji mającej na celu walidowanie poprawnego użytkownika, rejestrację itp.
Stwórzmy zatem własną klasę providera dziedziczącą po klasie &lt;code&gt;MembershipProvicer&lt;/code&gt;.
&lt;code&gt;.NET&lt;/code&gt; dostarcza nam domyślny provider, którym jest &lt;code&gt;SqlMembershipProvider&lt;/code&gt;, jest on napisany w taki sposób, aby mógł porozumiewać się z bazą, którą stworzyliśmy na początku.
Aby wykorzystać wspomnianego wcześniej providera musimy odpowiednio zmodyfikować plik &lt;code&gt;Web.config&lt;/code&gt;.
Po pierwsze dodajemy do niego &lt;code&gt;ConnectionString&lt;/code&gt; do naszej bazy danych, w moim przypadku będzie to wyglądało w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;connectionStrings&amp;gt;
    &amp;lt;add name=&quot;aspnetdbConnectionString&quot; connectionString=&quot;Data Source=TOMEKKOMPUTERSQLEXPRESSRC2;Initial Catalog=aspnetdb;Integrated Security=True&quot;
      providerName=&quot;System.Data.SqlClient&quot; /&amp;gt;
&amp;lt;/connectionStrings&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Następnie musimy &quot;pokazać&quot; naszej aplikacji, że będziemy używać &lt;code&gt;FormsAuthentication&lt;/code&gt; oraz &lt;code&gt;MembershipProvider-ow&lt;/code&gt;.
Dorzućmy zatem do config następujące rzeczy:(w sekcji &lt;code&gt;system.web&lt;/code&gt;)&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;authentication mode=&quot;Forms&quot; /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;następnie dorzucamy do kolekcji providerów &lt;code&gt;SqlMembershipProvider&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;membership
            defaultProvider=&quot;PremiumHandsMembershipProvider&quot;
            userIsOnlineTimeWindow=&quot;20&quot;&amp;gt;
      &amp;lt;providers&amp;gt;
        &amp;lt;clear/&amp;gt;
        &amp;lt;add name=&quot;PremiumHandsMembershipProvider&quot;
             connectionStringName=&quot;aspnetdbConnectionString&quot;
            type=&quot;System.Web.Security.SqlMembershipProvider&quot;
            enablePasswordRetrieval=&quot;false&quot;
            enablePasswordReset=&quot;false&quot;
            requiresQuestionAndAnswer=&quot;true&quot;
            passwordFormat=&quot;Hashed&quot;
            applicationName=&quot;/&quot; /&amp;gt;
      &amp;lt;/providers&amp;gt;
&amp;lt;/membership&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We wpisach tych dorzuciliśmy możliwość autentykacji poprzez providery, ustawiliśmy &lt;code&gt;SqlMembershipProvider&lt;/code&gt; jako domyślny provider, oraz dorzuciliśmy go do listy wszystkich providerów.
W celu sprawdzenia czy nasza konfiguracja jest poprawna możemy posłużyć się mechanizmem dostarczonym nam przez &lt;code&gt;Visual Studio&lt;/code&gt;.
Klikamy &lt;code&gt;Projekt&lt;/code&gt;, a następnie &lt;code&gt;ASP.NET Configuration&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-1/ASPConfiguration.jpg&quot;&gt;&lt;img src=&quot;images/ASPConfiguration.jpg&quot; alt=&quot;ASPConfiguration&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Zostaniemy przeniesieni do domyślnej przeglądarki internetowej, a naszym oczom ukaże się następująca strona.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/silverlight-koncepcja-logowania-z-uzyciem-membershipproviders-oraz-wcf-ria-cz-1/AdminTool.jpg&quot;&gt;&lt;img src=&quot;images/AdminTool.jpg&quot; alt=&quot;AdminTool&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Z poziomu tej stronki możemy dodawać użytkowników, przydzielać im role itp, dzięki czemu możemy szybko sprawdzić czy podstawowe funkcje naszego providera działają, oraz czy nasza konfiguracja została przeprowadzona prawidłowo.
Wracając natomiast do naszego systemu logowania, pozostało nam jedynie odpowiednio zmodyfikować funkcję odpowiedzialną za logowanie.
Robimy to w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;protected  UserDTO ValidateCredentials(string name, string password, string customData, out string userData)
{
    UserDTO user = null;
    userData = null;
    
    if (Membership.Provider.ValidateUser(name, password))
    {
        userData = name;
        user =  new UserDTO {DisplayName = name,Name = name,Email = name};
    }
    
    if (user != null) userData = name;
    
    return user;
}

public UserDTO Login(string userName, string password, bool isPersistent, string customData)
{
    string userData;
    UserDTO user = ValidateCredentials(userName, password, customData, out userData);
    
    if (user != null)
    {
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(/* version */ 1, userName,
                                                   DateTime.Now, DateTime.Now.AddMinutes(30),
                                                   isPersistent,
                                                   userData,
                                                   FormsAuthentication.FormsCookiePath);
                                                   
        string encryptedTicket = FormsAuthentication.Encrypt(ticket);
        HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
        HttpContextBase httpContext = (HttpContextBase)ServiceContext.GetService(typeof(HttpContextBase));
        httpContext.Response.Cookies.Add(authCookie);
    }
    else
    {
        HttpContextBase httpContext = (HttpContextBase)ServiceContext.GetService(typeof(HttpContextBase));
        httpContext.AddError(new FormsAuthenticationLogonException(&quot;Nieprawidłowy login lub hasło&quot;));
    }
    return user;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W funkcji &lt;code&gt;ValidateCredentials&lt;/code&gt; odbywa się sprawdzanie czy użytkownik podał właściwe hasło oraz login.
Do walidacji wykorzystujemy dodany wcześniej &lt;code&gt;SqlMembershipProvider&lt;/code&gt; - właściwość &lt;code&gt;Membership.Provider&lt;/code&gt; zawsze zwraca obiekt domyślnie zdefiniowanego providera.
W przypadku gdy walidacja się powiedzie tworzymy obiekt użytkownika, a następnie tworzymy i szyfrujemy &lt;code&gt;FormsAuthenticationTicket&lt;/code&gt; oraz tworzymy ciasteczko (&lt;code&gt;cookie&lt;/code&gt;), które przesyłamy w responsie wysyłanym przez serwer do klienta.
Mechanizm logowania jest już prawie gotowy. Musimy jedynie zaimplementować jeszcze pozostałe funkcje interfejsu &lt;code&gt;IAuthentication&lt;/code&gt;.
Nie ma raczej w nich nic trudnego&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public UserDTO Logout()
{
    FormsAuthentication.SignOut();
    return null;
}

public UserDTO GetUser()
{
    IPrincipal currentUser = ServiceContext.User;
    
    if ((currentUser != null) &amp;amp;&amp;amp; currentUser.Identity.IsAuthenticated)
    {
        FormsIdentity userIdentity = currentUser.Identity as FormsIdentity;
        if (userIdentity != null)
        {
            FormsAuthenticationTicket ticket = userIdentity.Ticket;
            if (ticket != null &amp;amp;&amp;amp; !ticket.Expired)
            {
                 return new UserDTO { DisplayName = currentUser.Identity.Name, Name = currentUser.Identity.Name };
            }
        }
    }
    
    return null;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Funkcja &lt;code&gt;Logout&lt;/code&gt; po prostu wywołuje funkcję &lt;code&gt;SingOut&lt;/code&gt; z klasy &lt;code&gt;FormsAuthentication&lt;/code&gt;.
Natomiast funkcja &lt;code&gt;GetUser&lt;/code&gt; zwraca zalogowanego użytkownika.
W funkcji tej najpierw sprawdzamy czy użytkownik jest zalogowany (do tego celu używamy zmiennej &lt;code&gt;IsAuthenticated&lt;/code&gt;), a następnie sprawdzamy czy przypadkiem jego sesja nie wygasła.
W przypadku gdy wszystko jest &lt;code&gt;OK&lt;/code&gt; zwracamy obiekt typu &lt;code&gt;UserDTO&lt;/code&gt;, w przeciwnym razie zwracamy &lt;code&gt;null&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Podsumowując, udało nam się stworzyć mechanizm logowania. Jak na razie gotowa jest strona serwera.
W następnym wpisie pokażę w jaki sposób należy wywołać logowanie od strony klienta. Przedstawię również pomysł w jaki sposób zmieniać providerów przez które użytkownik ma się logować. Może to być przydatne jeżeli chcielibyśmy logować się np. poprzez inne serwisy jak &lt;code&gt;Google&lt;/code&gt;, &lt;code&gt;Facebook&lt;/code&gt; itp.&lt;/p&gt;
</content:encoded></item><item><title>Coded UI Test - tworzenie testów UI przy pomocy Visual Studio Ultimate</title><link>https://tpodolak.com/blog/coded-ui-test-tworzenie-testow-ui-przy-pomocy-visual-studio-ultimate/</link><guid isPermaLink="true">https://tpodolak.com/blog/coded-ui-test-tworzenie-testow-ui-przy-pomocy-visual-studio-ultimate/</guid><pubDate>Sun, 04 Dec 2011 00:54:00 GMT</pubDate><content:encoded>&lt;p&gt;Poszukując sposobów automatycznego testowania aplikacji natrafiłem na ciekawą funkcjonalność &lt;code&gt;Visual Studio 2010 Ultimate&lt;/code&gt;.
Mianowicie w tej wersji naszego ulubionego &lt;code&gt;IDE&lt;/code&gt; znalazło się miejsce na nowy typ testów - &lt;code&gt;Coded UI Test&lt;/code&gt;.
&lt;code&gt;Coded UI Test&lt;/code&gt; jest to automatyczny test &lt;code&gt;UI&lt;/code&gt;, który tworzymy poprzez nagrywanie akcji jakie wykonujemy w naszej aplikacji.
Nie musimy pisać ani jednej linijki kodu żeby przetestować jakąś funkcjonalność naszego programu.
Jedyne co musimy zrobić jest to przejście przez wszystkie niezbędne kroki w naszej aplikacji, tak aby zweryfikować naszą funkcjonalność.
W celu stworzenia &lt;code&gt;Coded UI Test&lt;/code&gt; musimy po pierwsze zaopatrzyć się w wersję &lt;code&gt;Ultimate Visual Studio 2010&lt;/code&gt;.
Z tego co wiem, niestety niższe wersje nie mają funkcjonalności automatycznego testowania.
Następnie musimy stworzyć nowy &lt;code&gt;Test Project&lt;/code&gt;. W tym celu z menu &lt;code&gt;File&lt;/code&gt; wybieramy &lt;code&gt;New&lt;/code&gt; a następnie &lt;code&gt;Project&lt;/code&gt;.
W oknie, które się pokaże, w drzewie po lewej stronie wybieramy &lt;code&gt;Test&lt;/code&gt;, a następnie w prawej części okna &lt;code&gt;Test Project&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/coded-ui-test-tworzenie-testow-ui-przy-pomocy-visual-studio-ultimate/Project.jpg&quot;&gt;&lt;img src=&quot;images/Project.jpg&quot; alt=&quot;Project&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Mając stworzony projekt testowy dodajemy do niego nowy &lt;code&gt;Coded UI Test&lt;/code&gt;.
W &lt;code&gt;Solution Explore-rze&lt;/code&gt; klikamy &lt;code&gt;PPM&lt;/code&gt; na projekt testowy, a następnie z menu contextowego wybieramy &lt;code&gt;Coded UI Test&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/coded-ui-test-tworzenie-testow-ui-przy-pomocy-visual-studio-ultimate/CodedUITest.png&quot;&gt;&lt;img src=&quot;images/CodedUITest.png&quot; alt=&quot;CodedUITest&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;W oknie, które się pojawi wybieramy &lt;code&gt;Record actions, edit UI map or add assertion&lt;/code&gt; lub gdy mamy już gotowe testy możemy wybrać opcję nr 2.
Po wybraniu pierwszej opcji okno &lt;code&gt;Visual Studio&lt;/code&gt; zostanie zminimalizowane, a w prawym dolnym rogu pulpitu ukaże się następujące okienko.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/coded-ui-test-tworzenie-testow-ui-przy-pomocy-visual-studio-ultimate/Record.jpg&quot;&gt;&lt;img src=&quot;images/Record.jpg&quot; alt=&quot;Record&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Służy ono do nagrywania testu. Naciskając czerwony przycisk rozpoczynamy proces nagrywania testu.
W moim przypadku będę testować aplikację, którą testowałem również w poprzednim poście.
Wykonuje zatem czynności mające na celu sprawdzenie funkcjonalności dodawania liczb.
Po kliknięciu na textbox-a pojawia się nad nim dymek,że dana akcja jest nagrywana.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/coded-ui-test-tworzenie-testow-ui-przy-pomocy-visual-studio-ultimate/UI.jpg&quot;&gt;&lt;img src=&quot;images/UI.jpg&quot; alt=&quot;UI&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Po &quot;wyklikaniu&quot; całej ścieżki mającej sprawdzić funkcjonalność klikamy przycisk &lt;code&gt;Generate code&lt;/code&gt; (ten najbardziej z prawej strony).
Następnie w okienku, które się pojawi&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/coded-ui-test-tworzenie-testow-ui-przy-pomocy-visual-studio-ultimate/MethodName.jpg&quot;&gt;&lt;img src=&quot;images/MethodName.jpg&quot; alt=&quot;MethodName&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;podajemy nazwę naszego testu. Po kliknięciu &lt;code&gt;OK&lt;/code&gt;, &lt;code&gt;Visual Studio&lt;/code&gt; wygeneruje nam kod odpowiedzialny za nasz test.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/coded-ui-test-tworzenie-testow-ui-przy-pomocy-visual-studio-ultimate/SourceUIMap.jpg&quot;&gt;&lt;img src=&quot;images/SourceUIMap.jpg&quot; alt=&quot;SourceUIMap&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;W celu odpalenia naszego testu z menu &lt;code&gt;Test&lt;/code&gt; wybieramy &lt;code&gt;Run&lt;/code&gt;, a następnie &lt;code&gt;Tests in Current Context&lt;/code&gt;.
&lt;code&gt;Visual Studio&lt;/code&gt; przejdzie teraz wszystkie kroki, które zostały nagrane w teście.
Ok, niby wszystko ładnie pięknie, ale tak naprawdę nic nie sprawdziliśmy.
Jedyne co zrobiliśmy to wykonaliśmy pewne operacje na naszej aplikacji, jednakże nie zweryfikowaliśmy danych otrzymanych w wyniku operacji dodaj.
W celu dodania warunku sprawdzającego do naszego testu, musimy dodać tzw. asercję.
Aby to zrobić klikamy &lt;code&gt;PPM&lt;/code&gt; na wolne pole edytora, pod funkcją &lt;code&gt;this.UIMap.RecordedMethod1()&lt;/code&gt; (ta funkcja została wygenerowana podczas nagrywania testu).
Następnie z menu contextowego wybieramy&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/coded-ui-test-tworzenie-testow-ui-przy-pomocy-visual-studio-ultimate/Generate.jpg&quot;&gt;&lt;img src=&quot;images/Generate.jpg&quot; alt=&quot;Generate&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Otwiera nam się znane już wcześniej okienko nagrywania testu.
Jednakże tym razem naciśnijmy przycisk celownika i przeciągnijmy go na textbox-a, w którym ma pojawić się wynik dodawania&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/coded-ui-test-tworzenie-testow-ui-przy-pomocy-visual-studio-ultimate/AutomationAdding.jpg&quot;&gt;&lt;img src=&quot;images/AutomationAdding.jpg&quot; alt=&quot;AutomationAdding&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Nasz textbox zostanie obramowany, natomiast w prawym dolnym rogu pulpitu pojawi się nowe okno pokazujące propertisy naszego przycisku.
Wybierzmy właściwość &lt;code&gt;Text&lt;/code&gt; ,a następnie naciśnijmy przycisk &lt;code&gt;Add Assertion&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/coded-ui-test-tworzenie-testow-ui-przy-pomocy-visual-studio-ultimate/Assertion.jpg&quot;&gt;&lt;img src=&quot;images/Assertion.jpg&quot; alt=&quot;Assertion&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;W oknie, które się pojawi możemy wybrać warunek, który musi spełnić dana właściwość (w tym przypadku &lt;code&gt;Text&lt;/code&gt;), aby test przeszedł.
Ustawmy tam wartość np. 3. Następnie klikamy &lt;code&gt;OK&lt;/code&gt; oraz nadajemy nazwę naszej assercji.
Po wykonaniu tych czynności w kodzie naszego pojawi się dodatkowa linijka&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/coded-ui-test-tworzenie-testow-ui-przy-pomocy-visual-studio-ultimate/AddAssertion.jpg&quot;&gt;&lt;img src=&quot;images/AddAssertion.jpg&quot; alt=&quot;AddAssertion&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Teraz za każdym razem gdy odpalimy test na samym jego końcu będzie sprawdzana nasza assercja.
W przypadku gdy wartość właściwości Text nie będzie równa 3 nasz test nie przejdzie.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/coded-ui-test-tworzenie-testow-ui-przy-pomocy-visual-studio-ultimate/AssertionFailed.jpg&quot;&gt;&lt;img src=&quot;images/AssertionFailed.jpg&quot; alt=&quot;Coded UI Test&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>UI Automation - czyli testy automatyczne w .NET</title><link>https://tpodolak.com/blog/ui-automation-czyli-testy-automatyczne-w-net/</link><guid isPermaLink="true">https://tpodolak.com/blog/ui-automation-czyli-testy-automatyczne-w-net/</guid><pubDate>Sat, 03 Dec 2011 15:10:00 GMT</pubDate><content:encoded>&lt;p&gt;Biblioteka &lt;code&gt;Microsoft UI Automation&lt;/code&gt; ujrzała światło dzienne wraz z premierą &lt;code&gt;.NET 3.0&lt;/code&gt; - jednakże pozostała ona w cieniu swoich większych braci &lt;code&gt;WPF&lt;/code&gt; oraz &lt;code&gt;WPF&lt;/code&gt;, które również zostały wprowadzone do &lt;code&gt;Frameworka 3.0&lt;/code&gt;.
&lt;code&gt;Microsoft UI automation&lt;/code&gt; zapewnia nam dostęp do wszystkich elementów drzewa wizualnego aplikacji. Dzięki czemu mamy możliwość:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Znajdowania wybranych przez nas kontrolek&lt;/li&gt;
&lt;li&gt;Interakcji z kontrolkami - wpisywanie tekstów do TextBox-ów, klikanie w przyciski itp&lt;/li&gt;
&lt;li&gt;Wczytywania wartości już wprowadzonych do kontrolek&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Każda kontrolka znajdująca się na widoku jest traktowana przez &lt;code&gt;UI Automation&lt;/code&gt; jako &lt;code&gt;AutomationElement&lt;/code&gt;.
Rootem naszego drzewa wizualnego pulpit, dostęp do niego uzyskujemy poprzez statyczną właściwość&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;AutomationElement.RootElement

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Mając dostęp do roota możemy następnie poruszać się po drzewie tak aby znaleźć interesujące nas elementy.
Załóżmy, że napisaliśmy prostą aplikację &lt;code&gt;WPF-ową&lt;/code&gt;, która wykonuje podstawowe obliczenia matematyczne (pomysł na prostą aplikację do testowania zaczerpnięty z &lt;a href=&quot;http://blog.ganeshzone.net/index.php/2011/08/automated-ui-testing-of-wpf-applications-using-microsoft-ui-automation-library/&quot;&gt;tej&lt;/a&gt; strony - kod jednak pisałem po swojemu :D).
Wizualnie aplikacja ta przedstawia się w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Window x:Class=&quot;UIAutomation.Views.MainWindow&quot;
        xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
        Height=&quot;350&quot; Width=&quot;525&quot; Title=&quot;{Binding Title}&quot;&amp;gt;
    &amp;lt;Grid x:Name=&quot;SomeUniqueName1&quot;&amp;gt;
        &amp;lt;Grid.RowDefinitions&amp;gt;
            &amp;lt;RowDefinition&amp;gt;&amp;lt;/RowDefinition&amp;gt;
            &amp;lt;RowDefinition&amp;gt;&amp;lt;/RowDefinition&amp;gt;
            &amp;lt;RowDefinition&amp;gt;&amp;lt;/RowDefinition&amp;gt;
            &amp;lt;RowDefinition&amp;gt;&amp;lt;/RowDefinition&amp;gt;
        &amp;lt;/Grid.RowDefinitions&amp;gt;
        &amp;lt;Grid.ColumnDefinitions&amp;gt;
            &amp;lt;ColumnDefinition&amp;gt;&amp;lt;/ColumnDefinition&amp;gt;
            &amp;lt;ColumnDefinition&amp;gt;&amp;lt;/ColumnDefinition&amp;gt;
            &amp;lt;ColumnDefinition&amp;gt;&amp;lt;/ColumnDefinition&amp;gt;
            &amp;lt;ColumnDefinition&amp;gt;&amp;lt;/ColumnDefinition&amp;gt;
        &amp;lt;/Grid.ColumnDefinitions&amp;gt;
        &amp;lt;Label Content=&quot;Pierwsza liczba:&quot; HorizontalAlignment=&quot;Center&quot; VerticalAlignment=&quot;Center&quot; Grid.ColumnSpan=&quot;2&quot;&amp;gt;&amp;lt;/Label&amp;gt;
        &amp;lt;Label Content=&quot;Druga liczba:&quot; HorizontalAlignment=&quot;Center&quot; VerticalAlignment=&quot;Center&quot; Grid.Row=&quot;1&quot; Grid.ColumnSpan=&quot;2&quot;&amp;gt;&amp;lt;/Label&amp;gt;
        &amp;lt;Label Content=&quot;Wynik:&quot; HorizontalAlignment=&quot;Center&quot; VerticalAlignment=&quot;Center&quot; Grid.Row=&quot;2&quot;  Grid.ColumnSpan=&quot;2&quot;&amp;gt;&amp;lt;/Label&amp;gt;
        &amp;lt;Button Name=&quot;btnAdd&quot;  Grid.Column=&quot;0&quot; Grid.Row=&quot;3&quot; Content=&quot;Dodaj&quot; Command=&quot;{Binding AddCommand}&quot; /&amp;gt;
        &amp;lt;Button Name=&quot;btnSubtract&quot; Grid.Column=&quot;1&quot; Grid.Row=&quot;3&quot;  Content=&quot;Odejmij&quot; Command=&quot;{Binding SubstractCommand}&quot; /&amp;gt;
        &amp;lt;Button Name=&quot;btnMultiply&quot; Grid.Column=&quot;2&quot; Grid.Row=&quot;3&quot;  Content=&quot;PomnÃ³Å¼&quot; Command=&quot;{Binding MultiplyCommand}&quot; /&amp;gt;
        &amp;lt;Button Name=&quot;btnDivide&quot; Grid.Column=&quot;3&quot; Grid.Row=&quot;3&quot;  Content=&quot;Podziel&quot; Command=&quot;{Binding DivideCommand}&quot; /&amp;gt;
        &amp;lt;TextBox Name=&quot;txtFirstNumber&quot;  Grid.Column=&quot;2&quot;  VerticalAlignment=&quot;Center&quot; Grid.ColumnSpan=&quot;2&quot; Text=&quot;{Binding FirstNumber,Mode=TwoWay}&quot;&amp;gt;&amp;lt;/TextBox&amp;gt;
        &amp;lt;TextBox Name=&quot;txtSecondNumber&quot; Grid.Column=&quot;2&quot; Grid.Row=&quot;1&quot; HorizontalAlignment=&quot;Stretch&quot; VerticalAlignment=&quot;Center&quot; Text=&quot;{Binding SecondNumber,Mode=TwoWay}&quot; Grid.ColumnSpan=&quot;2&quot;&amp;gt;&amp;lt;/TextBox&amp;gt;
        &amp;lt;TextBox Name=&quot;txtResult&quot;  Grid.Column=&quot;2&quot; Grid.Row=&quot;2&quot; HorizontalAlignment=&quot;Stretch&quot; VerticalAlignment=&quot;Center&quot; Text=&quot;{Binding Result,Mode=TwoWay}&quot; Grid.ColumnSpan=&quot;2&quot;&amp;gt;&amp;lt;/TextBox&amp;gt;
    &amp;lt;/Grid&amp;gt;
&amp;lt;/Window&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W celu poruszania się po drzewie wizualnym możemy skorzystać z dwóch metod&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public AutomationElement FindFirst(TreeScope scope, Condition condition);
public AutomationElementCollection FindAll(TreeScope scope, Condition condition);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;pierwsza z nich zwraca nam konkretny element, który spełnia podane przez nas kryterium.
Pierwszy parametr funkcji TreeScope scope określa nam sposób przeszukiwania drzewa wizualnego. Dostępne opcje to:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Element&lt;/code&gt; - wyszukiwanie odbywa się tylko na danym elemencie&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Children&lt;/code&gt; - wyszukiwanie odbywa się na wszystkich dzieciach danego elementu - nie zagłębiamy się rekurencyjnie,sprawdzamy tylko jeden poziom w dół od danego elementu&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Descendants&lt;/code&gt; - wyszukiwanie odbywa się na wszystkich potomkach - przeszukiwanie rekurencyjne w dół&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Subtree&lt;/code&gt; - wyszukiwanie odbywa się na wszystkich potomkach, oraz elemencie od którego zaczynamy&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Ancestors&lt;/code&gt; - wyszukiwanie odbywa się na wszystkich rodzicach - rekurencyjnie w górę drzewa&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Drugim z parametrów jakie musimy podać jest to &lt;code&gt;UIAutomation.Condition&lt;/code&gt;.
Parametr ten określa jaki warunek musi spełnić dany element aby został uwzględniony w wyniku wyszukiwania.
Sama klasa &lt;code&gt;Condition&lt;/code&gt; jest klasą abstrakcyjną, z której dziedziczą wyspecjalizowane klasy.
Do określenia warunków najczęściej będziemy korzystać z potomka klasy &lt;code&gt;Condition&lt;/code&gt;, mianowicie z&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;PropertyCondition

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;określa ona jaka właściwość kontrolki/aplikacji będzie uwzględniana przy wyszukiwaniu wyniku.&lt;/p&gt;
&lt;p&gt;Pierwszym krokiem przy testowaniu aplikacji będzie oczywiście znalezienie głównego okna programu.
Mając w solucji stworzony projekt z aplikacją &lt;code&gt;WPF-ową&lt;/code&gt;, dodajmy drugi projekt - tym razem będzie to projekt typu &lt;code&gt;ConsoleApplication&lt;/code&gt;.
Następnie musimy dodać referencję do odpowiednich ddl-ek.
Potrzebujemy następujących bibliotek:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;UIAutomation.dll&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;UIAutomationClient.dll&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;UIAutomationType.dll&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Następnie w naszym projekcie konsolowym w metodzie main odpalamy aplikację, którą chcemy testować.
W moim przypadku wygląda to w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Console.WriteLine(&quot;Odpalam aplikacje&quot;);
Process p = Process.Start(&quot;..\..\..\UIAutomation\bin\Debug\UIAutomation.exe&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Następnie musimy dostać się do głównego okna testowanej aplikacji. Możemy to zrobić używając funkcji &lt;code&gt;FindFirst&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;AutomationElement mainForm =  AutomationElement.RootElement.FindFirst(TreeScope.Children,new PropertyCondition(AutomationElement.ProcessIdProperty, p.Id));
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;lub możemy uzyskać dostęp do okna przy pomocy funkcji&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;AutomationElement mainForm = AutomationElement.FromHandle(p.MainWindowHandle);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W pierwszym przypadku wykorzystując funkcję &lt;code&gt;FindFirst&lt;/code&gt; przeszukujemy wszystkie dzieci (&lt;code&gt;TreeScope.Children&lt;/code&gt;) roota (czyli pulpitu).
Jako warunek wyszukiwania podaliśmy obiekt klasy &lt;code&gt;PropertyCondition&lt;/code&gt;.
Jako właściwość do porównywania podaliśmy id processu (&lt;code&gt;AutomationElement.ProcessIdProperty&lt;/code&gt;).
W drugim przypadku po prostu uzyskujemy dostęp do okna dzięki znajomości jego uchwytu (właściwość &lt;code&gt;MainWindowHandle&lt;/code&gt; z klasy &lt;code&gt;Process&lt;/code&gt;).
Według mnie lepiej skorzystać z funkcji pierwszej, zwłaszcza gdy odpalamy aplikację, która się długo uruchamia.
W pierwszym przypadku wystarczy zrobić odpowiednią funkcję oczekującą na odpalanie (gdyż funkcja zwróci nam &lt;code&gt;null&lt;/code&gt; gdy okna jeszcze nie będzie), natomiast druga opcja rzuci nam wyjątek.
Oczekiwania na załadowanie okna może wyglądać w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;AutomationElement mainForm;
while ((mainForm = AutomationElement.RootElement.FindFirst(TreeScope.Children,new PropertyCondition(AutomationElement.ProcessIdProperty,p.Id)))==null)
{
    Thread.Sleep(100);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Mając dostęp do głównego okna możemy przeprowadzić testy - przetestujemy czy po wpisaniu danych do tekstboksów i przeprowadzeniu odpowiednich akcji (dodawanie,usuwanie,odejmowanie,dzielenie) w polu wynik pojawi się odpowiednia wartość.
Zacznijmy od zlokalizowania textboxów. Posłużmy się tutaj przedstawioną wcześniej funkcją &lt;code&gt;FindFirst&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var firstTextbox = mainForm.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.AutomationIdProperty, &quot;txtFirstNumber&quot;));
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Wyszukiwanie odbywa się po właściwości &lt;code&gt;AutomationElement.AutomationIdProperty&lt;/code&gt; - właściwość ta jest zawsze taka sama jak nazwa kontrolki - chyba, że ktoś ją zmieni przy pomocy &lt;code&gt;AttachedProperty&lt;/code&gt; &lt;code&gt;AutomationProperties.AutomationId&lt;/code&gt;.
Odpalając powyższy kod okazuje się, że nasza zmienna firstTextbox jest nullem - czyli framework nie był w stanie znaleźć naszego textboxa.
Dlaczego tak się stało? Odpowiedzi może nam dostarczyć aplikacja &lt;code&gt;Snoop&lt;/code&gt;, dzięki której możemy podejrzeć drzewo wizualne naszego programu.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/ui-automation-czyli-testy-automatyczne-w-net/snoopResult.jpg&quot;&gt;&lt;img src=&quot;images/snoopResult.jpg&quot; alt=&quot;snoopResult&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Na powyższym screenie widzimy, że szukany textbox nie jest bezpośrednim dzieckiem &lt;code&gt;MainWindow&lt;/code&gt;, jest natomiast dzieckiem grida (tego można było się spodziewać zwłaszcza, że umieściliśmy textbox w gridzie).
Zauważmy jednak, że MainWindow nie jest bezpośrednim rodzicem grida - znajduje się on dopiero na poziomie 4 w drzewie.
Z racji dużego skomplikowania drzewa wizualnego aplikacji według mnie bezpiecznie jest używać funkcji &lt;code&gt;Find&lt;/code&gt; z parametrem &lt;code&gt;TreeScope.Descendants&lt;/code&gt;.
Unikniemy dzięki temu przykrych niespodzianek z nieodnalezionymi kontrolkami.
Nasza funkcja zatem powinna wyglądać w następujący sposób.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var firstTextbox = mainForm.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, &quot;txtFirstNumber&quot;));

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W analogiczny sposób znajdujemy pozostałe przyciski na naszej formie, a następnie postarajmy się wprowadzić do nich jakiś text.
W celu interakcji z kontrolkami wykorzystamy tzw. &lt;code&gt;Patterns&lt;/code&gt;.
&lt;code&gt;Patterns&lt;/code&gt; definiują określone funkcjonalności, które wspiera nasza kontrolka.
Do najczęściej używanych patterns należą:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;SelectionPattern&lt;/code&gt; - używany do manipulacjami kontrolkami wspierającymi zaznaczanie np. &lt;code&gt;ListBox-ami&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;TextPattern&lt;/code&gt; - używany do manipulacjami kontrolkami wspierającymi edycję&lt;/li&gt;
&lt;li&gt;&lt;code&gt;ValuePattern&lt;/code&gt; - używany do pobierania i ustawiania wartości kontrolek nie wspierających wielokrotnych wartości&lt;/li&gt;
&lt;li&gt;&lt;code&gt;InvokePattern&lt;/code&gt; - używane do kontrolek wspierających wywołania - np. przyciski (wywołanie przyciśnięcia)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;ScrollPattern&lt;/code&gt; - używane do kontrolek posiadających &lt;code&gt;ScrolBar-y&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;RangeValuePattern&lt;/code&gt; - używany do kontrolek mogących posiadać jakiś zakres wartości np. &lt;code&gt;ComboBox&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Zatem w celu ustawienia wartości w textbox-ie posłużymy się następującym kodem&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var pattern = txtFirstNumber.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
pattern.SetValue(&quot;50&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W analogiczny sposób ustawiamy zawartość drugiego textbox-a&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var pattern = txtSecondNumber.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
pattern.SetValue(&quot;50&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Mając wprowadzone dane do textbox-ów wypadałoby teraz przeprowadzić obliczenia.
Zatem musimy w jakiś sposób aby &quot;nacisnąć&quot; jeden z naszych czterech przycisków.
Znajdźmy zatem nasze przyciski:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var btnAdd = mainForm.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, &quot;btnAdd&quot;));
var btnSubtract = mainForm.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, &quot;btnSubtract&quot;));
var btnMultiply = mainForm.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, &quot;btnMultiply&quot;));
var btnDivide = mainForm.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, &quot;btnDivide&quot;));
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Następnie wykorzystując wspomniany wcześniej &lt;code&gt;InvokePattern&lt;/code&gt; naciśnijmy przycisk &lt;code&gt;Dodaj&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;InvokePattern ipClickButton1 = (InvokePattern)btnAdd.GetCurrentPattern(InvokePattern.Pattern);
ipClickButton1.Invoke();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Ostatnim krokiem będzie zweryfikowanie czy wartość w textbox-ie txtResult jest zgodna z oczekiwaniami.
W celu wyciągnięcia wartości z txtResult po raz kolejny posłużę się &lt;code&gt;ValuePattern&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;var value = (txtResult.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern).Current.Value
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Wynik otrzymany w textbox-ie porównujemy z oczekiwanym rezultatem&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Console.Write(&quot;Dodawanie test OK ? , {0}&quot;,value == &quot;100&quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Na koniec najlepiej wrzucić nasz test w jakąś pętle, losowo generować wartości oraz porównywać je z wartościami oczekiwanymi.
Dobrym pomysłem jest również stworzenie sobie jakiejś klasy pomocniczej, w której zostałyby umieszczone funkcje do wypełniania textbox-ow, klikania w buttony itp - gdyż jak widać dużo kodu jest powtarzalna.
Ostatecznie aplikacja testowa może wyglądać w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;class Program
{
    static void Main(string[] args)
    {
        Random rand = new Random();
        try
        {
            Console.WriteLine(&quot;Odpalam aplikacje&quot;);
            Process p = Process.Start(&quot;..\..\..\UIAutomation\bin\Debug\UIAutomation.exe&quot;);
            AutomationElement mainForm;
            while ((mainForm = AutomationElement.RootElement.FindFirst(TreeScope.Children,new PropertyCondition(AutomationElement.ProcessIdProperty,p.Id)))==null)
            {
                Thread.Sleep(100);
            }
            
            var txtFirstNumber = mainForm.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, &quot;txtFirstNumber&quot;));
            var txtSecondNumber = mainForm.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, &quot;txtSecondNumber&quot;));
            var txtResult = mainForm.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, &quot;txtResult&quot;));
            
            var btnAdd = mainForm.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, &quot;btnAdd&quot;));
            var btnSubtract = mainForm.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, &quot;btnSubtract&quot;));
            var btnMultiply = mainForm.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, &quot;btnMultiply&quot;));
            var btnDivide = mainForm.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, &quot;btnDivide&quot;));
            
            for (int i = 0; i &amp;lt; 200; i++)
            {
                double firstNumber = rand.Next(1, 1000);
                double seconNumber = rand.Next(1, 1000);
                Console.WriteLine(&quot;nn Test dla wartości: {0} , {1}&quot;, firstNumber, seconNumber);
                txtFirstNumber.SetTextBoxValue(firstNumber.ToString());
                txtSecondNumber.SetTextBoxValue(seconNumber.ToString());
                btnAdd.Click();
                Console.WriteLine(&quot;Dodawanie test OK ? , {0}&quot;, txtResult.GetTextBoxValue().ConvertToDouble() == firstNumber + seconNumber);
                btnDivide.Click();
                Console.WriteLine(&quot;Dzielenie test OK ? , {0}&quot;, Math.Round(txtResult.GetTextBoxValue().ConvertToDouble(), 2) == Math.Round(firstNumber / seconNumber, 2));
                btnSubtract.Click();
                Console.WriteLine(&quot;Odejmowanie test OK ? , {0}&quot;, txtResult.GetTextBoxValue().ConvertToDouble() == firstNumber - seconNumber);
                btnMultiply.Click();
                Console.WriteLine(&quot;Mnożenie test OK ? , {0}&quot;, txtResult.GetTextBoxValue().ConvertToDouble() == firstNumber * seconNumber);
            }
            
            Console.WriteLine(&quot;nEnd test runn&quot;);
            Console.ReadKey();
            p.Close();
            p.Kill();
        }
        catch (Exception ex)
        {
            Console.WriteLine(&quot;Fatal error: &quot; + ex.Message);
            Console.WriteLine(&quot;nEnd test runn&quot;);
            Console.ReadKey();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;oraz klasa pomocnicza&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static class UiAutomationHelper
{
    public static string GetTextBoxValue(this AutomationElement automationElement)
    {
        return (automationElement.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern).Current.Value;
    }
    
    public static void SetTextBoxValue(this AutomationElement automationElement,string value)
    {
        (automationElement.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern).SetValue(value);
    }
    
    public static void Click(this AutomationElement automationElement)
    {
        InvokePattern ipClickButton1 = (InvokePattern)automationElement.GetCurrentPattern(InvokePattern.Pattern);
        ipClickButton1.Invoke();
        Thread.Sleep(100); // dajmy czas na pokazanie okna, wykonanie funkcji itp
    }
    
    public static double ConvertToDouble(this string str)
    {
        double number;
        if (double.TryParse(str.Replace(&apos;.&apos;,&apos;,&apos;), out number  ))
            return number;
        throw new Exception(&quot;Niepoprawna wartość&quot;);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/12/ui-automation-czyli-testy-automatyczne-w-net/result.jpg&quot;&gt;&lt;img src=&quot;images/result.jpg&quot; alt=&quot;result&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</content:encoded></item><item><title>MVVM i okna modalne</title><link>https://tpodolak.com/blog/mvvm-i-okna-modalne/</link><guid isPermaLink="true">https://tpodolak.com/blog/mvvm-i-okna-modalne/</guid><pubDate>Wed, 30 Nov 2011 17:10:00 GMT</pubDate><content:encoded>&lt;p&gt;Często podczas użytkowania programów zachodzi konieczność pokazania dodatkowego okna, służącego do interakcji z użytkownikiem.
Najczęściej okno takie należy pokazać w określonym przypadku.
Jak już wcześniej zostało wspomniane cała logika powinna być umieszczona w &lt;code&gt;ViewMoedlu&lt;/code&gt;, zatem nasuwa się pytanie, w jaki sposób z ViewModelu pokazać okno modalne - przecież &lt;code&gt;ViewModel&lt;/code&gt; nie powinien mieć żadnych informacji o widoku.
Rozwiązanie tego problemu polega na oddelegowaniu pokazywania widoków lub &lt;code&gt;MessageBox-ów&lt;/code&gt; do wyspecjalizowanych klas tzw. serwisów.
Ponadto w przypadku gdy chcemy pokazywać proste komunikaty możemy również skorzystać z &lt;code&gt;Interaction&lt;/code&gt;/&lt;code&gt;Interactivity&lt;/code&gt; oraz klasy &lt;code&gt;Prisma&lt;/code&gt; &lt;code&gt;InteractionRequest&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;1. InteractionRequest&lt;/h3&gt;
&lt;p&gt;Jak już wcześniej wspomniano klasa &lt;code&gt;InteractionRequest&lt;/code&gt; odpowiedzialna jest za pokazywanie komunikatów użytkownikowi - koordynuje ona działanie pomiędzy &lt;code&gt;ViewModelem&lt;/code&gt; a widokiem.
W celu skorzystania z klasy &lt;code&gt;InteractionRequest&lt;/code&gt; w &lt;code&gt;ViewModelu&lt;/code&gt; tworzymy publiczną właściwość udostpęniającą obiekt typu &lt;code&gt;InteractionRequest&lt;/code&gt; na zewnątrz&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public InteractionRequest&amp;lt;Confirmation&amp;gt; Request { get; set; }
Request = new InteractionRequest&amp;lt;Notification&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Jak widać za generyczny typ &lt;code&gt;T&lt;/code&gt; została podstawiona klasa &lt;code&gt;Notification&lt;/code&gt;.
Parametr &lt;code&gt;T&lt;/code&gt; może przyjmować klasy dziedziczące po klasie &lt;code&gt;Notification&lt;/code&gt;.
Domyślnie w &lt;code&gt;Prismie&lt;/code&gt; są dwie takie klasy:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Notification&lt;/code&gt; - wspomniana już wcześniej, służy do powiadomienia użytkownika o jakimś zdarzeniu&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Confirmation&lt;/code&gt; - również służy powiadominiu użytkownika o jakiś zdarzeniu, ale zwraca ona reakcję użytkownika (czy potwierdził daną akcję czy nie - coś jak &lt;code&gt;MessageBox YesNo&lt;/code&gt;)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;W celu wywołania okienka należy odpalić funkcję &lt;code&gt;Raise&lt;/code&gt; na przykład w taki sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Request.Raise(new Notification { Content = &quot;Info dla użytkownika&quot;, Title = &quot;sth&quot; }, confirmation =&amp;gt; AfterMessageAction());
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Funkcja &lt;code&gt;Raise&lt;/code&gt; przyjmuje jeden lub dwa parametry.
Przedstawy bardziej zaawansowaną wersję tej funkcji - tą z dwoma parametrami.
W pierwszym parametrze podajemy obiekt typu &lt;code&gt;Notification&lt;/code&gt;, w którym przekazujemy informacje do przekazania użytkownikowi (&lt;code&gt;Content&lt;/code&gt;) oraz tytuł okna (&lt;code&gt;Title&lt;/code&gt;).
Drugim parametrem jest delegat &lt;code&gt;Action&lt;/code&gt; , który określa co mamy zrobić po zamknięciu okna przez użytkownika.
Ostatnią rzeczą jaką musimy zrobić, żeby wykorzystać &lt;code&gt;NotificationRequest&lt;/code&gt; jest zdefiniowanie triggera w widoku, który będzie reagował na odpalenie funkcji &lt;code&gt;Raise&lt;/code&gt;.
Robimy to w następujący sposób:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;definiujemy w XAML-u alias do namespaca interactivity&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;xmlns:i=&quot;http://schemas.microsoft.com/expression/2010/interactivity&quot; 
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;tworzymy &lt;code&gt;InteractionRequestTrigger&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;i:Interaction.Triggers&amp;gt;
   &amp;lt;prism:InteractionRequestTrigger SourceObject=&quot;{Binding Request}&quot;&amp;gt;
       &amp;lt;prism:PopupChildWindowAction&amp;gt;&amp;lt;/prism:PopupChildWindowAction&amp;gt;
   &amp;lt;/prism:InteractionRequestTrigger&amp;gt;
 &amp;lt;/i:Interaction.Triggers&amp;gt;

&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;2. MessageBoxService&lt;/h3&gt;
&lt;p&gt;Alternatywą dla &lt;code&gt;InteractionRequest&lt;/code&gt; jest stworzenie własnej klasy, do której zostałyby oddelegowane wszystkie prośby o pokazania &lt;code&gt;MessageBoxa&lt;/code&gt;.
Przykładowa implementacja takiego serwisu może wyglądać w następujący sposób.
Po pierwsze stwórzmy interfejs z funkcjami potrzebnymi do pokazania &lt;code&gt;MessageBoxa&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public interface IMessageBoxService
{      
    MessageBoxResult ShowMessageBox (string info, string caption,MessageBoxButton buttons);      
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Następnie zaimplementujmy ten interfejs w klasie &lt;code&gt;MessageBoxService&lt;/code&gt; - właśnie do tej klasy będą oddelegowywane wszystkie prośby o pokazanie &lt;code&gt;MessageBoxa&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class MessageBoxService : IMessageBoxService
{
    public MessageBoxResult ShowMessageBox(string info, string caption, MessageBoxButton buttons)
    {
        return MessageBox.Show(info, caption, buttons);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Taki serwis musimy następnie przekazać do każdego &lt;code&gt;ViewModelu&lt;/code&gt; , w którym będzie potrzeba pokazania &lt;code&gt;MessageBoxa&lt;/code&gt;.
Jako, że ręczne przekazywanie tego obiektu może być nużące, możemy skorzystać z dobrodziejstw &lt;code&gt;Inversion of Control&lt;/code&gt;.
Ja skorzystałem z kontenera z &lt;code&gt;Unity&lt;/code&gt;.
Po pierwsze musimy zarejestrować nasz typ w kontenerze&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;_container.RegisterType&amp;lt;IMessageBoxService, MessageBoxService&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;następnie &lt;code&gt;MessageBoxService&lt;/code&gt; może zostać wstrzyknięty do każdego &lt;code&gt;ViewModelu&lt;/code&gt; przy np. przy pomocy wstrzykiwania właściwości.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Dependency]
public IMessageBoxService MessageBoxService
{
  get { return  messageBoxService; }
  set { messageBoxService = value; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Oczywiście żeby nasza właściwość została wstrzykniętai, nasz &lt;code&gt;ViewModel&lt;/code&gt; musi zostać stworzony przy użycia kontenera &lt;code&gt;IO&lt;/code&gt;.
Zauważmy, że właściwość &lt;code&gt;MessageBoxService&lt;/code&gt; nie jest konkretnym typem, lecz interfejsem.
Dzięki takiemu podejściu nasza aplikacja wciąż jest w łatwy sposób testowalna oraz &lt;code&gt;ViewModel&lt;/code&gt; nie ma nic wspólnego z klasami widoku.&lt;/p&gt;
&lt;h3&gt;3. ModalWindowService&lt;/h3&gt;
&lt;p&gt;Do pokazywania widoków(jako okien) z poziomu &lt;code&gt;ViewModelu&lt;/code&gt; posłużmy się podobnym mechanizmem jak w przypadku pokazywania &lt;code&gt;MessageBox-ów&lt;/code&gt;.
Zasada działania klasy, która stworzymy będzie taka sama, jednakże będziemy musieli odrobinę poszerzyć jej funkcjonalność.
Po pierwsze tak jak poprzednio stwórzmy odpowiedni interfejs - &lt;code&gt;IModalWindowService&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;:::warning[UWAGA]
Przykład &lt;code&gt;ModalWindowServicu&lt;/code&gt; zostanie zaprezentowany dla &lt;code&gt;Silverlight-a&lt;/code&gt;, gdyż okna modalne w &lt;code&gt;silverlighcie&lt;/code&gt; to tak naprawdę okna semi-modalne.
Główny wątek się nie zatrzymuje, jednakże użytkownik nie ma możliwości interakcji z oknami będącymi pod aktualnie widocznym oknem.
:::&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public interface IModalDialogService
{
    void ShowDialog&amp;lt;TViewModel&amp;gt;(IModalView&amp;lt;TViewModel&amp;gt; view,Action&amp;lt;TViewModel&amp;gt; CloseAction) where TViewModel : ViewModelBase;       
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Zauważmy, że funkcja &lt;code&gt;ShowDialog&lt;/code&gt; w parametrze nie przyjmuje konkretnego widoku, lecz interfejs, który każde okno modalne powinno implementować - &lt;code&gt;IModalView&lt;/code&gt;.
Interfejs ten może wyglądać w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public interface IModalView&amp;lt;TViewModel&amp;gt; where TViewModel : ViewModelBase
{
    /// 
    /// ViewModel odpowiedzialny za dane okno
    /// 
    TViewModel ViewModel { get; set; }
    /// 
    /// DialogResult po zamknieciu okna
    /// 
    bool? DialogResult { get; set; }
    /// 
    /// zamkniecie okna
    /// 
    void Close();
    /// 
    /// Pokazanie okna
    /// 
    void Show();
    /// 
    /// Zdarzenie wywoływane w momencie zamkniecia okna modalnego
    /// 
    event EventHandler Closed;
    /// 
    /// Zdarzenie wywoływane w chwli zamykania widoku 
    /// 
    event EventHandler&amp;lt;CancelEventArgs&amp;gt; Closing;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Jako, że okna modalne w &lt;code&gt;Silverlighcie&lt;/code&gt; są tak naprawdę oknami semi-modalnymi musimy wiedzieć kiedy dane okno zostanie zamknięte.
Dlatego, też interfejs ten zawiera zdarzenie&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;event EventHandler Closed;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;ponadto wypadałoby sprawdzić czy dane wpisane w oknie są poprawne, dlatego też dodano zdarzenie&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;event EventHandler&amp;lt;CancelEventArgs&amp;gt; Closing;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;w przypadku gdy dane wpisane w oknie nie będą poprawne, nasz &lt;code&gt;ModalDialogService&lt;/code&gt; zapobiegnie zamknięciu okna.
Ostatecznie nasza klasa ModalDialogService może wyglądać w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class ModalDialogService : IModalDialogService
{
    private EventHandler&amp;lt;CancelEventArgs&amp;gt; ClosingEventHandler;
    private EventHandler CloseEventHandler;
    public void ShowDialog&amp;lt;TViewModel&amp;gt;(IModalView&amp;lt;TViewModel&amp;gt; view, Action&amp;lt;TViewModel&amp;gt; CloseAction) where TViewModel : ViewModelBase
    {
        view.Closing += ClosingEventHandler = (sender, args) =&amp;gt;
        {
            if (view.DialogResult.HasValue &amp;amp;&amp;amp; view.DialogResult.Value)
            {
                if (!(args.Cancel = !view.ViewModel.Validate())) // jezeli mozna zamknac okno to odczepiamy handler
                    view.Closing -= ClosingEventHandler;
            }
        };
        if (CloseAction != null)
        {
            view.Closed += CloseEventHandler = (sender, args) =&amp;gt;
                {
                    CloseAction(view.ViewModel);
                    view.Closed -= CloseEventHandler;
                };
        }
        view.Show();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Nasz serwis podobnie jak w przypadku &lt;code&gt;MessageBoxServicu&lt;/code&gt; rejestrujemy w kontenerze, a następnie wstrzykujemy go do &lt;code&gt;ViewModelu&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;_container.RegisterType&amp;lt;IModalDialogService, ModalDialogService&amp;gt;();
[Dependency]
public IMessageBoxService MessageBoxService
{
 get { return  messageBoxService; }
 set { messageBoxService = value; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Pozostaje nam jedynie kwestia wyjaśnienia w jaki sposób wywołać nasze okno.
Nie powinniśmy tworzyć okna w &lt;code&gt;ViewModelu&lt;/code&gt;, gdyż łamie to zasadę &lt;code&gt;MVVM-a&lt;/code&gt;.
Dlatego też po raz kolejny skorzystamy z kontenera &lt;code&gt;IoC&lt;/code&gt;. W kontenerze &lt;code&gt;IoC&lt;/code&gt; rejestrujemy sobie nasz widok&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;_container.RegisterType&amp;lt;IModalView&amp;lt;AddPersonViewModel&amp;gt;, AddPersonView&amp;gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;jako, że &lt;code&gt;ViewModel&lt;/code&gt; jest wstrzykiwany do &lt;code&gt;View&lt;/code&gt; poprzez &lt;code&gt;Dependency Injection&lt;/code&gt; należy również w kontenerze zarejestrować odpowiedni typ &lt;code&gt;ViewModelu&lt;/code&gt; - czyli w tym przypadku &lt;code&gt;AddPersonViewModel&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;_container.RegisterType&amp;lt;AddPersonView&amp;gt;()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Mając już zarejestrowane w kontenerze wszystkie niezbędne typu możemy wywołać okno z &lt;code&gt;ViewModelu&lt;/code&gt; w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;ModalDialogService.ShowDialog&amp;lt;EditAllPlayersViewModel&amp;gt;(_container.Resolve&amp;lt;IModalView&amp;lt;AddPersonViewModel&amp;gt;&amp;gt;(), model =&amp;gt; {//tutaj jakas logika });
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Obiekt widoku otrzymujemy z kontenera &lt;code&gt;IoC&lt;/code&gt; wykorzystując funkcję &lt;code&gt;Resolve&lt;/code&gt;, w miejsce &lt;code&gt;LambdaExpression&lt;/code&gt; wstawiamy nasze wyrażenie w którym określamy co zrobimy po poprawnym zamknięciu okna.
Zauważmy, że ViewModel nie ma żadnych informacji o widoku - kontener nie zwraca nam konkretnego typu lecz interfejs.
Dzięki takiemu podejściu nasza aplikacja może być w łatwy sposób testowalna.&lt;/p&gt;
</content:encoded></item><item><title>Interactivity oraz Interaction</title><link>https://tpodolak.com/blog/interactivity-oraz-interaction/</link><guid isPermaLink="true">https://tpodolak.com/blog/interactivity-oraz-interaction/</guid><pubDate>Tue, 29 Nov 2011 21:01:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;code&gt;Interactions&lt;/code&gt; oraz &lt;code&gt;Interactivity&lt;/code&gt; są to dwie dll-ki, które poszerzają sposób komunikacji pomiędzy widokiem oraz &lt;code&gt;ViewModelem&lt;/code&gt;.
Wprowadzają one nowy typ &lt;code&gt;EventTriggerów&lt;/code&gt;(w &lt;code&gt;Silverlighcie&lt;/code&gt; nie ma triggerów, natomiast w &lt;code&gt;WPF-ie&lt;/code&gt; event triggery można praktycznie używać jedynie do animacji) oraz dodatkowo wprowadzają ciekawe sposoby(funkcje) na interakcję widoku z &lt;code&gt;ViewModelem&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Pierwszym z tych sposobów jest użycie właściwości &lt;code&gt;InvokeCommandAction&lt;/code&gt;.
Jak sama nazwa wskazuje można wywołać komendę z &lt;code&gt;ViewModelu&lt;/code&gt;.
Jaka jest różnica między wywołaniem komendy poprzez &lt;code&gt;InvokeCommandAction&lt;/code&gt;, a &lt;code&gt;Command=&quot;{Binding CommandName}&quot;&lt;/code&gt;?
&lt;code&gt;InvokeCommandAction&lt;/code&gt; ma tą przewagę nad normalnm bindowaniem do property &lt;code&gt;Command&lt;/code&gt;, że pozwala wywołać daną komendę w odpowiedzi na zajście jakiegoś zdarzenia na widoku.
Przykładowe użycie może wyglądać następująco:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Button Content=&quot;Submit&quot; IsEnabled=&quot;{Binding CanSubmit}&quot;&amp;gt;
      &amp;lt;i:Interaction.Triggers&amp;gt;
        &amp;lt;i:EventTrigger EventName=&quot;MouseMove&quot;&amp;gt;
           &amp;lt;i:InvokeCommandAction Command=&quot;{Binding SubmitCommand}&quot;/&amp;gt;
        &amp;lt;/i:EventTrigger&amp;gt;
      &amp;lt;/i:Interaction.Triggers&amp;gt;
&amp;lt;/Button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Powyższy przykład działa w następujący sposób.
Za każdym razem gdy zostanie wywołane zdarzenie &lt;code&gt;MouseMove&lt;/code&gt; na przycisku, odpalona zostanie komenda &lt;code&gt;SubmitCommand&lt;/code&gt;.
Wadą używania &lt;code&gt;InvokeCommandAction&lt;/code&gt; jest to, że sami musimy się martwić o wygaszenie kontrolki w przypadku gdy dana komenda nie może być wykonana.
Dlatego też w pierwszej linii mamy bindowanie właściwości &lt;code&gt;IsEnabled&lt;/code&gt; przycisku do właściwości CanSubmit z &lt;code&gt;ViewModelu&lt;/code&gt;.
Alias &lt;code&gt;i:&lt;/code&gt; jest aliasen na namespace interactivity z dll-ki&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;System.Windows.Interactivity.xmlns:i=&quot;clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity&quot;.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Drugim sposobem powiadomiania &lt;code&gt;ViewModelu&lt;/code&gt; o jakimś zdarzeniu w widoku jest użycie &lt;code&gt;InvokeMethodAction&lt;/code&gt;.
Dzięki tej właściwości możemy bezpośrednio z widoku (z &lt;code&gt;XAML-a&lt;/code&gt;) wywołać funkcję w &lt;code&gt;ViewModelu&lt;/code&gt;.
Składnia przedstawia się w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Button Content=&quot;Submit&quot; IsEnabled=&quot;{Binding CanSubmit}&quot;&amp;gt;
     &amp;lt;i:Interaction.Triggers&amp;gt;
       &amp;lt;i:EventTrigger EventName=&quot;Click&quot;&amp;gt;
        &amp;lt;i:CallMethodAction TargetObject=&quot;{Binding}&quot; Method=&quot;Submit&quot;/&amp;gt;
      &amp;lt;/i:EventTrigger&amp;gt;
     &amp;lt;/i:Interaction.Triggers&amp;gt;
&amp;lt;/Button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;TargetObject&lt;/code&gt; jest zbindowany do &lt;code&gt;DataContextu&lt;/code&gt;, to właśnie tam będzie szukana funkcja &lt;code&gt;Submit&lt;/code&gt;.
Należy pamiętać, że właściwość &lt;code&gt;CallMethodAction&lt;/code&gt; nie wspiera parametrów funkcji.
Zatem jeżeli musimy wywołać jakąś funkcję z parametrami, należy opakować ją w funkcję bezparametrową, natomiast wszystkie parametry przekazać z właściwości &lt;code&gt;ViewModelu&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Kolejnym ciekawym featurem &lt;code&gt;Interactivity&lt;/code&gt; jest klasa &lt;code&gt;Behavior&lt;/code&gt;.
Jest niezastąpiona jeżeli potrzebujemy ingerować w działanie widoku po jakimś zdarzeniu.
Nie musimy wówczas tworzyć obsługi eventów w code behind.
Możemy wyłuskać daną funkcjonalność i zamknąć ją w klasie &lt;code&gt;Behavior&lt;/code&gt; a następnie doczepić do wszystkich widoków danego typu.
Załóżmy, że sterujemy &lt;code&gt;ListBoxem&lt;/code&gt; z poziomu &lt;code&gt;ViewModelu&lt;/code&gt; (przełączamy &lt;code&gt;SelectedItem&lt;/code&gt;).
Możemy zaznaczyć jakiś Item, co jednak jeżeli nasza lista jest bardzo długa,a zaznaczamy ostatni element.
Na widoku element rzeczywiście się zaznaczył jednak lista się nie przewinęła.
Przez co cały czas wiszą elementy z początku i nie widać czy któryś element jest zaznaczony.
Dopiero gdy przeskrolujemy ręcznie &lt;code&gt;ListBoxa&lt;/code&gt; widzimy, że rzeczywiście prawidłowo zareagował na zmianę property w &lt;code&gt;ViewModelu&lt;/code&gt;.
Jest to idealna sytuacja, aby stworzyć własny &lt;code&gt;Behavior&lt;/code&gt;, który będziemy mogli podczepić do wszystkich listboxów w każdym widoku.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Behavior&amp;lt;ListBox&amp;gt;
{
  protected override void OnAttached()
  {
    AssociatedObject.SelectionChanged += ListBoxSelectionChanged;
  }

  protected override void OnDetaching()
  {
     AssociatedObject.SelectionChanged -= ListBoxSelectionChanged;
  }

  private void ListBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
  {
    if (sender is ListBox &amp;amp;&amp;amp; ((ListBox)sender).SelectedItem != null)
    {
        var listBox = sender as ListBox;
        listBox.ScrollIntoView(listBox.SelectedItem);
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Metoda &lt;code&gt;OnAttached&lt;/code&gt; odpala się w momencie, gdy behavior jest podpinany do kontrolki.
W metodzie tej powinniśmy podpiąć się pod wszystkie eventy, które są dla nas istotne.
W momencie, gdy widok jest niszczony wywołuje się metoda &lt;code&gt;OnDetaching&lt;/code&gt;, w której powinniśmy odpiąć wszystkie metody od eventów.&lt;/p&gt;
</content:encoded></item><item><title>Prism - CommandBehaviors</title><link>https://tpodolak.com/blog/prism-commandbehaviors/</link><guid isPermaLink="true">https://tpodolak.com/blog/prism-commandbehaviors/</guid><pubDate>Tue, 29 Nov 2011 20:20:00 GMT</pubDate><content:encoded>&lt;p&gt;Analizując wcześniejsze przykłady pokazujące użycie &lt;code&gt;DelegateCommand&lt;/code&gt; można odnieść wrażenie, że mimo tego iż są one bardzo użyteczne, ich użycie jest niestety bardzo ograniczone.
Jedynie niektóre komponenty &lt;code&gt;WPF-a&lt;/code&gt; i &lt;code&gt;Silverlight-a&lt;/code&gt; mają właściwość &lt;code&gt;Command&lt;/code&gt; do której można zbindować nasz obiekt &lt;code&gt;DelegateCommand&lt;/code&gt;.
Ponadto właściwość ta reaguje jedynie na wybrane zahardcodowane w kontrolce zdarzenie (zdarzenie &lt;code&gt;Click&lt;/code&gt;).
Co w przypadku gdybyśmy chcieli zareagować np. na zdarzenie &lt;code&gt;MouseMove&lt;/code&gt; za pomocą komendy? Nasz problem możemy rozwiązać poprzez:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Interactivity&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Interactions&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;CommandBehaviors&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;W tym poście zostanie przedstawione rozwiązanie trzecie - &lt;code&gt;CommandBehaviors&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Pierwszą rzeczą jaką należy zrobić w celu stworzenia komendy reagującej na inne zdarzenie niż &lt;code&gt;Click&lt;/code&gt; jest stworzenie klasy dziedziczącej po &lt;code&gt;CommandBehaviorBase&lt;/code&gt;.
Załóżmy, że zrobimy komendę reagującą na zdarzenie &lt;code&gt;MouseMove&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class MouseMoveCommandBehavior : CommandBehaviorBase&amp;lt;Control&amp;gt;
{
    private MouseOutCommandBehavior(Control control) : base(control)
    {
        control.MouseMove += (sender, args) =&amp;gt; 
        {
            this.ExecuteCommand();
        };
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Piersza część już za nami, ale pojawia się teraz pytanie jak z tego skorzystać.
Żeby mieć możliwość użycia powyżej klasy wykorzytamy attached dependency property.
Musimy sobie stworzyć pomocniczą statyczną klasę, w której to zarejestrujemy nasze właściwości.
Zacznijmy od zarejestrowania dependency property o nazwie &lt;code&gt;Command&lt;/code&gt; - do tego obiektu będziemy bindowali komendy z &lt;code&gt;ViewModelu&lt;/code&gt; (komendy reagujące na zdarzenie &lt;code&gt;MouseMove&lt;/code&gt;)&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static class MouseMove 
{
    public static ICommand GetCommand(DependencyObject obj)
    {
        return (ICommand)obj.GetValue(CommandProperty);
    }

    public static void SetCommand(DependencyObject obj, ICommand value)
    {
        obj.SetValue(CommandProperty, value);
    }

    public static readonly DependencyProperty CommandProperty =
            DependencyProperty.RegisterAttached(&quot;Command&quot;, typeof(ICommand), typeof(MouseMove), new PropertyMetadata(OnSetCustomCommandCallback));
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;zauważmy, że podłączyliśmy event handlera reagującego na zmianę naszej nowo stworzonej właściwości &lt;code&gt;Command&lt;/code&gt;.
Funkcja &lt;code&gt;OnSetCustomCommandCallback&lt;/code&gt; wygląda następująco:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;private static void OnSetCustomCommandCallback(DependencyObject dep, DependencyPropertyChangedEventArgs e)
{
    var control = dep as Control;
    if (control != null)
    {
        MouseMoveCommandBehavior behavior = GetorCreateMouseMoveBehavior(control);
        behavior.Command = e.NewValue as ICommand;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Funkcja ta po prostu w razie potrzeby tworzy nowy obiekt typu &lt;code&gt;MouseMoveCommandBehavior&lt;/code&gt; (gdy ktoś zbinduje komende) i dopina go do naszej kontrolki.
Pomocnicza funkcja &lt;code&gt;GetorCreateMouseMoveBehavior&lt;/code&gt; wygląda tak:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;private static MouseMoveCommandBehavior GetorCreateMouseMoveBehavior(Control listBox)
{
    var behavior = listBox.GetValue(MouseMoveBehaviorProperty) as
        MouseMoveCommandBehavior;
    if (behavior == null)
    {
        behavior = new MouseMoveCommandBehavior(listBox);
        listBox.SetValue(MouseMoveBehaviorProperty, behavior);
    }
    return behavior;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Obiekt rejestrowany poprzez funkcję &lt;code&gt;GetorCreateMouseMoveBehavior&lt;/code&gt; jest dopinany do kolejnej attached property, która również została zadeklarowana w tym pliku&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static MouseMoveCommandBehavior GetMouseMoveBehavior(DependencyObject obj)
{
    return (MouseMoveCommandBehavior)obj.GetValue(MouseMoveBehaviorProperty);
}

public static void SetMouseMoveBehavior(DependencyObject obj, MouseMoveCommandBehavior value)
{
    obj.SetValue(MouseMoveBehaviorProperty, value);
}

public static readonly DependencyProperty MouseMoveBehaviorProperty =
    DependencyProperty.RegisterAttached(&quot;MouseMoveBehavior&quot;, typeof(MouseMoveCommandBehavior), typeof(MouseMove), null );
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Mając zdefiniowane wszystkie powyższe właściwości możemy już wykorzystać naszą komendę.
Jednakże przydałoby się dodać jeszcze jedną właściwość (opcjonalnie), mianowicie właściwość &lt;code&gt;CommandParameters&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static object GetCommandParametr(DependencyObject obj)
{
    return (object)obj.GetValue(CommandParametrProperty);
}

public static void SetCommandParametr(DependencyObject obj, object value)
{
    obj.SetValue(CommandParametrProperty, value);
}

public static readonly DependencyProperty CommandParametrProperty =
    DependencyProperty.RegisterAttached(&quot;CommandParametr&quot;, typeof(object), typeof(MouseMove), new PropertyMetadata(OnSetCustomCommandParameterCallback));`
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W tym propertisie również reagujemy na przypisnie obiektu.
Handler &lt;code&gt;OnSetCustomCommandParameterCallback&lt;/code&gt; wygląda następująco&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;private static void OnSetCustomCommandParameterCallback(DependencyObject dep,DependencyPropertyChangedEventArgs e)
{
    var listBox = dep as Control;
    if (listBox != null)
    {
        MouseMoveCommandBehavior behavior = GetorCreateMouseMoveBehavior(listBox); ;
            behavior.CommandParameter = e.NewValue;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Mając już zdefiniowane wszystkie niezbędne właściwości możemy użyć ich w &lt;code&gt;XAML-u&lt;/code&gt;.
Po pierwsze musimy dodać alias do namespaca gdzie znajduje się nasza statycza klasa &lt;code&gt;MouseMove&lt;/code&gt;.
W moim przypadku wygląda to następująco:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;xmlns:AttachedCommands=&quot;clr-namespace:MainModule.Commands&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Następnie bindujemy jakąś kontrolkę do naszego attached property &lt;code&gt;Command&lt;/code&gt;.
Wygląda to w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Button Name=&quot;txtButton&quot; Grid.Column=&quot;2&quot; AttachedCommands:MouseMove.Command=&quot;{Binding SomeCommandFromViewModel}&quot;&amp;gt;&amp;lt;/Button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Od teraz za każdym razem jak najedziemy na &lt;code&gt;txtButton&lt;/code&gt; wywoła się komenda &lt;code&gt;SomeCommandFromViewModel&lt;/code&gt;.
Podsumowując trzeba się całkiem sporo napisać żeby zmusić do działania &lt;code&gt;CommandBehaviors&lt;/code&gt; .
W następnym poście przedstawię dwa sposoby na osiągnięcie tego samego efektu mniejszym kosztem.&lt;/p&gt;
</content:encoded></item><item><title>Prism - Komendy</title><link>https://tpodolak.com/blog/prism-komendy/</link><guid isPermaLink="true">https://tpodolak.com/blog/prism-komendy/</guid><pubDate>Tue, 29 Nov 2011 19:33:00 GMT</pubDate><content:encoded>&lt;h3&gt;1. DelegateCommands&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;DelegateCommands&lt;/code&gt; w &lt;code&gt;Prismie&lt;/code&gt; są to obiekty, które implementują interfejs &lt;code&gt;ICommand&lt;/code&gt;, służą one do interakcji widoku z &lt;code&gt;ViewModelem&lt;/code&gt;.
Korzystając z &lt;code&gt;Prisma&lt;/code&gt; nie musimy już pisać własnej klasy implementującej ten interfejs (tak jak to zrobiliśmy &lt;a href=&quot;http://tpodolak.com/blog/2011/11/27/commands-czyli-interakcja-widoku-z-viewmodelem-cz-2/&quot;&gt;tutaj&lt;/a&gt;).
Konstruktor klasy &lt;code&gt;DelegateCommand&lt;/code&gt; przyjmuje dwa parametry:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Action&lt;/code&gt; &lt;code&gt;execteMethod&lt;/code&gt; - funkcja odpalania przy wywołaniu komendy,&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Func&lt;/code&gt; &lt;code&gt;canExecuteMethod&lt;/code&gt; - funkcja sprawdzająca czy daną komendę można wywołać&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;code&gt;DelegateCommands&lt;/code&gt; z &lt;code&gt;Prisma&lt;/code&gt; używamy w taki sam sposób w jaki używaliśmy komend w &lt;a href=&quot;http://tpodolak.com/blog/2011/11/27/commands-czyli-interakcja-widoku-z-viewmodelem-cz-2&quot;&gt;tym&lt;/a&gt; poście.&lt;/p&gt;
&lt;h3&gt;2. CompositeCommands&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;CompositeCommands&lt;/code&gt; są to obiekty, które przechowują kolekcją obiektów typu &lt;code&gt;DelegateCommand&lt;/code&gt;.
Tworzenie &lt;code&gt;CompositeCommand&lt;/code&gt; jest bardzo proste. Po pierwsze musimy stworzyć obiekt typu &lt;code&gt;CompositeCommand&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public CompositeCommand SomeCompositeCommand = new CompositeCommand();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;następnie rejestrujemy w tym obiekcie obiekt implementujący interfejs &lt;code&gt;ICommand&lt;/code&gt;, czyli w naszym przypadku jakiś obiekt typu &lt;code&gt;DelegateCommand&lt;/code&gt;.
Robimy to w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;DelegateCommand DistributeCommand = new DelegateCommand(DistributeCards);
SomeCompositeCommand.RegisterCommand(DistributeCommand);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;w razie potrzeby możemy usunąć komendę z kolekcji komend przy pomocy następującej składni:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;SomeCompositeCommand.UnregisterCommand(DistributeCommand);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Mając już stworzony obiekt typu &lt;code&gt;CompositeCommand&lt;/code&gt; oraz zarejestrowane w nim obiekty &lt;code&gt;DelegateCommand&lt;/code&gt; możemy zastosować bindowanie.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Button Command=&quot;{Binding SomeCompositeCommand}&quot; Grid.Column=&quot;1&quot;&amp;gt;Rodzaj&amp;lt;/Button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Od teraz, w chwili naciśnięcia przycisku, najpierw sprawdzane jest czy dana &lt;code&gt;CompositeCommand&lt;/code&gt; może zostać wykonana.
&lt;code&gt;CompositeCommand&lt;/code&gt; może zostać wykonana tylko wtedy, gdy wszystkie komendy do niej podpięte mogą zostać wykonane.
Jeżeli warunek ten zostanie spełniony następuje wywoływanie po kolei wszystkich metod execute z komend podpiętych do danej &lt;code&gt;CompositCommand&lt;/code&gt;.
&lt;code&gt;CompositeCommand&lt;/code&gt; znajduje zastosowanie w przypadku gdy pozwalamy użytkownikowi na edycję wielu elementów jednocześnie i potrzebujemy w prosty sposób przeprowadzić walidację na poszczególnych widokach.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://tpodolak.com/blog/wp-content/uploads/2011/11/prism-komendy/CompositeCommand.jpg&quot;&gt;&lt;img src=&quot;images/CompositeCommand.jpg&quot; alt=&quot;Komendy&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;CompositeCommand&lt;/code&gt; może również wykorzystana np. do zapisania tylko aktywnego widoku.
Dzięki temu, że &lt;code&gt;DelegateCommand&lt;/code&gt; implementuje interfejs &lt;code&gt;IActiveAware&lt;/code&gt;, &lt;code&gt;CompositeCommand&lt;/code&gt; wie, który widok jest aktualnie zaznaczony i zapisze tylko wybrany widok.&lt;/p&gt;
&lt;p&gt;Interfejs &lt;code&gt;IActiveAware&lt;/code&gt; wygląda w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public interface IActiveAware
{    
    bool IsActive { get; set; }
    event EventHandler IsActiveChanged;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;bool IsActive&lt;/code&gt; - wskazuje czy dana komenda jest aktualnie aktywna&lt;/li&gt;
&lt;li&gt;&lt;code&gt;event EventHandler IsActiveChanged&lt;/code&gt; - informuje o zmianie aktywności komendy&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;W celu wykorzystania tego interfejsu przez &lt;code&gt;CompositeCommand&lt;/code&gt; należy skorzystać z drugiego dostępnego konstruktora tej klasy&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;CompositeCommand SomeCompositeCommand = new CompositeCommand(true);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Od teraz po naciśnięciu przycisku zbindowanego do tej komendy, wywołana zostanie jedynie aktywna komenda - czyli taka, której właściwość &lt;code&gt;IsActive&lt;/code&gt; została ustawiona na true.
Niestety o ustawianie aktywności danej komendy musimy zadbać sami.&lt;/p&gt;
</content:encoded></item><item><title>Kolekcje wspierające sortowanie, grupowanie oraz filtrowanie</title><link>https://tpodolak.com/blog/kolekcje-wspierajace-sortowanie-grupowanie-oraz-filtrowanie/</link><guid isPermaLink="true">https://tpodolak.com/blog/kolekcje-wspierajace-sortowanie-grupowanie-oraz-filtrowanie/</guid><pubDate>Mon, 28 Nov 2011 20:13:00 GMT</pubDate><content:encoded>&lt;h3&gt;1. ListViewCollection (WPF)&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;ListViewCollection&lt;/code&gt; jest to kolekcja wprowadzona do &lt;code&gt;WPF-a&lt;/code&gt;, która wspiera sortowanie, grupowanie oraz filtrowanie.
Kolekcję taką tworzymy w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;List&amp;lt;Player&amp;gt; palyerList = new Player { new Player(),new Player()};
public ListViewCollection&amp;lt;Player&amp;gt; PlayerListCollectionView {get;set;}
ListViewCollection&amp;lt;Player&amp;gt; PlayerListCollectionView= new ListViewCollection&amp;lt;Player&amp;gt;(playerList);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;czyli po prostu w konstruktorze przesyłamy obiekt implementujący interfejs &lt;code&gt;IEnumerable&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Filtrowanie&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;W celu przefiltrowania kolekcji wystarczy podać odpowiedni obiekt typu &lt;code&gt;Predicate&lt;/code&gt;(czyli tak naprawdę wystarczy napisać funkcję zwracającą &lt;code&gt;bool&lt;/code&gt; oraz przyjmującą w parametrze obiekt).
Załóżmy, że chcemy pokazać na widoku jedynie tych graczy, który nazywają się &lt;code&gt;Tomek&lt;/code&gt;.
W tym celu wystarczy, że zrobimy coś takiego:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;PlayerListCollectionView.Filter = val =&amp;gt; { return (val as Player).Name.ToLower() == &quot;tomek&quot;; }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;po zaaplikowaniu predicata widok zbindowany do danej listy automatycznie się odświeży.
W razie czego można zawsze wymusić oświeżenie przez wywołanie funkcji&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;PlayerListCollectionView.Refresh();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Grupowanie&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Kolekcja &lt;code&gt;ListViewCollection&lt;/code&gt; wspiera również grupowanie.
W celu pogrupowania listy po jakimś elemencie wystarczy do naszej listy dorzucić tzw. &lt;code&gt;group description&lt;/code&gt;.
Odbywa się to w taki sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;PlayerListCollectionView.GroupDescriptions.Add(new PropertyGroupDescription { PropertyName = &quot;Name&quot; }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Po dodaniu &lt;code&gt;PropertyGroupDescription&lt;/code&gt; widok automatycznie pogrupuje nam elementy po danych właściwościach.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Sortowanie&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Nasza kolekcja wspiera również sortowanie.
W celu posortowania wystarczy stworzyć obiekt implementujący interfjes &lt;code&gt;IComparer&lt;/code&gt;, a następnie przypisać go do właściwości &lt;code&gt;CustomSort&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class PlayerComparer : IComparer
{
    public int Compare(object x, object y)
    {
        if (((Player)x).Age &amp;gt; (((Player)y).Age))
        {
            return 1;
        }
        return -1;
    }
}

PlayerListCollectionView.CustomSort = new PlayerComparer ()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;po takiej akcji widok automatycznie się odświeży i pokaże posortowane dane.&lt;/p&gt;
&lt;h3&gt;2. PagedCollectionView (Silverlight)&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;PagedCollectionView&lt;/code&gt; jest to uboższą wersja &lt;code&gt;ListCollectionView&lt;/code&gt; z &lt;code&gt;WPF-a&lt;/code&gt;.
Grupowanie oraz filtrowanie dobywa się w ten sam sposób, jednakże sortowanie zostało w znaczny sposób utrudnione.
Sortować możemy jedynie po właściwościach, nie możemy stworzyć własnego comparera, który zostałby użyty do wykonania operacji sortowania.
Wykonanie operacji może wyglądać w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;PlayerPagedCollection.SortDescriptions.Clear();
PlayerPagedCollection.SortDescriptions.Add(new System.ComponentModel.SortDescription(&quot;Name&quot;, ListSortDirection.Ascending));
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W tym wypadku nasza kolekcja zostanie posortowana po właściwości &lt;code&gt;Name&lt;/code&gt;&lt;/p&gt;
</content:encoded></item><item><title>Walidacja</title><link>https://tpodolak.com/blog/walidacja/</link><guid isPermaLink="true">https://tpodolak.com/blog/walidacja/</guid><pubDate>Mon, 28 Nov 2011 19:03:00 GMT</pubDate><content:encoded>&lt;p&gt;Walidacja jest to technika sprawdzająca, czy dany obiekt spełnia pewne założenia poprawności danych.
W &lt;code&gt;WPF-ie&lt;/code&gt; oraz &lt;code&gt;Silverlighcie&lt;/code&gt; istnieją trzy sposoby walidacji obiektów:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;walidacja poprzez rzucanie wyjątków,&lt;/li&gt;
&lt;li&gt;walidacja z użyciem interfejsu &lt;code&gt;IDataErrorInfo&lt;/code&gt;,&lt;/li&gt;
&lt;li&gt;walidacja z użyciem interfejsu &lt;code&gt;INotifyDataErrorInfo&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;1. Walidacja poprzez rzucanie wyjątków&lt;/h3&gt;
&lt;p&gt;Walidacja poprzez rzucanie wyjątków odbywa się w następujący sposób.
W seterze danej właściwości dodajemy warunek sprawdzający czy wpisane dane są poprawne.
Jeżeli nie to najzwyczajniej w świecie rzucamy wyjątek, w którym podajemy komunikat błędu.
Przykładowy properties z walidacją może wyglądać w ten sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;private string _name;
public string Name
{
    get { return _name; }
    set
    {
        _name = value;
        if (string.IsNullOrEmpty(_name))
            throw new Exception(&quot;Nazwa nei może być pusta&quot;);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W celu &quot;wyłapania&quot; tego wyjątku i pokazania odpowiedniego komunikatu, w bindingu musimy ustawić właściwość &lt;code&gt;ValidatesOnExceptions&lt;/code&gt; na wartość &lt;code&gt;true&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;TextBox Text=&quot;{Binding Name, ValidatesOnExceptions=True, Mode=TwoWay}&quot; /&amp;gt;

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Taki sposób walidowania jest jednak rzadko stosowany i wielu programistów twierdzi, że rzucanie wyjątków powinno się odbywać tylko w przypadku nieprawidłowego działania aplikacji.
Ponadto walidowane propertisy nie mogą być autopropertisami, co dodatkowo wydłuża czas tworzenia klas.&lt;/p&gt;
&lt;h3&gt;2. Walidacja z użyciem interfejsu &lt;code&gt;IDataErrorInfo&lt;/code&gt;&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;public interface IDataErrorInfo
{
    string this[string columnName] { get; }
    string Error { get; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W celu wyłapywania błędów w widoku, należy w bindingu ustawić &lt;code&gt;ValidatesOnDataError = true&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;TextBox Text=&quot;{Binding Name, ValidatesOnDataError=True, Mode=TwoWay}&quot; /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Przykładowa klasa implementująca interfejs &lt;code&gt;IDataErrorInfo&lt;/code&gt; może wyglądać następująco:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Customer : IDataErrorInfo
{
    public string Name { get; set; }
    
    public string Error
    {
        get { return string.Empty; }
    }
    
    public string this[string propertyName]
    {
        get 
        {
            string result = string.Empty;
            if (propertyName == &quot;Name&quot;)
            {
                if (string.IsNullOrEmpty(Name))
                    result = &quot;Wartość nie moż być pusta&quot;;
            }
            
            return result;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Najważniejszą metodą w powyższej klasie jest indekser&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;string this[string propertyName]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;to właśnie tutaj mogą zostać sprawdzone wszystkie właściwości danego obiektu - &lt;code&gt;propertyName&lt;/code&gt; oznacza nazwę propertisu, który walidujemy.
W przypadku, gdy wartość jakiejś właściwości jest nieprawidłowa, w pole &lt;code&gt;result&lt;/code&gt; wpisujemy komunikat błędu.
Komunikaty te &quot;wyłapywane&quot; są przez widok, a następnie wyświetlane w postaci komunikatów przy odpowiednich kontrolkach.
Jeżeli wszystko jest &lt;code&gt;OK&lt;/code&gt; zwracamy &lt;code&gt;string.Empty&lt;/code&gt;. Walidacje przy pomocy interfejsu &lt;code&gt;IDataErrorInfo&lt;/code&gt; idealnie nadają się do walidowania modelu.&lt;/p&gt;
&lt;h3&gt;3. Walidacja z użyciem interfejsu &lt;code&gt;INotifyDataErrorInfo&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;Interfejs &lt;code&gt;INotifyDataErrorInfo&lt;/code&gt; prezentuje się w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public interface INotifyDataErrorInfo
{
     bool HasErrors { get; }
     event EventHandler&amp;lt;DataErrorsChangedEventArgs&amp;gt; ErrorsChanged;
     IEnumerable GetErrors(string propertyName);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;bool HasErrors&lt;/code&gt; - określa czy dany obiekt zawiera błędy&lt;/li&gt;
&lt;li&gt;&lt;code&gt;event EventHandler ErrorsChanged&lt;/code&gt; - zdarzenie informujące o zmienie ilości błędów w obiekcie&lt;/li&gt;
&lt;li&gt;&lt;code&gt;IEnumerable GetErrors(string propertyName)&lt;/code&gt; - funkcja pobierająca kolekcję błędów dla danego propertisa&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;W celu &quot;wyłapania&quot; błędów przez widok należy w bindingu ustawić properties &lt;code&gt;NotifyOnValidationError = true&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;TextBox Text=&quot;{Binding Name, NotifyOnValidationError=True, Mode=TwoWay}&quot; /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Jak już wcześniej wspomniano funkcja &lt;code&gt;GetErrors(string propertyName)&lt;/code&gt; zwraca kolekcję błędów dla danej właściwości.
Zatem do klasy, która będzie implementowała interfejs &lt;code&gt;INotifyDataErrorInfo&lt;/code&gt; należy dodać kolekcję przechowującą obiekty typu &lt;code&gt;ValidationResult&lt;/code&gt;.
Przykładowa implementacja interfejsu może wyglądać w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class BaseViewModel : INotifyDataErrorInfo
{
    private ICollection&amp;lt;ValidationResult&amp;gt; _validationResults;
    public IEnumerable GetErrors(string propertyName)
    {
        return _validationResults.Where(result =&amp;gt; result.MemberNames.Contains(propertyName));
    }
 
    public bool HasErrors
    {
        get { return _validationResults.Count &amp;gt; 0; }
    }
 
    public event EventHandler&amp;lt;DataErrorsChangedEventArgs&amp;gt; ErrorsChanged;
    
    private void NotifyErrorsChanged(string propertyName)
    {
        if(ErrorsChanged!=null)
            ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
    }

    protected void Validate()
    {
        _validationResults.Clear();
        Validator.TryValidateObject(this, new ValidationContext(this, null, null), _validationResults, true);
     
        foreach (var result in _validationResults)
            NotifyErrorsChanged(result.MemberNames.First());
    }
    
    protected void Validate(string propertyName)
    {
        var validationResults = _validationResults.Where(result =&amp;gt; result.MemberNames.Contains(propertyName)).ToList();
        foreach (var result in validationResults)
               _validationResults.Remove(result);
        
        Validator.TryValidateProperty(value, new ValidationContext(this, null, null) { MemberName = propertyName }, _validationResults);
           NotifyErrorsChanged(propertyName);
     }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Funkcja &lt;code&gt;Validate()&lt;/code&gt; najpierw czyści wszystkie poprzednie wyniki walidacji, a następnie przy pomocy klasy &lt;code&gt;Validator&lt;/code&gt; oraz funkcji &lt;code&gt;TryValidateObject&lt;/code&gt; waliduje wszystkie właściwości, które zostały oznaczone atrybutem dziedziczącym po klasie &lt;code&gt;ValidationAttribute&lt;/code&gt;.
Z kolei funkcja &lt;code&gt;Validate(string propertyName)&lt;/code&gt; waliduje tylko konkretną właściwość.
Przykładowe walidowanie właściwości przy pomocy atrybutów może wyglądać w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;[Required(ErrorMessage = &quot;Pole nie może być puste&quot;)]
public string Subject
{
    get { return _subject; }
    set
    {
        _subject = value;
         Validate(“Subject”)
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W celu stworzenia własnych regół walidacji, nie uwzględnionych w zapewnionych przez framework atrybutach należy stworzyć własną klasę dziedziczącą po klasie &lt;code&gt;ValidationAttribute&lt;/code&gt;, a następnie przeciążyć metodę &lt;code&gt;IsValid&lt;/code&gt;.
Przykładowa klasa może wyglądać w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class IntValidation : ValidationAttribute
{
    private bool allowNull;
    public IntValidation(bool allowNull)
    {
        this.allowNull = allowNull;
    }
    
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            int resul;
            if (int.TryParse(value.ToString(), out resul))
                return ValidationResult.Success;
            else
                return new ValidationResult(ErrorMessage, new List{validationContext.MemberName });
        }
        
        return allowNull ? ValidationResult.Success : new ValidationResult(ErrorMessage);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Walidacja przy użyciu interfejsu &lt;code&gt;INotifyDataErrorInfo&lt;/code&gt; idealnie nadaje się (wg mnie) do walidowaniu całych &lt;code&gt;ViewModeli&lt;/code&gt;.
Przy zamykaniu okna wystarczy wywołać funkcję &lt;code&gt;Validate&lt;/code&gt; z bazowego &lt;code&gt;ViewModelu&lt;/code&gt;, a w przypadku gdy zwróci ona &lt;code&gt;false&lt;/code&gt; zatrzymać zamykanie okna.
Jako, że walidacja zostanie przeprowadzona na wszystkich wybranych przez nas propertisach, widok automatycznie się zaktualizuje i pokaże komunikaty błędów na odpowiednich kontrolkach okna.&lt;/p&gt;
</content:encoded></item><item><title>Routed Events - nowy rodzaj zdarzeń w WPF-ie</title><link>https://tpodolak.com/blog/routed-events-nowy-rodzaj-zdarzen-w-wpf-ie/</link><guid isPermaLink="true">https://tpodolak.com/blog/routed-events-nowy-rodzaj-zdarzen-w-wpf-ie/</guid><pubDate>Mon, 28 Nov 2011 18:20:00 GMT</pubDate><content:encoded>&lt;p&gt;&lt;code&gt;RoutedEvent&lt;/code&gt; jest to nowy typ zdarzeń, który po raz pierwszy został zaprezentowany w &lt;code&gt;WPF-ie&lt;/code&gt;.
Głównym założeniem &lt;code&gt;RoutedEventów&lt;/code&gt; jest to, że w momencie wywołania takiego zdarzenia może ono podróżować w górę, lub w dół drzewa wizualnego oraz drzewa logicznego.
Każdy &lt;code&gt;RoutedEvent&lt;/code&gt; może przyjmować jedną z trzech strategii poruszania się po drzewie:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Bubbling&lt;/code&gt; - zdarzenie najpierw jest wywoływane w elemencie źródłowym, a następnie podróżuje ono w górę drzewa wizualnego (od naszego elementu do korzenia drzewa), aż do roota (lub do momenty gdy nie zostanie obsłużone poprzez &lt;code&gt;e.Handled = true&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Tunelling&lt;/code&gt; - zdarzenie wywoływane jest w korzeniu drzewa, a następnie podróżuje w dół drzewa, aż osiągnie element źródłowy (lub gdy nie zostanie obsłużone poprzez &lt;code&gt;e.Handled = true&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Direct&lt;/code&gt; - zdarzenie jest wywoływane tylko i wyłącznie w elemencie źródłowym - czyli zdarzenie to zachowuje się tak samo jak standardowe &lt;code&gt;.NET-owe&lt;/code&gt; zdarzenia&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Definiowanie własnych &lt;code&gt;RoutedEvents&lt;/code&gt; wygląda następująco.
W pierwszym kroku przy pomocy &lt;code&gt;EventManagera&lt;/code&gt; i jego funkcji &lt;code&gt;RegisterRoutedEvent&lt;/code&gt; rejestrujemy nasze zdarzenie.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static RoutedEvent PreviewTrippleClickEvent = EventManager.RegisterRoutedEvent(&quot;PreviewTrippleClick&quot;, RoutingStrategy.Tunnel, typeof(RoutedEventHandler), typeof(MyContentControl));
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;następnie piszemy wrapper &lt;code&gt;RoutedEventa&lt;/code&gt; na zwykłe zdarzenie&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public event RoutedEventHandler PreviewTrippleClick
{
    add
    {
        AddHandler(MyContentControl.PreviewTrippleClickEvent, value);
    }
    remove
    {
        RemoveHandler(MyContentControl.PreviewTrippleClickEvent, value);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Funkcja &lt;code&gt;RegisterRoutedEvent&lt;/code&gt; przyjmuje cztery parametry:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Nazwa naszego zdarzenia&lt;/strong&gt; - taka sama jak nazwa standardowego eventa opakowującego &lt;code&gt;RoutedEvent&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Strategia routingu&lt;/strong&gt; - czyli czy nasze zdarzenie będzie typu &lt;code&gt;Bubble&lt;/code&gt;, &lt;code&gt;Tunnel&lt;/code&gt; lub &lt;code&gt;Direct&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Typ handlera&lt;/strong&gt; - czyli typ delegata/funkcji jaki będzie można podłączyć do zdarzenia, żeby je obsłużyć&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Typ właściciela&lt;/strong&gt; - czyli typ klasy do której należy dany event&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Jako, że stworzenie nowego &lt;code&gt;RoutedEventa&lt;/code&gt; jest dość czasochłonne (w porównaniu ze zwykłym zdarzeniem) warto zassać sobie snippet, który znacząco przyśpiesza tworzenie routed eventów.
Snippet taki można znaleźć tutaj &lt;a href=&quot;http://interactiveasp.net/blogs/natesstuff/archive/2008/10/15/routed-event-code-snippet.aspx&quot;&gt;RoutedEventSnippet&lt;/a&gt;.
Mając już zdefiniowany nowy &lt;code&gt;RoutedEvent&lt;/code&gt; można go wywołać w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;RaiseEvent(new RoutedEventArgs(MyContentControl.TrippleClickEvent, this));
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Funkcja &lt;code&gt;RaiseEvent&lt;/code&gt; w parametrze przyjmuje obiekt typu &lt;code&gt;RoutedEventArts&lt;/code&gt;.
W przypadku gdyby nie był on dla nas wystarczający (potrzebujemy przesłać więcej parametrów itp.), musimy napisać klasę rozszerzającą klasę &lt;code&gt;RoutedEventArts&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Routowanie zdarzenia może zostać zatrzymane, poprzez ustawienie flagi &lt;code&gt;e.Handled&lt;/code&gt; na &lt;code&gt;true&lt;/code&gt;.
Gdzie e jest to obiekt klasy &lt;code&gt;RoutedEventArgs&lt;/code&gt;.
Przykładowe zatrzymanie routowania eventa może wyglądać w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;private void Window_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    e.Handled = true;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;:::warning[UWAGA]
Można zadeklarować zdarzenie w taki sposób aby wartość flagi &lt;code&gt;e.Handled&lt;/code&gt; była pomijana.
Jednak można to zrobić jedynie z poziomu kodu.
Za pomocą metody &lt;code&gt;AddHandler(RoutedEvent, Delegate, bool)&lt;/code&gt; jeżeli ustawimy ostatni parametr na true, wówczas nasza metoda wykona się nawet w przypadku gdy &lt;code&gt;e.Hadnled == true&lt;/code&gt;.
Metoda ta dostępna jest dla klasy &lt;code&gt;UIElement&lt;/code&gt; i wszystkich klas po niej dziedziczących.
:::&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Attached events&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;Attached events&lt;/code&gt; działają podobnie jak &lt;code&gt;attached dependency properties&lt;/code&gt;.
Pozwalają one rozszerzyć kolekcję zdarzeń danej kontrolki o dodatkowe zdarzenia(nawet jeżeli nie mamy dostępu do źródeł danej kontrolki.
Przykładowo, istnieje możliwość obsługi eventu &lt;code&gt;click&lt;/code&gt; na kontrolce, która tak naprawdę takiego eventu nie posiada.
Każdy &lt;code&gt;RoutedEvent&lt;/code&gt; może zostać użyty jako attached event.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Window x:Class=&quot;MCTSTrainingChapter1.ThirdMainWindow&quot;
        xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
        Title=&quot;ThirdMainWindow&quot; Height=&quot;300&quot; Width=&quot;300&quot;&amp;gt;
    &amp;lt;Grid Button.Click=&quot;Grid_Click&quot;&amp;gt;
        &amp;lt;Grid.RowDefinitions&amp;gt;
            &amp;lt;RowDefinition&amp;gt;&amp;lt;/RowDefinition&amp;gt;
            &amp;lt;RowDefinition&amp;gt;&amp;lt;/RowDefinition&amp;gt;
            &amp;lt;RowDefinition&amp;gt;&amp;lt;/RowDefinition&amp;gt;
        &amp;lt;/Grid.RowDefinitions&amp;gt;
        &amp;lt;Button Grid.Row=&quot;0&quot;&amp;gt;Top&amp;lt;/Button&amp;gt;
        &amp;lt;Button Grid.Row=&quot;1&quot;&amp;gt;Middle&amp;lt;/Button&amp;gt;
        &amp;lt;Button Grid.Row=&quot;2&quot;&amp;gt;Bottom&amp;lt;/Button&amp;gt;
    &amp;lt;/Grid&amp;gt;
&amp;lt;/Window&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Na gridzie mamy zdefiniowane 3 przyciski, chcielibyśmy aby po naciśnięciu każdego z tych przycisków, wywoływała się odpowiednia funkcja.&lt;/p&gt;
&lt;p&gt;Jednym ze sposobów napisania takiej funkcjonalności jest podłączenie eventa &lt;code&gt;Click&lt;/code&gt; z każdego przycisku do jednego handlera.
Rozwiązanie to jest jak najbardziej poprawne, jednakże w przypadku dużej ilości przycisków może być to czasochłonne.
Można zrobić to prościej, przy wykorzystaniu attached events.
Jak widzimy w listingu przedstawionym wyżej, do grida &quot;przypięto&quot; event &lt;code&gt;Click&lt;/code&gt; z klasy Button.
Od teraz za każdym razem gdy jakikolwiek przycisk będący w obrębie &lt;code&gt;Grida&lt;/code&gt; zostanie naciśnięty, zdarzenie to zostanie przechwycone przez handler zdefiniowany w gridzie - &lt;code&gt;Grid_Click&lt;/code&gt;&lt;/p&gt;
</content:encoded></item><item><title>Trigery - Triggers</title><link>https://tpodolak.com/blog/trigery-triggers/</link><guid isPermaLink="true">https://tpodolak.com/blog/trigery-triggers/</guid><pubDate>Mon, 28 Nov 2011 17:20:00 GMT</pubDate><content:encoded>&lt;p&gt;Trigery jest to mechmizm &lt;code&gt;WPF-a&lt;/code&gt; służący reakcji &lt;code&gt;UI&lt;/code&gt; na jakieś zdarzenie. Wyróżniamy cztery rodzaje triggerów&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Property triggers&lt;/code&gt; - używane do zareagowanie na zmiany dependency property w danej kontrolce,&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Data triggers&lt;/code&gt; - używane do zareagowanie na zmiany w bindowanych obiektach - można podłączyć się do właściwości z &lt;code&gt;DataContextu&lt;/code&gt; jak i z danej kontrolki,&lt;/li&gt;
&lt;li&gt;&lt;code&gt;MultiDataTriggers&lt;/code&gt; - używane do reagowania na zmiany kilku właściwości,&lt;/li&gt;
&lt;li&gt;&lt;code&gt;MultiTrigger&lt;/code&gt; - używane do reagowania na zmiany kilku dependecy property w danej kontrolce,&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Event triggers&lt;/code&gt; - używane do reagowania na jakieś zdarzenie - służą do odpalania animacji&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;1. Property triggers&lt;/h3&gt;
&lt;p&gt;Oto przykład wykorzystania &lt;code&gt;Property Triggera&lt;/code&gt;. W &lt;code&gt;ResourceDictionary&lt;/code&gt; tworzymy styl, który zostanie przypisany do przycisku.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Style TargetType=&quot;{x:Type Button}&quot;&amp;gt;
    &amp;lt;Style.Triggers&amp;gt;
        &amp;lt;Trigger Property=&quot;IsMouseOver&quot; Value=&quot;True&quot;&amp;gt;
            &amp;lt;Setter Property=&quot;Background&quot; Value=&quot;Black&quot;&amp;gt;&amp;lt;/Setter&amp;gt;
        &amp;lt;/Trigger&amp;gt;
    &amp;lt;/Style.Triggers&amp;gt;
    &amp;lt;Setter Property=&quot;Background&quot; Value=&quot;Red&quot;/&amp;gt;
&amp;lt;/Style&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Widzimy, że dany trigger jest powiązany z właściwością &lt;code&gt;IsMouseOver&lt;/code&gt;.
W przypadku gdy wartość tej właściwości zostanie ustawiona na &lt;code&gt;true, tło przycisku zostanie zmienione na czarne. Natomiast gdy &lt;/code&gt;IsMouseOver&lt;code&gt;powróci do stanu&lt;/code&gt;false`, tło przycisku wróci do wartości sprzed zmiany.&lt;/p&gt;
&lt;h3&gt;2. Data triggers&lt;/h3&gt;
&lt;p&gt;Oto przykład wykorzystania &lt;code&gt;Data Triggera&lt;/code&gt;. W &lt;code&gt;ResourceDictionary&lt;/code&gt; tworzymy styl, który zostanie przypisany do przycisku.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Style x:Key=&quot;bindingTest&quot; TargetType=&quot;Button&quot;&amp;gt;
    &amp;lt;Style.Triggers&amp;gt;
        &amp;lt;DataTrigger Binding=&quot;{Binding Path=Text}&quot; Value=&quot;Kolor&quot;&amp;gt;
            &amp;lt;Setter Property=&quot;Background&quot;  Value=&quot;Beige&quot;/&amp;gt;
        &amp;lt;/DataTrigger&amp;gt;
    &amp;lt;/Style.Triggers&amp;gt;
&amp;lt;/Style&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W tym przypadku nasz trigger reaguje na zmiany właściwości &lt;code&gt;Text&lt;/code&gt;.
Jako, że nie ustawiliśmy źródła bindowania, właściwość &lt;code&gt;Text&lt;/code&gt; będzie wyszukiwana w &lt;code&gt;DataContext&lt;/code&gt; danej kontrolki.
W przypadku gdy &lt;code&gt;DataContext&lt;/code&gt; nie zostanie ustawiony, właściwość ta będzie wyszukiwana w kontrolce będącej wyżej w hierarchii.
W przypadku gdy wartość właściwości &lt;code&gt;Text&lt;/code&gt; będzie wynosiła &lt;code&gt;Kolor&lt;/code&gt; tło kontrolki zostanie zmienione na kolor beżowy.&lt;/p&gt;
&lt;h3&gt;3. MultiData triggers&lt;/h3&gt;
&lt;p&gt;Oto przykład wykorzystania &lt;code&gt;MultiDataTriggera&lt;/code&gt;. W &lt;code&gt;ResourceDictionary&lt;/code&gt; tworzymy styl, który zostanie przypisany do przycisku.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Style x:Key=&quot;MultiDataTrigger&quot; TargetType=&quot;{x:Type Button}&quot;&amp;gt;
    &amp;lt;Style.Triggers&amp;gt;
        &amp;lt;MultiDataTrigger&amp;gt;
            &amp;lt;MultiDataTrigger.Conditions&amp;gt;
                &amp;lt;Condition Binding=&quot;{Binding Path=Text}&quot; Value=&quot;Kolor&quot;/&amp;gt;
                &amp;lt;Condition Binding=&quot;{Binding Path=Title}&quot; Value=&quot;Spider-Man&quot;/&amp;gt;
            &amp;lt;/MultiDataTrigger.Conditions&amp;gt;
            &amp;lt;Setter Property=&quot;Background&quot; Value=&quot;Black&quot;/&amp;gt;
        &amp;lt;/MultiDataTrigger&amp;gt;
    &amp;lt;/Style.Triggers&amp;gt;
&amp;lt;/Style&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Tym razem nasz trigger zareaguje, tylko i wyłącznie gdy wartość właściwości &lt;code&gt;Text&lt;/code&gt;(znajdującej się w &lt;code&gt;DataContext&lt;/code&gt;) będzie równe &lt;code&gt;Kolor&lt;/code&gt;, oraz wartość właściwości &lt;code&gt;Title&lt;/code&gt; będzie równa &lt;code&gt;Spider-Man&lt;/code&gt;.
W chwili gdy warunek ten zostanie spełniony, tło kontrolki zmieni się na kolor czarny.&lt;/p&gt;
&lt;h3&gt;4. MultiTrigger&lt;/h3&gt;
&lt;p&gt;Zasada działania &lt;code&gt;MultiTriggera&lt;/code&gt; jest analogiczna z zasadą działania &lt;code&gt;MultiDataTriggera&lt;/code&gt;.
Różnica między ni mi jest taka, że w &lt;code&gt;MultiTriggerze&lt;/code&gt; możemy jedynie odnosić się do propertisów danej kontrolki (kontrolki dla której styl tworzymy,oraz kontrolek wchodzących w skład naszej kontrolki).
Przykładowy kod &lt;code&gt;MultiTriggera&lt;/code&gt; może wyglądać w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Style x:Key=&quot;MultiTrigger&quot; TargetType=&quot;{x:Type Button}&quot;&amp;gt;
    &amp;lt;Style.Triggers&amp;gt;
        &amp;lt;MultiTrigger&amp;gt;
            &amp;lt;MultiTrigger.Conditions&amp;gt;
                &amp;lt;Condition Property=&quot;Background&quot; Value=&quot;Black&quot;/&amp;gt;
                &amp;lt;Condition Property=&quot;IsMouseOver&quot; Value=&quot;True&quot;/&amp;gt;
            &amp;lt;/MultiTrigger.Conditions&amp;gt;
            &amp;lt;Setter Property=&quot;Content&quot; Value=&quot;MultiTrigger&quot;/&amp;gt;
        &amp;lt;/MultiTrigger&amp;gt;
    &amp;lt;/Style.Triggers&amp;gt;
&amp;lt;/Style&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Tym razem nasz trigger zareaguje, tylko i wyłącznie gdy tło naszej kontrolki będzie czarne, oraz kursor myszy będzie znajdował się nad przyciskiem.
W chwili gdy warunki ten zostaną spełnione, napis na przycisku zmieni się na &lt;code&gt;MultiTrigger&lt;/code&gt;&lt;/p&gt;
&lt;h3&gt;5. Event triggers&lt;/h3&gt;
&lt;p&gt;Event triggery wykraczają poza zakres tej części tutoriala, gdyż są one ściśle związane z animacjami.&lt;/p&gt;
</content:encoded></item><item><title>Style</title><link>https://tpodolak.com/blog/style/</link><guid isPermaLink="true">https://tpodolak.com/blog/style/</guid><pubDate>Sun, 27 Nov 2011 17:41:00 GMT</pubDate><content:encoded>&lt;p&gt;Style jest to mechanizm wprowadzony w &lt;code&gt;WPF-ie&lt;/code&gt;, a następnie w &lt;code&gt;Silverlighcie&lt;/code&gt;, dzięki któremu w łatwy sposób można ujednolicić wygląd elementów naszej aplikacji.
Style z reguły definiowane są w zasobach.
Mogą to być zarówno zasoby całej aplikacji, danego okna lub nawet wybranej kontrolki.
Przykładowy styl może wyglądać w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Style x:Key=&quot;przycisk&quot;&amp;gt;
    &amp;lt;Setter Property=&quot;Button.FontSize&quot; Value=&quot;22&quot; /&amp;gt;
    &amp;lt;Setter Property=&quot;Button.Background&quot; Value=&quot;Orange&quot; /&amp;gt;
    &amp;lt;Setter Property=&quot;Button.Width&quot; Value=&quot;60&quot; /&amp;gt;
&amp;lt;/Style&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Każdy styl jest rozpoznawany dzięki unikalnemu kluczowi - parametr &lt;code&gt;x:Key&lt;/code&gt;.
Możliwe jest pominięcie klucza, w przypadku gdy ustawiona zostanie właściwść &lt;code&gt;TargetType&lt;/code&gt;.
Jednakże zdefiniowanie właściwości &lt;code&gt;TargetType&lt;/code&gt; spowoduje, że dany styl będzie automatycznie zastosowany do wszystkich kontrolek danego typu.
W przypadku gdybyśmy jednak chcieli wyłączyć dany styl dla pojedynczej kontrolki możemy zawsze przypisać mu wartość &lt;code&gt;x:Null&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Jak widać styl posiada kolekcję obiektów typu &lt;code&gt;Setter&lt;/code&gt;. Najważniejszymi propertisami każdego &lt;code&gt;Settera&lt;/code&gt; są:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Property&lt;/code&gt; - określa nazwę właściwości, którą dany styl będzie modyfikować,&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Value&lt;/code&gt; - określa wartość właściwości określonej w elemencie &lt;code&gt;Property&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Dla przykładu - następujący styl:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
&amp;lt;Style x:Key=&quot;przycisk&quot;&amp;gt;
    &amp;lt;Setter Property=&quot;Button.FontSize&quot; Value=&quot;22&quot; /&amp;gt;
&amp;lt;/Style&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;ustawi rozmiar czcionki na buttonie na &lt;code&gt;22 pkt&lt;/code&gt;.
Jako, że nie została ustawiona właściwość &lt;code&gt;TargetType&lt;/code&gt; dla stylu, musimy podawać pełną nazwę właściwości(czyli nazwę klasy oraz nazwę właściwości).
Oczywiście możemy również ustawiać bardziej skomplikowane właściwości&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Style TargetType{x:Type Button}&amp;gt;
    &amp;lt;Setter Property=&quot;RenderTransform&quot;&amp;gt;
        &amp;lt;Setter.Value&amp;gt;
            &amp;lt;SkewTransform CenterX=&quot;.5&quot; CenterY=&quot;.5&quot; AngleX=&quot;-10&quot; AngleY=&quot;15&quot; /&amp;gt;
        &amp;lt;/Setter.Value&amp;gt;
    &amp;lt;/Setter&amp;gt;
&amp;lt;/Style&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W przypadku gdybyśmy pisali w &lt;code&gt;Silverlighcie&lt;/code&gt; właściwość &lt;code&gt;TargetType&lt;/code&gt; ustawia się troszeczkę inaczej.
Mianowicie zamiast &lt;code&gt;TargetType{x:Type Button}&lt;/code&gt; piszemy &lt;code&gt;TargetType{Button}&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Właściwość &lt;code&gt;TargetType&lt;/code&gt; określa nam dla jakiego typu obiektów(kontrolek) dany typ jest przeznaczony.
Styl z pierwszego przykładu można zapisać następująco:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Style  TargetType={x:Type Button}&amp;gt;
    &amp;lt;Setter Property=&quot;FontSize&quot; Value=&quot;22&quot; /&amp;gt;
&amp;lt;/Style&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Dzięki użyciu właściwości &lt;code&gt;TargetType&lt;/code&gt;, kompilator wie, że dany styl jest przeznaczony dla &lt;code&gt;Buttona&lt;/code&gt;, dlatego też możemy w &lt;code&gt;Setterze&lt;/code&gt; użyć skróconej nazwy właściwości(&lt;code&gt;FontSize&lt;/code&gt; zamiast &lt;code&gt;Button.FontSize&lt;/code&gt;).
Ponadto dzięki użyciu &lt;code&gt;TargetType&lt;/code&gt;, możemy pominąć definiowanie klucza po jakim nasz styl będzie rozpoznawany.
Od tej chwili wszystkie buttony będą renderowane z użyciem powyższego stylu (oczywiście jeżeli styl ten będzie w resourcach danej kontrolki).&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Dziedziczenie styli&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Style mogą być dziedziczone. Oznacza to tyle, że styl pochodny będzie rozszerzał styl bazowy.
W przypadku gdy styl bazowy ma zdefiniowany &lt;code&gt;TargetType&lt;/code&gt;, styl dziedziczący nie może go zmienić.
W celu zdefiniowania dziedziczenia używa się właściwości BasedOn.
Przykładowe dziedziczenie styli pokazano poniżej&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Style x:Key=&quot;baseStyle&quot;&amp;gt;
    &amp;lt;Setter Property=&quot;FontSize&quot; Value=&quot;12&quot; /&amp;gt;
    &amp;lt;Setter Property=&quot;Background&quot; Value=&quot;Orange&quot; /&amp;gt;
&amp;lt;/Style&amp;gt;
&amp;lt;Style x:Key=&quot;boldStyle&quot; BasedOn=&quot;{StaticResource baseStyle}&quot;&amp;gt;
    &amp;lt;Setter Property=&quot;FontWeight&quot; Value=&quot;Bold&quot; /&amp;gt;
&amp;lt;/Style&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W stylu dziedziczącym można przesłaniać właściwości ze stylu bazowego.
W przypadku gdy nie zostaną one przesłonięte, użyte zostaną propertisy ze stylu bazowego.
W celu zaaplikowania stylu do jakiejś kontrolki posługujemy się następującą składnią&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Button Style=&quot;{StaticResource myStyle}&quot;&amp;gt;&amp;lt;/Button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;myStyle&lt;/code&gt; - klucz stylu zdefiniowanego w zasobach.&lt;/p&gt;
</content:encoded></item><item><title>Commands - czyli interakcja widoku z ViewModelem cz.2</title><link>https://tpodolak.com/blog/commands-czyli-interakcja-widoku-z-viewmodelem-cz-2/</link><guid isPermaLink="true">https://tpodolak.com/blog/commands-czyli-interakcja-widoku-z-viewmodelem-cz-2/</guid><pubDate>Sun, 27 Nov 2011 16:05:00 GMT</pubDate><content:encoded>&lt;p&gt;Tak jak wspomniałem w poprzednim wpisie, tym razem zajmiemy się tworzeniem własnej klasy implantującej interfejs &lt;code&gt;ICommand&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;1. Implementacja interfejsu &lt;code&gt;ICommand&lt;/code&gt; - &lt;code&gt;WPF&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;Klasa implementująca &lt;code&gt;ICommand&lt;/code&gt; może wyglądać w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class DelegateCommand : ICommand
{
    private Action&amp;lt;object&amp;gt; execute;
    private Func&amp;lt;object, bool&amp;gt; canExecute;
    
    public event EventHandler CanExecuteChanged
    {
        add
        {
            CommandManager.RequerySuggested += value;
        }
        remove
        {
            CommandManager.RequerySuggested -= value;
        }
    }
    
    public DelegateCommand(Action&amp;lt;object&amp;gt; execute, Func&amp;lt;object, bool&amp;gt; canExecute)
    {
        this.execute = execute;
        this.canExecute = canExecute;
    }
    
    public bool CanExecute(object parameter)
    {
        if (canExecute == null) return true;
        return canExecute(parameter);
    }
    
    public void Execute(object parameter)
    {
        if (execute == null) return;
        execute((object)parameter);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Klasa &lt;code&gt;DelegateCommand&lt;/code&gt; przyjmuje w konstruktorze dwa parametry - delegaty do funkcji.
Pierwszy z nich jest to delegat do funkcji, która ma się wykonać, gdy komenda może zostać wykonana.
Drugi natomiast jest to delegat do funkcji, która sprawdza czy dana komenda może zostać wykonana.
Ważnym elementem jest tutaj następujący kawałek kodu:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public event EventHandler CanExecuteChanged
{
    add
    {
        CommandManager.RequerySuggested += value;
    }
    remove
    {
        CommandManager.RequerySuggested -= value;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;który podłącza naszą klasę do &lt;code&gt;WPF-owego&lt;/code&gt; systemu komend.&lt;/p&gt;
&lt;p&gt;Teraz wystarczy w ViewModelu stworzyć obiekt typu DelegateCommand przekazać do niego odpowiednie funkcje, a następnie zbindować go do widoku.
Może to wyglądać w następujący sposób:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;ViewModel&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public ICommand AddCommand { get; set;}

public WatchListViewModel()
{
    AddCommand = new DelegateCommand(val =&amp;gt; Add(), val =&amp;gt; CanAdd());
}
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Widok (&lt;code&gt;XAML&lt;/code&gt;)&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Button Command=&quot;{Binding AddCommand}&quot;/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;2. Implementacja interfejsu &lt;code&gt;ICommand&lt;/code&gt; &lt;code&gt;Silverlight&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;Przedstawiony powyżej przykład skompiluje się jedynie w aplikacji &lt;code&gt;WPF-owej&lt;/code&gt;.
&lt;code&gt;Silverlight&lt;/code&gt; niestety nie posiada &lt;code&gt;CommandManagera&lt;/code&gt;, dlatego też gdy chcemy używać komend właśnie w tej technologii musimy zmodyfikować nasz kod na następujący:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class DelegateCommand : ICommand
{
    public event EventHandler CanExecuteChanged;
    private Action&amp;lt;object&amp;gt; execute;
    private Func&amp;lt;object, bool&amp;gt; canExecute;
    private bool previousState;
    
    public DelegateCommand(Action&amp;lt;object&amp;gt; execute, Func&amp;lt;object, bool&amp;gt; canExecute)
    {
        this.execute = execute;
        this.canExecute = canExecute;
    }
    
    public DelegateCommand(Action&amp;lt;object&amp;gt; execute)
    {
        this.execute = execute;
    }
    
    public bool CanExecute(object parameter)
    {
        if (canExecute == null) return true;
        bool currentState = canExecute((object)parameter);
        if (currentState != previousState)
        {
            previousState = currentState;
            if (CanExecuteChanged != null)
                CanExecuteChanged(this, EventArgs.Empty);
            return currentState;
        }
        return currentState;
    }
    
    public void Execute(object parameter)
    {
        if (execute == null) return;
        execute((object)parameter);
    }
    
    public void RaiseCanExecute()
    {
        if (CanExecuteChanged != null)
            CanExecuteChanged(this, EventArgs.Empty);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Jak widać w funkcji&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public bool CanExecute(object parameter)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;sami musimy zadbać o wywołanie zdarzenie&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public event EventHandler CanExecuteChanged;

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Ponadto dopisana została funkcja&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public void RaiseCanExecute()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;funkcję tą musimy wywoływać zawsze gdy zmieni się jakaś właściwość, która ma mieć wpływ na stan przycisku zbindowanego do naszej komendy.&lt;/p&gt;
&lt;h3&gt;3. Przykład&lt;/h3&gt;
&lt;p&gt;Załóżmy, że na widoku mamy przycisk edytuj, który powinien być aktywny tylko i wyłącznie wtedy, gdy zaznaczono jakiś element na gridzie.
Przycisk ten jest zbindowany do komendy &lt;code&gt;EditCommand&lt;/code&gt;.
Jak już wcześniej wspomniano, z powodu braku w &lt;code&gt;Silverlighcie&lt;/code&gt; &lt;code&gt;CommandManagera&lt;/code&gt; sami musimy wywołać zdarzenie informujące o potrzebie zmiany stanu przycisku.
Dlatego też, w &lt;code&gt;ViewModelu&lt;/code&gt; została stworzona właściwość &lt;code&gt;SelectedItem&lt;/code&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public Department SelectedItem
{
    get { return selectedItem; }
    set
    {
        selectedItem = value;
        NotifyPropertyChanged(() =&amp;gt; SelectedItem);
        EditCommand.RaiseCanExecute();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;która reaguje na zmiany zaznaczenia na gridzie.
W chwili, gdy zaznaczenie się zmienia, wywoływany jest seter z tej właściwości, w którym to wywołujemy funkcję &lt;code&gt;EditCommand.RaiseCanExecute&lt;/code&gt;.
Dzięki czemu informujemy kontrolkę o ewentualnej potrzebie zmiany jej stanu.&lt;/p&gt;
&lt;h3&gt;4. Podsumowanie&lt;/h3&gt;
&lt;p&gt;Komendy w bardzo prosty i wygodny sposób pozwalają nam wywoływać metody bezpośrednio z &lt;code&gt;ViewModelu&lt;/code&gt;.
Niestety mają one również swoje ograniczenia:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;reagują jedynie na zdarzenie &lt;code&gt;Click&lt;/code&gt;,&lt;/li&gt;
&lt;li&gt;można je wykorzystać jedynie na kontrolkach dziedziczących po klasie &lt;code&gt;ButtonBase&lt;/code&gt; oraz kontrolkach typu &lt;code&gt;MenuItem&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
</content:encoded></item><item><title>Commands - czyli interakcja widoku z ViewModelem cz.1</title><link>https://tpodolak.com/blog/commands-czyli-interakcja-widoku-z-viewmodelem-cz-1/</link><guid isPermaLink="true">https://tpodolak.com/blog/commands-czyli-interakcja-widoku-z-viewmodelem-cz-1/</guid><pubDate>Sun, 27 Nov 2011 15:21:00 GMT</pubDate><content:encoded>&lt;h3&gt;1. Wstęp&lt;/h3&gt;
&lt;p&gt;Każdy programista, który napisał chociaż parę linijek kody w &lt;code&gt;WinFormsach&lt;/code&gt; wie, że kontrolki używają eventów do powiadamiania o zmianach swojego stanu.
W przypadku, gdy interesuje nas odpowiednia reakcja na zdarzenie, podpinamy się do niego odpowiednią funkcją i wykonujemy założone przez nas operację.
W analogiczny sposób można postępować w &lt;code&gt;WPF-ie&lt;/code&gt; oraz w &lt;code&gt;Silverlighcie&lt;/code&gt;, jednakże podejście takie niejako mija się z modelem &lt;code&gt;MVVM&lt;/code&gt;.
Posiadanie event handlerów w kodzie, ściśle wiąże nam widok (&lt;code&gt;XAML&lt;/code&gt;) z code behind lub nawet z samym &lt;code&gt;ViewModelem&lt;/code&gt; danego widoku.
Ponadto używanie eventów jest problematyczne (a właściwie niemożliwe), gdy widoki zostaną zdefiniowane w &lt;code&gt;Resourcach&lt;/code&gt;.
Dodatkową wadą używania event handlerów jest fakt, że aplikacje w których widok jest mocno związany z codebehind nie należą do aplikacji, które w łatwy sposób można poddać testom automatycznym.&lt;/p&gt;
&lt;h3&gt;2. Interfejs &lt;code&gt;ICommand&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;W celu rozluźnienia połączenia między widokiem a &lt;code&gt;ViewModelem&lt;/code&gt; wprowadzono interfejs&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public interface ICommand
{  
    event EventHandler CanExecuteChanged;    
    bool CanExecute(object parameter);    
    void Execute(object parameter);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Funkcja&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public bool CanExecute(object parameter)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;ma za zadanie sprawdzić, czy daną komendę można wykonać.
Jeżeli nie,funkcja zwraca false i kontrolka zbindowana do danej komendy jest wygaszana (właściwość &lt;code&gt;IsEnabled&lt;/code&gt; danej kontrolki ustawiana jest na &lt;code&gt;false&lt;/code&gt;).
Z kolei funkcja&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public void Execute(object parameter)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;jest to odpowiednik event handlera podłączonego do zdarzenia. Zdarzenie&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public event EventHandler CanExecuteChanged;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;informuje widok o tym czy dana komenda może się wykonać czy też nie - dzięki temu kontrolka wie kiedy się odświeżyć(zmienić wartość właściwości &lt;code&gt;IsEnabled&lt;/code&gt;).&lt;/p&gt;
&lt;h3&gt;3. Sposób użycia&lt;/h3&gt;
&lt;p&gt;Załóżmy, że mamy okno na którym znajduje się przycisk.
Po naciśnięciu przycisku chcielibyśmy aby wykonała się jakaś czynność.
Każdy obiekt typu &lt;code&gt;Window&lt;/code&gt; oraz &lt;code&gt;Control&lt;/code&gt; posiada kolekcję &lt;code&gt;CommandBindings&lt;/code&gt;, która przechowuje wszystkie komendy danego okna.
W celu dodania nowej komendy należy zrobić następującą rzecz.
Po pierwsze musimy stworzyć nową komendę. Robimy to przy pomocy następującego kodu:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;private static RoutedCommand AddCommand = new RoutedCommand();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W celu dodania komendy do danego okna/kontrolki wykonujemy następującą operację&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;this.CommandBindings.Add(new CommandBinding(AddCommand,ExecuteAddCommand,CanExecuteAddCommand));
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Funkcja &lt;code&gt;Add&lt;/code&gt; z klasy &lt;code&gt;CommandBindingCollection&lt;/code&gt; przyjmuje w parametrze obiekt typu &lt;code&gt;CommandBinding&lt;/code&gt;.
Konstruktor takiego obiektu składa się z trzech parametrów:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;RoutedCommand&lt;/code&gt; - obiekt typu &lt;code&gt;RoutedCommand&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;delegat typu &lt;code&gt;ExecutedRoutedEventHandler&lt;/code&gt; - jest to delegat do funkcji, która ma się wykonać w przypadku gdy dana komenda spełnia warunki do “uruchomienia”&lt;/li&gt;
&lt;li&gt;delegat typu &lt;code&gt;CanExecuteRoutedEventHandler&lt;/code&gt; - jest to delegat do funkcji, która sprawdza czy daną komendę można wykonać.
W celu zabronienia wykonania komendy należy ustawić argument &lt;code&gt;ExecutedRoutedEventArgs&lt;/code&gt; &lt;code&gt;CanExecute&lt;/code&gt; na &lt;code&gt;false&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Na koniec należy jeszcze zbindować naszą komendę z przyciskiem.
Przykładowy kod dodawania komendy może wyglądać w następujący sposób.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public partial class WatchList : Window
{
    private static RoutedCommand AddCommand = new RoutedCommand();
    
    public WatchListViewModel viewModel = new WatchListViewModel();
    
    public WatchList()
    {  
        InitializeComponent();
        this.CommandBindings.Add(new CommandBinding(AddCommand, ExecuteAddCommand, CanExecuteAddCommand));
    }
    
    private void CanExecuteAddCommand(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = viewModel.CanAdd();
    }
    
    private void ExecuteAddCommand(object sender, ExecutedRoutedEventArgs args)
    {
        viewModel.Add();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Bindowanie w przycisku do komendy może wyglądać w następujący sposób&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;Button {x:Static local:WatchList.AddCommand}&amp;gt;&amp;lt;/Button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;gdzie &lt;code&gt;local&lt;/code&gt; jest aliasem na namespace, w którym znajduje się okno.&lt;/p&gt;
&lt;h3&gt;4. Podsumowanie&lt;/h3&gt;
&lt;p&gt;Użycie komend w pewnym stopniu oddzieliło nam widok od codebehind-a, jednakże wciąż nie jest to rozwiązanie idealne.
Z codebehind-a wywołujemy metody &lt;code&gt;ViewModelu&lt;/code&gt;, więc niejako ciągle jesteśmy bezpośrednio zależni od widoku.
W części drugiej zaprezentuję w jaki sposób można stworzyć własny obiekt implementujący interfejs &lt;code&gt;ICommand&lt;/code&gt;, dzięki czemu ograniczymy do minimum ilość kodu pisanego w codebehind.&lt;/p&gt;
</content:encoded></item><item><title>INotifyPropertyChanged oraz Expresssion Trees</title><link>https://tpodolak.com/blog/inotifypropertychanged-oraz-expresssion-trees/</link><guid isPermaLink="true">https://tpodolak.com/blog/inotifypropertychanged-oraz-expresssion-trees/</guid><pubDate>Sun, 27 Nov 2011 10:24:00 GMT</pubDate><content:encoded>&lt;p&gt;Interfejs &lt;code&gt;INotifyPropertyChangedPropertyChanged&lt;/code&gt; znany jest prawdopodobnie każdemu programiście &lt;code&gt;C#&lt;/code&gt;.
Interfejs ten zawiera jedynie jedno zdarzenie&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public event PropertyChangedEventHandler PropertyChanged;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;które powinniśmy odpalić w momencie gdy dana właściwość zostanie przez nas zmieniona.
Dzięki temu dowolny obiekt, który będzie nasłuchiwał zmian danej właściwości zostanie o tym poinformowany.
Przykładowa klasa implementująca ten interfejs może wyglądać w następujący sposób:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    
    private string viewModelName;
    public string ViewModelName
    {
        get { return viewModelName; }
        set
        {
            viewModelName = value;
            NotifyPropertyChanged(&quot;ViewModelName&quot;);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Jak widać została stworzona funkcja pomocniczna&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public void NotifyPropertyChanged(string propertyName)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;którą wywołujemy w setterze danej właściwości, podając w parametrze nazwę tej właściwości.
Niestety podejście takie jest bardzo podatne na błędy.
Po pierwsze bardzo łatwo można przekręcić nazwę właściwości, a co gorsze rozwiązanie takie nie jest uwzględniane podczas refactoringu.
Dlatego też w celu poprawienia naszego rozwiązania skorzystamy z mechanizmów dostarczanych przez &lt;code&gt;Expression Trees&lt;/code&gt;.
Po pierwsze zmieniamy funkcję&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public void NotifyPropertyChanged(string propertyName)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;na&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public void NotifyPropertyChanged(Expression&amp;lt;Func&amp;lt;object&amp;gt;&amp;gt; propertyExpression)
{
    if(PropertyChanged == null) return;
    
    PropertyChanged(this, new PropertyChangedEventArgs(GetPropertyName(propertyName)));
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;funkcja pomocnicza &lt;code&gt;GetPropertyName&lt;/code&gt; ma następującą postać&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;private string GetPropertyName(Expression&amp;lt;Func&amp;lt;object&amp;gt;&amp;gt; propertyExpression)
{
    var unaryExpression = propertyExpression.Body as UnaryExpression;
    var memberExpression = unaryExpression == null ? (MemberExpression)propertyExpression.Body : (MemberExpression)unaryExpression.Operand;
    var propertyName = memberExpression.Member.Name;
    return propertyName;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Teraz wystarczy prosty zapis&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;NotifyPropertyChanged(()=&amp;gt; ViewModelName)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;który odwołuje się bezpośrednio do właściwości a nie jej nazwy.
Dzięki temu kod w całości zostanie zrefaktoryzowany.
Rozwiązanie to jest teoretycznie odrobinę wolniejsze od używania stringów, jednak w praktyce jest to niezauważalne.
Można również funkcję&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;string GetPropertyName(Expression&amp;lt;Func&amp;lt;object&amp;gt;&amp;gt; propertyExpression)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;wyciągnąc do osobnej klasy i zrobić z tej funkcji extension method.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static string GetPropertyName(this object obj, Expression&amp;lt;Func&amp;lt;object&amp;gt;&amp;gt; propertyExpression)
{
    var unaryExpression = propertyExpression.Body as UnaryExpression;
    var memberExpression = unaryExpression == null ? (MemberExpression)propertyExpression.Body : (MemberExpression)unaryExpression.Operand;
    var propertyName = memberExpression.Member.Name;
    return propertyName;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Od teraz wystarczy, że zaimportujemy odpowiedni namespace i możemy wykorzystać naszą funkcję w każdej klasie.&lt;/p&gt;
</content:encoded></item></channel></rss>