Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

31/08/2016

AjaxExtensions.BeginForm doesn't work. Really?

Home


Source: own resources, Authors: Agnieszka and Michał Komorowscy

The goal of using Ajax is to communicate with the server asynchronously without reloading the entire page. Specifically AjaxExtensions.BeginForm can be used to updated a selected part of a web page. It is relatively easy in use but can be also troublesome. Especially, when we try to apply it in an application which wasn't using Ajax earlier. I decided to wrote this short technical post because recently I came across the following issue the few times:

AjaxExtensions.BeginForm redirects a user to a new page instead of refreshing a fragment of a current one.

This problem has an easy explanation. Under the hood AjaxExtensions.BeginForm uses Java Script library called Microsoft jQuery Unobtrusive Ajax. The issue is that this library is not installed by default if we create a new project. It's easy to forget about it.

If you have the described problem:
  • Check in packages.config file contains Microsoft.jQuery.Unobtrusive.Ajax package.
  • Check if jquery.unobtrusive-ajax.js file is referenced in html e.g.: <script src="/scripts/jquery.unobtrusive-ajax.js"></script>
  • If you use bundles checik if jquery.unobtrusive-ajax.js was included in a bundle e.g.:
    public static void RegisterBundles(BundleCollection bundles)
    {
       ...
       var js = new ScriptBundle("~/bundles/MyBundle").Include("~/Scripts/jquery.unobtrusive-ajax.js");
       ...
    }
  • Besides, check if a bundle with jquery.unobtrusive-ajax.js is rendered properly e.g.:
    @Scripts.Render("~/bundles/MyBundle")

19/08/2016

My struggels with GitHub, Subtrees and Nuget

Home


Source: own resources, Authors: Agnieszka and Michał Komorowscy

Some time ago I decided to publish my projects on GitHub. This decision had very positive repercussion because it mobilized me to do more refactoring and to clean my solutions. Additionally, I switched totally to management of external references via NuGet. Earlier, I had some binaries in a dedicated directory on my computer. It took me some time but it was worth doing it.

I also had to solve the following problem. I have a solution called Common. It is a collection of libraries, utilities, algorithms, helpers etc. that are used in my other projects. Before migration to GitHub, after a build, all Common binaries were copied to the well known location i.e. N:\bin Thanks to that all other projects could reference them from this location. It works. However, if someone wants to download my projects from GitHub, he or she will need to create a mapped drive N manually. I din't like it.

The next step was to switch from absolute references to binaries to relative references to projects. For example let's consider a library MK.Utilities and a project LanguageTrainer that uses it. Initially LanguageTrainer was referencing:

N:\bin\MK.Utilities.dll

After migration this reference was changed to:

..\..\Common\MK.Utilities\MK.Utilities.csproj

Much more better, isn't it? Still, it is not perfect. This relative path will work only if the folder with Common and LanguageTrainer solutions will be in the same place on the disk. Besides, in order to compile LanguageTrainer solution Common solution must be built first. What's more Common and LanguageTrainer are two separate repositories which have to be downloaded individually. My goal was to be able to download any repository/solution and then be able to compile it without any further steps.

I started reading about possible solutions and I found information about git submodules and git subtrees. There is so much about them in Internet so I will not repeat others. For example see this post. At the end I decided to use subtrees. Simplifying a subtree is a copy of some repository in the another one. Returning to my earlier example, by using subtrees I got a copy of Common repository/solution in LanguageTrainer repository/solution. Then I could change the reference to MK.Utilities as follows:

..\Common\MK.Utilities\MK.Utilities.csproj

Besides, I needed to add MK.Utilities project to LanguageTrainer.sln solution so that all projects could be build at the same time. Finally, my LanguageTrainer repository/solution looks in the following way. On left side you can see GitHub and on the right side Visual Studio:


If needed I can refresh a copy of Common repository/solution inside LanguageTrainer at any time. Why I used subtrees? Well, they work for me and are extreamly easy to create via Source Tree ;) By the way, I like git but I hate all this complex commands. Source Tree solves this problem and allows me to use git via friendly GUI. I strongly recommend it.

At the end I had to solve one more problem with Nuget. Let's return again to my example and let's assume that LanguageTrainer solution is located here:

