Monthly Archives: April 2012

Publish Access Web Database to SharePoint 2010 Access Services

My blog has been moved to http://sundarnarasiman.net.


It has been migrated to wordpress platform
You can find this post http://sundarnarasiman.net/?p=73


 

Error when running .NET Application that is consuming CRM 2011 Services

Hi All,

I was trying to run a .NET application that consumes CRM 2011 WCF Services and i was getting this exception:

Could not load file or assembly ‘Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′ or one of its dependencies. The system cannot find the file specified.

The cause of this issue is to due to missing dlls in your machine for Microsoft Identity framework that is required to have to run your application.

Install Microsoft Identity Framework in your computer that is compatible with your operating system.

For Windows 7 & Windows 2008 R2 you need to install Version 6.1

After you install this update re-run your application and will run with no exceptions!

Note: Make sure to stop your development web sever before rerun your application to reload all required assemblies.

**Download link:
http://www.microsoft.com/en-us/download/details.aspx?id=17331

Hope this helps!


New MVVM Tutorial

With the increased importance of XAML in Windows 8, I have decided to update my tutorial on the Model View View-Model pattern. As I said in my original MVVM tutorial, I finally understand the pattern well enough to make some intelligent comments about its use.


The tutorial begins by contrasting the traditional “code behind” approach with the MVVM approach and provides motivation for using the MVVM pattern. The tutorial uses a Silverlight client as the demonstration application. We start by building a simple view model that downloads data from a RIA Data Service and exposes the collection of data to the UI. We then add CRUD (minus the update) functionality to the application and show how our view model handles these requirements.


The tutorial uses Visual Studio 11 beta and Visual Basic. If any changes are needed after VS 11 is released, I will update the tutorial appropriately.


When the tutorial is complete, a simple functioning application is created using the MVVM pattern and zero lines of code behind.


clip_image002

New Website Design

I have just launched a new web design for myVBProf.com. The new site is HTML based and uses some HTML 5 features. I have tested it with current releases of the major browsers and have not encountered any issues.

New videos will be published on the new site and will focus on Visual Studio 11 (or whatever it will be called) and Windows 8. The new site has a link to the old site where all current videos still live.

When a new tutorial is published that updates an existing tutorial, the link to the one being replaced will be deleted.

bill

Add File Hashes Tab in File Properties in Windows 7 [How To]

A file’s hash value is a signature for that file that uniquely identifies it. If a file’s contents change, its hash value will also change. You can use the hash value of a file to know whether it has been modified or altered. You can also cross-check the hashes of a suspicious file online to [...]

Add File Hashes Tab in File Properties in Windows 7 [How To]

A file’s hash value is a signature for that file that uniquely identifies it. If a file’s contents change, its hash value will also change. You can use the hash value of a file to know whether it has been modified or altered. You can also cross-check the hashes of a suspicious file online to [...]

#SPSHOU Creating Business Intelligence SP2010 & SQL2012 & Windows 8 SharePoint Server

http://www.sharepointsaturday.org/la/Pages/meetings.aspx
Please join us for this Business Intelligence session on the SharePoint and Office set of BI features to build and integrate data-driven spreadsheets and applications with SharePoint 2010. This session will cover topics such as PowerPivot, PerformancePoint Services, Reporting Services, Excel Services, KPIs, and much more

See yall in Houston on my way to LAX now landing at 630am and just have time to check out Steve Foxs Keynote..

 

 

-Ivan

Updated Thoughts on CISPA

Since I wrote my last post on CISPA a few weeks ago, a number of things have changed and my own opinion has evolved some as well. I still feel that the EFF’s interpretation was perpetuation a great amount of FUD, but that doesn’t really justify the merits of CISPA. There are many things to [...]

Accédez à SkyDrive depuis l’Explorateur Windows

Bonsoir tout le monde,

Avec SkyDrive pour Windows vous entrez tout simplement dans le monde du Cloud.

