Wednesday, September 5, 2012

2 small things


It’s been a busy month or so, so I’m behind on the blog.

For now, I’ll just toss 2 small things.
First is an observation about life in IT:

“You don’t have to run faster than the mountain lion. You just need to run faster that the person next to you.”

That actually happened this week. My group was on a project with a silly-tight deadline. This was one of those things where the management had promised a target date a year ago, then sat on the project. In February, they started to hammer out the requirements.  On the last week of August, they produced a one-page requirements doc (no, really!) with hand-drawn scribbles all over it, since it had been changed just a few minutes before the IT handover. It necessitated the change of almost every software system my group controls. We were given 4 weeks – less 2 weeks testing time.

This week, one of the other teams got eaten by the mountain lion and admitted they couldn’t make the date. We implemented nothing, but look like heroes.


The 2nd thing is a link to an article I thought was interesting. The OP-ED author ventures his opinion that it’s time to drop Java. His reasons are actually somewhat compelling, I think, although I’m not sure I totally agree with the conclusion and suspect there are other options. At least, I thought the piece was worth a read. Note that he’s specifically talking about Java on the clients, not on the servers.


Thanks for playing.
--kevin

Wednesday, August 8, 2012

The top 10 most interesting things about Microsoft Store’s developer agreement or “It’s good to be the king”


I was going to post about custom objects in DataTables today. But I ran across this and needed to comment (cuz, you know… I can’t help myself).

For disclosure, the whole thing is here:

So here are my top 10 most interesting points from the Microsoft Store Developer Agreement.  
(or the top 10 reasons “it’s good to be the king”):

