Tuesday 26 January 2016

Write Right!: Creative Writing Using Storytelling Techniques, by Kendall Haven

Book cover Write Right! is a monster. It goes through every step of writing a book, including the one that the author, Kendal Haven, considers the most important: editing. Then, in its second half, it contains exercises for improving writing. The intended audience of this book is teachers of creative writing, not just beginner writers, so that makes it even more valuable.

The mystery for me was how can someone write about captivating and engaging writing in a book as dry as Creative Writing Using Storytelling Techniques. I understand it is mostly a manual, but it was really difficult to go through it, as it was full of information start to finish. Now I must reread it at speed and make a summary of the techniques in order to even begin to absorb the huge amount of very useful information in the work. Not to mention actually doing the exercises at the end.

What I really liked about this book is that it is very algorithmic. At every page I was considering - and still am - how I might codify this into a software to help me evaluate a piece of literature and maybe even suggest improvements automatically. If I am to extract an essential idea of the work it would be "editing is very important". The author acknowledges the need to write fast, from your gut, to lay the words out there, not even considering spelling or grammar, just vomit your thoughts onto the page, but then he submits that the process of evaluating each scene, each chapter and the book for structure, wording, verb uses, sense involvement, specificity of language, action, dialogue, sequels (not book sequels, but that thing that details what characters think and feel about what just happened), etc. is perhaps the most important in translating that story that you have into an interesting book to read. And after getting a final version you are happy about, he makes you eliminate 15% of the words. Ruthless! :)

Let me make this clear, though: writing is damn tough. It consists of two parts: observing the world and describing the world. In a recent post I was complaining at how bad I am at the former, but this book makes it clear how complex is the latter. Making the written word express what is in your brain at the moment of creation is extremely difficult and complicated. This book helps in defining exactly what that is and give you tools to do it and improve on doing it. A great tool!

To sum it up: This is not light reading. It is a manual for writing teachers (what the hell are those? I wish I had some in school). It helps tremendously if you are self-taught, also. It requires multiple readings or at least a summarizing effort at the end, to structure it in a way that makes it easy using it as a reference. And then, of course, are the exercises for improving writing which take the second half of the book

Thursday 21 January 2016

Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4, by Stephen Toub

Patterns of Parallel Programming Stephen Toub wrote this document, as he calls it, but that is so full of useful information that it can be considered a reference book. A 118 pages PDF, Patterns for Parallel Programming taught me a lot of things about .NET parallel programming (although most of them I should have known already :-().

Toub is a program manager lead on the Parallel Computing Platform team at Microsoft, the smart people that gave us Task<T>, Parallel, but also await/async. The team was formed in 2006 and it had the responsibility of helping Microsoft get ready for the shift to multicore and many-core. They had broad responsibility around the company but were centered in the Developer Division because they believed the impact of this fundamental shift in how programming is done was mostly going to be on software developers.

It is important to understand that this document was last updated in 2010 and still some of the stuff there was new to me. However, some of the concepts detailed in there are timeless, like what is important to share and distribute in a parallel programming scenario. The end of the document is filled with advanced code that I would have trouble understanding even after reading this, that is why I believe you should keep this PDF somewhere close, in order to reread relevant parts when doing parallel programming. The document is free to download from Microsoft and I highly recommend it to all .NET developers out there.

Date Published: 7/16/2010 File Size: 1.5 MB

Tuesday 19 January 2016

SpaceX first stage landings on a sea barge: Three failures should be a strong indicator of a design flaw

Falcon 9 first stage explodes on barge In January 2016 SpaceX made history by landing the first stage of a rocket that they have just launched. I know, Blue Origin did it first, but SpaceX rockets are designed for GEO orbits, while Bezos' reusable rocket is for LEO, so different animals. However, they have tried doing the same three times, last time just yesterday, only landing on a special barge at sea. Each time this have failed. But let's watch the three attempts, see what's going on.

First time, a year ago, January 2015, you can see that something was wrong with the way the stage came down, it was already angled and the horizontal speeds were really high.


Second time, three months later in April 2015, it almost got it right:


Third time, yesterday, 18 December 2016, it actually landed, then a landing leg gave out:


But what happened? Each time the stage reached the landing spot, each time in a vertical position and with low vertical speeds. Every time the engine exploded it did when the stage tried to stop and fell over. Wouldn't a specialized grabbing mechanism have prevented some of these accidents? Maybe even the first one!

Now, I understand that the purpose of SpaceX is to have a first stage that can land anywhere, and so they must rely on their device only, assuming nothing of the landing site, but once they go through the engineering issues, just catch it in a net, intersect three metal cables to support the upper part of the stage, do something. Look of those things, slowly falling down: you want to jump and catch them, like you would a drunken friend. Make your rocket understand it's not alone, Elon, that it's got our support! :)

Seriously now, I can't even imagine what would happen if the wind started blowing harder while the rocket tried to land on the barge. Since you have a specialized landing vehicle, make it better. The rocketry is fine, it is time to work on the support infrastructure with just as much aplomb and creativity.

Monday 18 January 2016

3 and 9 Feb, Bucharest: ReactiveX in .NET

