##[18] y dotnet hasn’t caught on #enterprise-focus

Don’t spend too much time about this unless considering to take up c#.

In 2012/13 I invested my time into c# just in case c# would become more widespread and high-paying. However, after 2013, I have not noticed this trend strengthening. If I have to guess why, here some personal glimpses:

  • web-GUI — Rise of alternative user interfaces such as mobiles and javascript-based web UI, etching away the strongest stronghold of C#. Nowadays, which new build chooses a fat client built in swing, javaFX, winforms, WPF or Silverlight? Fewer and fewer, to my surprise.
  • Linux — Maturity and further performance improvement of Linux machines compared to windows machines. For large server side apps, or cloud apps, I see more and more adoption of Linux.
  • Java@server-side — (in financial sector) Strengthening of java as the technology of choice on the server side. c# made a valiant but unsuccessful attempt to dethrone java in this game. Java may have limitations (do we know any?), but somehow the decision makers are not worried about them.
  • Open source — there’s continuing community effort to improve the java ecosystem (+ python, javascript, c++ ecosystems). C# is losing out IMO.
  • C++@windows — (My personal speculation) I feel c# offers higher performance than java on windows machines, but vc++ is even faster.

Among ibanks, the main reasons for the current c# situation are 1) Linux 2) web-GUI

— Some update based on Wallace chat.

I think 1) microsoft stack, 2) jvm stack and 3) web 2.0 stack all have vast ecosystems, but at enterprise level, only microsoft^jvm

How about server side c++ or python? much smaller mind-share.

Wallace said on Wall St (where he worked for 5+ years) he knows no ibank using c# on the back-end. Wallace believed Unix/Linux is the main reason.

How about outside ibanks? Wallace said c# back-end is not so rare.

c# delegates – 2 fundamental categories

Update: java 8 lambda. [[mastering lambds]] P 5 mentions AA BB DD as use cases for Command pattern

AA — is the main topic of the book
BB — https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
DD — http://www.oracle.com/technetwork/articles/java/lambda-1984522.html and http://www.drdobbs.com/jvm/jdk-getting-a-head-start-with-lambdas/240008174

Today I finally feel ready to summarize the 2 usage categories of c# delegates. If you are new like me, it’s better to treat them as 2 unrelated constructs. Between them, the underlying technical similarities are relevant only during initial deep dive, and become less important as you see them in various patterns (or “designs”).

In java, these features are probably achieved using interface + other constructs. Dotnet supports interfaces too, but in some contexts offers more “specialized” constructs in the form of delegates. As shown below, in such a context interfaces are usable but less than delegates.

Most tutorials would start with unicast delegate, without the inv list.

Coming from a java or c++ background, you will want to find a counterpart or close equivalent to delegates. Almost hopeless for BB. For AA there are quite a few, which adds to the confusion.

AA) lambda as function AAArgument
* I believe compiler converts such a lambda into a STATIC method (there’s really no host object) then bind it to a delegate Instance
* often returns something
* Usually _stateless_, usually without captured variables.
* predominantly unicast
* Action, Func and Predicate are often used in this context, but you can also use these 3 constructs as closures, which is a 3rd category beyond AA and BB
* Domain? Linq; functor argument as per Rajesh of OC
* Before java 8, often implemented as an interface or an anonymous inner class

BB) event field Backed by a multicast delegate instance (See other posts on “newsletter”)
* Usually NON-STATIC methods, esp. in GUI context
* Usually returns void
* A callback method is usually _stateful_, because the callback method often does its job with “self-owned” i.e. this.someField objects, beyond the argument objects passed in
* event is a pseudo _f i e l d_ in a class. Static field or non-static field are both common.
* Domain? GUI + asynchronous WCF
* we must register the callback method with the event source.
** can lead to memory leak
* in java, implemented by several callback Objects supporting a common interface (cf swing)