C:\LanguageTrainer

In that case, by default, Nuget packages will be located here:

C:\LanguageTrainer\packages

However, we also have a subtree:

C:\LanguageTrainer\Common

And projects from a subtree expects that their packages will be here:

C:\LanguageTrainer\Common\packages

Of course they won't be there so Common projects will not compile. To overcome this problem I had to manually update csproj files and replace ..\packages with $(Solutiondir)packages. For example:

..\packages\structuremap.3.1.6.186\lib\net40\StructureMap.dll

Was changed as follows:

$(SolutionDir)packages\structuremap.3.1.6.186\lib\net40\StructureMap.dll

I hope that this post will help you in your struggles with GitHub, Subtrees and Nuget.

18/03/2016

Two things I learned about HTML and CSS

Home

I've never worked a lot of with CSS. However, from time to time I do something with it, for example in order to check out new possibilities. Recently, I read about CSS transformations and I decided to give it a try. For the beginning I wanted to achieve a very simple effect i.e. a red square with a blue and a green diagonal lines. It sounds simple and it is simple but there are traps in this exercise. I decided to write this post because it took me a moment to figure out that was wrong. It was also difficult to find a solution in Internet. Maybe because it is so obvious ;)

My idea was to use 3 div elements. One for a square and 2 for diagonal lines. I also wanted to use transformations in order to rotate divs so that they look like diagonals. My first attempt looks as follows. Do you know what is wrong? There are 2 main problems here.

Scroll down if you want to see a correct solution:
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.


I changed two things, one in html and one in CSS:
  • The first problem was that I used div as a self closing tag. It is not allowed. Browsers treat <div /> as <div >. It is quite difficult to spot.
  • The second problem was in the greenLine style. It was not enough to rotate the green div by 45 degrees. Firstly we need to translate it in this way: translate(100px,-141px) rotate(45deg). It might be surprising because in the case of the blue div the rotation was enough. However, we we have to remember that the green div is not located in the origin of the coordinate system but just below the blue div. The blue div looks like a thin line but it's height is set to 141 pixels.

27/02/2016

Tips & Tricks: How to tell VS to modify variables in the runtime for us?

Home

Today, I'd like to share with you a simple but useful trick. Imagine yourself that you are debugging an application and you find a place with the following very simple code:
            
var flag = ReadConfiguration();
if (flag)
{
   //...
}
else
{
   //...
}
The problem is that the flag variable is set to false but you need to check what would happen if it is set to true. Of course you can easily change the value of this variable in Visual Studio. But what would you do if this kind of code is executed dozens, hundreds... of times and every time the flag variable must be set to true? One solution is to modify a configuration, another might be to change the source code. However, all these things require an additional action. It would be much more better to tell Visual Studio to do it for us. How? In order to achieve desired effect we can utilize breakpoints and custom actions. I'll show how to do it in Visual Studio 2015.

Firstly, put a breakpoint in the line with if.


Right click the breakpoint and from a context menu select Actions... Then in the text box enter {flag = true}. You can even use IntelliSense here. At the end click Close button.


An that's all. Now, if you run the application under debugger control a flag variable will be set to true whenever a line with a breakpoint is executed. What's more this trick also works with other types of variables and you can also execute methods in this way e.g.:


At the end I want to say 2 things. Custom actions are usually used to write diagnostic messages to Output window. This trick works because in order to write a message Visual Studio has to execute some code and this code can have side effects. Besides, you can also use this trick in older versions of Visual Studio. The only difference is that from a context menu you need to select When Hit... option.

21/02/2016

My list of online editors

Home

Online editors (testers, debuggers) are awesome if we want to quickly test some code. They are also very useful to check our solution when we want to post an answer on Stack Overflow. Here is my collection of various online editors that I encountered, though personally I use only some of them.

I'm publishing it because it can be helpfull for others and because I'd like to have this list easily accessible in Internet. Of course this list is not complete and there are many other editors. If you know something interesting let me know and I will add it here.


