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

by Oliver 16. September 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.aspxAbsoluteUri: http://localhost:55235/logg.aspxAuthority: localhost:55235Host: localhostHostNameType: DnsIsDefaultPort: FalseIsFile: FalseIsLoopback: TrueIsUnc: FalseLocalPath: /logg.aspxPathAndQuery: /logg.aspxPort: 55235Query: Fragment: Scheme: httpOriginalString: http://localhost:55235/logg.aspxDnsSafeHost: localhostIsAbsoluteUri: TrueSegments: 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: FalseUserEscaped: FalseUserInfo: Nice 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!

JSON Import In .NET

by Anton 22. July 2011 13:37

Bantam Is Quitting Services We as teamaton were using bantam for all of our todos. At the beginning of this year bantam was bought by ConstantContact, and they announced that bantam will cease services as of July 1. Since we are developing our own todo management tool (see our blog), we decided to push the development and use it instead of bantam. Of course we wanted to take all of our todos with us. We used bantams export feature which gave us a JSON-file with all our tasks (closed and open ones). So I took on the task to write an JSON import feature into our tool. Json.NET After a bit of researching, I found that the library Json.NET would suit our import needs perfectly. Applying the deserialization was pretty straightforward – the documentation helped a lot. Here is the code from the Import controller: [HttpPost] public ActionResult Import(HttpPostedFileBase file) { var todos = new List<Todo>(); if (file != null && file.ContentLength > 0) { var streamReader = new StreamReader(file.InputStream); string text = streamReader.ReadToEnd(); streamReader.Close(); var bantamTodos = JsonConvert.DeserializeObject<IList<BantamTodo>>(text) as List<BantamTodo>; todos = bantamTodos.Select(bantamTodo => bantamTodo.ConvertToTodo()).ToList(); _todoRepository.SaveImport(todos); } return RedirectToAction("List"); } It just opens the file, extracts the content as a string, deserializes the string into a list of bantam todos, and then converts these bantam todos into our “normal” todos. Indirection Via BantamTodo-Class As you can see, I did not convert the JSON directly into our Todo-class. You can use attributes and the converter class to deserialize JSON into a class of your liking. There are two reasons, why I did not choose to do so: I did not want to load the Todo-class with attributes and converters, and I thought it would be easier to introduce a middle class (BantamTodo), which poses as a container and converter. I used a nice tool, to take a good look into the original JSON-file: JSON Viewer. With the information about the structure of the JSON file I started implementing via the TDD pattern. Here is my test class, which tests the deserialization of the the bantam todos and the conversion from the class BantamTodo to Todo: [Test] public void Should_Import_BantamToDo_FromJson() { var jsonToDo = ArrangeTaskAsJson(); var bantamToDo = JsonConvert.DeserializeObject<BantamTodo>(jsonToDo); bantamToDo.Categoy.Should().Be.EqualTo("Organisation"); bantamToDo.Complete.Should().Be.EqualTo(true); bantamToDo.Created_At.Should().Be.EqualTo(new DateTime(2011, 6, 30, 0, 41, 57)); bantamToDo.Due.Should().Be.EqualTo(new DateTime(2011, 7, 1)); bantamToDo.Author.Name.Should().Be.EqualTo("Anton"); bantamToDo.Assigned_To.Name.Should().Be.EqualTo("Oliver"); bantamToDo.Related_To[0].Name.Should().Be.EqualTo("ToDo-Management Tool"); bantamToDo.Name.Should().Be.EqualTo("Entwicklung nach Gebieten Personen zuordnen - Verantwortliche, Blogs, etc."); bantamToDo.Description.Should().Be.EqualTo("some good description"); bantamToDo.Flagged.Should().Be.EqualTo(true); } [Test] public void Should_Convert_BantamToDo_ToTodo() { var jsonToDo = ArrangeTaskAsJson(); var bantamToDo = JsonConvert.DeserializeObject<BantamTodo>(jsonToDo); var todo = bantamToDo.ConvertToTodo(); todo.Status.Should().Be.EqualTo(bantamToDo.Complete ? Status.Closed : Status.Open); todo.Description.Should().Contain(bantamToDo.Name); todo.Description.Should().Contain(bantamToDo.Description); todo.Tags.Select(t => t.Name).Should().Contain(bantamToDo.Categoy); foreach (var bantamProject in bantamToDo.Related_To) todo.Tags.Select(t => t.Name).Should().Contain(bantamProject.Name); todo.DateCreated.Should().Be.EqualTo(bantamToDo.Created_At); todo.DateCompleted.Value.Date.Should().Be.EqualTo(bantamToDo.Due); todo.DateDue.Should().Be.EqualTo(bantamToDo.Due); todo.Creator.Name.Should().Be.EqualTo(bantamToDo.Author.Name); todo.Assignee.Name.Should().Be.EqualTo(bantamToDo.Assigned_To.Name); todo.Priority.Value.Should().Be.EqualTo(bantamToDo.Flagged ? 2 : 0); } The implementation was pretty straightforward. Since it was my first time working with MVC, and also my first time working with JSON, it took me some time. All in all – research, export and meetings included – it took me about 12 hours. If you have any suggestions as to improvement I would appreciate them. If you are trying to import JSON into .NET yourself, I hope that this article helps.

