Friday, October 26, 2007

Holiday Spirit: Site Changes

I just thought I would get in the holiday spirit and modify some of the look & feel of the site to align with the holidays. My first change is a nice Halloween pumpkin for an image.

pumpkin_128

I will likely experiment with some other changes as the holiday season progresses.

 

scream_128

Sunday, October 21, 2007

Feedback: DevExpress Layout Control Main Demo

 

Here is a screen shot of the Developer Express Layout Control Main Demo:

Demo1

 

If I click a feature, such as Validating, I get a screen shot similar to this:

Demo2

 

Its a nice demo - I want to learn from it, and so I open the source code for the demo that is included with my subscription where I see something in VS2005 similar to this:

VS20051

 

Hmm... there are a LOT of custom User Controls and I start looking/ learning (as I suspect most users may) by looking at the main form (frmMain) and attempt to "go backwards" through the code. Here is the code behind frmMain.cs:

VS20052

 

I highlighted where the form inherits from a base form "DevExpress.DXperience.Demos.frmMain". Can you see it in the rectangle? Its a little frustrating to chase down code in a demo, but hey... okay... so I click on "Go to Definition" and this is what I get:

VS20053

 

* This is my summary *

First (metatdata): Notice... or... look carefully... the base or inherited class I chased down (the very first step I took to understand the demo code) is "FROM METADATA" and this is just "wrong" (IMO) - for any demo. Isn't a demo supposed to include the code? Inheriting from classes that are not included is not the best choice (IMO). I found numerous objects that inherit from classes that are not contained directly in the demo.

DevExpress: Please, do NOT create a demo that utilizes custom controls or features that are hidden within your source code library! I am fairly certain that the base class "frmMain" is not a standard control for your library and I am also certain that this confuses users and does not help them. Why is this "frmMain" not part of the demo solution? I certainly can understand that some elements are common to many demo solutions, but they should simply be referenced as a separate "common"  project, should they not? The common projects should be included DIRECTLY in each demo solution.

Second (organization): I started "browsing" the code and looked at the "BaseControl" which inherits from some TutorialControl which is located in a file named DemoControls.cs; yet the BaseControl is not part of DemoControls, it is special and gets its own file.  However, for some reason the LayoutAppearanceMenu is also located in the DemoControls.cs file. What I am getting at is that there is  a very difficult to follow pattern for why certain classes are located within certain files. There really needs to be some organization and logic followed to make it easy to locate objects. A possible simple approach I might recommend would be a file for every class. Grouping classes into files without clear understanding of any reasoning for grouping them makes the code more difficult to understand.

Why is the "TutorialControl" and the "LayoutAppearanceMenu" contained in DemoControls? I don't see the logical relationship here... maybe someone else does???

 

Third (Isolation): These demos, obviously, offer many benefits. For example, I was trying to understand how to properly deal with Visual Inheritance and understand Visual Studio's problem with collection members in inherited or derived forms. To understand: if someone adds a DevExpress LayoutControl to a base user control or form and then tries to inherit or derive a form from that base, the LayoutControl would be unusable in the designer because Visual Studio does not support adding, removing, or changing collections via the designer in a derived form when the source collection is in a base class. 

So why am I mentioning isolation?

Well, I suspect most users look at the choices within a Demo or the "Features" such as Validating, Localization, Image Layout , etc and they just want to understand that specific feature. This really screams or demands that code is NOT inherited. Most users (I suspect) want to see the all the code in one spot, where they can follow the logic, where they don't chase down inheritance, and where they don't get confused where pieces of the puzzle aren't even located within the demo. I suggest that each "feature" be self-contained and easy-to-follow.

 

This post is not meant to be a complaint, it is meant to suggest what I feel is the perspective of the typical end-user - the one who actually needs and uses the various demos. I am trying to share the overall experience and I simply feel the experience could be improved. Ironically, there is no specific demo for visual inheritance - it is addressed in every demo. I consider Visual Inheritance, custom user controls, deep inheritance chains, etc. to be advanced examples. It just does not seem right to make every demo based on advanced functionality and I stand by my premise that no demo should be pieced together with significant custom code elements that are not included in the demo directly, such as the frmMain.cs file I highlighted.

Friday, October 19, 2007

