Visar inlägg med etikett C#. Visa alla inlägg
Visar inlägg med etikett C#. Visa alla inlägg

Meet my new HtmlHelper extensions friends, ForEach and If

Posted by Kenny Eliasson | Posted in , , , | Posted on 13:15

How many times have you written code like this in your MVC views?

<%
 int currentIndex = 0;
 foreach(var item in Model.Items) {
%>
    <% if(currentIndex == 0) {%>
       <div class="item first"><%= item.Name %></div>
    <% } else if(currentIndex == Items.Count()-1) { %>
       <div class="item last"><%= currentIndex + 1 %> <%= item.Name %></div>
    <% } else { %>
       <div class="item"><%= item.Name %></div>
    <% } %>
<%
 currentIndex++;
 }
%>

This is pure ugliness :(

What I missed was something like django for variables. They include both a Last and First variable on the loop.

After reading Phil Haacked's blog about "A code based repeater for .NET MVC" I decided to shamelessy take some parts of his code and write my own extension methods.

The first extension method I wrote was the Html.ForEach which gets me a index counter.

public static void ForEach<T>(this HtmlHelper html, IEnumerable<T> items, Action<T, int> render)
{
    if (items == null)
        return;

    int i = 0;
    items.ForEach(item => render(item, i++));
}

And to use it

<% Html.ForEach(Model.Items, (item, index) => { %>
    <div>#<%= index + 1 %> <%= item.Name %>
<% }); %>

Pretty slick and I dont need to have the counter variable in the view code. It uses lambda in way I didn't thought was possible before I read Haacked blog post.

I then decided to see if I could manage to check if I was on the first or last item in the loop.

I came up with this

public static void ForEachExtra<T>(this HtmlHelper html, IEnumerable<T> items, Action<T, ForLoop<T>> render)
{
    if (items == null)
       return;

    var loop = new ForLoop<T>(items);

    int i = 0;
    items.ForEach(item => { render(item, loop.Update(i)); i++; });
}

public class ForLoop<T>
{
    private readonly int _itemCount;

    public ForLoop(IEnumerable<T> items)
    {
        _itemCount = items.Count();
    }

    public int Counter { get; set; }
    public int Counter0 { get; set; }
    public bool First { get; set; }
    public bool Last { get; set; }

    public ForLoop<T> Update(int i)
    {
        Counter = i + 1;
        Counter0 = i;
        First = i == 0;
        Last = i == _itemCount-1;
        return this;
    }
 }


And to use this you will write

<% Html.ForEachExtra(Model.Templates, (template, loop) => {%>
   <% if(loop.First) { %> First! <% }%>">
   <div>#<%= loop.Counter %> - <%= template.Name %></div>
   <% if(loop.Last) { %> Last! <% }%>
<% }); %>


Starting to look impressive here! :) But I still think I can get it better, so onto my other new extension method, If()!

What I want is to have code that looks something like this

<% Html.ForEachExtra(Model.Items, (item, loop) => { %>
   <div class="item <%= Html.If(loop.First).Write("first").ElseIf(loop.Last).Write("last") %>
       #<%=loop.counter%> <%= item.Name %>
   </div>
<% }); %>

That would be awesome so off I went to write it.

public interface IConditionWrite
{
    IElseIfConditionBuilder Write(string output);
}

public interface IElseIfConditionBuilder
{
    IConditionWrite ElseIf(bool condition);
}

public class ConditionBuilder : IConditionWrite, IElseIfConditionBuilder
{
    private readonly IList<FluentHtmlCondition> _conditions;
    private FluentHtmlCondition _lastAddedCondition;

    public ConditionBuilder()
    {
        _conditions = new List<FluentHtmlCondition>();
    }

    public IConditionWrite AddCondition(FluentHtmlCondition condition)
    {
       _lastAddedCondition = condition;
       _conditions.Add(condition);
       return this;
    }
        
    public override string ToString()
    {
        foreach (var condition in _conditions) {
            if (condition.Fulfilled)
                return condition.Output;
        }

        return "";
    }

    public IConditionWrite ElseIf(bool condition)
    {
        AddCondition(new FluentHtmlCondition(condition));
        return this;
    }

    public IElseIfConditionBuilder Write(string output)
    {
        _lastAddedCondition.Output = output;
        return this;
    }
}

public class FluentHtmlCondition
{
    public readonly bool Fulfilled;
    public string Output;

