Thursday, December 5, 2013

You Probably Shouldn't Buy Bitcoin

Edit I've reversed my position. Everyone should hold some bitcoin. The reward potential far outweighs the risks outlined below. Read more here.

TLDR - It is probably a bad idea for you to invest in bitcoin. Instead consider the S&P 500 which has never lost value in a 20 year period.

My Excitement
I'm very excited about bitcoin. It is going to do to payment companies what the telephone did to the telegraph. If that does happen an individual bitcoin is going to be worth tens of thousands of dollars.

My Mistake
Lately I've been wrongly advising friends to put some money into bitcoin, but by some I really mean hundreds or thousands of dollars. I claim 'an amount you can lose without issue', but if something is going to go up soooo much why would anyone get in for just a few bucks? If they believe what I'm saying why in the world would they just get $10 worth?

9 Reasons not to Invest in Bitcoin
Yesterday I blogged about bitcoin and unfortunately recommended readers buy some. Some friends brought up good counterpoints and I've reversed my position. Here is why you should not invest in bitcoin
  1. Bitcoin could drop in price 99% tomorrow. In fact on 8/17/2012 it dropped 30% in an hour.
  2. 100% of your bitcoins could be stolen from your online wallet, stolen from your computer, stolen by your online wallet, stolen by a virus on your computer, stolen by a virus on your smartphone, stolen by your online wallet host, and stolen by security flaws in your online wallet software.
  3. The online wallet you hold your bitcoins with could go out of business.
  4. You can lose 100% of your bitcoins by forgetting your password or throwing out a hard drive.
  5. You can easily violate US laws you are unaware of. I was unaware of the Foreign Account Tax Compliance Act or of the Banking Secrecy Act Report of Foreign Bank and Financial Accounts requirement which I could easily have violated.
  6. Tax compliance is difficult. You should plan ahead but probably won't.
  7. Bitcoin price swings will stress you out if your bitcoins go up a lot in price.
  8. Bitcoin price swings may cause you to sell at the wrong time, buy at the wrong time, sell at the wrong time, over and over and over. Read this man's unfortunate story.
  9. There are lots of bitcoin scams like this ponzi scheme.
How to Surely Get Rich
The sure way to riches is with steady payments and compounding interest. I think the S&P 500 is a great investment and has never lost value in a 20 year period. I have a large percent of my retirement portfolio in the S&P through the SPY fund.

Wednesday, December 4, 2013

Bitcoin is Provably Valuable

