Thursday, January 31, 2019

Use ClosedXML to make sense of an .xlsx extension Excel sheet in a stream of bytes slurped from a file control in C#.

In the app I am working on I just use a Razor form like the one here in a .NET Core MVC project. I grab ahold of the file a user finds like so at a controller action:

[Authorize(Policy = "AdminOnly")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Uploading(IFormFile CsdmeNcoaData)
{
   if (CsdmeNcoaData != null)
   {
      string[] piecesOfFileName = CsdmeNcoaData.FileName.Split('.');
      string extension = piecesOfFileName[piecesOfFileName.Length
            - 1].ToLower().Trim();
      if (extension == "xlsx")
      {
         using (var reader = new StreamReader(CsdmeNcoaData.OpenReadStream()))
         {
            using (var memoryStream = new MemoryStream())
            {
               var buffer = new byte[CsdmeNcoaData.Length];
               var bytesRead = default(int);
               while ((bytesRead = reader.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
               {
                  memoryStream.Write(buffer, 0, bytesRead);
                  ExcelHelper.CdsmeNcoaImport(memoryStream);
               }
            }
         }
         ViewBag.Xlsx = "The file was processed.";
      }
      else
      {
         ViewBag.Xlsx = "The file uploaded did not have the .xlsx extension.";
      }
   }
   else
   {
      ViewBag.Xlsx = "No file was uploaded.";
   }
   return View();
}

 
 

I then hand into static utility the MemoryStream above like so:

using System.IO;
using ClosedXML.Excel;
namespace Foo.Bar.Baz.Qux
{
   public static class ExcelHelper
   {
      public static void CdsmeNcoaImport(MemoryStream memoryStream)
      {
         using (XLWorkbook excelWorkbook = new XLWorkbook(memoryStream))
         {
            foreach (IXLWorksheet worksheet in excelWorkbook.Worksheets)
            {
               foreach (IXLRow row in worksheet.Rows())
               {
                  foreach (IXLCell cell in row.Cells())
                  {
                     string setting = cell.Value.ToString();

 
 

It is important to note that the first blob of code above is in a .NET Core project while the second is in a .NET Framework project. I installed ClosedXML (to the .NET Framework project) from the NuGet command prompt with this command line command:

install-package ClosedXML Foo.Bar

Wednesday, January 30, 2019

When you add one Entity Framework 6 migration and then turn around and have to add another because you realize your column deserves a better name...

Well, you don't really want two migrations back-to-back where a column is added and then removed again do you? Really the two migrations should be cleaned up into one migration. Here is how you do that:

  1. Roll the database back to two migrations ago.
  2. Manually delete the two files which inherit from DbMigration which hold the latest two migrations.
    namespace Peeps.Business.Migrations.Peeps
    {
       using System;
       using System.Data.Entity.Migrations;
       public partial class AddNicknameToContacts : DbMigration
       {
          public override void Up()
          {
             AddColumn("dbo.Contacts", "Nickname", c => c.String());
          }
          
          public override void Down()
          {
             DropColumn("dbo.Contacts", "Nickname");
          }
       }
    }
  3. Create a new migration, making a file like so:
  4. Update the database anew.

The thing NOT to do is to manually doctor up a migration's C# and remove the creation or destruction or both of a column. This will come back to bite you. Entity Framework will end up complaining that it cannot deal with the column somehow in a later migration.

Tuesday, January 29, 2019

Write a unit test which will crawl all of your AutoMapper mappings and make sure nothing is missing!

When you add a new column to a database table and, along those lines, a new getsetter at a corresponding POCO, well, you'd better not leave it out of any of your AutoMapper mappings that use that type or else this test will break, well, unless you have the .ForAllOtherMembers(opt => opt.Ignore()) trick the mappings that might otherwise squawk.

using Smorgasbord.Features.Common;
using Xunit;
namespace Smorgasbord.Tests.Features.Common
{
   public class AutoMapperProfileConfigurationTests
   {
      [Fact]
      public void AutoMapperConfiguration_IsValid()
      {
         var config = new AutoMapper.MapperConfiguration(cfg =>
         {
            cfg.AddProfile(new SmorgasbordConfiguration());
         });
         var mapper = config.CreateMapper();
         mapper.ConfigurationProvider.AssertConfigurationIsValid();
      }
   }
}

 
 

SmorgasbordConfiguration here would inheirt from AutoMapper.Profile and live in the Smorgasbord.Features.Common namespace. Best unit test ever?

Is Paul Miami a real name?

The [ValidateRecaptcha] attribute at controller actions in the .NET Core project I am looking at seems to come from the PaulMiami.AspNetCore.Mvc.Recaptcha namespace. I wonder if this is the source code for this magic. <recaptcha /> appears in MVC views to make the control appear at that spot in the HTML.

Areas are logical collections of controllers in the name of splitting numerous controllers up into groupings in lieu of just having dozens of controllers sprinkled together.

Denote the area for a controller at an attribute like so in a .Net core project:

[Area("Frontend")]
[Route("Classes")]
public class WorkshopsController : Controller
{

Razor style menu item!

<li class="@Html.IsSelected(action: "Upload")" policy="@Policy.AdminOnly">
   <a asp-controller="Reports" asp-action="Upload">Upload</a>
</li>

Monday, January 28, 2019

Rollback to a particular migration with Entity Framework 6!

At the NuGet console command line...

EntityFramework\Update-Database -TargetMigration:"Yin"
      -ConfigurationTypeName "Yang" -Force

when the insert key and the delete key are the same key

Turn off overtype mode by pressing fn with the delete key.

Sunday, January 27, 2019

Parasoft SOAtest

It's a tool for testing APIs.

[NotMapped]

Put this attribute at a C# POCO's getsetter to prevent the .NET Core implementation of Entity Framework 6's code first paradigm from making a database column in a migration for as much.

Saturday, January 26, 2019

Edited in both

Alright we see this error and prompt of "Manually resolve these conflicts and push new changes to the source branch." at Azure DevOps when we push up from GitHub Desktop and there is a merge conflict. You can pull the branch you wish to merge against down into your current branch with GitHub Desktop or with a command tool such as Git Bash like so:

git pull origin WHATYOUWANTTOMERGEAGAINST

 
 

Resolve your conflicts and recommit!

IBM FlashSystem

These are just products that use flash memory and solid state stuff.

Friday, January 25, 2019

options for Verify in MOQ 4.8.0.0

If you do something like this to verify that the Rollback method on your mock has never been run:

myMock.Verify(x => x.Rollback(), Times.Never);

 
 

Alright, what are the options for Times here? They are:

  1. Times.AtLeast(13)
  2. Times.AtLeastOnce
  3. Times.AtMost(27)
  4. Times.AtMostOnce
  5. Times.Between(42, 69, Range.Inclusive)
  6. Times.Exactly(86)
  7. Times.Never
  8. Times.Once

 
 

.Inclusive here will include the forty-two and the sixty-nine along with forty-three to sixty-eight while .Exclusive would include everything between these two numbers.

AggregateException

This shows up in unit tests when multiple exceptions are thrown. You don't want to validate for this in a unit test. You want to be more specific. I notice that .ReturnsAsync is a thing too elsewhere in MOQ in similar tests... I digress.

Thursday, January 24, 2019

Simple moment formatting.

var yin = moment(yang).format('L');

... is just going to give you something easy like 01/24/2019 that is to the point. The L reminds me of the X in that regard.

Wednesday, January 23, 2019

yadcf

Yet Another DataTables Column Filter is a jQuery plugin.

 
 

Addendum 1/24/2019: Make a date column sort in descending order by default at a yadcf amid Razor and jQuery.

  • Map the your date to a string when casting from your POCO to your DTO with Automapper. If you cannot live without a real date at your view model you are going to have to have a second property for a stringified date.
  • Doctor up your stringified date like so:
    int counter = 1000000;
    myCollection.ForEach(x =>
    {
       x.MyDate = $"<span style='display:none;'>{counter.ToString()}
             </span> {x.MyDate}";
       counter++;
    });

    This allows for ascending sorting based on the hidden counter which fakes descending sorting for the date.
  • At the yadcf this column...
    { title: 'My Date', name: 'MyDate', data: 'myDate' },
    ...must become...
    { title: 'My Date', name: 'MyDate', data: 'myDate',
          render: (data, type, full) => `${data}` },

    The full here variable is kind of interesting. You may dot off of it and get at other properties for the object. I don't know what type does.

.ToListAsync()

In C# this makes a Task<List<YourThingHere>> off of an IQueryable.

Inject an ordering into a .SelectMany in C#!

private IQueryable<Cat> GetCatsForUser(int id)
{
   return _context.Users.Where(u => u.Id == id).SelectMany(u => u.Cats).Distinct();
}

 
 

...becomes:

private IQueryable<Cat> GetCatsForUser(int id)
{
   return _context.Users.Where(u => u.Id == id).SelectMany(u =>
         u.Cats).Distinct().OrderByDescending(r => r.BirthDay);
}

 
 

Something NOT to do is:

private IQueryable<Cat> GetCatsForUser(int id)
{
   return _context.Users.Where(u => u.Id == id).SelectMany(u =>
         u.Cats.OrderByDescending(r => r.BirthDay)).Distinct();
}

 
 

Distinct is for removing dupes.

Tuesday, January 22, 2019

FOR XML AUTO

...in T-SQL this will take a SELECT statement and return it as XML. This has some notes on as much.

 
 

FOR XML PATH('YourNameHere')

...in contrast specifies a specific type of XML formatting.

 
 

FOR XML PATH('YourNameHere'), ROOT('Taco')

...moreover creates a root XML node of Taco to wrap the other nodes.

If the control, its label, and its validation control are all wrapped together in a div with display: none; on it in an MVC view...

Well, the validation won't validate. This can be a blessing in disguise. Unhide the div when you are ready. An example of what I'm talking about is...

<div style="display: none;" id="unhideMe">
   <label asp-for="@Model.Yin"></label>
   <select asp-for="@Model.Yin" asp-items="@Model.Yang" required>
      <option value="">-- Please Select --</option>
   </select>
   <span asp-validation-for="@Model.Yin"></span>
</div>

 
 

The required keyword is legit HTML. I'm not sure how it does its magic. This has some more on it and it basically says that the first setting in the dropdown list has to be an empty value.

soft skills

This is the part of the interview that is not tech questions but is instead stuff like "What would you say your biggest weaknesses are?" and "What do you do to promote a good culture?"

Monday, January 21, 2019

Select2 is a would-be better-than-before select list in the jQuery space.

This has some notes on it and just as you might otherwise have...

$("#changeme")[0].change(funtion() { ...

 
 

...you may now have...

$("#changeme")[0].select2(funtion() { ...

 
 

...but I'm not yet sure how this is different than the change approach or what the benefit is.

SOX Compliance

SOX just stands for Sarbanes–Oxley. You don't need SOX compliance for a rolodex app, but any app that has financial records requires auditability to trace back how the various transactions happened.

Sunday, January 20, 2019

How may I have two actions with the same verb in same controller in a .NET Core application?

You need to differentiate the two as otherwise you just get a confusing CORS error when you try the verb. The differentiation needs to be route based:

[Route("api/President")]
public class PresidentController : Controller
{
   public IFlatFileMechanics _flatFileMechanics;
   
   [HttpPut]
   public ObjectResult Put([FromBody] List<President> presidents) {
      _flatFileMechanics.SetPresidents(presidents);
      return Ok(null);
   }
   
   [HttpPut("{id}")]
   public void Put(string id, [FromBody] President president)
   {

 
 

What you cannot do is method overloading. I tried that and there probably isn't any way for .NET Core to know what's in a JSON object proactively in advance of you landing at an API endpoint.

Friday, January 18, 2019

The major menu items in Azure DevOps seem to be...

  1. Overview
  2. Boards
  3. Repos
  4. Pipelines
  5. Test Plans
  6. Artifact

Overview has things like the Wiki and also Dashboards where I suppose you may make a dashboard with some quick reference graphs for reporting on the project. Boards has a "Boards" option inside of it where one sees cards for the various stories in various swim lanes. There are also Work Items, Backlog, and Sprints submenu items here that have plain Jane lists of the things you might expect. Repos has interface access to the file repository at GitHub. There is a Pull requests submenu item here where one goes to create pull requests when one commits a branch to source control. The continuous integration machinery is at Pipelines.

A PLM will manage a software product from upfront brainstorming to development to rollout to retirement.

PTC Windchill, Siemens Teamcenter, and Dassault Systèmes Enovia and examples. PLM stands for Product Lifecycle Management Software and PTC for Parametric Technology Corporation.

.AsNoTracking() in Entity Framework 6

This will return a collection without any second level cache madness going on.

.ReverseMap() in AutoMapper

CreateMap<Person, PersonViewModel>()
   .ForMember(vm => vm.Yin, opt => opt.MapFrom(src => src.Yang))
   .ForMember(vm => vm.SomethingElse, opt => opt.Ignore())
   .ReverseMap();

 
 

What does this do? Alright, if Person has a getsetter for Address that is of an Address type and the Address type has a City, and what is more PersonViewModel has an AddressCity getsetter well the City property on the Address property on Person is gonna get mapped to AddressCity per the AutoMapper convention right? This is the flattening associated with the tool. Those fields are not called out in the example above but, as .ForAllOtherMembers(opt => opt.Ignore()) is not used, the fields which can be mapped by naming convention will be. The two types in the generic for CreateMap correspond generically to TSource and TDestination IN THAT ORDER so Person is getting mapped to PersonViewModel here right? Well with .ReverseMap() in the mix the one-way mapping becomes a two-way rule as best as I can tell allowing PersonViewModel to be mapped back to Person complete with unflattening! The CreateMap implementations may show up in mass in a method in an implementation of the Profile type in the Automapper namespace and to keep things from being reduantly verbose we have this trick it would seem.

I have a reputation of 6 on Stack Overflow!

Look! I found myself! It looks like I asked a question back in 2009. I wondered why this only worked in Firefox?

$(":text:visible:enabled:first").focus();

 
 

2009 huh? I guess I should dust off my iPod. Honestly, I never owned an iPod and I had the original iPhone during that year. That year I got divorced. Two years later, I would start a blog called "Whatever" because Jagruthi Mamidi, who I worked with, said "Whatever" all the time and I would use this blog for all of my notes instead of Stack Overflow like everyone else. Eventually, I would earn the nickname "Spaghetti Tom" and learn that someone else had a "Whatever" blog so there was a name change. I can't remember who the other guy was. He is a SciFi (science fiction) writer. Cash for clunkers in 2009? My "clunker" got me a rep of 6!

Thursday, January 17, 2019

When fishing out the value of a control by id in modern query you have to drill into an array of one item.

var defaultQtyPerItem = $("#DefaultQtyPerItem").val();

 
 

At some point what's above became what is below. Don't ask me when.

var defaultQtyPerItem = $("#DefaultQtyPerItem")[0].value;

Cast a string to a boolean value in jQuery.

var lockDefaultItemQty = ($("#LockDefaultItemQty")[0].value.toLowerCase() === 'true');

old school jQuery UI numeric control

Before input HTML tags with a type setting of "number" were widely supported by browsers, you could make a regular "text" type input and then dress it up in jQuery UI like so:

$("#MinInventoryOrder").spinner({ min: 0, max: 1000 });

 
 

Set the value of the spinner like so:

$("#MinInventoryOrder").spinner("value", number);

The version of Entity Framework that is EF Core 2 and better allows for merge conflicts with migrations to be resolvable.

This was not doable in Entity Framework 6 as if two developers were checking in two branches to merge that each had a migration there was not a way to make sense of the ordering and basically one of the two developers had to back down in the short term. The ordering is now, in modernity, kept in a JSON file and you can obviously do merges against that.

Wednesday, January 16, 2019

ViewData.TemplateInfo.HtmlFieldPrefix in Razor

for="@(ViewData.TemplateInfo.HtmlFieldPrefix)[@i]_TextValues[0]"

 
 

Alright in the line above, the...

@(ViewData.TemplateInfo.HtmlFieldPrefix)

 
 

...part of all this in a partial can be set with a third parameter where the partial is called like so:

@Html.Partial("SurveyPartial", Model.PostSurveyQuestions,
      nameof(Model.PostSurveyQuestions))

 
 

"PostSurveyQuestions" is the magic string in this case.

Tuesday, January 15, 2019

passwordless login?

I heard about this today from my superior. You don't have to have a password, just an email address. You will be emailed a link to use to enter app. You'll request a link every time you enter, etc.

Set references to primary keys in other tables at a POCO in Entity Framework 6's code first approach to thing.

public class ProgramSurvey
{
   [Key, Column(Order = 1)]
   public int ProgramId { get; set; }
   public virtual Program Program { get; set; }
   
   [Key, Column(Order = 2)]
   public int SurveyTypeId { get; set; }
   public virtual SurveyType SurveyType { get; set; }
   
   [Key, Column(Order = 3)]
   public int QuestionId { get; set; }
   public virtual Question Question { get; set; }

Open Graph Tags

These are some tags you can put in your web site that will make a link shared over Facebook make a little more sense to Facebook and people viewing Facebook. A post with a video clip may just show the video clip as if embedded right there in Facebook for example and there are other could-be dressups along these lines, etc. See: https://developers.facebook.com/docs/sharing/webmasters and https://developers.facebook.com/docs/sharing/opengraph/using-objects/

DML stands for Data Manipulation Language and DDL for Data Definition Languages.

In T-SQL DML would be for CRUD commands against records while DDL has to do with the T-SQL to make a table and adding and dropping columns and the like.

canonical data model

In API design a CDM is a model that is independent of specific applications. The model should be human-readable and make sense standalone.

Monday, January 14, 2019

when Visual Studio 2019 Preview tells you that your test projects are incompatible...

...by putting the work incompatible in parenthesis by the name of the project in the Solution Explorer:

  1. install more stuff with the installer (I cannot tell what the magic ingredient is specifically.)
  2. reopen Visual Studio and right-click on the projects with (incompatible) by them
  3. there will be an option to make the (incompatible) go away

System.Net.Sockets.SocketException: 'No connection could be made because the target machine actively refused it'

Alright this, is the first error I started to see in Visual Studio 2017 when I started to work with a Visual Studio 2017 solution which had been updated to the Visual Studio 2019 Preview by someone else. When I unchecked the checkbox for "Break when this exception type is thrown" there were a series of other wacky error messages downstream of this. The fix is to get modern Visual Studio. It's 2019 people! Oh, one of the wacky error messages, the second after the socket exception, suggested that it could not find an Edmmetadata table which doesn't exist in our databsae anyways. I guess we lost all of our notes from the rave. EDM = electronic dance music ???

Switch CSS?

Alright "ASP.NET Core 2 and Angular 5" by Valerio De Sanctis suggests this is a fourth alternative alongside Sass, LESS, and Stylus. I cannot find it in Googling and it would not be the first time the book has lied to me. The same page (275) also suggests LESS Compiler by Mads Kristensen as a good plugin for Visual Studio for getting LESS to CSS compilation to work.

Matt and Megan move

I saw on Facebook over the weekend that Matt Underwood and Megan Mohajer have moved to Houston so if I visit Austin anew I won't see them and it won't feel like Austin. It was Megan who gave me the nickname "Spaghetti Tom" and she is pictured waving here with her best friends Christina Milstone at right and Angela Golemi doing the thumbs up.

I found this old photo in my Facebook photos. I took it on 12/17/2013 which was Matt's 25th birthday. This was at a party at the Trudy's at Burnet and 183.

Sunday, January 13, 2019

I need to learn React, but do I need to learn it right now?

I'm not sure. A former coworker showed me codesandbox.io code for his React projects and in wondering how to get started I found this which suggests you should update Node and npm and then run these three commands at a command prompt:

  1. npx create-react-app my-app
  2. cd my-app
  3. npm start

Alright, this should spin up a browser pointed to http://localhost:3000/ are therein you will see a page prompting you to change the App.js file inside of the src folder immediately inside of the outermost project folder you just made. I have not gotten to the changes yet. When I look at this file I see:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
   render() {
      return (
         <div className="App">
            <header className="App-header">
               <img src={logo} className="App-logo" alt="logo" />
               <p>Edit <code>src/App.js</code> and save to reload. </p>
               <a className="App-link" href="https://reactjs.org" target="_blank"
                     rel="noopener noreferrer" > Learn React </a>
            </header>
         </div>
      );
   }
}
export default App;

Saturday, January 12, 2019

To make a recommendation for someone on LinkedIn...

  1. Go to their profile.
  2. Click the "More..." button by their avatar.
  3. Pick "Recommend" in the little menu that appears.

I don't normally write praise for others, but I did just now for Veena Nagendrappa and I had to figure out how to do so. As much as I use LinkedIn, this is one thing I hardly do with it.

Friday, January 11, 2019

System.Text.Encoding.CodePages is going to work in .NET Core and not .NET Framework.

StreamWriter.Encoding might be something to try if you need something to work in both (for encoding).

ReactJS supports the spread operator in JavaScript!

I don't understand it yet.

Push stuff up to Google Drive!

Go to https://www.google.com/drive/ and if this is your first time to visit you'll see a bunch of flashing ad graphics for Google Drive so just click "Go to Google Drive" at upper right to get to the normal UI (user interface). Click the "New" button at the upper left to upload something. After you have uploaded something, right-click on the icon that look like two horizontal hotdogs above a downward pointing arrow, kinda like a military badge, to get a little menu with "Get shareable link" in it which should allow you to procure a URL to advertise the file to others with. You will need to go back to this same menu and click "Share" instead of "Get shareable link" to spec whom may have access to the file as, to start with, outsiders will not have access.

Windows-1252 "is probably the most-used 8-bit character encoding in the world" per Wikipedia.

The ISO-8859-1 standard for ANSI (American National Standards Institute) is similar.

Check to see if a column exists at a table in T-SQL!

IF NOT EXISTS(
   SELECT * FROM INFORMATION_SCHEMA.COLUMNS
   WHERE TABLE_NAME = 'Customer' AND COLUMN_NAME = 'Address2'
   ) ALTER TABLE Customer ADD Address2 varchar(255) null

.dbml is kinda like the .edmx of LINQ to SQL.

There is not a GUI visual tool however. It will have a designer.cs file in it with all of the data fed classes. These are partials and you may extend each of them with your own partial in a different file that will not get replaced when the database changes and updates the .dbml stuff. This is very three layers, huh? No onion architecture here. No seperation between POCOs and their database implementation. Have fun writing unit tests around that! You may need to install the "LINQ to SQL tools" in Visual Studio to update the .dbml from your schema.

When you map to DTOs from Entity Framework you're going to have to do some righthand/lefthand stuff when you go back to Entity Framework.

If I get a Person from Code First Entity Framework and I use AutoMapper to cast it to a PersonViewModel and then the PersonViewModel makes its way up to a form in an ASP.NET MVC view and then the modified PersonViewModel is rolled back into a Person shape with AutoMapper, the reference to Entity Framework is going be lost right? I have a new Person at this point and I have to query the same Person with Entity Framework and then map the properties off of the altered Person to the queried Person. I see little escape.

Thursday, January 10, 2019

another shape of Html.DropDownList in Razor

@Html.DropDownList("ddlCountryCodes", (SelectList) ViewBag.CountryCodes)

 
 

Also, here is an example of hydrating the SelectList...

List<Country> countries = repository.ActiveCountryCodes();
ViewBag.CountryCodes = new SelectList(countries, "ERPCode", "Name", "");

 
 

Note that the four parameters are:

  1. the collection
  2. the getsetter on the POCO for the dropdown behind-the-scenes value
  3. the getsetter on the POCO for the dropdown public-facing value
  4. the setting itself

There is a canned "Calendar" app at Windows 10 and you may see it by typing "Calendar" at the start bar.

When you double-click an .ics file and you're using gmail instead of Outlook, the .ics file will try to use the "Calendar" app and will have an option to sync up to the Google calendar.

You cannot email a .zip file with an .exe file inside of it with gmail.

You cannot even do the usual hack where you change the .zip extension to something else.

Wednesday, January 9, 2019

Disable All Breakpoints

Just as there is a Delete All Breakpoints in the Debug menu in Visual Studio 2017 there is also a Disable All Breakpoints and it does what you might think allowing for a placeholder for a breakpoint that does not actually act as breakpoint until you pick Enable All Breakpoints which is what Disable All Breakpoints toggles to and from in the Debug menu. The disabled breakpoints appear as hollowed see-through circles with a red outline instead of solid red circles.

MessageBox.Show is the alert of WinForms!

alert("look at me!");

 
 

The JavaScript above has a counterpart in the C# below which will make like a little modal within a WinForm appear. The first parameter is the guts of the message and the second is what goes in the title bar of the box.

MessageBox.Show("look at me!", "Attention:");

The provided URI scheme 'http' is invalid; expected 'https'. Parameter name via

I get this error at a WinForms app which looks to an .asmx for interact with the data and everything beyond itself. The end of the app.config file looks like so:

   <system.serviceModel>
   <bindings>
      <basicHttpBinding>
         <binding name="BulkServiceSoap">
            <security mode="Transport" />
         </binding>
         <binding name="BulkServiceSoap1" />
      </basicHttpBinding>
   </bindings>
      <client>
         <endpoint address=" http://localhost:3908/BulkService.asmx"
               binding="basicHttpBinding" bindingConfiguration="BulkServiceSoap"
               contract="BulkUploadService.BulkServiceSoap" name="BulkServiceSoap" />
      </client>
   </system.serviceModel>
</configuration>

 
 

The http://localhost:3908/BulkService.asmx is a replacement for the production .asmx which has an https address. I just changed bindingConfiguration="BulkServiceSoap" to bindingConfiguration="BulkServiceSoap1" to dumb down the security. Do you see why? This tipped me off suggesting WebHttpSecurityMode.Transport was the villian.

You are debugging a Release build of BulkUploader.exe. Using Just My Code with Release builds using compiler optimizations results in a degraded debugging experience (e.g. breakpoints will not be hit).

Pick the option for disabling "Just My Code" to wiggle free from this.

Did you know that you may make any HTML tag in a web form into a web forms control by putting runat="server" inline in it?

Then from the C# code behind you may do things like set the .Visible equal to false, etc. There are a few common things one may generically do with any control such as set the Visible setting. You will also need an ID="yournamehere" inline setting to give a handle to use at the server side.

Tuesday, January 8, 2019

LESS options switches!

"ASP.NET Core 2 and Angular 5" by Valerio De Sanctis gives more detail than I expected on LESS importing on pages 270 and 271. For example this...

@import "watermelon";

 
 

...and this:

@import "watermelon.less";

 
 

...in a LESS (Leaner Style Sheets) file, turns the guts of the LESS content into CSS and injects it into the file made when the referencing file gets made into CSS too while...

@import "watermelon.css";

 
 

...merely loops in some CSS. Alright, that's not crazy, but did you know that you may have options switches like so?

@import (less,css,optional) "watermelon.css";

 
 

The options are:

  • reference references the other file externally like the CSS @import flavor of things
  • inline does not cast LESS to CSS in importation
  • less imports as if .less without regard to extension
  • css imports as if .css without regard to extension
  • once will restrict the number of times the content may be spliced in to once
  • multiple will have multiple copies of the same content in the file getting the splice in if applicable
  • optional means do not break the compiler if you can't find it

Monday, January 7, 2019

If you drag icons into a little folder that you've made at your Galaxy phone you may have some heartache in getting them back out again.

A coworker was fighting with this today. I found the following in Googling and trying to be helpful:

The second of these links suggests there may be an Edit button (at the Apps screen that you may get to in pressing the Apps icon at the lower right) to touch at the upper right to allow the icon in a folder to be dragoutable. I don't really know what I am talking about because I don't have an Android.

Sunday, January 6, 2019

I am hearing that the OnePlus is a pretty good modern Android phone.

It apparently costs half of the thousand dollars I spent on my iPhone X and is pretty solid. I wonder if Apple is pricing themselves out of the phone game. I run into kids who have restaurant jobs and the like all the time who just can't afford iPhones and seem fine without them.

Comments in LESS can be denoted with a double forward slash.

You may also use the forward slash followed by an asterisk trick to open a comment that you may use in CSS too wherein you close off such a comment with an asterisk followed by a forward slash, but in plain CSS the double-forward slash comments we associate with C# are not legit. They are in LESS however. This is more knowledge from "ASP.NET Core 2 and Angular 5" by Valerio De Sanctis.

random stupidity

I'll share a couple of random adventures with you. I was just at Uptown Diner tonight and one of these guys brought in a brown bag of food from elsewhere and planned to eat from it at the table with his friends. A waitress told him he could not bring in outside food and eat it inside so he stood outside of the window at the table and ate with his friends that way.

On August 1st of last year, I got my new apartment in Eden Prairie, Minnesota and then went to Wal-Mart to buy stuff for the apartment. As I checked out there was a mom ahead of me in line who got her grocery order somehow so severely tangled up that it took three different cashiers a while to unscrewup the cash register. While this was going on the mom wasn't watching her kids. She was just sort of staring off into space and zoning out, done for the day.

Eventually, the attention of the oldest of the three kids here drifted away from those dolls and up to the cans of Off! He sprayed a circular damp spot onto the palm of one of his hands and smelled it before sticking his tongue out for a taste of the minty goodness and which point I screamed "DON'T PUT THAT IN YOUR MOUTH! IT'S POISON!" and it made for a fun moment because I didn't just scare the hell out of these kids. I scared all of the adults around me too.

Saturday, January 5, 2019

Pin a tweet at your Twitter profile.

Visit twitter.com at your laptop, not your phone. Find one of your tweets and then click the downwards pointing arrow at the upper right of it. Pick "Pin to your profile page." from the menu that appears and this will make visitors to your Twitter web presence see this tweet first in the list without regard to chronological order. There is also an "Unpin from profile page." option later (in the same place) for getting rid of this.

How can I message exceptions from .NET Core REST endpoints which return void?

I personally prefer a purist approach to REST in which PUTs and DELETEs are fire-and-forget returning nothing. There are some challenges with this in an Angular 6 app insofar as if you want to do a .subscribe against an Observable you cannot as the ear you are listening with never gets fed and indeed it (probably) never should. (Think exception for the exception.) I eventually learned the way around this was to just use a promise instead of an Observable for REST endpoints which return void. The second function in a .then will catch an error message in these circumstances, but getting an error message to come back up when you are specifically returning nothing takes a bit of work. I don't recommend that you return a ceremonial object which maybe has some metadata on it or even an HTTP response from the endpoint. Instead write a filter like so:

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Rest;
namespace GroverClevelandHopscotch.RestApi.Filters
{
   public class BubbleUpExceptions : ExceptionFilterAttribute
   {
      public override void OnException(ExceptionContext context)
      {
         context.Result = new JsonResult(context.Exception);
         if (context.Exception is ValidationException)
         {
            context.HttpContext.Response.StatusCode = (int)
                  HttpStatusCode.NotAcceptable;
         }
         else
         {
            context.HttpContext.Response.StatusCode = (int)
                  HttpStatusCode.InternalServerError;
         }
      }
   }
}

 
 

At Startup.cs the .AddMvc() implementation is going to have to get this filter jammed into it. It can be more verbose than what I have above, make massages as needed for whatever variants of classes inheriting from Exception as you deem fit and then make an insertion like so:

.AddMvc(options =>
   {
      options.Filters.Add(new BubbleUpExceptions());
   })

 
 

Back at the TypeScript in the Angular app do something like this:

deletePresident():void {
   this.http.delete(this.route).toPromise().then(function(){
      console.log('success');
   }, function(error){
      console.log("Error Code: " + error.status);
      console.log(JSON.parse(error._body).Message);
   });
}

 
 

this.http above comes from...

import { Http } from '@angular/http';

Delete an Instagram account.

  1. Log in as you at your laptop, not your phone.
  2. Go to: https://www.instagram.com/accounts/remove/request/permanent/

Regular Expressions in a .NET Core Unit Test!

using System.Text.RegularExpressions;
using GroverClevelandHopscotch.Core.Objects;
using GroverClevelandHopscotch.Core.Utilities;
using Xunit;
namespace GroverClevelandHopscotch.Core.Tests.Utilities
{
   public class ValidationRulesUtilityTests
   {
      [Fact]
      public void ValidationRulesUtilities_behave_as_expected()
      {
         
//arrange
         ValidationRules validationRules = ValidationRulesUtility.GetRules();
         var presidentialNameValidationRule = new
               Regex(validationRules.PresidentialNameValidationRule);
         var presidentialPartyValidationRule = new
               Regex(validationRules.PresidentialPartyValidationRule);
         var deadMouse = "deadmau5";
         var joelThomasZimmerman = "Joel Thomas Zimmerman";
         var misterZimmerman = "Mr. Zimmerman";
         
         
//act
         Match deadMouseNameMatch =
               presidentialNameValidationRule.Match(deadMouse);
         Match deadMousePartyMatch =
               presidentialPartyValidationRule.Match(deadMouse);
         Match joelThomasZimmermanNameMatch =
               presidentialNameValidationRule.Match(joelThomasZimmerman);
         Match joelThomasZimmermanPartyMatch =
               presidentialPartyValidationRule.Match(joelThomasZimmerman);
         Match misterZimmermanNameMatch =
               presidentialNameValidationRule.Match(misterZimmerman);
         Match misterZimmermanPartyMatch =
               presidentialPartyValidationRule.Match(misterZimmerman);
         
         
//assert
         Assert.Equal(deadMouseNameMatch.Success, false);
         Assert.Equal(deadMousePartyMatch.Success, false);
         Assert.Equal(joelThomasZimmermanNameMatch.Success, true);
         Assert.Equal(joelThomasZimmermanPartyMatch.Success, true);
         Assert.Equal(misterZimmermanNameMatch.Success, true);
         Assert.Equal(misterZimmermanPartyMatch.Success, false);
      }
      
      [Fact]
      public void ValidationRulesUtilities_disallows_empty_strings_when_applicable()
      {
         
//arrange
         ValidationRules validationRules = ValidationRulesUtility.GetRules();
         var presidentialNameValidationRule = new
               Regex(validationRules.PresidentialNameValidationRule);
         var presidentialPartyValidationRule = new
               Regex(validationRules.PresidentialPartyValidationRule);
         var deadAir = "";
         
         
//act
         Match deadAirNameMatch = presidentialNameValidationRule.Match(deadAir);
         Match deadAirPartyMatch = presidentialPartyValidationRule.Match(deadAir);
         
         
//assert
         Assert.Equal(deadAirNameMatch.Success, false);
         Assert.Equal(deadAirPartyMatch.Success, true);
      }
   }
}

I saw Elsa Vezino speak at the Twin Cities .NET User Group on "Everyday Agile for One" on Thursday night.

You probably should have a little standup with yourself as a mental exercise when working alone. It will mentally prepare you to speak to what you are doing when someone asks. You should probably also break things up into stories and the like. Elsa put an emphasis on estimating Scrum points and also a metric for how much of a value a story is really worth regarding just how much it matters big picture (i.e. can you live without it?) and with these metrics you can have a conversation with your stakeholder about what's what and what's next a lot better than is the case in the absence of such a structure. A lot of this talk was stuff I had already heard about as Agile isn't new and a lot kinda strayed beyond Agile (for example, Elsa encourages you to bold text the one line of an email someone should read if someone only reads one line of any email you send and for that line to be at the top of the email), so I will focus on what was new to me. Crystal was mentioned as an old out of vogue practice. I Googled it and Crystal was a lightweight form of Agile which assumed that each project required a slightly tailored set of rules. Someone in the crowd mentioned that where they work all of the various teams do Agile but they are allowed to define how to do Agile themselves and they each do Agile their own way. In a demo, let your stakeholders take the mouse and drive themselves. It will allow for better feedback/commentary. Coding Horror as a blog offers a lot on the dangers of coding alone, falling behind in tech, no one to sanity check your stuff, etc. stackexchange.com is QA tool. Stop, start, and continue are things to think about in a retrospective. What should you stop doing? What should you start doing? What should you continue doing? "Lean Software Development: An Agile Toolkit" by Mary and Tom Poppendieck (Minnesota locals) was suggested to be a pretty good book and I think a quote from that book is "Quality in design means realization of purpose or fitness for use rather than conformance to requirements." and in other words quality code should enhance Agility not get in the way. The book suggests there are seven types of waste:

  1. unfinished work
  2. extra features
  3. relearning
  4. handoffs
  5. delays
  6. task switching
  7. defects

Elsa Vezino sighted the twelve principles behind The Agile Manifesto a few times:

  1. Our highest priority is to satisfy the customer through early and continuous delivery of valuable software.
  2. Welcome changing requirements, even late in development. Agile processes harness change for the customer's competitive advantage.
  3. Deliver working software frequently, from a couple of weeks to a couple of months, with a preference to the shorter timescale.
  4. Business people and developers must work together daily throughout the project.
  5. Build projects around motivated individuals. Give them the environment and support they need, and trust them to get the job done.
  6. The most efficient and effective method of conveying information to and within a development team is face-to-face conversation.
  7. Working software is the primary measure of progress.
  8. Agile processes promote sustainable development. The sponsors, developers, and users should be able to maintain a constant pace indefinitely.
  9. Continuous attention to technical excellence and good design enhances agility.
  10. Simplicity--the art of maximizing the amount of work not done--is essential.
  11. The best architectures, requirements, and designs emerge from self-organizing teams.
  12. At regular intervals, the team reflects on how to become more effective, then tunes and adjusts its behavior accordingly.

Friday, January 4, 2019

mixer.com keeps opening up in Edge on my Windows 10 laptop.

Lame! Try this maybe...

  1. give "Settings" at the start bar
  2. click "Apps" at the "Windows Settings" pane that appears
  3. at "Apps & features" search for "Edge"
  4. click on "Microsoft Edge" when it appears and then click the "Advanced options" link that is exposed by as much
  5. click the "Reset" button here

 
 

Addendum 1/17/2019: This does not work. I am not sure what the fix is to get rid of mixer.com. mixer.com is of Microsoft and is not adware. It just looks like adware when it shows up in Edge. Microsoft is doing this to you.

When you revert files you shouldn't have committed in the first place to address visualstudio.com pull request comments...

...well, there is no way to resolve the comments because now the files have been dropped out of the tree. I hacked around this today by putting some line returns back into the files I reverted and recommitting them.

If you put both a border and an outline on a div in CSS the border will wrap the div and the outline will wrap the border.

This will give us a white edge around the black edge around the burnt orange rectangle:

#privacy-policy-callout {
   color: #FFFFFF;
   background-color: #D67D07;
   border: 2px solid #000000;
   outline: 2px solid #FFFFFF;
}

Thursday, January 3, 2019

Allow an IP address access through the firewall at portal.azure.com!

  1. Go to "Resources groups" at the left nav.
  2. Drill into the appropriate group.
  3. Drill into the appropriate database.
  4. Click "Set server firewall" at the top nav.
  5. Add and edit rules here!

The underlying provider failed on Open

My head was going to explode over this error. I could connect to a database via SSMS and I could not interact with the database from a C# app in Visual Studio. What was different? This suggests it might be a transaction permissions thing. Maybe if the database connection is one of two being used in an orchestration of SQL across the two... maybe then you are in trouble. This would also explain the impossible to explain difference.

 
 

Addendum 1/4/2019: It turns out that Entity Framework 6 tries to open and close a database connection whenever it talks to a database and when this happens in a transaction you may have the permissions problem. The solution is to manually open a connection and hand that connection into the transaction.

Wednesday, January 2, 2019

Entity Framework 6 subquery example

public async Task<IList<ProgramSurvey>> GetProgramSurveysFor(int workshopId)
{
   var query = from programSurvey in _context.ProgramSurveys
      where (from workshop in _context.Workshops
         where workshop.Id == workshopId
         select workshop.ProgramId).Contains(programSurvey.ProgramId)
      select programSurvey;
   return query.ToList();
}

Enable First Chance exceptions in Visual Studio 2017.

Somewhat in following this...

  1. Go to "Customize..." under the "Tools" menu.
  2. Go to the "Commands" tag at the "Customize" dialog box which appears.
  3. Select "Debug" and then pick "Add Command..."
  4. At the "Add Command" dialog, again select "Debug" and pick "Exception Settings"
  5. Click "OK"
  6. There will be a little icon to click on between the "Build" and "Debug" dropdown menus at the top nav now. Click on it to open up the "Exception Settings" pane. It looks like maybe a monitor screen with an exclamation mark in it while a gear sits at the lower left corner of the screen.
  7. Put a check by "Common Language Runtime Exceptions" here.
  8. A coworker suggested testing this stuff by putting a breakpoint in the constructor of a class that was throwing a hard-to-pin-down error message. In theory this catches explosions farther upstream than usual debugging when the debugger first catches an exception but before it decides how to present it. That explains the name, right?

Unlock the connection strings for a given web application at Azure.

  1. At portal.azure.com click "Resource group" at the left nav.
  2. Drill into a resource group.
  3. Then drill into the "App Service" for the resource as opposed to one of the databases. This is the web app.
  4. Click on "Application settings" at the second left nav just right of the main left nav.
  5. Scroll down until you see: "Connection Strings"
  6. Click: "Show Values"

Kodi

It's some sort of media player. You can get it to jive with your TV (television) too.

Tuesday, January 1, 2019

I was at an event last night for New Years and some kids loaned me a pair of glasses that make lights into hearts when you look through them.

Specifically, I was at The Armory at 500 South 6th St, Minneapolis, MN 55415 for an event called Snowta. I don’t like everyone, but I wish most of you a happy and prosperous 2019.