Monday, June 30, 2014

TransactionScope and MSDTC

Following up on this, I found this which suggests there is a MSDTC (Microsoft Distributed Transaction Coordinator) service in Windows which the TransactionScope type in C# will use to wrap database calls, called out within its using statements like so...

using (TransactionScope scope = new TransactionScope())
{
   PutSomethingInTheDatabase();
   AddSoftReferencesToThatOtherTable();
   scope.Complete();
}

 
 

...thus allowing for the rolling back of writes to a database should something fail midstream in a process. In the System.Transactions namespace lives the C# TransactionScope type which subclasses IDisposable as is clearly obvious when you look at the above code. This hints that one may make the MSDTC interface with two different datasources at the same time! Only one datasource may be used with MSDTC in its default setting and also in its absence, and yes, as this suggests, there is a way to forgo using MSDTC whatsoever with TransactionScope. You may not want use MSDTC on a project because one has to open up some particular ports that perhaps you'd rather not expose.

When logging exceptions, bring try/catch wrappers for code as far up in the chain of events as possible.

This ensures that you're "getting everything" and they might as well sit at the "top" (in the UI layer) least you end up having to wrap one try/catch within another.

LINQPad's real strength may be for LINQ queries against data in flat files.

LINQPad could slurp in a flat file you've scrapped off of XML or JSON from a service so that you might make sense of it with LINQ queries. My superior suggested that was a pretty good use for the tool.

Sunday, June 29, 2014

using a DevExpress GridView in MVC

The stuff here, here, here, and here was a learning-how-to implementation for a DevExpress ASPxGridView. Yesterday I tried to do something similar for MVC. I made the default ASP.NET MVC Web API application in Visual Studio 2013. First, I recreated in the Models folder the Planet, PlanetType, and Measurements models I had in my web forms experiment and then I recreated the Utilities folder and again put CommonSource and PlanetFactory in it. Next, I erased all of the guts of Index.cshtml and then I right clicked in Index.cshtml where I picked an option for "Insert DevExpress MVC Extension" from the menu which appeared.

 
 

A wizard of sorts appeared. I went to the "Data" tab and picked "GridView" to make a GridView which seems to be the MVC counterpart to an ASPxGridView. This has more about the GridViews, I think. I found that I had to pick a model class, but I was frustrated that I could not pick just any class I wanted to use. I ended up just picking Antlr.Runtime.ICharStream. Whatever.

 
 

After I clicked the Insert button, Web.config was changed up quite a bit and Index.cshtml looked like this:

@Html.Action("GridViewPartial")

 
 

A partial it defered to looked like this:

@{
   var grid = Html.DevExpress().GridView(settings => {
      settings.Name = "GridView";
      settings.CallbackRouteValues = new { Controller = "Home",
            Action = "GridViewPartial" };
      
      settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "Home",
            Action = "GridViewPartialAddNew" };
      settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "Home",
            Action = "GridViewPartialUpdate" };
      settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "Home",
            Action = "GridViewPartialDelete" };
      settings.SettingsEditing.Mode = GridViewEditingMode.EditFormAndDisplayRow;
      settings.SettingsBehavior.ConfirmDelete = true;
      
      settings.CommandColumn.Visible = true;
      settings.CommandColumn.NewButton.Visible = true;
      settings.CommandColumn.DeleteButton.Visible = true;
      settings.CommandColumn.EditButton.Visible = true;
      
      settings.KeyFieldName = "Line";
      
      settings.SettingsPager.Visible = true;
      settings.Settings.ShowGroupPanel = true;
      settings.Settings.ShowFilterRow = true;
      settings.SettingsBehavior.AllowSelectByRowClick = true;
      
      settings.Columns.Add("Line");
      settings.Columns.Add("CharPositionInLine");
   });
   if (ViewData["EditError"] != null){
      grid.SetEditErrorText((string)ViewData["EditError"]);
   }
}
@grid.Bind(Model).GetHtml()

 
 

HomeController looked like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DevExpress.Web.Mvc;
 
namespace DummyDevExpressApplication.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         ViewBag.Title = "Home Page";
         
         return View();
      }
      
      
      [ValidateInput(false)]
      public ActionResult GridViewPartial()
      {
         var model = new object[0];
         return PartialView("_GridViewPartial", model);
      }
      
      [HttpPost, ValidateInput(false)]
      public ActionResult GridViewPartialAddNew([ModelBinder(typeof(
            DevExpressEditorsBinder))] Antlr.Runtime.ICharStream item)
      {
         var model = new object[0];
         if (ModelState.IsValid)
         {
            try
            {
               // Insert here a code to insert the new item in your model
            }
            catch (Exception e)
            {
               ViewData["EditError"] = e.Message;
            }
         }
         else
            ViewData["EditError"] = "Please, correct all errors.";
         return PartialView("_GridViewPartial", model);
      }
      [HttpPost, ValidateInput(false)]
      public ActionResult GridViewPartialUpdate([ModelBinder(typeof(
            DevExpressEditorsBinder))] Antlr.Runtime.ICharStream item)
      {
         var model = new object[0];
         if (ModelState.IsValid)
         {
            try
            {
               // Insert here a code to update the item in your model
            }
            catch (Exception e)
            {
               ViewData["EditError"] = e.Message;
            }
         }
         else
            ViewData["EditError"] = "Please, correct all errors.";
         return PartialView("_GridViewPartial", model);
      }
      [HttpPost, ValidateInput(false)]
      public ActionResult GridViewPartialDelete(System.Int32 Line)
      {
         var model = new object[0];
         if (Line != null)
         {
            try
            {
               // Insert here a code to delete the item from your model
            }
            catch (Exception e)
            {
               ViewData["EditError"] = e.Message;
            }
         }
         return PartialView("_GridViewPartial", model);
      }
   }
}

 
 

There is a lot to understand here and I didn't try to figure it out all at once. I just wanted to get something working. I changed GridViewPartial in HomeController like so:

[ValidateInput(false)]
public ActionResult GridViewPartial()
{
   var model = PlanetFactory.GetPlanets();
   return PartialView("_GridViewPartial", model);
}

 
 

