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 πŸ˜‰

Categories
Technology

SharpDevelop + Monorail

Monorail rocks, but getting going in #Develop can be cumbersome in that you need to create a lot of placeholders. Fortunately, you can create a template which you can drop into your data/templates/project/CSharp sub-path of your #develop installation
for example: C:\Program Files\SharpDevelop\2.2\data\templates\project\CSharp
Using this template, you can now

Create a “MonoRails” web project

create.png

Have it create all the skeletal placeholders

created.png

Build (change relevant config settings) and view when hosting it locally

running.png

This template in it’s current form references the Castle binaries from the install directory. You might want to change that bit of detail if your installation is not “standard” (ie. next > agree > all > next > finish).

Download Template

Categories
Rants Technology

Recycled Software

What’s up with everything being ported to .NET? There’s nothing more boring than copying somebody else’s idea, unless of course, your own ideas are pretty crap πŸ™‚

And (sup)porting a dozen applications to be used with the .NET framework surely cannot be considered as innovative either- it’s real name is “market strategy”. I must confess though, we’ve (that is, i) benefitted much from having tried and trusted Java libraries (example, NHibernate) ported across, but i’ve also wondered many a time, why not just use Java then? And now emacs.net?

An aside, what i loved about the marketing around NHibernate is that it builds on the solid reliability and legacy robustness of Hibernate in a Java world πŸ™‚

But it’s all just recycled software ideas and methinks a large pop of the lemming community are looking for “innovation” in all the wrong places.

<warning>Massive Generalisation About to Occur</warning>

Software developers are more into being “advertained” (advertisement + entertainment) than any other population group i know. Trouble is, i always presupposed we’re more critical than most. But perhaps we’ve reached a point where we’ve started buying into our own hype? Afterall, we can make it fly with words like interoperability, multi-platform and integration. Oooooo… :p

Preserving the Stacktrace

Exception handling is important enough to get right. And there’s plenty of sample code out there to help you get it right, nonetheless, i come across two major variations:
catch (Exception ex) {
throw;
}

and

catch (Exception ex) {
throw ex;
}

There’s more about catching general Exception but that’s beyond the scope of this post. So, moving right along…

There is one other variation:

catch (Exception ex) {
throw new Exception(ex);
}
But the first two are more interesting. The second (throw ex;) is the least desirable, unless of course you have a good reason to not preserve the stacktrace.

rethrowexception.PNG
Code attached rethrow.txt

DefaultWsdlHelpGenerator Gotcha

Whiskey Tango Foxtrot, but this was super unpleasant to uncover.

I’ve got a website up ‘n running and wanted to add a webservice to it, aight? Wizards make the job easy so here i go:

“Add > New item > Asp.Net > Web Service > Ok” Programming has never been so easy…
Navigate to webservice and … *poof!*

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Line 1333:
Line 1334:    OperationBinding FindHttpBinding(string verb) {
Line 1335:        foreach (ServiceDescription description in serviceDescriptions) {
Line 1336:            foreach (Binding binding in description.Bindings) {
Line 1337:                HttpBinding httpBinding = (HttpBinding)binding.Extensions.Find(typeof(HttpBinding));
    
[NullReferenceException: Object reference not set to an instance of an object.]
ASP.defaultwsdlhelpgenerator_aspx.FindHttpBinding(String verb) in
c:WINDOWSMicrosoft.NETFrameworkv2.0.50727CONFIGDefaultWsdlHelpGenerator.aspx:1335

Dang wizards! Obviously badly generated code? Not so…
All the performance hints and profilers will tell you, if you don’t need to automatically wire up your events, set the AutoEventWireUp=false (no, i’m not going on a blatant tangent here) in your .config. What they don’t tell you is that the @Page directive influences the generation of Wdsl for your webservice. Obviously. :S

http://www.dotnet247.com/247reference/msgs/35/177335.aspx

http://forums.asp.net/p/385662/385662.aspx#385662

http://support.microsoft.com/default.aspx?scid=kb;en-us;324151

And in the immortal words of John Lennon: “I’m not the only one” (who got duped).

MS, you’re gonna have to do better than that if you want to catch us out πŸ˜‰

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 πŸ˜‰

New Territory

for a .net “junkie”, migrating technology skills can be quite daunting- well, that is for me at least. after too long a delay, i finally decided to start shifting some of my stuff across to Linux. i like the community drive behind Ubuntu and so… here i am. I guess there are lots of reasons for finally getting going with this… thing is, i’ve always enjoyed having an eclectic knowledge of sorts about technology in general and after so long into .net, it feels like i have an ecelectic .net grasp of all things microsoft. not that it’s a bad thing, it’s just not what i _really_ wanted πŸ™‚ anyways, it’s also hard to be technology-agnostic and objectively equipped to recommend a strategy you can actively be involved in when the last line of Java code you wrote was… erm… *then*. and as great as some of the .net stuff is [and 3.0 and upcoming LINQ… oooohhhh] i can’t help but think i could be _selling out_ if i don’t make a decent effort to stay even half-decently current across the board. now if i can get my wireless card to work, i could start blogging from my new desktop πŸ™‚

WT? #2

This was a commercial online system- tried to make a reservation and…

 webexception.PNG