Monday, April 30, 2012

unicode forward slash

%2f is the unicode forward slash.

Copy always... Content

When publishing a project out of Visual Studio 2010 to a folder, you may wish to look at the properties for a given file and assure that the "Build Action" setting is set to "Content" and the "Copy to Output Directory" setting is set to "Copy always" as the absence of these settings may prevent a file from being published. Warning: "Copy always" will put a copy in the bin folder which may or may not be desired.

Sunday, April 29, 2012

smart phone bar codes

http://mashable.com/2008/05/19/scanlife-iphon/ and http://mashable.com/2008/01/29/google-barcode-ads/ touch on the new barcodes for smart phones from Google which I have not yet played with. The second link suggests that your iPhone will interpret a URL from the 2D barcode and take you there.

Math.Pow is cool and there is no way to have a Func of void.

What follows is a refactoring of the second controller here. Notice that I had to use Action and that I made Raiser much simplier. I read of Math.Pow today in: C# 4.0 in a Nutshell

using System;
namespace DelegateExample.Controllers
{
   public class CalculationController : BaseController
   {
      private string thirdValue;
      
      public RenderJsonResult Go(string act, string one, string two)
      {
         Int32 firstInteger = Convert.ToInt32(one);
         Int32 secondInteger = Convert.ToInt32(two);
         Action mathDelegate;
         switch(act)
         {
            case "add":
               mathDelegate = () => Adder(firstInteger, secondInteger);
               break;
            case "multiply":
               mathDelegate = () => Multiplier(firstInteger, secondInteger);
               break;
            case "power":
               mathDelegate = () => Raiser(firstInteger, secondInteger);
               break;
            default:
               mathDelegate = () => StatusQuoSustainer(firstInteger);
               break;
         }
         mathDelegate();
         var result = new { calulation = thirdValue };
         return RenderJson(result);
      }
      
      private void Adder(Int32 firstInteger, Int32 secondInteger)
      {
         thirdValue = (firstInteger + secondInteger).ToString();
      }
      
      private void Multiplier(Int32 firstInteger, Int32 secondInteger)
      {
         thirdValue = (firstInteger * secondInteger).ToString();
      }
      
      private void Raiser(Int32 firstInteger, Int32 secondInteger)
      {
         thirdValue = Math.Pow(firstInteger,secondInteger).ToString();
      }
      
      private void StatusQuoSustainer(Int32 loneInteger)
      {
         thirdValue = loneInteger.ToString();
      }
   }
}

DNS Tools

http://www.viewdns.info/ was shared over twitter just now. It seems pretty awesome.

Saturday, April 28, 2012

Closures come in many shapes!

The C# example below comes from a refactoring of the controller here. This is based on how Jon Skeet defines a closure on page 151 of his first edition of "C# in Depth." He makes a distinction between outer variables such as firstInteger and secondInteger which exist in the same method as the closure and are merely used by it, and a captured variable such as captured which gets effected by the closure. The x name for the ThreadStart comes from Mr. Skeet, so don't blame me for the odd variable name. :P It is important to note that if one does not run the line reading x(); that the magic will never happen and captured's shape will remain unchanged. This approach allowed me to drop that silly StatusQuoSustainer method from the controller as I no longer need a default for my case statement! Yay! As you can see, when x(); is run it considers captured and then effects the captured variable based upon its contents with the outer variables.

using System;
using System.Threading;
namespace DelegateExample.Controllers
{
   public class CalculationController : BaseController
   {
      public RenderJsonResult Go(string act, string one, string two)
      {
         string captured = act;
         Int32 firstInteger = Convert.ToInt32(one);
         Int32 secondInteger = Convert.ToInt32(two);
         ThreadStart x = delegate
                        {
                           switch (captured)
                           {
                              case "add":
                                 captured = Adder(firstInteger, secondInteger);
                                 break;
                              case "multiply":
                                 captured = Multiplier(firstInteger, secondInteger);
                                 break;
                              case "power":
                                 captured = Raiser(firstInteger, secondInteger);
                                 break;
                           }
                        };
         x();
         var result = new { calulation = captured };
         return RenderJson(result);
      }
      
      private string Adder(Int32 firstInteger, Int32 secondInteger)
      {
         return (firstInteger + secondInteger).ToString();
      }
      
      private string Multiplier(Int32 firstInteger, Int32 secondInteger)
      {
         return (firstInteger * secondInteger).ToString();
      }
      
      private string Raiser(Int32 firstInteger, Int32 secondInteger)
      {
         Int32 growingInteger = firstInteger;
         Int32 counterIntger = 1;
         while (counterIntger < secondInteger)
         {
            growingInteger = growingInteger * firstInteger;
            counterIntger++;
         }
         return growingInteger.ToString();
      }
   }
}

 
 

The next example is also of C#, illuminates the = () => operator, and comes from "C# 4.0 in a Nutshell: The Definitive Reference" by Joseph Albahari and Ben Albahari. The operator signifies a closure per page 132. I have modified the controller here to make this code. These closures allow us to pull the inbound values for a Func out of the Func's signature and instead set them on the other side of the operator. So instead of asserting that a Func<Int32,Int32,string> is equal to a method we may instead assert that a Func<string> is equal to a method while clarifying that the method takes two Int32 types for inbound parameters. Not only is this a little bit easier to read, but we are now no longer in a straightjacket in terms of restraints for inbound parameters. We may use a method of any manner of signature so long as the method returns the string. See how I was able to clean up StatusQuoSustainer. I removed an arbitrary variable once I was able to do so.

using System;
namespace DelegateExample.Controllers
{
   public class CalculationController : BaseController
   {
      public RenderJsonResult Go(string act, string one, string two)
      {
         Int32 firstInteger = Convert.ToInt32(one);
         Int32 secondInteger = Convert.ToInt32(two);
         Func<string> mathDelegate;
         switch(act)
         {
            case "add":
               mathDelegate = () => Adder(firstInteger, secondInteger);
               break;
            case "multiply":
               mathDelegate = () => Multiplier(firstInteger, secondInteger);
               break;
            case "power":
               mathDelegate = () => Raiser(firstInteger, secondInteger);
               break;
            default:
               mathDelegate = () => StatusQuoSustainer(firstInteger);
               break;
         }
         string thirdValue = mathDelegate();
         var result = new { calulation = thirdValue };
         return RenderJson(result);
      }
      
