Check for LEAP YEAR in VB.Net

January 5th, 2009

Nothing overly impressive here but wanted to point out the built-in functionality of VB.Net to let you know if your year is a leap year or not.

HERE IS THE CULPRIT:
If Date.IsLeapYear(Int(TextBox1.Text)) Then

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object,
               ByVal e As System.EventArgs)Handles Button1.Click

        If Not TextBox1.Text = "" Then
            If IsNumeric(TextBox1.Text) Then
                If Int(TextBox1.Text) > 1950 And
                      Int(TextBox1.Text) < 2500 Then
                    If Date.IsLeapYear(Int(TextBox1.Text)) Then
                        TextBox2.Text = "This IS a LEAP YEAR!"
                    Else
                        TextBox2.Text = "Not a leap year."
                    End If
                Else
                    TextBox2.Text = "SOMETHING between 1950 & 2500 please."
                End If
            Else
                TextBox2.Text = "NOT NUMERIC"
            End If
        Else
            TextBox2.Text = "BLANK... enter something."
        End If
    End Sub

End Class

OK, there are alot of reasons why JQuery is nice to use OVER Javascript… (shorter syntax…cool stuff in very little code, etc…)… AND YES EVERYONE (my co-workers included) I know that JQUERY IS Javascript…

However, the gurus who created JQuery have apparently found a fix to a firefox/javascript problem that Mozilla has not wanted to address and because of that … JQUERY is officially better than Javascript!

With that out of the way… let me explain the situation…

We were trying to disable a checkbox based simply upon another checkbox being checked… it looked something like this:

if(document.getElementById(’roleStateAdmin’).getAttribute(’checked’)) {
document.getElementById(’roleTechAdmin’).setAttribute(’checked’,  false);
document.getElementById(’roleTechAdmin’).setAttribute(’disabled’, true);
}
else if(document.getElementById(’roleTechAdmin’).getAttribute(’checked’)) {
document.getElementById(’roleStateAdmin’).setAttribute(’checked’,  false);
document.getElementById(’roleStateAdmin’).setAttribute(’disabled’, true);
}
else {  // Neither checked.
document.getElementById(’roleStateAdmin’).setAttribute(’disabled’, false);
document.getElementById(’roleTechAdmin’).setAttribute(’disabled’, false);

This code worked just as intended in I.E.  but completely broke in FF. After several Google searches to find the problem, I officially chocked it up to being Broken in FF and decided that my only option was to see if JQuery could make it work.

It COULD and did… here it is the ALTERNATE Jquery code that makes this action work just fine:

if($(’#roleStateAdmin’).attr(’checked’)) {
$(’#roleTechAdmin’).attr(’checked’,  false);
$(’#roleTechAdmin’).attr(’disabled’, true);
}
else if($(’#roleTechAdmin’).attr(’checked’)) {
$(’#roleStateAdmin’).attr(’checked’,  false);
$(’#roleStateAdmin’).attr(’disabled’, true);
}
else {  // Neither checked.
$(’#roleStateAdmin’).attr(’disabled’, false);
$(’#roleTechAdmin’).attr(’disabled’, false);

If there is one problem that I have with JQuery… it is with it’s simplicity!  Too many times I overthink the solution… here is a case in point.

SETTING THE SELECTED VALUE OF A DROPDOWN.

I spent about 2 hours trying to figure out how to dynamically set my dropdown… I figured it had to be something like $(’#dropdown option:selected’).val or $(’#dropdown selected’).val blah blah blah

When all you simply need to do to set a dropdown box’s selected value is to call the name and the .val attribute… this may seem like it doesn’t even merit a post but I guarentee there are others out there like me over thinking it.  So I hope this helps someone.

//Setting the dropdown - EXAMPLE

if ($(‘#myHiddenField’).val() > 0)
{
$(‘#myDropDownBox’).val($(‘#
myHiddenField).val());
}
else
{
$(‘#
myDropDownBox).val(‘-1′);
}


IF you need to clear a type=FILE after you the user has chosen the a file…
you need to surround the input with a span - and then on your clear function,

just overwrite the span with a NEW input type-file box.
This needs to be done because in IE, you will not be able to just clear out text with
filebox.value = ” .

function clearMe() {
document.getElementById(”test”).innerHTML=”<input type=\”file\” id=\”fn\”>”;
}

Picture : <span id=”test”><input type=”file” id=”fn” ></span>
<input type=”button” value=”Clear” onClick=”clearMe()”>

I found this on the asp.net site by a John Stodola (site here: http://blog.josh420.com/)

It’s a simple function, but very useful…thought I would spread the word (thanks John!)

function checkFileExtension(elem) {
var filePath = elem.value;

if(filePath.indexOf(‘.’) == -1)
return false;

var validExtensions = new Array();
var ext = filePath.substring(filePath.lastIndexOf(‘.’) + 1).toLowerCase();

validExtensions[0] = ‘jpg’;
validExtensions[1] = ‘jpeg’;
validExtensions[2] = ‘bmp’;
validExtensions[3] = ‘png’;
validExtensions[4] = ‘gif’;
validExtensions[5] = ‘tif’;
validExtensions[6] = ‘tiff’;
validExtensions[7] = ‘txt’;
validExtensions[8] = ‘doc’;
validExtensions[9] = ‘xls’;
validExtensions[10] = ‘pdf’;

for(var i = 0; i < validExtensions.length; i++) {
if(ext == validExtensions[i])
return true;
}

alert(‘The file extension ‘ + ext.toUpperCase() + ‘ is not allowed!’);
return false;
}

NOW I AM LOOKING FOR A FUNCTION THAT LITERALLY FILTERS THE FILES
OUT IN THE FILES WINDOW LIKE THE .NET FILTER CAN.
ANYONE???

I had a dataTable with three columns

Name |  Rank  |  Percentage

For my own personal reasons, I needed the Percentage to be the second column and not the third.  Here’s the code to do the trick.

myDataTable.Columns(2).SetOrdinal(1)

Sounds easy enough… of course, NOT!  Try it a normal way and you will be scolded for trying to add a row that already belongs to another table… JEEZ WHAT WERE YOU THINKING!  (God forbid, it just know that I want it copied….freaking reference types.)

Anyway,  here’s how you make add a new row to a datatable that is the same as the row in a different datatable.

‘CREATE THE ROW
Dim newRow As DataRow = finalTable.NewRow
‘COPY the ITEMS from your OLD ROW
newRow.ItemArray = OLDrow.ItemArray
‘ADD THE ROW (again… I mean what the heck does finaltable.NewRow do!?!?!?!)
finalTable.Rows.Add(newRow)

===================================================

And that’s it… another nugget.

Wanna be a .Net / Excel GENIUS CODE MONKEY in seconds? Well let me show you how….

If you would like to know how to create sweet Charts on your excel spreadsheet straight from your code (especially if you are using VB) - do this.

  1. Open your excel spreadsheet.
  2. Record a macro and do all your cool charting stuff
  3. Open the Macro box from the Tools
  4. Choose your newly created Macro and click EDIT

Whalah - the Script editor will open up will all the proper VB code in there for you.  Simply cut and paste this code into your code and then tell your PM that you are a friggin CODING genius and that you need a raise or you’re WALKING!  (ok, that last part might be a bit much).

IF YOU do not know how to create an Excel doc in the first place from Code - check out my previous post entitled: EXCEL : Run, Fill, and Execute Macro… with .Net

** FINALLY you might have to do some small changes to the way the code is formatted… look below to see how I created my own chart object, added it to my workbook and then simply added my NINJA (ahem, macro) code:

‘   Generating the graph
Dim chart As Excel.Chart
chart = wkbk.Charts.Add()

With chart
.ChartType = Excel.XlChartType.xlColumnClustered
.SetSourceData(wksheet.Range(”C1:E11″), 2)

.SeriesCollection(1).Name = “=”"In Range”"”
.SeriesCollection(2).Name = “=”"Attempts”"”

.Location(Where:=Excel.XlChartLocation.xlLocationAsNewSheet, Name:=”Charted Data”)
.HasTitle = True
.ChartTitle.Characters.Text = “HFZ STATE REPORT”

.Axes(1, Excel.XlAxisGroup.xlPrimary).HasTitle = True
.Axes(1, Excel.XlAxisGroup.xlPrimary).AxisTitle.Characters.Text = “Tests”
.Axes(2, Excel.XlAxisGroup.xlPrimary).HasTitle = True
.Axes(2, Excel.XlAxisGroup.xlPrimary).AxisTitle.Characters.Text = “Attempts”

End With

C# Escape Characters

December 1st, 2008

Escape Characters:
\’                    Single quote
\”                   Double quote
\\                  Backslash
\0                 Null
\a                 Alert
\b                 Backspace
\f                  Form feed
\n                 New line
\r                  Carriage return
\t                  Horizontal tab
\v                 Vertical quote

Ok, you know what you want to remove from the end of a string but for whatever reason you do not know how long the string is (maybe you built it dynamically) -

Here’s my solution - use the .Remove method of the String object and use the .Length method as the first parameter.

i.e. - say I want to remove “<br>” from the end of my string but I am not sure how long it is.  Well I can get the length this way  myString.Length and I want the starting position to be 4 from that total.  So my statement would be:

myString = myString.Remove(myString.Length - 4, 4) — 4 being the amount of places to remove — and whalah… you just removed the last 4 characters of your string!