The ‘yield’ keyword

The ‘yield’ keyword is something that I’ve just ignored for years and even though I had an idea of what it was doing i’ve actually never used it myself.

This is what msdn has to say:

When you use the yield keyword in a statement, you indicate that the method, operator, or get accessor in which it appears is an iterator. Using yield to define an iterator removes the need for an explicit extra class (the class that holds the state for an enumeration, see IEnumerator<T> for an example) when you implement the IEnumerable and IEnumerator pattern for a custom collection type.

Alright, all clear?

So basiclly you are able to return an IEnumerable to use in say a for each. I guess it hasn’t that many uses, but one use is to batch a list so I came up with a great extension method for batching lists.

 

Now look at that beauty 🙂

So it returns <count> number of elements every iteration.

My test code was the following

and the output of this is as follows

So every iteration it returns 3 elements except the last iteration where it returns 1 element.

Now, it’s not the most used scenario, but definitely something to have i you library when needed.

Asp.net Core and Docker (vs2015)

At home I have one desktop computer where I do 99% of my work and one old laptop which i installed Ubuntu server on a couple of months ago. I don’t really use it for anything at this point so I got the idea to run my latest project in docker containers on that one. The plan is to use it for testing server.

So, where to start?

You will need asp.net core installed on your dev machine and docker on your server. I run git bash on my local dev and ssh server on my ubuntu to be able to send files back and forth.

So, on your dev machine, just create a new asp.net core project in visual studio and then run it. If you did everything correctly you should see something like this:
2016-12-17-13_02_12-home-page-dockertest3

The next step is to create a file called “Dockerfile” in your project folder.

2016-12-17-13_04_34-dockertest3-microsoft-visual-studio

Add this to the file.

What this does is to tell docker to use the microsoft/dotnet image, copy the root dir to app and set that to working directory. After that “dotnet restore” and “dotnet build” will be run. Since we use port 5000 by default we will expose that. Then we will run “dotnet run”.

This is basiclly what we need to do, so let’s build the docker image.

Send it to your server. Since we are using git bash we wont see any progress of the transfering, but when the prompt comes back it should be done. It will likley take a couple of minutes (about 1 gig to transfer)

And run it on your server

At this step you might get an error saying you’ve got the wrong version of .net core. At the time of writing this post the latest version is 1.1.0 and when i create projects in vs.net it defaults to 1.0.1. So just change it to 1.1.0 in project.json, rebuild docker image, transfer and try again.
Now the image should be running on your linux machine and by going to :8080 you should get the page.

[Reflection] Invoking method passed by string

Today I got an idea to do some basic data manipulation through a terminal, and since I’m a bit lazy I wanted to be able to type something like Substring to preform a substring for a string. I was thinking that it should be possible with reflection and sure, I was right 🙂

The only problem I had was that I needed to pass what parameters the method takes and parse that parameter. It’s ugly, but for a test it worked. The reson for this is that substring is overloaded. Both (int startIndex) and (int startIndex, int length);

Below is the ugly code from my first test.

Since I will only use this for my own classes which has no overloading I don’t have to specify the parameters. The casting will also be avoided if i just do pass string all over and cast later. So, all in all, this will be helpful 🙂

Console application with Window (WPF and Windows Forms)

My latest project is a tool to help me analyze and visualize soccer data and for this I felt that I needed a Console Application to control and modify the data, and a window or two to show graphs and other visualizations. When I started I had a couple of options to make this work.

  1. Show a Console from wpf/windows forms project. This means that when i close my form, the app will terminate.
  2. Do a terminal with the rich text control.
  3. Show a wpf/windows form window from Console.

Since the application is controlled by the terminal and pops up a window every now and then option 1 goes away.
Option 2, well, I want a real feeling of a terminal, rich text doesn’t really give me that. So option 3 it was.

Console + Windows Forms

I turns out that for Windows Forms it was pretty straight forward.
I have created a Console Application project, added a “Windows Form” to my project that is called “WindowsForm”, and to show the Window form console, just do

One tip, since i was going to show graphs I needed to pass some data to my form and i did this with a custom constructor, and if you do this, don’t forget:

Otherwise it will be an empty control.

Console + WPF

Wpf was a little bit trickier, as always.

The first thing I did was to create a UserControl, and in the .cs file i changed the inheritance from UserControl to Window, and in the xaml i change the UserControl tag to Window.

The next step was to add a reference to System.Xaml. After this step it was possible to build at least.

In order to show the form I took a similar approach as for windows forms (but using a different package for application)

And this was the first lesson, apparently the Main must be marked as a STAThread (more info here)

This will indeed open a wpf window from a console, but as it turns out, Application.Run won’t return like the Windows Forms counterpart.

So my solution was to start another thread and use that to show the window, and the final code is shown below.

I pretty sure there will be tons of issues that i haven’t found yet, but so far so good 🙂

If you find problems or has a better solution, please leave a comment.

 

Logging with Serilog in .NET

A logger might be one of the most boring task to do while coding, but fortunately there is packages like Serilog that handles that for you. I don’t have that high demands for a logger, as long as it outputs my log entries where I want it and the way I want while beeing easy to use, I’m happy 🙂

Installing Serilog

The first thing you’ll need to do is add Serilog to your project with nuget.