TLDR (too long didn't read) - bitcoin is valuable. The easiest way to buy them is Coinbase.

Bitcoin is two things:
  1. A payment network (think PayPal, Visa, MasterCard, Western Union)
  2. Money - a medium of exchange, a unit of account, and a store of value.
Why are payment networks valuable?
It is more efficient to exchange money for goods and services instead of barter. For example if I wanted a pound of rice and had a cow it would be hard to fairly divide the cow for my rice, especially if I don't have a way to store the remainder of the cow. Using money it is easy to sell the cow and then purchase the pound of rice. Payment networks make it more convenient to pay for goods and services than physical money. Visa, MasterCard, Discover, and Western Union have shown that payment networks are valued by society. Today their combined market cap is over $250 billion dollars.

Why is money valuable?
Money is valuable because other people will give goods and services for it. If a government states money is valuable but people will not accept it for goods and services. Think that can't happen? It has happened many times before.  Gold is not money, but it is a store of value and gives an idea of how much something can be worth that is not backed by a government. Today the gold in the world is estimated at a value of $8 trillion. For comparison the market capitalization is 14 billion. That means bitcoin would have to go up another 571 times to be equivalent to gold. I don't think there is a question of if that can happen, but a question of if it will happen.

How does this make bitcoin provably valuable?
Bitcoin is a great payment network. Unlike PayPal, Visa, MasterCard, etc. bitcoin cannot go out of business, cannot steal from you, cannot cheat you, etc. It has no marketing budget, no CEO to compensate, no board of directors, etc. 

Bitcoin is great money. Bitcoin is the best way for people to accept money because it is the most efficient, it is nearly impossible to counterfeit, and there is no way for a third party to cancel or modify the payment. It does not use any countries currency making it immune to mistakes made by politicians and rulers of fiat currencies. Like gold there are a fixed number of bitcoins meaning after the volatility settles down it will be a great store of value.

Should I invest hundreds or thousands in bitcoin?
No and here are 9 reasons why.
If you have some money you can lose without issue I recommend considering buying some bitcoins. I believe this is a special time in history, like the 1889 land run it is possible to get very wealthy very quickly with bitcoin, like the gentleman whose $27 investment turned into just under a million dollars in 4 years.

How do I get bitcoins?
The easiest way if you live in the US is through Coinbase.

Tuesday, November 19, 2013

Your business can accept Bitcoin in 5 minutes

Bitcoin is a great way to get paid because transactions are irreversible and bitcoins can't be forged. So there are no worries about credit card chargebacks and almost no worries about fraud.

The easiest way to accept payment is through Coinbase. After signing  up on their site you can use the Coinbase merchant tools to invoice a customer via email.

Coinbase will let you avoid the price conversion fluctuations of Bitcoin by immediately converting your customers Bitcoin payment into cash and depositing it into your bank the next day. They charge a 1% fee for this service, but have a special right now where the first million USD in sales has no charge.

Coinbase also has services to setup shopping carts allowing customers to buy merchandise from your website with Bitcoins, but that takes a little bit more work to setup. If the volume would support it you may even be able to automate it where they order a product from your website, your website orders from the supplier and then when the order is delivered the customer is emailed for pickup.

Wednesday, September 18, 2013

Explaining Bitcoin to Grandma

Want to know more about Bitcoin but don't care about the geeky underpinnings?

Here are some differences between Bitcoin and the traditional US financial system:

TraditionalBitcoin
Accounts
  • Most users hold a small amount of spending money in a wallet and most of their money in an account. 
  • To create an account one needs to find a financial institution to supply the account, apply for the account, give them all kinds of personal details, fund a minimum deposit. 
  • Banks accounts pay interest for using account holder's money and charge fees for services. 

  • It is a best practice to hold a small amount of spending money in a "spending account" and large amounts of money in accounts created on machines not connected to the internet.
  • Accounts are created through software or using a service provider.
  • There are no minimum balances and no interest paid on account balances.
  • It is recommended when sending funds to include an optional fee. Today the recommended fee is around 6 cents.
Transaction History
  • A receipt is needed to provide documentation of payment between parties.
  • In financial institutions transactions are kept private, but may be provided to government entities (courts, regulators, law enforcement)

  • All transactions and account balances are publicly visible. However account holders are only known if they disclose their identity - such as submitting identifying information to an exchange or as part of a transaction.
Reversibility
  • Cash transactions are irreversible.
  • Most other types of transactions are reversible.

  • Transactions are irreversible but the other party may issue refunds.
Issued By

  • Computers solving mathematical puzzles.
  • The process is called mining. 
  • Today specialized hardware is needed to profitably mine Bitcoins.
Currency Limits
  • Governments can create as much currency as they want.
  • This devalues that government's existing currency.

  • 21 million Bitcoins. 
  • Bitcoin is created at a predictable rate and will stop being created around 2140.
Risk of Loss
  • When I've had fraudulent transactions on debit cards and credit cards they have been reversed no problem by my banks.
  • When I've had cash stolen I've never recovered any of it.
  • US depository funds are covered by the FDIC. Banks have bonds to cover losses.



  • Improper use of software can result in loss of funds.
  • Having a computer hacked can result in loss of funds.
  • Software bugs can result in loss of funds.
  • Institutions being hacked have resulted in loss of funds.
  • Computer destruction or theft can result in loss of funds.


Sending
  • To send money a great length of distance I need to use a third party or deliver it in person.
  • Taking amounts over $10,000 across the US border needs to be declared to FinCEN.

  • The difficulty of sending funds does not change with distance. Bitcoin can be delivered across the globe the same way Bitcoin is delivered to your neighbor.




Tuesday, May 22, 2012

Don't use Video Clips when Presenting

I recommend do not play video clips in your presentation. Find a different way to deliver the message.

Over the past year I've attended a few presentations where the presenter played a video clip. Often these clips range from two to five minutes.

Here are the problems with the video clips:

  1. I am here to watch the presenter. If I wanted to watch that clip I would watch it on the computer.
  2. Sometimes the clips are excerpts of shows or movies and don't make sense without the context.
  3. Audio can be hard to hear and video can be hard to see because of the lighting.  Often there is scrambling at the beginning of the clip to adjust the audio volume. It works fine on the presenters computer at home, but is then presented on a different projector and probably even a different computer.
  4. During the video clip the presenter often stands awkwardly to the side of the presentation area or look at their computer screen. This loses the audience.
Find a way for you to deliver the message instead of the video clip.

Tuesday, December 13, 2011

Free conference calling

Have you ever needed to setup a conference call without access to a corporate conference calling number?

This summer I had just such a need. For four months I used freeconference.com for weekly morning conference calls. Instead of scheduling a meeting every week I used their reservationless conference feature to have a conference call always ready to go! This enabled the meeting notices to have the same dial in number and access code and alleviated me from having to manage the meetings through their software. No  need to hand out codes to attendees each week.

This software has worked so well I hadn't logged in since I set it up. Fortunately my password manager saved my password so when I accessed the site today I didn't have to dig around for my credentials.

Tuesday, October 25, 2011

Never forget another password

In 1994 when I got on the internet in the sixth grade I had one username and password. I can remember one username and password. Life was good. Fast forward to 2011 I have no idea how many usernames and passwords I have: 50 , 200? Who knows. I've had to use forgot password buttons, forgot login buttons, had my accounts frozen for months, written passwords down in documents, had to call help desk support for assistance. I don't have to do any of that anymore.

What changed? I installed a piece of software called LastPass. This handy software remembers my usernames and passwords for me. I have it set to automatically login to sites I visit requiring passwords. It works by using a master password. I have my master password set to a passphrase, something easy to remember but impossible for computers to guess, like "myfavoriteteacherwasMrs.SavageIn7thGrade"

There have never been any security breaches of LastPass, but I don't use it to store my financial passwords just in case. This means I only have to remember 5 passwords, one for everything non-financial, and then one password per financial institution.

Try LastPass it is free and makes your life better.

Tuesday, September 27, 2011

Page_LoadComplete not being called in a user control

I needed some logic to execute in a page load event after a control event had occurred.

Initially I wrote:

        protected void Page_LoadComplete(object sender, EventArgs e)
        {
            if (newQuestionControl.ShouldShow)
            {
                mpeNewQuestion.Show();
            }
        }


I put a breakpoint and noticed my logic was not being called.

Since I'm in a user control there is no LoadComplete event. I fixed it like this:


        protected void Page_Init(object sender, EventArgs e)
        {
            this.Page.LoadComplete += new EventHandler(Page_LoadComplete);
        }

Tuesday, August 30, 2011

I was on a SQL Server 2008 R2 database I wanted to backup and put on my machine.

First I tried backing it up and got this error:


Backup failed for Server. 'MyDatabaseServerName' (Microsoft.SqlServer.SmoExtended)

System.Data.SqlClient.SqlError: Cannot open backup device 'C:\MyBackupFileName.bak'. Operating system error 5(Access is denied.). (Microsoft.SqlServer.Smo)



For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.50.1600.1+((KJ_RTM).100402-1539+)&LinkId=20476

Then I tried generating scripts and got this error:

Microsoft.SqlServer.Management.Smo.SmoException: Could not read metadata, possibly due to insufficient access rights. at Microsoft.SqlServer.Management.SqlScriptPublish.GeneratePublishPage.worker_DoWork(Object sender, DoWorkEventArgs e) at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e) at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)

