ToDebugString() – give me some debug info about my object, e.g. Request.Url

by Oliver Fri, September 16 2011 20:06

Lately, I was having trouble debugging certain parts of my code in Visual Studio, and all I wanted to know was the value of some variable at some point in time. Well, I’d use some logging if I could just get at that value easily. But for some objects I don’t really know what I’m looking for or where I should be looking for it. So just give me the values of all the members of that object, will ya? And could you recurse that? But no deeper than 3 levels, alright? Or let’s say… 5?

public static string ToDebugString(this object obj, int maxdepth, int depth=0)
{
    if (obj == null)
        return "null";
 
    if (obj is IConvertible)
        return obj.ToString();
 
    if (depth >= maxdepth)
        return "...";
 
    var sb = new StringBuilder();
 
    if (depth > 0)
        sb.AppendLine();
 
    foreach (var propertyInfo in obj.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance))
    {
        sb.Append(new string(' ', 2*depth)).Append(propertyInfo.Name).Append(": ");
        try
        {
            var value = propertyInfo.GetValue(obj, new object[0]);
            sb.AppendLine(ToDebugString(value, maxdepth, depth + 1));
        }
        catch (Exception ex)
        {
            sb.AppendLine(string.Format("[{0}]", ex.Message));
        }
    }
 
    // remove newline from end of string
    var newLine = Environment.NewLine;
    if (sb.Length >= newLine.Length)
        sb.Replace(newLine, "", sb.Length - newLine.Length, newLine.Length);
 
    return sb.ToString();
}
With this little helper I can now simply call anyobject.ToDebugString(4 /* maxdepth */) and I get a nicely formatted debug view of that object; e.g. Request.Url.ToDebugString(3) gives me:
AbsolutePath: /logg.aspx
AbsoluteUri: http://localhost:55235/logg.aspx
Authority: localhost:55235
Host: localhost
HostNameType: Dns
IsDefaultPort: False
IsFile: False
IsLoopback: True
IsUnc: False
LocalPath: /logg.aspx
PathAndQuery: /logg.aspx
Port: 55235
Query:
Fragment:
Scheme: http
OriginalString: http://localhost:55235/logg.aspx
DnsSafeHost: localhost
IsAbsoluteUri: True
Segments:
Length: 2
LongLength: 2
Rank: 1
SyncRoot:
Length: 2
LongLength: 2
Rank: 1
SyncRoot: ...
IsReadOnly: False
IsFixedSize: True
IsSynchronized: False
IsReadOnly: False
IsFixedSize: True
IsSynchronized: False
UserEscaped: False
UserInfo:

Nice Smile

Right now this method chokes on indexed properties but once I’ll need it I’ll go and look for a way to include them. It also chokes any exceptions on the way to just get the job done.

Happy coding!

Tags:

.NET | C# | Debugging | Software development | Tips & Tricks | Visual Studio | developer

Unexpected EOF encountered in BCP data-file

by Oliver Thu, September 15 2011 17:05

Today, I tried importing a CSV file like the following into one of our MS SQL Server databases:

Id;Latitude;Longitude
4610;43.7119;-1.0737
5502;49.4297;-1.806
11360;46.9343;-1.8875

I tried it using the following command line:

   1: bcp GeoDataImport in geodata.csv -w -t; -T

but that threw the mentioned error:

“Unexpected EOF encountered in BCP data-file”

cmd> bcp GeoDataImport in geodata.csv -w -t; -T
Starting copy...
SQLState = S1000, NativeError = 0
Error = [Microsoft][SQL Server Native Client 10.0]Unexpected EOF encountered in BCP data-file
0 rows copied.
Network packet size (bytes): 4096
Clock Time (ms.) Total     : 1

I’ve had this problem before and somehow managed to remember that it might have something to do with the encoding of the file. So I opened it with Notepad++ where you can easily check and change the file encoding and found it was ANSI encoded:

image

