Friday, September 30, 2016

Tech Fail!

I took these photos on 7/10/2016 at Arlanda Airport just north of Stockholm, Sweden whilst on vacation.

I'm not sure what was supposed to be on the display, but I am sure the wrong thing is being communicated.

Tuesday, September 27, 2016

'ref' argument is not classified as a variable

This error message which may be found in Visual Studio 2013 also appears in Visual Studio 2015 only therein it is the second of two lines of error messages. The first is:

A property of indexer may not be passed as an out or ref parameter

 
 

Perhaps it's now a little more clear what is going wrong, eh? The problem would occur at the last line of this code for example...

var buckToothedTreeGnawers = new List<Beaver>()
{
   new Beaver()
   {
      Name = "Flotsam",
      MillimetersOfTeeth = 30
   },
   new Beaver()
   {
      Name = "Jetsam",
      MillimetersOfTeeth = 29
   },
   new Beaver()
   {
      Name = "Lagan",
      MillimetersOfTeeth = 40
   }
};
var lumber = Woods.ChopDownPine(ref buckToothedTreeGnawers[2]);

 
 

buckToothedTreeGnawers[2] will get the squiggly red line under it in Visual Studio letting you know that something is wrong and when you roll your mouse pointer over it... Voilà! There is our error! You cannot hand a ref variable into a method signature while referencing it out of a list. Whatever. I don't see why not, but then I don't make the rules. I'm not Anders Hejlsberg. Anyhow, code like this will actually work:

var flotsam = new Beaver()
{
   Name = "Flotsam",
   MillimetersOfTeeth = 30
};
var jetsam = new Beaver()
{
   Name = "Jetsam",
   MillimetersOfTeeth = 29
};
var lagan = new Beaver()
{
   Name = "Lagan",
   MillimetersOfTeeth = 40
};
var lumber = Woods.ChopDownPine(ref lagan);

 
 

I think you'll find this shortcoming won't get in your way all that much really. I only stumbled upon it today for the first time and I've written C# for ten years.

flash drives have "solid state storage"

...as opposed to a spinning disc making them vaguely twice as fast. Also, there are fewer moving parts to break.

PHP at NGiNX

FastCGI will allow you to run PHP on NGiNX. Another approach is to run let Apache run PHP and use NGiNX merely as a router (as a front door to Apache). NGiNX is apparently petty light in and of itself.

Monday, September 26, 2016

CTE within SUM or COUNT!

Starting with this T-SQL and improving upon it gives us:

SELECT c.CurrencyId AS 'Id'
c.CurrencyCode,
COUNT(i.TotalAmount) AS 'OpenInvoices',
COALESCE(SUM(i.TotalAmount), 0) AS 'Balance',
(SELECT COUNT(TotalAmount) FROM #Invoices
   WHERE DueDate < GETDATE() AND Id = CurrencyId) AS 'OpenInvoices',
COALESCE((SELECT SUM(TotalAmount) FROM #Invoices
   WHERE DueDate < GETDATE() AND Id = CurrencyId), 0) AS 'Balance',
FROM #Currencies c
LEFT JOIN #Invoices i ON c.CurrencyId = i.CurrencyId
GROUP BY CurrencyCode

 
 

Note that if you want to use a column from another table not specified in your CTE that it better be one of the columns returned in the select statement. Otherwise, expect an error. To that end I've looped CurrencyId into the list of columns returned and have fudged its name so there is no ambiguity when matching CurrencyId to CurrencyId in my CTEs without a leading c. or i. to distinguish them.

Use COALESECE in T-SQL to make columns which sum up nothing return a zero instead of NULL.

This...

SELECT c.CurrencyCode,
COUNT(i.TotalAmount) AS 'OpenInvoices',
SUM(i.TotalAmount) AS 'Balance',
COUNT(pdi.TotalAmount) AS 'PastDueInvoices',
SUM(pdi.TotalAmount) AS 'PastDueBalance'
FROM #Currencies c
LEFT JOIN #Invoices i ON c.CurrencyId = i.CurrencyId
LEFT JOIN #PastDueInvoices pdi ON c.CurrencyId = pdi.CurrencyId
GROUP BY CurrencyCode

 
 

...needs to become...

SELECT c.CurrencyCode,
COUNT(i.TotalAmount) AS 'OpenInvoices',
COALESCE(SUM(i.TotalAmount), 0) AS 'Balance',
COUNT(pdi.TotalAmount) AS 'PastDueInvoices',
COALESCE(SUM(pdi.TotalAmount), 0) AS 'PastDueBalance'
FROM #Currencies c
LEFT JOIN #Invoices i ON c.CurrencyId = i.CurrencyId
LEFT JOIN #PastDueInvoices pdi ON c.CurrencyId = pdi.CurrencyId
GROUP BY CurrencyCode

 
 

Get it?

You may skip the empty curly braces when newing up a list in C# if you like.

var buckToothedTreeGnawers = new List<Beaver>();

...and...

 
 

var buckToothedTreeGnawers = new List<Beaver>() { };

...are basically the same thing.

