Sunday, January 31, 2016

Look into the future!

I saw Peter Myers give a talk called "Introduction to Time Series Forecasting" at this year's SQL Saturday yesterday, and it had to do with using existing business intelligence data broken down across recorded time increments (for example ice cream sales, chocolate versus strawberry, per maybe calendar week which is close to his example if memory serves) to then extrapolate what comes next. If I am the ice cream vendor and I have years of weekly data and I want to know what sales will likely be like next week, one week into the future, I should be able to do that, right? Yes, your history may predict BI data points in a chronological order sense using the "Microsoft Time Series Algorithm" which is a feature of Microsoft Analysis Services, and, yes, you have to have Microsoft Analysis Services. Some things about this of note:

  • This has sort of been around since SQL Server 2005 starting with a different algorithm called ARTXP, but as of SQL Server 2008 a second algorithm called ARIMA has been spliced in with ARTXP to create the Microsoft Time Series Algorithm. You may configure the algorithm to only use ARTXP or to only use ARIMA and a concept called prediction smoothing will furthermore let you mix a little more or a little less ARTXP with your ARIMA. This suggests that ARTXP is more for the immediacy while ARIMA is for the far future. That is the distinction. Keep in mind that predictions are just predictions, so if you can game the likelihood of their credibility you will have incentive to do so. You can mess with prediction smoothing until you have the outcome you want not unlike channel surfing between CNBC and Fox News more or less to one than the other to see the world as you want to see it.
  • Specificity decays the farther you walk out into the future. The first projected period is just based on existing data, but the second will use the projected first, and so on. The Jenga game gets progressively less stable as fingers-crossed hopefulness gets optimistically stacked on top of more fingers-crossed hopefulness.
  • Supposedly there is a way to make a new "multidimensional" project in Visual Studio which cross talks to Microsoft Analysis Services and allows for "visualizations" which may then be drug into ASP.NET apps!
  • SSDT stands for SQL Server Data Tools and DMX stands for Data Mining Extensions. These may get mixed in somehow.

I saw Jennifer McCown speak on stored procedures in a different talk right before this one and there was only one thing said that was new and it ties into this subject matter so I will just mention it here in lieu of giving it its own blog posting. She suggested that if you are recording snapshot data off to a database daily (or on some other time-based interval) that you should NOT just skip a day when Tuesday's data looks just like Monday's data. How do you really know after the fact that the skipped time period represents a carryover of the old data and not a day when your ETL just failed to run?

Friday, January 29, 2016

Paul Allen is the co-founder of Microsoft.

He's that other guy who started Microsoft who is not Bill Gates. At some point he bowed out and let Gates have it. I can never remember his name. Supposedly he was the nice one of the two.

You may alter a not null varchar column in T-SQL to expand its capacity so to speak.

varchar(128) may easily become varchar(max) like so:

ALTER TABLE Foo ALTER COLUMN Bar VARCHAR(MAX) NOT NULL

Double quotes go inside of single quotes in T-SQL when making an assignment, not the other way around.

It's messing with my mind.

Drop stuff out of the cache in C#.

System.Web.HttpContext.Current.Cache.Remove("bytes");

Otherwise you may put stuff to and from Cache as you would Session with the square brackets and do null checks the same way. At an .ashx you may get .Cache off of the context.

How may I access Session at an .ashx in C#?

Inherit from System.Web.SessionState.IRequiresSessionState and not just (System.Web.IHttpHandler) and then you may get at .Session off of the HttpContext defined at the ProcessRequest signature.

Get an image back from a bytes array at an .ashx in C#!

context.Response.ContentType = "image/png";
context.Response.BinaryWrite(myBytes);

Fish out a url line variable at an .ashx in C#!

