Tag Archives: linq

Dynamic LINQ to XML

Language Integrated Query (LINQ) is a cool feature of .NET languages like C# that allows you to perform SQL-like query right within the language against language’s data structures (lists, arrays etc.) But one drawback of LINQ – you have to know in advance, at compile time which fields to select, what filter conditions would be. Sometimes there’s a need to supply these at runtime – e.g. user selects which fields they want to see

Thankfully there exists Dynamic LINQ Library that allows you to supply LINQ parameters as a string akin Dynamic SQL. Here’s an example of such query from the library’s homepage:

var query = db.Customers
    .Where("City == @0 and Orders.Count >= @1", "London", 10)
    .OrderBy("CompanyName")
    .Select("new(CompanyName as Name, Phone)");

Now, one thing that LINQ can do is query XML. So in theory if we load, say, this XML:

<DATA_CENTER>
   <SERVER IP="1.2.3.4">
      <OS>Windows</OS>
   </SERVER>
   <SERVER IP="5.6.7.8">
      <OS>Linux</OS>
   </SERVER>
</DATA_CENTER>

into an XElement and run something like this

var query0 = myXElement.Elements()
          .AsQueryable()
          .Select("new (Attribute(\"IP\").Value as IP, Element(\"OS\").Value as OS)")

it would produce list of IPs and OSes. Unfortunately this doesn’t work. Continue reading →

Export Dynamic LINQ to CSV

LINQ allows to perform various queries against different data structures. Wouldn’t it be great if you could easily export result of a LINQ query to CSV? Fortunately you can! This article by Scott Hanselman explain how and culminates in cool in its simplicity code:

namespace FooFoo
{
    public static class LinqToCSV
    {
        public static string ToCsv<T>(this IEnumerable<T> items)
            where T : class
        {
            var csvBuilder = new StringBuilder();
            var properties = typeof(T).GetProperties();
            foreach (T item in items)
            {
                string line = string.Join(",",properties
                      .Select(p => p.GetValue(item, null)
                      .ToCsvValue()).ToArray());
                csvBuilder.AppendLine(line);
            }
            return csvBuilder.ToString();
        }
   
        private static string ToCsvValue<T>(this T item)
        {
            if(item == null) return "\"\"";
   
            if (item is string)
            {
                return string.Format("\"{0}\"", item
                      .ToString().Replace("\"", "\\\""));
            }
            double dummy;
            if (double.TryParse(item.ToString(), out dummy))
            {
                return string.Format("{0}", item);
            }
            return string.Format("\"{0}\"", item);
        }
    }
}

Continue reading →

Pushing pins to Pebble Time timeline from .NET code

Timeline on Pebble Time Pebble Time timeline is a very cool user interface allowing you to see future and past events and act upon them right on your watch. Right out of the box Pebble Time supports calendar pins that shows your future and past appointments in the timeline as well as weather alerts. But the real power comes from 3rd party apps using timeline – they can add anything from sports scores to latest news to TV showtimes – limit is just your imagination.
Pebble has always had open SDK – this is one of its major strengths, and Timeline is not an exception. Timeline API is a very straightforward way to push your own pins to users of your app. There’re various examples and libraries including PHP and node.js on how to deal with the timeline, but I, being mostly a Microsoft developer by trade, decided to bring Timeline into .NET. This particular example is in ASP.NET – pin is pushed from Webpage when user clicks a button, but it’s just one of the possible scenarios.

In order to push timeline pins successfully you will need 2 pieces:

  1. A watchapp that runs on Pebble. In fact after first run, that subscribes user to timeline, the app doesn’t have to be running on the watch anymore. It doesn’t even have to be on the watch. As long as it simple remains in your locker on the phone – you will continue to receive its pins
  2. Your own server that sends calls to Pebble public Timeline API to control pins

Continue reading →

Select Distinct DataRows from ADO.NET DataTable using LINQ

If you’re trying to retrieve distinct rows from your ADO.NET data table using code like

From oRow As DataRow In dtTable.Rows Select oRow Distinct

or

(From oRow As DataRow In dtTable.Rows Select oRow).Distinct()

You may find that rows that are being return are not unique. That’s because by default LINQ compares table rows by reference. If you need to compare by actual values – use DataRowComparer in Distinct method call:

(From oRow As DataRow In dtTable.Rows Select oRow).Distinct(DataRowComparer.Default)

Totally custom filter for UltraWebGrid using LINQ

Last time I described how LINQ can be used to custom filter ADO.NET DataTable. This time I will demonstrate how this technique can replace built-in server-side filtering in Infragistics UltraWebGrid.

