Sunday, March 1, 2009

Livescribe and Accounting

BigPromoImage_02I purchased a new Livescribe pulse pen and… well.. it ROCKS!

I am currently attending PSU (Portland State University) and, as most college students will know, not only is it difficult to take notes at the speed in which some professors may speak, it is nearly impossible to recall everything they have said… until now…

 

livescribepen2

 

The Livescribe pen is amazing. It records audio (yes, the pen itself) that really captures the sound from an entire room very well. Of course, the more personal the scenario and the less ambient noise the better, but this pen works very well in a classroom. If it only recorded audio, this pen would be amazing, but it records what you write as the audio (sounds) happen. After recording, you can upload the sound and notes to your PC. Once loaded, you can watch or observe every pen stroke as the original audio plays. Even further, the software uses OCR (optical character recognition) technology and you can search through the handwritten notes which are now loaded on the PC. You can take the original note book and just touch a spot on the notebook and the sound plays that matches that exact moment in time. In addition, you can touch a spot in the already written notes (where you couldn’t possibly keep up with an instructor) and re-listen to the speech… here is the cool part… you can add additional notes that are synchronized to the audio. Not only that, you can upload the result to the web and share it with others (privately or publicly).

 

Here is my very first class and my first day using the pen:

http://www.livescribe.com/cgi-bin/WebObjects/LDApp.woa/wa/MLSOverviewPage?sid=NxjZSxcW1zsl

 

The beginning or first page is not the best example: the instructor was talking about the results of an exam and I was writing notes related to a transparency on the screen. I do think it shows off some usefulness for the pen.

 

Go to their web site: www.livescribe.com

 

Watch the demos.

 

Get the darn thing!

 

image.php

Friday, February 6, 2009

Understanding the Economy

image We are in a recession. The housing market has faltered. The banking system is hoarding funds. Jobs are being lost.

 

What can be done?

 

Right now, it appears there are two choices: lower taxes or the government steps-in and spends money. Which is it? Let's explore... Ahhh... wait a minute... before we begin... whenever given any task, it is important to define the goal or objective: to understand how we define success.

I suggest everyone go here:

www.dictionary.comhttp://dictionary.reference.com/browse/economy

Did you READ the definitions? Let me share some of them:

  1. Economy: the prosperity or earnings of a place: Further inflation would endanger the national economy seriously.
  2. Economy: the efficient, sparing, or concise use of something: an economy of effort; an economy of movement.
  3. Economy: the management of the resources of a community, country, etc., esp. with a view to its productivity.
  4. Economy: thrifty management; frugality in the expenditure or consumption of money, materials, etc.

What I don't see listed in the dictionary reference to the term economy is what I believe most people mean: the complex relationships intertwined in business and government interaction that either results in overall prosperity or overall depression. Let's be clear. Don't we all want the "economy" to mean that - overall - people are most able to be prosperous?

I listened to President Obama as he he urged the Senate to pass the Stimulus Bill. Here are some of his comments:

    • image

  • "If nothing is done, this recession might linger for years."
  • "Our economy will lose 5 million more jobs."
  • "Unemployment will approach double digits."
  • "Our nation will sink deeper into a crisis that, at some point, we may not able to reverse."
  • "That's why I feel such a sense of urgency about the recovery plan before Congress, the Action Americans Need."

I ask you (the reader) to consider, "How many decisions are 'good' decisions, the 'right' decisions, when people are urged not to think, not to take time to give any issue proper considerations, and are asked simply to support the decision?"

I have learned two very important rules over time and they apply everywhere:

  1. Anyone who tries to solve a problem by simply "writing a check" is simply funding an idea with no direction. There is no guarantee of results, but there are very high odds that the money is NOT well spent. So, the rule is: Beware of anyone, anywhere, at anytime, who claims any problem will be resolved simply by "writing a check."
  2. Panic is bad. Whether you arrive at an accident scene and lives are in danger, or whether you manage a business in a seemingly perilous position, or whether you are a government official facing a crisis... no matter what scenario, a poor approach involves panic. It is always better to be calm, collective, reserved, and to take the time to assess and evaluate in order to form a prudent and wise decision.