      private string Adder(Int32 firstInteger, Int32 secondInteger)
      {
         return (firstInteger + secondInteger).ToString();
      }
      
      private string Multiplier(Int32 firstInteger, Int32 secondInteger)
      {
         return (firstInteger * secondInteger).ToString();
      }
      
      private string Raiser(Int32 firstInteger, Int32 secondInteger)
      {
         Int32 growingInteger = firstInteger;
         Int32 counterIntger = 1;
         while (counterIntger < secondInteger)
         {
            growingInteger = growingInteger * firstInteger;
            counterIntger++;
         }
         return growingInteger.ToString();
      }
      
      private string StatusQuoSustainer(Int32 loneInteger)
      {
         return loneInteger.ToString();
      }
   }
}

 
 

The final example comes from Derek Greer and is of jQuery. What follows is a revision of the TryToCalculate() method here. I broke the sanity checking up into two hunks, one inside of another, to illustrate that one may create a closure and prep it for use before actually using it downstream in code. In crafting this last example I realized that I've misspelled growingInteger as growingIntger in all of my previous examples. Whatever.

function TryToCalculate() {
   var checky = "";
   var checkact = "" + $('input[name=act]:checked').val();
   checky = checky + checkact;
   if (checky.indexOf("undefined") < 0) {
      var calculationRules = function (act) {
         return function (firstInteger, secondInteger) {
            if (act == "add") return firstInteger + secondInteger;
            if (act == "multiply") return firstInteger * secondInteger;
            var growingInteger = firstInteger;
            var counterInteger = 1;
            while (counterInteger < secondInteger)
            {
               growingInteger = growingInteger * firstInteger;
               counterInteger++;
            }
            return growingInteger;
         };
      };
      closure = calculationRules(checky);
      var checkone = "" + $('input[name=one]:checked').val();
      var checktwo = "" + $('input[name=two]:checked').val();
      checky = checky + checkone + checktwo;
      if (checky.indexOf("undefined") < 0) {
         var castingOne = parseInt(checkone);
         var castingTwo = parseInt(checktwo);
         document.getElementById('equals').innerHTML = closure(castingOne,castingTwo);
      }
   }
}

Friday, April 27, 2012

Multicast Delegate Example

using System;
namespace DelegateExample.Controllers
{
   public class CalculationController : BaseController
   {
      private Int32 dependentVariable;
      
      public RenderJsonResult Go(string act, string one, string two)
      {
         
//Step One: Prep Chain of Delegates
         dependentVariable = Convert.ToInt32(one);
         Func<Int32,Int32> mathDelegate;
         mathDelegate = Adder;
         mathDelegate += Multiplier;
         mathDelegate += Reducer;
         
         
//Step Two: Use Delegate with Numeric Data
         Int32 thirdValue = mathDelegate(Convert.ToInt32(two));
         var result = new { calulation = thirdValue.ToString() };
         return RenderJson(result);
      }
      
      private Int32 Adder(Int32 independentVariable)
      {
         dependentVariable = dependentVariable + independentVariable;
         return dependentVariable;
      }
      
      private Int32 Multiplier(Int32 independentVariable)
      {
         dependentVariable = dependentVariable * independentVariable;
         return dependentVariable;
      }
      
      private Int32 Reducer(Int32 independentVariable)
      {
         dependentVariable = dependentVariable - independentVariable;
         return dependentVariable;
      }
   }
}

 
 

The code offers a refactoring of the controller here. (The act string is used for nothing.) What happens? Two variables will be handed in. The first will be kept in a private field. The second will be used to mess with the value of the private field once it has been set. If 5 and 7 are handed in then 5 will go into the private field and 7 will be used to alter the 5. We use += to shove numerous methods into our delegate in a precession. All of the methods will be handed the 7 to use in effecting the contents of the private field. The methods will fire off in the order they were specified by way of += concatenation. The methods do not hand data from one method to the next. (The return data is ignored until the very last method runs.) Instead, a private field is used to manage state. 7 gets added to 5 making it 12. 7 gets multiplied against 12 making it 84. 7 gets subtracted from 84 making it 77. 77 is returned to us. This is another something I learned from "C# 4.0 in a Nutshell."

Make a pie chart in a SSRS report.

I figured out how to make a pie chart in an .rdl file inside of BIDS for SSRS2008. Assisting me were these links:

  1. http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/MS-SQL_Reporting/A_1884-Pie-Chart-Techniques.html
  2. http://msdn.microsoft.com/en-us/library/cc281304.aspx

 
 

Steps:

  1. Drag a chart out of the Toolbox to the Design view of a report.
  2. A dialog box will appear prompting you to pick a type of report. Pick "Pie" under "Shape."
  3. You will have a pie chart. If you click on it twice you should see three areas appear about three edges of the chart reading:
    • Drop date fields here
    • Drop series fields here
    • Drop category fields here
  4. Open the Report Data pane. You will find it at: View > Report Data
  5. Drag the field you wish to track to "Drop category fields here" first. (This should make the legend populate)
  6. Drag the field you wish to track to "Drop date fields here" next. (This should calculate the pieces of the pie)

 
 

I am assuming here that you wish to pick a column, such as FullName, which has both varying values and duplicates of the varying values, from a dataset and report percentages on how much of the record set John Doe appears in as opposed to Joe Shmoe.

If you right click on the "Drop date fields here" item and select "Series Properties..." you should get a dialog box like the leftmost below and clicking the fx button by the Value field should produce a dialog box like the rightmost below.

Share photos on twitter with Twitpic

=Count(Fields!FullName.Value)

...should calculate the count of FullName for a given pie slice.

Specify output parameters in stored procedures and set them up so that you do not have to specific inbound values.

ALTER procedure [dbo].[Whatever]
   @foo int,
   @bar int,
   @baz datetime = null OUTPUT,
   @qux datetime = null OUTPUT
as

 
 

Bonus: Today I learned that a stored procedure may hand back output parameters and even another dataset along side a dataset procured with a select statement!

select all columns from one table within a SQL join

foo.bar could be replaced with foo.* here

the TOP keyword in MSSQL

SELECT * FROM vwWhatever

 
 

May be refactored as follows to ensure the query does not time out in trying to pull back too many records.

SELECT TOP 1000 * FROM vwWhatever

 
 

Update on 10/22/2012: I think the 1000 above should be surrounded in parenthesis.

