How to add Microsoft.Extensions.DependencyInjection to OWIN Self-Hosted WebApi

October 17, 2016 .NET, HowTo, WebApi 1 comment

I could not find an example showing how to use Microsoft.Extensions.DependencyInjection as IoC in OWIN Self-Hosted WebApi, as a result here is this blog post.

Let’s imagine that you have WebApi that you intend to Self-Host using OWIN. This is fairly easy to do. All you will need to do is to use Microsoft.Owin.Hosting.WebApp.Start method and then have a bit of configuration on IAppBuilder (check out ServiceHost.cs and WebApiStartup.cs in the gist below).

It becomes a bit more complicated when you want to use an IoC container, as OWIN’s implementation takes care of creating Controller instances. To use another container you will need to tell the configuration to use implementation of IDependencyResolver (see WebApiStartup.cs and DefaultDependencyResolver.cs). DefaultDependencyResolver.cs is a very simple implementation of the resolver.

In case you are wondering what Microsoft.Extensions.DependencyInjection is. It is nothing more than a lightweight DI abstractions and basic implementation (github page). It is currently used in ASP.NET Core and EF Core, but nothing prevents you from using it in “normal” .NET. You can integrate it with more feature-rich IoC frameworks. At the moment it looks like Autofac has the best integration and nice documentation in place. See OWIN integration.

Rest is just usual IoC clutter. See the gist

I hope this blog post helps you with integrating Microsoft.Extensions.DependencyInjection in WebApi hosted via OWIN.


1 comment


Ember upgrade from 1.7.0 to 1.13.13

October 4, 2016 EmberJS No comments

EmberRelease Obviously there are general upgrade guides provided by Ember team and many fellow bloggers. This is just to document one of the experiences with upgrading from ember 1.7.0 to 1.13.13.

At the moment of this writing Ember latest stable version is 2.8. My team was one of the early adopters of Ember. I believe the team started incorporating it in late 2013, which is very soon after the 1.0 release. We went live with the version 1.7 at the beginning of 2015 and since that time we didn’t do any updates for “penny wise and pound foolish” reasons.

Upgrade itself was a bit of pain as it spread for couple of months. We allocated few days per sprint and at the same time continued developing new features the old way in other branches. Bad idea.

Another pain was that we adopted Ember Data while it was still beta. As a result we have custom code altering adapter’s and serializer’s behaviour. There are many breaking changes between beta versions of Ember Data, so using it while in beta was a very bad idea.

One of great things about being on Ember 1.13.13 version is that you are effectively on 2.0.0 version unless you have deprecation messages in your console. This also means that you can still release your application with some parts not being completely converted to the new way of doing things. ember.prod.js doesn’t generate warnings and works just fine. I really like the way Ember tries to make upgrading easy. Here is a nice write up on handling deprecations as of 2.3.0.

List of useful links:

Gotcha list:

This list is composed from notes I took so it is not very well organized and does not contain all of the items we had to fix.

When upgrading from 1.7 to 1.8

  • Update ember data to 1.0.0-beta.11 for compatibility and as a fix for “Ember Data cannot read property 'async' of undefined"
  • Replace pushObject with addRecord to fix “You looked up the relationship on a with id but some of the associated records were not loaded.”
  • This does not work and has to be rewritten Ember.Handlebars.helpers.render.call(this, name, contextString, options)
  • Use Ember.set() whenever there was controller.isNew property with some set