DuckTyping - A Nice Tool to Keep in Your Bag of Tricks

Technorati Tags: , , , , , ,

 

I was recently working on a class designed to manage simple data entry within Windows forms. Essentially, the majority of data objects are always edited with the same business logic; the only difference is the actual properties of the data being edited. Before, I discuss how DuckTyping fits-in, its important to understand the situation:

When I am designing, I perpetually seek to recognize repeated patterns. For example, while creating several data entry forms, it became obvious they all required something like the following:

DataEntryBar

DataEntryBar2

 

"Data entry bars" similar to these are located on every data entry form. I originally added each button manually to each form. Then I recognized a "pattern" and created a UserControl that contained all the buttons. However, I was still left with registering each of the respective click events for Add, Delete, edit, etc. for each respective form and then calling matching methods within my data manager.

Again, I recognized a pattern and realized I wanted my data entry manager to auto-register the events for me and my next change resulted in defining an enumeration for pre-defined "button functions". In other words, how would my data manager know that the Cancel button was actually for canceling? I had to assign something to each button to declare their purpose.

Then... the next problem... I didn't just have bars such as the above, I also had drop-down menu support such as this:

DataEntryMenu

 

Both could be "active" at the same time. Therefore, I chose not to add the bar or menu directly to the manager. I decided to have each control expose an IList<Button> containing all the buttons. Well, not exactly Button either. The control library I use utilizes different buttons for menu support than the buttons used in the tool bar. It meant their was no common interfaces or base class (one is not even derived from Control) between the different button options. I was getting a little frustrated with finding a way to get Visual Studio or C# to recognize that there is usable commonality between different objects.

 

I could create an interface and , in fact, I did, but some objects are contained in a third party library and I didn't necessarily have the option to implement the interface (either I had no access to the source code, or a class was sealed, or it was really just a pain).

 

In came DuckTyping to the rescue! I first experimented with DuckTyping after reading this article on the Code Project: http://www.codeproject.com/cs/library/nduck.asp

 

I use this DuckTyping library which does differ from above: http://www.deftflux.net/blog/page/Duck-Typing-Project.aspx

 

I use the latter library because it seems to be maintained/ upgraded while the version on the code project does not appear to be maintained.

 

What does it do? Well, let's say I know that all the objects I need for my data manager require this interface:

 

Code Snippet

    /// <summary>

    /// Implemented on objects that respond with standard Click event.

    /// </summary>

    public interface IStandardClick {

        /// <summary>

        /// Occurs when the control is clicked.

        /// </summary>

        event EventHandler Click;

    }

 

However, none of the objects actually implement that interface; although, I happen to know they do expose the correct Click event.

 

With DuckTyping I now have an option to dynamically cast at runtime to the interface I need. Here is a sample:

 

Code Snippet

            IStandardClick clickableObject = DuckTyping.Cast<IStandardClick>(myButton);

 

The "myButton" object does not actually implement IStandardClick, but it does contain the required members (the click event). In other words, with DuckTyping I can cast any object to any interface so long as the object actually does implement the required interface members.

For me, DuckTyping is very cool and has an appropriate place in my bag of tricks. I suggest all C# developers download the library (http://www.deftflux.net/blog/page/Duck-Typing-Project.aspx) and experiment, you may never know when such a tool will come in handy.

Friday, October 5, 2007

C#: Advanced Event Handling: Memory Optimization, Thread-safety, and Proper Disposal

 

Recently I have been developing custom objects that expose numerous events and there were several issues I needed to address or consider:

  1. What are the 'Best Practices' for handling events?
  2. What happens to memory when there are a large number of events?
  3. If the object closes, what happens to any event delegates still registered if the listener did not unregister the events? Will the GC collect the disposed object? In other words, how do I properly dispose of all those events if they are still registered?
  4. Are my events thread-safe?

Let's try to establish a 'Best Practice' by looking at typical event declarations:

 

Code Snippet

    public class NonDisposableClass {

 

        public NonDisposableClass() {

 

        }

 

        public event EventHandler<EventArgs> SomeEvent;

 

        protected virtual void OnSomeEvent(EventArgs ea) {

            if (SomeEvent != null)

                SomeEvent(this, ea);

        }

 

    }

 

