Entity Framework: Update single column

Yesterday I blogged about how to delete a detached entity using Entity Framework 5 by only using its Id. A common practice in many applications today is to not actually delete the entity from the database, but instead mark it as deleted and make sure your data access layer filters out those “deleted” items when selecting. So I wanted to implement a general “delete” method that would update the DateDeleted column of an entity without touching any other column. Again I use a detached entity, so the trick is to only mark the DateDeleted column as modified, and not the entire entity. public bool DeleteEntity(T entity) where T : ModelBase { entity.DateDeleted = DateTime.UtcNow; this._databaseContext.Set().Attach(entity); this._databaseContext.Configuration.ValidateOnSaveEnabled = false; this._databaseContext.Entry(entity).Property(m => m.DateDeleted).IsModified = true; int recordsAffected = this._databaseContext.SaveChanges(); this._databaseContext.Configuration.ValidateOnSaveEnabled = true; return recordsAffected == 1; } Notice how I disable validation, and … Continued

Entity Framework: Delete Entity by Id – Using Detached Instance

Entity Framework 5, with the Code First approach can do some pretty powerful things without much effort. Create your model classes, and it spins up a brand new and shiny database for you. But sometimes you do need to tweak a few things in order to achieve what you want. For example, I don’t want to load an entity before I can delete it. What’s the point? Say I have a list of Accounts on a webpage, with a shiny delete button that makes an AJAX call to an MVC controller, (or Backbone model, that hits the web backend). In that situation I’ll only have the Id of the entity, which should be enough to delete it. Attach, Delete To delete only by Id, you need to create a dummy instance of your model with the Id you wish to … Continued

Use Recurly.js with ASP.NET (MVC), C# with this Nu Get library

Recurly is a full suite recurring payment service that lets you easily create subscription plans, billing cycles, handle customers, revenue etc. They made payment integration dead easy with their awesome JavaScript library called Recurly.js that you can use to inject a payment form onto any page with a simple piece of JavaScript, a long with a server generated signature. But .Net as a platform, and C# as a language is not very well supported by Recurly. They don’t event provide a client library for creating those signatures. I needed a client library and wrote this simple class that I’ve now uploaded to Nu Get. The package is called RecurlyJS, and the source code is on GitHub. Enjoy!

Make CSS inline in C# and ASP.NET using PreMailer.Net

Being able to make CSS inline is something you need all the time when sending HTML e-mails. HTML E-mails simply don’t render perfectly in all e-mail clients if you don’t make all your styles inline. Campaign Monitor introduced the ability to make CSS inline years ago, and it just works. They use the premailer Ruby project to do this, and it seems to work perfectly. You can edit your HTML e-mails using styles embedded inside the HTML document’s <head> tag, and they automatically make the CSS inline on all elements that match your selectors. At the end of my latest blog post on How to Send HTML E-mail from an ASP.NET MVC Controller, I wrote that I’d like to combine the ActionMailer.Net library with the premailer Ruby project, to be able to send great HTML e-mails from an application, that renders well in … Continued

Serialize C# dynamic and Anonymous types to XML

Dynamic / Anonymous types in C# was a great improvement to the framework, made in version 3.0. I use it a lot when doing AJAX callbacks from JavaScript to ASP.NET MVC Controllers, not to forget the extensive use of anonymous types already used in ASP.NET MVC. Then yesterday, one case where I absolutely needed to use anonymous types was in my application’s logging service. I want to be able to save behaviors/actions as well as errors. I have two separate tables, but both behaviors and errors can provide a set of details. To do the actual logging, I call an implementation of this interface: /// <summary> /// Defines methods for logging errors and behavior. /// </summary> [ServiceContract] public interface ILogService { /// <summary> /// Logs the behavior with data. /// </summary> /// <param name=”applicationInstanceId”>The application instance id.</param> /// <param name=”action”>The … Continued

Making your ASP.NET Global Resource files work in JavaScript. IntelliSense included!

