Sunday, March 31, 2013

A SignalR Hello World

I have some good news. Today I got SignalR working, at least minimally working in a hello world sort of way. In attempting to follow this example, I got nowhere. The only part of it that I ended up using was the upfront use of NuGet to get SignalR to begin with. In refactoring this, I have the following Global.asax.cs:

using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using ShockCaperShivers.Core;
using ShockCaperShivers.Infrastructure;
using ShockCaperShivers.SignalR;
using StructureMap;
namespace ShockCaperShivers
{
   public class WebApiApplication : System.Web.HttpApplication
   {
      protected void Application_Start()
      {
         ObjectFactory.Initialize(x =>
         {
            x.ForRequestedType<IClockRepository>
                  ().TheDefaultIsConcreteType<ClockRepository>();
            x.ForRequestedType<IHandRepository>
                  ().TheDefaultIsConcreteType<HandRepository>();
         });
         RouteTable.Routes.MapConnection<EchoConnection>(
            name: "signalservice",
            url: "/signal"
         );
         AreaRegistration.RegisterAllAreas();
         WebApiConfig.Register(GlobalConfiguration.Configuration);
         FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
         RouteConfig.RegisterRoutes(RouteTable.Routes);
         BundleConfig.RegisterBundles(BundleTable.Bundles);
      }
   }
}

 
 

The new thing to see about the above is a reference to EchoConnection. EchoConnection is a new class I made in a new folder I made at the root of the UI called "SignalR." It subclasses PersistentConnection.

using System;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using ShockCaperShivers.Core;
using StructureMap;
namespace ShockCaperShivers.SignalR
{
   public class EchoConnection : PersistentConnection
   {
      protected override Task OnConnected(IRequest request, string connectionId)
      {
         IClockRepository clockRepository = ObjectFactory.
               GetInstance<IClockRepository>();
         Clock clock = clockRepository.RetrieveClock();
         Hand hand = new Hand();
         hand.HandAtHand = "paper";
         hand.IpIdentity = "1.2.3.4";
         hand.TimestampIdentity = clock.CurrentTime;
         hand.UniqueIdentity = Guid.NewGuid();
         IHandRepository handRepository = ObjectFactory.GetInstance<IHandRepository>();
         handRepository.AddHand(hand);
         return base.OnConnected(request, connectionId);
      }
   }
}

 
 

Now here is the magic. I can speak into the method above from a JavaScript function! Observe this view. Loading the view will pump a record into the database!

@{
   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")
      <script language="javascript">
         $(function () {
            var connection = $.connection("/signal");
            connection.start();
            connection.send("Hi there!");
         });
      </script>
   </body>
</html>

Restart this application under different credentials.

...is an option that appears when I launch Visual Studio 2012 by way of double-clicking an .sln file in C:\inetpub\wwwroot where I will need administrative privileges to resave Web.config. If I click this option, I get the administrative privileges. This is happening in a Windows 8 environment where the "Run as administrator" trick is not available from right-clicking on a desktop icon and one has to go out to the Metro interface to find it. I guess this is a convenience hack that compensates for this dumbness. I wonder if there is a way to unlock "Run as administrator" at the desktop. Whatever.

I remember hating you for loving me, riding on the Metro...

Allow SQL Server Authentication connection in SQL Server Management Studio Express 2012.

If you got this error message when attempting a SQL Server Authentication connection in lieu of a Windows Authentication connection in Mircosoft SQL Server Management Studio Express 2012 would you know what to do?

A connection was successfully established with the server, but then an error occurred during the login process. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.) (Microsoft SQL Server, Error: 233)

 
 

Well, I have spent my morning figuring this out and have fought my way through these four links:

  1. http://msdn.microsoft.com/en-us/library/cc646023.aspx
  2. http://www.bopup.com/support/install_sql_server_2005_2008_2012_as_database_server.html
  3. http://blogs.technet.com/b/danstolts/archive/2011/06/08/how-to-open-firewall-port-1433-for-sql-server-database-engine-for-use-with-scom-or-anything-else.aspx
  4. http://csharpdotnetfreak.blogspot.com/2010/01/sql-server-shared-memory-provider-error.html

 
 

The second half of the last article had my solution:

  1. Log onto SQL Server Management Studio Express 2012 as yourself with Windows Authentication.
  2. In the "Object Explorer" right-click on the server name and pick "Properties."
  3. The "Server Properties" dialog box will appear. Click on Security at the upper left.
  4. Change the "Server authentication" radio button from "Windows Authentication mode" to "SQL Server and Windows Authentication mode" and then click the "OK" button.
  5. Back at the "Object Explorer" you should again right-click the server and then this time pick "Restart."

 
 

Yay! While fucking around in trying to figure out how to do this I learned anew how to open up port 1433 at my firewall. This post I wrote some time back has details applicable to Windows 8 too, especially the part on Windows Firewall with Advanced Security, though I got to that dialog box on my laptop by going to the control panel, picking "Large Icons" from "View by:," clicking "Windows Firewall" and then clicking "Advanced settings."

run web applications in IIS

If you want to run a Visual Studio project as a web site in IIS, you do not have to have a web site type project in lieu of web application. I was able to spin up an MVC4 web app and bolt other projects onto it while still running it through IIS by making the UI project standalone a web site, mapping a host header to it with hosts file magic, and then just bringing the site up in a browser by way of the appropriate URL. I suppose I cannot use the debugger to debug in this manner however.

Addendum: I found that if I am not running Cassini, that I have to rebuild in Visual Studio to get UI code changes to be reflected in the browsing I do via IIS Express.

IIS Express is not IIS.

I had an exchange with David Fowler, SignalR's coauthor, over Twitter in which encouraged me to run a SignalR project in IIS Express and not Cassini. He also cautioned that IIS Express and IIS are not the same.

Saturday, March 30, 2013

gpresult /V

...run at a command prompt will give you a dump of all of the groups your Active Directory account is tied to.

stop sharing

Pick: Share with > Nobody ...after right-clicking on a folder to stop sharing it.

pretending to be a different Active Directory user while connecting to a database

I looked into trying to connect to a database as a different Active Directory user via impersonation a smidge today and I also looked at http://www.connectionstrings.com/ to try to find a hack for this. The immediate consensus seems to be to give up on this corny idea of pretending to be a different Active Directory user.

Friday, March 29, 2013

Istanbul Not Constantinople ...of SignalR

Server-side events should probably be server-sent events here per the SignalR ebook. I have been using the wrong term. I think I misheard Scott Hanselman speak. Whatever. :P

signature versus public key handshake

In a signature a private key encrypts and a public key decrypts. I think one might refer to the opposite scenario in which a public key encrypts and a private key decrypts as a public key handshake. This comes from chapter 20 of C# 4.0 in a Nutshell.

Log into Microsoft SQL Server Management Studio as a different Active Directory user.

To do this, right-click on the SSMS icon while holding Shift. Then pick "Run as different user"

ClickOnce