En installant SkyDrive, un dossier SkyDrive est créé sur votre PC.

Chaque fichier placé dans ce dossier est automatiquement synchronisé imageentre vos ordinateurs (PC ou Mac) et SkyDrive.com. De cette manière, il devient facile d’accéder à vos fichiers les plus récents depuis pratiquement n’importe où.

Chaque fois que vous ajoutez, modifiez ou supprimez les fichiers Ă  un emplacement, tous les autres emplacements sont mis Ă  jour.

Si vous avez oublié de placer un fichier dans votre dossier SkyDrive, vous pouvez revenir sur votre PC pour accéder à tous ses fichiers et dossiers depuis SkyDrive.com.

Fonctionnalités
  • AccĂ©dez directement Ă  SkyDrive depuis l’Explorateur Windows (photos, documents et autres fichiers importants).
  • Ajoutez rapidement de nouveaux fichiers Ă  SkyDrive en les faisant glisser vers le dossier SkyDrive.
  • Organisez sans peine vos fichiers et dossiers dans SkyDrive, comme vous le feriez dans tout autre dossier.
  • Connectez-vous Ă  nouveau Ă  votre PC si vous avez oubliĂ© d’insĂ©rer un Ă©lĂ©ment dans SkyDrive.

Installation

image

 

L’installation est très simple !

Depuis la page de Bienvenue, cliquez sur Commencer.

A l’aide de vos identifiants Windows Live, connectez-vous au monde Live…

 

image

Skydrive vous demande de confirmer ou de modifier le dossier qu’il vous présente…

Cliquez sur Suivant.

image

SkyDrive procède ensuite à la synchronisation de vos dossiers et fichiers.

Cliquez sur Terminer.

 

 

 

 

 

image

 

 

Dans votre Explorateur Windows un nouveau favoris est présent : Microsoft Skydrive !

Et maintenant, Ă  vous les applications SkyDrive https://apps.live.com/skydrive

Bonne soirée.
Patrice.

Fazendo Tethering no Samsung Focus

  • Abra a tele de chamada do telefone, teclando no Ă­cone de telefone;
  • Digite o cĂłdigo ##634#;
  • Desta forma vocĂŞ acessará a tela de diagnĂłsticos do telefone;

Diagnostics-Menu[1]

  • Agora digite o cĂłdigo *#7284#;
  • Aparecerá uma tela com trĂŞs opções:
    • Zune Sync (opção PadrĂŁo);
    • Modem, Tethered Call;
    • Modem, USB Diag.
  • Selecione a opção do meio;
  • O telefone reiniciará;
  • Conecte o cabo USB ao seu computador e aguarde a instalação dos drivers;
  • Agora Ă© sĂł configurar o nĂşmero para onde ele deve ligar, usuário e senha.

Se estiver usando na rede da AT&T use:
nĂşmero: *99***1#
user name: WAP@CINGULARGPRS.COM
password: CINGULAR1
APN: NĂŁo precisa

Claro
nĂşmero: *99#
user name: claro
password: claro
APN: claro.com.br (em alguns estados precisa usar bandalarga.claro.com.br)

Vivo
nĂşmero: *99#
user name: vivo
password: vivo
APN: zap.vivo.com.br

TIM
nĂşmero: *99#
user name: tim
password: tim
APN: tim.br

Oi
nĂşmero: *99#
user name: oi
password: oi
APN: gprs.oi.com.br

Free ebook – Secrets of PowerShell Remoting

You wouldn’t have had to read too much of this blog to know that I’ve regularly recommended PowerShell books by Don Jones and Tobias Weltner. They’ve announced the availability of a new free ebook that they’ve co-authored, called Secrets of PowerShell Remoting.


Remoting is one of the most powerful features of PowerShell, but it’s not necessarily the simplest area to understand. In Windows Server 2012, PowerShell remoting is enabled by default, so now is a good time to get up to speed.


