Replace as in batch replace

Posted by myself on September 03, 2010

So I once again needed to replace several patterns in multiple files with something new... Instead of doing this all in my favorite text editor by using repeatedly find/replace, I decided that something more handy was needed. Of course I could have done all that replace stuff with xslt, but hey, who actually likes xslt.

The result of my disapproval of the above mentioned options is the Batch Replacer. As always it is released under the gpl. I also used git for the first time and published the source code on github.

Navigate to those... out of the box with firefox

Posted by myself on March 30, 2010

Ok well, this doesn' seem to be new at all, but nevertheless I missed that. Firefox has the great functionality to assign shortcuts to certain bookmarks and supply a parameter to the URL. This leads to really great quick searches (aka. the art of bookmarking).

What I have now are shortcuts to all my often used search sites. To search in wikipedia e.g. I type CTRL + L (shortcut for placing the cursor in the URL bar in firefox), then type wp asdf and there I go.

 

I guess this fact renders my previously posted quick link access tool obsolete...

Navigate to those URLs over and over again...

Posted by myself on May 15, 2009

I've written a tool that allows to define commonly used URLs for repeated access, varying only by a defined parameter-part. When you call one of those URLs, you just need to pass a parameter and it opens in the browser. That way you get quick access to often used URLs, e.g. your preffered search engine, your ticketing system or whatever. For even faster access the URLs are bound to predefined global hotkeys.

More infos can be found on the project page.

Screenshot of the main application's window

SharePoint list item and its ItemAdding event

Posted by myself on April 01, 2009

I've found many solutions and discussions trying to find one about the ItemAdding event for a SharePoint list item on the internet, neither of which fixed my problem. Actually I've had two. 

