Thursday, September 29, 2011

render a view in another folder (not the shared folder)

@Html.Partial("~/Views/Foo/_ListModel.cshtml", Model.Whatever) is an example of this approach.

how to collect the names of only string value columns from a DataTable, how to test an abstract class, and when to nest two classes in one file

ListViewModel is an abstract class that has a method called ReturnListOfNamesOfStringBasedColumns in it which has one line within it:

return this.ListTable.Columns.Cast<DataColumn>().Where(column => column.DataType == typeof (string)).ToDictionary(column => column.ColumnName, column => column.ColumnName);

 
 

I am testing it like so:

[TestClass]

public class ListViewModelTest

{

   [TestMethod]

   public void ReturnListOfNamesOfStringBasedColumns_Behaves_As_Expected()

   {

      //arrange

      PseudoChildForTestingAnAbstractClass listModel =

            new PseudoChildForTestingAnAbstractClass();

      listModel.ListTable = new DataTable();

      listModel.ListTable.Columns.Add("Foo", typeof (string));

      listModel.ListTable.Columns.Add("Bar", typeof (Int32));

      listModel.ListTable.Columns.Add("Baz", typeof (string));

      listModel.ListTable.Columns.Add("Qux", typeof (string));

      

      //act

      Dictionary<string, string> dictionary =

            listModel.ReturnListOfNamesOfStringBasedColumns();

      

      //assert

      Assert.AreEqual(3, dictionary.Count);

      Assert.AreEqual("Foo", dictionary["Foo"]);

      Assert.AreEqual("Baz", dictionary["Baz"]);

      Assert.AreEqual("Qux", dictionary["Qux"]);

   }

}

 

public class PseudoChildForTestingAnAbstractClass : ListViewModel<object>

{

 

}

 
 

This is a rare case where it seems OK to have two classes in one file. Another example might be having an Enum class next to the only class that is ever going to use it.

Tuesday, September 27, 2011

.Verifiable();

.Verifiable() in MOQ is apparently something like Assert.WasCalled in Rhino Mocks. This suggests that .VerifyAll(); needs to be called at the end of a unit test to make the .Verifiable() calls mean anything.

Friday, September 23, 2011

rename a DataTable column

this.ListTable.Columns["FirstShipDate"].ColumnName = "First Ship Date";

giving a "friendly name" for a database field at our project

We can enter our .edmx, select a field, go to "Properties" and then expand "Documentation" to give a friendly name at "Long Description." The friendly name may be used, for example, to display "First Name" in lieu of "FirstName"

press F12 in IE9 to masquerade as IE7 or IE8

there will be an obvious spot for "Document Mode" to change the setting

to see your open bugs in TFS

Go to: Work Items > Team Queries > [Your Project Name Here] > My Open Bugs

Wednesday, September 21, 2011

Tuesday, September 20, 2011

filter a collection with a bag of ids

Use LinqSpecs to match a collection against a collection of ids like so:

public static Specification<Foo> IdCriteria(IList<Guid> Ids)

{

   var fooSpec = new AdHocSpecification<Foo>(f => Ids.Contains(f.Id));

   return fooSpec;

}

   

Call the method like so:

specBuilder.AddAnd(GetSpecs.IdCriteria((Array.ConvertAll(myListOfIdsAsStrings, e => new Guid(e)))));

don't store state statically

it's not "thread-safe"

use base like this in a class

...the only difference is you are referencing the parent of the current class.

deeper dive into our mocking

Trying to better understand how we mock...

using System;

using System.Collections.Generic;

using System.Linq;

using MyApp.Core.Infrastructure;

using MyApp.Core.Services;

using MyApp.Tests.Support;

using MyApp.Web.UI.Models;

using MyApp.Web.UI.Tests.Support;

using Microsoft.VisualStudio.TestTools.UnitTesting;

using MyApp.Core.Repositories;

using MyApp.Core.Entities;

using MyApp.Core;

using Moq;

using MyApp.Tests;

using MyApp.Web.UI.Controllers;

using System.Security.Principal;

using System.Web.Mvc;

using LinqSpecs;

namespace MyApp.Web.UI.Tests

{

   [TestClass]

   public class FooControllerTest : WebTestBase

   {

      MocksRegistry registry;

      private static string userName = WindowsIdentity.GetCurrent().Name;

      

      [TestInitialize]

      public void TestSetup()

      {

         registry = new MocksRegistry();

         ServiceLocator.LookupSource = () =>

         {

            return registry;

         };

      }

      

      [TestMethod]

      public void Can_Find_Within_Filtered_Set()

      {

         
14 lines of code go here

      }

      

      private IQueryable<Foo> BuildFoos()

