Tuesday, April 30, 2013

Did you know there was a version 1 for ASP.NET before version 1.1?

Not really a surprise I guess. Things start at 1. Wikipedia has timeline of ASP.NET versions. I have worked on 1.1 projects but never a 1.0 project. The write up at Wikipedia suggests there wasn't much difference. I guess we got some web forms validation controls or something-er-other else comparable with 1.1 which appeared in 2003 following the original version the year before. I did not hear about ASP.NET until 2005 myself.

more on wrapping numeric types in unit types in advance of calculations

This should necessitate this sort of thing I would think as there is a need to wrap numbers in types yet still have them behave as numbers without pain. Also a class inheriting from IComparable gains the power of number-based sorting in spite of a nonnumeric shape.

Method overloading is not the same as polymorphism.

Not the same! When I first heard of polymorphism I believed it was basically what method overloading is, the art of having different methods with the same name but different signatures side by side in the same class.

Modern Entity Framework

Install-Package EntityFramework -Pre ...gets Entity Framework 6 Alpha from NuGet. http://www.youtube.com/watch?v=HbDOhCjjxSY is on the Code First stuff. There are a bunch of advertisements that you must suffer through to watch it. :(

Write your own equality comparisons for a given class in C#.

The goofy book on philosophy I recently found has kept me entertained between jobs. I am inappropriately reading programming concepts onto the subject matter.

C# 4.0 in a Nutshell, the book I've been reading for far too long, explains how to write your own equality comparisons for a given class, and I thought of how I might apply this trick when measuring happiness as John Stuart Mill might define it. I thus might be able to roll a class called Act and assert that one instance of Act was superior to another like so:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Utilitarianism.Core.Acts;
namespace Utilitarianism.Tests
{
   [TestClass]
   public class ActTests
   {
      [TestMethod]
      public void reading_wordsworth_is_greater_than_drinking_ale()
      {
         ReadingWordsworth thatTimePoemsWereRead = new ReadingWordsworth();
         DrinkingAle thatTimePintsWereDrunk = new DrinkingAle();
         Assert.IsTrue(thatTimePoemsWereRead > thatTimePintsWereDrunk);
      }
   }
}

 
 

The vapid-while-not-vapid book I bought suggests he would agree with this test passing as it does. When I first heard of Utilitarianism (an ethics doctrine of: that which creates the most happiness is that which is moral) twenty years ago in an Austin Community College class I immediately feared how it could be the rationale for slavery. Mr. Mill had a different fear per the book. He feared it could be the rationale for epicurean excess in lieu of intellectual pursuits. Observe:

The book is too skim-the-surfacesque to delve into how reading Wordsworth is graded superior to drinking ale, yet Mill surely had a way to distinguish the two. This makes me wonder if there could be a subjective corny algorithm for as much like so:

namespace Utilitarianism.Core
{
   public static class Happiness
   {
      public static int Measurement(Act act)
      {
         return BalloonImportanceOfStimulation(act) * act.Joy;
      }
      
      private static int BalloonImportanceOfStimulation(Act act)
      {
         if (act.Stimulation < 0)
         {
            return act.Stimulation * act.Stimulation * -1;
         } else {
            return act.Stimulation * act.Stimulation;
         }
      }
   }
}

 
 

One makes the greater than comparison work at Act as shown below. Please note that without the "greater than method" below that the test at the top of this posting cannot compile and without the sister "lesser than method" one cannot have the "greater than method." Comparably the "equals method" has to have an accompanying "not equals method." If you have all four methods, you may wish to try to pull some of the mechanics out to a fifth private method as I did below. In the case of an inanely subjective algorithm that is apt perhaps to being swapped out with something else, the fifth method has a "Don't Repeat Yourself" function too, decoupling the algorithm from four places where it might otherwise be referenced.

namespace Utilitarianism.Core
{
   public abstract class Act
   {
      public int Joy { get; protected set; }
      public int Stimulation { get; protected set; }
      
      public static bool operator ==(Act yin, Act yang)
      {
         int position = JudgeBestOfTwoActs(yin, yang);
         return (position == 0);
      }
      
      public static bool operator !=(Act yin, Act yang)
      {
         int position = JudgeBestOfTwoActs(yin, yang);
         return (position != 0);
      }
      
      public static bool operator >(Act yin, Act yang)
      {
         int position = JudgeBestOfTwoActs(yin, yang);
         return (position == 1);
      }
      
      public static bool operator <(Act yin, Act yang)
      {
         int position = JudgeBestOfTwoActs(yin, yang);
         return (position == 2);
      }
      
      private static int JudgeBestOfTwoActs(Act yin, Act yang)
      {
         int yinValue = Happiness.Measurement(yin);
         int yangValue = Happiness.Measurement(yang);
         if (yinValue > yangValue) return 1;
         if (yangValue > yinValue) return 2;
         return 0;
      }
   }
}

 
 

In feeding my corny algorithm I tried to imagine why Mill might fear others being drawn to happiness by alcohol in lieu of literature and I constructed two goofy getsetters for Act to somehow delineate high-minded happiness from that which is of base pleasures. They both get numeric values. The farther they stray upwards, the better. Again, I have no idea what Mill's measuring stick for this really looked like, but I bet his was pretty silly too.