    public FluentHtmlCondition(bool fulfilled)
    {
        Fulfilled = fulfilled;
    }

    public void Write(string output)
    {
        Output = output;
    }
 }

And in my Html-helper extension class i add

public static IConditionWrite If(this HtmlHelper html, bool condition)
{
    return new ConditionBuilder().AddCondition(new FluentHtmlCondition(condition));
}

And there you have it all, hope someone can have some use with it.

How I do data-access

Posted by Kenny Eliasson | Posted in , , , , | Posted on 10:04

Over the years I've tested alot of different techniques for getting data from a database in a .NET application.

From the simple ADO.NET wrapper that executes raw sql or SP's and then returning a DataTable to the more specified "Repository" where each entity in my domain had a corresponding Repository for querying the data.

I then discovered ORM's, especially NHibernate and started using it with the "One repository for each entity" approach. This worked great but when my projects grew bigger and bigger the need to create a new Repository for each new entity was to cumbersome (and often the Repository would have an interface, so for each new entity I created 3 new classes).

I later implemented Linq2NHibernate and made it so that the most basic queries (i.e find by name, ordering etc) was made using it. More advanced queries I still shuffled into a entity-specific repository.

My interface at this time looked at this

public interface INHibernateRepository
{
    ICriteria ExecuteCritera(DetachedCriteria criteria);
    IQuery ExecuteCritera(string hql);
    IList ExecuteMultiCriteria(params DetachedCriteria[] criterias);
    void Delete(int id) where ENTITY : DomainObject;
    int Save(ENTITY entity) where ENTITY : DomainObject;
    IQueryable Query() where ENTITY : DomainObject; //Linq2Nhibernate
    ENTITIY Get(int id) where ENTITIY : DomainObject;
}

Pretty basic stuff for querying and fetching by Primary Key.

If i got a entity specific repository i would extend INHibernateRepository like this

public interface QuestionRepository : INHibernateRepository
{
    Question GetLatestInserted();
    //more question specific implementations
}

I then, of course, had implementing classes of these interfaces.

To use it in a MVC application I used Dependency Injection to wire up my controllers.

public class QuestionController(INHibernateRepository repository, IQuestionRepository questionRepository, IUserRepository userRepository /* etc */)
{
}

Some may say that I shouldn't inject repositories directly to my controller, but even if I broke it out to a domain-service, it would still need 3 dependencies.

So instead of using the approach above I have begun using Domain Queries. I've read abit about them before but I was when i read Implementing Domain Queries i realized how it would benefit me.

I started my refactoring spree by adding two new methods on my repository interface

public interface INHibernateRepository : IRepository
{
    IEnumerable Query(IDomainQuery query);
    T FindOne(IDomainQuery domainQuery);
    /* All other methods */
}

I then one by one extracted the more complicated queries to their own query-class.

During this process I didn't encounter a single problem and I could remove all of my entity specific repositories and use _one_ repository for all database calls.

So when I'm writing a query nowadays, I first and foremost try to use Linq, if that doesn't work I create a new query class instead of creating a whole new repository for a single entity.

The template method pattern

Posted by Kenny Eliasson | Posted in , , | Posted on 11:44

One of my favorite patterns is the "Template method pattern".

Basically its about having a abstract class that defines common behaviour with points that can be customizable.

Yesterday I was refactoring alot of classes tha't didn't make use of the template pattern, but they all inherited from the same base-class. The base-class acted more like a common place for methods that all objects needed.

Let me show you some code that I had before the refactoring.