When you pick the publish options from under the Build menu in Visual Studio 2010 while you have a WinForms app spun up, you are beginning the process of making a ClickOnce application installer which will end up holding a setup.exe for installing the WinForms. If told: "Application cannot be started. Contact the application vendor." ...after trying to run a setup.exe made from a ClickOnce process, delete the 2.0 folder at C:\Users\Tom_Jaeschke\AppData\Local\Apps\2.0 and then try again.

Let Internet Explorer see a site it is blocked from.

You may bump into this or something like it in Internet Explorer at Windows Server 2008 R2 where permissions are tightened up...

Content within this application coming from the website listed below is being blocked by Internet Explorer Enhanced Security Configuration.

https://www.salesforce.com

 
 

Tool > Internet Options > Security Tab > Trusted sites > Sites Button ...in Internet Explorer is the place to permission sites. A good list of sites to permission for SalesForce in particular are:

  1. https://cs3.salesforce.com
  2. https://na6.salesforce.com
  3. http://test.salesforce.com
  4. https://test.salesforce.com
  5. http://salesforcecom.tt.omtrdc.net
  6. https://salesforcecom.tt.omtrdc.net
  7. https://secure2.sfdcstatic.com
  8. http://www.google.com
  9. https://www.google.com
  10. http://www.salesforce.com
  11. https://www.salesforce.com
  12. http://www2.sfdcstatic.com

Finalizers are syntaxically like constructors that start with a tilde.

This suggests that you can use them to dispose of open connections and do the sort of things that you should probably be doing with using statements instead. I read about these in C# 4.0 in a Nutshell and decided I didn't care. I thought of them again yesterday when two guys a cube away were having a fascinating conversation about interview questions that went into internal and protected internal accessibilities. I interrupted and asked questions about my poor understanding of internal and my understanding got better. The same guys went on to talk about destructors (finalizers) and I wondered anew if I should care. I looked into them again this morning and have decided that using statements are cooler. You know?

namespace MvcApplication1.Models
{
   class Foo
   {
      internal string Bar;
      internal Foo()
      {
         Bar = "started";
      }
      ~Foo()
      {
         
//whatever
      }
   }
}

HP LoadRunner is a performance testing tool.

I haven't used LoadRunner, but it can't be as awesome as Lode Runner. I'm not being cynical. I'm being realistic.

Thursday, March 28, 2013

Upload a file in C# and ASP.NET MVC with Razor.

using System.IO;
using System.Web;
using System.Web.Mvc;
using MvcApplication.Models;
namespace MvcApplication.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         return View(new Dummy());
      }
      
      [HttpPost]
      public ActionResult Index(HttpPostedFileBase zip)
      {
         if (zip.ContentLength > 0)
         {
            var fileName = Path.GetFileName(zip.FileName);
            var path = Path.Combine(Server.MapPath("~/App_Data/" + fileName));
            zip.SaveAs(path);
         }
         return View();
      }
   }
}

 
 

I thought of doing this in combing through some of my old notes.

The form itself:

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype =
      "multipart/form-data" }))
{
   @Html.TextBoxFor(x => x.zip, String.Empty, new { type = "file",
         style = "width: 300px;" })
   <button type="submit">go</button>
}

 
 

I am using this hack for a model to make the Razor stuff work. (grumble)

namespace MvcApplication.Models
{
   public class Dummy
   {
      public int? zip { get; set; }
      public Dummy()
      {
         zip = null;
      }
   }
}

protected internal

...is going to act like internal as described here but outsiders may have at protected internal methods by inheriting from the class holding them. "protected internal" is more open than "internal" which may seem confusing.

The default accessibly is not internal.

To say "the default accessibly is internal" is a simplification. The default accessibility for a class is internal and the default accessibility for a method is private. Observe:

namespace MvcApplication1.Models
{
   class Foo
   {
      string Bar()
      {
         return "bar";
      }
   }
}

 
 

Now look at this:

namespace MvcApplication1.Models
{
   class Baz
   {
      string Qux()
      {
         Foo foo = new Foo();
         return foo.Bar();
      }
   }
}

 
 

The first line of the Qux method would compile fine but not the second. The word Bar in the Qux method would be given a squiggly red line beneath it by ReSharper. Internal works like public within the assembly/project at hand and like private elsewhere and to outsiders.

Windows Service logging

Assuming a class inheirts from ServiceBase it could "write to the logs" like so:

private System.Diagnostics.EventLog eventLog;
eventLog = new System.Diagnostics.EventLog();
((System.ComponentModel.ISupportInitialize)(eventLog)).BeginInit();
eventLog.Log = "Application";
eventLog.Source = "FooService";
((System.ComponentModel.ISupportInitialize)(eventLog)).EndInit();
eventLog.WriteEntry("look at this");

Media queries in CSS are key to accessibility.

I am working a contract at Dell in Round Rock, Texas (an Austin border town) for Sogeti. It is OK. Dell paid for me to spend seven weeks in Nashua, New Hampshire and business travel was a first for me. There has also been at least one neat free presentation over Lync too. I saw Tyson Matanich of Microsoft speak over a Lync meeting on accessibility and he asserted that beyond stuff like ARIA, accessibility in web design also means compatibility for mobile devices, tablets, and, yes, smart watches. Tyson recommended using responsive layouts with media queries to accommodate this.

@media screen and (min-width: 680px) {
   body {
      font-size: 0.8em;
   }
}

 
 

I made the page below on my desktop in the name of experimentation. If I open it in a browser and then drag the browser wider and then smaller again horizontally, I can see the color of the div change in real time. This sort of accommodation is cornerstone to responsive layout. A change of color is perhaps a silly example though. :)

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Whatever</title>
      <meta charset="utf-8">
      <style type="text/css" media="all">
         #foo {
            background-color: #FFCCCC;
         }
         @media screen and (min-width: 300px) {
            #foo {
               background-color: #CCFFCC;
            }
         }
         @media screen and (min-width: 600px) {
            #foo {
               background-color: #CCCCFF;
            }
         }
      </style>
   </head>
   <body>
      <div id="foo">Whatever</div>
   </body>
</html>

 
 

The word screen following @media should keep this stuff from having bias on print. Notice in my example that I set a default value for the narrowest possible width and then write exception cases for scaling upwards. Tyson said this is good practice. Write for mobile FIRST! He gave the following slide showing off how he adds alterations as a page width grows.

Tyson said the viewport tag is a weak way to accommodate the same sort of stuff that media queries address above.

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

 
 

This is more gauge-your-environment CSS, but I think it is inferior to media queries too.

@-webkit-viewport { width: device-width; }
@-moz-viewport { width: device-width; }
@-ms-viewport { width: device-width; }
@-o-viewport { width: device-width; }
@viewport { width: device-width; }

 
 

The layouts Tyson envisions and authors are fluid. Text wraps around images, things float, and there isn't a fixed width, but beyond that they have a responsive web design meaning:

  1. media queries
  2. flexible content

 
 

Picturefill is an example of flexible content that allows for swapping out pictures of different sizes:

