Tuesday, May 1, 2012

Generic Scalar And List type SQL Select Function (VB.NET)

Here are a couple of utility functions I wrote to select basic types from a database, given that you have an open SqlConnection object. 

SqlSelect returns a single element of the specified type.

   1:      Public Function SqlSelect(Of T)(ByVal CN As SqlConnection, ByVal szSQL As String, ByRef szError As String) As T
   2:   
   3:          Dim T_value As T
   4:   
   5:          szError = String.Empty
   6:   
   7:          Try
   8:              Using sqlCmd As SqlCommand = New SqlCommand(szSQL, CN)
   9:                  T_value = CType(sqlCmd.ExecuteScalar(), T)
  10:              End Using
  11:          Catch ex As Exception
  12:              szError = ex.Message()
  13:          End Try
  14:   
  15:          Return T_value
  16:   
  17:      End Function

 

SqlSelectList returns a List of the specified type.

   1:      Public Function SqlSelectList(Of T)(ByVal CN As SqlConnection, ByVal szSQL As String, ByRef szError As String) As List(Of T)
   2:   
   3:          Dim T_LIST As New List(Of T)
   4:          szError = String.Empty
   5:   
   6:          Try
   7:              Using sqlCmd As SqlCommand = New SqlCommand(szSQL, CN)
   8:   
   9:                  Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
  10:                  If sqlReader.HasRows() = True Then
  11:                      Do While sqlReader.Read() = True
  12:                          T_LIST.Add(CType(sqlReader.GetValue(0), T))
  13:                      Loop
  14:                  End If
  15:                  sqlReader.Close()
  16:   
  17:              End Using
  18:          Catch ex As Exception
  19:              szError = ex.Message()
  20:          End Try
  21:   
  22:          Return T_LIST
  23:   
  24:      End Function

Now, with an open SqlConnection object CN, you can easily retrieve a scalar or list of scalar values like this:

   1:  szSQL = "SELECT COUNT(*) FROM [Users]"
   2:  Dim n As Integer = SqlSelect(Of Integer)(CN, szSQL, szError)
   3:   
   4:  szSQL = "SELECT name FROM sysobjects where type='U' and name <> 'sysdiagrams' order by name"
   5:  Dim TableList As List(Of String) = SqlSelectList(Of String)(CN, szSQL, szError)

enso

Tuesday, April 24, 2012

Recipe: Homemade Sauerkraut




2 Lbs green cabbage
2 Tbsp coarse pink sea salt 
1 tsp sugar

(Yield: about 5 cups)

Shred the green cabbage, with a food processor or knife, and place all ingredients in a large bowl.  Cover and allow mixture to sit at room temperature for about an hour, until the cabbage has released a lot of liquid (brine).

Move the cabbage to a new container, preferably glass or porcelain (if plastic, avoid BPA: plastics tend to leech into food!) and squeeze out the brine as you move it.  Once you have moved the squeezed cabbage, compact it a little and cover with brine, which was just squeezed out, until it is submerged by about an inch.

Next you want to cover the cabbage mixture with something that will apply a little pressure and keep the cabbage submerged in the brine.  Most people use a plate, upside down, with some sort of weight on top (a rock would do!).  You don't want the plate to float.  Finally, cover the entire thing with a cloth to keep any air-borne dust from getting in.

Let sit for 2 to 4 weeks, but check it once a day to be sure the plate and cabbage is submerged.  If there is any "froth", use a spoon to remove it.

Temperature should be in the range of 72 to 74 degrees.  At 75 degrees, allow 3 weeks for fermentation.  At 70 degrees, allow 4 weeks.  At 65 degrees, allow 5 weeks.  At 60 degrees, allow 6 weeks.  It's not advised to allow the temperature go above 75: it may not ferment and could spoil.

  • Do not use aluminum utensils!  Aluminum is a reactive metal that will alter the taste.
  • Cleanliness is important to avoid bacterial contamination: wash utensils, containers and hands! 

Eating sauerkraut is a great way to protect the balance of bacteria in your GI tract
Sauerkraut is one of the few foods that contain the beneficial bacteria called Lactobacilli plantarumL. plantarum is found in certain food products that undergo fermentation (sauerkraut, green olives, sourdough bread, naturally brewed wines and beer).  Until rather recently, L. plantarum was a common part of the human diet.

Friday, April 20, 2012

HttpWebRequest.GetResponse() taking a long time (Microsoft Security Essentials, DefaultProxy)

I wrote a simple VB.NET command-line (Console) program to grab a web page using HttpWebRequest and HttpWebResponse.

The following code snippet (req is an HttpWebRequest) would take 13 to 17 seconds to grab a simple 4k web page that would come up instantly under the IE or Chrome browser.

   1:  SWATCH = Stopwatch.StartNew()
   2:  Dim resp As HttpWebResponse = DirectCast(req.GetResponse(), HttpWebResponse)
   3:  SWATCH.Stop()
   4:  Console.WriteLine("OK - Elapsed Time: " & SWATCH.Elapsed.ToString())
   5:   

I did some fiddling around and found TWO areas that I had to make modifications.