Rx for .Net On the 3rd and 9th of February I will be presenting a demo of Reactive Extension in action on a Windows Presentation Foundation app that I am going to be building as I speak, first without and then with Rx. The presentation should be about 30-45 minutes, in Romanian, but I am sure we can accommodate foreign speakers by doing it in English if you request it. These events are all free, but you must register in order to know how many people to prepare for. Here are the Meetup links:
ReactiveX in Action, Wednesday, February 3 2016, 19:00, Impact Hub, Strada Halelor 5, Bucharest
MsSql / Reactive Extensions, Tuesday, February 9 2016, 19:00, Electronic Arts - Afi Park 2, Bulevardul General Vasile Milea 4F, București 061344
See you there!

Facebook won! I created an account...

So I've finally created a Facebook account. Yes, it won. I also accessed the Twitter one I created a few good years before and never used. These new social accounts will probably be used to publish what I post here, but anyway, I've updated the blog layout with my Facebook and Twitter accounts (see the icons top right).

Wednesday 13 January 2016

Apologies for people from domains like co.uk or co.in, etc.

It seems that for a very long time, since Blogger implemented the ugly system that changes the blog domain to a local domain, my blog was inaccessible for people in the UK and other places where the domain country had more segments, like co.in, co.uk, com.au, etc. due to a bug in my solution for it. I need to apologize for that. I fixed the problem now, but damn it is a long standing bug, a full three years.

Saturday 9 January 2016

You can use C# version 6 features right now, and how glorious they are!

Some of you may have heard of C# 6, the new version of the Microsoft .NET programming language, but what I am not certain about is that you know you can use it right now. I had expected that a new version of the language will be usable from the brand new upcoming fifth version of the .NET runtime, but actually no, you can use it right now in your projects, because the new features have been implemented in the compiler, in Visual Studio and, you have no idea how cool it is until you try, in ReSharper.