Thursday, April 26, 2012

casting a child class to a parent interface

There is an example like this in "C# 4.0 in a Nutshell" that I like:

namespace Whatever
{
   public interface Ape
   {
      int UseTool();
   }
}

 
 

Let's say Man inherits from Ape like so:

namespace Whatever
{
   public class Man : Ape
   {
      public string Speak()
      {
         return "It is EASY for me to talk.";
      }
      
      public int UseTool()
      {
         return 42;
      }
   }
}

 
 

Then this test would work as Ape has placeholder for UseTool() to be filled by Man.

[TestMethod]
public void ApeMayUseTool()
{
   Man man = new Man();
   Ape ape = man;
   Assert.AreEqual(ape.UseTool(), 42);
}

 
 

One could also not make our ape Speak() however. The following line will not compile.

ape.Speak();

 
 

Also, if one uses a class instead of an interface, the UseTool method CANNOT be private like so:

namespace Whatever
{
   public class Ape
   {
      private int UseTool()
      {
         return 21;
      }
   }
}

 
 

I made the mistake of thinking the above was feasible.

You may show the total number of records in an SSRS report.

Get a total count of records like so in SSRS:

<Value>= Count(Fields!TimeEntryID.Value)</Value>

 
 

Try specifying the dataset as seen below if you are told that the field holding the Value node "references a field in an aggregate expression without a scope. A scope is required for all aggregates in the page header or footer which reference fields."

<Value>= Count(Fields!TimeEntryID.Value, "DataSet1")</Value>

 
 

Other things I tried which did not work:

  • <Value>= Sum(iif(Fields!TimeEntryID.Value,0,0,1))</Value>
  • <Value>= Sum(iif(Fields!TimeEntryID.Value,0,0,1), "DataSet1")</Value>

 
 

If the iifs were to work, the second parameter shows the value to match, the third parameter shows the value to use in the event of a match, and the fourth parameter shows the value to use in the event of a mismatch.

difference between Parameters and Fields in SSRS reports

Having this in a report:

<Value>= "Logged Hours during the period from " & Parameters!StartDate.Value & " to " & Parameters!EndDate.Value</Value>

 
 

...assumes that StartDate and EndDate are handed in as parameters while having this in a report:

<Value>= "Logged Hours during the period from " & Fields!StartDate.Value & " to " & Fields!EndDate.Value</Value>

 
 

...assumes that StartDate and EndDate are handed in back from a stored procedure or other query as part of the dataset:

<DataSets>
   <DataSet Name="MyDataSet">
      <Fields>
         <Field Name="StartDate">
            <DataField>StartDate</DataField>
            <rd:TypeName>System.DateTime</rd:TypeName>
         </Field>
         <Field Name="EndDate">
            <DataField>EndDate</DataField>
            <rd:TypeName>System.DateTime</rd:TypeName>
         </Field>
         <Field Name="MoreStuff">
            <DataField>MoreStuff</DataField>
            <rd:TypeName>System.String</rd:TypeName>
         </Field>

jqGuid might be worth a look.

Wednesday, April 25, 2012

SQL Server Business Intelligence Development Studio looks like Visual Studio 2008.

But you use it for editing .rdl (reports) and .rds (data sources) files for SSRS. You install BIDS as part of Microsoft SQL Server 2008. Here one may modifty the parameters that get passed to a stored procedure that an .rdl wraps.

<ReportParameters>
   <ReportParameter Name="StartDate">
      <DataType>DateTime</DataType>
      <AllowBlank>true</AllowBlank>
      <Prompt>StartDate</Prompt>
   </ReportParameter>
   <ReportParameter Name="EndDate">
      <DataType>DateTime</DataType>
      <AllowBlank>true</AllowBlank>
      <Prompt>EndDate</Prompt>
   </ReportParameter>
</ReportParameters>

edit security in SSRS2008

At the "Home" for SQL Server Reporting Services, when editing via Internet Explorer, one should see a list of project folders. Mousing over any one folder should reveal a dropdown arrow at the right of any one item. Clicking the arrow opens a submenu and in selecting "Security" there one may see/edit the users and roles assigned to the suite of reports. From within a suite of reports, one may click a comparable arrow to get a comparable submenu for a data source. Picking "Security" from this menu will open a screen for configuring how the data source will expose the MSSQL Database holding the tables or stored procedures needed by reports.

overwrite in TFS

When Team Foundation Server tells you: "The file Web.config cannot be saved because it is write-protected. You can either save the file in a different location or Microsoft Visual Studio can attempt to remove the write-protection and overwrite the file in its current location." you can click the overwrite button to break the read-only status on the file in question.

Monday, April 23, 2012

Getting at that old stuff in SourceSafe via Visual Studio 2005 is clunky.

This suggests:

  1. Go to: Tools > Options > Source Control > Plug-In Selection
  2. In the combo box in that page, select the Visual SourceSafe plug-in.
  3. Then to access the Projects already on SourceSafe you use the File > Web Site... dialog, and click the SourceSafe button on the left bar of the Open Project dialog.

Sunday, April 22, 2012

QueueExplorer

QueueExplorer is a tool for browsing MSMQ content.

Type "powershell" at the start menu to bring up Windows PowerShell ISE in Windows 7.

You may open .ps1 files with PowerShell.

"Set As Start Project" for .svc

If one right-clicks on an .svc file in Visual Studio at the Solution Explorer and picks "Set As Start Project" (assuming the .svc file is in a startup project) one will then get a WCF Test Client to interact with upon running the solution.

Run the Command Prompt as an Administrator.

Right-click at: Start Menu > All Programs > Accessories > Command Prompt ...and then select Run as administrator to be unhindered. I need this to run some .bat files in a particular app.

Use Action instead of Func when you wish for a Func to return nothing.

Imagine if, in this scenario, one was to:

  1. make the private methods return void (warning: this is a silly example)
     
  2. replace these two lines:
    string thirdValue = mathDelegate(firstInteger, secondInteger);
    var result = new { calulation = thirdValue };

     
    with these two lines:
    mathDelegate(firstInteger, secondInteger);
    var result = new { calulation = "?"};

     
  3. replace this line:
    Func<Int32,Int32,string> mathDelegate;
     
    with:
    Func<Int32,Int32> mathDelegate;
     

 
 