<div data-picture data-alt="Microsoft" data-resolved="true">
   <div data-src="lg-1x.png"></div>
   <div data-src="lg-2x.png" data-media="(min-device-pixel-ratio: 2.0)"></div>
   <div data-src="sm-1x.png" data-media="(max-width: 539px)"></div>
   <div data-src="sm-2x.png" data-media="(max-width: 539px) and
         (min-device-pixel-ratio: 2.0)"></div>
   <noscript><img src="lg-1x.png" alt="Microsoft" /></noscript>
   <img alt="Microsoft" src="lg-2x.png" data-source-index="1" />
</div>

 
 

Icon Fonts were also recommended.

 
 

Raj Kaimal, introduced Tyson Matanich and in his introduction, he himself touched on LESS:

@dellColor: Lighten(black, 20%);
.mastHead {
   background-color: @dellColor;
}
.myHeading {
   color: @dellColor;
}
.myClass {
   padding: 5px;
}
.mySecondClass {
   margin: 10px;
}

 
 

LESS compiles to CSS. The LESS above makes the CSS here:

.mastHead {
   background-color: #333333;
}
.myHeading {
   color: #333333;
}
.myClass {
   padding: 5px;
}
.mySecondClass {
   margin: 10px;
}

Wednesday, March 27, 2013

One may simply save a document to a .pdf type in Microsoft Word 2010!

You no longer need to "print" to make a PDF within Microsoft Word! This is first "Save As" implementation for PDF I've seen.

Keep a newly installed Windows Service from automatically starting upon a restart of the server it runs upon.

  1. Type "services" at the start menu which either brings up the "Services" pane or the "Component Services" pane which has "Services" nested inside of it.
  2. Right-click on the service and pick "Properties."
  3. Change the "Startup type" dropdown to "Disabled" instead of the default "Automatic."

Is a Windows Services installer tied to an environment?

When I tried to rerun my installer to install what I installed at UAT to production, it began attempting to uninstall the UAT install. I hacked around the problem by just creating a second installer project for production.

Nest an ASP.NET web site within an ASP.NET web site.

In IIS, if you want to run a web site within a web site with ASP.NET the "Covert to Application" trick should accommodate. If you were to host a vanity website for a business at example.com and then host a subtext ASP.NET blog at www.example.com/blog/ you would prep example.com as a web site and then right-click on the "blog" folder within the web site within Internet Information Services (IIS) Manager to pick "Convert to Application" which will allow the contents of the folder, findable by a URL within a different web site, to run as its own web site. The contents of the folder would see the folder as the root and not look upward to the root of the greater web site for the bin folder and Web.config.

Palermo/Miller stuff

using System;
using System.Web.Mvc;
using ShockCaperShivers.Core;
using StructureMap;
namespace ShockCaperShivers.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         IClockRepository clockRepository = ObjectFactory.
               GetInstance<IClockRepository>();
         Clock clock = clockRepository.RetrieveClock();
         Hand hand = new Hand();
         hand.HandAtHand = "rock";
         hand.IpIdentity = "127.0.0.1";
         hand.TimestampIdentity = clock.CurrentTime;
         hand.UniqueIdentity = Guid.NewGuid();
         IHandRepository handRepository = ObjectFactory.GetInstance<IHandRepository>();
         handRepository.AddHand(hand);
         return View(hand);
      }
   }
}

 
 

What is happening in the code above? We are using ObjectFactory to come up with a Clock object, creating a Hand object, setting a bunch of getsetters on the Hand object including setting a DateTime value using the Clock object, and then handing the Hand object back to ObjectFactory. What is going to happen? I have a database table named Hand with columns for HandAtHand, IpIdentity, TimestampIdentity, and UniqueIdentity in it and a new row will be added to this database table. Why would I do this and why should you care? Alright, I have decided that I would like to know more about SignalR and to that end I have decided that I would like to build an AJAX-driven game of rock-paper-scissors in which one may play rock-paper-scissors online with the whole of humanity. If I can't get SignalR to work I'll just write the app using typical AJAX long polling. I envision each hand a player plays to correspond to a Hand object which will be saved to a Hand table at a database. I have set up, free of AJAX, the initial code for pushing a record into the database and I have done it faithful to the Onion Architecture one might associate with Jeffrey Palermo while using some of the open source tools one might associate with Jeremy Miller, namely StructureMap and also Fluent NHibernate. The image here shows the ASP.NET MVC 4 with Web API project (ShockCaperShivers) I am using to keep the Controller shown above and also two other projects (ShockCaperShivers.Core and ShockCaperShivers.Infrastructure) which I will explain in a moment. My original blog that I set up at Headspring has postings on this sort of thing here and here, but I've been out of Headspring for over two years now and the postings have fallen into disrepair in that their images became broken links. It's time to revamp! The rock-paper-scissors idea I have is the perfect excuse for a new blog posting and here it is! I hope you enjoy it.

using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using ShockCaperShivers.Core;
using ShockCaperShivers.Infrastructure;
using StructureMap;
namespace ShockCaperShivers
{
   public class WebApiApplication : System.Web.HttpApplication
   {
      protected void Application_Start()
      {
         ObjectFactory.Initialize(x =>
         {
            x.ForRequestedType<IClockRepository>
                  ().TheDefaultIsConcreteType<ClockRepository>();
            x.ForRequestedType<IHandRepository>
                  ().TheDefaultIsConcreteType<HandRepository>();
         });
         AreaRegistration.RegisterAllAreas();
         WebApiConfig.Register(GlobalConfiguration.Configuration);
         FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
         RouteConfig.RegisterRoutes(RouteTable.Routes);
         BundleConfig.RegisterBundles(BundleTable.Bundles);
      }
   }
}

 
 

Above is the Global.asax.cs for the ShockCaperShivers project. The only thing I added was the first line for ObjectFactory. This is needed to wire up StructureMap. StructureMap also needs a config file called StructureMap.config with its "Build Action" set to "Content" in the Properties pane and its "Copy to Output Directory" setting set to "Copy always" at the Properties pane. For me this file has the following XML in it:

<StructureMap>
   <PluginFamily Type="ShockCaperShivers.Core.IClockRepository"
         Assembly="ShockCaperShivers.Core" DefaultKey="Default">
      <Plugin Assembly="ShockCaperShivers.Infrastructure"
            Type="ShockCaperShivers.Infrastructure.ClockRepository"
            ConcreteKey="Default" />
   </PluginFamily>
   <PluginFamily Type="ShockCaperShivers.Core.IHandRepository"
         Assembly="ShockCaperShivers.Core" DefaultKey="Default">
      <Plugin Assembly="ShockCaperShivers.Infrastructure"
            Type="ShockCaperShivers.Infrastructure.HandRepository"
            ConcreteKey="Default" />
   </PluginFamily>
</StructureMap>

 
 

The associations above associate interfaces for repositories in the Core project with repository classes in the Infrastructure project. Both ShockCaperShivers.Core and ShockCaperShivers.Infrastructure are referenced by ShockCaperShivers so it, the user interface project, may act at bootstrapper and wire up these associations. The Infrastructure inherits from the Core only and the Core inherits nothing. The Core is going to hold the business logic free from external dependencies kept in the Infrastructure. In a three-layered approach the UI would inherit Core and Core would inherit Infrastructure, but in the Onion model the dependencies are injected into the Core against the flow of inheritance via StructureMap. This allows the logic in the core, free of external dependencies, to stay clean and be easy to test. By the way, if you think there should be a fourth project for tests, you're right. I'm just keeping it simple in this example. There are no more files that I wish to show off in the UI, but there are four files in the Core and four files in the Infrastructure that we should look at. Let's look at the Core first. Here is the Clock object class:

using System;
namespace ShockCaperShivers.Core
{
   public class Clock
   {
      public DateTime CurrentTime { get; set; }
      public Clock(DateTime time)
      {
         CurrentTime = time;
      }
   }
}

 
 

Here is the interface the Core will lean upon to get a new Clock:

namespace ShockCaperShivers.Core
{
   public interface IClockRepository
   {
      Clock RetrieveClock();
   }
}

 
 

Here is the Hand object:

using System;
namespace ShockCaperShivers.Core
{
   public class Hand
   {
      public virtual string HandAtHand { get; set; }
      public virtual Guid? HandOpposing { get; set; }
      public virtual string HandOutcome { get; set; }
      public virtual string IpIdentity { get; set; }
      public virtual DateTime TimestampIdentity { get; set; }
      public virtual Guid UniqueIdentity { get; set; }
   }
}

 
 

Here is the interface the Core will lean upon to push a Hand object to the Infrastructure project:

namespace ShockCaperShivers.Core
{
   public interface IHandRepository
   {
      void AddHand(Hand hand);
   }
}

 
 

The last four files were in the Core. The remaining four files are in the Infrastructure. The first one is the repository for the Clock interface. As you can now see all I am doing is wrapping DateTime.UtcNow in this repository and all the Clock object does is wrap DateTime.UtcNow. Why all this ceremony? The timekeeping is an external dependency. You do not want to sprinkle DateTime.UtcNow all over your code as it could be painful to replace with DateTime.Now or something else later on. This stuff (timekeeping) should really be driven from one locale in the Infrastructure.

using System;
using ShockCaperShivers.Core;
namespace ShockCaperShivers.Infrastructure
{
   public class ClockRepository : IClockRepository
   {
      public Clock RetrieveClock()
      {
         return new Clock(DateTime.UtcNow);
      }
   }
}

 
 

The next three files and also the last three files I'll show off, all have to do with the saving of Hand objects in the Infrastructure. The first one is a SQL script for creating the Hand table which serves no functional purpose in the application whatsoever. It is however a good idea to hang onto the SQL scripts that you use to craft SQL for your apps.

BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Hand
   (
   HandAtHand nvarchar(8) NOT NULL,
   HandOpposing uniqueidentifier NULL,
   HandOutcome varchar(255) NULL,
   IpIdentity nvarchar(28) NOT NULL,
   TimestampIdentity datetime NOT NULL,
   UniqueIdentity uniqueidentifier NOT NULL
   ) ON [PRIMARY]
GO
ALTER TABLE dbo.Hand ADD CONSTRAINT
   DF_Hand_IpIdentity DEFAULT (newid()) FOR IpIdentity
GO
ALTER TABLE dbo.Hand ADD CONSTRAINT
   PK_Hand PRIMARY KEY CLUSTERED
   (
   UniqueIdentity
   ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
ALTER TABLE dbo.Hand SET (LOCK_ESCALATION = TABLE)
GO
COMMIT

 
 

Our token table:

We need a map for each object we manipulate with Fluent NHibernate. Here is ours:

using ShockCaperShivers.Core;
using FluentNHibernate.Mapping;
namespace ShockCaperShivers.Infrastructure
{
   public class HandMap : ClassMap<Hand>
   {
      public HandMap()
      {
         Map(x => x.HandAtHand);
         Map(x => x.HandOpposing);
         Map(x => x.HandOutcome);
         Map(x => x.IpIdentity);
         Map(x => x.TimestampIdentity);
         Id(x => x.UniqueIdentity);
      }
   }
}

 
 

Finally here is our repository for Hand. I hope I have the using statements appropriate below to prevent the memory leak I experienced previously. "FluentNHibernateConnection" corresponds to an appSettings key in Web.config which holds a database connection string.

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();
               }
            }
         }
      }
      
      private static ISessionFactory CreateSessionFactory()
      {
         return Fluently.Configure().Database(MsSqlConfiguration.MsSql2005
               .ConnectionString(c => c.FromAppSetting("FluentNHibernateConnection")))
               .Mappings(m => m.FluentMappings.AddFromAssemblyOf<HandRepository>
               ()).BuildSessionFactory();
      }
   }
}

Tuesday, March 26, 2013

Event Viewer

Type "event viewer" at the start menu to see the logs for IIS. The logs here are akin to those seen for services. Navigate to: Event Viwer (Local) > Windows Logs > Application

net stop w3svc

...run at the command line stops everything (IIS and the AppPools) while this command starts it again:

net start w3svc

drill into a particular difference in a folder with Beyond Compare

  1. open Beyond Compare
  2. at the "Specs" tab enter values for "Left folder" and "Right folder"
  3. at the "Comparison" tab, check the checkbox for "Compare contents" and then the radio button for "CRC comparison" (CRC stands for Cyclic redundancy check and is a means for finding differences in files that are somewhat alike)
  4. click the "Open" button to see the files in the folders
  5. double-click any red file to do a comparison

Sunday, March 24, 2013

Encrypt and Decrypt in C#

This is more fun from C# 4.0 in a Nutshell. This test passes:

using System.IO;
using System.Security.Cryptography;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestProject
{
   [TestClass]
   public class EncryptionTest
   {
      [TestMethod]
      public void Test()
      {
         byte[] encrytionKey = new byte[16];
         encrytionKey[0] = 0;
         encrytionKey[1] = 255;
         encrytionKey[2] = 77;
         encrytionKey[3] = 42;
         encrytionKey[4] = 8;
         encrytionKey[5] = 88;
         encrytionKey[6] = 188;
         encrytionKey[7] = 205;
         encrytionKey[8] = 254;
         encrytionKey[9] = 38;
         encrytionKey[10] = 49;
         encrytionKey[11] = 213;
         encrytionKey[12] = 13;
         encrytionKey[13] = 89;
         encrytionKey[14] = 57;
         encrytionKey[15] = 67;
         
         byte[] initializationVector = new byte[16];
         initializationVector[0] = 123;
         initializationVector[1] = 18;
         initializationVector[2] = 9;
         initializationVector[3] = 1;
         initializationVector[4] = 8;
         initializationVector[5] = 176;
         initializationVector[6] = 190;
         initializationVector[7] = 167;
         initializationVector[8] = 4;
         initializationVector[9] = 12;
         initializationVector[10] = 54;
         initializationVector[11] = 222;
         initializationVector[12] = 13;
         initializationVector[13] = 98;
         initializationVector[14] = 98;
         initializationVector[15] = 103;
         
         string helloWorld = "Hello World";
         byte[] foo = Encoding.ASCII.GetBytes(helloWorld);
         byte[] bar;
         byte[] baz;
         using (SymmetricAlgorithm fooAlgorithm = Aes.Create())
         {
            using (ICryptoTransform fooEncryptor =
                  fooAlgorithm.CreateEncryptor(encrytionKey, initializationVector))
            {
               using (MemoryStream fooMemory = new MemoryStream())
               {
                  using (Stream fooStream = new CryptoStream(fooMemory, fooEncryptor,
                        CryptoStreamMode.Write))
                  {
                     fooStream.Write(foo, 0, foo.Length);
                  }
                  bar = fooMemory.ToArray();
               }
            }
         }
         Assert.AreEqual(ASCIIEncoding.ASCII.GetString(bar), "v>C??(?c?8@?'\t d");
         using (SymmetricAlgorithm barAlgorithm = Aes.Create())
         {
            using (ICryptoTransform barDecryptor =
                  barAlgorithm.CreateDecryptor(encrytionKey, initializationVector))
            {
               using (MemoryStream barMemory = new MemoryStream())
               {
                  using (Stream barStream = new CryptoStream(barMemory, barDecryptor,
                        CryptoStreamMode.Write))
                  {
                     barStream.Write(bar, 0, bar.Length);
                  }
                  baz = barMemory.ToArray();
               }
            }
         }
         Assert.AreEqual(ASCIIEncoding.ASCII.GetString(baz), "Hello World");
      }
   }
}