Here is the Act subclass Mill exalts: Here is a lesser Act child:
namespace Utilitarianism.Core.Acts
{
   public class ReadingWordsworth : Act
   {
      public ReadingWordsworth()
      {
         Joy = 1;
         Stimulation = 3;
      }
   }
}
namespace Utilitarianism.Core.Acts
{
   public class DrinkingAle : Act
   {
      public DrinkingAle()
      {
         Joy = 5;
         Stimulation = 1;
      }
   }
}

 
 

The book also has this interesting view of how everything (all experience) works per George Berkeley, who did not believe that matter existed!

This sort of one-way broadcasting is how RSS feeds work and really anything else with subscribers drinking up from a publisher. Meh. I go back to work in a week's time. I am probably overdue for being busy again given how I've distracted myself.

Sunday, April 28, 2013

Oracle eBusiness Suite

Oracle EBS (eBusiness Suite) is Oracle's version of SAP. It's "enterprise software."

using a DTO in ASP.NET Web API

Refactoring my experiment which yielded 7 + 13 + 22 = 42, I introduce a data transfer object in lieu of serializing anonymous types:

namespace Learning.Models
{
   public class CornyThing
   {
      public int Foo { get; set; }
      public int Bar { get; set; }
      public int Composition { get; set; }
      public string Explanation { get; set; }
   }
}

 
 

The Web API Controller gets trimmed way down...

using System.Web.Http;
using Learning.Models;
namespace Learning.Controllers
{
   public class ExperimentController : ApiController
   {
      public CornyThing Put(int id, [FromBody]CornyThing value)
      {
         value.Composition = id + value.Foo + value.Bar;
         value.Explanation = id + " + " + value.Foo + " + " + value.Bar + " = " +
               value.Composition;
         return value;
      }
   }
}

 
 

Finally, you may see below that I am talking to the Controller above at a domain name as suggested below. If I put a copy of the code base to IIS8 Express and then run the code below from Cassini I am able to make it all work as both sides understand what the CornyThing object is. I can also imagine how this sort of sharing could be painful and come with maintenance overhead. Hmmmm.

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Mvc;
using Learning.Models;
namespace Learning.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         string status;
         HttpClient client = new HttpClient();
         client.BaseAddress = new Uri("http://www.dummygunk.com/");
         client.DefaultRequestHeaders.Accept.Add(new
               MediaTypeWithQualityHeaderValue("application/json"));
         CornyThing whatever = new CornyThing() { Foo = 13, Bar = 22 };
         var response = client.PutAsJsonAsync("api/experiment/7", whatever).Result;
         if (response.IsSuccessStatusCode)
         {
            CornyThing dto = response.Content.ReadAsAsync<CornyThing>().Result;
            status = dto.Explanation;
         } else {
            status = "Fail!";
         }
         ViewBag.Status = status;
         return View();
      }
   }
}

Saturday, April 27, 2013

Method Not Allowed

...is an error I have seen in attempting to use PUT within ASP.NET Web API at IIS8 Express. This is merely a configuration problem. To fix this go to Windows Features as suggested here and then uncheck the checkbox at: Internet Information Services > World Wide Web Services > Common HTTP Features > WebDAV Publishing

Talking to a PUT method in ASP.NET MVC Web API and back by way of serializing anonymous types.

Given the following ASP.NET MVC Web API Controller...

using System;
using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Learning.Controllers
{
   public class ExperimentController : ApiController
   {
      public string Put(int id, [FromBody]string value)
      {
         var json = (JObject)JsonConvert.DeserializeObject(value);
         int foo = Convert.ToInt32(json["Foo"].ToString());
         int bar = Convert.ToInt32(json["Bar"].ToString());
         int composition = id + foo + bar;
         string explanation = id + " + " + foo + " + " + bar + " = " + composition;
         var compositionWithExplantion = new { Composition = composition,
               Explanation = explanation };
         return JsonConvert.SerializeObject(compositionWithExplantion);
      }
   }
}

 
 

I can report that...

   7 + 13 + 22 = 42

      ...ends up in the "status" variable here:

 
 

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Learning.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         string status;
         HttpClient client = new HttpClient();
         client.BaseAddress = new Uri("http://localhost:55352/");
         client.DefaultRequestHeaders.Accept.Add(new
               MediaTypeWithQualityHeaderValue("application/json"));
         var whatever = new { Foo = 13, Bar = 22 };
         var response = client.PutAsJsonAsync("api/experiment/7",
               JsonConvert.SerializeObject(whatever)).Result;
         if (response.IsSuccessStatusCode)
         {
            string messageBackFromApi = response.Content.ReadAsAsync<string>
                  ().Result;
            var json = (JObject)JsonConvert.DeserializeObject(messageBackFromApi);
            status = json["Explanation"].ToString();
         } else {
            status = "Fail!";
         }
         ViewBag.Status = status;
         return View();
      }
   }
}

 
 

.PutAsJsonAsync above could be .PostAsJsonAsync in a Post scenario or perhaps also either .DeleteAsync or .GetAsync in scenarios in which one passes the first of the two variables to the method but not the second. The signature is different for .DeleteAsync and .GetAsync as one does not hand in serialized junk with the DELETE and GET verbs. This, this, and this were some things I found while working this out. I supposed I could serialize a type that both sides understand instead of shoving anonymous types in and out of string types in the name of crosstalk. That may be the next thing to try.

Friday, April 26, 2013

The Composer Tab in Fiddler