Here is a sample of a class (listener) registering with the event:

 

Code Snippet

    public class NonDisposableEventListener {

 

        public NonDisposableEventListener() {

            RegisterEvent();

        }

 

        // A reference to the non disposable class exposing an event

        private NonDisposableClass m_nonDisposableClass = new NonDisposableClass();

 

        void RegisterEvent() {

            m_nonDisposableClass.SomeEvent += new EventHandler<EventArgs>(m_nonDisposableClass_SomeEvent);

        }

 

        void m_nonDisposableClass_SomeEvent(object sender, EventArgs e) {

            // Do something when event occurs here...

        }

 

    }

 

These samples work with each other, but are they the 'Best Practice'?

First, we need to understand that the C# keyword event is special and allows this line of code in the NonDisposableEventListener class to work:

Code Snippet

            m_nonDisposableClass.SomeEvent += new EventHandler<EventArgs>(m_nonDisposableClass_SomeEvent);

 

Under the hood (or in the resulting IL), the C# compiler is creating a delegate with Add/Remove handlers that allow the += or -= operators to work. More than that and importantly... this style of event declaration has some serious potential for problems. Let's begin with a look at memory usage; here is a quote from this link : .NET Matters

"This hints at one of the primary reasons for writing your own add and remove accessors: to provide your own underlying data store. One reason you might want to do this [use EventHandlersList] is if you have lots of exposed events on your class, but in such a way that only a few are typically in use on an instance at any point in time. In such a scenario, there can be significant memory overhead associated with maintaining a delegate field for each event. Take the Windows® Forms Control class as an example.

In the Microsoft .NET Framework 2.0, Control exposes 69 public events. If each of these events had an underlying delegate field, on a 32-bit system these events would add an overhead of 276 bytes per instance. Instead, Control (or, more specifically, its base class System.ComponentModel.Component) maintains a list of key/value pairs, where the value is a delegate. Every event on Control then has custom add and remove accessors that store the registered delegates for all events into this list, an instance of the System.ComponentModel.EventHandlersList class. "

Huh? What is the issue?

MEMORY: Well, what I believe the author is stating is that events declared in such a manner as the typical example I provided will cause the C# compiler to reserve memory for the event's delegate regardless of whether a listener has actually registered with the event. With numerous events, the available memory is reduced and can have a significant impact on performance when resources are tight. *I will address a solution after examining other issues.

 

DISPOSING: Next we should look at the example again and consider what happens when they are disposed (out of scope): in the example, there was no code added to specifically manage resources on disposal, but it was not necessary because the class broadcasting the events is created within the class receiving the events. There is an inherent mutual dependency and they coexist and are created and disposed together...

However, what if there is some form of Dependency Injection where the class broadcasting the events is instantiated outside the class and its reference is added via the constructor? Would problems possibly arise? Let's explore this scenario:

If the listener class registers with the event, under the hood, there is a link or reference to each other maintained between each class once the listener has registered with the event. If the listener class goes out of scope (is no longer in use), the GC (Garbage Collector) may not identify the class for garbage collection because of this underlying reference and may keep it alive for as long as the NonDisposableClass is still alive. Conversely, if the class responsible for announcing the event (the NonDisposableClass) goes out of scope it may not be garbage collected because of the reference to the listener. In essence, there is potential for mutual dependency that results in both classes remaining in memory until both are disposed or removed from scope. When there are multiple listeners and multiple events, this can become very significant and the previous example would expose potential 'memory leaks' - unintended storage or references of objects that hang around in memory significantly longer than desired.

 

Let's expand my example to include disposal when a form of dependency injection exists (note the constructor):

