Wednesday, December 31, 2008

Convert DateTime in MSSQL

If you need to convert the format of a DateTime field in your SQL statement, utilize the following SQL function:

SELECT CONVERT(varchar, DateField, 101) AS DateField FROM [someTable]

Where DateField is the field name that holds your date, and 10 being the format. See this page for formats: http://msdn.microsoft.com/en-us/library/aa226054.aspx

Problems: If you're looking to sort this field, don't expect it to sort like a DateTime field as this converts it to a varchar field.

Add JavaScript from CodeBehind

Utilize the RegisterStartupScript() function in the Page Load event:

ClientScript.RegisterStartupScript(GetType(Page), "keyname", "<script>//javascript here</script>")

Where "keyname" can be any unique key name as string.

Tuesday, December 30, 2008

Get record count from ObjectDataSource

Use the "Selected" declaration for your ObjectDataSource like so:

Private Sub ObjectDataSource1_Selected(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ObjectDataSourceStatusEventArgs) Handles ObjectDataSource1.Selected

End Sub

Now, utilize the following code within that subroutine:
Dim numRows As Integer = (e.ReturnValue).Tables(0).Rows.Count

Monday, December 29, 2008

Format a Phone Number

Dim pn As String = "(444) 444-444"
Dim newPn As String = Replace(Replace(Replace(pn, "-", ""), "(", ""), ")", "")
newPn = String.Format("{0:###-###-####}", Convert.ToInt64(newPn))


It's important that the newPn var that you pass into the Convert.ToInt64 function is in the xxxxxxxxxx format and that no characters are present.

Execute Code On Enter from Textfield

If you need to execute code when someone presses enter on a textfield, wrap the textfield with a panel and utilize the "DefaultButton" property in the panel control.

<asp:Panel ID="Panel1" runat="server" DefaultButton="btn_search">
<asp:TextBox ID="txt_search" runat="server" Font-Names="Tahoma" Font-Size="12px"></asp:TextBox>
<asp:Button ID="btn_search" runat="server" Font-Italic="False" Font-Names="Tahoma" Font-Size="12px" Text="Search" />
</asp:Panel>

In this example, we have a search area with a text field and a button. In the code behind, for the button, we have the code that we want to execute. When we press enter in the textfield, the "DefaultButton" (in thise case, "btn_search") is "clicked" and the code in the codebehind runs.

Zoom to points on Google Maps

If you have implemented a Google map, placed custom GPoints on it, and want to automatically zoom to best fit these points, try the following javascript:

function fitMap(map, points) {
   var bounds = new GLatLngBounds();
   for (var i=0; i< points.length; i++) {
      bounds.extend(points[i]);
   }
   map.setZoom(map.getBoundsZoomLevel(bounds));
   map.setCenter(bounds.getCenter());
}

Where "map" is the global map variable that is needed already by your Google Maps API code, and where "points" is an array of GLatLng() points; like so:

var zoompoints = new Array();
zoompoints = [];
zoompoints[0] = new GLatLng(longitude,latitude);
zoompoints[1] = new GLatLng(longitude,latitude);

fitMap(map, zoompoints);


Where "longitude" and "latitude" are the custom longitude and latitude you want for your individual points.

Loop through a DataSet

Assuming your DataSet (named, ds) is already populated with Data and contains only one table:

For Each DataRow As DataRow In ds.Tables(0).Rows
   Dim outData as String
   outData = DataRow("fieldName").toString
Next

Wednesday, December 24, 2008

Use a Generic Dictionary

Declaring a generic dictionary; adding values:
Dim xGD As New Generic.Dictionary(Of String, String)
xGD.Add("key1", "value1")


Where the Key and Value (String, String) can be any object.

Getting access to a value:
Dim value as String = xGD("key1")


Looping:
For Each xKVP As Generic.KeyValuePair(Of String, String) In xGD
   Consoe.Writeline(xKVP.Key & ", " & xKVP.Value)
Next

Monday, December 22, 2008

Access Field(s) from FormCode in an InfoPath Form

1. In the DataSource view, right click on the field you want to obtain the value from. Select, "Copy XPath" from the content menu.
2. In your FormCode utilize the following code (C#):

XPathNavigator myField = this.MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:fieldName", NamespaceManager);

Where "myField" can be any variable name you'd like (I choose to call it the same as the name on the InfoPath form; and where "/my:myFields/my:fieldName" is the copied XPath from your clipboard (from Step 1).

You can now access that field like so:
string fooBar = fieldName.value

Protect Javascript

Sometimes you may have proprietary functions/algorithms that you don't want copied as they are a core object to what you're offering on your Web site (i.e. Users have payed a subscription fee to use custom-made algorithms). You want to prevent people from saving the Web site to their hard drive and simply using the functions there. Granted, you could protect the function in the code behind, or on a postback in the ASP/PHP programming, but sometimes the speed of client-side scripting is a determining factor. The downside is anyone can view the JavaScript (even if it's referenced in an external .js file). Here's a simple trick:

Note: This trick was originally done in the PHP environment; the concept should translate into the .NET world:

In your main .html, .php, .asp page, point to a file that will contain your javascript code. The file extension should be .php or .asp (whichever environment you're in):
<script language="javascript" type="text/javascript" src="/protectedJavascript.php"></script>

In the "protectedJavascript.php" file, place the following code:

if(!eregi("/originatingPage.html",$_SERVER['HTTP_REFERER'])) {
   echo "Message to those snooping here.";
} else {
   echo "//JAVASCRIPT CODE HERE";
}

Where "/originatingPage.html" is the path of which calls this protected page. In the PHP world. the !eregi() function simply looks for a match between the two strings passed in.

Anyone trying to access this page will be shown the "Message to those snooping here." text (or whatever you have placed here.) because their HTTP_REFERER will not (or ever) be "/originatingPage.html". The only way they could see just the code is if you had a hyperlink pointing directly to "protectedJavascript.php" from "/originatingPage.html."

You can obtain this same functionality with an .asp page.

Validate Decimals with Javascript

Validating a decimal such as a measurement of time or currency (10.5 or 0.4) is as easy as:

function valNum(inNum {
   var RegEx = /[0-9]{1,8}\.?[0-9]{0,2}/;
   var ValidNumber = inNum.match(RegEx);
   return ValidNumber;
}

This function will return the correct number. If you feed in "10.5foo" the function will spit back 10.5. If you feed in "bar" the function will return nothing.