Sorting some result list by the ids of another list

by Oliver 24. June 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 Happy Coding, Oliver

Mocking revisited – mocking a method and passing a parameter using FakeItEasy and Moq

by Oliver 21. June 2011 23:35

Finally, I’ve started mocking things in our kind of legacy project while building new functionality. Now, I wanted to replace some DAL service with a mock that would would just serve me some results instead of ramping up NHibernate, going to the DB and assembling all the entities for this test. At first I tried to use FakeItEasy as I liked the syntax more than that of Moq: 1: var _geoObjectServiceMock = A.Fake<IGeoObjectService>(); 2: var results = new List<int>{ 1, 2, 3, ... }; 3: A.CallTo(() => _geoObjectServiceMock.GetSearchResultIds(A<GeoObjectSearchDesc>.Ignored)) 4: .Returns(results); This was easy. Just fix up the result you want the method to return and set it up. Well – I needed more. I needed to return my results list dependent on the GeoObjectSearchDesc parameter passed to the method. In short: I did not find a way to do this. I searched Google and Stackoverflow but to no avail. What I did find was an example using Moq showing exactly what I wanted to do. From Moq’s QuickStart wiki page: 1: // access invocation arguments when returning a value 2: mock.Setup(x => x.DoSomething(It.IsAny<string>())) 3: .Returns((string s) => s.ToLower()); 4: // Multiple parameters overloads available So I quickly installed Moq using NuGet, e.g. from the Package Manager Console: 1: Install-Package Moq -project Tests Now I have something like this which is exactly what I was looking to do: 1: var _geoObjectServiceMock = new Mock<IGeoObjectService>(); 2: var results = new List<int>{ 1, 2, 3, ... }; 3: _geoObjectServiceMock.Setup(svc => svc.GetSearchResultIds(It.IsAny<GeoObjectSearchDesc>())) 4: .Returns<GeoObjectSearchDesc>(gosd => results.Take(gosd.PageSize).ToList()); That’s what I expected – to get control over the method parameter(s) inside the mock. Great! Thank you Moq. Happy Coding, Oliver

Mocking for the first time – a short overview of a few .NET mocking frameworks

by Oliver 25. March 2011 15:50

In my recent post Testing: trying to get it right I mentioned that a lot of our tests are of the dirty hybrid kind, somewhere between real Unit tests and real Integration tests. Focusing on the Unit test part, we’re looking into using a mocking framework right now to change the way we write tests – most of all to decouple the different components that we use in the application under test. Wanting to use the fresh and hype NuGet package manager to install the mocking frameworks, I chose among the ones that were both available there and also looked promising: RhinoMocks: the sample found in the introduction did not look at all inviting to me so I dropped this one Telerik JustMock (Free Edition) Moq FakeItEasy Really, it could not have been easier to get all these libraries into the project than using NuGet! Sample code So I went ahead and wrote a short and simple test just to get a feel of the syntax they offer. At first I wanted to mock a simple Repository using its interface. Here is what I ended up with: Telerik JustMock: using syntax from their quick start manual 1: public void MockRepositoryInterfaceTest() 2: { 3: // Arrange 4: var repo = Mock.Create<ITodoRepository>(); 5: Mock.Arrange(() => repo.Todos) 6: .Returns(new List<Todo> {new Todo {Description = "my todo"}}.AsQueryable); 7: 8: // Act + Assert 9: repo.Todos.ToList().Count.Should().Be.EqualTo(1); 10: } Moq: just visit the project homepage 1: public void MockRepositoryInterfaceTest() 2: { 3: // Arrange 4: var repo = new Mock<ITodoRepository>(); 5: repo.SetupGet(rep => rep.Todos) 6: .Returns(() => new List<Todo> {new Todo {Description = "my todo"}}.AsQueryable()); 7: 8: // Act + Assert 9: repo.Object.Todos.ToList().Count.Should().Be.EqualTo(1); 10: } FakeItEasy: just visit the project homepage 1: public void MockRepositoryInterfaceTest() 2: { 3: // Arrange 4: var repo = A.Fake<ITodoRepository>(); 5: A.CallTo(() => repo.Todos) 6: .Returns(new List<Todo> {new Todo {Description = "my todo"}}.AsQueryable()); 7: 8: // Act + Assert 9: repo.Todos.ToList().Count.Should().Be.EqualTo(1); 10: } In the first test-ride FakeItEasy and JustMock look pretty much identical, whereas the syntax Moq offers is a bit awkward with the SetupGet() method name and the need to call repo.Object to get the instance. I hope to examinate further differences in use as the project moves on. Mocking concrete classes Since we’re working with a large application that still has a lot of services and classes not implementing any interface I also wanted to make sure we’ll be able to mock concrete types. Well, this didn’t go so well: JustMock and FakeItEasy simply returned an instance of the concrete class I gave them, Moq complains that it can’t override the Todos member. So I added the virtual modifier to it and the test is now green. Still, I got the impression that I was trying to do something that I shouldn’t. The following blog post motivates further not to mock concrete classes: Test Smell: Mocking concrete classes. So I guess introducing interfaces as a kind of contract between classes is the way to go, but in the meantime and where we can’t avoid mocking concrete types we’ll be left using Moq. That’s it for now, happy coding! Oliver

C# access modifiers: protected internal vs. protected vs. internal

by Oliver 27. January 2011 22:50

As I just read here on msdn, the modifiers protected and internal are orthogonal as in that they can be specified in all combinations and are combined with a logical OR. This means: protected members are accessible from inheriting classes internal members are accessible from classes within the same assembly protected internal classes are accessible from inheriting classes and all classes from the same assembly The last option is maybe the most unclear – but just imagine a subclass defined in a different assembly and you’ll see what this might be good for :-) Happy Coding, Oliver