Some of the other categories —
CC) CCClosure — stateful, seldom passed in as a func arg
DD) thread start
EE) Passing in a delegate instance as a function input is the lambda usage (AA). How about returning from a function? P83 [[c#precisely]] shows examples to return an anon delegate instance. This is an advanced and non-trivial unicast use case. The underlying anon method is usually static and stateless

In a source code with AA, we see lots of custom delegate Types created on the fly.

In a source code with BB, delegate Instances take center stage, since each instance is assigned to a … pseudo field. The delegate type is less complicated.

enough c# mileage accummulated@@

Your mileage will show in IV and in projects, but IV is way, way more important than real project performance — You only need to be barely competent to get your job done, solving common problems at your pace (though at Baml my own pace was slower than other team members). No need to be competent to solve all tricky problems, some are too tough for everyone. But you better ace the IV.

– – I still feel less familiar with some everyday tasks than my c# veteran colleagues.
– – i did rather few complete projects like Guardian and many enhancement projects. In contrast, veteran c# guys did more big projects. The number of years isn’t as important as complexity and variety of challenges. VARIETY — for eg a web dev expert (or a DB-centric c# coder) isn’t really a complete c# expert.

– – wpf is a specialized skillset, like swing, or web dev or sockets. I didn’t get a lot of wpf hands-on mileage yet.
– – wcf is another specialized skillset. I lack mileage.
– – assembly, appdomain, GAC

= = people agree that I can get my job done and meet most technical challenges, even if non-trivial. (“tactical”)
= = explaining, justifying my design choices – not always convincing. Not only c#, but java too.

= = excel integration is one of the most valuable among the specialized c# skills. I have some experience.

+ + When presented a new c# challenge, when pushed to the frontier of my c# know-how, I am competent to construct a basic “infrastructure” and then search on-line for the missing pieces to complete the loop meeting the challenge

+ + competent with most everyday troubleshooting.  Some troubleshooting is beyond my current skill but I feel many are hard for my veteran colleagues too. If my colleagues can solve 50% of the tech problems, then my level is close to that. This competence comes from mileage i.e. real world projects. The more projects one takes on, the more competent.

+ + like Venkat, I did practice with some hot c# features like threading, closure, remote debugging …

+ + much more confident with MSVS than before. Perhaps comparable to my Eclipse confidence.
+ + on some of the hot but purely theoretical IV topics (fake mileage), I have read up quite a bit and appreciate their nuances. I can follow most discussions on these topics –
*GC, dtor, finalizer
*threading
*value/reference types
*dynamic type

## some of my c# dotnet achievements

1) home-grown web server to download any file in the local file system – essentially my invention, as no one in the team know how to do it

GUI – full ownership

stability improvement in the microagent and Guardian server

Bloomberg piece – no one dared to touch it given the complexity

Excel add-in

Created many windows services

dotnet must convert your source code into machine code

You know that Java and c# convert (Phase 1) your source code into IL bytecode, but it must still become (Phase 2) machine code before it can run on the processor, under supervision of the VM.

In Phase 1, the Intermediate Language compiler (javac or csc.exe) converts source code into platform-Independent IL bytecode, packaged into physical files — class files, jars or assemblies in extended PE [1] format. Note Phase 2 would produces no file.
** Unlike a C++ object file the IL files aren’t strictly executable on the Real Machine. Executable on the VM installed in the Real Machine.
**The most attractive feature of the JVM lies in the platform-independent bytecode. Write once run anywhere (including Mac, Linux, etc) with decent performance comparable to C. That’s why we could (unbelievable at first) build jars on windows and run them on unix.

In Phase 2, the JIT compiler converts IL bytecode into platform-dependent, CPU-specific machine code.
** presumably, happens at run time, each time you execute the IL files
** Is there a command line tool to run JIT compilers and produce the native executable file? Look at ngen.exe. Even if you can get the native code it is designed to execute within the VM

Phase 2 is less visible. When app developers talk about compilation, they mean Phase 1

Phase 2 is platform-specific. Phase 1 is platform-independent.

Regular assembly file holds IL code on disk. Upon first use each method is JIT-compiled to platform-dependent machine code. So if you monitor the execution speed of such a method, you see
app launch – slow – fast – fast – fast …app launch – slow – fast – fast …app launch – slow – fast – fast …

Now, ngen.exe dose a pro-active JIT, so the native machine code is saved on disk in the GAC and/or native image cache. The same method would show no “slow” —
app launch – fast – fast – fast …app launch – fast – fast – fast …app launch – fast – fast – fast …

It’s interesting to compare perl. I believe perl also compiles source code into bytecode, which gets interpreted.

For python, see http://stackoverflow.com/questions/471191/why-compile-python-code

[1] for the PE format extended for dotnet, see other posts in this blog, or see http://www.informit.com/articles/article.aspx?p=25350

dotnet IPC implemented by eventvwr, perfmon

Though this post is about dotnet, it is likely to be also applicable to non-dotnet apps.


You can create/delete custom event logs. The 3 built-in event logs (app, security and sys) can’t be deleted. All of the above are viewable on eventvwr.exe

Except security log, all other event logs are writable – including app, sys and custom event logs. I feel this is a simple way to implement basic application logging in dotnet. The EntryWritten event firing feature looks neat.

Further, it looks like multiple (Local) processes can subscribe to the same EntryWritten event, so you could perhaps coordinate 2 processes using EntryWritten — IPC

You can even access remote event logs.


Perf counter is Another simple IPC mechanism. You can create custom perf counters, visible to other processes + perfmon.exe.

Since one process can update the counter and another process can see it in real time, it’s IPC.


I have yet to implement IPC this way.

WCF (and related) jargon, a short list + 1-line notes

background — I used wcf many times but a clear understanding doesn’t come automatically.

See other blog posts about the “Service” jargon.

A TYPICAL wcf service is characterized by these items
– always remote;
– always requires serialization across network
– always uses a public url (part of the so-called service endpoint)
– protocol — typically http or tcp
– serializer/formatter/encoding — typically xml or binary
– channel
– there must exist a local proxy INSTANCE for some remote “object”, though the “service” concept isn’t strongly object-oriented.
– hosting process — any process that stays up, such as —
** console host
** winforms, wpf
** windows service (similar to linux daemons, visible on services applet)
** web server

A wcf service must be hosted — basically a server process. In contrast, the client process can be short-lived. The host is the realization of a lot of the above abstract concepts.

wcf and soap? wcf is frequently implemented using soap + other technologies

wcf and the remoting technologies? see separate post

http web service in async mode@@ #YH

I think in my dotnet client/server system, we use WCF duplex extensively, meaning the server can push updates to the clients. Each client must subscribe though. I think this is exactly event-driven as you said.

I remember that if I put a break point in the client’s updateReceived() callback method, it gets hit automatically, without the client polling the server.

WCF duplex is a standard and mature feature in microsoft WCF.

The server endpoint uses https, and I believe it’s a web service.

Is it possible that the server push is implemented actually by client poll under the hood? I don’t think so. There’s a polling duplex ..

See http://msdn.microsoft.com/en-us/library/cc645027(v=vs.95).aspx

dotnet eager root collection

[[Pro .net performance]] P95 real example illustrates that Even Before a local variable goes out of scope, the GC could figure out the object behind it is no longer needed and reclaim it.

 

Debug mode – no surprise

Release mode – eager! Use GC.KeepAlive(theLocalVariable) to fend it off.

__Tan Bin (+65)6530 1386 OC Centre #17__

 

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.

c# coding drill for IV

These questions will seldom hit the phone round…

Q: Implement IEnumerable foo(IEnumerable aa, IEnumerable b) such that foo returns string in either aa or b but not both.

To keep things simple, let’s assume aa holds unique elements, and b too.

Q: regex engine supporting quantifier “*”, and the wild-card “.”
Q: IteratorTest from MS
Q: circular buffer
Q: reverse a linked list in-place
Q: rotate a long array by 3
Q: spreadsheet concretization

(610610 blog has a letter to XR, which shows a list of coding practice projects I completed.)

memory leaks in one WPF/Silverlight app

The app has multiple screens (windows). A user can open and close them throughout a login session.

The acid test – when we close a data-heavy window, actual memory usage (not the virtual) should reduce. In our case, memory stayed high. In some cases it reached 1G+ and the entire application crashed. We fixed the issue – capped at 300M.

The leaks and the fixes

* Event registration was found to be the #1 category. In window OnClose, a lot of clean-up was needed. Release references, unregister events.

* Dispose() method was added to many classes.

some random comparisons – wpf ^ swing

I'm no expert. Just some observations of a newbie

* jtable vs grid

* dependency property, attached property – fundamental in wpf. No counterpart in swing.

* events (field-like delegate fields) are used throughout wpf, not only for event-handlers on a visual component (like button's mouse-click)

* the containment hierarchy is central to wpf command routing, event routing, property inheritance, and data binding. In swing, ……

* property change listener is another area to compare

* declarative programming via xaml? Many basic functionalities of xaml can be achieved in c# code, which looks like swing code.

* routed event? How does swing handle it?
* commanding? No such feature in swing.
* in both technologies, a visual object comprises many constituents.

AttachedProperty – clarifying questions

Attached Property is a tricky construct. When confused, a beginner (like me) could ask a few key questions

Q: Which class (not “object”) defines the AProp?
Q: Which object’s (not “class”) hashtable holds the property value?

The holder object is the visual/screen object “decorated” by the property value. Just like Opacity, “Dock.Left” describes some aspect of a visual. The “provider” is a class not an object. The AProp provider class is like a category or namespace, and tells us what category this property falls into. Is it a docking property or a text formatting property?

Any AProp (or any DProp) data can be seen as a key-value pair. In the Dock example, an OKButton’s hashtable holds the value of “Left” under the key DockPanel.DockProperty. Note the property is “specified” or “defined” not by Button class but by the DockPanel class.

After the OKButton saves the “Left” value, the natural question is who reads it? Answer — The container. In this case, the user of this property happens to be an instance of the provider class — DockPanel. In some cases, the user is unrelated to the AProp provider. You can even attach a nonsensical property to a nonsensical object, so the property value is never used.

dispatcher ^ dispatcherObject in WPF — some simple tips

Probably a low-level detail we seldom need to know. Don't spend too much time here.

See P928 [[Pro WPF in c#]]

I feel DispatcherObject means “UI object under a UI dispatcher”. Every visual (including Button) derives from the type System.Windows.Threading.DispatcherObject. See http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.asp

DispatchObject as a base class also offers the popular methods
– this.CheckAccess() and

– this.VerifyAccess()

Every DispatcherObject (including myButton) has a this.Dispatcher property, whose type is  System.Windows.Threading.Dispatcher

size of a CLR (c# etc) heap object

(JVM is probably no different. See the post on Java) [[.NET performance]] circa 2012 shows a layout of a typical CLR heap object containing some simple custom fields.

–32-bit machine (4-byte alignment) —
For a no-field object, Logically 8 bytes needed = sync block + vptr. However, 12 bytes used in reality. No explanation given.

Due to memory alignment, For an object with a single small field, it’s 12 bytes. Small means a byte, bool, or pointer etc.

–64-bit machine (8-byte alignment), basically everything doubled
For a no-field object, logically 16 bytes needed. In reality? Not sure.

For an object with a single small field, it’s 24 bytes.

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.

y minimize code behind xaml

I feel this is a valid question. Many wpf designs make this a high priority. It takes extra effort. Why make the “sacrifice”?

Code behind is a melting pot paradigm. In contrast, code in VM, M and command classes are far easier to read, test and modularize. They are often much shorter. These classes often have very few members. To a certain extent, I would say the more classes you use to organize the code, the better — imagine all of these logic put into one class — the code behind:(

See also http://stackoverflow.com/questions/3878610/why-keep-code-behind-clean-and-do-everything-in-xaml

Codebehind is considered part of Xaml and in the View layer. The code logic in CB is married to the view and not Reusable.

It’s considered best practice to
– move stuff from code behind to xaml or
– move stuff from code behind to VM or other c# classes

The reverse is usually easier — quick and dirty, sometimes clever manipulations to achieve an effect. These manipulations done in CB tend to be messy and not modularized or compartmentized.

tricks – wpf/swing IV

As my friend Guillaume pointed out, a lot of GUI know-how fall into the “tricks” category. Just open any cookbook on WPF/swing. (Let's not elaborate why GUI technologies have this commonality.)

Q: How would you deal with “how-would-you” interview questions ☺

A: prioritize according to rarity. Avoid those tricks less widely needed

A: prioritize among the visual components by rarity. jtable is by far the most used jcomponent in swing. I wasted a lot of time over text-related components.

A: real time application and related tricks are priority

A: memory management is priority but there are no feature “tricks” here

A: prioritize according to layer. Some knowledge is fundamental and used in a lot of tricks. Perhaps browse some books

*dispatcher/EDT

*dependency property, attached property

*event handler

xaml resource dictionaries – a few pointers

What's the confusion with RD elements “” and WR

elements “”?

1) All these elements define an INSTANCE of the ResourceDictionary

class. If you see 5 chunks of it in a xaml, then in the VM there will

be 5 instances(?).

2) I believe most visual controls have a non-static property

Resources, of type ResourceDictionary. Therefore Each layer on the

containment hierarchy should offer a ResourceS field, often empty. You

can populate it like



See http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.resources.aspx

3) This “Resources” field often encloses a RD element, instantiating

an RD instance. Often the element simply define the

key/value pairs, without an RD layer — Confusing.

4) The resource dict instance at any Container level is available to

be shared by the children. The highest level is probably Application

level, but i usually use the Window level. That meets my basic needs

of sharing a resource.

[[wpf succinctly]] points out

You can create a resource dictionary at the Application, Window, and

UserControl levels. A custom RD allows you to import your own C#

objects to use (and share) in XAML data binding.

A common practice is to put your view model Instance in a window-level

RD. See [[wpf succinctly]]. This resource must be defined before it's

used as a data context.

ObjectDataProvider, learning notes

I feel ObjectDataProvider is an unsung hero….

One of the usages is binding to non-static method of some stateful util class. See also [[wpf recipes in c#]]. First you need to put an instance of your class into a resource dict. ObjectDataProvider element with an “ObjectType” attribute would instantiate it.
It's useful to put an instance of your stateful util class into the window's resource dict. You can later use it in many ways (won't elaborate). Without ObjectDataProvider, the instance is constructed by the default ctor — serious limitation.

wpf – suppress a keyboard/mouse event

… standard events like MouseDown, KeyUp.

P682 [[wpf recipes]] presented a surprisingly brief yet complete solution. The sample code takes fewer than 10 lines of xaml and c#,

but it's good to point out the salient features —

– no command, just routed events

– this technique requires a containment hierarchy, which exists in every WPF window

– If you want to suppress an event within a container, then apply the trick at that container level

– Trick is on the Preview tunneling event

wpf topics for IV, Proj

–IV + proj
prism
button
Grid
TextBox
layout?
data templates
triggers

–IV
dprop (dependency property), aprop (attached property)?
styles
routed events
routed commands
logical ^ visual tree

—–proj
items control
resource dict
user controls
debugger
containers – details
event handling – deeper
various common controls
bind to a method

command methods using VM — a few observations

In most of my projects, my commands inevitably need access to the VM. The Execute() and CanExecute() all need to access the VM. (See

other posts why VM is one of the top 3 players in a command set-up.)

Q: how does the command methods get a handle on the VMs? I know more than 1 technique.

A: [[wpf succinctly]] shows that in xaml, we can pass the VM as CommandParameter into the Execute() method

A: ctor injection — VM is constructor-injected in the command instance.

In a way, the command objects and VM objects are inter-dependent.

0) The VM often exposes the command as a CLR property, to be accessed by the xaml “Hollywood”

1) The command methods directly uses the VM object.

To reduce coupling, perhaps we can introduce interfaces. Necessary?

a little trick to avoid ViewModel referencing View #tight coupling

In my project a view model’s method VM.RepaintColors() needs to modify a View object DataGrid.

By basic OO principle, we know views “depend” on ViewModels, so ViewModels should not depend on (or directly edit the properties of) Views. When a data change needs to bubble up to view, we use the event infrastructure to notify the binding system to re-query the ViewModel objects.

Therefore my design above was a violation – VM.RepaintColors() directly manipulates DataGrid. I eventually solved the problem using event notification. RepaintColors() was moved into MainPage.xaml.cs i.e. the code behind class (I know this is anti-MVVM but still an improvement). As part of the view, CodeBehind (CB) class has full access to all ViewModel objects and View objects. Therefore if the original VM. RepaintColors() implementation need any field of the VM object, it still has access.

Remember the VM used to call this.RepaintColors() inside its various methods. Now with this change, it must fire the event RepaintColorsNeeded. This would notify the listening  CodeBehind and trigger CB. RepaintColors() method. The hook-up is by event registration —

Right after the CodeBehind instantiates the VM, it registers CB. RepaintColors() with the VM’s RepaintColorsNeeded event.

Note despite the notation in this write-up, RepaintColor() is always a non-static method, and uses the non-static fields.

collection view ^ collection view source, my take

My conclusion — many constructs in this space have limited practical value — CV base type, CVS.

http://www.zagstudio.com/blog/466 is an authoritative comparison.

* CVS (not CV) can be constructed in xaml.
* CV and CVS can both be used in c# cod, but i feel almost *always* we only use a subtype of CV.

CVS is designed to support __simple__ custom sorting/filtering etc directly in xaml. First You inject the collection into your CVS instance, then secondly you retrieve the view from CVS and inject the view into the visual (items control). A CVS instance is a wrapper over 2 objects
– The physical collection (often an ObservableCollection)
– A CV (or subtype) object

I guess a CV baseclass instance isn’t terribly useful if you want any customization — see below. Instead, you either use a CVS or a CV subclass instance
– For __simple__ sorting, use cvs in xaml
– For sophisticated sorting that demands c# coding, cast the CV to one of the 2 subclasses. This is the standard and natural choice.

http://www.zagstudio.com/blog/441 seems to agree with my guess.

As other authors pointed out, we should and could avoid using a view that’s a CollectionView base type — poor performance, no sorting/grouping. A subtype like ListCollectionView is always preferred. This is easy as most of the time, physical collection is some kind of IList. Therefore, whenever we retrieve the view as a CV, we almost always cast it to a subtype.

define a custom attached property

Once we reach a basic understanding of something sophisticated like Attached Property, looking at a custom AProp implementation could bring us to the next level.

http://msdn.microsoft.com/en-us/library/cc903943(v=vs.95).aspx points out

“If your class (the Provider class) is defining the attached property strictly for use on other types, then the provider class does not need to derive from DependencyObject. But you do need a DependencyObject as the method parameter in the getter/setter.

Define your attached property as a dependency property by declaring a public static readonly field of type DependencyProperty.”

Content vs Resource in a WPF build (MSVS)

If your wpf app needs to access a file (like my.jpg, or my.xml or whatever), you can include it with MSVS build-action CONTENT or RESOURCE.

1) RESOURCE (Avoid “EmbededResource” –  irrelevant) – will embed it in the assembly. No more separate file my.jpg in deployment.

2) CONTENT – will not include it in assembly but somehow registers (relative path to) the “loose file”. In the deployment, we usually put the loose file in the same folder as the assembly, so the application can reference this file with the bare name.

3) Sometimes you are lucky to get away without telling the builder about the file . Not recommended. As far as possible, any file needed by the app should be “included” somehow.

4) However, if the file name is known only at run time then it’s technically impossible to “include” it at build time. Must try other tricks.