...seems to be where one pushes out to test ASP.NET Web API with GET, PUT, POST, and DELETE requests. I'm currently struggling some to get it to work.

Windows Mobile versus Windows Phone

You have to use Visual Studio 2008 and the ASP.NET 3.5 Framework to interface with Windows Mobile as Windows Mobile has been thrown away for Windows Phone. Microsoft offers a significant shakeup in this space.

PhoneGap

PhoneGap is a JavaScript library that will allow you access to things like the camera on a smart phone from an HTML5 application. I'd imagine you can get the phone's location on planet Earth and some other things too.

David Hume explains dynamic programming.

David Hume should get a compiler and stop working in Ruby. Ha! Maybe that will shake up his boundaries between the nominal and the phenomenal. (I knew I was going to have to wait in the lobby at a National Tire and Battery some yesterday and in advance of that I wandered around BookPeople looking for something I could occupy myself with and found "Introducing Empiricism" by Dave Robinson and Bill Mayblin which seemed the right mix of smart and corny and fluffy. The image here is from the book.)

push-me—pull-you

I'm soon to start working with the Mercurial HG shell anew after after twenty months of TFS. I am brushing up on my GIT jargon, although GIT and Mercurial are not technically the same thing. This suggests that Bitbucket offers pull request functionality for Mercurial which is a way to broadcast a commit (a push) to subscribers, baiting them to "pull" --get it?

The most interesting thing I remember about Mercurial is that there are both local and real-to-the-repository commits. Without ties to a bug tracking system, there is not that awful TFS requirement in which one has to give a task number in order to make a commit. Yay! I won't miss that.

Wednesday, April 24, 2013

SMPP is for SMS (text message) messaging.

SMPP stands for Short Message Peer-to-Peer Protocol (I think) and SMS stands for (Short Message Service).

Azure is Stateless?

One thing I forgot to mention anew when recreating this was that Session is not going to work in an Azure scenario in which a site is hosted across numerous servers. Apparently there is an Azure way around the problem, a way to have pseudosession, but perhaps it is best to build a stateless app for the cloud.

this!

in jQuery...

$("#button1").mouseover(function() {
   $(this).removeClass("thing1");
   $(this).addClass("thing2");
   highlight($(this));
}).mouseout(function() {
   $(this).addClass("thing1");
   $(this).removeClass("thing2");
   unhighlight($(this));
}).mousedown(function() {
   window.location="/about/";
});

Thursday, April 18, 2013

.call and .apply in JavaScript!

.call was explained to me in an interview today:

function whatever() {
   alert(this);
}
$(function () {
   whatever.call("Hello World");
});

 
 

Here is it is in a different shape of sorts:

function whatever(name, taste) {
   alert(name + " likes " + taste + ".");
}
$(function () {
   whatever.call(undefined, "Sally", "blueberries");
});

 
 

This (no pun intended) shows off the difference between .call implementation immediately above and the .apply implementation here:

function whatever(name, taste) {
   alert(name + " likes " + taste + ".");
}
$(function () {
   whatever.apply(undefined, ["Roy", "strawberries"]);
});

Tuesday, April 16, 2013

z-index is kind of like old school 1980s BASIC in a way.

This reminds of this stuff that we used to do in the 1980s as kids when we weren't playing Zork:

10 PRINT "HELLO WORLD"
20 GOTO 10
RUN

 
 

Everyone who did BASIC wrote lines in increments of ten so that they could later jam in new lines of code between the increments of ten. You should not start at 1 as you are then making it impossible to have a line of code before line 1. In a similar manner, I would recommend setting the z-index property in CSS in increments of ten and especially so after reading this which leads me to believe that zero is not the default for z-index and you should not confidently believe that if you have only one specification for a z-index in CSS and that it is set to 1 that therefore anything using the class/id/tag will come out on top of other items not having it.

z-index: 10;

Session_Start in Global.asax might be a good place to kick off the logic for a hits counter.

This came up as a challenge in an interview I had. From Session_Start one could see if a cookie was already set (flagging the browser/IP combo as already logged) and from there a database could be checked to see if the IP had already been logged. Fun stuff. I tried the following and was able to pull it off:

public class WebApiApplication : System.Web.HttpApplication
{
   protected void Session_Start()
   {
      HttpCookie cookie = new HttpCookie("foo");
   }
}

Xamarin

Xamarin is the new Titanium? Perhaps! This is what Twitter is abuzz with at the moment.

Umbraco

...is an open source CMS for ASP.NET. See: http://umbraco.com/

Monday, April 15, 2013

Some ways Oracle is different from MSSQL...

  1. Dates are very different, but otherwise most of the heavy differences are "deep down."
  2. There is not bit type. Use a 1 or a 0 at an integer type to express true/false.
  3. There is no way to wrap the creation of tables in transactions.
  4. Oracle is "better" at concurrency and scenarios involving millions of records.

Change scale appropriately from portrait to landscape at an iPhone in a HTML5 hybrid application.

There is a way to doctor up the viewport metatag as I elude to here. In the example I got to work, I have a single viewport tag which looks like this:

<meta name="viewport" id="viewport" content="width=device-width, width=320">

 
 

The following code gets the height and width of the browser. I don't use the height, so my example below is a little dirty. I found the code for getting the browser size somewhere online. Maybe at Stack Overflow. I dunno. Anyways, I then use the width to doctor up the viewport tag. I tried this in a web page and it worked at my iPhone. The scale changes appropriately from portrait to landscape. Yay!