In _GridViewPartial.cshtml which is the previously mentioned partial, I replaced the lines which started out with settings.KeyFieldName and settings.Columns.Add like this:

settings.KeyFieldName = "Name";

 
 

...and like this:

settings.Columns.Add("Name");
settings.Columns.Add("ClosestAstronomicalUnitDistanceFromSun");
settings.Columns.Add("PlanetType");
settings.Columns.Add("MilesInDiameter");
settings.Columns.Add("DiscoveryDate");

 
 

Now I may run the application and see something like this:

 
 

Clearly, I have a long way to go yet. My stylesheet styles could use some love, no?

Thursday, June 26, 2014

Spaghetti Tom

...is the nickname I've earned at the Olive Garden at 183 and Burnet where I eat all the time because I eat... spaghetti. It's really not a flattering nickname for someone who writes code.

View the code for a .resx resource file in Visual Studio 2013 by...

...right-clicking on it and picking "View Code" in the Solution Explorer. Any HTML that goes into the value for a line item must be <encoded> mkay?

Java, Haskell, C++, and MATLAB

...are the four languages that one learns in a traditional computer science curriculum in modern America. If these are the only four languages on your resume it kind of says you only care so much. That said, I don't know any of these and I only hold an Associates in Multimedia so who am I judge you?

MIS stands for Management Information Systems. This is that "lightweight" degree that people get when they can't get computer science degrees, yet it still comes with those four semesters of calculus that you'll never use. I get the impression that this is more tailored to recordkeeping (line of business applications) than the hardcore computer science degree which looks a little better on a resume. However, the line of business applications sphere is where all of the jobs are and if you get a computer science degree you'll likely just end up doing MIS anyways. This is what happens to you if you’re an electrical engineer too. I can tell the guys who have the Bachelors in the three aforementioned studies do know something I don't, but there are more jobs in the line of business application realm than there are people in these fields. Well, at least that is the case in America right now. I guess we could solve that problem by not making so hard for Indians and Chinese to immigrate. I digress.

Wednesday, June 25, 2014

The Other Reflector

Red Gate .NET Reflector (not to be confused with Reflector) is a tool like JetBrains dotPeek which allows you to cast the CLR out of a complied .NET assembly back to C# code that you may step into. In Visual Studio you will see a new pane dubbed ".NET Reflector Object Browser" and from it you may drill into namespaces in .dlls. Cool.

.ashx in ASP.NET web forms

http://www.dotnetperls.com/ashx-handler starts out saying: "Some ASP.NET files are dynamic." ...and an .ashx seems to be for files that should be calculated dynamically. For example, instead of giving a link to example.txt you could give an link to example.ashx if you need to ultimately be handed a dynamically crafted text file for example.txt.

Tuesday, June 24, 2014

Trojan Horses

I haven't heard of these since the 1990s but I guess the "Trojan Horse" term is still legitimate in virus terminology. Trojan Horses are anything sinister that get snuck in as part of an installation while you are installing something think you want.

More Phishing Terminology

SMiShing is phishing in which victims are baited by SMS text messaging. Phaxing is phishing in which victims are baited to fill out information on a sheet of paper and fax it into a fax number. Vishing is phishing wherein victims are baited to give credit card information. I guess if I text you and ask you to photo copy both sides of your credit card and fax it into 555-DUMB that would be a SMiShing/phaxing vishing attack. Blanket phishing attacks such as these are only going to get a small percentage of victims through the funnel to a "conversion" (stealing a sales term). An approach which starts with a smaller pool yet ultimately yields more conversions than could be gained through traditional phishing is called spear phishing. (I mean to convey: The top of the spear phishing "sales funnel" is smaller than that of the phishing "sales funnel" but the bottom of the spear phishing "sales funnel" is larger than that of the phishing "sales funnel.") In spear phishing one baits a respond not from the whole of the online/not Amish public, but from a targeted subset, members of a particular company or shopping habit, etc. The targeted messages are more believable.

There is a "Show All" button at the lower left of the dialog which appears when one browses logs in TortoiseSVN.

This is the thing to click when you notice that the history is cut off by the range of dates in the "From:" and "To:" fields at the upper right.

params keyword in C#

Stack Overflow illuminates that:

public static int addTwoEach(params int[] args)
{
   return args.Sum() + 2 * args.Length;
}

 
 

...may be called like so:

var foo = addTwoEach(1, 2, 3, 4, 5);

 
 

...and not just like so:

var foo = addTwoEach(new int[] { 1, 2, 3, 4, 5 });

 
 

The second scenario works just fine without the params keyword of course.

AutoMapperesque mappings from DataSet stuff to better C# objects in DotNetNuke.

I'm understanding a little more how the IHydratable objects are hydrated in a DotNetNuke application. It is pretty cool and effectively creates a way to hydrate objects out of a database by stored procedures in an ORMish, loosely-coupled manner keeping core object classes independent from the data layer which feeds their object instances. Assuming you have a class, in this example, FluffyBunny, which inherits from IHydratable in the DotNetNuke.Entities.Modules namespace, you could call a stored procedure and get a list of fluffy bunnies like so:

List<FluffyBunny> foo = GetStuff<FluffyBunny>("GetFluffyBunnyByColor", new []
   {
      new SqlParameter(Color, "White")
   });

 
 

"GetStuff" starts out like this...

