Skip to content

Communities

How to write to a text file in C#

C-Sharpcorner - Latest Articles - Fri, 07/30/2010 - 20:15
This code sample shows how to write to a text file in C#.
Categories: Communities

How to read a text file in C#

C-Sharpcorner - Latest Articles - Fri, 07/30/2010 - 19:48
This code sample shows how to read text files in C#.
Categories: Communities

Using an NHibernate Formula to aid searching

Executive Summary: Use a formula in an NHibernate mapping to facilitate searching the entire string, “LastName, FirstName”, for a User object.

Will see how long this Executive Summary thing lasts. Getting tired of people wasting my time by posting comments saying I’m wasting their time. (I’m also working on an idea for curbing “Smells like fail” comments as well but it’ll involve some serious changes to your browser. Or, based on the average age of people that say things like that, a call to your parents to discuss how much time you spend on Facebook.)

When I’m not Google Web Toolkittin’, I have a nice side project that I use to keep my .NET skills sharp, keep one foot in the door, and whatever other reason I can think of to avoid saying the real reason, which is “pay the bills”. Because one thing start-ups ain’t got a lot of is stable (read: any) income.

In said project, I have a page with an auto-suggest feature to search for users. I.e. you enter some text, and it finds any users with the entered text in the name and displays them in a dropdown. I’d show a screenshot but in the time between when I developed it and when I wrote this, the feature was dropped.

The mechanics of the auto-suggest might be the subject of another post but I doubt it because it’s been covered to death (though not so much in ExtJS which is what we’re using). I’m going to talk about what happens in the back-end. That is, how do I get the data from the database with NHibernate.

We’re using Linq to NHibernate so my first pass was straight-forward:

public IList<User> Search(string searchText) {
    var session = NHibernateSession.Current;

    return ( from w in session.Linq<User>()
                where w.FirstName.Contains(searchText) || w.LastName.Contains(searchText)
                select w).ToList();
}

This works exactly as one would expect. If the user enters "will", it will display "William F. Buckley" and "Ted Williams" and "William 'Wild Bill' W. Williamson" in the search results. Or rather, it will show "Buckley, William F.", "Williams, Ted", and "Williamson, William 'Wild Bill' W." because that's how we're displaying our search results.

And to facilitate that display, we have a Name property on the User object:

public string Name {
   get { return LastName + ", " + FirstName; }
}

Problem is that this search doesn't cover a common scenario. What if the user types 'Williams, T'? This would be a natural thing to do. They want Ted Williams, so they start typing Williams. The search results are too big and they are showing items in the "Last, First" format so it makes sense to keep typing and try to narrow it down further.

The code above will return zero results for such a search. Really what we want is to search the Name property, like so:

public IList<User> Search(string searchText) {
    var session = NHibernateSession.Current;

    return ( from w in session.Linq<User>()
                where w.Name.Contains(searchText)
                select w).ToList();
}

Which doesn't work either because Name isn't a database field and as yet, NHibernate is not able to parse formulas in your properties and convert them into SQL or Criterion.

But NHibernate *does* allow formulas if you describe the formula to it in the mapping. We're using Fluent NHibernate (assuming it hasn't been merged into the NHibernate project yet and completely replaced mapping files, which it should be):

public class UserMapOverride : IAutoMappingOverride<User>
{
    public void Override(AutoMapping<User> mapping)
    {
        mapping.Map(x => x.Name).Formula("LastName + ', ' + FirstName");
    }
}
And update the Name property in the User object accordingly:
public virtual string Name { get; private set; }

Now, our Search function works the way I want.

Kyle the Formulaic

Categories: Communities

Cursor in WPF and C#

C-Sharpcorner - Latest Articles - Fri, 07/30/2010 - 12:28
In this we will learn how to create Cursor in WPF with C#.
Categories: Communities

Working with Menus - Windows Programming

C-Sharpcorner - Latest Articles - Fri, 07/30/2010 - 11:10
In this article you will leann how to work with Menus in Windows Programming.
Categories: Communities

YouTrack for OSS Projects, or “How to broadcast your issues”