public class QuestionQuery : QueryBuilder {

public IFluentMdxQuery BuildQuery() {
  return new FluentMdxQuery(_context)
  .Get(x =>
  {
    x.Rowset.ForQuestion(_queryId).WithChildren();
    x.AddMeasure(DefaultMeasure.RespondentCount);
    x.AddMeasure(DefaultMeasure.RespondentShare);

    base.AddComparisonIndex(x);
    base.AddBreakdown(x);
    base.AddTimeBreak(x);
    base.SwapAxes(x);
  })
  .WithFilter(base.FilterManager)
  .Order.By(_properties.OrderBy)
  .TheMeasureIs(currentMeasure)
  .AscendingIf(_properties.OrderBy != OrderBy.Measure)
  .SetupWith(setup => {
    setup.HideTheseIds(q => q.AddRange(_properties.HiddenIds));
    setup.AddHighlight.OnMeasure(DefaultMeasure.RespondentShare);
  })
  .WithRules(rules => {
    rules.AddDefaultRules(_properties.ShowAllAnswers());
    foreach (var rule in base.AddedRules) {
      rules.Add(rule);
    }
    rules.Add(new MakeQuestionLevelTotalAndPlaceLastRule());
  });

Thats alot of base-method calls in there.
Now take into consideration that I've got somewhere between 5 to 10 more classes like this.

So yesterday I was assigned to add new functionality to the system which involved these classes. And because the classes are built as they are, I was forced to add the functionality to all classes, and that tingled my "bad code sense". I was duplicating code all over the place!

So I sat down and realized that the Template method would be a perfect pattern to implement here. Make all common calls in a base-class and add ways of overriding the certain parts of the creation.

So heres my new base class. (Some methods are missing since they not add any value besides of taking up space)
public IFluentMdxQuery BuildQuery(ISetupFluentFilterManager filterQueryManager)
{

  return new FluentMdxQuery(_context)
  .Get(x => {
    SetupDimensionCollector(x);
    AddComparisonIndex(x);
    AddBreakdown(x);
    AddTimeBreak(x);
    SwapAxes(x);
  })
  .WithFilter(AddFilter(filterQueryManager))
  .SetupOrder(SetupOrder)
  .SetupWith(AddSetupRules)
  .WithRules(ruleCollector => {
    ruleCollector.AddDefaultRules();
    foreach (var rule in _addedRules) {
      ruleCollector.Add(rule);
    }
    AddExtraRules(ruleCollector);
  });
}

  protected abstract void SetupDimensionCollector(IDimensionCollector dimensionCollector)

  protected virtual void SetupOrder(IFluentMdxSortCommand sortCommand)
  {
    sortCommand.UseDefault();
  }

  protected virtual void AddExtraRules(IRuleCollector ruleCollector) { }


Its almost looks the same as the old one, but this time I've added the metods to the base class, implemented the default behaviour and made them virtual so they can be overriden in the child classes. I also made some methods abstract to force the implementing classes to add them.

So, how did these changes affect my QuestionQuery class?

protected override void SetupDimensionCollector(IDimensionCollector dimensionCollector)
{
  dimensionCollector.Rowset.ForQuestion(_queryId).WithChildren();
  dimensionCollector.AddMeasure(DefaultMeasure.RespondentCount);
  dimensionCollector.AddMeasure(DefaultMeasure.RespondentShare);
}

protected override void SetupOrder(IFluentMdxSortCommand sortCommand)
{
  sortCommand.By(_querySettings.OrderBy);
  sortCommand.TheMeasureIs(GetCurrentMeasure());
  sortCommand.AscendingIf(_querySettings.OrderBy != OrderBy.Measure);
}


Damn! Only 2 methods needed to be overriden. Everything else was default behaviour. Of course not all my classes we're as simple as this, but they all got more to the point and I avoided alot of duplication.

These changes also make it easy for me to add functionality to all query classes easy, just add it to the base class and we're done :)

Shout it

Fluent NHibernate och automappa komponenter

Posted by Kenny Eliasson | Posted in , , , | Posted on 13:28

Nu så vart man "äntligen" tillbaka på jobbet efter en skön jul och nyårsledighet.

Det första jag tog tag i var att generera den nya tabeller till våran rapporteringsapplikation. Jag har tidigare berättat om hur jag använder Fluent NHibernate för att göra detta, men denna gången störde jag mig mycket på att jag var tvungen att göra många mappningar "by-hand" via IAutoMappingOverride för att jag skulle mappa Components.

En Component är en egen klass men datan för klassen ligger i föräldrens tabell.
T.ex. en MetaData-klass som innehåller Created, Version m.m.
Denna MetaData-klass vill man inte mappa till en helt egen tabell utan man mappar min MetaData-klass till kolumner i dess föräldrer. I detta fall mappar jag min Report-entitet till en tabell med namnet Reports som även innehåller kolumner för MetaData-klassen.

Problemet är ju att MetaData-klassen ligger som en property på Reports-klassen och därmed kommer mappas som en "one-to-many" referens. För att komma runt detta innan har jag ofta mappat komponenter för hand, men detta tröttnade jag på idag och bestämde mig för att se hur man kommer runt detta.

Efter lite eftersökningar hittade jag hur säger vilka typer som skall hanteras som komponenter.

På Fluent Nhibernates AutoPersistanceModel finns det en metod som heter Setup(). Via denna kan man bestämma vilka klasser som skall hanteras som komponenter.

.Setup(s => { s.IsComponentType = type => typeof (MetaData) })

Nu fick jag MetaData-klassen att vara mappad som en komponent. Men hur jag gör om så att alla mina befintliga komponenter mappas in på samma sätt?

.Setup(s => { s.IsComponentType = type => typeof (MetaData) || type => typeof(Component2) || etc.. etc.. })

Att göra som ovan med flera "eller" alternativ kan ju bli lite grötigt.

Det jag gjorde istället var att jag gjorde ett tomt interface, ett så kallat marker-interface

public interface IComponent { }

och gjorde så att alla mina komponent-klasser ärvde av det. Sen ändrade jag Setup-koden till

.Setup(s => { s.IsComponentType = type => typeof (IComponent).IsAssignableFrom(type) })

Detta jag tycker jag är sjukt smidigt :)

Om man inte vill använda marker interfaces kan man ju t.ex. använda sig av attribut men då måste man använda reflection för att läsa av klasserna.

Vad tycker ni, vettig lösning? Vad tycker ni om Marker-interfaces vs. Attribut?

NHibernate, skillnader mellan Load, Get och Criteria

Posted by Kenny Eliasson | Posted in , , , , , , | Posted on 08:56

Stötte på ett konstigt problem häromdagen när jag satt och refaktorerade data-access kod via NHibernate till ett av de första projekten där vi använde det. Problemet som skulle lösas var att ConnectionStrings var hårdkodade i vårt hemgjorda assembly.

För att lösa problemet använde jag kod från ett nyare projekt.

I projekten har vi ett Bas-repository som vi använder oss utav och när jag satt och kikade på skillnaderna såg att GetById() metoden skiljde sig åt i de båda klasserna.

I den gamla klassen anropades Session.CreateCriteria() istället för det Load() eller Get() som man kanske hade kunnat förutspå.

Skillnaderna mellan Criteria, Get och Load som jag fattat det är att