Code Snippet

    public class DisposableEventListener : IDisposable {

 

        public DisposableEventListener(NonDisposableClass nonDisposableClass) {

            if (nonDisposableClass == null)

                throw new ArgumentNullException("nonDisposableClass");

 

            m_nonDisposableClass = nonDisposableClass;

            RegisterEvent();

        }

 

        // A reference to the non disposable class exposing an event

        private NonDisposableClass m_nonDisposableClass;

 

        protected virtual void RegisterEvent() {

            m_nonDisposableClass.SomeEvent += new EventHandler<EventArgs>(m_nonDisposableClass_SomeEvent);

        }

 

        void m_nonDisposableClass_SomeEvent(object sender, EventArgs e) {

            // Do something when event occurs here...

        }

        public void Dispose() {

            Dispose(true);

            GC.SuppressFinalize(this);

        }

 

        private bool IsDisposed = false;

        protected void Dispose(bool Disposing) {

            if (!IsDisposed) {

                if (Disposing) {

                    //Clean Up managed resources

                    // Ensure we clean-up references to event

                    if (m_nonDisposableClass != null)

                        m_nonDisposableClass.SomeEvent -= new EventHandler<EventArgs>(m_nonDisposableClass_SomeEvent);

                }

                //Clean up unmanaged resources

            }

            IsDisposed = true;

        }

        ~DisposableEventListener() {

            Dispose(false);

        }

    }

 

Ah, we are getting somewhere. Now, the listener takes on the responsibility of ensuring that it unregisters it own event(s) (which is the base for the underlying mutual reference between the listener and the class announcing the event and can prevent proper garbage collection). PROPER DISPOSAL IS CRUCIAL WHEN REFERENCES EXIST OUTSIDE THE CLASS.

Further, I did not find an example where the class broadcasting events also takes on the responsibility of removing any registered listeners when it is disposed. Should it? Well, if listeners are outside the control of the developer creating the class broadcasting events, I would say yes. In fact, I believe it is a 'Best Practice' even when the developer is in control of the listeners. Consider my dependency injection sample where some outside class that is inaccessible from listener is managing the life-cycle of the class broadcasting events. What if this manager class is disposed? All the underlying references for events could keep a big chain alive in memory as all of the listeners are unaware of the disposal and are still registered. Here is a sample with the class broadcasting events handling the disposal of its registered listeners:

 

Code Snippet

    public class DisposableEventClass : IDisposable {

 

        public DisposableEventClass() {

 

        }

 

        public event EventHandler<EventArgs> SomeEvent;

 

        protected virtual void OnSomeEvent(EventArgs ea) {

            if (SomeEvent != null)

                SomeEvent(this, ea);

        }

 

        public void Dispose() {

            Dispose(true);

            GC.SuppressFinalize(this);

        }

 

        private bool IsDisposed = false;

        protected void Dispose(bool Disposing) {

            if (!IsDisposed) {

                if (Disposing) {

                    //Clean Up managed resources

                    // Ensure we clean-up references to event

                    SomeEvent = null;

                }

                //Clean up unmanaged resources

            }

            IsDisposed = true;

        }

        ~DisposableEventClass() {

            Dispose(false);

        }

    }

 

Whew! Now we ensure that we a class responsible for broadcasting events ensures that all registered event listener references are disposed.

*** I will not provide another example because I think the reader can understand what is needed, but, a 'Best Practice' should also include, at a minimum) a 'Closed' event for classes that broadcast events. This way listeners are informed that the broadcasting class is no longer available to broadcast events and the listeners will be able to react to such a scenario appropriately

 

 THREAD-SAFETY: If we deploy the latter code examples, would the events be thread-safe? The short answer is NO. A longer answer involves the developer understanding the specific EventArgs passed via the events and the resulting actions taken based on the events. If there are any (even one) shared member altered due to the events, a potential for problems related to thread-safety exists. If, for example, there is a static counter shared across instances,one thread could alter the counter just after another new thread accesses the counter value and weird,  unwanted, incorrect behavior can occur.

I found a nice reference to a code snippet for events on this link:

Here is the snippet:

Code Snippet

    public class ThreadSafeEventHandler {

 

        public ThreadSafeEventHandler() {

 

        }

 

        private readonly object TextChangedEventLock = new object();

        private EventHandler<EventArgs> TextChangedEvent;

 

        /// <summary>

        /// Event raised after the <see cref="Text" />  property value has changed.

        /// </summary>

        public event EventHandler<EventArgs> TextChanged {

            add {

                lock (TextChangedEventLock) {

                    TextChangedEvent += value;

                }

            }

            remove {

                lock (TextChangedEventLock) {

                    TextChangedEvent -= value;

                }

            }

        }

 

        /// <summary>

        /// Raises the <see cref="TextChanged" /> event.

        /// </summary>

        /// <param name="e"><see cref="EventArgs" /> object that provides the arguments for the event.</param>

        protected virtual void OnTextChanged(EventArgs e) {

            EventHandler<EventArgs> handler = null;

 

            lock (TextChangedEventLock) {

                handler = TextChangedEvent;

 

                if (handler == null)

                    return;

            }

 

            handler(this, e);

        }

    }

 

