Category: .NET

Automatic migration was not applied because it would result in data loss.

You might get this error while doing update-database -verbose via Package Manager Console:

This error happens when your data model is not in synch with your database. There are two ways to fix this:

The first approach is by adding/deleting the columns that you added/dropped manually to your table and then re-running update-database again. The second approach is to force the update by issuing:

Doing so will force the update and recreate your columns and tables.

Design Patterns : Singleton

A Singleton, in software engineering, is a design pattern that is used when you only want/need to allow one instance of a class. This is specifically useful when the class instantiation of the said class is resource expensive (e.g. database connection, graphics driver, network resource and file streams…).

Below is a UML describing the implementation details of a Singleton.

designpatternsworkbook_singleton_diagram

Here is an example of a Thread-safe Singleton implemented in C#. In this example, we are trying to simulate a DbConnection object. The DbConnection object has a private constructor that blocks users of this class from ‘new-ing’ this object. Instead, the DbConnection object has a property called Instance that allows users creates a copy of DbConnection.

designpatternsworkbook_singleton_classdiagram

Running the above code will have this output:

designpatternsworkbook_singleton_outputresult

 

Error: The reference assembly could not be resolved because it has a dependency on System.Web

I was working on a sample project today when I encountered this error after adding a new Console Application project to my Visual Studio solution that references other Class Library projects contained in the solution:

.NET 4.0 Client Profile Assembly Error

The referenced assembly “C:devcenterdotnetpersonalKeithRull.BibliaKeithRull.Biblia.Service.RepositorybinDebugKeithRull.Biblia.Service.Repository.dll” could not be resolved because it has a dependency on “System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” which is not in the currently targeted framework “.NETFramework,Version=v4.0,Profile=Client”. Please remove references to assemblies not in the targeted framework or consider retargeting your project. KeithRull.Biblia.ConsoleApp.

There are two possible cause of this error. The first possible reason is when you have an assembly that is referencing System.Web and you try to add that assembly to project that does not have any reference to System.Web (if necessary which most of the time is not). The second possible reason is that your project is using the .NET 4.0 Client Profile which is just a subset of the .NET Framework. Below are the steps that illustrate how to fix this issue.

1. Select your project, right-click and then select “Properties”.

Visual Studio Properties Menu

 

2. The properties tab, change the value for “Target Framework” and then set it’s value to “.NET Framework 4”

Visual Studio Change Target Framework

Compile your application and that should fix the problem.

Interested in learning more? Below are some useful links if you want to read more about this issue and the .NET 4 Client Profile.

Error: This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

Assembly is loaded by a newer runtime error

I received this error while deploying a WCF 4.0 service to a newly created virtual directory.

 

Could not load file or assembly ‘KeithRull.Biblia.Service’ or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded. 

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.BadImageFormatException: Could not load file or assembly ‘KeithRull.Biblia.Service’ or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly ‘KeithRull.Biblia.Service’ could not be loaded.

WRN: Assembly binding logging is turned OFF.To enable assembly bind failure logging, set the registry value [HKLMSoftwareMicrosoftFusion!EnableLog] (DWORD) to 1.

Note: There is some performance penalty associated with assembly bind failure logging.

To turn this feature off, remove the registry value [HKLMSoftwareMicrosoftFusion!EnableLog].

 

It turns out that the error occurred because the application pool for this new virtual directory is using .NET 2.0 profile instead of .NET 4.0 which is the .NET framework version that I used to compile my web service.

RIA Services: Access to operation ” was denied

While working on RIA Services and Silverlight you might get an error like this:

ria services silverlight access to operation error was denied
RIA Services access to operation was denied

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; HPNTDF; InfoPath.3; .NET4.0C; .NET4.0E; MS-RTC LM 8)
Timestamp: Fri, 18 Feb 2011 18:20:46 UTC