DProp ^ CLR prop as SOURCE of data binding

See other posts on INPC. This is just another quick learning note.

You need INotifyPropertyChange if you use a regular property as Source of data binding. The host class (usually a VM) need to

implement INPC. Otherwise, changes to the property won't show up.

Is INPC required if the source is a DProp? I don't think so.

If you bind a regular collection (as Source) to an items control, then the collection class must implement INotifyCollecitonChanged,

otherwise add/delete won't show up. ObservableCollection is a subclass.

AttachedProperty # first lesson

AProp is one of the sophisticated features in WPF IMHO. First get a grip on DependencyProp (DProp) — see other blog posts.

–motivation for AProp–
If you want a concrete justification for AProp, look no further than Dock. Many top top WPF experts pick Dock as the showcase of AProp. Don’t read about StackPanel or FontSize. Don’t both with inheritance – we will deal with them much later.

Focus on #1 usage. Don’t bother with the #2 or #3, such as the “inheritance” or the “service” patterns in http://msdn.microsoft.com/en-us/library/ms749011.aspx#howused

Spend enough time and go deep enough to understand the Dock usage, before digging deeper.

Here’s the Dock usage outlined on MSDN. “The DockPanel.Dock property is created as an attached property because it is designed to be set on child controls within a DockPanel, rather than on DockPanel itself. The DockPanel class defines the static AProp named DockProperty, and then provides the GetDock and SetDock *static* accessors for the AProp.

–storage of the AProp values–
Same as ordinary DProp. One hash table per child DependencyObject. Absolutely Irrelevant is the hash table of the dock panel.

[[Pro WPF & Silverlight MVVM]] says “Once a DependencyProperty is registered as an attached property using the DependencyProperty.RegisterAttached method, that property can be set on any DependencyObject subclass.

–how to set/get–
In xaml, the aprop “Dock” looks comfortably like any other property of the child (eg Button), but we know that DockPanel not Button defines this property. Therefore the setter has to be defined in DockPanel. A Xaml declaration would translate to

   DockPanel.SetDock(myButton, Dock.Left); //STATIC method call

Internally, this runs

  buttonArgument.SetValue(DockPanel.DockProperty, Dock.Left); //AP setter

Look at this AP Setter 3 times, 5 times until you clearly understands —

* SetValue() is a NON-static method defined in the base class DependencyObject. Internally this method uses that hash table thing. All DProp and AProp setters goes through this Choke point.
* Note the dock property is unrelated to the host object i.e. the button. This is the funny/magical thing about Attached Property.
* Physically, the button object’s (NOT the panel’s) hash table records key={theButton.type + DockProperty.name}, value=Left. This property is useful to the parent container (the doc panel) during layout. The dock panel will scan all children, querying this button’s dock property, and another button’s doc property …

MSDN said “Attached properties are a XAML concept, whereas dependency properties are a WPF concept“. The way you set a AProp is very natural in xaml but not in code.

–extreme freedom–
The top top experts like to emphasize the extreme flexibility to attach anything to anything, whether meaningful or not.

Bencon said something like “simplest way to explain an attached property is that it allows the place where the property is defined and the place where it is stored to be completely different classes that know nothing about each other. Property value can only be stored on DependencyObject objects (which happens to be the base class for most Avalon things).”

Nick said things like

“You can call panel.SetValue(CheckBox.CheckedProperty, true), and property engine will happily set that attached property to true. Doesn’t matter that nobody is ever going to try to read that property value. Doesn’t matter that the author of CheckBox probably never intended this.”

“From a property engine perspective, it’s irrelevant that Button happens to be inside a DockPanel. You could set DockPanel.Dock even if your parent is a Grid — that property won’t do any good, because Grid doesn’t look at the DockPanel.Dock property, but you can do it.”

–References————–
Bencon – http://blogs.msdn.com/b/bencon/archive/2006/07/26/more-advanced-attached-property-use-the-ramora-pattern.aspx
Nick — http://blogs.msdn.com/b/nickkramer/archive/2005/08/25/456024.aspx
MSDN — http://msdn.microsoft.com/en-us/library/ms749011.aspx#howused

gridbag-container = most versatile layout in swing/wpf

In swing/wpf, there exist 2 most versatile/flexible layout techniques — nested container  vs gridbag. It's also possible to combine the 2 techniques.

“Gridbag container” is a generic term.

* In wpf, the standard grid panel would meet this requirement.

* In Swing, we can use a JPanel with a gridbag layout manager.

* in html, we use a html table. Soon after I started using html, i realized (often nested) table is THE standard way to layout an html page.

However, popularity is different —

* in wpf, grid container is widely used and often the default container.
* in swing, gridbag container is too hard and seldom used.

button click using command ^ events, briefly

As illustrated in other blog posts (like http://bigblog.tanbin.com/2013/06/routed-events-learning-notes.html), a button click can be connected to (via xaml) a regular instance method in the xaml class (code behind), provided the method is an event handler. In this implementation, we are using a CLR event, not really routed event.

This simple design draws criticism such as tight coupling etc. There’s an alternative. Using commands, we can refactor to meet the same requirement. [[wpf succinctly]] has a simple example of this refactor.

Another book says — “In WPF and Silverlight, there are two ways to respond to user interaction: with events and with commands. Most controls will support both of these methods of interaction, but it seems more common for events to be exposed.

## xaml’s job duties in a GUI app (in broad-strokes)

#1) lay out – the controls within a “container”. Lay out each sub-panel and sub-sub-pane. Lay out each leaf-node control in each panel.
** This is also html’s main job.
** strictly a Containment hierarchy, or “object tree”, good for xml
** containment hierarchy is needed for routed command and data context

# binding – command (+event handlers) to input controls
# binding – data binding to VM, with updates in both directions
# implicitly create instance fields (aka data members) of the code behind class
# style triggers

Which of these can be replaced with c# code? See other blog posts.

wpf tree-grid (like swing tree table)

I feel treegrid is the most useful variation of a grid

http://blogs.msdn.com/b/delay/archive/2009/09/23/if-it-walks-like-a-duck-and-talks-like-a-duck-it-must-be-a-treegrid-a-simple-xaml-only-treegrid-ui-for-wpf.aspx
is a xaml-only clever solution, without third-party tools.

http://www.codeproject.com/Articles/30721/WPF-TreeListView-Control is a different xaml-only solution.

http://dotnetlearning.wordpress.com/2010/09/19/treelistview-in-wpf-containing-heterogeneous-hierarchical-data/ is another xaml-only
solution.

## most useful xaml keywords, briefly

[[WPF unleashed]] has a one-pager on xaml keywords. I trimmed the list further to just 3 —

– x:Name specifies a name for a xaml element, which would become an instance field in the code-behind class. This is mostly to make it accessible programmatically. Handy!

– x:FieldModifier defines the visibility of that field, which is internal by default. Can be public, private etc. You can specify a field modifier for each x:name

– x:Code – embeds c# code in a cdata block

– x:XData? Took me a while to find a usage example. http://learnwpf.com/post/2006/03/20/How-do-I-bind-to-XML-data-in-WPF.aspx embeds an “island” of static data in xdata, and uses it “locally” in subsequent xaml. It’s kind of nice to collocate data + visual next to each other.

xaml – declarative ^ programmatic

[[Dynamic .net 4.0 applications]] P155 claims that

“Xaml is completely optional. Anything you can accomplish in xaml, you can accomplish in source code”

If you do that your c# code will be like swing. Verbose, with large number of objects — every aspect of the visual is usually some property, represented by some object.

Biggest Power feature — you can write code to “set up” what is usually declared in xaml. Programmatic set-up is dynamic, flexible, based on user input, not hardcoded in xaml. Xaml is declarative, representing a major advancement over the traditional programmatic approach. Here we reverse the trend.

There are many more xaml techniques when we combine the programmatic + declarative. One example http://www.codeproject.com/Articles/19112/Dynamic-User-Interfaces-in-WPF

You can easily write code to access the object tree (a type of object graph), whether it’s in xaml or created by code. This access is so easy that I feel xaml format was designed for programmatic access.

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.

wpf dock panel ^ swing border layout

I don't remember the details of swing border layout. Dock panel is similar and fairly flexible.

Based on http://www.codeproject.com/Articles/30904/WPF-Layouts-A-Visual-Quick-Start

Red 1



Green 1

Pink

Blue 2

Yellow 1



Orange 1

Green 2

Note it matters which region is declared first.

– Left is declared before Bottom, so Left region swallows all real estate. The later-declared Bottom region is “constrained”.

– If we move the Bottom declaration ahead of Left, then Bottom region swallows all real estate, and Left region would be constrained.

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);
                    }
                }
            }
        }

topics in c# interviews

protobuf!
serialize? presumably
xml? presumably
generics
dynamic type?
auto-boxing
task library?
linq? yes
ado.net? perhaps too simple for many jobs
web service? yes
async web service?
wcf? prominent
GC
COM?
unmanaged code?
p/invoke?
assembly, app domain
GAC
win services? ever asked?
algo with standard data structures (c# version). This tends to be a favorite at high-end jobs. This requires
** no threading,
** no generics,
** no linq,
** no wpf,
** no wcf

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 —

WPF Commanding components – fluff^barebones

Q: Key players in a typical commanding set-up?

The 4 key players identified in the MSDN article is the perspective from the builtin commands (RoutedCommand). I’d rather /unlearn/ the whole thing because I prefer a minimalist perspective.

1) ICommand (#1) is the single most important component. Together with the ViewModel (#2) and the xaml, it can meet many simple commanding requirements, without the CommandSource, CommandTarget, CommandBinding crap.

2) For a slightly more complex requirement, I feel these are the key players —
– ICommand instance
– command source instance
– ViewModel instance
– xaml (and code behind it)
? routed command? LG2. This is more advanced. A lot of xaml commands are much simpler
? command binding? LG2 See other posts.
? command target? LG2. Needed in RoutedCommand cases.
? CanExecuteChanged? not always needed
? CanExecute() can simply return true always.
? Execute() can simply hold the business logic rather than delegating to something else

CanExecute and CanExecuteChanged provide lots of flexibility, which is often unneeded in simple requirements.

ViewModel is relevant because there’s good reason to move logic out of the code behind, into … usually into the VM. Therefore the real command logic lives in the VM classes. Specifically, the Execute() logic often involves the VM. Ditto CanExecute()