Head over to powershellbooks.com for the download links.

Dispose Pattern and “Set large fields to null”

I was involved in a short side discussion about “should” fields be set to null in the Dispose method(s).  I’m not sure what the impetus of the question was; but, if you read through the dispose pattern MSDN documentation (in most versions I believe) there’s a comment // Set large fields to null. in the implementation of the virtual Dispose method within the if(!disposed) block and after the if(disposing) block.  But, that’s the only reference to setting fields to null during dispose.  There’s nothing else that I’ve been able to find in MSDN with regard to setting fields to null.

At face value, setting a field to null means that the referenced object is now unrooted from the class that owns the field and, if that was the last root of that reference, the Garbage Collector (GC) is now free to release the memory used by the object that was referenced by that field.  Although advanced, this seems all very academic because the amount of time between unrooting the reference and the return from Dispose (and thus the unrooting of the parent object) would seem like a very short amount of time.  Even if the amount of time between these two actions is small, setting a single field to null (i.e. a single assignment) seems like such a minor bit of code to provide no adverse affects.  The prevalent opinion seems to be that the GC “handles” this case and does what is best for you without setting the field to null.

The GC is pretty smart.  There’s a lot of bright people who have worked on the GC over the years; and it improves every release of .NET.  But, that doesn’t answer the question; is there benefit to setting a field to null in the Dispose method?  Considering there isn’t much guidance on the topic; I’d though I’d set aside any faith I have in the GC and throw some science at the problem: take my theory, create some experiments, make observations, and collect some evidence.

What I did was to create two classes, identical except that the Dispose method doesn’t set a reference field to null.  The classes contain an field that could reference a “large” or “small” object: I would experiment with large objects and small objects and observe the differences.  The following are the classes:

	public class First : IDisposable {
		int[] arr = new int[Constants.ArraySize];
		public int[] GetArray() {
			return arr;
		}
		public void Dispose() {
			arr = null;
		}
	}
 
	public class Second : IDisposable {
		int[] arr = new int[Constants.ArraySize];
		public int[] GetArray() {
			return arr;
		}
 
		public void Dispose() {
		}
	}


I would vary Constants.ArraySize constant to make the arr reference a “large” object or a “small” object.  I then created a loop that created several thousand instances of one of these classes then forced a garbage collection at the end; keeping track of the start time and the end time via Stopwatch:



	public class Program {
		private const int Iterations = 10000;
 
		static void Main(string[] args)
		{
			var stopwatch = Stopwatch.StartNew();
			for (int i = 0; i < Iterations; ++i)
			{
				using (var f = new First())
				{
					ConsumeValue(f.GetArray().Length);
				}
			}
			GC.Collect();
			stopwatch.Stop();
			Trace.WriteLine(String.Format("{0} {1}", stopwatch.Elapsed, stopwatch.ElapsedTicks));
			stopwatch = Stopwatch.StartNew();
			for (int i = 0; i < Iterations; ++i)
			{
				using (var s = new Second())
				{
					ConsumeValue(s.GetArray().Length);
				}
			}
			GC.Collect();
			stopwatch.Stop();
			Trace.WriteLine(String.Format("{0} {1}", stopwatch.Elapsed, stopwatch.ElapsedTicks));
		}
 
		static void ConsumeValue(int x) {
		}
	}


I wanted to make sure instanced got optimized away so the GetArray method makes sure the arr field sticks around and the ConsumeValue makes sure the First/Second instances stick around (more a knit-picker circumvention measure :).  Results are the 2nd result from running the application 2 times.



As it turns out, the results were very interesting (at least to me :).  The results are as follows:



Iterations: 10000 ArraySize: 85000 Debug: yes Elapsed time: 00:00:00.0759408 Ticks: 170186.
Iterations: 10000 ArraySize: 85000 Debug: yes Elapsed time: 00:00:00.7449450 Ticks: 1669448.