It wouldn't work! You cannot compile this. C# 4.0 in a Nutshell has pointed out to me that the last parameter in the angle brackets of a Func is the expected return type! One must use Action in lieu of Func like so to get the desired effect:

Action<Int32,Int32> mathDelegate;

 
 

I find a lot of the nuisances that one must be obedient to in the name of shapeshifting in various ASP.NET circumstances to just be goofy, not intuitive, and impossible to guess at without the crutch of reference. Another example: The order and number of parameters that go into an ActionLink effect an ActionLink in really odd ways. Whatever.

Saturday, April 21, 2012

The Func of C# makes delegates easier.

More magic from C# 4.0 in a Nutshell: I found it easy to get rid of the independent delegate called MathyThing in its own file here by replacing it with a Func of <Int32,Int32,Int32> shape. I then refactored the controller below to make the potential methods to be given to the Func return strings instead of integers. Why? To distinguish the return value by making it a different type. The Func took a <Int32,Int32,string> shape to accomodate this. The last value is the return value. What is the Func for? As you can see it gets rid of the need to have another file somewhere to keep code for a delegate's shape.

using System;
namespace DelegateExample.Controllers
{
   public class CalculationController : BaseController
   {
      public RenderJsonResult Go(string act, string one, string two)
      {
         
//Step One: Make Sense of Act
         Func<Int32,Int32,string> mathDelegate;
         switch(act)
         {
            case "add":
               mathDelegate = Adder;
               break;
            case "multiply":
               mathDelegate = Multiplier;
               break;
            case "power":
               mathDelegate = Raiser;
               break;
            default:
               mathDelegate = StatusQuoSustainer;
               break;
         }
         
         
//Step Two: Make Sense of Numeric Data
         Int32 firstInteger = Convert.ToInt32(one);
         Int32 secondInteger = Convert.ToInt32(two);
         
         
//Step Three: Use Act with Numeric Data
         string thirdValue = mathDelegate(firstInteger, secondInteger);
         var result = new { calulation = thirdValue };
         return RenderJson(result);
      }
      
      private string Adder(Int32 firstInteger, Int32 secondInteger)
      {
         return (firstInteger + secondInteger).ToString();
      }
      
      private string Multiplier(Int32 firstInteger, Int32 secondInteger)
      {
         return (firstInteger * secondInteger).ToString();
      }
      
      private string Raiser(Int32 firstInteger, Int32 secondInteger)
      {
         Int32 growingInteger = firstInteger;
         Int32 counterIntger = 1;
         while (counterIntger < secondInteger)
         {
            growingInteger = growingInteger * firstInteger;
            counterIntger++;
         }
         return growingInteger.ToString();
      }
      
      private string StatusQuoSustainer(Int32 firstInteger, Int32 secondInteger)
      {
         return firstInteger.ToString();
      }
   }
}

Delegates don't have to be intimidating.

using System;
namespace DelegateExample.Models
{
   public delegate Int32 MathyThing(Int32 firstInteger, Int32 secondInteger);
}

 
 

The item above is a delegate! I've been building a silly little calculator app today and the code below uses the delegate above while replacing the CalculationController as documented here. The one action in CalculationController will have handed to it three strings. The first string will contain one of three words: add, multiply, or power. The other two strings are integers in string form. Why should we care about delegates? I am reading C# 4.0 In A Nutshell and I get the impression that one would use a delegate to prep upstream for something that will be needed downstream so to speak. Observe:

namespace DelegateExample.Controllers
{
   public class CalculationController : BaseController
   {
      public RenderJsonResult Go(string act, string one, string two)
      {
         
//Step One: Make Sense of Act
         MathyThing mathDelegate;
         switch(act)
         {
            case "add":
               mathDelegate = Adder;
               break;
            case "multiply":
               mathDelegate = Multiplier;
               break;
            case "power":
               mathDelegate = Raiser;
               break;
            default:
               mathDelegate = StatusQuoSustainer;
               break;
         }
         
         
//Step Two: Make Sense of Numeric Data
         Int32 firstInteger = Convert.ToInt32(one);
         Int32 secondInteger = Convert.ToInt32(two);
         
         
//Step Three: Use Act with Numeric Data
         Int32 thirdInteger = mathDelegate(firstInteger, secondInteger);
         var result = new { calulation = thirdInteger.ToString() };
         return RenderJson(result);
      }
      
      private Int32 Adder(Int32 firstInteger, Int32 secondInteger)
      {
         return firstInteger + secondInteger;
      }
      
      private Int32 Multiplier(Int32 firstInteger, Int32 secondInteger)
      {
         return firstInteger * secondInteger;
      }
      
      private Int32 Raiser(Int32 firstInteger, Int32 secondInteger)
      {
         Int32 growingInteger = firstInteger;
         Int32 counterIntger = 1;
         while (counterIntger < secondInteger)
         {
            growingInteger = growingInteger * firstInteger;
            counterIntger++;
         }
         return growingInteger;
      }
      
      private Int32 StatusQuoSustainer(Int32 firstInteger, Int32 secondInteger)
      {
         return firstInteger;
      }
   }
}

 
 

StatusQuoSustainer above is silly and unneeded. I had to have a default on my switch statement even though there is no way the default will ever be used. I could have used Adder again in lieu of StatusQuoSustainer, but I feared that would be confusing.

Newtonsoft.Json may be used in an ASP.NET MVC Project.

I refined the function at the base of this blob of jQuery as given below in the name of updating the question mark in this table.

function TryToCalculate() {
   var checky = "";
   var checkact = "" + $('input[name=act]:checked').val();
   var checkone = "" + $('input[name=one]:checked').val();
   var checktwo = "" + $('input[name=two]:checked').val();
   checky = checky + checkact + checkone + checktwo;
   if (checky.indexOf("undefined") < 0) {
      var callback = function (data) {
         document.getElementById('equals').innerHTML = data.calulation;
      };
      var message = $.ajax({
         type: "POST",
         url: "/Calculation/Go/?act=" + checkact
         + "&one=" + checkone
         + "&two=" + checktwo,
         dataType: 'json',
         success: callback
      }).responseText;
   }
}

 
 

Alright, the AJAX above reaches out to the one action, which I will later refine so that "?" isn't returned all of the time, in this controller:

namespace DelegateExample.Controllers
{
   public class CalculationController : BaseController
   {
      public RenderJsonResult Go(string act, string one, string two)
      {
         var result = new {calulation = "?"};
         return RenderJson(result);
      }
   }
}

 
 