Bug tracking probably means something different to you than it does to the Hillbilly but if it gets you half as excited as it gets me, be sure to wander on over to http://youtrack.codebetter.com. As a sister-aunt service to http://teamcity.codebetter.com, we’re now offering a free issue tracking service to OSS projects, courtesy of the gentle folk at JetBrains.

Hadi Hariri has more details on how to sign up. Despite doing all the work, he also graciously thanks me for all my hard work and if replying to emails with “Good idea” and “Let’s do it!” and “If you think I’m supporting all these &*%$ whiners and their ‘issues’ then you’d better add ‘Hadi’s Personality’ to the project list ‘cause you got issues of your own” is all it takes to get gratitude these days, then I’m owed a whole lotta appreciation.

Happy bugging!

Kyle the Etymologist*

*Yes, yes, I know. I’m trying to be subtle here.

Categories: Communities

ILMerge to the Rescue?

As I continue to work on the 'nu' story, one of the things I am thinking about a lot is how we are going to make this happen. Last week I also had the pleasure to spend some time talking about version management with Udi Dahan and Chris Patterson while they were both in Kansas City. While we discussed a variety of topics one of the things we discussed was how to manage dll dependencies. After this discussion I have come to my current 'thought.'

We should use ilmerge internal more. I have no doubt it has its issues but let me work this out. And then you can tell me what you think.

I am currently working on a new area of the Magnum project that is adding a nice abstraction on top of the file system. One of the features is handling zip files. For this I am using a third party library to handle all that nastiness. It was been a pleasure so far to work with. The problem is that in order to use this you now have to reference 3 assembilies:

  • Magnum.dll
  • Magnum.FileSystem.dll
  • Ionic.Zip.dll (DotNetZip)

So, some of this is due to the Magnum core philosophy that we are going to take dependencies with this library. So because I want to use Ionic.Zip I have to now have a new dll Magnum.FileSystem. That's fine but adding 3 references sucks. Not only that but I now have to add a new gem dependency for magnum as well. :( As I thought about this it occurred to me: "Why does the user care about Ionic.Zip?" the user never interacts with this library and if I replaced it with the next hot thing you wouldn't even know. :) Ok, so what if I just 'ilmerge' this bad boy in. What would happen? Well I think I would have fully encapsulated my code. And if I ilmerge internal it, you could actually use your own version of 'Ionic.Zip' and we wouldn't conflict with each other! How cool is that? Once, I have ilmerged that in I can probably just either drop the Magnum.FileSystem project or I can just ilmerge it in to Magnum as well. Suh-weet.

So lets take a second and think about what this would do for us as a process. Lets look at NHibernate:

  • NHibernate.dll
  • Antlr3.Runtime.dll
  • Iesi.Collections.dll
  • log4net.dll
  • YourByteCodeProvider and its dlls

NHibernate.dll of course that guy is going to stay around, he's the beef! What about Antlr3.Runtime.dll? If you are going to use Antlr3.Runtime in your own project do you want to be limited/constricted to whatever NHibernate is using? I would think not, so that puppy gets ilmerged in. Iesi.Collections? Gotta be honest, I should probably use more set based classes, but I don't; and when I do I use HashedSet<T> which I am pretty sure NH supports at this point. But because this dll isn't fully encapsulated, I am pretty sure we can't just absorb this guy in. Question? Why don't we just merge the Iesi code base into NHibernate, I have never used it outside of NH. Have you? Last we have log4net, the venerable work horse of logging. This is another dll that I see us having a hard time with, we could merge it in, but configuring it would get interesting and I really like the log4net story. So that gets us from 4 -> 3 dlls. Not to much of a win.

So lets take a look at MassTransit. A fully configured MassTransit setup (at least as of now) could put the following dlls into your mix:

MassTransit.dll

MassTransit.Infrastructure.dll

MassTransit.Transports.{YourTransportChoice}.dll

MassTransit.{YourContainerChoice}.dll

{YourContainersStuff}.dll (from 1 to possibly 4 dlls)

That a whopping 5 dlls, and if you use the saga support that is another 7-8 dlls, bringing the total to what could be 13 dlls. Schnikeys!

 

