November 2007 - Posts
If you programmatically add attributes with namespaces to an XElement, when the XElement is written out it will give each attribute a namespace prefix and then define a xmlns for that prefix. The way XElement does this is first it examines the namespaces already active and also those defined in the element for a match. If it doesn't find a match, it then creates a new prefix based on the count of the current namespaces in scope, e.g p1, p2, p3,....pn.
Now sadly, although it did first scan for namespaces, it appears it doesn't scan for prefixes in the current element *after* the current attribute. It does scan for previous declared prefixes, and will use one if the namespace matches. If the namespace doesn't match but a prefix clashes with the proposed prefix, the prefix is added a 0, e.g p10, p20, ... pn0. If that one also clashes then the number will be increased e.g p11, p21, ... pn1. And so forth.
The problem is it doesn't check for clashes inside the element it arbitrarily adds a namespace to. This code causes an exception due to the same attribute being named twice.
Dim books = New XElement("books")
books.Add(New XAttribute("{abc}attrib1", "one"))
books.Add(New XAttribute(XNamespace.Xmlns.GetName("p1"), "zzz"))
The moral of the story is don't use "pn" for your namespace prefixes. (where n is any integer). You end up potentially "p"ing on your code ;)
I was working with Visual Studio and a few other applications, and put the computer to sleep while I took a break. Shortly after I resumed the computer did a hard restart. I presume it is something to did with Vista and the power management, but the nice thing was Visual Studio actually recovered the temporary project for me :)
When working with VB9 you may get this cryptic error :
XML namespace prefix 'xmlns' is not defined
If you are using only default namespaces you can fix this by including a definition for the xmlns as an Import statement or as an xmlns attribute on the XML literal. But if you are using prefixed namespaces imported at file level, then you must add an imports at project level via the project properties reference tab.
You have two choices:
- Import System.Xml.Linq for the entire project, or
- Import a namespace for the entire project
If you decide to import a namespace it can be any namespace at all. I named one _do_not_use. Problem is it will show up in XML axis properties in intellisense, but with a name like _do_not_use, that isn't really a big problem. Of course you could add one that you might want to use.
You may prefer to simply import System.Xml.Linq, but I thought I'd at least throw all the alternatives out there for you to decide what suits you best.
hopefully this is another bug that will make it into 2008 SP1 ;)
If you use XML literals in your code, adding one to another:
Dim e1 = <a:books></a:books>
dim e2 = <a:book></a:book>
e1.Add(e2)
You will have the xmlns declaration repeated in each of the elements, when really it is only needed once per the document or outer element. The problem is caused by VB adding a xmlns declaration as an attribute to the root element. It can get a bit more complex if you have duplicate namespace declarations with different prefixes. So I decided to write a CleanUpNS extension, that keeps the xml written clean by removing un-necessary namespace declarations. To use it, simply add a call to CleanUpNS to the end of your literals, e.g:
Dim e1 = <a:books></a:books>.CleanUpNS
dim e2 = <a:book></a:book>.CleanUpNS
e1.Add(e2)
<Runtime.CompilerServices.Extension()> _
Function CleanUpNS(ByVal el As XElement) As XElement
Dim current = el.LastAttribute
Do While current IsNot Nothing
Dim temp = current.PreviousAttribute
If current.IsNamespaceDeclaration AndAlso el.Name.NamespaceName = current.Value Then
current.Remove()
End If
current = temp
Loop
Return el
End Function
I go into more details about how this works and how the XML is stored and emitted in my January On VB article in Visual Studio Magazine.
Beth posted about the VS 2008 SDK saying it had many VB samples. When I installed it I didn't see any in the DSL tools, so I thought there weren't any at all. turns out there are some VB samples, but no DSL samples as well as others completely missing. This is what is there:
| | VS 2005 SDK | VS 2008 SDK |
| | C# | VB | C# | VB |
| Categories | 9 | 5 | 12 | 6 |
| Samples | 48 | 32 | 58 | 31 |
| Projects | 137 | 79 | 168 | 72 |
| Files | 1636 | 804 | 2296 | 731 |
Note:
The values for VS 2005 are for V4 after the extra VB samples are downloaded and installed. These didn't ship till only recently; prior to that there were only about 35 .vb files in total in the VS SDK.
File numbers and project numbers are based on search for .vb, .cs , .vbproj and .csproj files.
Despite VB being the *most popular* language on .NET, many teams over at Microsoft like to give VB the finger. But before I start on this month's FU awards, a big anti-fu award (aka kudos) goes to Don Box who said :
"I'd be an idiot not to walk in their shoes as much as possible"
Sadly, other teams at Microsoft still don't get that. So onto the FU list of shame for this month:
- First mention just has to go to the XNA team. Their continual bigotry is outstanding
- The Windows Workflow Foundation Hosting Quickstart Sample comes in at second place, delivering only C# templates. Well it's not like anyone who writes in VB would want templates for that now is it ?
- A contender for equal first place is the Windows Media Centre SDK team who sends out a very big FU to all you wanting to code in VB. They must figure media centre is too advanced for VB folk
- The Health SDK team only gets a minor mention this month as they release new downloads but still haven't included VB samples even after being requested to. Eric won the previous month's FU arrogance award.
- Arguably the number one spot has to go to the Visual Studio SDK team. They've released the 2008 SDK again with no VB samples for Controls, Debugger, DSL tools, Project or Team System Test. Like 2005 we'll probably have to wait 2 or 3 years till version 4 is released before they even think about releasing the VB samples as a separate download. Way to go team !!
So to this month's top five FU award winners, congratulations ! I salute you with my middle finger.
Kathleen has posted about a real nasty bug in the VB 9 (VB 2008) compiler. And I mean nasty !!
The compiler won't warn you, won't give an error of any sort.. it will just omit lines of code from your application ! Yep, it will compile as if nothing is wrong, yet it will remove your code !! If you're lucky, your test scenarios will pick up on this, otherwise expect the unexpected .
It'd be nice if the VB team would post about this and let us all know the exact scale of the problem and when a fix will be available.
If you install VS 2008 on a machine that has VS 2005 on it, you'll be prompted to let VS 2008 import as many of your settings from 2005 as possible. Generally this is a good thing, but you might run into some issues with code snippets as you might have both the 2005 and 2008 collections loaded in VS 2008.
The problem is Visual Studio stores snippets by default in the %InstallRoot%, which for VS 2005 is Program Files\Microsoft Visual Studio 8 and for VS 2008 it's Program Files\Microsoft Visual Studio 9.0. But when Visual Studio migrates your settings from 2005 to 2008, it just copies the registry value which include %InstallRoot% in the paths as a replacement variable. So what this means is if you modified the snippets by hand or using some other tool, your new snippets will NOT include the ones you previously modified.
If on the other hand you used the snippet editor in 2005, it saves the paths as the full path, so in VS 2008 you'll have both the 2005 paths and the 2008 paths. This also is not ideal. You can quickly remove the root folders you don't want by right clicking on them and selecting remove. (Note: root level folders are the folders stored in the registry and have a blue asterisk on them in the snippet editor)
In either scenario you are still faced with maintaining multiple collections of snippets by default. The best thing you can do is to create a folder in your user do documents folder, and then move sub folders and snippets to that path. This makes it easy to share snippets between versions of Visual Studio. You'll need to open the collections to remove the paths that are in the %InstallRoot%, but once done you have a centralized common folder tree for your snippets.
In fact, I like the idea of doing that so much, I think I will add a wizard to the Snippet Editor that does this for you. This would also let you have your snippets where you don't need administer rights to modify them.
There's also a couple of other minor changes I plan to make later this week, such as surfacing the collection selection onto the folder pane.
Oh, and if you are using the Snippet Editor as is with VS 2008 alongside VS 2005, you might be seeing duplicates for snippets in Visual Studio but not in the Snippet Editor. This is yet another one of the undocumented "quirks" about how Visual Studio deals with snippets. If you look in the languages\CodeExpansions key registry you'll probably see some values stored under "Basic" and others under "Visual Basic". This is a "temporary" state. If you run Visual Studio's Snippet Manager and click on the OK, it will remove the "Basic" key and put all the values under the "Visual Basic" key, at which point the Snippet Editor and VS's Snippet Manager will all be showing the same collection. When I wrote the Snippet Editor, once the "Visual Basic" key was established in the registry, it meant that the collection was already initialised. If it wasn't there then I'd initialise it for you. Same kind of thing with "CSharp" and "Visual C#". But now with 2008 that pattern has changed, as in both keys can be there.
Unfortunately little of this if any is documented, so it means my code has to be reactionary rather than pro-active: That is, I have to fix it when they do things that break it ;)
In VB9, there's a bug when using XML literals with any type member that is a protected keyword. For example, given the following psuedo types,
Class Doc
Public Property [Imports]() As List(Of DocImports)
End Class
Class DocImports
Public Property [Namespace]() As String
End Class
The following code won't compile:
Dim d As New Doc
Dim xml = <?xml version="1.0" encoding="utf-8"?>
<Imports>
<%= From item In d.Imports _
Select <Import><Namespace><%= item.Namespace %></Namespace></Import> %>
</Imports>
The trick is to escape the Imports property inside the the XML query:
Dim xml = <?xml version="1.0" encoding="utf-8"?>
<Imports>
<%= From item In d.[Imports] _
Select <Import><Namespace><%= item.Namespace %></Namespace></Import> %>
</Imports>
This seems to only apply to some keywords, not all. Imports, Sub, Function all cause the problem, yet Class, Private and Namespace don't. One thing you'll see is the <%= substitution block won't get the characteristic highlight colour.
And another quirk is if the property is called Option, VB will colour that as if it is a keyword even when it is a property such as stock.Option. This one only seems to impact Option, and does not impact the actual compile, only code aesthetics ;)
Kathleen talks about security being Vistas biggest asset.... for me, a power user who use to run XP in limited access mode, using run as admin scripts, it isn't really anymore secure. In fact, I now find it harder to find a good software firewall that shows me what's happening and allows me to easily change things. But for me, the biggest problem with Vista is I simply don't trust it. The reason for this is the shell is explorer right ? Yet explorer in vista is extremely buggy. Even though I have it set not to remember any folder views, it seems to randomly decide to change views as I browse from folder to folder. Then recently I had it no longer allow me to select any more than one file at a time ! To fix that I had to browse the online forums to find that I should try deleting mru bags or similar in the registry and also try resetting all views.
So am I really meant to feel that the software is secure when explorer itself is so incredibly buggy ? After all these years they still can't even write a reliable file explorer ! Given the short comings of such a major and central piece of software, it's hard for me to really believe that any of the rest is more secure. Like if you bought a new car that supposedly had improved safety features, yet the dash was rattling apart, would you really feel more safe in it ? With Vista I don't.
Just spotted it on MSDN subscriber downloads.
Enjoy :)
I see Paul Vick has suggested Ben Franklin as a better persona for VB than Mort. How very ironic !!
Ben has his picture on American currency... the $100 note in fact.
Yes that's right folks. the "C Note"
I wonder if he means sharp or flat ;)
I've finally given the Snippet Editor a major make over including a new look.
To go with this, I've given it a new home on my web site:
http://billmccarthy.com/Projects/Snippet_Editor
And I've added a Snippets category to this blog for feedback, info etc. I'll update the web page with new releases if/when they occur including a change history.
Enjoy :)
P.S. I'd love to get feedback on the new UI, especially the "About" screen ;)
Andrew Coates has a picture of what he coins an "illusion". I prefer to think of it as a perception, not an illusion. In the picture a square is rendered as being in the shade. So the mind adjusts what the colour actually is in full light based on surrounding information. The reason for this is so as we can readily identify things in changing light conditions. So there's that perception. And the other perception is the colour is as rendered, and it's the effective colour that's important. That's the view of the pixel in isolation, which is how a computer screen, a graphics card, or any other non intelligent hardware would "see" it. But let's assume the picture is in fact a 3D rendering of a cylinder on a checkered surface, and there is in fact shadows. If you move the cylinder so as there is no shadow over the centre square, that square would have to be rendered a lighter colour. But if the only information the computer has is the original picture it can't do that unless it tries to interpret surrounding data, much like what our brain does. The computer either has to have more information (such as the original 3D model), or it has to become smart like us; the alternative being the inability to render it correctly and the potential false assumption that the colour of the square has changed when the shadow is removed.
To the mind, it's not important to match the shadowed colour with a colour that isn't shadowed, rather the interpretation of the true colour is more important, and hence that's what we perceive. Ah the joys of the memories of all those hours I spent in psychology lectures :D
In playing with Windows.Forms in VS 2008, I got the same old error I use to get in VS 2005 sometimes:
Type must be a type provided by the runtime. Parameter name: type
The good news is it looks so much prettier in VS 2008. It's not fixed, but look, isn't it pretty ?
So why is it that the phrase "lipstick on a pig" come flooding into my mind ???
BTW: The fix is to show the DataSources window before trying to open the form designer
.
I've updated the Snippet editor to work with Visual Studio 2008 and 2005 releases.
Note this release requires .NET 3.5.
Changes/fixes:
- Added 2008 product range to the list of products
- Fixed replacement of the install root variable for Visual Studio that was resulting in a double \ midway of file paths
- Removed VB's single instancing and replaced it with named pipes messaging. This fixes various issues to do with firewalls, and the remoting VB tries to do. See Visual Studio Magazine November for details on the NamedPipes usage.
- Set the required permissions to run the application as Administrator for Vista. Without this, the app would run, but snippets would be saved in the VirtualStore where Visual Studio wouldn't see them properly. The problem revolves around Visual Studio having the snippet stores in the Program Files tree.
The download includes the source and the release build. (in the bin\release path)
UPDATE: The files are now available from my web site (http://billmccarthy.com/Projects/Snippet_Editor)
Enjoy :)
I recall almost four years ago to this day, I was at the 2003 PDC in LA. On the last day of the conference, the head architects of different .NET languages got together and talked about language directions, generics and some of the "VS 2005" stream of things. There was a Q&A session at the end, and I stood in line to ask a question about generics. They were about to cut off all questions, but I managed to ask the final question for the day. I asked about generics and "polymorphism". Anders didn't seem to quite get what I meant at first, then when I gave the example of being able to treat IList(of Apple) as IList(Of Fruit), he said "oh you mean generic covariance and contravariance" or words to that effect. The reply was no, saying the cost would be too high although he did suggest one of the other less common languages on .NET (no not VB <g>)
Fast forward four years, and now the C# team are finally talking about this ! At first I thought cool, Eric and the C# team are onto this. Then around his seventh or eight post on the topic he started to loose me as it seems they've shifted the focus on to a new syntax for defining the interfaces, which isn't really going to address the issue IMO. And I question just how that will surface in the IDE, and whether T is + or - really even makes sense at the interface level as it really needs depends on whether T is a return value or a parameter. Potentially I could see some advantage there, probably to do with that functional programming cloud, but it seems to have drifted away from the real need.
The most common need I see is when you have things such as a List(Of Customer) and you want to work with it as a List(Of BusinessBase). It's also especially difficult when you are passed the list as an Object, such as from a DataSource and you want to check to see if it is a IList(of BusinessBase). Really what we need is a view of the object.
Some views are safe, such as treating an IEnumerable(Of Customer) as IEnumerable(Of BusinessBase), but others are not, such as IList(Of Customer) to an IList(Of BusinessBase), but for the most part when we want those views we are interested in only the safe part. It's not like we can retrospectively change IList, or that at present we could have one Interface definition for the Item Get, and another for the Item Set. What would be nice is being able to use a view, and the compiler/IDE warn if you use any of the unsafe part, like Item Set, or if you pass the view to a method etc, yet allow you safely to do things such as access Count, get the Items and do operations on them as if they were business object base classes. These things are safe, yet today generics does not allow for that (note if you have generic parameters cascading throughout this issue does not arise, but that doesn't work with Object parameters, or current event design etc)
So some psuedo verbose code to explain what I would like:
' assume datasource is As Object, but is a IList(Of Customer)
If datasource IsViewable As IList(Of BusinessBase) Then
Dim view As ViewOf IList(Of BusinessBase) = ViewOf( datasource, IList(Of BusinessBase))
For i As Int32 = 0 to view.Count - 1
view(i).Validate ' legal as Validate is defined on BusinessBase
Dim temp as BusinessBase = view(i) ' legal
view(i) = temp ' compiler warning of potential runtime error
Next
Likewise you could create a ViewOf IList(Of Customer) from an IList(Of Person), but here the inverse would apply in code, meaning you could add a customer to the datasource, but you'd get a warning treating a person as a customer as that might not be the case.
If the datasource is as object though, the compiler can't know if the datasource is contra or co variant to the view. By default a "View" should be treated as a widening, that is a ViewOf IList(of BusinessBase), would mean the datasource is assumed to be a ViewOf IList(Of DerivedFromBusinessBase). The same rules for variance as we see today with delegate variance would apply. If the view wanted was one that is potentially unsafe, such as IList(Of Customer) from an IList(Of Person) then the view should be specified as a NarrowingView.
I don't want to redefine IList, or have to mess with defining which generic parameters are covariant and contravariant and where. What I want is to be able to deal with generic types with variance and create views such as the compiler tells me what is and isn't legal with that view, what's safe and what isn't. And most importantly it has to work with existing generic types and interfaces out there today.
So perhaps my response is four years late, but no I don't mean contravariance and covariance, I mean polymorphism :)
Paul Vick released some statistics in relation to VB, which for discussion sake I'll repeat here :
- Visual Basic is the #1 .NET language (as reported by Forrester Research)
- Visual Basic is the #1 downloaded and #1 registered Express Edition (topping the #2 position by 20%)
- Visual Basic is the #1 MSDN language dev center and blog in terms of traffic
- The Visual Basic Team blog is in the top 1% in readership of all MS bloggers (I don't know where I fall in that since I host independently.)
I think you'd have to be taking the happy pills to see anything great in those stats, after all they avoid real numbers and they don't tell the underlying trend or growth.
Five or so years ago, before .NET formally launched, Microsoft reported VB as being the *MOST* popular language of *ALL* programming languages. Reports from Forrester backs this up, and this graph from O'Reilly books shows that VB was the most popular titles.
Note in the above graph that VB was as popular as Java at the start of 2003 but has been on a steady decline. C# on the other hand was showing a slow but steady increase.
Forrester also in mid 2005 released these figures:
- Java's 66% penetration is the highest among strategic programming languages for enterprise applications.
- Visual Basic 6 (VB6) and C/C++ have nearly as much penetration as Java,
- Visual Basic .NET (VB.NET) had 34% penetration
- C# had 15% penetration
- If all VB6 users converted to VB.NET, its share would increase to 70%.
The last statistic is an interesting one, what it tells us is that VB was the most popular language, and by mid 2005 VB.NET had managed to attract less than half of those VB had prior to the move to .NET.
More recent statistics are harder to come by. Anecdotal reports are that book sales of C# related topics are out selling VB at the ratio of 2:1. If books aren't a great indicator of growth trends perhaps jobs are. Searches at seek.com.au show C# jobs running at 7 jobs per every 3 that specify VB. There's some overlap but that's still a greater than 2:1 ratio. Likewise jobs at monster.com tally up similarly. Interestingly both also show J2EE about on par with C# and Java slightly higher. If you combine VB and C# there's not much in it compared to Java overall in the job market.
So what of stats from Microsoft ? Surely Microsoft would have figures and be touting it's success ?? Well no, not really. These cryptic figures Paul released are all I can find except for anecdotal quotes such as the quote from Joe Stagner that there are more VBers than "C# folk but the gap is narrowing". So what is it Paul actually is telling us ?
1. Visual Basic is the #1 .NET language (as reported by Forrester Research)
Okay so VB has gone from being the most popular language, to being just the most popular on .NET, a relative decline in market share. And the titanic was still the biggest floating ship right up till the moment it sunk, even when it was taking on water. To take a language from the most popular of ALL languages, to one of just a subset of languages is a negative trend :(
2. Visual Basic is the #1 downloaded and #1 registered Express Edition (topping the #2 position by 20%)
That figure alone is to be expected given VB6 was the most popular. You'd expect those people to at least try out VB Express unless marketing really screwed up. Again it tells us nothing about forward trends, just an indication of the past penetration that was there
3. Visual Basic is the #1 MSDN language dev center and blog in terms of traffic
Again that related heavily to the previous versions of VB. If you visit the VB MSDN site, that's where you also find info on previous versions. Look at the downloads for VB, and even today the most popular download is Visual Basic 6.
4. The Visual Basic Team blog is in the top 1% in readership of all MS bloggers
There are about 4500 blogs on MSDN, so 1% is the top 45 blogs. What that is telling us is that the team blog for VB only rates in the top 45 of blogs for Microsoft's Developer Network blogs. What are the other 44 ? And what does that tells us ? That we should all be programming in Scobble ?
I think the sad truth is that VB continues to decline due to market place perception. VB is in fact a very capable language. In fact in many ways it is better than C#. Form a pure technical perspective VB is the best language of the two for working with COM legacy applications. In 2008, VB is also the best of the two for working with XML. C#'s only technical feature that gives it a real edge is unsafe code.
So why is VB declining while C# is on the rise ? Microsoft is heavily to blame here. Although they say you are free to choose what ever language you like, they don't do that, they continue to choose C# over VB and the market place knows that. Given it's their platform we are actually coding on, it's understandable that we view their developers as leaders. And they lead towards C#.
Cost and time also figure into it heavily. Microsoft has sent out a clear message that if you want to work with Windows Live Id, Windows Search, Health Vault, .NET Micro Framework, XNA, then they don't view VB as important enough for them to vest any time on, so why should/would you ? They've made it clear they are going to pigeon hole VB.
Let me give you an example. Let's say today you wanted to incorporate the latest from the Patterns and Practices team. If you go over to CodePlex, you'll find the latest code in C#. If you want to build your app, but still have the flexibility to make changes, you'll need to go with C#. In fact if you look over at CodePlex, you'll find that C# projects outweigh VB at the ratio of about 7 : 1. And many of those projects are lead by Microsoft employees as part of their day job.
This leading of community projects, the work being done internally around C# all lead to C# developing greater market share as well as improving C# itself as the language gets "dog-fooded" more by Microsoft, thus gaining input from some of the world's best developers from practical usage of it. It's self feeding.
For Microsoft as a whole, they look at .NET penetration. The increase in C# at the expense of VB doesn't really matter, it's overall market share that does. Except perhaps for one really telling statistic. As Forrester said, if all the VB community switched to VB.NET back in 2005, VB would have had 70% market penetration. Given such a huge potential, it has to be negligent to let that slip away, and instead favor a new language because internally more people at Microsoft used C++. Really, the question should have been was there ever any need for C# given VB's huge market share ? Now the question is beginning to be the opposite.
And so it goes, we should be happy when they tell us how many deck chairs on the titanic, that the ship is unsinkable, yet we see the water line drawing nearer and nearer.......
I've been rummaging through the Windows Vista User Interface Experience Guidelines draft, a 33 MB pdf file, and it poses some interesting questions around warning and exception dialog messages. Now apparently it is not OK to present the user with an exception message and an OK button. Instead the guidelines recommend the button caption should be "Close". Is that close as in "so close but yet so far" ? Or close as in we're about to shut down your application and windows and you'll loose all unsaved work ? (that one always gets people when you use a modal dialog <g>) .
Close seems incredibly wrong to me. In fact I'm sure when I've assisted folks over the phone and some other application or windows has presented them with only the option of "close" it has caused much angst. I raised this with Nick Randolph and he suggested that perhaps a better caption would be "Continue" . I think that's a good option in some cases. In others where you can't continue as such, instead you "Resume" and in others you might go back to the screen/page from where you launched the original request, hence "Back".
Continue, Resume, Back, and dare I even suggest Retry or Ignore, but not Close.