1.      1.  Microsoft plans to charge for the account, regardless of whether I put up any apps.
This was from my email and re-stated on the sign up page:
Developer accounts are a one-time 12 month benefit. Registration and promo codes are non-transferable
and from the agreement:
“YOU CAN RECOVER …YOUR ACCOUNT FEE” (point #8 below….and *that* one is a doosie).

They don’t say how much. I suspect they don’t know yet.

2.       2. Microsoft will limit what you can download based on your manufacturer and/or cell phone provider.
 “If your app is designated as preinstallable by an OEM or other channel partner, or "channel exclusive”…

This confirms what everyone suspected: if you buy a Microsoft Surface branded by Borders, you’ll get content specific to Borders. In other words, don’t expect to by a Borders Surface and download a Kindle app. This is essential for Microsoft and Borders. But a little disappointing for the consumer. There was a day when I got to choose which applications I installed on my computer, but don’t expect that to continue.

3.       3. You give up a bunch of rights to Microsoft
“You grant to Microsoft the worldwide right to: host, install, use, reproduce, format, make available to customers …, and sign the app (including by removing preexisting signatures)…. [and] to publicly perform and display, duplicate and demonstrate your app, pieces of your app, or associated Marks and materials…”

Again, this isn’t unusual. They have to be able to reproduce the app to sell it.
But a couple things caught my eye. First, they can remove my digital signatures and put in their own. That’s really kinda scary.

Second, they get the right to “use” the app for free. I used to work at Micro Center computer retail stores. When we wanted to use one of Microsoft’s apps, we had to pay them for it. Just because we sold it, didn’t give us the right to install it on our computers and use it. But this sounds like Microsoft is demanding that.

And third, they get the rights to all my materials for their marketing. On the one hand, that’s required. They can’t show my app’s icon on their store if they don’t have rights to it. On the other hand, it’s a little disconcerting if they plan on using my app to sell their product, then don’t even pay me for that. Technically, by that argument, they could come out with a Facebook branded Surface if Facebook submitted even one app. I’m sure they won’t do that to Facebook, but for the small developer, things like icons and fonts and images matter.

Also, make a mental note of this; I’ll come back to it.

4.      4. Microsoft removes the idea of individual licenses.
“Your Metro style app must be licensed and technically enabled to support "roaming." Roaming is a Windows 8 feature that enables users to use your app on up to 5 Windows 8 enabled devices at any one time”

As a consumer, my thought is “it’s about *time*.” It’s always been annoying to me that I can listen to the same audio CD in my car or in my home but if I want to install an app on my desktop and laptop, I’m “supposed” to buy two copies.
As a developer, though, this bugs me. There are a million companies that have “seat licensing” based on one individual user. Who are they to tell me that I can’t do it? For the small developer, this may kill some of their apps. If I have 2,000 users, but only sell 500 copies, that extra support burden and loss of revenue could really nail me.

5.       5. Microsoft wants money… and likes BIG developers.
“[T]he percentage of Net Receipts that is retained by Microsoft as a fee …is 30%, unless and until your app takes in total Net Receipts of USD$25,000, after which time the percentage is 20% for that app….”

First of all… so much for encouraging the small developer. Out of the gate, small shops have to fork over an additional 10% of their profit. You’ll hear a lot about how the Windows Store will foster growth in the small developer community, but they don’t seem to want to support that if it costs them anything.

 Also, note that the fee is based on Net Receipts not net revenue. That’s understandable (and probably the only way they could do it), but that means I have to raise my prices by 30% out of the gate just to cover my distribution costs. There was a time when people said that the internet would remove distribution expenses, making software cheaper, but this goes the other way.

Also, make a mental note of this; I’ll come back to this, too.

6.       6. Taxes & Fees
Most of the tax and fee stuff is pretty standard. Microsoft will charge normal sales taxes from its store. You’re responsible for anything else. So if your state has a regulation that charges extra tax on your software, it’s all on you. But Microsoft will collect and process the normal sales tax.

The only concerning thing is that they take it out of the total revenue they collect. From what I can tell, a $10 app won’t charge the consumer $10.60 to cover the 60 cent sales tax, but $10. Microsoft will take $3 for its fee. Then take $.60 for the tax, leaving the developer $7.40. Not a huge deal, but again, the developers will need to inflate their prices to account for it.

7.       7. Microsoft keeps its fee, even if I don’t.
“You are responsible for all costs and expenses for returns and chargebacks of your app, including the full refund and chargeback amounts paid or credited to customers”

So the developer does the refund not Microsoft. That makes sense. But there’s never anything mentioned about Microsoft refunding the developer for the store fee for that sale. In other words, someone downloads an app for $10. MS takes its $3 and takes another $.60 for taxes, giving the developer $7.40. But when the customer wants a refund, the developer has to do it. Microsoft keeps the $3 and doesn’t back out the taxes. The developer can either charge a fee to the consumer or (more likely) be expected to eat the cost.

I’d expect two things: first, the refunds of apps will get ugly, expensive and difficult. And second, Microsoft will change this to mandate a full refund for the customer processed through its store, but still will keep its $3. I think forcing the customers to deal with each individual vendor for the refund will just be a looser for Microsoft, but it will still want to recoup the cost it incurs.

The practical side of this, though, is that Microsoft has no reason to de-emphasize sucky apps. Most sales reps are commissioned based on sales minus refunds. Microsoft keeps its pound of flesh either way. So it will be tempted to market the things that sell, even if those things take massive amounts of returns.
.
8.       8. It’s good to be the King.
“YOU CAN RECOVER FROM MICROSOFT…ONLY DIRECT DAMAGES UP TO AN AMOUNT EQUAL TO YOUR ACCOUNT FEE ... YOU AGREE NOT TO SEEK AND WAIVE ANY RIGHT TO RECOVER ANY OTHER LOSSES OR DAMAGES, INCLUDING …LOST PROFITS…PUNITIVE OR INCIDENTAL DAMAGES… THESE LIMITS AND EXCLUSIONS APPLY EVEN IF MICROSOFT KNEW OR SHOULD HAVE KNOWN ABOUT THE POSSIBILITY OF THE DAMAGES. “

Translation: “It’s good to be the King. “
So, if I write an app to give you behind the scenes access to the Olympics and I sell my house to buy a 30-second add on NBC right at the start of the opening ceremonies, and Microsoft’s store goes down an hour before for a planned, but unannounced, 8 hour down time… I’m just… homeless.

And if they come back online and accidently (or on  purpose) remove my app… well, too bad. Thanks for playing.

Oh, wait, I can get my monthly account fee back from Microsoft (they say they’ll give me $1 if I got the account for free) so I’m good.
Who wouldn’t love this agreement? AND what’s really cool? There’s *NO MENTION OF SERVICE LEVEL AGREEMENTS* in the whole thing! The idea that I can’t sue them for loss of profits, even if it’s their fault , would actually be ok, if they gave me a service level agreement of 99.999% with some financial re-imbursement if they don’t.

Remember this one too for later, too.


9.       9. It’s really, really good to be the King
“You will defend … and hold harmless Microsoft …from and against …any and all third party claims: … relating to the use of or inability to use the app, including any product liability claims; or … by any tax authority based on any nonpayment or underpayment of any sales”
This is normal, really. They’re basically saying “hey, we’re just the retail store, not the manufacturer”.
Sure, it’s a small issue that they want you to defend against tax claims when they collect the standard taxes, but, realistically, they’ll do what they need to do to stay out of trouble with the IRS or state tax agencies, so that’s not much of a deal.
But here’s the cool part. Remember points 4, 5 and 8 above? Basically, Microsoft gets to use and distribute my software (or not, at their choice). They get my logos for their ads without having to pay for them. They get the 30% fee that they don’t have to refund. And they get a “get out of jail free” card on any outages or mistakes that cost you money. And they get complete immunity from prosecution.
This is a blank check. Microsoft can screw up as much as they like and cost you as much as they want, but still use your logos and keep your fees.

1    10.   Welcome to the future, but don’t worry, this won’t impact desktops … unless it does.
“You may submit an app description for one or more desktop apps to the …Windows Store. Notwithstanding anything else in this agreement, you understand that Microsoft will not offer any desktop apps through the Store and only Metro style apps are made available through the Windows Store.

So, don’t worry. This is just for notepads, and isn’t anything different than what Apple does.

Only…that’s not quite accurate.

The same ARM-type processors that are powering phones and tablets are now powerful enough to power ultra-books and laptops. If you’re bored and don’t believe me, you can see what PC World says:

Face it, the x86 architecture is on the way out for consumers. In 5-10 years, the majority of home computers won’t be desktops, but laptops and ultras and notepads. And most of these will probably have ARM-based chips in them. Under Microsoft’s definition, anything with an ARM chip won’t run “desktop” Windows 8, only Metro. Of course, they may have to revisit that (I think they will), but who knows? It’s up to them. For right now, if you pick up an ARM-based device, you’ll be desktop-less.

And that means that all apps will need to move to Metro (which is MS’ stated plan, of course), which means that all apps will need to follow this model. Sure, there will be exceptions made for large companies who want to work around the process. But for the small or medium sized shop… not so much.

Some people are really worried about this. Windows Store will be direct competition to Valve’s Steam service. And their CIO is a bit grumpy about that:

In the short term, I think one of the things that will happen is that small-shop developers will be less than enthusiastic to develop Metro apps. Even big shops seem pretty hesitant. Microsoft has been paying companies to develop Windows phone software for quite a while now:

Hey, this is great for Pandora and Instagram, but smaller shops just don’t get any of the love. I’m wondering what happens to companies like Stardock. They make some great software and games (when I saw Window Blinds for the first time, I had a geek-drool moment). But I don’t think they can get MS to fund their apps. Nor do I think they will be willing to sign off to put their apps in Windows Store. Right now, they don’t make any Metro apps, but, again, if ARM makes it into the ultra-book market, they may have to re-think that.

Steam is betting on desktop Linux. I’m not sure that’s a great idea, but then….maybe. Desktop Linux has finally matured enough that the average user can install Ubuntu without issue. And, if they get Steam’s support, they’d get a host of apps they could add to their stack. Moreover, the desktop OS is becoming less and less important. Chrome/Android? Mac? Linux? Windows? WebOS? Who cares? I can get my email and watch Netflix on any of them.



Meanwhile… I want to be a king, too.
--kevin










Friday, July 27, 2012

MS Sql and my pain.



SQL Server has some really nice features. It’s best isn’t even really a part of the core database; it’s the Management Studio used to access it. If MS Sql is the only thing you’ve ever used, you’re spoiled. If you’ve never used MSSQL, you don’t know what you’re missing. It really does provide great tools for scripting data constructs, exporting and importing data, database profiling, etc.

But it always annoys me what is missing from MS tools and how we’re told we don’t really want it anyway. In SQL, it’s the “group by”. Suppose you have a set of sales records in your database. You want to find any that don’t have master account records (because something failed) and add the account record, so you won’t have dangling transactions. (Looking at the dangling transactions, dangling participles seem harmless.)

Now, I know… I know. You should have a database constraint that creates a foreign key between the sales table and the accounts table so this can never happen. But, the world should be at peace too. You can’t always control those things.

So you sit down to write the query: “select account_number from sales where [it doesn’t exist in accounts] [then insert it]“. And you realize that there can be multiple sales on that account, but account number is unique in the accounts table. So all you want to do is de-dupe a little.

So far this isn’t too bad. Until you realize that “Customer_Name” is in both sales and account. From a pure normalization perspective, maybe that doesn’t make sense, but it actually does make some sense from a practical  view, since not all the sales on the account may be done by the same person. And the world still isn’t at peace, so you shrug it off and move on.

But how do you do it? You need one of the names from sales to put into the account. Frankly, which one doesn’t really matter. So you try the obvious:

Select account_number, Customer_Name from sales group by account_number.

This works in MySql. It gives one row per account number with a somewhat randomly chosen name. In SQL Server, it throws a compile error and complains that the Customer_Name needs to be part of the group by.

Easy to fix.
Select account_number, Customer_Name from sales group by account_number, Customer_name, right?

No. Now it will give you duplicate account numbers, if there are multiples sales with different names.

After a week of cussing, you end up coming up with a solution, but it’s ugly. It will involve inner selects, MAX/MINs (which won’t work the way you’d think because you’ll have to be concerned with NULLS and the like) or getting the row id with a “Partition Over”. It’s all ugly. It gets worse when you have a combined key, so “account_number” alone isn’t unique, but it’s account_number + store_id + district_code + random_silly_grouping_value.

If you ask MS (or one of their fanbois) they'll tell you that you don't really want to do that. I love it when they say that. They'll say "you don't want that because you can't guarantee which Customer_Name you're getting." When you say you don't care, they'll tell you that the database is mis-designed then. OK... and the world is not at peace. I usually want to give them my boss' number and have them explain how he doesn't really want what he wants, and if he does, he needs to shell out a few million $$ to re-design the data.

It’s the kind of thing that drives me nuts about Microsoft. Doing simple things is so easy. Doing complex things is  easy too. But varying off the path – easy or hard – is so painful.

If you don't believe me, try this: Go to Management Studio and right click on a database and run the wizard to script all the objects in the database. Now, try to do the same thing from a command line, so you can actually.... you know, schedule it. Turns out to be impossible (without rolling your own tool).
Getting up at 3am each night to script things is on the path. Automating it is off.

And the world is not at peace.
--kevin

Wednesday, July 18, 2012

Microsoft and the courts

According to the news from Reuters, the EU is investigating whether Microsoft is in violation of anti-trust rules for blocking non-MS browsers from having fill access to the Windows8 API.

http://in.reuters.com/article/2012/07/18/eu-microsoft-browser-idINL6E8IIALJ20120718

 Here’s a prediction.
Microsoft will say, basically, “It doesn’t matter, we’re not a monopoly anymore.”

To prove that, they’re argue that Windows8 is not a PC operating system, but an OS for PC’s, phones, Xboxes, notepads and greeting cards that play music when you open them. Since, they will say, Microsoft is getting walloped in non-PC devices, they don’t count as a monopoly. It’s analogous, they will say, to saying that Toyota has a monopoly on cars because it sells more hybrids. The PC, they will argue, is only one part of the target market for Windows8, in the same way that the Prius is only one target for windshields.

 Microsoft has a lot of reasons to push Windows8. They seriously have fallen behind in their business strategy. But one of the key reasons, I’m guessing, is that by creating a “one OS to rule them all” platform, they create a legal hole to crawl into.

 For years, they’ve been a monopoly (as defined by law, anyway) and they’ve made a zillion dollars. But they’ve also paid billions in fines for breaking anti-trust laws. If they can convince the courts that Windows8 combines markets the way Toyota combines car styles, they can still keep their current markets and profits without the annoying billions of dollars in fines they face all the time. To them, it must seem like a huge win.

Have your cake + eat it = no more anti-trust.

Personally, I think their argument is actually decent and the courts may go for it. I also think we’ll see more restrictions and modifications to Windows8 to make it better fit the model and support the legal argument. I think that’s actually their hidden reason for forcing PC users to use the Metro start screen. And to that end, ultra-books are a Godsend for Redmond. With them, they get to launch the same ARM-based Windows8 they plan to put on notepad and say “see? A laptop is just a glorified notepad. Since we’re not a monopoly in notepads, we’re not one in notebooks either.”

Will be interesting following what happens in the European courts.

 --kevin

Wednesday, July 11, 2012

Distinct on custom objects in datatables and lists

I use this blog a lot to make notes for myself so that I don’t … umm… what’s the word?

Anyway, here’s some of the latest notes that caused me a research headache. Maybe it will save you a headache, or maybe I’ll remember to look here the next time my headache starts.

Suppose you have a data table in C#.
Let’s say it has a date time and a custom object (type = “myclass”).
The “myclass” thing is simple – it’s just a class with one property “v” which is a DateTime (I’ll plug that in later) and the code to set up and load the table is here:

DataTable dt = new DataTable("sometable"); 
DataColumn dc = new DataColumn("someDate", typeof(DateTime));
 dt.Columns.Add(dc);
 dt.Columns.Add(new DataColumn("someObj", typeof(myclass))); 
List l = new List(); for (int i=0;i<10; i++) 
    DataRow dr = dt.NewRow();
    dr[0] = DateTime.Now; 
    myclass m = new myclass();
    m.v = DateTime.Now.ToString();
    dr[1] = m;
    dt.Rows.Add(dr); l.Add(m); 

So we end up with a table with two columns: one is a DateTime and the other is a myclass. Conceptually, the DateTime and the myclass objects are about the same thing.
You head shouldn’t hurt yet. If it does, maybe you should stop now. But get the aspirin ready:
var n = (from p in dt.AsEnumerable() select p["someDate"]).Distinct();
This is good. Walk through a foreach on n and it gives one instance for every unique date. In theory, each value in the table is distinct because it’s a DateTime and the loop iteration takes a fraction of a second. In practice, the code is so fast, that the runtime engine eats the fraction of a second, and you’ll get one unique entry in n, so your foreach will have one loop iteration. My head is still pain free. Until I do this:
var n = (from p in dt.AsEnumerable() select p["someObj"]).Distinct();
Now the “Distinct” acts on the custom objects and you get 10 items in n. The headache is small, though, because I get that .Net doesn’t know how to compare my custom objects. So it can’t distinct them. MSDN says that myclass needs to implement IEquatable. There are some examples out there that seem to work.
For simplicity, let me the load 10 custom objects into a List, rather than a data table, and I’ll modify myclass to implement IEquatable.
public class myclass: IEquatable

public object v;
public override string ToString()
{
return v.ToString();
}
public override int GetHashCode()
{
return v.GetHashCode();
}
public bool Equals(myclass other)
{
return true;
}
}