Apart from that you will also need sinks which is not in the core package. The easiset way to find those are probably to search for Serilog in nuget package manager. The first one I will use is Serilog.Sinks.ColoredConsole.

Setup Serilog

To create a global ColoredConsole logge, this is all you need to do:

And of course, if you want a local logger:

And to actually output anything you can try this:

If you try to run this you will only see 4 of the 6 prints (Information, Warning, Error and Fatal) and this is because you have a minimum level set. The default minimum level is Information, which means that everything including and above Information will be displayed.

Output with serilog

If you want to see verbose and debug as well you need to change the minimum level, This is done when initializing the logger:

And this is the result

Output with serilog

I want more!

Usually it’s pretty useful to log the same logs to different sinks, at least one to console and one to file. And this is also pretty straight forward during initialization:

There are a log more features for serilog like

  • Sinks – Write to more places such as mail, azure, rabbitmq and more
  • Enrichers – Enrich your logs with different properties sucha as thread id
  • Filters – filter out specific entries

Conclusion

There is a lot more to do with Serilog than I have described here and if you are interested you should go to the documentation and check out what you really can do. From my perspective it does everything i want a logger to do which is log to console, file, rolling file and being able to set levels for each while at the same time being lightweight and easy to add.

 

Getting started with unit tests in C#

As a first real post, unit tests seems like a good idea since you are supposed to write unit tests before the real code. Most developers would agree that they are really great when properly maintained, but not a lot of developers really want to write them.

From my experience, projects fall in to one of three categories when it comes to unit tests.

  1. Little or no unit tests – Either they started doing tests in the beginning of the project and when the horrible deadline started getting close the just skipped the tests or the project were in panic mode from day 1 which means no tests. This will lead to project type 2.
  2. The project has been active for a good while, with little or no unit tests, and suddenly everyone wants full test coverage. This leads to a massive effort from all of the developers (or maybe some consultants) to get 100% coverage. The quality of the tests will probably be crap since only coverage counts and the tests are useless.
  3. The developers in this project has been in a type 1 or type 2 project before, so they are really motivated to write the tests before the implement the function. The coverage might not be 100%, but the quality will be top notch. Even when the deadline is getting closer they will persevere and keep writing those tests because they know that in the end, the will save a lot of time. Every now and then they will find some bugs with help from those test.

This is at least how all projects I’ve been working on could be defined.

Even though I really hate writing tests i really enjoy having them, so type 3 is the way to go. Hell, I even write tests for my personal projects every now and then.

Writing your first unit test

Project to test

First up is to create a project to test, and for today I will go with a class library. I create a project called MyLibrary with one single class called MyClass:

Nothing fancy, but it will do to demonstrate unit testing.

Test project

The next step is to create a test project. The wat to do this is just to create a new project in the same solution as MyLibrary and select “Unit Test Project” and name it. You will also need to add references to MyLibrary.

Add new "Unit Test Project"

After the project is created you need to create a new class, mine is called “TestMyClass” is just an empty class without methods.

In order for Visual Studio to find the tests, the class needs “TestClass” attribute, the methods needs a TestMethod attribute and needs to be public like this:

 

The next step is to write the actual tests. We will start with a simple test that just calls ToLower with the parameter “Foo”. If everything works like it should, we should get “foo” back.
If you have read the tutorial on unit test on MSDN you probably noticed that they use the pattern “Arrange, Act, Assert” which I find pretty intuitive.

This means that you first set upp everything, call the method to test then check the return value. For our class that means:

After you’ve added this to your test class, you run the test by going to Test -> Run -> All test. Now Visual Studio will MyLibrary and TestProject, open Test Explorer and run all tests and the result should be something like this:

Test result

When testing your code you should test all possibilities, and one of them testing for exceptions. You could of course do this by a try/catch around your method, but a more elegant solution is to add “ExpectedException” attribute to your class. In our case a test with null would look something like this:

This is two small examples of unit tests just to show you how it could be done to get you started writing your own tests. MSDN has a pretty good article series which is probably a good idea if you want to dig deeper. You can find it here.

Organizing your tests

I guess you could do any way you want, but having a clear naming convention helps you find the correct test within seconds and when a test fails, you know why immediately.

Naming classes

First off, every single class get there own test class, so if your tested class is named Foo, the name for the test class should be something like TestFoo.

Naming methods

I like to name it Mehod_Params_Result, so if the function is Add with parameters 3 and 4, the name for that test would be Add_With3And4_7. I think it’s a simple and clear way of naming methods. Although, if you have a lot of parameters it will be a mess.

I also think that each test should be kept in a separate method.

 

 

First post

The first post of a blog is always the hardest to write. I have started a few blogs before, and the first one is always a pain in the neck. Usually I write about what this blog will cover, in great detail. But who cares? You will probably see my next couple of posts.

So this time a welcome and an introduction should be enough.

So, who am I?
My name is Daniel and I work as a developer for one of those new and hip company where everything is JavaScript *shrugs* and NoSQL. Before that I worked as a .Net developer which I still miss. I’ve been developing for at least 20 years and 10 of those years it’s been professionally. I’ve worked at a big consultant company, small start ups, medium size companies and huge companies. It’s been C, C++, C#, Java, JavaScript and much much more. And apart from this I of course code on my spare time as well.

That’s it about me….So welcome to ByteMeBlog.com!