Thursday, January 31, 2013

throw an exception in C#

This per this:

catch (EndOfStreamException end)
{
   throw (e);
}
catch (NullReferenceException nullRef)
{
   throw (nullRef);
}

The parameterless constructor on a base class is always called when a child's constructor is called in C#.

Something interesting is to come, but first, look at this:

using System;
namespace ParameterlessConstructorExample.Models
{
   public class Animal
   {
      public Int32 numberOfMouths { get; set; }
      
      public Animal()
      {
         numberOfMouths = 1;
      }
   }
}

 
 

Now for something interesting: If Bird inheirts from Animal, then newing up a Bird will cause the parameterless constructor on Animal to be called.

using System;
namespace ParameterlessConstructorExample.Models
{
   public class Bird : Animal
   {
      public Int32 numberOfLegs { get; set; }
      
      public Bird()
      {
         numberOfLegs = 2;
      }
   }
}

 
 

ViewBag.Whatever below will end up with the number one in it.

using System.Web.Mvc;
using ParameterlessConstructorExample.Models;
namespace ParameterlessConstructorExample.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         Bird bird = new Bird();
         ViewBag.Whatever = bird.numberOfMouths;
         return View();
      }
   }
}

 
 

This comes from chapter 18 of C# in a Nutshell. I tried to find a way to set numberOfLegs in Animal and have the Animal setting sabotage the Bird's setting, but fortunately there isn't an easy way to "accidentally" do this. I found this which made me smile. The first bullet of the Conclusion is: "C# is not Java."

In C# a method cannot be both virtual and override. Am I wrong?

This suggests there is no good way to override from a grandchild to a grandparent as a method cannot be decorated with both override and virtual. Am I wrong?

 
 

Addendum 1/25/2014: Please see this as there is grandchild to grandparent overriding available in C#.

Wednesday, January 30, 2013

Tuesday, January 29, 2013

GO is important when nesting sproc creations inside of larger SQL scripts.

Without GO preceeding and coming after the creation for the sproc, you will get an error about how the creation has to be at the top of the script.

Monday, January 28, 2013

try to change ports in IIS

This points out that you may change the port for an IIS web site at the "Bindings..." link which should appear at the right nav in IIS7 when you select a site at the left nav. When I try to switch to port 443 from 80 I am told: "This Web site cannot be started. Another Web site may be using the same port." I navigated to C:\Windows\system32> at the command prompt and typed netstat -a to get a list of ports being used. I found 443 set to a state of LISTENING in two line items of the results returned.

Here is one last posting on finding oneself like Keira Knightley as Sabina Spielrein. Well, actually that is a terrible analogy.

Addendum 4/10/2013: A lot of this posting is really bad. See: this

Trilogy complete!
  1. this
  2. and this
  3. go with this...

Keira Knightley as Sabina Spielrein gives an excellent performance in David Cronenberg's film "A Dangerous Method" and yes, I think it the very best Cronenberg film, and I've seen every single one except for Spider, including the overrated Scanners. Naturally, Sabina Spielrein finding herself really doesn't have anything at all to do with finding yourself in C#...

string nameOfTheComputer = System.Net.Dns.GetHostName();
string localIp =
   System.Net.Dns.GetHostByName(nameOfTheComputer).AddressList[0].ToString();
string publicIpv4 = Request.ServerVariables["REMOTE_ADDR"];
string publicIpv6 =
   System.Net.Dns.GetHostEntry(nameOfTheComputer).AddressList[0].ToString();
string url = Request.Url.ToString();
string nameOfCurrentPage = Request.ServerVariables["SCRIPT_NAME"];
string localeInFileTree =
   Server.MapPath(System.IO.Path.GetFileName(nameOfCurrentPage));

 
 

Maybe VB script is more suitable, as it feels like it is eighty years old and thus from Sabrina's era...

Dim nameOfTheComputer As String = System.Net.Dns.GetHostName()
Dim localIp As String =
      System.Net.Dns.GetHostByName(nameOfTheComputer).AddressList(0).ToString()
Dim publicIpv4 As String = Request.ServerVariables("REMOTE_ADDR")
Dim publicIpv6 As String =
      System.Net.Dns.GetHostEntry(nameOfTheComputer).AddressList(0).ToString()
Dim url As String = Request.Url.ToString()
Dim nameOfCurrentPage As String = Request.ServerVariables("SCRIPT_NAME")
Dim localeInFileTree As String =
      Server.MapPath(System.IO.Path.GetFileName(nameOfCurrentPage))

 
 

Nah. The truth is, this is really bad analogy and I just like goofing off with Tumblr. So, what am I struggling to say?

Well, the stuff above will help you "find yourself." The variables are largely going to end up with stuff in them that corresponds appropriately to their names. One exception is that either the publicIpv4 or publicIpv6 variable is going to be botched in the code above, but I'll get to that in a minute. Other things to mention are:

  • The code above, in both cases, is from an MVC4 app, and, yes, you can make a VB script MVC4 app in case you're, well, crazy. (Hey, the analogy is starting to work again!) But you may need to replace everything that starts out with Request. with HttpContext.Current.Request. instead in some older versions of MVC or in web forms apps.
  • url will look like http://localhost:54197/ in an MVC4 app at the HomeController and nameOfCurrentPage returns a single forward slash.
  • Inspecting localeInFileTree by setting a breakpoint, I saw C:\\this\\that\\theotherthing in C# and C:\this\that\theotherthing in VB. Note that neither has a trailing slash.

 
 

Alright, the only thing really new about this posting in contrast to the other two is the IP stuff. First remember that a local IP starts with...

  1. 10,
  2. or 198.168,
  3. or 172.16,
  4. or 172.31,
  5. or anything between bullets three and four above.

 
 

publicIpv6 will end up with the same string as localIp (not literally the same... I do understand the heap and reference types) if there is not an IPv6 IP address to be had, which are those new freaky things that look like fe80::4869:3aca:f1b9:d214%10 for example. (The world is running out of the traditional IPv4 IP addresses the same way it is running out of tungsten. Those left not on the list above are public IP addresses.) So what will publicIpv4 look like?

