Thursday, April 12, 2012
#
When using Entity Framework 4.x Code First you can put your validation code in Data Annotations or inside the DbContext class (this is my preferred mode).
It’s possible to override the virtual method ValidateEntity exposed by the DbContext class and then define your own validation logic in one place.
This method is called once for each distinct entity being modified in your context, and it provides an opportunity for developers to stop the entity update process when some properties are in invalid state.
Here’s an example:
protected override DbEntityValidationResult ValidateEntity(
DbEntityEntry entityEntry,
IDictionary<object, object> items)
{
var errors = new DbEntityValidationResult(entityEntry,
new List<DbValidationError>());
if (entityEntry.Entity is Customer)
{
Customer customer = (Customer) entityEntry.Entity;
if (string.IsNullOrEmpty(customer.Lastname))
{
var error = new DbValidationError("Lastname",
"Lastname cannot be null or empty");
errors.ValidationErrors.Add(error);
}
}
if (errors.ValidationErrors.Count > 0)
return errors;
return base.ValidateEntity(entityEntry, items);
}
This code will be invoked only if the “ValidateOnSaveEnabled” property of the class DbContextConfiguration is set to true.
Thursday, March 29, 2012
#
This is my second post about my Entity Framework Code First usage experience. You can find my first post here.
The Entity Framework Power Tool is a must-have tool for those who use EF in Code First mode, especially with fluent API. With this tool you can reverse-engineering an existing data source and then generate both domain classes (POCO) and the mapping configuration files. The latter are generated by creating a class which inherits from EntityConfiguration<T>, where T is your domain entity type. The tools is able to understand all the existing relations in the database and to transform them in the correct relation mapping in code.
Thursday, March 22, 2012
#
Here are a few scattered notes on the use of Entity Framework 4.2 Code First:
- The core EF Api is contained in the System.Data.Entity.dll assembly
- The DbContext Object is a lightweight version of the ObjectContext object, the former provides more functionality than the first. If you need to get an ObjectContext instance starting from a DbContext instance you can use the IObjectContextAdapter interface for casting, as shown in the following example:
1: (myDbContext as IObjectContextAdapter).ObjectContext;
- The DbSet class is just a wrapper around the ObjectSet class
- A Complex Type has some limitations, the main are: a) it can expose only properties with primitive types b) it cannot be exposed as a multi-instance (collection)
- The EntityTypeConfiguration<T> class has an interesting method called WillCascadeOnDelete(bool), whose name makes the idea of the action it takes. Invoking this method with true parameter allows dependent data to be automatically deleted when main data is deleted, but you must pay attention to some aspects: a) it doesn’t work with optional relations but only with required relations b) The dependent data must be explicitly loaded into the context by invoking the “Include” extension method. If you don’t, there are no dependent data in memory and therefore no data will be deleted on database
- Table splitting requirements: a) entities must have a 1 to 1 relation b) entities must share a common key
- How a particular class is part of the EF context ? a) Because the context as a property DbSet<T> which reference that class b) Because the class is referenced by another class already tracked by the context c) Because you just inserted a configuration for that class and added to the model builder
- EF supports three mapping inheritance typologies a) TPH (table per hierarchy) => a base type and all its inherited types are mapped to a single database table with a discriminator column b) TPT (table per type) => There are distinct tables for base type and all its derived types. The tables for derived types contain only the additional fields exposed, while the common fields are mapped to the base type’s table c) TPC (table per concrete type), very similar to TPT. The only difference is that all derived type’s fields are stored in separate tables and not only the common ones. For guidance on which typology to choose depending on various scenarios, you can see this link
- EF Code First is based on conventions. Conventions are assumptions that can save developers from a lot of work when you define the mapping between domain classes and tables. For example, a convention states that the Id property of a class is also the primary key for that class. Conventions can be singly removed by code, as shown here:
1: modelBuilder.Conventions.Remove<IdKeyDiscoveryConvention>();
Tuesday, March 13, 2012
#
If your Entity Framework context is proxy-enabled, the runtime will create a proxy instance of your entities, i.e. a dynamically generated class which inherits from your entity class and overrides its virtual properties by inserting specific code useful for example for tracking changes and lazy loading.
The proxy instance has a dynamically generated name by the runtime that looks like this:
{System.Data.Entity.DynamicProxies User_00394CF1F92740F13E3EDBE858B6D599DFAF87AA5A089245977F61A32C75AA22}
(User is the original entity class name which the proxy class inherited from).
Starting from the proxy type, if you need to know the original type you have to use the static method GetObjectType of ObjectContext type, as shown in this example:
1: var userType = ObjectContext.GetObjectType(user.GetType());
Through the FullName property of the type returned by this method you can get the full name of the original type (User in this example)
Thursday, January 26, 2012
#
 | This is not the usual technical post that I generally write. Instead it is a post dedicated to my dear friend Nicola Gaeta, who has written a book about his passion (which is also my passion), the music. The book is called Una preghiera tra due bicchieri di gin, il jazz italiano si racconta published by Caratteri Mobili. It’s a very good book and very particular, it has not the classic narrative style but is a passionate collection of interviews conducted by Nicola to the greatest exponents of the Italian jazz about ambitious and very interesting topics, to which is not easy to answer. The question that has remained impressed to me is 'What is jazz?' Friend, if you have to ask it, you'll never know it (Louis Armstrong)” It’s an instinctive book written by a music passionate that plays anything in everyday work (like me too), it’s the book of a dear friend of mine who reminds me the happy times when I was back in high school (many years ago), and very often I avoid studying to listen to his not-to-missing musical broadcasts on a local radio. Enjoy your passion, Nicola. |
