Wednesday 26 December 2012

Single cast delegate vs. Multi cast delegate

In C# all delegates are multicast delegates. A singlecast delegate is simply a multicast delegate with one handler attached. All delegates inherit from System.MulticastDelegate in mscorlib.

The Underlying Type of an Enum

Enums in C# are generally backed by the underlying type int (actually System.Int32). This is a signed value ranging from -2 billion to positive 2 billion (a little over, actually, 2.147 billion).  However, this underlying type can be overridden e.g. enum Selection : sbyte. Now the enum is a signed 8 bit integer (ranging from -128 to 127). Note, however, that the base type of Selection is System.Enum and not sbyte! Forget what you know about base type specification!

Sunday 2 December 2012

Technology

Technology (especially hardware) can be quite intimidating for those unaccustomed to the products out there. Features seem to be implemented beyond what the end-user wants or needs. It takes time to get familiar with the products out there. There may be many manufacturers. This is more true for appliances e.g. kitchen appliances, home technology etc. much more so than computing, which has become quite commoditised as of late.

Disable Privacy Warnings in Excel when Saving Workbooks

Go to Developer tab, and select the "Macro Security" button (with the "Roadworks" sign), Privacy Options and un-check everything. Hey Presto, you are done!

Wednesday 28 November 2012

What is Secure Coding?

UNMANAGED CODE IS THE ROOT OF ALL EVIL (LET THE CANARIES PROTECT YOU)

The issue of "secure coding" comes into play when you are writing "Internet" software.

An old classic example of "insecure code" would be buffer overruns (something that can occur in poor C++ coding). It's rather harder to do in Java or C# due to run-time checking of array boundaries. Michael Howard and David LeBlanc call buffer overruns "Public Enemy Number One" in their book, "Writing Secure Code" (published by Microsoft Press, December 2004), also known as "The Grey Book".

Visual C++ .NET comes with a /GS option that employs canaries to neutralise buffer overflow attacks (its etymology comes from the "canary in the coal mine" analogy). The canary is a known word inserted into the stack to monitor buffer overflows, such as if data in the stack gets corrupted, the first data to get corrupted is the canary.

One of the "good practices" identified in The Grey Book is identifying parts of your infrastructure in C or C++ which could be re-implemented in a managed language, to reduce the risk of classes of attacks, such as buffer overflow.

GREAT THING ABOUT C#

One of the great things about C# is you don't have to worry about the so-called "secure coding" issues that you have to worry about (or at least be mindful of) in C++.

PRINCIPLE OF LEAST PRIVILEGE

This is a useful security principle, whereby you give a user the rights to do what they need to do and nothing more.

Tuesday 6 November 2012

Contending with Tiredness: Progammer as Fighter Pilot

WRITE THINGS DOWN WHEN YOU ARE TIRED

You are at the tail end of your project. Tired from the insane momentum of the last few days of coding, tiredness sets in. You think you can program at the same level but are fighting to stay awake. At this point, switch to "low impact" coding mode. Open a spreadsheet and write down each step you are planning to take (identifying targets). This will prevent slowness due to forgetfulness caused by tiredness. It will also enable you to take breaks and resume work without disruption.

The Appetite for Tactical Refactoring

Have RESPECT for Tactical Refactoring

At times mid-way through a project, you may find it opportune to undertake some "tactical refactoring". This might involve pushing some data structures into a common library project, as they will need to be used in various independent, or co-dependent, systems, such as a client and server program. At these times, you may ask "should I bother". Unless the deadline is five minutes away (and a swift cut and paste will get your system to its target state) it is worth "biting the bullet" and taking on the tactical refactoring challenge. The benefits will pay off swiftly as you extend the program's functionality.

Binding to DataGridCells - Thinking about the Binding Mode!

When you create a binding in XAML, you specify a Path (usually pointing to a property in the DataContext) and, more often than not, a Binding Mode.

For example: is it a "OneTime" binding? A "TwoWay" binding? A "OneWay" Binding? These are important things to consider!

Fast-paced MVVM

The POWER to RAISE PROPERTYCHANGED Events!

The trick to getting good at something is to do it hundreds of times. But sometimes that alone is not enough, you have to up the pace, and see whether you can still perform just as accurately at the faster pace. Consider the writing of Models and ViewModels. Writing a ViewModel at pace might seem just an elementary window in on a Model..but...whoops...you forgot to implement INotifyPropertyChanged! Oops, binding won't work then! Get MSVS to auto-implement this interface for you - no need for all that extra typing!

Wednesday 24 October 2012

Dependency Properties in WPF

We have already alluded to dependency properties, albeit in a Silverlight context. Now we talk about it from the WPF perspective (not too different).

Wednesday 17 October 2012

Saving sln files in Visual Studio - UTF-8, Unicode or ANSI?

SAY NO TO ANSI

