Linq

 

This is just a quick sample to show you can use Linq in 2 different yet identical ways.

The task is to show the count of people that have the same ages in our sample input data

   1:  class Program
   2:      {
   3:          class Person
   4:          {
   5:              public string Name { get; set; }
   6:              public int Age { get; set; }
   7:          }
   8:          static void Main(string[] args)
   9:          {
  10:              // some test data
  11:              var info = new List<Person> {
  12:                  new Person { Name = "Brian", Age = 34 }, new Person { Name = "Dee", Age = 29 },                
  13:                  new Person { Name = "Bob", Age = 21 }, new Person { Name = "Dave", Age = 25 },
  14:                  new Person { Name = "Tim", Age = 33 }, new Person { Name = "Jacques", Age = 43 },
  15:                  new Person { Name = "Simon", Age = 33 }, new Person { Name = "Jame", Age = 34 },
  16:                  new Person { Name = "Jason", Age = 34 }, new Person { Name = "Niamh", Age = 34 }};
  17:              
  18:              var duplicates = from p in info
  19:                               group p by p.Age into g
  20:                               where g.Count() > 1
  21:                               select g;
  22:              Print(duplicates);            
  23:   
  24:              var dups = info.GroupBy(p => p.Age).Where(p => p.Count() > 1);
  25:              Print(duplicates);
  26:          }
  27:   
  28:          static void Print(IEnumerable<IGrouping<int, Person>> obj)
  29:          {
  30:              obj.ToList().ForEach(p => Console.WriteLine(p.Key + ":" + p.Count()));
  31:          }
  32:      }

 

image

Dynamically load html into a div using jQuery

 

Mucking about more and more with jQuery now that’s it’s pretty much become the industry standard, so I needed a little project to work on. I’ve previously created my online c.v. in a Silverlight4 app (must dig that out and add it to the site); this time I decided to stay clear of any server side tech. and do everything client side.

So I decided to use jQueryUI  http://jqueryui.com/ for a few UX components; first step was to create some tabs.

Creating tabs:

 

Now if you look at jQueryUI samples for tabs you’ll see something like this.

        <div id="tabs">
            <ul>
                <li><a href="#tabs-1">First</a></li>
                <li><a href="#tabs-2">Second</a></li>
                <li><a href="#tabs-3">Third</a></li>
            </ul>
            <div id="tabs-1">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et .</div>
            <div id="tabs-2">Phasellus mattis tincidunt nibh. Cras orci urna, blandit id, pretium vel, aliquet ornare, felis. .</div>
            <div id="tabs-3">Nam dui erat, auctor a, dignissim quis, sollicitudin eu, felis. Pellentesque nisi urna, interdum eget.</div>
        </div>

 

Now this is all well and good, but I’ve never been one for dumping a load of html/c#/javascript etc onto my page, maybe it’s my c++ beginnings etc that causes me to look for a structured solution, but whatever it is, I decided to put the content of each tab into a separate web page.

Here’s how:

  • Create your webpages

    image

 

  • Load your content into the tab divs (I’ve just done this after the DOM is loaded with jQuery, I may lazy load other pages…)
<script type="text/javascript">
    $(function(){                        
        // Init the tab control with jQuery 
        $('#tabs').tabs();
        // Load the first page
        $('#tabs-1').load('ResumeTabs/Personal.htm');                    
    });
</script>

image

image

 

That’s it, pretty impressive ey… (that or I’m just easily impressed)

Automatically Scaling Telerik Radial Guage

 

Took a little time out tonight from the web application I’m working on as I want to create a little dashboard prototype that has to be desktop based as a result of where it will be used.

I’ve got a server JBPM (Java business process management.. pretty similar to WF4)  component that is writing log files, these log files are divided into subdirectories for each JBPM workflow that gets executed.

image

