NRW Conf 2011 community conference: The doors are open

Since the year 2005 the non-commercial organization JustCommunity e.V. organises once a year the NRW Conf community event. Over the time it has become one of the biggest community events in Germany. This years conference will be on the 8th and 9th of September located in Wuppertal, Germany. We will host over 20 speakers and sessions from Germany and Europe, and as last year there will be a workshop day upfront: ASP.NET MVC SCRUM PowerShell Last but not least let me throw in some buzzwords, before you head over to the registration: Windows Phone 7.5, Agile, SQL Server, ASP.NET MVC, REST, Windows Azure, Rails, SCRUM, Powershell, Sharepoint, Oracle, Kinect, MS Office, Git, Performance-Analysis, TMG, UAG, FEP, FPE, FSSP, FPSMC, FIM, FOPE. Click here to sign up…

Settings in Silverlight

A few months ago I was developing a Silverlight Line of Business Application with a customer when I stumbled across the requirement to store some information over multiple user sessions - user works with the app, closes the browser and reopens the browser and works with the app again. My first idea was to store the info in a cookie. It all worked out fine until I started to enable the localization using the culture/uiculture param. Setting these results in just the culture values are found in the cookie (Ahmmm… could anybody fix this please). The other option (the only one left) is to use the isolated store. It’s a few lines more to code than using a cookie (the reason this was my second shot) but gives you the advantage of e.g. Silverlight 3.0 out-of-browser-experience support. I was just about to add a new item to my solution – while I was awaiting the dialog to come up – when I wondered how a developer could easily define and edit settings. Some Visual Studio support would be great. The default resources dialog for example… wait … wasn’t there some settings feature in desktop apps since .NET 2.0? Yep, it’s called “Settings”. It’s exactly what I wanted – even more as you can store values at machine level, which cannot be achieved using Silverlight (currently?). It has an item template to easily add it to a project. it has a nice UI. It has a code generator. It has developer experience. … but it has no support for Silverlight. So I had a look at what is in the *real* .NET Framework. I identified a few necessary classes and their members to get settings up and running in Silverlight. I fired up the IDE again and started to write the following classes: ApplicationSettingsBase – The abstract base class for generated settings classes. DefaultSettingsValueAttribute – The attribute used to define a default value. UserScopedSettingAttribute – The attribute used to differentiate a user setting from machine wide settings.   using System.Collections.Generic; using System.IO; using System.IO.IsolatedStorage; using System.Reflection; using System.Xml; namespace System.Configuration { public abstract class ApplicationSettingsBase { … } public class DefaultSettingValueAttribute : Attribute { public object Value { get; set; } public DefaultSettingValueAttribute(object value) { Value = value; } } public class UserScopedSettingAttribute : Attribute { } } The settings values will be stored in a static dictionary. The values can be accessed through the indexer that just forwards the call to the dictionary. private static readonly Dictionary<string, object> s_values = new Dictionary<string, object>(); private static readonly object s_valuesLock = new object(); Since Silverlight 3 supports threads we ensure the thread safe write access to the dictionary inside the indexer through the lock statement. protected object this[string key] { get { return s_values.ContainsKey(key) ? s_values[key] : null; } set { lock (s_valuesLock) { if (s_values.ContainsKey(key)) { s_values[key] = value; } else { s_values.Add(key, value); } } } } The dictionary is filled using the static method named “Syncronized”, which is called form the class that is generated by the “SettingsSingleFileGenerator” code generator. public static ApplicationSettingsBase Synchronized( ApplicationSettingsBase instance) { lock (s_valuesLock) { s_values.Clear(); var type = instance.GetType(); var properties = type.GetProperties( BindingFlags.Public | BindingFlags.Instance); var attributeType = typeof (DefaultSettingValueAttribute); for (var i = 0; i < properties.Length; i++) { var attributes = properties[i].GetCustomAttributes( attributeType, true); if (attributes == null) continue; var defaultAttributes = (DefaultSettingValueAttribute[]) attributes; s_values.Add( properties[i].Name, defaultAttributes[0].Value); } LoadFromIsolatedStore(); return instance; } } It gets all default values defined by the developer by utilizing reflection, on the “DefaultValueAttribute” which decorates the properties in the generated class, on the generated class. Here is an example of a property, how it can be found in a generated settings class. [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("anonymous")] public string UserName { get { return ((string)(this["UserName"])); } set { this["UserName"] = value; } } After the default values have been assigned the method sets up a call to “LoadFromIsolatedStore”. This is the functionality that loads any persisted settings from the isolated storage. This is the point, where it comes to the question: which format do I store the information in? I’ve chosen the format of the *real* settings file (the one that is a feature for desktop apps) not of its simplicity (cough) but for the sake of compatibility. Here is an example: <?xml version='1.0' encoding='utf-8'?> <SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="Xyz" GeneratedClassName="Settings"> <Profiles /> <Settings> <Setting Name="UserName" Type="System.String" Scope="User"> <Value Profile="(Default)">anonymous</Value> </Setting> </Settings> </SettingsFile> The next step is to read this format from a file stream located in the Silverlight isolated storage. The isolated store can be found (starting from Windows Vista) below the directory path (based on the drive where the OS is installed) “C:\Users\{username}\AppData\LocalLow\Microsoft\Silverlight\is\”. private static void LoadFromIsolatedStore() { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { if (!store.FileExists(SettingsFile)) return; using (var fileStream = store.OpenFile(SettingsFile, FileMode.Open)) { When it comes to reading, writing or manipulating XML I personally prefer the XmlReader/XmlWriter over the XmlDocument because of the memory consumption – even if has not a lot to do with Object Oriented Programming (welcome to structural world again…) and it does not make such a strong matter on the client. using (var reader = XmlReader.Create(fileStream)) { while (reader.Read()) { if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "Setting") continue; var name = string.Empty; var type = string.Empty; while (reader.MoveToNextAttribute()) { switch (reader.LocalName) { case "Name": name = reader.Value; break; case "Type": type = reader.Value; break; default: break; } } To get the required information, as for instance the type of the property, the first loop (inside the read()-loop) goes through the attributes. while(reader.NodeType != XmlNodeType.Element && reader.LocalName != "Value" && reader.Read()) { while (reader.Depth >= 3 && reader.Read() && reader.NodeType != XmlNodeType.Text) { } if (reader.NodeType != XmlNodeType.Text) { break; } object value = null; switch (type) { case "String": case "System.String": value = reader.ReadContentAsString(); break; … default: throw new InvalidOperationException( string.Concat( "Type \"", type, "\" is not supported as a " + "settings value.")); } After that we convert the read value to its intended type and add or update the setting to the static dictionary. if (value != null) { if (s_values.ContainsKey(name)) { s_values[name] = value; } else { s_values.Add(name, value); } } Last but not least changed Values need to be persisted. To keep the number of writes small and under control I implemented a method called “Persist” that writes all values to the settings file in the isolated storage of Silverlight. public void Persist() { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { if (store.FileExists(SettingsFile)) { store.DeleteFile(SettingsFile); } using (var fileStream = store.OpenFile(SettingsFile, FileMode.CreateNew)) { using (var writer = XmlWriter.Create(fileStream)) { if (writer == null) return; writer.WriteStartDocument(); { writer.WriteStartElement( "", "SettingsFile", "http://schemas.microsoft.com/" + "VisualStudio/2004/01/settings"); writer.WriteAttributeString( "CurrentProfile", "(Default)"); writer.WriteAttributeString( "GeneratedClassNamespace", "http://schemas.microsoft.com/" + "VisualStudio/2004/01/settings"); writer.WriteAttributeString( "GeneratedClassName", "Settings"); { writer.WriteStartElement("Profiles"); writer.WriteEndElement(); writer.WriteStartElement("Settings"); { foreach (var key in s_values.Keys) { writer.WriteStartElement("Setting"); writer.WriteAttributeString( "Name", key); writer.WriteAttributeString( "Scope", "User"); writer.WriteAttributeString( "Type", s_values[key] == null ? "System.String" : s_values[key].GetType().FullName); { writer.WriteStartElement("Value"); writer.WriteAttributeString( "Profile", "(Default)"); writer.WriteString( (string)s_values[key]); writer.WriteEndElement(); } writer.WriteEndElement(); } } writer.WriteEndElement(); } writer.WriteEndElement(); } writer.WriteEndDocument(); } } } } This allows us to have (at least from the API) a standard way of storing settings in Silverlight. I hope that Microsoft picks “settings” as a feature for the next Silverlight Version…. That’s all folks!

ASP.NET MVC 3: German Web Casts Series

Heute sind die ASP.NET MVC 3 Web Casts die ich machen durfte online gegangen: ASP.NET MVC ist Teil des ASP.NET Framework; Anfang 2011 ist die Version 3 des ASP.NET MVC erschienen. Diese Webcast-Reihe führt in das Entwurfsprinzip des Model View Controller-Schema (MVC) ein. ASP.NET MVC (Teil 1 von 3) – Fundamentalshttp://www.microsoft.com/germany/msdn/webcasts/library.aspx?id=1032481618 ASP.NET MVC (Teil 2 von 3) - Views & Layouts mit Razorhttp://www.microsoft.com/germany/msdn/webcasts/library.aspx?id=1032481619 ASP.NET MVC (Teil 3 von 3) - Forms, Binding & Validationhttp://www.microsoft.com/germany/msdn/webcasts/library.aspx?id=1032481620

Regions are like knives

Most people state that regions are bad. I prefer a more fine grained definition: Regions in code are like knives. They can cause serious injury. But a surgeon can use one to do good. What are region intended for? Regions provide you the ability to expand and collapse code. You can do this with members, classes and namespaces without a region. The difference is that the region keeps the collapsed state when opening a file. The ugly There are a few problems with regions like merging in source control or the growth of classes but these are not my main pain points. Most times I stumble across region they are used in a bad manor. On a code review today this is what showed up in the editor: What is so bad about it? Well I like to read code and believe that reading code is really important. Therefor readability of code is important to me. It increases the maintainability. Lowers the times to understand and extend or refactor code. In short: Things that make me happy. The regions showed force me to do unnecessary stuff, before I can read the code – I need to expand the regions, otherwise: I can’t see what members are contained in the class. I can’t read the names of the members that tell me what they do/the code does (Yes, I know – I assume that developers read the C# coding guidelines and name their stuff by using their brain). You could argument that VS has this nice little thing that shows all members in a drop down list on the upper right corner of the editor. But I don’t want to read code in a drop down list, sorry. I use regions Despite of the many things on the negative side, I like regions and I use them. I believe that regions can even give you a plus on the pain point I described. I create regions to decrease the time somebody needs to read or understand code. For me a region is an abstraction. And as we all know also abstraction can be good as well as bad is used wrong. Abstracting code by wrapping member types together is contra-productive because I don’t care for instance what members are in the class. That’s only a technical perspective. On the opposite an increased productivity can be achieved by providing a layer that shows the skeleton or structure of the class. This way I can see what’s in the class from a functional perspective. If I now want to drill down into the code (after I already know what’s there) I’m forced to react. That is o.k. and my intention because the regions give me an overview and do not hide almost everything.  

Do not debug on daylight saving time switch

  WTF? Solution: Unmark the auto adjustment EDIT: While I blogged this I had the same issue on my blog. Here is the snapshot of the event log Event code: 3005 Event message: An unhandled exception has occurred. Event time: 10/31/2010 2:11:48 AM Event time (UTC): 10/31/2010 12:11:48 AM Event ID: 2da507c58aa84c7b8ed29e8fbf3908bc Event sequence: 496 Event occurrence: 9 Event detail code: 0  Application information:     Application domain: /LM/W3SVC/4/ROOT-1-XXXXXXXXXXX     Trust level: Full     Application Virtual Path: /     Application Path: X:\xxxxxxx\lennybacon.com\www\     Machine name: DEVPLEXHQ  Process information:     Process ID: 4212     Process name: w3wp.exe     Account name: NT AUTHORITY\NETWORK SERVICE  Exception information:     Exception type: ArgumentOutOfRangeException     Exception message: Specified argument was out of the range of valid values.Parameter name: utcDate  Request information:     Request URL: http://lennybacon.com/FormatPage.aspx?path=SiteConfig/pageerror.format.html     Request path: /FormatPage.aspx     User host address: XX.XX.XX.XX    User:      Is authenticated: False     Authentication Type:      Thread account name: NT AUTHORITY\NETWORK SERVICE  Thread information:     Thread ID: 18     Thread account name: NT AUTHORITY\NETWORK SERVICE     Is impersonating: False     Stack trace:    at System.Web.HttpCachePolicy.UtcSetLastModified(DateTime utcDate)   at System.Web.HttpCachePolicy.SetLastModified(DateTime date)   at newtelligence.DasBlog.Web.Core.SiteUtilities.GetStatusNotModified(DateTime latest)   at newtelligence.DasBlog.Web.Core.SharedBasePage.NotModified(EntryCollection entryCollection)   at newtelligence.DasBlog.Web.Core.SharedBasePage.Page_Load(Object sender, EventArgs e)   at System.Web.UI.Control.OnLoad(EventArgs e)   at System.Web.UI.Control.LoadRecursive()   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

More comfort reading values from lines in CSV-files

Today I had to read values from multiple CVS-files. I wanted to build a testable and reusable solution instead of the ugly sequential spaghetti that easily happens. So here is a sample of a line: 1 var lineReadFromCsv = 2 "42;Daniel;Fisher;1980-03-25;{79704C0D-1A4F-4DDD-80F6-CA79E81BF7CD}"; To increase the readability I created enumerations that point to the index of the position of the values in each line that I wanted to read: 1 public enum DataFormatField 2 { 3 Id = 0, 4 GivenName = 1, 5 Surname = 2, 6 DateOfBirth = 3, 7 UniqueId = 4, 8 } I created a class called ParserParameter that contains enums that 1 public class ParserParameter 2 { 3 prop Enum FirstName { get; set; } 4 //... 5 } 6 Last but not least an extension class the provides a generic method TryGetValueOrDefault<T>(). It takes an enum member as parameter. It can convert int, long, float, decimal, double, guid, datetime as well as string and can easily be extended. 1 int id; 2 if (fields.TryGetValueOrDefault( 3 DataFormatField.Id, 4 out id)) 5 { 6 Console.WriteLine(id); 7 } 8 9 string givenName; 10 if (fields.TryGetValueOrDefault( 11 DataFormatField.GivenName, 12 out givenName)) 13 { 14 Console.WriteLine(givenName); 15 } 16 The complete code can be downloaded at forkcan.

NRW Conf 09

Auch in diesem Jahr veranstaltet der Just Community e.V. wieder das größte Developer und IT-Pro Community Event. Unter dem Motto „Check-In zum Wissensvorsprung“ holen wir am 28.08.2009 zahlreiche nationale und internationale Speaker nach Wuppertal. Neben den Vorträgen haben Sie natürlich auch dieses Jahr wieder viel Zeit für das Networking mit anderen ITlern aus Nah und Fern. Alle Informationen, wie die Agenda und eine Übersicht über die Speaker gibt es unter http://www.nrwconf.de/. Wir freuen uns, Ihnen auch dieses Jahr sowohl bekannte Gesichter, als auch neue Speaker vorstellen zu dürfen. Die Veranstaltung wurde in diesem Jahr möglich durch unsere Sponsoren: Hewlett Packard, devcoach, Microsoft Deutschland, Brockhaus AG, Itemis AG, sepago GmbH, MT AG, sowie weiteren Unternehmen. Eine weitere Neuerung in diesem Jahr ist der Workshop Day, der am Vortag der eigentlichen Konferenz – sprich am 27.08.2009 – in den Räumlichkeiten unseres Sponsoren Ontaris GmbH stattfindet. Der Developer-Workshop befasst sich mit der Microsoft Web Platform und behandelt die Themen Rich Internet Applications mit Silverlight 3.0 und Web 2.0 Applikationen mit ASP.NET AJAX und JQuery. Die Workshops haben eine begrenzte Teilnehmerzahl (je acht) um den Lernerfolg zu garantieren. Also schnell einchecken…

Project Springboard

Am 5. Juni war ich als Sprecher beim “Project Springboard” zu Gast. Dennis Zielke und das Student Partner Team haben ganze Arbeit geleistet und ein Spitzen Event auf die Beine gestellt – nochmal nochmal nochmal! Mein Vortrag “IIS, PHP & WCF – Web Services InterOp” hat wirklich Laune gemacht und ist laut Feedback bester Vortrag der Konferenz – DANKE, IHR WARD EINE SUPER AUDIENCE!!!   Hier nun wie versprochen das Slide und der Code (PHP gehostet über FastCGI im IIS 7.0 ruft über SSL und Basic Athentication einen WCF Service mit einer Complex-SOAP-Message auf…): springbreak_IIS_PHP_und_WCF.zip

netug-niederrhein.de User Group Meeting

  The user group met today at netzkern, a company in Wuppertal specialized in .net development and SiteCore - thanks the venue and drinks! Thanks to Matthias for the pic! This time we had "Sliverlight 2 in the real world" as a topic presented by Florian Kruesch. He presented new visual features as well as use cases and projects he's working on. Because he didn't touch the non-visual stuff like Isolated Storage he invited me to show something that I've build with the bits: The "Silverlight Cache" for javascript - most commonly used to cache json returned by web services. A lovely way to reduce traffic :-)