When upgrading from 1.8 to 1.10.1

  • Start using HTMLBars instead of Handlebars by incorporating ember-template-compiler
  • add stripBOM to grunt file… as template compiler includes those: template = template.replace(/\uFEFF/g, ''); // remove BOM
  • Fix HTML to be correct (closing tags, missing tbody, etc)
  • ember-data 1.0.0-beta.11 has bug in findQuery asserts => upgrade ember-data to 1.0.0.beta12
  • Remove //# sourceMappingURL=ember-data.js.map
  • Ensure models are generated with {async: false}
  • Remove code that works with MetamorphView. Fixes this: Assertion Failed: A fragment cannot be pushed into a buffer that contains content because of: view.createChildView(Ember._MetamorphView, {

When upgrading from 1.10.1 to 1.11.4

At this point you start to get tons of deprecation messages.

  • You attempted to access `someProperty` from `<App.SomeXyzController:ember2661>`, but object proxying is deprecated. Please use `model.someProperty` instead.
  • Convert this {{action bubbles=false preventDefault=false}} to this {{action "ok" "close" "cancel" bubbles=false preventDefault=false}}
  • Fix dynamic compilation of HTMLBars. Cannot call `compile` without the template compiler loaded. Please load `ember-template-compiler.js` prior to calling `compile`. Ember.HTMLBars.compile(submitHtmlTemplate); doesn’t produce a correct function to retrieve HTML. Can be solved as in this SO answer.
  • Using @each at the end of a computed key is deprecated and will not work in Ember 2.0
  • Replace Ember.Enumerable.mapProperty with mapBy
  • Replace Ember.Handlebars.helper with Ember.Helper.helper

When upgrading from 1.11.4 to 1.13.13

  • Rewrite code that uses itemController
  • Rewrite properties that have setter to the new computed syntax

I hope this comes in handy for you.


No comments


Running Challenge Completed. Health, Motivation, and Other Aspects Of Running

October 2, 2016 Opinion No comments

Are you bent by scoliosis programmer? Do you spend too much time sitting? Maybe you look a bit flabby? Super tired at and after work? High chances are that some of these are true for you. Some certainly are true for me. This year I tried to improve my situation by running. Here are my thoughts and humble recommendations.

Dirty Running Shoes

Running and its impact on your Health

“Being physically active reduces the risk of heart disease, cancer and other diseases, potentially extending longevity.” – many studies show accordingly to this article. Probably one of the most accessible forms of exercising is running. All you need to start is just pair of shoes. This research paper is a good resource on learning about impact of running and other exercises on chronic diseases and general mortality.

So why running? – Because it is easy to start with and because we are made for it. “Humans can outrun nearly every other animal on the planet over long distances.” – says this article. Funnily enough there is yearly Human vs. Horse marathon competition.

If you ask yourself how you want your last two decades before death look like, most likely you would picture a healthy, mobile, and socially active person. Also you would prefer those two decades better be 80’s and 90’s. Right? Light running for as little as 1 hour a week could add as much as 6 years to your life. This long-term study showed that “the age-adjusted increase in survival with jogging was 6.2 years in men and 5.6 years in women.” (For those who are pedantic and want to know net win: (2 hrs/wk * 52 wks a year * 50 years) / 16 day hours = 325 days lost to running still gives you net 5 years).

Motivation

At my age I do not think about the death that much. My main motivation for running is improvement of my health. I know that for many people extra weight is motivating factor. For me it is not as instead of loosing weight I gained some 2-3 kg. Likely I’m so skinny there is no way to loose fat, though there is room for leg muscles growth. Unfortunately running is often boring and it is very hard to get yourself outside and go for a run on that nasty cold day. Here are few things that helped me running this year:

Run different routes

Always running at same location taking same path is boring. If you travel somewhere, just take your shoes with yourself and have a run at new place. Not only you get to have another run, but you explore the location. I ran in five different countries this year and could tell that those runs are more interesting than usual next to home ones.

Running in Ireland Gap Of Dunloe

Join friends or running club

I was going for runs rather rarely at the beginning of the year, but later as I started running with friends I started to run more frequently. It is always much more pleasant to have a conversation and learn few new things from friends, especially if areas of your interest overlap more than just running.

Running With Friends

Sign up for a challenge

Sports are competitive by nature. You can have friendly competition with your fellow runners, or you can take a virtual challenge. That works great because the clock is ticking and you want to have it done. This September I took it to the next level by signing up to Strava monthly challenges. I have completed all of them. See Trophy Case below:

Strava September Running Challenge

Be careful and avoid injury

You don’t want to walk with a cane when old because you were too stupid and run too much and too hard when young. I’m sick of running because of this September challenge. I completed it, but last two runs I ran through the pain being injured. I’m recovering now using RICE recovery technique. From now on I will take it easier. Suggesting the same for you.

RICE Recovery - Icing an Ankle

You can do it

I’m not a good runner. At the beginning of the year I could barely run 5km, I didn’t know how I will complete my planned 40 runs as it was so hard. Running 40 times was my main year goal. I did not expect that I will ran for around 50 times totaling 320 km. And it is not the end of the year yet. I also ran a Half-Marathon distance running a top Kahlenberg hill next to Vienna. If I can do it – you can!

Conclusion

I completely agree with research and studies that “for majority of people the benefits of running overweight the risks” and at the same time I voluntarily ran through the injury just to complete my challenge. Motivation is an important factor, but runners have to be careful and moderate their exercising. This is especially true if you run for the health reasons. Just try to make your runs more interesting and enjoy your life… longer.

Running under Speed sign


No comments


Book Review: What If?: Serious Scientific Answers to Absurd Hypothetical Questions

September 20, 2016 Book Reviews No comments

What if - Book CoverI read this book because of the recommendation I found online. It was in one of the Bill Gate’s reading lists. Maybe this post will have same effect on you… and you will decide to pick it for your reading.

“They say there are no stupid questions,” the author writes. “That’s obviously wrong. . . . But it turns out that trying to thoroughly answer a stupid question can take you to some pretty interesting places.”

Indeed, I remember we had a lot of hypothetical scientific discussions with my friends during my university days and these discussion would just go on and on ending sometime around 2AM. It was a lot of fun diving deep and exploring every possible twist. You get to have same fun when you read the book.

Well… it is actually more fun to read the book, since it is very nicely illustrated and thoroughly researched. Basically you don’t get to read rant – everything is cross checked with scientists by Munroe.

I guess this book also teaches to approach problems that require scaling, approximation, simplification, calculation, estimation. It also helps to understand physics better. And if you have some silly question that keeps you awake at nights you can always submit it on the xkcd web site.

This book is pure entertainment and joy. I can surely recommend this book to anyone generally interested in science.


No comments


Book Review: Coders At Work

April 26, 2016 Book Reviews No comments

coders-at-work-cover-bigThe book “Coders At Work” is a collection of interviews of famous coders. The book takes a reader through 15 career stories. It inspires and gives insight into minds of great programmers.

Most of the selected coders are of older generations, so at times, it is hard or, rather, not exceptionally interesting to follow some of their career endeavours. Especially, if the whole career was around one system or one language that is “dead” today (think of COBOL, Fortran, PDP-1, etc). I don’t mind to know the history of the industry, but I’m not interested in too much of the details (you can blame me if you wish). On the other hand, it was very interesting to try to understand how these people think and how they approached problems they had. I really believe there is a lot to learn from them.

The author, Peter Seibel, starts interviews with a usual but interesting question about how the interviewees got involved in programming. Then, the author proceeds to questions that relate somehow to what interviewees have done in their careers. There are standard questions about debugging, favorite editor, opinion on some programming language, and other.

I liked answers to the question on how they hired people and what advise they can give to the young programmers.

There were a couple of questions that I didn’t like. One was “Do you consider yourself a scientist, an engineer, an artist, or a craftsman?”. I think it is a pointless question. These nouns can be interpreted in different ways and any answer would be just fine.

Throughout the book there was a discussion about the importance of computer science education and one of the questions was if interviewees have read the book “The Art Of Computer Programming”. It was kind of introduction to the last interview with Donald Knuth. I liked the interview with him, but I’m not sure if the author had to put so much emphasis on this personality.

The list of interviews is available at book’s website with short descriptions of who those people are and what they did. To be honest, before reading “Coders At Work”, I only knew about Douglas Crockford, Joshua Bloch, and Donald Knuth.

Conclusion

The book gives insight into how some of the great programmers achieved what they have achieved. It educates and inspires, though some of the stories might not be very exciting. At times, you may think that other big names would have made the book even more interesting. Nevertheless, I liked reading the book “Coders At Work”.



No comments


Working with Excel files using EPPlus and XLSX.JS

February 29, 2016 C#, JavaScript, Opinion, QuickTip, Tools 1 comment

Need to quickly generate an Excel file on the server (.NET) with no headache or need to import  another Excel file in your JS client?

I can recommend two libraries for their simplicity and ease of use.

XLSX.JS

To smooth transitioning from Excel files to electronic handling of data we offered our users possibility of importing data. As our application is web based it meant some JS library to work with Excel files. A bit of complication was that our users over time developed a habit of having all kinds of modifications in their “custom” Excel files. So something that would allow us easily work with different formats was a preference.

XLSX.JS library available on GitHub proved to be a good choice. I could only imagine how much better it is over some monsters that would only work in IE. I think starting documentation is fairly good, so I will just go through some bits and pieces from our use case.

Setting up XLSX.JS and reading files is straight forward: npm or bower, include of file and you are ready to write XLSX.readFile('test.xlsx') or App.XLSX.read(excelBinaryContents, {type: 'binary'}).

Reading as binary is probably a better bet as it will work in IE, though you will have to write some code to implement FileReader.prototype.readAsBinaryString() in IE. You can have a look at our implementation of file-select component on gist.

Using XLSX in your JavaScript is fairly easy, though there might be some hiccups with parsing dates. See this gist.

EPPlus

We also have two use cases where we need to generate Excel file on the server. One was to generate some documentation for business rules so we can have it up to date and share with our users at all times. It was implemented as part of CI that would save a file to a file system. The other use case was downloading of business related data via web interface. These two were super easy to do with open source library called EPPlus.

You just add EPPlus through NuGet and start using (var excelPackage = new ExcelPackage(newFileInfo)). See the gist below. First file demonstrates how to operate with cells and the other one just shows how you can use streams to make file downloadable.

These two libraries really helped me to efficiently implement some of the Excel file business use cases.

Next time I will have to generate Excel file on server or read it on client I will most certainly use these two again.


1 comment


Book Review: Release it! Design and Deploy Production-Ready Software

February 19, 2016 Book Reviews No comments

Book Review: Release it! Design and Deploy Production-Ready Software“Release it!” is an excellent book that makes you and your application prepared for the harsh production world. The book entertains on all kinds of things related to the most important part of development lifecycle – releasing your product and keeping it alive.

The book has four parts – stability, capacity, general design issues, and operations. Each part is introduced by interesting case studies, for instance describing how single unhandled exception costed an airline a day of nightmare and tons of money.

Keywords

Let me list some of the keywords from the book for better idea what the book is about:

  • Part I – Stability: scaling strategies; fail fast; SLA; timeouts; circuit breaker; bulkhead (don’t sink entire ship); common sense on log files; health checks; etc.
  • Part II – Capacity: resource pools; threads; payload sizes; db performance; cookies; caching; etc.
  • Part III – General Design Issues: load balancing; clustering; configurations; networking; security; etc.
  • Part IV – Operations: transparency; statistics; logging; monitoring systems; etc.

Pros

Things that I really liked about the book:

  • It easy to read, provided you have relevant experience
  • Real world case studies
  • “Remember This” sections after most of the chapters (better than boring summaries)
  • Realistic strategies and approaches
  • Business costs and impact discussed

There is a really nice strategy explained on zero-downtime. One, that especially boggles me, was approach related to database upgrade process for zero downtime. The strategy is relatively simple: 1) you extend the system/db and add some bits and pieces so it is backwards compatible, for db it could mean new nullable columns and triggers to fill-in data, 2) you roll out, 3) you cleanup. Easy!