      {

         var Bar = TestObjects.BuildFoo("Bar");

         Bar.Id = Guid.NewGuid();

         Bar.IsSane == false;

         var Baz = TestObjects.BuildFoo("Baz");

         Baz.Id = Guid.NewGuid();

         Baz.IsSane == true;

         List<Foo> foos = new List<Foo> { Bar, Baz };

         return foos.AsQueryable();

      }

   }

}

 
 

The 14 lines of code that are really interesting are:

  1. IEnumerable<Foo> foos = BuildFoos();
  2. Assert.AreEqual(2, foos.Count());
  3. var url = "/foo/index";
  4. var fooController = TestUtils.BuildTestController<FooController>("POST", url);
  5. fooController.Session["PrevUrl"] = url;
  6. fooController.Session["CurUrl"] = url;
  7. fooController.FooRepository = ServiceLocator.Get<IFooRepository>(AppCtxIds.FOO_REPOSITORY);
  8. registry.FooRepositoryMock.Setup(repo => repo.GetAll()).Returns(BuildFoos()).Verifiable();
  9. registry.FooRepositoryMock.Setup(repo => repo.FindAll(It.IsAny<Specification<Foo>>())).Returns(BuildFoos().Where(f => f.IsSane == true)).Verifiable();
  10. var viewModel = new FooListModel();
  11. viewModel.Initialize(fooController.FooRepository, new List<string>(new[] { RoleNames.Super_User }), viewModel.IsPost);
  12. var result = fooController.Index(viewModel, 1, 5, null, "", "ASC") as ViewResult;
  13. var resultModel = result.Model as FooListModel;
  14. Assert.AreEqual(1, resultModel.FooDTO.Entities.Count());

 
 

About the 14 lines of code that are really interesting:

  1. This line grabs the dummy objects from the lowermost method in the class.
  2. This line affirms that we have an unfiltered set.
  3. This line is used in the next three lines to mock the environment.
  4. Here we mock a FooController and mock its environment too by asserting that it has been accessed by way of the post verb at /foo/index
  5. This line and the one below are part of a means Byron rolled for gauging if the verb at hand is post or get.
  6. Ditto
  7. Let's fake our repository!
  8. This line does nothing ultimately, but you can see that it mocks a repository call so that it will return the same set as the first line of code.
  9. This line is used. It too mocks a repository call. If we were not mocking FindAll we would be handing in a specification. The It.IsAny thing handles the placeholder by successfully mocking anything that might actually get passed into FindAll in the FooController. The set returned is filtered down, but we control what that filtering is here, at this line of code.
  10. We have to have a model.
  11. Here we initialize the model. What is this method for? It turns out that often one will wish to do other mechanics beyond the simple model binding, hence there is a need to call a method in lieu of trying to jam a bunch of code into the getsetters for the model. viewModel.IsPost may seem a little silly here. In the controller we hand in this.IsPost which in this cause is true. We also hand in the repository and the permissions of the current user for security concerns.
  12. Let's create a view. Parameters: the model, current page in pagination, current size of pages in pagination, another model for governing searching which is not applicable here, what column we should sort on, what direction we should sort in, if the post verb is applicable.
  13. Let's get the model out of the view.
  14. Our filtered-down record set should have one item in it.

Monday, September 19, 2011

my hack make a DataTable column full of anchor tags have the capacity for alphabetical sorting

I am replacing this:

row["Name"] = string.Format("<a href='/Program/Details?id={0}'>{1}</a>", row["Id"], row["Name"]);

 
 

...with this:

row["Name"] = string.Format("<!--{1}--><a href='/Program/Details?id={0}'>{1}</a>", row["Id"], row["Name"]);

for attribute on a label tag

The for attribute on a label tag should match up with the id attribute of the tag the label tag is "for."

how to grab an id and put it into a variable in SQL

DECLARE @fooid uniqueidentifier

SET @fooid = (SELECT TOP 1 Id FROM Foo WHERE Name = 'Tom')

INSERT INTO Bar (Id,Name,FooId)

VALUES (N'fffed049-b03e-4d89-fffc-9f5100d8ed92','Jaeschke',@fooid)

Sunday, September 18, 2011

Mock When You Can


(forgive the bad iFrame)
This creepy footage of Woodrow Wilson drawing for who the first "lucky" draftee will be for the U.S. to step into World War I is not unlike tests that interact with live data. It's random. Who knows what you'll get back. You can fab up data and then destroy it, but what if you are just trying to check a row count and some preexisting local data is making a test break by throwing the count off? It's better to mock if you can. In the example below, FooRepository can be mocked.

[TestMethod]

public void GetAllFoo()

{

   var foo = TestObjects.BuildProgram("aNameForMyFoo");

   foo.Save();

   var foos = this.FooRepository.GetAll();

   Assert.IsTrue(foo.ToList().Count == 1);

}

 
 