VoIP stands for Voice Over Internet Protocol

The last blog posting I just typed up made me think of Voice over IP. This stuff allows your business telephone to interface with your PC, etc. You can get voicemail messages as email attachments and the like.

marketing misadventures

There are two different members of the waitstaff at the Olive Garden that I always eat at who are trying to improve their lot and get into marketing and out of service. One of them is a young guy whom, to me it sounds, has landed his first office job gig in the marketing space. I think it's gonna be mostly office admin stuff, but there will be some email campaign marketing going on there too. It sounds like a good start. I certainly had to answer the phone a lot in my day, and there was a time when I was in restaurants too, making sandwiches at Texadelphia or bussing tables at Fresh Choice. To this day my heart bleeds for people suffering in service jobs who don't want to be there because I've been there myself. I always tip well. I digress. The other person is a woman my age with a large history in pharmaceutical marketing in New Jersey (including focus groups!) who has moved to Texas and is trying to find her footing here. They both have me thinking of marketing in general. I really don't know that much about it, all in all. I've gotten to work some with Christa Tuttle and Shawna Boyce of Launch Marketing and I get the impression that the typical background is one of a bachelors in, well, marketing, which is an awful lot like a generic bachelors in business with only a few classes differing, just enough to make a specialization of a business degree. From Launch I learned that anymore to make a press release you just write something up and put in on your web site. Maybe back in the day you had to have a press kit, but not anymore. I don't know what a press kit even is and if it varies from a press packet and opens other doors. Someone with the formal background knows these things. Eleven years ago towards the end of my time at Network Logistic, Inc. I was given the grandiose, ridiculous title of Director of Marketing before I had ever rubbed elbows with a real marketer. Before then I had designed some marketing slicks when I worked for Gary McKibben and Michael Johnson at Johnson/McKibben Architects and I had made some 3D models for presentations when I both did a week long contract with Joel Shakespear at a now dead startup called TRiAD and a much longer stint for John Drury at his slaveworks, but this isn't really, obviously, the background for someone who is a Director of Marketing. What a joke. I made twelve dollars an hour in this role, and, it gets better, all I did was the web developer job I had before while I also now sent out email campaigns. Yes! Plus, there was no one to direct. I was director without underlings. This is the kind of place that would give the title Vice President of Sales or Vice President of Engineering out like it was nothing. I guess it was a part of their posturing as they hired staff on the cheap while acting as if not Mickey Mouse in whole. Paul Williams, an engineer who worked at NLI, suggested that I shouldn't feel awkward about my bogus title because "There's nothing to those fucking people." However, when I eventually started to really know some of them I found them pretty impressive and I wished I knew more of what they knew. I eventually grew some SEO (search engine optimization) chops, but I've let that skill decay and I can't really do it anymore. That other Tom Jaeschke, the volleyball player, always appears when I Google my own name. Yeesh. I ran into Stacy Tallent of Telco-Data maybe a year ago at a, well, Texadelphia, and he spoke well of me for designing the logo that they are still using today way back when Telco-Data and Network Logistic, Inc. were sister companies sharing a common owning partner. I've never learned much of anything about telephony. I can remember Penn Rabb of PrismNet expressing some frustration with me for not knowing more about a business telephone system I was using. Whatever. I digress again. Anyhow, I think I shall always find marketing intriguing and have an ear open to it. It's on my mind right now.

There is no need to do a casting to match two differing types in a join in T-SQL.

It will just work. :) In an app I'm working on there is a table that more or less manages key value pairs with a different column for the key and the value. The value column is of nvarchar(50) but if an "int" is kept there and then matched against an int that is the primary key on another table in a join in a select, it's will work alright. Yay!

Maybe I spoke too soon, one of my coworkers, J.D. Gonzalez, tweets to me: that is true it will be at the expense of an implicit cast. That can cause performance problems on large datasets.

Saturday, September 24, 2016

When NuGet puts stuff into my Web.config for a library, what is it up to?

The ConfigurationSection class in/at System.Configuration.ConfigurationSection allows configurations to be handed into your .dll from the Web.config of another project. Make your own class which inherits from ConfigurationSection. Let's say it's called InData. Then...

<section name="foo" type="MyApp.MyFolder.InData" />

 
 

...goes in configSections in the Web.config and this goes outside configSections...

<foo bar="baz" />

 
 

InData itself looks like...