What defines a senior developer?

This is subjective. I consider myself a junior developer and I suspect I will always be, yet I've seen others use "senior" in their titles who… well, let's put it this way: I don't see why I can't slap that label on myself if they can. That would be using their measuring stick however and in using my own, I see myself as a junior developer. My definition for a senior developer:

  1. You can run a team.
  2. You can play architect.
  3. You can do the continuous integration stuff too.

 
 

I see three levels for developers:

  1. Senior
  2. Junior
  3. Noob/Layman

 
 

I think the notion of a midlevel developer is a euphemism. If you're "really good" but can't handle the senior role then you're really just a junior developer. When people speak of midlevel developers, those equate to junior developers in my model and when people speak of junior developers in contrast to midlevel developers, they are probably talking about individuals who need their hands held a lot. The "junior developers" in that model aren't far removed from laymen really, not in terms of what they bring to the table. If you are really a junior dev you should be competent enough to take away someone else's pain instead of adding to it by sucking up their time with questions. I'm giving some harsh subtext here about newbies, but I've also been there myself. I always hated it when my betters would roll their eyes at me instead of helping me. I seem to have somehow fought my way into the junior space from toolhooddom and on the other side of the journey I both understand the lack of patience and feel a strong desire not to similarly be impatient with someone who sincerely wants to learn and grow. Wow, I've really wandered off on a tangent...

Saturday, March 23, 2013

I wonder if there is a way to uninstall an Ektron min site without uninstalling Ektron itself.

When I botch a min site install by putting the files in the wrong folder or putting the assets in the wrong place, there doesn't seem to be a way to roll back the install. I've been uninstalling all of Ektron, deleting the stuff which is inappropriately placed, and then reinstalling everything to hack around the problem.

Addendum on 3/24/2013: Bill Cava of Ektron wrote me on Twitter with: @jaeschke having trouble commenting on that blog post - nutshell, use cmsuninstall.exe in utile folder in c program files\ektron\...

Compatibility View Settings in IE10

Tools > Compatibility View settings ...in Internet Explorer 10 will spawn the "Compatibility View Settings" dialog box where one may specify a list of domain names to view in an early version of Internet Explorer. I'm not sure what the version is, but I know I can now use the one site that I could not use in IE10.

generic cheat sheet on installing a Windows Service

How to install a Windows Service once you have an installer:
  1. You will need a user to run the service
    • Right-click on "My Computer" or the comparable icon and pick "Manage."
    • At the Computer Manager pane that appears.
    • Navigate to: Configuration > Local Users and Groups > Users
    • Add a user.
    • At: Configuration > Local Users and Groups > Groups ...right-click on the "Administrators" group and select "Add to Group..." from the menu which appears.
    • Add the new user here at the "Administrators Properties" window which pops up.
  2. Uninstall the same service if it exists in a botched form. (This can be just another part of getting the installation right.)
    • Stop the service.
    • Run the command prompt as an administrator, and yes, you must be an administrator.
    • Navigate to: C:\Windows\Microsoft.NET\Framework\v4.0.30319
    • Run: installutil /u C:\LocaleOfPublishedFiles\NameOfApplication.exe
  3. Install the service from an installer, this may mean pushing to a shared folder on another server. If you are using a local .wsdl (for SalesForce for example) you may need to beforehand update the "Web Reference URL" property at Visual Studio to point to the appropriate folder within the share folder as found from the root of the applicable drive.
  4. Once the files have been installed from the installer, the App.config will have, at the installation, a counterpart named something like NameOfApplication.exe.config. Do not assume that the settings in this file mirror those at the App.config. Somehow they may grow apart. Perhaps the installer caches these settings. You may need to update these settings.
  5. Once the files have been installed from the installer, they must ALSO be installed from the installutil tool:
    • Run the command prompt as an administrator, and yes, you must be an administrator.
    • Navigate to: C:\Windows\Microsoft.NET\Framework\v4.0.30319
    • Run: installutil C:\LocaleOfPublishedFiles\NameOfApplication.exe
  6. Type "component services" at the start menu to bring up the "Component Services" dialog box. Go to services and find your service.
    • Right-click on the service and pick "Properties" to specify the user who will use the service. A dialog box with four tabs will appear. Specify the user at the second tab dubbed "Log On."
    • Right-click on the service and pick "Start."
    • Console Root > Event Viewer (Local) > Windows Logs > Application ...should be navigated to within the "Component Services" dialog box. Herein, check the logs for progress and signs of health or a lack of health.

Friday, March 22, 2013

exec sp_helpdb

...is a pretty impressive blob of SQL to run at a server. It gives you a list of all databases for which the user running the command has access to and gives you "dbid" ids for each database which will allow you to filter against "DatabaseID" instead of "DatabaseName" here. When adding DatabaseIDs in the profiler, press the semicolon key to add a second (or third) line item.

local NuGet

NuGet repositories may be set up locally to manage team dependencies. This means that when you go to get Entity Framework, for example, that you by default get the version that your team uses instead of the newer, latest version. It also means you may check in your own libraries to NuGet and roll out new versions from one arm of a distributed to team to another. There is a config file to adjust (at each developer's copy of code) for getting a newer version in this circumstance.

Thursday, March 21, 2013

Three ways to scrape?

One: Scrape the Initial/Infant HTML by Code

using System.IO;
using System.Net;
using System.Text;
using System.Web.Mvc;
namespace Scraper.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         string url = "https://twitter.com/";
         HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
         StringBuilder scrappingSpool = new StringBuilder();
         using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
         {
            using (Stream stream = response.GetResponseStream())
            {
               int counter = 0;
               byte[] buffer = new byte[1000000];
               do
               {
                  counter = stream.Read(buffer, 0, buffer.Length);
                  if (counter != 0)
                  {
                     string chunk = Encoding.ASCII.GetString(buffer, 0, counter);
                     scrappingSpool.Append(chunk);
                  }
               } while (counter > 0);
            }
         }
         string scrapping = scrappingSpool.ToString();
         return View(scrapping);
      }
   }
}

 
 