Online Editor Language / Technology Share function Collaborate function
yUMLUMLYes
draw.ioDiagramsYes (via Google docs)Yes
moqupsUI moqupsYesYes
ideoneC#, Java, Haskell, C++, Ada and many otherYes
SQL FiddleSQL (MySQL, Oracle, PostgreeSQL, SQLLite, MSSQL)Yes
regular expressions 101Regular expressionsYes
.NET FiddleC#, VB.NET, F#YesYes
C# PadC#
D3.jsD3.js Java Script library
CodePenHTML + CSS + JSYes
jsfiddleHTML + CSS + JSYesYes
JS BinHTML + CSS + JSYesSoon
CSS DeckHTML + CSS + JSYesYes
LiveweaveHTML + CSS + JSYesYes
PlunkerHTML + CSS + JSYesYes
cpp.shC++Yes

By share function I mean a possibility to create a pernament link to our code. Collaborate functions allows a group of developers to write a code together.

16/02/2016

Interview Questions for Programmers by MK #7

Home

Question #7
You have the following code that uses Entity Framework to retrieve data from Northwind database. Firstly it finds customers that are from London and then process their orders. All data model classes were generated with the code first from database approach. Unfortunately, this code contains a bug that can lead to performance problems. Identity this problem and propose a fix.
using (var ctx = new NorthwindContext())
{
   var londoners = ctx.Customers.Where(e => e.City == "London");
   foreach (var londoner in londoners)
   {
      foreach (var o in londoner.Orders)
      {
         foreach (var d in o.OrderDetails)
         {
            //....
         }
      }
   }               
}
Answer #7
This code is a classical example of N+1 select problem where too many queries are sent to a database. The first query will be sent to a database in order to find customers from London. Then for each customer another query will be sent to read orders. Finally, for each order another query will be sent to retrieve details of a given order. Instead, all data could be retrieved by sending only one query. To do so we need to tell EF that we want to read customers together with their orders and orders details. It can be achieved with Include method.
using (var ctx = new NorthwindContext())
{
   londoners = ctx.Customers.Include("Orders").Include("Orders.Order_Details").Where(e => e.City == "London");
   ...
}
A quick test will show that originally 53 queries are sent to a database and after a fix only 1.

15/11/2015

Interview Questions for Programmers by MK #6

Home

Question #6
What is the arithmetic overflow and how is it handled in .NET?

Answer #6
It is a situation when the result of an arithmetic operation exceeds (is outside of) the range of a given numeric type. For example the maximum value for byte type in .NET is 255. So in the following example, an operation a+b will cause an overflow:
byte a = 255;
byte b = 20;
byte c = a + b;
The final result depends on the used numeric types:
  • For integer types either OverflowException will be thrown or the result will be trimmed/cropped (the default behaviour). It depends on the compiler configuration and usage of checked / unchecked keywords.
  • For floating point types OverflowException will never be thrown. Instead the overflow will lead either to the positive or the negative infinity.
  • For decimal type OverflowException will be always thrown.
var b = byte.MaxValue;
//The result will be zero because:
//b = 255 = 1111 1111 
//b++ = 256 = 1 0000 0000
//The result has 9 bits so the result will be trimmed to 8 bits what gives 0000 0000
b++; 
         
checked
{
 b = byte.MaxValue;
 //Exception will be thrown 
 b++; 
}

var f = float.MaxValue;
//The result will be float.PositiveInfinity
f *= 2;  

decimal d = decimal.MaxValue;
//Exception will be thrown
d++; 

22/10/2015

TransactionScope and multi-threading

Home

It's my third post about TransactionScope. This time I'll write about using it with multi-threading. Let's start with the following code:
using (var t = new TransactionScope())
{
   var t1 = Task.Factory.StartNew(UpdateDatabase);
   var t2 = Task.Factory.StartNew(UpdateDatabase);
   Task.WaitAll(t1, t2);
   t.Complete();
}

private static void UpdateDatabase()
{
   using (var c = new SqlConnection(connectionString))
   {
      c.Open();

      WriteDebugInfo();

      new SqlCommand(updateCommand, c).ExecuteNonQuery();
   }
}