One might say: "Hell, I've seen these syntactic sugar thingies before, they are nothing but a layer over existing functionality. New version, my ass, I stick with what I know!", but you run the risk of doing as one of my junior developer colleagues did once, all red faced and angry, accusing me that I have replaced their code with question marks. I had used the null-coalescing operator to replace five line blocks like if (something == null) { ....

Let me give you some examples of these cool features, features that I have discovered not by assiduously learning them from Microsoft release documents, by but installing ReSharper - only the coolest software ever - who recommends me the changes in existing code. Let's see what it does.

Example 1: properties with getters and no setters

Classic example:
public int Count {
get {
return _innerList.Count;
}
}

Same thing using C# 6 features?
public int Count => _innerList.Count;
Cool or what?

Example 2: null checking in a property chain

Classic example:
if (Granddaddy!=null) {
if (Daddy!=null) {
if (Child!=null) {
return Grandaddy.Daddy.Child.SomeStupidProperty;
}
}
}

Same thing using C# 6 features?
return Grandaddy?.Daddy?.Child?.SomeStupidProperty;
Convinced yet?

Example 3: using the name of members as strings

Classic example:
public int Number {
get { return _number; }
set {
if (_number!=value) {
_number=value;
OnPropertyChanged("Number");
//with some custom code you could have used a better, but slower version:
//OnPropertyChanged(()=>Number);
}
}
}

C# 6 version?
public int Number {
get { return _number; }
set {
if (_number!=value) {
_number=value;
OnPropertyChanged(nameof(Number));
// this assumes that we have a base class with a method called OnPropertyChaged, but we can already to things inline:
PropertyChanged?.Invoke(this,new new PropertyChangedEventArgs(nameof(Number))
}
}
}

Example 4: overriding or implementing simple methods

Classic example:
public override string ToString() { 
return string.Format("{0}, {1}", First, Second);
}

Now:
public override string ToString() => $"{First}, {Second}";

Example 5: exception filters

Classic example:
try {
SomethingUnpredictable();
}
catch (Exception e) {
if (e.InnerException!=null) {
UnpackAndLogException(e);
} else {
throw;
}
}

C# 6 version:
try {
SomethingUnpredictable();
}
catch (Exception e) when (e.InnerException!=null) {
UnpackAndLogException(e);
}

Example 6: using static

I don't particularly like this, but it can simplify some code when used right. Classic example:
return degrees*Math.PI/180;

C# 6 way:
//somewhere above:
using static System.Math;

return degrees*PI/180;

There are other more complex features as well, like special index initializers for Dictionary objects, await in catch and finally blocks, Auto-property initializers and Primary Constructors for structs. You can use all these features in any .NET version 4 and above. All you need is the new Roslyn compiler.

Enjoy the new features. I know I will!

Friday 8 January 2016

BindingList vs ObservableCollection

There are a lot of people asking around what is the difference between BindingList<T> and ObservableCollection<T> and therefore, there are a lot of answers. I am writing this entry so that next time I look it up, I save StackOverflow some bandwidth. Also, because my blog is cooler :)

So, the first difference between BindingList and ObservableCollection is that BindingList implements cascading notifications of change. If any of the items in the list implements INotifyPropertyChanged, it will accept any change from those items and expose it as a list changed event, including the index of the item that initiated the change. ObservableCollection does not do that. So BindingList is better, right?

Wrong. BindingList is not "properly supported" by WPF, say some. Why is that? Well, because BindingList, as its MSDN page says, is just "an alternative to implementing the complete IBindingList interface". Yes, you've got it. BindingList is a lazy, thin, ineffective implementation of the interface. The Missing Docs blog has a very good explanation of this. Do keep in mind that BindingList was created during the time of Windows Forms and is being used by WPF only as an afterthought.

So let's use ObservableCollection then! No. The functionalities implemented by BindingList are far superior to that of ObservableCollection. Just thinking that you must somehow handle changes of every object in the list is killing the idea.

A subtle recommendation on the same MSDN page goes like this: "the typical solutions programmer will use a class that provides data binding functionality, such as BindingSource, instead of directly using BindingList". Well, what does that mean? It means using System.Windows.Forms.BindingSource, which does about everything, since it implements IBindingListView, IBindingList, IList, ICollection, IEnumerable, ITypedList, ICancelAddNew, ISupportInitializeNotification, ISupportInitialize, ICurrencyManagerProvider and is also a subclass of Component. A bit heavy, though, isn't it?

An interesting idea comes from a StackOverflow user: implement IBindingList on a subclass of ObservableCollection<T>. Should be enough to implement a scalable version of IBindingList.

There is more. The BindingListCollectionView page says "Specifically, IBindingList is required for BindingListCollectionView, and IBindingListView is an optional interface that gives additional sorting and filtering support.", which indicates that IBindingListView is also useful when getting a collection view for your object.

To recap: the best solution seems to be an ObservableCollection<T> that also implements IBindingListView (which itself implements IBindingList). The implementation must be scalable (getting the index of an object that causes a change in an efficient manner), though and I wonder, if I am implementing IBindingList, why should I even bother with inheriting from ObservableCollection? The same StackOverflow user seems interested only in the INotifyCollectionChanged interface for the ObservableCollection which is also implemented by IBindingListView!

Therefore, let's implement a class that explicitly implements IBindingListView and IList<T>, then publish the members we actually use! What could possibly go wrong? My idea is to store the index of an item next to the item, therefore removing the need to search for it. It seems that I must first implement an advanced List<T>, with a fast and efficient IndexOf method, then I can basically just copy paste the BindingList code and use this class of mine as the base. Unfortunately, BindingList uses Collection<T> as the base class, which itself implements IList<T>, IList, IReadOnlyList<T>. It seems I will have to implement all.

Immediately I have hit a snag. IBindingView is very difficult to implement, since it tries to filter using a string that is interpreted as a sort of DSL, so I would use a lot of reflection and weird conditions. Sorting is not much better. This is an interface invented when .NET did not support Predicates and lambda expressions, which would make sorting and filtering trivial and the subject of another post. So I go back to implementing a scalable BindingList, and just implement INotifyCollectionChanged over it.

For an implementation of IBindingView, check this out: BindingListView

Code time.

I've decided to implement the IndexOf caching as a dictionary with the objects as keys. The values are lists of integers representing all indexes of that value or object. Frankly I never realized that IndexOf for lists was not taking a start parameter, so it only returns the first occurrence of an item in the list.

There are three classes: AdvancedCollection is a fast IndexOf implementation of Collection. AdvancedBindingList is the copy pasted code of BindingList, with the base class changed from Collection to AdvancedCollection and with INotifyCollectionChanged implemented over it. SecurityUtils is only needed for the AddNew method of IBindingList and is again copy pasted from the Microsoft code. Enjoy!

Click to collapse/expand
internal static class SecurityUtils
{
private static volatile ReflectionPermission _memberAccessPermission;
private static volatile ReflectionPermission _restrictedMemberAccessPermission;

private static ReflectionPermission memberAccessPermission =>
_memberAccessPermission ??
(_memberAccessPermission = new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));

private static ReflectionPermission restrictedMemberAccessPermission =>
_restrictedMemberAccessPermission ??
(_restrictedMemberAccessPermission =
new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess));

private static void demandReflectionAccess(Type type)
{
try
{
memberAccessPermission.Demand();
}
catch (SecurityException)
{
demandGrantSet(type.Assembly);
}
}

[SecuritySafeCritical]
private static void demandGrantSet(Assembly assembly)
{
var permissionSet = assembly.PermissionSet;
var accessPermission = restrictedMemberAccessPermission;
permissionSet.AddPermission(accessPermission);
permissionSet.Demand();
}

private static bool hasReflectionPermission(Type type)
{
try
{
demandReflectionAccess(type);
return true;
}
catch (SecurityException)
{
}
return false;
}

internal static object SecureCreateInstance(Type type)
{
return SecureCreateInstance(type, null, false);
}

internal static object SecureCreateInstance(Type type, object[] args, bool allowNonPublic)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
var bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance;
if (!type.IsVisible)
demandReflectionAccess(type);
else if (allowNonPublic && !hasReflectionPermission(type))
allowNonPublic = false;
if (allowNonPublic)
bindingAttr |= BindingFlags.NonPublic;
return Activator.CreateInstance(type, bindingAttr, null, args, null);
}

internal static object SecureCreateInstance(Type type, object[] args)
{
return SecureCreateInstance(type, args, false);
}

internal static object SecureConstructorInvoke(Type type, Type[] argTypes, object[] args, bool allowNonPublic)
{
return SecureConstructorInvoke(type, argTypes, args, allowNonPublic, BindingFlags.Default);
}

