Kanon Wakeshima has a cool cello and voice song, taken from the soundtrack of an anime, of course, but still, a pretty cool song: Kanon Wakeshima - Suna No Oshiro
Emilie Autumn has some really nice instrumental songs, like the one I put here, and some nice voice songs. Unfortunately I don't like the instrumentation of the voice songs. I am still looking for a perfect crazy electric violin and voice song, but it may be that singing and playing the violin is impossible or at least too difficult. So here is Emilie Autumn - Manic Depression:
It appears that a British project, secretly conducted by the Rutherford Appleton Laboratory, has produced a method of encapsulating hydrogen into microparticles of porous material. The result is something that acts like a liquid, burns like hydrogen and can be used inside normal cars without any engine modification. The price they propose is 1.5$ per gallon, which is 0.396$ per liter or 0.2915 euros. What is cool about it is that they don't need to extract any resource in order to produce this miracle fuel.
Could THIS be the end of oil? Frankly I am amazed that this news reached me and not the one about Stephen Bennington found dead in a ditch somewhere. I can only hope that the secrecy of the project paid off and that the guys at Cella Energy have really managed to find the solution while under the radar of Big Oil. Or maybe it is simply the time in which the dependency on oil has become a bigger threat to national security than the lack of funding coming from oil companies.
Update:I may have spoken too soon. A NewScientist article explains the process in a slightly different light. The beads do store hydrogen, but they must be heated in order to release that hydrogen, then the hydrogen would be used in fuel cells. That is at odds with the idea that you can use it as gasoline in a petrol tank car. Oh, well, I hope they get it right someday.
Another interesting List of Wikipedia is the list of religious texts. It's a medium sized list, although I suspect it is not nearly complete and that some of the works there are pretty big.
I am not much on religion, but I wonder what one would come to think of if presented with all the texts in the list, exposed to them without any cultural bias. Would some sort of distilation of the concept of religion emerge from it, or would everybody just choose a religion they feel more comfortable with? Or maybe they would write their own religious texts.
When I think about it, I can't help but compare it with the emergence of certain genres in fiction, like alien invasion sci-fi or comic book super heroes. First there are some original authors that come up with an idea. The idea is well liked, bought and distributed. It becomes well known so that other people start making work of their own that is inspired by that. It's almost organic, with reproduction, mutation, cross breeding and extinction. However, the integrity of religions is mostly enforced by communities of people that insist on changing nothing. They stop evolution, but also protect against extinction. Is stagnation the hallmark of religion or is it the stability that it provides in a world in continuous flux of change?
I will tell you this: I like evolution. And I mean it in the most general sense, not only the Darwinian one. I find it ironic that in my mind religion is the opposite of evolution. Or maybe that's a cultural bias. Hmm...
The Shigurui (Death Frenzy) manga is now complete. The beautifully terrible story of two exceptional samurai in a world of politics, betrayal and cultural conditioning, locked in absolute rivalry, has ended with the 84th chapter, Pure Crimson. There is an anime with the same subject, I've also seen it and it is really great, even if it stops dead after 11 episodes. I actually recommend to watch the anime and then continue with the chapters in the manga, in order to understand better the feeling of the story. It must be said that the translation from a book written by a war veteran to a graphic novel by a mangaka 58 years his young and then translated to TV anime has not lost, but gained insight and emotion.
I've never thought to check if there is such a list on the Internet, but apparently it is, as described in the xkcd comic. Good thing I at least read that! Wikipedia's List of common misconceptions is a very interesting read, many of the myths described there being reedited regularly through the media without them actually being true! So, get reading.
If you are like me, you often google a .Net class and find it at MSDN. Also, since you want the page to load quickly and get you the information you need, you probably selected the Lightweight view on MSDN. If you haven't, you should :) Anyway, a problem with MSDN is that it shows you every possible member of the class, which is especially annoying with WPF classes as they inherit from FrameworkElement that has a gazillion events. Wouldn't it be great if one could hide the inherited members from an MSDN page?
At first I thought I would parse the content of each row and detect the (Inherited from string, but it appears it is even simpler: table row elements have a data attribute that (if the member is inherited) contains the word inherited. Probably someone at MSDN wanted to make the same thing as me, but forgot to implement it (at least on the lightweight view). The javascript is simple enough:
var trs=document.getElementsByTagName('tr'); var l=trs.length; for (var i=0; i<l; i++) { var tr=trs[i]; var data=tr.getAttribute('data'); if (!data||data.indexOf('inherited')==-1) continue; tr.style.display=tr.style.display=='none'?'':'none'; }
You probably wonder why I haven't used jQuery. It is because I want it to work in a javascript: url so I can put it in a bookmark! Just as with the Firebug bookmarkyou need to manually create a bookmark in the Favorites folder (or to add any page as a favorite, then edit its URL) in Internet Explorer or to simply add a bookmark in the browser in Chrome and Firefox and paste the one line script. To make it easier, I will write them both here. The content of the .url favorite file:
[DEFAULT] BASEURL=http://msdn.microsoft.com/en-us/library/ [InternetShortcut] URL=javascript:var trs=document.getElementsByTagName('tr');var l=trs.length;for (var i=0; i<l; i++) { var tr=trs[i]; var data=tr.getAttribute('data'); if (data&&data.indexOf('inherited')>-1) tr.style.display=tr.style.display=='none'?'':'none'; }; void(0); IDList= IconFile=http://msdn.microsoft.com/favicon.ico IconIndex=1 [{000214A0-0000-0000-C000-000000000046}] Prop3=19,2
and the javascript line to use in other browsers:
javascript:var trs=document.getElementsByTagName('tr');var l=trs.length;for (var i=0; i<l; i++) { var tr=trs[i]; var data=tr.getAttribute('data'); if (data&&data.indexOf('inherited')>-1) tr.style.display=tr.style.display=='none'?'':'none'; }; void(0);
The fifth book in the Dexter Morgan series by Jeff Lindsay, Dexter is Delicious is slightly better written than the first four, but also less credible. The main character is torn between his Dark Passanger and the desire to love and protect his newly born child. He thus decides to "become human" in the worst possible moment. His brother Brian, who attempted to kill Dexter's adoption sister Deborah, also makes an appearance. The bad guys in the story are a cannibal ring and they are quite the gourmet, requiring Dexter as a main course.
The problem with this book, apart from the general Dexter Morgan hard to swallow leaps of faith, is that the Dark Passenger is pushed back, as Dexter gets in tough with his parental instincts. For me, at least, Dark-Dexter was the main character and the mischievous whispers of his inner demon were the delight of the series. If I would want to know people having kids and loving their pinkness I would read something else entirely.
I will continue to follow the series, but I can't help feeling a little dissappointed every time I read one of the books in the series. With such a wonderful subject, the possibilities are limitless and a great deal of potential wasted.
It all started from a Sacha Barber post on CodeProject, enumerating ways in which one can use Aspect Oriented Programming to mark simple automatic properties so that they get compiled into fully fledged INotifyPropertyChanged properties, thus saving us the grief of repeating the same code over and over again in each property setter. The implementations there were good, but too complex, relying on third party libraries, some of them not even free. He completely ignored template generators like T4, but then again, that particular approach has a lot of issues associated with it, like having to either parse source files or somehow tap into the compiled assembly... before you compile it. However, this brought forth the idea that I could do this, maybe in some other way.
Enter Felice Pollano, with his article on CodeProject detailing a method of using CodeDom generation to create at runtime the INotifyPropertyChanged object from an already existing type. This is pretty slow, but only when first creating the type, so with a cache system it would be totally usable. I liked this approach better, but I noticed there were some errors in the generated code and when I tried changing the generating code I had to look at it for half an hour just to understand where to change it. Wouldn't it be better to use some sort of template that would be easy to edit and use it to generate the proxy type?
So this is my take on generating INotifyPropertyChanged classes dynamically, avoiding the repetitive plumbing in property setters. The library contains a template for the class and a separate template for the properties. The proxy type is being generated in memory from a string that is generated from the source type and the two templates. All in all, one class, two templates, three public methods and four static methods. As easy as 1,2,3,4 :) Here is the code:
As you can see, the code needs only a type that has public virtual properties in it and it will create a proxy that will inherit that class, implement INotifyPropertyChange and override each virtual property with a notifying one. The templates are so basic that I feel slightly embarrassed; I keep thinking if I should have created template entities that would stay in the same file. :) Here are the templates:
privatevoid OnPropertyChanged(string propertyName) { var handler=PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } }
publicoverride {propertyType} {propertyName} { get { returnbase.{propertyName}; } set { if (!Equals(value,base.{propertyName})) { base.{propertyName}=value; OnPropertyChanged("{propertyName}"); } } }
Don't forget to save the templates as Embedded Resource in the assembly.
Update: At Sacha Barber's advice I took a look at the DynamicObject solution for the INotifyPropertyChanged code smell. The link he provided is OlliFromTor's CodeProject article Using DynamicObject to Implement General Proxy Classes. While this works a lot easier than with compiling generated code, it also has a major drawback: the proxy class does not inherit from the original object and so it can only be used as such, but only in dynamic scenarios. Otherwise, it seems to be a perfect solution for proxy scenarios, if you are willing to discard the type safety.
I restarted my computer and afterwards I could not access any of the local sites via IIS. The error message in the Application logs of the EventViewer was
Event Type: Error Event Source: ASP.NET 4.0.30319.0 Description: aspnet_wp.exe could not be started. The error code for the failure is C0000142. This error can be caused when the worker process account has insufficient rights to read the .NET Framework files. Please ensure that the .NET Framework is correctly installed and that the ACLs on the installation directory allow access to the configured account.
to no avail. I was about to curse and restart the computer again when I found this pretty little link: IIS doesn't start. Error code: C0000142. A solution is at the bottom, as the least voted answer: Go to Task Manager, kill explorer.exe, Run another explorer.exe. This starts IIS (aspnet_wp.exe under inetinfo.exe) correctly.
Update: It bugged me that I had to kill explorer.exe. First of all it is a manual solution, then it always messed with my system tray icons. So I searched a little more. Short story shorter, you need to edit machine.conf and replace <processModel autoConfig="true" /> with <processModel userName="system" password="AutoGenerate" />. That effectively makes ASP.Net work under the System account, not the default machine. It does indicate the issue is permission related, but I don't get exactly where and why it should work if I restart explorer.exe. As long as you don't mind running ASP.Net under the System account, this solution seems to solve it. Here is the long version.
Note: you can find the machine.config file in %windir%\Microsoft.NET\Framework\[framework version]\Config\machine.config.
I personally think that the IE8 developer tools are better than Firebug, but let's face it: Firebug was first. Besides, Firebug has also a completely javascript version called Firebug lite that you can inject into any page. Well, you might say, as a developer it is a nice tool, but how can I, the Internet surfer, use this in any page? And the answer is: the favorites links!
It all started from this brilliant post: Bookmark to inject FireBug Light into Internet Explorer. that showed how you can create a specific URL file, add it to the Favorites folder of your Windows user and then use it on any page. Elegant it may be, but it's lazy. It only works on pages that have loaded jQuery. So I did the version that works with simple javascript.
Then I realized that, since I like the Internet Explorer tools better, this is useless for me. How cool would it be to have Firebug lite on Chrome, which has yet to provide a decent developer tool. And it's even easier! Here is how you do it.
For Internet Explorer, follow the steps described in the ElegantCode post but use generic javascript: create a file called Firebug.url containing
And that is it. Click on the link in any of the said browsers and a small icon will appear in the bottom-right corner. Click on it and voila: Firebug! Of course, one can install the Firebug extension, which is actually also a javascript link, albeit really weird, but I think this is more clear and user friendly.
When I first tried to do drag and drop in WPF I thought it would be something easy like DragAndDrop.IsDraggable="True". Boy,was I wrong! The mechanism for this has remained almost unchanged from the Windows Forms version. It is completely event driven and has nothing in the way of actual graphical feedback of what is going on except making the mouse cursor look different. If you want to do it using MVVM, you have another thing coming.
Disclaimer:Now, I have found a good solution for all the problems above, but the drag and drop behaviour is part of a larger framework that I have been working on and creating a separate project just for it might prove difficult. I mean, you want to show MVVM drag and drop, you should also have Views and ViewModels and base classes and helpers and everything. The solution, I guess, is to make separate articles for the main features in the framework, then present the project as a whole in the end. The framework itself is work in progress and untested in a real life project, so this might have to wait, as well. I will make sure, though, to put much code directly in this post.
Ok then, let's define the requirements of this system. We need:
A drag item
A drop target
Showing the target is being dragged
Showing the target can or cannot be dropped
Showing the item being dragged
Changing the appearance of the original dragged element while dragging
Changing the appearance of the drop target while dragging something over
Allowing for drag and drop between Windows
Allowing for drag and drop between applications
Changing an application that works but has no drag and drop in an easy and maintainable way
Using as simple a system as possible
Doing everything using the Model-View-ViewModel pattern
From these requirements we can form a basic idea of the way we would like this to work. First of all, we need the ability to mark any element as a drag item. Also, we need a container that can be marked as a drop target. We can do this using boolean IsDragSource and IsDropTarget Attached Properties; once set they will force a bind of the drag and drop events to some special handlers that would then direct decisions to ICommands.
As we are doing it in MVVM, we don't use the elements directly, but the data they represent, so we work with dragging and dropping commands using data objects. The classes responsible with the decisions for the drop permissions and actions should be in the ViewModel. We could, of course, link all events to commands, but that would be very cumbersome to use. Besides, we want it simple, we don't really want the user of the system to care about the drag and drop inner workings. Therefore, the solution is to change the IsDragSource and IsDropTarget to DragSource and DropTarget properties that accept objects of type IDragSource and IDropTarget containing all the methods needed for the events in question:
/// <summary> /// Holds the data of a dragged object in a drag-and-drop operation. /// </summary> publicinterface IDraggedData { /// <summary> /// A dictionary with the format as the key and the data in that format in the value /// </summary> IDictionary<string, object> Values { get; }
/// <summary> /// Optional object for additional information /// </summary> object Tag { get; } }
/// <summary> /// Business end of the drag source /// </summary> publicinterface IDragSource { /// <summary> /// Gets the supported drop effects. /// </summary> /// <param name="dataContext">The data context.</param> /// <returns></returns> DragEffects GetDragEffects(object dataContext);
/// <summary> /// Gets the data. /// </summary> /// <param name="dataContext">The data context.</param> /// <returns></returns> object GetData(object dataContext); }
/// <summary> /// Defines the handler object of a drop operation /// </summary> publicinterface IDropTarget { /// <summary> /// Gets the effects. /// </summary> /// <param name="dataObject">The data object.</param> /// <returns></returns> DragEffects GetDropEffects(IDraggedData dataObject);
/// <summary> /// Drops the specified data object /// </summary> /// <param name="dataObject">The data object.</param> void Drop(IDraggedData dataObject); }
We need the methods for the effects to instruct the system about the types of operations that are allowed during drag and drop: None, Copy, Move, Scroll, All.
If you are going for the purist approach, you should use your own DragEffects enumeration, as above, since the DragDropEffects enumeration is in the System.Windows assembly, which in theory should have nothing to do with the ViewModel part of the application (one could want to use the ViewModel in a web environment, for example, or in a console application).
You will notice that the GetDropEffects method receives an IDraggedData object. This is also because the IDataObject interface and the DataObject class used in Windows drag and drop operations are also in the System.Windows assembly.
The IDraggedData interface is basically a dictionary that uses the data format as the key and the dragged data object stored in that format as the value. An important fact is that, when trying to drag and drop between applications, you need that the dragged data object be binary serializable. If not, you will only get the expected result when dragging to the same application. Here is an implementation of the interface, complete with a totally lazy way of getting the data based on which type is more "important":
/// <summary> /// Holds data for a drag-and-drop operation /// </summary> publicclass DraggedData : IDraggedData { #region Instance fields
/// <summary> /// A dictionary with the format as the key and the data in that format in the value /// </summary> /// <value></value> public Dictionary<string, object> Values { get { if (mValues == null) { mValues = new Dictionary<string, object>(); } return mValues; } }
/// <summary> /// A dictionary with the format as the key and the data in that format in the value /// </summary> /// <value></value> IDictionary<string, object> IDraggedData.Values { get { return Values; } }
/// <summary> /// Optional object for additional information /// </summary> /// <value></value> publicobject Tag { get; set; }
/// <summary> /// A dictionary for exceptions when retrieving the data in a specified format /// </summary> /// <value>The exceptions.</value> public Dictionary<string, Exception> Exceptions { get { if (mExceptions == null) { mExceptions = new Dictionary<string, Exception>(); } return mExceptions; } }
#endregion }
In the IDragSource interface we need the GetData method to extract the data object associated with a dragged object, since the Windows drag and drop mechanism encapsulates the objects in an application agnostic way, so one can perform drag and drop between applications or to/from the operating system. Finally, we need the Drop method in the IDropTarget interface to handle in the ViewModel what happends when an item is dropped.
Let's get to the juicy part: a DragService static class that will register the attached properties that we need. Besides the DragSource and DropTarget properties we need status properties like DragOverStatus (for the target), DraggedStatus and IsDragged (for the original dragged item) as well as two properties called BringIntoViewOnDrag and ActivateOnDrag which would bring an item completely into view or activate it (if a Window) when a valid drop target. This one is long. It also contains some extension methods that would be explained later.
Most of the code here is self explanatory: you have attached property that bind to the element drag and drop events and handle them either through direct code or by delegating to the values set. There are some extension methods like ExecuteWhenLoaded and ExecuteWhenUnloaded which execute an action when the element has finished loading or when it is unloading. An important aspect here is that a window closing does not trigger the Unloaded event for its child elements, so you need to bind to the Dispatcher.StartedShutdown event as well:
That is pretty much it for the drag and drop itself. You can implement IDropTarget on the ViewModel directly, but IDragSource needs to be binary serializable if you intend to drag and drop across application domains, so you usually implement it into a separate class that is a property of the dragged item view model or DataContext.
Because the DragService sets the status properties for each element, you can manipulate the appearance and behaviour of both drag source and drop target based on them. However, at this point the mouse will be the only indication that you are dragging something. You might want to actually drag something, especially since in a move operation the original element would be hidden during the drag. The problem here is that the drag source element cannot control the display of the dragged item in other applications, nor should it in its application, since it is not its responsibility. The solution: decorate an element over which you would drag something (like the root element of the entire window) with something that knows how to display dragged items:This code uses an adorner to display the dragged item over it. Nothing fancy, since the actual template for the dragged data is defined in the decorator as the content. This is not the place to discuss the adorner, though, so here is just the code:You would only need to decorate a view and then define the AdornerContent property for the decorator and, optionally, the grab point offset for the dragged element.
All that is left here is to show some usage examples. Let's assume we need a View over which we can drag and drop items:
Here you have a user control view which has the drop target set to its own view model and it is set to update the DragOverStatus property of the ViewModel when its attached DragOverStatus property is changed. The status properties are inheritable, so all the children of the view have them set. It is easy to define a Button style that has its text bolded when a copy operation is allowed for a drop item:
The container for the items is a simple WrapPanel and it is placed in a dock panel together with add and remove item buttons. This dock panel is decorated as a drag visual container, and the content that is dragged is set to a custom control called ContentItem, with a drag point set to 40,40. The DataContext property of the item is set to the DraggedData property so that it expresses the actual dragged object.
Now we have set up a container to be a drop target for items. It displays the items as they are dragged over it. All we have left is to set up the items, the ContentItem control, to be a DragSource:
The control style defines as a drag source the DragSource property of the data context of the item and synchronizes with the data context the properties of IsDragged and DragStatus. Triggers then make is pinkish when dragged and greenish when it can be dropped. Notice that this applies to the original item, while its representation is dragged, so you have a feedback of what is going on with the item right at the source.
I won't put here the ViewModels or the data items, since they are pretty much part of the business context, not the drag and drop. Just return DragEffects. All on the effects methods and you can drag anything anywhere, for example.
That's it, folks: drag and drop completely MVVM, without as much as writing an event handler or caring about the actual elements in the viewmodel. It would be even easier if you would allow references to WPF assemblies in the ViewModels, since you could also get the source elements and do stuff with them, but that wouldn't be much of an MVVM pattern, would it?
And here is the AdornerBase class, just a simple helper class:
/// <summary> /// Basic adorner class that exposes simple Attach and Dettach methods /// </summary> publicabstractclass AdornerBase : Adorner { #region Instance fields
privatebool mIsDettached;
#endregion
#region Properties
publicbool IsDettached { get { return mIsDettached; } }
public AdornerLayer AdornerLayer { get; private set; }
I am a .NET programmer living and working in Bucharest, Romania.
Posts are divided into programming and misc.
Check out the icons above on how to contact or chat with me.
Unless otherwise specified, all code or any type of work you find on this blog is under MIT license. While I welcome attribution, I don't require it. Just use anything in any way you see fit. Consider it completely and utterly shared for the lulz.