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)

When you deserialize a string of XML in C#, try not to make a brittle implementation.

This...

List<FormField> formFields = new List<FormField>();
XDocument xml = XDocument.Parse(responsePacket);
foreach (XElement element in xml.Root.Elements())
{
   if (element.Name == "Fields")
   {
      foreach (XElement formField in element.Elements())
      {
         var xmlReader = XmlReader.Create(new StringReader(formField.ToString()),
               new XmlReaderSettings());
         var serializer = new XmlSerializer(typeof (FormField));
         var deserializedObject = serializer.Deserialize(xmlReader);
         formFields.Add((FormField)deserializedObject);
      }
   }
}

 
 

...for example, is a little bit better than this...

List<FormField> formFields = new List<FormField>();
XDocument xml = XDocument.Parse(responsePacket);
foreach (XElement element in xml.Root.Elements())
{
   if (element.Name == "Fields")
   {
      foreach (XElement formField in element.Elements())
      {
         string name = null;
         string value = null;
         bool? isToTokenize = null;
         foreach (XElement attribute in formField.Elements())
         {
            if (attribute.Name == "Name") name = attribute.Value;
            if (attribute.Name == "Value") value = attribute.Value;
            if (attribute.Name == "IsToTokenize") isToTokenize =
                  Convert.ToBoolean(attribute.Value);
         }
         if (name != null && value != null && isToTokenize != null)
         {
            formFields.Add(new FormField()
            {
               Name = name,
               Value = value,
               IsToTokenize = (bool) isToTokenize
            });
         }
      }
   }
}

 
 

...as in the first example the FormField type may change shape without breaking the implementation.

I saw a 3D Printer for the first time yesterday.

It was being used to make some promotional materials.

Other things I learned at the same outing:

  1. WOWZA is a place to host streaming video.
  2. A "press packet" in the traditional sense is sort of a resume for a professional company or music band. This will have a paragraph of copy on who the entity is and it will also have contact information in bullet points. Phone number, email address, web site, etc.

Monday, November 3, 2014

Change out a value in XML with Regex!

public static String ChangeStatusAtPayload(String stuff, String status)
{
   var regex = new Regex("<Status>.*</Status>");
   Match match = regex.Match(stuff);
   String piece = match.Value;
   return piece.Replace(statusValue, String.Format("{0}", status));
}

Redirect to another web site from an an MVC Controller.

using System.Web.Mvc;
namespace Foo.Ui.Controllers
{
   public class BarController : Controller
   {
      public ActionResult Index()
      {
         return Redirect("http://www.example.com");
      }
   }
}

Saturday, November 1, 2014

I saw Raif Harik give a talk called "selling CQRS to your team or boss" at this year's Code Camp.

This went a little deeper than what was covered in this other talk I saw at the start of the year which touched on CQRS as well. Immutable events are stored in an event store sequentially and incrementally and if you pool the history of a thing you may get a complete picture of it by building up the history of events. I don't really understand how this works without having actually seen the code for a CQRS project though. There was time when I was working at that place I should really stop dwelling on where this guy who I shouldn't mention by name did a project like this and told us all about it and this girl who I also shouldn't mention by name suggested that if you set enough pieces of tracing paper with different shapes upon them on top of each other that together they would add up to a picture and that in such a manner one could have the equivalent of what Eric Evans might consider an object. Everyone at the place I should let go of thought this was a good analogy and I still have this memory because I'm lost in the past. I digress. In terms of how sell CQRS, the argument is that, per force, an application will have more reads than writes and thus we should make it easy to read (minimizing the complicated SQL joins in reporting) and as easy as it is to write. The most interesting thing Mr. Harik said touched on the difference of opinion between Udi Dahan and Greg Young and their two schools of thought. He suggested that Udi Dahan is all about maintaining both normalized and denormalized schemas in CQRS applications while Greg Young would argue that you might as well not even worry about the normalized schema. In an app with only a denormalized schema, reading is easy and for writing one does have to do some painful stuff, but who cares because 80% of the queries, where performance counts, will be of reading. When I think of that conversation from another time that I should just forget about, that guy I shouldn't mention by name seemed to be doing things the Greg Young way. What follows is a chart on what would be more of an Udi Dahan approach to CQRS. It was in one of the slides that Mr. Harik showed off:

Rename all instances of a variable in a method by renaming the variable just once at the method signature in Visual Studio 2013.

  1. Highlight the variable.
  2. Type the new name. Just the last letter of the new name will be underlined with a little red accent.
  3. Click on the little red accent. A menu should appear giving you an option to "Rename 'alice' to 'bob'" so to speak.
  4. The act will occur!