Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Contents tagged with LINQ

  • Create Tag-Cloud from RSS Feed in ASP.NET MVC

    Say you want to generate your own tag-cloud from a list of categories or tags you pull from an RSS-feed or similar. This is one way to do it. I’m using ASP.NET MVC for this sample which creates a simple tag-cloud in a Razor-view with HTML looking something like this:

    image

    The controller-code to start out with looks like this, where you read in the RSS-feed into a SyndicationFeed class, then pull out and flatten all the categories you have in that feed. Then group all those categories and count them to build up this simple view-model which is a Dictionary of category and percentage:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            //get feed
            var feed = SyndicationFeed.Load(XmlReader.Create("http://blog.irm.se/blogs/MainFeed.aspx"));

            //get flat list of all categories/tags in the feed
            var categoriesList = feed.Items.SelectMany(item => item.Categories).Select(category => category.Name);

            var categoryGroups = categoriesList.GroupBy(category => category);

            decimal maxNrOfACategory = categoryGroups.Max(w => w.Count());

            //build a dictionary with category/percentage of all categories
            var tagCloudDictionary = new Dictionary<string, int>();
            foreach (var tag in categoryGroups)
            {
                var percent = (tag.Count() / maxNrOfACategory) * 100;
                tagCloudDictionary.Add(tag.Key, (int)percent);
            }

            return View(tagCloudDictionary);
        }
    }

     

    So now we got this view-model which is a Dictionary<string,int> and contains category/percentage data like this:

    image

    So all we need to do is create some kind of cloud in HTML or similar in the view. One way of doing it is this, which creates the output shown at the top:

    @model Dictionary<string, int>

    @{
        ViewBag.Title = "Index";
    }

    <h2>Tag cloud</h2>
    <div style="width: 400px; font-size: 25px;">
        @foreach (var tag in Model)
        {
            <span style="font-size: @(tag.Value / 2 + 50)%; ">
            @if (tag.Value > 10)
            {
                <span style=" font-weight: bold;">@tag.Key </span>
            }
            else
            {
                <span>@tag.Key </span>
            }
            </span>
        }
    </div>

     

    Obviously, to be able to click on a tag and so on you need to create a richer view-model, I just wanted to show how I grab and count the tags from the feed Smile

  • Please Feedback! Unity, nHibernate, Fluent, Linq... Trying New Architecture Combinations

    We're thinking about a new architecture for a set of pretty large WCF (and perhaps also REST) services that's going to be developed during the next year and perhaps you dear reader would like to comment!

    The services themselves are pretty straight forward, we're going to serve data from a huge SQL Server database which unfortunately is old and lacks relationship/fk/pk between most tables. Nothing we can do about that I'm afraid but we thought that nHibernate could be a good way to map data to domain objects. Some of the services will need to handle more complex business rules, but no heavy computing or long running stuff (not atm anyway).

    What more can I say... everything is going to be running on .NET 3.5, and we have a pretty good view of the business domain, we're currently modelling the information/domain together with the customer and we will probably be developing the whole thing in a DDD-ish way, using unit and integration tests, IoC...

    So, currently we're thinking of WCF/REST for the service layer, Unity as container and building something around nHibernate for the Repository (looking at the IRepository implementation in Fluent). We're new to nHibernate but have been looking at nHibernate.Linq which looks really nice, and I think we'll use the Fluent API and map the classes in code instead of using XML configuration (which I'm allergic against). Just have to figure out a good way to make it all fit together, especially to get a decent UnitOfWork to work with the nHibernate session and the repository. I'll see what I come up with and post it here.

    Ideas? Please comment or send me an email of you like.

  • LINQ to XML in VB.NET and Using the Right Language for the Job

    I'm almost always using C# in my .NET projects, unless I'm doing Office automation where the VB-way of dealing with optional parameters helps out making the code a bit cleaner.

    The last week we've been upgrading ASMX-clients to become WCF-clients for a number of old .NET 1.1 and 2.0 projects, and we ended up with a bunch of app.config files with loads and loads of WCF client endpoint sections, each of them pointing at their own binding configuration. To manually clean this up would take hours and hours of tedious work which would probably result in more than a few errors.

    So I thought maybe I could do search/replace with a regexp-capable editor... or try out XML Literals in VB.NET. I wanted to remove old behaviors, extensions and bindings, then add my own behaviors and extensions and finally change some attributes on each client endpoint. Doing this with XML Literals and XDocument/XElement in VB.NET was quite straight forward and didn't result in too many lines of code:

    Imports System
    Imports System.Xml.Linq
    Imports System.IO
    Imports System.Linq
        Sub FixupConfig(ByVal infile As String, ByVal outfile As String)
            Dim defaultBindingConfigurationXml = <binding name="defaultBindingConfiguration"
                                                  maxBufferSize="1065536"
                                                  maxBufferPoolSize="524288"
                                                  maxReceivedMessageSize="1065536"/>
    
            Dim behaviorsXml = <behaviors>
                                   <endpointBehaviors>
                                       <behavior name="FacadeSoapEndpointBehavior">
                                           <SetMaxFaultSizeBehavior size="100000"/>
                                           <ClientExceptionHandlerBehavior/>
                                       </behavior>
                                   </endpointBehaviors>
                               </behaviors>
    
            Dim extensionsXml = <extensions>
                                    <behaviorExtensions>
                                        <add name="SetMaxFaultSizeBehavior" 
    type="SomeType.SetMaxFaultSizeBehavior, SomeAssembly, Version=1.0.0.0, 
    Culture=neutral, PublicKeyToken=null"/>
                                        <add name="ClientExceptionHandlerBehavior" 
    type="SomeType.ClientExceptionHandler, SomeAssembly, Version=1.0.0.0, 
    Culture=neutral, PublicKeyToken=null"/>
                                    </behaviorExtensions>
                                </extensions>
    
    
            Dim xdoc = XDocument.Load(infile)
    
            xdoc...<system.serviceModel>.<behaviors>.Remove()
            xdoc...<system.serviceModel>.<extensions>.Remove()
    
            xdoc...<system.serviceModel>.Single().AddFirst(extensionsXml)
            xdoc...<system.serviceModel>.Single().AddFirst(behaviorsXml)
    
            xdoc...<system.serviceModel>.<bindings>.<basicHttpBinding>.Descendants.Remove()
            xdoc...<system.serviceModel>.<bindings>.<basicHttpBinding>.Single().Add(defaultBindingConfigurationXml)
    
            Dim elems = xdoc...<client>.<endpoint>
            For Each element In elems
                element.@bindingConfiguration = "defaultBindingConfiguration"
                element.@behaviorConfiguration = "FacadeSoapEndpointBehavior"
            Next
    
            xdoc.Save(outfile)
    
        End Sub
    

    I've heard people recommend to use VB.NET when dealing with XML and I agree - use the right language for the job. When doing this - remember to import System.Linq or you'll miss some vital extensions like the .Add() and .Single() methods ;)