Notice the changes where we manually handle the add/remove methods for the event and our new implementation wraps them in a lock. Also notice that calls to OnTextChanged (raising the event) is also uses a lock. This combination ensures that our events are thread-safe.

 

MEMORY-REVISITED: I previously delayed addressing the memory issue where numerous events can result in less-than-desirable memory usage. What can we do? Well, let's look at Microsoft's solution that they implemented on the Control class. Within the framework is a handy class for managing multiple events, the  System.ComponentModel.EventHandlerList. If you create a Windows form and type 'this' (dot), intellisense will reveal a property named 'Events'. Events is simply a reference to an instance of the EventHandlerList. Using the list to stores events frees up memory for the events that are not registered. It also has a bonus feature where its much easier to dispose of all events in one call by setting Events = null in the dispose method rather than each respective event. If you are using a class that inherits from control, you should use the Events property to add/remove events, rather than use private fields.

Here is a sample using the Control class:

Code Snippet

    public class ControlEventSample : Control {

 

        public ControlEventSample() {

 

        }

 

        private readonly object TextChangedEvent = new object();

 

        /// <summary>

        /// Event raised after the <see cref="Text" />  property value has changed.

        /// </summary>

        [Category("Property Changed")]

        [Description("Event raised after the Text property value has changed.")]

        public event EventHandler<EventArgs> TextChanged {

            add {

                lock (TextChangedEvent) {

                    Events.AddHandler(TextChangedEvent, value);

                }

            }

            remove {

                lock (TextChangedEvent) {

                    Events.RemoveHandler(TextChangedEvent, value);

                }

            }

        }

 

        /// <summary>

        /// Raises the <see cref="TextChanged" /> event.

        /// </summary>

        /// <param name="e"><see cref="EventArgs" /> object that provides the arguments for the event.</param>

        protected virtual void OnTextChanged(EventArgs e) {

            EventHandler<EventArgs> handler = null;

 

            lock (TextChangedEvent) {

                handler = (EventHandler<EventArgs>)Events[TextChangedEvent];

            }

 

            if (handler != null)

                handler(this, e);

        }

    }

 

Okay, so what if you don't inherit from a built-in class where the Events property is already implemented? Can you still use this class? The answer: Yes!

Simply add this property to your class:

Code Snippet

        public EventHandlerList Events {

            get {

                return m_events;

            }

        }

        private EventHandlerList m_events = new EventHandlerList();

 

STATIC VERSUS INSTANCE EVENTS: Events like other members of a class can be declared as static. I caution developers to be careful when using the System.ComponentModel.EventHandlerList and warn not use the EventHandlerList to manage static events. Manage them using private static fields. The reason I add such a caution is the handy way of disposing all registered events by setting Events to null on disposal of an instance. If static events are referenced in the EventHandlerList and multiple instances are open, then any instance closing would unregister all other open instances and this is clearly unwanted behavior.

 

CONCLUSION: Events are a powerful feature of the .NET Framework, but perils exists if they are not understood and implemented properly. I shared what I believe addresses potential pitfalls regarding memory optimization, thread-safety, proper disposal, and static versus instance events. I hope my post helps others and am open to any comments or suggestions others may provide.

 

DISCLAIMER: THE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE CODE  OR THE USE OR OTHER DEALINGS WITH THE CODE.

 

 

 

Wednesday, October 3, 2007

WTO agreement: Will it boost the world economy?

I was reading an old post on the BBC with the same title : LINK

 

Here is an excerpt where I believe I have a personal connection:

"It is ironic that the "multi-nationals" have provided the kind of world whereby Zafar Almas, from Pakistan, can express himself to me here in the US ... the telephone, the computer (with all its technical components), the internet, the video screen ... the list goes on and on. Like all his kind, they want the best of what we have invented and made available, but do not wish to participate in, encourage or take responsibility for promoting the very culture that encourages such innovations! I'd wager that there is much latent talent and brilliance in Pakistan just bursting to get out, if only the Luddites and the primitive thinking of the cultural institutions in developing countries let freedom rip! In the end, you'll understand ... in the meantime, just keep buying our stuff!
Mark M. Newdick, US/UK