The first modification I made was inside the settings for my anti-virus program: Microsoft Security Essentials.  After playing around, I found that one particular setting was causing 10 seconds of the 13+ second delay: the Enable behavior monitoring setting.

image

The next culprit was the fact that HttpWebRequest will use the default proxy set in IE.  I do not have a proxy set, but it was still causing about a 3 second delay.  The solution was to create a .config file for my program that turned this behavior off.

   1:  <?xml version="1.0" encoding="utf-8"?>
   2:  <configuration>
   3:      <system.net>
   4:          <defaultProxy>
   5:               <proxy autoDetect="false" />
   6:          </defaultProxy>
   7:      </system.net>
   8:  </configuration>

 

Another method is to disable the Automatic Proxy Detection in Internet Explorer:

image

image

#WINNING!

The offending 13+ seconds was reduced to 0.12 seconds!

image

enso

Wednesday, March 21, 2012

Add Hints & Auto Focus Form Fields (jQuery)

1: $(document).ready(function () {

   2:          //Focus auto-focus fields
   3:          //  add class="auto-focus" to first field
   4:          $('.auto-focus:first').focus();
   5:          //Initialize auto-hint fields
   6:          //  add class="auto-hint" to fields
   7:          //  needs CSS: .auto-hint{color: #AAAAAA;}
   8:          $('INPUT.auto-hint, TEXTAREA.auto-hint').focus(function () {
   9:                 if ($(this).val() == $(this).attr('title')) {
  10:                         $(this).val('');
  11:                         $(this).removeClass('auto-hint');
  12:                 }
  13:          });
  14:          $('INPUT.auto-hint, TEXTAREA.auto-hint').blur(function () {
  15:                 if ($(this).val() == '' && $(this).attr('title') != '') {
  16:                         $(this).val($(this).attr('title'));
  17:                         $(this).addClass('auto-hint');
  18:                 }
  19:          });
  20:          $('INPUT.auto-hint, TEXTAREA.auto-hint').each(function () {
  21:                 if ($(this).attr('title') == '') { return; }
  22:                 if ($(this).val() == '') { $(this).val($(this).attr('title')); }
  23:                 else { $(this).removeClass('auto-hint'); }
  24:          });
  25:  });

Tuesday, March 6, 2012

Restoring PDF Thumbnails to display in Windows Explorer (x64)

I recently upgraded from Windows 7 32-bit to Windows 7 64-bit.  Under the 32-bit OS, I was able to see thumbnails of PDF files (the first page) as the file’s icon.  Under 64-bit Windows 7 I only get the Adobe PDF icon and no thumbnail.

The reason Windows Explorer 64 won’t generate thumbnails?  This occurs because a 64-bit process that runs on a computer that is running an x64-based version of Windows cannot load the 32-bit DLL file that is required to generate the thumbnails.

This describes how you can generate thumbnails for specific PDF files (it’s a little tedious) – however, this will not restore Windows Explorer’s ability to generate them itself.  Pity!

image

The first thing to do is to be sure you have the folder options set correctly- though this will not take care of the problem, there is another step.  Open up the Folder Options dialog in Windows Explorer:

image

Ensure the “Always show icons, never thumbnails” is unchecked:

image

Next open Adobe Acrobat Reader and click the “Open Files” dialog and navigate to a folder with PDF files.

Adobe Reader will generate thumbnails for the files that are in view.

image

Go back to Explorer and you should see the thumbnails generated by Adobe.  Notice that thumbnails are displayed only for those PDF files that were processed by Adobe.

image

awesome

Tuesday, February 14, 2012

(VB.NET) Remember Application Window Size and Position

This is pretty common, to remember your form’s size and position.  I will use the Application Settings feature to persist the required information, but you could just as easily save it to a text file, .INI file, XML or database.  Whatever floats your app.

We want to remember the size and location of our main window, so we’ll add two settings for that.  We will initialize the settings with negative numbers to signal that they have not been set yet.  In my current case, I also have a splitter bar on the main form, so I’m going to include a setting for it’s size – I’d like the application to remember that also.

Here are the Settings I created.  It doesn’t matter what you call them.  I used WindowLocation, WindowSize and WindowSplitterPosition.

image

In the Form’s Load event, we’ll call LoadWindowPosition to load and apply the settings:

image

I have a dual monitor setup with the following Screens (DeviceName, Bounds, WorkingArea)

image

When we restore our window’s size and position, I’d like to ensure that the top left corner of our form is visible on one of the screens.

Here is a LoadWindowPosition() function to check the screens and abort if the upper left corner isn’t visible on any screen.  You could, if you wanted to, replace the “Bounds” with “WorkingArea”.  See the MSDN Docs for the difference and decide for yourself.

image

Finally, to make this work, we need to save our settings so they can be loaded the next time the application is run.  I’ll put the code in the FormClosing event of my main window:

image

Pretty trivial, really!

image

Thursday, December 22, 2011

PRH Paul Richard Heffler

Go about your business, and do what you know best.
Keep yourself in season and know just when to rest.

puffertr