Updated Span API : NonPortableCast and AsReadOnlySpan to MemoryMarshal.Cast and AsSpan

One of the interesting changes (not sure why Microsoft changed this) was moving/changing the Span<T> API’s a bit. For example, the Span<T>.NonPortableCast Method was moved as an extension method under MemoryMarshal.

Previous API

Span<byte> byteSpan = BitConverter.GetBytes(originalPrimitiveType);
Span<int> intSpan = byteSpan.NonPortableCast<byte, int>();

Current API

Span<byte> byteSpan = BitConverter.GetBytes(originalPrimitiveType);
Span<int> intSpan = MemoryMarshal.Cast<byte, int>(byteSpan);

Similarly, the string.AsReadonlySpan method has been renamed. The new API is as follows.

Previous API

ReadOnlySpan<char> keyString = "SomeText".AsReadOnlySpan();

Current API

ReadOnlySpan<char> keyString = "SomeText".AsSpan();

The MemoryMarshal extensions can be found under the System.Runtime.InteropServices namespace. Code discussed in my earlier post about Benchmarking Span has been updated in my Github.

The new String Interpolation and Ternary Operator

A quick tip for the new C# string interpolation. The new string interpolation has made things more simpler and readable. One might be tempted to include ternary operators within string interpolation.

However if you attempt something like following, the compiler would throw an error

Console.WriteLine($"{1==1?"Msg1":"Msg2"}");

The fix is as simple as it can get. Just include a brace within your ternary statement.

Console.WriteLine($"{(1==1?"Msg1":"Msg2")}");

That’s it. Brace up for a week with lot of fun and coding.

Deconstruct and Extension Methods

In an earlier post, we explored the Deconstruct feature for Non-Tuples. It was a pretty useful feature that came along in the 7.x series . If one does have access to source, adding deconstruct is quite easy. But what about classes we do not have (source code) access to ? For example, the .Net framework classes ? Can we add a deconstruct to it ? It turns out, it is quite simple as well. Extension Methods allows us to add deconstruct to existing classes without breaking the Open Closed Principle.

For demonstration purpose, let us write a deconstruct for Point Class under the System.Drawing namespace.

public static class ExtensionMethods
{
    public static void Deconstruct(this Point source,out double x,out double y)
    {
        x = source.X;
        y = source.Y;
    }
}

void Main()
{
       Point point = new Point(100,500);
       var (x,y) = point;
       Console.WriteLine($"Point.X={x},Point.Y={y}");
}

As observed, it is quite easy to add deconstruct to your existing classes using the Extension Methods.

Lock for Async Methods

Despite the intended nature, we seldom might come across situation where we would want to place a lock around an async statement and make it behave differently, especially when accessed from different threads. Let’s try to mock the scenario first to demonstrate the issue.

The lock-async Problem

Consider the following code snippet.

void Main()
{
     Parallel.For(0,5,async (x,y)=>{await TestMethod();});
}

async Task<bool> TestMethod()
{
Console.WriteLine("In");
// Do some tasks here. For demonstration purpose we will use Task.Delay to mock a long running task.
await Task.Delay(2000);
Console.WriteLine("Out");
return await Task.FromResult(true);
}

The output of the above code would be as following, understandably allowing multiple threads to access the ‘intended long running process code‘.

In
In
In
In
In
Out
Out
Out
Out
Out

The most common workaround is placing a lock statement around the code. Try placing a lock around the await statement and you would surprised to know you are not allowed to do so.

“Cannot await in the body of a lock statement”

This is where the trouble starts.

The Solution

The workaround for the issue with Semaphore. Instead of lock, you could use a semaphore to ensure only one/limited threads access the async method at a time.

Let us rewrite the code with semaphore now.

void Main()
{
       Parallel.For(0,5,async (x,y)=>{await TestMethod();});
}
static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1,1);
async Task<bool> TestMethod()
{
await semaphoreSlim.WaitAsync();
try
{
Console.WriteLine("In");
await Task.Delay(2000);
Console.WriteLine("Out");
}
finally
{
semaphoreSlim.Release();
}
return await Task.FromResult(true);
}

As you can observe, the compile would accept this solution as desired. The output of following can seen below.

In
Out
In
Out
In
Out
In
Out
In
Out

Enjoy coding

IEnumerable.Shuffle Implementation

Following code is an implementation of Shuffle method on IEnumerable based on the Durstenfeld modification of Fisher Yates Shuffle algorithm, a simple and efficient method.

