Tuesday, March 3, 2009

The type initializer for ‘SomeClass’ threw an exception.

I spent a good hour this afternoon troubleshooting a bizarre WPF designer error. I've been working on an app for my church, and I was using an ObjectDataProvider in a particular page to return a "Donation" object from my data-layer with some appropriate defaults set.

<ObjectDataProvider x:Key="defaultDonation" ObjectType="{x:Type classes:Data}" MethodName="GetNewDonation" />

This had been working fine for a while, but after I refactored a bit of the code in my data layer, the WPF designer stopped loading any form that touched this data layer. It kept returning the error:

The type initializer for 'WouldBeTheologian.PledgeManager.Classes.Data' threw an exception.

Interestingly enough, although the WPF forms wouldn't load, the project itself would run just fine; and specifically, the Data class would load and execute just fine. But it's a pain and a half to lose IntelliSense, and to have no hint of what your XAML is gonna look like.

It took some work to figure out what was going on. It turns out that after I refactored my Data class, I was instantiating a reference to my Entity Data Model during the class' static constructor, like so:

static Data() { pledgesEntities = new PledgesEntities(); }
But beneath the hood, when the EF tries to initialize its ObjectContext, it's doing so by reading the appropriate connection strings from the application's .config file. That works fine when the "application" is, in fact, your own application. But when it's called by the WPF designer, the "application" is Visual Studio, which (presumably) doesn't have the appropriate connection strings in its .config file; and hence the constructor throws an exception.

Once I figured this out, I fixed it by moving the instantiation of my Entity Data Model into a property, like so:

private static PledgesEntities pledgesEntities = new PledgesEntities(); 
public static PledgesEntities PledgesEntities 
{
    get
    {
        if (pledgesEntities == null)
        {
            pledgesEntities = new PledgesEntities();
        }
        return pledgesEntities;
     }
     set
     { 
         pledgesEntities = value; 
     }
}
In other words, the static PledgesEntitities instance doesn’t get initiated until it’s actually needed, and hence doesn’t throw an exception when the designer loads the class. It's a bit uglier and infinitesimally slower, but it works.
 
I should note that there are lots of other ways around this problem as well; a more general approach is just to wrap any code that might give the designer trouble with a check to see whether you’re running in the designer or not, like so:
if (!DesignerProperties.IsInDesignTool)
{
    // Do stuff that won't work in the designer
}

Of course, I'm not the first person to figure out that the Visual Studio WPF designer sucks at providing any help troubleshooting these errors. Among many other things, there's no way to access the InnerException of the error in question, which is a serious limitation, and has bit me on several occasions. Hopefully VS 2010 will fix this, though I haven't yet seen any firm indication that will be the case.

6 comments:

Anonymous said...

In case, if you feel this time schedule unsuitable market that in financial troubles at any cost. In case you have to avail loans, so as lots of people love to take it. Hence you can easily attain month after which it is paid in full in a single payment. However, fixed monthly salary is not enough financial then would have had to wait for them to check all of your details and reply in a similar fashion. This credit gets approved within then they can really help everything run that little bit more smoothly. As the lenders are available online so you just might never have to in the society, cash, go of interest charged on the fund is a bit high. It's a short term loan which provides you immediate collateral free your you need to be a civilian of UK who must have celebrated his/her eighteenth birthday. pay day uk Do you wish to approve the kind of acclaim on time cash in your account. This is why one tends to run can take care of additional expenses in the middle of the month. Need a payday loan is specifically designed for UK into support you in your difficulty directly.

Anonymous said...

buy louis vuitton handbags online
I am really inspired with your writing abilities and also with the format in your blog.
Is this a paid theme or did you modify it yourself? Anyway stay up the nice quality writing, it's rare to see a nice blog like this one these days..

Anonymous said...

Oh my goodness! Impressive article dude! Thank you, However I am having issues with your RSS.
I don't understand why I am unable to join it.

Is there anybody else having similar RSS problems?
Anyone who knows the solution can you kindly
respond? Thanks!!

Anonymous said...

Oh my goodness! Impressive article dude! Thank you, However I am having issues with your RSS.
I don't understand why I am unable to join it. Is there anybody
else having similar RSS problems? Anyone who knows the solution can you kindly respond?
Thanks!!

Anonymous said...

Worldwide Journal οf Proteins іs really a
peer reviewed, оpen access record tҺat writes original reseaгch posts аs well as review posts in ɑll areаs οff
peptide analysis. The dividing ƿoint reaches aboսt 50 amino-acids.
Profeins possess a wide variety օf apps in medication аnd biotechnology.
Molecules աith molecular weights ranging fгom severɑl thoսsand ɑ number off tҺousand daltons
(D) arre named polypeptides.

Α rule-of-thumb іn designing soluble proteins wоuld Ье to ensue hat ONE frm every ϜIVE amino acids iѕ recharged.
Thеse peptides include switching perfumed аnd essential residues ɑnd tɦerefore arе in ɑ posution to uniquely goal
tɦе inside membrane of mitochondria; fսrthermore, such modest-peptide antioxidants arre believed tto permeate tissues іn a energy-independent ɑnd no-saturable ԝay withօut a dependenche on peptide transporter.
Ҭhey ɑгe oftеn ƿut through prpteolysis tо buiild thе oldеr type.
Elements ѕmaller enoսgh to be synthesized fгom the component amino-acids ɑre, by
convention, named peptides іn the plɑϲe օf proteins. [1] Many peptides еxcept cyclic proteins possess an N-fatal and
H-terminal remains ɑt the end of the peptide
(as demonstrated fοr the tetrapeptide inside tҺe impression).

peptides for sale
ҬҺе effect οf differеnt colors on theiг scientific behaviour ѡaѕ examined.
Oligopeptides ɦave ten or leѕs amino acids.
Peptides aгe divided into numerous sessions,
determined ƅy how they'гe produced:

Two naturally occurring milk peptides are established fгom your milk proteins casein when intestinal enzymes break thіs dߋwn; they can additionally occur in the proteinases established Ƅy lactobacilli through tҺe fermentation οf milk.
Entirеly manufactured personalized libraries tɦat assist high throughput screening assays
tߋ map epitopes οr identify immunogenic websites іn proteins.
Аbout 140 peptide medication сome in scientific studies and morе than 500 are in pre-clinical improvement.


, "ingested", based ߋn , "to consume") are bгief chains
οf amino acid monomers linked ƅy peptide (amide)
proνides. [4]
peptides international careers
A peptide іs just a compound compound comprising seveгal
amino-acids (amino acid polymers) աhich are coupled with a peptide relationship.
Twο-step method of qualified assay growth аnd utter quantitation Ƅy picked reaction checking (SRM)
inside a handled budget. Yߋu can find siҳty fda-approved peptide drugs aѵailable іn tɦe market.
We ɦave intended ѕome fluorescently-branded limited
peptides ɑnd also have considered tɦeir capability to company-localize
ѡith mitochondria.

Ƭhe covalent compound bonds are formed once tɦe carboxyl numƄеr of one amino acid reacts tօgether with tҺe amino-grօup of ɑnother.
Іf tɦiѕ can't Ƅe performed, tҺen

Anonymous said...

Anyone who is interested in this plan can find numerous recipes
and resources on the Internet. This is not the energy expenditure
with planned exercise. "Never feeling hungry is not a sign of being healthy," stated Dr.


Feel free to visit my site; weight loss pills