Cons

Not so great things about the book:

  • Some technologies mentioned are somewhat outdated (book released in 2007)
  • Examples are in Java and frameworks mentioned are Java-world, so not totally language agnostic
  • At places a bit too ops heavy

Conclusion

The book will be most useful for developers of large enterprise applications, especially where downtime costs real money.

But, in any case, I would highly recommend any developer, and deployment engineer for that matter, to read this book!



No comments


Book Review: The Design of Everyday Things

February 1, 2016 Book Reviews No comments

TheDesignOfEverydayThings_BookCoverThere were few not so technical books that have made it to my technical reading list last year. One of those was a book called “The Design of Everyday Things”. It can probably be considered a classics for designers, it is also helpful for software developers who do some UI. But it doesn’t harm to read the book even if you have nothing to do with designing anything as it allows to understand how things are designed and why in many cases designer is there to blame and not you when something isn’t working as you were expecting.

For starters, have you even been in situation wondering how that damn thing is working? It could have been a microwave impossible to open or a complicated ticket machine in some country or software written by “lousy” software developers. Just look at the kettle on the book’s cover. Any ideas how to pour water with this kettle?

The book brings many show cases for good and bad design (somewhat dated, though). It explains what a good design means and what are constraints designers have to battle, like time, price and not the least look and feel.