Message: Unhandled Error in Silverlight Application Load operation failed for query ‘GetUserDetails’. Access to operation ‘GetUserDetails’ was denied. at System.ServiceModel.DomainServices.Server.DomainService.ValidateMethodPermissions(DomainOperationEntry domainOperationEntry, Object entity)
at System.ServiceModel.DomainServices.Server.DomainService.ValidateMethodCall(DomainOperationEntry domainOperationEntry, Object[] parameters, ICollection`1 validationResults)
at System.ServiceModel.DomainServices.Server.DomainService.Query(QueryDescription queryDescription, IEnumerable`1& validationErrors, Int32& totalCount)
at System.ServiceModel.DomainServices.Hosting.QueryProcessor.Process[TEntity](DomainService domainService, DomainOperationEntry queryOperation, Object[] parameters, ServiceQuery serviceQuery, IEnumerable`1& validationErrors, Int32& totalCount)
at System.ServiceModel.DomainServices.Hosting.QueryOperationBehavior`1.QueryOperationInvoker.InvokeCore(Object instance, Object[] inputs, Object[]& outputs)
Line: 1
Char: 1
Code: 0
URI: http://yourapplicationwebsite/

The reason behind this is that the service you are calling requires privileges in order for it to be executed. This is specifically true when RequiresAuthenticationAttribute attribute or the RequiresRoleAttribute is applied to your service. To solve this error make sure that the application calling the service has the required access/permission to call the service method or you can remove both attributes on the service if the are not really needed(which might be risky).

How To: Create a BulletList in Silverlight

I was working on a prototype application today when I needed to use a BulletList. At first I thought it existed on the toolkit controls but to my surprise it wasn’t so I ended up creating an ItemsControl template that mimics how a BulletList would behave. I wanted to post it here to show you how I did it:

 

As allways you can download a sample project here: KeithRull.SLBulletList

Fun! Now time to get back to my code zen.

Cheers!

How To: Calculate Mathematical Expressions in .NET

Everyday you learn something new. You do. That is if you let yourself to be taught everyday.

I didn’t know that you could solve this expression string in .NET in one line of code: “4 + 5 + 10 – 4 / 5 * 2”

 

The result is 17.4. Nifty huh? You can also group the expressions to display a clearer evaluation instruction and it still will work.


string expressionToEvaluate = “(((4 + 5) + (10 – 4)) / 5) * 2”; //will result to 6

This is all cool but there’s a gotcha. DataTable.Compute() method can only evaluate simple expressions so your

string expressionToEvaluate
= “Tan(10) * 2”;
//error

Would throw an exception of type EvaluateException because it could not recognize the function Tan().

One solution you could take to solve this problem is to use a dynamic language in the DLR like IronRuby or IronPython.

 

You can check out Kirill Osenkov’s post for more info regarding this approach.

Another way which i think is the better way is using a third-party library that already support this like NCalc.

NCalc is an open source Mathematical Expression Evaluator for .NET that can parse any expression and evaluate the result, including static or dynamic parameters and custom functions.

Pretty cool huh?!

Just Released: Silverlight 4 Tools for VS 2010, new SL themes and WCF RIA Services

Just in case you missed it, Tim Heuer has announced that Silverlight 4 Tools for Visual Studio 2010, WCF RIA Services and 3 new SL themes have been released today. This is an exciting news for Silverlight aficionados who have been waiting for the RTM version of SL4 Tools since the last RC who are itching to put their hands on this new set of goodies.

If you want to learn more about SL, the best place to start is to go to Silverlight.net and checkout the Getting Started section. I would also suggest you follow Tim’s blog and subscribe to his updates and also as follow Silverlight Cream for the latest stream of info from SL developers.

If you are looking for Silverlight books for beginners my suggestion would be to get Laurent’s book (a SL4 edition will come out in September) and start from there. You should also checkout Jeff Pairies mind boggling book about Silverlight animation and also John Papa’s classic SL book that talks about data-driven services with Silverlight. Although some of these books are 1-2 versions behind I still believe that there are a lot of value in them that you can still apply with your Silverlight 4 projects.

I’ve just downloaded the package via the WPI
and I can’t tell you how much excited I am to see SL4T-4-VS2010 RTMed.
This will surely be a fun week.

Nice, time to rock this ship!

How To: Encrypt the ViewState in ASP.NET

Sometimes its the basic things that we tend to forget. It’s true. One example is encrypting the ViewState. Someone asked me this question today and I had to admit that I wasn’t able to answer on top of my head. Whats funny is that I’ve been doing it all along but never told myself to remember how.

Anyhow, lets go back to the topic on how to encrypt the ViewState in ASP.NET.

Prior to .NET 2.0 the way you would do this is via the machineKey element validation attribute. In .NET 2.0 onwards Microsoft provided us with an option to specify ViewState encryption in the page level or web.config level via the ViewStateEncryptionMode attribute.

ViewStateEncryptionMode has three enumeration values that you could use defending on what you need. They are Auto, Never and Always. ViewStateEncryptionMode.Auto means that the page will be encrypted if a control request for encryption. By default the value for ViewStateEncryptionMode is set to Auto. ViewStateEncryptionMode.Never means that ASP.NET will not encrypt the ViewState on your page even if a control request for it. This is a good bypassing mechanism if and only if you know that the page does not need to have ViewState encryption on it. ViewStateEncryptionMode.Always on the otherhand will encrypt your page all the time. A good practice for pages with sensitive information is to always set this ViewStateEncryptionMode to Always as you don’t want anybody compromising your ViewState.

To enable ViewState encryption in the page all you need to do is specify the value for ViewStateEncryptionMode at the Page directive

<%@Page ViewStateEncryptionMode=”Always” %>

To enable ViewState encryption via web.config to apply to the whole application

<configuration>
   <system.web>
      <pages ViewStateEncryptionMode=”Always” />
   </system.web>
</configuration>

One thing to remember though is that you can’t set ViewStateEncryptionMode via code

To request for ViewState encryption inside a control all you need to do is call RegisterViewStateEcryption() method from the Page class

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    if(Page != null)
    {
        Page.RegisterRequiresViewStateEncryption();
    }
}

Ahhh, such reverie. Now I need to remember this for future use (or questions). Cheers!