So as you can see, its not a 100% win, but I THINK the idea is going in the right direction. Framework builders, lets try to encapsulate our dependencies and ilmerge internal them. It will give our users a better experience and should make our out of the box experience that much better.

 

Please let me know what you think. Is this trash? Or is it good?

 

 

Categories: Communities

Write an Online Basketball Shooting Game Using Silverlight 4 and Farseer Engine - Part 2

DotNetSlackers Latest ASP.NET Articles - Fri, 07/30/2010 - 01:00
In the first article of this series, you’ve learned the fundamentals in using Farseer Engine and its enhanced buddy - PhysicsHelper. Starting from this installment, we are going to develop the online basketball shoot game itself.

Categories: Communities

Video of FubuMVC at MvcConf

My talk from MvcConf is up on Viddler at:  http://www.viddler.com/explore/mvcconf/videos/15/.  I was disappointed with how it turned out, but other people were asking me about when it would be up, so here you go.  At a minimum, it does show some of the significant differences of the Fubu approach.  One of the criticisms I heard repeatedly was that I didn't really do a good job of comparing FubuMVC to ASP.Net MVC and showing the warts on both frameworks.  I constantly get asked for the comparisons between Fubu and MSMVC anyway, so at some point in August I'll publish a longish write up explaining my criticisms towards ASP.Net MVC, why I don't like the technical approach it takes, the opportunities I think the ASP.Net MVC misses out on because of its architecture, and a bit about how we think the Fubu approach helps to solve those problems.  Don't worry, I'll try hard to keep it grounded and avoid being unnecessarily inflammatory.