I already snuck the List into the code above, so I can use it (cuz I’m sneaky like that).

So I can do:
var lc = (from pp in l
select pp).Distinct();

And this is *supposed* to call the “GetHashCode()” on the custom objects to do the distinct…. But it doesn’t. If you loop through lc, it will give you 10 iterations.

The good news is that I can add a IEqualityComparer to the mix:
class TheComparer:IEqualityComparer
{
public bool Equals(myclass x, myclass y)
{
return true;
}
public int GetHashCode(myclass m)
{
return m.v.GetHashCode();
}
}

Now if I set the EqalityComparer to the Distinct() on the list, it seems to work: TheComparer c = new TheComparer();

var lc = (from pp in l
select pp).Distinct(c);

Yay! So I should be able to apply the same EqualityComarer to the data table’s Distinct() and it should work, right? var mmm = (from p in dt.AsEnumerable() select p["someObj"] ).Distinct(c);

Nope. Not only doesn’t this work, it gives a *compile error*. This is where I got into some really serious aspirin. Turns out that this statement returns a result of IEnumerable, while the previous one returns IEnumerable. They’re both generics that implement IEnumerable, so they support the same methods, right? Not exactly.

The EqualityComparer has to be type cast. If you look at the definition, it is bound to a type. So, even though a DateTime is an object, creating an EqualityComparer with an object type GenericComparer:IEqualityComparer And then trying to use it on a Distinct() for a List will throw a compiler error.

