Sunday, May 6, 2012

How to set line colors in Flot graph

// could not find simple example of setting line colors in Flot graph

var lcolors = ["#FFA500","#00BFFF","#DC143C","#3CB371"];

// get the data after graph is plotted, change line colors, then redraw

var plot = $.plot($("#placeholder"), data, getOptions());

series = plot.getData();

for (var i = 0; i < series.length; ++i) {
    if (i < lcolors.length) { 

        series[i].color = lcolors[i];   // override the default color
    }
}

plot.draw();


// options for time series graph with live refresh
function getOptions() {

    return {
        // drawing is faster without shadows
        series: {
            shadowSize: 0
        },
        lines: {
            show: true
        },
        grid: {
            hoverable: true,
            clickable: true
        },
        legend: {
            show: false,
            backgroundOpacity: 0,
            position: 'nw'
        },
        xaxis: {
            mode: 'time',
            max: new Date().getTime() - (new Date().getTimezoneOffset() * 60000),
            timeformat: "%H:%M%p"
        },
        yaxis: {
            min: 0,
            tickFormatter: function suffixFormatter(val, axis) {
                return val.toFixed(axis.tickDecimals);
            }
        }
    };
}

Saturday, April 28, 2012

HP Pavillion dv7t instructions for enabling function keys to work when pressed

as of April 28th, 2011 the instructions on HP website are backwards, I had to select DISABLED to get my Function keys to work normally on my hp dv7t laptop


Who the heck thought of disabling the function keys as the default? 

Friday, March 30, 2012

Gmail Basic HTML view looks restores the old Gmail interface

Just learned you can restore the old gmail interface by switching to basic HTML view.

Click this link to open Gmail in basic view  or just add the ui=html flag to your URL, i.e. https://mail.google.com/mail/?ui=html

The fact that this disables Chat and a bunch of other nuisances just adds to the benefit.

Wednesday, September 1, 2010

Sorting sub-directories using IComparer in Visual Basic .NET

First we create an IComparer class:

Imports System.IO

Public Class DirectoryCompare
    Implements IComparer

    Public Overridable Overloads Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compare
        Dim objX As DirectoryInfo = CType(x, DirectoryInfo)
        Dim objY As DirectoryInfo = CType(y, DirectoryInfo)
        Return objX.Name.CompareTo(objY.Name)
    End Function

End Class

And some code showing how to use it:

                    Dim dArray() = New DirectoryInfo("C:\\Results").GetDirectories

                    If Not dArray Is Nothing Then

                        Dim dc As New DirectoryCompare()
                        Dim dirs As ArrayList = New ArrayList(dArray)
                        dirs.Sort(dc)

                        dim lastDirPath as String = CType(dirs(dArray.Length - 1), DirectoryInfo).FullName

                        'step through
                        For Each dir As DirectoryInfo In dArray

                        Next

                        'step backwards
                        For idir As Integer = dArray.Length - 1 To 0 Step -1

                            Dim dir As DirectoryInfo = CType(dirs(idir), DirectoryInfo)
                        Next

                    End If

Thursday, August 26, 2010

Table Adapters invalid and cannot be generated after altering ODBC Firebird database

I may have generated a unique cause for this error, but it's a scary moment when all your ODBC table adapter queries disappear so I'll document the experience.

This Visual Basic.Net (2008) project started out with an Access database for convenience, and I prefer mixed case table and field names for legibility.

About 10 days ago I switched to a Firebird database, and it was pretty cool that the table adapters worked with Firebird after minor edits (e.g. remove the back-quotes on field names, handle missing native boolean type in Firebird)

But, today after adding some columns in the Firebird database all my table adapters disappeared. The error is briefly summarized as "Failed to generate code. No mapping exists from DbType Object to a known OdbcType" The IDE showed "unknown type" critical errors on every reference in code.

This error would occur even though I could hit Execute Query in the Table Adapter designer and see valid data appear.

After some thrashing and a restore of all the relevant Dataset files from backup I figured out the error was rooted in case-sensitivity. One of the table adapters could no longer reference it's underlying table, and that meant the code for all the table adapters in the class could not be generated. Interestingly, in dataset design view the obviously broken adapter was *not* on the table with the new columns.