Using the following links...

  1. http://iridescence.no/post/ASPNET-MVC-ActionResult-for-Rendering-JSON-using-JSONNET.aspx
  2. http://james.newtonking.com/pages/json-net.aspx
  3. http://json.codeplex.com/releases/view/85975
  4. http://tom-jaeschke.blogspot.com/2012/01/here-is-some-interesting-ajax-we.html

 
 

...I crafted this:

using System.Web.Mvc;
using Newtonsoft.Json;
namespace DelegateExample.Controllers
{
   public class RenderJsonResult : ActionResult
   {
      public object Result { get; set; }
      
      public override void ExecuteResult(ControllerContext context)
      {
         context.HttpContext.Response.ContentType = "application/json";
         JsonSerializer serializer = new JsonSerializer();
         serializer.Serialize(context.HttpContext.Response.Output, this.Result);
      }
   }
}

 
 

I also had to make a "BaseController" like so. I suppose I could have just stuck the one method below in CalculationController, but a better pattern for this sort of thing begs for a base controller. It seems like every controller could potentially use the method below.

using System.Web.Mvc;
namespace DelegateExample.Controllers
{
   public class BaseController : Controller
   {
      protected RenderJsonResult RenderJson(object obj)
      {
         return new RenderJsonResult { Result = obj };
      }
   }
}

pressing the space bar to select a radio button is the same as clicking upon it

I wanted to have an event fire whenever anyone altered one of the radio buttons here. I did not plan well as I wrote three seperate classes for the three seperate controls. Anyways... I wanted to make sure I covered myself for a mouse click, an arrow key click, and a space bar click. I tried to write some logic around keyCode 32 (for the space bar), but as it turns out, when you click the space bar to select a radio button, it fires the click event!

<script language="javascript" type="text/javascript">
   $(function () {
      $('.act').keypress(function (e) {
         switch (e.keyCode) {
            case 37:
               TryToCalculate();
               break;
            case 38:
               TryToCalculate();
               break;
            case 39:
               TryToCalculate();
               break;
            case 40:
               TryToCalculate();
               break;
         }
      });
      $('.act').bind('click', function () {
         TryToCalculate();
      });
      $('.one').keypress(function (e) {
         switch (e.keyCode) {
            case 37:
               TryToCalculate();
               break;
            case 38:
               TryToCalculate();
               break;
            case 39:
               TryToCalculate();
               break;
            case 40:
               TryToCalculate();
               break;
         }
      });
      $('.one').bind('click', function () {
         TryToCalculate();
      });
      $('.two').keypress(function (e) {
         switch (e.keyCode) {
            case 37:
               TryToCalculate();
               break;
            case 38:
               TryToCalculate();
               break;
            case 39:
               TryToCalculate();
               break;
            case 40:
               TryToCalculate();
               break;
         }
      });
      $('.two').bind('click', function () {
         TryToCalculate();
      });
   });
   function TryToCalculate() {
      alert("It works!");
   }
</script>

old school HTML table example

3 5
6 9
plus
multiplied by
to the power of
2 4
7 8
is...
?

 
 

The HTML for the table with three tables nested inside of it, given above, is below:

<table>
   <tr>
      <td width="100" align="center">
         <table>
            <tr>
               <td nowrap>
                  <input type="radio" name="one" class="one" value="3">3
               </td>
               <td nowrap>
                  <input type="radio" name="one" class="one" value="5">5
               </td>
            </tr>
            <tr>
               <td nowrap>
                  <input type="radio" name="one" class="one" value="6">6
               </td>
               <td nowrap>
                  <input type="radio" name="one" class="one" value="9">9
               </td>
            </tr>
         </table>
      </td>
      <td>
         <table>
            <tr>
               <td nowrap>
                  <input type="radio" name="act" class="act" value="add">plus
               </td>
            </tr>
            <tr>
               <td nowrap>
                  <input type="radio" name="act" class="act" value="multiply">multiplied by
               </td>
            </tr>
            <tr>
               <td nowrap>
                  <input type="radio" name="act" class="act" value="power">to the power of
               </td>
            </tr>
         </table>
      </td>
      <td width="100" align="center">
         <table>
            <tr>
               <td nowrap>
                  <input type="radio" name="two" class="two" value="2">2
               </td>
               <td nowrap>
                  <input type="radio" name="two" class="two" value="4">4
               </td>
            </tr>
            <tr>
               <td nowrap>
                  <input type="radio" name="two" class="two" value="7">7
               </td>
               <td nowrap>
                  <input type="radio" name="two" class="two" value="8">8
               </td>
            </tr>
         </table>
      </td>
      <td>is...</td>
      <td>
         <div id="equals" style="width: 50px; font-size: 25px;">?</div>
      </td>
   </tr>
</table>

Wednesday, April 18, 2012

I hate fat classes.

Don't make fat classes and try to break them up with regions. Instead strive for an OCP approach in which fat classes are broken up into smaller ones. It will make testing much easier. There is nothing more frustrating than putting a method into an existing fat class that is not under test and then trying to merely get the method you added under test. You can spend hours on a scavenger hunt trying to find all of the dependencies to mock just in the name of surviving the trip through the constructor in test without exception. This headache will make you NOT want to test. You'll understand why there weren't tests there to begin with and once you get tests there you will find them hard to maintain as new dependencies to mock materialize. Why? Because the class in question is doing too much!

MongoDB notes both new and old are offered here.

  1. http://twitpic.com/6ix7xr has an example of using Mongo/C#/10gen
  2. http://www.10gen.com/ is what one would typically use to interface with Mongo from ASP.NET
  3. https://github.com/BancVue/MongoLinqTranslator is BancVue's LINQwithMONGO tool. Ask questions of: peterson.joshua.k@gmail.com
  4. MongoDB is a document database like Apache CouchDB or RavenDB.
  5. Mongo and Couch use JSON, but Mongo uses binary JSON.
  6. The database holds collections. Collections hold documents. Documents hold fields. Fields hold key value pairs.
  7. XML is "bigger" than JSON as deserialization is slower, heavier, and fincky with XML.
  8. There is a not free version of Mongo that has better security.
  9. MongoVUE is a good WYSIWYG tool to browsing Mogno records.
  10. 10Gen made Mongo.

Fluent NHibernate examples can be easy.

This is a class from an old project:

using System;
namespace AdministrableApplication.Core
{
   public class Details
   {
      public virtual Guid detailsId { get; set; }
      public virtual Boolean formDisplayed { get; set; }
      public virtual Boolean formExtraFieldDisplayed { get; set; }
      public virtual string formExtraFieldName { get; set; }
      public virtual string formName { get; set; }
      public virtual string formRedirectsTo { get; set; }
      public virtual Boolean formSendsUserAnEmail { get; set; }
      public virtual string h1 { get; set; }
      public virtual string h2 { get; set; }
      public virtual string htmlMain { get; set; }
      public virtual string htmlSidebar { get; set; }
      public virtual string htmlSupplement { get; set; }
      public virtual string metatagDescription { get; set; }
      public virtual string metatagKeywords { get; set; }
      public virtual string metatagTitle { get; set; }
      public virtual Guid pageId { get; set; }
   }
}

 
 

It has this Fluent NHibernate map:

using AdministrableApplication.Core;
using FluentNHibernate.Mapping;
namespace AdministrableApplication.DataIntegration
{
   public class DetailsMap : ClassMap<Details>
   {
      public DetailsMap()
      {
         Id(x => x.detailsId);
         Map(x => x.formDisplayed);
         Map(x => x.formExtraFieldDisplayed);
         Map(x => x.formExtraFieldName);
         Map(x => x.formName);
         Map(x => x.formRedirectsTo);
         Map(x => x.formSendsUserAnEmail);
         Map(x => x.h1);
         Map(x => x.h2);
         Map(x => x.htmlMain);
         Map(x => x.htmlSidebar);
         Map(x => x.htmlSupplement);
         Map(x => x.metatagDescription);
         Map(x => x.metatagKeywords);
         Map(x => x.metatagTitle);
         Map(x => x.pageId);
      }
   }
}

 
 

It has this repository:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using AdministrableApplication.Core.interfaces;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Criterion;
using Details = AdministrableApplication.Core.Details;
namespace AdministrableApplication.DataIntegration
{
   public class DetailsRepository : IDetailsRepository
   {
      public void addDetails(Details details)
      {
         var sessionFactory = CreateSessionFactory();
         using (var session = sessionFactory.OpenSession())
         {
            using (var transaction = session.BeginTransaction())
            {
               session.Save(details);
               session.Flush();
               transaction.Commit();
               session.Close();
               transaction.Dispose();
               sessionFactory.Close();
            }
         }
      }
      
      public void deleteDetails(Details details)
      {
         var sessionFactory = CreateSessionFactory();
         using (var session = sessionFactory.OpenSession())
         {
            using (var transaction = session.BeginTransaction())
            {
               session.Delete(details);
               session.Flush();
               transaction.Commit();
               session.Close();
               transaction.Dispose();
               sessionFactory.Close();
               sessionFactory.Dispose();
            }
         }
      }
      
      public Details retrieveDetails(Guid pageId)
      {
         var sessionFactory = CreateSessionFactory();
         using (var session = sessionFactory.OpenSession())
         {
            session.CreateCriteria(typeof (Details)).List();
            IList iList = session.CreateCriteria(typeof(Details))
                  .Add(Restrictions.Eq("pageId", pageId)).List();
            IList<Details> allDetailsList = getDetails<Details>(iList);
            Details[] relevantDetails = new Details[] { };
            relevantDetails = allDetailsList.ToArray();
            session.Flush();
            session.Close();
            sessionFactory.Close();
            sessionFactory.Dispose();
            if (relevantDetails.Length == 1)
            {
               return relevantDetails[0];
            } else {
               return null;
            }
         }
      }
      
      public void updateDetails(Details details)
      {
         var sessionFactory = CreateSessionFactory();
         using (var session = sessionFactory.OpenSession())
         {
            using (var transaction = session.BeginTransaction())
            {
               session.SaveOrUpdate(details);
               session.Flush();
               transaction.Commit();
               session.Close();
               transaction.Dispose();
               sessionFactory.Close();
               sessionFactory.Dispose();
            }
         }
      }
      
      public static IList<T> getDetails<T>(IList iList)
      {
         IList<T> result = new List<T>();
         foreach (T value in iList)
         {
            result.Add(value);
         }
         return result;
      }
      
      private static ISessionFactory CreateSessionFactory()
      {
         return Fluently.Configure().Database(
         MsSqlConfiguration.MsSql2005
               .ConnectionString(c => c
               .FromAppSetting("FluentNHibernateConnection"))
            )
            .Mappings(m =>
               m.FluentMappings.AddFromAssemblyOf<SettingsRepository>())
            .BuildSessionFactory();
      }
   } }

 
 

The repository is called via this interface:

using System;
namespace AdministrableApplication.Core.interfaces
{
   public interface IDetailsRepository
   {
      void addDetails(Details details);
      void deleteDetails(Details details);
      Details retrieveDetails(Guid pageId);
      void updateDetails(Details details);
   }
}

What changes in XML when an SSRS data source uses Windows Authentication?

<IntegratedSecurity>true</IntegratedSecurity> will be added after </ConnectString> as shown here when this is done.

make an SSRS data source use Windows Authentication

The way to solve this problem locally when testing in Visual Studio 2008 is:

  1. Open a data source
  2. Go to “Credentials”
  3. Click “Use Windows Authentication (integrated security)"

struggling to use Windows authentication with SSRS

When attempting to use Windows authentication in an SSRS datasource like so:

Data Source=ThatServiceThatRunsOnPortFourteen,14;Initial Catalog=Whatever;Trusted_Connection=Yes

 
 

One may get this error in running a report:

To use the values in the connection string, you must configure the unattended report processing account for the report server.

 
 

http://msdn.microsoft.com/en-us/library/ms156302(v=sql.90).aspx touches on Configuring an Account for Unattended Report Processing

Tuesday, April 17, 2012

80/20 rule

The 80/20 rule seems to suggest that 80 percent of value comes from 20 percent of a resource.

How do I keep Microsoft Office Communicator from turning red?

Well, one thing that will help will be to set the "Show me as Inactive when my computer has been idle for this many minutes" and "Show me as Away when my status has been Inactive for this many minutes" settings to their maximum values of 60 minutes a piece. To do this, click on the arrow next to the big circular traffic lightesque light that shows your status at the Communicator window and then pick Options... (The settings mentioned are in the Personal options.)