Well, the UCS-2 Little Endian encoding is what SQL Server expects as default encoding, so I changed the encoding, saved the file and imported it again – with success. UCS-2 might be something you rarely hear about – that’s because it’s been superseded by UTF-16 but in most situations they are pretty much identical (check out http://en.wikipedia.org/wiki/UTF-16/UCS-2 for more info).

That’s all for now – happy coding!

Tags:

MS-SQL Server | developer | Tips & Tricks

Creating a new module in ‘discoverize’ – using multi-file templates and good ol’ batch scripts

by Oliver Fri, July 15 2011 09:07

For our portal software discoverize I was looking for a way to create new modules faster and more reliably. The basic structure would always be the same, so a Visual Studio multi-file template seemed appropriate:

module

Well, unfortunately I didn’t find a way to create new folders with that approach. Multi-file templates really do what they say: they create multiple files from templates. Nothing else.

So I put together a short batch script that would create the directory structure needed for any new module:

image

I can quickly open a new command line window by using any one of several Visual Studio extensions (e.g. PowerCommands for Visual Studio 2010):

image

… and simply run:

image

Now going back to Visual Studio we have to include the new Feature folder in the project:

image

Then hit Ctrl + Shift + A to open the Add New Item dialog, select ‘Discoverize Module’ and type Feature in the Name textbox (unfortunately, there seems to be no easy way to automatically put the name of the folder inside that textbox):

image

This step will generate three code files, that are the backbone of every module: FeatureConfig.cs, FeatureModule.cs, and FeatureViews.cs. Finally, our multi-file item template comes into play!

Handling the multi-file template

The multi-file item template for a new module consists of four files: the template definition file Module.vstemplate and the template code files Config.cs, Module.cs, and Views.cs:

image

Those four files have to be packed into a zip file and copied to a folder underneath %UserProfile%\My Documents\Visual Studio 2010\Templates\ItemTemplates\ – I put this one into Visual C#\Code. That’s how it appeared under the Visual C# –> Code section in the Add New Item dialog.

Since it is somewhat cumbersome to zip and copy updated versions of the template (especially during early development where I keep adjusting and tuning the template code), I put together another batch file that does that for me. It basically does three things:

  1. Get the name of current folder to use as name for the zip file (found the solution here)
  2. Use 7-zip to zip the four files.
  3. Copy the zip file to the VS custom template directory.

image

The real script contains some safety nets and more output so that in case it won’t work across all developer machines I can get quick feedback as to what exactly didn’t work instead of just “it didn’t work”.

Happy Coding!

Tags: ,

Software development | developer | Tips & Tricks | Productivity

Sorting some result list by the ids of another list

by Oliver Fri, June 24 2011 21:47

Imagine we have the following list of ids of some kind of objects and a mapping of some of the ids to some values (also int’s here):

   1: var ids = new List<int> { 6, 2, 5, 3, 7 };
   2: var valueMap = new List<int[]> { new[] { 5, 15 }, new[] { 2, 12 }, new[] { 3, 13 } };

Now, if we want to return the results a.k.a. the valueMap in the same order we have the ids, we can use the LINQ extension method .Join()like this:

   1: var joined = ids.Join(valueMap, id => id, arr => arr[0], (id, arr) => string.Format("id: {0} - value: {1}",  id, arr[1])); 

Really convenient! Let’s look at the output:

   1: Console.WriteLine(string.Join("\r\n", joined)); 
   2:  
   3: // Prints:
   4: // id: 2 - value: 12
   5: // id: 5 - value: 15
   6: // id: 3 - value: 13

By the way, I use FastSharp to write and test this kind of small code snippets Winking smile

Happy Coding,

Oliver

Tags:

.NET | C# | Software development | Tips & Tricks

Embed Facebook Like Button – Right Align with css and Settings

by andrej Sun, January 09 2011 18:28

If you want to embed a Facebook Like button and you want it to align to the right here is a fix with css only:

First, get the embed code from facebook: http://developers.facebook.com/docs/reference/plugins/like

If you embed the XFBML code and the button is smaller than the size you specified, the button will always align to the left. There is nothing you really can do about it due to the iframe structure of the embed code.

facebook like button embed left align

However, if you specify the width of the like button to be 0, the iframe will always be almost the size of the button, which means you can align it whichever way you want.

facebook like button right align set with to zero

There in the settings make sure to select width to equal 0. This leads to the facebook like button element always being the size it actually is. Which allows you to position whichever way you want, to the right for example.

However there is one little trick, you still have to pull: There is a 15 pixel margin to the right of the element. You can align the button exactly to the right by giving your parent html element following css style: position:relative; right:-15px;

The result looks like this:

facebook like button right align

Tags:

Tips & Tricks | Design | html + css

Javascript in UserControl in UpdatePanel

by Oliver Sat, November 28 2009 15:17

Wenn man weiß, wie es geht, ist alles einfach. Aber JavaScript in UserControls innerhalb eines UpdatePanels funktionstüchtig zu bekommen hatte für mich - bis heute! - immer etwas mit Magie zu tun... Hinzu kam heute, dass ich noch Sys.UI.DomElement-Methoden nutzen wollte (aus der AJAX-Bibliothek). Folgende Versuche habe ich gemacht:

1. Page.ClientScript.RegisterClientScriptBlock(GetType(), "helpful_css_" + ClientID, script, true);
2. ScriptManager.RegisterClientScriptBlock(this, GetType(), "helpful_" + ClientID, script, true);
3. Page.ClientScript.RegisterStartupScript(GetType(), "helpful_css_" + ClientID, script, true);
4. ScriptManager.RegisterStartupScript(this, GetType(), "helpful_css_" + ClientID, script, true); // <-- this is it!

 

Zu 1. und 3. ist zu sagen, dass sie innerhalb einen UpdatePanels nur nach dem ursprünglichen PageLoad funktionieren, nicht nach einem asynchronen Postback. Also fallen sie raus. Außerdem fallen 1. und 2. weg, weil an der Stelle, an der der hier übergebene JavaScript-Code in die Seite generiert wird, der $Sys-Namespace noch nicht definiert ist (ähnlich wie hier: http://encosia.com/2007/08/16/updated-your-webconfig-but-sys-is-still-undefined/).

Bleibt nur 4. Und 4. funktioniert sowohl nach dem initialen PageLoad als auch nach einem async Postback und man kann $Sys verwenden. Wunderbar!

1. oder 2. bleiben allerdings nützlich, wenn man Custom Javascript in die Seite einfügen will, um es weiter unten auf der Seite zu nutzen. Wahlweise kann man natürlich auch die Methode RegisterClientScriptInclude nutzen, um das Javascript in eine eigene Datei auszulagern. Soviel dazu.

Oliver

Tags: , ,

ASP.NET | Tips & Tricks | WEB 2.0 | Web Applikationen

Enum / Flags einfach und sicher definieren

by Oliver Fri, November 13 2009 22:33

Hier (http://blogs.msdn.com/kcwalina/archive/2004/05/18/134208.aspx#5943757) habe ich eine Methode gefunden, wie man einfach und ohne Mathekenntnisse (für einige von uns ;-)) Flag-Enums definiert:

enum Color
{
    None   = 0,
    Blue   = 1 << 0,
    Red    = 1 << 1,
    Yellow = 1 << 2,
    
    Purple = Blue | Red,
    Orange = Red | Yellow,
}

Oliver

Tags:

.NET | Architecture | Tips & Tricks

CPE (CollapsiblePanelExtender) per JavaScript öffnen

by Oliver Thu, November 12 2009 20:53

Bevor ich noch x Mal durchs Web klicke, hier der Einzeiler:

hplCatBox.Attributes["onclick"] = "javascript:$find('" + cpeInqCat.BehaviorID + "').expandPanel(new Sys.EventArgs)";

Tags: , ,

ASP.NET | Tips & Tricks | WEB 2.0

VS2008 Code Snippet zum Repeater-Befuellen

by Stefan Mon, September 14 2009 18:26

Wir befuellen ja haeufig im Frontend einen Repeater. Das einfaedeln der DataSource und das Erstellen und Verknuepfen des EventHandlers fuer ItemDataBound bekommt man mit IntelliSense innerhalb weniger Sekunden hin. Aber wenn man dann den Befuell-Code schreibt, geht es immer wieder los: Wie waren gleich nochmal die ersten 3 Zeilen? Damit ist jetzt Schluss. Einfach die Datei "repeater.snippet" in "Documents/Visual Studio 2008/Code Snippets/Visual C#/My Code Snippets" des Nutzers mit dem man VS ausfuehrt kopieren. Leider zeigt die ReSharper-IntelliSense den Shortcut nicht an, funktionieren tut es trotzdem. Man tippe: rpt [ESC] [TAB]

Der Rest versteht sich von selbst:

repeater.snippet (1,03 kb)

Tags:

Productivity | Tips & Tricks | Visual Studio

Configuration mit configSource auslagern - Copy always

by Oliver Sat, September 05 2009 10:01

Eine kleine Notiz für die Zukunft:

Wenn man eine Configuration-Section aus einer *.config-Datei in eine eigene Datei auslagert, so wie neulich geschehen für die NHibernate-Konfiguration, dann sollte man die "Copy to Output Directory"-Option auf "Copy Always" setzen:

<!-- Lokal eine passende NH.config anlegen -->
<hibernate-configuration configSource="NH.config" />



Ansonsten bekommt man nämlich eine der folgenden ähnliche Fehlermeldung:

System.Configuration.ConfigurationErrorsException: Die configSource-Datei "NH.config" kann nicht geöffnet werden.
(G:\Projects\Camping.Info\Tests\bin\Debug\Tests.dll.config line 12)

Oliver

Tags:

Software development | Tips & Tricks | Visual Studio