It is likely going to look like ::1 if there is an IPv6 address and legitimate otherwise. Note that "legitimate" may include 127.0.0.1 which is not technically a private IP address. This means, that in order to really use the code above, one needs to do an equality comparison between publicIpv6 and localIp to see if either publicIpv4 or publicIpv6 holds the value for the public IP address. If publicIpv6 and localIp do match then publicIpv4 holds the public IP address while the absence of a match means that publicIpv6 holds the public IP address.

Saturday, January 26, 2013

Wow! Where am i?

Do you every feel lost and just wish you could ping the cave walls like a bat? I found a way to sniff the url line yesterday. Awake last night, I realized that if you split a url on the slash and take the third item in the collection that you will have your hands on the subdomain standalone.

public static string GetSecureSubDomainWithoutTrailingSlash()
{
   string fullUrl = HttpContext.Current.Request.Url.ToString();
   return "https://" + fullUrl.Split('/')[2];
}

 
 

This posting may serve as a companion piece for this which shows off how to find where one is at in a file structure. Also, here is the VB Script way to do the thing I did above in C#:

Imports Microsoft.VisualBasic
Public Class LocationProvider
      Public Shared Function GetSecureSubDomainWithoutTrailingSlash() As String
            Dim fullUrl As String = HttpContext.Current.Request.Url.ToString()
            Dim revisedUrl As String = "https://" + Split(fullUrl, "/")(2)
            Return revisedUrl
      End Function
End Class

 
 

Call things static-style in VB script like so:

Label1.Text = LocationProvider.GetSecureSubDomainWithoutTrailingSlash()

Friday, January 25, 2013

Thursday, January 24, 2013

Server.Transfer hated

The guy running our project turns out to hate Server.Transfer and wants me to replace all of the Server.Transfer stuff I wrote to replace Response.Redirect stuff to make HP Fortify happy with the Response.Redirect stuff I just got rid off. He hates that the URL line does not change as the "page" changes and it is also a downer that one has to route to http://www.example.com/somethinglikethis/default.aspx and not merely http://www.example.com/somethinglikethis/ which will cause a red and yellow screen of death.

get the connection string from Web.config in VB script

ConfigurationManager.ConnectionStrings("foo").ConnectionString

Wednesday, January 23, 2013

ghetto view autosort fun

Per this a hacky way to autosort a view is:

SELECT TOP 99 PERCENT Whatever FROM SomethingErOther
ORDER BY Whatever

WHERE NOT EXISTS ()

this returns true if the select inside of it returns nothing, I think

add a linked server

exec sp_addlinkedserver @server = 'yournamehere' (SELECT * FROM sysservers at "Master" will give you a list of linked servers)

force shutdown at command line

This posting isn't something to worry about. Instead just use the command line to force a shutdown:

shutdown /r /t timeout_in_seconds

give a number for "timeout_in_seconds" (duh)

what to do if there is not an option for shutdown

http://support.microsoft.com/kb/555449

is the PC in front of me 64-bit?

http://www.stata.com/support/faqs/windows/64-bit-compliance/ has a pretty good cheat sheet for determining if a given PC is of a 64-bit shape. In Windows 7 go to: Start > Control Panel > System and Security > System ...and then find the line item for "System type"

Tuesday, January 22, 2013

Select to an output parameter at a stored procedure.

SELECT TOP 1 @ValueToReturn = HorseName FROM Horses

...is how it is done in lieu of...

SELECT TOP 1 HorseName FROM Horses

 
 

This is an older blog posting I wrote on output parameters for stored procedures.

Monday, January 21, 2013

looping logic in VB

Public Shared Function IsRouteParametersSane(ByVal dataSet As DataSet, url As
            String) As Boolean
   If InStr(url, "?") = 0 Then
      Return True
   End If
   Dim secondHalfOfUrl As String
   secondHalfOfUrl = Split(url, "?")(1)
   Dim routeParametersAndTheirVariables As New ArrayList()
   If InStr(secondHalfOfUrl, "&") = 0 Then
      routeParametersAndTheirVariables.Add(secondHalfOfUrl)
   Else
      Dim routeParametersAndTheirVariablesAsArray = Split(secondHalfOfUrl, "&")
      routeParametersAndTheirVariables = New
                  ArrayList(routeParametersAndTheirVariablesAsArray)
   End If
   Dim routeParameters As New ArrayList()
   Dim routeParameterAndValue As String
   For Each routeParameterAndValue In routeParametersAndTheirVariables
      If InStr(routeParameterAndValue, "=") = 0 Then
         routeParameters.Add(routeParameterAndValue)
      Else
         routeParameters.Add(Split(routeParameterAndValue, "=")(0))
      End If
   Next
   Dim routeParameter As String
   For Each routeParameter In routeParameters
      Dim isFailure As Boolean = True
      For Each Row As DataRow In dataSet.Tables(0).Rows
         If Row(2) = "Route Parameter" Then
            If Row(1).ToLower() = routeParameter.ToLower() Then
               isFailure = False
            End If
         End If
      Next
      If isFailure = True Then
         Return False
      End If
   Next
   Return True
End Function

Sunday, January 20, 2013

