Tag: C#

Visual Studio 2017 Editor new line wrapping

We all have our favourite settings when it comes to setting up Visual Studio, and the editor is quite often set up differently for a group of developers working together. I like having the opening brace ({) on the same line as the class, struct or whatever the brace signals the beginning of.

I like this:

class {

as compared to this:

class {

I frequently use the key combination Ctrl+K, Ctrl+D to format my document after having typed some code. I dislike it, if the formatting is not to my liking. It should therefore not come as a surprise, if I tell you that while working on a new UWP app, in which I had copied across some code from a Template10 project template, the key combo seemingly didn’t work anymore. After some investigation, including opening an existing Console app, in which the key combo did work, I took a look at this code:

namespace Template10.Views
{
    public sealed partial class SettingsPage : Page
    {
        readonly Template10.Services.SerializationService.ISerializationService _serializationService;
 
        public SettingsPage()
        {
            InitializeComponent();
            NavigationCacheMode = NavigationCacheMode.Required;
            _serializationService = Template10.Services.SerializationService.SerializationService.Json;
        }
 
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var index = int.Parse(_serializationService.Deserialize(e.Parameter?.ToString()).ToString());
            MyPivot.SelectedIndex = index;
        }
    }
}

Because of the Page class, from which the class shown, SettingsPage, is derived has a notification stating “Base type ‘Page’ is already specified in other parts”, the class/type name Page is greyed out. This effectively blocks for the document formatting placing the opening brace { on the same line as the class declaration. If I remove : Page, and press the key combination Ctrl+K, Ctrl+D, this is what I get.

namespace Template10.Views {
    public sealed partial class SettingsPage {
        readonly Template10.Services.SerializationService.ISerializationService _serializationService;
 
        public SettingsPage() {
            InitializeComponent();
            NavigationCacheMode = NavigationCacheMode.Required;
            _serializationService = Template10.Services.SerializationService.SerializationService.Json;
        }
 
        protected override void OnNavigatedTo(NavigationEventArgs e) {
            var index = int.Parse(_serializationService.Deserialize(e.Parameter?.ToString()).ToString());
            MyPivot.SelectedIndex = index;
        }
    }
}

 

Advertisements

C# Comments

This is another of my pet peeves when looking at other people’s code. If you add a comment, using the double forward-slash //, then add a freaking space after // to make it stand out from code that has been commented out. It pisses me off right, left and center to see this:

//TODO blah, blah

…or this:

//Here is where you add...

Why not just do this, so flipping simple:

// TODO:

This will avoid any potential mistake when glancing over the code, where the code below has is clearly commented out code, and the first examples above are not:

//var numDays = int.Parse(Console.ReadLine());
//var numPeople = 5;
//var numPeopleShared = 0;

Do feel free to share your opinion and experience on the same.

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… 🙂

Is a string an Anagram of another string?

How do you check if a word is an Anagram of another word? It’s reasonably simple, although I’m sure this can be simplified.

bool IsAnagram(string s1, string s2) {
    if (s1.Length != s2.Length) return false;
 
    var s1C = s1.ToCharArray();
    var s2C = s2.ToCharArray();
    Array.Sort(s1C);
    Array.Sort(s2C);
 
    return s1C.Equals(s2C);
}

Is a string a Palindrome?

A string is a palindrome if it reads the same, forwards and backwards, but how can you check in C#? There are at least hundreds of possible solutions for how to achieve this, but I think this is an easy one.

var originalString = "jjkjhkjhkj";
var reverseString = new string(s.Reverse().ToArray());
// Check for existing palindrome
if (s == reverseString)
    ...

Is a string a Pangram?

When is a string a pangram? Is actually fairly easy to check and beow you can see one implementation in C#.

var charsFound = new bool[26];
var s = Console.ReadLine().ToUpper();
 
// We need at least 26 characters (English alphabet) in the string...
if (s.Length >= 26) {
    
 
    foreach (var c in s)
        if (c >= 'A' && c <= 'Z') {
            // Uppercase ascii character codes starts at decimal index 65
            var index = c - 65;
            // Already marked, continue loop...
            if (charsFound[index]) continue;
 
            charsFound[index] = true;
        }
}
 
// Did we find all 26 chars?
Console.WriteLine(charsFound.Where(c => c).Count() == 26 ? "pangram" : "not pangram");

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.

Dynamic Data – First text field focus

The Insert page template that is created for you when you create a new ASP.NET Dynamic Data Entities Web Application project, does not set focus to the first field in the template. By adding the following code (which can be simplified I’m sure) to the partial Insert class, you can achieve just that:

protected void Page_LoadComplete(object sender, EventArgs e)
{
    Text_EditField usrCtl = Utility.FindControl(FormView1.Controls);

    TextBox txtBox = (TextBox) usrCtl.FindControl("TextBox1");

    if (txtBox != null && !txtBox.ReadOnly)
        txtBox.Focus();
}

The static generic FindControl method was found here, http://erikporter.com/Blog/asp-net-findcontrol-recursive-with-generics.

ASP.NET Page base class differences in VB and C#

When you use a base class for your pages in VB and C# there are some subtle differences, if your base class implements event handlers for one or more of the Page events, such as Page_Load. In VB, you can simply use the Handles keyword, like this:

Public Class BasePage
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    End Sub
End Class

This way, the Page_Load event will be called in the base class, and the page class derived from it (if the Page_Load event handler is implemented ;-). However, in C# there is no Handles keyword, and adding the AutoEventWireUp to the markup file like this, does not work with a base class:

<%@ Page Language="C#" ... AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %> 

This will only wire up the Page events implemented in the Default class. One way to fix this is to override the OnLoad event in the base class, like this:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    ...

}

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…