public static IEnumerable<TSource> Shuffle<TSource>(this IEnumerable<TSource> dataArray)
{
    var dataArrayList = dataArray.ToList();
    var returnValue = Enumerable.Empty<TSource>();
    for (int index = dataArrayList.Count()-1; index > 0; index--)
    {
        var randomKey = _randomGenerator.Next(1, index);
        var temp = dataArrayList[randomKey];
        dataArrayList[randomKey] = dataArrayList[dataArray.Count() - 1];
        dataArrayList[dataArray.Count() - 1] = temp;
    }
    return dataArrayList;
}

More information on the algorithm can be found in Wiki.

The complete code can be found in Github

VS Extension & HttpClient : FileNotFoundException

Recently I was working on a Visual Studio Extension which required HttpClient when I ran into the following exception. Frustratingly enough, I wasn’t able to resolve it myself, despite playing around with the versions and using Binding Redirect.

System.IO.FileNotFoundException: ‘Could not load file or assembly ‘System.Net.Http,Version=4.2.0.0, Culture=neutral, ….. The system cannot find the file specified.

The Binding Redirect didn’t quite as it is not possible to use the redirects in VS Extensions. However, the solution turned out to be choosing an alternative for HttpClient as pointed in SOF.

Instead of HttpClient, I had to depend on something which is more native to.Net, like HttpWebRequest. Hope this post is useful to anyone who stumbles on similar issues.

Linq Recipes : IsIncreasing/IsDecreasing & IsAlternating

LINQ, ever since its introduction has turned out to be one of the favorite tools for .Net Developers. The post focus on couple of quick recipes for common scenarios.

Scenario 001
You have a collection of objects and you would like verify if the collection is sorted in increasing/decreasing order.

Recipe

We could always sort the collection and compare with the original version, however, if you really want to stick to a LINQ based solution, following extension methods is one approach.

public static bool IsIncreasing<TSource>(this IEnumerable<TSource> data) 
{ 
   return data.Zip(data.Skip(1),(first, second) => Comparer.Default.Compare(first,second) < 0).All(b => b);
}


public static bool IsDecreasing<TSource>(this IEnumerable<TSource> data)
{
   return data.Zip(data.Skip(1),(first, second) => Comparer.Default.Compare(first,second) > 0).All(b => b);
}

Demo

void Main()
{
       var itemSet1 = new[] {1,3,4,5,6};
       var itemSet2 = new[] {5,4,3,2,1};
       Console.WriteLine($"Is {nameof(itemSet1)} increasing ? {itemSet1.IsIncreasing()}" );
       Console.WriteLine($"Is {nameof(itemSet1)} decreasing ? {itemSet1.IsDecreasing()}" );
       Console.WriteLine($"Is {nameof(itemSet2)} increasing ? {itemSet1.IsIncreasing()}" );
       Console.WriteLine($"Is {nameof(itemSet2)} decreasing ? {itemSet1.IsDecreasing()}" );
}

Output

Is itemSet1 increasing ? True
Is itemSet1 decreasing ? False
Is itemSet2 increasing ? True
Is itemSet2 decreasing ? False

Scenario 002:

Consider you have a Collection ‘A’. You want to ensure that each element in the series vary in an alternating way, that is, for each element in A, A[i] < A[i+1] > A[i+2] or A[i] > A[i+1] < A[+2]. For example, for the collection {1,3,2,4,3,5} follows the pattern.

Recipe
Once again we will write the solution as an extension method. Well, that’s easier to ‘reuse’ right.

public static bool IsAlternating<TSource>(this IEnumerable<TSource> dataList)
{
       return VerifyIfAlternating(dataList.ToList(),true) || VerifyIfAlternating(dataList.ToList(),false);
}

private static bool VerifyIfAlternating<TSource>(IList<TSource> data,bool toggle)
{
return data.Zip(data.Skip(1), (first, second) =>
                                            {
                                                toggle = !toggle;
                                                return Comparer.Default.Compare(first,second) > 0 == toggle;
                                            })
                                            .All(b=>b);
                                                              
}

Demo

void Main()
{
       var itemSet3 = new[] {1,4,1,4,1};
       var itemSet4 = new[] {2,4,3,2,1};

       Console.WriteLine($"Is {nameof(itemSet3)} alternating ? {itemSet3.IsAlternating()}" );
       Console.WriteLine($"Is {nameof(itemSet4)} alternating ? {itemSet4.IsAlternating()}" );

}

Output

Is itemSet3 alternating ? True
Is itemSet4 alternating ? False

That’s it for now. This is one series I would like to continue.