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.

Thursday, October 21, 2010

Run synchronous process with a timeout

I have run into situations where the blocking call I'm making isn't guaranteed to terminate itself ever. I want control over how long I wait before giving up.


private static void RunSync(int timeout, Action toDo)
    {
 
      Exception threadException=null;
      Action wait = ( ) =>
      {
        try
        {
          toDo( );
 
        }
        catch (Exception ex)
        {
 
          threadException=ex;
        }
 
      };
      var thread = new Thread(( ) => wait( ));
      thread.Start( );
 
 
      if (!thread.Join(timeout))
      {
        thread.Abort( );
        throw new TimeoutException("No connection found within timeout:"+timeout/100+" seconds");
      }
      if (threadException!=null)
        throw threadException;
 
    }
This function is set up to wait for another multi-threaded class to try to find a connection and use it. If the timeouts on that class are set improperly or the threading code is bad and just never does a timeout or return, this gives me the option to stop waiting.

Simple MsBuild Custom Task

Here's a very simple custom task that reads in the number in a text file (which only contains a number) increments, passes it back out to the calling MsBuild, and then writes the new value to the text file.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
 
namespace BMsBuildTasks
{
  public class IncrementerTask:Task
  {
    [Output]
    public ITaskItem OutputFullPath { getset; }
    [Output]
    public int Value { getset; }
    public override bool Execute( )
    {
      
      var path =OutputFullPath==null?OutputFullPath.GetWellKnownMetaData(WellKnownMetaData35.FullPath ):
        @"c:\temp\version.txt";
 
      int value;
      using (var file=new System.IO.StreamReader(path))
      {
        
        if (!int.TryParse(file.ReadToEnd( ), out value))
          return false;
 
      }
      value++;
      Value=value;
      using (var file=new System.IO.StreamWriter(path,false))
      {
        file.Write(value);
 
      }
      OutputFullPath = new TaskItem(path);
      return true;
    }
  }
}



    public static string GetWellKnownMetaData(this ITaskItem item, WellKnownMetaData35 value)
    {
      return item.GetMetadata(value.ToString( ));
    }



public enum WellKnownMetaData35
  {
    FullPath,
    RootDir,
    Filename,
    Extension,
    RelativeDir,
    Directory,
    RecursiveDir,
    Identity,
    ModifiedTime,
    CreatedTime,
    AccessedTime
  }

Wednesday, October 20, 2010

EF4 whitelist/explicit eager loading

In linq to sql it was very simple:

    var loadOptions = new System.Data.Linq.DataLoadOptions();
    loadOptions.LoadWith<alliance>(a => a.Players);
    dc.LoadOptions = loadOptions;

where dc was the datacontext.

This specifies that any queries that are submitted to this DataContext that return an Alliance object/entity would also go ahead on the same db trip and fetch it's related Players.

In EF4.0 so far it looks like you have to resort to magic strings. Magic strings are a pet peeve of mine. Your compile time type safety goes out the window in this type of magic string use.

Here are 2 solutions I've found on my googling that can get rid of the magic strings for EF4.

http://j.mp/bub2FW

and

http://j.mp/bKX7X6

Wednesday, September 15, 2010

MSBuild: Copy a list of files to a list of directories

I have config files in a master directory (team does not allow svn:externals, which I believed was designed for this task, perhaps I did not set it up correctly) that I need to svn update and copy to my modules.


 <PropertyGroup>
  <LocalBranchPath>C:\branches\November<\LocalBranchPath>
  <LocalSourcePath>$(LocalBranchPath)\Source<\LocalSourcePath>
  <TortoisePath>C:\Program Files\TortoiseSVN\bin\TortoiseProc.exe<\TortoisePath>
  <ClientConfigPath>$(LocalSourcePath)\MasterDirectory<\ClientConfigPath>
  <TortoiseUpdate>&quot;$(TortoisePath)&quot; /closeonend:1 /command:update /path:<\TortoiseUpdate>
  <ReferencedAssembliesPath>$(LocalSourcePath)\ReferencedAssemblies<\ReferencedAssembliesPath>
  <DbProjLocalPath>$(LocalBranchPath)\Database\DBProjects<\DbProjLocalPath>
  <PropertyGroup>
