Wednesday, December 31, 2014

I read an article online about the Great Firewall of China yesterday.

It seems that most of Google is now blocked there (Red China) with only about a fifth of the people being able to access it. This is really hurting business... er, well, at least it's irritating business people and making them cranky. Most of social media is forbidden too. China has its own thing (I can't recall the name) which it pushes people to use in lieu of Facebook and Twitter and China itself censors descent against the government at its own thing. The only social media still allowed is LinkedIn and in order for it to be acceptable it had to work out an arrangement with China wherein it self-censored some content on Tiananmen Square's history.

In attempting to add a plain Jane .html page in Visual Studio, I found the option for .html comically hard to find.

I right-clicked in the Solution Explorer and picked "Add" from the menu that appeared and "New Item..." from the menu that unfolded below that. I found the .html option under "Markup" under "Web" under "Visual C#" and I spent ten seconds searching so that merits spending a minute or three on this blog posting right?

Monday, December 29, 2014

the "Settings" table

I recalled this morning demoing an application for others which had a Settings table with many columns for random things like "what should the SMTP server be?" and one and only one row full of the settings. It was pointed out to be that this was really a goofy design as I'd have to change the table all the time to add new settings and that really a better format might be a table with a different row for each setting. :P

Friday, December 26, 2014

when a name is an adjective

Alright, I've just made it home from seeing the film "The Imitation Game" and some of my confusion regarding the use of Alan Turing's surname as an adjective has been alleviated. It didn't make sense to me for the longest time because it can mean two different things depending upon the context just as the term Boolean which comes from George Boole can mean two different things, namely and/or/not in 3D graphics or true/false in variables in code. I was building my own little theory that Turing meant "of cryptography" but it doesn't mean that at all as it turns out. In the case of a Turing machine, the machine is a computer. It's that simple. Turing machines are not the subset of all machines which are "of cryptography" but instead, more plainly, they are the subset of all machines which are computers. This is stated outright in the end notes of the movie I just saw. The other, different case is one of a Turing test which is a test to see if a subject is a person or a machine based upon interactions with it, the subject. There is some talk of these sorts of tests in the movie and I recalled another movie, Blade Runner, in which Harrison Ford's character gives Sean Young's character such a test and deduces that she is a machine.

Later on in the film, Sean Young, disillusioned, depressed, and realizing that she is a machine, turns around and asks Harrison Ford if he has ever given himself his own test heavily implying something! WAS DECKARD A REPLICANT? Meh, I digress.

Thursday, December 25, 2014

Type "view source" in at the app store at your iPhone and you'll see many tools you may download to view the HTML source at an iPhone's Safari browser.

I've always wondered how easy it would be to see into a Web SQL database at a web clip. I haven't per say found an app that will let me do so yet but it is a little hard to imagine it's impossible to do so.

XML stands for extensible markup language but what is extensible about it?

You can take some of the markup and easily change it up or shove new gunk into it, but you can say that about HTML too. What is extensible about XML that is not extensible about HTML? Perhaps it opens the gateway to extensibility for other stuff in empowering SOAP messaging. Whatever. Merry Christmas.

Saturday, December 20, 2014

disenchantment with Entity Framework 5 Code First stuff

I've rather lazily been tinkering on a GitHub project which uses the Entity Framework 5 code first stuff. I was all in love with this stuff because when you went to populate a database table and the table didn't exist, it just made the table! Well, I've finally gotten around to introducing a second database-hydrated object to my application and it turns out that it is not that simple after all. If you add an object in this manner to an empty database things work great, but if you try to add a second object you'll see an error like so:

Additional information: The model backing the 'CampaignContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

 
 

In my case, my first object was called Person and my second object was called Campaign and the two don't even join to each other in any way, but the presence of a Persons table makes it impossible to add a Campaigns table. This and this touch on the official workarounds and this suggests that if you do things the way you're supposed to that you may have NHibernate-style lazy loading. I ended up just making two separate databases with the two separate objects and then using Red Gate SQL Compare 11 to make a SQL script that I could run to spin up a schema with both objects. That accommodated the creating of both objects, error-free. The whole inherit-from-DbMigration trick (the official workaround) sure looks to me like it breaks the Don't Repeat Yourself rule in that you have to update your class that inherits from DbMigration whenever you also update your objects. An example of this might be adding another field to an object and having to add another column to the database at the class you have inheriting from DbMigration. The first of the links I share in this post also eludes to the need to have a separate console application independent of your real application for spinning up the database. Dirty! What a dream-crushing shutdown.

I sink. I'm crestfallen. I don't know what I'm going to do when I actually bring relational data into my app.

Friday, December 19, 2014

hard and soft controls for adjusting audio at an iPhone

Today's story:

  • Just two days ago I upgraded the iOS on my iPhone 4S to 8.1.2 (12B440) and found that video clips at YouTube (which now must be downloaded separate of default, baked-in apps) and Vine played audio at muted levels.
  • I found the soft control for the audio levels (a slider at "Sounds" under "Settings") and cranked it up, but this still did not return things to full blast (welcome to my world).
  • I convinced myself that there must be a second slider somewhere for video and when I couldn't Google my way into finding it I broke down and went to the Apple store today. It was pointed out to me that the physical volume control at the upper left of my phone was the other, hard control for audio and I was able to "turn things up to ten" by pressing its buttons.
  • I've had my phone for three years now and I had completely forgotten that the physical controls were even there because I never adjust them. If you make the big leap from 5.1.1 (9B206) to 8.1.2 (12B440) like I just did you may find the setting for the physical audio controls reset to a midstream default!

Thursday, December 18, 2014

censorship?

Someone or some organization has hacked Sony and leaked a bunch of gossipy emails about what a pain it is to work with certain celebrities embarrassing executives at Sony. There is analysis to suggest the government of North Korea is behind it all! It's hard to imagine that Sony would be targeted just because North Korea would find the comedic film "The Interview" about a plot to meet Kim Jong-un and...

"Take him out!" so offensive that it merits this sort of orchestration, but the same analysis pointing the finger at North Korea suggests this is the reason behind everything and as a result Sony isn't going to release "The Interview" on Christmas Day because they don't want anyone who attempts to see the movie to get hurt by terrorists retaliating in either a cyber sense or a more sinister way. What is really going on? I think it stinks that a Hollywood film (millions of dollars in production costs) has been shelved. I recall after 9/11 the Arnold Schwarzenegger film "Collateral Damage" (not his best work) was withheld from release for many months as its subject matter was about terrorism. When that awful movie finally was allowed to see the light of day I ran out and saw it and if "The Interview" ever becomes consumable I'll consume it too. What is really going on? Is this just what it appears to be on the surface?

Git Flow

I found this slide from this talk on my phone this morning and now I wish I had shared it earlier.

All of the main line commits in blue are development releases, each with a new version number, paralleled by a development branch in purple. You still check into a development branch before you go home for the day no matter what and hence the development branch is always going to be a little nasty and cowboyesque. The sea green or teal color is a release branch wherein a development branch's code is going spruced up a little bit before it gets merged into the main line where it becomes (ta-da) a versioned release of the software. The red is for a bug fix. In staring at the notes I scribbled down for the talk I can tell that I did not come away from the talk with guidance as to what the green branches are. If memory serves these are tangential development branches off the main (purple) development branch.

Wednesday, December 17, 2014

I suppose any exception that you're gonna hide from the public should be logged.

If you have a web site which attempts to send an email and just tells users that it can't in the event of the catch half of a try/catch wrapping the attempt to send mail being used, you probably should still be doing something with the exception instead of just swallowing it. This is a time to log!

Tuesday, December 16, 2014

Send an email via IMAP from C#! (compatible downwards to the 3.5 Framework, but assuming an Outlook server)

using System.Net;
using Microsoft.Exchange.WebServices.Data;
namespace AdministrableApplication.Email
{
   public class EmailFacilitator
   {
      public void Send()
      {
         ExchangeService service = new ExchangeService();
         service.Credentials = new NetworkCredential("me@example.com", "abc123",
               "outlook.whatever.com");
         service.TraceEnabled = true;
         service.AutodiscoverUrl("me@example.com", RedirectionCallback);
         EmailMessage message = new EmailMessage(service);
         message.Subject = "Can you see this?";
         message.Body = "Please write me back if you got this!";
         message.ToRecipients.Add("tomjaeschke@tomjaeschke.com");
         message.SendAndSaveCopy();
      }
      