http://relentlessdevelopment.wordpress.com/2010/03/30/simplified-mvvm-commanding-with-delegatecommand/ has a simple example. It illustrates xaml, view model, delegate command… It deliberately defines CanExecute and CanExecuteChanged, but never uses them!

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);

delegate command with(out) CommandManager

Now I feel you can implement a basic delegate command with or without CommandManager. (My sample wpf application description is in another blog post.)

A) The original RelayCommand by Josh Smith uses CommandManager. With CommandManager, we developers don’t need to add InvalidateRequerySuggested() after some VM state change, since CommandManager will take care of that.

One consequence is, the CommandManager fires a hell lot of activity via (static) event CommandManager.RequerySuggested. Since our custom CanExecuteMyCommand() callback is in the inv list, it gets called every time.

B) Some prefer a home-grown delegate command without CommandManager. Event firing is better understood and less opaque than with CommandManager. However, we do need to remember to add something like MyCommand.RecheckStatus() in many places.

Here’s my guess — Since the inv list is no longer provided by CommandManager, we must provide it in our delegate command class. There’s one inv list per command instance. By contrast, the CommandManager has one application-wide inv list for all the command instances. The inv list is behind the application-wide static event.

who subscribes to the ICommand.CanExecuteChanged event@@

I put a breakpoint on the event add{} and found out exactly which object is subscribing to the ICommand.CanExecuteChanged event.

 

————— wpf_proj_readme.txt —————–

This entire wpf app has a single VM. Among other things it defines a bool method vm.CanExecuteSave(). Note VM isn’t subclass of ICommand; TanBinRelayCommand is. It’s just a generic relay command class.

 

Xaml has a textbox and a Save button. Textbox is data-bound to a string property in VM; button to an ICommand property in VM – consistency. Entire xaml uses the VM as the only data context, so all data bindings are between the xaml (visuals) and the VM (properties) – consistency.

 

This vm.CanExecuteSave() method (wrapped in a delegate) is passed in when instantiating TanBinRelayCommand, the Command object behind the button. Therefore button “dimmer” is connected to vm.CanExecuteSave() method. Later at runtime the button is dimmed when CanExecuteSave becomes false.

———————————————————–

 

Question is how does the runtime know when to requery CanExecuteSave(). The solution, as a standard pattern, is event subscription. Specifically, the button adds this.OnCanExecuteChanged() method into the inv list of the ICommand.CanExecuteChanged event.   But when is this method added into the inv list? At xaml initialization, HookCommand() performs this registration.

 

    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;

       

DelegateCommand – various sample implementations

http://wpftutorial.net/DelegateCommand.html is a simple and clean DelegateCommand class, very similar to my own. No complete WPF sample app included.

http://blog.rdeverett.com/post/812093504/wpf-delegatecommand is similar but a bit old-fashioned

http://relentlessdevelopment.wordpress.com/2010/03/30/simplified-mvvm-commanding-with-delegatecommand/ is similar

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx (MSDN) has a similar simple class named RelayCommand

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]]

c# variable naming convention

Without a context, these identifiers all look indistinguishable.

Argument passed in? arg_
Local temp variables? tmp_
Fields? Just qualify it with this.field1 or MyClass.field1
Events? Just qualify ith with this.event1 or MyClass.event1
Properties? CapitalizeFirstLetter. Actually, these are primarily used outside host class. In such cases they are fairly identifiable.

wpf commanding – web of references

Too many cross-referencing in the commanding architecture. I'd say ignore the conceptual and focus on a typical implementation. Even

at the implementation levle, Commanding involves a web of references — non-trivial.

command source (typically a visual) often not always defines a command property and a command target property.

command target (typically a visual) often not always defineds a command binding and command handlers/reactors.

UI thread restriction in wpf/winforms, briefly

This is a popular question, and also an interesting question, for the curious. [[More effective c#]] says there are 2 reasons why we need Dispatcher or ControlInvoke —

1) STA — windows controls including those in .Net use COM Single-Threaded-Apartment model
2) message pump – the author said “many” (I would think all) of the controls use the message pump

http://stackoverflow.com/questions/2222365/what-is-a-message-pump has interesting comments on both 1) and 2)

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.

wpf data binding – target Object holds the binding

One ticker (like the SPX last move direction — up or down) can drive 22 visuals controls. Each visual control is a target objects

and can have only one driver. In this case, there would be 22 binding Objects for the 22 linkages.

The binding object is injected into the target object, not into the source object. The single source drives 22 targets, so it can't

accept and hold 22 binding objects.

Remember both source and target must be properties. Therefore, one source Property drives 22 target properties. 2 of the 22 target

properties might belong to the same visual control (since one visual can have many properties like font, background…), but it's

not likely. Usually, the 22 target properties belong to 22 visual controls.

Incidentally, the source may not be a visual and may not exist on xaml. It could be a plain old property of a plain old object, but

this object needs to be visible to xaml, so xaml can bind to it. Alternatively, it can be visible to the code behind, so we can set

the binding in code behind.

LINQ – narrow moving window

Which part of linq operates this way??

—–
Imagine you can only use 1 unit of memory…. You get the narrowest possible moving window (size 1) over the “stream” of items. You can’t query how many items in total — You have to remember the past items. You can’t query the sequence for a past or future item.

I feel this is similar to SAX parser…

I feel this is similar to database drivers. When you iterate the rows from a large query, the server gives you one row at a time.

It also reminds me of the c++/java/c# stream concept, but streams consist of bytes not “composite, structured objects”

transformer blackboxes in linq

A lambda used in Linq is often a transformer function, or a converter or lookup or mapper or translator function.  All of these words describe the same generic blackbox having exactly 1 input object and 1 output object.

The 1 input object is carried by the range variable in Linq. Output can be a field of the input. Output can be another object (perhaps of anonymous class). Output can be a true/false flag…

Many Linq sequence operations “Apply a Transformer On” the input sequence.
eg: Where() applies a filtering transformer on the input sequence
eg: OrderBy() applies a sorter transformer on the input sequence
eg: Select() applies a one-to-one mapping transformer from input sequence to an output sequence

— OrderBy() —
Comparitor.java takes *2* arguments and returns a comparison result. Ditto for comparitor in STL sort(). Linq OrderBy() is a bold departure.

OrderBy() looks more like SQL order-by, specifying a sorting “key-field”.

This is the Hollywood principal like spring RowMapper. Inernally, the sorter (“the Hollywood”) will pick 2 elements from the sequence and compare that key-field to decide who wins….(imprecise language, admittedly). The only info needed by Hollywood is “which (pseudo) field to use for Ranking items”. A crude example — You can rank companies by reputation, by popularity, by profit … OrderBy() answers that question.

Therefore OrderBy accepts a transformer blackbox with 1 input i.e. the range var , and 1 output i.e. a “key” pseudo-field. Actually the field can be any value computed from fields of the input object.

SERVICE means … in WCF, SOA etc

The concept of Service is central to wcf, but the “service” word is overloaded and vague. Here are a few distinct meanings

* windows service – daemon process. I think a unix network daemon is similar. However many windows services and unix daemons aren’t exposed to the network

* web service

* a remote callable [1] thingy, like a RPC. Any remote callable would qualify as a service!
** I feel web service qualifies as a type of of rpc service.
** a network daemon qualifies too.
** I feel in wcf, “service” means something like this.

Remote means you don’t call it like calling ToString() or localtime() within the same process.

Callable means on-demand, online, like a 24-hour call center, ready to serve callers.

How is it implemented? A base form is a Function or Procedure, but frequently there are “service OBJECTs” involved. In fact, the service objects are in the official Model of a service;) but I actually feel these objects are unnecessary to the basic concept of service. Nevertheless, “Service”, WebService, and SOA are big buzzwords, and these people just love the OO jargon. I feel these jargon terms add confusion without adding value. Too much abstraction can lead to health problems;)

In WCF, there are many jargon phrases containing “service”, which is a central concept in WCF.
* service host — the Process hosting the service.
* service reference — just a fancy name for the proxy class.
* ServiceEndpoint

WCF ^ remoting, briefly

WCF and the remoting technologies are related. I feel both are umbrella technologies. Both nebulous. Both having a lot of abstract concepts and jargon.

I feel remoting as a concept is like RMI (or ejb?), but remoting as an umbrella technology also can use soap.

WCF is designed as a superset of remoting. In addition to TCP and HTTP channels, wcf added MSMQ channel and a considerably faster named pipes channel.

WCF and Remoting can coexist side-by-side.

See http://msdn.microsoft.com/en-us/library/aa730857(v=VS.80).aspx

ICommand instance CAN define actual action

When The MSDN article talks about ICommand, it only talks about one subtype i.e. the RoutedCommand. For RoutedCommand, the command instance doesn’t contain actual action, as echoed by other authors, but I am not sure if that is true across all ICommand implementations.

I think It’s possible to implement ICommand with a real Execute() method. See [[wpf succinctly]]

dotnet unmanaged RESOURCES, learning notes

(Many open questions below are a bit arcane and may not be relevant to IV or projects.)

I feel “managed” means “automatically-released”. In that case, most dotnet Objects qualify as managed “Resources”. Any time you need Dispose() in your CLASS, that’s a telltale sign of unmanaged resources.

“Resource” is a rather abstract term, best understood by example[1]. In my mind, a resource is some runtime object(s) needed by our App, something constructed and configured. Like a natural resource it is scarce, shared and rationed. Like a library book, there’s usually an acquisition “protocol”, and a return protocol.

[1] As a crude example, what’s a city and what’s not a city? Best learn by example.

http://stackoverflow.com/questions/13786570/determine-managed-vs-unmanaged-resources has some interesting comments.

–Unmanaged resource and … IntPtr + handle ?
What’s an IntPtr? Basically a struct that represents a native void pointer (or a native handle) —
http://stackoverflow.com/questions/1148177/just-what-is-an-intptr-exactly Many unmanaged “resources” are accessed via IntPtr.

–Unmanaged resource and unsafe code?

–Unmanaged resoruce and p/invoke?

–Unmanaged resource and … win32 + COM?

–some managed resources
filestream is a MR. It contains a native file handle, which is UR. It’s IntPtr, but not a integer-based file descriptor as in C/python. See MSDN.

A socket object is a MR. It contains a socket handle, which is UR and IntPtr

A DB connection is probably UR.

OneWayToSource, briefly

Logically, there are 2 sides to a (logical) binding — Source property and Target property. Both must be properties (not fields) of some class. Target must be a dependency property, not a plain property.

Behind the scene, there is a Binding object, with a Source field (not to be confused with the “source” property) and a Path field (Better rename to “PropertyNameInSourceObject”). You inject Binding object into the Target visual control. Once injected, the target visual is wired up to the source property, via the binding.

I feel target is usually a visual. Source property often isn’t a visual — it could be a plain property in a POCO object. When source property gets edited, WPF engine would somehow update the visual. That’s the plain vanilla OneWay update mode.

When used as a Target visual, some visuals default to 2-way update, like TextBox. Other visuals default to one-way update i.e. source to target.

OneWayToSource is a special mode. One reason you may need it — when exactly one of the 2 sides is a dependency property. By WPF policy that side must be the Target, whereas the non-dependency side will be Source. If you need to update the non-dependency side, you can use OneWayToSource. Imagine the non-dependency side could be a POCO object with a plain property, but you need to update it when the textbox gets edits. In summary, system automatically updates the non-dependency property from a visual control on screen.