Anything but ANSI - that's 8 bits and can only hold a limited number of characters (2^8 = 256).

To Update an ObservableCollection on a Background Thread or Not To?

ADD, REMOVE, REPLACE - NO
MODIFY - YES

Modifying an ObservableCollection will lead to an event being raised, which is handled on the same thread as the modification. If you add or remove items from an ObservableCollection from a background thread, the event gets raised before the Add/Remove gets completed.

If you are just changing properties in the elements (trivial updates) you should be fine. The processing can happen in the background, and the trivial update can happen on the main thread, no problems. GUI response time should not be impacted.

protected set

READ ONLY VIEW MODEL FIELD IN BOUND GUI

Making a property setter protected means the property will be non-editable in a GUI control when the data is being used as a ViewModel in the context of data binding.

Domain-neutral Assemblies

BUILD CLEAN SEVERAL TIMES TO CLEAR APPDOMAIN SECURITY ERRORS

What are domain-neutral assemblies?

Domain-neutral assemblies are assemblies designed to work across appdomains. They wil be jitted only once. The idea is to get performance gains in multiple appdomain scenarios. mscorlib is always domain-neutral.

Why are they important?

They are important to understand error messages that come from app domain security messages e.g. on why a particular assembly cannot be loaded when trying to run an application.

Refactoring WPF (IOException: Cannot Locate Resource)

CHECK STARTUPURI

Minimal Structure WPF

What is the minimal structure of a WPF Application, for example, when you go into Visual Studio and click to create a new WPF Application?

This is a guide to a bare-bones WPF application. In fact, you can happily write WPF applications without knowing the bare-bones, but at some point it's essential to look back and fully understand what's going on in order to move forward.

App.xaml, App.xaml.cs and StartupUri (VIRF = Very Important when Refactoring)

Look at App.xaml and App.xaml.cs. This represents a single logical unit, representing the Application (or more precisely a subclass of System.Windows.Application) implemented over two partial classes.