As usual, we have extraordinarily comments about global trade, this time from Mark M Newdick. Leaving aside the problems of the Western view of development being necessarily 'good', the thesis that 'innovation' produces profit is extremely flawed. In the West, we see that much low-paid, physically demanding (and frequently dangerous) manual work in production has given way to work in management and service sectors. But the production work is still done - usually in poor countries for offensively low wages as corporations seek to reduce production costs. The WTO and IMF help to stifle competition from poor nations by forcing them to adhere to free trade agreements (no subsidies or trade barriers, goods produced solely for export), while the West frequently ignores these rules. Nobody subsidises rice more heavily than the US, and each economic downturn is met by embargos on imports to help domestic products. So Mark M Newdick, the wealth that you enjoy relies more on the US breaking free trade agreements and exploiting workers in poor countries than all of those high-minded notions about cultural freedom and good-ol' US innovation.
Paul R, Wales "

I wish I could respond (post my own comments) on the now closed article... I cannot, but I can respond here!

 

I suspect that I personally know this particular Mark Newdick and if he is the man I know,  he is a man with a particular history that likely provides him with more accurate and meaningful insight than Paul.

The Mark I know is from England and now lives in the USA; he volunteered (or was hired) as a accountant related to the international efforts to build desalinization plants in Africa. The world is full of wealthy countries and compassionate people who seek to help developing countries. The USA's contribution efforts are unmatched anywhere in the world. The idea that Western nations are the major corrupting influence is ridiculous. Consider who paid (funded) the building of the desalinization plants. The reasoning can be conveyed simply with this proverb:

"You can give a man a fish and he can eat for a day, or you teach him to fish and he can eat for life."

Paul seems to think that the poverty suffered by the people living in developing countries around the world is due to the gluttony of the United States and/or to other Western Civilization Nations and their respective citizens along with some scheming plot to dump menial,  low-wage jobs into poor nations. That's how it works isn't it? Another nation has a positive environment for building the overall standard of living for all its citizens and then Evil Western nations con them into unfair trade agreements, block each country's respective production, and forces them to do our menial, low-wage jobs. does that make sense to you?

 

Paul should know that Mark is one of those idealistic persons that imagined helping setup desalinization plants to bring self-sufficiency and prosperity to these nations; he imagined water irrigating dry soil, new farming jobs, and large-scale agricultural production being established to,  "teach the people to fish and eat for life." He arrived in Africa where local politicians smiled and greeted these ostensibly "Evil Westerners". He watched their public handshaking as cameras flashed for the media. Billions of dollars were poured into poor nations via the graciousness of Western nations, Western businesses, and Western citizens. There has never been and there is not likely ever going to be an expectation from Western nations that they receive a profit on the overall support they have given. Any "paybacks" that have been received are a fraction of what has been given. It is not corruption to give with rules under these circumstances. Oh... but why are there these rules?

 

Mark continued to watch as the media and foreign politicians left their photo-op. He watched as local warlords (thugs with guns) drove up in various vehicles armed with AK47s and small armies of troops. He watched as the politicians publicly claiming to help their people greeted these thugs, and, over-time, discovered how the funds for aid were used to fund diamond and drug trafficking. He watched as the shipments of food and medicine (supplied by various international - mostly Western - aid organizations)  arrived for the poor. The food and medicine - most often - did not get delivered to the poor and suffering, it was carted off to the warlords who used it to influence, oppress and control the local citizens.

 

Handling all the logistics necessary for desalinization is no small task. Mark watched as huge rubber tanks holding thousands of gallons of water were air-dropped into remote areas. These rubber tanks are expensive. He watched as warlords drove up to intercept the airdrop, were they punched holes into the tanks to fill a few 55 gallon drums. The tanks were ruined, the water wasted, and the people dependent on it: in trouble.

 