private static void WriteDebugInfo()
{
   Console.WriteLine("Thread= {0}, LocalIdentifier = {1}, DistributedIdentifier = {2}",
      Thread.CurrentThread.ManagedThreadId,
      Transaction.Current?.TransactionInformation.LocalIdentifier,
      Transaction.Current?.TransactionInformation.DistributedIdentifier);
}
It seems simple but it doesn't work. The problem is that a connection that is created in UpdateDatabase method will not participate in any transaction. We can also observe that WriteDebugInfo will write empty transaction identifiers to the console. It happens because in order to read an ambient transaction (the transaction the code is executed in) TransactionScope uses Transaction.Current property which is thread static (i.e. specific for a thread).

To overcome this issue we have two possibilities. The first one is to use DependentTransacion. However, I'll not show how to do it because since .NET 4.5.1 there is a better way - TransactionScopeAsyncFlowOption enum. Let's try.
using (var t = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
   ...
}
Unfortunately, there is a big chance that this time we will get TransactionException with the message The operation is not valid for the state of the transaction. in the line with ExecuteNonQuery. The simplified stack trace is:

at System.Transactions.TransactionStatePSPEOperation.get_Status(InternalTransaction tx)
at System.Transactions.TransactionInformation.get_Status()
...
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Sandbox.Program.UpdateDatabase(Object o)

I read a lot about this but nobody was able to explain why it happens. I also looked into the source code of TransactionStatePSPEOperation class. It was instructive because I learned what is PSPE - Promotable Single Phase Enlistment. However, it also didn't give me an exact answer.

So, I played a little bit with the code and I noticed that the problem occurs when:
  • One thread tries to run ExecuteNonQuery.
  • Another thread waits for the opening of the connection.
However, when both connections were already opened then the exception wasn't thrown.

At this point it is worth reminding one thing - when there are 2 or more connections opened in a transaction scope at the same time then a transaction is promoted to a distributed one. I'm not 100% sure but I think that the problem occurs because it is not allowed to use a connection which participates in a transaction which is in the middle of promotion to the distributed one. So, the solution is to assure that a transaction will be distributed from the beginning. Here is a fixed code with a magic line (I found it here):

using (var t = new TransactionScope())
{
   //The magic line that makes a transaction distributed
   TransactionInterop.GetTransmitterPropagationToken(Transaction.Current);

   var t1 = Task.Factory.StartNew(UpdateDatabase);
   var t2 = Task.Factory.StartNew(UpdateDatabase);
   Task.WaitAll(t1, t2);
   t.Complete();
}
Nonetheless, the more I think about this the more convinced I'm that using TransactionScope with multi-threading is asking for problems.

13/10/2015

How not to use TransactionScope. Another WTF!

Home

This time I will write again about TransactionScope. It is a very useful class and seems to be extremely easy in use. In majority of cases it is true. However, there are also some pitfalls lurking for developers. Especially for these who don't like to waste time for reading MSDN documentation if not really needed i.e. probably vast majority of us ;)

Some time ago, I was analysing more or less the following code:
using(var t = new TransactionScope())
{
   var c = ConnectionProvider.ProvideConnection();
   //Use a connection to update a database
   //...
   t.Complete();
}
ConnectionProvider is a class that hides details of managing connections to a database. There was also a bug in the code responsible for updating a database which caused exceptions. I fixed it and I run tests again. This time an exception was not thrown but something was wrong because a database contained unexpected data. It looked like the transaction was not rollbacked!

Firstly, I though that it is some kind of magic. However, as usual in this kind of cases it wasn't. I digged into ConnectionProvider and I found out that this class was performing some kind of pooling and a connection wasn't opening every time. It was a big problem because connections opened outside a transaction scope do not participate in a transaction. The solution of this problem is to explicitly enlist a connection in an existing transaction scope with the EnlistTransaction method.

It is also worth highlighting that the described problem won't occur if ConnectionProvider doesn't try to implement polling on its own. In general we don't have to do it because .NET do it for us. The problem will also not occur if using statement is used to close a connection returned by a provider.

09/09/2015

TransactionScope + Ninject + a small mistake = WTF

Home

Sometimes one stupid mistake can cost a lot of time. A few days ago my application (AngularJS + ASP.NET Web API) started crashing because of the following error:

MSDTC on server 'XXX' is unavailable

It was strange. I wasn't aware of any distributed transactions in my application. To be honest, I was using TransacionScope but I was sure that there was no reason to promote a lightweight transaction into a distributed one. To make things more strange the error wasn't reported every time. When I tried to update data for the first time everything was ok. However, the second attempt (and every next) was failing.