I figured I must not have rights to some metadata or something. In the wizard I try selecting Tables, Views, and Schemas. My script generates fine. I notice there is no create database in the resulting script. I go back to the Choose Objects screen, unselect "Script entire database and all database objects" and "Select All" objects. My script generates fine.

Monday, February 28, 2011

Storing your SQL Server Database as Text

Have you ever had trouble moving a database from one server to another?  Ever wanted to store the database in source control?  Storing the database as text (a SQL Server Script) enables plain text tools to operate on your database.

Jeff McWherter from Gravity Works showed me how to easily store a SQL Server Database as Text:
  1. In SQL Server Management Studio right click on a database
  2. However over Tasks
  3. Select Generate Scripts
  4. Click 'Set Scripting Options' to skip the first two steps.
  5. Click the 'Advanced' button
  6. For the last option in general change 'Types of data to script' from schema only to 'Schema and data'
  7. Click OK to close the Advanced dialog
  8. Select a location to save the script to
  9. Click Next to go to summary.
  10. Click Next for SQL Server Management Studio to generate the script.
  11. Click Finish and you've got your text!
  12. When executing this script
    1. Ensure the Filename in the CREATE DATABASE Statement is correct when executing this script. (Or you can comment out everything after CREATE DATABASE $YOURDBNAME$ until the first GO to have SQL Server use defaults)
    2. Since this works at the SQL Server level, you will get errors when the script attempts to create users that don't exist on the target server and then errors when it authorizes that user.