This venture occurred during the 1980s and this article highlights that nothing has changed: Failed Water Plants; although, one should take note that the article points fingers in the wrong direction. No wonder Paul doesn't understand: too many media sources are not interested in truth anymore. My sister travels to Africa often. She just climbed Mount Kilamanjaro a few months ago. If you read the article, then you know that foreign aid amounts to a whopping 1/3 of the income in Tanzania. The failed plant was not due to Western corruption, its due to local corruption. This local corruption been going on so long that many nations are demanding rules or they will cutoff support.

 

Mark knows there is a consistency in the world where the higher the corruption, the more impoverished its people. Corruption exists everywhere, but its highest in poor nations - and that is why they are poor. When Warlords storm the supply depots for the desalinization plants and take critical supplies, when they take food and medicine, when they murder their own citizens, when they divert funds intended for aid to diamond and drug traffickers and to purchase weapons, when they do these things, they are killing their people and they are making their country poor, and they make the dreamy, idealistic notion of helping them seem far beyond reach.

 

Western nations do have their own corruption, but it is not the gluttony of Western nations nor the result of international trade agreements that is making poor nations poor. It is the local corruption and the local policies of the respective nations that is the root cause, not the subsidies of US rice farmers.

Finally: A Code Snippet Plugin that Works!

 

I am new to blogging and am using Windows Live Writer (beta) and am really liking it. However, I did have an initial stumbling block: I could not easily post source code and get it to display properly.

I downloaded the Code Snippet Plugin for Windows Live Writer authored by Leo Vildosola and here is the best result I could obtain:

 

using System;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.ViewInfo;
 
namespace CustomSimpleButton {
 
 public class CustomButton : SimpleButton {
 
 public CustomButton() {
 this.TabStop = this.AllowFocus = false;
 }
 
 CustomButtonViewInfo m_customButtonViewInfo;
 
 protected override BaseStyleControlViewInfo CreateViewInfo() {
 if (m_customButtonViewInfo == null)
 m_customButtonViewInfo = new CustomButtonViewInfo(this);
 return m_customButtonViewInfo;
 }
 }
}

 

If it displays on this web page for you, the same as it does for me, all of my lines of code are shifted or justified left (it's hard to read) and it does not use the colors or formatting that I use in Visual Studio. It seems like a potentially decent plugin with some unusable flaws for me; although, other users do not seem to have the same justification problem I am experiencing. I wrote the author about my justification problem and have not received a response, so I moved on to look for something better...

 

I tried every plugin I could find for WLW ( Windows Live Writer ) and I could tire you by demonstrating that none of them would display properly. Either they lost the basic formatting similar to above, or they used hard-coded color schemes that were offensive to me, or something just not acceptable happened with each plugin I tried... and I tried every one available for download (approx. 5 to 8).

 

I did, however, find a clear winner and it was not a plugin for Windows Live Writer, it is a plugin for Visual Studio! It uses the formatting settings that I use in Visual Studio and is very simple to use. You tell me, does this second sample appear better to you?

 

Code Snippet

using System;

using DevExpress.XtraEditors;

using DevExpress.XtraEditors.ViewInfo;

 

namespace CustomSimpleButton {

 

    public class CustomButton : SimpleButton {

 

        public CustomButton() {

            this.TabStop = this.AllowFocus = false;

        }

 

        CustomButtonViewInfo m_customButtonViewInfo;

 

        protected override BaseStyleControlViewInfo CreateViewInfo() {

            if (m_customButtonViewInfo == null)

                m_customButtonViewInfo = new CustomButtonViewInfo(this);

            return m_customButtonViewInfo;

        }

    }

}

 

What is this magical plugin? It is CopySourceAsHTML written by Colin Coller and released by J.T. Leigh & Associates Inc.

Note: the Code Snippet box is my own wrapper and is not created as part of the plugin: the plugin just auto-creates wonderfully formatted code for the web.

The steps I take are simple:

I insert my Code Snippet template in Live Writer, I switch to Visual Studio and highlight my code, then I right-click and select CopyAsHTML from the context menu. I then switch back to Live Writer and place my mouse cursor in the Code Snippet box. The final step is choose Edit, Paste Special, and select the option, Keep Formatting. Wa La - it's done!

All of this is done with an easy to use WYSIWYG blog post editor: Windows Live Writer (beta) and the assistance of a very helpful plugin.