<ItemGroup>
 <MyModules Include="$(LocalSourcePath)\CommonControls\LimitsInformation;
  $(LocalSourcePath)\CommonControls\BalanceInquiry;
  $(LocalSourcePath)\CommonControls\AuditTrail;
  $(LocalSourcePath)\Administration\Reassignment;
  $(LocalSourcePath)\IndividualControls\Configuration\ActivityList"
 />   
</ItemGroup>

 I need the config files in ClientConfigPath

to be copied to the subfolder of MyModules called ModuleName.UnitTest





let's get the svn update out of the way 





<Target Name="SvnUpdateClientConfigs">
 <Exec Command="$(TortoiseUpdate)&quot;$(ClientConfigPath)&quot;"
/><Target>

Very short and sweet, now the hard part, copying multiple files to multiple subdirectories. I had no idea FileName was a shortcut in this case for the final directory name only, it came in handy.





<Target Name="CopyClientConfigsBatched" Outputs="%(MyModules.FullPath)">
  <Message Text="@(MyModules -> '%(FullPath)\%(FileName).UnitTest')"/>
 <ItemGroup>
  <ClientConfigs
  Include="$(ClientConfigPath)\*.config"
  Exclude="$(ClientConfigPath)\P*.config" >
  </ClientConfigs>
 <ItemGroup>
 <Copy SourceFiles="@(ClientConfigs)" DestinationFolder="@(MyModules -> '%(FullPath)\%(FileName).UnitTest')"
   SkipUnchangedFiles="true"/>
<Target/>





The Outputs was necessary because Copy.DestinationFolder will not accept multiple items.
So first I build the list of files, which could have been done at the project level but this was the only target that needed it, and those files may not be present until the svn update was run.  The Exclude prevents PolicyCache.config from being part of the copy. SkipUnchangedFiles makes sure files that haven't changed aren't copied wasting time.




Thursday, September 9, 2010

My first Rx attempt

I think I overshot for a first attempt by far and I'm not sure how to validate the efficiency/concurrency of the code. However, here is Rx that so far as I've used it appears to correctly do recursive producer-consumer iteration of a call graph.



 public override ProblemCollection Check(TypeNode type)
    {
      Debug.WriteLine("Checking type:"+type.FullName);
      var initializer = type.Members.OfType<Method>( ).FirstOrDefault(x => x.FullName==type.FullName+".InitializeComponent");
 
      if (initializer==null)
        return null;
      Debug.WriteLine(initializer.FullName);
      var constructorsWithNoInitCall = type.Members.OfType<Method>( ).Where(m => m.NodeType==NodeType.InstanceInitializer).ToList( );
      var visitedMethods = new HashSet<string>( );
      var foundMethods = new ObservableHashSet<Method>( );
 
      var whenMethodsFound = Observable.FromEvent<NotifyCollectionChangedEventArgs>(foundMethods, "CollectionChanged");
 
      whenMethodsFound.Subscribe(
        e =>
        {
          switch (e.EventArgs.Action)
          {
            case NotifyCollectionChangedAction.Add:
              if (constructorsWithNoInitCall.Any( ))
                Parallel.ForEach(e.EventArgs.NewItems.Cast<Method>( ).Where(m => visitedMethods.Any(v => v==m.FullName)==false),
                  i =>
                  {
 
                    lock (visitedMethods)
                    {
                      if (visitedMethods.Contains(i.FullName))
                        return;
                      visitedMethods.Add(i.FullName);
 
                    }
                    Debug.WriteLine("Visiting:"+i.FullName);
                    var callers = (CallGraph.CallersFor(i));
                    constructorsWithNoInitCall.RemoveAll(x => callers.Any(c => x.FullName==c.FullName));
                    if (constructorsWithNoInitCall.Any( ))
                      foreach (var item in callers.Where(c => visitedMethods.Any(v => v==c.FullName)==false))
                      {
                        foundMethods.Add(item);
                      }
                  });
              break;
            default:
              break;
          }
        }
        );
      foundMethods.Add(initializer);
 
 
      ReportProblem(constructorsWithNoInitCall, type);
 
      return Problems;
    }

Vs2010 Code Analysis Custom Rules

I've written my first custom rules for visual studio to help me on my team with the written and unwritten rules. It was a long journey but I have the hang of it. These rules are set to run on every debug build I do and take about 8 seconds to run all.

 As I understand it custom rules ( Inherited from Microsoft.FxCop.Sdk) can also be used as code check in policies on TFS or in the build process to produce a nice xml report.

Here's the base class (.net 4.0 class library project type)


