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.

Tuesday, November 18, 2008

Automatically Scroll to the bottom of a DataGridView

DataGridView.CurrentCell = DataGridView(1, DataGridView.RowCount - 1)


Where DataGridView is the instance name of your DataGridView component. You're passing in Column and Cell selection into DataGridView()

Friday, October 24, 2008

Generate a Random String

If you need to generate a random string of mixed characters, this simple function will do it for you:
Public Function GenerateRandomString() As String
   GenerateRandomString= System.Guid.NewGuid.ToString
End Function

This will return something like this: 80a7a705-9c23-47bc-92b6-2b5c4f9d728d. Which you then can do various string functions to make it the way you want.

Thursday, October 23, 2008

Formatting Dates in GridView

If you have a date coming back to your GridView and it displays "11/01/2008 12:00am" and you'd rather just display the date and not the time, you can fill in the DataFormatString field when editing the column, with: {0:MM/dd/yyyy}

Friday, August 22, 2008

Call a Function in your MasterPage from your .aspx page

If you're going to be using a common function throughout the Web site, you can include the function in your MasterPage and gain access to it from each aspx that inherits from this MasterPage; like so:

CType(Me.Master, MasterPages_MasterPageName).FunctionOrSubName()


Simple as that!

Thursday, August 14, 2008

Randomize Query in SQL

Sometimes you want to return a bunch of data from a table, but you want it coming back in a random order. Maybe it's for keeping some content on a home page fresh. Here's how:

ssql="SELECT TOP 10 * FROM [someTable] ORDER BY NEWID()"


The key here is "ORDER BY NEWID()"

Loop through a DataReader

If you have stuff in a table, and you just want to loop through it, using a DataReader is your best bet:

Dim objDR As SqlClient.SqlDataReader
Dim objCommand As SqlClient.SqlCommand
Dim ConnectionString As String = "YOUR CONNECTION STRING HERE"
Dim objConnection As SqlClient.SqlConnection
Dim ssql As String

objConnection = New SqlClient.SqlConnection(ConnectionString)
ssql = "SELECT * FROM someTable"

If objConnection.State <> ConnectionState.Open Then
   objConnection.Open()
End If
objCommand = New SqlClient.SqlCommand(ssql, objConnection)
objDR = objCommand.ExecuteReader(CommandBehavior.CloseConnection)
objCommand = Nothing

If objDR.HasRows Then
   While objDR.Read()
      ' do your code here
      ' the following gives access
      ' to the table's field:
      ' objDR.Item("someField")
   End While
End If
objDR.Close()
objDR = Nothing

Monday, July 14, 2008

Managing your code into Regions

Separate code with regions:
#Region "print functions"
  'place all related subs, functions, etc here.
#End Region


Why use Regions? Simply put, regions just allow you to organize your code. They provide no functionality or interact with the rest of your code. Regions allow you to separate code and collapse the regions.

Friday, July 11, 2008

Accessing a variable in your masterpage from an .aspx page.

If you have a regular .aspx page that inherits a master page and you want access to some variable(s) in that masterpage, consider the following.

Say you currently have a variable in your masterpage dim'd as such:

Dim foo As String = "bar"


In order to access this foo variable in any of your pages that inherit this masterpage, simply add the following code in your masterpage.

Public Property foo() As String
  Get
    Return foo
  End Get
  Set(ByVal value As String)
    foo = value
  End Set
End Property


Now, in your regular .aspx content page you can gain access to the foo variable by doing the following in your Page_Load sub:

Dim newFoo As String = CType(Me.Master, MasterPages_Home).foo()


Conversely, you can change foo's value (or "set" it) by doing:

CType(Me.Master, MasterPages_Home).foo() = "new value"


In this example, MasterPages_Home is the class name of our MasterPage.

Thursday, July 10, 2008

Clear Recent Projects in Visual Studio 2005

Tired of seeing your Recent Projects list appear on the start page of Visual Studio .NET? Follow the directions outlined below:

1. Go to: Start > Run
2. Type "regedit"
3. Navigate to "HKEY_CURRENT_USER\software\microsoft\visualstudio\8.0\projectMRUList"
4. Delete any unnecessary listings.


This is unconfirmed for 2008

Wednesday, July 9, 2008

Inserting Dynamic HTML via Code Behind

If you need to insert HTML or any other code into your aspx source code at runtime use an asp:Literal control. The control is placed where the HTML or code should show up:

<asp:Literal runat="server" ID="favIcon" />


Now in the code behind, you can reference the literal and place any code into the literal like so:

favIcon.Text = "<link rel=""shortcut icon"" href=""favicon.ico"" />"


asp:Literal's come in handy when you need to insert code at specific places in your html source. Page.ClientScript.RegisterClientScriptBlock() is a great way to insert JavaScript and other code at run time too, but unfortunately the code is placed on the bottom of the html source where ASP wants it and not where you want it.

This is in no way a replacement for RegisterClientScriptBlock() as this function has its own great benefits for inserting JavaScript.

Wednesday, July 2, 2008

Access any table field in RowDataBound

Make sure you're in a DataRow, we don't want to do this when in a header, footer, or paging row, then give the table's field name you're looking for:

Dim FieldValue As String = ""
If e.Row.RowType = DataControlRowType.DataRow Then
    FieldValue = DataBinder.Eval(e.Row.DataItem, "fieldname")
End If

Thursday, January 3, 2008

Reindex, or Reseed your SQL Tables

If you've erased all the data in a table, and insert a new record, the first record ID will not be 1, or whatever the starting index number is that you required when setting up the table. To reset, reindex, or reseed these numbers and start at 1 again execute the following SQL:

DBCC CHECKIDENT (yourtable, reseed, 0)


Where 'yourtable' is the table you're reindexing.