Clearing the ClickOnce App Cache

I had a user complain that they were unable to launch an application that was published using ClickOnce. They were kind enough to pass along a log file that the error message provided making finding the issue very easy. The log file contained the following error:

Following errors were detected during this operation.
 * [6/7/2010 10:54:17 AM] System.Deployment.Application.DeploymentException (Subscription)
  - Unable to install this application because an application with the same identity 
    is already installed. To install this application, either modify the manifest version
    for this application or uninstall the preexisting application.
  - Source: System.Deployment

I took this to mean that the user needed to remove the currently installed version of the application, and remove it. However, the application must be launched from the deployment page, and cannot be installed local. So how do you clear this cache for ClickOnce deployed applications? Easy, Google knows. I just needed to use a simple command line tool mage.exe (Manifest Generation and Editing Tool). For me it was found in /Program Files/Microsoft Sdks/Windows/v7.0A/bin. Calling the tool like this mage -cc cleared the cache. However, on a machine for non developers, this was not an option, as they don't have the Sdks on their machines. So, I needed an alternative.

A little more Google-fu resulted in an alternate call that would do the same thing on a computer without development sdks. And I know some day I'll need to remember this, so here it is: rundll32 dfshim CleanOnlineAppCache

  
VB.NET Gotchas for C# Devs

I have been coding in VB.NET on contract for just under a year now. And having done so, I have come up with a small list of 'Gotchas' that I have encountered. At times, these differences have cost me quite a bit of time in debugging, and if I can save someone else even a small amount of this pain, it will be worth it.

VB.NET does not throw a compiler error when you create a function without a return type. Can you tell me the return type of the method below?

    Public Function GetNumberOne()
        Dim num As Integer = 1
        Return num
    End Function

VB.NET is also content compiling a Function without a return statement. It isn't frequent that I forget to add a return statement, but it has happened.

    Public Function WithoutReturnStatement() As Integer
        Dim bool = False
        Dim s = "A String"
        Dim concat = String.Concat(s, bool)
 
    End Function

Another good idea: turn on Option Strict. If you don't, the runtime will attempt to do a lot of implicit conversions for you. I wrote some code where I thought that I could call GetBoolean() on a DataReader passing in a string representing the column name. It compiled fine. After running the application, I realized that I needed to pass in the columns index instead. Sure, if I would have slowed down, Intellisense would have told me different, but I was cocky

    Public Sub TakesNumberParam(ByVal value As Integer)
        Dim result = value + 1
    End Sub

Without option explicit on, I am able to write a test for the above method, that passes in a string that cannot be cast to an integer, and the project builds. At runtime, the code will throw an InvalidCastException.

    
Wholesale Linqification, everything must be Linqified

I have been browsing through the source for the Subtext Blog Engine, and have come across a lot of cool ideas, and also, a lot of code that is showing its age. Subtext has been around for a long time, and in some places, the code could use some updating. Of course, the contributors to the project are probably not going to find a need to go through every line of code and modernize it, but it's hard not to see places where Linq can really make things more awesome. For instance, there are a handful of methods that try to determine what kind of request is being made, and specify a RequestLocation based on that. One of the methods that tests for a request to a static file looks like this:

private static bool IsStaticFileRequest(HttpRequestBase request)

{

    string filePath = request.FilePath;

 

    return filePath.EndsWith(".css", StringComparison.OrdinalIgnoreCase)

           || filePath.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase)

           || filePath.EndsWith(".js", StringComparison.OrdinalIgnoreCase)

           || filePath.EndsWith(".gif", StringComparison.OrdinalIgnoreCase)

           || filePath.EndsWith(".png", StringComparison.OrdinalIgnoreCase)

           || filePath.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)

           || filePath.EndsWith(".txt", StringComparison.OrdinalIgnoreCase)

           || filePath.EndsWith(".html", StringComparison.OrdinalIgnoreCase)

           || filePath.EndsWith(".htm", StringComparison.OrdinalIgnoreCase)

           || filePath.Contains("/images/", StringComparison.OrdinalIgnoreCase);

}

However, this can be made much more awesome with Linq. Behold the More Awesome:

private static bool IsStaticFileRequest(HttpRequestBase request)