The idea is to provide a quick view for the counts of server logs at a glance with a gauge, (i'll be putting this gauge into a template for use in a listbox, but as a first step I’ve just displayed the details of the files in the first workflow folder.

Here’s what it looks like

image

The text is bound to the directory name, the yellow/orange radial bar is the count of all the log files in all subdirectories, and the needle is the count of files in the EchoLoader directory.

 

Here’s the xaml

   1:  <Window x:Class="Datagenic__Monitor.MainWindow"
   2:                  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   3:                  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:                  xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
   5:                  Title="MainWindow" Height="350" Width="525">
   6:      <Window.Background>
   7:          <ImageBrush ImageSource="/Datagenic-%20Monitor;component/Images/background.png" />
   8:      </Window.Background>
   9:      <Grid>
  10:          <telerik:RadialGauge>
  11:              <telerik:RadialScale x:Name="radialScale" Min="0" Max="{Binding Path=MaxScale}" MajorTicks="10"
  12:                              MiddleTicks="1" MinorTicks="3">
  13:   
  14:                  <telerik:RadialScale.MajorTick>
  15:                      <telerik:MajorTickProperties />
  16:                  </telerik:RadialScale.MajorTick>
  17:                  <telerik:RadialScale.MiddleTick>
  18:                      <telerik:MiddleTickProperties Length="0.07" />
  19:                  </telerik:RadialScale.MiddleTick>
  20:                  <telerik:RadialScale.MinorTick>
  21:                      <telerik:MinorTickProperties Length="0.05" />
  22:                  </telerik:RadialScale.MinorTick>
  23:   
  24:                  <telerik:RadialScale.Label>
  25:                      <telerik:LabelProperties FontSize="10" />
  26:                  </telerik:RadialScale.Label>
  27:   
  28:                  <telerik:IndicatorList>
  29:                      <telerik:RadialBar x:Name="gauge1_radialBar" IsAnimated="True"
Value="{Binding Path=TotalLogCount}" />
  30:   
  31:                      <telerik:Needle x:Name="gauge1_needle" IsAnimated="true"
Value="{Binding Path=WFExecutions[0].LogCount}" />
  32:                  </telerik:IndicatorList>
  33:              </telerik:RadialScale>
  34:          </telerik:RadialGauge>
  35:          <Grid>
  36:              <Grid.RowDefinitions>
  37:                  <RowDefinition Height="0.60*" />
  38:                  <RowDefinition Height="0.40*" />
  39:              </Grid.RowDefinitions>
  40:   
  41:              <TextBlock Grid.Row="1" VerticalAlignment="Top" HorizontalAlignment="Center"
  42:                              Foreground="GhostWhite" FontFamily="CourierNew"
Text="{Binding Path=WFExecutions[0].FolderName}" />
  43:          </Grid>
  44:   
  45:      </Grid>
  46:  </Window>

Here’s the code

 

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  using System.Windows;
   6:  using System.Windows.Controls;
   7:  using System.Windows.Data;
   8:  using System.Windows.Documents;
   9:  using System.Windows.Input;
  10:  using System.Windows.Media;
  11:  using System.Windows.Media.Imaging;
  12:  using System.Windows.Navigation;
  13:  using System.Windows.Shapes;
  14:  using System.Collections.ObjectModel;
  15:  using System.ComponentModel;
  16:  using System.IO;
  17:   
  18:  namespace Datagenic__Monitor
  19:  {
  20:      /// <summary>
  21:      /// Interaction logic for MainWindow.xaml
  22:      /// </summary>
  23:      public partial class MainWindow : Window
  24:      {
  25:          public MainWindow()
  26:          {
  27:              InitializeComponent();
  28:   
  29:              this.DataContext = _wfExecutions;
  30:          }
  31:   
  32:          private WorkflowsExecutions _wfExecutions = new WorkflowsExecutions();
  33:      }
  34:   
  35:   
  36:      class WorkflowsExecutions :NotifyPropertyChangedBase
  37:      {
  38:          public WorkflowsExecutions()
  39:          {
  40:              this.WFExecutions = new List<WorkflowExecutions>();
  41:   
  42:              // Get the individual folders that corresponds to the logs
  43:              var executionFolders = System.IO.Directory.EnumerateDirectories(_executionFolder);
  44:              if (executionFolders != null)
  45:                  executionFolders.ToList().ForEach(f =>
  46:                      {
  47:                          var we = new WorkflowExecutions(f);                        
  48:                          we.PropertyChanged += ItemPropChanged;
  49:                          this.WFExecutions.Add(we);
  50:                      });
  51:          }
  52:   
  53:          void ItemPropChanged(object sender, PropertyChangedEventArgs e)
  54:          {
  55:              if (e.PropertyName == "LogCount")
  56:              {
  57:                  FirePropertyChanged("TotalLogCount");
  58:                  if (TotalLogCount > MaxScale)
  59:                      FirePropertyChanged("MaxScale");
  60:              }
  61:          }
  62:   
  63:          public int TotalLogCount
  64:          {
  65:              get
  66:              {
  67:                  return this.WFExecutions.Sum(we => we.LogCount);
  68:              }
  69:              set { }
  70:          }
  71:   
  72:          public int MaxScale
  73:          {
  74:              get
  75:              {
  76:                  int max = (int)(this.TotalLogCount * 1.5);
  77:                  max = max + (10 - max % 10);
  78:                  return Math.Max(100, max);
  79:              }
  80:              set { }
  81:          }
  82:   
  83:          public List<WorkflowExecutions> WFExecutions { get; set; }
  84:          
  85:   
  86:          private string _executionFolder = Properties.Settings.Default.ExecutionLogFolder;
  87:   
  88:   
  89:   
  90:          //event PropertyChangedEventHandler PropertyChanged = (s, e) => { };
  91:      }
  92:   
  93:      class WorkflowExecutions : NotifyPropertyChangedBase
  94:      {
  95:          public WorkflowExecutions(string folder)
  96:          {
  97:              this.FolderName = System.IO.Path.GetFileName(folder);
  98:              _watcher = new FileSystemWatcher(folder);
  99:              _watcher.Deleted += (s, e) => Update();
 100:              _watcher.Created += (s, e) => Update();
 101:              _watcher.EnableRaisingEvents = true;            
 102:              Update();
 103:          }
 104:          
 105:   
 106:          public string FolderName { get; set; }
 107:                    
 108:   
 109:          public int LogCount
 110:          {
 111:              get { return _logCount; }
 112:              set
 113:              {
 114:                  _logCount = value;
 115:                  base.FirePropertyChanged("LogCount");
 116:              }
 117:          }
 118:   
 119:          private void Update()
 120:          {
 121:              var files = System.IO.Directory.EnumerateFiles(_watcher.Path);
 122:              this.LogCount = files.Count();
 123:          }
 124:   
 125:          private int _logCount = 0;
 126:          private FileSystemWatcher _watcher;
 127:   
 128:      }
 129:  }

 

 

The interesting part is the auto scaling, if the TotalLogFile count passes the max scale level the view will get the property changed notification and update it bindings. (Note: I half expect telerik gauge to auto scale, if i spend a few minutes to figure out how… Shifty )

Asp MVC Entity Framework and Data annotations

 

image

 

When you create a MVC view for data entry it already has the scaffolding in place to handle client side validation (and server)
However you need to specify the data annotations you need.

You’ve two options.

1) Modify the T4 code generation templates