This is like Global.asax in ASP.NET land. It's where you can put shared resources to be shared across multiple windows. It also specifies (in the App.xaml "header element" the StartupUri which will be set to the auto-generated MainWindow.xaml). If you change the StartupUri to something that doesn't except (e.g. PainWindow.xaml instead of MainWindow.xaml you will get an IOException ("Cannot locate resource: PainWindow.xaml"). This can happen after a refactor where you can't decide the name for the MainWindow.xaml and then forget to change the StartupUri (or MSVS fails to change the StartUri automagically - it happens).

App.xaml.cs purports to be the "interaction logic" for App.xaml but in reality it is usually left empty. App.xaml is frequently underutilised in WPF projects and should be given more a higher profile by WPF developers.

MainWindow.xaml and MainWindow.xaml.cs

This contains the window XAML and the IntializeComponent code after which you can define your own initialization logic (e.g. creation of ViewModels etc).

Furthering your Understanding

To understand more completely what a WPF Application actually is, one can read the MSDN document describing System.Windows.Application and its parent classes.

Psychology of XAML

DON'T KNOCK XAML, LEARN IT

Reams and reams of XAML, long XML-based definitions of ControlTemplates and VisualStateManager and StoryBoards, may seem daunting, incomprehensible and unmanageable at first. However, this is a great advancement in computing - as declarative GUI-related information has been isolated and sectioned away from the main imperative and application-related coding. The only time you need to enter into the structured chaos that is XAML is when you need to.

Templates, Templates Everywhere, But what about Controls?

Control Templates Introduced

We have seen DataTemplates in action in a previous post. But controls, too, have a great templating feature. This is known as Control Templates. You MUST, as a WPF MASTER, be completely comfortable with Control Templates. As a LEARNER, you MUST seek every opportunity to use them and become proficient in their use.

Where is and What it does

First go to the Sir Winston Churchill namespace (the "alt-name" for System.Windows.Controls). Here you will find the ControlTemplate class, that specifies the visual structure and behavioural aspects of a Control that can be shared across multiple instances of the control. Not quite control arrays, but you get the picture.

A quote from Sir Winston Churchill might inspire further WPF-learning and indeed create the appetite for greater changes in the toolkit, and indeed might even be interp'ed as a commentary on the toolkit itself, "To IMPROVE is to change, to be PERFECT is to change often".

How is it used?

A control author may specify a default ControlTemplate and an application author may override it.

Changing the Appearance of a Button

A control template can be used to change the visual appearance of a button, making it appear round, for example. This is the canonical MSDN example.

Other types of template to contemplate

CONTROL TEMPLATE - the subject of this post and a wonderful feature of WPF
DATA TEMPLATE
FRAMEWORK TEMPLATE - read all about it here

Tuesday 16 October 2012

Visual Studio 2012 Welcomes C++ 11

C++ 11 (formerly C++Ox) is the latest version of C++ supported in Visual Studio 2012. New STL headers include <atomic> and <chrono>. The atomic library defines atomic types (data types free from race conditions - so if one thread reads from an atomic item and another writes to it, the behaviour is well-defined). Examples are atomic::int and atomic::long. The chrono library deals with time, specifically objects representing time spans and points in time.

Kinect

Win-Joe has been somewhat remiss in not covering, at least in passing, Microsoft's Kinect technology (where "YOU are the Controller"). The Kinect is an attachment for the Xbox 360 that combines a depth camera (sometimes know "in the trade" as RGB-D), standard RGB camera, motorized tilt and four microphones. MSDN Magazine has a good introduction to Kinect programming.

The October 2012 SDK exposes the infrared stream, allowing image capture in low-light situations. However, it is currently not possible to capture infrared and colour streams simultaneously.The Accelerometer Data APIs now provide information on the sensor's orientation. Desktop robotics - Aloha!

Microsoft UI Automation

This comes bundled with .NET Framework 3.0 as part of WPF. This is covered in the following MSDN magazine article. WPF made its debut in .NET Framework 3.0. Instead of using the GDI as previous libraries did, WPF employed DirectX. The relevant DLL is UIAutomationProvider.

Monday 8 October 2012

C# Semiotics

We talk about the "lexical structure" of a programming language as if programmers are specialists in linguistics. This is not necessarily the case. Lexical analysis informally relates to "parts of speech", or more generally, parts of sentences. In this case, we are analysing "sentences" in the C# programming language.

Taking a "lexical view" of C# is an interesting exercise and helps to explain programming to semiotics majors, for example.

Take the simple assignment: double pi = 3.14159;

Analysing this lexically we can say:

1. double is an "abstract noun". An abstract noun refers to a concept or idea. In this case, the idea is of a 64-bit floating point value.

2. pi is a "proper noun". A proper noun can refer to a place, object or name of a person. In the above case, it is the name we have given to a specific realisation of the concept, double.

3. the value 3.14159 is a "concrete noun" that refers to the physical object.

The acronym to remember this language of nouns is APC (Abstract, Proper, Concrete).

Language also has the concept of collective nouns. A List of doubles is one example; similar to a gaggle of geese or a flight of swallows or even "a troop of kangaroos".

C# Lexical Structure: Keywords vs Contextual Keywords

How do you extend a language without changing its keywords? Contextual keywords go some way to providing an answer.

An example keyword in C# is "double". Double is a simple type that can store 64-bit floating point values. A contextual keyword only has meaning within a specific context e.g. get/set within a property declaration.

The ascending contextual keyword is used in LINQ queries and only has meaning in LINQ context, for example:

IEnumerable<string> sortAscendingQuery = from elephant in zoo orderby elephant ascending select elephant.

There is no specific word for non-contextual keywords. One might call them, "context-independent" keywords.

Saturday 29 September 2012

Nuget

NuGet is a Visual Studio extension to make it easy for you to find and install third-party libraries and tools. As of September-end 2012, NuGet has had 25 million downloads. Amongst the packages available on NuGet, there is Json.NET, a high performance Json framework for .NET.

Wednesday 26 September 2012

PFX (Parallel Extensions) built on System.Threading.Tasks

What is PFX? (I heard about it on Channel 9).

PFX stands for Parallel Extensions for the .NET framework (released in .NET 4.0) and is something of increasing importance, judging from the multiple references to PFX on channel9.msdn.com. This post will be a primer to PFX - getting you up-to-speed with the basic terminology and concepts.

Who developed PFX?

Both Microsoft Research and the CLR team were involved in the development of PFX.

Two Parts to PFX and their Relationship

First is Parallel LINQ (PLINQ) and second is Task Parallel Library (TPL). PLINQ uses TPL for execution. The other technical term is CDS which stands for coordination data structures - used to synchronise and co-ordinate execution of concurrent tasks.

Example

using System.Threading.Tasks;
Parallel.ForEach(myListOfStrings, s => Console.WriteLine(s));

Data Structures for Parallel Programming

More can be found here. Ex: System.Collections.Concurrent.ConcurrrentDictionary<Key,Value>

IE9 heralds HTML5 Video Support

HTML5 defines a new element (<video>) specifying a standard way to embed video in a web page (supported in IE9, Chrome, Safari, Firefox).  Supported video formats are:
* MP4 - MPEG4 files (H264 video codec, AAC audio codec
* WebM - WebM files (VP8 video codec, Vorbis audio codec
* Ogg - Ogg files (Theora video codec, Vorbis audio codec)

Reactive Extensions (Rx)

About time WinJoe covered Reactive Extensions, Rx, an interesting library for handling streams of data. It is starting to be used as a tool for CEP (Complex Event Processing) applications.

IE7 is already in the History Books

Many modern websites (e.g. force.com) have no support for IE7. IE8 is built from the ground up. It passes the Acid2 browser test (documented on the Web Standards Project website), IE7 fails. This shows IE7 has poor web standards compliance! Acid2 tests support for so-called "data URLs" (RFC 2397).

IE8 also introduces some web security-oriented features. Some of these are MS-specific (e.g. restrictions on ActiveX controls) whilst others are more wide-ranging (e.g. relating to cross-site scripting (XSS)).

To understand web security, a good resource is OWASP (Open Web Application Security Project) whose mission is to "make software security visible".

Sunday 23 September 2012

The Importance of Managed Debugging Agents (MDAs)

MDAs work with CLR to provide information on runtime state. One of the most famous MDAs is loaderLock MDA.

The idea of MDAs is to isolate hard-to-find app-bugs when transitioned from managed to unmanaged code.

Thursday 13 September 2012

MSVS 2010 Autoformat Code

Cntrl-E Cntrl-D.
(Eclipse: Cntrl-shift-F)

WPF Multibindings

Bind multiple items and return a single value.

Excellent functionality in all kinds of control panel scenarios.

The WPF DataGrid - Explained

It might seem mysterious how one can populate a WPF DataGrid from System.Windows.Controls, the "Fourth" Incarnation of the DataGrid.

Answer: Create your own ObservableCollection

All lies in setting the ItemsSource property to an ObservableCollection of custom-built ViewModel objects. As we know from MVVM design, the ViewModel is just like a "screen" on top of the Model that keeps the Model up to date and is also responsible for notifications when properties change, to the relevant observers.

From ObservableCollection to NotifiableCollection

ObservableCollection is good for dealing with "macro" changes to the Collection (as when an Item gets added or deleted) but is not good at detecting and propagating changes when properties on individual items change. For that, a custom-built NotifiableCollection is appropriate (see this discussion on forums.silverlight.net (general principle applies to WPF also)) and also this blog post from a software consulting firm specialising in "nearshoring").

Declaring the NotifiableCollection has to be done in "Generic" Style

public class NotifiableCollection<T>: ObservableCollection<T> where T: class, INotifyPropertyChanged {... }

Note that you also need to declare an EventHandler within the Collection definition, which can be simply done: public event EventHandler<MyEventArgsClass> InterestingPropertiesChanged, or some such similar declaration. Conceptually, this is like defining a multicast delegate to hold the function pointers representing methods to be invoked when an "interesting" property is changed.

Conclusions

The main conclusion is this.

It's nice to know what you can do in WPF using System.Windows.Controls. But a knowledge of controls alone is no use without working knowledge of the relevant object model and component model namespaces.

Thes are System.ComponentModel (INotifyPropertyChanged) and System.Collections.ObjectModel (ObservableCollection). Understand the ComponentModel and Collections Object Model in detail.

Tuesday 11 September 2012

Respect to System.Windows.Input

For it brings us the RoutedCommand.  RoutedCommand is a central pillar to Commanding in WPF and implements the ICommand interface (also part of System.Windows.Input) with which every .NET programmer should be really familiar with. ICommand? Oh yeah, that old thing. That means the RoutedCommand has to implement Execute and CanExecute, is all. And not just RoutedCommands, either. Also RoutedUICommands, which is, like, a special case of a RoutedCommand. I won't explain the differences between the various RoutedCommands. Let experience be your teacher.

Recap: Name three classes in System.Windows.Input related to Commanding. Hint: See Above.

But one thing we must mention.

System.Windows.Input ain't just about Commanding. 

Oh no, there's a whole PLETHORA of crazy stuff in there. Everything to do with the WPF input system, including keyboard, mouse and stylus input processing types. One such crazy class would be e.g. StylusButton, that represents a button on a stylus. Much cooler than going pound-include iostream; and all that malarkey in C++. Forget C++. This is the Age of C#.

Monday 13 August 2012

Art of C# Sockets II: "Lineage" of NetworkStream

What is a NetworkStream? Specifically what makes it unique from its abstract base class Stream.

A network stream is like a stream of water, only instead of H20 going from the top of the mountain to the valley below, we instead have "molecules" of data (which we call bytes)  travelling continuously from a source to a destination. If the source and desination are at different parts of a computer network, the connecting byte stream can be loosely termed a "NetworkStream".

Ok, so we know vaguely know what a Network Stream, as they call it, is all about. Where does the NetworkStream class come from? What's its lineage, so to speak, in terms of the object model/class hierarchy.

Stream is the abstract base class of all Streams (the top of the Himalayas, if you will). Stream is the only class that NetworkStream directly subclasses from. Indirectly, NetworkStream also inherits from MarshalByRefObject and System.Object but these are rather peripheral facts (we'll look at the esoteric implications much later).

NetworkStream is a specialization of a Stream that supports reading, writing and seeking for Streams over the Network and lives in the System.Net.Sockets namespace. The class is very useful when writing TCP clients and servers.

NetworkStream extends System.IO.Stream. Has methods to read and write byte arrays. Streams also provide seeking capabilities - ability to query and modify the current position within a stream.

What is the practical usage of NetworkStream?

To send messages from TCP client to server.

C# Sockets Programming (Intro to System.Net.Sockets)

Desperate Programmer: I want to write network software and not be bound by weirdo libraries that limit me in how many connections I can make and such like.
Wise Programmer: Then what you need is Sockets. Master sockets and cross the impasse of data transfer across networks.
Adage: Don't trust a Dot Net Programmer to architect an application who has never programmed network software in C# and moreover has never programmed Sockets.
Desperate Programmer: So, then how do I unlock the Sockets functionality of .Net?
Wise Programmer: Start with the System.Net.Sockets namespace and progress from there

Concept Check: What is the Relation between TCP and Sockets?

Socket is a SOFTWARE OBJECT -> that REPRESENTS an endpoint for inter-process communication. Sockets can use various PROTOCOLS (rulesets), such as TCP and UDP.

How do you create a TCP Client in C#? Tell me PRECISELY.

The answer is SIMPLE. You can guess it without knowing C#. Use the TcpClient class. Where does that great TCP client class live? Ans: System.Net.Sockets (part of System.dll).

Suppose your TCP client is aptly named client. To connect the client to a socket, you need to do client.Connect(IPEndPoint). The endpoint consists of an IP address and a port. Now we have a connection. The server has to be up though for this connection to work.

How do you send a message from the Client to the Server?

You need to grab the NetworkStream from the TcpClient.  You can do stuff with the Stream, like write byte arrays to it, and Flush it. To convert a string to a byte array, you can use the class ASCIIEncoding (System.Text, from mscorlib.dll) which represents an encoder. Calling GetBytes on the encoder creates a byte buffer.

How do you create a TCP Server in C#? Again, a precise explanation is requested.
This is just a TcpListener. You create a TcpListener using IPAddress.Any, and the required port.  Calling Start() on the listener starts it listening to incoming requests. The method AcceptTcpClient returns the next TCP client accepted by the listener. Once you have the client object, you can spawn a new thread to handle the client communication.

Writing a TCPClient is child's play. Writing a TCP server is a little more involved.

Friday 27 July 2012

A Guide to C# Interfaces for the Dotnet Architect

When drawing up an interface, one may wonder: "What are the valid constructs I can include in a C# interface?" An ARCHITECT of .Net software must be clear on this point, to be able to design interfaces that are a) SYNTACTICALLY CORRECT b) FIT FOR PURPOSE.

The answer is not as obvious as it may seem.

What CAN be put into a C# Interface? (MPE IND - Mumbai-Pune Expressway, India)
Methods, certainly.  Properties, yes. Events and indexers too - but not operators - why, because operators are declared static, and C# has no mechanism to require a type to implement static methods. The concept of interfaces in C# is thus much richer than the same construct in Java (which supports declaration of methods and constants).

What CANNOT be put into a C# Interface?
The reason why C# uses static operator overloading is based on cost/benefit analysis (read this piece from the C# compiler team. The question naturally arises since in  C++ operator overloading is done at instance level rather than static level (doesn't use the static keyword)). The upshot (or rather downshot) of this is that operator overloading cannot be prescribed at the interface level.

An Interface Specifies a Contract
A non-abstract implementation of an interface MUST implement ALL its members.

Accessibility Modifiers and Interfaces (Restaurant Example)
By definition, all interface members are public, since an interface is the public visage of a class or struct, it is what the class or struct wants to show to the outside world. (Like a restaurant that allows customers to orderFood, payBill, addTip and so forth). It may also have properties such as Address, StyleOfCuisine and so on. It may not expose the method CookFood unless clientele are able to cook their own food, for example using a grill built into the table. That may be part of the implementation but not part of the interface. An indexer may not be appropriate, unless be are creating an interface for RestuarantChain and want to access particular outlets of the chain. Events could be things like: CallForTakeawayOrder.

Boost Math Basics

Understanding Boost Math is about a) understanding the underlying mathematical concepts, but additionally you have to understand b) what the typenames mean.