Any modern web application needs localization! You simply can’t ignore the huge amounts of people who doesn’t speak your language, or whose native language is different from yours. You’re probably using resource files (.resx) in .NET, but how do you go about getting values from your resource files in JavaScript? Rick Strahl wrote a great blog post about an HttpHandler that serves the content of your resource files in JavaScript. You basically add a script tag to your page that points to the HttpHandler, and the HttpHandler will produce the resources in JavaScript as an object with properties on it, like this: [code lang="js"]var localRes = { AreYouSureYouWantToRemoveValue: "Sind Sie sicher dass Sie diesen Wert l\u00F6schen wollen?", BackupComplete: "Der Backup f\u00FChrte erfolgreich durch", BackupFailed: "Der Backup konnte nicht durchgef\u00FChrt werden", BackupNotification: "Diese Operation macht einen Backup von der Lokalisationtabelle. \nM\u00F6chten … Continued

Translate text in C#, using Google Translate, revisited

A long time ago, I wrote a blog post about how to translate text in C# using Google Translate. Since then, an official AJAX API has been released, which is a much better solution. Reading the comments of the blog post indicates that the code was broken quite quickly! Google’s AJAX Language API, also includes functionality to detect language from a given string. All you can do on translate.google.com you can do via the API. Reading the class reference for the Translation API, for Flash and other Non-Javascript environments gives us the information we need to perform translations from C#. Most important is the URL and the parameters required and accepted. Another very important thing we can read in the documentation is this: Applications MUST always include a valid and accurate http referer header in their requests We must remember … Continued

Generate HTML e-mail body in C# using templates

Almost a year ago, I answered a question on StackOverflow, about if there’s a better way to generate HTML e-mails in C# than using a StringBuilder and just appending strings one by one. I think that any modern piece of software today, needs to send e-mail. Whether it being password recovery e-mails, rich reports, newsletters or anything else – being able to easily see and customize the look and feel of your e-mails is vital. So, the worst way I could think of is having your HTML hidden away in some StringBuilder.Append() hell. The best solution (in my opinion) would be, if you could have plain old HTML files with parameters like <#FirstName#> so you could dynamically replace those at runtime. The MailDefinition class Luckily, there’s a class for that! If you read the comments on my answer on StackOverflow, … Continued

Unit test for verifying references from DataAnnotation validation to the ErrorMessageResourceName value

I love the new model validation features in System.ComponentModel.DataAnnotations. One thing I don’t like though, is that the ErrorMessageResourceName is loosely typed. The ErrorMessageResourceType, however, is a System.Type which will be strongly typed by assigning its value using the typeof(Namespace.ResourceSetType) method. Since there’s no build-breaking reference between a resource file and the value of the ErrorMessageResourceName on all classes where you use it, I thought it would be cool to have a unit test that verifies the existence of all referenced resource keys. Remember to add a reference to System.ComponentModel.DataAnnotations. Code /// <summary> /// Verifies that all properties that are decorated with validation data-annotations, refers to /// an existing resource. This will make sure, that missing resources are not referenced. /// </summary> [TestMethod] public void All_Properties_With_Validation_Annotations_Must_Refer_To_Existing_Resource() { Assembly assembly = Assembly.Load(new AssemblyName(“MyApp.Model.Namespace”)); var types = assembly.GetTypes().Where<Type>(t => t.IsClass && !t.IsAbstract); … Continued

Multiple SSL certificates on IIS using host headers

In IIS SSL sites have seemed to be limited to only one site per network interface, since you (from IIS Manager) cannot specify a host header binding on the HTTPS protocol. It turns out, that it is only a limitation in the UI. So to have e.g. two sites with their own dedicated SSL certificate we need to add a host header binding on port 443 from either appcmd, managed code or by editing the applicationHosts.config file. I like managed code the most, so I’ve written a small method in C# that does the trick. You need to have two SSL certificates named www.ssl1.com and www.ssl2.com installed on the machine. I just created a self signed certificate for both of them using the IIS Manager. using System.Security.Cryptography.X509Certificates; using Microsoft.Web.Administration; namespace IisSsl { class Program { static void Main(string[] args) { … Continued