      static bool RedirectionCallback(string url)
      {
         return url.ToLower().StartsWith("https://");
      }
   }
}

 
 

The following links helped me figure this out:

 
 

I originally got the project from here for the Microsoft.Exchange.WebServices.Data namespace which I then bolting into an existing solution in Visual Studio, but then I also ended up getting it anew from here when I got this error:

Could not find any resources appropriate for the specified culture or the neutral culture. Make sure \"Microsoft.Exchange.WebServices.Strings.resources\" was correctly embedded or linked into assembly \"Microsoft.Exchange.WebServices.Data\" at compile time, or that all the satellite assemblies required are loadable and fully signed.

 
 

Again, I got the error using the first of the two here links above and I got around the error by using the later. Yet, another error I then hit looked like this:

Autodiscover blocked a potentially insecure redirection to https://autodiscover-s.outlook.com/autodiscover/autodiscover.xml. To allow Autodiscover to follow the redirection, use the AutodiscoverUrl(string, AutodiscoverRedirectionUrlValidationCallback) overload.

 
 

The line which looks like...

service.AutodiscoverUrl("me@example.com", RedirectionCallback);

 
 

...in my above code had to be rewritten to its current shape as it originally looked like so...

service.AutodiscoverUrl("me@example.com");

 
 

...bringing in the static method which also had to be added in. This fix got me around this second pitfall.

Saturday, December 13, 2014

Specify the port when sending an email with an SmtpClient in C#?

SmtpClient smtpAgent = new SmtpClient();
smtpAgent.Host = "smtp.example.com";
smtpAgent.Port = 587;

Friday, December 12, 2014

I saw Jeffrey Palermo speak on "Iteration Zero" at the Austin .NET User Group Monday night.

Iteration zero is, as the name suggests, a leg of work before the first iteration of development on an application. It conceptually has a let's-set-things-up-right theme to it and it's sort of akin to laying down that blanket in a field before you set down everything else in a picnic as if you skip that step and just set food on the ground you may find ants crawling into the jam. There are things you can do upfront to set yourself up for success and if you just skip these things... the bugs get in. Jeffrey touched on the six pillars of Software Configuration Management as suggested in "Configuration Management Best Practices: Practical Methods That Work In The Real World" by Bob Aiello and Leslie Sachs which are:

  1. Source code management
  2. Build engineering
  3. Environment configuration
  4. Change control
  5. Release engineering
  6. Deployment

Only the first half of these really have to do with iteration zero. If you squint your eyes this first half (as a whole) should look like continuous integration to you and perhaps half of the talk focused on continuous integration. Jeffrey name-dropped another book: "Continuous Integration" by Paul M. Duvall ...JetBrains TeamCity is what his company Clear Measure uses for checking to see if a build script needs to be run every sixty seconds and then kicking off builds when GIT repositories have indeed changed and the Psake PowerShell approach to build scripts of James Kovacs is his preferred way of doing what everyone used to do with NAnt. There was a chunk of the presentation where Jeffrey showed off his canned, tweak-me-from-project-to-project Psake script which you can see for yourself here, and there was a chunk of the presentation where Jeffrey spoke to good practices in setting up a folder structure at a GIT repository (put the source code in a "src" folder in the root and not directly in the root itself), and there was a chunk of the presentation where Jeffrey went over the benefits of Onion Architecture. A lot of this is his "greatest hits" stuff covered elsewhere already on this blog. So what did I hear that was new?

  • He suggested that AliaSQL is the new Tarantino Project. It looks like you may get it at NuGet. This touches on what that's all about and why you should care.
  • Entity Framework 7 will not support anything from the prior versions. It will be a completely new animal, and with regards to the Onion Architecture this is a perfect example of why you should decouple your data integration from your core logic. MVC6 is going to be built out on top of the Web API stuff and will abandon the prior MVC architecture leaving no way to upport (making my own word up) the prior versions of MVC to it. This is a great reason to decouple your user interface implementation from your core logic.
  • Trello was suggested to be a good Kanban visualization tool as was JIRA, though JIRA sorta sounded second best.

In circling back to "Iteration Zero" thematically, the things to do upfront before you start writing code for the stories in the first sprint are:

  1. Set up your code base with the Onion Architecture.
  2. Set up source control for your code base.
  3. Set up continuous integration and use a tool like AliaSQL to roll out database changes as a part of that.

Thursday, December 11, 2014

It appears that not all paths through a C# method must return the return type if they instead throw an exception.

This is handy and good to know. You don't have to immediately follow up the line which throws the exception with a silly line that returns something which will never get run.

Wednesday, December 10, 2014

ThreatMetrix

...is a fraud protection service.

Natively compiled stored procedures look the same in SSMS but compile to .dll files on disk and thus take up disk space.

One needs to angst over if one has enough memory when using these. There is a performance payoff to make the worry worth it all.

white-space: pre-wrap;

...when placed on a pre tag will allow the pre tag to be set to a fixed width and force content inside to wrap to the next line. HOWEVER, spaces will still be respected normally within the pre tag.

an example of using a Java Bean

This .jsp page is gonna say: "My dog has fleas."

<%--
   Document : whatmydoghas
   Created on : Dec 10, 2014, 8:03:01 AM
   Author : tjaeschke
--%>
 
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>What My Dog Has</title>
   </head>
   <body>
      <h1>What My Dog Has</h1>
      <jsp:useBean id="lentil" scope="page" class="whatever.Lentil" />
      <jsp:setProperty name="lentil" property="owner" value="dog" />
      <jsp:setProperty name="lentil" property="possessions" value="fleas" />
      <jsp:getProperty name="lentil" property="sentance" />
   </body>
</html>

 
 

It's gonna use this Java Bean to craft the sentance.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package whatever;
 
/**
 *
 * @author tjaeschke
 */
public class Lentil {
   private String owner;
   private String possessions;
 
   public void setOwner(String owner) {
      this.owner = owner;
   }
 
   public void setPossessions(String possessions) {
      this.possessions = possessions;
   }
 
   public String getSentance(){
      return "My " + owner + " has " + possessions + ".";
   }
}

 
 

If the values are left off of the set tags in the .jsp page, Java will attempt to find request variables of the same names as the variables to set and hand in their values to the Bean. The presence of both a request variable and an inline value seemed to cause Java to blow up when I experimented with it.

Tuesday, December 9, 2014

Setup a passcode at an iPhone 4S.

Per this I went to:

Settings > General > Passcode Lock > Turn Passcode On

 
 

One may turn the passcode feature back off in the same place. My phone has iOS version 5.1.1 (9B206) still I should caution.

Make XML-within-HTML display well in .jsp/Java content.

Inspired by this, I started a .jsp page like so:

<%@page import="org.owasp.encoder.Encode"%>
<%@page import="java.io.StringReader"%>
<%@page import="java.io.StringWriter"%>
<%@page import="javax.xml.transform.OutputKeys"%>
<%@page import="javax.xml.transform.Source"%>
<%@page import="javax.xml.transform.Transformer"%>
<%@page import="javax.xml.transform.TransformerFactory"%>
<%@page import="javax.xml.transform.stream.StreamResult"%>
<%@page import="javax.xml.transform.stream.StreamSource"%>

 
 

I then quickly break into Java at the top of the .jsp page before getting into significant HTML content. Amongst the stuff in Java is this blob of code which takes in an existing string called xml, reshapes it, and assigns it to a request attribute called xml also. The majority of this is shamelessly stolen from this.

Source xmlInput = new StreamSource(new StringReader(xml));
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", 5);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(xmlInput, xmlOutput);
xml = xmlOutput.getWriter().toString();
request.setAttribute("xml", Encode.forHtml(xml));

 
 

I render the request attribute like so and I want to stress that the pre tag is required and without it all the work done so far becomes moot.

<pre>${xml}</pre>

 
 

It turns out that this line...

transformer.transform(xmlInput, xmlOutput);