Quick revision guide on typenames in C++: They are used to disambiguate type declarations, but have a dual role in that they can be used in place of class in template parameter declarations.

Math typenames from Boost:
1. RealType - denotes a real number, usually represented/approximated by, a double.
2. Policy - transmits behaviour, e.g. what to do when certain error conditions are met. An example in STL of a policy class would be std::allocator which communicates memory management policy to container classes.

You also need to understand error functions, mathematically denoted by erf(z) and erfc(z)=1-erf(z). erfz is e to the minus t squared integrated between 0 to z and "normalized" by two divided by the square root of pi.

The error function (also known as the "Gauss error function") is one of the "special functions" in mathematics. It has a sigmoid (or "S") shape.

You will see also that Boost header files have a .hpp extension rather than .h (which signifies pure C++). .h files are also used in C.

Wednesday 18 July 2012

Inverting the STANDARD Cumulative Normal Distribution in Excel and C++

For various financial applications, you will need to invert the cumulative standard normal distribution. The correct Excel worksheet function for this is:

NORMSINV

You need to give it a number between 0 and 1. The function NORMSINV is confusing, because the name does not allude to the fact that we are inverting the CUMULATIVE normal distribution. (NORMINV is the cousin of NORMSINV that inverts the Normal Distribution more generally. Consequently, mean and standard deviation parameters must be specified explicitly. NORMSINV can be regarded as a special case of NORMINV that just accepts a probability as parameter).