  • Load()
    Hämtar aldrig ifrån databasen utan returnerar bara en proxy. Det vill säga, använder du Load() med ett ID som inte finns i databasen kommer du inte få ett fel förrens du försöker komma åt objektets egenskaper. Denna lösningen är den att rekommendera när du vill koppla på referenser till t.ex. nya skapade objekt men inte vill ladda upp alla dessa referenser bara för att kunna spara det nya objektet.

  • Get
    Samma som Load() men kommer att gå till databasen/cachen för att veta att ID:et verkligen finns.

  • CreateCriteria
    CreateCriteria är lite svårare, kommer man ifrån en värld där man är van att skriva Sql själv så tänker man ju förstås att det måste vara den korrekta vägen att gå. Men CreateCriteria hoppar över cachen (om inte specifierat annorlunda) och objektet man får tillbaka cachas inte.

  • Källa
    Läs mer här Ayende om Load, Get och Query By Id


Jag tänkte inte särskilt mycket mer på att vi använde CreateCriteria utan bytte helt sonika ut den mot en Load. Efter mycket pill så hade jag lyckats byta ut den gamla implementation mot den nya.

Tryckte på F5 och körde igång projektet. Och till min stora förvåning funkade allt perfekt, ett tag iallafall. Helt plötsligt fick jag ett exception ifrån NHibernate.

(No persister exists for QS.Product.Core.Interfaces.ICustomer)

Nu tänker man såklart, detta kanske har med att jag glömt embedda en mapping fil, men si, så lätt var det inte. Jag gick till mappningen och kollade, såg att vi mappade till klassen som interfacet implementerade och använde interfacet som proxy-klass.

Koden i som kastade felet såg ut så här:

_session.Load<ICustomer>(531);

Med tanke på felmeddelandet så måste ju detta betyda att ICustomer inte var mappad, vilket den ju inte heller var, det var ju implementation av Interfacet som var mappat. Men hur kunde det funkat innan? Jag bytte ju bara ut bas-repositoriet, inte alla repositoryn som användes, inte heller ändrade jag configuration eller mappningen.

Problemet låg i att CreateCriteria() kan hantera detta, varför, det vet jag inte :)

Men lösningen för mig var att typa om alla mina repositories till att använda klassen istället för interfacet.

Det vore intressant att veta varför CreateCriteria funkar men inte Load/Get :)

Detta blev ett långt första inlägg, får hålla mig lite kortare i framtiden.