delete or hide a column in a list in SharePoint 2010

When you edit a column in SharePoint 2010 there should be a delete button at the base of the page. However, there are some columns such as "Title (linked to item with edit menu)" that I cannot seem to delete. I instead hid this item like so:
  1. click in the list to make the ribbon navigation appear
  2. go to the "List" subtab within the "List Tools" tab
  3. click "Modify View"
  4. uncheck "Display" checkboxes as desired

Dependency Walker fail?

I tried to point Dependency Walker at a .sln file and got "No DOS or PE signature found. This file is not a valid 32-bit or 64-bit Windows module." (PE is of Windows Authenticode Portable Executable Signature Format I think.)

Dependency Walker

Dependency Walker is a free utility that scans any 32-bit or 64-bit Windows module (exe, dll, ocx, sys, etc.) and builds a hierarchical tree diagram of all dependent modules per http://www.dependencywalker.com/.

Monday, April 16, 2012

NHibernate ISession

NhSession is an instance of ISession below:

FooObject bar = (FooObject)NhSession.Load(typeof(FooObject), FooId);

add your emails to a library in SharePoint 2010

  1. go to the "Library" subtab at the "Library Tools" tab
  2. click on "Open with Explorer"
  3. a file window will open to which you may drag and drop emails from Microsoft Outlook

rename a list in SharePoint

  1. go to: Site Actions > Site Settings > Site libraries and lists
  2. select an appropriate list
  3. click on: Title, description and navigation

Saturday, April 14, 2012

virtual opens the door for override and there is a reason for you to care

If we have a class called Bird like so:

namespace Aviary.Core.Objects
{
   public class Bird
   {
      public Bird() {}
      public virtual string Speak()
      {
         return "Chirp!";
      }
   }
}

 
 

...and we had a class named Owl that inheirted from Bird like so that hid its Speak() method like so:

namespace Aviary.Core.Objects
{
   public class Owl : Bird
   {
      public Owl() {}
      public string Speak()
      {
         return "Who?";
      }
   }
}

 
 

C# 4.0 in a Nutshell, a book I am reading, suggests this is what might be called hiding a method. In this approach an Owl could ask "Who?" but if we upcast the Owl to a Bird the bird would lose the ability to ask "Who?" and would only chirp as seen here:

[TestMethod]
public void TestOwl()
{
   Owl owl = new Owl();
   Bird birdMadeFromOwl = owl;
   Assert.AreEqual(owl.Speak(),"Who?");
   Assert.AreEqual(birdMadeFromOwl.Speak(), "Chirp!");
}

 
 

I'll leave it to you to decide if this is a good thing or a bad thing, but I will offer that there is a way to keep this from happening by using the override keyword as seen here:

namespace Aviary.Core.Objects
{
   public class Parrot : Bird
   {
      public Parrot() {}
      public override string Speak()
      {
         return "Yo! What's up?";
      }
   }
}

 
 

Look at the difference:

[TestMethod]
public void TestParrot()
{
   Parrot parrot = new Parrot();
   Bird birdMadeFromParrot = parrot;
   Assert.AreEqual(parrot.Speak(), "Yo! What's up?");
   Assert.AreEqual(birdMadeFromParrot.Speak(), "Yo! What's up?");
}

 
 

Override lets our child's method survive the manhandling of an upcasting. The override word alone does not do the trick however. Without the virtual keyword at the Bird object at the top of this blog posting it would not have been possible. In the absence of the virtual keyword at a parent's method signature only the hiding approach is feasible.

bottleneck through a parent

Visualize how the "contact us" form at a vanity web site might bind to this:

using System;
namespace Bottleneck.Core
{
   public class UserSubmission
   {
      public string FullNameOfUser { get; set; }
      public string UserEmailAddress { get; set; }
      public string UserPhoneNumber { get; set; }
      public string UserComments { get; set; }
      public DateTime SubmissionDate { get; private set; }
      
      public UserSubmission()
      {
         SubmissionDate = Clock.CurrentTime();
      }
   }
}

 
 

Alrighty, what are some things we might do with our object that records the values a user entered for his or her name, email address, phone number and thoughts (UserComments)? We might:

  1. create a lead in SalesForce
  2. alert the our sales team with an email
  3. send an email response back to the user
  4. save a record at our database

 
 

Hmmm... all four are calls to external dependencies, this is starting to sound like a Saga process. Well, yes, but, I don't have the chops to write a Saga just yet. Also, I want to keep this example simple, because I wish to illustrate something different altogether. (The Saga post will have to come another day.) Let's just assume that we are just going to send our model to a static method called Save() in a static class called UserSubmissionProcessing which will have four lines of code for the four acts:

  1. CrmSubmission.Submit(item);
  2. InHouseEmailAlert.Send(item);
  3. OutboundEmailAlert.Send(item);
  4. Persistence.Save(item);

 
 

And now...the point! What if you were maintaining this site and it started to grow as the startup you worked for started to do better and better? What if you hosted free events at your facility and wanted to manage the registration yourself instead of using Eventbrite. If the events are free and there is no credit card processing, there is really no reason why you couldn't have a user give his or her name, email address, phone number and thoughts at a form not unlike the "contact us" form. However, more tricky, the way the form would be processed would have to vary. You might want to send a different confirmation email or not send a confirmation email at all if the event was full up. Beyond this let's get more complicated and have it that the same web site lets visitors download whitepapers, request sales appointments, and occasionally raffles off prizes. The different varieties of form submissions naturally must be handled differently while nonetheless have many needs in common. It seems reasonable to have UserComments be a parent to a smattering of child objects that will give it variance. Our Save() method in UserSubmissionProcessing will still consume a UserComments object, but will vary what it does with the object based upon the nature of the child. I've seen a pattern like this before. It adheres to the DRY Principal (Don't Repeat Yourself) and thus seems superior to having five different Save() methods for the five varieties of form submissions mentioned above. Child objects of UserComments will get up upcast to a UserComments object which will be handed to UserSubmissionProcessing and then the "childish nature" will get rediscovered with the Save() method and considered on the other side of the parental bottleneck.

 
 

At first glance you might think the extra bits of information associated with a child might get lost in upcasting like so:

WhitePaperDownload whitePaperDownload = (WhitePaperDownload)userSubmission;
whitePaperDownload.UrlForDownload = "http://www.example.com/";
whitePaperDownload.WhitePaperName = "How To Tie Your Shoes";
UserSubmissionProcessing.Save(whitePaperDownload);

 
 