Here is an algorithm for computing the inverse cumulative normal distribution. Note that the function is a continuous, non-linear (curve rather than a straight line) function and maps the (0,1) open interval on the x-axis into the entirety of the real line (although most visibly between -3 and 3 on the y-axis). It's very important to understand visually what this function is, to avoid confusing it with any other related function.

If you want to do this in Visual C++, then the Boost Math library (written by John Maddock and Paul Bristow) will do the needful.

Boost implements a generalized version of this, using the notion of Quantiles. A quantile can be thought of as the inverse of a Cumulative Distribution Function, returning a value x such that cdf(dist, x) == p. The quantile is also known as the percent point function, or percentile, or the lower critical value of the distribution.

Summary: Quantile = Inverse CDF

To understand the Boost API, we should also understand what is the complement of the cumulative distribution function. This is the probability that a variable take a value greater than x.

Thursday 12 July 2012

Operator Overloading in C#

A feature from C++. Operands can be custom classes or structs. syntactically just a static method with keyword operator immediately preceding the operator to overload, then the operand params. Exs. +, -, ++, % (modulo), == etc.

Example from MSDN:
public static Complex operator+ (Complex c1, Complex c2)

If you are implementing your own collection classes, you may want to add support for subscripting into the collection. In this case, you cannot "overload" the subscript operator, but instead must create an INDEXER.