using Microsoft.FxCop.Sdk;
 
public abstract class BaseRule:BaseIntrospectionRule
{
 protected BaseRule(string ruleName)
  : base(
   ruleName,
   //typeof(BaseRule).Assembly.GetName().Name+".Rules"
   "ProjectNamespace.RuleMetadata",
   typeof(BaseRule).Assembly
   ) { }
}


This class was defined without a namespace, I believe it did not work while it was in one. It's also quite important to note that the string literal Must match your project namespace+xml filename without the .xml on it. The commented method may work as well if your xml file is called Rules.xml. This file must be set to Embedded Resource.

Rules can be set as Messages, Warnings, or Errors and show up in the standard Error List control if code analysis is turned on in your project.

The general classes of rules I have written so far include:

  • Do not use method - Things like GC.AddMemoryPressure, MessageBox.Show (we use a custom dialog with styling)
  • Do not inherit - We don't want anyone inheriting from Windows.Forms.Form
  • Do not raise- We don't want code that has NotImplementedExceptions still present.
  • UseHungarian for controls
    • uses a dictionary to determine if the control has a preferred name we use on the team.
  • Fields should be private
  • Control Property must be set to x
    • For example, in most cases we want all dialog border styles to be fixed - I check the Initialize Component method of anything that inherits from Form for the property to be set there.
  • MustOverride - For legacy reasons (old Visual Studio bug they tell me) we have methods/properties that are virtual instead of abstract, and if they aren't overridden will throw a runtime exception.

Friday, August 20, 2010

Visual Studio find and replace with regular expressions totally sucks.

The syntax for regular expressions in Visual studio's find and replace option are incredibly convoluted.

I wanted to replace all instances of width in a style sheet with something that was variable based.

so width:75px; would become width:@(width=75)px;

This syntax is using the new Razor view engine and the result is we set a local variable and render it to the page in a nice terse expression. Combined with:

left:@(leftStart+width)px;

we now have the beginning of a nice sliced row of images. Where all the things on a particular row would incrementally build, and then on the next row, I can reset leftStart.

This was the syntax for finding all lines of an html document and capturing the width:
width\:{[0-9]+}

And the syntax for the replacement?
width\:\@(width=\1)

I understand that c# syntax uses a ton of the same conflicting symbols, but... could you guys make something like rexexpal so that we can iteratively solve for the expressions we need?

Wednesday, August 18, 2010

WPF DataGrid Row-level styling

It took me a very long time to figure out how to do this. The following code takes a WPF (and probably silverlight) datagrid and changes the row foreground color based on a single property in that row.

<DataGrid AutoGenerateColumns="True"  Name="dgProjects" >
    <DataGrid.RowStyle>
                <Style TargetType="DataGridRow">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=HasProblems}" Value="True">
                            <Setter Property="Foreground" Value="Red"/>
                        DataTrigger>
                    Style.Triggers>
                   
                Style>
            DataGrid.RowStyle>
DataGrid>

Monday, August 16, 2010

Vs Add-in solution explorer context menus with a little MEF

My first MEF success. I wrote a visual studio add-in context menu for solution explorer where you can right click a project (or solution file for all projects) so that it:



  • reads the project file checking several problem areas 
    • hint paths
    • copy local
    • pre/post build events
    • target framework version
  • then makes a backup copy
  • cleans those local customizations
  • invokes msbuild to make sure it still builds
  • brings up the Source control commit dialog
  • restores your local customizations that we don't want in the source.
I used MEF so that the UI was not hard coded into the add-in. It  was amazingly simple. While I was developing a solution someone was nice enough to post on stackoverflow telling me you can't hydrate static properties. Which I did.

Thursday, July 15, 2010

Bookmarklet: Change the page title

So on some sites, when you get a new ajax message (think facebook, gmail, or maybe meebo) the new message indicator never goes away in the page title on your tabs. Also some titles aren't nearly as clear on your tabs as to what they are, so you can use this to set the title on your tabs to the domain of the page.


So this is what I've come up with as a nice bookmarklet to clear the title without having to reload the page.

javascript:void(function(){document.title=document.domain;}())

or if you like you can set it to document.location

Tuesday, June 29, 2010

Recent POC experiments

What's a POC? - POC

I don't learn details very well, I learn why or why not. So I keep a base of code to refer back to the details and how to repeat something that I haven't done enough times to memorize. I also try to keep a thorough history of sites which helped me reach the conclusion in case I forget some of the why, or miss a few hows on things I didn't need at the time.