$(function () {
   setInterval("my_function();",500);
});
function my_function(){
   winwidth = document.all ? document.body.clientWidth : window.innerWidth;
   winHeight = document.all ? document.body.clientHeight : window.innerHeight;
   if (winwidth < 400) {
      document.getElementById("viewport").setAttribute('content', 'width=device-width,
            width=320, maximum-scale=1.0, minimum-scale=1.0');
   }
   else
   {
      document.getElementById("viewport").setAttribute('content', 'width=device-width,
            width=480, maximum-scale=1.0, minimum-scale=1.0');
   }
}

Sunday, April 14, 2013

Make an old school animated .gif in Abode Photoshop CS6.

I could not get this or this to work out for me. Here is how I did it:

  1. I went to: File > Scripts > Load Files into Stack...
  2. At the dialog box that appeared, I selected a series of four images of .jpg extension and then I clicked "OK."
  3. The Layers pane showed the four images as a series of layers!
  4. I opened the timeline pane from: Window > Timeline
  5. I clicked the "Create Video Timeline" button in the middle of the Timeline pane to create a timeline.
  6. I messed around with the timeline and got it the way I wanted it to be.
  7. I went to: File > Save for Web...
  8. In the "Save for Web" dialog box I set the "Looping Options" drop down at the lower right to "Forever."
  9. I clicked the "Preview..." button to preview.
  10. I clicked the "Save..." button to save.

 
 

Addendum 6/24/2017: I thought of this just now. It still works. I made this .gif of Laurie Segall with screen grabs off of cnn.com

 
 

Addendum 6/25/2017: I updated yesterday's .gif and made it even more fun!

Make a web page open at the desired size at an iPhone.

This suggests what one may enforce a screen width at an iPhone with the following metatags:

<meta name="viewport" content="width=device-width">
<meta name="viewport" content="width=320">

 
 

I have tried it and it works. However, if I turn my phone from portrait to landscape I would like the 320 setting to turn into a 480 value. How may I have this happen? This suggests there is a way with JavaScript. I have not tried it yet.

Saturday, April 13, 2013

ASP.NET MVC Web API in contrast to REST

Here is my recreation of two slides from Ryan Vice's talk on Monday. First up is the convention for an RPC (Remote Procedure Call) RESTesque API:

ROUTE ACTION VERB ARGUMENTS
\AccountManager\GetAccounts Get all accounts GET none
\AccountManager\GetAccounts\:id Get account by ID GET query string
\AccountManager\AddAccount Add account POST header
\AccountManager\UpdateAccount Update account POST header
\AccountManager\DeleteAccount Delete account POST query string
\AccountManager\Deposit Deposit funds POST header
\AccountManager\Withdraw Withdraw funds POST header

 
 

The Resource Centric ASP.NET MVC Web API is like so in contrast to what is above:

ROUTE ACTION VERB ARGUMENTS
\Accounts Get all accounts GET none
\Accounts\:id Get account by ID GET query string
\Accounts Add account POST header
\Accounts\:id Update account PUT header
\Accounts\:id Delete account DELETE header
\Accounts\:id\Deposit Deposit funds POST header and query string
\Accounts\:id\Withdraw Withdraw funds POST header and query string

Friday, April 12, 2013

Make an arc on a canvas move counterclockwise.

In drawing on the canvas replace something like this:

foo.arc(230, 195, 20, 2 * Math.PI, 1.25 * Math.PI);

...with...

foo.arc(230, 195, 20, 2 * Math.PI, 1.25 * Math.PI, true);

LMS stands for Learning management system.

When you take an online class at your community college, the public facing interface is probably a piece of an LMS. See: http://en.wikipedia.org/wiki/Learning_management_system

Things I've brushed into in job hunting of late.

  1. IBM Maximo is an assets management enterprise service.
     
  2. The producer/consumer problem is of threading. The Wikipedia article I read suggests that one may write to a buffer and read from a buffer with different threads, but that it is problematic to read when there is nothing to read and write when the buffer is full. Keeping separate variables for the number of slots left to read and fill seems to be suggested. If a process cannot deincrement an applicable variable, it should be put to sleep before it attempts to act.
    http://en.wikipedia.org/wiki/Producer-consumer_problem
    http://www.albahari.com/threading/part2.aspx
     
  3. XRM may imply extensibility for Microsoft Dynamics CRM. I found an article about doing data modeling in Dynamics CRM which will ultimately live in the shape of MSSQL database tables while being utilized by Dynamics CRM. I suppose independent applications could furthermore access the database tables allowing for a traditionally app to interact with Dynamics.
    http://msdn.microsoft.com/en-us/library/ee830281.aspx
     
  4. Apache Cordova and Phone Gap may be used in an HTML5 Hybrid application in the name of getting access to the camera.
    http://en.wikipedia.org/wiki/PhoneGap
     
  5. Microsoft Solomon is a workflow management tool.
    http://www.uhyadvisors-us.com/uhy/Services/TechnologyAssuranceAdvisoryServices/TechnologyConsultingServices/Products/MicrosoftSolomon/tabid/219/Default.aspx
     
  6. "ECMAScript 5's strict mode is a way to opt in to a restricted variant of JavaScript." Think of TypeScript and CoffeeScript. Strict mode is not a means for code compilation like these two, but it is another way to let yourself know you are doing something stupid in the same vein of compiler safety.
    https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/Strict_mode
     
  7. The prototype keyword allows one to have class inheritance in JavaScript. Observe:
    function superclass() {this.stuff="stuff";}
    function subclass() {}
    subclass.prototype = new superclass();
    alert(new subclass().stuff);

Thursday, April 11, 2013

threading 101

Chapter 21 of C# 4.0 in a Nutshell is on Threading. I spun up the corny example below and I can tell that it is writing to two files at once as is desired. If I were to use try/catches to make sure a different note was logged when a thread failed (which would be smart) I would do it inside the Foo and Bar methods and not inside the Go method for if you wrap the newing up of threads in a try the catch will never be reached. The failure will go unseen in such a circumstance.

using System;
using System.IO;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MvcApplication.Tests
{
   [TestClass]
   public class UnitTest
   {
      [TestMethod]
      public void Go()
      {
         Thread foo = new Thread(Foo);
         Thread bar = new Thread(Bar);
         foo.Start();
         bar.Start();
         foo.Join();
         bar.Join();
         Assert.AreNotEqual("Blondie", "Deborah Harry");
      }
      
      static void Foo()
      {
         for (int i = 0; i < 10000; i++)
         {
            using (StreamWriter baz =
                  File.AppendText(@"C:\Users\Thomas\Desktop\baz.txt"))
            {
               baz.WriteLine("(baz" + DateTime.Now + ")");
            }
         }
      }
      
      static void Bar()
      {
         for (int j = 0; j < 10000; j++)
         {
            using (StreamWriter qux =
                  File.AppendText(@"C:\Users\Thomas\Desktop\qux.txt"))
            {
               qux.WriteLine("(qux" + DateTime.Now + ")");
            }
         }
      }
   }
}

Wednesday, April 10, 2013

I am hunting for work again and I know I'm going to get asked about WCF.

I revisited this today as I am hunting for work again and I know I'm going to get asked about WCF. ASP.NET interviews seem to go here. OK, so I made a new WCF Service Application like so:

Let's look at the default .svc file inside:

using System;
namespace WcfService
{
   public class Service1 : IService1
   {
      public string GetData(int value)
      {
         return string.Format("You entered: {0}", value);
      }
      
      public CompositeType GetDataUsingDataContract(CompositeType composite)
      {
         if (composite == null)
         {
            throw new ArgumentNullException("composite");
         }
         if (composite.BoolValue)
         {
            composite.StringValue += "Suffix";
         }
         return composite;
      }
   }
}

 
 

There is another default file. It comes with both an interface for the service and a class for a serializable DTO type jammed into it. Note the attributes below as they are all important:

using System.Runtime.Serialization;
using System.ServiceModel;
namespace WcfService
{
   [ServiceContract]
   public interface IService1
   {
      [OperationContract]
      string GetData(int value);
      
      [OperationContract]
      CompositeType GetDataUsingDataContract(CompositeType composite);
   }
   
   [DataContract]
   public class CompositeType
   {
      bool boolValue = true;
      string stringValue = "Hello ";
      
      [DataMember]
      public bool BoolValue
      {
         get { return boolValue; }
         set { boolValue = value; }
      }
      
      [DataMember]
      public string StringValue
      {
         get { return stringValue; }
         set { stringValue = value; }
      }
   }
}

 
 

I published this default project as is to a folder and then I took the files and prepped them as a web site in IIS Express. I then set up a separate MVC application and was able to latch onto the web service by adding a reference as suggested in the link I give at the top of this blog posting. In a Controller, I shoved in this code and set a breakpoint after it. I this confirmed that the types get populated as I expected. My adding of a reference allows the MVC app to have the DTO for the serializable type.

Service1Client foo = new Service1Client();
string bar = foo.GetData(42);
CompositeType baz = new CompositeType();
baz.BoolValue = true;
baz.StringValue = "baz";
CompositeType qux = foo.GetDataUsingDataContract(baz);

 
 

I am doing all of this with VS2012 and C# 4.5 and I noticed that beyond the two methods I utilize above that Async versions of both methods are exposed!

Pain points:

  • "It is possible that a handler mapping is missing. By default, the static file handler processes all content." shows up when you visit the URL for your WCF service and you do not have WCF features turned on for IIS Express. Turn them on in Windows 8 at: charm bar > Search > Settings > Turn windows features on and off > .NET Framework 4.5 Advanced Services > WCF Services
     
  • When I made a reference I ended up making the folllowing files in a folder:
    1. configuration.svcinfo
    2. configuration91.svcinfo
    3. MvcApplication.ServiceReference1.CompositeType
    4. Reference.cs
    5. Reference.svcmap
    6. Service1.disco
    7. Service1.wsdl
    8. Service1.xsd
    9. Service11.xsd
    10. Service12.xsd
    If the reference seems... "unreferenceable" ...then Reference.cs likely has nothing in it and you should try try this:
    1. right-click on the reference and pick "Configure Service Reference..."
    2. uncheck the checkbox for "Reuse types in referenced assemblies" in the dialog box which appears
    3. get out of the dialog box and back to the Solution Explorer
    4. right-click on the reference and pick "Update Service Reference"

     
  • This may reveal the trick to beating the environment-swapping problem I suggest here.
    BasicHttpBinding binding = new BasicHttpBinding();
    EndpointAddress address = new
          EndpointAddress("http://www.dummygunk.com/Service1.svc");
    Service1Client serviceClient = new Service1Client(binding, address);

 
 

Addendum 3/14/2014: My reference to C# 4.5 should really be a reference to the ASP.NET 4.5 Framework which uses C# 5.0.

PUT is idempotent which POST is not.

I saw Ryan Vice speak on ASP.NET Web API at Monday night Austin .NET User Group. I would say that this API is next on my list of things to learn but that may all change depending upon where I go work next. An example of a Web API method:

public void Put(int id, [FromBody]string value)
{
   
//whatever
}

[FromBody] above allows for binding against more than just stuff passed at the URL line. Think of JSON pushed in the body or header of a request. You may hand an object easily to POST and PUT. Mitch Fincher asked what the difference between the two was and Ryan explained that PUT is idempotent which POST is not. If you repeat an idempotent action act the repeat should cause no effect. You should be only causing an effect on the first push. Example: If you quadruple-click that button which is wired up to a PUT push-out you will not shove four identical records into the database. Ryan said that there is a "Client API" which will show you how to use the PUT method from the C# side. This is something for me to Google.

 
 

The opening act for Ryan was my employer of over five years, Dustin Wells, who sure seems like he knows what he's doing and especially so given some of the craziness I've witnessed during the past two years of not working for him. Dustin mentioned that he bought the pizza and that Headspring, his shop which you may have heard of, is hiring. I had some of his pizza and it was pretty good. That isn't really a surprise. He has the Midas touch. :P

Tuesday, April 9, 2013

bad post on IPv6

Here I tried to write a how-to on getting your external IPv6 versus IPv4, but it is just bad. The IPv6 stuff is of the machine at hand while the IPv4 will come from outside requests hitting the web app. I really wanted IPv6s to also come from outside requests, but I do not know how to do so and I do not have an environment to tinker in to figure this out. Not yet. The world should come to me eventually however.

A Dangerous Blog Posting

OK. This turned out to be weak. You will just end up with the IP address of the server running the app and not the visiting individual. Boo.

A Dangerous Method

In contrast to what I thought was my last find-yourself-Sabrina posting, I've read online that the best way to go fish for the external IP is by way of a call to another service like so:

private string location()
{
   var request = (HttpWebRequest)WebRequest.Create("http://ifconfig.me");
   request.UserAgent = "curl";
   string publicIPAddress;
   request.Method = "GET";
   using (WebResponse response = request.GetResponse())
   {
      using (var reader = new StreamReader(response.GetResponseStream()))
      {
         publicIPAddress = reader.ReadToEnd();
      }
   }
   return publicIPAddress.Replace("\n", "");
}

One of the pain points I've fought through with SignalR is that something doesn't want to publish correctly.

I bought some third party hosting at discountasp.net and then became frustrated when I couldn't get the same SignalR project that ran in both Cassini and IIS Express to run there. After banging my head against the wall some I realized I was running unpublished code at Cassini and IIS Express and code I had published to a folder at discountasp.net. On the other side of realizing my mistake I pushed up my UI project to discountasp.net (with the other projects existing as .dlls so-to-speak within its bin folder) and then, suddenly, my app started working. I have been working on a SignalR project as detailed here, here, here, here (where MagicStringFactory has not yet been renamed to MagicStringLibrary), here, and here.

Sunday, April 7, 2013

BundleConfig note on SignalR

I forgot to mention here, here, here, here (where MagicStringFactory has not yet been renamed to MagicStringLibrary), and here that you will have to add to BundleConfig an entry that wires up SignalR to @Scripts.Render("~/bundles/signalr") in my view in order to get it to work.

(roundtrip) around the world, the Hello World of SignalR that is

The thing I've been building here, here, here, and here (where MagicStringFactory has not yet been renamed to MagicStringLibrary) now has blossomed to the point of a functioning SignalR application. Observe:

using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ShockCaperShivers.Core;
using StructureMap;
namespace ShockCaperShivers.SignalR
{
   public class EchoConnection : PersistentConnection
   {
      protected override Task OnConnected(IRequest request, string connectionId)
      {
         return base.OnConnected(request, connectionId);
      }
      
      protected override Task OnReceived(IRequest request, string connectionId,
            string data)
      {
         var json = (JObject)JsonConvert.DeserializeObject(data);
         IClockRepository clockRepository = ObjectFactory
               .GetInstance<IClockRepository>();
         Hand hand = HandFactory.CreateHand(json["HandAtHand"].ToString(),
               json["IpIdentity"].ToString(), clockRepository);
         IHandRepository handRepository = ObjectFactory.GetInstance<IHandRepository>();
         string status = Game.Play(hand, handRepository);
         var message = new { body = status };
         return this.Connection.Broadcast(message);
      }
   }
}

 
 

Every browser bringing up the following view will catch and work with the anonymous type at second to last line of the second method above. This will happen "in real time" and whenever applicable without a user needing to update a browser manually.

@model ShockCaperShivers.Models.Ip
@{
   Layout = null;
}
<!DOCTYPE html>
<html>
<head>
   <title>Shock Caper Shivers</title>
</head>
   <body>
      @Styles.Render("~/Content/css")
      @Scripts.Render("~/bundles/modernizr")
      @Scripts.Render("~/bundles/jquery")
      @Scripts.Render("~/bundles/signalr")
      @Html.Hidden("ip", Model.Address)
      <button id="@ShockCaperShivers.Core.MagicStringLibrary.Rock" class="hand">
            </button>
      <button id="@ShockCaperShivers.Core.MagicStringLibrary.Paper" class="hand">
            </button>
      <button id="@ShockCaperShivers.Core.MagicStringLibrary.Scissors" class="hand">
            </button>
      <div id="outcome"></div>
      <script language="javascript">
         $(function () {
            var connection = $.connection("/signal");
            connection.start();
            $('.hand').bind('click', function () {
               var hand = {
                  HandAtHand: $(this).attr("id"),
                  IpIdentity: $('#ip').val()
               };
               var string = JSON.stringify(hand);
               connection.send(string);
            });
            connection.received(function (message) {
               var status = message.body;
               var location = "|" + $('#ip').val() + "|";
               if (status.indexOf(location) >= 0) {
                  var identity = location + "(YOURSELF)";
                  $("#outcome").html(status.replace(location, identity).replace(location + " ",
                        identity + " "));
               }
            });
         });
      </script>
   </body>
</html>

Saturday, April 6, 2013

Spool up Fluent NHibernate filtering conditions.

The thing I've been building here, here, and here now has the following Fluent NHibernate-flavored repository. Check out the second method below:

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Criterion;
using ShockCaperShivers.Core;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
namespace ShockCaperShivers.Infrastructure
{
   public class HandRepository : IHandRepository
   {
      public void AddHand(Hand hand)
      {
         using (var sessionFactory = CreateSessionFactory())
         {
            using (var session = sessionFactory.OpenSession())
            {
               using (var transaction = session.BeginTransaction())
               {
                  session.Save(hand);
                  session.Flush();
                  transaction.Commit();
               }
            }
         }
      }
      
      public Hand[] RetrieveFirstFewUnmatchedHands()
      {
         using (var sessionFactory = CreateSessionFactory())
         {
            using (var session = sessionFactory.OpenSession())
            {
               session.CreateCriteria(typeof (Hand)).List();
               IList criteria = session
                  .CreateCriteria(typeof(Hand))
                  .Add(Restrictions.IsNull(MagicStringFactory.HandOpposing))
                  .AddOrder(Order.Asc(MagicStringFactory.TimestampIdentity))
                  .SetMaxResults(3)
                  .List();
               Hand[] handsSurvivingFiltering = GetHandsSurvivingFiltering<Hand>
                     (criteria).ToArray();
               session.Flush();
               return handsSurvivingFiltering;
            }
         }
      }
      
      public void UpdateHands(Hand handAtHand, Hand handOpposing)
      {
         using (var sessionFactory = CreateSessionFactory())
         {
            using (var session = sessionFactory.OpenSession())
            {
               using (var transaction = session.BeginTransaction())
               {
                  session.SaveOrUpdate(handAtHand);
                  session.SaveOrUpdate(handOpposing);
                  session.Flush();
                  transaction.Commit();
               }
            }
         }
      }
      
      private static IList<T> GetHandsSurvivingFiltering<T>(IList criteria)
      {
         IList<T> handsSurvivingFiltering = new List<T>();
         foreach (T value in criteria)
         {
            handsSurvivingFiltering.Add(value);
         }
         return handsSurvivingFiltering;
      }
      
      private static ISessionFactory CreateSessionFactory()
      {
         return Fluently.Configure().Database(MsSqlConfiguration.MsSql2005
               .ConnectionString(c => c.FromAppSetting("FluentNHibernateConnection")))
               .Mappings(m => m.FluentMappings.AddFromAssemblyOf<HandRepository>
               ()).BuildSessionFactory();
      }
   }
}

Thursday, April 4, 2013

How do I make a new Windows Service?

This seemed to me a pretty good article on setting up a new Windows Service. I don't have the need to do so, but I've wondered how I might set one up anew from nothing. A class which subclasses ServiceBase is the cornerstone of such an application. One thing that messed with my mind was the fact that such a class had a different icon as if it were made in Visual Studio from a means other than just creating a new class. The artice I give a link too suggests that is not the case.

using System.ServiceProcess;
namespace AreYouBeingServed
{
   class FooService : ServiceBase
   {
      private System.Diagnostics.EventLog eventLog;
      
      public FooService()
      {
         this.eventLog = new System.Diagnostics.EventLog();
         ((System.ComponentModel.ISupportInitialize)(this.eventLog)).BeginInit();
         this.eventLog.Log = "Application";
         this.eventLog.Source = "FooService";
         this.ServiceName = "FooService";
         ((System.ComponentModel.ISupportInitialize)(this.eventLog)).EndInit();
      }
      
      protected override void OnStart(string[] args)
      {
         eventLog.WriteEntry("service started");
      }
      
      protected override void OnStop()
      {
         eventLog.WriteEntry("service is stopping");
      }
      
      public void Debug()
      {
         
//whatever
      }
   }
}

 
 

I made the class above in a console application. My Program.cs is below. I have no idea if this would run or not. It is just an example.

namespace AreYouBeingServed
{
   class Program
   {
      static void Main(string[] args)
      {
         #if(!DEBUG)
         ServiceBase[] ServicesToRun;
         ServicesToRun = new ServiceBase[] { new FooService() };
         ServiceBase.Run(ServicesToRun);
         #else
         FooService myService = new FooService();
         myService.Debug();
         #endif
      }
   }
}

Wednesday, April 3, 2013

Deserialize with Newtonsoft

using System;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ShockCaperShivers.Core;
using StructureMap;
namespace ShockCaperShivers.SignalR
{
   public class EchoConnection : PersistentConnection
   {
      protected override Task OnConnected(IRequest request, string connectionId)
      {
         return base.OnConnected(request, connectionId);
      }
      
      protected override Task OnReceived(IRequest request, string connectionId,
            string data)
      {
         var json = (JObject)JsonConvert.DeserializeObject(data);
         IClockRepository clockRepository = ObjectFactory
               .GetInstance<IClockRepository>();
         Clock clock = clockRepository.RetrieveClock();
         Hand hand = new Hand();
         hand.HandAtHand = json["HandAtHand"].ToString();
         hand.IpIdentity = json["IpIdentity"].ToString();
         hand.TimestampIdentity = clock.CurrentTime;
         hand.UniqueIdentity = Guid.NewGuid();
         IHandRepository handRepository = ObjectFactory.GetInstance<IHandRepository>();
         handRepository.AddHand(hand);
         return this.Connection.Broadcast(data);
      }
   }
}

 
 

What is above is part of a first attempt at SignalR I've been building as detailed here and here. My Controller looks like so:

using ShockCaperShivers.Models;
namespace ShockCaperShivers.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         string nameOfTheComputer = System.Net.Dns.GetHostName();
         string localIp = System.Net.Dns
               .GetHostByName(nameOfTheComputer).AddressList[0].ToString();
         string publicIpv4 = Request.ServerVariables["REMOTE_ADDR"];
         string publicIpv6 = System.Net.Dns
               .GetHostEntry(nameOfTheComputer).AddressList[0].ToString();
         Ip ip = new Ip();
         if (localIp == publicIpv6)
         {
            ip.Address = publicIpv4;
         } else {
            ip.Address = publicIpv6;
         }
         return View(ip);
      }
   }
}

 
 