internal static object SecureConstructorInvoke(Type type, Type[] argTypes, object[] args, bool allowNonPublic,
BindingFlags extraFlags)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (!type.IsVisible)
demandReflectionAccess(type);
else if (allowNonPublic && !hasReflectionPermission(type))
allowNonPublic = false;
var bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | extraFlags;
if (!allowNonPublic)
bindingAttr &= ~BindingFlags.NonPublic;
var constructor = type.GetConstructor(bindingAttr, null, argTypes, null);
return constructor?.Invoke(args);
}

private static bool genericArgumentsAreVisible(MethodInfo method)
{
return !method.IsGenericMethod || method.GetGenericArguments().All(type => type.IsVisible);
}

internal static object FieldInfoGetValue(FieldInfo field, object target)
{
var declaringType = field.DeclaringType;
if (declaringType == null)
{
if (!field.IsPublic)
demandGrantSet(field.Module.Assembly);
}
else if (!declaringType.IsVisible || !field.IsPublic)
demandReflectionAccess(declaringType);
return field.GetValue(target);
}

internal static object MethodInfoInvoke(MethodInfo method, object target, object[] args)
{
var declaringType = method.DeclaringType;
if (declaringType == null)
{
if (!method.IsPublic || !genericArgumentsAreVisible(method))
demandGrantSet(method.Module.Assembly);
}
else if (!declaringType.IsVisible || !method.IsPublic || !genericArgumentsAreVisible(method))
demandReflectionAccess(declaringType);
return method.Invoke(target, args);
}

internal static object ConstructorInfoInvoke(ConstructorInfo ctor, object[] args)
{
var declaringType = ctor.DeclaringType;
if (declaringType != null && (!declaringType.IsVisible || !ctor.IsPublic))
demandReflectionAccess(declaringType);
return ctor.Invoke(args);
}

internal static object ArrayCreateInstance(Type type, int length)
{
if (!type.IsVisible)
demandReflectionAccess(type);
return Array.CreateInstance(type, length);
}
}

public class AdvancedCollection<T> : IList<T>,IList, IReadOnlyList<T>
{
private readonly List<T> _innerList;
private readonly Dictionary<T, List<int>> _reverseIndex;
private readonly object _syncRoot=new object();

public AdvancedCollection()
{
_innerList = new List<T>();
_reverseIndex = new Dictionary<T, List<int>>();
}

public AdvancedCollection(IList<T> list):this()
{
_innerList.Clear();
_innerList.AddRange(list);
refreshIndexes();
}

private void refreshIndexes()
{
lock (_syncRoot)
{
_reverseIndex.Clear();
for (var i = 0; i < _innerList.Count; i++)
{
var item = _innerList[i];
List<int> indexes;
if (!_reverseIndex.TryGetValue(item, out indexes))
{
indexes = new List<int>();
_reverseIndex[item] = indexes;
}
indexes.Add(i);
}
}
}

public int IndexOf(T item)
{
List<int> indexes;
if (!_reverseIndex.TryGetValue(item, out indexes)) return -1;
return indexes.Count == 0 ? -1 : indexes[0];
}

public void Insert(int index, T item)
{
lock (_syncRoot)
{
var indexesList = Enumerable.Range(index, _innerList.Count - index)
.Select(i => _reverseIndex[_innerList[i]])
.Distinct();
foreach (var indexes in indexesList)
{
for (var j = 0; j < indexes.Count; j++)
{
if (indexes[j] >= index)
{
indexes[j]++;
}
}
}
_innerList.Insert(index, item);
}
}

public void RemoveAt(int index)
{
lock (_syncRoot)
{
var indexesList = Enumerable.Range(index, _innerList.Count - index)
.Select(i => _reverseIndex[_innerList[i]])
.Distinct();
foreach (var indexes in indexesList)
{
for (var j = 0; j < indexes.Count; j++)
{
var i = indexes[j];
if (i == index)
{
indexes.RemoveAt(j);
j--;
continue;
}
if (indexes[j] > index)
{
indexes[j]--;
}
}
}
_innerList.RemoveAt(index);
}
}

public T this[int index]
{
get { return _innerList[index]; }
set
{
lock (_syncRoot)
{
var indexes = _reverseIndex[_innerList[index]];
indexes.Remove(index);
if (!_reverseIndex.TryGetValue(value, out indexes))
{
indexes = new List<int>();
_reverseIndex[value] = indexes;
}
indexes.Add(index);
indexes.Sort();
}
}
}


int IList.Add(object value)
{
return add((T) value);
}

bool IList.Contains(object value)
{
return ((IList<T>) this).Contains((T) value);
}

void IList.Clear()
{
lock (_syncRoot)
{
_innerList.Clear();
_reverseIndex.Clear();
}
}

int IList.IndexOf(object value)
{
return ((IList<T>) this).IndexOf((T) value);
}

void IList.Insert(int index, object value)
{
((IList<T>)this).Insert(index, (T)value);
}

void IList.Remove(object value)
{
var index = ((IList) this).IndexOf(value);
if (index < 0) return;
((IList) this).RemoveAt(index);
}

void IList.RemoveAt(int index)
{
((IList<T>) this).RemoveAt(index);
}

object IList.this[int index]
{
get { return ((IList<T>)this)[index]; }
set
{
var item = (T) value;
((IList<T>)this)[index] = item;
}
}

bool IList.IsReadOnly => false;

bool IList.IsFixedSize => false;

void ICollection.CopyTo(Array array, int index)
{
((IList)_innerList).CopyTo(array,index);
}

public int Count => _innerList.Count;

object ICollection.SyncRoot => _syncRoot;

bool ICollection.IsSynchronized => false;

IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return _innerList.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<T>) this).GetEnumerator();
}