{

    string filePath = request.FilePath;

    var extensions = new[]

        { ".css", ".jpg", ".js", ".gif", ".png",

          ".xml", ".txt", ".html", ".htm", "/images/" };

 

    return extensions.Any(e => filePath.EndsWith(e, StringComparison.OrdinalIgnoreCase));

}

I hope I never have to go back to .NET 2.0; I will most certainly weep heavily.

  
Careful Letting Your Objects Expose Themselves

I have been working on a project recently where many classes have collections (specifically Lists) of related information contained within them, but expose the full functionality of the list to consumers of the class. The issue with this, is that any consuming class has to be aware of any rules or restrictions that need to be applied to the child elements before adding to the collection. It also makes it more difficult for the class to validate the items being put into the collection and ensure that they are valid.

As an example, consider a pile of cards used in a card game.

public class CardPile

{

    public CardPile()

    {

        Cards = new List<Card>();

    }

 

    public List<Card> Cards { get; private set; }

}

In this scenario, I can add, insert, remove, or clear the entire pile of cards. Maybe that is exactly the scenario you want, but usually there are rules associated with adding or removing cards from a pile. Consider a game like Solitare. In order to play a card, the face value needs to be 1 lower than the previous card in the pile, and of the opposite color. So, anywhere I want to add a card to the pile, I need logic like this:

var addCard = false;

var last = cardPile.Cards.LastOrDefault();

 

if (last != null && last.FaceValue - card.FaceValue == 1

    && last.Color != card.Color) addCard = true;

 

if (last == null && card.FaceValue == FaceValue.King) addCard = true;

 

if (!addCard) return;

 

cardPile.Cards.Add(card);

It's all about Tell don't Ask here. We have to ask the CardPile about the last card, and do a lot of checking before we can add the card. I don't want to deal with all of that. I just want to tell the CardPile, here is a card, I am adding it to you. Then the CardPile can take it, or tell me to buzz off. The CardPile knows best. I really want to have an AddCard() method here that encapsulates the logic above. The result is less code duplication, and good encapsulation.

At this point you might have a red flag. In our example of Solitare, we need to have two types of card piles. The lower staging piles build downwards from King to Ace while alternating colors. The top home piles count up from Ace to King and must have the same suit throughout. The CardPile class is a very basic class that should be able to function for any CardPile needed by a game. So, for this example, it does make sense to just expose the List, and place the logic outside of the class. Right?! Wrong, I don't want to create repeated validation logic around when a card can and can not be added to a pile, and I don't want different CardPile classes for each implementation of AddCard(). The best solution in my mind is to use the Strategy pattern, and encapsulate the card adding validation logic into a CardPilePolicy class.

public interface ICardPilePolicy

{

    bool CanAdd(Card card, CardPile pile);

}

 

Now that I have the policy class, I need to implement the validation logic for my two types of card piles, the play area, and the home row.

public class PlayFieldPilePolicy: ICardPilePolicy

{

    public bool CanAdd(Card card, CardPile pile)

    {

        var addCard = false;

        var last = pile.Cards.LastOrDefault();

 

        if (last != null && last.FaceValue - card.FaceValue == 1

            && last.Color != card.Color) addCard = true;

 

        if (last == null && card.FaceValue == FaceValue.King) addCard = true;

 

        return addCard;

    }

}

 

public class HomePilePolicy: ICardPilePolicy

{

    public bool CanAdd(Card card, CardPile pile)

    {

        var addCard = false;

        var last = pile.Cards.LastOrDefault();

 

        if (last != null && card.FaceValue - last.FaceValue == 1

            && last.Suit == card.Suit) addCard = true;

 

        if (last == null && card.FaceValue == FaceValue.Ace) addCard = true;

 

        return addCard;

    }

}

Now let's look at what the new CardPile class would look like.

public class CardPile

{

    private readonly List<Card> _cards;

 

    public CardPile(ICardPilePolicy policy): this(policy, null) {}

 

    public CardPile(ICardPilePolicy policy, IEnumerable<Card> initalCards)

    {

        Policy = policy;

        if (initalCards == null) return;

        _cards = new List<Card>(initalCards);

    }

 

    public bool IsEmpty { get { return !_cards.Any(); }}

 