2) Use meta data classes (this post)

The generated EF classes are partial classes, this allows us to do the following

   1:  #region Feed
   2:   
   3:      [MetadataType(typeof(FeedMetadata))]
   4:      public partial class Feed
   5:      {
   6:      }
   7:   
   8:   
   9:      public class FeedMetadata
  10:      {
  11:          [Required(ErrorMessage="Please enter a valid name for this feed")]
  12:          public string Name { get; set; }
  13:      }
  14:   
  15:      #endregion Feeds

 

Note: while mvc3 supports these annotations they are limited to [range/required/stringlength/regularexpression]. If you wish to have a bigger offering consider the extensions offered.

Here’s how.

Go the NuGet Extension Manager (right click on references and select add Library Package Reference) and search for “DataAnnotationsExtensions.”  You should see the following two packages, choose the second (includes client side validation, first is server side only.)

Btw: If NuGet is alien to you, then don’t worry, it’s basically a packet manager to make your life a littler easier… a post for another day!

SqlServer 2008 Prevent Saving changes

 

When you modify a table in SqlServer and this change requires the table to be dropped and recreated, it’s necessary that SSMS is configured to allow this.

 

image

 

Go to SSMS/Tools/Options designers and uncheck this option.

See below

 

image

Create those delete views

 

You may wonder why you would create a view for the delete action

image

 

One reason is to prevent webcrawlers interfering with your data, so create those delete views!

Using Telerik RadScheduler with MVC3

 

The cool hip thing these days is MVC, hang ur head in shame if you are still plodding along with plain old asp.net.

Actually that’s not quite right, in fact it couldn’t be further from the truth, asp.net is alive and strong and will be for a long long time, don’t mind those people complaining about

  • Not having direct (easy) control over what html gets rendered
  • Testing lets a little to be desired
  • You can’t get ur grubby little hands on the @razor (at least i’m not currently aware if it can be used outside MVC3);

ASP is alive and strong and Microsoft are actively working on it, what’s more you’ve most likely already have some pretty good controls that you slaved over or bought ready made…

I’m a bit partial to Telerik controls and tonight I wanted to use the RadScheduler in a webportal i’m working on, and here it is in action

image

 

image

So how did I manage to do this?

Well I started out with a HtmlHelper extension and then realized it was even easier.