...has to be wrapped in a try/catch if you implement it in a plain Jane Java class instead of a .jsp page. They may be made like this:

 
 

try
{
   transformer.transform(xmlInput, xmlOutput);
}
catch(Throwable t)
{
   String whatever = t.toString();
}

String foo = Integer.toString(bar);

Is an example of casting an int type to a String type in Java.

BigDecimal in Java

public void whatever(BigDecimal amount) {

When attempting to call a method like this, you will need at the top of your file...

 
 

import java.math.BigDecimal;

...or...

<%@page import="java.math.BigDecimal"%>

 
 

You will find that you will not be able to just hand in a float for a BigDecimal like so:

whatever(13.42);

 
 

Instead, you'll have to do something like this:

whatever(new BigDecimal(13.42));

the SMART acronym for writing requirements

  • Specific
  • Measurable
  • Attainable
  • Relevant
  • Testable

Monday, December 8, 2014

React when a dropdown menu changes with jQuery!

$(function() {
   $("#template").bind("change", function(){
      window.location = "foo.jsp?bar=" + $(this).find(':selected').val();
   });
});

.ToLower() is to C# what .toLowerCase() is to Java.

alright?

A double-slash in a URL is largely harmless.

These two behave the same in that they both work:

 
 

...however I also found a thread here which suggests that a double-slash may confuse Google when it attempts to crawl your website.

desaturate

...in a Photoshop context might mean to drop the color from an image and make it black and white. Any one color on the RGB scale has a saturation level. Unsaturated colors are grey scale colors, but the more saturation a color has the closer it is to a bright, vivid, and unmuddied color.

We can edit and upload Vines now?

That sucks. It kinda ruins it for me. I liked how they were in the moment and of the moment.

Sunday, December 7, 2014

I may need to write some C# code which sends email via IMAP instead of SMTP.

That means an SmtpClient implemenation like this is out and per this there is not a way do the IMAP stuff baked into C# itself. I'll have to use a third party library. Suggestions at the Stack Overflow thread include:

death march

Wikipedia says: "In project management, a death march is a project where the members feel it is destined to fail, or requires a stretch of unsustainable overwork."

Friday, December 5, 2014

the explosion-free way to check to see if a string is not null in Java

if (!(foo.bar() + "").equals("null")) {

String.format in Java!

String foo = "My %s has %s.";
String bar = String.format(foo, "dog", "fleas");

Specify the English culture when casting a decimal to a string and then splitting on the decimal point as there is no decimal point in Spanish counterpart.

public static string CovertPaymentAmountToCardinalCommerceFriendlyString(Decimal
      paymentAmount)
{
   string decimalAsString = Math.Round(paymentAmount, 2).ToString(new
         System.Globalization.CultureInfo("en"));
   if (decimalAsString.Contains("."))
   {
      string[] paymentAmountArray = decimalAsString.Split(".".ToCharArray());
      if (paymentAmountArray[1].Length == 1)
      {
         return paymentAmountArray[0] + paymentAmountArray[1] + "0";
      } else {
         return paymentAmountArray[0] + paymentAmountArray[1].Substring(0, 2);
      }
   } else {
      return decimalAsString + "00";
   }
}

 
 

The Spanish stringification would have a comma in it in lieu of a period. :(

a hack to make sure a missing GET variable doesn't cause an error downstream in Java

String whatever = "" + request.getParameter("whatever");
if (whatever.equals("foo")) {

String whatever = request.getParameter("whatever");

...seems to be the way to fish out both GET and POST variables at a .jsp page.

F7 seems to step into code in NetBeans IDE 8.0.1.

Ctrl-F7 is to step out.

Thursday, December 4, 2014

dummy routing numbers to test ACH stuff with

What follows comes from here.

021272655Citibank FSB
031000053PNC Bank NA
044000804Bank One Trust, NA
121000358Bank of America, NA
121000497Union Bank of California
121042882Wells Fargo and Company
121100782Bank of the West
121122676United States Bank
121140218West America Bank
121181866World Savings Bank, FSB
122000247Wells fargo and Company
122000496Union Bank of California
122000661Bank of America, NA
122101191Wells Fargo and Company
122105278Wells Fargo and Company
122220593Santa Barbara Bank & Trust
122221686Mid-State Bank & Trust
122239982HeritageOaks Bank
123000220US Bank, NA
125000024Bank of America, NA
125200057Wells Fargo Bank Alaska
256074974Navy FCU
321070007California Federal Bank FSB
321075947Chevron Texaco FCU
321171184Citibank FSB
321175261Golden One Credit Union
321176833MeriWest Credit Union
321177706Bay Federal Credit Union
321180379Addison Avenue FCU
321270742Wells Fargo Bank Nevada
322270356Downey Savings & Loan
322270822Coast Hills Federal Credit Union
322271724Citibank FSB
322271779California Federal Bank FSB
322281617San Diego County CU
322282001Orange County Teachers FCU
322282713SESLOC FCU
322271627Washington Mutual Bank
325070760Washington Mutual Bank
021204416Amboy National Bank
261071548Excel Federal Credit Union

oldapps.com seems to be the place get old installers for old versions of Internet Explorer

See: http://www.oldapps.com/internet_explorer.php?old_internet_explorer=27

Use a web page as a ghetto/scrape web service in any of the old web technologies which have been around since the turn of the millennium side by side with jQuery .ajax.

This is example could be a .jsp page:

<%--
   Document : pseudoservice
   Created on : Dec 3, 2014, 9:38:40 AM
   Author : tjaeschke
--%>
<%@page contentType="text/html; charset=UTF-8"%>
<%
   String foo = request.getParameter("foo");
   String bar = request.getParameter("bar");
   String result = foo + bar;
   request.setAttribute("result", result);
%>
${result}

 
 

Talk to it and back like this:

var pseudoServiceData = new Object();
pseudoServiceData.foo = "baz";
pseudoServiceData.bar = "qux";
$.ajax({
   url: "http://www.example.com/pseudoservice.jsp",
   type: "POST",
   data: pseudoServiceData,
   success: function(data) {
      $('#whatever').html(data);
   },
   error: function() {
      $('#whatever').html("Oh no!");
   }
});

The Galaxy 4.4 will allow you to compose text messages verbally.

A coworker told me about this yesterday. Dictation gets "listened to" and then made sense of and cast to English words.

Addendum 5/13/2015: It have learned that running iOS 8.1.3 (12B466) that my iPhone 4S has this capacity too. When one begins to type a text message a microphone icon appears at the lower row of buttons just left of the spacebar.

Wednesday, December 3, 2014

Use .replace to remove a piece of a string in Java!

String uri = request.getScheme() + "://" + request.getServerName();
if(request.getServerPort() != 80) {
   uri = uri + ":" + request.getServerPort();
}
uri = uri + request.getRequestURI();
uri = uri.replace(request.getServletPath(),"");

figure out what is at the URL line in Java

This suggests fishing out what is in the URL line from a .jsp page like so...

String uri = request.getScheme() + "://" + request.getServerName() +
      ":" + request.getServerPort() + request.getRequestURI() + "?" +
      request.getQueryString();

 
 

...and that seems to work really good. If you are wondering what "request" is, it seems to be per this a HttpServletRequest and it seems to just work in a .jsp page. When I attempted to wire it up to work (as suggested in the second stack overflow link in this posting) NetBeans IDE 8.0.1 told me:

variable request is already defined in method mergedScriptlets(HttpServletRequest, HttpSession, ServletContext, JspWriter, ServletConfig, JspContext, Object, PageContext, Throwable)

The green play arrow button in NetBeans IDE 8.0.1 does not let you stop at brake points like you are used to in Visual Studio.

Instead, the NetBeans version of the debugger is run from the icon immediately to the right which looks like a smaller green play arrow next to a torn scrap of paper with the numbers one and three on it. F5 works just like F5 in Visual Studio but F8 steps to the next line instead of F10. I don't yet know how to step into a method call as I might with F11 in Visual Studio.

Content is not allowed in prolog.

This touches on this error message that rears its head when parsing XML in Java. Here "prolog" implies header and the first character of your XML is not going to be a less than sign like it should be. It is something sick, a product of goofy encoding. It may look like a less than sign but its not. Manually replace it.

Monday, December 1, 2014

Sometimes the restart is the fix after all.

I changed a username at a VMware VM and a web site hosted there lost the ability to talk to a database hosted at a different VM even though the application pool for the web site was using my LAN account whose password did not change and which had always been able to access said database. Also, the connection string specified "Integrated Security" in lieu of a username and password so things should have just fallen over to use whatever user was specified at the application pool. I don't get it. Anyways, I restarted the physical machine hosting both VMs and now everything is shipshape. What changed? The error I had been getting was "The target principal name is incorrect. Cannot generate SSPI context." and now it is magically alleviated.

cannot "action" request parameter method

This error rears its head in Java when attempting to talk to a web service as suggested here without having a parameter for "action" on the JSON object handed in.

I'm learning that one does not have to worry about burning two separate MSDN keys when installing a Windows operating system at two separate VMware VMs.

Nothing sanity checks the uniqueness.

Sunday, November 30, 2014

SDLC stands for systems development life cycle

The Wikipedia write-up has a chart with an arrow leading from Design to Implementation then to Maintenance then to Planning then to Analysis and then back to Design in a circular pattern. It's a would-be play for keeping things clean.

Thursday, November 27, 2014

faking type safety in dynamic languages?

Happy Thanksgiving everyone! I was thinking today in doing laundry of a conversation I had with a coworker about the challenge of exposing a .js script to the public and dealing with the public's capacity to hand in anything for variables. I don't know what my coworker did to try to fake the type safety he needed in his situation. I guess if it were me and it were JavaScript, I'd pass the object through a bunch of truthy/falsey interrogations wrapped inside a try/catch and ultimately set a flag for whether or not the visitor was tall enough to ride the rollercoaster ride ahead.

Monday, November 24, 2014

I start a six day break confused as to how to use the web services in Java.

Right-click on the applicable folder in NetBeans IDE 8.0.1 and pick "Web Service..." from the submenu under the "New" option in the menu which appears and you will be able to make a web service like so:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package foo.bar.baz.qux;
 
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
 
/**
 *
 * @author tjaeschke
 */
@WebService(serviceName = "AjaxWebService")
public class AjaxWebService {
 
   /**
    * This is a sample web service operation
    */
   @WebMethod(operationName = "hello")
   public String hello(@WebParam(name = "name") String txt) {
      return "Hello " + txt + " !";
   }
}

 
 

It's gonna look like this, and you'll have to click over to the "Source" tab to actually see the code:

 
 

Under your project in the "Projects" pane there will be a "Web Services" folder and therein you may right-click on your web service and pick "Test Web Service" to test the web service. It will bring up a form at a url such as http://localhost:8080/Java/AjaxWebService?Tester which will post to itself while passing, in the case of the example above, two fields PARAMhello0 and action with action passing "hello" for its value. { PARAMhello0: "World", action: "hello" } may be passed as an object to a jQuery .ajax POST against http://localhost:8080/Java/AjaxWebService?Tester to also get back the test results which are more than just what I'd expect for the usual results. The question is, how do I only get back the usual results. That I have yet to figure out.

You shouldn't have to restart IIS to see a change you just made in the Web.config.

A change to Web.config should restart the web application or web site, even an extraneous space. There should not be any sort of Web.config caching.

Who sings this?

Shazam and SoundHound are tools which will let you identify what song is playing in the restaurant you are catching lunch at from you smartphone. Your phone will "listen" to the ambient audio and tell you what it is. I went to Swift's Attic for lunch with some coworkers today for the very first time and ate goat for the first time as well. They play some pretty good music in Swift's Attic and thus Shazam and SoundHound creeped into our conversation.

Coworkers were talking today about whether it is OK to test old versions of IE using the emulator in Edge or if VMs needed to be spun up with older versions.

One of my coworkers felt that the VM overhead was really the best way to go. We have seen discrepancies between the real thing and emulations. I think the example I am thinking of had to do with DevExpress control wackiness. Naturally this challenge begs the question: "How do I even install old versions of IE?" Well, a different coworker pointed out that if you install Windows 7 and just don't upgrade IE that you'll have IE8. But how can one have IE9 or IE10 without upgrading all the way to IE11? Well, the coworker who suggested the VM trick found http://www.microsoft.com/en-us/download/internet-explorer-9-details.aspx for IE9 and I don't know what to do about IE10. I kind of just use the emulator myself, but then my title is developer and not tester.

search Skype history

  1. select a conversation
  2. open up the history as far back as is appropriate
  3. press Ctrl-F

The IDE will determine if you like your job (if you're me).

There is no way to right-click on a method call in NetBeans IDE 8.0.1 and "go to declaration" so that means that writing Java is going to be just as ghetto as writing JavaScript in Sublime Text. Luckily, that challenge is not representative of my greater employment. It's just for one sprint and then I'll get back in Visual Studio and be kissing the ground like an astronaut who has just been through a rocky flight.

Sunday, November 23, 2014

A div is going to be at least 19 pixels tall in Internet Explorer 6.

If you don't specify a width on a div it will be as wide as it can be, filling whatever wraps it horizontally. If you don't specify a height on the div or put anything inside of it then it will be zero pixels tall vertically, unless you are using IE6 where it will be nineteen pixels tall.

How can you really tell what percentage of your codebase is under test?

I wondered this to myself this weekend. How do you really know? If I'm supposed to have 85% coverage how close am I? In the C# space there is a JetBrains tool called dotCover for this it seems. I Googled some just now and found it.

convert numbers into spelled-out words

Humanizer was mentioned in this talk by Shawn Weisfeld. I forgot to mention it until now. It will do things like, per what Shawn said (I haven't tried it), break up Pascal casing and camel casing into space separated words and also convert numbers into spelled-out words such that 13 becomes thirteen, etc.

a virtual burka for bikini model Kate Upton

  • The following cascading style sheet formatting...
<div style=" width: 124px;
height: 69px;
 
  background-image:url('https://31.media.tumblr.com/
cb208f23be8c5b7f8ec74b65a9e0b1bc/
tumblr_nckypp4zmb1sfer7xo1_1280.jpg');
"></div>
  • ...will show us merely a portion of an image which is seven hundred ninety-seven pixels wide by a dozeny hundred pixels tall as the background of a div. It specifically shows us what is in the very upper left corner.
  • If we wish to offset the chunk of the greater image shown to in effect show a different chunk of the greater image we may do so with the background-position CSS property like so...
<div style=" width: 124px;
height: 69px;
background-position: -391px -825px;
 
  background-image:url('https://31.media.tumblr.com/
cb208f23be8c5b7f8ec74b65a9e0b1bc/
tumblr_nckypp4zmb1sfer7xo1_1280.jpg');
"></div>
  • ...creating an effect like such:
  • I was a little surprised to learn that if we moreover rotate one hundred and eighty degrees like this...
<div style=" width: 124px;
height: 69px;
background-position: -391px -825px;
-ms-transform: rotate(180deg);
-webkit-transform: rotate(180deg);
transform: rotate(180deg);
 
  background-image:url('https://31.media.tumblr.com/
cb208f23be8c5b7f8ec74b65a9e0b1bc/
tumblr_nckypp4zmb1sfer7xo1_1280.jpg');
"></div>
  • ...that the content rotated will be restrained to the original "selection" instead of showing us what is offset from the lower right corner of the background image. I guess I shouldn't really have been surprised. We are, after all, rotating the div itself and not the background image. Duh.

 
 

Addendum 12/14/2015: Yesterday I realized that the tumblr image has been done away with and thus this blog posting has been sabotaged. Here is a recreation of sorts of what once was:

 
 

Addendum 6/5/2018: The missing image is back! Good stuff. Silly tumblr.

Saturday, November 22, 2014

border-spacing: 0; is the CSS way of emulating the old school cellspacing="0" inline tag for an HTML table.

You slap border-spacing: 0; as a style onto a table to make it happen.

Encode.forHtml in Java!

<%@page import="org.owasp.encoder.Encode"%>

...then later in code...

<% request.setAttribute("foo", Encode.forHtml(bar)); %>

read from a file in Java

<%@page import="java.nio.file.Files"%>
<%@page import="java.nio.file.Path"%>

 
 

...imagine more code here and then...

 
 

if(isDescription) {
   Path descriptionPath = Paths.get(location + description + extension);
   for (String descriptionLine: Files.readAllLines(descriptionPath)){
      descriptionContents = descriptionContents + descriptionLine;
   }
}
%>

see if a file exists in Java

<%@page import="java.io.File"%>
<%
String location = getServletConfig().getServletContext().getRealPath("/") + "x.txt";
File file = new File(location);
if(file.exists() && !file.isDirectory()) {
   %> There is a file. :) <%
} else {
   %> There is NOT a file. :( <%
}
%>

page directive cannot be used in a tag file

One cure for an inability to bring significant coding content into a Java master page kept in a .tag file is have the .tag file reference a .jsp file with an include tag and then do what needs to be done inside of the .jsp page.

Java comments

<%--
   Whatever
--%>

splitting and comparing strings in Java

Should request.getServletPath().toLowerCase() give /index.jsp then...

<%
String location = request.getServletPath().toLowerCase();
for (String pieceOfLocation: location.split("/", 0)) {
   for (String anotherPieceOfLocation: pieceOfLocation.split("\\.")) {
      if (!anotherPieceOfLocation.equals("jsp")) {
         location = anotherPieceOfLocation;
      }
   }
}
if (location.equals("index")) {
   location = "default";
}
%>
<%=location%>

 
 

...with give back default

that squiggly red line

  • in Microsoft Word it means you have a misspelled word
  • in Visual Studio it means you have something that won't compile
  • in NetBeans IDE 8.0.1 it can mean either thing :(

svn externals

This is the subversion space trick for sharing one stylesheet across numerous projects in source control or doing a similar stunt to keep content referenced by multiple projects in one place in source control.

 
 

Addendum 10/28/2015: Use TortoiseSVN to add a new external at a folder that has externals intergrated already like so:

  1. right-click on a folder and pick "Properties" under "TortoiseSVN"
  2. select the svn:externals line item and click "Edit..."
  3. click the "New..." button at the list of externals

Friday, November 21, 2014

Hey Java, what .jsp page am I on?

<li <% if(request.getServletPath().toLowerCase().contains("fun.jsp")) { %> id="current"
      <% } %>><a href="index.jsp">Fun</a></li>

including classes in Java

This should allow you to use a class in a .jsp page:

<%@page import="foo.bar.baz.qux.Signature"%>

 
 

Signature would live here:

C:\rootofyourproject\src\java\foo\bar\baz\qux\Signature.java

 
 

If Signature has this inside:

package foo.bar.baz.qux;
public class Signature {
   public static String Somethingerother = "meh";
}

 
 

You might use it in your .jsp page like so:

<% request.setAttribute("thingy", Signature.Somethingerother); %>

Making a "master page" in a Java web site!

At first I thought I might have to make classic includes as described here around page content like so:

<jsp:include page="whatever.jsp" />

 
 

But this revealed a better way. It suggests building a file at web/WEB-INF/tags/genericpage.tag like so:

<%@tag description="Overall Page template" pageEncoding="UTF-8"%>
<%@attribute name="header" fragment="true" %>
<%@attribute name="footer" fragment="true" %>
<html>
   <head>
      <jsp:invoke fragment="header"/>
   </head>
   <body>
      <div id="whatever">
         <jsp:doBody/>
      </div>
   </body>
</html>

 
 

...and using it like so:

<t:genericpage>
      <jsp:attribute name="header">
         <title>Foo</title>
      </jsp:attribute>
      <jsp:body>
         <p>Baz</p>
      </jsp:body>
</t:genericpage>

 
 

This mostly worked great, but I started seeing an error to do with breaking into Java inside of the jsp:body tag which looked like this:

Scripting elements (<%!, <jsp:declaration, <%=, jsp:expression, <%, <jsp:scriptlet ) are disallowed here.

 
 

To fix things implementations like this:

<script src="<%=Signature.Foo %>" type="text/javascript" language="javascript">
</script>

 
 

...were made like look this:

<script src="${bar}" type="text/javascript" language="javascript">
</script>

 
 

...begging the question: What is ${bar}? Per this, that is an example of something which would need to be defined as an attribute upstream of the opening t:genericpage tag like so:

<% request.setAttribute("bar", Signature.Foo); %>

marshalling and unmarshalling

...means serializing and deserializing respectively to Java peeps.

Three hurdles I cleared in previewing a Java app!

  1. When you click the "Run Project" button in NetBeans IDE 8.0.1 and you see an error saying "The target server has not been set or has been removed. Right-click the project in the Projects window and choose Resolve Missing Server Problem to set the target server." ...really you need to right-click the topmost node in the "Projects" pane to make this happen. I picked GlassFish as the server.
  2. "C:\Whatever\nbproject\build-impl.xml:1014: Warning: Could not find file C:\Users\jdoe\Downloads\encoder-1.1.1.jar to copy. BUILD FAILED (total time: 3 seconds)" is another error I saw in attempting to run the server for the first time. I was missing a reference to encoder-1.1.1.jar which one may download at https://www.owasp.org/index.php/OWASP_Java_Encoder_Project ...right-click on "Libraries" in the "Projects" pane and pick "Properties" to remove and readd the dependency. Libraries is to Java what References is to ASP.NET it seems.
  3. "The Java DB location is not set correctly." is yet another error I encounted. It was set to C:\Program Files\Java\jdk1.7.0_71\db abd I had to set it to C:\Program Files\Java\jdk1.8.0_25\db instead. This was done by tabbing to the "Services" pane, right-clicking "Java DB" and picking "Properties..."

Different versions of Java side-by-side?

I started to write a blog posting which said: "It seems like it is pretty painless to install several versions of Java side by side. All you have to do is swap out where the JAVA_HOME variable points to to use a different version." ..but that's not true. I had to uninstall the version 1.7x stuff to get the version 1.8x stuff to behave.

Download the latest version of Java...

...here!

Wednesday, November 19, 2014

Why does everyone hate Java?

import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;

...will allow you to do Base64 encoding with JDK 1.7.0_71 but when you include lines in NeatBeans there will be a yellow highlight beneath the lines. If you mouse over the lines you will get text telling you that it "is internal proprietary API and may be removed in a future release"

 
 

import java.util.Base64;

...in contrast will allow for Base64 encoding in the latest JDK but not in JDK 1.7.0_71.

The typical unhiding-of-files stuff in Window Server 2008 R2...

...upon starting up a new machine or a VM may be done from the ribbon at the top a Windows Explorer window. The "View" tab will have checkboxes for: "File name extensions" and "Hidden items"

NetBeans is another IDE for Java

https://netbeans.org/downloads/ has it!

If you only want to check out some folders one tier deep within the greater folder you are to checkout with TortoiseSVN...

...that's doable! Click the "Choose items..." button. This will allow you to set "Custom depths" instead of having a "Fully recursive" checkout.

prep Java?

some dirty notes from walking through a better blog posting at http://www.javacodegeeks.com/2013/03/setup-your-java-development-environment-in-windows-7.html

  1. latest JDK versions is JDK 7u17 (update 17 that is)
  2. get "Java SE Development Kit 7" at http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html and install it
  3. Java ends up at 'C:\Program Files\Java\jdk7_17' and the JRE (java run time) is at 'C:\Program Files\Java\jre7'
  4. https://docs.oracle.com/javase/7/docs/ appears at the end of the install
  5. type "java -version" at a command prompt to confirm it is installed
  6. we need to set the JAVA_HOME variable
  7. Type "View Advanced System Settings" at the search in Windows Server 2012 R2 to bring up the "System Properties" dialog box with the "Advanced" tab up. Then click on "Environment Variables..."
  8. Add a "JAVA_HOME" variable and map it to C:\Program Files\Java\jdk7_17
  9. test by opening a command prompt and typing "echo %JAVA_HOME%" (I had to close out the "System Properties" dialog box and reopen the command prompt to get this to work/stick)
  10. next is to set up Apache Ant 1.9.4 and ANT_HOME (a variable like JAVA_HOME)
  11. get Apache Ant at http://ant.apache.org/bindownload.cgi and unzip to C:\ant194\ then make an ANT_HOME environment variable just as was made the JAVA_HOME environment variable and map it to C:\ant194\
  12. Environment Variables will also have "System variables" and one of these will be called "Path" and if you edit this variable you will see something like this inside: %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\
  13. We need another semicolon separated value here. Add, in editing: %ANT_HOME%\bin
  14. Run "ant -version" at the command prompt to be sure you are not told "huh? what?" or a similar error message
  15. "Unable to locate tools.jar. Expected to find it in C:\Program Files\Java\jre7\lib\tools.jar" is an error message I saw when I attempted this. After some digging I realized that this file really lives at C:\Program Files\Java\jdk1.7.0_71\lib\tools.jar and if I just copied it (made a duplicate outright) to location expected the error message would go away.
  16. alright, next is Apache Maven (a build tool and a dependency management tool as well which may be found at http://maven.apache.org/download.cgi) and MAVEN_HOME
  17. download Maven 3.2.3 (Source zip) then unzip it to C:\maven323\bin\ and finally map the MAVEN_HOME variable to C:\maven232\apache-maven\src and also jam %MAVEN_HOME%\bin into the Path variable
  18. in attempting to test with "mvn -version" I got... Error: JAVA_HOME is set to an invalid directory. JAVA_HOME = "C:\Program Files\Java\jdk7_17" Please set the JAVA_HOME variable in your environment to match the location of your Java installation.
  19. I then realized that I had JAVA_HOME mapped to C:\Program Files\Java\jdk7_17 when it should instead be mapped to C:\Program Files\Java\jdk1.7.0_71
  20. After some investigation I realized that fixing the path is also the fix for the first error I ecountered with Ant.
  21. On the other side of this error I find a different error claiming "Error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher"
  22. The cure: since writing the above I have realized I should "Maven 3.2.3 (Binary zip)" from C:\maven232\apache-maven\src and not "Maven 3.2.3 (Source zip)" ...and I've changed MAVEN_HOME to M2_HOME and I have it mapped to C:\maven232

Tuesday, November 18, 2014

an interesting trick with a primary key

On an application I'm working upon there is a column with a numeric value which references the numeric key in another table. The other table has a plain-text explanation for what each of the ids (a 1, a 2, and a 3) mean in a different column, but this other column with varchar data is never joined into any queries. This separate table exists ONLY to restrain what the values back at the first table are and to make sure they are each a 1, a 2, or a 3! The one, two, and three are made sense of in code on the C# side where they are cast to an enum.

When writing a "lock" around a jQuery .ajax implementation...

...with some fashion of JavaScript truthy or falsey variable being used as a flag. It might be best to...

  1. Start unlock
  2. Lock at first attempt
  3. Only unlock upon error (not success, not complete)

...if you can help it. The asynchronous churning that you don't want to interrupt by triple-clicking the button that kicks off the process is likely going to happen when things are going right. If there is not a need to allow a successful process to be run twice then just take that out of the workflow.

Monday, November 17, 2014

'None' is an invalid XmlNodeType. Line 1, position 123.

I hit this error trying to read the second of a series of nodes with an System.Xml.XmlReader type in C# like so:

myXmlReader.ReadToFollowing("Whatever");

 
 

The cure was to put line breaks between the nodes with a backslash and a lowercase n like so:

\n

 
 

...but I should not of had to do this. What's going on?

Sunday, November 16, 2014

} else {

My superior really doesn't care for my love of...

} else {

 
 

...and is pretty vocal of having me break it into three lines* like so:

}
else
{

 
 

*At least this is the case in C#, not JavaScript where I still do it.

How did I fall in love with } else { anyways? I think this was an old PHP convention. I like that it tucks everything onto one line. Also, if I can make an if statement and what happens should the if statement's condition be met be one line of code, I'm going to do so. They didn't like this at my prior place of employment.

Redis Cache for Cats!

First read this. OK. Now that you've read that, consider a "Cat" made like so:

using System;
namespace RedisExperiment.Models
{
   public struct Cat
   {
      public DateTime BirthDay { get; set; }
      public int Lives { get; set; }
      public bool IsPurring { get; set; }
   }
}

 
 

Alright, if we have something like what follows then "You have cloned your cat!" will end up in ViewBag.Whatever.

using System;
using System.Web.Mvc;
using RedisExperiment.Models;
using StackExchange.Redis;
namespace RedisExperiment.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         Cat orginalCat = new Cat()
         {
            BirthDay = new DateTime(2011,6,7),
            Lives = 9,
            IsPurring = true
         };
         var _connection = ConnectionMultiplexer.Connect("localhost");
         IDatabase db = _connection.GetDatabase();
         db.HashSet("Cat", "BirthDay", orginalCat.BirthDay.ToString());
         db.HashSet("Cat", "Lives", orginalCat.Lives.ToString());
         db.HashSet("Cat", "IsPurring", orginalCat.IsPurring.ToString());
         Cat clone = new Cat();
         foreach (var item in db.HashGetAll("Cat"))
         {
            if (item.Name == "BirthDay") clone.BirthDay = Convert.ToDateTime(item.Value);
            if (item.Name == "Lives") clone.Lives = Convert.ToInt32(item.Value);
            if (item.Name == "IsPurring") clone.IsPurring = Convert.ToBoolean(item.Value);
         }
         if (orginalCat.Equals(clone))
         {
            ViewBag.Whatever = "You have cloned your cat!";
         } else {
            ViewBag.Whatever = "Your clone is messed up!";
         }
         return View();
      }
   }
}

Redis Cache!

using System;
using System.Web.Mvc;
using StackExchange.Redis;
namespace RedisExperiment.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         var _connection = ConnectionMultiplexer.Connect("localhost");
         IDatabase db = _connection.GetDatabase();
         db.StringSet("MyName", "Tom", TimeSpan.FromHours(13));
         ViewBag.Whatever = db.StringGet("MyName");
         return View();
      }
   }
}

...is about the easiest example I can think for how to use Redis Cache. In the above code for an ASP.NET MVC C# Controller, ViewBag.Whatever is gonna end up with "Tom" in it. If you take out the middlemost line of code with StringSet in it, then "Tom" will end up in ViewBag.Whatever anyways if you run the code again within, I suppose, thirteen hours. If you were to run the code more than thirteen hours later or you were to never have the middlemost line of code in the code above to begin with to set a value for MyName then ViewBag.Whatever would just end up with null inside. Make sense? The code above is largely a recreation of code displayed by Shawn Weisfeld at a talk he gave on Monday night at the Austin .NET User Group. In his example he used "Shawn" and not "Tom" though as you might imagine. Anyways... something Shawn didn't really touch on is how sexy this stuff is in the Azure space (where I've never worked personally) where there can be no reliance on using the traditional cache or session as your application will straddle many machines instead of being hosted on just one. I think this is the real reason most of us care about Redis. I haven't had to go there myself and I haven't used it at my work. I have just played with Redis for the first time in the past few days now that I've been exposed to it. You need two things to get this stuff working if you want to spin up an easy example like the one I have above:

  1. You need StackExchange.Redis as a reference in your ASP.NET project to make the lines of code above not be angry with you. You may get that here, or you may just pull it from NuGet like so to have it end up in your packages folder:
    Install-Package StackExchange.Redis

  2. You need an actual server to talk to. You may get that here or you may also get this from NuGet like so:
    Install-Package Redis-64
    "localhost" seems to find the server just fine which will by default run on port 6379. The server will be an executable called redis-server.exe and if you get it the NuGet way it will just end up in your packages folder. If you double click you should see a console app sitting open on your desktop. Just keep this up to experiment.

There was more to Shawn's presentation than just what I offer here. Perhaps I'll write more later. Dunno.

Friday, November 14, 2014

Use the TestInitialize attribute to do setup steps for all tests in a class in C#.

using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Whatever.Yo.Tests
{
   [TestClass]
   public class UnitTests
   {
      private string _foo;
      
      [TestInitialize()]
      public void MehTestInitialize()
      {
         _foo = "foo";
      }
      
      [TestMethod]
      public void foo_test()
      {
         Assert.AreEqual(_foo,"foo");
      }
      
      [TestMethod]
      public void bar_test()
      {
         Assert.AreNotEqual(_foo, "bar");
      }
   }
}

Beneath the "TOOLS" menu in Visual Studio 2013 "Extensions and Updates..." shows you plugins while "Add-in Manager..." shows us add-ins.

Yawn.

Thursday, November 13, 2014

That plugin Mike Swanson wrote for saving Adobe Illustrator vector shapes as XAML markup has a smarter sister!

Before you read this blog posting please first read this blog posting which should leave you mildly impressed. You're probably thinking to yourself: Well, that's kind of interesting but when am I ever gonna use XAML? I certainly know how you feel. Well, now for the good news, Ai->Canvas Plug-In for Adobe Illustrator is a comparable Adobe Illustrator plugin, installed in the same manner, by Mike Swanson, which lets you export to an HTML5 Canvas. You'll see an option for <canvas> (*.HTML) whenever you go to export and it will make an .html file.

Let's go through an example. Having made a swan sing a swan song for XAML in my prior blog post, I wanted to instead use some artwork for this blog posting which said "new" and "modern" instead of "old" and "dying" and in sticking with birds and being jokey I thought I'd make a stork bringing us a baby in a bag which symbolizes the newness of HTML 5 I guess. I broke my artwork up across several layers again in Adobe Illustrator. The background surrounding everything was a 600 points by 300 points rectangle carefully made in the name of having a canvas that was ultimately 600 pixels by 300 pixels. The number 5 which you see was converted to curves instead of being kept as text.

Once I export, and save an .html file in doing so, a browser opens showing me that my artwork has survived the translation. If I open the .html in Notepad I may see the JavaScript which crafts the visuals I see in the browser. It all happens by way of drawing on a Canvas. The artwork is indeed 600 pixels by 300 pixels and comments break up the code along the divides that once were layers back in Illustrator.

If you're like me, you've just jumped from mildly impressed to really impressed and you're imagining how you'll actually use this at work!

When adding a new project to a solution in Visual Studio 2013 and encountering an inability to reference other projects...

Well, you likely need to set the target framework for the project to be 4.5.1 instead of 4.5. Duh! The symptoms of this sickness will be a triangle with an exclamation mark in it appearing over the reference in the Solution Explorer and an inability on the part of the compiler to understand namespaces in the other projects you call out to.

Once you make a snip with the Windows 7 snipping tool you may just turn around and Ctrl-V to send it to someone in Skype without having to save off a .PNG first.

Nice.

Doing a .Response.Write off of the current HttpContext in an ApiController may misbehave in Internet Explorer.

Internet Explorer cannot display the webpage.

...is the error message you are apt to see in Internet Explorer even as it works in Chrome and Firefox.

 
 

ourContext.Response.Write(whatever);

...is not enough.

 
 

ourContext.Response.Write(whatever);
ourContext.Response.Flush();
ourContext.Response.End();

...is better. This worked for me in IE8 and above.

You may just save out as an .eps in Inkscape.

This is a good way to get stuff from Inkscape into Adobe Illustrator.

Tuesday, November 11, 2014

Use JavaScript to tell if the immediate web page sits within an iFrame or not.

This Stack Overflow thread offers:

function inIframe () {
   try {
      return window.self !== window.top;
   } catch (e) {
      return true;
   }
}

 
 

...which seems to work pretty good.

Return a specific view and hand it a specific string as a model.

StringBuilder stringBuilder = new StringBuilder("Hello World!");
return View("Whatever", stringBuilder);

 
 

You may exclusively write the HTML for the model from the C# side (NOT RECOMMENDED) in an ASP.NET MVC Controller with this approach if your .cshtml view is kept this simple:

@model System.Text.StringBuilder
@{
   Layout = null;
}
@Html.Raw(Model.ToString())

 
 

As best as I can tell one does have to use the StringBuilder trick to use a string as a model or do something else to make the string not immediately a string type. If you just hand in a string to the View method it will be used in a different context in its method overloading.

Cast Adobe Illustrator shapes to SVG and then, perhaps as a second step, get them into Inkscape.

From the "Save As..." option under the "File" menu in Adobe Illustrator one may save a .svg file. If you open this file in Notepad you will see the SVG markup plain as day. From the "Open..." option under the "File" menu in Inkscape one may turn around and open up the thing Illustrator spit out.

In a linked list...

...each node has its data and also a pointer to the next node, hence there is an overall order to the list. The nodes are links on a chain. Get it?

The "Limits" setting in the stroke pane in Adobe Illustrator will define a line in the sand for how sharp an acute angle must be to have a stroke that spikes in a point instead of a stroke that is sort of rounded-off or truncated at a corner.

The artwork above has a setting of 1 and the artwork below has a setting of 400. I honestly don't know what the numbers mean.

Sunday, November 9, 2014

InCycle Software's InRelease

...is an ALM solution. You may configure rollouts to different environments to have approval hurdles which require the sign off of applicable parties. I saw a Paul Hacker speak to this at this year's Code Camp. In the picture here, he is the individual in the dead center.

"Web Performance and Load Test Project" is now a type of project in Visual Studio.

You may use this to see how much traffic your separate web application may handle. I saw Joseph Reynolds give a talk on the Web Performance and Load Test Projects at this year's Code Camp.

That plugin Mike Swanson wrote for saving Adobe Illustrator vector shapes as XAML markup is back!

Ai->XAML Export Plug-In Version 0.2 by Mike Swanson now works in the latest and greatest Adobe Illustrator (18.1.0 but not 18.0.0 so be sure you update at "Updates..." under the "Help" menu) and you may download it here. The applicable .aip file in .zip file goes in C:\Program Files\Adobe\Adobe Illustrator CC 2014\Plug-ins or wherever else your "Plug-ins" folder for Adobe Illustrator may be. You will know it is working if you can export the contents of an .ai file to a .xaml file. Let's go through what that looks like.

To start with I opened up Adobe Illustrator, made a blank empty new .ai file saved to my desktop, and then made a rectangle in it by selecting the Rectangle tool and then right-clicking in the workspace. By right-clicking instead of dragging out a Rectangle freehand, I was able to enter very-specific point values for how wide and tall I wished the rectangle to be and I made my rectangle 400 points wide and 300 points tall. I was being specific and calculated about this as I wished to ultimately move the shapes I was to make to a Silverlight presentation which will be 400 pixels wide and 300 pixels tall. The one-to-one points to pixels translation that comes out of the box with this plugin is pretty sweet. A made sure that my rectangle had no stroke around the border as I feared such might make the rectangle a little fatter than 400 x 300. If you make a rectangle like this for a background and then make sure that all of your other shapes sit within the background not straddling any of its edges you will find it easy to predict where shapes end up in Silverlight. I'll explain this more soon.

Next, I made some other shapes in the Adobe Illustrator file. I broke the shapes out onto different layers. I made some text but I also converted the text to curves before I tried to push it out to XAML so that the text was just vector shapes like all of the other vector shapes.

When I was done I picked "Export..." from the "File" menu and found .xaml as a viable extension. This ended up making a file I could open up in Notepad to see the XAML markup. A Viewbox tag wraps everything and just inside of that there is a Canvas tag wrapping everything else. All of individual layers are broken into Canvas tags within the outer Canvas tag and Path tags detail the individual shapes inside of the Canvas tags for the layers. Here we see, first, the Path for my rectangle and, next, the Path for the shape of a swan I created in Illustrator.

One important thing to note here is that the background rectangle sits zero pixels off of the upper left corner of wherever it may be placed making this approach to getting shapes into Silverlight predictable in terms of how things align. In this approach, in contrast, I could not easily find a comparable way to guarantee placement. That does not mean that there is not a way to better align things in Blend, but the beauty of Mike's plugin is that I get to sidestep Blend. I am an old man with a multimedia degree from the 1990s. I've been using the Adobe tools for twenty years and they are what I am good at. I have never learned GIMP or Paint.NET as I would rather fly in Photoshop than learn to crawl in either of those two environments. Comparably, if I can just stick to the Illustrator stuff I'm good at and turn a blind eye to Blend I'm apt to do so. This approach to building shapes outside of Silverlight's go-to tooling is not outrageous. When I did Macromedia Flash work I would never use the awful tools for creating shapes in Flash. I would always import from Illustrator.

The next step is to make a new Silverlight project in Visual Studio. MainPage.xaml will have a Grid tag wrapped by a UserControl tag. At the UserControl tag, set d:DesignHeight and d:DesignWidth to make the presentation the appropriate size (400 pixels by 300 pixels, remember?).

The next thing I did was copy everything inside of the outmost Canvas tag in my .xaml file to the inside of the Grid tag in Visual Studio.

My swan has survived the translation in pretty good shape. I may see it by previewing the presentation with that "Play" button at the top center of Visual Studio's interface.

When I made this blog posting (for which this most immediate blog posting is an update) XAML was "the future." It doesn't seem like the future anymore though. It and Flash both seem ghetto. We've rebelled against this sort of thing and have decided that we just want to do exciting content with HTML and JavaScript which is what we already knew. This kinda goes back to the old-man-stuck-in-his-ways thing. Anyways, I hope you've enjoyed this swan song for XAML. I don’t know when I'll blog of it again. I never use it professionally.

Saturday, November 8, 2014

Byte Order Mark

Today I noticed  sitting at the top of my web site like so:

http://stackoverflow.com/questions/2554445/how-to-fix-byte-order-mark-found-in-utf-8-file-validation-warning suggests that &iuml;&raquo;&iquest; may appear at very beginning of a "UTF-8" file and offers a fix. This thingamabob is called Byte Order Mark and I removed it by just FTPing down the Default.aspx home page for my site, opening it in Notepad, removing the Byte Order Mark which was the very first thing which appeared, and then FTPing it back up anew. Now the question is: How did it get there to begin with? Did the company hosting me (Network Solutions) move my web site to a different server and end up recreating Default.aspx somehow in the process? What happened? This problem appeared out of thin air!

Friday, November 7, 2014

WordPress Engine is not WordPress

WP Engine offices in the same building as the company I work for, but these guys are not the keepers of WordPress itself. This suggests that Automattic, the parent company of WordPress, invests in WP Engine however. WP Engine offers hosting for WordPress sites.

Smarty is NOT the only option for PHP templates anymore.

At my work, instead of using Smarty in a SDK sample PHP app we might give our clients, we will offer a PHP-only implemenation with simple includes bringing in common HTML. That way if a client is using a different template they won't have a nose bleed. I'm glad I don't do PHP anymore. Just Googling for templates revealed too many options. Examples:

I'm an old man and I remember when Smarty was new and first.

Convert a string to an ushort in C#.

ushort currencyCode = Convert.ToUInt16("840");

strongly-typed

...sort of suggests "not dynamic" ...a programming language with specific, compiler-safe types for things like character and decimal, etc. (not interpreted)

Accidentally making a duplicate copy of one of the .cs files in the App_Code folder will, yes, sabotage a web site.

C#'s compiler will not tolerate two classes with both the same name and same namespace unless the partial keyword is being used which will not apply in this circumstance. As all files in the root folder of a solutionless ASP.NET web site are included in the web site, in the absence of a .csproj file decrying what to include, a duplicate of any one file containing a class should do a pretty good job of wrecking things.

Thursday, November 6, 2014

XAMPP

...gets Apache working with PHP. https://www.apachefriends.org/index.html seems to have links to download it.

highlight.js

...appears to be a tool for formatting code snippets for how-to examples. It has an impressive variety of options for color coding and I think I like "School Book" the best. Get it here.

crafting complicated shapes in Adobe Illustrator

This is a recreation of a prior blog posting. I deleted three blog postings recently that I felt embarrassed by, but after thinking about it, I don't see why I should shy aware from this post in particular so here it is again. I made an Adobe Illustrator .ai file which held the seven fruits from 1982's Ms. Pac-Man in a vertical progression with denotations for how many point values the fruits were worth in game. The idea was taken from in-game artwork and also some very similar artwork for the cabinet of the arcade game which I've run across in Googling. Here is a raster rendering of the vector shapes:

In looking at an .eps of the shapes, one will be able to tell that many of the complex shapes are in fact made by having several shapes sit on top of each other first to then get grouped together as a whole. For example, if you ungroup the pretzel in Adobe Illustrator and drag from the middle of the left edge upwards, you should be able to drag a chunk of a pretzel beneath the other parts upwards and away from its playmates like so:

You will note that the shapes overlaying the piece we moved utilize some trickiness in the name of creating the illusion of a stroke around a single shape that somehow goes under the shape's fill at times. Obviously, this effect is completely faked. A brown shape with no stroke used to overlay the bit we moved and a second shape that has a stroke but no brown fill sits on top of the brown shape without a stroke and extends a smidge farther towards the upper left than the shape it sits over. This stroke shape is longer than the fill shape and independent from it for if we had just one shape there can be some nastiness in which a piece of a fill peaks out over a stroke on the shape below if its own stroke is broken. By broken, I mean having loose, visible ends as opposed to a stroke that is in, for example, a circle. To break a stroke, select a vertex and delete it outside of the pen tool for explicitly safely deleting vertexes. An unbroken shape will suddenly become a line with two distinct ends. You may need to splice in a new vertex to delete in the name of getting the effect you crave. I like to both show the grid and snap to the grid in the name of lining things up precisely. This really helps if you need to make two sides of a shape symmetrical. Make shapes overtop of other shapes on new layers initially and then flatten the layers together. Then group. Another good trick is to duplicate a shape onto a second layer and then make two different surgical edits on the two different layers so that the twins grow apart in form. You will find working with the grid and layers to be restrictive and challenging. You will find it impossible to make even the simple stuff I show off here without some upfront planning and creative problem solving, but that is just the nature of the vector graphics game. You will also need to make shapes you will not keep. These will be used to truncate the shapes you do want or to punch holes in them. The shapes you don't keep get subtracted from the ones you are to keep in the name of hammering them into shape. The example I show ultimately ended up as a tattoo on my back:

Credits:

  • original tattoo by "Mike Pain" at Atomic Tattoo (5533 Burnet Road, Austin, TX 78756) on 2/8/2014
  • touch-ups by Bobby Baker at Skin Art Gallery (4297 Beltline Road, Addison, TX 75001) on 3/29/2014 and 5/3/2014 and 5/18/2014
  • photo by Matt Underwood on 10/5/2014

Wednesday, November 5, 2014

Make a form "out of thin air" with JavaScript and then post it and its contents.

var form = window.document.createElement("form");
form.setAttribute('method', "post");
form.setAttribute('action', myUrl);
window.document.body.appendChild(form);
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'whatever';
input.value = whatever;
theForm.appendChild(input);
form.submit();

Cast XML directly to JSON in C#.

This suggests this:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);

 
 

...which seems to work just dandy. If Visual Studio seems not to recognize .SerializeXmlNode then you probably need the latest Newtonsoft from NuGet like so:

Install-Package Newtonsoft.Json

 
 

Also, casting back to XML from JSON is even easier. Behold:

XmlDocument doc = JsonConvert.DeserializeXmlNode(json);

 
 

...as suggested in the link at the top of this posting works great.

Make an XmlNode in C# from a string full of XML.

XmlTextReader xmlTextReader = new XmlTextReader(new StringReader(myXml));
XmlDocument myXmlDocument = new XmlDocument();
XmlNode xmlNode = myXmlDocument.ReadNode(xmlTextReader);
XmlDocument myOtherXmlDocument = new XmlDocument();
myOtherXmlDocument.ImportNode(xmlNode, false);

Tuesday, November 4, 2014

a static C# method for deserializing XML to a specific type

public static T Deserialize<T>(string xml)
{
   var xmlReader = XmlReader.Create(new StringReader(xml), new
         XmlReaderSettings());
   var xmlSerializer = new XmlSerializer(typeof(T));
   var deserializedObject = xmlSerializer.Deserialize(xmlReader);
   return (T)deserializedObject;
}

 
 

Use it like so:

var foo = Whatever.Deserialize<Foo>(myXml)