So before going deep into analysis, I have to say that I am disturbed. I am disturbed that we are "urged" to stop thinking and support a $900+ billion dollar bill (simply writing a check does not work). I am disturbed that nearly every definition of an economy involves frugality and the "wise" or efficient use of resources. Where did anyone get the idea that confiscating tomorrow's money today (from taxpayers) and spending it willy-nilly will result in a prosperous economy?

Now, it is time to explain, to define why Obama's plan is destined to fail (it has zero chance to boost the economy).

First, when Obama suggests that he is only spending $800 billion, he is understating the amount. The government is already spending more than they receive; they are in deficit spending now. In order to spend more money, they must borrow the money. It is like a consumer buying a car via a loan and telling you that it only costs $10,000. They neglect to include the interest. In the end, the car may cost $15,000+ after interest. $800 billion in spending today is simply going to cost much more... more like $1.2+ trillion!

This is important. The government "spending" option immediately involves added cost.

If the government were operating at a surplus (they took in more than they spent), then there would not be added cost and they would be freeing capital. If businesses and individuals were hoarding money, if savings accounts were building, if - essentially - people were holding their money back in fear of a bad economy, then government spending might change the "psychology" of the market and induce people to free their capital to better the economy. However, this is not the case.

Obama has repeatedly bashed former President Bush and has let everyone know, in no uncertain terms, that the economy faltered under Bush; therefore, all his policies were bad for the economy. In particular, Obama highlights George Bush's tax cuts. I ask, this:

If you have a business and the government cuts your taxes, how does that cause your business to decline?

How does any single person buy that argument? It is complete nonsense! While it is true that the economy faltered under Bush, it is not due to tax cuts. So, what did happen? Perhaps, it is because government grew massively under Bush? How about the idea that tax rates mean nothing if government spends the money anyway? The only difference is that government essentially issued credit cards in the name of taxpayers to compensate for the lower tax rates.  How about the idea that government is supposed to ensure that business transactions and the overall business environment is safe, secure, and managed well. Instead, government actually ordered Fanny-Mae  and Freddie-Mac to give loans to those who could not afford loans. How about government getting rid of usury laws allowing credit cards companies to gouge consumers? How about "mandatory arbitration" clauses in contracts so consumers get screwed. How about government allowing executives to run banks to the ground and they fix the problem by handing them billions of our money?

We are being taught that businesses are "evil". We are taught to hate the "rich". Let me ask this to test your business acumen, "If a corporation earns a profit, what does that mean to the owners or stockholders, or better yet what can the corporation do with the money?"

The answer:

A corporation can only do this with profits:

  1. Buy property, plant, equipment or other items; they can "buy stuff"
  2. Give employees raises
  3. Hire new employees
  4. Invest the money (which just goes to another business)
  5. Pay dividends

That is it, but why is this important? Well, I ask people if Microsoft earned $100 million dollars, how much can Bill Gates spend for his personal use? The answer is ZERO!

Microsoft would have to issue a dividend (a payment to stockholders)  or Bill Gates would have to sell shares of his stock. Dividends are TAXED! Wages are TAXED! Selling stock is TAXED!

So, why is there a "corporate tax"? Think about it. A corporation can only buy stuff which drives the economy and adds jobs, or they can pay employees more, or they can hire employees, or they can invest which provides to other businesses and individuals. In other words, lowering the corporate tax (what Bush failed to do) can only drive the economy. If corporate taxes were lowered, it could have no other effect than boost the economy.

So, why is Obama so against lowering corporate taxes? Why? Why? Why?

It is simple. You KNOW the answer. It means the money goes STRAIGHT to businesses. It avoids government involvement. Obama wants POWER! If, instead of lowering corporate tax, they "spend" the money, what happens?

The money goes to Obama, not business. Businesses then must line-up outside the White house door to beg for their share. Look at the Bank Bailout. What happened? Bank executives lined up and streamed inside to "beg" for some money. This is the real goal. It is not to feed the hungry, boost the economy, save the nation, or any other line that will convince you of his deepest support for your needs. Look at the Stimulus Bill. Read it!

It pays off his political supporters. It does not get spent anytime soon. In other words, it is NOT a stimulus bill. It spends some now and most later. More importantly, it is simply PORK! LOTS OF PORK! Nearly ALL PORK! It is a PONZI scheme! In fact, what is the difference between Bernard Madoff and Barack Obama?