When both source Obj and target Obj are visuals, we can often make do without data binding — use event instead.

c# bbg IV – 15minutes

Q: Can a struct implement an interface
%%A: an interface is a reference type. When casting to the interface type, you get autoboxing
A: http://stackoverflow.com/questions/63671/is-it-safe-for-structs-to-implement-interfaces shows many standard structs implement
IEquatable and other interfaces

Q1 When I create a custom class, what’s the type I derive from?
%%A: System.Object, which is a reference type

Q1b What methods do you usually override in your custom class
%%A: tostring, gethashcode, equals. Fairly good answer.

Q: what are the value types you normally create
%%A: enums and structs

Q: what’s IDisposable

Q: what’s the relationship – IDisposable vs Finalizer

Q: Mutex vs Monitor

dotnet remoting and related jargon

P4 [[.net 1.1 remoting, reflection and threading]] shows a insightful history leading to dotnet remoting —
#1) RPC (pre-OO).
OO movement brought about the Next generation in the form of distributed objects (aka distributed components) —
#2) CORBA, RMI (later ejb) and dcom, which emerged around the same time.
COM is mostly for in-process and dcom is distributed
#3) soap and web services , which are OO-agnostic
I feel soap is more like RPC… The 2 distinct features of soap — xml/http. All predecessors are based on binary protocols (efficient), and the “service component” is often not hosted in any server.
#4) dotnet remoting feels more like RMI to me…According to the book above, remoting can use either
1) http channel with the soap formatter, or
2) tcp channel  with the binary formatter

Therefore, I feel remoting is an umbrella technology with different implementations for different usage scenarios.

#5) WCF
Remoting vs wcf? See other post.

y Dispose should call SuppressFinalize(this)

See [[accelerated c# 2010]]. Even more details are in [[.net gotchas]].

* small optimization idiom. I think it’s a sign of mastery, esp. if you can explain why.
* by default, if the class has a finalizer, then after Dispose, the object is still be seen with a finalizer. Will be moved to finalize queue. Delayed deallocation
* Often Dispose() handles all clean-up. In that case the final final finalization isn’t required any more.

Note GC.SuppressFinalize is a static method

c# lambda/closure executes when #again

The increment below is not executed when CLR executes Line #2 which sets up the thread. It’s executed only when the thread gets the “driver’s seat“, which doesn’t happen when Line #2 executes.

int x = 0; //#1
ThreadPool.QueueUserWorkItem(() => x++); //#2

The void lambda is more like a standalone method. This method is not executed when it seeds the new thread. It’s executed only when the thread runs.

More specifically, this lambda is more like a nameless closure —

Action myClosure = (() => x++);

CLR thread vs kernel/native thread data structures in memory

In the current CLR, each “CLR thread” maps to exactly one kernel/native thread after it start running. Before starting, it maps to

no kernel thread.

There's a kernel data structure for each running thread, including the stack. The dotnet CLR thread enriches that data structure

with additional info. One important additional info is the GC info. For each thread, CLR needs to know how to find local pointers to

heap objects. Unencumbered with this special GC requirement, the kernel doesn't have this additional data structure. See P86

[[concur programming on windows]]

c# DYNAMIC expando object (ExOb) – phrasebook

dynamic – better assign the exob instance to a dynamic variable. If you use a ExpandoObject variable, you lose a lot of features but i won’t elaborate …

javascript/python/perl – in these languages, a class instance is conceptually(?) and physically(?) a dictionary of name-value pairs. Exob is somewhat similar.

name-value pairs — In an exob instance, a field is (obviously) name-value pair. Ditto for a runtime-created method. The “value” is basically a (possibly void) lambda expression.

Emit — is the traditional technique to create a brand new class at run time and “emit” IL code into it. Exob is newer and simpler. I guess it’s more practical.

Finalize()/dtor ^ Dispose()

c# dtor is different from c++ dtor.

–some keywords
manual — Dispose() is NOT automatically invoked like Finalize(). Upper-layer programmers should but often forget to call it (Murphy’s law)
** defensive — better include a call to Dispose() in the dtor. Note dtor calling Dispose, not the other way round.

deterministic — Dispose(). You can control when it takes place. For serious resource management, use Dispose, since Finalize() may be pending for a long time on the finalizer thread.

Q: So what resource release should I put into Dispose()?
A: eg: window handlers (HWND), database connections… For these resources, Finalize() is another layer of defence. See P210 [[C# For Java Programmers]] for an HWND example.

–[[accellerated C# 2010]] has a concise coverage of the finalizer pitfall. Here are a few pointers.
Any class with a custom dtor must implement IDisposable, according to this book.

The finalizer thread calls Finalize() on each thread in the finalizer queue. Finalize() method is virtual but not overridable in c# (despite some confusing MSDN articles). Instead, you define a dtor like in c++, and Finalize() would invoke your dtor before all base dtors, just like c++.

See also http://stackoverflow.com/questions/1076965/in-c-sharp-what-is-the-difference-between-a-destructor-and-a-finalize-method-in

If you need to do anything in the dtor, it’s often better done in Dispose(). There is more than 1 reason to avoid custom dtor, so much so that I don’t see any good reason to ever do it.

c# REF parameter – pointer reseat

After using “ref” keyword for a while, I slowly realized it’s only useful if inside the method you reseat the pointer. Suppose the  caller of method m1() has a variable ovar and the object is at address 0x3. This is passed into m1 as parameter “pvar”.

If m1() reassigns to pvar, then you probably should use “ref” keyword
If m1() never reassigns to pvar, then you need not (and should NOT) use “ref” keyword

These are the guidelines for the common scenario, where pvar is class-type, so pvar is a pointer-VARIABLE (not a mere address; not a pointer-object). When pvar is reassigned, the behavior depends
** ref param? ovar is also reseated to a new address 0x7
** non-ref param? ovar is unaffected.

The much less common scenario is a struct-type method parameter. I feel most developers aren’t familiar, so better avoid it.
** ref, with assignment to pvar? ovar’s fields are completely overwritten and replaced. Note ovar still refers to (NOT “points to”) the object at 0x3.
** ref, with editing on pvar.field1? field1 of the object at 0x3 is modified.
** non-ref, with assignment to pvar? no effect on ovar, the change is local to the method
** non-ref, with editing on pvar.field1? ditto

%% c# brain bench

Q: what modifiers are equivalent to static when defining a class? Perhaps a invalid question
Q: build a comparison lambda using expression tree. Will we use Binary.. or Boolean….?
Q: foreach on my custom class … will call which methods — MoveNext/Current or GetEnumerator()
Q: calling ToUpper() on a dynamic variable, where ToUpper is both an instance method and an extension method?
%%A: instance meth takes precedence. Ext method may not be found at all. But there are workarounds.

Q: benefit of compiling an expression tree?
Q: can I assign twice to an out parameter within Method1? I think there’s no restriction.
Q: how to p/invoke on a win32 DLL
Q: execution order between base ctor, my ctor, static ctor of a type used in my ctor
Q: GetType().ToString() on System.NotSupportedException shows “System….” ?
Q: linq group-by

Q: can Main() method take 0 parameter?
AA: yes

Q: in Main(), can I initialize a variable before passing it to a out parameter of Method1?
%%A: yes optional. Pre-initialize is compulsory for ref-params and optional for out-params. Consequently, the method is requried to
populate out-param (since pre-initlialize was possibly skipped) but not required for ref-params.

Q: which is a managed resource – file handle, memory stream, socket, windows handle, db conn?
A: socket

Q: throw; vs throw ex;
A: throw; is better — more complete stack trace. see stack overflow

Q: can you pass an anonymous delegate into Thread ctor?
A: quite common

Q: static readonly field – set in static ctor or declaration?
A: both

c# IV – Eikon pre-screening

This is a 1) Knowledge based and 2) algo-based IV. The areas covered are evergreen and stable.

TCP vs UDP
ArrayList vs List
Mutex vs Semaphore — see other blog

Q: lock vs Mutex
%%A: any reference type object can be a lock…

Q3a: implement a data structure with random access and fast add/remove on both ends.
%%A: deque, using sements linked by a directory, as in STL
A: now I know circular array is simpler.

Q3b: How about the directory data structure in your deque
%%A: perhaps a hashtable?
A: Now I know it’s a vector of pointers

Q: 2 servers to synch their clocks on startup. No need for correct time, just the same time.
%%A: Side B will query A (or receive broadcasts) and update itslef. Side A will blindly broadcast. Both query and broadcast are
simple TCP operations.

c# – some must-know but seldom used features#YH

(Blog post. No need to reply.)

Hi YH,

Sharing some recent experience. In any language, the features we need to use is a tiny portion of the language feature set. Many of these features are designed for robust, high-performance, exception-safe coding but most applications have no such requirement.

However, As an experienced c# coder, we need to know enough to carry a intelligent discussion with other veterans on these topics. Otherwise we look like fake:)

* unsafe code
* p/invoke
* reflection on Generic type
* custom attributes (like java annotation)
* expression tree
* dynamic keyword
* closures
* linq to objects
* linq group-by
* GC intricacies
* Dispose vs Finalizer. When to use
* empty throw; vs throw ex;
* new MyStruct()
* SafeHandle
* interlocked
* override ToString() for a custom MyStruct
* wait/pulse
* synchronization context

All of the above features I didn’t need in my c# programming. However, I did go out of my way to explore c#, and managed to use these useful constructs
* generic type constraints
* submit a task to thread pool
* wait handles

c# log level +! log4net or NLog

I guess c# has builtin support but the log is written to the MSVS output window by default. If you want to also log to a file, you

can add a TextWriterTraceListener

The app.config can contain a TraceLevelSwitch like in DEBUG/INFO/ERROR log levels of log4net. This is probably a runtime change,

since the config can change after compilation.

[ Conditional (“TRACE”) ] also affects the logging, but at compile time.

c# captured var in closures

Local vars may live “beyond” the closing curly bracket. Local struct vars may no longer live on the stack as in java…

Most complicated scenario — local variable declared inside a loop. This is uncommon, considered code smell, and can be avoided. Note for(int index = ….) declares a variable OUTside the loop.

y learn Trace/Debug classes in dotnet

I believe log4net (and others like NLog) are better than the built-in, but the built-in has one nice feature — In visual studio, the output window conveniently shows the log messages if you use Trace.WriteLine or Debug.WriteLine.

Note output window isn’t the console.

Can log4net write to the output window? See http://angledontech.blogspot.sg/2011/08/direct-log4net-output-to-visual-studio.html. A bit of work. When I start a new project and have no time to set up log4net, then I use Trace/Debug to dump to the output window automatically, by default.

Reason2 – some projects may use the builtin not log4net.

Reason3 – some projects use other logging frameworks, so you may need to learn multiple logging frameworks. If you are lazy and you can decide, then the builtin is a basic solution always available.

one event delegating to another event – WPF

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090030 shows an interesting mini “pattern” of one event (“event-pseudo-field”) delegating all its add/remove logic to another event (pseudo-field).

public event EventHandler CanExecuteChanged{
  add { CommandManager.RequerySuggested += value; }
  remove { CommandManager.RequerySuggested -= value; }
}

This reveals the true meaning of an event member. If an object studentA (of class Student) has an event pseudo field evt2, this field is basically a chain of callbacks (or notification targets, or event handlers). The evt2 field is nothing but a handle to add/remove on this chain.

In many cases, the callbacks run sequentially on the same thread as the event-firing code.

See also http://bigblog.tanbin.com/2010/06/field-like-event-syntax-restrictions.html

the q[assembly] concept in dotnet – phrasebook

– An “assembly” sounds like purely logical but no no no it is also a physical File — either an EXE or a DLL, which could be an app

or a lib.

– Access modifier “internal” — is defined for an assembly

– unit of deployment

– unit to be versioned

– qualified type name — 2 assemblies “Soccer” and “Guitar” can both export Player class. The fully qualified Player type is

qualified with the host assembly.

– strong name — special subset of qualified type name

– GAC

– private unshared assembly – used by 1 app

new MyDlg ^ delegate {} – confusing syntax

1a) equivalent forms:
button.Click += new EventHandler(Method1);
1b)
button.Click += delegate { /* the code in the body of Method1 */ }

2a)
Action action = new Action(Method5);
2b)
Action = delegate (int a) {/* the code in Method5 body */ }