Here the "scrapping" variable will end up with the immediate contents of https://twitter.com/ that one gets served up just by visiting the page. This begs the questions: "What if I want to log in at the Twitter site and make some content appear which only appears after the page loads by way of AJAX?" and "What if I want to scrape after that?" Well, I'm getting to that next. The C# above is a spruced up version of something I've had in my notes for a while:

Two: Scrape the Matured HTML by Firebug

  1. Get Firefox and install it.
  2. Install the Firebug plugin for Firefox.
  3. Restart Firefox and then visit https://twitter.com/.
  4. Log in.
  5. Scroll down on the page on the other side of the log in, forcing new HTML content for older tweets to appear by way of AJAX.
  6. Click on the Firebug icon at the upper right of Firefox. It will open a pane for Firebug.
  7. "Click an element in the page to inspect." should appear when you hover over the icon that looks like a rectangle with a pointer over it which is the second in from the left at the upper left of the Firebug pane. Click this icon.
  8. Move the mouse about the browser window. Try to highlight the div holding all of the tweets and then click on it.
  9. The appropriate line of code will be highlighted in the Firebug pane. Right-click on it and pick "Copy innerHTML."
  10. Copy into Notepad!

 
 

Three: Scrape the Matured HTML by Code

PhantomJS should be the key to the best of both of the worlds above. Have I used it yet? No I haven't. :(

installing a Windows Service

When installing a Windows Service remember to run the command shell as an administrator. Otherwise the install will "rollback."

To remove a Windows Service, just uninstall it at the control panel like any other application.

:P

Addendum: This may be really wrong and this may be better:

  • sc delete "Foo Bar"
  • sc delete FooBar

Second Addendum: This is really best.

Debug a Windows Service!

I find I am learning more and more about Windows Services and in doing so I have found the need to revisit the #if(!DEBUG) hat trick that I orginally read about in the book I've been reading (C# 4.0 in a Nutshell) but which I thought was too ghetto to take seriously. It turns out that you need to use it like so in testing a Windows Service which basically seems to be a console application which uses the ServiceBase type somewhere within.

#if(!DEBUG)
   ServiceBase[] ServicesToRun;
   ServicesToRun = new ServiceBase[] { new FooService() };
   ServiceBase.Run(ServicesToRun);
#else
   FooService myService = new FooService();
   myService.PublicMethodOnFooService();
#endif

 
 

If you fail to use this hack and you just try run the debugger you get this:

Cannot start service from the command line or a debugger. A Windows Service must be installed (using installutil.exe) and then started with the ServerExplorer, Windows Services Administrative tool or the NET START command.

Wednesday, March 20, 2013

define which user runs a Windows Service

You may create a user and make the user an administrator and then use the user to run a service. Right-click on the service at the "Component Services" pane and pick Properties. A dialog box with four tabs will appear. Go to the "Log On" tab and do what needs to be done. You will have to stop and then restart the service to make the change take effect. If the user is not an administrator you may get an error telling you that access is denied.

Addendum: You will need to add a user at Users beneath "Local Users and Groups" as mentioned here and then add the user to the Administrators group. You may right-click on the user, pick "Properties" and then go to the "Member Of" tab to do so.

learning more about Windows Services

The stuff leading up to PollProcess() as shown here is shown below:

using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
namespace FooStuff
{
   partial class FooService : ServiceBase
   {
      private Thread m_oPollingThread = null;
      
      public FooService()
      {
         InitializeComponent();
      }
      
      protected override void OnStart(string[] args)
      {
         eventLog1.WriteEntry("Foo service started");
         if (m_oPollingThread == null)
               m_oPollingThread = new Thread(new ThreadStart(PollProcess));
         m_oPollingThread.Start();
      }
      
      protected override void OnStop()
      {
         eventLog1.WriteEntry("Foo service is stopping.");
         m_oPollingThread.Abort();
      }
      
      private void PollProcess()
      {

 
 

We are using that corny, confusing Designer.cs antipattern and here is what is in the designer:

namespace FooStuff
{
   partial class FooService
   {
      private System.ComponentModel.IContainer components = null;
      
      protected override void Dispose(bool disposing)
      {
         if (disposing && (components != null))
         {
            components.Dispose();
         }
         base.Dispose(disposing);
      }
      
      private void InitializeComponent()
      {
         this.eventLog1 = new System.Diagnostics.EventLog();
         ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit();
         this.eventLog1.Log = "Application";
         this.eventLog1.Source = "Foo";
         this.ServiceName = "FooService";
         ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();
      }
      
      private System.Diagnostics.EventLog eventLog1;
   }
}

 
 

I don't really understand the ServiceBase base class yet as of this writing. I am running this service at a server. I installed it will an installer. When I type "services" at the start menu at that server, I get the "Component Services" dialog box. At the left, I can expand "Event Viewer (Local)" and then "Windows Logs" beneath it and then click on "Application" to browse a list of errors for the service.

Is this good code for polling from a Windows Service via C#? :P

private void PollProcess()
{
   do
   {
      PollingPass();
      int Sleep = (Convert.ToInt32(Settings.MailPoll)) * 60000;
      Thread.Sleep(Sleep);
   }
   while (1 == 1);
}

ScriptBundle paths

A ScriptBundle in BundleConfig.cs seems to need to end like so:

bundles.Add(new ScriptBundle("~/bundles/signalr").Include(
   "~/Scripts/jquery.signalR-1.0.1*"));

 
 

...with an ASTERISK or perhaps with {version}.js as I had trouble pointing one of these directly to a .min.js file. Whatever.

Tuesday, March 19, 2013

Layout = null

The following Razor markup in MVC4 ensures a view will not use _Layout.cshtml as a master page.

@{
   Layout = null;
}

BundleConfig.cs

...in the App_Start folder in an ASP.NET MVC 4 project determines how this sort of thing renders in a view:

  1. @Styles.Render("~/Content/css")
  2. @Scripts.Render("~/bundles/modernizr")
  3. @Scripts.Render("~/bundles/jquery")

Change backgrounds at Windows 8.

  1. Charm Bar > Settings > Change PC Settings ...is where one changes many of the background in Windows 8.
  2. Right-clicking on the desktop and picking "Personalize" followed by "Desktop Background" at the dialog box which appears is still the spot for changing the background on the desktop.

a better SQL example on output parameters, transactions, and selecting TOP 1

USE [Foo]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_IMS_GetNextAutoNumberAvailable]
   @NextAutoNbr int = 0 OUTPUT
AS
BEGIN TRANSACTION incrementSA
   DECLARE @NextIncrement int
   Select @NextIncrement = (SELECT TOP 1 SettingIntValue FROM Settings WHERE
         SettingName = 'SA')
   SET @NextIncrement = @NextIncrement + 1
   UPDATE Settings SET SettingIntValue = @NextIncrement WHERE SettingName = 'SA'
   SET @NextAutoNbr = @NextIncrement
COMMIT TRANSACTION incrementSA

vocal again

As before, I again decided to be vocal again today. I am finding it harder and harder to be brave. We are maybe going to have to push back on a deadline. If we do we need to explain why we are doing so and how long it will really take to be ready to deliver. We can't have an estimate unless we shift gears from fighting fires and focus on testing that which has not yet been tested to know if the untested is also going to need love and thus require time.

Monday, March 18, 2013

the RenderSection trick

The RenderSection Razor trick seems kind of hacky. Per this one would do a declaration like this in _Layout.cshtml (the master page):

@RenderSection("SideBar", required: false)

 
 

You may then write contents for the Section anywhere in a view using the master page:

@section SideBar {
   <p>foo</p>
}

 
 

Where the section will end up rendering in the HTML will be driven by where the section is defined in the master page and not the inheriting view!

MSSQL jobs may be migrated from one server to another.