There appeared to be problems in the <Mappings> for the newly altered table. I saw both mixed-case to mixed-case and upper-case to upper-case mappings, but no mixed-case to upper-case mappings. In addition, the column types were declared differently in mixed case from upper case, probably because they were based on Access when first generated, and Firebird when regenerated.

This was going to be a problem because all the queries were written in mixed case, but Firebird stores all field and table names in upper case (unless you quote each field and table name, which I figured is only going to cause problems later), so there was no possible way to map the text in the commands and field definitions to the Firebird interface.

After converting queries and fields on the broken table adapter to upper case, and eliminating conflicting mapping statements and using all upper case in the newly altered table, the table adapters all work again. For safety I converted all the other table adapters to upper case as well.

It looked like the behind-the-scenes work to incorporate the newly added columns had a problem with the mixed case of the fields. All the columns of the table were there in upper case

One symptom you can look for is the field list in the table adapter disappears, all that's left is a list of queries. A second symptom which I missed because the relevant table has 30+ fields is that field names are listed twice, once in mixed case and once in all upper.

Another symptom is after doing Configure on any query in the table adapter you get the "unable to convert object to a known ODBC type" error when you hit Finish.

Since the case and field type issues were a result of moving from Access to Firebird I'm not sure how many people are going to run into this. Bottom line, if you think your going to adopt Firebird later then declare everything in upper case to start with or prepare to comb your code for case-dependencies.

Case-insensitive sorting of Firebird field in a Visual Basic web application

I wanted to sort elements in a ListBox alphabetically without regard to case. However, Firebird does a case-sensitive sort, and I couldn't get it to recognize UPPER() in the SELECT statement.

One solutions is to add the rows in the table adapter data table to an array of elements of a custom class. The custom class implements IComparable, so when you do Array.sort you can get the case-insensitive order desired. Here's my custom class:

Public Class trendpoint
    Implements IComparable

    Public name As String
    Public description As String

    Public Sub New(ByVal name As String, ByVal description As String)
        Me.name = name
        Me.description = description
    End Sub

    Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo

        Dim comparepoint As trendpoint = CType(obj, trendpoint)

        If Me.name.ToUpper < comparepoint.name.ToUpper Then
            Return -1
        ElseIf Me.name.ToUpper > comparepoint.name.ToUpper Then
            Return 1
        Else
            Return 0
        End If

    End Function

End Class

Enable double click event on a ListBox in a vb.net web application

There's a nice concise C# example of supporting double click event on a listbox control in an asp.net web application, here is the equivalent code (for the page load event) in Visual Basic.

If (Not Request.Item("__EVENTARGUMENT") Is Nothing And Request.Item("__EVENTARGUMENT") = "move") Then

Dim idx As Integer = ListBox1.SelectedIndex
Dim item As ListItem = ListBox1.SelectedItem
ListBox1.Items.Remove(item)
ListBox2.SelectedIndex = -1
ListBox2.Items.Add(item)

End If

ListBox1.Attributes.Add("ondblclick", ClientScript.GetPostBackEventReference(ListBox1, "move"))

Friday, August 6, 2010

Connecting to a Firebird database from a VB.net 2008 web application

There's a couple of posts related to connecting to a Firebird database from an asp.net 2008 web application that are helpful but not complete.

First, you establish a DSN connection.

When adding the DSN connection the prompts were a little different on my Vista machine than the post describes. First, I picked the Database source


Then, after clicking New Connection button, click Change button on Data Source to switch from SQL Server to ODBC driver


Then, pick the Microsoft ODBC Data Source option


Once this is done when you add a new DSN connection the Firebird/Interbase drivers will be selectable.

During the configuration of the Firebird DSN connection I ran into one other change from the earlier post, rather than browse to the database on the local machine I used the localhost: connection method (e.g. Database = "localhost:c:\program files\ ... \_WEBLINK.FDB")


The Database string is quoted on both ends, in the picture some of the connection string is whited out for (excessive) security.

Now you can follow the second post to establish a data connection