The first one was that you have to set the changes made to the ChangedProperties property that belongs the AfterProperties property. If you try to set them on the AfterProperties directly (why you can do this I don't know) the changes will be ignored when creating the item.

The second problem was that all values at the point of that event are stored as strings, they are not yet converted to their respective classes. In my case I needed to set the end date of an event list item 45 minutes after the event date. The following code snippets shows how to achive this. Basically you first have to convert the string into a DateTime object, add the 45 minutes to it and convert the DateTime object back to a valid string representation.

  1. public override void ItemUpdating(SPItemEventProperties properties)
  2. {
  3.     base.ItemUpdating(properties);
  4.  
  5.     DateTime eventDate =
  6.         SPUtility.CreateDateTimeFromISO8601DateTimeString(properties.AfterProperties["EventDate"].ToString());
  7.  
  8.     properties.AfterProperties.ChangedProperties["EndDate"] =
  9.         eventDate.AddMinutes(45).ToString("o");
  10. }
 

Nullable average in LINQ

Posted by myself on October 12, 2008

The following code is one possibility (there may be more elegant solutions to this) to handle a nullable average from a linq query. The problem arises when the linq query does not return a result, thus the average being null. If you don't use a nullable type, you'll get an exception. To get a nullable average from an integer value you'll need to provide a transform function to the Average funtion.

  1. double? nullableAverage =
  2.   (from m in dataContext.Moods
  3.    join g in dataContext.Groups on m.GroupGUID equals g.GUID
  4.    where g.GUID == groupGUID
  5.    select m.Level)
  6.   .Average<int>(x => new double?(x));
  7.  
  8. int average = (int)Math.Round(nullableAverage.HasValue ? nullableAverage.Value : 0, 0);
  9.  
  10. // ...

Custom application settings

Posted by myself on June 28, 2008

Within a c# winform application I needed to store a generic collection to my settings, which I found out was not possible out of the box. It is possible though to set the required type in the properties designer dialog, but the serialization's output is always nothing.

On my research on the internet for a solution i stumbled upon the post Tips for C# .NET Software Developers, which described that the attribute [SettingsSerializeAs(SettingsSerializeAs.Binary)] was required for the settings property, and to set it accordingly in the Settings.Designer.cs file. The problem here is that modifying designer generated code file is not the best of all ideas, as the manual changes are overwritten every time the settings are modified by the designer. Thus, I followed the msn article on how to create application settings, which told me to create a custom settings class. The drawback with this solution is that I now have two settings classes, and not only one single to cover it all.

Here's an example of the settings class. Note the use of the SettingsSerializeAs attribute, as it is the key to the successful serialization.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Configuration;
  5.  
  6. namespace Koffeinfrei
  7. {
  8.     /// <summary>
  9.     /// This class provides extended settings. Use this class for types that need to have special
  10.     /// attributes for serialization, that cannot be set using the config designer dialog.
  11.     /// </summary>
  12.     internal class ExtendedSettings : ApplicationSettingsBase
  13.     {
  14.         private static ExtendedSettings defaultInstance =
  15.             ((ExtendedSettings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new ExtendedSettings())));
  16.  
  17.         /// <summary>
  18.         /// Returns the default instance of this class.
  19.         /// </summary>
  20.         /// <remarks>Get the value of the <see name="defaultInstance"/> member.</remarks>
  21.         public static ExtendedSettings Default
  22.         {
  23.             get
  24.             {
  25.                 return defaultInstance;
  26.             }
  27.         }
  28.  
  29.         /// <summary>
  30.         /// The <see cref="SomeCustomClass"/>s stored in the user scoped settings.
  31.         /// </summary>
  32.         /// <remarks>Get / set the value of the <c>CustomClasses</c> property.</remarks>
  33.         [global::System.Configuration.UserScopedSettingAttribute()]
  34.         [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
  35.         [global::System.Configuration.SettingsSerializeAs(
  36.             global::System.Configuration.SettingsSerializeAs.Binary)]
  37.         public global::System.Collections.Generic.Queue<SomeCustomClass> CustomClasses
  38.         {
  39.             get
  40.             {
  41.                 return ((global::System.Collections.Generic.Queue<SomeCustomClasses>)(this["CustomClasses"]));
  42.             }
  43.             set
  44.             {
  45.                 this["CustomClasses"] = value;
  46.             }
  47.         }
  48.     }
  49. }
  50.  

Rubyblood through your .NET veins with a vengeance

Posted by myself on June 28, 2008

In my last blog entry i totally neglected the fact that there are lamda expressions. This nice little C# 3.0 feature makes anonymous methods much more readable. With that in mind, we can make our Times method much nicer.

Example 1: Ruby style iterator with lambda expression

  1. 2.Times(
  2.   number => { Console.WriteLine("> " + number); }
  3. );

Compared to the former syntax, it increases readability considerably.

Example 2: Ruby style iterator with bare delegate

  1. 2.Times(
  2.   delegate(int number)
  3.   {
  4.     Console.WriteLine("> " + number);
  5.   }
  6. );

 

Rubyblood through your .NET veins

Posted by myself on April 07, 2008

No other programming language has been syntactically as nice as ruby. Ruby is fully object oriented, most other languages appear to be not so consistent, especially when it comes to primitive data types vs classes. In ruby, everything is an object, in many other object oriented language this is not the case. Most of them have primitive data types besides classes, which means that you cannot necessarily call methods on all types. And, ruby's syntax lets you write much functionality with little code.

But ruby is not alone, .NET is catching up a bit with each release. Now with version 3.5, M$ has introduced extension methods. They allow to extend classes dynamically, without the need to subclass.

My first thought was, let's .NET look more like ruby, in respect to its fully ojbect oriented data types. In ruby you could write 2.times {...} to create a neat loop. In .NET, this is now possible too! You just have to write a static class with static methods, where its first paramater is prefixed with this. The first parameter defines the class type the method is added to. That's it. You can even overload methods. And, the newly created methods popup in intellisense!

Extension methods - intellisense

2.Times? The rubyists among you know where this is going...

Example 1: Extend String class

Let's extend the string class with an overloaded Replace-Method that performs a regexp replace.

  1. public static class StringExtensions
  2. {
  3.   public static string Replace(
  4.       this string stringRef,
  5.       string pattern,
  6.       string replace,
  7.       RegexOptions options)
  8.   {
  9.     return Regex.Replace(stringRef, pattern, replace);
  10.   }
  11. }
Call it like this:
  1. class Program
  2. {
  3.   static void Main(string[] args)
  4.   {
  5.     string stringOrig = "this is stupid.";
  6.  
  7.     string stringReplaced = stringOrig.Replace(
  8.       @"(this) is ([^\.]+)\.",
  9.       "$1 is not $2!",
  10.       RegexOptions.None);        
  11.  
  12.     Console.WriteLine(string.Format(
  13.       "Orginal string: {0}\nReplaced string: {1}",
  14.       stringOrig, stringReplaced));
  15.    
  16.     Console.ReadLine();
  17.   }
  18. }

Pretty neat so far huh? But now, let's face the 2.times code.

Example 2: Create a ruby style iterator
  1. public static class IntegerExtensions
  2. {
  3.   public delegate void IntegerExtensionsDelegate(int intRef);
  4.  
  5.   public static bool IsEven(this int intRef)
  6.   {
  7.     return intRef % 2 == 0;
  8.   }
  9.  
  10.   public static void Times(
  11.       this int intRef,
  12.       IntegerExtensionsDelegate invokeMethod)
  13.   {
  14.     for (int i = 0; i < intRef; ++i)
  15.     {
  16.       invokeMethod(i);
  17.     }
  18.   }
  19. }
Let's call it now:
  1. class Program
  2. {
  3.   static void Main(string[] args)
  4.   {
  5.     /* ruby heart beats faster */
  6.     if (2.IsEven())
  7.     {
  8.       Console.WriteLine("Number 2 is even!");
  9.     }
  10.    
  11.     Console.WriteLine("And now: 2 times loop");
  12.  
  13.     /* ruby heart collapses in bliss */
  14.     2.Times(
  15.       delegate(int number)
  16.       {
  17.         Console.WriteLine("> " + number);
  18.       }
  19.     );
  20.  
  21.     Console.ReadLine();
  22.   }
  23. }

The Times method almost looks like a ruby iterator with a block assigned. Instead of having a block, we just pass a anonymous method (aka. delegate) to the Times method, and we pretty much get what we wanted.

If you're interested in details on the compiler output, you can read about it on Scott Hanselmann's Computer Zen.

Too many parameters?

Posted by myself on October 06, 2006

Today I came across an interesting fact about java (referring to the programming language, not the island). But first things first. You may not be interesting in the previous history but I'll tell it anyway.
During my diploma work (that will be finished in one week by the way) I had to generate some classes invoking the wsdl2java parser. I won't explain what that parser is about. Anyway, I invoked the parser on the amazon web service which got me an interesting error. ItemAttributes.java:538: too many parameters So I counted them and I got 261 arguments. That made me wonder how many arguments were actually allowed for a method in java. I searched the java forums and mailinglist and found the answer in the Java Virtual Machine Specification. The following summarizes the facts I was interested in.
"Java limits the number of method parameters to 255 or 254 or less if parmeters are of type long or double. The 255 method parameter limit is for static methods and 254 for non static methods." And some more limitation facts for that matter.

  • method bytecode: 65,535 bytes
  • local variables: 65,535 (each long or double counts as two variables)
  • fields: 65,535 (does not include inherited fields)
  • methods: 65,535 (does not include inherited methods)
  • method parameters: 255 (each long or double counts as two parameters)

I hope that no programmer will ever get even close to those limits. Otherwise the class design should definitely be reconsidered. Anyway, I'm positive that I'm not going to ever see a method that has more parameters than this one...

The white beverage

Posted by myself on September 23, 2006

At my workplace we have a coffee automat which I didn't consider more than just being my coffee supplier. Yesterday I noticed though that it has some peculiar beverage on offer. It's called "Weisses Getränk mit Kaffee" (that was German), and for the English speaking folks the translation would be like "White beverage with coffee" (that was English). That really sounds ominous. Maybe I don't want to try that one...
By the way, sorry for the crappy fotograph, the camera of my cellphone lacks almost everything that would make it a good camera.

White beverage

Random Quote

The pursuit of happiness is a most ridiculous phrase; if you pursue happiness you'll never find it.

C. P. Snow

» ...

Ying and Yang

where I am
where I should be