public void Add(T item)
{
add(item);
}

public void Clear()
{
((IList) this).Clear();
}

bool ICollection<T>.Contains(T item)
{
lock (_syncRoot)
{
return _reverseIndex.ContainsKey(item);
}
}

void ICollection<T>.CopyTo(T[] array, int arrayIndex)
{
lock (_syncRoot)
{
_innerList.CopyTo(array, arrayIndex);
}
}

bool ICollection<T>.Remove(T item)
{
var index = ((IList<T>)this).IndexOf(item);
if (index < 0) return false;
((IList<T>)this).RemoveAt(index);
return true;
}

int ICollection<T>.Count => _innerList.Count;

bool ICollection<T>.IsReadOnly => false;

int IReadOnlyCollection<T>.Count => _innerList.Count;

T IReadOnlyList<T>.this[int index] => ((IList<T>) this)[index];

private int add(T item)
{
lock (_syncRoot)
{
var index = _innerList.Count;
_innerList.Add(item);
List<int> indexes;
if (!_reverseIndex.TryGetValue(item, out indexes))
{
indexes = new List<int>();
_reverseIndex[item] = indexes;
}
indexes.Add(index);
return index;
}
}

protected virtual void ClearItems()
{
((IList<T>)this).Clear();
}

protected virtual void InsertItem(int index, T item)
{
((IList<T>)this).Insert(index,item);
}

protected virtual void RemoveItem(int index)
{
((IList<T>)this).RemoveAt(index);
}

protected virtual void SetItem(int index, T item)
{
this[index] = item;
}
}

/// <summary>
/// Provides a generic collection that supports data binding.
/// </summary>
/// <typeparam name="T">The type of elements in the list.</typeparam>
[Serializable]
[HostProtection(SecurityAction.LinkDemand, SharedState = true)]
public class AdvancedBindingList<T> : AdvancedCollection<T>, IBindingList, ICancelAddNew, IRaiseItemChangedEvents,
INotifyCollectionChanged
{
private int _addNewPos = -1;
private bool _allowEdit = true;
private bool _allowNew = true;
private bool _allowRemove = true;

[NonSerialized] private PropertyDescriptorCollection _itemTypeProperties;

[NonSerialized] private int _lastChangeIndex = -1;

[NonSerialized] private AddingNewEventHandler _onAddingNew;

[NonSerialized] private PropertyChangedEventHandler _propertyChangedEventHandler;

private bool _raiseItemChangedEvents;
private bool _raiseListChangedEvents = true;
private bool _userSetAllowNew;

/// <summary>
/// Initializes a new instance of the <see cref="T:System.ComponentModel.BindingList`1" /> class using default values.
/// </summary>
public AdvancedBindingList()
{
initialize();
}

/// <summary>
/// Initializes a new instance of the <see cref="T:System.ComponentModel.BindingList`1" /> class with the specified
/// list.
/// </summary>
/// <param name="list">
/// An <see cref="T:System.Collections.Generic.IList`1" /> of items to be contained in the
/// <see cref="T:System.ComponentModel.BindingList`1" />.
/// </param>
public AdvancedBindingList(IList<T> list)
: base(list)
{
initialize();
}

private bool itemTypeHasDefaultConstructor
{
get
{
var type = typeof (T);
return type.IsPrimitive ||
type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance,
null, new Type[0], null) != null;
}
}

/// <summary>
/// Gets or sets a value indicating whether adding or removing items within the list raises
/// <see cref="E:System.ComponentModel.BindingList`1.ListChanged" /> events.
/// </summary>
/// <returns>
/// true if adding or removing items raises <see cref="E:System.ComponentModel.BindingList`1.ListChanged" /> events;
/// otherwise, false. The default is true.
/// </returns>
public bool RaiseListChangedEvents
{
get { return _raiseListChangedEvents; }
set { _raiseListChangedEvents = value; }
}

private bool addingNewHandled
{
get
{
if (_onAddingNew != null)
return (uint) _onAddingNew.GetInvocationList().Length > 0U;
return false;
}
}

/// <summary>
/// Gets or sets a value indicating whether you can add items to the list using the
/// <see cref="M:System.ComponentModel.BindingList`1.AddNew" /> method.
/// </summary>
/// <returns>
/// true if you can add items to the list with the <see cref="M:System.ComponentModel.BindingList`1.AddNew" /> method;
/// otherwise, false. The default depends on the underlying type contained in the list.
/// </returns>
public bool AllowNew
{
get
{
if (_userSetAllowNew || _allowNew)
return _allowNew;
return addingNewHandled;
}
set
{
var num1 = AllowNew ? 1 : 0;
_userSetAllowNew = true;
_allowNew = value;
var num2 = value ? 1 : 0;
if (num1 == num2)
return;
fireListReset();
}
}

/// <summary>
/// Gets or sets a value indicating whether items in the list can be edited.
/// </summary>
/// <returns>
/// true if list items can be edited; otherwise, false. The default is true.
/// </returns>
public bool AllowEdit
{
get { return _allowEdit; }
set
{
if (_allowEdit == value)
return;
_allowEdit = value;
fireListReset();
}
}