Progress:

  • Asp.net Profile provider
    • I've successfully configured and used the default functionality here in asp.net Mvc2
      • I would love to figure out how to enable some items to be for even anonymous visitors and the rest for authenticated users only.
  • VSTO - outlook add in
    • Outlook 2007 for whatever reason does not allow you to add rules involving distribution groups
      • I wrote an add-on (far from release quality) that gets around that and has a WPF window with a WPF data-grid to sort mail involving distribution groups into proper folders.
  • WPF - this leads me of course to the fact I've now done my first WPF window
  • VS2010 Add-in
    • The process of unloading the project, then editing the project file to look at what hint path a reference has was a pain. In my position I need to check for the presence of bad paths. I wrote an add-in that will open the project file without unloading it, and report back if there are any of these bad paths present.
  • VS2010 - Guidance Package migrated from vs2008 to a .vsix extension.
    • We have a guidance package that just barely qualifies as such to help developers create new components for our incredibly huge (443 projects, not counting testing projects) application. It generates 4 projects for every component (common, control(s), service, test).
      • I converted it to a .vsix and made many improvements such as adding a default form instead of just the existing user control for components that have a full form pop or dialog.
      • I added class file template projects (both the .cs and the designer.cs) for adding another user control or dialog
  • MsBuild tasks- We do not have a solution file for our 443 project application! We build the projects individually then assemble them together. Our build process involves CC.net, 2 huge build scripts, no custom logger, a .net app to generate/build locally,  and a lot of spaghetti Msbuild code.
    • I wrote a build task that takes the app's logic and my own Linq to XML to generate a proper build order on the fly by reading in the ITaskItem[] for all the project files, and comparing the list of assembly names against project references (intra-component references in our project depend on all dependencies going to 1 of 2 special folders instead of direct project references)
    • The next step was generating a project file that has the items in the right order already, with additional convenient message output.
    • I've been thinking of trying to generate a solution file or making the projects reference each other for MSBuild auto-dependency-detection and build ordering, but I've not hit enough dead-ends the way I'm currently going.
  • Entity Framework - I've made 2 poor attempts or perhaps good attempts that failed to use EF4.0 in the same way I'm used to with Linq to SQL.

Wednesday, May 19, 2010

Call chain that could be null at any step. Enter IfNotNull or Maybe.

It could be called IfNotNull or Maybe, currently i'm going with Maybe.

Project available at http://Maybe.codeplex.com

So we've all had to write code like

if(one==null) return null;
if(one.two==null) return null;
if(one.two.three==null) return null;
return one.two.three.four;

Now there's code to do it all in one fell swoop.

return one.Maybe(o=>o.two.three.four);

It also handles primitives not just classes:

return one.MaybeNullable(o=>o.two.three, t=>t.four);

Source

Inspired by:

http://blogs.msdn.com/alexj/archive/2008/03/03/maybe-there-is-more.aspx

and

http://blogs.developpeur.org/miiitch/archive/2008/02/29/vendredi-c-est-expression-tree.aspx

Some reading on the subject:

http://abdullin.com/journal/2009/10/6/zen-development-practices-c-maybe-monad.html

http://stackoverflow.com/questions/1196031/evil-use-of-maybe-monad-and-extension-methods-in-c

Note to self: Answer this once posted: http://stackoverflow.com/questions/854591/how-to-check-for-nulls-in-a-deep-lambda-expression/854619#854619

Tuesday, April 20, 2010

Javascript tooling