It took me some time to examine all recent changes but finally I found a problem. It was quite tricky so I decided to write about it. Let's start with the fact that I use Ninject as a dependency injection container. Among others Ninject allow us to control a lifetime of objects (instances). Particularly, in the case of web applications, we can use:
  • InRequestScope method - it tells Ninject that one object of a particular type should be created for each individual request.
  • InSingletonScope method - it tells Ninject that one object of a particular type should be created for all requests.
For example:
kernel.Bind(x => x
   .FromAssembliesMatching("test.dll")
   .SelectAllClasses().InheritedFrom(typeof(IInterfaace))
   .BindAllInterfaces()
   .Configure(z => z.InSingletonScope()));
The problem was that accidentally I mixed InSingletonScope and InRequestScope. For example, let's assume that each request requires objects of two classes A and B. Objects of type A are within the request scope and objects of type B are within the singleton scope.

Both objects perform updates/inserts/deletes and are used inside TransacionScope. For the first request it is not a problem. Both objects are initialized within the same request and use the same database connection. It means that a lightweight transaction is used.

However, for the second (and every next) request an object of type B is re-used whereas a new object of type A is created. Object of type B was initiated in the previous request and it uses a different connection than the one used by an object of type A. It means that a distributed transaction will be used in this case.

To sum up:
  • DI containers give a great power but with the power comes great responsibility.
  • Be careful when using objects of a different scope together. Especially when these objects require data access.
  • Be careful when using multiple connections inside TransacionScope. In the case of MSSQL 2005 in this situation a distributed transaction will be always used. In the case of MSSQL 2008 or newer it is possible to use more than one connection inside TransacionScope without automatic promotion. However, if and only if these connections are not opened at the same time.
  • TransactionScope automatically escalating to MSDTC on some machines? is a great source of knowledge about TransacionScope and about the process of promoting lightweight transactions into distributed ones.

21/08/2015

Do you know OUTPUT clause?

Home

Today, I'll write about using OUTPUT clause together with INSERT statements. It seems to be that it is not a very well known syntax. However, it is especially useful when use Identity columns to generate keys. Let's start with a simple table:
CREATE TABLE dbo.Main
( 
 Id int Identity (1,1) PRIMARY KEY,
 Code varchar(10),
 UpperCode AS Upper(Code)
);
The old fashioned approach to retrieve a value of Identity column for a new row is to use SCOPE_IDENTITY(). For example:
INSERT INTO dbo.Main (Code) VALUES ('aaa');
SELECT SCOPE_IDENTITY();
With OUTPUT clause it will look in the following way:
DECLARE @InsertedIdentity TABLE(Id int);
INSERT INTO dbo.Main (Code) OUTPUT INSERTED.Id INTO @InsertedIdentity VALUES ('aaa')
SELECT TOP(1) * FROM @InsertedIdentity
You can say wait a minute. If I want to use OUTPUT I have to declare a table variable first and then use SELECT. It is more complex than just using SCOPE_IDENTITY().

Well, the first benefit is that with OUTPUT clause we can read values from many columns, including these that are computed (as it was shown above). However, the real power of OUTPUT clause can be observed if we want to insert many rows into a table:
DECLARE @ToBeInserted TABLE(Code varchar(10), Name varchar(100));

INSERT INTO @ToBeInserted
VALUES ('aaa','1111111111'), ('ddd','2222222222'), ('ccc','3333333333');

DECLARE @Inserted TABLE(Id int, Code varchar(10), UpperCode varchar(10));

INSERT INTO dbo.Main (Code)
OUTPUT INSERTED.Id, INSERTED.Code, INSERTED.UpperCode INTO @Inserted
SELECT Code
FROM @ToBeInserted;

SELECT * FROM @Inserted;
Without OUTPUT we would have to write a nasty loop!