image

Bernard Madoff convinced people to give him money with the promise to make them money. He knew better. He knew he was scheming. He knew that what he really wanted was their money!

Barack Obama is either a complete idiot, a moron, the dumbest individual on the planet, OR...

Barack Obama knows he is feeding you rhetoric. He knows that he could "do the right thing" (I.e. lower corporate taxes and not spend unwisely), but that doesn't divert the money into his arena, his world... the world of forming special relationships and living the good life off of our tax payer money. 

Bernard Madoff only ripped-off investors for $50 billion... if you support Obama and his Ponzi scheme, he is just beginning with $900+ billion.

When is our country going to wake up? If you are a Barack supporter, when will you look at what he does and not what he says? If anything like the current bill passes, our economy will decline, we will have the Jimmy Carter era all over again, and, God Help Us, we may actually experience another depression. The only good from this may be that Americans wake up and stop accepting phony speeches and start demanding results, common sense, and someone with a history of success before voting them in as President.

Are you still possibly a Barack supporter? Didn't you hear him during his election campaign? Didn't he say he would go "line-by-line" through the government budget to keep what is good and eliminate the bad? Are you one of those who watched the movie Dave and thought Barack would be the real-life equivalent? Do you still believe that?

Hmmm?

Answer this: Why is it that the "line-by-line" items in the "stimulus bill" are, hands down, the most egregious, offensive, and disgusting pile of stinking pork in the history of the United States that totals more than all stimulus bills ever signed combined? Add up all the stimulus bills from the depression, to the sixties, the seventies, and onwards. This single bill (adjusted for inflations) is MORE than all of them combined! It is not the dollar amount that is so bad, it is where they actually plan to spend the money. Hello? Is anybody awake out there?

 

References:

http://news.xinhuanet.com/english/2009-02/06/content_10770840.htm

Monday, January 19, 2009

The Economy: What will fix it?

There are certain moments in life when a person realizes that their ideas remain solely in their thoughts; within their own mind; there is no record. I, like many others, often listen to the news and have some expectation that 'expert opinion' or competent views are the ideas expressed widely by news organizations. This blog is an effort to cement a moment in time with my own personal opinion. It is an effort to forecast the U.S. economy based on personal opinion and simultaneously create a record to validate or invalidate my opinions.

George Bush and italian Romano Prodi meeting This moment is an end of an era: the George W. Bush era. I meet few people that are happy with George W. Bush - overall. This blog focuses on one aspect of his Presidency: the economy! First, there is no question that the economy at the end of George Bush's Presidency is not good. However, there are important questions: What happened? What went wrong? What will fix the economy?

 

Perhaps you are one of those who heard, "George Bush was President the last eight years. The economy is bad under George Bush. George Bush supported "trickle-down" economics. George Bush supported reductions in capital gains taxes; therefore, reductions in capital gains taxes are bad for the economy!"

Is this true? Shouldn't we ban any reduction in capital gains taxes? After all, these tax reductions must have benefited the rich and made the poor more poor, correct? Before answering these questions, let's consider some basic concepts in any beginning-level philosophy class. Let's consider some fallacies of reason. Let's assume that "All ducks are white." The point is not whether all ducks really are white, the point is to understand logic and reasoning. So, if I say, "All ducks are white. Harold is a duck; therefore, Harold is white." Is the the logic sound? I submit that the logic is sound. If, in fact, all ducks are white and Harold is a duck, it must be true that Harold is white. Now, if I change the statement to: "All ducks are white. Harold is white; therefore, Harold is a duck." Is that logic sound? I submit that it is not. While all ducks are white, it is not true that all things white are ducks. It is important to note that sound reasoning must be understood and employed or there is no point in analysis. The point is to identify fallacies of reason, to look for truth not rhetoric.

So, George W. Bush supported reductions in capital gains taxes and while he was President the economy went south: the economy has entered into a severe recession. I ask this, "How does reducing taxes, in any form, cause an economy to decline?" There is only one major argument to support such a statement. The argument must be that government failed to collect taxes AND that those taxes would have been spent in support of the private sector for necessary fundamental government functions such as roads, highways, or, importantly, an overall oversight of the market such that the market is allowed to function freely. Is that what happened? The U.S.  had insufficient infrastructure? There were too few resources for police, law enforcement, and those that are part of the legal system? I submit that the U.S. had ample resources and ample infrastructure. While there are substantial arguments for improvement, I don't believe there was such a massive reduction in government resources that the economy had to to decline into a recession.