An indexer works as follows.

class MyCoolCollectionWithIndexerSupport<T>
{
   public T this[int i]
  {
    get { return _arr[i]; }
    set { _arr[i] = value; }
  }
}

(this is an interesting use of the this keyword. commonly this is used to refer to the current instance of a class, and as a qualifier for variables within a class. static member functions do not have a this pointer).

Friday 29 June 2012

Isolated Applications: The Role of the Manifest FIle

To quote MSDN "An application is considered an isolated application if all of its components are SxS assemblies" (actually this applies to private assemblies too).

Concept One: Full versus Partial Isolation

Fully isolated applications rely solely on SxS assemblies. Partially isolated applications use a blend of SxS and "regular" assemblies.

Concept Two: Insuring against Breakages

The concept of isolated applications exists to prevent applications from breaking due to the installation and uninstallation of other applications using shared libraries.

Concept Three: The Role of the Manifest File

Manifests are XML files that go alongside SxS assemblies or isolated applications, containing information that has traditionally been stored in the registry e.g. COM classes and interfaces. SxS assemblies are not installed in the registry - dependencies are specified in manifest files.

C# Reflection - Dynamic Method Calls

The Type class is very important. It allows you to access METADATA relating to a type - this is very useful. For example, if you need a program to call a method, where the method name is called dynamically. Type is the root of the System.Reflection hierarchy.

That Good 'Ol String[] args!

OK, so you want to write a command-line program. It can't be a  very flexible / interesting program if it doesn't accept some command line parameters.

But how do you handle common issues (like optional arguments, for example). Is there an elegant way to process these in C#?

You could do separate cases e.g. if args.length ==2, 3 etc. do something different.

The Folly of Dictionary.Keys()

Keys is a property on the Generic Dictionary object. Trying to use it like a method will result in a "non-invokable member xxx cannot be used like a method". Other properties on Dictionary include Values (which interestingly returns a "ValueCollection") and Count (returns an int).

Wednesday 20 June 2012

Gaining a Strong, Technical Grasp of Web Services Concepts (aka Why Soap?)

One must know web services concepts if one claims to be a Windows programmer in this day and age. Here are the most popular concepts that any self-respecting Windows don would be able to define at the drop of the hat.

(I know we've been talking advanced stuff about WSDL etc in these blog posts but let's just do some CONCEPT CONSOLIDATION of web services now, just as a REFRESHER).

Q1. WHY is XML so important for web services?
XML is used as a data interchange format for web services. It is what the SOAP protocol is based on. It's human readability allows for easier diagnostics and human reading of web interfaces, or web exposed interfaces.