My model like so:

namespace ShockCaperShivers.Models
{
   public class Ip
   {
      public string Address { get; set; }
   }
}

 
 

My view like so:

@model ShockCaperShivers.Models.Ip
@{
   Layout = null;
}
<!DOCTYPE html>
<html>
<head>
   <title>Shock Caper Shivers</title>
</head>
   <body>
      @Styles.Render("~/Content/css")
      @Scripts.Render("~/bundles/modernizr")
      @Scripts.Render("~/bundles/jquery")
      @Scripts.Render("~/bundles/signalr")
      @Html.Hidden("ip", Model.Address)
      <div id="rock" class="hand">rock</div>
      <div id="paper" class="hand">paper</div>
      <div id="scissors" class="hand">scissors</div>
      <script language="javascript">
         $(function () {
            var connection = $.connection("/signal");
            connection.start();
            $('.hand').bind('click', function () {
               var hand = {
                  HandAtHand: $(this).attr("id"),
                  IpIdentity: $('#ip').val()
               };
               var string = JSON.stringify(hand);
               connection.send(string);
            });
         });
      </script>
   </body>
</html>

Keep Team Foundation Server from connecting automatically upon opening up Visual Studio 2012.

  1. Type "RegEdit" at the start menu to bring up the Registry Editor in Windows 7.
  2. Computer > HKEY_CURRENT_USER > Software > Microsoft > Visual Studio > 11.0 > TeamFoundation ...should be right-clicked upon and then "DWORD (32-bit) Value" should be picked from the "New" submenu of the menu which appears.
  3. Change the name of the new item to "AutoLoadServer."

 
 