/// <summary>
/// Gets or sets a value indicating whether you can remove items from the collection.
/// </summary>
/// <returns>
/// true if you can remove items from the list with the
/// <see cref="M:System.ComponentModel.BindingList`1.RemoveItem(System.Int32)" /> method otherwise, false. The default
/// is true.
/// </returns>
public bool AllowRemove
{
get { return _allowRemove; }
set
{
if (_allowRemove == value)
return;
_allowRemove = value;
fireListReset();
}
}

/// <summary>
/// Gets a value indicating whether <see cref="E:System.ComponentModel.BindingList`1.ListChanged" /> events are
/// enabled.
/// </summary>
/// <returns>
/// true if <see cref="E:System.ComponentModel.BindingList`1.ListChanged" /> events are supported; otherwise, false.
/// The default is true.
/// </returns>
protected virtual bool SupportsChangeNotificationCore => true;

/// <summary>
/// Gets a value indicating whether the list supports searching.
/// </summary>
/// <returns>
/// true if the list supports searching; otherwise, false. The default is false.
/// </returns>
protected virtual bool SupportsSearchingCore => false;

/// <summary>
/// Gets a value indicating whether the list supports sorting.
/// </summary>
/// <returns>
/// true if the list supports sorting; otherwise, false. The default is false.
/// </returns>
protected virtual bool SupportsSortingCore => false;

/// <summary>
/// Gets a value indicating whether the list is sorted.
/// </summary>
/// <returns>
/// true if the list is sorted; otherwise, false. The default is false.
/// </returns>
protected virtual bool IsSortedCore => false;

/// <summary>
/// Gets the property descriptor that is used for sorting the list if sorting is implemented in a derived class;
/// otherwise, returns null.
/// </summary>
/// <returns>
/// The <see cref="T:System.ComponentModel.PropertyDescriptor" /> used for sorting the list.
/// </returns>
protected virtual PropertyDescriptor SortPropertyCore => null;

/// <summary>
/// Gets the direction the list is sorted.
/// </summary>
/// <returns>
/// One of the <see cref="T:System.ComponentModel.ListSortDirection" /> values. The default is
/// <see cref="F:System.ComponentModel.ListSortDirection.Ascending" />.
/// </returns>
protected virtual ListSortDirection SortDirectionCore => ListSortDirection.Ascending;

bool IBindingList.AllowNew => AllowNew;

bool IBindingList.AllowEdit => AllowEdit;

bool IBindingList.AllowRemove => AllowRemove;

bool IBindingList.SupportsChangeNotification => SupportsChangeNotificationCore;

bool IBindingList.SupportsSearching => SupportsSearchingCore;

bool IBindingList.SupportsSorting => SupportsSortingCore;

bool IBindingList.IsSorted => IsSortedCore;

PropertyDescriptor IBindingList.SortProperty => SortPropertyCore;

ListSortDirection IBindingList.SortDirection => SortDirectionCore;

/// <summary>
/// Occurs when the list or an item in the list changes.
/// </summary>
public event ListChangedEventHandler ListChanged;

object IBindingList.AddNew()
{
var obj = AddNewCore();
_addNewPos = obj != null ? ((IList<T>) this).IndexOf((T) obj) : -1;
return obj;
}

void IBindingList.ApplySort(PropertyDescriptor prop, ListSortDirection direction)
{
ApplySortCore(prop, direction);
}

void IBindingList.RemoveSort()
{
RemoveSortCore();
}

int IBindingList.Find(PropertyDescriptor prop, object key)
{
return FindCore(prop, key);
}

void IBindingList.AddIndex(PropertyDescriptor prop)
{
}

void IBindingList.RemoveIndex(PropertyDescriptor prop)
{
}

/// <summary>
/// Discards a pending new item.
/// </summary>
/// <param name="itemIndex">The index of the of the new item to be added </param>
public virtual void CancelNew(int itemIndex)
{
if (_addNewPos < 0 || _addNewPos != itemIndex)
return;
RemoveItem(_addNewPos);
_addNewPos = -1;
}

/// <summary>
/// Commits a pending new item to the collection.
/// </summary>
/// <param name="itemIndex">The index of the new item to be added.</param>
public virtual void EndNew(int itemIndex)
{
if (_addNewPos < 0 || _addNewPos != itemIndex)
return;
_addNewPos = -1;
}

public event NotifyCollectionChangedEventHandler CollectionChanged;

bool IRaiseItemChangedEvents.RaisesItemChangedEvents => _raiseItemChangedEvents;

private void fireListReset()
{
fireListChanged(ListChangedType.Reset, -1);
CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}

/// <summary>
/// Occurs before an item is added to the list.
/// </summary>
public event AddingNewEventHandler AddingNew
{
add
{
var num1 = AllowNew ? 1 : 0;
_onAddingNew = _onAddingNew + value;
var num2 = AllowNew ? 1 : 0;
if (num1 == num2)
return;
fireListReset();
}
remove
{
var num1 = AllowNew ? 1 : 0;
// ReSharper disable once DelegateSubtraction
_onAddingNew = _onAddingNew - value;
var num2 = AllowNew ? 1 : 0;
if (num1 == num2)
return;
fireListReset();
}
}

