Thursday, April 30, 2015

Tor

direct from https://www.torproject.org/projects/torbrowser.html.en is this explanation: "Tor software protects you by bouncing your communications around a distributed network of relays run by volunteers all around the world" ...I'm reading an article about a drug trafficing web site which has been shut down (was called Silk Road) which made it's users use Tor for anonymity.

Addendum 5/1/2015: Now I've finished reading the article. It seems that Silk Road currently lives again as Silk Road Reloaded and that a different browser named IP2 must be used to interface with it.

mouseenter, mouseleave, and affecting every child but the first one in jQuery

$('#DummyData tr').not('#DummyData tr:first').bind('mouseenter', function () {
   $(this).attr('style', 'background-color: #FFFFCC; cursor: pointer;');
});
$('#DummyData tr').not('#DummyData tr:first').bind('mouseleave', function () {
   $(this).attr('style', 'background-color: #FFFFFF; cursor: pointer;');
});
$('#DummyData tr').not('#DummyData tr:first').bind('click', function () {

 
 

...this would be pretty good for making every row in an HTML table clickable and also highlightable upon mouseover save for the first as perhaps the first is used as a header instead of a data row.

Get the IP Address of the thing poking at you in an ApiController in C#!

string ip = HttpContext.Current.Request.UserHostAddress;

 
 

Addendum 11/2/2015: On a similar note...

HttpContext.Current.Request.Browser.Browser

 
 

...will give you a friendly, simple name for the browser touching you, and if you set a breakpoint in the ApiController while debugging and then open the Immediate Window and type the following you will get a dump of all sort of facts about who is peering in your window from outside:

HttpContext.Current.Request

Tuesday, April 28, 2015

skiplagged.com

Imagine you want to fly (by, yes, airplane) from Austin to Baltimore, but that instead of flying direct from Austin to Baltimore it turns out to be cheaper to book a flight from Austin to Boston with a layover in Baltimore and you just get off in Baltimore midway through what was meant to be a longer journey in the eyes of the airline. You can't take any luggage other than carryon in such a loophole expedition, but you may save a few dollars and you're not technically breaking any laws. skiplagged.com finds pricing to price flights with this quirk in mind and finds people cheap flights that way. There has been at least one lawsuit aimed at pushing this party out of business but they are still around, changing the game, and exposing a secret that airlines would rather you not know about. On the other hand, I've heard that the airline business is a terrible business to be in and that air travel has just gotten progressive worse all of my life. I guess this doesn't help make the lives of the airfare-fed easier by squeezing pricing even more, but it is a legitimate insight in a capitalist society.

May I use a space inside of an id tag in HTML?

No! Don't be stupid. Duh. This details the HTML4 and HTML5 standards for element naming and neither of them allow it. The HTML4 standard is a little more restrained than that of the HTML5 standard and I'd just do things it's way to accomodate both. That criteria: ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

I learned today that a PlayStation 3 has a Blu-ray player bundled into it!

Why does it need it? I don't want to know.

IsNullOrWhitespace

A more complicated version of this...

if (!String.IsNullOrEmpty(whatever)) {

 
 

...the following will also check to see if a string has characters which are just spaces.

if (!String.IsNullOrWhitespace(whatever)) {

Sunday, April 26, 2015

Web forms projects sure are a lot more upwards compatible than MVC projects.

Open that old web forms project you made in Visual Studio 2005 in Visual Studio 2013. It should be OK. Now try to get that old MVC1 thing you made in Visual Studio 2008 running in Visual Studio 2013. You are in for quite a fight!

Saturday, April 25, 2015

I learned today that if you're an American and you go to Canada that your cell phone should still work.

You may get some roaming charges bolted onto your bill however.

Addendum 5/13/2015: I pen this inside of Canada and I have now been through the roaming charge experience. I will need to call Verizon wireless when I am back stateside to turn off the roaming plan I turned on. As soon I as I was over the border they texted me with a number to call to get my phone to work anew. (It has stopped working outright.) Using iOS 8.1.3 (12B466) at my iPhone 4S I had to ultimately go into Settings > General > About to read off the ICCID number to the party with Verizon on the other end of my phone call. I had to go into Settings > Cellular > Roaming to explicitly turn on "Data Roaming" too in order to shove vacation photos up to Facebook.

Friday, April 24, 2015

SaaSy exception handling

When you catch an exception in C# in a web-based SaaS app, you probably want to log in detail what happened, but perhaps bubble up to the public an error message a bit less explicit (more generic).

VMWare frustrations

Two or three days ago a VMWare VM was just freezing up on me. A coworker suggested that I try to run an update, but it looks like my VMWare is up to date. Another coworker suggested turning off ReSharper in Visual Studio because it may be doing something heavy-handed under the hood. Maybe I'll try that if it happens again. As it is, I've just been restarting every time I get a freeze, which isn't all that often really. I also hate how painful it can be to copy and paste between a VM and my desktop. Sometimes I have to explicitly right-click, select copy, and then right-click, and select paste instead of just using Ctrl-C and Ctrl-V.

NOC (pronounced knock) stands for network operations center.

It is a warroom for monitoring one's network and other IT infrastructure and their traffic.

Did you know you may get freaky in speaking from a child's constructor to a parent's constructor in C#?

It doesn't have to be a one-to-one pass-right-though type of mapping. If we have a parent like so...

namespace Cats.Models
{
   public class Feline
   {
      public string Speak { get; private set; }
      public Feline(string meow)
      {
         Speak = meow;
      }
   }
}

 
 

...there is plenty of room for dress up on the child's part.

namespace Cats.Models
{
   public class Panther : Feline
   {
      public Panther(string roar) : base(roar.ToUpper() + "!!!")
      {
      }
   }
}

 
 

You may also call out to static methods in static classes to undertake more complicated surgical procedures, allowing what goes into the base constructor to be maintained as a single line of code, or really less than a single line of code, just variables, you know?

Make your own variety of exception in C#!

You will write a class that inheirts from ApplicationException. When you throw an exception of your custom shape you may then try to catch your variety of exception first in a try/catch wrapping greater mechanics (inside which the point in code which actually throws your exception is likely deeply nested) before falling over to a more generic catch. That kind of looks like this, but more specifically like:

try
{
   DoSomethingDangerous();
}
catch (FooException fooException)
{
   DoSomethingFooFlavored(fooException);
}
catch (Exception exception)
{
   DoSomethingElse(exception);
}

 
 

There is a parameterless constructor for ApplicationException, but also a handful of parameters. The constructor shaped like...

ApplicationException(string message, System.Exception innerException)
{

 
 

...may in effect define a message and an inner exception handed in from your custom thing shaped like so:

using System;
namespace Whatever
{
   public class FooException : ApplicationException
   {
      public FooException(string bar, Exception baz) : base(bar, baz) { }
   }
}

 
 

Deep in the bowels of the greater stuff wrapped in a try/catch, you'll implement your specific exception in a different try/catch (yes, nested inside of the DoSomethingDangerous logic above) like so:

try
{
   DoSomethingFooSpecific();
}
catch (Exception exception)
{
   throw new FooException("yikes!", exception);
}

travelling salesman problem

copied directly from Wikipedia: "The travelling salesman problem (TSP) asks the following question: Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city exactly once and returns to the origin city? It is an NP-hard problem in combinatorial optimization, important in operations research and theoretical computer science." ...and for NP-hard Wikipedia verbosely describes a tough challenge as: "NP-hard (Non-deterministic Polynomial-time hard), in computational complexity theory, is a class of problems that are, informally, 'at least as hard as the hardest problems in NP'. More precisely, a problem H is NP-hard when every problem L in NP can be reduced in polynomial time to H. As a consequence, finding a polynomial algorithm to solve any NP-hard problem would give polynomial algorithms for all the problems in NP, which is unlikely as many of them are considered hard." ...while another gem is: "combinatorial optimization is a topic that consists of finding an optimal object from a finite set of objects"

Thursday, April 23, 2015

Offer a default value for loose coupling only.

One cool thing about named and optional arguments in C# is that one may have an an optional arguement at an interface's method's signature without having to make a class implementing the interface also specify an optional argument at its own dance partner method's signature. I'm not yet sure about how overriding/hiding methods a parent class works along these lines. Things will not work the other way around for interface and implementer. You may not have an optional variable at the implementer and just leave that bit of the method signature off at the interface and get away with it.

 
 

Addendum 6/14/2016: I a rereading this and wondering what I meant. If you have something like int? id=null at the method signature in one place (interface or implementing class) you have to have it in the other.

Wednesday, April 22, 2015

Address1 and Address2 are fairly typical variable names for the two lines of a street address.

I remember from reading Bob Martin's Clean Code that variables and class instances which are named in a series with a numbers bolted onto the end like this are named poorly (per the book) as this goofy abbreviated encoding like most such shortcuts of "speech" is counter to the goals of ubiquitous language as suggested in Eric Evans' Domain Driven Design. It seems Address1 and Address2 are a silly convention that is here to stay however and we might as well embrace it instead of fight with it. There are numerous examples of this in the works of others. It's nearly a standard. If I were to name a variable SecondOptionalAddressLineForSuiteNumber to be explicit it would confuse everyone but myself.

Skype may elect to run on port 443.

If it does so, then naturally it may sabotage the ability to browse https:// web sites. This came up in a conversation today. I haven't myself experienced it firsthand. One party in the conversation thought that it has to do with what spins up first upon reboot and another thought it might be a quirk restrained just to Skype for Business.

Is LifeLock CEO Todd Davis' social security number a good one to use in testing code that needs an SSN?

I'm really asking and it's famously: 457-55-5462

If you look up Mr. Davis on YouTube you can find an advertisement in which a truck drives around a city with his social security number painted on the side of it. This was a TV commercial in 2007 or 2008 or so meant to inspire confidence in his company's ability to protect SSN numbers from abuse. He advertised his own number. What is a better bit of dummy data to use if not this one. By the way I Googled if it was criminal for me to rebroadcast someone else's SSN and it seems not to be. I found: this

Alliance Data's web services have different inbound parameters for zip codes and Canadian postal codes.

If 00130 is handed in for the zip, that seems to be a flag to tell Alliance Data to make sense of the otherwise optional and ignored postal code setting. I surmise this allows them an easier time of running regular expressions or whatever against what is handed to them to figure out if the given thing is legit and what it was for to begin with. K1A 0B1 is after all very different from 78759, and this particular datum is something vital in the credit card space. Interesting API. Puts some figure-it-out work on the user's back.

Tuesday, April 21, 2015

ASP.NET web sites (instead of solutions with projects) are just ghetto and their Web.config files will freak out when you run them as IIS applications it seems.

I am able to run a web site as a web site just fine in IIS, but when I turn around and run it as an application, it starts to break on the sixth line of the Web.config as seen here.

<?xml version="1.0"?>
<configuration>
   <configSections>
      <sectionGroup name="system.web.extensions"
      type="System.Web.Configuration.SystemWebExtensionsSectionGroup,
      System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
      PublicKeyToken=31BF3856AD364E35">
         <sectionGroup name="scripting"
               type="System.Web.Configuration.ScriptingSectionGroup,
               System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
               PublicKeyToken=31BF3856AD364E35">
            <section name="scriptResourceHandler"
                  type="System.Web.Configuration.ScriptingScriptResourceHandlerSection,
                  System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
                  PublicKeyToken=31BF3856AD364E35" requirePermission="false"
                  allowDefinition="MachineToApplication"/>

 
 

This isn't the only point of pain as I can remove this line and hit another hurdle too. The solution seems to be to dumb way down the Web.config, only for IIS applications, like so:

<?xml version="1.0"?>
<configuration>
   <system.web>
      <compilation debug="true" targetFramework="4.0"/>
      <httpRuntime requestValidationMode="2.0" />
      <webServices>
         <protocols>
            <add name="HttpGet"/>
            <add name="HttpPost"/>
         </protocols>
      </webServices>
      <customErrors mode="Off"/>
   </system.web>
</configuration>

 
 

Why so? I don't know yet. Maybe the app pool for 4.0 struggles to provide for the 3.5 stuff? It really doesn't make a lot of sense to me. The Web.config stuff is the most obtuse and murky part of the whole of the ASP.NET/Visual Studio experience in my opinion. None of the wireups are intuitive. You have to just learn the hard way how to deal with stuff not unlike having your car break down on you in order to learn how to maintain an automobile. Trying to hide Web.config doctorings within a NuGet package's magic kind of makes sense and also kind of admits aloud there is something painful that none of us want to think about.

I keep hearing about how easy it is to use TurboTax.

...instead of physically going into H&R Block to do taxes supposedly turbotax.com lets you do it yourself for a comparable price while automating the process and making it brainlessly easy. I have not yet tried it. It is so cheap and easy either way that I feel little incentive to change up my once-a-year routine. Whatever.

hbogo.com has an archive of all of the HBO shows and you may just watch them on your laptop.

I'm serious. It's mad. For years I've heard people rave about "Game of Thrones" and now I'm finally starting to watch it. It seems like it really is that good.

Monday, April 20, 2015

Unit test HttpResponseMessage when it is returned from a Web API controller in C#!

using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace ApiControllerTesting.Controllers
{
   public class WhateverController : ApiController
   {
      public HttpResponseMessage Post()
      {
         string commentary = "I like cats!";
         return Request.CreateResponse(HttpStatusCode.Created, commentary);
      }
   }
}

 
 

Per this what is above may be tested like so:

using System.Net.Http;
using System.Web.Http;
using ApiControllerTesting.Controllers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ApiControllerTesting.Tests.Controllers
{
   [TestClass]
   public class WhateverControllerTest
   {
      [TestMethod]
      public void Test()
      {
         string goody;
         WhateverController whateverController = new WhateverController();
         whateverController.Request = new HttpRequestMessage();
         whateverController.Configuration = new HttpConfiguration();
         HttpResponseMessage httpResponseMessage = whateverController.Post();
         httpResponseMessage.TryGetContentValue<string>(out goody);
         Assert.AreEqual(goody, "I like cats!");
      }
   }
}

 
 

On the controller side, we are, in this example, returning the response in a shape different than I am used to. I am used to handing back strings or serialized objects as strings like so:

return new HttpResponseMessage
{
   Content = new StringContent("I like cats!")
};

 
 

...but, I cannot figure out how to both do this and test it. Rats!

Sunday, April 19, 2015

It's hard to be critical of pseudoagile.

All arguments about why something is bad are a variation of "Com'on guys. We're not really doing Agile." and the counterargument is: "Yeah. You knew that. Get over it." That said, pseudoagile can work! The only time I worked somewhere that truly adhered to the Agile process was that big project at that place I won't keep mentioning that I wasn't much of a part of. Otherwise, it has been something vaguely like Agile. Most companies seem to do pseudoagile in my observation. My current employers started doing "Agile" to turn around some problems and the thing they are doing is working for them and it is healthy. In contrast, the team at AMD only did Agile, not to solve a problem, but because... i-don't-know ...I think Joel Holder just thought it sounded cool. In both pseudo circumstances there is little reason to pipe up with a dissenting voice when going around the room in a retrospective and mentioning what went right and what went wrong. The management won't want to be "undermined" by suggestions after all, especially so in the latter case where they are trying to humor a hero instead of solve a problem. So don't make yourself an enemy by asking the tough questions. No one likes that.

If you don't hate your environment and you don't want to leave try to find ways to contribute and be helpful. This seemed to be my tireless personal mantra at that place I won't name. However, if you wish your employers were just better people, I wouldn't hold out optimism for change. Just bail. Get out of it. The "entrenched aristocracy" as Scott Bellware puts it won't want to hear that they need to clean up their act.

Saturday, April 18, 2015

delete and scope isolation in JavaScript

I saw Chander Dhall speak on JavaScript at Iron Yard, which seemed to be a business in one of those buildings by Penn Field in South Austin, on Thursday night. The talk covered a wide variety of things. The first of the two things he said which I found the very most interesting was that one should not be too quick to use var and not put a variable in global scope as there is no way to delete a variable when it is declared with var. In this example...

var x = 0;
y = 0;
delete x;
delete y;
console.log(x);
console.log(y);

 
 

...the console will first get a zero in it because x could not be deleted and then will have to deal with the undefined, perhaps writing out "Uncaught ReferenceError: y is not defined" in the case (my case) of Google Chrome. The other interesting thing said almost trended in the opposite direction suggesting that it might be wise to wrap your "global" scope variables in a self-executing function like this...

(function(){
   var x = 0;
   console.log(x);
})();

 
 

...as just about anything may be overpowered by another thing downstream in JavaScript. If you have several AngularJS applications which all declare an "app" variable then the app variable for one app can just overwhelm that of another app variable defined upstream in flow. The scoping here isolates one from that havoc. Even "reserved keywords" like undefined may be overpowered by just setting them to something else by putting them at the left of an equals sign. I'm serious. You can set undefined to a function you author and I almost don't want to think about the hacking creativity that may stem from this sort of thing. A lot of the talk was on stuff I wish I didn't have to think about. Chander showed us a lot of scary stuff that had an "Oh, yikes!" quality. We went out into the badlands. Did you know that every variable has a writable, enumerable, and configurable true/false setting? You largely don't have to think about these because they are, by default, true, yet they are there! Oh, yikes! An Eric McVicker gave a talk on the coming ECMAScript 5 right after Chander's talk and while I didn't stick around for his talk I did make a note of his very first example which showed off the let keyword like so:

var i = 1
for (var i = 0; i < 10; i++) {
   console.log('loop ' + 1)
}
console.log(i)
 
let j = i
for (let j = 0; j < 10; j++) {
   console.log('loop ' + j)
}
console.log(j)

 
 

I didn't stay to find out what this does. The lack of semicolons above is not a typo.

hide/show

.hide() and .show() in jQuery behave an awful lot like .attr("style", "display: none;") and .attr("style", "display: block;") respectively. Cool.

method overloading at Web API Controllers to accommodate old versions of Internet Explorer

...looks like this:

public bool Post(Foo foo)
{
   return Bottleneck(foo);
}
 
public bool Get(Foo foo)
{
   return Bottleneck(foo);
}
 
public bool Get(string param)
{
   var foo = JsonConvert.DeserializeObject<Foo>(param);
   return Bottleneck(foo);
}

 
 

IE9 and less will only be able to interface with the last of these. DeserializeObject will need the Newtonsoft.Json namespace as a using directive.

Driving CORS through attributes at the controller level in C#.

While, yes, you may do this at a method, you may also do the following at the controller level for all the verb methods.

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class MyController : ApiController
{

Nest a do loop inside of an .ExecuteReader implementation to make something happen for every row returned from a sproc.

sqlConnection.Open();
using (var command = new SqlCommand("whatever", sqlConnection)
   {
      CommandType = CommandType.StoredProcedure
   })
{
   command.Parameters.Add(CreateParameter("foo", "bar"));
   using (var row = command.ExecuteReader())
   {
      if (row.Read())
      {
         do
         {
            string stuff = Convert.ToString(row["myColumn"]);
            DoThatThingYouDo(stuff);
         } while (row.Read());
      }
   }
}

 
 

...will run the DoThatThingYouDo method for every row returned while the following will only do so for the first row:

sqlConnection.Open();
using (var command = new SqlCommand("whatever", sqlConnection)
   {
      CommandType = CommandType.StoredProcedure
   })
{
   command.Parameters.Add(CreateParameter("foo", "bar"));
   using (var row = command.ExecuteReader())
   {
      if (row.Read())
      {
         string stuff = Convert.ToString(row["myColumn"]);
         DoThatThingYouDo(stuff);
      }
   }
}

Did you know you may use const values in an abstract class kind of like static values in a static class in C#?

public abstract class Stuff
{
   public const string Foo = "Bar";
   public const string Baz = "Qux";
}

 
 

The above should let you do something like this:

string foo = Stuff.Foo;

Thursday, April 16, 2015

When someone posts to an Web API Controller and you return a HttpResponseMessage, you may spec where the user gets routed back to!

I continue to be amazed at the freedom I have to reach back up to a web site that spoke into me from the API side in ASP.NET MVC Web API controllers. Not unlike this, the following lets you change what it at the browser, only this time we are redirecting to another URL instead of replacing the existing HTML with our own HTML:

Uri uri = new Uri(myMagicString);
HttpResponseMessage httpResponseMessage =
      Request.CreateResponse(HttpStatusCode.Moved);
httpResponseMessage.Headers.Location = uri;
return httpResponseMessage;

 
 

Clearly, in this example myMagicString would contain a URL. If you want to just use the URL that the browser was at when it spoke into the API to begin with you may do so like this:

string myMagicString =
      System.Web.HttpContext.Current.Request.UrlReferrer.ToString();

 
 

If you use this trick to route back to where one was you should probably trim away the URL line variables first like so:

if (myMagicString.Contains("?")) myMagicString = myMagicString.Split('?')[0];

heuristic

any approach to problem solving, learning, or discovery that employs a practical methodology not guaranteed to be optimal or perfect, but sufficient for the immediate goals

(not panacea, a cure-all)

Wednesday, April 15, 2015

Zoom in and out the size of code in Visual Studio 2013.

This is how public speakers make the text big when presenting and projecting at the same time. Hold Ctrl and Shift and then click the greater than and less than signs to go up and down. In the lower left corner of Visual Studio you should see a number changing which denotes what percentage of zoom you are currently at.

Create a custom view in Rally to let you see if there are any code reviews in the current iteration which need your attention.

  1. Under the "TRACK" dropdown at the top navigation, click the plus button to add a new custom page.
  2. A "Custom Page" dialog box will appear. You may give the page a name here and decide if you want to filter the report you will make based on "None" or "Iteration" or "Release" and, obviously, I suggest the "Iteration" options. Wrap this up and save.
  3. You'll see a light blue box which says "Welcome to your custom page!" in it and there will be a few custom layouts to pick from. Pick the layout that represents two reports side by side. We will need to have one report for stories and one report for defects as both may need code reviews.
  4. Click "Start adding apps." which will take you to the "APP CATALOG" where you should pick "Custom List (formerly Custom Grid)" and then click: "Add This App"
  5. You'll next see your custom page with the beginnings of a report in one of its layout halves. Under the columns dropdown pick "Code Review" and "Code Reviewed" and "State" and then give the piece of the page a name and save it. The default setting for "Object" should be "User Story" here which is good.
  6. Alright, that will give you, at a glance, some reporting on stories and it should be easy to tell which ones have code reviews. All that remains is to do the same thing for defects. Click on the gear at the upper right and pick "Add App..." to add the second half of the report. You will basically repeat the last two steps while changing the "Object" setting to "Defect" before checking the checkboxes.
  7. This will give you the two reports side by side. (To delete the report go back into the "TRACK" dropdown, click the pencil, and then click the gear by your report. This should expose a way to delete.)

Private label cards don't always have expiration dates!

That Macy's credit card can last you a lifetime!

examples of restrictions in XSDs

  1. <xs:element name="MyString" minOccurs="0">
       <xs:simpleType>
          <xs:restriction base="xs:string">
             <xs:pattern value="^[^a-z]+$"/>
             <xs:minLength value="1"/>
             <xs:maxLength value="25"/>
          </xs:restriction>
       </xs:simpleType>
    </xs:element>
  2. <xs:element name="MyIntegerInStringForm" minOccurs="0">
       <xs:simpleType>
          <xs:restriction base="xs:string">
             <xs:pattern value="[0-9]{7}"></xs:pattern>
          </xs:restriction>
       </xs:simpleType>
    </xs:element>
  3. <xs:element name="MyDateTimeInStringForm">
       <xs:simpleType>
          <xs:restriction base="xs:dateTime"/>
       </xs:simpleType>
    </xs:element>

.FirstOrDefault came up in a conversation last night.

In C# it will behave a lot like .Single but it will not throw an exception if there is not just one item returned from filtering a collection. This should allow you to be more evil, clop around all cloven-hooved.

 
 

Addendum 12/19/2015: .FirstOrDefault will not break when it finds nothing. It will return null. In the case of value types, such as a list of int, it will return a default value (which would be 0 for int types).

Tuesday, April 14, 2015

Cain & Abel is a tool for guessing/finding passwords.

This has some copy on it. It uses dictionary, brute-Force and cryptanalysis varieties of attacks. I don't yet understand the distinctions.

There is such a thing as attribute routing in ASP.NET MVC.

This has the following example which I bet behaves just as you'd expect...

[Route("customers/{customerId}/orders")]
public IEnumerable<Order> GetOrdersByCustomer(int customerId) {
... }

Change the sensitivity in Microsoft Outlook 2010.

  • go to the "File" tab
  • pick "Options" from that menu that runs down the far left below the "File" tab
  • the "Outlook Options" dialog box appears and herein you should click "Mail" at the upper left
  • scroll down until you see "Default Sensitivity level:"
  • change the setting to Normal, Personal, Private, or Confidential as desired

Monday, April 13, 2015

A reference to 'System.Core' could not be added. This component is already automatically referenced by the build system.

This and this both suggest that this problem may rear its head when one deletes System.Core (and/or maybe mscorlib) as a reference and tries to readd it. A suggested fix is to close Visual Studio 2013, open a .csproj file in Notepad, find this line...

<Reference Include="System" />

 
 

...and add this line below it...

<Reference Include="System.Core" />

 
 

...and yet that doesn't work for me because I sense something sinister of a greater scope. I think the fact that the application I am working on, which used to be of C# 2.0, has been upgraded to C# 4.5.1 is causing strangeness. I have no real evidence to back up my theory, I just don't see what else gives. In my case when I attempt the fix System.Core appears as a reference in the Solution Explorer when I open Visual Studio back up again, but when I try to bring in a using directive that makes use of System.Core it appears as red and angry in Visual Studio and does not compile. I should be able to dot out to things which theoretically exist off of a dynamic type like so:

dynamic dateTimeOffset = (dynamic)DateTimeOffset.UtcNow;
DateTime dateTime = dateTimeOffset.DateTime;

 
 

...but I cannot. I get the squiggly red line beneath the dateTimeOffset.DateTime and when I put my mouse over it I am told:

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dill?

 
 

I can hack around the shortcoming like this:

dynamic dateTimeOffset = (dynamic)DateTimeOffset.UtcNow;
DateTime dateTime = ((DateTimeOffset)dateTimeOffset).DateTime;

 
 

...but I shouldn't have to. What am I missing?

 
 

Addendum 1/29/2019: DateTimeOffset.Now is also a thing.

Saturday, April 11, 2015

another break with the Onion Architecture

In the onion approach one should be motivated to push as much logic into the core as possible, without bringing in external dependencies, making it at fat as possible. One should loathe to keep logic in the UI, where it has been traditionally hard to test. However, the UI testing is getting easier, especially with the way now that modern StructureMap hydrates dependencies at MVC4 constructors for controllers and at my work we have found another reason (see this for the first) to break with the traditional onion framework. If, in a workflow, different steps may throw different exceptions or cause different here-is-what-happened messaging to come back out of a controller, it is probably cleanest to have this logic in a controller and to just wrap the controller in test. The alternative to keep the logic in the core and have it bubble up a core object to the controller where there has to be a new rat's nest of logic to cast the core object to the here-is-what-happened UI messaging type. The controllers are easier to test now. One may stub or mock the dependencies at the constructor's signature. It is trickier to deal with Session. It probably needs to be brought in to scope as one of the dependencies.

WordPress now powers 20% of the web.

Mom and pop web sites are marinated in PHP.

When the debugger in Visual Studio is telling you the problem is in "CSC" instead of pointing you to a particular line of code in a particular file...

...that means it vaguely knows that something in the project is jacked, but it cannot know where for sure as it cannot compile that project because an afferently coupled project can't compile. You shouldn't see this error standalone. It will appear in the debugger with other errors, and you'll just have to fix the other errors first.

a button inside of a web form will make the web form postback no different than an input of type=submit

onclick="doSomething(); return false;" put inline in the tag will prevent this behavior and let you do something in JavaScript instead. type="button" helps with this too.

Elements specified in an XSD are all required by default.

If nillable="true" is placed inside an element tag then a null value may be supplied for that element.

IE9 and less apparently cannot send AJAX over POST.

They have to use GET. :(

StructureMap polymorphism!

We have circled back to using polymorphism to tackle the problem described here and here but instead of using Activator.CreateInstance we are now using StructureMap like so:

For<IWebServiceVersion>().Use<WebServiceVersion13>().Named("Web Service 13");

 
 

...and like so:

public IContainer Container { get; set; }
public IWebServiceVersion WebServiceVersion(int version)
{
   return Container.GetInstance<IWebServiceVersion>("Web Service " + int);
}

Manage a mix of both DateTime.Now and DateTime.UtcNow as an external dependency.

It's easy to put just one of these behind an interface and just call the interface whenever you need the time, but what if you legitimately want a hodgepodge of both your server's time and the universal time in your application. Well, if you hand back DateTime.Now you may then use .ToUniversalTime() to cast it to universal time outside of the interface, but as this reveals, this hack is done assuming that a time is local and then calculating what it would take to offset the local time to universal time before finally warping what is in the DateTime type based on the calculation. If you ever change out what is behind the interface away from DateTime.Now you're in trouble and if you can't make such a change then you haven’t really isolated an external dependency. The solution is going to be to put DateTimeOffset.Now or DateTimeOffset.UtcNow behind the interface thus returning a DateTimeOffset which you need to cast into a DateTime outside of the interface like so:

DateTimeOffset dateTimeOffset = DateTime.UtcNow;
DateTime dateTime = dateTimeOffset.DateTime;

 
 

Before undertaking such a casting you may do a .ToUniversalTime() off of the DateTimeOffset type and expect results not to vary based upon what the interface doles out for the time.

Uncheck "Enable code analysis" in the Options dialog box which comes up from the "Options..." option in the RESHARPER menu of Visual Studio 2013.

This may make Visual Studio run a little faster. If it is really dragging, this could be why.

Wednesday, April 8, 2015

Make a reference key creatable in a manner friendly to MSSQL 2005.

ALTER TABLE dbo.MyTable WITH CHECK ADD CONSTRAINT
FK_MyTable_MyColumn FOREIGN KEY(MyColumn)
REFERENCES dbo.MyOtherTable (MyOtherColumn)

Microsoft Distributed Transaction Coordinator

The DTC allows for transactions to straddle multiple databases. It works out the transaction and allows one to write to one database and then roll back that change when failing to write to a second database. It going to allow one to slurp in a second connection string, I believe. Putting...

enlist=false;

 
 

...in a connection string will keep transactions restrained to a single database so that basically after a write to one database and a failed write to another the write to the first database is not undone. There is, without this, some after the fact auditing across the two databases to make sure things are shipshape. None of this is just going to work out the box. The databases have to have permissions opened up.

Wireshark

...from SolarWinds allows one to inspect packets of network traffic and the like.

Tuesday, April 7, 2015

Microsoft Office 365

I hear the new version of office will allow you to log into everything with your active directory account including SharePoint. It comes with SharePoint 2013 apparently. It also has Lync and as long as you may connect to Lync by way of WiFi you may make phone calls through it. Even from an airplane.

Can't hand a GUID into a UNIQUEIDENTIFIER variable when you run a sproc directly in SSMS?

Try wrapping the GUID in curly brackets and then wrap the GUID wrapped in curly brackets with single quotes.

Force a column to have unique values in MSSQL.

ALTER TABLE dbo.MyTable
ADD CONSTRAINT UQ_MyTable_MyColumn UNIQUE (MyColumn);

See how references may be crafted in MSSQL in your particular version of MSSQL.

Right-click on an existing table in SSMS and pick...

Script Table as > CREATE To > New Query Editor Window

 
 

This should spit up some legit SQL for making references. What you can get away with in SQL Server 2012 and SQL Server 2005 differ!

 
 

Addendum 1/28/2020: Make a CREATE TABLE script from a database table in SSMS with this trick too. Right-click on a table in the Object Explorer.

Monday, April 6, 2015

out variables return new instances of reference types

My Hydrate method here was to look like this:

public override void Hydrate(string packet)
{
   Exception exception;
   WebServiceVersion13 referenceTrick = this;
   WebServiceVersion13.Deserialize(packet, out referenceTrick, out exception);
}

 
 

...but Xsd2Code++ would really need to allow me to hand in a ref variable for a variable passed as a reference to be affected (hydrated) instead of an out variable which is just going to uselessly return a new instance of WebServiceVersion13 thus keeping me from altering "this" as desired. My superior ended up telling me to just use a case/switch statement instead of polymorphism today so all of the stuff I thought was superslick on Friday has been rolled back. Oh well. It was fun and it's all good.

specify a WCF endpoint in C# while keeping the bindings in Web.config

You may keep both the bindings and the endpoint for a web service in Web.config and then in C# overpower what address the endpoint uses like so:

ICalculatorInTheSky calculator = new CalculatorInTheSkyClient("MyEndpointName",
      "https://www.example.com/hellothere");

 
 

This shows how this may be revamped so that the binding stuff doesn't have to live on the C# side which is way painful configure. If you want to have a Service Reference in a project that is not the startup project, you'll need to move the bindings and endpoint which appear in that projects app.config (which didn't exist until just now) to Web.config. Freak.

Port 443 is the default port for SSL.

not 80 ;)

If your indentation is jacked in Visual Studio 2013...

Just remove one of the curly braces wrapping everything and add it back. Cool hack, huh?

When debugging in Visual Studio 2013 a solid red dot suggests a breakpoint you may actually stop at and a hollow red circle suggests a breakpoint that won't work for some reason.

Mouse over the breakpoint that won't work for some reason to see what's wrong. Its message may seem cryptic, but it is basically telling you to go into "Options and Settings..." in the "DEBUG" menu and therein uncheck a checkbox.

In order to send custom types to a WSDL in SmartBear SoapUI...

...well, you'll see the XML markup in the Request window with a bunch of question marks standing in for real data. Just replace the question marks here.

I'm learning this morning that series of YouTube clips may be collected into a playlist.

Kermit Meister authored a DVD in such a manner that his nearly two hour movie was broken up into chunks of twenty-seven minutes and forty-seven seconds each across a series of .vob files. I don't know if this is commonplace or not, but I ended up with several different YouTube movies for each of the files. Perhaps there is a way to stitch them all together too, but I haven't researched that either. Anyways, Cisco Buitron made a playlist here so that one may watch all of the clips sequentially.

Sunday, April 5, 2015

Honeybees are dying in mass and there is a ping pong ball inside of every can of Guinness.

These are things I learned eight days ago during the last day of filming this fine piece of cinema under the direction of Kermit Meister:

  • Note to future self: After an uploading has finished at YouTube you do not need to wait for the processing to finish. You may just turn around and upload another movie. YouTube will finish up the processing behind the scenes.
  • Note to everyone else: I don't drink but I do like honey.

Facebook now seems to recognize Twitter hashtags and make the most of them.

I tweeted "Everyone go see #ItFollows this weekend if you haven't seen it yet. (It's not like anything good came out this weekend to compete with it.)" and when my tweet fell over to my Facebook, as all of my tweets do, the #ItFollows was a link to bunch of stuff about the film "It Follows." Well done Zuckerberg? I guess this is a pretty small accomplishment for you all and all.

What is the difference between WCF and some other SOAP service from an ASP.NET perspective?

Not a lot. You'll consume a route that ends in ?wsdl instead of .svc as there is no .svc endpoint. There should be something like a client and maybe custom types to populate the getsetters on and then hand to the client. Don't be surprised if a lot of these "types" are in camel case instead of Pascal case, but otherwise they sure act like C# POCOs. You may instantiate them and dot off them in Visual Studio to see what is hanging onto them, etc.

Saturday, April 4, 2015

When wrapping a SOAP API with your own API, the versioning may present a challenge.

Let's say you wish to expose an API that needs to talk to an API itself. Let's say the other API is a SOAP API and this other thing just offers a different WSDL for each version of its service and whenever there is to be a new version there will be a new WSDL. This makes it painful to wrap. The other option this third party would have had would have been to consume an XML packet as a serialized string which could then be upwards compatible by being capable of being flexible to take in really any settings and also a version number in that packet in the name of making sense of the packet. Alright, well if they aren't going to do it I guess we have to. I have recently put together some code for this which uses:

  1. Xsd2Code++
  2. XmlDocument
  3. Activator.CreateInstance
  4. dynamic

I envision a wrapper class using an instance of a generic parent class that is an upcasting of a version-specific class to call a web service before/after it does whatever else it needs to do (no one writes a wrapper just to wrap, right?) as seen in my goofy notes here:

 
 

This is done and works, but I don't like that I have to populate the meat of the child in child-specific code. I'm going to try to making things better by overriding a virtual method as seen below so that the parent may give its kids data upstream of the kids doing their own thing. That is the next step I think. I guess I must like my job if I'm off work daydreaming of what I'll do as soon as I get back.

Restart at 1

If you right-click on an ordered list that you copied and pasted from the page above in Microsoft Word at one of its numbers, you should be able to use the option to get it to stop thinking its a continuation of something else and that it should pick up numbering its bullets where the other list left off.

Friday, April 3, 2015

New up a type in C# from a magic string.

Stuff below is an an assembly name an Stuff.Bar.Foo a class.

ObjectHandle objectHandle = Activator.CreateInstance("Stuff", "Stuff.Bar.Foo");
Foo foo = (Foo)objectHandle.Unwrap();

Fish a particular value out serialized XML in C#.

int? versionNumber;
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(myBlobOfXml);
foreach (XmlNode outerXmlNode in xmlDocument)
{
   foreach (XmlNode innerXmlNode in outerXmlNode)
   {
      if (innerXmlNode.Name == "Version")
      {
         versionNumber = Convert.ToInt32(innerXmlNode.InnerText);
      }
   }
}

When you make a C# partial class dance partner for an XSD with Xsd2Code++ you must explictly turn on the serialize/deserialize stuff.

Otherwise you will not end up with methods for serializing and deserializing at the partial code. When you see the xsd2code++ Version 4.0.0.392 dialog box, you may expand "Serialization" at the "Options" tab at the right to find the switch for "Enabled" which needs to be set to "True" for the methods to be built out. If a string called blobOfGunk contained a serialization of Foo you could deserialize like so:

Foo foo = new Foo();
Exception exception = new Exception();
bool isDeserialized = Foo.Deserialize(blobOfGunk, out foo, out exception);

 
 

...and also turn back around and reserialize like this:

string serialization = foo.Serialize();

Thursday, April 2, 2015

Anniversary!

I have actually stayed with one employer for an entire year as of today! I really love my job, and I'm enjoying working downtown too. Please don't think the cake pictured here was for me. Instead, I bought it for all of my coworkers who have had to put up with me for a year now. :P What did I learn today in particular?

  • You may right-click on a file in Visual Studio 2013's Solution Explorer and pick "Open With..." which will allow you to set how different file types open. "XML (Text) Editor (Default)" is a rocking good setting for .xsd files. If you don't set this setting they seem to open in a goofy manner that I "don't get" in a Jerry Seinfeld sense.
  • robocopy is "Robust File Copy" and a DOS command not unlike copy only with more options (bells and whistles)
  • Can you use a CTE with an INSERT statement in MSSQL? Not exactly. You can nest a SELECT within the INSERT like so however:
    INSERT INTO Foo (Id, Username, [Password])
    VALUES ((SELECT Bar FROM Baz WHERE Qux = 42), 'jdoe', 'letmein')

How do I run command line commands from an C# console application?

Well, a coworker has found one way... System.Diagnostics.Process.Start ...for example, this suggests one may open Notepad with a specific file loaded like so:

System.Diagnostics.Process.Start("Test.Txt"):

Wednesday, April 1, 2015

Post to a WebAPI controller from C# with a WebRequest instead of using an HttpClient.

Instead of this you may do this...

string message;
var request = WebRequest.Create("http://www.example.com/api/whatever");
var data = Encoding.ASCII.GetBytes(string.Format("Foo={0}&Bar={1}", "baz", "qux"));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var requestStream = request.GetRequestStream())
{
   requestStream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
using (var responseStream = response.GetResponseStream())
{
   using (var reader = new StreamReader(responseStream))
   {
      message = reader.ReadToEnd();
   }
}

 
 

This assumes the Post method returns a HttpResponseMessage wrapping, in this case, a string like so:

return Request.CreateResponse(HttpStatusCode.OK, "hi there");

You can't do POST, PUT, and DELETE with jsonp.

...only GET

"Backlog" under the "PLAN" menu has the backlog in Rally.

Com'on, I shouldn't have to tell you this.

You likely need to include a reference to System.IdentityModel when denoting a CertificateValidationMode when using a WCF web service.

Here I don't seem to mention it. But this...

x.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode =
      System.ServiceModel.Security.X509CertificateValidationMode.None;

 
 

...strangely requires the System.IdentityModel namespace.

how to use Xsd2Code++

  • Intall the Add-in in Visual Studio.
  • In the Solution Explorer, right-click on your XSD file (should have an .xsd extension and the outermost xs:element should probably have a name matching the file name too) and pick "Run Xsd2Code++" to do the deed.
  • A dialog box titled "xsd2code++ Version 4.0.0.392" appears. Click the "Generate" button here.
  • A file named the same thing as your XSD file only ending in .Designer.cs will be created. It will contain a partial class, so that you may make another file to extend the class if you so desire.

At a glance it looks like break; is the way to wiggle out of a foreach loop in JavaScript once you've found what you want.

This suggested it. I woke this morning thinking about the pain of the inability to return out of a foreach loop as detailed here. In my example, I find what I want, tuck into a variable to return later, and then finish looping... but I shouldn't have to finishing looping. Duh.

 
 

Addendum 1/4/2017: What's above is really terrible! There is no early escape form a .forEach in JavaScript. At best, you may minimize how "heavy" the looping is after a certain point if you want to do a little dance.

var whatever = function() {
   var message = "No records were found.";
   var isToKeepGoing = true;
   this.columns.forEach(function (column) {
      if (isToKeepGoing) {
         if (column.expandableRow) {
            isToKeepGoing = false;
            if (column.expandableRowEmptyError) {
               message = column.expandableRowEmptyError;
            }
         }
      }
   });
   return message;
};