public class InData : ConfigurationSection
{
   [ConfigurationProperty("bar", DefaultValue="qux", IsRequired=false)]
   public string Bar
   {
      get { return (String)this["bar"]; }
      set { this["bar"] = value; }
   }

get your exceptions in your MVC actions to end up as yet another validation fail at @Html.ValidationSummary() in your views

catch (Exception ex)
{
   ModelState.AddModelError("Exception", ex.Message);
   return View(whatever);
}

Could not copy "C:\Whatever\LibSassHost.Native\msvcp120.dll" to "bin\LisSassHost.Native\msvcp120.dll". Exceeded retry count 10. Failed.

When I got this error upon attempting to compile in Visual Studio 2015, I learned to deal with it by turning IIS off when compiling. If there is a way to change the .dll from "Copy Always" to "Copy Newer" that helps in situations like this.

I don't see why one can't put a title tag right by the H1 tag in a page.

Who says it has to go in the head tag? One may have link tags for stylesheets and JavaScript script tags partway down the body after all. I guess title-outta-head (fish-outta-water) may not work in IE9. In views in ASP.NET MVC apps we do some contortions to reach up the "MasterPage" view to doctor stuff up there on a "page by page" basis for customizations, but... do we have to?

Fixed widths may not play nicely with copy that changes when a new resource is used for a different language.

I'm not sure what to do about that. :(

You may import one Sass file into another much like importing one .css file into another.

@import 'whatever.scss';

This will allow you to make one file with common variable settings for others.

You must compare INT type T-SQL variables to a zero default instead of doing the ISNULL thing with them.

This isn't true at all. Use IS NULL not ISNULL ...er, that is to say I think I accidentally used ISNULL where I attempted an IS NULL comparison which obviously won't work.

The article HTML5 tags should wrap something that could stand alone as a web page's exclusive content.

And, section is for sizable sections like a left sidebar. Don't use these tags for tiny bits of content just in the name of not using div.

list-style: disc;

...puts the bullets back on an unordered list if you need to stamp over a list-style: none; setting elsewhere.

UserManager

A UserManager which takes an IUserStore<IdentityUser, int> at its constructor is a helper object in the Identity paradigm that one may ask questions to about the latest bag of claims and it helps to extend it with your own class that inherits from it. You're getting into the async/await "magic" with this class. I don't know much about it yet. At an MVC action you'll be returning a Task<ActionResult> in lieu of just an Action result and that is part of the price you pay so to speak, etc.

Edit This Cookie

...is a Google Chrome plugin that will put a cookie icon at the upper right. Click that icon and then click the trash can icon that appears to throw away (destroy) all cookies for the current site.

To delete a changeset at the Review Materials in SmartBear Collaborator use the controls at the upper right.

Switch the Overlay toggle to Separate to unlock the delete button.

an attribute that will catch a lot of verbs

[HttpGet, HttpPost, HttpPut, HttpDelete, HttpHead, HttpOptions,
      AcceptVerbs("PATCH")]

add more room to grow to a VM

A VMWare VM with snapshots cannot have its hard drive expanded. The way you might otherwise expand a drive is by clicking "Edit virtual machine settings" at the upper left and then clicking on a hard drive and clicking the "Utilities" button. After you expand the size of a VMWare VM (do this while it's powered off), power the VM back on and go into the Server Manager to expand the size of the partition. At Windows Server 2012 R2 for example you will go to "File and Storage Services" at the upper left, then pick "Disks" from the upper left menu that comes after that. Finally, right-click on a drive and pick "Extend Volume..."

Defrag your hard drive in Windows 7.

Pick "Computer" from the start menu to get a familiar Windows window listing your drives and from there right-click on a drive, pick "Properties" from the menu that appears, and then the "Tools" tab. The "Defragment now..." button will also let you schedule. Access the defragmenter this way.

A hot dog menu may also be called a hamburger menu.

It looks to me more like three hotdogs than it does a cross-section of a hamburger. Maybe it's just me.

Write a test for an exception of a particular shape in C#.

[ExpectedException(typeof(Exception), "Whatever")]

...goes below the [TestMethod] attribute, setting the expectation that the test will blow up in this way. "Whatever" herein represents the exception message.

An exception of type 'NSubstitute.Exceptions.AmbiguousArgumentsException' occurred in NSubstitute.dll but was not handled in user code.

This basically means you're trying to define a mocking of the same thing twice.

EXEC sp_refreshsqlmodule 'MySprocNameHere'

...will refresh the custom data types (User-defined Table Types at least) a sproc uses. Use this trick when you rename and then recreate a custom data type out from under such a sproc.

var whatever = new DataTable("Whatever");

Compiler sickness? I saw some madness in which I could not manually add a sixteenth column in code downstream like so...

whatever.Columns.Add(new DataColumn("Foo", typeof(string)));

 
 

...until I changed the magic string: "Whatever"

When you want to destroy a parameter in a request in SoapUI...

Find the "endpoint" at the top of the window and then find that "endpoint" in the "Navigator" (left nav) and drill down below it to find the appropriate configuration driving your parameters. This window will look an awful lot like the one you were just at but here you may click the parameters, then click a red X to destroy them, and finally see the update at your original window.

Drop a User-defined Table Type in T-SQL.

DROP TYPE Foo

SELECT into an INSERT in T-SQL

INSERT INTO Ids (ID) SELECT FooId FROM Foo

A JavaScript alert is good for vetting HTML encoding!

<script>alert("hello world");</script>

These changes might cause deployment errors or data loss.

In SQL Source Control there will be a triangle with an exclamation mark in it alerting you "These changes might cause deployment errors or data loss. Make sure a migration script covers the change." This likely means you'll need a migration script. There will be a loud button for creating the migration script at the "Commit" tab if you select the angry line item. Remember to doctor up the suggested script to replace existing null values with zeros or whatever. Make migration scripts right before you check in as you cannot gracefully have the other changes afterwards.

I want to allow nulls without dropping a table!

Tools > Options... > Designers holds a checkbox for "Prevent saving changes that require table re-creation" that you may uncheck in SSMS2014 to allow for saving a table when you uncheck an "allows null" checkbox when editing a column. Obviously, you can't make this happen until you've first gotten rid of all nulls in that column.

to see dotCover specs...

Run tests in ReSharper, right-click somewhere in the tree of tests that appears in a panel and pick "Cover Unit Tests" from the menu that appears to get details on what is covered.

capital and lowercase Zs in datetimes

tell you that this date is in UTC time with no offset or report the offset respectively

YYYY-MM-ddTHH:mm:ssz ...is... 2016-12-01T00:00:00-6
   
YYYY-MM-dd HH:mm:ssz ...is... 2016-12-01 00:00:00-6
   
YYYY-MM-ddTHH:mm:ssZ ...is... 2016-12-01T00:00:00Z
   
YYYY-MM-dd HH:mm:ssZ ...is... 2016-12-01 00:00:00Z

You may need to use a T if you can't have a space. T is a time designator.

in Symmetric Arithmetic Rounding that which ends in .5 gets rounded "up"

(away from zero) always, but in Bankers Rounding that which ends in .5 gets rounded to the nearest even number, maybe up or maybe down, depending.

When you upgrade a ReSharper license to also include a copy of dotCover...

In Visual Studio 2015 go to: Resharper > Help > Check for updates... ...to turn the new stuff on.

In SoapUI the Request tab shows a convenient table of header variables...

...while the Raw tab shows what is actually gonna go over the wire in a HTTP request.

Microsoft Publisher

I guess I'll make a blog posting on Microsoft Publisher since I just made one on Microsoft FrontPage. You can squint your eyes and sort of see the following as cut from the same cloth:

  • Macromedia Illustrator
  • Adobe Freehand
  • Corel Draw
  • Microsoft Publisher

HOWEVER, there was no exporting Publisher stuff to .eps or .ai file types to get them into the other vector graphics programs. This is sort of the opposite problem of it being hard to open something you made in Illustrator in Inkscape. What you had to do was save out an Adobe PDF and then suck the PDF into Illustrator and manhandle its goofiness there. In a PDF many lines of copy in a nice paragraph have a habit of entering Illustrator as many sets of text in independent text blocks and sometimes there would be breaks in text between two bounding boxes on the same line of text. You only ever saw Publisher creations because someone, not a designer, started there not knowing any better.

Groovy can compile with Java and to Java to run in Java environments.

Groovy scripts may be run in SoapUI to make complicated requests easy to run. One may save out a SoapUI project, complete with Groovy Scripts to an .xml file with supporting .xml and .wadl (for REST projects) files.

 
 

Addendum 3/21/2018: Both Java and Groovy compile to bytecode that runs on the Java Virtual Machine (JVM) but Groovy does not compile to Java.

Microsoft FrontPage

...was Microsoft's verison of Macromedia's (now Adobe) Dreamweaver, BUT in order to also conveniently FTP up with it (in case you were too stupid understand the concept of File Transfer Protocol on your own) you had to have a bunch of goofy FrontPage extensions installed at your server, so it both held your hand and made you sick. If you tried to just FTP changes manually it would be out of sync with crap in FrontPage and a manual update could get lost the next time you pushed or pulled through FrontPage. This is something to just forget about, like it never happened. Sorry to remind you.

Friday, September 23, 2016

Time Warner Cable is now a company called Spectrum.

They called me today and tried to upsell me stuff. This has some stuff on the change up. Charter Communications, whom I had never heard of, joined with Time Warner to form this new thing, or maybe it bought Time Warner and also another entity called Bright House Networks. dunno.

joins in LINQ!

While I was at Santanna Energy for a few weeks, Ragan Morris wisely pointed out that a CTE/subselect in the middle of a select in T-SQL statement made for an n+1 problem and the way to fix that in optimizing a stored procedure was to pull that which was in the inner query out to one upfront query to a temp table and to then join that which you were to otherwise query to the temp table. That way n+1 queries becomes just two! But... What if you have some O(n²) issue in C#? How do you fix that? A coworker recommends using a join in LINQ! Using AsParallel in a LINQ join (looping in PLINQ) can break the heavy stuff up across different threads too, but you really only want to go there if things are indeed heavy. Try to join two record sets with a LINQ join in lieu of having a loop inside a loop. That will get expensive when data gets fat.

What causes 405 Method Not Allowed error messages?

In the ASP.NET Web API it's gonna be strange verbs you shouldn't be using. Beyond this list of verbs, the first link I give here suggests the other verbs are:

  • COPY
  • MOVE
  • MKCOL
  • PROPFIND
  • PROPPATCH
  • LOCK
  • UNLOCK
  • PATCH

WordPerfect

In the mid 1990s WordPerfect was a word processor that rivaled Microsoft Word. Word won the space. I guess WordPerfect is still around and now owned by the Corel corporation. This all seems so long ago. I can remember when you were supposed to chase a period at the end of a sentence with two spaces when using a word processor.

Wednesday, September 21, 2016

Did you know you may "Eject" a USB drive?

Right-click on the drive letter and pick this option, just like you are ejecting a CD-ROM. You will then not be able to go into the drive until you pull it out of the USB (Universal Serial Bus, a bus or buss being a data transfer communication means between two endpoints) port and put it back in again. What does this get us? I just watched a woman waiting on me do this at the FedEx store and I wondered why she bothered. Whatever.

The Compare attribute on a getsetter, making sure the double entry for a password is sound in MVCland, may reference a resource for its error message.

[Compare("Password", ErrorMessageResourceType = typeof(Resources.Resources),
      ErrorMessageResourceName = "Whatever")]

For more on the Compare attribute see this. It is possible to just only give [Compare("Password")] for the attribute in which case an error message will just be made up for you. It's very plain Jane and has a "cannot compare 'X' to 'Y'" flavoring.

Connected Fitness

A little bird tells me that Under Armour has consolidated MapMyFitness and a bunch of similar purchased smart phone entities into Connected Fitness and there is but one central app for it all now.

4chan.org

Is an older NSFW (not safe for work) image surfing smorgasbord that was what tumblr became before tumblr took off. I think there is also an association with Anonymous too. It's heyday wasn't long lived honestly. It was very 2011.

Tuesday, September 20, 2016

What are the rules for passwords in PCI 3.0?

I find that a question with surprisingly frustratingly fuzzy (conflicting/ambiguous) answers. Here is what I would think they would be based upon an aggregate of various sources.

  1. Passwords should be at least seven characters long containing an uppercase letter, a lowercase letter, a number, and also at least one special character, and by special characters we are specifically talking about at symbols, pound signs, carats, and exclamation and question marks. Moreover, asterisks, ampersands, spaces, and plus and percentage symbols should be disallowed. They are less special in this light. Source: https://limoanywhere.uservoice.com/knowledgebase/articles/170461-what-are-the-password-requirements-for-pci-complia
  2. A user cannot use his/her username as his/her password. Source: https://limoanywhere.uservoice.com/knowledgebase/articles/170461-what-are-the-password-requirements-for-pci-complia
  3. Passwords must expire every ninety days. Source: https://limoanywhere.uservoice.com/knowledgebase/articles/170461-what-are-the-password-requirements-for-pci-complia
  4. Users may not reuse any of the last four passwords when changing a password. Source: http://searchsecurity.techtarget.com/answer/Password-compliance-and-password-management-for-PCI-DSS
  5. There may not be shared passwords across multiple users or any other communalbowlesque approaches to breaking in. Source: http://searchsecurity.techtarget.com/answer/Password-compliance-and-password-management-for-PCI-DSS
  6. Do not use any canned defaults for first time passwords. Source: https://thycotic.com/solutions/pci-dss-compliance/
  7. First time passwords must have unique values and you should also force users to change the first time passwords to something else upon first login. Source: http://www.slideshare.net/nFrontSecurity/pci-password-policy-compliance-31299104
  8. Use strong cryptography standards and not, for example, plain text passwords in your recordkeeping. Source: Section 8 of "PCI DSS Quick Reference Guide Show" as listed at https://www.pcisecuritystandards.org/document_library?category=pcidss&document=pci_dss
  9. There should be two-factor authentication. Source: Section 8 of "PCI DSS Quick Reference Guide Show" as listed at https://www.pcisecuritystandards.org/document_library?category=pcidss&document=pci_dss

This has more on two-factor authentication.

Monday, September 19, 2016

no more "predeclaring" out variables, well, unless you want to

This has a bunch of notes on C# 7.0 and it starts out mentioning that you may new up out variables right when you hand them into a method signature as out variables so that this...

int peaches;
int bananas;
blender.MixNMutilate(out peaches, out bananas);
blender.PourOutPaste(peaches, bananas);

 
 

...may now become...

blender.MixNMutilate(out int peaches, out int bananas);
blender.PourOutPaste(peaches, bananas);

 
 

...and you can probably even use var...

blender.MixNMutilate(out var peaches, out var bananas);
blender.PourOutPaste(peaches, bananas);

 
 

...and hand in a wildcard for that thing you don't care about.

blender.MixNMutilate(out var peaches, out *);
blender.PourOutPaste(peaches);

Sunday, September 18, 2016

Blue Shoes

This was an old administration tool wherein one would log in as an administrator, browse a vanity web site normally, and be able to click on content within the web site to edit it right there in lieu of going into a separate backend system. In a time before WordPress you tied this into web sites you tossed together with your own spaghetti code.

RAT stands for remote administration tool

It's malware which will let others spy on you through the camera on your laptop. I saw the "Snowden" movie last night so it's on my mind.

Pinterest

...was another goofy photo-sharing app. You never hear about it anymore. It's at pinterest.com if you want to see it.

Saturday, September 17, 2016

Not every credit check slightly lowers your credit score.

Equifax, Experian, and TransUnion are the three credit bureaus. There is a distinction between hard and soft credit inquiries. Only the hard ones lower your credit score and the distinction is that hard inquiries are meant for decision-making while the soft are merely test/informational in nature. Behind the scenes in the banking sphere soft inquires will happen as part of your bank's dabblings, but if you actually walk into your bank and ask them to tell you your credit score then, yes, that's a hard inquiry.

Get the name of the server in T-SQL!

IF OBJECT_ID('tempdb..#TempTable') IS NOT NULL DROP TABLE #TempTable
SELECT @@ServerName AS 'ServerName' INTO #TempTable
SELECT ServerName FROM #TempTable

var foo = System.Environment.MachineName;

...will get you a string in C# with the name of the hosting server.

When you want to "delete" an invoice in SAP...

...you give it a "credit memo" status and it behaves as if paid.

ticking time bomb

A few weeks ago I became paranoid about using int/int where bigint/long should be used in T-SQL/C# and using an inappropriate hodgepodge of the two. It's such an easy mistake to make. This is something that can sleep, sleep, sleep as a bug past unit tests, past the testing team, and right into production where it will sit unnoticed until... KABOOM! What to do? The old FramesDirect.com (a .com experience of mine) convention of naming variables with a few leading characters to decry type may be applicable for variable distinctions to distinguish long and bigint? The approach used would ideally be less dirty though. The FramesDirect way was "Hungarian notation" (it's a thing) and a string you might otherwise name address would become sAddress in that paradigm. There were some leading encodings like three characters long. Nasty stuff.

Cerberus allows one to talk into it from C#!

...and one will be able to do file transfer manipulations, make byte streams, make the streaming secure, manage user accounts with various permissions, allow some users to FTP without writing your own code for FTPing and so on...

Give the execute permission to a role at a User-defined Table Type in T-SQL.

Herein Foo is the Type and Bar the role:

GRANT EXECUTE ON TYPE::[dbo].[Foo] To Bar

You can't cherry pick a commit to subversion and then remove it from source control.

I don't know what one does about this problem. Set up a new trunk? Yikes!

Enable Filestream at SQL Server

  1. right-click on your server in SSMS's object manager and pick "Properties" then "Advanced" from the dialog which appears and set "FILESTREAM Access Level" under "FILESTREAM" to "Transact-SQL access enabled"
  2. open "SQL Server Configuration Manager" and click on "SQL Server Services" at the left and at the right right-click on "SQL Server (MSSQLSERVER)" and pick "Properties" and then the "FILESTREAM" tab where you should check the checkbox for "Enable FILESTREAM for Transact-SQL access"
  3. open services and restart "SQL Server (MSSQLSERVER)"
  4. you're gonna need some SQL like this...
    USE [master]
    GO
    ALTER DATABASE [Foo] ADD FILEGROUP [Files]
    CONTAINS FILESTREAM
    GO
    ALTER DATABASE [Foo] ADD FILE (Name='Nice_Files',
          FILENAME=N'E:\whatever\Nice_Files') TO FILEGROUP [Files]
    GO

 
 

Addendum: @jdgonzalez mentions: @jaeschke one clarification. The file you list is actually a folder.

see sprocs using a User-Defined Table Type in SSMS2014

right-click on the Type and pick: "View Dependencies"

Add a new, conditional flag to a WHERE clause in T-SQL at a SELECT for filtering.

ALTER PROCEDURE [dbo].[Whatever]
   @Iwasalwayshere INT,
   @Iamnew VARCHAR(50) = NULL

AS
BEGIN
   SELECT * FROM Gunk
   WHERE MatchId = @Iwasalwayshere
   AND (@Iamnew ISNULL OR BlahBlahBlah = @Iamnew)
   AND IsActive = 1
END

Go into your "Documents" in Windows and delete the VMWare virtual machines you haven't used in forever.

This will free up gigabytes of wasted space.

Try not to have if/else logic around what you return. Clean it up.

if (foo) return bar;
return baz;

 
 

...is cleaner than...

if (foo)
{
   return bar;
}
else
{
   return baz;
}

 
 

...which is silly.

keepvid.com

seems like a pretty good tool for saving off a YouTube movie as an .mp4

You may jam a lambda expression inside of a .Count() done on a collection in C#.

This blog posting is sort of the opposite of this one. A where clause will filter things down.

an interesting pitfall with SQL Source Control

When you first hookup the database and you don't have the tables it thinks you mean to delete the tables. You need to revert a bunk changeset to bring in the tables which otherwise cannot be slurped down due to the conflict.

in REST API approaches the "accept" header determines (or suggests) what should be handed back on response (JSON or XML)

while the "content-type" header denotes what is handed in and thus how to deserialize (as JSON or as XML) what is handed in

Joomla

I never hear of this anymore but it's a CMS like WordPress and Drupal. I thought of it just now. It used to be legit. dasBlog was a CMS which was .NET-flavored before Orchard CMS.

Saturday, September 10, 2016

var person = people.Single();

If there is no Lambda clause with a .Single() then the one and only member of a collection will be fished out of the collection. If there are less or greater than one things in the collection then an exception will be thrown.

Add a header variable in SoapUI.

  1. click the green plus symbol for: "Adds a parameter to the parameter table"
  2. fill out name and value
  3. set the style to HEADER and the level to RESOURCE

A mid-running process is something you might break off the main thread in C#, but a long-running process technically includes, as a step, a human action.

Both things may be wrapped in a rollback mechanism written at the C# side similar to transactions in T-SQL.

JsonIgnore and IgnoreDataMember

[JsonIgnore]
This attribute in the NewtonSoft.Json namespace can be slapped on a getsetter at a POCO in C# to keep it from being serialized to JSON and to keep JSON handed in from being mapped to it.

 
 

[IgnoreDataMember]
This attribute in the System.Runtime.Serialization namespace is something similar and includes XML concerns too.

Friday, September 9, 2016

There is a type in C# that's just generically called Enum and you may generically upcast your custom enums to it.

I suppose all you may do with the parental type is cast it to a string or cast it to an int. I don't know what other angles one might work with it.

Serialize a type as an anonymous type.

Just wrapping the type in curly braces may make it friendly to be handed back as JSON from C# in an ASP.NET Web API paradigm.

var foo = new Foo() { Whatever = "Whatever" };
return new { foo };

Allow the DELETE verb to work at the Web API.

This is applicable for DELETE as it is for PUT.

When deleting against an IN clause in T-SQL, wrap the thing to delete against in parenthesis.

DELETE FROM Foo WHERE (FooId) IN ((SELECT FooId FROM Bar WHERE BarId=13))

override!

If you use a "grandchild" of a child "inheriting" (implementing) an interface, where there is an upcasting to the interface, the child's methods will get used and not the grandchild's unless you explicitly override them.

You may specify a type at an MVC Web API route.

...like so: whatever/{id:int} ...but don't use string for the type. For a string just leave out the colon and the type like so whatever/{id} as not doing so will throw a cryptic error to do with DefaultConstraintResolver.

upsert through PUT in pseudo/quasi REST?

It's an interesting idea. In the event of a concurrency fail in which record 100 is deleted at the same moment it's updated, we would just recreate the old data at auto-incrementing id 100! New records would start getting added downstream past 100 obviously at the point where the counting left off. So what's stopping someone from handing in an id millions ahead in sequence or running the id count up to at or just before the cap in this way? We discussed this concept at my work but did not implement it and I can't recall how we were maybe gonna get around that pitfall.

suggestions from a coworker on good code

  • Look at how a feature will behave at the database before writing any code. Figure out the steps needed at the database considering the existing schema.
  • LINQ (Find, First, FirstOrDefault, Where) is for finding something and foreach for doctoring up records. Don't go finding with foreach.
  • Try to write your own test cases.

Addendum 9/10/2016: Find isn't really LINQ-related, strictly-speaking.

bookmarks in Visual Studio

  • Ctrl-K followed by Ctrl-K in Visual Studio will allow you to bookmark something
  • View > Bookmark Window or perhaps
  • View > Other Windows > Bookmark Window in Visual Studio 2015 will show a list of the bookmarked bits of code while there are also some icons at the top nav for managing this too

Thursday, September 8, 2016

In the end, architecture boils down to what the important stuff is.

This is a quote by Martin Fowler offered in Jeffrey Palermo's keynote at his MeasureUp conference this year. Depending on your perspective it's either vapid or not vapid, eh? I saw it as vapid first and then I squinted my eyes some. Anyhow, I have five point five pages of hand scribbled notes from a month and a half ago with what I thought the important stuff was. Let me see if I can regurgitate it here. Here's a good start: It was suggested (in the keynote) that your code will be 95% defect free if you undertake and utilize...

  1. Unit Testing
  2. Static Analysis Tools
  3. Formal Inspections

Also in the keynote it was suggested that Scrum works best for something that takes up to one thousand functional points to build and then you're in trouble with it going beyond. At that line-in-the-sand Kanban becomes the better thing and the rollout process for as much should have separate steps for: Requirements discovery, Solution analysis, Key design decisions, Coding, Pull request & review, Integrated developer testing, and Functional testing. Each step needs an inspection process and tests. Every version control repository has one version control counter so it's important to have one application per version control repository. Don't do the old school subversion thing in which you just use a repository like a file share. Bad. The Addison-Wesley book "Continuous Delivery" was recommended. James Chambers talk was a .NET Core "all-you-can-eat buffet" and .NET Core is now open source and available on GitHub and treated as a first class citizen. He went through setting up a new MVC app and slurping down NuGet dependencies. WebBundler will be used instead of Gulp for bundling and minification. In the new paradigm there will be a wwwroot folder and .css and .dll files will get built here. When the web server spins up it will look here first and Startup.cs and Program.cs are the first two files it will find to orient itself. You will now just inherit from "Controller" to make either an MVC Controller or a Web API Controller and if you just use the WhateverController naming convention you don't even have to inherit from Controller. There is a Web.config but project.json is really the new Web.config. Kestrel is the new web server that's not IIS and not tied to Windows. You can stand up the Nginx web server in front of Kestrel in Linuxland and Kestrel is eight to ten times faster than Node.js. Throw in a Docker container to get this working at Amazon. The Program.cs entry point for the application exposes something that CAN be used for something other than the MVC framework. For example:

public static void Main(string[] args)
{
   var host = new WebHostBuilder()
         .UseKestrel()
         .UseContentRoot(Directory.GetCurrentDirectory())
         .UseIISIntegration()
         .UseStartup<Startup>()
         .Build();
   host.Run();
}

public IConfiguration Configuration {get;} in Startup.cs similarly allows for bringing in the configuration "options" pattern, opening the door to reading a bit of a configuration from AppSettings.json in the name of hydrating static unchanging properties. You're going to have a secrets file that does not get checked into source control. Some other wire-ups are:

builder.AddUserSecrets();
service.AddMvc();
app.UseDeveloperExceptionPage();

 
 

So the first of these loops in the secrets file, the second has to do with controller resolvers and other dependency injection stuff for MVC, and the last thing empowers the yellow and red screen of death, but conditionally so for dev and not production. Hmmm... I'm a little over halfway through my notes now. I'm going to take a break from typing and get something to eat. More later.

 
 

Addendum 9/9/2016: "Middleware is like Russian Dolls where you open it up, you open it up, you open it up..." was a quote from Simon Timms in his talk about "A sink full of C#" wherein he suggested that semaphores and mutexes require critical thinking. (Wikipedia says "a semaphore is a variable or abstract data type that is used for controlling access, by multiple processes, to a common resource in a concurrent system" and also "software that acts as a bridge between an operating system or database and applications, especially on a network" is the definition I see when I Google middleware.) Things have changed in our space. In "the old days" we had:

public static void Main(string[] args)
{
   var thread = new Thread(Whatever);
   thread.Start();
   Console.ReadLine();
}

 
 

result.AsyncWaitHandle is coming back to .NET but the task parallel library is the new way to go. It uses "tasks" which are basically just boxes holding results. The I/O completion port signals back into the framework when a task is complete in this model. There is a distinction between these two...

  • public async Task Whatever() {
  • public async void Whatever() {

...in that you can wrap them both in a try/catch but the exception will get swallowed in the case of the void. Async doesn't always run on a new thread. It is about using the client efficiently. During the lunch break at MeasureUp a strange video was played to make us glad we work with C# instead of JavaScript which showed off a lot of the wacky idiosyncrasies in JavaScript that makes me put up walls and close my mind rather than embrace the language. Number(true) will give you 1 for example, and stuff like that. Yucky. "foo" + + "bar" gives us fooNaN and 0.1 + 0.2 gives us 0.30000000000000004 and so on. ~~4.2 is the same as Math.round(4.2) in that there is an operator for rounding and you rock the double tilde to go there. Brian named dropped the Fetch Standard of which this suggests: "fetch() allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest." You need to install both node and jspm in Brian's model and some command line commands at npm were:

  • jspm init
  • jspm install aurelia-framework

Let's see. Some of the nonsense I scribbled down includes: Views in Aurelia are at the root and a template tag wraps everything else. Whatever that means. When you slurp in POCOs from a Web API endpoint at JSON objects, by default the names will swap from PascalCase to camelCase in abandoning the C# naming convention for the JavaScript convention. aurelia.io is the Aurelia homepage. Kyle Nunnery spoke last on making beautiful web APIs using ASP.NET Core. He suggested a good approach is an API first approach. His approach is:

  1. I'm going to build an API.
  2. I'm going to build my tooling on top of that.
  3. I'm going to build other tooling on top of that.

Kyle recommends url-based versioning like so: https://api.yourwebsite.com/v1/llamas ...and initially keeping messaging down to four simple status codes:

200OK
400Bad Request
401Unauthorized
500Internal Server Error

When you use Kestrel you can define options inside the parenthesis at .UseKestrel() as suggested above. Swagger was recommended for documentation.

Insert something at the very beginning of a list in C#.

List<string> strings = new List<string>() { "foo", "bar", "baz" };
strings.Insert(0, "qux");

 
 

The list will end up with this in it:

  1. qux
  2. foo
  3. bar
  4. baz

 
 

Addendum 10/12/2018: The zero doesn't have to be a zero. You may use this trick to insert midstream into a list.

Check to see if a restraint exists in T-SQL.

IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id =
      OBJECT_ID(N'FK_File_Users'))
   BEGIN
      PRINT 'Dropping FK_File_Users restraint.'
      ALTER TABLE dbo.[FILE] DROP CONSTRAINT FK_File_Users
   END
ELSE
   BEGIN
      PRINT 'FK_File_Users has already been dropped.'
   END

Find the foreign keys referencing a given table in T-SQL.

Exec sp_fkeys 'MyTableName'