Took me around a day to figure all this out and the solution. The solution is to type cast the Linq:

var mm = ((IEnumerable)(from p in dt.AsEnumerable()
select p["someObj"] as myclass)).Distinct(c);

Note that the only real difference between this and the code above is that I typecast IEnumberable with my custom object. But now, I don’t get a compiler error. Also note that this will not compile unless I also typecast the select.
*NOW* the Distinct will correctly accept and use the EqualityComparer and it can call the Equatable methods on the incoming objects to do the compare.

So far, this is the only way I’ve found to do a Distinct() on a DataTable with custom objects. Microsoft’s internal DataTable (non-Linq) methods don’t like custom objects at all. In fact, they pretty much ignore them.

Next time I’ll probably have a section on how to use custom object in data tables and bind to databound grids dynamically.

--kevin

Thursday, June 14, 2012

The biggest news from Apple.

I’m not an Apple fan-boy exactly, but I do respect the company and am constantly impressed by them. I’ve learned never to bet against them, especially in my stock portfolio.
So I’ve been keeping an eye on the latest news from their developer’s conference, and I think one story has been under-told.

This one.

Auto week reported this. For the most part, the mainstream media (and even the tech community) has been ignoring it.

Let me summarize, to save you the time of reading: Apple has agreements to put Siri in the cars made by these auto makers: BMW, GM, Mercedes, Jaguar, Audi, Toyota, Chrysler and Honda.

