Linq – deferred ^ immediate execution

update — java 8 streams …

(I feel this is a low-level but popular question…)

– if an operation returns a single value (aka aggregates) then ImmEx. ([[c# indepth]]  P281)

– if an operation returns another sequence, then defEx ([[c# indepth]]  P281)

– ToList() — ImmEx

– sort uses ImmEx in SQL. Ditto Linq — [[c# indepth]]  P369

– regular SQL Select with multiple output rows? Uses defEx. As you retrieve one row, all subsequent rows are subject to change.

– SQL Select with a single-row output? probably ImmEx.

Advertisements

c# attribute on method arg – usage

I feel attributes on method param is a rarely used feature. I feel it is meant for reflection or documentation. http://realfiction.net/go/108 presents a simple usage of this feature, whereby runtime reflection extracts the additional information contained in the attribute value. You can then act on the information.

It also shows that an override method can “add” such attributes.

argument validation — http://www.codinginstinct.com/2008/05/argument-validation-using-attributes.html presents a practical usage — argument validation. For example, you can mark an argument as NotNull

Here’s another usage, but I don’t remember if I tested it successfully.

Make ViewModel get key events only when its host tab is on top

In a tabbed GUI, I have a distinct ViewModel object for each tab. For e.g., tab3 is backed by vm3 object. In it I have a keyboard event handler to manipulate a lot of private data in the vm3 object (and update screen). This handler should fire when Tab 3 is on top. However, vm3 object has no way to tell if Tab3 is on top. MVVM in action.

My Solution: the “code-behind” Mainpage.xaml.cs ctor to register a private this.Handle3 to the this.KeyUp event, where this.Handle3 has access to the Tab3 object, so long as Mainpage.xaml exposes the Tab3 as a field via x:Name.

Handle3() checks if Tab3 is on top and then directly calls vm3.handler. Feasible because Mainpage.xaml.cs has a reference to vm3.

This relies on the code-behind as the melting pot. A quick and dirty solution.

an event inherited from interface->abstract class->concrete class

In this class hierarchy, the event is declared in interface ICommand, then declared abstract in the abstract class, finally implemented in the concrete classes.
Note the abstract must declare it.
    abstract public class TanBinRelayCommand: ICommand{
        private Action methodToExecute;
        private Func<bool> isEnabled;
        public TanBinRelayCommand(Action methodToExecute, Func<bool> isEnabled)
        {
            this.methodToExecute = methodToExecute;
            this.isEnabled = isEnabled;
        }
        #region ICommand members
        ///

        /// who subscribes to this event? I think the command binding (or other objects in the xaml)
        ///

        bool ICommand.CanExecute(object obj) {
            if (this.isEnabled == null) return true;
           
            return this.isEnabled.Invoke();
        }
        void ICommand.Execute(object obj)
        {
            if (this.methodToExecute != null)
                this.methodToExecute.Invoke();
        }
        abstract public event EventHandler CanExecuteChanged;
       

a simple c# SaxParser – NamespaceTolerant

Note: like an istream, the reader has an internal position pointer. reader.Name can return the name of either an element or an attribute, depending on the position.
Note: one common iteration idiom uses Read(), which advances the pointer to the next start/end tag??.  Like a subway express train, it won’t stop at the attributes – local stops.
        ///

        /// It’s not easy to find a SAX parser in c#
        /// It’s not easy to find a xml parser that tolerates undeclared namespaces
        ///
        /// Here’s a solution
        ///

        ///
        private static void SaxParser_NamespaceTolerant(string arg_xmlFullStr)
        {
            using (XmlTextReader reader = new XmlTextReader(
                                         new StringReader(arg_xmlFullStr)))
            {
                reader.Namespaces = false; //ignore undeclared namespaces
                while (reader.Read())
                {
                    if (string.IsNullOrWhiteSpace(reader.Name)) continue;
                    if (reader.IsStartElement())
                    {
                        Dump(reader.Name);
                        if (reader.HasAttributes)
                            while (reader.MoveToNextAttribute())
                                Dump(“\t” + reader.Name + “=” + reader.Value);
                    }
                }
            }
        }

c# DYNAMIC – TryCall_method1 on an Unidentified object#src

With dynamic type, we can try-call an arbitrary method m1(), which need not exist in any public interface. Behaviour — If the underlying type exposes m1, it is invoked. If unavailable you get a run time error, not a compile time error.

One usage idea — Instead of calling the standard ToString() on the unknown object, we want to try-call ToStringXml(), and pray the underlying type supports it. Traditionally, If we have a few types to add ToStringXml(), we would prefer compile-time type check by introducing an interface IXmlDumper. However, if you have 55 types that could pass into TryCall() and 33 of them exposes ToStringXml(), you may need to cast to IXmlDumper then call ToStringXml(). Worse, you would need to edit source code for the 33 types!

With dynamnic type, basically the compile-time type check is postponed to run time. Compile time type check would need m1() declared in the type C, like —

C c = new C(); c.m1();

But if we use dynamic, and type-check at run time, then we don’t need m1() exposed on any public interface —

small c# trick to log the current value of a field

Suppose you want to log (“StaticOrNonStaticField_AgeInConfig = ” + StaticOrNonStaticField_AgeInConfig), but you anticipate renaming on this field. When anyone uses any IDE to renames it next month, you want the log message to change automatically. Here’s a trick

public static string GetMemberName(Expression<Func> expr){
var body = ((MemberExpression)expr.Body);
return body.Member.Name;
}

Log.Info(GetMemberName(() => StaticOrNonStaticField_AgeInConfig) + ” == ” + StaticOrNonStaticField_AgeInConfig);

1 or 2 nameless classes generated for each yield block

If a (possibly static) method or getter has “yield”, then I call it (loosely) a “yield method” — officially an “iterator-method”. A yield method must return aa) IEnumerator or bb) IEnumerable.

–aa) If a “yield-method” has return type IEnumerator, then exactly 1 unnamed class generated. The yield-method return value is an instance of this unnamed class.

* This class implements IEnumerator

–bb) If a “yield-method” has return type IEnumerable, then 2 unnamed classes. The first (outside) class implements IEnumerable, so the yield-method return value is this type. This outside class implements the mandatory GetEnumerator() method returning an IEnumerator. GetEnumerator() return value is an instance of the other (inside) class.

* the 1st class implements IEnumerable

* the 2nd class implements IEnumerator

Here's a potential confusion. Say you write an IEnumerable subclass. In it you write a GetEnumerator() returning an IEnumerator. Is this the aa case or the bb case? Actually aa.

Q1: when is such a class instantiated?

A: every invocation of the yield method would instantiate an instance of 1 or 2 classes. The IEnumerator object is stateful, so you hold on to that object throughout the iteration. You don't call the yield method 55 times to hit the 55 items — you call Current/MoveNext 55 times.

Q2: but when exactly is the yield method invoked?

A: Invoked at the initialization of the foreach. The only way to use a yield-method is a foreach loop.

See P101 [[c# precisely]]

linq – a scratch seeking an itch

The more I read about linq2collection, the more convinced I feel that it’s not strictly necessary. Old fashioned for-loops are
cleaner and easier to read. Exception handling is cleaner. Branching is cleaner. Mid-stream abort is cleaner.

A linq proponent may say OO was not strictly necessary (compared to procedural), and relational DB was not strictly necessary
(compared to non-relational DB) but offer real values and so is linq. Here’s my argument, focusing on linq2collections.

– I feel this is a local implementation choice, not a sweeping, strictly enforced architectural choice. As such, a particular method
can choose not to use linq.
– Another comparison is ORM. Once ORM is chosen in a project, you can hardly choose not to use it in one particular method. Linq is
more flexible, less enforced and more “sociable”.

A java guy has no such tool but is perfectly productive, until java 8 streams…

I feel linq gained mindshare on the back of c# success. If F#, python or delphi invents such a cool feature, it would remain a niche feature. I don’t see another language embracing linq, until java 8

Neverthless, we must master linq for the sake of job interviews. This is somewhat comparable to c++ multiple inheritance – not used
widely but frequently quizzed by interviewers.