P.S. See my post SQL Server Management Studio Generating Change Scripts if you want to use SQL Server Management Studio to graphically modify the database but then script the change.

Monday, February 14, 2011

Windows and Mac are Dodo Birds

18 days ago I received a CR-48 and have used it as my exclusive computer outside of work.

This machine is perfect because :
  1. It is built for the internet.
  2. It is resilient.
  3. It is powerful.
  4. It is convenient.
Chrome OS is built for the internet.  When I'm online I am consuming information and communicating.  Neither of these tasks require the power and complexity of Windows or a Mac operating systems.  Chrome OS gets me online almost instantly and gets out of my way so I can use the web.

Chome OS is resilient.  Suffering data losses in 2001 and 2005 I moved all my important files to Google docs and Windows Skydrive.  Since moving to the cloud I have not lost a bit, and have not cared which operating system I'm on for my personal computing needs.  Chrome OS takes this a step further putting my files and applications in the cloud.  Now if my machine dies I won't waste time reconfiguring my machine the way I want it.

Chrome OS is powerful.  I was surprised I am able to take and edit photos on my CR-48, make phone calls, do online video conferencing with my son, and edit code.  Prior to receiving the CR-48 I assumed some applications didn't make sense as web apps, but now my thinking is flipped.  All apps make sense as web apps and they will all be web apps.  It is just a matter of time.

Chrome OS is convenient.  It is light, it is fast, it is portable, it is quiet, the battery lasts for 8 hours, it is secure, it is hardy.

When Windows Longhorn was announced waaaaaaaay back in the day I was excited about features it was going to deliver like WinFS.  When Windows 7 launched I didn't care about any of the features.  The world has changed.  I don't care about desktop features anymore.  None of them make my life easier and more convenient.  With Windows 8 on the horizon, I can't think of a single desktop feature I want.  Today's compelling use cases are cloud based.  I started using Mac this year.  Which features was I excited about?  Syncing with Google Calendar, syncing with Google Contacts, and storing my data in the cloud.  Chrome OS leapfrogged these operating systems and they will need to catch up or go the way of the dodo bird.

Monday, February 7, 2011

Adding Cascading Deletes

I needed to add delete functionality for an entity in one of our projects.  Unfortunately this table had 30 other tables referencing it.

This SQL generated the correct code for me faster than I could blink:


SELECT 'alter table [' + FK.TABLE_NAME + '] drop constraint [' + C.CONSTRAINT_NAME +']; ' +
'ALTER TABLE [' + FK.TABLE_NAME + 
      '] WITH CHECK ADD CONSTRAINT [' +  C.CONSTRAINT_NAME + 
      '] FOREIGN KEY([' + CU.COLUMN_NAME + 
      ']) REFERENCES [' + PK.TABLE_NAME + ']([' +
  PT.COLUMN_NAME + ']) ON DELETE CASCADE; '
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
SELECT i1.TABLE_NAME, i2.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT ON PT.TABLE_NAME = PK.TABLE_NAME
where CU.COLUMN_NAME = 'yourColumnName'