Here is one more example. Let's assume that we have an additional table that references dbo.Main.
CREATE TABLE dbo.Child
( 
 MainId int,
 Name varchar(100),
 CONSTRAINT [FK_Child_Main] FOREIGN KEY(MainId)REFERENCES dbo.Main (Id)
);
We want to insert a few rows into dbo.Main and then related rows to dbo.Child. It is quite easy if we use OUTPUT clause.
INSERT INTO dbo.Child (MainId, Name)
SELECT i.Id, tbi.Name
FROM @ToBeInserted tbi
 JOIN @Inserted i ON i.Code = tbi.Code;
Extremely useful thing that you must know!

At the end it is worth mentioning that OUTPUT clause can be also used together with UPDATE, DELETE or MERGE statements.

27/07/2015

A hint how to use TaskCompletionSource<T>

Home

Some time ago I wrote about using TaskCompletionSource<T> class in order to take advantage of async/await keywords. In that post I included the following code:
public async Task<Stream> ProcessFileAsync(string key, string secret, string path)
{
   var client = new DropNetClient(key, secret);
   //...
   var tcs = new TaskCompletionSource<Stream>();
   client.GetFileAsync(path, response => tcs.SetResult(new MemoryStream(response.RawBytes)), tcs.SetException);
   return tcs.Task;
}
Now, Let's assume that we want to provide a possibility to cancel a task returned from ProcessFileAsync method. We can do something like that:
public async Task<Stream> ProcessFileAsync(string key, string secret, string path, CancellationToken ct)
{
   var client = new DropNetClient(key, secret);
   //...
   var tcs = new TaskCompletionSource<Stream>();

   ct.Value.Register(tcs.SetCanceled);

   client.GetFileAsync(path, response => tcs.SetResult(new MemoryStream(response.RawBytes)), tcs.SetException);
   return tcs.Task;
}
I used CancellationToken.Register method in order to register a callback that will be executed when a token is canceled. This callback is responsible for notifying TaskCompletionSource<T> that underlying task should be cancelled.

You may say that it is not enough because this code doesn't inform DropNetClient that an action should be cancelled. You are right. However, according to my knowledge DropNet API doesn't provide such a possibility.

It leads to the situation when a task is cancelled but DropNetClient continues processing and finnaly TaskCompletionSource.SetResult method will be executed. This will cause ObjectDisposedException because this method cannot be executed for a disposed task. What can we do in this case?

The first solution is to check if a task is cancelled before calling SetResult method. However, it can still happen that a task will be cancelled after this check but before calling SetResult method.

My proposition is to use methods from TaskCompletionSource.Try* family. They don't throw exceptions for disposed tasks.
public async Task<Stream> ProcessFileAsync(string key, string secret, string path, CancellationToken ct)
{
   var client = new DropNetClient(key, secret);
   //...
   var tcs = new TaskCompletionSource<Stream>();

   ct.Value.Register(tcs.SetCanceled);

   client.GetFileAsync(path, response => tcs.TrySetResult(new MemoryStream(response.RawBytes)), tcs.TrySetException);
   return tcs.Task;
}
I'm aware that it is not a perfect solution because it actually does not cancel processing. However, without modifying DropNet code it is not possible. It the case of my application it is an acceptable solution but it is not a rule.

16/07/2015

Interview Questions for Programmers by MK #5

Home

Question #5
Here you have a very simple implementation of Template method pattern.
public abstract class BaseAlgorithm
{
   protected SomeObject Resource { get; set; }
   //Other resources

   public void Start()
   {
      // Configure
      Resource = new SomeObject();
      //...
      try
      {
         InnerStart();
      }
      finally
      {
         // Clean up
         Resource.Dispose();
         Resource= null;               
         //...
      }
   }

   protected abstract void InnerStart();
}

public class Algorithm1: BaseAlgorithm
{
   protected override void InnerStart()
   {
      //Do something with allocated resources
   }  
}
At some point someone decided to create a new class Algorithm2 derived from BaseAlgorithm. The difference between the new class and the previous one is that Algorithm2 starts an asynchronous operation. A programmer decided to use async/await keywords to handle this scenario. What do you think about this approach? What could possibly go wrong?
public class Algorithm2: BaseAlgorithm
{
   protected async override void InnerStart()
   {
      var task = DoAsyncCalculations();
      await task;

      //Do something with allocated resources
   }