Iterations: 10000 ArraySize: 85000 Debug: no Elapsed time: 00:00:00.0714526 Ticks: 160128.
Iterations: 10000 ArraySize: 85000 Debug: no Elapsed time: 00:00:00.0753187 Ticks: 168792.



Iterations: 10000 ArraySize: 1 Debug: yes Elapsed time: 00:00:00.0009410 Ticks: 2109.
Iterations: 10000 ArraySize: 1 Debug: yes Elapsed time: 00:00:00.0007179 Ticks: 1609.



Iterations: 10000 ArraySize: 1 Debug: no Elapsed time: 00:00:00.0005225 Ticks: 1171.
Iterations: 10000 ArraySize: 1 Debug: no Elapsed time: 00:00:00.0003908 Ticks: 876.



Iterations: 10000 ArraySize: 1000 Debug: yes Elapsed time: 00:00:00.0088454 Ticks: 19823.
Iterations: 10000 ArraySize: 1000 Debug: yes Elapsed time: 00:00:00.0062082 Ticks: 13913.



Iterations: 10000 ArraySize: 1000 Debug: no Elapsed time: 00:00:00.0096442 Ticks: 21613.
Iterations: 10000 ArraySize: 1000 Debug: no Elapsed time: 00:00:00.0058977 Ticks: 13217.



Iterations: 10000 ArraySize: 10000 Debug: yes Elapsed time: 00:00:00.0527439 Ticks: 118201.
Iterations: 10000 ArraySize: 10000 Debug: yes Elapsed time: 00:00:00.0528719 Ticks: 118488.



Iterations: 10000 ArraySize: 10000 Debug: no Elapsed time: 00:00:00.0478136 Ticks: 107152.
Iterations: 10000 ArraySize: 10000 Debug: no Elapsed time: 00:00:00.0524012 Ticks: 117433.



Iterations: 10000 ArraySize: 40000 Debug: yes Elapsed time: 00:00:00.0491652 Ticks: 110181.
Iterations: 10000 ArraySize: 40000 Debug: yes Elapsed time: 00:00:00.3580011 Ticks: 802293.



Iterations: 10000 ArraySize: 40000 Debug: no Elapsed time: 00:00:00.0467649 Ticks: 104802.
Iterations: 10000 ArraySize: 40000 Debug: no Elapsed time: 00:00:00.0487685 Ticks: 109292.



Iterations: 10000 ArraySize: 30000 Debug: yes Elapsed time: 00:00:00.0446106 Ticks: 99974.
Iterations: 10000 ArraySize: 30000 Debug: yes Elapsed time: 00:00:00.2748007 Ticks: 615838.



Iterations: 10000 ArraySize: 30000 Debug: no Elapsed time: 00:00:00.0411109 Ticks: 92131.
Iterations: 10000 ArraySize: 30000 Debug: no Elapsed time: 00:00:00.0381225 Ticks: 85434.



For the most part, results in debug mode are meaningless.  There’s no point in making design/coding decisions based on perceived benefits in debug mode; so, I don’t the results other than to document them above.



The numbers could go either way, if we look at percentages; release mode, setting a field to null seems to be slower 50% of the time and faster 50% of the time.  When setting a field to null is faster it’s insignificantly faster (5.41%, 9.59%, and 4.28% faster) when it’s slower it’s insignificantly slower but more slow than it is fast (133.68%, 163.52%, and 107.84% slower).  Neither seems to make a whole lot of difference (like 10281 ticks over 10000 iterations in the biggest difference for about 1 tick per iteration—1000 byte array at 10000 iterations).  If we look at just the time values, we start to see that setting a field starts to approach being faster (when it’s slower it’s slower by 295, 8396, and 6697 ticks; when it’s faster it’s faster by 8664, 10281, 4490).  Oddly though, setting “large” fields to null isn’t the biggest of faster setting field to null values.  But, of course, I don’t know what the documentation means by “large”; it could be large-heap objects or some other arbitrary size.