Recently we found out that one of our old applications is not used by users because it is too complicated. At that same time, if used, it could save hours and hours of manual work. It is on our roadmap to rewrite this app, but at least I will have more gear in my tools belt.

I don’t think this is a required reading for software developers, but it definitely enriches your outlook. As a bonus you cal explain your co-workers why a tap in a kitchen is designed is a such and not a different way.



No comments


2016: Where Do You Want to Be In a Year?

January 19, 2016 YearPlanReport 2 comments

Some people say that the best way to motivate yourself is to be inspired and/or desperate. At the moment I don’t feel like I’m any of those two. I was very ambitious and inspired in the past, but I guess things change as you get older.

One thing that still helps me a bit with motivation is planning and recognition of my work by others. You can get inspired just by thinking on what you want to do in your life. Also, in my opinion, planning puts you in somewhat desperate situation as you want to complete items from the list. I don’t know if you like planning or not, but I use it for the above reasons and for the reason of keeping track of greater picture of my life goals.

I’ve been writing year resolution posts on my blog since 2010. There are few things that I’ve learned about planning for a year. It is easy to overestimate what can be done and to lose track if no detailed planning was done. So for this year I want to set somewhat smarter goals and do a detailed elaboration on achieving them. I will break down tasks to monthly tasks and keep track of those separately from this blog, as it will be a total mess to post it here.