  1. At the server you will migrate FROM, open the "Object Explorer" and the "Object Explorer Details" from the "View" menu in Microsoft SQL Server Management Studio.
  2. In the "Object Explorer" click on "Jobs" beneath "SQL Server Agent" which will display a list of jobs in the "Object Explorer Details" pane.
  3. Select all the jobs and then right-click on the selection.
  4. pick: Script job as > CREATE To > File ...
  5. After saving out the SQL to create the server's jobs, run the SQL script at the server you wish to migrate to in Microsoft SQL Server Management Studio.
  6. Make a list of jobs on the new server in SSMS as before and right-click on each job and pick "Properties" to bring up the "Job Properties" pane.
  7. At the upper left there will be a "Schedules" option. Use this to adjust the schedule for each job.
  8. There is an option here for "Notifications" too. One may specify here that a the server emails an operator "When the job fails" (and one may create the operators at "Operators" beneath "SQL Server Agent" in the "Object Explorer").

see services

If typing "services" at the start menu does not bring up the "Component Services" dialog box (allowing you to see the Windows Services running at a given machine) you can try typing "tasklist /svc" at a command prompt.

Immediate Window in Visual Studio 2012

Debug > Windows > Immediate ...is where one opens the Immediate Window which is fun for debugging!

  • ? foo followed by a return in this window will show you the value for the variable "foo"
  • foo = "bar" followed by a return in this window will allow you to hijack a variable and reassign its value

test-ipv6.com is the new ipchicken?

See:
  1. http://www.ipchicken.com/
  2. http://test-ipv6.com/

Sunday, March 17, 2013

No persister for:

A Fluent NHibernate error which starts out with "No persister for:" means that your map is messed up. In my case I was just leaving off the public keyword.

Saturday, March 16, 2013

Install and open IIS8 Express in/at Windows 8.

  1. open the Control Panel
  2. go to "Programs and Features"
  3. click on "Turn Windows features on or off" which takes you to "Windows Features" (I have gotten confused trying to find "Windows Features" before.)
  4. under "Internet Information Services," in addition to checking the checkboxes under "World Wide Web Services," remember to go into "Web Management Tools" and check all the checkboxes save for the "IIS 6 Management Compatibility" checkbox (I keep forgetting to do this step and without it there is no frontend interface for IIS.)
  5. to then get to the frontend interface for IIS, right-click on the computer icon at the desktop and pick "Manage" which will bring up the "Computer Management" dialog box letting you will find "Internet Information Services (IIS) Manager" under "Services and Applications"

Show the computer icon at the desktop in Windows 8.

  1. Right click in the desktop and pick Personalize
  2. Click "Change desktop icons" at the upper left of the Personalization pane which appears

correction on .wmv recreation

This may not be so good. Every movie I've yet made has ended up being sickly.

Friday, March 15, 2013

scroll through a .wmv

At http://www.videohelp.com/download/WMEncoder.exe download Windows Media Encoder and install it. This tool will let you convert a .wmv file to another .wmv file. Why would you want to do so? If you record a .wmv with Lync you cannot scroll through it in Windows Media Player! This is a way to hack around the problem!

Set Next Statement

When debugging in Visual Studio 2010 or Visual Studio 2012, right-click and pick "Set Next Statement" to set the "playback head" at the line of code where you are clicking. You may then move forward from that point with F5, F10, or F11 as per the norm.

You may create users from logins at SSMS.

Go to "Logins" beneath "Security" in Microsoft SQL Server Management Studio and double-click a particular login to open the "Login Properties" dialog box. Go to the "User Mapping" option at the upper left. This will show a list of your databases with checkboxes by them. Those databases with checked checkboxes have users for the Login. Checking a checkbox creates a user for the login at the database.

more on sending mail via SQL

Something missing from this is permissions. Grant EXECUTE and also double-click on the user in SSMS to add database role memberships. Good memberships to hold are:

  1. db_accessadmin
  2. db_backupoperator
  3. db_datareader
  4. db_datawriter
  5. db_ddladmin
  6. db_owner
  7. db_securityadmin

Thursday, March 14, 2013

msdb.dbo.sp_send_dbmail

to get this to work...