Monday, January 31, 2011

Generating a memory dump for an IIS 6 hang

This post follows up on my sample demonstration and explains how to get a memory dump from a production web server crash.

Environment:
ASP .NET 3.5
IIS 6
Windows Server 2003 64bit
Windbg 6.11.0001.404 AMD64

w3wp was crashing on the server with this in the event log.

Event Type: Error
Event Source: .NET Runtime 2.0 Error Reporting
Event Category: None
Event ID: 1000
Date: 3/3/2010
Time: 1:22:18 PM
User: N/A
Computer: _____________
Description:
Faulting application w3wp.exe, version 6.0.3790.3959, stamp 45d691cc, faulting module kernel32.dll, version 5.2.3790.4480, stamp 49c51cdd, debug? 0, fault address 0x0000000000027ded.


For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

I set adplus to get a memory dump on hang.

After spelunking around I found out I was debugging the wrong dump file w3wp.exe-APPNAME

decided to debug a different dump file: w3wp.exe_-CRMAppPool
.sympath SRV*c:\debugsymbols*http://msdl.microsoft.com/download/symbol
.loadby sos mscorwks
!threads

ThreadCount: 11
UnstartedThread: 0
BackgroundThread: 11
PendingThread: 0
DeadThread: 0
Hosted Runtime: yes
                                              PreEmptive                                                Lock
       ID OSID        ThreadOBJ     State   GC     GC Alloc Context                  Domain           Count APT Exception
XXXX    1 1a14 00000000001aa520   1808220 Disabled 0000000000000000:0000000000000000 00000000055650d0     1 Ukn (Threadpool Worker) System.StackOverflowException (00000000100b10d0)
XXXX    2 2014 000000000019d5c0      b220 Enabled  0000000000000000:0000000000000000 0000000000122e20     0 Ukn (Finalizer)
XXXX    3 2298 0000000005722570      1220 Enabled  0000000000000000:0000000000000000 0000000000122e20     0 Ukn
XXXX    4 1524 000000000556b570    80a220 Enabled  0000000000000000:0000000000000000 0000000000122e20     0 Ukn (Threadpool Completion Port)
XXXX    5  904 000000000556bb40   200b220 Enabled  0000000000000000:0000000000000000 00000000055650d0     0 Ukn
XXXX    7 2228 000000000c7e17b0   880a220 Enabled  0000000000000000:0000000000000000 0000000000122e20     0 Ukn (Threadpool Completion Port)
XXXX    8 2324 000000000c6ee560   200b220 Enabled  0000000000000000:0000000000000000 00000000055650d0     0 Ukn
XXXX    9 19f8 00000000055c7480   200b220 Enabled  0000000000000000:0000000000000000 00000000055650d0     0 Ukn
XXXX    a 2104 0000000005b8b9e0   180b220 Enabled  0000000000000000:0000000000000000 00000000055650d0     1 Ukn (Threadpool Worker)
XXXX    b 213c 000000000d039d10   180b220 Enabled  0000000000000000:0000000000000000 0000000000122e20     0 Ukn (Threadpool Worker)
XXXX    6 2370 000000000de00b90   200b220 Enabled  0000000000000000:0000000000000000 00000000055650d0     1 Ukn