92-of-all-new-year-resolutions-fail

Let me start my planning with list of life areas to improve.

I want to improve:

  • health by running regularly and doing some gym
  • life satisfaction by travelling and having more quality time with family
  • soft skills by copying the best characteristics of people I admire
  • professional skills by learning one or two technologies and doing a personal project
  • foreign languages proficiency by acquiring German B1 and fixing English accent
  • financials by learning more on investing, keeping expenses low and deciding on home purchase

Now let me convert this list into some concrete achievable and measurable items.

  1. Run 2-3 times a week for at least 5 warm months.
  2. Make start of the day more healthy and productive. Ideal scenario would be: get up at 05:55AM, drink glass of water, do exercises for 15-30 min, shower, some important task and/or planning for the day, breakfast, work… But I will consider this item achieved if I start doing exercises regularly even if it is only 2 times a week just for 10 minutes.
  3. Travel to the UK, Norway, sea side country, and do a car trip somewhere nice.
  4. Spend one hour every day with my daughter playing and learning things.
  5. Count not more than 12 weekends in a year when we didn’t go out to do some activities.
  6. Learn 12 simple skills from other people. To achieve this goal I will first identify 12 people from the community and those surrounding me and chose some characteristic I admire.
  7. Read at least 6 technical books.
  8. Watch at least 12 pluralsight courses.
  9. Write a simple stock analysing web site. It could have any set of features, point is to get something interesting running.
  10. Write any simple useful open source tool. I have WCF related idea in mind.
  11. Learn at least two web technologies. I have NodeJS and AngularJS in mind at the moment.
  12. Share knowledge more actively. Minimum would be to write 24 blog posts, answer 12 questions on SO, help few people online.
  13. Acquire B1 German certificate, attend German course, finish entire German Duolingo tree.
  14. Learn English language prosody and fix pronunciation of vowels. Optionally attend a specialized language course.
  15. Save 24X my monthly spendings, go through 13 investment books I read in 2015 and extract notes, do reviews and write about them.