using System.Web;
namespace Whatever
{
   public class Logo : IHttpHandler
   {
      public void ProcessRequest(HttpContext context)
      {
         string urlParameter = context.Request.QueryString["id"];

Visual Studio Test Professional with MSDN?

There is a kids table version of MSDN just for the testers!

Convert.ToBase64String

Do this to a bytes array in C# when tucking an image into a varchar(max) column in a database. When pulling the gunk back out, convert it (column from SqlDataReader) to a string first and then wrap all of that in a Convert.ToBase64String and make an assignment from that.

Thursday, January 28, 2016

I actually engineered something today!

In a web forms application there is a form for configuring an email template. The template may include a client logo which you may upload. It would be nice if you could preview it before posting the form and naturally there is no way to slurp the bytes out of a file type input field with AJAX really so how could I get at the file to preview itself before submitting the greater form? The file upload field went into separate web form which got looped in via an iFrame. The code behind looked like this:

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using DevExpress.Web.ASPxUploadControl;
using MyExternalDependency;
namespace Whatever
{
   public partial class IFrameForLogo : System.Web.UI.Page
   {
      public string ButtonName;
      public int Height;
      public int Width;
      
      protected void Page_Load(object sender, EventArgs e)
      {
         User user = (User)Session["User"];
         Group group = user.Group;
         if (group.GroupID.ToString() != GroupId.Value)
         {
            GroupId.Value = group.GroupID.ToString();
            GetSizeAndMaybeResize(group.Logo);
         }
         var isExistingImage = group.Logo != null && group.Logo.Length > 0;
         StagePage(isExistingImage);
      }
      
      protected void EmailUploadControl_FileUploadComplete(object send,
            FileUploadCompleteEventArgs e)
      {
         var bytes = GetSizeAndMaybeResize(e.UploadedFile.FileBytes);
         var isExistingImage = bytes != null && bytes.Length > 0;
         StagePage(isExistingImage);
      }
      
      private void StagePage(bool isExistingImage)
      {
         if (isExistingImage)
         {
            ButtonName = "Change";
            ControlBox.Attributes.Remove("style");
            ControlBox.Attributes.Add("style", "width: 70px; padding-left: " + (288-Width) +
            "px;");
            ImageBox.Visible = true;
            ImageBox.Attributes.Add("style", "width: " + Width + "px; height: " + Height +
                  "px; margin-top: " + (80-Height) + "px; background-color: #EE3224;
                  background-image:url('Logo.ashx?id=" + GroupId.Value + "');");
         }
         else
         {
            ButtonName = "Upload Logo";
            ControlBox.Attributes.Remove("style");
            ControlBox.Attributes.Add("style", "width: 358px;");
            ImageBox.Visible = false;
         }
      }
      
      private byte[] CastImageToByteArray(Image image)
      {
         using(MemoryStream memoryStream = new MemoryStream())
         {
            image.Save(memoryStream, ImageFormat.Png);
            return memoryStream.ToArray();
         }
      }
      
      private Byte[] GetSizeAndMaybeResize(byte[] bytes)
      {
         var shrunken = new byte[0];
         if (bytes != null && bytes.Length > 0)
         {
            Session["bytes" + GroupId.Value] = bytes;
            using (var memoryStream = new MemoryStream(bytes))
            {
               var image = Image.FromStream(memoryStream);
               Height = image.Height;
               Width = image.Width;
               if (Height > 80)
               {
                  var ratio = (float)Width/(float)Height;
                  int difference = Height - 80;
                  Height = 80;
                  Width = Width - (int)(difference*ratio);
                  if (image.Height != Height && image.Width != Width)
                  {
                     Bitmap bitmap = new Bitmap(Width, Height);
                     using (Graphics shrinker = Graphics.FromImage((Image) bitmap))
                     {
                        shrinker.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        shrinker.DrawImage(image, 0, 0, Width, Height);
                     }
                     shrunken = CastImageToByteArray(bitmap);
                     Session["bytes" + GroupId.Value] = shrunken;
                  }
               }
            }
            if (shrunken.Length > 0)
            {
               if (Width > 200)
               {
                  using (var memoryStream = new MemoryStream(bytes))
                  {
                     var image = Image.FromStream(memoryStream);
                     Height = image.Height;
                     Width = image.Width;
                     var ratio = (float) Height/(float) Width;
                     int difference = Width - 200;
                     Width = 200;
                     Height = Height - (int) (difference*ratio);
                     if (image.Height != Height && image.Width != Width)
                     {
                        Bitmap bitmap = new Bitmap(Width, Height);
                        using (Graphics shrinker = Graphics.FromImage((Image) bitmap))
                        {
                           shrinker.InterpolationMode = InterpolationMode.HighQualityBicubic;
                           shrinker.DrawImage(image, 0, 0, Width, Height);
                        }
                        shrunken = CastImageToByteArray(bitmap);
                        Session["bytes" + GroupId.Value] = shrunken;
                     }
                  }
               }
               bytes = shrunken;
            }
            else
            {
               using (var memoryStream = new MemoryStream(bytes))
               {
                  var image = Image.FromStream(memoryStream);
                  Bitmap bitmap = new Bitmap(Width, Height);
                  using (Graphics shrinker = Graphics.FromImage((Image) bitmap))
                  {
                     shrinker.InterpolationMode = InterpolationMode.HighQualityBicubic;
                     shrinker.DrawImage(image, 0, 0, Width, Height);
                  }
                  var recast = CastImageToByteArray(bitmap);
                  Session["bytes" + GroupId.Value] = recast;
               }
            }
         }
         else
         {
            Height = 0;
            Width = 0;
         }
         return bytes;
      }
   }
}

 
 

The actual web form looks like this. I end up using a DevExpress ASPxUploadControl instead of the file type input so that I may restrict what types of files are acceptable (though that doesn't work in old IE and I still need a sanity check in jQuery nonetheless).

<%@ Page Language="C#" AutoEventWireup="true"
      CodeBehind="IFrameForLogo.aspx.cs" Inherits="Whatever.IFrameForLogo" %>
<%@ Register TagPrefix="dx" Namespace="DevExpress.Web.ASPxUploadControl"
      Assembly="DevExpress.Web.v13.1, Version=13.1.9.0, Culture=neutral,
      PublicKeyToken=b88d1754d700e49a" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
   <head runat="server">
      <title>Whatever</title>
      <script src="js/jquery-1.3.2.min.js"></script>
      <style type="text/css" media="all">
         body {
            margin: 0;
            padding: 0;
         }
         #bottom {
            position: absolute;
            margin-left: -9999px;
            width: 200px;
            height: 200px;
         }
         form {
            margin: 0;
            padding: 0;
         }
         .left {
            float: left;
            height: 20px;
            margin-top: 55px;
         }
         .left button {
            margin: 0;
         }
         .right {
            float: right;
         }
         .top {
            position: absolute;
            margin-top: 35px;
            margin-left: 0;
            left: 0;
            color: #333333;
            font-family: Arial;
            font-size: 10pt;
            font-weight: bold;
            height: 20px;
            width: 358px;
         }
         #wrapper {
            margin: 0;
            padding: 0;
            height: 80px;
            width: 358px;
            background-color: #FFFFFF;
         }
      </style>
   </head>
   <body>
      <form id="wrapperform" ClientIDMode="Static" runat="server">
         <div id="wrapper">
            <div class="top">Email Template</div>
            <div class="left" id="ControlBox" runat="server">
               <button id="button" type="button"><%=ButtonName %></button>
            </div>
            <div class="right" id="ImageBox" runat="server" Visible="false"></div>
            <div id="bottom">
               <dx:ASPxUploadControl id="EmailUploadControl" runat="server"
                     ClientIDMode="Static"
                     OnFileUploadComplete="EmailUploadControl_FileUploadComplete">
                  <ValidationSettings AllowedFileExtensions=".gif,.jpg,.png"
                        NotAllowedFileExtensionErrorText="Use a .gif, a .jpg, or a .png!"/>
                  <ClientSideEvents TextChanged="function(s,e){UploadLogo(s,e);}">
                  </ClientSideEvents>
               </dx:ASPxUploadControl>
            </div>
         </div>
         <asp:HiddenField runat="server" id="GroupId" value="0"/>
      </form>
      <script type="text/javascript">
         var clicking = false;
         $(function () {
            $("#button").bind('click', function () {
               var counter = 0;
               $('#bottom input').each(function () {
                  console.log(this);
                  if (counter === 3) {
                     $(this).click();
                  }
                  var readonly = $(this).attr("readonly");
                  if (counter != 3 || !readonly) {
                     counter++;
                  }
               });
            });
         });
         function UploadLogo(s,e) {
            $('#EmailUploadControl_TextBox0').each(function () {
               var title = $(this).attr("title");
               var extension = title.toLowerCase().substring(title.length - 4, title.length);
               if (extension === ".gif" || extension === ".jpg" || extension === ".png") {
                  $('#wrapperform').submit();
               }
            });
         };
      </script>
   </body>
</html>

 
 

Interesting things:

  • I sanity check the size of images and resize them if need be in the code behind and also each image gets cast to a .png for convenience.
  • Note that I hide the ASPxUploadControl and have a button to click on to click on it "under the hood" when I do I have to find a specific item in a set of items that DevExpress renders out. It's usually the third item, but in the case of IE it's the fourth!

 
 

Addendum 2/1/2016: A lot of this needs love. I am trying to put stuff into Session not yet saved, but when I send test emails the emails cannot pull stuff out of Session. I'm going to need a temp data table. Also my hacky way of finding the ASPxUploadControl blows. There is a way in DevExpress to just make that control look like a button. This might have it. I'm not sure yet. Also I forgot to mention earlier that I'd like you to note that I am forcing the form in this web form to submit with JavaScript whenever the ASPxUploadControl is "touched."

 
 

Addendum 2/2/2016: This suggests the following better way to emulate a click on an ASPxUploadControl.

document.getElementById("EmailUploadControl_TextBoxT_Input").click();

 
 

Addendum 2/3/2016: The thing I suggest immediately above really won't work because the file never gets uploaded that way. I'll try to find another way. Wait! I found it! It turns out that TextBoxT just needs to become TextBox0 for this to work.

Wednesday, January 27, 2016

Pair programming may be called peer programming.

The flub is legit.

Make the file type input controls in HTML show only a button and not an adjacent field or copy reading "No file selected."

I fought with this some yesterday. If you use CSS to make the control exactly ninety pixels wide you will end up with something that more or less just shows the button in IE, Firefox, Chrome, and Safari. I did not test with other browsers. However, in IE there is an ever-so-tiny "form field" clinging to the left of the button, and in Firefox you see the N of "No file selected." The Firefox problem may be sidestepped by setting the color in CSS to be the background color of piece of the page the control sits on top of. This will make the N invisible more or less. However, this is all still hacky as hell. I found this this morning which suggests you should just slap display:none; as a style on the control and show a button which forces a click on the control with jQuery when a user in turn clicks the button. I haven't tried that. I'm giving up on the file type input to use the sister control that DevExpress offers which should let me restrict what file types are handed in. This suggests as much is going to take some jumping through flaming hoops with a regular file type input control.

Tuesday, January 26, 2016

When the images you open or new up do not appear at all in Adobe Photoshop...

Well, a restart of my computer fixed the issue for me.

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.

This has to do with Response.Redirect and this suggests you should specify that second parameter in a Response.Redirect as false (it's true by default) to beat this problem. I have not myself tried it.

Monday, January 25, 2016

How may I make only the selected radio button have an id so that I may catch it with Request.Form["whatever"] in web forms?

$('input[type=radio]').bind("focus", function () {
   $('input[type=radio]').each(function (item) {
      $(this).removeAttr("id");
   });
   $(this).attr("id", "whatever");
});

TPL is Task Parallel Library

It helps with parallelism.

Dapper

It's a "simple object mapper for .NET" per this.

ADO dot NET

ADO.NET is the whole realm of interacting with the database from C# with sprocs pulling gunk into datasets and the like as opposed to using an ORM. There is some very specific syntax associated with this shape of things... SqlConnection and the like...

a sql_variant column in T-SQL

You may shove int, binary, and char values into such a column!

asterisk equals in JavaScript

var x = 13;
x *= 3;
alert(x);

 
 

The alert will have a 39 in it. Basically, we suggest this instruction: Assign to the left the left multiplied by the right. So we assign into the variable holding 13 the product of 13 and 3. There is also a minus equals and I bet you can guess what that does. If you need it spelled out to you this has a more idiotproof explanation.

Lisp

Here is another scripting language that I don't want to know anything about: Lisp

Sunday, January 24, 2016

Ransomware

As a term, this refers to malware which locks you out of your own stuff. In order for the name to make sense, you will be held ransom. Someone will expect a payment in the name of unlocking you.

Saturday, January 23, 2016

The Charlize Theron movie "Young Adult" has inspired me to write a book.

This film came out in 2011 and while it wasn't exactly inspirational insofar that it changed my life or nuthin' it did inspire me. I found my mind circling back to the ending for some time after I saw the film, and eventually I scratched the itch I had. In this movie Charlize Theron plays a thirty-something who writes easy-to-read, fluffy, teen fiction books which are crap in terms of literature. Her pen has been playing her bills and she lives in some big, modern city somewhere. She is professionally successful even if otherwise restlessly dissatisfied...

...but I'm wandering off topic as that really doesn't have anything to do with what I have to say. Anyhow, eventually our hero visits the tiny little town she is originally from and at the end of the film one of the little people from the little town tells her that she should feel really good about her work as no one else from that little town could have written a book! I thought about it and realized that I could write a hundred page crap novel that's less-than-Steinbeck, and then I could say that I've written a book. It's done as of today. Well, at least I have a first pass done. If you find a typ0 in it I won't be surprised. It's not Steinbeck. It's a rip-off of ideas from all of the bad horror and science fiction movies I grew up on. I hope you enjoy it! I made firstfocus.info to show it off, and I may make this web site better over time. Dunno. It's pretty quick and dirty as it is, but you can read what I've got there.

Friday, January 22, 2016

When a stub acts like a ref variable in a C# unit test, the way any reference type will even inexplicitly, it's pretty darn awesome!

Let's test this method!

using System;
using Whatever.Security.Web.Core;
using Whatever.Security.Web.Core.Interfaces;
using SomethingErOther.Core.Interfaces;
namespace SomethingErOther.Core
{
   public static class HtmlEmailFacilitator
   {
      public static void PrepareAndSendEmail(IHtmlEmailUtility htmlEmailUtility, User
            user, IRepository repository)
      {
         string emailHeader = user.Group.EmailTemplateHeader;
         string emailBody = user.Group.EmailTemplate;
         if (String.IsNullOrWhiteSpace(emailHeader) ||
               String.IsNullOrWhiteSpace(emailBody))
         {
            DIProperties properties = repository.GetProperties();
            if (String.IsNullOrWhiteSpace(emailHeader)) emailHeader =
                  properties.DefaultEmailTriggerSubject;
            if (String.IsNullOrWhiteSpace(emailBody)) emailBody =
                  properties.DefaultEmailTriggerBody;
         }
         htmlEmailUtility.SendEmail(emailHeader, emailBody, user.Email);
      }
   }
}

 
 

Wait a minute, how can we possibly test a void method? It doesn't return anything for us to do an Assert against, right? Well, I found a way today. Consider this stub for IHtmlEmailUtility:

using SomethingErOther.Core.Interfaces;
namespace SomethingErOther.Core.Test.Stubs
{
   public class HtmlEmailUtilityStub : IHtmlEmailUtility
   {
      public string EmailHeaderHandedIn { get; set; }
      public string EmailBodyHandedIn { get; set; }
      public string ToAddressHandedIn { get; set; }
      
      public void SendEmail(string emailHeader, string emailBody, string toAddress)
      {
         EmailHeaderHandedIn = emailHeader;
         EmailBodyHandedIn = emailBody;
         ToAddressHandedIn = toAddress;
      }
   }
}

 
 

It can dip into our method, do its job, and then dip back out carrying some acquired state from its journey. We can assert against the acquired state. Behold:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using NSubstitute;
using Whatever.Security.Web.Core;
using Whatever.Security.Web.Core.Interfaces;
using SomethingErOther.Core.Test.Stubs;
namespace SomethingErOther.Core.Test
{
   [TestClass]
   public class HtmlEmailFacilitatorTests
   {
      private User _user;
      private IRepository _repository;
      
      [TestInitialize]
      public void Prepare()
      {
         _user = new User();
         _user.Email = "me@example.com";
         _user.Group = new Group();
         using (_repository = Substitute.For<IRepository>())
         {
            _repository.GetProperties().Returns(new DIProperties()
            {
               DefaultEmailTriggerSubject = "Welcome to Corelas!",
               DefaultEmailTriggerBody = "It's a dirty place."
            });
         }
      }
      
      [TestMethod]
      public void HtmlEmailFacilitator_happy_pass_test()
      {
         _user.Group.EmailTemplateHeader = "Welcome to Austin!";
         _user.Group.EmailTemplate = "It's a fun place.";
         HtmlEmailUtilityStub stub = new HtmlEmailUtilityStub();
         HtmlEmailFacilitator.PrepareAndSendEmail(stub, _user, null);
         Assert.AreEqual(stub.EmailHeaderHandedIn, "Welcome to Austin!");
         Assert.AreEqual(stub.EmailBodyHandedIn, "It's a fun place.");
         Assert.AreEqual(stub.ToAddressHandedIn, "me@example.com");
      }
      
      [TestMethod]
      public void HtmlEmailFacilitator_lack_of_body_of_email_is_handled_as_expected()
      {
         HtmlEmailUtilityStub stub = new HtmlEmailUtilityStub();
         _user.Group.EmailTemplateHeader = "Welcome to Houston!";
         HtmlEmailFacilitator.PrepareAndSendEmail(stub, _user, _repository);
         Assert.AreEqual(stub.EmailHeaderHandedIn, "Welcome to Houston!");
         Assert.AreEqual(stub.EmailBodyHandedIn, "It's a dirty place.");
         Assert.AreEqual(stub.ToAddressHandedIn, "me@example.com");
      }
      
      [TestMethod]
      public void HtmlEmailFacilitator_lack_of_subject_line_is_handled_as_expected()
      {
         HtmlEmailUtilityStub stub = new HtmlEmailUtilityStub();
         _user.Group.EmailTemplate = "It's an angry place.";
         HtmlEmailFacilitator.PrepareAndSendEmail(stub, _user, _repository);
         Assert.AreEqual(stub.EmailHeaderHandedIn, "Welcome to Corelas!");
         Assert.AreEqual(stub.EmailBodyHandedIn, "It's an angry place.");
         Assert.AreEqual(stub.ToAddressHandedIn, "me@example.com");
      }
      
      [TestMethod]
      public void HtmlEmailFacilitator_unprepared_Group_at_User_behaves_as_expected()
      {
         HtmlEmailUtilityStub stub = new HtmlEmailUtilityStub();
         HtmlEmailFacilitator.PrepareAndSendEmail(stub, _user, _repository);
         Assert.AreEqual(stub.EmailHeaderHandedIn, "Welcome to Corelas!");
         Assert.AreEqual(stub.EmailBodyHandedIn, "It's a dirty place.");
         Assert.AreEqual(stub.ToAddressHandedIn, "me@example.com");
      }
   }
}

Don't you hate it when you double-click on a .sql file and it opens a new instance of SSMS?

Open the .sql files from the "File" menu in SSMS. Do it the hard way. Sigh. It takes a little self-discipline to save things in SSMS tabs in lieu of just closing the tabs. Whew! This a better way to write SQL than just in Notepad where RedGate can't assist you with IntelliSense.

If you need an effect to happen at an input when you either click in the field or tab to the field in HTML...

...jQuery .bind to "focus" to make it happen. "focus" is better than "click" for something like this (i.e. a watermark feature) as it supports arrival by tab and not just arrival by mouse click.

How do I change the color of a textarea?

It's not like affecting a text type input. Behold:

<script type="text/javascript">
   $(function() {
      var header = $(".emailTemplateHeader");
      var body = $(".emailTemplateTextArea");
      if (header[0].value == '<%=HeaderCopy %>') {
         $(".emailTemplateHeader").addClass('emailTriggerWatermark');
      }
      if (body[0].innerHTML == '<%=BodyCopy %>') {
         body[0].style.color = "#CCCCCC";
      }
   });
</script>

Last night I saw Chander Dhall speak at the Rockstar Developers meetup.com meetup on Redis.

When Azure first arrived in the ASP.NET space I told myself: "I need to know this!" As it turns out, I don't need to know it. Chander cautioned against Azure and asserted that if you do it at all you have to have an all-in commitment to it. He recommends Rackspace and Amazon as cloud solutions above Azure but furthermore he really doesn't recommend that you go to the cloud. Having your own datacenter is really the better thing to do all in all. Not everyone can afford that obviously. Anyways, I bring up Azure as I was going to a Redis talk and I assumed it would be about using Redis Cache with Azure. It turns out that I don't need to mentally map Redis to Azure and that it, Redis, is pretty awesome and useful all by itself. This is a legitimate NoSQL solution like Cassandra or Mongo, in that it can be used to store key/value pairs. In the Azure space, one uses it to store what would otherwise be stored in session as an ASP.NET session is tied to a specific machine or VM and an Azure solution distributed across multiple places cannot reliably yank stuff in and out of session. However, you may also just use Redis as you would CouchDB (now Couchbase) for NoSQL. Memcached does all of this too, but while it just merely keeps strings, Redis is smart of enough to keep lists, datasets, ordered collections, etc. in the value half of a key/value pair. Not impressed yet? Alright Redis has Pub/Sub (publish/subscribe) and Chander argued that it was a lot better to go to Redis for queuing than NServiceBus. He dislikes NServiceBus as he feels that it was written poorly in a hodgepodge of C++ and C# in the name of providing C# APIs when it should have been written exclusively in C++ in the name of memory management and speed. Also Chander suggested that the use of messaging through JSON in NServiceBus brings in yet more lag and overhead and fatigue. Binary arrays would have been a better choice. Redis gets in right! The event was scheduled to be at Capital Factory and while I waited for it to get rolling I was given a tour of Capital Factory which was very impressive, but, as it turned out, only I and one other attendee attended so he and I and Chander Dhall and Eric McVicker just jumped ship on Capital Factory and caught dinner at Gloria's nearby but elsewhere in the downtown. More informally, we discussed Redis over chips and salsa.

Thursday, January 21, 2016

targetFramework="4.0" making the debugger not work

...at an ASP.NET web site? Is the problem this part of Web.config?

<system.web>
   <compilation debug="true" targetFramework="4.0"/>

 
 

If so right-click on the project and prick "Property Pages" in Visual Studio 2013. Click the "Build" menu item at the left and then change the "Target Framework" to: ".NET Framework 4"

Let a TextBox in a web form pass the angle brackets.

To get away from errors that start out like like this:

A potentially dangerous Request.Form value was detected from the client...

 
 

Put this inside of system.web in Web.config:

<httpRuntime requestValidationMode="2.0" />

 
 

And put this...

ValidateRequest="false"

 
 

...inside of that topmost line of the .aspx markup that looks like:

<%@ Page Language="C#" CodeBehind="Foo.aspx.cs"...

 
 

By the way this suggested that you should use window.escape and window.unescape in JavaScript to just doctor up TextBox's contents in advance of a post-to-self in lieu of opening a security hole pagewide. I have not tried it. I found it interesting.

I saw Jeffrey Palermo speak at AzureAustin on continuous delivery with TeamCity and Octopus Deploy yesterday at Clear Measure's office.

Terms to know:

  1. Continuous Integration is just the act of running a build script to do things like run unit tests and increment a build number. Perhaps you are making a package but not rolling it out. A must is to have a build that breaks when someone checks in code that breaks a test. Anyways, this is not the act of deploying to an environment. When you are furthermore deploying to an environment you are now undertaking
  2. Continuous Delivery. In the TeamCity interface it is easy to initially deploy to a build server, and then to eventually promote that deployment to a test server, and then to ultimately promote what is at the test server to production. There is likely a manual step where someone (a manager) is pressing a button to do a promotion. If the promotions happen all by themselves and are kicked off by the commits of code which do not break a build, such as in the case of Netflix and Spotify's model, then an enterprise is at a third level dubbed
  3. Continuous Deployment. At last night's talk we saw TeamCity call out to Octopus Deploy to make the building blocks for the delivery/deployment and honestly the fine line between delivery and deployment is just a configuration in this space. This GitHub project shows an example of it all working and to get it working you will need an environment prepped with TeamCity, Octopus Deploy, Visual Studio 2015, and a SQL Server Express Instance named SQLEXPRESS2014. The free needs such as AliaSQL and NUnit are going to be part of what you download from GitHub herein. Psake and PowerShell will get used heavily too.

What else is interesting?

  • Version numbers may be pulled from source control and stamped inside of deployed .dlls.
  • TeamCity can wait on Octopus Deploy to finish or it can call out to Octopus in a fire and forget fashion. In terms of how it is triggered itself, its projects have a setting called Trigger which defines this behavior. You may set the trigger to run TeamCity upon the commit of source code. Another trigger might take a "wait for successful build integration" shape and this, I suppose would be used, if the test server were listening for a successful rollout to the initial build server to do an automatic promotion in a continuous deployment act.
  • You need to keep lots of space available for artifacts at deployment environments. You will want to have a versioned history you may consult and TeamCity may be set to keep the versioned history around as long as it can and then delete from the "bottom of the list" so to speak to clean up disk space when an environment starts getting pinched.
  • Octopus wraps different components into NuGet packages. There will stereotypically be a sequential list of steps in a build process. Perhaps the first step just runs the unit tests. Maybe the second builds the database. Let's say that the third deploys the UI. Each of these steps could be given roles. Let's give "databaseserver" to our second step and "webserver" to our third step in this example. A different NuGet package would be speced for each of these and these are our components. They will define where each package gets deployed to. We don't need to keep the app and the database on the same server, we can break these out in Octopus deployments. Octopus lets you define "tentacles" and a tentacle has a "Display Name" which the name of the server or VM to push to. There would be two different tentacles for app and database in our example.
  • I asked something like "How does one tentacle know about another?" and while the tentacles themselves don't cross-talk, obviously, somehow, the connection string in the rolled out app has to be doctored up to point to the rolled out database. How is that possible? In every step (component) there will be a screen for "Configure Features" in Octopus' interface and herein lies an option for "Configure Variables" where one may specify variables like
    #{DatabaseName} and Octopus will, upon deployment, doctor up all .config files to replace
    #{DatabaseName} with the ideal string. This pound sign and curly braces markup may also be used to call out to Octopus specifics like
    #{Octopus.Environment.Name} and Jeffrey even showed off wacky examples of putting things like CSS's
    display:none; or an HTML comment in variables which might in another environment (test instead of production perhaps) include nothing. This would allow something like
    #{Octopus.Environment.Name} to be displayed on a web page in a test environment as a convenience yet hidden in a production rollout although realistically you might not want such metadata hidden in production HTML.
    #{Octopus.Environment.Name} is not that egregious but you can probably imagine other things that you wouldn't want bubbling up to just-under-the-surface in production.
  • NUnit will be used for the tests and while TeamCity will run all tests by default, NUnit categories may be specified at TeamCity so that one may only run the tests that are decorated in C# with an attribute which says "AcceptanceTest" for example. This allows the quick unit tests and maybe integration tests to be run upon a push to build to keep the build time down to ten minutes and lets that more complicated test where you are reaching out to a web service be deferred to the push to the testing server. Test different things at different promotions.
  • Jeffrey showed in depth his NuGet package for rolling out a database change and it, beyond compiling code, would pull in flat files with .sql extensions (really just glorified .txt files holding SQL) for use in AliaSQL. OctoPack is something that you may get from NuGet which is not a NuGet package but is instead a special MSBuild target which tells Visual Studio how to use Octopus Deploy. We need this. A .nuspec file in the OctoPack paradigm will specify which not compliable content files (SQL scripts) to pull in. This file is just kept in the Visual Studio class library project. Octopus may be instructed to look for a post deployment PowerShell script to run and Jeffrey's was called PostDeploy.psl and it called out to AliaSQL. In many ways the NuGet package seemed to do next to nothing other than just set the stage for the post deployment script to be woken up when it was finished, and indeed the post deployment script is doing disproportionately more work than the NuGet package which at a glance seemed almost ceremonial. There is a way to make a "Web Smoke Test" in Octopus which will do nothing but run a PowerShell script and with as much one may do simple things like spin up IE, open the web site, and make sure the web site is there by crawling it a little bit... and thus that begs the question: Why not do everything with a "Web Smoke Test" and forgo the NuGet theatrics outright? The reasons why not are:
    1. You might want to do something more in C# in another example.
    2. We need to loop in flat files and while you could just do this standalone in PowerShell...
    3. You really only want to use a "Web Smoke Test" for something that won't change. Anything using versioned content out of source control (which should be where just about everything is kept) should use the NuGet glorification and not the more ghetto "Web Smoke Test" PowerShell hackery.
  • You can use RoundhousE instead of AliaSQL. Use what you wish to build your database.
  • Using a newrelic.config file in Visual Studio (at the NuGet packages you'll make) will allow you to use New Relic to test for CPU spikes and the like. Don't wait until a push to production to get the bad news if there is gonna be bad news.

Somewhat off topic:

  • I learned that there is a way to do try/catch logic in PowerShell.
  • It was rewarding to hear Jeffrey decry the nondeterministic practice of going to NuGet for dependencies and he felt that your .dlls should just be kept in source control, old school style. I really agree. I have in the JavaScript space hit so much heartache in trying to get Grunt or Gulp to pull dependencies to no avail. There have been so many open source projects which I would have loved to play with which I've never been able to get to spin up at my laptop. I've not yet been burned by NuGet but Jeffrey has and it's the same thing. He spoke of pulling RavenDB and being unable to hydrate the dependencies because while the wireup worked at the time it was authored it now pulled newer versions of dependencies which caused breaking changes. You can specify specific version numbers for NuGet packages to deploy but Jeffrey suggested that no one does that in practice.

Wednesday, January 20, 2016

Drop a restraint in T-SQL.

Often before you may drop a column you will need to drop a restraint. An example:

ALTER TABLE Whatever
DROP NameOfMyRestraint

change the name of a Windows 2012 R2 server

  • open a folder
  • right-click on "This PC" at the left and pick "Properties"
  • pick "Change settings" at the dialog that appears
  • pick "Change..." at next the dialog that appears
  • after you change the name, restart
  • after the restart type "ipconfig /registerdns" in PowerShell

The project requires user input. Reload the project for more information.

This error leads to this error:

The project ('Whatever') is configured to use the IIS Web server which is not installed on this computer. Would you like to convert the project to use IIS Express?

 
 

I think you know what to do. It looks a lot like this only you'll turn on IIS instead of "My Computer" okay?

Names change at product companies.

Something I've seen at the last two product companies I've been at: The name of an existing product changes to make it more sexy and marketable. The old name lingers in code. This creates a scenario wherein one must do a mental translation between two, or maybe three or four, terms. First world problems?

Tuesday, January 19, 2016

I saw Alex Sexton give a talk called "Client-side Security Stuff" at Austin JavaScript tonight.

You guessed it! It was about JavaScript security! I'll jump to the end and tell you that in summary that as he put it "There's no hope. You can always..." and thus you'll have to decide for yourself what you want to prioritize. He gave the Adam Sontag quote "There ain't no party, like a third party." in regards to web sites which loop in third party content inside of an iFrame, such as the Facebook like button, and cautioned that the .postMessage cross-talk across two domains can get really nasty and lead to collisions with other JavaScript at the "first" party (if you will) web presence. He works at a company called Stripe which has faced such a challenge and he recommends creating your own middleman page to serve up into your own iFrame. The middleman page will itself have an iFrame and that iFrame will hit the third party. Now we have a third level for our third party. The barrier minimizes crosstalk contamination. John-David Dalton recommends this sort of sandboxing. This was the very first thing in the talk and it set the stage for what was to come in that it was esoteric. At one point the template/XSS thing was discussed, but most of the attacks that were laid out were more colorful and things I had not heard of before. Interesting acronyms I had not heard before were:

  • HSTS (HTTP Strict Transport Security) may be added to an HTTP header (it's one line in the header) to force the content to display in https or not at all.
  • CSP (Content Security Policy) is a spec for security. This suggests that everything be locked down to a point wherein a site may only display HTML and then, from that point expanding beyond this baseline, other things that are needed are progressively whitelisted to be looped in as deemed to be likely not sinister. The BATSHIELD (Back-Acronymed Trustworthy Secure Helper Internet-Enabled Lightweight Defense) is a way to make CSP happen. There is also a CSP2 wherein there will be a hash in the header of a page and a hash at a script tag and if the two hashes do not play nicely with each other then the script tag will not run. This helps to neutralize injected script tags.
  • SRI (sub resource integrity) is a second security spec. This has to do with the dependency chain that materializes when you call a script that calls other scripts and does something-er-other to make those murky waters shallow so that you can't drown in them. (My analogy could be better.)

So what were some of the attacks mentioned? (attacks I've not heard of before)

  • You should use CORS instead of JSON-P (JSON with padding) as all JSON-P is doing behind the scenes is creating a script tag and dropping it at the URL. This is hackable. The XHR request approach of CORS is less flimsy. See: enable-cors.org
  • With CSS alone one can do something called Link Knocking. Just as CSS may be used to determine visited links from not yet visited links (purple versus blue, right?) one may somehow use this trick to get a list of not yet visited links in the immediate history. There are ways to brute force a list of Google URLs out of this gunk into what someone had searched at Google before they landed at the sinister web site. The Engagency peeps so interested in implicit data of visitors would love to have this sort of information, right? You could run an algorithm against it to judge what sort of cruise a visitor to a travel site might be interested in and then bait them with the right ad to get them to fill out a form so you could move on to the explicit data profile of the visitor.
  • There is a way to lay an SVG filter over an iFrame, max out its contrast so that every pixel appears as either pure black or pure white, push that to a canvas, save out an image from the canvas, and then run OCR (optical character recognition) against the image to read text out of any web site that may be hosted in an iFrame.
  • A guy named "Samy" wrote evercookie which takes existing cached temp data and casts it to every possible storage means imaginable. localStorage, sessionStorage, and a bunch of other shapes of this ilk all get the data and thus a security hole is ballooned. The only way to beat all of the dissemination to elsewhere that this does is to only use Safari and to restart it completely whenever changing sites.

Monday, January 18, 2016

What happened to "break on all exceptions" in Visual Studio 2015?

Click Ctrl+Alt+E to bring up the "Exception Settings" dialog. Check all of the checkboxes available. That will do the same thing basically.

Axway Acquires Appcelerator

I got the email today! So Axway owns Titanium! So who is Axway?

Following a username with a space may cause an implementation of System.Web.Security.RoleProvider in the Membership Provider paradigm to use the IsUserInRole method's override in lieu of the GetRolesForUser method's override as it would otherwise!!!

Wacky! This is something goofy inside of the Membership Provider code itself! (not our implementation of their interfaces)

jquery.validate.unobtrusive email validation and other validations

Email: { maxlength: 255, email:true }

Might be the way to validate an email address in the @Html.ValidationMessageFor paradigm of ASP.NET MVC. This shows a different setting other than just the required setting. I think there is also a minlength setting. Yes, there is! This has a list of the settings you may set. They are: required, remote, minlength, maxlength, rangelength, min, max, range, email, url, date, dateISO, number, digits, creditcard, equalTo (I don't see a way to break into regular expressions. There are some things you just can't do. A cross-compare of two fields followed by a judgement call might also be one of them. I don't think that is doable.)

JIT compliers

This has a good description of just-in-time compliers. Instead of a language compiling to an executable (if it is compliable at all) you have a scenario in which a language complies to another language (if it is compliable at all) such as C# compiling to CLR. This does not mean that the CLR is bulletproof and that it will not break as it is interpreted at runtime. Get it?

Groovy

This is something you bring into Java to compensate for Java's bad generics and to do stuff akin to the LINQ stuff of C#. (I think.)

 
 

Addendum 3/21/2018: Groovy is a sister language very much like Java, but it is not something you add onto Java. You can get a compiler that will compile both together and somewhat use objects from one in the other in a hodgepodge.

Sunday, January 17, 2016

Model bind to a more verbose child in the MVC paradigm before upcasting to the parent.

Our parent:

using System;
using System.ComponentModel;
namespace CatchingExperiment.Models
{
   public class Person
   {
      public string Name { get; set; }
      
      [DisplayName("Place of Birth")]
      public string PlaceOfBirth { get; set; }
      
      public DateTime? Birthday { get; set; }
   }
}

 
 

Our child:

using System.ComponentModel;
namespace CatchingExperiment.Models
{
   public class PersonAdditionHelper : Person
   {
      [DisplayName("New Infant?")]
      public bool IsNewInfant { get; set; }
      
      [DisplayName("Use Existing Place of Birth?")]
      public string ExistingPlaceOfBirth { get; set; }
   }
}

 
 

What will we do with these? Person is a domain object commonly used in our fictional application, but PersonAdditionHelper is a DTO of sorts for just helping us add a new Person. The reason for the child to begin with might be to accommodate a form which does not merely have fields which map one-to-one with the parent, a from with extra fields. An example:

@{
   Layout = null;
}
@using CatchingExperiment.Models
@model PersonAdditionHelper
<html>
   <head><title>Whatever</title></head>
   <body>
      @using (Html.BeginForm("Catch", "Home", FormMethod.Post))
      {
         <div>
            @Html.LabelFor(m => m.Name)
            @Html.TextBoxFor(m => m.Name)
         </div>
         <div>
            @Html.LabelFor(m => m.Birthday)
            @Html.TextBoxFor(m => m.Birthday, new { type = "date"})
         </div>
         <div>
            @Html.LabelFor(m => m.PlaceOfBirth)
            @Html.TextBoxFor(m => m.PlaceOfBirth)
         </div>
         <div>
            @Html.LabelFor(m => m.ExistingPlaceOfBirth)
            @{
               List<SelectListItem> existingItems = ViewBag.ExistingItems;
            }
            @Html.DropDownListFor(m => m.ExistingPlaceOfBirth, existingItems)
         </div>
         <div>
            @Html.LabelFor(m => m.IsNewInfant)
            @Html.CheckBoxFor(m => m.IsNewInfant)
         </div>
         <input type="submit" value="Go" />
      }
   </body>
</html>

 
 

Alright, we have a way to just define the person as "brand new" in lieu of setting a birthday and we have a way of picking from a list of existing locales for PlaceOfBirth. The simple form gives us more than three controls for configuring what is ultimately three fields.

 
 

As you can see, we cannot just map the fields shown to the Person object so we will map it to PersonAdditionHelper instead like so:

using System;
using System.Collections.Generic;
using System.Web.Mvc;
using CatchingExperiment.Models;
using CatchingExperiment.Utilities;
namespace CatchingExperiment.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         List<SelectListItem> existingPlaces = new List<SelectListItem>();
         existingPlaces.Add(new SelectListItem()
         {
            Text = "",
            Value = ""
         });
         foreach (string existingPlace in Repository.GetExistingPlaces())
         {
            existingPlaces.Add(new SelectListItem()
            {
               Text = existingPlace,
               Value = existingPlace
            });
         }
         ViewBag.ExistingItems = existingPlaces;
         return View(new PersonAdditionHelper());
      }
      
      public ActionResult Catch(PersonAdditionHelper personAdditionHelper)
      {
         Person person = (Person)personAdditionHelper;
         if (personAdditionHelper.IsNewInfant)
         {
            person.Birthday = DateTime.Now;
         }
         if (!String.IsNullOrWhiteSpace(personAdditionHelper.ExistingPlaceOfBirth))
         {
            person.PlaceOfBirth = personAdditionHelper.ExistingPlaceOfBirth;
         }
         Repository.SavePerson(person);
         return View(person);
      }
   }
}

 
 

At our controller we catch the child at the Catch action (where our form posts to) and then, after upcasting the child to the parent type, we massage the parent a little bit. Make sense? We can get this under test like so:

using System;
using System.Web.Mvc;
using CatchingExperiment.Controllers;
using CatchingExperiment.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CatchingExperiment.Tests.Controllers
{
   [TestClass]
   public class HomeControllerTests
   {
      private HomeController _controller;
      private PersonAdditionHelper _person;
      
      [TestInitialize()]
      public void HomeControllerTestsInitialize()
      {
         _controller = new HomeController();
         _person = new PersonAdditionHelper()
         {
            Name = "Tom",
            PlaceOfBirth = "Florida",
            Birthday = new DateTime(1974,8,24)
         };
      }
      
      [TestMethod]
      public void happy_pass()
      {
         var actionResult = _controller.Catch(_person);
         var viewResult = (ViewResult)actionResult;
         var person = ((Person)viewResult.ViewData.Model);
         Assert.AreEqual(person.Name, "Tom");
         Assert.AreEqual(person.PlaceOfBirth, "Florida");
         Assert.AreEqual(person.Birthday, new DateTime(1974, 8, 24));
      }
      
      [TestMethod]
      public void use_of_existing_locale_behaves_as_expected()
      {
         _person.ExistingPlaceOfBirth = "Texas";
         var actionResult = _controller.Catch(_person);
         var viewResult = (ViewResult)actionResult;
         var person = ((Person)viewResult.ViewData.Model);
         Assert.AreEqual(person.Name, "Tom");
         Assert.AreEqual(person.PlaceOfBirth, "Texas");
         Assert.AreEqual(person.Birthday, new DateTime(1974, 8, 24));
      }
      
      [TestMethod]
      public void new_infant_feature_behaves_as_expected()
      {
         _person.IsNewInfant = true;
         var actionResult = _controller.Catch(_person);
         var viewResult = (ViewResult)actionResult;
         var person = ((Person)viewResult.ViewData.Model);
         Assert.AreEqual(person.Name, "Tom");
         Assert.AreEqual(person.PlaceOfBirth, "Florida");
         Assert.AreNotEqual(person.Birthday, new DateTime(1974, 8, 24));
         Assert.IsTrue(person.Birthday > DateTime.Now.AddHours(-1));
         Assert.IsTrue(person.Birthday < DateTime.Now.AddHours(1));
      }
   }
}

 
 

Things to keep in mind about the tests:

  1. It's hard to test around DateTime.Now as this should really be an external dependency that is mockable which is looped in from elsewhere.
  2. I had to add the following references to the test project to get it to work:
    • the UI project
    • System.Web.Mvc
    • System.Web.WebPages

Saturday, January 16, 2016

Scala

It's another scripting language.

MCTS is the new MCP? Perhaps it's a distinction and a breakout.

I'm a Microsoft Certified Professional. I took a really silly test on Windows XP and got the MCP cred from the certification I received. Anymore that may be a sign of nothing-to-do-with-code as I'm learning today that one becomes a MCTS (Microsoft Certified Technology Specialist) when one takes a test such as 70-536 on C#.

Friday, January 15, 2016

How do I set a HiddenFor value in Razor markup?

@Html.HiddenFor(m => m.FunId)

Alright, in this case FunId should just really get set on the model that is getting bound to the view, get it? Hand it in on the model. Duh.

Put an id on a Razor form.

@using (Html.BeginForm("New", "User"))

 
 

...as seen here could be revised like so...

@using (Html.BeginForm("Invoice", "Buyers", FormMethod.Post, new { id = "form"}))

 
 

As much would allow for the following to come after the form to start the validations.

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript">
</script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript">
</script>
<script type="text/javascript">
   $(function() {
      $("#form").validate({
         rules: {
            Username: { required: true },
            Password: { required: true },
            PasswordConfirmation: { required: true },
            PhoneNumber: { required: true }
         }
      });
   });
</script>

How to use the DisplayName attribute with Html.LabelFor in MVC 5.

Consider this Razor form in a .cshtml view:

<div>
   @using (Html.BeginForm("New", "User"))
   {
      <div>
         <h3>Sign up!</h3>
         <div>
            @Html.LabelFor(m => m.Username, new {@class = "MyLabel"})
            <br/>
            @Html.TextBoxFor(m => m.Username, new {@class = "MyInput"})
            @Html.ValidationMessageFor(m => m.Username)
         </div>
         <div>
            @Html.LabelFor(m => m.Password, new {@class = "MyLabel"})
            <br/>
            @Html.PasswordFor(m => m.Password, new { @class = "MyInput" })
            @Html.ValidationMessageFor(m => m.Password)
         </div>
         <div>
            @Html.LabelFor(m => m.PasswordConfirmation, new {@class = "MyLabel"})
            <br/>
            @Html.PasswordFor(m => m.PasswordConfirmation, new {@class =
                  "MyInput"})
            @Html.ValidationMessageFor(m => m.PasswordConfirmation)
         </div>
         <div>
            @Html.LabelFor(m => m.PhoneNumber, new { @class = "MyLabel" })
            <br />
            @Html.TextBoxFor(m => m.PhoneNumber, new { @class = "MyInput" })
            @Html.ValidationMessageFor(m => m.PhoneNumber)
         </div>
         <input type="submit" value="Register" class="MyButton" />
      </div>
   }
</div>

 
 

Alright, we probably don't want the labels for the password confirmation and the phone number to be "PasswordConfirmation" and "PhoneNumber" without spaces between the words right? What if we want to customize a label, and, perhaps, have the confirmation's label just be "Confirm" tersely? Well, we can do all that by decorating our model like so:

using System.ComponentModel;
namespace Whatever.Models
{
   public class Registration
   {
      public string Username { get; set; }
      
      public string Password { get; set; }
      
      [DisplayName("Confirm")]
      public string PasswordConfirmation { get; set; }
      
      [DisplayName("Phone Number")]
      public string PhoneNumber { get; set; }
   }
}

Thursday, January 14, 2016

I see the "No images are available." error when I try to make a Windows Server 2012 R2 VMWare VM!

This has the work around. Look at the settings which expand from the left for the VM. Find "Floppy" and uncheck the "Connect at power on" checkbox. Then just restart the VM

The Web server is configured to not list the contents of this directory.

So far, I've been unable to best this IIS error. When try to go to "Directory Browsing" to enable "Directory Browsing" I get a different error saying:

Error: Can not log on locally to C:\inetpub\wwwroot as user YOUR\namehere with virtual directory password

Selecting text with the "End" key.

At a PC, in either Notepad or Word, click in the midst of a line of text. Hold Shift and press End. The copy from where you clicked to the end of the line will be selected.

Wednesday, January 13, 2016

Format Painter

...in the "Home" ribbon of Microsoft Word with allow you to copy to the clipboard the style of the thing you have selected (font size, font color, etc.) and then when you next select something that selection will get the style.

The ability to "Browse" a website will be found in different places in different versions of IIS.

In the connections pane you should be consistently able to right-click on a website or an application and pick "Manage Website" or "Manage Application" (as applicable) and then see the "Browse" option in a submenu that flys out from that option.

Tuesday, January 12, 2016

Why can't I install Web Essentials at Visual Studio 2013?

If you get Web Essentials from here you will have to have Update 4 for Visual Studio 2013 for its .vsix to run without issue for the install. I couldn't find Update 4 anywhere in searching so I just installed Update 5 from here.

There is always a fudge factor with timesheets.

To pretend it's not there is to lower yourself to the level of a criminal.

I guess you can constantly make notes as to what time it is as you multitask at work to get around this problem, but who really does that? Most of us just think of what we did last week and approximate time. I think you can see how it's halfway hogwash. (I used the pig term instead of the cow term. I'll be polite.) Halfway legit may just be good enough though. It depends on how meticulous your tracking is meant to be. Whatever. Your glass is half full.

Monday, January 11, 2016

How can I put a JavaScript onclick event on a web forms button when it already has a C# OnClick event?

At this...

<asp:Button ID="Foo" runat="server" Text="Go" OnClick="Foo_Click" />

 
 

The OnClick is going to correspond to something in the code behind like so:

protected void Foo_Click(object sender, EventArgs e)
{
   var whatever = "meh";
}

 
 

If you try to jam in a second onclick for JavaScript at the tag itself you will get this error:

The tag contains duplicate 'onclick' attributes.

 
 

Oh no! How do we get out of this pit of spiders? Well, here is one way to assign a second onclick event with jQuery:

$("#<%= Foo.ClientID %>").attr("onclick","return false;");

 
 

What is below is just a smidge better as it works with IE7 whereas the thing above does not.

$("#<%= Foo.ClientID %>").bind('click', function () {
   return false;
});

 
 

If you want to keep the button from submitting the web form you may have to have the return false; immediately there at the binding. I tried to put it in a function and call out to the function and, at least in Chrome, it didn't work.

The underscore in the middle of a name in C#.

This has a very specific convention. It really only appears in:

  1. snake case names for unit tests (and that's Ruby creeping in)
  2. web forms event handlers...
    protected void Button_Click(object sender, EventArgs e)
    {

Undo an event binding in jQuery.

$("#whatever").unbind("click");

A secure digital (SD) card slot is that place on the side of your device to take the memory card in and out.

At an Android device I think one may use this to keep memory which may be moved back and forth between the device and a laptop to move data between the two environments.

Why does Visual Studio 2013 crash each time I add package sources in NuGet?

Well, this would have you believe that you need to repair or redo the install of the IDE!