Tuesday, November 30, 2010

Project Ideas Numbers - Fibonacci Sequence

Tackling the Fibonacci project was far easier but still yielded new knowledge.

Recursion is horrible on performance compared to iterative or tail-recursion (assuming the compiler supports tail optimization).


public static class FibonacciSequence
  {
    public static long CalculateRecurse(int term)
    {
      if (term<1)
        throw new ArgumentOutOfRangeException("term""must be >0");
      const byte f0 = 0;
      const byte f1 = 1;
      if (term<2)
        return term;
      return CalculateRecurse(term-1)+CalculateRecurse(term-2);
    }
    public static long CalculateWhile(int term)
    {
      int i = 1, k = 0;
      while (i<=term)
      {
        k+=i;
        ++i;
      }
      return k;
    }
 
    public static long CalculateTail(int term)
    {
      if (term<1)
        throw new ArgumentOutOfRangeException("term""must be >0");
      return CalculateTail(term, 1, 1);
    }
 
    private static long CalculateTail(int term, int iter, int acc)
    {
      if (iter==term)
        return acc;
      return CalculateTail(term, ++iter, acc+iter);
    }
  }

Project Ideas

I've stumbled on an interesting coder's project ideas list



Then tackled the first one in my own way. The goal is to

Find PI to the Nth Digit – Enter a number and have the program generate PI up to that many decimal places. Keep a limit to how far the program will go.


Rather than do exactly that, I wanted to start small, and work through some of the existing formulas I could find and put them into C#. That would be a step in the right direction towards the goal. I think the actual project idea is currently out of my range, with little to gain from going farther than I did. I learned much more about floating point math, decimal vs. double, and binary vs. decimal vs. hexadecimal math.


Code Follows:



Monday, November 29, 2010

EF4 ToTraceString Method

So if your SoC is just a little muddy on the db-code to query-code like mine appears to be currently you might find yourself wanting to access the ToTraceString() method cleanly on the query side without bringing in EF4 using statements or references.

I accomplished this using the partial class feature.





using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Data.EntityClient;
 
namespace StarfleetCommanderSecure.EF4
{
    public partial class SfeEntities
    {


 public string ToTraceString(IQueryable query)
        {
            var objectQuery = (System.Data.Objects.ObjectQuery) query;
            return objectQuery.ToTraceString();
        }


    }
}

Wednesday, November 10, 2010

Static reflection... or T4 with EnvDte?

So I like static reflection for getting Class, Property or Method names for databinding, but a lot of people aren't comfortable with the possible performance implications, or for whatever reason (usually FUD).  I've found an alternative using T4+EnvDte.

Code is included in the link...

Tuesday, November 9, 2010

Quick custom build task

We needed something to delete all but the last 3 *.zip files for a particular app  in a directory during a build. This was particularly simple because of 1 assumption the files would properly sort by filename alone. This is often not the case when Dates or times are involved unless you are using fixed width, padded, or formatted date/time strings.


using System.Collections.Generic;
using System.Linq;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
 
namespace BMsBuildTasks
{
  public class RollingVersionCleaner:Task
  {
    [Required]
    public string Path { getset; }
    [Required]
    public string AppName { getset; }
    [Output]
    public ITaskItem[ ] Deleted { getset; }
    public override bool Execute( )
    {
      if (System.IO.Directory.Exists(Path)==false)
      {
        Log.LogError("Directory does not exist:"+Path);
        return false;
      }
      var files = System.IO.Directory.GetFiles(Path, AppName+"*.zip");
 
      var q= from f in files
             let fileName=System.IO.Path.GetFileName(f)
             orderby fileName descending
             where fileName.Contains(".")
             select f;
      if (q.Any( )==false)
      {
        Log.LogMessage("No files found "+System.IO.Path.Combine(Path, AppName));
        return true;
      }
      var toDelete=q.Skip(3);
      if (toDelete.Any( )==false)
      {
        Log.LogMessage("No files to delete "+System.IO.Path.Combine(Path, AppName));
        return true;
      }
 
      var deleted = new List<string>( );
      foreach (var item in toDelete)
      {
        System.IO.File.Delete(item);
        deleted.Add(item);
      }
      Deleted=deleted.Select(x => new TaskItem(x)).ToArray( );
      Log.LogMessage("Deleted "+deleted.Count+" file(s)");
      return true;
    }
  }
}

Wednesday, November 3, 2010

Experimental Technologies

Before I lose track of all the things I've been touching in the last 6 months, I wanted to say something on the matter of each and keep track of where I've been and where I might want to go.

Mef - twice (both plug-in UI projects)

Vs2010 Add-ins -

  1.  checks all project reference to ensure none are absolute paths, one that d
  2.  ExtensionsProject for my team
    1. parses all project files 
    2. locates .config files
    3. checks for config values to be in compliance with team standards
    4. checks your projects' FileCodeModel to confirm the code meets other team standards
    5. will remove some project file customizations temporarily, confirm it builds in release mode, then brings up the svn commit dialog
    6. allows you to store compliance information on your modules/projects on the team for easy access.
  3. used a pluggable UI by importing an Action or using the default built-in messagebox if no extension is found.

  1. Team policy reminder/enforcers
    1. warn on calls to forbidden methods
      1.  GC.Collect
      2. GC.AddMemoryPressure
      3. Messagebox.Show
    2. warn if inheriting directly from Windows.Forms or Windows.Control
    3. warn if a control or form subclass constructor does not call InitializeComponent()
    4. warn if a control property is not set per team standards
      1. DialogBorderStyle must be fixed
    5. error if you do not override certain virtual properties (legacy need from vs2005 designer bug)
    6. error if you have code that raises a NotImplementedException
    7. warn if you don't have hungarian notation to name controls
    8. warn if fields are not private
  2. Policy to ensure a project does not call a Config value or index that does not exist.
  • Mef extension  UI
  • Web data scraper/exporter
  • datagrid context menu
Mvc
  • Mvc 2
    • Lots of projects 2 at work, many more at home
  • Mvc 3
    • Got 2/3 through a project and had to go back to MVC2 due to changing requirements, transfer went very well.
  • Unity - Nice DI framework from Microsoft.
  • Ninject - Very nice lightweight DI framework
  • Poor Man's - Did manual DI for the longest time, so happy to have finally switched to learning Ninject and Unity
  • Wrote a task that walks all found project files under a path and determines safe build DirectedAcylicGraphs
    • Detects Circular dependencies/references
    • walks project files in parallel
  • Wrote a task on the ordering task that will generate a properly parallelizing and multi-threading MsBuild project file.
Parallelization/threading/async
  • Rx - wrote a producer consumer where a consumer can produce additional items to be consumed
  • PLinq - used in Rx producer consumer to parallelize the Rx search
  • Async CTP - have not used it quite yet, but did attend the 2010 PDC broadcast
  • Linq-2-Sql - lots of personal projects
  • EF4 - now that I've used it, I actually like it much better than linq to sql

Javascript cross site script without Preflight / Cross Origin Resource Sharing - also Http Access Control
  • Wrote javascript that uses jQuery in a bookmarklet to allow users to save data from a page on one site cross-domain into a private secured store in a db, with group sharing options, aka Cross Origin Sharing requests
Unit Testing - 

I'm sure I've forgotten some and did not get to looking at the future of where I want to go, but it's quite a nice start.