So I've been working with Javascript for a week or two now. I still loathe it. However I would not probably touch it at all were it not for


  • JQuery - Feels like a .net framework for javascript
  • JQueryUi - Ah a (ightweight custom control library
  • JQuerify - Inject jQuery onto pages that don't have it for making bookmarklets.
I've used Visual Studio 2010 Ultimate primarily for the script writing because of the code/syntax coloring and  built in (poor but still built in) {} () [] matching capabilities. Those aren't specific to Ultimate, or 2010 for all I know. 

For debugging scripts I've used
  • FireBug
  • Google Chrome's built-in developer tool bar (alot)
  • JsBin - online javascript collaborative debugger (seemed slightly buggy, but still worth it)
  • Javascript Lint - nice online static analyzer for syntax and other problems.
On top of those as base scripts to help with life
  • qTip - Nice jQuery plugin  tool tip script for web pages
  • Google's lovely api hosting content delivery network for jQuery, and jQueryUi.
    • Sidenote: apparently resizable, and who knows what else required I also reference "http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css"

Saturday, April 10, 2010

ClickOnce Bookmarklets...maybe click twice

I have a set of bookmarklets that go to my website, and actually use the current version of the bookmarklet. So the bookmarklet on the bar is just a pointer to a script out on my site. So I can update the bookmarklets to my heart's content without the end user having to do anything at all. Unless I move where the bookmarklets live on my site. So if your bookmarklet living space can be more permanent here's the cross domain bookmarklet injection code:

var e=document.createElement('script');

e.setAttribute(
'language', 'javascript');

e.setAttribute(
'token', '@testToken');

e.setAttribute(
'src', 'http://imaginarydevelopment.com/Sfc/Scripts/ClientScripts/AjaxXmlHttp.js');

document.body.appendChild(e);
void(0);

Notice the token code. That makes it so that in the child script I can pull in which user it is, and make posts to that user's account directly.

Friday, April 2, 2010

Macro Resources

So for any that live primarily never paying any attention to the fact that Visual Studio supports macros like me.  I thought in the spirit of my last post it would help to have some resources around other useful macros.

Additionally apparently macros can be auto triggered by 'Environment' Events such as solution open or close
Here's a nice list from the Stackoverflow community
  • Awesome Visual Studio Macros
    • Selected Text browser macros (whatever you have highlighted/selected in your code file)
      • google it
      • spellcheck the word
      • MSDN search
    • InsertNewGuidLiteral
    • AutoClose the start page when you open a solution
    • AutoOpen the start page when you close a solution
    • Automatic Build timer with every build to the output window
    • Dual monitor / Single monitor macro for switching back and forth on the fly
    • Outlining: Collapse to definitions but expand regions

Wednesday, March 31, 2010

VS2008 Macro problem

Maybe I'm slipping in my VB skills since I've been using C# exclusively for around 2 years now, but this seems like a major user unfriendly 'feature' in Visual Studio.

Macros do not work, nor expand into macro explorer if the module in the file doesn't have the same name as the file it is in.

So when I pasted Jeff Atwood's wonderful FormatCodeToHtml Macro into a macro file in the macro editor called FormatToHtml, nothing happened. The macro file was added to the MyMacros project, but none of the actual macros expanded under it. Google was not helpful since the terms "Visual Studio 2008 macro not expanding" didn't turn anything helpful up. Apparently my code snippet on code keep is the 2nd google result for "jeff atwood rtf to html" sweet!

And the real kicker is... Visual studio doesn't complain, it doesn't show an error. It does not show any output when you click build on the macro project. It gives you no hints whatsoever.

Wednesday, February 17, 2010

Enum Extensions

If you're a fan of Enums for readability in an application here are some resources for making them more usable.
The first item is used for places where you'd like some enum values to have a space in the name when displayed somewhere. You can use System.ComponentModel.DescriptionAttribute like so:

       [Flags]
       public enum PermissionType
       {

           Select = 1,
           Insert = 2,
           Update = 4,
           Delete = 8,
           Alter = 16,
           Execute = 32,
           [
Description("View Definition")]
           ViewDefinition = 64
       }
 
and here's the extension method to make it easily usable:
 
    using System.ComponentModel;
 
    /// from: http://www.moggoly.me.uk/blog/post/Enum-description-values.asp
    public static string DescriptionOrToString(this T value)
    {

        
var da = (DescriptionAttribute[])(typeof(T).GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false));

        
return da.Length > 0 ? da[0].Description : value.ToString();

    }

if you don't like the possible clutter of having every object have a DescriptionOrToString in your intellisense, change the signature to
 
public static string DescriptionOrToString(this T value) where T:struct

This method is for enumerating enum values that are used as [Flags] (where a single value can contain many different values in the same enum)

    
///
    /// Gets all combined items from an enum value.
    /// from: http://stackoverflow.com/questions/105372/c-how-to-enumerate-an-enum
    ///
    ///
    /// The value.
    ///
    public static IEnumerable GetAllSelectedItems(this Enum value)
    {
        
int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);

        
foreach (object item in Enum.GetValues(typeof(T)))
        {
            
int itemAsInt = Convert.ToInt32(item, CultureInfo.InvariantCulture);

            
if (itemAsInt == (valueAsInt & itemAsInt))
            {
                
yield return (T)item;
            }
        }
    }