Your tests are delicate and they need your love. Be good to them.


Friday, September 16, 2011

truncate a DateTime in Razor with jQuery

In a Razor control such as this:

@Html.EditorFor(model => model.Foo)

 
 

...a DateTime will appear as 1/1/2011 12:00:00 AM unless one proactively alters its appearance. The following is a trick to make the date appear as 1/1/2011

<script type="text/javascript">

   (function () {

      var thinDate = $('#Foo').val().split(' ')[0];

      $('#Foo').val(thinDate);

   })();

</script>

leave off the namespace when writing extension methods!

The real magic for extension methods lies in leaving off the namespace designation!

using System;

public static class DateTimeExtensions

{

   public static string ToYearString(this DateTime dateTime)

   {

      return dateTime.Year.ToString();

   }

}

Thursday, September 15, 2011

jQuery UI draggable quirk in IE9

This will cause problems with jQuery UI's draggable in IE9 as if a TH (with moveableColumn as a class) is "draggable" when one drags and mouses away the cursor will remain as the move cursor until one clicks:

<script language="javascript" type="text/javascript">

   $(function () {

      $('.moveableColumn').hover(function () {

         $(this).attr('style', "cursor: move;");

      },

         function () {

            $(this).attr('style', "cursor: default;");

         }

      );

   });

</script>

 
 

This is the fix:

<script type="text/javascript">

   $(function () {

      $('.moveableColumn').hover(function () {

         $(this).css('cursor', 'move');

      });

   });

</script>

jQuery UI's calendar controls are really easy to use

datepicker is easy to use:

<script>

   $(function () {

      $("#foo").datepicker();

      $("#bar").datepicker();

      $("#baz").datepicker();

   });

</script>

   

<form action="/" method="post">

   <input id="foo" name="foo" type="text" value="" />

   <br />

   <input id="bar" name="bar" type="text" value="" />

   <br />

   <input id="baz" name="baz" type="text" value="" />

   <br />

   <input type="submit" value="Go" />

</font>

Wednesday, September 14, 2011

find your Active Directory username with System.Security.Principal

Sniff your Active Directory username like so:

public static string userName = WindowsIdentity.GetCurrent().Name;

 
 

Use this namespace:

using System.Security.Principal;

a way to check for POST

protected bool IsHttpPost

{

   get { return base.ControllerContext.HttpContext.Request.HttpMethod == "POST"; }

}

Tuesday, September 13, 2011

of parsing MVC routing

MvcHtmlString foo = htmlHelper.ViewContext.RequestContext.HttpContext.Request.Url.AbsoluteUri;

foreach (string key in html.ViewContext.RequestContext.HttpContext.Request.QueryString.Keys) routeDataValues[key] = html.ViewContext.RequestContext.HttpContext.Request.QueryString[key].ToString();

other notes on NuGet

  1. The items in the "Packages" folder should not be checked into source control.
  2. If a bad reference is lingering, check the App.config of the project's folder. Version numbers of NuGet-driven dependencies are kept here.
  3. Add a different package source
    1. Go to: Tools > Library Package Manager > Package Manager Settings
    2. Select "Package Sources"
    3. Add a source

The other benefit of PagedList

Why not do all pagination client side? Why not just get the whole of the record set from the server and then do any pagination with a jQuery widget beyond the grasp of C#? Well, the obviously reason not to do this is that the record set could be very large, tens of thousands of records in size. It will be less of a performance drag to retrieve just a piece of a record set.

But let's say you need the whole of the record set anyways. Let's say you are going to cast the records to a DataTable and append some extra columns onto the table from other database calls to other objects. Once you have the complicated DataTable in our scenario, you need to keep it because you need to be able to sort it on both the appended and original columns. The pages you will show in a paged set will be pieces of this giant table.

Once you are hip deep in this scenario, why would PagedList<T> be beneficial over jQuery-based paging? There is another thing to consider and that is the render time of the screen. If you pump tens of thousands of records into HTML and then show just a dozen of them in pagination, you will not be saved from a lag.

const

public const string FOO = "Bar";

 
 

...varies from...

public static string Foo = "Bar";

 
 

...in that a const is defined upon compilation. It is in memory immediately and one does not have to make one's way through code to the point where it is called to have it in memory.

foo[0] does not work with IEnumerable.

You have to cast the IEnumerable to a List first. Hiss.

Monday, September 12, 2011

Service Locator woes

is this accurate: Dependency Injection & Service Locator are the two types of Inversion of Control?

...or this: IoC = Dependency Injection?

Either way, Service Locator seems inferior to Dependency Injection. It is going to be slower as it requires one to crawl the Application Context and it does not allow one to pass in mock dependencies in testing.