Event-Based-Components, Neue Mailingliste

by robert 13. June 2010 14:15

Gute Software Architektur ist schwer und das Feld noch sehr jung. Obwohl sich DI und IoC auch im Mainstream durchzusetzen scheinen und die PoEAA Stück für Stück in den Wortschatz von Entwicklern einkehren, ist noch Platz nach oben. Einen inkrementellen Fortschritt könnten EBCs darstellen. In diese Richtung zu denken, kann schnell und praktisch unseren Entwickleralltag bereichern. Wer lernen und sich über die Konzepte von EBC austauschen möchte, tut dies am besten auf der neuen Mailingliste: Event based Components.

Nein zu Static/Shared Methoden?

by robert 27. May 2010 17:21

Beim letzten Coding-Dojo der ALT.NET.BERLIN gab es unterschiedliche Meinungen zum Thema wann statische Methoden zu verwenden sind. Aus meiner Sicht sollte statischer Methoden behutsam angewendet werden. Wenn Business-Logik über statische Methode abgewickelt wird, dann ist aber vermutlich etwas im Argen! Was spricht gegen statische Methoden: verhindern OO (Schnittstellen, Ableitung/Vererbung,  Überschreibung) hart zu Mocken/Stuben, hart zu überschreiben macht das Testen von Verwenden statischer Methoden schwer zu testen verhindert Dependency Injection und damit IoC (Frameworks) Wann statische Methoden gut sind: Für Utility Klassen. (Beispiel „File“) Factory-Methoden Private Methode Geteilter globaler Datenzugriff (Als Ausnahme (?)) (Robert)

enjoyed the post?



Memory-Leak vs. Memory Waste

by robert 15. April 2010 14:55

kurzer Nachtrag zum vorherigen Post. Eigentlich kann management Code für sich keine Memory-Leak haben. Es ist lediglich möglich Speicher schlecht zu nutzen, in dem er zum Beispiel zu lange gehalten wird. Technisch ist das kein Memory-Leak. Nur unmanaged Code kann nicht mehr verwalteten Speicher zurück lassen. Deswegen suchen wir streng genommen vermutlich eher nach "Memory-Waste"!

ASP.NET Memory-Leak

by robert 15. April 2010 14:38

Wir sind auf der Suche nach einem Memory-Leak für Camping.Info. Es ist jetzt Donnerstag, 11:56Uhr. Der Web-Server läuft jetzt erst seit 16 Stunden.   Die aktuelle Session-Zahl liegt bei 652. Den Session Timeout von 20min rausgerechnet, bei einer Verweildauer von 7 Minuten, entspricht das ungefähr 70 tatsächlich aktiven, parallelen Besuchern zu diesem Zeitpunkt. (Im laufen des Tages, werden das deutlich mehr.) Der Speicherverbrauch ist für die aktuelle Session-Zahl zu hoch und steigt anscheinend stetig über mehrere Tage hinweg. Es gibt 2 Möglichkeiten für Memory-Leaks in Managed-Code. Referenzen auf Objekte werde nicht wieder frei gegeben, in dem Sie Beispielsweise im ASP.NET Cache gehalten werden. NET Code verwendet unmanaged Resourcen wie FileSystem oder "Datenbank-Connections und diese Resourcen werden nicht wieder explizit frei gegeben. Auch “System.Drawing" stellt ein Problem dar, da es auf unmanagement Resourcen verweist. Oliver hat einen Dump erstellt der wie folgt aussieht:   Wir sind auf der Suche, über die Lösung des Problems werden wir berichten.

About Oliver code blog logo I build web applications using ASP.NET and have a passion for javascript. Enjoy MVC and Orchard CMS, and I do TDD whenever I can. I like clean code. Love to spend time with my wife and our three children. My profile on Stack Exchange, a network of free, community-driven Q&A sites

About Anton code blog logo I'm a software developer at teamaton. I code in C# and work with MVC, Orchard, SpecFlow, Coypu and NHibernate. I enjoy beach volleyball, board games and Coke.