Ford already has a tight relationship for voice control software with Microsoft. Besides Ford, Apple gets…um… everyone else? OK, Hyundai and Ferrari aren’t in the list, but come on, everyone else is.

This is a big fat hairy deal for Apple. And a big, fat, hairy coup. Microsoft was really the first one to do this. They pioneered the trail and owned the market with Ford. And then Apple just stole it from them – not one or two other potential clients – but *all* the rest. I mean, what were the MS sales guys doing while Apple was pitching this? Were they off trying to flirt with Siri?

I think it’s a big, fat, hairy hit for Microsoft. OK, it’s a small hit for Google, too, but Google is only loosing what it never really had – not being a real player in this market anyway. But Microsoft… man… talk about shutting down an entire part of the business! Sure, they’ll hang onto Ford for a while, but how long before Apple gets that? How long before someone wants the same voice system in their Lincoln that their friends have in the Beemers? And even if they keep Ford, the growth potential of the market is gone .

And think about what this means for Apple. While all the world has been cursing or praising Windows 8 and MS is paddling hard to catch up in the ARM space (or is it ARMs race?), Apple flanked them big. Think about it. Think about what happens if you get used to Siri in your car giving you directions to a new Sushi place. That means extra revenue for Apple. It means add dollars from the Sushi place. It means integration with Apple’s new maps (take *that* Google). It means integration with Facebook and Open Table (they announced that too, by the way) so you can see if your friends liked the Sushi place and make a Siri-based reservation on the way. And it means a new reliance on Siri. So, if you are on a trip and you rent with Hertz, you’ll want Siri. If you are at home and you’re wondering where to grab dinner, you‘ll want Siri. It means getting people so used to the service that they’ll look for it everywhere.