Painful lessons learned regarding PagedList

  1. It seems that one may not cast an IQueryable to an IEnumerable and then turn around and cast the IEnumerable to a PagedList. The IQueryable needs to reach directly to the PagedList before the trip to the database.
  2. .ToPagedList(0, 99999999); should allow you to see everything
  3. .ToPagedList(1, 99999999); should be empty

Sunday, September 11, 2011

I'm still fascinated by ReSharper's ability to refactor foreach loops into lambda expressions.

This...

foreach (DataRow dataRow in myDataTable.Rows)

{

   if (dataRow[FindBy].ToString().ToLower().Contains(FindText.ToLower()))

   {

      myStringList.Add(dataRow["Name"].ToString());

   }

}

 
 

May become...

foreach (DataRow dataRow in myDataTable.Rows.Cast<DataRow>().Where(dataRow => dataRow[FindBy].ToString().ToLower().Contains(FindText.ToLower()))) myStringList.Add(dataRow["Name"].ToString());

Saturday, September 10, 2011

see how NuGet is influencing a project

  1. Right-click on a project in the Solution Explorer
  2. Select "Properties"
  3. Go to the "Build Events" tab

Friday, September 9, 2011

Package source

With regards to NuGet, at Powershell there will be a dropdown menu for "Package source" which will have "NuGet official package source" and “All” as options. We have an in-house library which has a more current version of PagedList than the 1.0 version that will be installed by default when one runs Install-Package PagedList, but I do not yet know how to add it to this list.

Don't try to new up Guids when both newing up objects and using NHibernate

The odd are that NHibernate will not jive with what you are attempting and you will not be able to save your objects. One must specifically open up permissions to allow the alternative.

coercion operator in C# ??

Our subject is foo below. If it isn't null then foo just stays as foo. Otherwise, foo gets set to new List<Bar>();

foo = foo ?? new List<Bar>();

 
 

Is this the coercion operator?? (note the pun of the double question marks)

UPDATE on 3/13/2012: This operator is called the null-coalescing operator.

use conditional logic within @Html.Raw

<tr @Html.Raw(foo == row["Name"].ToString() ? "class=\"shaded\"" : string.Empty)>

Thursday, September 8, 2011

if (foo != null) is a code smell

...per Joel we should replace these instances with lists and just let the lists be empty when applicable.

trying to understand Func

public ActionResult Index()

{

   Func<Int16, string> convertInteger = TryToGiveGermanNameForSingleDigit;

   Int16 numberOfFingersOnOneHand = 5;

   ViewBag.Message = convertInteger(numberOfFingersOnOneHand);

   return View();

}

   

private static string TryToGiveGermanNameForSingleDigit(Int16 digit)

{

   string valueToHandBack;

   switch(digit)

   {

      case 0:

         valueToHandBack = "null";

         break;

      case 1:

         valueToHandBack = "eins";

         break;

      case 2:

         valueToHandBack = "zwei";

         break;

      case 3:

         valueToHandBack = "drei";

         break;

      case 4:

         valueToHandBack = "vier";

         break;

      case 5:

         valueToHandBack = "fünf";

         break;

      case 6:

         valueToHandBack = "sechs";

         break;

      case 7:

         valueToHandBack = "sieben";

         break;

      case 8:

         valueToHandBack = "acht";

         break;

      case 9:

         valueToHandBack = "neun";

         break;

      default:

         valueToHandBack = "Scheisse!";

         break;

   }

   return valueToHandBack;

}

string formatting DateTime

http://www.csharp-examples.net/string-format-datetime/

 
 

Addendum 9/19/2014: This test passes:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TimeKeeping.Tests
{
   [TestClass]
   public class UnitTests
   {
      [TestMethod]
      public void Test()
      {
         DateTime yin = new DateTime(2013,1,2,4,5,6);
         DateTime yang = new DateTime(2013,11,12,14,15,16);
         Assert.AreEqual(String.Format("{0:MM/dd/yyyy HH:mm:ss tt}", yin),
               "01/02/2013 04:05:06 AM");
         Assert.AreEqual(String.Format("{0:MM/dd/yyyy HH:mm:ss tt}", yang),
               "11/12/2013 14:15:16 PM");
         Assert.AreEqual(String.Format("{0:M/d/yy h:m:s tt}", yin), "1/2/13 4:5:6 AM");
         Assert.AreEqual(String.Format("{0:M/d/yy h:m:s tt}", yang), "11/12/13 2:15:16 PM");
      }
   }
}

monkey patching

I paired with Jorge Luna yesterday and during that time we monkey patched an instance of the class for time abstraction that I wrote here like so:

[TestInitialize]