Rough notes on studying up for HTML5 interview...

  • <link rel="stylesheet" type="text/css" href="styles.css" media="screen"> is a typical stylesheet tag, but one may also embed the stylesheet tag in HTML like so:
    <style type="text/css" media="all">
       p {
          margin-left: 20px;
       }
    </style>
  • http://validator.nu/ will crawl and validate the quality of your HTML.
  • Does HTML5 smell? (smell has a different meaning for ASP.NET and Java peeps)
  • article/section/header/footer (semantic tags instead of div for search engine spiders) http://channel9.msdn.com/Series/HTML5-CSS3-Fundamentals-Development-for-Absolute-Beginners
  • Type "Character Map" at the start menu in Windows 7 to get the character map tool:

    Bob Tabor encourages just using the real special characters in lieu of encodings.
  • <!DOCTYPE html> is the way to declare an HTML5 document and <html lang="en"> is a good line to immediately follow and will specify English. Note that <!DOCTYPE html> is not <!DOCTYPE html /> as the end slash syntax is no longer encouraged. HTML5 is not XHTML. HTML does not need to double as XML.
  • Typical structure:
    <!DOCTYPE html>
    <html lang="en">
       <head>
          <meta charset="utf-8">
          <title>Whatever</title>
       </head>
       <body>
          <header>
             Content
          </header>
          <section>
             <article>
                Content
             </article>
             <article>
                Content
             </article>   
          </section>
          <footer>
             Content
          </footer>
       </body>
    </html>
  • Associate header tags:
    <hgroup>
       <h1>Big Header</h1>
       <h2>Subheader</h2>
    </hgroup>
  • Wrap a menu in a nav tab:
    <nav>
       <ul>
          <li>Imagine a link</li>
       </ul>
    </nav>
  • A figure tag associates an caption with something else, say for example an image...
    <figure>
       <img src="whatever.gif" alt="show me in absence of an image">
       <figcaption>
          This will hug the base of the image.
       </figcaption>
    </figure>

    ...however, the img tag above could be replaced with a <pre><code></code></pre> blob too
  • <small>makes small text</small>
  • <aside></aside> is yet another tag which may be styled like a div. This one is for, well, asides. We are going to more creative lengths not to use "div" I guess.
  • overflow: hidden; ...if the item styles spills into another thing, the spillover will be "clipped"
  • list-type-style: none; ...hides bullets or numbers on a list
  • text-transform: uppercase; ...does what you might think it does
  • box-shadow: 3px 3px 5px 1px #CCCCCC; ...here the last of the five values is clearly the color while the first two items are the amount of shadow below and to the right (horizontal first, use negative numbers to go up and to the left), the third is the amount of blur, and the fourth seems to be the amount of solid shadow before a blurred edge starts
  • box-shadow: inset 3px 3px 5px 1px #CCCCCC; ...here inset makes the shadow inside the box
  • http://www.w3.org/TR/html5-author/ is the spec for HTML5.
  • http://www.w3.org/TR/html5-author/global-attributes.html has a list of attributes that are legitimate for any tag and also a list of event handlers.
  • <address></address> is for keeping contact info stuff
  • While the section and article tags behave basically like div tags but have different semantic meanings, the same is not true for some of the tags which wrap snippets of text as many of the tags, while given new semantic meanings, do NOT mundanely behave as span tags which provide nothing new without being styled, for example this html...
    <p><blockquote cite="http://www.example.com/">This isn't a real quote. It is
          an example.</blockquote>
    <cite><a href="http://www.example.com/">fake website</a></cite></p>
    <p><b>important</b> <mark>marked</mark> <em>emphasis</em> <i>offset
          mood</i> <u>unarticulate</u> <s>old, no longer valid info</s> <del>for a
          strikethrough</del></p>
    <pre>
    <code class="language-pascal">var i : Integer;
    begin
       i : 1;
    end.</code>
    </pre>

    makes this...
  • <q></q> is for quoted text per http://www.w3.org/TR/html-markup/q.html and some of the CSS that might go with it is:
    q {
       display: inline;
    }
    q:before {
       content: open-quote;
    }
    q:after {
       content: close-quote;
    }
  • <hr> still does what it used to but is now considered to be of separating themes
  • </dl>, </dt>, and </dd> can optionally be left off and if you are wondering what </dt> and </dd> are...
    <dl>
       <dt>deprecated</dt>
       <dd>to express earnest disapproval of</dd>
       <dt>depreciate</dt>
       <dd>to lessen the value or price of</dd>
    </dl>
  • Remember:
    • <input type="reset" value="reset values">
    • <button type="submit"></button>
    • <button type="reset"></button>
    • <button type="button"></button>
  • Use fieldsets and legends to put a box around a set of controls with a header as following, noting that you must immediately follow the open fieldset tag with the legend tag:
    <fieldset>
       <legend>This is part of a form</legend>
       <label for="foo"><span>Foo</span><input type="radio"
             name="whatever" value="foo"></label>
       <label for="bar"><span>Bar</span><input type="radio"
             name="whatever" value="bar"></label>
       <label for="baz"><span>Baz</span><input type="radio"
             name="whatever" value="baz"></label>
       <label for="qux"><span>Qux</span><input type="radio"
             name="whatever" value="qux"></label>
    </fieldset>
  • New attributes to decorate tags inline include required (which will force a validation both of a not-empty variety and also of a type-specific variety while returning an error message in the case of a failure) and autofocus (which will make the field the place the cursor starts when the form loads) and pattern which allows for regular expressions like this one which validates a five or nine digit zip code: pattern="^\d{5}(-\d{4})?$" ...there is also: placeholder="meh" which will prepopulate some "grey" text which will disappear when a user clicks in the field to really type something
  • there are some new types:
    • email
    • tel (telephone numbers)
    • url
    • date (or datetime, datetime-local, month, time, week)
    • number (step=5 is an example of an inline parameter for denoting what an accepted value must be divisble by)
    • range (step=5 is an example of an inline parameter for denoting what an accepted value must be divisble by, while min and max denote the range itself with zero and one hundred being the default values respectively, and value denoting the place on the slider, and yes, this control makes a slider)
    • color
  • This will create a text box which you may type anything into, but which comes with some canned selections in the name of being helpful not being strict in scope:
    <input type="text" list="somelist">
    <datalist id="somelist">
       <option label="foo" value="foo">
       <option label="bar" value="bar">
       <option label="baz" value="baz">
       <option label="qux" value="qux">
    </datalist>
  • Some of the new CSS3 stuff:
    @import url('http://www.example.com/main.css');
    p:first-letter {
       font-size: 3em;
    }
    article:before {
       content: 'hello world';
    }
    p:first-of-type {
       margin-left: 42px;
    }
    li:first-child {
       margin-left: 42px;
    }
    li:last-child {
       margin-left: 42px;
    }
    li:nth-of-type(3) {
       margin-left: 42px:
    }
    span[title] {
       color: black;
       /* find a parameter in the span tag called "title" */
    }
    span[title="first idea"] {
       text-decoration: line-through;
       /*match parameter with exact value */
    }
    a[href^="email"] {
       text-decoration: overline;
       /*match beginning of parameter value */
    }
    span[title$="marker"] {
       margin-left: 42px;
       /* match end of parameter value */
    }
    article span {
       /* any span within any article */
    }
    article > span {
       /* any span that is an immediate child of any article */
    }
    article + span {
       /* any span that has an article immediately before it */
    }
    article ~ span {
       /* any span that has an article somewhere before it */
    }
    .whatever {
       font-weight: 100;
       /* normal font weight, the lightest of the 100 to 900 scale */
    }
    #whatever {
       font-weight: 900;
       /* heavy font weight, the darkest of the 100 to 900 scale */
    }
  • vertical-align CSS options include:
    1. super
    2. sub
    3. middle
    4. top
    5. baseline
    6. text-top
    7. text-bottom
  • The following div is styled like so:
    background-color: rgb(100,0,13);
    background-image: url('http://placekitten.com.s3.amazonaws.com/homepage-
          samples/200/286.jpg');
    background-repeat: no-repeat;
    background-position: right bottom;
    border: 1px solid #FFFFFF;
    height: 400px;
    width: 400px;
  • In a table, border-collaspe: collaspe; will make two adjacent 1 pixel borders display as a 1 pixel wide line while border-collaspe: separate; will make a 2 pixel wide line in the same situation.
  • cellspacing="0" still has to be inline in a table. This is never gonna change.

 
 

Addendum 1/4/2017: list-style: none; and not list-type-style: none; gets rid of bullets. I hope you weren't pulling your hair out over this. ;)

Friday, January 18, 2013

null dereferences

Null dereferences are not so much security holes as they are of performance problems. If one attempts to use a pointer that points at null as though it points to legitimate content on the heap it may "invariably result in the failure of the process" per https://www.owasp.org/index.php/Null-pointer_dereference

Thursday, January 17, 2013

D3 and SVG

Today I learned about D3.js which is a JavaScript project for "Data-Driven Documents" at what will hopefully be the first of many Far North Austin geek lunches. D3.js allows for all sorts of creative charts, maps, tree views, reports, etc. Some of them can work with div tags and some of them work with SVG (Scalable Vector Graphics, an XML markup for Flashesque vector content without the overhead of the third-party plugin).

  1. Inkscape is a WYSIWYG editor for SVG.
  2. IE9 or better allows for SVG.

There are practical reasons to bundle web forms controls together when creating them dynamically in a code behind file.

Refactoring the work I begun here I have learned that if one wants to have n number of controls for each record out of a database such as, for example...

  1. a checkbox for whether to delete a row
  2. a form field for editing a data point on the row
  3. a hidden form field to keep the integer id of the row

 
 

...that when creating web forms controls dynamically it is tricky to associate the n controls. I got around this by creating a new Panel for each set of three as seen here:

foreach (KeyValuePair<int,string> keyValuePair in subdomains)
{
   TextBox textBox = new TextBox();
   textBox.Attributes.Add("style", "float: left; width: 350px; margin-top: 4px;");
   textBox.Text = keyValuePair.Value;
   CheckBox checkBox = new CheckBox();
   checkBox.Attributes.Add("style", "float: left; margin: 6px 0px 0px 10px;");
   HiddenField hiddenField = new HiddenField();
   hiddenField.Value = keyValuePair.Key.ToString();
   Panel innerPanel = new Panel();
   innerPanel.Controls.Add(checkBox);
   innerPanel.Controls.Add(textBox);
   innerPanel.Controls.Add(hiddenField);
   LeftPanel.Controls.Add(innerPanel);
}

 
 

I then get a collection of panels back when its time to analyze stuff in the controls. From any one item in the collection, it isn't too tough to associate its three children together.

List<Panel> panels = new List<Panel>();
foreach (Panel panel in LeftPanel.Controls) panels.Add(panel);
foreach (Panel panel in panels)
{
   List<Control> controls = new List<Control>();
   foreach (Control control in panel.Controls) controls.Add(control);
   Tuple<bool, string, int> changeSet = new Tuple<bool, string, int>(((CheckBox)
         controls[0]).Checked, ((TextBox) controls[1]).Text,
         Convert.ToInt32(((HiddenField)controls[2]).Value));
}

define a parameter for a sproc in C# (yawn)

private void UseAddStoredProcedure(string newEntry)
{
   try
   {
      using (SqlConnection sqlConnection = new SqlConnection(AddConnectionString()))
      {
         using (SqlCommand sqlCommand = new SqlCommand())
         {
            sqlCommand.CommandText = addStoredProcedure;
            sqlCommand.Parameters.Add("@Item", SqlDbType.VarChar).Value = newEntry;
            sqlCommand.CommandType = CommandType.StoredProcedure;
            sqlCommand.Connection = sqlConnection;
            sqlConnection.Open();
            sqlCommand.ExecuteNonQuery();
         }
      }
   }
   catch
   {
      throw new System.ApplicationException(addStoredProcedure + " failed");
   }
}

Check to see if a Session of ViewState variable exists before trying to cast it to a type.

if (ViewState["AddOrAlter"] != null)
{
   if (ViewState["AddOrAlter"] as string == "add")
   {
      string whatever = "somethingerother";
   }
}

typeof Reflection comparisons in C#

Compare an instance to a type!

  1. if (foo.GetType() == typeof(HiddenField)) {
  2. if (foo.GetType().FullName == typeof(HiddenField).FullName) {

Wednesday, January 16, 2013

display line numbers

TOOLS > Options... > Text Editor > All Languages > General ...is where one turns on and off showing line numbers for code in Visual Studio 2012.

Ctrl-F brings up the generic and handy "Find" window in Visual Studio.

F for "Find"

Making controls dynamically in the Page_Init event in ASP.NET web forms isn't too tough.

I just did it for the first time. You are going to have to have some controls (think Panel) to put the code-created controls in. Here is a web form that will work:

<%@ Page Language="C#" AutoEventWireup="true"
      CodeBehind="WhitelistForReroutingAdministration.aspx.cs"
      Inherits="ResponseRedirectWhitelisting.WhitelistForReroutingAdministration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
      Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Whitelist For Rerouting Administration</title>
</head>
<body>
   <form id="form1" runat="server">
      <div style="margin:0 auto; width: 800px;">
         <div style="float:left; width: 400px;">
            <asp:Panel runat="server" ID="LeftPanel"></asp:Panel>
         </div>
         <div style="float:right; width: 400px;">
            <asp:Panel runat="server" ID="RightPanel"></asp:Panel>
         </div>
         <div style="clear:both; height:20px;"></div>
      </div>
   </form>
</body>
</html>

 
 

Here is the magic in the code behind. (not too tough really)

using System;
using System.Web.UI.WebControls;
namespace ResponseRedirectWhitelisting
{
   public partial class WhitelistForReroutingAdministration : System.Web.UI.Page
   {
      protected void Page_Init(object sender, EventArgs e)
      {
         int counter = 0;
         while (counter < 10)
         {
            counter++;
            TextBox textBox = new TextBox();
            textBox.Attributes.Add("style", "float: left; width: 370px; margin-top: 4px;");
            textBox.Text = counter.ToString();
            LeftPanel.Controls.Add(textBox);
         }
         while (counter < 13)
         {
            counter++;
            TextBox textBox = new TextBox();
            textBox.Attributes.Add("style", "float: right; width: 370px; margin-top: 4px;");
            textBox.Text = counter.ToString();
            RightPanel.Controls.Add(textBox);
         }
      }
      
      protected void Page_Load(object sender, EventArgs e)
      {
      }
   }
}

 
 

Tuesday, January 15, 2013

Persistence API in SignalR

Adding onto this, one configures a route in RouteConfig as show here, and again, this is Mr. Sullivan's code.

routes.MapConnection<ChatConnection>("chat", "chat/{*operation}");

 
 

He (Brian Sullivan) made a view which looks like so:

<div id="chatArea"></div>
<div>
   <input type="text" id="chatText" />
   <button id="sendButton">Send</button>
</div>
@section scripts
{
   <script type="text/javascript" src="~/Scripts/jquery.signalR-1.0.0-rc1.js"></script>
   <script type="text/javascript">
      $(function () {
         var conn = $.connection("/chat");
         $("#sendButton").click(function () {
            conn.Send($("#chatText").val());
            $("#chatText").val("");
         });
         conn.received(function (data) {
            $("#chatArea").append("<div>" + data + "</div>");
         }
         conn.start().done(function() {
            if (conn.eventSource) {
               conn.eventSource.addEventListener('message', function(event) {
                  console.log("EventSource message: " + event.data);
               });
            }
         });
      });
   </script>
}

 
 

conn.Send($("#chatText").val()); above is going to send the contents of the chatText input field to a ChatConnection object as defined below. From there, am I not sure how the magic happens, but every browser listening via SignalR is going to get updated by SignalR! My notes have the ChatConnection object looking like so. I can't remember if the speaker added other lines to this object or not. Maybe all of the voodoo is in the view above and the C# object just empowers it, you know?

namespace SignalRChat
{
   using Microsoft.AspNet.SignalR;
   public class ChatConnection : PersistentConnection
   {
      protected override System.Threading.Tasks.Task OnReceivedAsync(IRequest
            request, string connectionId, string data)
      {
         return base.OnReceivedAsync(request, connectionId, data);
      }
   }
}

The second parameter in C#'s .Substring() was not what I expected.

The second parameter in Substring in C# denotes the distance from first parameter (the place in the string to start collecting characters) to stop collecting characters and not the locale in the string to stop collecting characters. I am midway into writing some code and I will eventually do more with urlAfterDoubleSlashes than what is given below as what is given below, partially finished, is goofy. I really need the -7 and -8 below as without out it there is drama.

private static bool IsCompleteUrl(string redirect)
{
   string urlAfterDoubleSlashes = null;
   if (redirect.ToLower().Substring(0, 7) == "http://")
   {
      urlAfterDoubleSlashes = redirect.Substring(7, redirect.Length-7);
   }
   if (redirect.ToLower().Substring(0, 8) == "https://")
   {
      urlAfterDoubleSlashes = redirect.Substring(8, redirect.Length-8);
   }
   if (urlAfterDoubleSlashes == null) return false;
   return true;
}

 
 

The drama I refer to is a System.ArgumentOutOfRangeException with a message of "Index and length must refer to a location within the string." and this code will get you that drama:

private static bool IsCompleteUrl(string redirect)
{
   string urlAfterDoubleSlashes = null;
   if (redirect.ToLower().Substring(0, 7) == "http://")
   {
      urlAfterDoubleSlashes = redirect.Substring(7, redirect.Length);
   }
   if (redirect.ToLower().Substring(0, 8) == "https://")
   {
      urlAfterDoubleSlashes = redirect.Substring(8, redirect.Length);
   }
   if (urlAfterDoubleSlashes == null) return false;
   return true;
}

Brian Sullivan of Improving spoke on SignalR at the Austin .NET User Group last night.

Mr. Sullivan's talk on SignalR was very informative and it showed off a lot of how-to. For example one pulls SignalR out of NuGet like so:

install-package Microsoft.AspNet.SignalR -pre

 
 

Other things I learned included that WebSockets requires either Windows8 or WindowsServer2012 in tandem with both IIS8 and ASP.NET 4.5 and that with Forever Frame, the browser holding the iFrame is tricked into believing that the page within the iFrame never finishes loading so that the page within the iFrame may consistently load new scripts as part of "loading a page." Bigger yet, there is a new version of ASP.NET coming down the pipe to us soon, this per Brian Sullivan last night, and it will have SignalR already baked into it. Microsoft has an all-chips-in investment. Such is prudent, the equivalent power of SignalR already exists in Node.js. The trick is getting IIS to play catchup. There are two varieties of web-based SignalR APIs. The one I've seen before is called the persistence parsing API and it basically allows one to talk string variables back and forth to a server as part of what Scott Hanselman referred to a real-time updates. The other seemed to allow one to fire off C# code upon the click of the button or another act which could then ultimately fire off events back in jQuery! The second variety was called Hubs. To allow for Hubs to work, one has to install the Nuget package and put this in the RouteConfig:

routes.MapHubs();

 
 

I did not come out of the training with a comprehensive understanding of Hubs, but some of the C# code which would ultimately allow for reaching back to JavaScript looked as seen below. Please make note of inheritance from Hub and the call to .cardCreate(card); as cardCreate is a JavaScript method!

using System;
namespace SignalRKanban.Hubs
{
   using Microsoft.AspNet.SignalR.Hubs;
   using SignalRKanban.Models;
   public class KanbanHub : Hub
   {
      public void CreateCard()
      {
         var id = Guid.NewGuid();
         var card = new Card { Content = "", Lane = "1", ID = id };
         clients.All.cardCreate(card);
      }
   }
}

 
 

The jQuery side of things looks like so:

$(function () {
   var kanbanHub = $.connection.kanbanHub;
   
   KanbanBoard.prototype.createCard = function() {
      kanbanHub.server.createCard();
   }
   
   var vm = new KanbanBoard();
   ko.applyBindings(vm);
   
   kanbanHub.client.cardCreated = function (card) {
      vm.addNewCardToLane(card.ID, card.Content, card.Lane);
   }
   
   $.connection.hub.start();
   
});

 
 

A script tag needs to call out to ~/Scripts/jquery.signalR-1.0.0-rc1.mis.js and a second script tag will need to call out to ~/signalr/hubs for this to work in a view. Note that this whole thing assumes MVC4 and ASP.NET Web API.

Monday, January 14, 2013

Check Out and Check In documents in SharePoint.

In SharePoint: I found that I need to check out and then check in an Excel sheet at a list to be able to push up changes to the Excel sheet. The links for "Check Out" and "Check In" are at the "Documents" tab under the "Library Tools" tab at the ribbon.

Saturday, January 12, 2013

Aaron Swartz, the creator of RSS, has died.

News is breaking now about Mr. Swartz's death. Honestly, I did not know who he was until this moment, but I have used his XML template/convention in the past certainly. It's growing antiquated, but was once the new hotness. Aaron Swartz seems to have died... badly. I am glad he got some recognition. I wish the following inventors recognition while I am thinking of it:

  1. Marc Andreessen invented the World Wide Web. What the internet was before and what it became couldn't be more stark. This turning point seems more important to me than the start of the internet back in the 1960s. Why isn't Marc a household name? Addendum 3/10/2014: This isn't really true. He just first exposed the World Wide Web to the greater public. See: this
  2. Philo T. Farnsworth was a farm boy who worked a field back and forth while progressively up to down. He realized that you could paint a pane of glass with electrons in a comparable manner to make a picture! He invented the television.
  3. Catherine Greene invented the cotton gin.

 
 

Friday, January 11, 2013

A PC on your LAN will have a group called Remote Desktop Users.

You need to add yourself to the group (in the same spot you might create users) in order to be able to remote into the machine.

Thursday, January 10, 2013

optimize queries and save query history

Quest's Toad apparently allows one to optimize SQL for Oracle. One can ping a server with the tool and the tool will try to rewrite existing, specified SQL in different ways while gauging the roundtrip speed of each implemenation and eventually picking a winner. Quest has a comparable tool for MSSQL (I think). SSMS Tools is something else I heard of today. It allows you to do other things that you cannot do with SSMS (SQL Server Management Studio) standalone such as save your query history.

How permanent is a deletion at Team Foundation Server?

One of my coworkers mentioned to me today that if I delete something from a solution and then commit my changes to TFS that what I've deleted could be undone as a delete. However, if I browse the files directly at TFS and then delete something there, my coworker asserted I was destroying it forever. I wonder how I would thus temporarily delete from a web site as opposed to a web solution.

Read the first line from a text file in the current directory in either C# or VB.

OK, I want to put Sabrina Spielrein's two favorite hobbies in a paragraph on an ASP.NET web form. The copy will mostly come from a text file in the same folder as the ASP.NET web form. I used the word mostly because the hobbies themselves will be injected into the paragraph which will have a sentance in it like so: "Sabrina's favorite hobbies are {1} and {2}, in no particular order." allowing for a String.Format approach to injecting the values for the hobbies which will be driven from the web form's C# code behind which looks like this:

using System;
public partial class SomeFolder_Modern : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
      TemplateParser templateParser = new TemplateParser();
      Label1.Text = templateParser.CraftCopy("suicide", "interplanetary travel",
            
Server.MapPath(System.IO.Path.GetFileName(Request.ServerVariables
            ["SCRIPT_NAME"]
)));
   }
}

 
 

The copy above in black gets the file path to the filename handed to it and the copy in white within black gets the name of the web form itself (Modern.aspx). The real work is done from the TemplateParser class which looks like this:

using System;
using System.IO;
public class TemplateParser
{
   public string CraftCopy(string firstHobby, string secondHobby, string location)
   {
      string templateLocation = "";
      string[] pathParts = location.Split(Path.DirectorySeparatorChar);
      int counter = 0;
      foreach (string pathPart in pathParts)
      {
         counter++;
         if (counter < (pathParts.Length))
         {
            templateLocation = templateLocation + pathPart + Path.DirectorySeparatorChar;
         }
      }
      templateLocation = templateLocation + "HobbyTemplate.txt";
      using (var stream = new StreamReader(templateLocation))
      {
         return String.Format(
stream.ReadLine(), firstHobby, secondHobby);
      }
   }
}

 
 

Alright, in the copy above, before the using statement, we are basically taking the file path to Modern.aspx and trimming off "Modern.aspx" and replacing it with "HobbyTemplate.txt" which I mentioned sits in the same folder. Our cleaned up file path ends up in the templateLocation variable and allows us to create a StreamReader connection. The copy above in black will read the first line out of the file. As it is tied to the return statement (and yes, you can nest the return inside a using statement) it will be the only line read. That means that if there is a second line in the text file reading "Sabrina also likes being punished." that such a line will not make its way back to the web form's label.

The practial application of the read-one-line-but-not-the-other-thing is to use the first line of the text document as a content template and the second line for a note. A better note might denote who the author was or what the purpose of the text file was. I wrote some C# vaguely of this shape at work today as an excerise as I had to really write the code in VB script and I wanted to know how to do the same thing in C#. I know you probably don't care about the VB stuff, but here it is:

Partial Class SomeFolder_Whatever
   Inherits System.Web.UI.Page
   Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
               Handles Me.Load
      Dim templateParser As TemplateParser
      Label1.Text = templateParser.CraftCopy("suicide", "interplanetary travel",
                  Server.MapPath(System.IO.Path.GetFileName(Request.ServerVariables
                  ("SCRIPT_NAME"))))
   End Sub
End Class

 
 

In this version, TemplateParser is very different:

Imports System.IO
Imports Microsoft.VisualBasic
Public Class TemplateParser
   Public Shared Function CraftCopy(ByVal firstHobby As String, ByVal secondHobby
               As String, ByVal location As String) As String
      Dim templateLocation = ""
      Dim pathParts() As String = location.Split(Path.DirectorySeparatorChar)
      Dim counter As Int32 = 0
      For Each pathPart In pathParts
         counter = counter + 1
         If counter < (pathParts.Length) Then
            templateLocation = templateLocation + pathPart + Path.DirectorySeparatorChar
         End If
      Next
      templateLocation = templateLocation + "HobbyTemplate.txt"
      Dim stream = CreateObject("ADODB.Stream")
      stream.Open()
      stream.CharSet = "UTF-8"
      stream.LoadFromFile(templateLocation)
      Dim linesOfCopy As Object
      linesOfCopy = Split(stream.ReadText, vbCrLf)
      stream.Close()
      stream = Nothing
      Return String.Format(linesOfCopy(0), firstHobby, secondHobby)
   End Function
End Class

 
 

Above, I had to call out UTF-8 or the copy that came back from the template would be preceded by three strange characters. vbCrLf seems to allow for splitting at line breaks.

Wednesday, January 9, 2013

I am learning more than I wanted to about VB.NET.

This is a VB script class:

Imports Microsoft.VisualBasic
Public Class EmailTemplateParser
   Public Shared Function ConfigureEktronGroups(ByVal
               identity As String, ByVal secret As String) As String
      Return identity + secret
   End Function
End Class

 
 

I can populate a web forms label using the class like so:

Partial Class _Default
   Inherits System.Web.UI.Page
   Protected Sub Page_Load(ByVal sender As Object,
               ByVal e As System.EventArgs) Handles Me.Load
      Dim emailTemplateParser As EmailTemplateParser
      Label1.Text = emailTemplateParser.
                  ConfigureEktronGroups("hello", "world")
   End Sub
End Class

a list of web content types?

This offers the following list:

  1. application/atom+xml
  2. application/atom+xml
  3. application/x-www-form-urlencoded
  4. application/json
  5. application/octet-stream
  6. application/svg+xml
  7. application/xhtml+xml
  8. application/xml
  9. multipart/form-data
  10. text/html
  11. text/plain
  12. text/xml

HttpWatch is a thingamabob like Fiddler!

I noticed that Fiddler did not want to spy on localhost and I found this this online as possible fix, but I couldn't get it to work. (I used port 443 for an https port, which I think is the right port to use. I dunno. I somehow screwed this up.) But, rather than face this challenge, I just worked around it using HttpWatch which is comparable to Fiddler. Note:

  • All you have to do in Fiddler is to open the tool to spy on http traffic.
  • For HttpWatch, you must right-click in a browser and select "HttpWatch Basic" to spy.

Tuesday, January 8, 2013

fish stuff out of a Fortify repository

The same URL you push to in the name of uploading to a Fortify repository may be entered at a browser (just use the same URL) to see a control panel for managing everything shoved up. At the Projects tab, pick a project. Finally, go to the Artifacts tab to get saved .fpr files.

Sunday, January 6, 2013

implementing pessimistic and optimistic locks

This and this seem to imply that one would approach pessimistic and optimistic locks by managing the existence of a lock by merely having some extra columns on a database table to denote if a lock exists, the moment a record was last locked, and the id of the party locking it. Transaction locking in something else altogether.

Friday, January 4, 2013

How may I route the subject of my using statement into another method and back midway through the using statement?

You cannot do this!

private static DataSet PopulateDataSetFromStoredProcedure(string connectionString)
{
   DataSet dataSet = new DataSet();
   using (SqlConnection connection = new SqlConnection(connectionString))
   {
      using (SqlCommand command = new SqlCommand())
      {
         command.CommandText = "dbo.Whatever";
         command.CommandType = CommandType.StoredProcedure;
         command = AddParametersToSqlCommand(command);
         
command.Connection = connection;
         using (SqlDataAdapter adapter = new SqlDataAdapter())
         {
            adapter.SelectCommand = command;
            adapter.Fill(dataSet);
         }
      }
   }
   return dataSet;
}
   
private static SqlCommand AddParametersToSqlCommand(SqlCommand sqlCommand)
{
   sqlCommand.Parameters.AddWithValue("@Foo", "my");
   sqlCommand.Parameters.AddWithValue("@Bar", "dog");
   sqlCommand.Parameters.AddWithValue("@Baz", "has");
   sqlCommand.Parameters.AddWithValue("@Qux", "fleas");
   return sqlCommand;
}

 
 

The variable in black above will cause this error:

Readonly variable cannot be used as an assignment target

 
 

This is one way you might try to hack around the problem, but this won't work either.

private static DataSet PopulateDataSetFromStoredProcedure(string connectionString)
{
   DataSet dataSet = new DataSet();
   using (SqlConnection connection = new SqlConnection(connectionString))
   {
      using (SqlCommand command = new SqlCommand())
      {
         command.CommandText = "dbo.Whatever";
         command.CommandType = CommandType.StoredProcedure;
         bool refHackWorks = AddParametersToSqlCommand(
command);
         command.Connection = connection;
         using (SqlDataAdapter adapter = new SqlDataAdapter())
         {
            adapter.SelectCommand = command;
            adapter.Fill(dataSet);
         }
      }
   }
   return dataSet;
}
   
private static bool AddParametersToSqlCommand(ref SqlCommand sqlCommand)
{
   sqlCommand.Parameters.AddWithValue("@Foo", "my");
   sqlCommand.Parameters.AddWithValue("@Bar", "dog");
   sqlCommand.Parameters.AddWithValue("@Baz", "has");
   sqlCommand.Parameters.AddWithValue("@Qux", "fleas");
   return true;
}

 
 

The variable in black above will cause this error:

Arguement is 'value' while parameter is declared as 'ref'

 
 

The soultion is to create a new using "loop" inside of the existing one like so:

private static DataSet PopulateDataSetFromStoredProcedure(string connectionString)
{
   DataSet dataSet = new DataSet();
   using (SqlConnection connection = new SqlConnection(connectionString))
   {
      using (SqlCommand dumbCommand = new SqlCommand())
      {
         dumbCommand.CommandText = "dbo.Whatever";
         dumbCommand.CommandType = CommandType.StoredProcedure;
         using (SqlCommand parameterizedCommand =
               AddParametersToSqlCommand(dumbCommand))
         {
            parameterizedCommand.Connection = connection;
            using (SqlDataAdapter adapter = new SqlDataAdapter())
            {
               adapter.SelectCommand = parameterizedCommand;
               adapter.Fill(dataSet);
            }
         }
      }
   }
   return dataSet;
}
   
private static SqlCommand AddParametersToSqlCommand(SqlCommand sqlCommand)
{
   sqlCommand.Parameters.AddWithValue("@Foo", "my");
   sqlCommand.Parameters.AddWithValue("@Bar", "dog");
   sqlCommand.Parameters.AddWithValue("@Baz", "has");
   sqlCommand.Parameters.AddWithValue("@Qux", "fleas");
   return sqlCommand;
}

tail database table rows

http://logview4net.com/ is a way to tail database tables and watch what rows are being asserted into them.

A data transfer object may be the cure for a smelly method signature.

I thought of Robert C. Martin's words as I had retyped them here from his Clean Code treatise...

The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification - and then shouldn't be used anyway.

...as I was abstracting a method in a web form's code behind out to a standalone class. The method which took no parameters at its signature now needs to be handed the string values kept in numerous web form controls. At first I started writing a method with twenty string variables in the signature as I've seen this sort of thing elsewhere in a sister codebase. I then thought of Uncle Bob's words and considered handing in a string array instead. This would introduce an encoding however and just be more confusing. The thing to do here is to roll a DTO (data transfer object). I should populate the DTO before calling the method and then just hand the method the DTO which will be the only thing in the method's signature.

twitpic is shrinking down all of the images pushed to it

http://twitpic.com is... running low on space? It's time for me to find another place to store images. Grrr.

Thursday, January 3, 2013

SmartBear SoapUI is for Web Service testing!

See: http://www.soapui.org/

Page lifecycle stuff for ASP.NET is going to be different between IIS6 and IIS7.

We had some conversations about this today and about if Page_Init (where one would register a control made in the code behind of a web forms application's web form in advance of being called in Page_Load) would be effected. Some links bumped into along the way:
  1. http://msdn.microsoft.com/en-us/library/c0az2h86(v=vs.100).aspx
  2. http://stackoverflow.com/questions/11296871/register-click-event-for-user-control-in-page-init-method
  3. http://stackoverflow.com/questions/1948704/changes-to-asp-net-page-lifecycle
  4. http://msdn.microsoft.com/en-us/library/bb470252(v=vs.100).aspx
  5. http://www.codeease.com/asp-net-application-life-cycle-and-page-life-cycle.html

turn on ASP.NET 4.0

This and this has a good article on how to beat this error when running a web site in Visual Studio via IIS:

ASP.NET 4.0 has not been registered on the Web server. You need to manually configure your Web server for ASP.NET 4.0 in order for your site to run correctly, Press F1 for more details.

  • Try to turn on everything when prepping IIS7 except for "IIS6 Management Console"
  • Open a command prompt as an administrator and type:
    aspnet_regiis.exe -i
    ...at:
    C:\Windows\Microsoft.NET\Framework\v4.0.30319\

DirectCast in VB allows for downcasting!

The last line of C# code here will cause an error:

Cat cat = new Cat();
Lynx lynx = new Lynx();
Cat attemptedUpcast = (Cat) lynx;
Lynx attemptedDowncast = (Lynx) cat;

Share photos on twitter with Twitpic

 
 

But none of the following lines of VB Script are problematic:

Partial Class VBform
   Inherits System.Web.UI.Page
   Dim snake As Snake
   Dim viper As Viper
   Dim attemptedUpcasting As Snake = CType(viper, Snake)
   Dim attemptedDowncasting As Viper = DirectCast(snake, Viper)
End Class

Share photos on twitter with Twitpic

put a user in a group

Share photos on twitter with Twitpic

see also: http://tom-jaeschke.blogspot.com/2012/12/create-users-for-iis7-in-windows7.html

to change the Application Pool for a web site in IIS...

...select the web site in IIS and then click on "Advanced Settings..." ...The application pool will, amongst other things, dictate what version of the .NET framework a site runs within

Share photos on twitter with Twitpic

older App Pool notes:

  1. http://tom-jaeschke.blogspot.com/2012/06/iis7-notes.html
  2. http://tom-jaeschke.blogspot.com/2012/12/change-framework-version-of-aspnet-for.html

Wednesday, January 2, 2013

Option Explicit On

...at the top of a file in VB Script asserts that, in the code to come, one must use the Dim keyword when declaring variables.

Use CLR assemblies in SQL!

  1. See the assemblies Object Explorer at: Your Server > Databases > Your Database > Programmability > Assemblies
  2. This is an example of calling the assemblies from SQL like so:
    WITH EXECUTE AS CALLER
    AS
    EXTERNAL NAME [NameOfAssembly].[NameOfClassWithinAssembly].
       [NameOfMethodWithinClass]
    GO

What Linked Servers does your server recognize?

  1. Connect to your server in MSSQL Management Studio 2008.
  2. In the Object Explorer go to: Your Server > Server Objects > Linked Servers