public List<T> GetStuff<T>(string sprocName, params SqlParameter[] variables)
{
   using (SqlConnection go = new SqlConnection(_connectionString))
   {
      connection.Open();
      using (SqlCommand act = new SqlCommand(sprocName, go)
         { CommandType = CommandType.StoredProcedure
      })
      {

 
 

Next would come some usual logic for associating the SqlParameter stuff with the SqlCommand. Finally, "GetStuff" could be wrapped up like so:

         using (SqlDataReader read = act.ExecuteReader())
         {
            return CBO.FillCollection<T>(read);
         }

 
 

.FillObject<T> could be used instead of .FillCollection<T> if you were just hydrating a single object. Both of these tricks are from the DotNetNuke.Common.Utilities namespace. This stuff seems pretty neat. FluffyBunny has to have getsetters which correspond to the column names in the database one-to-one to pull this off of course. I suppose you could fudge some name changes with AS in the stored procedure itself. I don't recommend using DotNetNuke for a CMS, but it might be OK to selectively use this piece of its functionality. The GetStuff method also shows off some of the cool ways C# generics may be manipulated as discussed in C# 4.0 in a Nutshell. I supposed this hydration posting is multiheaded... not unlike.. the Hydra!

Cache!

Based on this, I got an example of using the cache in an ASP.NET MVC application working. I will keep a simple model in the cache in the example that follows. In C# my object looks like so:

namespace PiggyBank.Models
{
   public class Money
   {
      public decimal Amount { get; set; }
      public string Curreny { get; set; }
   }
}

 
 

A view manages what goes in the cache and looks like this:

 
 

More specifically, the Razor markup for the view looks like this:

@{
   Layout = null;
}
@model PiggyBank.Models.Money
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
   @Html.EditorFor(model => model.Amount)
   @Html.EditorFor(model => model.Curreny)
   @:...are in the bank.
   <input type="submit" value="change this?"/>
}
<a href="/">refresh</a>

 
 

The "refresh" link will just go to the same URL one is already at while the form itself updates the cache. The view should always show what is in the cache so clicking the "refresh" link will not show the user what he/she first saw upon spinning up the app if he/she has changed the cache with the form. I am pleased to say that it all works! My controller is as follows. I had to add in the System.Runtime.Caching namespace to get this to work. It was not an included reference by default for an ASP.NET MVC Web API application.

using System;
using System.Runtime.Caching;
using System.Web.Mvc;
using PiggyBank.Models;
namespace PiggyBank.Controllers
{
   public class HomeController : Controller
   {
      private string _piggybankinnards = "piggybankinnards";
      private ObjectCache _cache{ get { return MemoryCache.Default; } }
      
      public ActionResult Index()
      {
         Money money = GetCache() as Money;
         return View(money);
      }
      
      [HttpPost]
      public ActionResult Index(Money money)
      {
         SetCache(money);
         return View(money);
      }
      
      private object GetCache()
      {
         if (_cache[_piggybankinnards] != null)
         {
            return _cache[_piggybankinnards];
         } else {
            return new Money()
            {
               Amount = 0m,
               Curreny = "Dollars"
            };
         }
      }
      
      private void SetCache(Money money)
      {
         if (_cache[_piggybankinnards] != null)
         {
            _cache.Remove(_piggybankinnards);
         }
         CacheItemPolicy life = new CacheItemPolicy();
         life.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(30);
         _cache.Add(new CacheItem(_piggybankinnards, money), life);
      }
   }
}

Issuers issue credit cards and acquirers take payments for credit cards.

Processors may just pass through to an acquirer (while not being the end acquirer) while then being paid a cut by the acquirer.

interchange rates

There is a minimum fee associated with credit card transactions. The interchange rate is always going to gobble up ten cents worth of the transaction outside of a percentage. Many who take credit card payments just gamble that there won’t be many transactions for less than ten cents. Others do something about it. I found this which suggests that minimums for purchases may be set for up to ten dollars but that Visa, for example, forces no minimums to be set when others take its card. Visa will blacklist you if it catches you setting minimums for Visa charges. The rates for the three levels of credit card processing are as follows. Note that as the level goes up to accomodate more pricey transactions, a break is given.

  • Level 1: 2.65% + $0.10
  • Level 2: 2.05% + $0.10
  • Level 3: 1.80-1.95% + $0.10

Monday, June 23, 2014

When doing a code review and using Rally...

There will be a "Code Reviewed" checkbox to check in Rally when editing the story. There will also be a "Code Review" textarea-as-an-HTML-WYSIWYG-editor control which may be used to type up some notes.

Sunday, June 22, 2014

mixing StructureMap with NSubstitute

I am looking at an app where the core has its external dependencies hydrated by StructureMap when the application spins up. In testing, they are supplied a different way and the methods on the interfaces corresponding to external dependencies are easily mocked with NSubstitute in C# in individual test classes by doing dot syntax off of dependencies (interfaces) in protected fields on a common base class that the test classes inherit from. The base class looks like this:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using NSubstitute;
using StructureMap;
namespace Whatever
{
   [TestClass]
   public class CommonBaseForTests
   {
      protected IFooDependency FooDependency;
      protected IBarDependency BarDependency;
      
      [TestInitialize()]
      public void NSubstituteBaseControllerTestInitialise()
      {
         ObjectFactory.Initialize(x => x.AddRegistry(new WireUpMagic()));
         FooDependency = ObjectFactory.GetInstance<IFooDependency>();
         BarDependency = ObjectFactory.GetInstance<IBarDependency>();
      }
   }
}

 
 

What I am calling WireUpMagic has a better name in the app I am looking at. I don't really understand it yet. It inherits from Registry which sits in the StructureMap.Configuration.DSL namespace. It looks like so:

using StructureMap.Configuration.DSL;
using NSubstitute;
namespace Whatever
{
   public class WireUpMagic : Registry
   {
      public WireUpMagic()
      {
         var foo = Substitute.For<IFooDependency>();
         var bar = Substitute.For<IBarDependency>();
         For<IFooDependency>().Use(foo);
         For<IBarDependency>().Use(bar);
      }
   }
}

Saturday, June 21, 2014

CCTV stands for Closed-circuit Television.

I actually found this on the "Ask" search engine! CCTV cameras are for your in-house surveillance system.

If you're not going to have a burndown chart in your pseudoscrum process you might as well not estimate story points.

The things you are working on you will likely work on anyway. There will never come that moment when you ask yourself "What do we need to sacrifice in the name of being done on time?" I guess the estimating can help you be sure you have enough to do before the next scheduled planning. Meh.

Friday, June 20, 2014

The VLC Media Player will supposedly play *.mkv files.

I won't share the link where I found it online. It installed a bunch of other stuff I didn't want. :(

Security Accounts Manager does password stuff for Active Directory.

Wikipedia tells us: "The Security Accounts Manager (SAM) is a database file in Windows XP, Windows Vista and Windows 7 that stores users' passwords. It can be used to authenticate local and remote users. Beginning with Windows 2000 SP4, Active Directory is used to authenticate remote users. SAM uses cryptographic measures to prevent forbidden users to gain access to the system."

Thursday, June 19, 2014

Talk into a web user control from a web form.

This is really pretty easy to do, but I only learned how to do it this week. Previously, I would just put stuff into session in the web form and then pull it back out again in the .ascx. In my example to show of the right way to go, I have a simple one page application which just looks like this:

 
 

The markup for the web user control just looks like this.

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Reverser.ascx.cs"
      Inherits="MyApp.Reverser" %>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>

 
 

Alright, so it holds a label and nothing more. The code behind for the .ascx on the other hand has some stuff going on inside of it. I made two getsetters which only set. They look like this:

using System;
using System.Drawing;
namespace MyApp
{
   public partial class Reverser : System.Web.UI.UserControl
   {
      public string Bookend
      {
         set
         {
            char[] array = value.ToCharArray();
            string eulav = "";
            for (int i = value.Length - 1; i > -1; i--)
            {
               eulav += array[i];
            }
            Label1.Text = value + " backwards is " + eulav;
         }
      }
      
      public Color Hue
      {
         set { Label1.ForeColor = value; }
      }
      
      protected void Page_Load(object sender, EventArgs e)
      {
      }
   }
}

 
 

I nested the .ascx in a web form which looks like this:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
      Inherits="MyApp.Default" %>
<%@ Register src="Reverser.ascx" tagname="Reverser" tagprefix="uc1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title></title>
</head>
<body>
   <form id="form1" runat="server">
      <uc1:Reverser ID="Reverser1" runat="server" Bookend="god" />
   </form>
</body>
</html>

 
 

Notice how Bookend is specified above? That is one way to talk into the control from the outside. There is another way to do so from the C# side like so:

using System;
using System.Drawing;
namespace MyApp
{
   public partial class Default : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
      {
         Reverser1.Hue = Color.Firebrick;
      }
   }
}

jamming a CASE statement into a WHERE clause in MSSQL

This caused an error:

WHERE p.CompanyId=c.CompanyId
AND (CASE WHEN @Location = 13 THEN p.StateId = 42 ELSE p.StateId =
      p.StateId END)

 
 

This didn't cause an error, but the ELSE scenario ended up returning no records. I don't know why. It seems to me like it should have worked.

WHERE p.CompanyId=c.CompanyId
AND p.StateId = (CASE WHEN @Location = 13 THEN 42 ELSE p.StateId END)

 
 

This is the porridge Goldilocks picked:

WHERE p.CompanyId=c.CompanyId
AND 42 = (CASE WHEN @Location = 13 THEN p.StateId ELSE 42 END)

A clean desk without spare scraps of paper is a requirement of PCI compliance.

Whiteboards needs to be wiped down after you're done brainstorming too.

alter an element by an attribute in jQuery

$("[uniqueidentifier=note" + myId + "]").attr("style", "display:none;");

Wednesday, June 18, 2014

Roslyn

Roslyn is a mining town in Washington, State. It was where the TV show "Northern Exposure" was filmed and recently it has been undergoing a rejuvenation as cobwebs are brushed off and trendy condo buildings are put up. Microsoft has decided to name its compiler for C# 6.0 Roslyn. It too has a shaking-off-the-cobwebs feeling and is to be the baseline for supporting modern era C# for hopefully a decade to come. Roslyn is written in managed code (not C++) and contains complete top to bottom rewrites of C# and VB. It is ready for concurrency and massively parallelized. It will come with Visual Studio 14 and C# has become an open source language. I saw an Anthony Green of Microsoft speak on Roslyn on Saturday at the Cowtown Code Camp. He showed us the following neat things coming in C# 6.0:

public class Vector2D(int x, int y)
{
   public int x { get; } = x;
   public int y { get; } = y;

 
 

What is above shows off setting default values for property accessory while this shows a code block which will only be run if a string called foo is not null:

If (foo?.Length > -1)
{

 
 

Wouldn't it do the same thing without the question mark? No, without the question mark a null value would cause the line of code to throw an exception. Anthony cautioned the audience not to run Roslyn on the same PC as another Visual Studio compiler. This could cause havoc. One will get live diagnostics tips as one codes with Roslyn. It all seems pretty cool to me. I enjoyed this talk. Mr. Green was on vacation from his day job in Seattle when he presented. Many thanks to him.

Tuesday, June 17, 2014

CausesValidation="false"

...when decorating the ASP.NET markup for a DevExpress ASPxButton may, as the name suggests, prevent validation driven by a ValidationSettings type control from happening.

Monday, June 16, 2014

C# getsetters which tuck away stuff to session

public List<Foo> Foos
{
   get
   {
      if (HttpContext.Current.Session[SessionKeys.FooKey] == null) return null;
      return HttpContext.Current.Session[SessionKeys.FooKey] as List<Foo>;
   }
   set { HttpContext.Current.Session[SessionKeys.FooKey] = value; }
}
 
public int MyId
{
   get
   {
      if (HttpContext.Current.Session[SessionKeys.MyKey] == null)
         HttpContext.Current.Session[SessionKeys.MyKey] = -1;
      return (int)HttpContext.Current.Session[SessionKeys.MyKey];
   }
   set { HttpContext.Current.Session[SessionKeys.MyKey] = value; }
}

Dealing with a C# ambiguous reference in what is probably the wrong way.

I made a web user control. Within it I broke into <%# ... %> and inside of this I had a reference that had a squiggly red line under it. I put my mouse pointer over it and got a tooltip which read "Ambiguous reference:" followed by the same namespace listed twice and finally followed by "match" to which I could find no solution. This speaks to the same problem, but it didn't help me. I ended up just using the <%# ... %> to call a method in the code behind which returned what I needed. In the code behind's method I then referenced the namespace which was otherwise ambiguous in the ASP.NET markup. Whatever.

blurry Skype photo?

This touches on this fix for a blurry skype photo which works so-so:

  1. exit skype
  2. download and start Skype 5.0 portable
  3. change your picture
  4. exit skype 5
  5. start your normal skype

 
 

Also: Did you know that Microsoft now owns Skype?!

Cowtown Code Camp

I attended Cowtown (Fort Worth, Texas) Code Camp for the first time this year, though I only stayed for the first half of the day. Midway through the proceedings I won a Windows Phone in a drawing and that seemed to me like a pretty good time to vámonos. I would have seen an opening talk by a Jeff Brateman but he was a no show. I did see Anthony Green speak on Roslyn and that was worth the trip. I will try to write up another blog posting on that later. I also saw a talk by a Devlin Liles called "The Inner Ninja: The Art of Code Productivity" which touched on good productivity habits such as just turning your cell phone off at work, etc.

Pardot

...not only allows you to both manage your SalesForce contacts and send them email campaigns, eliminating the need for vertical response or mail chimp. If you have forms on your web site which feed SalesForce contacts, Pardot should be yet another service to wrap that act and give you yet more analytics in the process.

Sunday, June 15, 2014

Swift

...is a Macintosh language which is supposed to replace Objective-C.

Thursday, June 12, 2014

an interesting pitfall in wiring up a client side event for a DevExpress control in C#

MyButton.ClientSideEvents.Click = String.Format("function(s,e){{Whatever({0},
      {1},{2},{3});}}", foo, bar, baz, qux);

 
 

What is above will work great if foo, bar, baz, and qux are all integers, but if qux is a string you will get an error message in the console telling you that qux cannot be made heads or tail of. The better thing to do in that scenario is:

MyButton.ClientSideEvents.Click = String.Format("function(s,e){{Whatever({0},
      {1},{2},'{3}');}}", foo, bar, baz, qux);