In the end of this year I don’t want to find myself among those 92% who fail with their new year’s resolutions, therefore keep an eye on me and I promise I will keep an eye on you, provided that you share your list with me.

Happy New Year!

 

2016-Feb-01 UPDATE: This is how I’m now tracking completion of the above list. I have a broken-down list of tasks for each month in OneNote and I also have recurring and detailed tasks tasks in Wunderlist app.

ExampleOfTrackingNewYearResolutionList


2 comments


What I have done in 2015

January 15, 2016 YearPlanReport No comments

Year 2015 was the year of travel.

AndriyBudayInIceland_1500_500

In the resolution for 2015 we only planned for Iceland and the coast of Italy. But now I wouldn’t even be able to count the number of countries we visited in just one year with our little daughter.

I somehow managed to take short vacations almost every warm month. For that I had to work some additional time, but extra effort was definitely worth the experience. Outside of Schengen Area we went to Turkey and Israel and in Schengen Area itself there are only two countries left where we haven’t been.

I was so much engaged in enjoying my life that didn’t progress that well with my professional life, but on the other hand I expanded and improved some other areas of my life by travelling, investing and doing sports.

Now let’s go through the resolution list:

Travel to Iceland

It was the greatest trip of all we had so far. My wife wrote series of blog posts on this trip (in Ukrainian).

Travel the coast of Italy and do many other car trips

Italy was a week and two days car trip from Austria, but besides of this one we had two Nordic car trips. We drove all the way to Finland from Austria and also took a hired car from Germany to Sweden. I legally set my speed record of 220km/h. I drove two absolutely different car types in Iceland and Israel – two absolutely opposite countries by weather and security situation. Contrast between these two countries is just staggering. You cannot appreciate it unless you visit those two.

Improve German by attending at least 1 course

Attended two courses and hopefully learned something.

Improve English fluency and vocabulary by spending more time on learning words from read books

Subjective, but I guess there is some improvement. I indeed spent some time after reading books on vocabulary. Next big milestone should be my accent.

Read 4 sci-fi books

Done. Enjoyed some.

Read 13 software engineering books

Partially done. Unfortunately, I started way too many of them and haven’t finished reading. Notable mention would be “C# in Depth”.

Read 13 investment books

All done. This was my list. Will have a separate review list, maybe with ratings.

Start project with potential to make money

Not really. Had few friendly offers to work on things together, but I didn’t like any.

Do programming in other languages than C# or JavaScript

Total fail. I tried to start learning F# and didn’t get it past few simple “hello world” apps.

Take part in at least one programming contest

SRM at TopCoder, but this probably cannot be considered a “contest”, therefore fail.

Visit at least one conference (even small one)

Visited .concat() in Salzburg

Write at least 26 blog posts

17 blog post written.

Increase community visibility by contributing more on github, tweeting, commenting on blogs

Subjective, but fail.

Improve health by exercising and attending swimming pool for at least 1 month

Rather success than fail. I didn’t attend swimming pool, but I ran for couple of months and will start again when it gets warmer.

Make at least 2015 euro profit on new investments in 2015

Success and fail at the same very time. I didn’t set this goal properly as I didn’t know much about investing. I was up and down as much few times during the past volatile year. I have some very small realized profit, but I’m not so keen on being active investor as it only makes brokers rich. Will tell more when it gets to it.

It is a bit late to say, but I wish you all

HAPPY NEW YEAR!


No comments