I think the weaknesses of Fubu are much more obvious (flat out missing functionality, limited community support, very little documentation, no VS integration (which doesn't concern me per se, but others do care), no real "warmup" / "storyteller createproject MyNewProject" bootstrapping yet -- but it's coming).

 

 

Categories: Communities

The '8 Commandments' for Choosing a Unit Testing Solution

C-Sharpcorner - Latest Articles - Thu, 07/29/2010 - 10:02
In this article you will learn how to use 8 Commandments for Choosing a Unit Testing Solution.
Categories: Communities

Login and Logout Page Navigation in Silverlight 4

C-Sharpcorner - Latest Articles - Thu, 07/29/2010 - 08:31
In this article we will see how we can navigate to a default page when user logs out in Silverlight 4 navigation framework.
Categories: Communities

StatusBar in C#

C-Sharpcorner - Latest Articles - Thu, 07/29/2010 - 04:31
A StatusBar control is a combination of StatusBar panels where each panel can be used to display different information. In this article, I will discuss how to create and use a StatusBar using StatusBar class in a Windows Forms application.
Categories: Communities

Why Java?, or “How to describe a decision process”

Executive Summary: With all of our experience in Microsoft technologies, why did we choose Google Web Toolkit over other technologies for our start-up?

Almost six months ago, I described my initial reaction to Java coming from ten years in the Microsoft world. At the time, I tastefully glossed over the reason we ended up using Java, or more specifically, Google Web Toolkit saving the discussion for a time when all I really wanted to do was make sure there were no gaps in the list of months in my Archive. Plus the original post inspired would-be blog-reviewer, Dinesh Gajjar, to comment on the lack of content, a position that leads me to believe he’d only recently started reading my blog. In any case, one of his concerns was that I didn’t explain “why I chose what” which I will assume means “why I chose GWT” (and apologies, Dinesh, if by “what”, you really meant “to waste time that could be spent writing comments on other people’s blogs”).

When first deciding on how to proceed, our default was .NET, which led to some obvious options. MVC seemed a no-brainer and since I was involved in Sharp Architecture, my first reaction before we even finished the conversation was to run the Sharp project template. “But,” says we, “we’re pragmatic programmers. Why do we automatically reach for .NET? This is *our* project!”

Thus explains why my resume says I have two days of experience with Ruby. I played with it for (almost) that long before we changed our minds again. As we discussed the nature of the application, we discovered it would rely *very* heavily on JavaScript. So we wanted something that would facilitate that.

At the time, we were also a little apprehensive about the learning curve with Ruby. Not that we wanted to shy away from it. But this wasn’t some fictitious client’s money we were playing with. It was hours. “Learning on the client’s dime” had a more ominous effect when the client’s dime was my dime.

So we ventured back to .NET being familiar territory and telling ourselves “it’ll help us get this out the door faster.” We also looked seriously at OpenRasta because it seemed to facilitate our view of having the server serve up resources rather than the default view of serving up pages. Our intent was to have a single page and dynamically modify the various pieces view JavaScript. We weren’t looking forward to managing history support for something like that but we felt it offered the best user experience, which is more important than our nagging little technical problems.

One nagging aspect to this approach was testing the JavaScript, something I had little experience with. I did some smoke tests with WatiN and was encouraged a little but it always felt a little uncomfortable, especially trying to run the tests on a CI server. And both my partner and I (admittedly, he more than I) were concerned about the costs of long-term maintainability and were pretty adamant on making the app testable and following a strong focus on quality while we built it. WatiN didn’t give us that warm fuzzy feeling and I don’t believe we looked at Selenium at the time.

Around this time, my partner discovered Google Web Toolkit which looked tailor-made for the type of application we wanted to build: A single page with various pieces updated based on user clicks. And you could write it all in Java, which was easily testable. And better yet, it had history support built in.

So we both did smoke tests and decided it was the way to go. To summarize, it gave us (in order of importance):

  • an AJAX application with a good user experience
  • history support (also important for user experience)
  • easily tested
  • strong community and many resources

In retrospect, it seems there is a fine line between “pragmatic” and “indecisive”. There’s a good chance that not all of our decisions were the right ones, just the ones we made at the time with the information available to us. As I reflect on it, maybe we dismissed Ruby too soon. Or maybe we could have built the app faster in .NET and still made it maintainable. Or maybe or maybe or maybe…

Truth be told, writing this post is about all the reflecting I’ve done on it. Because I have no regrets using GWT whatsoever. It’s lived up to its promise. Yes, we’ve run into issues but none that have been insurmountable and certainly no more than we would with .NET (can’t speak for Ruby).

More importantly, it’s because we use Java/GWT that we have the team that we do and, with all due respect to the awesome team I worked with on my first Livelink project a couple of years ago, it is by far the best team I’ve been in in my twelve years of consulting. And this from a guy who gets along with everyone (almost).

Kyle the Indefinite

Categories: Communities

Crooked architecture

By now I’ve got rid of most of the soot resulting from the reactions on a previous post. Flames were pointed at my need for a case selector. In this post I will delve a little deeper into that. I’m only presenting the core of the problem, the point where the case seems unavoidable and hoping for any more elegant solutions from you. I’m on a tightrope between an (over-)simplification of the problem, a strict NDA and you as a critical reader. Nevertheless I think the problem is worth some reflections so I am giving at a try.

The domain

The domain of our system handles the reselling of licenses. A subscription has a any number of running licenses, to which it’s not much more than a key and an expiration date. Which makes a simple model, a subscription has a list of licenses. The crooked part is (and should be) completely invisible to the subscription. It is where we buy these licenses, we have several suppliers for them. Each license supplier has a completely different way we should interact with them. For one we do the complete administration and send them an Excel sheet every three months. For another one they do all administration themselves, every detail is communicated over a web service. For yet another one there is another different scenario. The list of these suppliers will grow over time. Adding another supplier will require writing specific code, but this code should affect other parts of the system as little as possible.

Having data stored in different ways (db table, web service, spreadsheet) per entity is not that great a problem; there is a vertical split. The core of our problem is that we have the data of one entity stored in a variety of ways; we have a horizontal split.

Consequences for the implementation

Having such different ways to get to the data has the consequence that the internal behavior of the license in the domain depends on the supplier of the license. The external behavior of the license should be the same for all licenses. It is highly undesired for the subscription-customer entity to know where the licenses where bought. (That’s where the profits are made :))

To make things more complicated, implementing the behavior of some suppliers will result in dragging in all kinds of code which should be completely unknown to the domain model. All solutions you presented me, including the nice one using lambda’s, would result in just that. For instance: when it comes to the web service based supplier we need things like credentials which are stored in the db. To get those you need the repository. You don’t want the domain model to depend on the repository; that’s even technical impossible. As a repository depends on a domain model that would result in a cyclic dependency.