And what amazes me, again, is that Microsoft invented the market, but just didn’t have the ability to capitalize on it. Microsoft is the true innovator here (something they claim to do more than they really do). But – most likely—Apple is the true winner.

Now, I wish I wouldn’t have sold that Apple stock…..
--kevin

Monday, June 4, 2012

Debugging tricks

I was sitting with someone the other day and watching him debug an application and it made me want to post a couple tricks with the debugger that can help. 

first: learn some of the simple shortcuts. F5 starts the app with debugging ctrl+F5 starts it without. I was surprised by the fact that he took his hands off the keyboard to look for the mouse so that he could click the little icon on the toolbar every time he wanted to run something.

F9 sets (and clears) breakpoints – this is probably the handiest thing--  and F11 will “step into” a method, while F10 will step over it.
Those are the basics.

In addition, you can go to view->other windows->command window in Studio and have access to all the debugger info (and then some). A couple of the most useful things are:

        “Debug.DisableAllBreakpoints” and “Debug.EnableAllBreakpoints”. These alone are so useful, it’s scary. On any complex application, you know, the one that you’ve been working on for the last 3 days without coming up for air, you’ve got lots of steps to do before you get to the “good stuff”. Once you do actions X + Y, you want to step through loop Z to see what it’s doing. But you don’t want to step through Z until you’ve done X and Y. So you can end up stepping through lots of code that you really don’t care about. But if you disable all breakpoints, then run, do X and Y, then Enable all breakpoints, you will fly right past your breakpoints until you need them. Very cool.



      typing ? followed by a variable (there needs to be a space between the ? and the variable name) will print the contents of the variable. This is basically the same as hovering over the variable with your mouse or doing a quick watch, but typing it is easier when you’re looking for someArray[i].someObject.someProperty . I’ve seen lots of people spend all day trying to “drill down” in hover over without clicking on the wrong thing and making it vanish. I do it too, but the debug command is way easier. 

 
      Also, remember conditional breakpoints. When you set a break point, you can right click on it and select “condition”. This will open a dialog that will allow you to enter whatever you like and stop only when the condition is true. So, you can break on the 321st iteration of the loop without having to step through the first 320. 

