I have installed Portable Ubuntu under Windows XP and have been configuring it to run some experiments.
Portable Ubuntu is conceptually like running Ubuntu in a virtual machine, except that the Windows all feel like native Windows windows.
Actually getting it working properly involves a bit of tweaking. Here is a summary of what I have done.
First of all, the default install button on SourceForge doesn't actually point to the full install. You can get it from the folder labeled TRES.
To run, just invoke pubuntu.exe. Start up takes a while -- actually as long as a normal boot sequence. To see the boot messages, single click on the Portable Ubuntu icon in the system tray.
The very first thing I would recommend is to disable the Ubuntu screen saver, otherwise your windows will lock up after a period of inactivity and there's no way to unlock them. You can disable the screen saver in System/Preferences/Screen Saver in the GUI.
Portable Ubuntu comes with Open Office. I am running experiments and have no interest in word processing applications. I saved 366MB disk space by removing Open Office:
sudo apt-get remove openoffice*
The default root password is 123456.
To give Ubuntu access to your drive c:, you need to edit a file in your Windows file system. Go the directory where pubuntu.exe lives, and edit the file config\portable_ubuntu.conf. Add the following line:
shared_folder0=c:\
While you're in that file, you might want to increase the amount of RAM allocated to Linux too. You have to restart your Portable Ubuntu session for these changes to take effect.
On start-up your drive C: should be mounted and available as /media/cofs2.
To enable DNS resolution, inside your Portable Ubuntu session, edit the file /etc/dhcp3/dhclient.conf to specify the DNS servers to use. To use the Open DNS servers, add the following line before the request line.
prepend domain-name-servers 208.67.222.222,208.67.220.220;
On start up I often get an error about not being able to mount the Linux partition. There's extensive discussion and some good solutions on this Ubuntu forum. People offer various partial solutions like dropping into an emergency console during boot up and typing:
mount -o remount /
Then Ctrl-D to exit the emergency console
But these mask the underlying issue: one of the start up scripts has inserted a line containing -e into the /etc/fstab file, which causes mounting of volumes to fail.
I finally resolved this. Portable Ubuntu copies aside your /etc/fstab file and makes its own during startup. Inside Portable Ubuntu you can edit the version it copied aside. It's called /etc/fstab.pubuntu.bak. Remove the line that says -e. Shut down Portable Ubuntu. This will copy back fstab.pubuntu.bak to fstab. Restart pubuntu.exe. Problem solved.
Friday, 15 October 2010
Thursday, 30 September 2010
Emoticons: no noses please
I work on text input for mobile devices, e.g. making it easier to type text messages.
Recently we have been reviewing our support for entering emoticons. In one meeting, I observed that it seems to be more common to type emoticons without noses than with them these days. Since we take an empirical approach to these questions, we thought we'd look at our English web corpus. Sure enough, in the period 2007 to early 2010, the nose-less forms are about four times more common than the nose forms i.e. :) beats :-) and ;) beats ;-).
This is of course a perfectly natural linguistic development: words undergo reduction in form over time. It'd be fascinating to take a finer-grained look at the frequencies.
Recently we have been reviewing our support for entering emoticons. In one meeting, I observed that it seems to be more common to type emoticons without noses than with them these days. Since we take an empirical approach to these questions, we thought we'd look at our English web corpus. Sure enough, in the period 2007 to early 2010, the nose-less forms are about four times more common than the nose forms i.e. :) beats :-) and ;) beats ;-).
This is of course a perfectly natural linguistic development: words undergo reduction in form over time. It'd be fascinating to take a finer-grained look at the frequencies.
Wednesday, 16 June 2010
ActiveState Komodo IDE 5.2
I have been using ActiveState Komodo on Windows for almost a year now, mostly for Python development, with some legacy Perl maintenance and Bash scripting.
Komodo is a solid but unexciting IDE. It makes a fair stab at providing contextual information in dynamic languages and does a very good job at flagging syntax errors.
One thing it is really not very good at is multi-monitor support. The various panels and sub-windows are all solidly docked in the parent window and cannot be dragged to a second monitor, which severely impacts how much code you can see at once.
The other not-so-great thing is start up time, which can take the better part of a minute if it's reopening a few dozen very small source files. This is a small complaint since I really only start it after a machine restart and that doesn't happen very often.
Komodo is a solid but unexciting IDE. It makes a fair stab at providing contextual information in dynamic languages and does a very good job at flagging syntax errors.
One thing it is really not very good at is multi-monitor support. The various panels and sub-windows are all solidly docked in the parent window and cannot be dragged to a second monitor, which severely impacts how much code you can see at once.
The other not-so-great thing is start up time, which can take the better part of a minute if it's reopening a few dozen very small source files. This is a small complaint since I really only start it after a machine restart and that doesn't happen very often.
Friday, 17 April 2009
Cross-site XMLHttpRequest in Javascript
You know how sometimes you put together a simple bit of code and things seem fine but in the back of your mind you think there might be an issue. So you try another scenario/browser and sure enough it doesn't work and you remember why? Well that's what happened a few days ago.
I decided to put together a fairly straightforward site that would let users search for jobs across a range of Craigslist sites. My first impulse was to do this in ASP.Net, doing the scraping on the server side. But Craigslist takes a dim view of people scraping their content and repackaging it.
The next solution I explored was a simple bit of Javascript that would run client-side. The user would fill in a simple form, press go and the Javascript would use XMLHttpRequest to grab search results from Craigslist. It sounds simple enough and worked in IE7.
I had a nagging feeling that I had been reading something recently about cross-site XMLHttpRequests. Sure enough, in the latest incarnation of Firefox, the code didn't work at all, and in VS2008 in the debugger it threw security exceptions.
Cross-site XMLHttpRequest is now severely restricted/forbidden.
I put together a C# WinForms app to do it all for me. It works like a charm. I can now search for telecommuting opportunities across a range of Craigslist sites. The tool is a convenience app that federates user queries. It's a classic case of developers writing the tools that they want for themselves.
I will make the tool available for others shortly. I'll use it for a few days before releasing it. It's always a good idea to let things sit for a day or two.
I spent two hours today bringing the code into conformance with StyleCop. I have mixed feelings about StyleCop. It can be persnickety (Boolean properties with getters and setters have to have XML documentation that starts with the exact words "Gets or sets a value indicating whether...") but a lot of the advice is good. I particularly like the warnings about the correct implementation of IEnumerable<> and IDisposable. By now I have internalized the normative rules concerning casing of variables, methods etc and the ordering of members of a class according to visibility. The added benefit that I derive from using StyleCop is similar to a code-review -- it forces me to reexamine some pieces of code that in hindsight could do with reworking.
I decided to put together a fairly straightforward site that would let users search for jobs across a range of Craigslist sites. My first impulse was to do this in ASP.Net, doing the scraping on the server side. But Craigslist takes a dim view of people scraping their content and repackaging it.
The next solution I explored was a simple bit of Javascript that would run client-side. The user would fill in a simple form, press go and the Javascript would use XMLHttpRequest to grab search results from Craigslist. It sounds simple enough and worked in IE7.
I had a nagging feeling that I had been reading something recently about cross-site XMLHttpRequests. Sure enough, in the latest incarnation of Firefox, the code didn't work at all, and in VS2008 in the debugger it threw security exceptions.
Cross-site XMLHttpRequest is now severely restricted/forbidden.
I put together a C# WinForms app to do it all for me. It works like a charm. I can now search for telecommuting opportunities across a range of Craigslist sites. The tool is a convenience app that federates user queries. It's a classic case of developers writing the tools that they want for themselves.
I will make the tool available for others shortly. I'll use it for a few days before releasing it. It's always a good idea to let things sit for a day or two.
I spent two hours today bringing the code into conformance with StyleCop. I have mixed feelings about StyleCop. It can be persnickety (Boolean properties with getters and setters have to have XML documentation that starts with the exact words "Gets or sets a value indicating whether...") but a lot of the advice is good. I particularly like the warnings about the correct implementation of IEnumerable<> and IDisposable. By now I have internalized the normative rules concerning casing of variables, methods etc and the ordering of members of a class according to visibility. The added benefit that I derive from using StyleCop is similar to a code-review -- it forces me to reexamine some pieces of code that in hindsight could do with reworking.
Thursday, 5 March 2009
Version Control
Version control is a vitally important part of software development. But really, who wants to get it all set up for small projects?
Well this is the age of free/cheap hosting. I have a wonderful solution going. I am using Unfuddle.com for free SVN hosting and AnkhSVN as the version control provider for Visual Studio 2008. It's a great combination. AnkhSVN integrates seamlessly into Visual Studio. As an added bonus, Unfuddle provides a defect ticket system.
Well this is the age of free/cheap hosting. I have a wonderful solution going. I am using Unfuddle.com for free SVN hosting and AnkhSVN as the version control provider for Visual Studio 2008. It's a great combination. AnkhSVN integrates seamlessly into Visual Studio. As an added bonus, Unfuddle provides a defect ticket system.
C# interop
C# interop with unmanaged code is not nearly as difficult in practice as it sounds on paper. Most of the interop I have done has been COM (to/from managed code) but for my current freelance gig I need to call from C# into an ANSI C DLL.
I wrote a few simple ANSI C functions to act as the interface to my managed code, just to save some work. I could call them fine. Crucially, I could pass in ANSI strings and get them back.
Then I started getting an AccessViolationException "Attempted to read or write protected memory". I was positive that I had annotated the ANSI C code correctly to export the functions. The C# code had the appropriate DllImport decorations. C# and ANSI C thought the function was CDECL. Everything looked just fine.
The symptoms were downright peculiar. If I declared a local variable in the ANSI C function that I was calling the code threw the exception. If I attempted to call another function from inside the ANSI C function the code threw the exception.
As with so many things, it boiled down to an incorrect setting in the project file, a residual glitch from the fact that I first produced an EXE to exercise the code and then flipped to producing a DLL.
Along the way I learned that I don't need to mess about with IntPtr allocation and freeing. When I have a mutable string (e.g. the result is returned in a char* parameter), I can create a StringBuilder with the appropriate size and pass that from C#. C# marshals it for me.
I wrote a few simple ANSI C functions to act as the interface to my managed code, just to save some work. I could call them fine. Crucially, I could pass in ANSI strings and get them back.
Then I started getting an AccessViolationException "Attempted to read or write protected memory". I was positive that I had annotated the ANSI C code correctly to export the functions. The C# code had the appropriate DllImport decorations. C# and ANSI C thought the function was CDECL. Everything looked just fine.
The symptoms were downright peculiar. If I declared a local variable in the ANSI C function that I was calling the code threw the exception. If I attempted to call another function from inside the ANSI C function the code threw the exception.
As with so many things, it boiled down to an incorrect setting in the project file, a residual glitch from the fact that I first produced an EXE to exercise the code and then flipped to producing a DLL.
Along the way I learned that I don't need to mess about with IntPtr allocation and freeing. When I have a mutable string (e.g. the result is returned in a char* parameter), I can create a StringBuilder with the appropriate size and pass that from C#. C# marshals it for me.
Sunday, 1 March 2009
Rebuilding machines
This past month has been the month of installing stuff. My wife's hard drive crashed. I managed to resuscitate it enough to pull most data off, then dropped a new drive in. I got a new laptop (an insurance replacement for the laptop that got stolen from our house) and had to set that up. Then serious issues with my primary machine. I am now freelancing. None of this is billable time of course.
My primary machine is a seven (!) year old Dell. It has served me well. Lately I have had difficulty installing software, especially some Windows Updates and Visual Studio 2008. The errors have never been very helpful but in the event logs I could see recurring errors with the Cryptographic Provider Service not being able to start. The error is simply "error: 193".
It seems that people had big issues with the Cryptographic Service in 2003-2004 associated with some service packs, but none of the solutions from that time (deleting corrupt databases so it would rebuild them, checking your "Trusted Root Certification Authorities") made a bit of difference.
In the end I reinstalled the Windows XP Pro, then all my usual applications, then various service packs (SP3 can't be installed without a prior SP; SP1 is not available; SP2 can be installed without anything prior), drivers from Dell etc.
This past month has blown out our data caps several times. New Zealand ISPs charge by data throughput. We have a 5Gb per month allocation. This past month we used 14Gb. Of course, downloading a 1.7Gb IDE for iPhone development didn't help.
My primary machine is a seven (!) year old Dell. It has served me well. Lately I have had difficulty installing software, especially some Windows Updates and Visual Studio 2008. The errors have never been very helpful but in the event logs I could see recurring errors with the Cryptographic Provider Service not being able to start. The error is simply "error: 193".
It seems that people had big issues with the Cryptographic Service in 2003-2004 associated with some service packs, but none of the solutions from that time (deleting corrupt databases so it would rebuild them, checking your "Trusted Root Certification Authorities") made a bit of difference.
In the end I reinstalled the Windows XP Pro, then all my usual applications, then various service packs (SP3 can't be installed without a prior SP; SP1 is not available; SP2 can be installed without anything prior), drivers from Dell etc.
This past month has blown out our data caps several times. New Zealand ISPs charge by data throughput. We have a 5Gb per month allocation. This past month we used 14Gb. Of course, downloading a 1.7Gb IDE for iPhone development didn't help.
Sunday, 11 January 2009
Evidence for the AppDomain: The resolution
To recap what has been a continuing saga: I discovered that attempts to get Streams on PackageParts in an OpenXML Package were failing because of an issue in the .Net framework. Under the hood, a MemoryStream was overflowing to disk. The framework examines the evidence of the assembly and then examines the evidence of the AppDomain. Our managed COM component was getting created in the DefaultDomain and didn't have the evidence (a SecurityZone of MyComputer) that was needed to satisfy the framework.
As I discussed here, I resolved this by having the COM interface act as a shim. It created a second AppDomain that had the evidence necessary to satisfy the framework.
Further testing did not reveal any more show-stoppers but it was obvious that performance was not great. Large blobs of XML were being marshaled across AppDomain boundaries (from the child AppDomain to the DefaultDomain) and then marshalled again across the COM boundary to the Win32 application.
I briefly considered hosting the CLR so that I could explicitly create the AppDomain of my dreams but decided I'd really rather not.
Fortunately help came in the form of this post. (Can I just say how great it is that everyone with a keyboard in Microsoft seems to be blogging these days. Shawnfa's posts have been a great help.)
To summarize: you don't have to do all the work of hosting the CLR. You can just write (in managed code) an AppDomainManager and tell the CLR (by setting two environment variables) to use it.
This was almost the complete answer to my problem: when an AppDomain gets created I can add the Evidence I need, namely a SecurityZone of MyComputer. Sure enough, when I set the environment variables and my managed COM component gets called, I see a new instance of my AppDomainManager get called. But the CreateDomain() method never gets called. The CLR is just loading my COM component into the DefaultDomain; it's not making a new AppDomain.
It's almost the solution though. It's apparent that my AppDomainManager is getting called, and that the HostSecurityManager property is being used by the framework to make decisions. All I need is for that property to return my own subclass of a HostSecurityManager with the evidence set. In my subclass, I override the method ProvideAppDomainEvidence to provide the Evidence that I need.
Now my COM component works like a charm! Performance has improved too. We are marshaling large XML blobs across COM boundaries but at least we aren't also marshaling across the boundary to a second AppDomain.
As I discussed here, I resolved this by having the COM interface act as a shim. It created a second AppDomain that had the evidence necessary to satisfy the framework.
Further testing did not reveal any more show-stoppers but it was obvious that performance was not great. Large blobs of XML were being marshaled across AppDomain boundaries (from the child AppDomain to the DefaultDomain) and then marshalled again across the COM boundary to the Win32 application.
I briefly considered hosting the CLR so that I could explicitly create the AppDomain of my dreams but decided I'd really rather not.
Fortunately help came in the form of this post. (Can I just say how great it is that everyone with a keyboard in Microsoft seems to be blogging these days. Shawnfa's posts have been a great help.)
To summarize: you don't have to do all the work of hosting the CLR. You can just write (in managed code) an AppDomainManager and tell the CLR (by setting two environment variables) to use it.
This was almost the complete answer to my problem: when an AppDomain gets created I can add the Evidence I need, namely a SecurityZone of MyComputer. Sure enough, when I set the environment variables and my managed COM component gets called, I see a new instance of my AppDomainManager get called. But the CreateDomain() method never gets called. The CLR is just loading my COM component into the DefaultDomain; it's not making a new AppDomain.
It's almost the solution though. It's apparent that my AppDomainManager is getting called, and that the HostSecurityManager property is being used by the framework to make decisions. All I need is for that property to return my own subclass of a HostSecurityManager with the evidence set. In my subclass, I override the method ProvideAppDomainEvidence to provide the Evidence that I need.
Now my COM component works like a charm! Performance has improved too. We are marshaling large XML blobs across COM boundaries but at least we aren't also marshaling across the boundary to a second AppDomain.
Link multiple .netmodule files
This past week I was attempting to add evidence to an assembly directly, i.e. to bake it into the DLL, to satisfy some security requirements. The .Net linker (al.exe) has an option (/evidence:) that lets you add a serialized Evidence object as a resource with the magic name Security.Evidence. There is some discussion of producing this resource file here.
A little poking around on the web showed me how to compile to .netmodule files, which seemed analogous to .obj files in the C++ Win32 world. I had to rework the .csproj file produced by Visual Studio so that I could invoke msbuild and produce one .netmodule file for each .cs file, build the resources etc and then link.
Everything appeared to work just fine. The link stage didn't give any errors or warnings. Curiously, the resulting DLL was only about 8Kb in size. The assembly when produced in Visual Studio from the .csproj file is a little more than 1Mb.
This turns out to be "by design". You can indeed compile to a .netmodule and link but if you have more than one .netmodule file it really is not analogous to the linking of various C++ obj files to produce a single DLL. Instead, the resulting assembly is a meta-assembly. It contains references to the various .netmodule files, which you would have to deploy with the assembly.
Luckily all was saved when I realized that I could compile all the files and produce a single assembly directly using csc.exe (the command line C# compiler). I just needed to specify a resource file containing the serialized Evidence and name the resource Security.Evidence. Indeed, it would seem there is little that you can do with the linker (al.exe) that you couldn't just do with csc.exe (the command line compiler), a point made here.
A little poking around on the web showed me how to compile to .netmodule files, which seemed analogous to .obj files in the C++ Win32 world. I had to rework the .csproj file produced by Visual Studio so that I could invoke msbuild and produce one .netmodule file for each .cs file, build the resources etc and then link.
Everything appeared to work just fine. The link stage didn't give any errors or warnings. Curiously, the resulting DLL was only about 8Kb in size. The assembly when produced in Visual Studio from the .csproj file is a little more than 1Mb.
This turns out to be "by design". You can indeed compile to a .netmodule and link but if you have more than one .netmodule file it really is not analogous to the linking of various C++ obj files to produce a single DLL. Instead, the resulting assembly is a meta-assembly. It contains references to the various .netmodule files, which you would have to deploy with the assembly.
Luckily all was saved when I realized that I could compile all the files and produce a single assembly directly using csc.exe (the command line C# compiler). I just needed to specify a resource file containing the serialized Evidence and name the resource Security.Evidence. Indeed, it would seem there is little that you can do with the linker (al.exe) that you couldn't just do with csc.exe (the command line compiler), a point made here.
Monday, 15 December 2008
Unable to determine the identity of domain
Don't you just hate it when you have some code that works fine in your development environment but not when you hand it to testers?
Loyal readers might recall that I have been migrating a bunch of legacy Win32 code to .Net. In the case of our GUI editor, that people use to map out their business processes, I have been writing a C# COM component that gets called from the legacy Delphi.Win32 code. Gradually more and more functionality is migrating to C#.
Along the way we have been storing the user's business process map in an OpenXML package. This is basically a ZIP file containing images, the model XML and bits of XML specifying how things are connected. Then it's a case of using System.IO.Packaging to get at it all.
Testing discovered that some larger client models were failing to upgrade with the mysterious error message "Unable to determine the identity of domain". This turns out to have nothing to do with Windows domains or user permissions.
As with all things .Net, someone somewhere has no doubt hit this problem before. Kevin Rohrbaugh had a similar scenario
http://www.coderoni.com/2008/04/04/server-side-office-document-generation-bug/. His workaround was to ensure that they were running under an account that did not have a profile on the local machine (more below). That's not an option for us.
I'll spare you a gruesome recap of the full debugging which involves much "spelunking" with Reflector as Kevin so aptly calls it. Here are the broad strokes:
When you get a stream on a part in an OpenXML package (so that you can get at the uncompressed bits), you think you are getting something in-memory. However, if the package part is too big (more than 1.3Mb compressed), the framework decides to unzip the entire package part to disk and to give you a handle on that instead. This has unforeseen performance consequences, but we'll ignore them for now.
Where does it unzip them to? Isolated Storage. Exactly what kind of isolated storage depends on the user account you are running under. If you are running under a user account that doesn't have a profile on the local machine, the framework uses a machine-scoped location. If you are running under an account that does have a profile on the local machine (as we will be -- it'll be running under the account of the user of the GUI tool) it uses a user-scoped account.
If I add a reference to the assembly containing the code that accesses the package, and run it in the debugger all is well. But under COM all is far from well.
Running reflector on the Isolated Package class shows that when using user-scoped isolated storage, the framework examines the "evidence" of the AppDomain (where an AppDomain is a lightweight process). Under COM, we are running in a DefaultDomain that doesn't have any evidence.
You can't set the evidence for an AppDomain once it has been started and it's not possible to specify that the COM DLL should run with certain evidence or in a special AppDomain. Running the "Microsoft .NET Framework 2.0 Configuration" tool and granting Full Trust to our assembly doesn't solve the problem because there is still no "evidence" for the Framework code to examine. So there are two options:
1) In the Win32 code, host the CLR, create an AppDomain with the appropriate evidence and load the assembly. Use reflection to get at the methods.
2) (What I did in the interests of expediency). In the COM component, create a new AppDomain with the appropriate evidence. and execute the code in that. This works fine. There is a performance hit because we are now marshaling across AppDomains as well as marshaling across COM. We will see if the performance is acceptable. If not we will have to go with (1).
Doing (2) is similar to what you have to do for Office add-ins. For Office add-ins, the recommended strategy to satisfy the security model is to have an unmanaged shim. You sign the shim to make Office happy. Office talks to the shim, the shim acts as a proxy passing everything to your managed code.
In our case, the COM interface now loads up the AppDomain and proxies calls to an instance of our class running in that AppDomain.
The crucial (necessary and sufficient) piece of evidence is that we require the code to be running in the MyComputer zone.
First we need a simple AppDomainSetup:
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory.ToString();
Then we need our evidence
Evidence evidence = new Evidence();
evidence.AddHost(new Zone(SecurityZone.MyComputer));
Now we can fire up an AppDomain running with that evidence.
AppDomain hostedAppDomain = AppDomain.CreateDomain("Demo", evidence, setup);
Now we get a handle on an instance of our class running in that AppDomain
ObjectHandle handle = hostedAppDomain.CreateInstance("MyStuff.Demo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d0e8b069449d61a1", "MyStuff.Demo.DemoComponent");
To pull this off, DemoComponent has to inherit from MarshalByRefObject so now we have a little .Net remoting magic to do. We have to get a lease on the object and extend its lease if we are not done with it. A trivial class LicenseRenewer that implements ISponsor does the trick
lease = (ILease)handle.GetLifetimeService();
lease.Register(leaseRenewer);
Finally we can get a usable instance of the class. We access this locally and it transparently proxies calls to the other AppDomain.
demoComponent = (IDemoComponent)handle.Unwrap();
Now calls to our COM interface can just explicitly proxy to demoComponent e.g.
public bool Demo()
{
return demoComponent.Demo();
}
Then our COM interface just proxies things to demoComponent. Any types you want to marshall across AppDomains have to marked [Serializable()] of course.
Loyal readers might recall that I have been migrating a bunch of legacy Win32 code to .Net. In the case of our GUI editor, that people use to map out their business processes, I have been writing a C# COM component that gets called from the legacy Delphi.Win32 code. Gradually more and more functionality is migrating to C#.
Along the way we have been storing the user's business process map in an OpenXML package. This is basically a ZIP file containing images, the model XML and bits of XML specifying how things are connected. Then it's a case of using System.IO.Packaging to get at it all.
Testing discovered that some larger client models were failing to upgrade with the mysterious error message "Unable to determine the identity of domain". This turns out to have nothing to do with Windows domains or user permissions.
As with all things .Net, someone somewhere has no doubt hit this problem before. Kevin Rohrbaugh had a similar scenario
http://www.coderoni.com/2008/04/04/server-side-office-document-generation-bug/. His workaround was to ensure that they were running under an account that did not have a profile on the local machine (more below). That's not an option for us.
I'll spare you a gruesome recap of the full debugging which involves much "spelunking" with Reflector as Kevin so aptly calls it. Here are the broad strokes:
When you get a stream on a part in an OpenXML package (so that you can get at the uncompressed bits), you think you are getting something in-memory. However, if the package part is too big (more than 1.3Mb compressed), the framework decides to unzip the entire package part to disk and to give you a handle on that instead. This has unforeseen performance consequences, but we'll ignore them for now.
Where does it unzip them to? Isolated Storage. Exactly what kind of isolated storage depends on the user account you are running under. If you are running under a user account that doesn't have a profile on the local machine, the framework uses a machine-scoped location. If you are running under an account that does have a profile on the local machine (as we will be -- it'll be running under the account of the user of the GUI tool) it uses a user-scoped account.
If I add a reference to the assembly containing the code that accesses the package, and run it in the debugger all is well. But under COM all is far from well.
Running reflector on the Isolated Package class shows that when using user-scoped isolated storage, the framework examines the "evidence" of the AppDomain (where an AppDomain is a lightweight process). Under COM, we are running in a DefaultDomain that doesn't have any evidence.
You can't set the evidence for an AppDomain once it has been started and it's not possible to specify that the COM DLL should run with certain evidence or in a special AppDomain. Running the "Microsoft .NET Framework 2.0 Configuration" tool and granting Full Trust to our assembly doesn't solve the problem because there is still no "evidence" for the Framework code to examine. So there are two options:
1) In the Win32 code, host the CLR, create an AppDomain with the appropriate evidence and load the assembly. Use reflection to get at the methods.
2) (What I did in the interests of expediency). In the COM component, create a new AppDomain with the appropriate evidence. and execute the code in that. This works fine. There is a performance hit because we are now marshaling across AppDomains as well as marshaling across COM. We will see if the performance is acceptable. If not we will have to go with (1).
Doing (2) is similar to what you have to do for Office add-ins. For Office add-ins, the recommended strategy to satisfy the security model is to have an unmanaged shim. You sign the shim to make Office happy. Office talks to the shim, the shim acts as a proxy passing everything to your managed code.
In our case, the COM interface now loads up the AppDomain and proxies calls to an instance of our class running in that AppDomain.
The crucial (necessary and sufficient) piece of evidence is that we require the code to be running in the MyComputer zone.
First we need a simple AppDomainSetup:
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory.ToString();
Then we need our evidence
Evidence evidence = new Evidence();
evidence.AddHost(new Zone(SecurityZone.MyComputer));
Now we can fire up an AppDomain running with that evidence.
AppDomain hostedAppDomain = AppDomain.CreateDomain("Demo", evidence, setup);
Now we get a handle on an instance of our class running in that AppDomain
ObjectHandle handle = hostedAppDomain.CreateInstance("MyStuff.Demo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d0e8b069449d61a1", "MyStuff.Demo.DemoComponent");
To pull this off, DemoComponent has to inherit from MarshalByRefObject so now we have a little .Net remoting magic to do. We have to get a lease on the object and extend its lease if we are not done with it. A trivial class LicenseRenewer that implements ISponsor does the trick
lease = (ILease)handle.GetLifetimeService();
lease.Register(leaseRenewer);
Finally we can get a usable instance of the class. We access this locally and it transparently proxies calls to the other AppDomain.
demoComponent = (IDemoComponent)handle.Unwrap();
Now calls to our COM interface can just explicitly proxy to demoComponent e.g.
public bool Demo()
{
return demoComponent.Demo();
}
Then our COM interface just proxies things to demoComponent. Any types you want to marshall across AppDomains have to marked [Serializable()] of course.
Tuesday, 30 September 2008
Open XML
I am working on a report that a few customers are very keen on. We take the description of roles and business processes and produce a role/task matrix to show which roles can perform which operations in the business.
The HTML version of the output is a thing of beauty if I say so myself. It has lots of merged rows so that we can represent a process consisting of several stages then in each cell in the matrix we have a pretty icon that shows the effective permissions.
Now the task is to produce the same thing in Excel. We'll be targeting Excel 2007, which means using the Open XML package format. No problem there. As mentioned in earlier postings, I have been converting our file formats to that format anyway. But now it's time to grapple with the issue of images in Excel. When you think of a tabular representation of data like this in HTML, you think of cells containing (references to) images. In Excel, however, the cells contain data and somewhere else altogether is some DrawingML that specifies what the icons look like and where they go.
I have started doing some investigation of the DrawingML but quotes like this make me think I might have a steep learning curve:
http://openxmldeveloper.org/articles/2327.aspx
"The attribute “editAs” specifies how the drawing object is moved/resized when the rows and columns are resized. For the possible values and their details, refer to page 4765 of the ECMA Open XML specification document."
Ah yes, the infamous 6,000 page document submitted for standards approval. I sense some work ahead of me.
The HTML version of the output is a thing of beauty if I say so myself. It has lots of merged rows so that we can represent a process consisting of several stages then in each cell in the matrix we have a pretty icon that shows the effective permissions.
Now the task is to produce the same thing in Excel. We'll be targeting Excel 2007, which means using the Open XML package format. No problem there. As mentioned in earlier postings, I have been converting our file formats to that format anyway. But now it's time to grapple with the issue of images in Excel. When you think of a tabular representation of data like this in HTML, you think of cells containing (references to) images. In Excel, however, the cells contain data and somewhere else altogether is some DrawingML that specifies what the icons look like and where they go.
I have started doing some investigation of the DrawingML but quotes like this make me think I might have a steep learning curve:
http://openxmldeveloper.org/articles/2327.aspx
"The attribute “editAs” specifies how the drawing object is moved/resized when the rows and columns are resized. For the possible values and their details, refer to page 4765 of the ECMA Open XML specification document."
Ah yes, the infamous 6,000 page document submitted for standards approval. I sense some work ahead of me.
Thursday, 28 August 2008
Start 'em young
My 6.5 year old son was off school sick yesterday. I decided it's time to introduce him to the joys of coding. What better language than Logo to get someone started. I know, I know, it's really a symbolic processing language with a noble Lisp pedigree and so much more than turtle graphics, but turtle graphics seemed like a good place to start.
We used a browser-based Logo implementation at http://www.calormen.com/Logo. It's a site that won't win any beauty contests, but it seemed fairly functional. I explained the underlying metaphor of the turtle with a pen that can be raised or lowered and showed him how to draw a few simple things by a sequence of commands e.g. fd 100 rt 90 fd 100 rt 90 fd 100 rt 90 fd 100. That seemed to make sense once I explained how 90 degrees meant going from vertical to horizontal. This is the kid who asked me when he was four if two dots could ever make a curve, so I figured he'd be good.
He immediately wanted to try a few things, like moving the turtle forward 1,000. I just let him try and see. Whoa! The turtle goes out of the visible region. We cleared the screen (cs) and tried some more things. What happens if you go forward a really large number like 100000000000000. I was expecting an error but no it just went out of the visible region. What happens if you turn right one degree and draw?
Interestingly he said he was "asking" the turtle to do things although after listening to me referring to "commands" he started to say he was "commanding" it to do things. I left him to experiment on his own for a while.
Perhaps next time we'll do some control structures. Perhaps something simple like repeat 4 [ rt 90 fd 100].
We used a browser-based Logo implementation at http://www.calormen.com/Logo. It's a site that won't win any beauty contests, but it seemed fairly functional. I explained the underlying metaphor of the turtle with a pen that can be raised or lowered and showed him how to draw a few simple things by a sequence of commands e.g. fd 100 rt 90 fd 100 rt 90 fd 100 rt 90 fd 100. That seemed to make sense once I explained how 90 degrees meant going from vertical to horizontal. This is the kid who asked me when he was four if two dots could ever make a curve, so I figured he'd be good.
He immediately wanted to try a few things, like moving the turtle forward 1,000. I just let him try and see. Whoa! The turtle goes out of the visible region. We cleared the screen (cs) and tried some more things. What happens if you go forward a really large number like 100000000000000. I was expecting an error but no it just went out of the visible region. What happens if you turn right one degree and draw?
Interestingly he said he was "asking" the turtle to do things although after listening to me referring to "commands" he started to say he was "commanding" it to do things. I left him to experiment on his own for a while.
Perhaps next time we'll do some control structures. Perhaps something simple like repeat 4 [ rt 90 fd 100].
Friday, 1 August 2008
F5 / F9
I am slowly but surely going mad. I am currently grafting some lovely shiny C# 3.5 code on to the side of our legacy Delphi.Win32 code. This means working in Visual Studio and the Delphi IDE simultaneously.
I doubt that I will ever love the Delphi IDE. OK, I am still annoyed that it was crashing 20 times per day (literally -- I took to obsessively recording them) until I applied the service pack, but at least it's stable now. The IDE lacks the most basic functionality: no moving the cursor back to a line before this one, no clicking on a point in the call stack and having it set the frame so you can inspect variables at that point, no examining the values of variables if an exception gets thrown. Still, I don't have to love it. Delphi is obviously circling the drain as a development environment. Their latest schedule of coming features makes it obvious they are a few years behind the curve. Coming real soon, Unicode strings! 64 bit will have to wait until the time of our children's children.
But that's not what's driving me mad. It's the F5/F9 thing. In Visual Studio F5 is run, F9 is set breakpoint. In Delphi it's exactly the opposite. For the past twenty odd years, I have used IDEs where F5 means run, so it's now burned into my brain. Having F5 mean "insert breakpoint" just seems profoundly wrong.
There doesn't seem to be a way to remap the keys in Delphi beyond choosing a Visual Studio emulation mode (it doesn't specify what version of VS). I could remap the keys in Visual Studio, but VS has things the way I like them.
In the interests of fair and balanced whining, I should point out that even Microsoft can't decide about the whole F5/F9 thing. I usually have a folder open on the Global Assembly Cache. I have to hit F5 to refresh it. In Outlook, refreshing (checking for new messages) is F9.
I doubt that I will ever love the Delphi IDE. OK, I am still annoyed that it was crashing 20 times per day (literally -- I took to obsessively recording them) until I applied the service pack, but at least it's stable now. The IDE lacks the most basic functionality: no moving the cursor back to a line before this one, no clicking on a point in the call stack and having it set the frame so you can inspect variables at that point, no examining the values of variables if an exception gets thrown. Still, I don't have to love it. Delphi is obviously circling the drain as a development environment. Their latest schedule of coming features makes it obvious they are a few years behind the curve. Coming real soon, Unicode strings! 64 bit will have to wait until the time of our children's children.
But that's not what's driving me mad. It's the F5/F9 thing. In Visual Studio F5 is run, F9 is set breakpoint. In Delphi it's exactly the opposite. For the past twenty odd years, I have used IDEs where F5 means run, so it's now burned into my brain. Having F5 mean "insert breakpoint" just seems profoundly wrong.
There doesn't seem to be a way to remap the keys in Delphi beyond choosing a Visual Studio emulation mode (it doesn't specify what version of VS). I could remap the keys in Visual Studio, but VS has things the way I like them.
In the interests of fair and balanced whining, I should point out that even Microsoft can't decide about the whole F5/F9 thing. I usually have a folder open on the Global Assembly Cache. I have to hit F5 to refresh it. In Outlook, refreshing (checking for new messages) is F9.
Saturday, 12 July 2008
It's the little things
Yesterday afternoon I was walking up the hill from work, headed to Starbucks to buy some coffee filters.
The area where I work is full of little boutiques that survive on a steady flow of tourists offloaded from package tour buses. One boutique that sells (as near as I can determine from glancing in the window) very expensive letter paper and body parts for Pinocchio dolls of various sizes had a sign in the window saying that it was open and "Back in 5 minutes". The door was ajar. The proprietor was nowhere to be seen. I was greatly amused that they had left the door open so customers could come in from the cold and look around.
Back to the coffee filters. At home we make American-style drip coffee, i.e. what they call "coffee" (with no modifiers) in the US. Coffee filters are something of a specialty item in New Zealand and surprisingly expensive in the supermarkets. At Starbucks the filters are about half the price of the supermarkets.
I picked two boxes of 100 filters and took them to the counter. The cashiers looked at the boxes as if they had never seen them before, turning them around hunting for the price sticker. They rang them up then asked if I wanted them to remove the stickers -- i.e. they thought these novelty items must be gifts. I just chuckled. I declined the special little carry bag too.
I guess we're not in Seattle any more.
The area where I work is full of little boutiques that survive on a steady flow of tourists offloaded from package tour buses. One boutique that sells (as near as I can determine from glancing in the window) very expensive letter paper and body parts for Pinocchio dolls of various sizes had a sign in the window saying that it was open and "Back in 5 minutes". The door was ajar. The proprietor was nowhere to be seen. I was greatly amused that they had left the door open so customers could come in from the cold and look around.
Back to the coffee filters. At home we make American-style drip coffee, i.e. what they call "coffee" (with no modifiers) in the US. Coffee filters are something of a specialty item in New Zealand and surprisingly expensive in the supermarkets. At Starbucks the filters are about half the price of the supermarkets.
I picked two boxes of 100 filters and took them to the counter. The cashiers looked at the boxes as if they had never seen them before, turning them around hunting for the price sticker. They rang them up then asked if I wanted them to remove the stickers -- i.e. they thought these novelty items must be gifts. I just chuckled. I declined the special little carry bag too.
I guess we're not in Seattle any more.
Tuesday, 8 July 2008
Anticipatory medicine
My 6.5 year old son was asking why doctors can't cure the common cold. I explained that one problem is that the various viruses keep mutating, so you can't just have one medicine to solve the problem. He suggested that the scientists should anticipate the way that the viruses will mutate and make the medicine for that scenario. Then when the viruses mutate the medicine will get them.
OpenXML Packages
I am taking the various files that users refer to when documenting the process flow in their organization and putting them all in an OpenXML package (using System.IO.Packaging).
Office provides an additional layer around these packages to make it a bit easier to produce Office documents (which are just packages with a particular internal structure). See here for the SDK.
The Office SDK makes some things a little easier, although some of the names had me a bit confused at first (CustomXmlPart for example has nothing XML-ish about it, it's just a nice way to put things in the place in a .docx file where Word expects the custom XML to go). But with that extra layer you lose some of the functionality of the underlying System.IO.Packaging. For example, the Office SDK provides some nice functions to add images but you don't get to specify the compression. One JPG file ended up going from 276,216 bytes to 403,084 bytes, i.e. actually getting bigger. Using the underlying System.IO.Packaging, I am able to specify no compression for JPGs -- they have such low entropy all you do is add the overhead of the ZIP housekeeping bits.
Curiously, with both the Office SDK and the underlying classes you have to specify the image type. I couldn't find anything in the DotNet foundation classes to tell me the image type given a stream or even given a file name, so I had to bake something trivial. Fortunately, a lot of the time I know exactly what the image type is anyway.
Office provides an additional layer around these packages to make it a bit easier to produce Office documents (which are just packages with a particular internal structure). See here for the SDK.
The Office SDK makes some things a little easier, although some of the names had me a bit confused at first (CustomXmlPart for example has nothing XML-ish about it, it's just a nice way to put things in the place in a .docx file where Word expects the custom XML to go). But with that extra layer you lose some of the functionality of the underlying System.IO.Packaging. For example, the Office SDK provides some nice functions to add images but you don't get to specify the compression. One JPG file ended up going from 276,216 bytes to 403,084 bytes, i.e. actually getting bigger. Using the underlying System.IO.Packaging, I am able to specify no compression for JPGs -- they have such low entropy all you do is add the overhead of the ZIP housekeeping bits.
Curiously, with both the Office SDK and the underlying classes you have to specify the image type. I couldn't find anything in the DotNet foundation classes to tell me the image type given a stream or even given a file name, so I had to bake something trivial. Fortunately, a lot of the time I know exactly what the image type is anyway.
DotNet Stream to IStream
Lately I have been grafting some new cloth on to our legacy code. In this case, that means writing C# COM servers that get called from legacy Delphi.Win32 code.
I have been taking the various files that together comprise a user's model of the process flow in their organization and bundling them together using System.IO.Packaging (a nice wrapper on a ZIP file).
In all the places in the legacy Delphi code where it might try to get a TFileStream (Delphi people like to start their class names with the letter T) it will instead be getting a TOleStream on a C# object that implements IStream.
Here's the kicker. C# Stream objects don't implement IStream so you need a wrapper. Blech. Luckily for me, Oliver Sturm has already posted a partial solution (it implements Read but not Write) here so I was spared too much grief. Then it was just a matter of regenerating the Delphi wrappers for the assembly and now we're as good as gold, as they say in this country.
I have been taking the various files that together comprise a user's model of the process flow in their organization and bundling them together using System.IO.Packaging (a nice wrapper on a ZIP file).
In all the places in the legacy Delphi code where it might try to get a TFileStream (Delphi people like to start their class names with the letter T) it will instead be getting a TOleStream on a C# object that implements IStream.
Here's the kicker. C# Stream objects don't implement IStream so you need a wrapper. Blech. Luckily for me, Oliver Sturm has already posted a partial solution (it implements Read but not Write) here so I was spared too much grief. Then it was just a matter of regenerating the Delphi wrappers for the assembly and now we're as good as gold, as they say in this country.
Tuesday, 27 May 2008
Visual Studio templates
Visual Studio 2008 sticks a bunch of using statements at the top of any new C# source file. They include System.Collections.Generic and System.Linq. I tend to not use these for my current projects, but instead to use System.Collections.ObjectModel (where Collection<> lives) and System.Xml.Linq (where XElement etc live).
After a little poking around, here's what you do to change the template:
In %ProgramFiles%\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
is a template called Class.cs. Edit it to say something like this:
using System;
using System.Collections.ObjectModel;
$if$ ($targetframeworkversion$ == 3.5)using System.Xml.Linq;
$endif$
namespace $rootnamespace$
{
class $safeitemrootname$
{
}
}
Save it back into the zip file and run
devenv.exe /setup
Then restart Visual Studio and all is good.
One caveat: I am not sure exactly what features might get reset by running with the /setup option. It didn't trash my custom font settings at least.
After a little poking around, here's what you do to change the template:
In %ProgramFiles%\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
is a template called Class.cs. Edit it to say something like this:
using System;
using System.Collections.ObjectModel;
$if$ ($targetframeworkversion$ == 3.5)using System.Xml.Linq;
$endif$
namespace $rootnamespace$
{
class $safeitemrootname$
{
}
}
Save it back into the zip file and run
devenv.exe /setup
Then restart Visual Studio and all is good.
One caveat: I am not sure exactly what features might get reset by running with the /setup option. It didn't trash my custom font settings at least.
Land of expensive books
Books are expensive in New Zealand. Always have been. Now that we are living here, we have become avid users of the public library, which is probably a Good Thing (R) (TM) anyway.
Over the weekend I decided to spend a gift card at Borders (the same chain as in the US). I had read a good review of Steve Skiena's "The algorithm design manual" -- $75.50 USD on BetterWorld including shipping. That's $100 NZD at the current exchange rate. Shipping from the US usually takes 7-10 days -- USPS doesn't ship by sea any more.
Borders didn't have it but they could special order it for the princely sum of $215 NZD. BetterWorld it is then.
This is completely nuts -- more than double the price of buying it from a US retail source. For items that might involve after sales support (e.g. electronics goods) I could understand paying a small premium. Labor costs in NZ are high after all. But this is a book we're talking about.
Over the weekend I decided to spend a gift card at Borders (the same chain as in the US). I had read a good review of Steve Skiena's "The algorithm design manual" -- $75.50 USD on BetterWorld including shipping. That's $100 NZD at the current exchange rate. Shipping from the US usually takes 7-10 days -- USPS doesn't ship by sea any more.
Borders didn't have it but they could special order it for the princely sum of $215 NZD. BetterWorld it is then.
This is completely nuts -- more than double the price of buying it from a US retail source. For items that might involve after sales support (e.g. electronics goods) I could understand paying a small premium. Labor costs in NZ are high after all. But this is a book we're talking about.
Tuesday, 20 May 2008
XLinq in C#
I have been converting some rather inelegant bits of C# code (stuff I had written, no reflection on anyone else) from the DotNet 2.0 XPathNavigable way of doing things to the DotNet 3.0 Linq way of doing things.
Using XLinq (Linq on XML) is fun. It's a shiny new hammer that you can use for banging in all sorts of nails, but you can get a bit carried away.
In my case, I have been extracting the externalNames (think, fully qualified names) of some XSOL variables and stuffing them in a Collection called variables. MSDN has trivial examples that are more or less like this
That all seems simple enough: extract the contents of the descendant elements.
Of course, it can be collapsed to make things a little more elegant without making them more obscure:
But then I get to thinking, why not do it all in one go? The result of all that Linq stuff is an IEnumerable. I can't implicitly convert it to a Collection but there is an overload for the constructor for Collection<> that will do the trick:
So there you go. You can do it using the new shiny hammer but things are starting to look more complex than is necessary. Thinking about it some more, it really is sufficient to skip all that Linq and say
This is not to say that XLinq is not a good thing. Clearly it would be wonderful for more complex queries.
Using XLinq (Linq on XML) is fun. It's a shiny new hammer that you can use for banging in all sorts of nails, but you can get a bit carried away.
In my case, I have been extracting the externalNames (think, fully qualified names) of some XSOL variables and stuffing them in a Collection
IEnumerable externalNames =
from externalName in root.Descendants("externalName")
select (string)externalName;
foreach (string name in externalNames)
{
variables.Add(name);
}
from externalName in root.Descendants("externalName")
select (string)externalName;
foreach (string name in externalNames)
{
variables.Add(name);
}
That all seems simple enough: extract the contents of the descendant
Of course, it can be collapsed to make things a little more elegant without making them more obscure:
foreach (string name in
from externalName in root.Descendants("externalName") select (string)externalName)
{
variables.Add(name);
}
from externalName in root.Descendants("externalName") select (string)externalName)
{
variables.Add(name);
}
But then I get to thinking, why not do it all in one go? The result of all that Linq stuff is an IEnumerable
variables = new Collection(
(from externalName in root.Descendants("externalName") select (string)externalName)
.ToList());
(from externalName in root.Descendants("externalName") select (string)externalName)
.ToList
So there you go. You can do it using the new shiny hammer but things are starting to look more complex than is necessary. Thinking about it some more, it really is sufficient to skip all that Linq and say
foreach (XElement externalName in root.Descendants("externalName"))
{
variables.Add(externalName.Value);
}
{
variables.Add(externalName.Value);
}
This is not to say that XLinq is not a good thing. Clearly it would be wonderful for more complex queries.
Subscribe to:
Posts (Atom)