Now I have to ask, "Does every reader even understand what is a capital gain?" It is a simple concept but many simply do not know. A capital gain is the result of a purchase and sale. If some property is purchased (whether it be stocks, a building, or whatever) there must be a resulting sale where the sale price is greater than the purchase price. If this happens, there is a capital gain. For example, if a building is purchased for $100,000 dollars and it is later sold for $120,000 dollars, there is a capital gain of $20,000 dollars. The U.S., generally, requires citizens to report these gains and pay taxes on these gains. I ask, "How is it possible that reducing taxes will cause the economy to decline?" Other than the government reason supplied above, it is NEVER possible!

barack_obama So, what really happened during the last eight years? This is the "meat" of what I want to have on record. Further, I want to have on record my predictions for the current proposals by the incoming administration, the Barack Obama Administration.

 

 

 

My view of what happened:

  1. Both state and federal governments have substantially increased deficit spending: they spend more than they collect. When governments spend more than they collect, they essentially issue credit cards against those who pay taxes. Currently, there is about 303 million citizens in the United States. The recent "bailout bill" cost $700 billion dollars. If we divide $700 billion by 300 million citizens we get approximately $2,310 per citizen. However, 40% of American citizens do not pay tax. They do not contribute their income to address such deficits. In my opinion, it is incorrect to include those who are not liable for the debt; therefore, we need to divide by approximately 182 million people who are liable. The result is $3,850 per tax-paying citizen. The current total deficit (before the bailout) is about $10 trillion dollars! Each tax paying citizen (before bailout) is liable for ~$55,005 dollars in debt. This burden is dominating the private sector (business) and driving the economy down - period.
  2. Federal and state laws have increased the cost of business by continually adding the burden of increased laws and regulations. For example, building construction requires permits and inspections. Right here in the state of Oregon, we have inspectors to verify the proper installation of various structural components. Businesses must submit proposals, pay fees, and wait for inspections. Isn't it interesting that the building inspectors failed to catch severe flaws in their own building? Water pipes burst and flooded the building - after their inspection. What is important is that, for all the costs and delays, statistically, there are the same number of flaws in construction as there are without inspections. What are these inspections for? It might be understandable, or acceptable, if these added costs resulted in structures with substantially reduced failures and increased safety. That is not the case; we just pay more and wait longer for the same result.
  3. The Abandonment of Usury laws. If you look at the one possible reason that reducing taxes could possibly cause the economy to fail. Usury laws would be part of that reason. Isn't it interesting that there has been a trend for citizens to pay increasingly higher interest rates and penalties to maintain their debt? Increased taxes did not result in better oversight, it resulted in the opposite: worse oversight. Credit cards now have interest rates as high as 39%, so do credit lines and many other forms of debt. Our government has taken increased tax revenue but have failed to protect citizens. It is my submittion that failure for proper oversight is the underlying reason why homeowners are defaulting in higher percentages than ever before. Government is not short money, they are large in corruption.
  4. Failure to stomp out corruption - Yes, this is a broad topic, but it is simply too true. AOL had millions of customers requesting to end their payments; to stop their service and AOL simply kept billing them and refused to acknowledge customer requests to end service. AOL's actions were criminal and massively costly. Did the government react? Did they help? No! They allowed AOL to collect cash they did not earn. Further, this was one more stone cast on the average citizen that resulted in one more step closer to bankruptcy. AOL should have been forced to compensate every last customer who requested their service to end and instead had their bills extended. There is only one reason why AOL and other organizations get away with such scandalous behavior, they lobby politicians and buy their protection. The scandals in Chicago and California and New York and Connecticut, etc never cease. I live in Oregon. We need a new bridge. We have paid millions to "study" the "right" new bridge. The bridge that collapsed in Minnesota was replaced for approximately $280 million. The bridge we need is smaller. The current proposal: in excess of $4 billion dollars! Corruption is rampant in Oregon too.
  5. Credit Reporting Bureaus - as noted with AOL, many businesses simply lie; they report debt that they are not entitled to collect. I personally was billed by Direct TV after I canceled my service. I paid after I canceled by phone and could not prove that I canceled. However, after that experience, I wrote on my check, "Last payment, by accepting this check the bill is paid in full". Direct TV canceled me and mysteriously reactivated me retroactively. I referred to my check, and they removed their claim... until they SOLD that claim to third-party collectors. To this day: I prove I canceled and paid and the phony debt resurfaces and ends up with a new collector (it has been removed and reactivated more than ten times for more than ten years). The process of removing bogus debt is atrocious. I worked as a loan officer for a brief time and read thousands of credit reports and worked with many people with similar issues. There is simply a hugely weighted scale in favor of anyone claiming a debt and almost nothing in place that actually works long-term to remove false claims. My opinion why? It is simple, bad credit reports allow every lender to charge higher rates. These lenders lobby politicians and get what they want. The result is a debt-laden society on the verge of a depression.
  6. Gambling - this is a no-brainier. Anyone who travels anywhere that gambling is legalized knows that the majority of those "playing" are those who don't make a lot of money and are those who can afford such habits least. It is simply predictable that a percentage of the population WILL gamble more than they can afford. Even those who gamble and still manage to still pay their bills. Of these, there is a percentage who have essentially kept themselves from growing their wealth. It was one thing to support casinos on reservations, in limited fashion, in order to provide a means for native Americans to add value to their land. That concept was destroyed when tribes were allowed to lease land and call it "reservation" land. Simply put: gambling destroys a significantly predictable percentage of the population.
  7. Okay - there are many more reasons, but you get the point. These type of problems MUST be corrected: the actual reasons that the economy has scaled back and began to decline. We don't need rhetoric and we should be scared of what could actually make things worse.