Q2. What is THE SOAP PROTOCOL. What makes it so SPECIAL in WEB SERVICE WORLD?
SOAP is mentioned everywhere in web services. SOAP is a protocol for exchanging TYPED information across the web. The phrased TYPED INFORMATION is most crucial. This is what enables us to define how to access SERVICES, OBJECTS and SERVERS in a platform-independent manner. That's the SECOND important point about the SOAP protocol, the PLATFORM INDEPENDENT nature. So, to recap, "TYPENESS" and "PLATFORM INDEPENDENCE". These are two key characteristics of SOAP protocol.

Q3. While we're on this topic. we might as well mention WSDL.
Used to declare the web service interfaces; return types and so forth. It's the XML grammar underlying these definitions.

Q4. What is UDDI?
Some kind of web services global registry concept.

Saturday 16 June 2012

Basic OpenGL Concepts for C# Programmers

Q. Ok, C# programmer, so you think you know OpenGL, do you? So, tell me, In what sense is OpenGL a "client-server system"? Hurry up, I haven't got all day!

A. OpenGL is a client-server system in the sense that your application is the "client" and the OpenGL implementation of your machine is the "server".

Q. What are these functions that begin with glut? e.g. glutInitDisplayMode?

A. Cross-platform functions from the utility toolkit.

Wednesday 6 June 2012

The Tao of Open GL in C#

Open GL'ing in C# can be done using the Tao Framework. It is recommended by game programmer Daniel Schuller in his book on C# Game Programming. An interesting alternative to Tao is OpenTK which is also a wrapper for OpenCL (Open Computing Language - created as a response to GPGPU) and OpenAL (a 3D audio library that complements OpenGL) - the three basic objects of which are Listener, Source and Buffer.

If you know C# and want to absorb only OpenGL knowledge, try the OpenGL Programming Guide (already in its Eight Edition) by Dave Shreiner et al.

Visual Studio Stinky Defaults (DFCP)

Explore the Stinky default Visual Studio project. It basically makes things (like namespaces) stop working.

Are Unit Tests in MSVS 2010 Ready for Prime-Time?

What happens when you create a new Visual Studio Test Project is TWO FILES get automatically generated. These are:
  • project.vsmdi
  • Local.testsettings
which appear under a "Solution Items" folder. The vsmdi is an XML metadata file which stores information about the tests list. Unit tests are stored in .cs files and web performance test files have the suffix .webtest, and .generictest for the "generic test" test type (kind of a "wrapper" for other tests). We'll focus our scrutiny on unit tests, giving scant attention to the so-called "generic tests".

FYI MSVS is a little rigid when it comes to unit testing. Whether you choose to use its features is something only you can decide. MS also have a product called MTM (Microsoft Test Manager) sold separately from Visual Studio main-line. Do you really want all that yarn or maybe just stick with nunit - the original TDD product for Dot net. To learn more about TDD, you may want to glance at the haphazard (but useful!) wiki entry on the same.

Tuesday 17 April 2012

Why WMI is cool

get mgmt data from remote computers

unsecapp.exe

There are strange exe's running in your Task Manager, and unsecapp.exe may be one of them. It describes itself as a "sink to receive asynchronous callbacks for WMI client application". WMI is Windows MANAGEMENT instrumentation where management in this context means "sysadmin" or more fancifully "system management".

Sunday 1 April 2012

The WPF Learning Curve

"Going from WinForms to WPF requires a major mental adjustment" - Josh Smith

Wednesday 21 March 2012

Audio CDA Files

CDA stands for Compact Disc Audio. CDA files are created by the Windows CD driver - they are representations of what's on the disc and are not actually on the CD! CDA files are all a magical 44 bytes in length and contain a Windows shortcut allowing access to audio tracks. Working with CD audio you must first convert to WAV or MP3 or some other format that computers understand.

Thursday 16 February 2012

Control Templating in WPF

Here's an old, but on-topic, blog post, summarising Control Templating and the Visual Tree concept in WPF.

Going Native 2012

"C++ is two halves: Core language: your pointers, integers, floating point and Standard Library, on which users actually build their programs". C++ is still the best choice for high-performance code that needs to be ROBUST. Check out these talks. Also, for comparison, check out Anders' C# talk on C# Five-Oh and writing "asynchronous Metro applications".

Saturday 11 February 2012

What are DEPENDENCY properties in Silverlight?

Remember, that Silverlight is a mere microcosm of a bigger library known as the behemoth WPF. So when we discuss the Silverlight property system what we are really talking about it just a small subset of what might be known as the "WPF" property system. So there you go.

The Silverlight property system (TM) provides ways to EXTEND the CLR PROPERTY SYSTEM. You all heard that, right? We are EXTENDING THE CLR PROPERTY SYSTEM. Great. A dependency property is, quite simply, a property that is backed by the SL property system is most appreciatingly known as a DEPENDENCY PROPERTY.