   private Task DoAsyncCalculations()
   {
      //Let's simulate asynchronous operation
      return Task.Factory.StartNew(() => Thread.Sleep(1000));
   }
}
Answer #5
I think that the developer who created Algorithm2 doesn't understand well how async/await keywords work. The main problem is that finally block inside Start method will be executed before DoAsyncCalculations method will end calculations. In other words resources will be disposed in the middle of calculations and this will cause an exception. Sequence of events will be as follows:
  • Start method begins.
  • SomeObject is created.
  • InnerStart method begins.
  • InnerStart method starts an asynchronous operation and uses await to suspend its progress.
  • This causes that control returns to Start method.
  • Start method cleanups resources.
  • When the asynchronous operation is finished InnerStart method continues processing. It tries to use resources, that have been already disposed, what leads to an exception.
It is also not recommended to have async void methods (except event handlers). If an async method doesn't return a task it cannot be awaited. It is also easier to handle exceptions if an async method returns a task. For details see also this article.

To fix a problem BaseAlgorithm must be aware of asynchronous nature of calculations. For example InnerStart method can return a task which will be awaited inside try block. However, it also means that synchronous version of InnerStart method in Algorithm1 will have to be changed. It may not be acceptable. Generally, providing asynchronous wrappers for synchronous methods is debatable and should be carefully considered.

In this case, I'll consider to have separated implementations of Template method pattern for synchronous and asynchronous algorithms.

12/07/2015

Interview Questions for Programmers by MK #4

Home

Question #4
You have to implement a very fast, time critical, network communication between nodes of a distributed system. You decided to use good old sockets. However, you haven't decided yet whether to use TCP or UDP protocol. Which one would you choose and why?

Answer #4
If a speed is the only one important factor, I'd choose UDP. UDP is faster than TCP because it has a smaller overhead. In comparison to TCP it is a connection-less, unreliable protocol that doesn't provide features like retransmission, acknowledgment or ordering of messages.

However, it also means that usage of UDP might be more difficult and will require additional coding in some cases. For example, if we have to assure that sent messages have been delivered. In this case, I'd certainly use TCP.

Finally, there is one more thing in favor of UDP. It provides broadcasting and multicasting. So, if it is required I'd also use UDP instead of TCP.

What every blogger should do if using someone else's code #3

Home

Recently, I've written a post about integration with Dropbox. This one is also about integration but this time with Skydrive. I spent some time on investigating how to implement this feature in a desktop application. I was even considering to write what I need from the scratch on my own.

Fortunately, it turned out that someone did it for me. I found a nice piece of code prepared by Microsoft. It includes sample applications showing how to do everything step by step. You can download it from github.

06/07/2015

A practical example of using TaskCompletionSource<T>

Home

Recently I've found a question about real life scenarios for using rather unknown TaskCompletionSource<T> class. I started thinking where I would use it and very quickly I found a good practical example.

I have a pet project LanguageTrainer that helps me in learning words in foreign languages. Some time ago I added Dropbox support to it. It allows me to export/import list of words to/from Dropbox. I developed it in synchronous way. Now I prefer an asynchronous approach and I want to take advantages of async/await keywords.

The problem is that DropNet library, that makes communication with Dropbox easy, doesn't use async/await. It has asynchronous API but it is callback based. The really easy solution here is to use TaskCompletionSource<T>. Here is an example (simplified). Let's start with the original code that downloads a given file from Dropbox.
public void ProcessFile(string key, string secret, string path)
{
   var client = new DropNetClient(key, secret);
   // ...
   var bytes = client.GetFile(path)
   //Process bytes
}
The version that uses DropNet asynchronous API looks in the following way:
public void ProcessFileAsync(string key, string secret, string path)
{
   var client = new DropNetClient(key, secret);
   //...
   client.GetFileAsync(path, 
      response => 
      {
         var bytes = response.RawBytes;
         //Process bytes
      }, 
      ex => 
      {
         //Handle exception
      });
}
And finally the asynchronous version with async/await looks in the following way:
public async Task<Stream> ProcessFileAsync(string key, string secret, string path)
{
   var client = new DropNetClient(key, secret);
   //...
   var tcs = new TaskCompletionSource<Stream>();
   client.GetFileAsync(path, response => tcs.SetResult(new MemoryStream(response.RawBytes)), tcs.SetException);
   return tcs.Task;
}
...
var bytes = await ProcessFileAsync(key, secret, path);
//Process bytes
The method ProcessFileAsync is marked as async and returns a task so it can be awaited. Easy. isn't it? A few lines of code and you can use async/await with other types of asynchronous APIs.