Thursday, July 22, 2010

Registry key for IIS subauthenticator is not configured correctly

Installed a Visual Basic web app on a Windows Server 2003 box with IIS 6 today and got some strange intermittent symptoms. The customer could login about 2 times out of 3, and could access some second-level pages intermittently, but other second-level pages would fail immediately. Failures took the user back to the login page.

The Event Viewer showed an error each time the user got bumped back to the login page, saying "Registry Key for IIS subauthenticator is not configured correctly"

I found the Microsoft KB article with instructions to enable IIS management of the anonymous user password. After applying the 3 steps the website works perfectly.

Took a while to resolve because I was baffled by the intermittent nature of the error, but once the correlation to the Event Viewer error was observed it was quick.

Wednesday, May 19, 2010

Insert multiple records to Microsoft Access database

Did not find a simple answer as to how to insert multiple rows of raw data into an Access database using an Insert Into SQL statement, this post is one of many to point out that VALUES is for single-row inserts, and you need to use a SELECT to insert more than 1 row - which means your values have to already be in the database.

I don't believe there's a straightforward way to do it with a single SQL statement, but you can use free MyOLEDBExpress database editing tool to accomplish it by cutting/pasting your columns of data from Excel spreadsheet or other source directly into a table. If you are combining data with values already in the database you can use a SELECT clause with the INSERT INTO statement to extract the insert values from tables.

It may be worth the effort if you have hundreds of rows of data or more. Here's the Insert statement after the temp table has been created.

INSERT INTO the_Access_Table (field1, field2) SELECT col1, col2 FROM temp_Table INNER JOIN other_Table ....

Thursday, March 25, 2010

VB.net Opening Connection to SQLServer

Was unable to connect from Visual Basic .NET 2008 to a SQL Server Express 2008 database using the online examples. I was getting the error "network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible"

Changing from Data Source=(local) to Data Source=.\SQLEXPRESS fixed the issue

Full example:

Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim dr As SqlDataReader

myConnection = New SqlConnection("Data Source=.\SQLEXPRESS;User ID=youruser;Password=yourpassword;Initial Catalog=yourdatabase")

Try
myConnection.Open()

myCommand = New SqlCommand("Select * from tblRoom", myConnection)

dr = myCommand.ExecuteReader()

While dr.Read()

MessageBox.Show("Field1 " & dr(0).ToString() & " Field2 " & dr(1).ToString())

End While
dr.Close()
myConnection.Close()

Catch e As Exception
'handle errors
End Try

Friday, December 4, 2009

JDI thread evaluations - Exception processing async thread queue

After some debugging Eclipse may throw an async thread exception every time it hits a breakpoint. The message is along the lines of

JDI thread evaluations
Exception processing async thread queue

You can clean this up by removing all watch statements and all breakpoints and restarting Eclipse.

Wednesday, November 11, 2009

Firebird -902 error localhost refused connection

Seems too obvious but you will get this error if you try to Connect after you Stop or Pause your Firebird Server service. More common causes are amply documented on the web - Firewall blocking and Incorrect port # (default is 3050)

Thursday, September 17, 2009

Launching CHM help file from a Java application on Windows

Seems like an obvious need but could not find an example for how to launch a compiled HTML help file from inside a Java JAR application on a Windows machine, so here's one:

String myHelpfile = path + "help.chm";
String[] command = { "hh.exe", myHelpfile };
try {
Process proc = Runtime.getRuntime().exec(command);
} catch (IOException e) {
e.printStackTrace();
}

Friday, August 28, 2009

Removing requirement for NET Framework 3.5 from setup projects

A new setup and deployment project in Visual Basic 2008 will by default require .NET Framework 3.5 on the target machine

If your application targets .NET Framework 2.0 this is a waste of time

To change the requirement right-click on your setup project, select View, Launch Conditions, go to properties of the ".NET Framework" item under the Launch Conditions node and change the Version property to 2.0.50727

Friday, August 14, 2009

How to find the control that generated a postback

Had a little trouble finding a good example of how to identify the control that generated a postback within the page_load