To compare revisions across numerous commits in TortoiseSVN...

  1. pick the "Show log" option
  2. select a revision
  3. click while holding Ctrl to select a second revision
  4. right-click and pick "Compare revisions"

Wednesday, June 11, 2014

EMV (Europay, MasterCard and Visa) chips are coming to credit cards which will make them more secure in card present (point of sale) scenarios wherein one may swipe a physical card at a machine.

This means that hackers will grow to see card not present (online sale) scenarios as more vulnerable to manipulation which is a switch from our modern day circumstance.

Pluck out just the immediate object from a list of T hydrating a DevExpress ASPxGridView in C#.

What follows kind of goes with this.

protected void FooGrid_CommandButtonInitialize(object sender,
      ASPxGridViewCommandButtonEventArgs e)
{
   var grid = sender as ASPxGridView;
   Foo foo = grid.GetRow(e.VisibleIndex) as Foo;

Tuesday, June 10, 2014

AS/400

...is the name for both an operating system and its scripting language. It came out in 1988 and came from IBM. There is ERP work which may be done with AS/400 but I don't know anything about it.

I learned of two interesting Chrome plugins today.

  1. Night Reading Mode inverts the colors you see. Black text in a white web page become white text in a black web page.
  2. Auto Refresh Plus is a hack to keep your session from expiring. It will set a timer that will refresh your browser as if you're pressing F5 on an interval of your choosing.

Setup a client side event at a DevExpress ASPxButton.

<dx:ASPxButton ID="Go" runat="server" AutoPostBack="false" Text="Go" >
</dx:ASPxButton>

 
 

What is above needs to become...

<dx:ASPxButton ID="Go" runat="server" AutoPostBack="false" Text="Go" >
   <ClientSideEvents Click="Whatever"></ClientSideEvents>
</dx:ASPxButton>

Trigger a CustomCallback on a DevExpress ASPxGridView and hand it a magic string.

If you have an ASPxGridView named MyGrid in an ASP.NET web forms project and you manually trigger its callback while passing it a magic string from the JavaScript side like so:

var myJunk = "fjsdojkslfjslfjsalf";
MyGrid.PerformCallback(myJunk);

 
 

...you may get "fjsdojkslfjslfjsalf" back into a variable on the C# side like this:

private void MyGrid_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
{
   string myJunk = e.Parameters;

how to cherry pick which children to manipulate with jQuery

<div id="x">
   <div>
      <span>Widget Count:</span>
   </div>
   <div>
      <span>PLACEHOLDER</span>
   </div>
</div>

 
 

Lets say we want to latch onto the outermost div above by its id and then reach down to the span containing "PLACEHOLDER" and swap out its copy. The way NOT to it is like so:

$('#x').children(2).children(1).html(count + " widgets");

 
 

What is immediately above will end up replacing the copy in BOTH span tags. The way to approach this challenge is like this:

$('#x').children().eq(1).children().eq(0).html(count + " widgets");

 
 

This reaches to ONLY the second child of the element decorated with the id of "x" and then reaches to the first child of the second child. There is another problem in that we could have "1 widgets" as a nonsensical note, but that is another thing for another blog posting perhaps. :)

There is no data remaining on your current plan. Would you like to add more data now? If you don't add now, you can do it later in Settings.

I got this error on my iPad while trying to connect to the internet yesterday. It turns out that when I got it (the iPad) from the Apple store that a second phone line was not set up for it with its own plan. Instead, a second phone line with an allotment of usage was set up. I had to call Verizon and straighten this out yesterday in order to see the internet again from the iPad. I need the iPad for work because this blog, where all of my notes are, is blocked from our LAN.

Saturday, June 7, 2014

Node.js is on version 0.10.28.

...but that hardly means that it is in Beta. There just hasn't been a breaking change yet in an upgrade. Their convention for versioning is MAJOR.MINOR.PATCH wherein only MAJOR changes are not downwards compatible. There have, thus, been ten MINOR releases. (Since the first??? Did the second number start at zero too?) This is another something I learned in this talk.

BEM (block, element, modifier) conventions help make CSS less ambiguous???

If something is a cascading effect wouldn't it be nice to just know by way of naming convention? That is what the BEM methodology is all about. This suggests that .block would effect an element directly, that .block__element would only effect all or certain children within the element it decorated, and that .block--modifier would effect an element directly yet is the sort of "modifier" that is a variation of .block. I learned of BEM for the first time at this talk.

In C#, a Count Lambda expression is going to return a total count across records where a criteria is matched.

http://msdn.microsoft.com/en-us/library/bb397687.aspx has a pretty good example of finding odd numbers which will put the value of 5 into a variable called "oddNumbers" in executing.

int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int oddNumbers = numbers.Count(n => n % 2 == 1);

Emails may be encrypted with PGP.

It's pretty good privacy. :P

TypeScript versus CoffeeScript

I saw half of a talk by a Mr. Jed Mao at the JavaScript Austin Meetup Group. The meeting was inside Volusion and Transverse sponsored (i.e. bought pizza for everyone). The talk was on Node.js but it delved into TypeScript too. Jed has authored an app in TypeScript and Node. Someone in the audience asked "Why TypeScript and not CoffeeScript?" or something comparable and Jed replied that he preferred TypeScript because it, as a language, was just JavaScript with some extra type semantics which compiled to JavaScript. If you dropped regular JavaScript into TypeScript it would compile and moreover just compile to an exact duplicate of the TypeScript code. The code for CoffeeScript is its own beast which cannot be mixed with JavaScript to be compiled to JavaScript. There is, thus, a heavier learning curve to commit to with CoffeeScript.

MapMyFitness

...makes mobile apps for tracking a run outdoors or maybe a bicycling outing. The company I am with used to office next to them but this past week has been the first week in a new building. One of my coworkers mentioned yesterday that he missed the MapMyFitness people. They used to be a PHP shop but they have started trying to distance themselves from PHP and to go the way of Python. I'd like to tell you that I've used their apps and that they are great, but I would have to upgrade my phone's iOS and leave the safety of version 5.1.1 to try them out. I'm not that curious. :P Strava is a rival product. I have used it. It seemed OK.

Get the "check all" checkbox working across all pages of pagination in a DevExpress ASPxGridView, understand the distinction between setTimeout and setInterval in JavaScript and pass a variable to a function called by setTimeout. Bonus: 32 is the spacebar keycode.

Alright, I have an ASPxGridView which starts out as seen below in ASP.NET markup. It is preceded by a hidden form field which I shall use as a backing store for state, specifically the state for if the "check all" checkbox should be checked or not. The string "true" or the string "false" will live inside the hidden form field. A trick like this is needed, as otherwise when one changes pages within the ASPxGridView's pagination, the "check all" checkbox will fall back into being unchecked.

<input type="hidden" value="false" ID="CheckAllCheckBoxStateManagement"
      runat="server" ClientIDMode="Static"/>
<dx:ASPxGridView AutoGenerateColumns="False" ID="MyGrid" ClientIDMode="Static"
      runat="server" KeyFieldName="FooId">
   <ClientSideEvents EndCallback="EndCallbackAct" />
   <Columns>
      <dx:GridViewCommandColumn ShowSelectCheckbox="true" Name="CheckAll"
            Width="5%" AllowDragDrop="False" VisibleIndex="0">
         <HeaderTemplate>
            <dx:ASPxCheckBox ID="CheckAllCheckBox" ClientIDMode="Static"
                  type="checkbox" runat="server" ToolTip="toggle me"
                  CssClass="TooltipCss">
               <ClientSideEvents CheckedChanged="CheckedChangedAct">
               </ClientSideEvents>
            </dx:ASPxCheckBox>
         </HeaderTemplate>
      </dx:GridViewCommandColumn>

 
 

Alright, clearly there are two client-side (JavaScript) events being defined here. I'll get to those in a moment, but it is also important to note that there is at least one server-side (C#) event in play too. It is wired up like so in C#:

MyGrid.CustomCallback += MyGrid_CustomCallback;

 
 

It has a signature like this and it will, by way of its code, either select all rows across all pages in the ASPxGridView's pagination (which do not have hidden checkboxes) or unselect all the rows. I have a different blog posting which details how this works.

private void MyGrid_CustomCallback(object sender,
      ASPxGridViewCustomCallbackEventArgs e)
{

 
 

...it is important to note that the MyGrid_CustomCallback server-side event will set off the EndCallbackAct client-side event when it ends which is defined in JavaScript like so:

function EndCallbackAct(s, e) {
   var isChecked = $('#CheckAllCheckBoxStateManagement').val();
   if (isChecked == 'true') {
      CheckAllCheckBox.SetChecked(true);
   } else {
      CheckAllCheckBox.SetChecked(false);
   }
}

 
 

EndCallbackAct is clearly reading from the hidden form field, but what writes to the hidden form field? The answer is the client-side event wired up to the "check all" checkbox, namely:

function CheckedChangedAct(s, e) {
   var isChecked = s.GetChecked();
   $('#CheckAllCheckBoxStateManagement').val(isChecked);
   MyGrid.PerformCallback(isChecked);
}

 
 

CheckedChangedAct, in its last line, kicks off MyGrid_CustomCallback, which either selects all selectable rows or unselects everything and then calls EndCallbackAct. That is the majority of the work to be done. The only outlier I saw was that if I unchecked a checkbox for a row in the ASPxGridView, it seemed to me like the "check all" checkbox should ALSO get unchecked so that it is no longer in an "everything is checked" state. Let's discuss how that may be facilitated. It is important to note that the HTML for the "check all" check box is going to look something like this:

<span class=" dxICheckBox_PortalDefault dxWeb_edtCheckBoxChecked_PortalDefault"
      id="CheckAllCheckBox_S_D">
   <span class="dxKBSW">
      <input id="CheckAllCheckBox_S" name="dnn$ctr2195$ViewWorkFlow
            $WorkFlowUC1$wfEnvironment$WorkFlowNav$GCTC2$TC
            $EnvironmentTemplateControls_8$certCallback$MyGrid$header0$TC$
            CheckAllCheckBox" value="U" type="text" readonly="readonly"
            style="opacity:0;width:1px;height:1px;position:relative;
            background-color:transparent;display:block;margin:0;padding:0;
            border-width:0;font-size:0pt;">
   </span>
</span>

 
 

The HTML for a checkbox for just selecting a row in the ASPxGridView will be as such. (Note that neither of these is really a checkbox in the traditional sense.)

<span class=" dxICheckBox_PortalDefault
      dxWeb_edtCheckBoxUnchecked_PortalDefault" id="MyGrid_DXSelBtn16_D">
   <span class="dxKBSW">
      <input id="MyGrid_DXSelBtn16" value="C" type="text" readonly="readonly"
            style="opacity:0;width:1px;height:1px;position:relative;
            background-color:transparent;
            display:block;margin:0;padding:0;border-width:0;
            font-size:0pt;">
   </span>
</span>

 
 

These two may vary in that they both may either have the dxWeb_edtCheckBoxChecked_PortalDefault class or the dxWeb_edtCheckBoxUnchecked_PortalDefault class depending on whether they appear as checked or not. Whenever I check one of the checkboxes, I check to see if it should uncheck the "check all" checkbox like so in JavaScript:

$(function() {
   $("input").live("focus", function () {
      var control = $(this);
      setTimeout(function () {
         UncheckCheckAllCheckboxIfApplicable(control);
      }, 200);
   });
   $("input").live("keydown", function () {
      var control = $(this);
      var key;
      if (window.event) {
         key = window.event.keyCode;
      } else {
         key = event.which;
      }
      if (key == 32) {
         setTimeout(function() {
            UncheckCheckAllCheckboxIfApplicable(control);
         }, 200);
      }
   });
});

 
 

Two acts do the same thing. A focus upon the control inside the "checkbox" HTML is one of the acts and the pressing of the spacebar to check or uncheck a "checkbox" is the other act. Both will delay for a fifth of a second before checking to see what class (dxWeb_edtCheckBoxChecked_PortalDefault or dxWeb_edtCheckBoxUnchecked_PortalDefault) is present at the "checkbox" giving other JavaScript mechanics time enough to change out the class if merited.

function UncheckCheckAllCheckboxIfApplicable(control) {
   control = control.parent().parent();
   var wrapper = control.parent().parent().parent().parent().parent().parent().parent().parent();
   if (control[0].className.indexOf("dxWeb_edtCheckBoxUnchecked_PortalDefault")
         >= 0) {
      if (control[0].id != "CheckAllCheckBox") {
         if (wrapper[0].id == "MyGrid") {
            if($('#CheckAllCheckBox').children(0)[0].className
                  .indexOf("dxWeb_edtCheckBoxChecked_PortalDefault") >= 0) {
               $('#CheckAllCheckBoxStateManagement').val('false');
               CheckAllCheckBox.SetChecked(false);
            }
         }
      }
   }
}

 
 

setTimeout unlike setInterval, is only going to run once. Hey, while we are discussing this, something else interesting that I learned how to do but never used was this:

ASPxCheckBox checkAllCheckBox =
      MyGrid.FindHeaderTemplateControl(MyGrid.Columns[0], "CheckAllCheckBox") as
      ASPxCheckBox;

 
 

Like so, one may latch onto the "check all" checkbox in C# to manipulate it.

Selectively select all rows in a DevExpress ASPxGridView (and not just all rows in the current page of pagination) with a custom callback.

Do something like this (only less corny).

private void MyGrid_CustomCallback(object sender,
      ASPxGridViewCustomCallbackEventArgs e)
{
   string isChecked = e.Parameters;
   if (isChecked == "true")
   {
      int counter = 0;
      while (counter < MyGrid.VisibleRowCount)
      {
         if (counter == 13 || counter == 42)
         {
            MyGrid.Selection.SelectRow(counter);
         }
         counter++;
      }
   } else {
      MyGrid.Selection.UnselectAll();
   }
}

 
 

Lead in like so:

<ClientSideEvents CheckedChanged="function(s,e)
      {MyGrid.PerformCallback(s.GetChecked());}">
</ClientSideEvents>

CustomCallback!

The CustomCallback for a DevExpress ASPxGridView may be prepped like so:

MyGrid.CustomCallback += MyGrid_CustomCallback;

 
 

...and like so:

private void MyGrid_CustomCallback(object sender,
      ASPxGridViewCustomCallbackEventArgs e)
{

 
 

In order to actually step into the method you're going to need to rickroll a client side event to this server side event like this:

<ClientSideEvents CheckedChanged="function(s,e) {MyGrid.PerformCallback(s.Value);}">
</ClientSideEvents>

unconditionally selecting all rows in a DevExpress ASPxGridView

The select everything across all rows with no exceptions version of the JavaScript function here is here:

function DoSomethingInJavaScript(s, e) {
   if (Foo.GetVisibleRowsOnPage() == 0)
      return;
   if (!s.GetChecked())
      Foo.UnselectRows();
   else {
      Foo.SelectRows();
   }
}

 
 

I must confess that the "check all" checkbox behaves badly and does not always stay checked when it should. I did not have much time to work on this.

Open the call stack in Visual Studio 2013.

At: DEBUG > Windows > Call Stack ...note that this option will only appear when debugging and that the topmost item in the call stack is the most recent method called with the following methods progressively working their way backwards in time to the point where you started debugging.

Act whenever a selection is made or unmade (by the checking or unchecking of a checkbox perhaps) at a DevExpress ASPxGridView.

Wire up an event on the C# side like so:

MyGrid.ClientSideEvents.SelectionChanged = "function(s,e){{ActOut(s,e);}}";

 
 

There needs to be a dance partner on the JavaScript side:

function ActOut(s, e) {
   alert(s.GetSelectedRowCount());
}

 
 

In this example whenever a selection is made or unmade the count of total selections will bubble up in an alert.

Change the CSS class of div made into a web forms control in C#.

<div id="Whatever" runat="server" class="displaynone">
   The quick red fox jumps over the lazy brown dog.
</div>

 
 

What is above may be manipulated like so.

private void Tweak(int foo)
{
   if (foo > 0)
   {
      Whatever.Attributes["class"] = "";
   } else {
      Whatever.Attributes["class"] = "displaynone";
   }
}

 
 

See also my trick for manipulating styles here.

A DevExpress ASPxNavBar is, I think, a bar one may click to make an expandable area expand into view or collapse away from view.

<dx:PanelContent>
   <dx:ASPxNavBar ID="MyNav" runat="server" EnableCallBacks="true" Width="100%"
         ClientInstanceName="MyNav" RenderMode="Lightweight">
      <ClientSideEvents EndCallback="Whatever" />
      <GroupContentTemplate>
         <asp:Panel ID="WorkFlowTemplatePanel" runat="server">
         </asp:Panel>
      </GroupContentTemplate>
   </dx:ASPxNavBar>
</dx:PanelContent>

HtmlDataCellPrepared versus HtmlRowPrepared at DevExpress ASPxGridViews

I had a problem in crafting hyperlinks within a DevExpress ASPxGridView like this in that when I had a JavaScript effect which had to happen upon a mouseover like so:

hyperLink.Attributes.Add("onmouseover", String.Format("ShowToolTips('{0}','{1}',',')", hyperLink.ClientID, _errors));

 
 

...there was a problem! One had to click in the page before the mouseover effect would work! At my wireup like this...

Foo.HtmlDataCellPrepared += Foo_HtmlDataCellPrepared;

 
 

...which used a method such as this...

private void Foo_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e)
{

 
 

...I ended up giving up on an expectation of hyperlink management. I instead added a new wireup like this...

Foo.HtmlRowPrepared += Foo_HtmlRowPrepared;

 
 

...which used a method such as this...

private void Foo_HtmlRowPrepared(object sender, ASPxGridViewTableRowEventArgs e)
{

 
 

...which could affect a column like this...

<dx:GridViewDataTextColumn Caption="Validation" Width="80px">
   <DataItemTemplate>
      <asp:HyperLink ID="ValidationLinkButton" runat="server" CausesValidation="false"
            CssClass="FooErrorLink">
      </asp:HyperLink>
   </DataItemTemplate>
</dx:GridViewDataTextColumn>

 
 

...like so:

private void Foo_HtmlRowPrepared(object sender, ASPxGridViewTableRowEventArgs e)
{
   var grid = sender as ASPxGridView;
   if (grid == null) return;
   var hyperLink = grid.FindRowCellTemplateControl(e.VisibleIndex, null,
         "ValidationLinkButton") as HyperLink;
   if (e.RowType == GridViewRowType.Data && hyperLink != null)
   {
      var foo = grid.GetRow(e.VisibleIndex) as Foo;
      if (!string.IsNullOrEmpty(foo.FlattenedErrorList))
      {
         hyperLink.Text = "Error";
         hyperLink.Enabled = false;
         hyperLink.Attributes.Add("onmouseover", String.Format("ShowToolTips('{0}','{1}',',')",
               hyperLink.ClientID, _errors));
      } else {
         hyperLink.Visible = false;
      }
   }
}

 
 

Hmmm... as I type this I'm not sure this had to be done. I also changed a CSS class at the links and that helped big. :P

Monday, June 2, 2014

Spin up two threads in C# and wait for them both to finish before proceeding.

I opened up C# 4.0 in a Nutshell by Joseph and Ben Albahari again today. In stared at pages 833 and 835 and then wrote this:

using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Web.Mvc;
namespace YingYang.Controllers
{
   public class HomeController : Controller
   {
      static EventWaitHandle _waitForYing = new AutoResetEvent(false);
      static EventWaitHandle _waitForYang = new AutoResetEvent(false);
      private const int _yingSleep = 3000;
      private const int _yangSleep = 4000;
      
      public ActionResult Ying()
      {
         new Thread(Yang).Start();
         using (Stream x = new FileStream(@"C:\Apps\YingYang\ying.txt",
               FileMode.Append))
         {
            byte[] foo = ASCIIEncoding.ASCII.GetBytes(DateTime.Now.ToString() + "\r\n");
            x.Write(foo, 0, foo.Length);
            Thread.Sleep(_yingSleep);
            byte[] bar = ASCIIEncoding.ASCII.GetBytes(DateTime.Now.ToString() + "\r\n");
            x.Write(bar, 0, bar.Length);
            Thread.Sleep(_yingSleep);
            byte[] baz = ASCIIEncoding.ASCII.GetBytes(DateTime.Now.ToString() + "\r\n");
            x.Write(baz, 0, baz.Length);
            Thread.Sleep(_yingSleep);
            byte[] qux = ASCIIEncoding.ASCII.GetBytes(DateTime.Now.ToString() + "\r\n");
            x.Write(qux, 0, qux.Length);
            Thread.Sleep(_yingSleep);
         }
         _waitForYing.Set();
         _waitForYang.WaitOne();
         return View(DateTime.Now);
      }
      
      static void Yang()
      {
         using (Stream x = new FileStream(@"C:\Apps\YingYang\yang.txt",
               FileMode.Append))
         {
            byte[] foo = ASCIIEncoding.ASCII.GetBytes(DateTime.Now.ToString() + "\r\n");
            x.Write(foo, 0, foo.Length);
            Thread.Sleep(_yangSleep);
            byte[] bar = ASCIIEncoding.ASCII.GetBytes(DateTime.Now.ToString() + "\r\n");
            x.Write(bar, 0, bar.Length);
            Thread.Sleep(_yangSleep);
            byte[] baz = ASCIIEncoding.ASCII.GetBytes(DateTime.Now.ToString() + "\r\n");
            x.Write(baz, 0, baz.Length);
            Thread.Sleep(_yangSleep);
            byte[] qux = ASCIIEncoding.ASCII.GetBytes(DateTime.Now.ToString() + "\r\n");
            x.Write(qux, 0, qux.Length);
            Thread.Sleep(_yangSleep);
         }
         _waitForYing.WaitOne();
         _waitForYang.Set();
      }
   }
}

 
 

ying.txt ended up with this in it when I ran the app I made:

6/2/2014 6:01:00 PM
6/2/2014 6:01:03 PM
6/2/2014 6:01:06 PM
6/2/2014 6:01:09 PM

 
 

yang.txt ended up with this in it when I ran the app I made:

6/2/2014 6:01:00 PM
6/2/2014 6:01:04 PM
6/2/2014 6:01:08 PM
6/2/2014 6:01:12 PM

 
 

The DateTime value which makes it into the view ends up being coughed up as a string to the user and it looks like this:

6/2/2014 6:01:16 PM

 
 

If _yangSleep is set to 2000 instead, the application doesn't behave appreciably different. Both text files will still end up with dates in them which come before the date that ends up making its way into the UI's HTML. Both threads finish their file I/O mechanics before this line of code is ever run:

return View(DateTime.Now);

 
 

This outcome will happen without regard to which thread is speedier in getting its work done.