public void TestSetup()

{

   DateService.Now = () =>

   {

      return new DateTime(2011, 9, 8);

   };

}

 

[TestMethod]

public void GetProgramStartDateTest()

{

   var startDate = DateService.Now();

   Assert.AreEqual(new DateTime(2011, 9, 8), startDate);

}

Wednesday, September 7, 2011

an example of creating a DataTable from nothing

[TestMethod]

public void SortingOfDataTableTest()

{

   DataTable dataTable = new DataTable();

   dataTable.Columns.Add("Foo", typeof(string));

   dataTable.Columns.Add("Bar", typeof(Int32));

   dataTable.Columns.Add("Baz", typeof(string));

   dataTable.Rows.Add();

   dataTable.Rows[0][0] = "Qux";

   dataTable.Rows[0][1] = 6;

   dataTable.Rows[0][2] = "Whatever";

   Assert.AreEqual(dataTable.Rows.Count, 1);

   Assert.AreEqual(dataTable.Columns.Count, 3);

   Assert.AreEqual(dataTable.Rows[0][1], 6);

}

sort a DataTable to another DataTable

public void resortDataTable(string sortBy)

{

   if (!sortBy.IsNullOrEmpty())

   {

      IEnumerable<DataRow> query = from row in Whatever.AsEnumerable()

         orderby row.Field<object>(sortBy)

         select row;

      DataTable boundTable = query.CopyToDataTable<DataRow>();

      Whatever = boundTable;

   }

}

what is NuGet?

NuGet is a dependency management tool.

Instead of adding a reference to a project in the usual way in the Solution Explorer, with NuGet it is appropriate to go to: Tools > Library Package Manager > Package Manager Console

At the pane that appears, pick the appropriate project from the "Default project:" dropdown.

Then type the appropriate installation command. Examples:

Tuesday, September 6, 2011

@Html.Raw(whatever) keeps whatever from being encoded

This blog posting touches on it.

two string manipulations

Split a string:

string emailAddress = "tomjaeschke@tomjaeschke.com";

string[] splitUponAtSymbol = emailAddress.Split("@".ToCharArray());

string domainNameHalfOfEmailAddress = splitUponAtSymbol[1];

 
 

Remove the first two characters from a string:

string listOfFoo = "";

foreach (Bar bar in Whatever)

{

   listOfFoo = listOfFoo + ", " + bar.Foo;

}

listOfFoo = listOfFoo.Substring(2, listOfFoo.Length - 2);

use ReSharper to refactor foreach loops to LINQ expressions

Eric Anderson illuminated that JetBrains ReSharper 6 and 5 allow one to refactor foreach loops into LINQ expressions. If you put your cursor at the word "foreach" and ReSharper sees a way to clean it up, a light bulb will appear with a drop down menu nested "inside of it" which expands upon a click. The refactorings are probably going to work better in some cases rather than others. For example, I just refactored this:

Int32 counterOfPrograms = 0;

foreach (Program program in ProgramsDTO.Entities)

{

   DateTime? startDate = program.StartDate();

   dataTable.Rows[counterOfPrograms][1] =

      (startDate != null) ? startDate.Value.Month + "/" + startDate.Value.Year : "";

   counterOfPrograms++;

}

 
 

Into this:

Int32 counterOfPrograms = 0;

foreach (DateTime? startDate in ProgramsDTO.Entities.Select(program

      => program.StartDate()))

{

   dataTable.Rows[counterOfPrograms][1] =

      (startDate != null) ? startDate.Value.Month + "/" + startDate.Value.Year : "";

   counterOfPrograms++;

}

 
 

...and it is only a marginal improvement.

Parting thought: Check out .TakeWhile here.

Monday, September 5, 2011

struggling in replacing foreach instances with lambdas

I am trying to refactor the following foreach (from here) to a select:

foreach (Program program in ProgramsDTO.Entities)

{

   dataTable.Rows[counterOfPrograms][1] = program.GoGetBaz();

   counterOfPrograms++;

}

 
 

My best effort:

var throwAwayVariable = ProgramsDTO.Entities.Select(program => dataTable.Rows[counterOfPrograms++][1] = program.GoGetBaz()).ToList();

 
 

I wish I did not have to cast to a variable I do not need. I wish I could do the following. (I cannot do the following.)

ProgramsDTO.Entities.Select(program => dataTable.Rows[counterOfPrograms++][1] = program.GoGetBaz());

 
 