  1. In SSMS at: Databases > System Databases > msdb ...you must add the same user that you will use to connect to your database to call the SQL
  2. In SSMS at: Management > Database Mail ...right click and pick "Configure Database Mail" to prep the SMTP and the profile to be used as seen here:
    set @Foo = ERROR_MESSAGE();
    SET @Bar = 'Something went wrong.'
    EXEC msdb.dbo.sp_send_dbmail
       @profile_name='CustomerService'
       ,@recipients='tomjaeschke@tomjaeschke.com'
       ,@subject = @Bar
       ,@body = @EFoo
       ,@body_format = 'HTML'

Wednesday, March 13, 2013

Azure and Android

I this evening saw Ryan Joy present on "Azure Mobile Services For Android Developers" which I am going to consider part of the South by Southwest activities given how Ryan advertises it here. This means I did something for SXSW this year for a change. The event was technically at some regularly occurring event (an Android user group) at Capital Factory which is a business which sits at the 16th Floor of the Omni hotel in Austin, Texas in the downtown. Casey Watson mentioned data storage at Azure in his talk and Ryan Joy suggested that one may push and pull from tables, blobs, and queues. If you push to an Azure queue from an app you could use a worker role on the Azure side to audit it for changes and then react. Ryan suggests one may wish to use an OAuth-style service as that of Facebook, Twitter, Google, or GitHub (no turnkey authentication yet for GitHub, it will take some craftsmanship for authentication credentials keeping) and then use the token for your identifier at tables/blobs/queues at Azure! This is a good way to manage logging in and user data. Restful APIs allow you to do everything in Azure. SDKs for Android and iOS use Node.js to speak to the API like so:

mssql.query('select top 1 * from foo',
   {success: function(results) {
      console.log(results);
   }
);

 
 

You don't need the Node.js stuff if you are just interfacing with Azure via JavaScript in a plain jane web site. It is a solution in the mobile tie-ins. Our city is bustling downtown for SXSW. Most of the interactive stuff ended yesterday and I think music and film is next up. I normally crave the regular free geek talks that happen about Austin more so than this annual event, but whatever. I guess tonight's thing straddled the line between the two. The view here is from the roof of the Omni.

Twitter Bootstrap

Twitter Bootstrap is yet another UI framework. At a glance, it contains a grid.

Ektron min site

"Min" sites should be set up for the proper local site. "Min" stands for minimum and a minimum Ektron site is a base install. From the base install the rest of the site should be flesh-outable by being fed from the "local" (master) site via eSync. Set bindings and the application pool for the min site in IIS. Install a min site from the Ektron installer and change its default connection strings as needed.

Tuesday, March 12, 2013

Tuning SQL Server Profiler

This touches on a way to constain SQL Server Profiler to only crawl one database at the server you connect to. Here is how:

  1. Type "SQL Profiler" at the start menu to bring up SQL Server Profiler.
  2. Pick "New Trace..." from the "File" menu. You will be prompted to make a connection to your database. Do so.
  3. At the "General" tab at the "Trace Properties" dialog box set the "Use the template:" dropdown to "Tuning."
  4. Go to the "Event Selection" tab and click the "Column Filters..." button at the lower right.
  5. Click on "DatabaseName" at the "Edit Filter" dialog box which appears.
  6. Expand "Like" and type in the name of your database in the spot for entering a Like filter which appears.
  7. Click the "OK" button in the "Edit Filter" dialog box and then the "Run" button in the "Trace Properties" dialog box.

polymorphism and abstract methods

The abstract methods are in fact a lot like the method signature definitions in an interface. They do not return anything in and of themselves and they require the inheriting subtypes to implement a comparable method signature. You have to address their neediness from a child with the override keyword as you would for a virtual method, but where a virtual method does not require overriding, an abstract method cannot be left without an overriding implementation in all subtypes inheriting from the abstract parent class containing the abstract method. Only abstract classes may have abstract methods. Clearly you may also put regular methods into abstract classes and thus the abstract classes vary from interfaces with this capacity for complication/complexity. Abstract classes are good candidates for middle rungs in an inheritance ladder in which an interface is a grandparent and a regular class is a grandchild in that they will allow for managing logic common to all grandchildren for which they are a parent. I saw John Teague speak at the Austin .NET User Group last night. Of all of the presentations I have seen at ADNUG, this one was probably the very best. It was basically on polymorphism, but went off on some other pretty interesting tangents too, such as abstract classes for example, and it was clarified that encapsulation is not merely the use of private methods, it is of trying to hide internal state, contrary to my prior understanding. Yes, that means private method implementations a lot of the time too, but thinking only in terms of the implementation is shortsighted. (An object's external state should be inaccessible to outsiders.) Prior to this evening, I understood polymorphism to be of situations in which two or more methods had the same name but different signatures where John instead offered: "Polymorphism lets you define different behavior for subtypes, while keeping a consistent contract." The shape this takes is often one in which two method signatures of the same name consume two different subtypes of a common parent, but, as with the poor interpretation of encapsulation, a focus on the implementation can blind one to the underlying goal of polymorphism. In the example below, one method signature takes different subtypes which are upcast to a parent. This too is polymorphism. The subtypes drive the shape-changing. John offered some code not unlike the code he also mentioned at Jimmy Bogard's blog on enumeration classes and not unlike the code I imagine Chris Missal writing when he tweets: "I can't remember the last time I saw a good excuse to use a 'switch' in C#. Ever since LINQ, these have been absent in my code." I imagine Chris' code to have where T contracts and list filtering based on type like this:

public IList<T> GetPersons<T>() where T : Person
{
   return persons.OfType<T>().ToList();
}

 
 

The method above could be used to go fishing in the collection called persons of Person exclusively for a subtype called Teacher for example. This example and the ones given at Jimmy's blog posting and by John last night show ways to refactor away switch statements which may be painful to consistently revisit for revisions. Consider:

Bad

Better

namespace App.Stuff
{
   public enum Taste
   {
      Sweet,
      Sour,
      Salty,
      Bitter
   }
}

 

namespace App.Stuff
{
   public class Food
   {
      public Taste Variety { get; set; }
   }
}

namespace App.Stuff
{
   public interface Food
   {
      int ToothDecay();
   }
}

namespace App.Stuff
{
   public class Gar
   {
      public int Teeth { get; set; }
      public Gar() { Teeth = 100; }
      public void Eat(Food food)
      {
         switch (food.Variety)
         {
            case Taste.Sweet:
               Teeth = Teeth - 10;
               break;
            case Taste.Sour:
               Teeth = Teeth - 2;
               break;
            case Taste.Bitter:
               Teeth = Teeth - 1;
               break;
         }
      }
   }
}

namespace App.Stuff
{
   public class Gar
   {
      public int Teeth { get; set; }
      public Gar() { Teeth = 100; }
      public void Eat(Food food)
      {
         Teeth = Teeth - food.ToothDecay();
      }
   }
}

 

namespace App.Stuff
{
   public class SweetFood : Food
   {
      public int ToothDecay()
      {
         return 10;
      }
   }
}

 

namespace App.Stuff
{
   public class SourFood : Food
   {
      public int ToothDecay()
      {
         return 2;
      }
   }
}

 

namespace App.Stuff
{
   public class SaltyFood : Food
   {
      public int ToothDecay()
      {
         return 0;
      }
   }
}

 

namespace App.Stuff
{
   public class BitterFood : Food
   {
      public int ToothDecay()
      {
         return 1;
      }
   }
}

In the above left the enum/switch will ultimately lend itself to refactorings which break the Open Closed Principal paradigm. When you add pungent and astringent you have to change the enum and the switch. This is not so with the code on the right! Other things I learned were:

  1. John Teague suggested that polymorphism could be done, either with generics or subtype inheritance stuff as seen above. Honestly, this is in conflict with what I said above about different method signatures. I guess my prior understanding was weak.
  2. The Liskov Substitution Principle demands that one be able to "treat" all subtypes as the base type as shown above.
  3. Order.LineItems.Count is an ambiguous puzzle with regards to The Law of Demeter which suggests that the "two dot rule" may reveal a code smell. If an Order does not necessarily have LineItems and the Count property may thus reveal if LineItems exist, then the Count may be of Order and not LineItems and hence not a violation. Otherwise the two dots reveal a violation.
  4. The Factory and Template patterns were discussed some as variations on the above. The factory way breaks with OCP to allow a case/switch to dole out particular subtypes and serves as a chokepoint so that only the factory is asked for subtypes.
  5. I learned about abstract classes last night.
    namespace App.Stuff
    {
       public abstract class Fish
       {
          public abstract int Bite();
       }
    }
     
    namespace App.Stuff
    {
       public class Gar : Fish
       {
          public override int Bite()
          {
             int teeth = 100;
             return teeth;
          }
       }
    }

     
     
    This should look to you a lot like an interface inheritance implementation.
    namespace App.Stuff
    {
       public interface Fish
       {
          int Bite();
       }
    }
     
    namespace App.Stuff
    {
       public class Gar : Fish
       {
          public int Bite()
          {
             int teeth = 100;
             return teeth;
          }
       }
    }