    public bool AddCard(Card card)

    {

        var canAdd = true;

        if((canAdd = Policy.CanAdd(card, this))) _cards.Add(card);

        return canAdd;

    }

 

    private ICardPilePolicy Policy { get; set; }

 

    public IEnumerable<Card> Cards

    {

        get { return _cards.ToArray(); }

    }

}

 

The idea here, is that we don't want consumers of our class to worry about the logic required to add to our collections. If we do let them worry about it, we might accidentally allow the consumer to do something bad with our card piles. Notice in the last version of the class, I do still allow the consumer to get the list of cards from the pile. This might be necessary for the game to draw the pile to the screen for instance. However, I expose it as an IEnumerable, and return an array, not the internal collection. In this example, Cards are an immutable object, so no harm can be done by giving the consumer direct access to the cards, they couldn't change the values or anything like that. If you see a class with an exposed collection, I hope you slow down and contemplate whether this is what you want or not.

These code samples are provided openly and freely for any use without warranty.

    
If Obama is a Socialist, what is Steve Jobs?

Yesterday, Steve Jobs, and Apple announced, and detailed iPhone OS 4. There's some interesting stuff there, if you care, there is lots of coverage elsewhere on the web. What I'm interested in, is this clause in the new developer agreement:

Applications may only use Documented APIs in the manner prescribed by Apple and must not use or call any private APIs. Applications must be originally written in Objective-C, C, C++, or JavaScript as executed by the iPhone OS WebKit engine, and only code written in C, C++, and Objective-C may compile and directly link against the Documented APIs (e.g., Applications that link to Documented APIs through an intermediary translation or compatibility layer or tool are prohibited).

This is just one more element of control that Apple puts over developers. I understand that Apple wants to maintain a level of quality over their products, but I'm guessing they also want to make money, and to do that, they need apps. The mobile space has been taking off, and there are several competing Smartphone platforms. If a company wants to add a mobile element to their product, they have several platforms to develop for, and that can be expensive. Groups like the Mono team are working to allow developers to utilize existing skills and code to get apps onto mobile marketplaces, and that's a good thing. Companies can't afford to have development staff that is familiar with Objective-C and Cocoa, and Android Java, and Windows Phone 7 Silverlight. That's too expensive, so if there is any way to simplify the porting of applications, that's great for business.

Apple wants to make sure that all iPhone apps are written in XCode using Objective-C, which in my opinion is strange because they give away the tools for free! I understand that there could be quality issues with these other cross compilers that might hurt the experience for the end user if the code isn't linked right. But why does Apple get to have so much control? At what point do they have to worry about anti-trust? They already don't allow apps that duplicate functionality that Apple puts into the iPhone (i.e. no other browsers), and they deny applications for unknown reasons, and now they dictate what tools you can use to build applications.

I realize that the implications of this are stricktly thorns in a developers side, and really have no effect on the end user. But Microsoft got in a bunch of hot water for bundling a browser with an OS. Why doesn't Apple? How did they manage this public perception? At what point will people realize, Apple products crash, are susceptible to viruses, and are a little too controlling? I guess good for Apple, they are making tons of money, and people are happy with the product.

But seriously Steve, loosen up.

  
Older >
Recent Posts
Clearing the ClickOnce App Cache
VB.NET Gotchas for C# Devs
Dreamhost 1 year Special
Can I Suggest Bit Torrent?
Moq and VB.Net are Frenemies
Google Buzz - Impressions
O Rly? Intellisense requires XML + DLL
Self Documenting Code - FAIL
The 'F' in TFS is for 'Friction'
NDC 2009 Videos
Skills Test - FAIL!
Tag Cloud
.net   apple   asp.net   beta   borked   buzz   c#   clickonce   clio   code   code camp   console   deals   deployment   documentation   dreamhost   fail   friction   general   git   gotchas   hosting   linq   mix   mocking   ndc09   note-to-self   opinion   orly?   patterns   practices   r#   rant   refactoring   resharper   screencasts   sell-out   session state   skills test   sql server   stack overflow   strategy   tccc   testing   tfs   tips   troubleshooting   twitter   typemock   vb   vb.net   video   visual studio   web 2.0