.  Hope this all helps. Please list some of your favorites below. 
-    --kevin

Friday, June 1, 2012

Extension methods



Yay! I finally have an excuse to use extension methods.
First, a brief explanation of what they are. Suppose you have an object – say a string. And you want to add some functionality to it. You could subclass the object (assuming it’s not sealed) and add your new method.

But if all you want to do is add one tiny little method, subclassing seems a bit top-heavy, doesn’t it? Besides, unless you’re using an object factory pattern (my favorite design pattern, by the way), you face the prospect of finding and changing every object instantiation in every line of code of your project to replace the parent with the child class. On large, multiple developer projects, this gets rough.

Microsoft gives you a work around. What you can do is to add a special static method somewhere in your code and .Net will automagically assign this to the desired class.

For example,
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ''.''?' },
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
The magic is the keyword “this” in the method signature. “This” tells the compiler that “WordCount” is an extension method on the string object.
The end result is that your code can now do something like:

       string x = "this is a test string";
       Console.WriteLine(x.WordCount());

And the Console will show the word count of x, just as if “WordCount” was a public method on the string class.

I’ve thought this was cool for a long time, but couldn’t find a use for it.

But, Dmytrii Nagirniak posted a reply to a thread on Stack Overflow that provides an awesome use:

http://stackoverflow.com/questions/1725903/determine-if-datacolumn-is-numeric

To sum it up, .Net has no “IsNumber()” method. So looking at a potential data value, it’s really hard to know if it’s a number type. What you end up with, is a complex if statement that does a GetType(), but then has to check to see if the type is a Double OR a Single OR an Int32 OR an Int64 OR a UInt16 OR…. Etc.

Putting this into an extension method makes a ton of sense. (I’m not sure why Microsoft didn’t already do this, frankly). This means that developers don’t need to deal with this mess each time, but just have to call
x.IsNumber().

The code for the extension just looks like this:
  public static Type[] numericTypes = new[] { typeof(Byte), typeof(Decimal), typeof(Double),
        typeof(Int16), typeof(Int32), typeof(Int64), typeof(SByte),
        typeof(Single), typeof(UInt16), typeof(UInt32), typeof(UInt64)};
 
 public static bool IsNumber(this object x)
    {
        if (x == null)
            return false;
      
        return numericTypes.Contains(x.GetType() );
    }

And this allows  you to instantiate any object and define whether the object is a number type.

A second (useful) variation of this examines whether a DataColumn (ie, in a DataTable) is a number type. It’s different because the DataColumn.GetType() would just return “DataColumn, you moron”, so you have to look at “DataColumn.DataType” :
  public static bool IsNumeric(this DataColumn col)
    {
        if (col == null)
            return false;
        return numericTypes.Contains(col.DataType);
    }


Pretty cool stuff.
--kevin