Aha!  three threads with locks and one with a StackOverflowException.
The column with the XXXX is supposed to list out the native thread so I can switch to it and see the problem.
0:000> ~
.  0  Id: 226c.2274 Suspend: -1 Teb: 000007ff`fffa2000 Unfrozen

When this memory dump was taken the native thread had already been cleaned up.

A KB article provided instructions on running an action when a process is orphaned.

Following those instructions I get a log file but no .dmp :(

I modify action.cmd changing %COMMAND% to %COMMAND% >> %LOG%

Now the log displays: 

Microsoft (R) Windows Debugger Version 6.11.0001.404 AMD64
Copyright (c) Microsoft Corporation. All rights reserved.

Cannot debug pid 8220, Win32 error 0n87
    "The parameter is incorrect."
Debuggee initialization failed, Win32 error 0n87
    "The parameter is incorrect."

Hmmm... maybe I can manually take a dump.

Using iisapp I see:

W3WP.exe PID: 11072   AppPoolId: ClientProject
W3WP.exe PID: 10824   AppPoolId: 3rdPartyVendor
W3WP.exe PID: 4836   AppPoolId: AnotherClientProject
W3WP.exe PID: 8220   AppPoolId: CRMAppPool

create problem.  wait 30 seconds:

C:\>"C:\Program Files\Debugging Tools for Windows (x64)\cdb.exe" -c ".dump /o /m
a c:\crash_PID_11072_3_03_2010_10_01_16_54.dmp;q" -p 11072

success!  Using this dump we were able to identify the problem.

Monday, January 24, 2011

Becoming a Better Listener

Today I received my first downvote on StackOverflow (a programmer question and answer site).  This means the downvoter said my answer sucked.  Fortunately they left a comment explaining why.  Immediately I thought "Hey! I'm right!" My answer is technically correct.  I think?.  I read the other two provided responses and noticed they both referenced a 50x50 Green square.  Mine did not.  Then I read the question again.  Oh, they want a green 50x50 square.  I didn't realize that!

I answered the question in as little time as possible without making a good attempt at understanding what they were trying to do.  I don't even know if my code really solves their problem because I copy and pasted code from my blog and put a warning on my answer "this worked two and a half years ago."  I told myself it was OK though because I put a smiley face at the end of the sentence to feel better about submitting an untested answer.

What happened after that?  Two people took time out of their day to improve the formatting and clarity of my answer and then a third person took time out to tell me why my answer wasn't good.  My answer did not provide value to the community.  Better answerers came along and posted more concise answers that directly solved the problem.  I had wasted community member's time.  I deleted my answer.

In the real world I do the same thing.  When people talk often times I have a response ready before they are done talking.  When someone criticizes me I often interrupt stating why I am right.  Listening is key to communication and learning.  I am working on being a better listener, and if you catch me not listening, help me out :)

Monday, January 17, 2011

Geeking out in Lansing

In 2008 I lived in Detroit and struggled to find like minded individuals to hang out with.  Individuals who code for fun and want to fix problems in their communities.  I ended up spending quite a few nights in Ann Arbor which has a similar tech scene to Lansing but a bit larger.  I enjoyed new events like CoffeeHouseCoders, Ann Arbor New Tech, and the TechBrewery.

I'm happy to report Lansing now has similar events so I can get all the goodness I was getting in Southeast MI right here at home.

The inaugural Lansing CoffeeHouseCoders meeting is 1/19/2011.  If you like to code in your free time in a social atmosphere, this is the place for you!

Hackers & Hustlers is a group focused on startup culture.  Attendees will hear entrepreneurs who are actually doing it give a talk or a pitch on their product.  The first meeting is 1/26.

In 2010 Lansing also got a coworking space, Second Gear.  More and more businesses are enabling their work force to work whenever and wherever they want.  For me often times that means I need to be somewhere for an evening event and I spend the day in a coffee shop.  That works OK, but I like to work near other programmers so I can learn from them and bounce ideas off of them.  Second Gear is meeting that need for the Lansing community.

Monday, January 10, 2011

Storing User Settings

I mentioned last week I want to store all settings for my application as user settings so I won't write to app.config and require administrative privileges.  I didn't like the constraints imposed by the .NET Settings implementation, such as configuring user settings at compile time and using attributes.  After implementing my own key value store implementation I'm realizing I may use the .NET settings provider for application settings, since I want it strongly typed, to have default values, and to have validation, and my property bag like implementation for storing settings application extenders write. For example Jane user writes a plugin and can persist settings in the user directory of my application.  This scenario doesn't work using LocalFileSettingsProvider.

Here is my initial key value store implementation:

using System.Configuration;
using System.Xml;
 
public sealed class DebuggerSettings
{
    public string this[string propertyName]
    {
        get
        {
            var store = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
            UserSettingsGroup values = (UserSettingsGroup)store.SectionGroups["userSettings"];
            if (values == null)
            {
                return null;
            }
            ClientSettingsSection myValues = (ClientSettingsSection)values.Sections[typeof(DebuggerSettings).FullName];
            if (myValues == null)
            {
                return null;
            }
            SettingElement setting = myValues.Settings.Get(propertyName);
            if (setting == null)
            {
                return null;
            }
            string returnValue = setting.Value.ValueXml.InnerText;
            return returnValue;
        }
        set
        {
            var store = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
            UserSettingsGroup addSectionGroup = (UserSettingsGroup)store.SectionGroups["userSettings"];
            if (addSectionGroup == null)
            {
                addSectionGroup = new UserSettingsGroup();
                store.SectionGroups.Add("userSettings",addSectionGroup);
            }
            string sectionName = (typeof(DebuggerSettings).FullName);
            ClientSettingsSection clientSettingsSection = (ClientSettingsSection)addSectionGroup.Sections[sectionName];
            if (clientSettingsSection == null)
            {
                clientSettingsSection = new ClientSettingsSection();
                clientSettingsSection.SectionInformation.AllowExeDefinition = ConfigurationAllowExeDefinition.MachineToLocalUser;
                addSectionGroup.Sections.Add(sectionName, clientSettingsSection);
            }
            SettingElement addMe = new SettingElement(propertyName, SettingsSerializeAs.String);
            XmlElement element = new XmlDocument().CreateElement("value");
            element.InnerText = value;
            addMe.Value.ValueXml = element;
            clientSettingsSection.Settings.Add(addMe);
                
            store.Save();
        }
    }
}

Monday, January 3, 2011

Implementing System.Configuration.SettingsProvider

I wanted to store all settings for an application as user settings so my app wouldn't writing to the app.config and require administrative privileges.  I struggled figuring out how the components in System.Configuration worked together, but luckily Reflector, Visual Studio's .NET Framework Source debugging, ProcessMonitor, MSDN articles, StackOverflow posts, and Code Project articles helped get my scenario working.

During this process I learned the SettingsProvider only handles retrieving and saving values to the datastore and how to implement one.  I didn't end up using it since the LocalFileSettingsProvider met my needs, but the code below is a good starting point for someone wanting to implement settings persistence in a different manner:

using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Diagnostics;
 
public sealed class CustomettingsProvider : SettingsProviderIApplicationSettingsProvider
{
    NameValueCollection settingValues = new NameValueCollection();
 
    public override void Initialize(string name, NameValueCollection config)
    {
        Debug.WriteLine("in initialize override");
        base.Initialize(this.ApplicationName, settingValues);
    }
 
    /// <summary>
    /// MSDN states this property should be implemented with this getter and a do nothing setter.
    /// </summary>
    public override string ApplicationName
    {
        get  {  return (System.Reflection.Assembly.GetExecutingAssembly().GetName().Name); }
        set { Debug.WriteLine("set application name called"); }
    }
 
    public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection)
    {
        SettingsPropertyValueCollection returnValue = new SettingsPropertyValueCollection();
        foreach (SettingsProperty item in collection)
        {
            SettingsPropertyValue addMe = new SettingsPropertyValue(item);
            addMe.PropertyValue = String.Empty;
            returnValue.Add(addMe);
        }
 
        return returnValue;
    }
 
    public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection)
    {
        Debug.WriteLine("in setPropertyValues");
 
        foreach (SettingsPropertyValue item in collection)
        {
            bool isUserScoped = (item.Property.Attributes[typeof(UserScopedSettingAttribute)] is UserScopedSettingAttribute);
            bool isAppScoped = (item.Property.Attributes[typeof(ApplicationScopedSettingAttribute)] is ApplicationScopedSettingAttribute);
            if (isUserScoped && isAppScoped)
            {
                throw new ConfigurationErrorsException("Property can't be userScoped and appScoped according to msdn: http://msdn.microsoft.com/en-us/library/system.configuration.settingsprovider(VS.80).aspx");
            }
        }
    }
 
    public SettingsPropertyValue GetPreviousVersion(SettingsContext context, SettingsProperty property)
    {
        Debug.WriteLine("in getPreviousVersion");
        throw new NotSupportedException("Get Previous Version is not supported");
    }
 
    public void Reset(SettingsContext context)
    {
        Debug.WriteLine("in Reset");
    }
 
    public void Upgrade(SettingsContext context, SettingsPropertyCollection properties)
    {
        Debug.WriteLine("in Upgrade");
    }
}

Monday, December 27, 2010

Quickly Testing and Changing Code

Sometimes when running software it is hard to make a particular code path execute.  Like if you want to ensure your code behaves correctly when bad data is passed to your function.  I love Visual Studio and the debugging capabilities are one of the things I love about it.  Using the watch window the values of variables can be changed to check those code paths, and by right clicking on a line one can set the next statement of execution wherever they want.

If we have code like this

int customerId = getCustomer("bob");
bool log = Settings.ShouldLog();
if(customerId < 0 && log)
{
    log.LogError("bob is invalid");
}

We can make the log code run by setting a breakpoint on the if line and then changing customerId to -1 and log to true in the watch window.  If we want to change the code in the if block and retest changing these values every time is repetitive.  Changing the breakpoint on the "if" to a conditional breakpoint allows additional code to execute when the breakpoint is evaluated.  We can leverage this feature to change the breakpoint condition to "customerId = -1."  Each time the breakpoint is evaluated customerId will be set to -1.  This is great, but in our example we have two variables which need to be set properly to satisfy the if condition.  To change both variables the conditional breakpoint can be changed to a lambda like this: () => { customerId == -1; log == false;};

I've found this technique can help me rapidly iterate on code changes to ensure edge case scenarios or hard to reproduce data scenarios execute properly for code that isn't under test.

Monday, December 20, 2010

How hard is it to change a column datatype?

One of our clients initially specified one of their columns as an int, and after being deployed for a month realized it needed to support other characters.  I found a couple of ways to do this in SQL Server 2008.

We'll use this sample table:

CREATE TABLE dbo.Orders
      (  OrderId int NOT NULL IDENTITY (1,1),
         OrderNumber int NOT NULL
      ) 
INSERT INTO Orders
      SELECT 234
     
SELECT * FROM Orders



The way I normally do things is by generating a change script in SQL Server Management Studio.  Here is the SQL output by that process.

CREATE TABLE dbo.Tmp_Orders
      (
      OrderId int NOT NULL IDENTITY (1, 1),
      OrderNumber varchar(50) NOT NULL
      )  ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_Orders SET (LOCK_ESCALATION = TABLE)
GO
SET IDENTITY_INSERT dbo.Tmp_Orders ON
GO
IF EXISTS(SELECT * FROM dbo.Orders)
       EXEC('INSERT INTO dbo.Tmp_Orders (OrderId, OrderNumber)
            SELECT OrderId, CONVERT(varchar(50), OrderNumber) FROM dbo.Orders WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT dbo.Tmp_Orders OFF
GO
DROP TABLE dbo.Orders
GO
EXECUTE sp_rename N'dbo.Tmp_Orders', N'Orders', 'OBJECT'
GO


I wasn't thrilled about copying the entire table for our whole dataset.  I thought the change script should create a new column, copy the data to it, remove the old column, and rename the new column to the old column's name.  Googling about for a way to do this I found it was even easier in SQL Server:


ALTER table dbo.Orders ALTER Column OrderNumber varchar(50)


It's a good old one liner :)

Monday, December 13, 2010

Oh how I love Visual Studio

Over the past month I've been working with a lot of JavaScript and I was really missing these features from Visual Studio:

  1. No find in solution - I was actually opening up Visual Studio and using the find feature to search my JavaScript directory structure to find things.
  2. No solution explorer - I had to keep switching over to Windows Explorer to see the files I wanted to open.
  3. No AhnkSVN - I love having source control integrated, so I don't have to worry about adding files, ignoring files, etc.
I found out I can get all my Visual Studio love by creating a web project at the root of my JavaScript Solution.  It gave me back all the features I missed without any problems.

Huzzah!