• WinForms: Errors, Holmes

      Picture 5

      We like to search for errors in Microsoft projects. Why? It's simple: their projects are usually easy to check (you can work in Visual Studio environment for which PVS-Studio has a convenient plugin) and they contain few errors. That's why the usual work algorithm is as follows: find and download an open source project from MS; check it; choose interesting errors; make sure there are few of them; write an article without forgetting to praise the developers. Great! Win-win-win: it took a little time, the bosses are glad to see new materials in the blog, and karma is fine. But this time «something went wrong». Let's see what we have found in the source code of Windows Forms and whether we should speak highly of Microsoft this time.
      Read more →
    • Saving Routing State to the Disk in a Cross-Platform .NET Core GUI App with ReactiveUI and Avalonia

      • Translation
      • Tutorial


      User interfaces of modern enterprise applications are quite complex. You, as a developer, often need to implement in-app navigation, validate user input, show or hide screens based on user preferences. For better UX, your app should be capable of saving state to the disk when the app is suspending and of restoring state when the app is resuming.

      ReactiveUI provides facilities allowing you to persist application state by serializing the view model tree when the app is shutting down or suspending. Suspension events vary per platform. ReactiveUI uses the Exit event for WPF, ActivityPaused for Xamarin.Android, DidEnterBackground for Xamarin.iOS, OnLaunched for UWP.

      In this tutorial we are going to build a sample application which demonstrates the use of the ReactiveUI Suspension feature with Avalonia — a cross-platform .NET Core XAML-based GUI framework. You are expected to be familiar with the MVVM pattern and with reactive extensions before reading this note. Steps described in the tutorial should work if you are using Windows 10 or Ubuntu 18 and have .NET Core SDK installed. Let's get started!

      Read more →
    • «Reader» monad through async/await in C#

        In my previous article I described how to achieve the "Maybe" monad behavior using async/await operators. This time I am going to show how to implement another popular design pattern "Reader Monad" using the same techniques.

        That pattern allows implicit passing some context into some function without using function parameters or shared global objects and it can be considered as yet another way to implement dependency injection. For example:

        class Config { public string Template; }
        public static async Task Main()
            Console.WriteLine(await GreetGuys().Apply(new Config {Template = "Hi, {0}!"}));
            //(Hi, John!, Hi, Jose!)
            Console.WriteLine(await GreetGuys().Apply(new Config {Template = "¡Hola, {0}!" }));
            //(¡Hola, John!, ¡Hola, Jose!)
        //These functions do not have any link to any instance of the Config class.
        public static async Reader<(string gJohn, string gJose)> GreetGuys() 
            => (await Greet("John"), await Greet("Jose"));
        static async Reader<string> Greet(string name) 
            => string.Format(await ExtractTemplate(), name);
        static async Reader<string> ExtractTemplate() 
            => await Reader<string>.Read<Config>(c => c.Template);
        Read more →
      • .NET – Tools for working with multithreading and asynchrony – Part 2

          I have originally posted this article in CodingSight blog.
          It's also available in Russian here.

          This article comprises the second part of my speech at the multithreading meetup. You can have a look at the first part here and here. In the first part, I focused on the basic set of tools used to start a thread or a Task, the ways to track their state, and some additional neat things such as PLinq. In this part, I will fix on the issues you may encounter in a multi-threaded environment and some of the ways to resolve them.


          Read more →
        • “Maybe” monad through async/await in C# (No Tasks!)

            Generalized async return types — it is a new C#7 feature that allows using not only Task as a return type of async methods but also other types (classes or structures) that satisfy some specific requirements.

            At the same time, async/await is a way to call a set of "continuation" functions inside some context which is an essence of another design pattern — Monad. So, can we use async/await to write a code which will behave in the same way like if we used monads? It turns out that — yes (with some reservations). For example, the code below is compilable and working:

            async Task Main()
              foreach (var s in new[] { "1,2", "3,7,1", null, "1" })
                  var res = await Sum(s).GetMaybeResult();
                  Console.WriteLine(res.IsNothing ? "Nothing" : res.GetValue().ToString());
              // 3, 11, Nothing, Nothing
            async Maybe<int> Sum(string input)
                var args = await Split(input);//No result checking
                var result = 0;
                foreach (var arg in args)
                    result += await Parse(arg);//No result checking
                return result;
            Maybe<string[]> Split(string str)
              var parts = str?.Split(',').Where(s=>!string.IsNullOrWhiteSpace(s)).ToArray();
              return parts == null || parts.Length < 2 ? Maybe<string[]>.Nothing() : parts;
            Maybe<int> Parse(string str)
                => int.TryParse(str, out var result) ? result : Maybe<int>.Nothing();

            Further, I will explain how the code works...

            Read more →
          • AdBlock has stolen the banner, but banners are not teeth — they will be back

          • Write Better Code Faster with Roslyn Analyzers

              Roslyn, the .NET compiler platform, helps you catch bugs even before you run your code. One example is Roslyn’s spellcheck analyzer that is built into Visual Studio. Let’s say you are creating a static method and misspelled the word static as statc. You will be able to see this spelling error before you run your code because Roslyn can produce warnings in your code as you type even before you’ve finished the line. In other words, you don’t have to build your code to find out that you made a mistake.

              Roslyn analyzers can also surface an automatic code fix through the Visual Studio light bulb icon that allows you to fix your code immediately.

              Read more →
            • Fighting complexity in software development

                What's this about

                After working on different projects, I've noticed that every one of them had some common problems, regardless of domain, architecture, code convention and so on. Those problems weren't challenging, just a tedious routine: making sure you didn't miss anything stupid and obvious. Instead of doing this routine on a daily basis I became obsessed with seeking solution: some development approach or code convention or whatever that will help me to design a project in a way that will prevent those problems from happening, so I can focus on interesting stuff. That's the goal of this article: to describe those problems and show you that mix of tools and approaches that I found to solve them.

                Read more →
                • +19
                • 2.1k
                • 2
              • Tutorial: Update interfaces with default interface members in C# 8.0

                  Beginning with C# 8.0 on .NET Core 3.0, you can define an implementation when you declare a member of an interface. The most common scenario is to safely add members to an interface already released and used by innumerable clients.

                  In this tutorial, you'll learn how to:

                  • Extend interfaces safely by adding methods with implementations.
                  • Create parameterized implementations to provide greater flexibility.
                  • Enable implementers to provide a more specific implementation in the form of an override.

                  Read more →
                • Microservices architecture & implementation Step-by-Step Part 1

                  Hi All,

                  I’m in the process of implementing a new simple microservices-based project as an example of a step-by-step guide for those who had a hard time with a microservices architecture and are still looking for “another” good reference. Also, I would really appreciate thought through feedback and proposal to make this project a high-quality chunk of work.

                  There are tons of articles and source code examples. But, unfortunately, I could not find any reference with simple step-by-step instructions, without doing a deep dive into Docker, Event Store, a multitude of configurations, cloud deployment stuff, etc. I cloned several projects and tried to start playing with them, but you know, only God knows how to start them, which dependencies are missing and why all those scripts are failing with thousands of ERRORS.

                  For example, this eShop project from Microsoft contains all we need, but it is not so simple to figure out what is going on there, SQL database connection strings, Docker scripts fail, no How-Tos and I’m not sure it is super-simple architecture you need to start with.

                  Read more →
                • Simplify working with parallel tasks in C# (updated)


                    No doubts that async/await pattern has significantly simplified working with asynchronous operations in C#. However, this simplification relates only to the situation when asynchronous operations are executed consequently. If we need to execute several asynchronous operations simultaneously (e.g. we need to call several micro-services) then we do not have many built-in capabilities and most probably Task.WhenAll will be used:

                    Task<SomeType1> someAsyncOp1 = SomeAsyncOperation1();
                    Task<SomeType2> someAsyncOp2 = SomeAsyncOperation2();
                    Task<SomeType3> someAsyncOp3 = SomeAsyncOperation3();
                    Task<SomeType4> someAsyncOp4 = SomeAsyncOperation4();
                    await Task.WhenAll(someAsyncOp1, someAsyncOp2, someAsyncOp4);
                    var result = new SomeContainer(
                         someAsyncOp1.Result,someAsyncOp2.Result,someAsyncOp3.Result, someAsyncOp4.Result);

                    This is a working solution, but it is quite verbose and not very reliable (you can forget to add a new task to “WhenAll”). I would prefer something like that instead:

                    var result =  await 
                        from r1 in SomeAsyncOperation1()
                        from r2 in SomeAsyncOperation2()
                        from r3 in SomeAsyncOperation3()
                        from r4 in SomeAsyncOperation4()
                        select new SomeContainer(r1, r2, r3, r4);

                    Further I will tell you what is necessary for this construction to work...

                    Read more →
                  • Dynamically generating robots.txt for ASP.NET Core sites based on environment

                      I'm putting part of older WebForms portions of my site that still run on bare metal to ASP.NET Core and Azure App Services, and while I'm doing that I realized that I want to make sure my staging sites don't get indexed by Google/Bing.

                      I already have a robots.txt, but I want one that's specific to production and others that are specific to development or staging. I thought about a number of ways to solve this. I could have a static robots.txt and another robots-staging.txt and conditionally copy one over the other during my Azure DevOps CI/CD pipeline.

                      Then I realized the simplest possible thing would be to just make robots.txt be dynamic. I thought about writing custom middleware but that sounded like a hassle and more code that needed. I wanted to see just how simple this could be.

                      Read more →
                    • SQL Index Manager – a long story about SQL Server, grave digging and index maintenance

                        SQL Index Manager

                        Every now and then we create our own problems with our own hands… with our vision of the world… with our inaction… with our laziness… and with our fears. As a result, it seems to become very convenient to swim in the public flow of sewage patterns… because it is warm and fun, and the rest does not matter – we can smell round. But after a fail comes the realization of the simple truth – instead of generating an endless stream of causes, self-pity and self-justification, it is enough just to do what you consider the most important for yourself. This will be the starting point for your new reality.

                        For me, the written below is just such a starting point. The way is expected to be lingering…
                        Let's go?
                      • Announcing .NET Core 3.0 Preview 6

                          Today, we are announcing .NET Core 3.0 Preview 6. It includes updates for compiling assemblies for improved startup, optimizing applications for size with linker and EventPipe improvements. We’ve also released new Docker images for Alpine on ARM64.

                          Read more →
                        • .NET: Tools for working with multi-threading and asynchrony – Part 1

                            I have originally posted this article in CodingSight blog
                            The second part of the article is available here

                            The need to do things in an asynchronous way – that is, dividing big tasks between multiple working units – was present long before the appearance of computers. However, when they did appear, this need became even more obvious. It is now 2019, and I’m writing this article on a laptop powered by an 8-core Intel Core CPU which, in addition to this, is simultaneously working on hundreds of processes, with the number of threads being even larger. Next to me, there lies a slightly outdated smartphone which I bought a couple of years ago – and it also houses an 8-core processor. Specialized web resources contain a wide variety of articles praising this year’s flagship smartphones equipped with 16-core CPUs. For less then $20 per hour, MS Azure can give you access to a 128-core virtual machine with 2 TB RAM. But, unfortunately, you cannot get the most out of this power unless you know how to control interaction between threads.
                            Read more →
                          • Porting desktop apps to .NET Core

                              Since I’ve been working with the community on porting desktop applications from .NET Framework to .NET Core, I’ve noticed that there are two camps of folks: some want a very simple and short list of instructions to get their apps ported to .NET Core while others prefer a more principled approach with more background information. Instead of writing up a “Swiss Army knife”-document, we are going to publish two blog posts, one for each camp:

                              • This post is the simple case. It’s focused on simple instructions and smaller applications and is the easiest way to move your app to .NET Core.
                              • We will publish another post for more complicated cases. This post will focus more on non-trivial applications, such WPF application with dependencies on WCF and third-party UI packages.

                              If you prefer watching videos instead of reading, here is the video where I do everything that is described below.

                              Read more →
                            • Nullable Reference types in C# 8.0 and static analysis

                                Picture 9

                                It's not a secret that Microsoft has been working on the 8-th version of C# language for quite a while. The new language version (C# 8.0) is already available in the recent release of Visual Studio 2019, but it's still in beta. This new version is going to have a few features implemented in a somewhat non-obvious, or rather unexpected, way. Nullable Reference types are one of them. This feature is announced as a means to fight Null Reference Exceptions (NRE).
                                Read more →
                              • The architecture of an exceptional situation: pt.2 of 4

                                  I guess one of the most important issues in this topic is building an exception handling architecture in your application. This is interesting for many reasons. And the main reason, I think, is an apparent simplicity, which you don’t always know what to do with. All the basic constructs such as IEnumerable, IDisposable, IObservable, etc. have this property and use it everywhere. On the one hand, their simplicity tempts to use these constructs in different situations. On the other hand, they are full of traps which you might not get out. It is possible that looking at the amount of information we will cover you’ve got a question: what is so special about exceptional situations?

                                  However, to make conclusions about building the architecture of exception classes we should learn some details about their classification. Because before building a system of types that would be clear for the user of code, a programmer should determine when to choose the type of error and when to catch or skip exceptions. So, let’s classify the exceptional situations (not the types of exceptions) based on various features.

                                  Read more →