private void initialize()
{
_allowNew = itemTypeHasDefaultConstructor;
if (!typeof (INotifyPropertyChanged).IsAssignableFrom(typeof (T)))
return;
_raiseItemChangedEvents = true;
foreach (var obj in this)
hookPropertyChanged(obj);
}

/// <summary>
/// Raises the <see cref="E:System.ComponentModel.BindingList`1.AddingNew" /> event.
/// </summary>
/// <param name="e">An <see cref="T:System.ComponentModel.AddingNewEventArgs" /> that contains the event data. </param>
protected virtual void OnAddingNew(AddingNewEventArgs e)
{
_onAddingNew?.Invoke(this, e);
}

private object fireAddingNew()
{
var e = new AddingNewEventArgs(null);
OnAddingNew(e);
return e.NewObject;
}

/// <summary>
/// Raises the <see cref="E:System.ComponentModel.BindingList`1.ListChanged" /> event.
/// </summary>
/// <param name="e">A <see cref="T:System.ComponentModel.ListChangedEventArgs" /> that contains the event data. </param>
protected virtual void OnListChanged(ListChangedEventArgs e)
{
ListChanged?.Invoke(this, e);
}

/// <summary>
/// Raises a <see cref="E:System.ComponentModel.BindingList`1.ListChanged" /> event of type
/// <see cref="F:System.ComponentModel.ListChangedType.Reset" />.
/// </summary>
public void ResetBindings()
{
fireListReset();
}

/// <summary>
/// Raises a <see cref="E:System.ComponentModel.BindingList`1.ListChanged" /> event of type
/// <see cref="F:System.ComponentModel.ListChangedType.ItemChanged" /> for the item at the specified position.
/// </summary>
/// <param name="position">A zero-based index of the item to be reset.</param>
public void ResetItem(int position)
{
fireListChanged(ListChangedType.ItemChanged, position);
CollectionChanged?.Invoke(this,
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, this[position],position));
}

private void fireListChanged(ListChangedType type, int index)
{
if (!_raiseListChangedEvents)
return;
OnListChanged(new ListChangedEventArgs(type, index));
}

/// <summary>
/// Removes all elements from the collection.
/// </summary>
protected override void ClearItems()
{
EndNew(_addNewPos);
if (_raiseItemChangedEvents)
{
foreach (var obj in this)
unhookPropertyChanged(obj);
}
base.ClearItems();
fireListReset();
}

/// <summary>
/// Inserts the specified item in the list at the specified index.
/// </summary>
/// <param name="index">The zero-based index where the item is to be inserted.</param>
/// <param name="item">The item to insert in the list.</param>
protected override void InsertItem(int index, T item)
{
EndNew(_addNewPos);
base.InsertItem(index, item);
if (_raiseItemChangedEvents)
hookPropertyChanged(item);
fireListChanged(ListChangedType.ItemAdded, index);
CollectionChanged?.Invoke(this,
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item,index));
}

/// <summary>
/// Removes the item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove. </param>
/// <exception cref="T:System.NotSupportedException">
/// You are removing a newly added item and
/// <see cref="P:System.ComponentModel.IBindingList.AllowRemove" /> is set to false.
/// </exception>
protected override void RemoveItem(int index)
{
if (!_allowRemove && (_addNewPos < 0 || _addNewPos != index))
throw new NotSupportedException();
EndNew(_addNewPos);
if (_raiseItemChangedEvents)
unhookPropertyChanged(this[index]);
var item = this[index];
base.RemoveItem(index);
fireListChanged(ListChangedType.ItemDeleted, index);
CollectionChanged?.Invoke(this,
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item,index));
}

/// <summary>
/// Replaces the item at the specified index with the specified item.
/// </summary>
/// <param name="index">The zero-based index of the item to replace.</param>
/// <param name="item">The new value for the item at the specified index. The value can be null for reference types.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="index" /> is less than zero.-or-
/// <paramref name="index" /> is greater than <see cref="P:System.Collections.ObjectModel.Collection`1.Count" />.
/// </exception>
protected override void SetItem(int index, T item)
{
if (_raiseItemChangedEvents)
unhookPropertyChanged(this[index]);
base.SetItem(index, item);
if (_raiseItemChangedEvents)
hookPropertyChanged(item);
fireListChanged(ListChangedType.ItemChanged, index);
CollectionChanged?.Invoke(this,
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, item,index));
}

/// <summary>
/// Adds a new item to the collection.
/// </summary>
/// <returns>
/// The item added to the list.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">
/// The <see cref="P:System.Windows.Forms.BindingSource.AllowNew" />
/// property is set to false. -or-A public default constructor could not be found for the current item type.
/// </exception>
public T AddNew()
{
return (T) ((IBindingList) this).AddNew();
}

/// <summary>
/// Adds a new item to the end of the collection.
/// </summary>
/// <returns>
/// The item that was added to the collection.
/// </returns>
/// <exception cref="T:System.InvalidCastException">
/// The new item is not the same type as the objects contained in the
/// <see cref="T:System.ComponentModel.BindingList`1" />.
/// </exception>
protected virtual object AddNewCore()
{
var obj = fireAddingNew() ?? getNewInstance();
Add((T) obj);
return obj;
}

private static object getNewInstance()
{
return SecurityUtils.SecureCreateInstance(typeof (T));
}