Of course there’s other variables that could affect things here that I haven’t accounted for (server GC, client GC, GC not occurring at specific time, better sample size, better sample range, etc.); so, take the results with a grain of salt.



What should you do with this evidence?  It’s up to you.  I suggest not taking it as gospel and making a decision that is best for you own code based on experimentation and gathered metrics in the circumstances unique to your application and its usage..  i.e. setting a field to null in Dispose is neither bad nor good in the general case.

(function() { var po = document.createElement(‘script’); po.type = ‘text/javascript'; po.async = true; po.src = ‘https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName(‘script’)[0]; s.parentNode.insertBefore(po, s); })();

Thoughts on the new Skydrive

I have swapped to the new version of Microsoft Skydrive, replacing my old Mesh setup. It is a nice slick experience, allowing easy viewing of files on Skydrive from Windows and WP7. However, I do have couple of issues

  1. I used Mesh to sync photos from my Window 7 Media Center up to cloud storage as a backup, don’t want to loose all the family photos due to a disk failure. This was simple with Mesh, just set up a sync. This is not so easy with the new Skydrive, which appears only as a folder in your user area. The only solution I can spot is to copy my photos into this folder e.g. xcopy d:photos c:usersrichardskydrivephotos. Once the copy is done this will be synced up to the cloud. With mesh if I added a file to my PC it sync’d without me doing anything, now I need to remember the xcopy (or whatever sync copy tool I am using), or have the copy being run on a regular basis via a timer.
  2. Letting Skydrive start automatically on a laptop Windows PC is dangerous. I was on site today using my Mifi and in about 10 minutes used a whole days credit. So I would recommend changing your tool tray setting to make sure you can see the Skydrive icon all the time, so you have a chance see when it is syncing and can stop it when on a connection that cost you money.

image

So any comments, or better ways to do the sync?

Thoughts on the new Skydrive

I have swapped to the new version of Microsoft Skydrive, replacing my old Mesh setup. It is a nice slick experience, allowing easy viewing of files on Skydrive from Windows and WP7. However, I do have couple of issues

  1. I used Mesh to sync photos from my Window 7 Media Center up to cloud storage as a backup, don’t want to loose all the family photos due to a disk failure. This was simple with Mesh, just set up a sync. This is not so easy with the new Skydrive, which appears only as a folder in your user area. The only solution I can spot is to copy my photos into this folder e.g. xcopy d:photos c:usersrichardskydrivephotos. Once the copy is done this will be synced up to the cloud. With mesh if I added a file to my PC it sync’d without me doing anything, now I need to remember the xcopy (or whatever sync copy tool I am using), or have the copy being run on a regular basis via a timer.
  2. Letting Skydrive start automatically on a laptop Windows PC is dangerous. I was on site today using my Mifi and in about 10 minutes used a whole days credit. So I would recommend changing your tool tray setting to make sure you can see the Skydrive icon all the time, so you have a chance see when it is syncing and can stop it when on a connection that cost you money.

image

So any comments, or better ways to do the sync?

Outil de suppression logiciels malveillants

Bonsoir Ă  tous,

Pat842L’outil de suppression des logiciels malveillants de Microsoft Windows analyse Windows Vista, Windows XP, Windows 2000 et Windows Server 2003 et aide Ă  supprimer les logiciels malveillants les plus connus, dont Blaster, Sasser et Mydoom.

Une fois la dĂ©tection et la suppression terminĂ©es, l’outil affiche la liste des logiciels malveillants qui ont Ă©tĂ© dĂ©tectĂ©s et supprimĂ©s. L’outil crĂ©e un fichier journal nommĂ© mrt.log. Ce fichier est placĂ© dans le dossier %WINDIR%debug.

Pour télécharger la version x64 de l’outil de suppression de logiciels malveillants, cliquez ici.
Cet outil ne remplace pas l’antivirus. Pour protĂ©ger votre ordinateur, vous devez300x250_GrayMail_Avril_2012 utiliser un antivirus.

Microsoft publiera une version mise Ă  jour de cet outil le deuxième mardi de chaque mois. Les nouvelles versions seront mises Ă  disposition par l’intermĂ©diaire de cette page Web, de Windows Update et du site Web Outil de suppression de logiciels malveillants de Microsoft.com.

Pour que les nouvelles versions soient fournies et installées automatiquement dès leur diffusion, réglez la fonction de mise à jour automatique sur Automatique.

La version Windows Update de cet outil est exĂ©cutĂ©e une fois par mois sur votre ordinateur, en arrière-plan. Si une infection est dĂ©tectĂ©e, l’outil affiche un rapport d’Ă©tat au dĂ©marrage suivant de l’ordinateur. Si vous souhaitez utiliser cet outil plus d’une fois par mois, exĂ©cutez la version disponible sur cette page Web ou utilisez la version prĂ©sentĂ©e sur le site Web Outil de suppression de logiciels malveillants.

Consultez le document KB890830 pour obtenir la liste des logiciels malveillants que la version actuelle est capable de supprimer, ainsi que des instructions d’utilisation. Notez Ă©galement que cet outil renvoie des informations anonymes Ă  Microsoft en cas d’erreur ou de dĂ©tection d’une infection. L’article de la Base de connaissances mentionnĂ© ci-dessus prĂ©sente le processus de dĂ©sactivation de cette fonctionnalitĂ© et indique quelles informations sont Ă©ventuellement envoyĂ©es Ă  Microsoft.

Avant d’envisager le dĂ©ploiement de cet outil dans un environnement d’entreprise, nous vous recommandons vivement de lire l’article KB891716.

Pour utiliser cet outil, l’utilisateur doit ĂŞtre administrateur. Cet outil ne fonctionnera pas sous Windows 98, Windows ME ou Windows NT 4.0.

Notez que cet outil est dĂ©sormais multilingue. Pour toutes les langues prises en charge, le mĂŞme outil affichera la langue correcte, en se basant sur la langue du système d’exploitation.

TĂ©lĂ©chargement en français…          Version x64…

Bon ménage et bonne soirée Clignement d'œil
Patrice.

Office 365 E Plan Family Chart

Office365EPlan

SOCA & FBI seize 36 Criminal Credit Card Stores

Today the Serious & Organised Crime Agency (SOCA) in the UK announced the completion of a joint operation targeting 36 criminal websites dealing with stolen credit card and online bank account information. The April 26th Press Release indicates that the operation targeted a particular type of e-commerce platform known as an Automated Vending Cart, or AVC. Here’s an advertisement from one of the sites, CVVPlaza.com:

The seized domains are now redirected to a website controlled by the FBI which reads:

The United States Government has seized this domain name pursuant to a seizure warrant issued by the United States District Court for the Eastern District of Virginia under the authority of 18 U.S.C. §§ 981(a)(1)(A) & (b)(2). A United States Magistrate Judge issued that seizure warrant after finding that a sworn affidavit established probable cause that this domain name was personal property involved in a transaction or attempted transaction in violation of section 18 U.S.C. § 1956(a)(2)(A) & (h)
If you registered this domain name, or otherwise claim an ownership interest in this domain name, you should consult an attorney about your rights.


(click for full size)

SOCA has requested that we not provide a full list of the domain names at this time, but two which they have revealed in their own products are “cvvplaza.com” and “ccstore.biz”. The others will be added once permission is received.

Some of the screenshots provided by SOCA include:

a site offering an inventory of more than 37,000 confirmed credit cards:

and a fairly nice “search screen:

SOCA has recovered more than 2.5 million card numbers or credentials that they say would have granted the criminals access to more than ÂŁ500 million (about $809 million US Dollars!) These were NOT the value of the cards currently available for sale in these card shops, but rather the value of the cards that have been recovered from criminals who purchased the cards from these card shops. The total inventory is expected to be much higher. SOCA is leading the way in international cooperation. In this case they worked with the BKA in Germany, the KLPD in the Netherlands, the Ukraine Ministry of Internal Affairs, the Australian Federal Police, the Romanian National Police and of course the FBI in the United States. These recoveries took place over the course of the past two years. The operator of at least one of these AVC stores was arrested in Macedonia by the Macedonian Ministry of the Interior’s Cyber Crime Unit. Some online card shops have very simplistic interfaces, such as this: while others have extremely beautiful websites. Check out the login page for this site: Our friend Dancho Danchev has written extensively about the online carding markets, for example in his article: Exposing Market for Stolen Credit Cards. Brian Krebs has also written extensively on the topic with articles such as How much is your identity worth?

My Favorite Passwords of the Month

Okay so I deal with passwords quite a bit and people tend to eagerly share their passwords with me way more than they should. And although most passwords I come across are pretty weak, I do sometimes come across some true greats, either for their strength, originality, or memorability. Here are some of my favorites [...]

Directions EMEA day 1

Ok, it is late and I am tired. But I will pack the day into few sentences:

  • Page preview in page designer – interactive preview of the page directly in C/SIDE, clicking on the object in the page select the corresponding line in the designer or you can open properties for the object (action/field)
  • “Find” function is back – you can again instantly search for specific data in the actual column
  • Variable filters – when filtering in the RTC, you can use “variables” like “%mycust”, which will be “expanded” to e.g. “10000|20000|300000” based on your customer selection. This replacement and expansion is handled with special codeunit in NAV, thus you can add own variables (some other default are already there like “%today”). Saving view with this variable in filter will save the filter including the variable, thus by changing the data will have effect to the saved view (each time when opening the view the variable is replaced with the values)
  • New tool to quickly setup the new company (something like RIM). Partners could add own packages, which will add new settings.
  • Cloud-RTC-debugger  — all is working together.
  • Query and OData – new way how to get the data from NAV to outside and consume them, e.g. in PowerPivot. Query generate complex SELECT statement on SQL with possible JOINS, GROUP BY and preselected set of fields. This could be consumed through OData protocol (something like RSS feed) which could be filtered.
  • New version of NAV should be released ONCE per YEAR! – partners needs really think about this and how to keep all customers up-to-date!

And short list from Waldo’s presentation:

  • Remote Desktop Manager
  • smtp4dev (www.nav-magno.be)
  • Codegenius
  • Mantis bug tracker
  • iFacto Revision

Ok, going into bed. Regarding details, I think more blog articles are needed, but right now, I still do not know how deeply I can go and not hit the NDA… you need to wait for the correct time.

“Virtual method call from constructor” What Could Go Wrong?

If you’ve used any sort of static analysis on source code you may have seen a message like “Virtual method call from constructor”.  In FxCop/Visual-Studio-Code-Analysis it’s CA2214 “Do not call overridable methods in constructors”.  It’s “syntactically correct”; some devs have said “what could go wrong with that”.  I’ve seen this problem in so many places, I’m compelled to write this post.

I won’t get into one of my many pet peeves about ignoring messages like that and not educating yourself about ticking time bombs and continuing in ignorant bliss; but, I will try to make it more clear and hopefully shine some light on this particular class of warnings that arguably should never have made it into object-oriented languages.

Let’s have a look at a simple, but safe, example of virtual overrides:

public class BaseClass {
	public BaseClass() {
	}
 
	protected virtual void ChangeState() {
		// do nothing in base TODO: consider abstract
	}
 
	public void DoSomething() {
		ChangeState();
	}
}
 
public class DerivedClass : BaseClass {
	private int value = 42;
	private readonly int seed = 13;
 
	public DerivedClass() {
	}
 
	public int Value { get { return value; } }
 
	protected override void ChangeState() {
		value = new Random(seed).Next();
	}
}

With a unit test like this:

[TestMethod]
public void ChangeStateTest() {
	DerivedClass target = new DerivedClass(13);
 
	target.DoSomething();
	Assert.AreEqual(1111907664, target.Value);
}

A silly example that has a virtual method that is used within a public method of the base class.  Let’s look at how we might evolve this code into something that causes a problem.

Let’s say that given what we have now, we wanted our derived class to be “initialized” with what ChangeState does (naïvely: it’s there, it does what we want, and we want to “reuse” it in the constructor); so, we modify BaseClass to do this:

public class BaseClass {
	public BaseClass() {
		DoSomething();
	}
 
	protected virtual void ChangeState() {
		// do nothing in base TODO: consider abstract
	}
 
	private void DoSomething() {
		ChangeState();
	}
}
 
public class DerivedClass : BaseClass {
	private int value = 42;
	private readonly int seed = 13;
 
	public DerivedClass() {
	}
 
	public int Value { get { return value; } }
 
	protected override void ChangeState() {
		value = new Random(seed).Next();
	}
}

and we modify the tests to remove the call to DoSomething, as follows:

[TestMethod]
public void ConstructionTest() {
	DerivedClass target = new DerivedClass();
 
	Assert.AreEqual(1111907664, target.Value);
}

…tests still pass, all is good.

But, now we want to refactor our derived class.  We realize that seed is really a constant and we can get rid of the value field if we use an auto property; so, we go ahead and modify BaseClass as follows:

public class DerivedClass : BaseClass {
	private const int seed = 13;
 
	public DerivedClass() {
		Value = 42;
	}
 
	public int Value { get; private set; }
 
	protected override void ChangeState() {
		Value = new Random(seed).Next();
	}
}

Looks good; but now we having a failing test: Assert.AreEqual failed. Expected:<1111907664>. Actual:<42>.

“Wait, what?” you might be thinking…

What’s happening here is that field initializers are executed before the base class constructor is called which, in turn, is called before the derived class constructor body is executed.  Since we’ve effectively changed the initialization of the “field” (now a hidden backing field for the auto-prop) we’ve switched it from a field initializer to a line in the derived constructor body: trampling all over what the base class constructor did when calling the virtual method.  Similar things happen in other OO languages; but, this particular order might be different.

Now, imagine if we didn’t have a unit test to catch this; you’d have to run the application through some set of specific scenarios to find this error.  Not so much fun.

Unfortunately, the only real solution to this is to not make virtual method calls from your base constructor.  One solution to this is to separate the invocation of ChangeState from the invocation of the constructor.  One way is basically reverting back to what we started with and adding a call to ChangeState in the same code that invokes the constructor.  Without reverting our refactoring, we can change BaseClass to what it was before and invoke the DoSomething method in the test, resulting in the following code:

public class BaseClass {
	public BaseClass() {
	}
 
	protected virtual void ChangeState() {
		// do nothing in base TODO: consider abstract
	}
 
	public void DoSomething() {
		ChangeState();
	}
}
 
public class DerivedClass : BaseClass {
	private const int seed = 13;
 
	public DerivedClass() {
		Value = 42;
	}
 
	public int Value { get; private set; }
 
	protected override void ChangeState() {
		Value = new Random(seed).Next();
	}
}
[TestMethod]
public void ChangeStateTest() {
	DerivedClass target = new DerivedClass();
 
	target.DoSomething();
	Assert.AreEqual(1111907664, target.Value);
}

Issues with virtual member invocations from a constructor are very subtle; if you’re using Code Analysis, I recommend not disabling CA2214 and promoting it to and error.  Oh, and write unit tests so you can catch these things as quickly as possible.


Recent Comments

Archives