3a)
new Thread( new ThreadStart(MyMethod2) );
3b)
ThreadStart ts = delegate { /* the code in MyMethod2 */ };
new Thread(ts);

The a) form is useful when an existing method hosting the logic is available. The b) form is useful if you have just a few lines of code and want no method created. In both cases, people often simplify this long-winded coding style. However, if it confuses you then you should use the un-abbreviated form.

win service vs console daemon

In the standard 70-536 textbook, Microsoft MVP Tony Northrup related his early experience running a console daemon app as a poor man's win service. He used schedule tasks to start the console app.

In my projects I also keep a console app running forever, as a simple alternative to a win service.

There's no need to open some network service.

jar ^ dotnet-assembly

I feel the dotnet “assembly” concept borrows the java “package” and “jar” features. Here we compare assembly with jar

– physical files? Yes both are physical files
– executable? assembly can be EXE or DLL. Jar can come with a main class or without. Jar is more like DLL.
– contains IL bytecode? Yes. However, you could have a native assembly (see ngen.exe)
– unit of deployment? identical
– versioning? assembly versioning is mandatory and builtin. Jar versioning is adhoc, home-made and not always necessary.
– access modifier? No a jar is never used in the access modifier rules
– manifest? identical
– each dotnet class loaded in the VM has a fully qualified name containing the assembly name and namespace. See
http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx. Not in java. Each java class is identified by the package name and unqulified class name.

ISerializable in java^dotnet

In java ISerializable is a marker interface. I think dotnet replaced (all?) marker interfaces with class-level attributes. Serializable is such an attribute.

In the same vein, java’s transient keyword is replaced in dotnet by a field-level attribute NonSerialized

Dotnet ISerializable interface does exist but specifies a method and means something else.

System.Nullable struct # essentials

Let’s take Nullable as a case study.

Physically, represented by a 64-bit object + some bytes for the boolean flag. See http://stackoverflow.com/questions/3559843/what-is-the-size-of-a-nullableint32

Accessing the “Value” property triggers exception if HasValue == false, but GetValueOrDefault property would return 0.0. I guess we usually don’t want to use GetValueOrDefault when it’s null.

NPE and other exceptions in SL OOB

I’m no expert on SL OOB. I realize unlike in other environments, when an exception is thrown in a SL OOB, the consequence is unexpected. Blank screen is common.

Most common exception is NPE. If I get to see a log msg that’s good, but it doesn’t say in which thread on which line.

In other contexts I often throw exception to indicate error. At least the stack trace is logged. I now avoid throwing any exception. Rather I create an exception object and log it without throwing. Then I either close the application or continue.

For non-NPE, I enable MSVS exception-debug to help me locate the bug.

I feel the Aplication_UnhandledException even handler doesn’t help much. It does get triggered when I “throw”, but I still get blank screen.

unboxing allocates mem on stack

We are more familiar with boxing – allocating heap memory for a 8-bit byte object and returning a pointer.

Actually, unboxing also needs to allocate memory, usually on the stack. Without this stack object, we would always access the heap object, which could be modified by another handle. Unboxing should return a pass-by-value object that's not shared with other handles.

my own c# regex examples

Regex _regex = new Regex(“(\<script(.+?)\)|(\<style(.+?)\)”,
            RegexOptions.Singleline | RegexOptions.IgnoreCase);

_regex.Replace(html, String.Empty);


 ret = loginNameQualified.ToUpper();
 ret = Regex.Replace(ret, @”(.+\+)?(.+)”, “$2”);


static Regex REGEX1 = new Regex(@”(https://)(.+)(:d+.*)”);
var ma = REGEX1.Match(strValue);if (ma.Success){
                        var tmp_hostname = ma.Groups[2].Value;


var str = Regex.Replace(upSince.ToString(), “.*(up since.*)”, “$1”, RegexOptions.IgnoreCase);

SL – how to grab dispatcher, random tips

Q: how many dispatchers are there in one SL process?
%%A: 1, according to many c# guys. However, a lot of literature mentions “a dispatcher”

Q: can you get hold of the dispatcher from Any thread Always?
A: http://www.jeff.wilcox.name/2010/04/propertychangedbase-crossthread/ says not always

Q: which source is best to get the dispatcher?
A: Deployment.Current.Dispatcher is preferred over Application.Current.RootVisual.Dispatcher. See http://www.jeff.wilcox.name/2010/04/propertychangedbase-crossthread/ and other sites

Q: Is SynchronizationContext better than dispatcher?
A: http://www.jeff.wilcox.name/2010/04/propertychangedbase-crossthread/ says dispatcher is easier
A: http://dotnetslackers.com/articles/silverlight/Multithread-Programming-in-Silverlight-4.aspx demonstrates both.

Q: how many UI threads are there?
%%A: 1, according to many c# guys.

icon in SL-OOB causing silent death

icon.png
icon.png
icon.png
icon.png

I realized if the icon.png is zero-byte, then a SL OOB will fail with inconsistent behavior. Launched from the desktop shortcut, blank screen would show up. From MSVS, F5 or Ctrl-F5 would show no screen no error no log even if you enable exception debugging. Even the constructor in App.xaml.cs won’t get invoked.

GarbageCollect in JVM ^ .NET

Disclaimer — I’m no developer of garbage collector and have no real insight. This is just a collection of hearsay online comments.

Diff: Large Object heap

Diff: config parameter? JVM has (far) more. One of the very few dotnet config param is gcConcurrent.
http://msdn.microsoft.com/en-us/library/at1stbec.aspx points out

By default, VM (i.e. the runtime) uses concurrent garbage collection, which is optimized for latency. If you set gcConcurrent to false, VM uses non-concurrent garbage collection, which is optimized for throughput.

See first paragraph of http://msdn.microsoft.com/en-us/library/at1stbec.aspx

c# programmatically retrieve file path of runtime objects

From a Method object you can get the host Type object.

From a Type object you can get the host Assembly object.

From Assembly object you can get the physical assembly file.

1) (tested) Assembly.GetExecutingAssembly().Location; // gives the dll fullpath
1c) new T().GetType().Assembly; //returns the Assembly object. Works even though T is a template dummy type!

2) Process.GetCurrentProcess().MainModule.FileName

3) AppDomain.CurrentDomain.BaseDirectory; // Similar to 1)

user-editable XML config file for silverlight OOB app

Requirement: user-editable XML config file (like app.config or yourAppName.config) to control my silverlight OOB app.

Solution: Here are the key steps based on http://www.mohamedibrahim.net/blog/2010/01/27/creating-and-using-silverlight-app-settings-webconfig-configuration-applicatioin-settings-to-change-wcf-service-address-after-deployment-servicereferencesclientconfig-servicereferences-clientconfig/

1) move your app.config content into ServiceReferences.ClientConfig. This file is editable post-install, unlike the app.config which gets converted to binary and embedded in the DLL during build-deploy.

The blog above describes how to pragmatically parse the xml config — nothing fancy.

2) After the install (using sllauncher), you can easily locate the xap file. On my winXP PC it’s in C:\Documents and Settings\myLogin\Local Settings\Application Data\Microsoft\Silverlight\OutOfBrowser\1352946853.theOriginHostname

C:\Users\a5113359\AppData\Local\Microsoft\Silverlight\OutOfBrowser on my win7.

As you would expect, this xap gets overwritten whenever you re-install (with sllauncher). This is one way to confirm any code change took effect.

3) edit the ServiceReferences.ClientConfig file inside the xap. The blog above describes the technique. Actually no need to rename. Just use 7z to open the xap.

4) restart the OOB app. See new config value.

install SL-OOB app by xcopy

Based on http://www.silverlightshow.net/items/How-to-distribute-a-Silverlight-OOB-Application.aspx

In short, install the XAP file via sllauncher.exe.

Q: What files are needed?

%%A: nothing but the XAP file. The MSVS project build creates the XAP in the Bin/Debug folder. You can give it to users.

Q: Can I send the file(s) to a user by email attachment?

%%A: I think so. User need to have Silverlight installed.

Q: User needs to go online?

A: no

%%c# log wrapper – homegrown

namespace LogWrapper
{
    ///

    /// strictly stateless  
    ///

    public class Log
    {
        private static readonly log4net.ILog log4n = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public const string FORMAT_BEGIN = ” vvv   {0}   vvv”;
        public const string FORMAT_CLOSE = ” ^^^   {0}   ^^^”;

        static Log()
        {
            //var fileInfo = new System.IO.FileInfo(PathFinder.APP_CONFIG);
            //if (!fileInfo.Exists) throw new Exception(“app.config not found”);
            //log4net.Config.XmlConfigurator.Configure(fileInfo);
        }
        ///

        /// This method conveniently logs to console, IDE output window and log4net
        ///

