Tag: .Net Framework

OutOfMemoryException in online test

I did an online test the other day, and while the code I had put together did work and passed 3 of the 4 testcases, the failing testcase throw an OutOfMemoryException. I was writing the code in Visual Studio 2017 and copying it to the web-based IDE on TestDome. Now, since I don’t know what the testcase did, I can only assume that it added a very large number of int’s to an array, for which I was to find the kth most common integer in the array. This is my code:

public static int KthMostCommon(int[] a, int k) {
    return a.GroupBy(v => v)
        .OrderByDescending(g => g.Count()).ElementAt(k - 1).Key;
}

I only got a 66% score for that task, but it dawned on me, that I should have tried using a byte array instead. Trying it with the following call to the method and obviously changing the method signature to accept a byte array instead of a an int array, worked a charm.

var t = Enumerable.Repeat<byte>(0, 1000000000)
    .Select(i => (byte) randNum.Next(minValue, maxValue)).ToArray();
var x = KthMostCommon(t, 2);

What would you have done, not knowing the number of integers that was in the array?

UPDATE:

I obviously couldn’t have changed the method signature as suggested in the actual test, as that would have caused all unit tests to fail. Another option is to pass the int array and convert to a byte array, and then disposing of the int array before processing the byte array.

var bytes = new byte[a.Length * 4]; 
for (var i = 0; i < a.Length; i++)
     Array.Copy(BitConverter.GetBytes(a[i]), 0, bytes, i * 4, 4);
a = null; 
GC.Collect();

Mind you, it would probably be better changing the processing alltogether… 🙂

Advertisements

.NET Framework Extension Methods

Going over the Design Patterns coined by the Gang of Four (GoF), and working with the Decorator pattern quite a bit recently, I did a comparison of this pattern and the .NET Framework extension methods. So, does an extension method extend a class such as the Decorator pattern advocates? On first looks possibly, but an extension method doesn’t wrap the class being extended, it is a compiler “trick”. I think that extension methods are more akin to the Visitor pattern.

C# Singleton

There are a number of ways to implement the Singleton pattern, and most will work well. This is the easiest implementation I can think of, making use of the various language features and the .NET Framework.

public sealed class Singleton : ICloneable {
    // Ensure lazy loading
    private static readonly Lazy<Singleton> Lazy =
        new Lazy<Singleton>(() => new Singleton());
 
    public static Singleton Instance => Lazy.Value;
 
    private Singleton() { }
 
    // Prevent cloning
    public object Clone() => throw new NotImplementedException();
}

I’m using the Lazy the class for the lazy loading, very easy. The readonly modifier ensures the Instance property cannot be assigned to after the first call to Instance. The private parameterless constrcutor ensures that you cannot create or new up an instance of the Singleton class. Finally, by implementing then ICloneable interface, you can prevent cloning using the MemberwiseClone method of the Object class.

var s = Singleton.Instance;
var s1 = s.Clone();

Console.WriteLine(s.GetHashCode());
Console.WriteLine(s1.GetHashCode());

Now you’ll see one hascode printed in the console, but the second call will throw an exception. You could of course choose not to implement the ICloneable interface, but then it wll be possible to create an extension method, like this:

public static class ObjectExtensionMethods {
    public static T Clone<T>(this T o) {
        var instance = o.GetType().GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance |
            System.Reflection.BindingFlags.NonPublic);
 
        return (T) instance?.Invoke(o, null);
    }
}

However, this will fail if you do implement the ICloneable interface.

The Web Application Project … is configured to use IIS. Unable to access the IIS metabase. You do not have sufficient privilege to access IIS web sites on your machine.

I just moved a Visual Studio solution containing a Web Application project from a Windows 7 based dev box to a Windows 8 based dev box, and in line with recommended security guidelines, I try to avoid running Visual Studio (2012 in this case) as an admin. However, in this case, the solution is to run VS as an administrator. Sigh… I do Wonder though as to why VS would need admin access to IIS. I’m sure there is a plausible explanation, but I just don’t see it.

System.ArgumentNullException: Value cannot be null. Parameter name: principal

I am working on my Dynamic Data website, or rather web application, in VS 2012 RC, and after reading Dynamic Data Unleashed, http://www.amazon.com/ASP-NET-Dynamic-Data-Unleashed-Oleg/dp/0672335654/ref=sr_1_1?ie=UTF8&qid=1342425509&sr=8-1&keywords=dynamic+data, I picked up a few nice tricks, including how to secure your data at the entity level. So, I copied some of the sample code across to my solution, and once everything was building nicely, I started testing the new bits. First access to an entity worked just fine, but any other attempt to access the same entity or any other entity for that resulted in this error:

System.ArgumentNullException: Value cannot be null. Parameter name: principal

Rather annoying, since the sample code worked just fine. It turns out that the methods for checking if the current user is allowed to read a specific entity received a principal that was null. Here is the signature of one of the methods:

public override bool CanRead(IPrincipal principal)

The method is called from another method that checks if a column should be scaffolded/shown to the current user.

private bool IsScaffoldable(MetaColumn column)

This method was calling the CanRead method passing HttpContext.Current.User. This works just fine when you use the ASP.NET Development Server when testing inside Visual Studio. However, if you use IIS Express, it does not work; the error described is consistent. So, I tried the full IIS, but the same thing happened.

It turns out that the issue is with the Integrated pipeline mode, which is new to IIS 7 and later. HttpContext.Current isn’t always available, as you can find more evidence of by Bing’ing it. The solution in my case was to use Thread.CurrentPrincipal instead.

Windows 8 – .NET Framework 3.5 must be installed

I reinstalled Windows 8 on my HP Slate2 today, as I was having some problems with the current installation, which was an upgrade on top of the pre-installed Windows 7. Everything worked just fine, until I needed to install my wireless driver. I managed to install it by downloading from HP’s website, but then I got this message, An app on your PC needs the following Windows feature, referring to the .NET Framework 3.5. However, you simply cannot install this manually, it must be installed by using the Turn Windows features on or off functionality, accessible from the Programs and Features Control Panel applet. If you have an Internet connection, you should be fine at this point, but I wasn’t as I was trying to install the driver for the wireless hardware.

You need to open a Command Prompt in administrator mode, which can be done by opening Windows Explorer, browse to Windows\System32, locate cmd.exe, “right-click” or rather press and hold down your finger on cmd.exe, and then click Run as administrator. In the Command Prompt window you can run the following command: Dism /online /enable-feature /featurename:netfx3 /all /source:D:\sources\sxs /LimitAccess

Package ‘Microsoft SQL Management Studio Package’ failed to load

I started getting this error message when opening Microsoft SQL Management Studio 2008 R2, right after installing some application and updates to Visual Studio 2010, by using the Web Platform Installer. It was fairly simple to fix though, because after running a repair of the .NET Framework 4 Client Profile and rebooting the machine, things were back to normal.

Visual Basic Bashing

I am a former Microsoft Visual Basic MVP (7 years running) and I love VB. Now, I also do a lot of work in C# and I like to think that I do both programming languages equally well. However, I much prefer VB over C#, and I really dislike some of these morons who have nothing better to do than bash VB with incredibly stupid remarks, such as “VB is a toy language”, “When is Microsoft going to get rid of VB?” In particular the last phrase annoys me. If you don’t like a programming language, fine stick with whatever language you know (if any), but stop spoiling other developer’s joy of using a particular language. I wonder if that particular individual knows that the number of Microsoft supplied .NET based languages are increasing with the release of the .NET Framework 4 and Visual Studio 2010? Actually, I don’t wonder as I’m sure the individual didn’t have that in mind. Sigh…