In trying to clean up other foreach instances here, I have discovered that .Select can be joined to a List or an IEnumerable but not to a collection of DataRow or DataColumn. :( ...I also cannot do the following. (Cannot convert expression type 'void' to return type 'TResult')

var throwAwayVariable = columnNames.Select(columnName => dataTable.Columns.Remove(columnName)).ToList();

 
 

Which I had hoped to do to replace this:

foreach(string columnName in columnNames)

   dataTable.Columns.Remove(columnName);

Sunday, September 4, 2011

an example of using a DataTable with n number of columns in a Razor view

<table style="border: 1px solid black">

   <thead>

      <tr>

      @foreach (DataColumn column in table.Columns)

      {

         <th>@column.Caption</th>

      }

      </tr>

   </thead>

   <tbody>

      @foreach (DataRow row in table.Rows)

      {

         <tr>

         @foreach (var cell in row.ItemArray)

         {

            <td>@cell.ToString()</td>

         }

         </tr>

      }

   </tbody>

</table>

data integration with columns appended to a DataTable

I now have data integration I eluded too here working. Noteworthy:

  1. Below: Program.GoGetBaz() in an example of an API on a partial extending a domain object that reaches out to a different domain object for information. Baz is not a parameter on Program. It is a parameter based on a different parameter on what we will call Qux, a domain object that has a many-to-one relationship with Program (i.e. a child of Program). Is this a good way to approach this or should this method be in the same View Model as FixupDataTable()? I'm still trying to decide. What do you think? The floor is open!

    public virtual Int32 GoGetBaz()

    {

       var quxes = this.Qux.Where(qux => qux.Whatever == true);

       List<QuxChild> quxKids = new List<QuxChild>();

       foreach (Qux qux in quxes)

       {

          quxKids.AddRange(qux.FishYetOneLevelDeeperForBaz());

       }

       return quxKids.Distinct().Count();

    }

  2. We are this sprint ironing out a good way to get data for views. It has been decided that we will both need an IEnumerable<Program> and a DataTable representing a flattened Program snapshot. The later is applicable for handing to a view listing records while former, with all of its nested concerns, is applicable for handing to an edit screen for CRUD concerns against one particular Program in the IEnumerable<Program>. ProgramsDTO, kept on our view model, keeps both concerns at ProgramsDTO.Entities and ProgramsDTO.DataTable.
  3. The content below in white has changed. The content in black is unchanged from here.

 
 

public DataTable FixupDataTable()

{

   //strip away redundant columns

   DataTable dataTable = this.ProgramsDTO.DataTable;

   List<string> columnNames = new List<string>();

   foreach(DataColumn dataColumn in dataTable.Columns)

      if (dataColumn.Caption != "Foo") columnNames.Add(dataColumn.Caption);

   foreach(string columnName in columnNames)

      dataTable.Columns.Remove(columnName);

   

   //rename the Name column

   dataTable.Columns[0].Caption = "Bar";

   

   //add Open Offerings column and populate it

   dataTable.Columns.Add("Baz", typeof(Int32));

   
Int32 counterOfPrograms = 0;

   foreach (Program program in ProgramsDTO.Entities)

   {

      dataTable.Rows[counterOfPrograms][1] = program.GoGetBaz();

      counterOfPrograms++;

   }


   

   //hand back the fixed up DataTable

   this.ProgramsDTO.DataTable = dataTable;

   return this.ProgramsDTO.DataTable;

}

 
 

The above example passes these tests.

Assert.AreEqual(dataTable.Rows.Count,13);

Assert.AreEqual(dataTable.Columns.Count, 2);

Assert.AreEqual(dataTable.Columns[0].Caption, "Bar");

Assert.AreEqual(dataTable.Columns[1].Caption, "Baz");

Assert.AreEqual(dataTable.Rows[0][1], 3);

Assert.AreEqual(dataTable.Rows[1][1], 1);

Assert.AreEqual(dataTable.Rows[2][1], 1);

Assert.AreEqual(dataTable.Rows[3][1], 0);

 
 

Again, forgive my use of foreach. I'll see if I can refactor these away too.

disappearing log4net .dll

This morning I have had the problem suggested here regarding the log4net .dll just disappearing. The posting I am linking to here (same link) suggests that one should set Copy Local to true for both log4net and NHibernate.

Saturday, September 3, 2011

How to add columns to DataTables

public DataTable FixupDataTable()

{

   //strip away redundant columns

   DataTable dataTable = this.ProgramsDTO.DataTable;

   List<string> columnNames = new List<string>();

   foreach(DataColumn dataColumn in dataTable.Columns)

      if (dataColumn.Caption != "Foo") columnNames.Add(dataColumn.Caption);

   foreach(string columnName in columnNames)

      dataTable.Columns.Remove(columnName);

   

   //rename the Name column

   dataTable.Columns[0].Caption = "Bar";

   

   //add Open Offerings column and populate it

   dataTable.Columns.Add("Baz", typeof(Int32));

   foreach (DataRow dataRow in dataTable.Rows) dataRow[1] = 88;

   

   //hand back the fixed up DataTable

   this.ProgramsDTO.DataTable = dataTable;

   return this.ProgramsDTO.DataTable;

}

 
 

The above example passes these tests.

Assert.AreEqual(dataTable.Rows.Count,13);

Assert.AreEqual(dataTable.Columns.Count, 2);

Assert.AreEqual(dataTable.Columns[0].Caption, "Bar");

Assert.AreEqual(dataTable.Columns[1].Caption, "Baz");

Assert.AreEqual(dataTable.Rows[0][1], 88);

 
 

Of course, it is nonsensically to have a column with 88 in it a bunch of times over and over. We will need to hydrate the column with actual data. I'm working on that at work now. More soon. Also, forgive my use of foreach. I'll see if I can refactor these away too.

Friday, September 2, 2011

learn from Woodrow Wilson's example

I am about to leave for the day having wrapped up working the month of August (since August first) and two days in September for New Iron at AMD. The three day Labor Day weekend beckons, but I know I will spend it up here in my cube working. That's alright. I love my job.

I've started keeping this blog in the name of ramping myself up on the app development I am stepping into. I feel I am largely ramped up now. I can think of a couple of things I don't know, but maybe I don't need to know those things just yet as it is...

  • In the first sprint just before I started, or perhaps even before then, a means to pull down Active Directory records for AMD (and furthermore base login and permissions around Active Directory) was implemented. The records are not of queries directly. A periodic push by a "middle app" publishes a list that is consumed by our app. I don't understand it. But then, I don't need to. It's a solved problem that has been hardly mentioned in my time here. If there is a sprint around Active Directory in the future, I can ramp up on it then.
  • QUnit for jQuery unit testing is another concern I do not have insight into. It is a part of our app. Again... when the time comes...

Woodrow Wilson, the best American president, won the 1st World War by waiting until the last possible moment to get in*. When he was in, he deferred to the military minds about him and let good people manage what they best knew how to manage without interference.

For all of the ramp up that comes with the fire hose of new information tied to ramping up on a new app in a new team, I am trying to not be distracted in such a way that I make a mountain out of molehill in worrying about every possible little thing I could be worrying about.

I'm also not about to distract my superiors with questions about Active Directory and QUnit when nothing to do with either is on my plate this sprint.

 
 
 
 

*I used a variation of this strategy when I used to play Magic the Gathering in 1995 and 1996 while in college at TSTC. I would attack no one and cause no problems for as long as I could, building while others fought.

when to use chaining

Today I experimented with an extension method that Kar-Khan wrote for casting an IEnumerable<T> to a DataTable. It starts out like so...

public static class GenericExtensions

{

   public static DataTable ToDataTable<T>(this IEnumerable<T> collection)

   {

 
 

...and may be used as such:

var foo = getIEnumerableOfSomeVariety();

var bar = foo.ToDataTable();

 
 

Kar-Khan recommended against doing this:

var bar = getIEnumerableOfSomeVariety().ToDataTable();

 
 

Why? Why not chain the two concerns together as is done here? Kar-Khan asserted that, in the case of his extension method, if the IEnumerable is null there will be trouble! (Expect an exception.) The code above comes from a (predictable) test class, but arguably this is merited:

var foo = getIEnumerableOfSomeVariety();

DataTable bar = new DataTable();

if (foo != null) bar = foo.ToDataTable();

 
 

It is good policy to not go nuts with chaining for this reason. You have to consider if there is a weak link in a chain. Exceptions:

James and the Giant foreach

I have an idea for a geek movie parody. It will be called "James and the Giant foreach" (instead of "James and the Giant Peach") and it will be about a developer named James who one day, while working, finds a giant foreach loop. Feeling brave, our hero, James, ventures inside and within the foreach he finds... wait of it... a bunch of bugs!


Back to real life: Joel Holder is asserting the foreach is old school and should be stepped away from where possible. An example:

 
 

var bars = foos.Where(foo => foo.IsOk).Select(foo => new Bar() {FooName = foo.Name, BarInteger = foo.SecondInteger}).ToList();

 
 

The copy above in white may be used to replace the copy below in black if one also uses the System.Linq namespace.

 
 

using System.Collections.Generic;

using Microsoft.VisualStudio.TestTools.UnitTesting;

using MyApp.Helpers;

namespace MyApp.Tests

{

   [TestClass]

   public class Whatever

   {

      [TestMethod]

      public void foreach_versus_select()

      {

         Foo uno = new Foo

         {

            Name = "uno",

            IsOk = true,

            FirstInteger = 88,

            SecondInteger = 213

         };

         Foo dos = new Foo

         {

            Name = "dos",

            IsOk = false,

            FirstInteger = 123,

            SecondInteger = 87

         };

         Foo tres = new Foo

         {

            Name = "tres",

            IsOk = true,

            FirstInteger = 37,

            SecondInteger = 56

         };

         Foo cuatro = new Foo

         {

            Name = "cuatro",

            IsOk = true,

            FirstInteger = 253,

            SecondInteger = 568

         };

         

         List<Foo> foos = new List<Foo> { uno, dos, tres, cuatro };

         List<Bar> bars = new List<Bar>();

         

         
foreach (Foo foo in foos)

         {

            if (foo.IsOk)

            {

               bars.Add(new Bar

               {

                  FooName = foo.Name,

                  BarInteger = foo.SecondInteger

               });

            }

         }


         

         Assert.AreEqual(bars.Count, 3);

         Assert.AreEqual(bars[1].FooName, "tres");

         Assert.AreEqual(bars[2].BarInteger, 568);

      }

   }

}

Assert.Inconclusive("Things are vague!");

fascinates me

Right-click in a file and pick "Create Unit Tests..."

...to create a test class file for a class.

more cygwin notes

The following appends the notes here.
  • Ctrl-C lets one wiggle back out of reading a file as tail -f sql.log20110831.9 empowers.
  • Right-click at the icon at the upperleft of the Window holding cygwin and select: Edit > Mark ...to be able to select text. Right-click to stop a selection and copy it to the clipboard.

Thursday, September 1, 2011

of cygwin and log4net

At http://www.cygwin.com/ one may download Cygwin!

<file value=" ...values in log4net.xml configuration files should be updated to put logs into a convenient place.

Spin up cygdrive. Run cd C:/ to start at the root of your C drive and then navigate to the appropriate folder. Remember these commands to help in moving about folders:

  • ls shows the contents of a folder (like dir at the cmd.exe shell)
  • cd whatever takes you into the whatever folder
  • cd "what ever" takes you into the what ever folder
  • cd.. takes you up a folder
  • tail -f sql.log20110831.9 is an example of reading a log4net log

mail routing in Microsoft Outlook

http://office.microsoft.com/en-us/outlook-help/manage-e-mail-messages-with-rules-HA010355682.aspx touches on how to route inbound mail off to certain folders in Microsoft Outlook 2010 and http://office.microsoft.com/en-us/outlook-help/manage-messages-by-using-rules-HA010096803.aspx?pid=CH101032741033 gives how to do the same for Microsoft Outlook 2007.

how to aggregate LinqSpecs specifications

Kar-Khan wrote a means to spool up LinqSpec specifications today which is something we have been struggling with. Here is his class:

using LinqSpecs;

namespace AMD.Avalanche.Core.Utils

{

   public class SpecificationBuilder<T>

   {

      private Specification<T> _masterSpec;

      

      public SpecificationBuilder() { }

      

      public void AddAnd(Specification<T> specification)

      {

         if (_masterSpec == null)

            _masterSpec = specification;

         else

            _masterSpec = new AndSpecification<T>(_masterSpec, specification);

      }

      

      public Specification<T> ToSpecification()

      {

         return _masterSpec;

      }

   }

}

 
 

How to use it: In...

var specBuilder = new SpecificationBuilder<Foo>();

specBuilder.AddAnd(new AdHocSpecification<Foo>(
p => p != null));

var bar = specBuilder.ToSpecification();

 
 

p => p != null is an example of a Specification<Foo> that may be shaped like so:

public static Specification Sanity(Boolean isOk)

{

   var isSane = new AdHocSpecification(p => p.IsOk == isOk);

   return isSane;

}

 
 

...and handed in like so:

var specBuilder = new SpecificationBuilder<Foo>();

specBuilder.AddAnd(new AdHocSpecification<Foo>(WebProgramSpecs.Sanity(true)));

var bar = specBuilder.ToSpecification();

Shift-F5 stops debugging in Visual Studio.

Duh.

develop test-first

Trying to approach development in a better way this month:
  1. Fight through unknowns in a unit test.
  2. Set breakpoints in the test.
  3. Right-click in the file and select: Run Tests
  4. Let the test run or stop it.
  5. The "Test Results" pane should appear and moreover this pane should be kept around, docked.
  6. Click on "Debug" in the "Test Results" pane.
  7. Do the usual debugging
    • F5 goesto the next breakpoint
    • F10 goes to the next line in the same file
    • F11 goes to the next line called even if it is in another file

Shelve in Team Foundation Server

Right-click at the top of your solution in Solution Explorer and select Shelve Pending Changes... to save a snapshot of your environment in TFS.

Go to: File > Source Control > Unshelve Pending Changes... to see a list of saved snapshots and monkey around with them.