Categories
programming

XSD minOccurs Specified And The XmlSerializer

In your XSD schema definitions, the minOccurs has a subtle nuance through a leaky abstraction. Getting right to the point:

Let’s take an element definition such as:

<xs:element name="OptString" type="xs:string" minOccurs="0"/>

Now when you create your default classes using the xsd.exe tool, you will end up with a class having a property OptString. Neat, since in code, you can just set that property (or not) and it will appear in the XML (or not). It’s optional.

Now what about:

<xs:element name="OptBool" type="xs:boolean" minOccurs="0"/>

Again, there will be a property named OptBool for you to set (or not). Only this time, it won’t appear in the serialized XML. There’s an additional property named OptBoolSpecified which you need to set. If false (which it is by default) then it won’t serialize.

Now, let’s look at:

<xs:element name="OptValueString" type="ValueString" minOccurs="1"/>

where ValueString is defined as:

<xs:simpleType name="ValueString">
    <xs:restriction base="xs:string">
      <xs:minLength value="3" />
      <xs:maxLength value="10" />
    </xs:restriction>
  </xs:simpleType>

This has the same effect as a regular string. If it’s set (or not), it will serialize (or not).

Then we have a custom type (an enumeration) such as:

<xs:element name="OptStrongString" type="TypedString" minOccurs="0"/>

where TypedString is defined as:

<xs:simpleType name="TypedString">
    <xs:restriction base="xs:string">
      <xs:enumeration id="ValueA" value="A" />
      <xs:enumeration id="ValueB" value="B" />
    </xs:restriction>
  </xs:simpleType>

It has it’s base in type String, but it’s an enumeration, so how will it behave?

Well, it needs it’s related Specified property to be set. Without that, it’s not going to serialize. And the same goes for type int.

In fact, experiment with the different types and understand the subtleties of minOccurs better. And you could question the existential “why” it is so or you could also just accept the way it is and move swiftly along 🙂

I’ve attached some code here to jumpstart your experimentation.

Download project XSDMinOccursSandbox

Categories
programming

Sort, BinarySearch and Anonymous Delegates

Generics has undoubtedly made life a lot easier in the world of 1s and 0s and so this code snippet will only deal with the generics version since the code reads a lot easier. This is also a great bookmark post for future reference…

public class Foo {
 public string Alpha {get;set;}
 public string Omega {get;set;}
}

This shouldn’t bother you too much, we just got Foo. Nice. But now we want to sort a bunch of instantiated Foos, as a “once-off” ascending, according to Alpha.

List<Foo> result = new List<Foo>();
.
.
results.Sort(delegate(Foo lhs, Foo rhs) {
                     return lhs.Alpha.CompareTo(rhs.Alpha);
                   });

Straightforward. Using the anonymous delegate to achieve that once-off without creating an unnecessary class. You might think you could do the same thing with BinarySearch.

Foo sample = new Foo{Alpha="a", Omega="z"};
results.BinarySearch(sample, delegate(Foo lhs, Foo rhs) { return lhs.Alpha.CompareTo(rhs.Alpha); });

But you can’t. In this case, you actually do need to create an unnecessary class.

Foo sample = new Foo{Alpha="a", Omega="z"};
srchIdx = results.BinarySearch(sample, new FooAlphaComparer());
.
.
.
internal class FooAlphaComparer : IComparer<Foo> {
			public int Compare(Foo lhs, Foo rhs) {
				return lhs.Alpha.CompareTo(rhs.Alpha);
			}
		}

Same one liner in the Compare function, but this time, it has to be a class.

However (there’s always a BUT somewhere even if you call it a ‘however’), with a bit of kung-fu and ninja superpowers (apparently) there is a way to plumb this and make it work- but i tend to shift the complexity in other areas of the problem domain. It gets complicated. Moving right along…

For interest sake, you want to compare by Alpha AND Omega?


public int Compare(Foo lhs, Foo rhs) {
  int cfA = lhs.Alpha.CompareTo(rhs.Alpha);
  int cfO = lhs.Omega.CompareTo(rhs.Omega);
  if(0 != cfA) { //Alphas are not equal
    return cFA;
  } else if(0 != cfO) {   
     return cf0; //Alphas are equal but Omegas aren't
  } else {
    return 0; //Alphas are equal and so are Omegas
  }
}
Categories
Business Technology

Investing in the Learning Curve

We have a concept of what the learning curve represents, and unfortunately, the same thing can represent 2 opposite concepts. What makes more sense to me is looking at a learning curve from a classical labour cost perspective and more keenly towards labour productivity. In this sense, the learning curve is interpreted, broadly, as: the more you work with something, the more productive (cheaper, better, faster, more knowledgeable) you become. And one can recognise that sentiment when it’s expressed variously with respect to success, specialization, expertise, productivity, quality or minimizing costs. So where’s the investment?

Programming technology changes rapidly, and sometimes to the detriment of programming and business, sometimes not, but also to the advantage of progress and for the sake of technology itself. But changes are also forced to be incremental in order to be successfully adopted, since any radical departure will result in a prohibitively expensive learning curve where the economic costs outweigh the advantages of the change. Similarly, you also cannot force change too frequently, even if it’s small enough, since you never get to break even or realise a profit from the previous change. I think this last point might also be reflected in the current developer attitudes towards the “next big Microsoft thing” and the ubiquitous jading of old hats. Everyone seems to hanging five for a bit before moving forward. Or maybe Douglas Adam’s theory is kicking in?