15/06/2015

Interview Questions for Programmers by MK #3

Home

Question #3
You found the following code and were asked to refactor it if needed:
var sb = new StringBuilder();
sb.AppendLine("<root>")
sb.AppendLine(String.Format("   <node id="{0}"/>", 1));
sb.AppendLine(String.Format("   <node id="{0}"/>", 2));
sb.AppendLine(String.Format("   <node id="{0}"/>", 3));
//Many, many lines of code
sb.AppendLine("</root>");
What would you do and why?

Answer #3
It is not the best idea to create XML documents using string concatenation because it is error prone. Besides created documents are not validated in any way. In .NET we have a few possibilities to refactor this code.

I recommend to use XmlWriter in this case because we want to create a new document and we do not want to edit an existing one. However, if we also want to modify existing XML documents, the good choice will be XDocument or XmlDocument class.

In the case of small XML documents (when performance is not critical) it might be a good idea to use XDocument or XmlDocument even if we don't want to edit existing documents. Especially XDocument can be simpler in use than XmlWriter.

Comments #3
I remember that when I wanted to create an XML document in C# for the first time I did it by using string concatenation. The code worked ok and I was surprised that it didn't pass a review :)

01/06/2015

Ray Tracing a Black Hole in C#

Home

A friend of mine Mikołaj Barwicki has published very interesting article about visualisation of black holes on codeproject. So far he received a grade 5 from 43 readers. It is a great result! If you interested in ray tracing, black holes, numerical analysis or parallel computing it is an article for you.


21/05/2015

What every blogger should do if using someone else's code #2

Home

This time I'd like to write about WPFLocalizationExtension library which makes localization of WPF applications easy. I've been using it for 4 years in my projects and it simply works. To be honest I've just realized that the version I'm using is considerably outdated. However, for all this time I haven't encountered problems that would make me to download a newer version of WPFLocalizationExtension.

I think that it is a quite good recommendation. So, if you work with WPF and you need to localize your application I encourage to give a chance to WPFLocalizationExtension.

06/05/2015

Interview Questions for Programmers by MK #2

Home

I prepared this question a long time ago in order to check knowledge of basic good practices.

Question #2
You have the following method which is responsible for updating a client in a database:
public void UpdateClient(
   int id,
   string name,
   string secondname,
   string surname,
   string salutation,
   int age,
   string sex,
   string country,
   string city,
   string province,
   string address,
   string postalCode,
   string phoneNumber,
   string faxNumber,
   string country2,
   string city2,
   string province2,
   string address2,
   string postalCode2,
   string phoneNumber2,
   string faxNumber2,
   ...)
{
   //...
}
Do you think that this code requires any refactoring? If yes, give your proposition. A database access technology doesn't matter in this question.

Answer #2
The basic problem with this method is that it has so many parameters. It is an error prone, difficult to maintain and use approach. I suggest to change the signature of this method in the following way:
public void UpdateClient(Client client)
{
   //...
}
Where Client is a class that models clients. It can look in the following way:
public class Client
{
   public int Id { get; set; }
   public string Name { get; set; }
   public string Secondname { get; set; }
   public string Surname { get; set; }
   public string Salutation { get; set; }
   public int Age { get; set; }
   public string Sex { get; set; }
   public Address MainAddress{ get; set; }
   public Address AdditionalAdddress { get; set; }
   /* More properties */
}
Address class contains details (country, city..) of addresses.

Comments #2
You may also write much more e.g.:
  • It may be good to introduce enums for properties like 'Sex' which can take values only from the strictly limited range.
  • UpdateClient method should inform a caller about the result of an update operation e.g. by returning a code.
However, the most important thing is to say that UpdateClient method shouldn't have so many parameters. Personally, if I see a code as above I immediately want to reduce the number of parameters. This question seemed and still seems to be very easy, however not all candidates were able to answer it. Maybe it should be more accurate. For example, I should have stressed that a candidate should focus ONLY on available code. What do you think?