The next post will contain a usage example for GetAllSelectedItems.

Thursday, February 4, 2010

MVC 2 reusable content options

There are 2 main sources of reusable or dynamic page content in Asp.net MVC. Partial Views(using Html.RenderPartial), and HtmlHelpers. Other options include Html.RenderAction, and Ajax calls (for adding content after the page is loaded).  Here's my understanding of them thus far.

Partial views can be strongly typed, but if the type is different from your hosting page(s) you lose the ability to do Html.DisplayFor, Html.TextBoxFor, and have it utilize that type's names. This can all be overcome by designing a custom DTO or ViewModel for the partial view, but that's more steps. Partial views internally work very similar to if they were inside a regular view, however the <%= %> does not seem to come up by default in intellisense. Instead, you get<%@ Assembly= %>. It's nice if you prefer to model your code in a similar way to how a view would look.

Another option is HtmlHelper, which is what you are using when you type Html.TextBox, or Html.TextBoxFor, etc... You write one of these by putting a static class in your project for extension methods. Then writing an Extension method that extends HtmlHelper like so

using System.Web.Mvc;
using BReusable; //For the Member class


public const string JavaScript = " < script type=\"text/javascript\" language=\"javascript\">\n";
public static string JqueryLoadForId(this HtmlHelper helper, Expression<Funcobject>> memberName,
                                  
string function)
{
    
return JavaScript + "$(function() {\n$('#' + '" + Member.Name(memberName) + "')\n." + function +
          
";\n});\n\n";
}

As you can see this code can start to look messy and probably suffers from pre-mature optimization. String.Format suffers a performance penalty, but using that would allow most of this code to sit in a .js or resource file instead of the poor formatting options that string literals leave us.

RenderAction is useful for returning one of the normal controller result types 
  • ViewResult – Represents HTML and markup.
  • EmptyResult – Represents no result.
  • RedirectResult – Represents a redirection to a new URL.
  • JsonResult – Represents a JavaScript Object Notation result that can be used in an AJAX application.
  • JavaScriptResult – Represents a JavaScript script.
  • ContentResult – Represents a text result.
  • FileContentResult – Represents a downloadable file (with the binary content).
  • FilePathResult – Represents a downloadable file (with a path).
  • FileStreamResult – Represents a downloadable file (with a file stream).
Ajax options
  • Ajax class
    • use AjaxOptions parameter to specify many options
      • Example:


        new AjaxOptions { 
                Confirm="Are you sure?",
                HttpMethod="POST",
                UpdateTargetId="divResultText",
                LoadingElementId="divLoading",
                OnSuccess = "myCallback"
            }
    • Ajax.ActionLink
    • using(Ajax.BeginForm()){}
  • javascript or jQuery Ajax calls to web methods

Thursday, January 28, 2010

UnitTesting made easy with the power of TypeMock

I want to test the persistence layer of my code. One of the recently added requirements for the persistence layer is that it accepts a domain class that wraps around the user name to ensure consistent handling throughout the application of a username. This is because currently the decision is to strip the Windows Domain name off of a userName before using it or storing it. Should the decision be reversed, there's a central configuration alteration to make, without having to recompile the application. How nice are changes that require a simple text file to be changed?

So the call would be:

var result=repository.GetAssociate(new UserName(DependencyContainer.GetAssociate()));
Which you can't call from the persistence layer because
  • The Dependency container is defined in an assembly not referenced by the persistence layer 
  • The UserName constructor is internal to the domain assembly
So to make the method repository.GetAssociate testable, we would have to alter the OOP design of the code to make it testable in most frameworks( because there is no public constructor for UserName).

You could of course messy up your code by using dependency injection on everything that needs testing. This concern does partly fall down if you centralize the coupling between your domain and external dependencies, but remains when you try to test individual methods inside a class, or anything internal, private, or that accesses static methods(most testing frameworks can not handle mocking out static methods, constructors, or factories, as I understand it TypeMock can)

You could make your code messier and more prone to issues in dependent code by changing username to a public interface and changing the persistence layer to accept that interface, but then automatic business logic enforcement goes out the window. If an object outside of the domain assembly can not create a copy of a domain object it has no reason to create, then it's tougher to accidentally not pass things through the proper domain classes/methods.

So how do I test this method?