At the same time though, you need to keep moving forward. So where do you invest your next generation of development so as to minimize the costs of the learning curve if you want to remain marketable and competitive across:
* web development
* mobile application development
* backend systems
* any platform (platform agnostic)

C++, C, C#, VB, Perl, PHP, Python, Ruby… ?

All these languages have their pro’s and con’s and more importantly, costs. As an example, I recently looked at Symbian C++ development, and the learning curve is relatively expensive. The idioms alone take time to get to grips with, so although you got a very powerful API, C++ on Windows desktop, or legacy ATL knowledge is not easily transferrable to a Symbian C++ development effort. Possible, but no as easy as say, being able to use a standard framework and language, with the same idioms, on both (all) platforms. That would be the ultimate prize (for me).

And it doesn’t have to be the same language. Case in point, i’m currently using Monorail (.NET web development) and RoR (other web development) concurrently on different projects and i’m enjoying the benefit of being able to work in a predictable (hence productive) manner switching between the two, relatively seamlessly. Whereas, switching between asp.net webform development and RoR, as an example would not be feasible. The traditional 30% context switch overhead would double.

So if you’re faced with “what to learn next”, take a closer look at the learning curve and where you can (need to) apply that knowledge in the future, in order to remain competitive- whether globally, or within your own department. Maybe it’s stating the obvious, but it’s surprising just how un-obvious the obvious can become when there are a lot of flashing lights going off all the time. So it’s not always about the language or the technology, but also a lot about the “way” in which things are done; which, by nature, is usually a little more sublime to spot since it’s hiding in plain sight 😉

log4net

Not gonna lie- it wasn’t altogether _that_ intuitive to begin with. Appenders, logging levels, loggers and a whole bunch of different configuration going on: it wasn’t just working. But, i thought to myself: many others are happy with it so it must be worth the initial pain. Of course, in a world of instant gratification and high-speed demands, how long exactly do you sit with a problem?

If it’s a maths problem, like something involving integrals, sometimes you can do nothing but sit with it. No amount of Google is ever gonna give you the answer. And if you think it can, i’ll happily take on the challenge 🙂 But this is code…

CodeBetter, CodeProject, Koders and even log4Net itself have plenty of sample code and tutorials designed to get you off the ground. And they all have their strong points so if you thinking about log4net, take some time upfront just to read how different people go about explaining various setups and configurations. You’re bound to find one you like. So back to this particular log4net experience…

What i wanted is to have an open console running which recorded anything i wanted while my asp.net application was executing. i love consoles ‘cos of their simplicity, power, flexibility and in-obtrusiveness. in the right place, at the right time, they definitely rock. So that’s the mission.

There’s this article which gave me a great jump start in the right direction. I made a few modifications (i am programmer) and as a result… well, this picture is worth a paragraph or two:

log4net console
More than anything, this is testimony that log4net really does work despite some of the comments and posts (and initial pain) and once you’ve got it down, you can add massive geek-value to your project. You also just might have fun, but keep that to yourself 😉

Gem

now where was this little gem when i needed it? 🙂
a series of articles entitled:

An Extensive Examination of Data Structures Using C# 2.0

there are 6 parts to this series, this link above will take you to “Part 5: From Trees to Graphs” [the part i’m interested in at the time of discovery :)]

Delegate Gotcha

A while back i was trying to find a solution to the delegate gotcha and stumbled upon, even more recently, some answers to a lot of my questions… they trackback and link with each other at some point, but my entry point to this discussion was mostly through, in no specific order:
Observable property pattern, memory leaks and weak delegates for .Net. – Alexey A. Popov
Simulating “Weak Delegates” in the CLR – Greg Schechter
.Net 2.0 Generics, Anonymous Methods, and Delegate inference bug – Udi Dahan

After reviewing a lot of the different solutions, i’m currently experimenting with an idea. Given your usual suspect:

public class EventSource
{
    public event EventHandler FireEvent;
    public void OnFireEvent( )
    {
      if(null != FireEvent)
          FireEvent( this, EventArgs.Empty );
    }
}

I’ve reworked some ideas and using WeakReference, rewritten the EventSource above as follows:

public class EventSource
{
    private Dictionary<EventHandler, WeakReference> origDelgs =
            new Dictionary<EventHandler, WeakReference>();   
    public event EventHandler FireEvent
    {
        add
        {
            if( !origDelgs.ContainsKey( value ) )
                origDelgs.Add( value, new WeakReference( value ) );
        }
        remove
        {
            if( origDelgs.ContainsKey( value ) )
                origDelgs.Remove( value );
        }
    }
    public void OnFireEvent( )
    {
        foreach( WeakReference aref in origDelgs.Values )
        {
            if( null != aref.Target )
            {
                EventHandler hdl = (EventHandler)aref.Target;
                hdl.Invoke( this, EventArgs.Empty );
            }
        }
    }
}

Now, at least, if my sink goes out of scope, it won’t get resurrected 🙂
Will continue experimenting with this idea and see how it performs….

FtpWebRequest Part II

.. following on from the first one, the project has now been updated to include some work with the new BackgroundWorker component available in Net 2.0… 😀

Creating responsive UI’s on lengthy processes has never been so easy!

including source code

FtpWebRequest

After looking for a trim Ftp client library for .Net 1.1, .Net 2.0 releases with FtpWebRequest. I completely missed this one in the search to find *something*.

After hacking around with it for a very short while, it proved to be by far the easist “library” to integrate with… the fruits of that freely available here .

There’s not much to the code itself as most of it is just a straightforward copy-paste out of MSDN but it ends up being the very light file dumper i was looking for.