Dependency properties, as their name suggests, are fundamentally about dependencies. We want a property to AUTO-COMPUTE based on the value of other properties. In this way, we might think of dependency properties, as nothing more than the oh-so-ordinary appellation called "dependent" properties, but we call them more fancy names, like "dependency" properties. "Dependency" does sound a lot cooler than "dependent".

Some rules of the game: a dependency property must be on a DependencyObject. They are usually public static and readonly members.

Please explain the WPF concept of DATA TEMPLATING

A very good question. Now you are understanding what it takes to be a WPF master. You CAN get away without understanding this concept, but you will NOT be a master. It is part of the knowledge base relating to "WPF Styling and Templating".

Practical, simple example of DATA TEMPLATING. You have a ListBox and want to configure how items are displayed in it. You can define a DATA TEMPLATE within the ITEM TEMPLATE tag (ListBox.ItemTemplate) within the "SCOPE" of the ListBox. The formatting declarations would then appear within a tag entitled <DataTemplate>. We can also define the DataTemplate within the Resources section of XAML to make it a reusable object. The DT defines HOW DATA APPEARS including appropriate bindings for textual information, borders etc.

The Healing Power of Programming = Less Target and More Journey

Programming is a practical and special skill. Once a specialist technique is mastered it can be re-used. Programming is time-intensive in terms of learning and presents a moving target. Sometimes programmers feel as if contending with a landslide as development infrastructure changes under their feet. More effort seems needed to achieve the same results achieved previously with less effort. But this is the learning cycle. New, more powerful, more general abstractions arrive with the ultimate aim of empowering you the programmer - not to take your freedoms away. Case in point is the evolution of the DataGrid or the evolution of DAO, ADO and ADO.NET. New paradigms mean old abstractions may at times need to be revamped totally to fit the new abstraction. People's minds need to be reformulated to orient themselves with the new paradigm. This requires fluid adaptation and tai-chi like re-harmonisation skills. It is like the separation of continents or coming or going of an Ice Age, no less. It may take time and so patience, and persistence too, is necessary. The healing power of programming relies on acceptance and enjoyment of the process of change, not fighting it, not resenting it, but appreciating it. Focus less on the target, though keep mindful of it, and focus more on the incredible learning journey and the learning process - you will enjoy it more. Failure to hit the target (due to necessary time spent learning and re-adapting to the new development landscape) should not be a source of frustration, though often is as ego enters and the anti-programming devil says: "why is this taking longer than what it should". Answer: Adaptation. Understand, appreciate and acknowledge. This is part of the healing power of programming. The commercial animal must be mitigated by the absolute acceptance of transitional learning phases - the tiger must relearn how to hunt.

Silverlight's DataGrid Class - The Third Incarnation of DataGrid

The DataGrid, like Microsoft's data APIs, is in a state of constant evolution. "Nous avons vu" le DataGrid of WinForms fame, followed by DataGridView (recall for one moment the software built in those paradigms), and now behold the DataGrid of Silverlight and WPF (formerly from WPFToolkit.dll). It is also known (via it's fully qualified namespace admonition) as System.Windows.Controls.DataGrid. It's XAML opening tag is <sdk:DataGrid>. Come, let us learn to think in DataGrid (la nouvelle DataGrid rather than Winforms DataGrid of yore)!

Let us begin with an elementary question. How doth one define the columns of la nouvelle DataGrid? Answer: via DataGridTextColumn, or via DataGridTemplateColumn.
To understand the latter, one must know about DATA TEMPLATING (fundamental WPF concept - so fundamental one cannot claim to be a WPF master-programmer without a detailed knowledge of the same, much like the mega-foundational concept of DEPENDENCY PROPERTIES. We will repeat now the WPF mantras once more for consolidation: DATA TEMPLATING. DEPENDENCY PROPERTIES. YEAH. Such great concepts.

Formatting tricks such as alternating row backgrounds, ability to show and hide grid-lines and scroll bars are all part of the standard DataGrid "bag of tricks". Let the GUI be with you. Always.

Resharper Stinks

Resharper is a very good concept and aims to do wonderful things (similar to IntelliJ in the Java world). It can even assist you in writing code by suggesting subtle and smart improvements. But, the keyboard shortcuts can get confused with the "natural" Visual Studio shortcuts and it can make your IDE extremely slow, particularly if you are working on a large codebase and have other, more essential, add-ins installed in your Visual Studio environment.

The Last Word in Word Wrap Options in WordPad

There's more than one type of "word wrap" living in View->Options in WordPad. These are: No Wrap, Wrap to Window (preferred) or Wrap to Ruler. Basically, you want "Wrap to Window" so that word wrap adapts to resizing of the window.