By default if server-side filtering is enabled in UltraWebGrid controls, it displays a small “funnel” icon in the column header, if you click this icon – a list of unique values from this column is displayed and selecting a value filters the grid by displaying only rows that have this value.

This default behavior works, sort of – it has many issues. If your grid has paging enabled – only values from the current page will be displayed. If your columns or values has characters that grid doesn’t like (commas, square brackets etc.) an exception will be thrown (this happens because under the hood grid converts your filters into a string that is passed to DataTable’s RowFilter), there’re other issues as well.

Why leave anything to chance when you can provide filtering yourself? Continue reading →

Replace DataTable RowFilter with LINQ

ADO.NET DataTable offers handy RowFilter property (via its DefaultView object), for example to filter by some string value and display filtered data in a grid a code like this is used:

odtMyData.DefaultView.RowFilter = "Field = 'value'"
odgDataGrid.DataSource = odtMyData
odgDataGrid.DataBind()

where odtMyData is a DataTable object and odgDataGrid is a Data Grid.

This works well, but what if you need preprocess data in the DataTable prior comparing it to the filter value – what if you need to apply a user-defined function to it? In my case I had a VB function called ProcessTags which stripped HTML tags from a string, so for example strings like this:

<a href="http://someurl">This is a sample text</a>

and this

<span style="color:red">This is a </span><label>sample text</label>

would be converted into the same text

This is a sample text

So I needed to create condition that would return DataTable rows with that have both HTML values by comparing to "This is a sample text".

How? RowFilter‘s syntax is pretty poor and external function cannot be used, so something like

odtMyData.DefaultView.RowFilter = "ProcessTags(Field) = 'This is a sample text'"
odgDataGrid.DataSource = odtMyData
odgDataGrid.DataBind()

would throw an error.
Continue reading →

CheckListBox to comma-separated string

Today I needed to do a simple thing: Combine selected values of .NET CheckListBox control into a comma separated string. I am lazy, so I decided to Google for a ready-to-use piece of code. Sure enough there’re tons of those. But all of them involve looping through control items, checking IF item is selected, then adding values.. Boring, routine stuff.

People! We live in the 21st century, age of inspiration! Uhm.. sorry, got carried away. Bottom line: I didn’t like any of those solutions and being a fan of LINQ I put together one of my own. Continue reading →

Stored Procedure in LINQ2SQL query

Linq2Sql has a great use of stored procedures – it converts them into methods which you can easily call using standardized .NET syntax. For example if you have SP:

ALTER PROCEDURE MyProcedure(MyParam int) ...

after dragging it into Linq2Sql designer you can call it in your .NET code like this:

Dim aResults = MyDbContext.MyProcedure(2011)

but there are 2 caveats. Continue reading →

String Aggregate in LINQ

In the past I described how to perform string aggregates in T-SQL. In this post I will show how strings can be concatenated in LINQ.

I am using ADO.NET data table as a source for the query, but LINQ being LINQ can pull data pretty much from anything so this example can easily be adjusted.

First things first, let’s create the source. As in T-SQL post I am using ol’ faithful Northwind database and getting data from the Employees table:

Dim oConn As New SqlConnection(sMyConnStr) : oConn.Open()
Dim oComm As New SqlCommand("SELECT Country, FirstName FROM Employees ORDER BY Country, FirstName", oConn)
Dim oAd As New SqlDataAdapter(oComm) : Dim oTable As New DataTable : oAd.Fill(oTable)

This will fill the datatable with employees’ first names and countries

Country FirstName
UK      Anne
UK      Michael
UK      Robert
UK      Steven
USA     Andrew
USA     Janet
USA     Laura
USA     Margaret
USA     Nancy

And now we want to group this by the country, combining first names into comma separated string. Continue reading →

Showing ALL filters in UltraWebGrid with paging

If you’re using Infragistics classic UltraWebGrid with LoadOnDemand not set and paging enabled, getting column filters to work can be tricky. By default clicking on Filter icon will display column data from current page only, ignoring other pages. To make it work you have to take matter in your own hands – populate filter data in code.

The best place to do it is in InitializeLayout event. There you can loop thru all the columns, calling function to populate column filters:

Protected Sub xMyGrid_InitializeLayout(ByVal sender As Object, ByVal e As LayoutEventArgs) Handles xMyGrid.InitializeLayout
    For Each ugColumn As UltraGridColumn In e.Layout.Grid.Columns
        GatherFilterDataForColumn(ugColumn)
    Next
End Sub

Continue reading →