The above comes from:

  1. http://stackoverflow.com/questions/13816331/prevent-visual-studio-from-connecting-to-team-foundation-server-on-startup
  2. http://support.microsoft.com/kb/136393

Updates for Visual Studio 2012

  1. http://www.microsoft.com/en-us/download/confirmation.aspx?id=35774
  2. http://support.microsoft.com/kb/2797912
  3. http://www.microsoft.com/en-us/download/details.aspx?id=36833

TFS cache revisited

C:\Users\Tom_Jaeschke\AppData\Local\Microsoft\Team Foundation\3.0\ and C:\Users\Tom_Jaeschke\AppData\Local\Microsoft\Team Foundation\4.0\ might be better paths than those mentioned here

TFS cache

There is a TFS cache you may delete stuff from at C:\Users\YourNameHere\Local Settings\Application Data\Microsoft\Team Foundation\2.0\Cache and C:\Users\YourNameHere\Local Settings\Application Data\Microsoft\Team Foundation\3.0\Cache.

Tuesday, April 2, 2013

Smoke testing is not functional testing.

Smoke testing is of happy pass use cases so-to-speak while functional testing implies: We tested everything.

Monday, April 1, 2013

change Application Pool Identity

At the list of application pools in IIS there will be a column for identity which probably has a default setting of "ApplicationPoolIdentity" for most most sites. Right-click on a line item and pick "Advanced Settings..." to change the Identity. You can set a custom account here to have a particular username and password and that may make it easier to connect to a database.

While we are on this I hate it that .NET Framework v2.0.50727 is the default framework for an application pool and not .NET Framework v4.0.30319. Does anyone know if there is a way to change this default? It makes me cranky?

http://www.example.com/workarea/workarea.aspx

...is the doorway to Ektron's backend for CMS management.