My forecast:

Barack Obama has suggested that massively increased government spending will solve the economic problems. He supports over a trillion dollars in increased deficit spending and simultaneously supports increased taxes. This is a recipe for disaster. The government cannot even account for the $350 billion dollars they recently spent in the bailout bill. I don't care if a person refers to a business or government. It is not likely that any major problem will be solved by simply writing checks and throwing money at the problem. Problems are solved by actually applying sound reasoning and judgment, by understanding fallacies of reason.

Can anyone name what Barack Obama identified as the cause the economic problems during the Bush Administration?  I am positive that no person can because he never did. He always stuck to generalizations. He played a 'guilt-by-association' game of Bush was there, bad things happened, they are bad, I am good. We are for change. Change with me will be good.

Hmmm? What did he say? How will things improve? Is he really 'good' (for the economy)?I am not saying he isn't, but I am saying that what little he has proposed seems to be a recipe for economic disaster. Increasing government spending, raising taxes, and finding more ways for government to be a burden via laws and regulations will never steer any economy into growth.

I needed to have this on-the-record. I needed to be able to look back after Barack has been in office and compare my forecast from today with the actual results of tomorrow.

It is my prediction that the economy will continue to decline until actual problems (like those I identified) are corrected. We need the government to cut-back, not expand. We need corporate tax cuts (different than capital gains cuts which don't provide significant incentives in declining economies; only in flat or growing). We need those who fail in business to be relieved of their jobs, not given bailout money.

What would have happened if we gave over a trillion dollars to those businesses that succeeded rather than hand-out money to those who failed... to the sinking ships?

The future (as proposed) does not seem hard to predict. I actually hope I am wrong, but I cannot map-out any logical scenario that leads to an improving economy when corruption continues to be brushed aside (in fact seems to be expanding), government is expanding, debt is increased, taxes are raised, and laws are increasingly more costly and burdensome. Help me understand, please, how can so many news organizations find so-called "experts" that actually believe the current proposals have any chance of success? We don't seem to have experts anymore. We have someone's pal, friend, or a supporter of some preconceived idea packaged as an expert. So, I am now on-the-record. Only the future will validate or invalidate the statements made.

Friday, December 7, 2007

Namespace Alias Qualifier

 

I have noticed a trend with code auto-generated from Microsoft tools.

 

Here is a sample section of code as I would have viewed it in older samples:

Code Snippet

   23     [System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName = "PizzaModel", Name = "PizzaOrder")]

   24     [System.Runtime.Serialization.DataContractAttribute()]

   25     [System.Serializable()]

   26     public partial class PizzaOrder : System.Data.Objects.DataClasses.EntityObject {

 

This is the exact same code, except it includes the more recent changes that I happened to notice:

Code Snippet

   23     [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName = "PizzaModel", Name = "PizzaOrder")]

   24     [global::System.Runtime.Serialization.DataContractAttribute()]

   25     [global::System.Serializable()]

   26     public partial class PizzaOrder : global::System.Data.Objects.DataClasses.EntityObject {

 

Notice the reference to 'global::'? Apparently, Visual Studio and ultimately the compiler can potentially be confused.

 

Here is a link to the Namespace Alias Qualifier:

http://msdn2.microsoft.com/en-us/library/c3ay4x3d(VS.80).aspx

 

According to that sample, you may have a namespace TestApp and within that TestApp namespace have a constant named Console within a class named System. The example also shows a using statement referencing the namespace System. That combination is apparently deadly to the compiler and even though Console.WriteLine() exists within the System namespace; it cannot be referenced because it conflicts with the Console constant. Here is the "non-working" code:

Code Snippet

    1 using System;

    // yada yada ...

    8     class TestApp {

    9         // Define a new class called 'System' to cause problems.

   10         public class System { }

   11 

   12         // Define a constant called 'Console' to cause more problems.

   13         const int Console = 7;

   14         const int number = 66;

   15 

   16         static void Main() {

   17             // Error  Accesses TestApp.Console

   18             //Console.WriteLine(number);

   19         }

   20     }

 

To the rescue: We have the 'global::' namespace qualifier available which forces a namespace comparison to be  based on the entire namespace starting from the root. I can only assume that namespace collisions (at least for Microsoft) happen more often than we assume; especially, when code generators are involved.

It is one thing to create and compile code within Visual Studio, but its entirely different if you are creating/ managing a code generator where you can never be sure of namespace conflicts. I happen to use CodeDOM (http://msdn2.microsoft.com/en-us/library/y2k85ax6.aspx) and understand completely how this could benefit my auto-generated code.

If you auto-generate code, it may be wise to to include a global reference similar to the new trend I am noticing. If you do not, this post may be helpful to simply understand the global reference.

 

 

 

Entity Framework Model Designer

I am just making a post to my BLOG here so that I can share an issue with the layout algorithm of the model designer with users in the Microsoft forum. Essentially I am showing the the automatic layout function could be improved (IMO).

 

Here are two images of the designer after choosing 'Layout Diagram' in the model editor. The model is the AdventureWorks database.

 

EntityModel-1

 

EntityModel-2

Technorati Tags: ,,,

 

The top image shows how text is overlapped and the diagrams are crammed together. The bottom image shows the entire layout where the algorithm clearly fails to use width appropriately.

Wednesday, December 5, 2007

eBay - Worse than SPAM?

I happened to be checking on current prices for the Nintendo Wii game console and browsed the listings on eBay.

 

Here are a couple of screen shots showing the search results:

This is of the "featured items":

Wii-1

 

... and this one is from "Highest to Lowest" pricing:

Wii-2

 

WOW!! the pricing of "featured items" ranged from ~$1,700 to $20,000 US. In the regular listings, the highest priced Nintendo Wii was listed at $5 million!!!

 

I suppose we all wish that we could list an item and receive far more than its worth (like millions more and simply retire). Surely we can all expect, out of the "goodness" of someone's heart, such outrageous purchase prices - but - seriously - this is making eBay the equivalent of a rotten Email program that not only doesn't block any SPAM; it supports and promotes the creation of SPAM. Ebay's listings are simply becoming inundated with more and more garbage and finding valid items within this slue of garbage is becoming ever more problematic.

From my view, it is becoming so hard to sift through search results that eBay is becoming a joke. I am not sure what can be done - maybe a rule that forbids pricing above suggested retail without some truly valuable and tangible asset being added to the item? Maybe separating these baloney listings into a separate category?

 

Is eBay becoming too cluttered with such garbage for you as well? What are your ideas or suggestions for eBay?

Technorati Tags: ,,

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.