Telerik RadScheduler works directly with webservices (please read their documentation for full info (because my posts are more pointers then full working samples)

The View contains the following (apologies in all my talk I didn’t use razor Embarrassed smile)

   1:  <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
   2:  <%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
   3:  <asp:Content ID="HeaderCnt" ContentPlaceHolderID="TitleContent" runat="server">
   4:      
   5:  </asp:Content>
   6:   
   7:  <script runat="server">
   8:      public override void VerifyRenderingInServerForm(Control control)
   9:      {
  10:      
  11:      }
  12:  </script>
  13:  <asp:Content ID="BdyCnt" ContentPlaceHolderID="MainContent" runat="server">
  14:      <h2>Index</h2>
  15:      <telerik:RadScheduler runat="server" ID="SampleRadScheduler" EnableAdvancedForm="false">
  16:          <WebServiceSettings Path="~/Models/FeedWebService.asmx" />
  17:          <AdvancedForm Modal="false" />
  18:      </telerik:RadScheduler>
  19:  </asp:Content>

 

That’s pretty muich it, I’m using a plain old .net 2.0 style Webservice as outlined in Telerik help samples but expect I can use WCF too (another post maybe).

 

enjoy..

SqlDatasource Strict Concurrency Checking–Simplistic approach

 

Lets say you have simple UPDATE command

UpdateCommand="Update SEC_USERS SET [email protected], Department = @Department, Gender = @Gender”
 
 
 

Now, lets assume that two end users of your system have already requested information for SEC_USER Bill whose a male janitor.

End user 1 updates Bills Department as he’s been promoted to CEO (hey it not impossible!).
End user 2 changes Bills Gender to female.

What actually ends up happening is the End user 2 overwrites the promotion and Bill (or maybe billie now ) ends up as a female janitor.

So how can we solve this problem assuming we are using a SqlDataSource.

Here’s how:

image

  • Set the ConflictDetection property to CompareAllValues
  • Set the OldValuesParameterFormatString to xxxx_{0}
  • Update your command with a WHERE restriction for XXXX_{0}

That’s it, the SqlDataSource manages the read_xxx parameters so you don’t have to.

I’ve achieved my coding certification

 

The "Works on My Machine" Certification Program

Joseph Cooney had a brilliant idea for a new application certification program. But Vista's bland white-on-gray badge, in my opinion, doesn't properly communicate the.. authoritative.. nature of said program. With the help of Jon Galloway, we zazzed things up a bit:

You might think attaining such a prestigious, rigorous level of certification would be far too challenging. But fear not! Participating in this innovative new application certification program is as simple as pressing the F5 key on your keyboard. Just follow the four easy steps Joseph outlined:

  1. Compile your application code. Getting the latest version of any recent code changes from other developers is purely optional and not a requirement for certification.
  2. Launch the application or website that has just been compiled.
  3. Cause one code path in the code you're checking in to be executed. The preferred way to do this is with ad-hoc manual testing of the simplest possible case for the feature in question. Omit this step if the code change was less than five lines, or if, in the developer's professional opinion, the code change could not possibly result in an error.
  4. Check the code changes into your version control system.

Congratulations! You're fully certified. Brand your app with your shiny new Works on My Machine badge. You'll certainly want to show it off to your fellow team members and key stakeholders. But please-- do try to keep your ego in check. Not everyone is capable of such an epic commitment to quality in software engineering.

 

source: codinghorror.

Too easy to be simple

 

Was having a conversation this evening with an ex colleague of mine, he’s recently ventured into the world of Silverlight which he loves, for him; even though it didn’t start out that way; this has become a stepping stone to the the wonderful world of web development.

Those of you that follow my blog know that I’m leaning more and more towards MVC where possible, so I ran through a demo of what’s involved dong a simple Master Details pattern with ASP MVC3 and razor and it didn’t go down all that well, sure it worked quite well but the tooling, or lack there of, was a big let down for him. Now lets recap here, back in the 90ies when I was plodding along with php/asp and iframes (*shiver*) ASP.net was being conceived; this technology was widely accepted for a number of reasons, most people may quote the postback but another one is most definitely the tooling.

As some stage in our developer life, we’ve all watched a msdn how to video etc, and the demo objective is often remarkably and simplistically achieved, either through

  • A few lines of code
  • Tooling
  • Some hocus pocus of some sort Smile.

The problem is only to know what combination of the above to apply, i.e it’s too easy to be simple. Below I outline the easy and simple way of creating a master/details page with no lines of code.

Demo

1) Open Visual Studio and create a new ASP.NET web application (I’m using .NET 4.0)

image

2) Drag a SqlDataSource onto the default.aspx webpage and configure it, I’ve chosen a database I’ve lying around, (note for membership please consider the the ASP.NET Membership API/Providers and associated schemas)

image

3) Drag a DropDownList from the toolbox and set it’s DataSourceID to be the ID you provided in the step above.
also set the DataTextField and DataTextValue to something that makes sense for your application, Here’s my generated code
<asp:DropDownList ID="lstUsers" runat="server" DataSourceID="SqlDataSourceUsers" DataTextField="NAME" DataValueField="ID" AutoPostBack="True" />

If you view your webpage now you’ll see the dropdown list populated with list of users. Now we want to populate the details part of the page,  Note: I set AutoPostBack to true, this ensures that the page is posted back each time the list selection gets changed.

4) Create another datasource and set this to the details table you wish considered.

image

5) Add a where clause setting the restriction to the selected value of the DropDownList you just created.

image

 

image

6) Now drag a GrivdView onto your page and set its datasource to the Datasource in step 5.

 

And ceca! Open your webpage in a browser now and you’ll be able to view all the workgroup id’s associated with each user.

image