There's a nice article for C#, after a bit of tinkering here's a VB implementation:

Public Function GetPostBackControl(ByVal curPage As Page) As Control

 Dim foundControl As Control
 Dim controlName As String = curPage.Request.Params.Get("__EVENTTARGET")

 If (Not controlName Is Nothing And controlName <> "") Then
  foundControl = curPage.FindControl(controlName)
 Else
  ' control causing postback must be a Button or imageButton
  For Each controlName In curPage.Request.Form.AllKeys

   ' image buttons have a ".x" or ".y" appended to name string
   If (controlName.EndsWith(".x") Or controlName.EndsWith(".y")) then
    controlName = controlName.Substring(0, controlName.Length - 2)
   End If

   Dim c As Control = curPage.FindControl(controlName)

   If (TypeOf c Is Button Or TypeOf c Is ImageButton) Then
    'first button we find is the one that caused the postback
    foundControl = c
    Exit For
   End If
  Next
 End If

 GetPostBackControl = foundControl

End Function

Friday, July 10, 2009

IIS hyperlinks fail - cannot open an anonymous level security token

Recently upgraded a test machine to Internet Explorer 8. While testing a new deployment today found that hyperlinks created in my web application stopped working. The error icon on the bottom left of the screen said: "Cannot open an anonymous level security token"

The solution from a microsoft community site was to reset DCOM default properties to "Connect/Identify".

After rebooting and reopening the site in IE8 the links now work.

We tinker with DCOM on this test machine quite often and I found it with default properties of "None/Impersonate" - maybe impersonate causes a problem for anon access but I don't remember these problems with IE7. Hopefully this is not a sign the IE8 is going to "UAC" all over the system like Vista did.

Getting version number from a visual basic 2008 web application

Dim versionInfo As String = System.Reflection.Assembly.GetExecutingAssembly().GetName() .Version.ToString()

Obvious in hindsight, but took me a little while to find it

Tuesday, July 7, 2009

Changing the background color of a checkbox at runtime

I wanted to show 3 values in a checkbox ("full", "partial", and "empty") by changing background color of the selected checkbox when state is "partial"

I thought we could simply set the background color property, but that had no effect for me at runtime. It took a while to find how to programatically change background color of a checkbox on a VB web form, finally this post and this post got me close enough.

How to change the color at runtime:

(1) Add CSS style declarations to your form's design view (.aspx page), for example:

.full {
background-color: #fff;
}
.partial {
background-color: #ccc;


(2) in the form load method add some code like this:

curControl = CType(Page.FindControl(sID), CheckBox)

if (ispartial) then
curControl.Checked = True
curControl.CssClass = "partial"
else if (isfull) then
curControl.Checked = True
curControl.CssClass = "full"
etc.

Thursday, June 25, 2009

Visual Studio 2008 IDE memory leak - "Enable error correction suggestions" causes sluggish behavior, freezing, and crashes

Have been experiencing slowdowns, freezing and crashing of the visual basic IDE on a consistent basis for a few days.

I can see memory leaking in megabyte+ chunks within Task Manager each time I type anything in the IDE on a VB code page. With just one file open I can keep the memory growing indefinitely in ~10MB increments by adding any text, erasing it, saving, and then repeating.

The additional memory is not fully recovered so I eventually have to restart the IDE to avoid a crash. I've seen it climb up to 1.4 GB (out of 3 GB). This was not a sustainable way to work.

Almost sure this behavior started after June 2009 windows hotfixes were applied. I had been working primarily in Java/Eclipse the last few months, but intermittenly spent time in the VS2008 IDE producing hotfixes and had not experienced this instability before.

Tried removing Office 2007 (trial) since that was mentioned as a possible issue in a couple of places, but no change. Tried removing MS Works which was recently installed as a "security hotfix" - only to find that is a whole can of worms by itself.

WORKAROUND: What finally seems to have stabilized the IDE is de-selecting the "Enable error correction suggestions" option.

HOW TO: to de-select this option go to Tools, Options, Text Editor, Basic, VB Specific - uncheck the box and hit OK.

If anyone has any better suggestions please feel free to post in comments.