        ///
        public static void Info(Object o, int levels = 2, bool isStackTraceNeeded = false)
        {
            /*The thread id seen by log4net. According to MSDN:
             * An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host
             * can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host
             * can use the CLR Hosting API to schedule many managed threads against the same operating system thread,
             * or to move a managed thread between different operating system threads.
             */
            var winThrId = AppDomain.GetCurrentThreadId();
            var thId = “/T” + Thread.CurrentThread.ManagedThreadId + “/” + winThrId + “/ “;

            #region locator
            StackTrace stackTrace = new StackTrace(fNeedFileInfo: true);
            var frames = stackTrace.GetFrames();

            StringBuilder locator = new StringBuilder(StackFrameToStr(frames[1]));

            for (int i = 2; i <= levels; ++i)
            {
                if (frames.Length > i)
                {
                    locator.Append(“<-" + StackFrameToStr(frames[i]));
                }
            }

            //if (frames.Length > 2)locator.Append(“<-" + StackFrameToStr(frames[2]));

            var locator2 = “{” + locator.ToString().Trim() + “} “;
            var msg1 = o ?? “_nul_”;
            var msg2 = thId + locator2 + msg1;
            #endregion

            if (isStackTraceNeeded) msg2 += “n” + stackTrace;

            log4n.Info(msg2);
            //System.Diagnostics.Trace.Write(“Trace is possible as well.”);
            System.Diagnostics.Debug.WriteLine(msg2);
            Console.WriteLine(msg2);
            return;
        }
        public static void Error(Object o, int levels = 3)
        {
            Info(o, levels, isStackTraceNeeded: true);
        }

        public static void Crash(string msg, Exception fatalException = null)
        {
            string a = “System ought to crash. Unwise to catch this error : ” + msg;
            a += (fatalException == null) ? “” : “n–> Root Cause –> ” + fatalException.ToString();
            Log.Error(a);
            Environment.Exit(-99);
        }

        public static void LogClose(string name)
        {
            Info(string.Format(FORMAT_CLOSE, name));
        }

        public static void LogBegin(string name)
        {
            Info(string.Format(FORMAT_BEGIN, name));
        }
        ///

        /// http://stackoverflow.com/questions/2045935/is-there-anyway-to-programmably-flush-the-buffer-in-log4net
        ///

        public static void FlushBuffers()
        {
            foreach (IAppender appender in LogManager.GetRepository().GetAppenders())
            {
                var buffered = appender as BufferingAppenderSkeleton;
                if (buffered != null) buffered.Flush();
            }
        }
        #region assertion tools
        public static void A(bool condition, string msg = “Programmer Error”, bool isFatal = false)
        {
            Assert(condition, msg, isFatal);
        }
        public static void Assert(bool condition, string msg = “Programmer Error”, bool isFatal = false)
        {
            if (!condition) Error(msg);
            Debug.Assert(condition, msg);
            if (!condition && isFatal) throw new Exception(“Fatal assertion failure.”);
        }
        #endregion

        #region private
        private static string StackFrameToStr(StackFrame f)
        {
            return Path.GetFileNameWithoutExtension(f.GetFileName()) + “.” + f.GetMethod().Name + “:” + f.GetFileLineNumber();
        }
        #endregion
    }
}

managed ^ unmanaged (dotnet)- what to Manage@@

A popular IV question — exactly what runtime Services are provided by the dotnet Hosting runtime/VM to the Hosted/managed code? In other words, how is the “managed code” managed?

Re http://bigblog.tanbin.com/2011/09/what-is-kernel-space-vs-userland.html, I believe an executing thread often has it’s lowest level stack frames in kernel mode, middle frames in the VM, and top frames running end-user application code. The managed code is like a lawyer working out of a hotel room. The hotel provides her many business services. Now, host environments have always provided essential runtime services to hosted applications, since the very early days of computers. The ubiquitous runtime host environment is the OS. In fact, the standard name of an OS instance is a “hostname”. If you have 3 operating systems running on the same box sharing the CPU/RAM/disk/network then there are 3 hosts — i.e. 3 distinct Hosting-Environments. In the same tradition, the dotnet/java VM also provides some runtime services to hosted applications. Hotel needs “metadata” about the data types, so a dotnet assembly always include type metadata in additional to IL code.

Below is a dotnet-centric answer to the IV question. (JVM? probably similar.) For each, we could drill down if needed (usually unneeded in enterprise apps).

– (uncaught) exception handling. See [[Illustrated c#]] (but how different from unmanaged c++?)
– class loading. See [[Illustrated c#]]
– security
– thread management? But I believe unmanaged code can also get userland threads manufactured by the  (unmanaged) thread library.
– reflection.See [[Illustrated c#]]
– instrumentation? Remember jconsole
– easier debugging – no PhD required. Unmanaged code offers “limited” debugging??
– cross-language integration?
– memory management?
** garbage collection. This service is so prominent/important it’s often listed on its own, but I consider this part of mem  mgmt.
** memory request/allocation? A ansi-C app uses memory management library to grab memory wholesale from kernel (see other posts) and a VM probably takes over that task.
** translate a C# heapy object reference to a “real virtual” heap address. Both JVM and .Net collectors have to move (non-pinned[1]) objects from one real-virtual address to another real-virthal address. Note the OS (the so-called Paging supervisor) translates this real-virtual address into physical RAM address.** appDomain. VM isolates each appdomain from other appdomains within a single Process and prevents memory cross-access. See http://msdn.microsoft.com/en-us/library/ms173138(v=vs.80).aspx

[1] pinned objects are not relocatable.

c# regex-match backslashes in strings

My suggestion — First find a “safe” character that’s guaranteed not to show up in the original string, like “_”. Replace all back slashes. Then proceed.

Problem with backslashes is the unnecessary complications. Here I want to match “one-or-more backslashes”. In the end I need to put 4 bachslashes in the pattern to represent that “one”.

var ret = Regex.Replace(@”any number of\\\backslashes”, “(.+\\\\+)?(.+)”, “$1 – $2”);

Alternatively, I could use @ to reduce the complexity @”(.+\\+)?(.+)”

Disappointingly the @ does a partial job. We still need 2 strokes — Confusing! I’d rather just remember one simple rule and avoid the @ altogether

auto vs star – in xaml, briefly

… in wpf (not Silverlight) means that the first column is 10x wider than the second. It's like saying “10 parts column 1, and 1 part column 2.” The cool thing about this is that your columns will resize proportionally.

////////////////

//eat up all available space that enclosing container has

////////////////

//Take up as much space as the contents of the column need

///////////////

//Fixed width: 100 pixels

string split c#

Requirement – Split by comma (or another delimiter). Handle consecutive delimiters. Trim white spaces around delimiters.

Solution –

string[] tmp = (commified ?? “”).Split(new string[] { “,” }, StringSplitOptions.RemoveEmptyEntries);

string[] tmp2 = Array.ConvertAll(tmp, p => p.Trim());

Timer to edit UI objects – WPF

http://www.silverlightshow.net/items/Tip-Asynchronous-Silverlight-Execute-on-the-UI-thread.aspx shows a common scenario. Say you want to periodically call WCF and in the callback method update UI directly — by editing UI objects. Not good practice, but sometimes this is quick and dirty.

1)
Solution: System.Threading.Timer, which uses background threads in the per-Process thread pool. Unfortunately these threads aren’t allowed to edit UI objects (only UI thread can). Result — blank UI.

Solution: this.Dispatcher.BeginInvoke(), but how do you get this.Dispatcher? Well, every UI object has a property this.Dispatcher, but is it easy to get a handle on the UI object?

In my case, WCF callback method is part of a static class. In this callback I raise an (static) event. One of the View Model objects subscribe to it. However, the View Model object should not have a handle on the UI objects, by OO principle.

Solution: the CodeBehind is the melting pot. It is part of the View and has access to every View Model object. So my VM exposes a public property this.Dispatcher which is set by the CB. Dependency injection

2) DispatcherTimer is the popular solution. However you can’t change the timer interval mid-flight.

event/method pairs in WPF

In learning WPF/Silverlight, I had a few confusions that are similar. These confusions probably fall into the same category. In all cases, one class has both an Event and a Method of a similar name. Here are some cases in point.

Tip: On*** is usually a method

1) Method OnPropertyChanged() vs PropertyChanged event
PC is more fundamental than OPC. PC is heart of the familiar INotifyPropertyChanged interface. As a result, wpf developers (like us) are frequently required to raise PC events explicitly. How do we raise? Often in a non-static OnPropertyChanged() method. So /there you are/, the link between PC and OPC.

http://msdn.microsoft.com/en-us/library/ms743695.aspx is an MSDN tutorial showing exactly this OPC/PC pattern.

The authoritative MSDN documentation http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx shows the same pattern except the OPC method is actually named NotifyPropertyChanged.

OPC is not a standard method name dictated by the framework. It’s more of a method naming convention.

2) This case is found in the commanding infrastructure of WPF. Method CanExecute() vs CanExecuteChanged event. Once the event fires[2] and a command source object [3] gets its callback method invoked[1], that callback method internally calls CanExecute() to check if it should paint itself dimmed.

[1] often on the GUI thread.
[2] (by invoking each callback on the inv list),
[3] (eg button)

delegate instance is passed by value@@

myEvent += myDelegate;

Q: Is myDelegate passed by reference?
A: No. member-wise copying. In other words, each item in the delegate inv list is passed in (by reference?).
A: No. The invocation list (say 2 callbacks) are appended to myEvent’s internal inv list, and new list is ReBound to myEvent internal delegate variable.

That’s a short answer. For the long answer, we need to forget events and callbacks and focus on pure delegates as list objects holding simple “items”. Suppose dlg1 variable points to address1, and dlg2 points to address2.

dlg1 += dlg2 // translates to
dlg1 = Delegate.Combine(dlg1, dlg2). // Note: re-binding dlg1

Now dlg1 points to newly allocated address11. At this address there’s a new-born delegate object whose inv list is

[item1 at addr1,
item2 at addr1 …
itemN at addr1,
item1 at addr2,
item2 at addr2, ….
itemM at addr2]

According to http://msdn.microsoft.com/en-us/library/30cyx32c.aspx, some of the items could be duplicates — Legal.

30 seconds after the Combine() operation, suppose dlg2 is subsequently modified (actually re-bound). Instead of 2 callbacks at addr2, variable dlg2 [1] now points to addr22 with 5 callbacks. However, this modification doesn’t affect the inv list at addr11, which dlg1 now points to.

Therefore, we can safely say that in a Combine() operation the RHS delegate’s inv list is copied-over, passed by value or “pbclone”.

[1] like all java reference variables, a c# delegate variable is a 32-bit pointer object. As explained in
http://bigblog.tanbin.com/2012/03/3-meanings-of-pointer-tip-on-delete.html, the compiler is likely to allocate 32 bit of heap for this 32-bit object.

Logging – thread id discovery, parent stack frame discovery

<!– /* Font Definitions */ @font-face {font-family:Calibri; panose-1:2 15 5 2 2 2 4 3 2 4;} @font-face {font-family:Consolas; panose-1:2 11 6 9 2 2 4 3 2 4;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {margin:0cm; margin-bottom:.0001pt; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-fareast-language:EN-US;} a:link, span.MsoHyperlink {mso-style-priority:99; color:blue; text-decoration:underline;} a:visited, span.MsoHyperlinkFollowed {mso-style-priority:99; color:purple; text-decoration:underline;} span.EmailStyle17 {mso-style-type:personal-compose; font-family:"Calibri","sans-serif"; color:windowtext;} .MsoChpDefault {mso-style-type:export-only; font-family:"Calibri","sans-serif"; mso-fareast-language:EN-US;} @page WordSection1 {size:612.0pt 792.0pt; margin:72.0pt 72.0pt 72.0pt 72.0pt;} div.WordSection1 {page:WordSection1;}

Logging showcasing thread id discovery, parent stack frame self-discovery ..
    ///

    /// strictly stateless   
    ///
    class Log
    {
        private static readonly log4net.ILog log4n = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public const string FORMAT_BEGIN = ” vvv   {0}   vvv”;
        public const string FORMAT_CLOSE = ” ^^^   {0}   ^^^”;
        ///

        /// This method conveniently logs to console, IDE output window and log4net
        ///
        ///
        public static void Info(Object o, int levels = 2, bool isStackTraceNeeded = false)
        {
            /*The thread id seen by log4net. According to MSDN:
             * An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host
             * can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host
             * can use the CLR Hosting API to schedule many managed threads against the same operating system thread,
             * or to move a managed thread between different operating system threads.
             */
            var winThrId = AppDomain.GetCurrentThreadId();
            var thId = “/T” + Thread.CurrentThread.ManagedThreadId + “/” + winThrId + “/ “;
            #region locator
            StackTrace stackTrace = new StackTrace(fNeedFileInfo: true);
            var frames = stackTrace.GetFrames();
            StringBuilder locator = new StringBuilder(StackFrameToStr(frames[1]));
            for (int i = 2; i <= levels; ++i)
            {
                if (frames.Length > i)
                {
                    locator.Append(“<-" + StackFrameToStr(frames[i]));
                }
            }
            //if (frames.Length > 2)locator.Append(“<-" + StackFrameToStr(frames[2]));
            var locator2 = “{“ + locator.ToString().Trim() + “} “;
            var msg1 = (o ?? “_nul_”);
            var msg2 = thId + locator2 + msg1;
           

–>

c# get unique thread id

I find the thread id number typically too low and not “realistic” enough. I am looking for a unique-looking identifier, one which I can search in log files.

Here’s my attempt to get it.

            /*According to MSDN:
             * An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host
             * can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host
             * can use the CLR Hosting API to schedule many managed threads against the same operating system thread,
             * or to move a managed thread between different operating system threads.
             */

            var winThrId = AppDomain.GetCurrentThreadId();
            var thId = “/T” + Thread.CurrentThread.ManagedThreadId + “/” + winThrId + “/ “;

c# log each msg with line number + thread id

This method conveniently logs to console, IDE output window and log4net

It also logs the file name, method name and line number of top 2 levels on the call stack

        public static void Info(Object o, bool isStackTraceNeeded = false)
        {
            /*According to MSDN:
             * An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host
             * can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host
             * can use the CLR Hosting API to schedule many managed threads against the same operating system thread,
             * or to move a managed thread between different operating system threads.
             */
            var winThrId = AppDomain.GetCurrentThreadId();
            var thId = “/T” + Thread.CurrentThread.ManagedThreadId + “/” + winThrId + “/ “;

            #region locator
            StackTrace stackTrace = new StackTrace(fNeedFileInfo:true);
            var frames = stackTrace.GetFrames();

            StringBuilder locator = new StringBuilder(StackFrameToStr(frames[1]));
            if (frames.Length > 2)
                locator.Append(StackFrameToStr(frames[2]));
         
            var locator2 = “{” + locator.ToString().Trim() + “}”;
            var msg = thId + locator2 + (o ?? “_nul_”);
            #endregion

            if (isStackTraceNeeded) msg += “n” + stackTrace;

            log4n.Debug(msg);
            //System.Diagnostics.Trace.Write(“Trace is possible as well.”);
            System.Diagnostics.Debug.WriteLine(msg);
            Console.WriteLine(msg);
            return;
        }

        public static string StackFrameToStr(StackFrame f)
        {
            return Path.GetFileNameWithoutExtension(f.GetFileName()) + “.” + f.GetMethod().Name + “.” +f.GetFileLineNumber() + ” “;
        }
    }

c# IV questions found online

I want to see some knowledge of things like the GAC, CLR and JIT. Here are some sample C#-specific questions: 
– Where are the framework assemblies stored? How is this useful? 
– Explain the abstract keyword and what is an example of its use? 
– Can you prevent a class from being inherited by another class? If so, how? 
Easy questions:
    * Is System.String a class or a struct (or reference or value type if you prefer).
    * Explain IDisposable and the 'using' statement.
    * Explain public, protected, private, and internal.
Intermediate questions:
    * What's the difference between Hashtable and Dictionary?
    * What does int? mean? Explain the relationship with Nullable.
Hard questions:
    * Explain the following snippet of code: 'from x in collection select new { x.Foo }'. What is the compiler doing? What is the CLR executing?
    * Explain the “yield” keyword. What is the compiler doing internally?
——
# What are Generics ? How do they affect performance.
# How would you define an Anonymous Functions? What is the difference between Anonymous Methods and Lambda Expressions?
# How does an Enumerator (IEnumerable & IEnumerator) work ? How does an Iterator work in C# 2.0 ?
# What is Garbage Collection ? How does it work ? What are generations in GC ?
# What is the role of an Extension Method ? When would you use it ?
# What is a Lambda Expression ? Where would you use it ?
# How would you define a new custom event ?
# How would you choose between a pure abstract base class and an interface.
# What is MVC how does it differ from MVP ?
# What is Dependency Injection / Inversion of Control ?
———
Everyone who writes code
    * Describe the difference between a Thread and a Process?
    * What is a Windows Service and how does its lifecycle differ from a “standard” EXE?
    * What is the maximum amount of memory any single process on Windows can address? Is this different than the maximum virtual memory for the system? How would this affect a system design?
    * What is the difference between an EXE and a DLL?
    * What is strong-typing versus weak-typing? Which is preferred? Why?
    * Corillian's product is a “Component Container.” Name at least 3 component containers that ship now with the Windows Server Family.
    * What is a PID? How is it useful when troubleshooting a system?
    * How many processes can listen on a single TCP/IP port?
    * What is the GAC? What problem does it solve?
Mid-Level .NET Developer
    * Describe the difference between Interface-oriented, Object-oriented and Aspect-oriented programming.
    * Describe what an Interface is and how it’s different from a Class.
    * What is Reflection?
    * What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP?
    * Are the type system represented by XmlSchema and the CLS isomorphic?
    * Conceptually, what is the difference between early-binding and late-binding?
    * Is using Assembly.Load a static reference or dynamic reference?
    * When would using Assembly.LoadFrom or Assembly.LoadFile be appropriate?
    * What is an Asssembly Qualified Name? Is it a filename? How is it different?
    * Is this valid? Assembly.Load(“foo.dll”);
    * How is a strongly-named assembly different from one that isn’t strongly-named?
    * Can DateTimes be null?
    * What is the JIT? What is NGEN? What are limitations and benefits of each?
    * How does the generational garbage collector in the .NET CLR manage object lifetime? What is non-deterministic finalization?
    * What is the difference between Finalize() and Dispose()?
    * How is the using() pattern useful? What is IDisposable? How does it support deterministic finalization?
    * What does this useful command line do? tasklist /m “mscor*”
    * What is the difference between in-proc and out-of-proc?
    * What technology enables out-of-proc communication in .NET?
    * When you’re running a component within ASP.NET, what process is it running within on Windows XP? Windows 2000? Windows 2003?
Senior Developers/Architects
    * What’s wrong with a line like this? DateTime.Parse(myString);
    * What are PDBs? Where must they be located for debugging to work?
    * What is cyclomatic complexity and why is it important?
    * Write a standard lock() plus “double check” to create a critical section around a variable access.
    * What is FullTrust? Do GAC’ed assemblies have FullTrust?
    * What benefit does your code receive if you decorate it with attributes demanding specific Security permissions?
    * What does this do? gacutil /l | find /i “Corillian”
    * What does this do? sn -t foo.dll
    * What ports must be open for DCOM over a firewall? What is the purpose of Port 135?
    * Contrast OOP and SOA. What are tenets of each?
    * How does the XmlSerializer work? What ACL permissions does a process using it require?
    * Why is catch(Exception) almost always a bad idea?
    * What is the difference between Debug.Write and Trace.Write? When should each be used?
    * What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not?
    * Does JITting occur per-assembly or per-method? How does this affect the working set?
    * Contrast the use of an abstract base class against an interface?
    * What is the difference between a.Equals(b) and a == b?
    * In the context of a comparison, what is object identity versus object equivalence?
    * How would one do a deep copy in .NET?
    * Explain current thinking around IClonable.
    * What is boxing?
    * Is string a value type or a reference type?
    * What is the significance of the “PropertySpecified” pattern used by the XmlSerializer? What problem does it attempt to solve?
    * Why are out parameters a bad idea in .NET? Are they?
    * Can attributes be placed on specific parameters to a method? Why is this useful?
C# Component Developers
    * Juxtapose the use of override with new. What is shadowing?
    * Explain the use of virtual, sealed, override, and abstract.
    * Explain the importance and use of each component of this string: Foo.Bar, Version=2.0.205.0, Culture=neutral, PublicKeyToken=593777ae2d274679d
    * Explain the differences between public, protected, private and internal.
    * What benefit do you get from using a Primary Interop Assembly (PIA)?
    * By what mechanism does NUnit know what methods to test?
    * What is the difference between: catch(Exception e){throw e;} and catch(Exception e){throw;}
    * What is the difference between typeof(foo) and myFoo.GetType()?
    * Explain what’s happening in the first constructor: public class c{ public c(string a) : this() {;}; public c() {;} } How is this construct useful?
    * What is this? Can this be used within a static method?

xaml pretty print

#) You can try the imperfect Format Document command from the Edit->Advanced menu to nicely format your XML document. (http://sidersdd.wordpress.com/2008/04/21/format-xml-in-visual-studio/)

#) http://www.softlion.com/webTools/XmlPrettyPrint/default.aspx is good

#) http://www.corefiling.com/opensource/xmlpp.html can sort attributes but unfortunately removes indents on xaml comments and converts double-quote to single-quote

xmlprettyprint.com is less precise about indent

notepad++ HTML-tidy is broken

CommandSource, briefly

Update: it looks like Command Source is usually a user input thingy?


Buttons, MenuItems, Hyperlinks, KeyGestures are command source objects. A command source Instance is a (typically) stateful object. Users issue commands via a command source.

Technically, CommandSource objects are instances of ICommandSource (ICS). It’s revealing to examine the properties of ICS….

Besides the ICS properties, the most important thing to Keep in mind is that Command Source objects subscribe to CanExecuteChanged events, by adding a (2-pointer) delegate instance into the invocation list (behind the event pseudo-field) inside the command object.

What a mouthful! Let’s try again. An event is a (pseudo) field inside a command. The command object “fires event A” by invoking callbacks in A’s invocation list. Each command source instance bundles “this” and one of its non-static methods into a callback object and appends it to the invocation list. Event A is the “CanExecuteChanged” event.

When a command source gets called back up on this event, it queries the command’s CanExecute() and gets a yes/no, and disables/enables itself accordingly. Note in a simple commanding usage, this even never fires and CanExecute() always returns true.

restrictions on delegate inv list

Restriction — a delegate is immutable, just like a string object. When you append or remove on a delegate instance, a new instance
is Returned (from a Method).

Restriction — when you remove the last item from the inv list, the delegate variable becomes null. You can’t have an non-null empty
list.

to-target ^ to-source updates in WPF binding

(Based on P502 [[Pro wpf in c#2008)

The fulcrum of MVVM is data binding. Data binding links 2 objects — Source and Target objects.

Rule 1: Source-to-Target is always immediate, in either one-way or two-way. In contrast, T-to-S is not always immediate.

Rule 1a: regular one-way is immediate, since regular one-way means S-to-T. OneWayToSource is like the  T-to-S  in two-way. See below.

Rule 2: In two-way, the immediacy of update is asymmetric.

– Source changes immediately fire events and hit Target object (usually a visual).
–  T-to-S  update mode in two-way set-up has several enum values, such as

** every key stroke
** on focus loss

Intuitively, LostFocus is more reasonable than key-stroke for a text input source. You don’t want event firing on every text box keystroke.