/// <summary>
/// Sorts the items if overridden in a derived class; otherwise, throws a <see cref="T:System.NotSupportedException" />
/// .
/// </summary>
/// <param name="prop">A <see cref="T:System.ComponentModel.PropertyDescriptor" /> that specifies the property to sort on.</param>
/// <param name="direction">One of the <see cref="T:System.ComponentModel.ListSortDirection" /> values.</param>
/// <exception cref="T:System.NotSupportedException">Method is not overridden in a derived class. </exception>
protected virtual void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)
{
throw new NotSupportedException();
}

/// <summary>
/// Removes any sort applied with
/// <see
/// cref="M:System.ComponentModel.BindingList`1.ApplySortCore(System.ComponentModel.PropertyDescriptor,System.ComponentModel.ListSortDirection)" />
/// if sorting is implemented in a derived class; otherwise, raises <see cref="T:System.NotSupportedException" />.
/// </summary>
/// <exception cref="T:System.NotSupportedException">Method is not overridden in a derived class. </exception>
protected virtual void RemoveSortCore()
{
throw new NotSupportedException();
}

/// <summary>
/// Searches for the index of the item that has the specified property descriptor with the specified value, if
/// searching is implemented in a derived class; otherwise, a <see cref="T:System.NotSupportedException" />.
/// </summary>
/// <returns>
/// The zero-based index of the item that matches the property descriptor and contains the specified value.
/// </returns>
/// <param name="prop">The <see cref="T:System.ComponentModel.PropertyDescriptor" /> to search for.</param>
/// <param name="key">
/// The value of
/// <paramref>
/// <name>property</name>
/// </paramref>
/// to match.
/// </param>
/// <exception cref="T:System.NotSupportedException">
/// <see cref="M:System.ComponentModel.BindingList`1.FindCore(System.ComponentModel.PropertyDescriptor,System.Object)" />
/// is not overridden in a derived class.
/// </exception>
protected virtual int FindCore(PropertyDescriptor prop, object key)
{
throw new NotSupportedException();
}

private void hookPropertyChanged(T item)
{
var notifyPropertyChanged = (object) item as INotifyPropertyChanged;
if (notifyPropertyChanged == null)
return;
if (_propertyChangedEventHandler == null)
_propertyChangedEventHandler = Child_PropertyChanged;
notifyPropertyChanged.PropertyChanged += _propertyChangedEventHandler;
}

private void unhookPropertyChanged(T item)
{
var notifyPropertyChanged = (object) item as INotifyPropertyChanged;
if (notifyPropertyChanged == null || _propertyChangedEventHandler == null)
return;
notifyPropertyChanged.PropertyChanged -= _propertyChangedEventHandler;
}

private void Child_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (!RaiseListChangedEvents)
return;
if (sender != null && e != null)
{
if (!string.IsNullOrEmpty(e.PropertyName))
{
T obj;
try
{
obj = (T) sender;
}
catch (InvalidCastException)
{
ResetBindings();
return;
}
var newIndex = _lastChangeIndex;
if (newIndex < 0 || newIndex >= Count || !this[newIndex].Equals(obj))
{
newIndex = IndexOf(obj);
_lastChangeIndex = newIndex;
}
if (newIndex == -1)
{
unhookPropertyChanged(obj);
ResetBindings();
return;
}
if (_itemTypeProperties == null)
_itemTypeProperties = TypeDescriptor.GetProperties(typeof (T));
var propDesc = _itemTypeProperties.Find(e.PropertyName, true);
OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, newIndex, propDesc));
return;
}
}
ResetBindings();
}
}

Tuesday 5 January 2016

Avoiding harm destroys free speech

Just a short revelation that I had. It starts with the definition of free speech, which is considered free if it does no harm. This is what is called the principle of harm. But what is increasingly happening all over the world is that more and more of what people do is considered harmful. Things like racism or misogyny have been now joined by online bullying, pro-life discussions, fat shaming, you name it. The result is a reduction of free speech.

If you want free speech, then brave the words of others. It is the penchant of humans and all life in general to categorize the world and then act in different ways based on discrete cases. It is not entirely correct, but it is how nervous systems work since worms were invented. It is a biological impossibility to be confronted with human behavior and not consider one category of people better than another based not only on color, but whatever you see differentiate them. And while I understand the need to push back with legislation against some biases that have become counterproductive, we have to eventually dial back even on those. Adding more exceptions to how thinking and feeling works just pushes people away and stifles the ability to speak freely.

An especially worrying trend puts copyright and commercial interests higher and higher on the list of things you should not cross. It is becoming so powerful a concept that it is increasingly used to stop people from expressing themselves. Online reviewers are being sued for not liking a product, people are being stopped from reading controversial material by buying the rights and then not publishing it and so on. But even small things that seem proper at first glance are just as toxic, like protecting children from all kinds of perceived threats. Forget they are children, just analyse the social cost of having them exposed to something; people learn from experience, there is always a balance between harm and evolution.

When will it end, you might ask yourself. Think of border cases like Snowden. Do you side with him, for disclosing information that affects all of us, literally, or do you side with the people that say he committed treason? Do you think encryption should be banned, so that governments can better take care of us by knowing everything there is to know about what we communicate? How about getting fined by the hotel you've just been to because you write a negative review. Are all these worth stopping people from calling you fat, gay, colored, old, stupid, or whatever you feel offends you most?