A factory as man in the middle

These are the main parts (assemblies) of the solution together with the parts they depend on

  • Domain model
  • Repositories (domain model)
  • Communication with supplier1 (domain model, repositories)
  • Communication with supplier2 (domain model, repositories)
  • UI (domain model, repositories)

As stated before the main problem is how to get the supplier specific data of a subscription into the UI (and other parts) without knowing anything about specific suppliers. Our solution is a subscription factory. Only this factory has knowledge of the specific suppliers. It has references to all underlying layers, that is the domain model, the repositories and all supplier services.

When creating a new subscription object it queries all suppliers for licenses

public static Subscription Subscription(int customerId)

{

    var repository = new SubscriptionRepository();

    var subscription = repository.Subscription(customerId);

    subscription.Licenses = new List<Licence>();

    subscription.Licenses.AddRange(LicenceProvider1.GetLicences(customerId));

    subscription.Licenses.AddRange(LicenceProvider2.GetLicences(customerId, "UserName", "Password"));

    return subscription;

}

The repository provides the plain db data for a subscription. The LicenceProviderX classes handle all supplier specific things. One class will just dive into our own repositories, the other one dives into the web to talk to the suppliers web service. Adding a new supplier leads to adding another line here.

This factory has to provide post production services as well. To do something with a license, like renewing it, requires talking to the license’s supplier. It’s up to the factory to do the magic of finding out who the supplier was. We use a database Id which is mirrored in an enum in code. (This is the dreaded enum this quest started with)

internal enum SupplierIds

{

    Supplier1,

    OtherSupplier

}

A helper method FindSupplier takes a license and returns the enum member. Using this the factory has a member to renew the licenses in a subscription

public static void OneMonthMore(Subscription subscription)

{

    foreach (var license in subscription.Licenses)

    {

        SupplierIds supplierId = FindSupplier(license);

        switch (supplierId)

        {

            case SupplierIds.Supplier1:

                LicenceProvider1.RenewLicence(1);

                break;

            case SupplierIds.OtherSupplier:

                LicenceProvider2.RenewLicence(1, "UserName", "Password");

                break;

        }

    }

}

And there is the switch. And IMHO it is a justified case.

Winding down

I don’t think I have presented you anything exiting at all. Which is IMHO good, because we do have a complicated problem. This solution works well in two ways. It is pretty easy to understand how it works and it is pretty easy to maintain. Adding another supplier boils down to, having written all specific code for that supplier, to adding another case. I hope I have made my point that there is a case for that. No doubt there are more elegant solutions. Please strike your matches. And enlighten me.

Categories: Communities

No GDI Calls between GetHdc and ReleaseHdc

C-Sharpcorner - Latest Articles - Wed, 07/28/2010 - 12:14
In this article you will learn how to use No GDI Calls between GetHdc and ReleaseHdc.
Categories: Communities

Interactive Menu using ListBox in WPF

C-Sharpcorner - Latest Articles - Wed, 07/28/2010 - 10:17
In this article we will see how we can make use of a ListBox control to look like a menu.
Categories: Communities

Customize AutoCompleteBox in WPF

C-Sharpcorner - Latest Articles - Wed, 07/28/2010 - 10:07
In this article we will see how we can customize an AutoCompleteBox in WPF.
Categories: Communities

Three way to form URI for REST Services

C-Sharpcorner - Latest Articles - Wed, 07/28/2010 - 08:29
In this article, I will show how we could construct URI in three ways.
Categories: Communities

Static classes in C#

C-Sharpcorner - Latest Articles - Wed, 07/28/2010 - 07:35
In this article you will learn how to use Static classes in c#.
Categories: Communities

Using an ASP.Net Master Page with theme and CSS

C-Sharpcorner - Latest Articles - Wed, 07/28/2010 - 04:25
Using an ASP.Net master page with a theme and CSS can be tricky. In this article, I'll show you how to do things right.
Categories: Communities