Thursday, January 19, 2012
#
This is the list of UgiAlt.Net sessions to be held next on next Saturday, Jan. 21 in Milan, I chose to attend
- WinRT e il futuro dello sviluppo per Windows
- SignalR. Code, not toothpaste. Using SignalR for realtime client/server communication
- oData può rappresentare il futuro del DataLayer?
See you there!
Friday, December 16, 2011
#
Next upcoming event of interest:

Friday, November 04, 2011
#
This is hard to believe, but is true:
Internet Explorer 7 & 8 will download stylesheets twice if the http(s) protocol is missing.
If you have a page with mixed protocol url request (i.e. a https page with tags “link” or “script” with http links), Internet Explorer displays a security warning like this:

This is a security warning which alerts the user that a web page requested by a security connection (https) contains web request using a non secure connection (http) as well. It’s not clear what is the answer that user must supply to this message to download both the secure and unsecure content. To make things more complicated, this answer is different between Internet Explorer version 7 and 8 (strange but true, too). In fact, in version 7 user had to click the “Yes” button (the default one), but in version 8 user would have to click “No” (it’s incredible, I know it, but it is so).
So, to avoid this confusion, it’s necessary avoiding mixed content on https requests, and this can be obtained using the short sintax for urls, that is a special sintax in which the protocol part of the url is missing, like this example:
//site.com/images/imageresource.jpg
Doing this browsers automatically use the same protocol as web page, and the problem seems solved, but Internet Explorer version 7 and 8, in this particular condition (missed protocol), download stylesheets twice, as you may easily notice using any software for capturing the http traffic, like HttpWatch
Hard to imagine, right ?
Wednesday, October 05, 2011
#
Oh yes I’ll be there…

Sunday, September 25, 2011
#
This extension method, applied to the object class and then available for all classes, allows to raise any events via reflection, providing as parameters the event name (as a string) and the TEvenArgs generic parameter.
public static void Raise<TEventArgs>(this object source, string eventName,
TEventArgs eventArgs) where TEventArgs : EventArgs
{
var eventInfo = source.GetType().GetEvent(eventName,
BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.Instance);
var eventDelegate = (MulticastDelegate)source.GetType()
.GetField(eventName, BindingFlags.Instance
| BindingFlags.NonPublic).GetValue(source);
if (eventDelegate != null)
{
foreach (var handler in eventDelegate.GetInvocationList())
{
handler.Method.Invoke(handler.Target,
new object[] { source, eventArgs });
}
}
}
Example of use:
CustomerViewModel vm = new CustomerViewModel();
vm.Raise("PropertyChanged", new PropertyChangedEventArgs("Name"));
Source for code in this example
Tuesday, June 28, 2011
#
If you host a WCF service on a machine with UAC enabled, Vista or Win7 for example, you might run into this seemingly strange exception:

The reason is due to the fact that to host a WCF service you need to register its url, and this task requires administrator privileges, and this means as well that if you run Visual Studio as Administrator everything works fine, but what if you don’t have this possibility ? Or how to register an URL for it to work ?
If you follow the link mentioned in the error message you waste your time because the resulting link is too general for this specific error. I used this approach: I downloaded HttpNamespaceManager, a little and nice open source utility (not an official Microsoft tool), also provided with source code, that just does this, register an URL even assigning permissions to users.
After the URL registration your service will work fine.
Starting from WCF 4.0 it’s possible to use a default endpoint in absence of explicit configuration. This means that you can avoid to configure an explicit endpont because of a default mapping between protocol schema and bindings described in the configuration file machine.config.
Here is the default content of that mapping:
<protocolMapping>
<clear />
<add scheme="http" binding="basicHttpBinding"
bindingConfiguration="" />
<add scheme="net.tcp" binding="netTcpBinding"
bindingConfiguration="" />
<add scheme="net.pipe" binding="netNamedPipeBinding"
bindingConfiguration="" />
<add scheme="net.msmq" binding="netMsmqBinding"
bindingConfiguration="" />
</protocolMapping>
For example, in the case of presence of “http” in the protocol, it will be used the default binding “basicHttpBinding” without the need to configure an endpoint explicitly.
Now, to test this new feature all you need is to create a simple service without an explicit endpoints configuration and then read hits configuration such as the following example:
using (ServiceHost host = new ServiceHost(typeof(MyService))
{
host.Open();
foreach (ServiceEndpoint end inhost.Description.Endpoints)
{
Console.Write("Address:{0}\nBinding:{1}\n", end.Address,
end.Binding.Name);
}
}
This code in .Net Framework 4.0 will work fine, while .Net 3.5 would have required the endpoint configuration
Monday, June 06, 2011
#
If it happens this strange and cryptic error in Visual Studio 2010 while compiling any project:
“The exec task needs a command to execute”
the reason is this: in any pre or post build event, there is a carriage return character to remove, because Visual Studio 2010 poorly digested the carriage return characters in 'text editor pre-post build events.
Friday, May 27, 2011
#
- Using HTML5’s New Semantic Tags Today
- Ncqrs, framework for .NET
helps build scalable, extensible and maintainable applications by supporting developers apply the CQRS architectural pattern.
- LINQ to LDAP
LINQ provider built on top of System.DirectoryServices.Protocols for querying LDAP servers
Wednesday, March 16, 2011
#
With jQuery you are able to invoke an action of a Asp .Net MVC application's controller.
This is the code you need:
1: $.ajax({
2: url: 'Controller/Action?parameter1='+parametervalue,
3: parameter1: parametervalue,
4: type: 'GET',
5: async: false,
6: cache: false,
7: success: function(data){
8: alert('Action called successfully');
9: }
10: });
You can establish the request type (GET, SET and so), whether the request should be asynchronous or not (parameter async true or false), whether the request should be cached or not (parameter cache), a Javascript function to be called in case of success of the server request (parameter success) or in case of request fails (parameter error).
The parameter "data" of the function called in case of success contains the return value by the server call.
However there are many others useful parameters you can use. For a complete list go here. It's also possible to make the same call but with a Json return value by the $.getJSON funtion.
Wednesday, March 09, 2011
#
Thursday, January 27, 2011
#
dotNetTips.Utility 4.0 R1
Very interesting Open Source .Net Library with a lot of utility code ready to use !
Great job.
You can download it from here.
Monday, January 24, 2011
#
I added a Creative Commons License to this blog.
In short, you are able for free to copy, distribute and transmit the work (to share), to adapt the work (to remix),
but you must attribute this work to Maurizio Tammacco.
You can find how to attribute this work in the link visible to the right.
.NET Extensions - Extension Methods Library for C# and VB.NET- Release 2011.03
- Combres
.NET library which enables minification, compression, combination, and caching of JavaScript and CSS resources for ASP.NET and ASP.NET MVC web applications. Simply put, it helps your applications rank better with YSlow and PageSpeed
- Migliorare le performance di una applicazione ASp .Net MVC
Excellent Dario Santarelli’s post (in Italian) full of various links in order to optimize performance of ASP .Net MVC applications
- MVC Music Store
MVC Music Store is a tutorial application built on ASP.NET MVC. It's a lightweight sample store which sells albums online, demonstrating ASP.NET MVC's productivity features and data access via Entity Framework 4. See what you can do with MVC in under 1000 lines of c# code!
HttpWatch 7.1
HttpWatch is an integrated HTTP sniffer for IE and Firefox that provides new insights into how your website loads and performs. And also Basic Edition is FREE
Monday, January 03, 2011
#
The last of SOLID principles about OOD is known as Dependency Inversion Principle (DIP).
This principle says that:
High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend upon details. Details should depend upon abstractions.
This principle, with the OCP principle already discussed, are intended to make software application loosely coupled. This feature is achieved by removing as much as possible dependencies between higher level modules (those usually more general) and the low-level modules (those usually more specific). In fact, usually in conventional application architecture, the high level modules use the functionality exposed by low-level modules using direct references to the latter, thus creating a strong coupling between them.
This coupling results in any change of low-level modules, also lead inevitably change of high-level, and this situation is certainly not desirable.
So instead of depending directly on low-level modules, the high-level modules should depend on abstractions, such as interfaces or abstract classes. In this way if you change some details behind those abstractions the high level modules remain unchanged as they depend on abstractions (interfaces).
The term "inversion"means that by applying this principle the direction of the dependency is reversed because the high-level modules do not depend on low-level modules buy they depend on abstractions, as well as the implementation details.
Moreover, as the abstractions raise a "wall" between the different levels, any changes can not propagate everywhere, but there are only confined within the module to which these changes belong logically.
The latter is a fundamental prerequisite so that software applications are easily maintainable.
You can find an implementation of DIP in Dependency Injection Pattern or in the Inversion of Control.
In fact there is some confusion around these terms and many people use them interchangeably, both refer to the principle or refer to patterns, but the fact remains that the inversion of control or dependency injection is an implementation of DIP.
Just to add to the confusion
the Hollywood Principle is just another way of calling the Inversion Of Control.
Wednesday, December 22, 2010
#
- Abstract SQL
ADO.NET Sql classes wrapper; provides a clean fluent interface library that allows you to write very concise code and avoid the repetitiveness of ADO.NET. It can be used in all types of applications, even supports CLR stored procedures. It is written in C# 2.0.
- Gridify for ASP .NET MVC
Easy solution for grids on top of ASP.NET MVC
Make grids from your data tables in a really lightweight manner! How lightweight? Well, exactly TWO line changes. You don't have to add new action parameters or anything. Really simple!
- Paypal adaptive payments using .Net (C#)
This is a C# project to help you interface with the PayPal adaptive payments API.
- In The Box
In the Box is a high quality, multi-media training that is consumed within Visual Studio 2010. Content is navigated and delivered using a next generation computer based training (CBT) experience, the Visual Studio 2010 Feature Extension
- ASP .Net 4.0 Code Samples Collection
- 10 Essential Tools to build ASP .Net Websites
- TweetSharp
TweetSharp is the most complete, and most effective client library for communicating with Twitter. TweetSharp works how you want to: simple service, fluent interface, or LINQ provider. It's designed so that you write less, and get more, from Twitter's API.
- Team Foundation Server Administration Tool 2.1
TFS Administration Tool 2.1, is the first version of the TFS Administration Tool which is built on top of the Team Foundation Server 2010 object model. TFS Administration Tool 2.1 can be installed on machines that are running either Team Explorer 2010, or Team Foundation Server 2010.
- Visual Studio 2010 Code Samples 2010-12-13
- How to write fluent interface with C# and Lambda
Tuesday, December 07, 2010
#
The Interface Segregation Principle (ISP) is another principle about OOD.
It simply states that:
“CLIENTS SHOULD NOT BE FORCED TO DEPEND UPON INTERFACES
THAT THEY DON’T USE”
If we return back to the first OOD principle, the Single Responsibility Principle, it can be said that this principle should also apply to interfaces or to abstract class, in addition to the concrete classes.
Therefore, one interface should mean one responsibility, without creating the so-called “fat interfaces”, i.e. interfaces that contain too many methods/properties that relate to more than 1 responsibility.
To find an example of violation of this principle does not need to go too far, just peek inside the .Net framework itself
.
If we take a look inside the abstract class MembershipProvider, which is the class which all providers, default and custom, inherit from, we’ll be looking at 28 abstract methods, which must be provide an implementation in case of creation of custom membership provider.
1: public abstract void Initialize(string name,
2: NameValueCollection config)
3: public abstract string ApplicationName { get; set; }
4: public abstract bool EnablePasswordReset { get; }
5: public abstract bool EnablePasswordRetrieval { get; }
6: public abstract bool RequiresQuestionAndAnswer { get; }
7: public abstract bool RequiresUniqueEmail { get; }
8: public abstract int MaxInvalidPasswordAttempts { get; }
9: public abstract int PasswordAttemptWindow { get; }
10: public abstract MembershipPasswordFormat PasswordFormat { get; }
11: public abstract int MinRequiredNonAlphanumericCharacters { get; }
12: public abstract int MinRequiredPasswordLength { get; }
13: public abstract string PasswordStrengthRegularExpression { get; }
14: public abstract bool ChangePassword(string username,
15: string oldPwd, string newPwd)
16: public abstract bool ChangePasswordQuestionAndAnswer(
17: string username, string password, string newPwdQuestion,
18: string newPwdAnswer)
19: public abstract MembershipUser CreateUser(string username,
20: string password, string email, string passwordQuestion,
21: string passwordAnswer, bool isApproved, object
22: providerUserKey, out MembershipCreateStatus status)
23: public abstract bool DeleteUser(string username,
24: bool deleteAllRelatedData)
25: public abstract MembershipUserCollection GetAllUsers(int pageIndex,
26: int pageSize, out int totalRecords)
27: public abstract int GetNumberOfUsersOnline()
28: public abstract string GetPassword(string username, string answer)
29: public abstract MembershipUser GetUser(string username,
30: bool userIsOnline)
31: public abstract MembershipUser GetUser(object providerUserKey,
32: bool userIsOnline)
33: public abstract bool UnlockUser(string username)
34: public abstract string GetUserNameByEmail(string email)
35: public abstract string ResetPassword(string username,
36: string answer)
37: public abstract void UpdateUser(MembershipUser user)
38: public abstract bool ValidateUser(string username,
39: string password)
40: public abstract MembershipUserCollection FindUsersByName(
41: string usernameToMatch, int pageIndex, int pageSize,
42: out int totalRecords)
43: public abstract MembershipUserCollection FindUsersByEmail(
44: string emailToMatch, int pageIndex, int pageSize,
45: out int totalRecords)
46:
47:
This methods has to do with authentication, persistence, retrieve of user based on various criteria, password management, and so on.
All these abstract methods must be implemented even if the client code that uses the feature is only interested in some of these aspects mentioned above.
In this way, the methods that you do not care end up being defined as follows:
1: public override int GetNumberOfUsersOnline()
2: {
3: throw new NotImplementedException();
4: }
This approach has several problems, including:
- Indirect and especially useless coupling between clients that use the functionality. If additional functionality is required, all clients must be modified, even those not interested in new features;
- Clients are misled because some methods explicitly raise an exception;
- Code maintenance is more difficult;
Wednesday, December 01, 2010
#
The Liskov Substitution Principle (LSP) is another principle that has to do with software design and namely with inheritance.
This principle takes its name from Barbara Liskov, U.S. scientist in computer science.
This principle simply states that
“CLASSES THAT USE REFERENCES TO BASE CLASSES MUST BE ABLE TO USE OBJECTS OF DERIVED CLASSES WITHOUT KNOWING IT"
In other words, if we have a class (say Class C) that use a reference to a base class inside (Class B), then Class C MUST be able to use a reference with ANY derivate class of Class B (present and future), without knowing it and especially without changing the logical behaviour.
It 's very easy to violate this principle when overriding virtual methods defined in a base class.
Let's consider an example like this:
1: public class BaseClass
2: {
3: protected double n1;
4: protected double n2;
5:
6: public BaseClass(double a, double b)
7: {
8: this.n1 = a;
9: this.n2 = b;
10: }
11:
12: public virtual double Multiply()
13: {
14: return this.n1 * this.n2;
15: }
16: }
This class simply accepts 2 double numbers by it’s constructor, and by a virtual method returns the two numbers multiplied together.
Now, let’s create a derived class like this:
1: public class DerivedClass : BaseClass
2: {
3: const double COEFFICIENT = 1.1;
4:
5: public DerivedClass(double a, double b)
6: : base(a, b) { }
7:
8: public override double Multiply()
9: {
10: return base.Multiply() * COEFFICIENT;
11: }
12: }
This class is derived by the first one and simply overrides the virtual method “Multiply” defining another implementation of it where the result of the multiplication is further multiplied by a fixed coefficient.
Therefore, having a method that takes a reference to BaseClass, like this:
1: public double DoSomeWork(BaseClass b)
2: {
3: return b.Multiply();
4: }
we can pass as a parameter any derived class, as in the example below:
1: BaseClass b = new BaseClass(-5, 20);
2: double result = DoSomeWork(b);
3: Console.WriteLine(result);
4:
5: DerivedClass d= new DerivedClass(-5, 20);
6: double result2 = DoSomeWork(d);
7: Console.WriteLine(result2);
Very trivial, right ? And everything works fine.
But when you develop your derived class and specifically when the virtual method is redefined, you must pay attention to some situations that, if they occur, involving the violation of the Liskov substitution principle. Specifically, a general rule to keep in mind is that a derived class should *not* require additional conditions or either provide fewer conditions than those required by the base class.
For example, what would happen if you change the redefinition of the method Multiply in this way ?
1: public override double Multiply()
2: {
3: if (this.n1 < 0)
4: throw new InvalidOperationException(
5: "Number n1 cannot be negative");
6:
7: return base.Multiply() * COEFFICIENT;
8: }
The overridden method adds an additional condition, namely that the parameter n1 cannot be negative by raising an exception, and then is demanding something more than its base class that takes two double numbers instead through its constructor, also providing negative numbers. This additional condition required makes the base class and derived class not interchangeable anymore and therefore the Liskov Substitution Principle is violated.
The LSP can be violated in different ways, but everyone has to do with inheritance. Therefore you must take extreme care when you redefine virtual methods.
Monday, November 29, 2010
#
Friday, November 26, 2010
#
In this post I will speak about the second principle of Object Oriented Design (OOD), i.e. the Open-Closed Principle (OCP). in addition to the first one (SRP) which I have already spoken in my previous post.
This principle was coined by Bertrand Meyer, the same person who coined the term "design by contract", to which I devoted an article that you can view on the UgiDotNet site.
This principle simply states that software entities, i.e. class, "should be opened for extensions but closed for modifications".
Now, what does it really means ?
We all know that code changes according to changing requirements. When we design a module software, we design it according to certain requirements valid at the time. When requirements change we should be able to extend that software module, i.e. add new features in addition to existing ones, and the latter should not be changed for any reason.
In other words, when we create a module with certain features, that module must be immutable, and immutable means stable.
This principle apparently shows a contradiction: how can something that is immutable be subject to extensions, and then ultimately to change?
The answer lies in the use of abstract classes or interfaces. In fact, you can see it from this point of view: an interface or an abstract class, once created and established the methods and properties with their signatures, must be unalterable, but you can create different concrete classes which implement that interfaces and abstract classes, and then different implementations, and then modify or extend their behavior leaving the contract intact.
In this way, the software module is closed for modifications (the interface doesn't never change), but is also open for extensions as you can create different implementations.
This principle would imply another principle: it's necessary to design on interface and not on concrete implementations, otherwise the OCP would inexorably violated.