...when the Save() signature looks like so:

public static void Save(UserSubmission item)

 
 

The child data does not get lost. This is one of the interesting things I found reading the O'Reilly book: C# 4.0 in a Nutshell by Joseph Albahari and Ben Albahari. Pages 78 and 79 touch on this. I will show how the child information is recovered. First, here are our children:

  1. using System;
    namespace Bottleneck.Core
    {
       public class EventRegistration : UserSubmission
       {
          public Guid EventId { get; set; }
       }
    }
     
  2. using System;
    namespace Bottleneck.Core
    {
       public class DrawingRegistration : UserSubmission
       {
          public Guid DrawingId { get; set; }
       }
    }
     
  3. namespace Bottleneck.Core
    {
       public class WhitePaperDownload : UserSubmission
       {
          public string WhitePaperName { get; set; }
          public string UrlForDownload { get; set; }
       }
    }
     
  4. namespace Bottleneck.Core
    {
       public class RequestForAppointment : UserSubmission
       {
       }
    }
     

 
 

What follows is UserSubmissionProcessing. It is now much more than four lines. I do not suggest this is great code, but it does exposition what I wish to exposition. The use of the keyword "is" is the most important thing to see below. Note that a couple of the methods used in UserSubmissionProcessing have had their signatures changed so that they too may handle a greater variety of user submissions.

namespace Bottleneck.Core
{
   public static class UserSubmissionProcessing
   {
      public static void Save(UserSubmission item)
      {
         
//1. submit to SalesForce
         if(item is RequestForAppointment)
         {
            CrmSubmission.Submit(item, SalesPriority.High);
         } else {
            CrmSubmission.Submit(item, SalesPriority.Medium);
         }
         
         
//2. send email alert to internal sales manager
         InHouseEmailAlert.Send(item);
         
         
//3. register user for raffle or free event if applicable
         bool? going = null;
         if (item is DrawingRegistration)
         {
            Registration.RegisterForDrawing((DrawingRegistration)item);
            going = true;
         }
         if (item is EventRegistration)
         {
            going = Registration.RegisterForEvent((EventRegistration)item);
         }
         
         
//4. send response to user
         EmailResponse email = new EmailResponse();
         if (item is WhitePaperDownload)
         {
            WhitePaperDownload request = (WhitePaperDownload) item;
            email.SubjectLine = "Here is your whitepaper!";
            email.TextOnly = TextTemplatesForEmail.HereIsYourWhitePaper();
            email.Html = HtmlTemplatesForEmail.HereIsYourWhitePaper();
            email.LinkWithinEmailBodyUrl = request.UrlForDownload;
            email.LinkWithinEmailBodyVanityName = request.WhitePaperName;
         } else {
            if (going == null)
            {
               email.SubjectLine = "Thank you for your response!";
               email.TextOnly = TextTemplatesForEmail.ThankYouForYourResponse();
               email.Html = HtmlTemplatesForEmail.ThankYouForYourResponse();
            }
            if (going == true)
            {
               email.SubjectLine = "Thank you for registering!";
               email.TextOnly = TextTemplatesForEmail.ThankYouForRegistering();
               email.Html = HtmlTemplatesForEmail.ThankYouForRegistering();
            }
            if (going == false)
            {
               email.SubjectLine = "Sorry, but our event is full.";
               email.TextOnly = TextTemplatesForEmail.SorryButOurEventIsFull();
               email.Html = HtmlTemplatesForEmail.SorryButOurEventIsFull();
            }
         }
         OutboundEmailAlert.Send(email, item);
         
         
//5. save record to database
         Persistence.Save(item);
      }
   }
}

 
 

Page 87 of the book I'm reading shows how to get at child specs by way of reflection. Here is the UserSubmissionProcessing refactored to use reflection. This code is a little worse because it uses object at the method signature and then assumes that the object is a UserSubmission or the child of a UserSubmission.

namespace Bottleneck.Core
{
   public static class UserSubmissionProcessing
   {
      public static void Save(object item)
      {
         
//1. submit to SalesForce
         if(item.GetType() == typeof(RequestForAppointment))
         {
            CrmSubmission.Submit((UserSubmission)item, SalesPriority.High);
         } else {
            CrmSubmission.Submit((UserSubmission)item, SalesPriority.Medium);
         }
         
         
//2. send email alert to internal sales manager
         InHouseEmailAlert.Send((UserSubmission)item);
         
         
//3. register user for raffle or free event if applicable
         bool? going = null;
         if (item.GetType() == typeof(DrawingRegistration))
         {
            Registration.RegisterForDrawing((DrawingRegistration)item);
            going = true;
         }
         if (item.GetType() == typeof(EventRegistration))
         {
            going = Registration.RegisterForEvent((EventRegistration)item);
         }
         
         
//4. send response to user
         EmailResponse email = new EmailResponse();
         if (item.GetType() == typeof(WhitePaperDownload))
         {
            WhitePaperDownload request = (WhitePaperDownload) item;
            email.SubjectLine = "Here is your whitepaper!";
            email.TextOnly = TextTemplatesForEmail.HereIsYourWhitePaper();
            email.Html = HtmlTemplatesForEmail.HereIsYourWhitePaper();
            email.LinkWithinEmailBodyUrl = request.UrlForDownload;
            email.LinkWithinEmailBodyVanityName = request.WhitePaperName;
         } else {
            if (going == null)
            {
               email.SubjectLine = "Thank you for your response!";
               email.TextOnly = TextTemplatesForEmail.ThankYouForYourResponse();
               email.Html = HtmlTemplatesForEmail.ThankYouForYourResponse();
            }
            if (going == true)
            {
               email.SubjectLine = "Thank you for registering!";
               email.TextOnly = TextTemplatesForEmail.ThankYouForRegistering();
               email.Html = HtmlTemplatesForEmail.ThankYouForRegistering();
            }
            if (going == false)
            {
               email.SubjectLine = "Sorry, but our event is full.";
               email.TextOnly = TextTemplatesForEmail.SorryButOurEventIsFull();
               email.Html = HtmlTemplatesForEmail.SorryButOurEventIsFull();
            }
         }
         OutboundEmailAlert.Send(email, (UserSubmission)item);
         
         
//5. save record to database
         Persistence.Save(item);
      }
   }
}