Tuesday, May 12, 2009

New Location

All new code snippets I find/write can now be found here:
http://snipplr.com/users/blackf0rk/

Thursday, April 16, 2009

Clear InfoPath Cache

InfoPath forms are stored here:
C:\Documents and Settings\[User]\Local Settings\Application Data\Microsoft\InfoPath\FormCache2
Delete what's in this folder.

Command line equivalent:
Infopath /cache clearall

Tuesday, February 3, 2009

Return Google Maps Coordinates from Street Address

This function will return Google Maps coordinates from a street address by using the Google-provided XML page. I have used regex to parse the data rather than the XML object to get the node(s):

Function GetGeoCoords(ByVal inString as String) As String
   Dim xmlString As String = GetHTML("http://maps.google.com/maps/geo?output=xml&key=abcdefg&q=" & inString, 1)
   Chunks = Regex.Split(xmlString, "coordinates>", RegexOptions.Multiline)
   outString = Replace(Chunks(1), ",0</", "")
End Function

Public Function GetHTML(ByVal sURL As String, ByVal e As Integer) As String
   Dim oHttpWebRequest As System.Net.HttpWebRequest
   Dim sChunk As String
   oHttpWebRequest = (System.Net.HttpWebRequest.Create(sURL))
   Dim oHttpWebResponse As System.Net.WebResponse = oHttpWebRequest.GetResponse()
   oStream = oHttpWebResponse.GetResponseStream
   sChunk = New System.IO.StreamReader(oStream).ReadToEnd()
   oStream.Close()
   oHttpWebResponse.Close()
   If e = 0 Then
      Return Server.HtmlEncode(sChunk)
   Else
      Return Server.HtmlDecode(sChunk)
   End If
End Function

Get Google Maps Coordinates from URL

This function will parse out the Google Maps coordinates from a Google Maps link url like this one: http://maps.google.com/?ie=UTF8&ll=43.068888,-87.978516&spn=23.565589,33.925781&t=h&z=5. The coordinates in this URL are 43.068888,-87.978516.

Public Function GetGeoCoords(ByVal inString As String) As String
   Dim Chunks As String()
   Dim outString As String = ""
   Chunks = Regex.Split(inString, "&")
   For Each s As String In Chunks
      If InStr(s, "ll") > 0 Then outString = s
   Next
   Return Replace(Replace(outString, "sll=", ""), "ll=", "")
End Function

Wednesday, January 28, 2009

Fix Version Increment in Visual Studio 2008

Visual Studio 2008's version increment doesn't work properly. Here's an add-in to fix it: http://www.codeplex.com/autobuildversion.

So if want the assembly version to be the same, but the file number to be incremented, this tool will allow you to easily configure these settings.

Tuesday, January 20, 2009

Return HTML from a Web page (VB.NET & PHP)

If you need to get the HTML from a Web page to rip it, process it, and/or display it in the way you want, the following function is key:

Public Function GetHTML(ByVal sURL As String, ByVal e As Integer) As String
   Dim oHttpWebRequest As System.Net.HttpWebRequest
   Dim oStream As System.IO.Stream
   Dim sChunk As String
   oHttpWebRequest = (System.Net.HttpWebRequest.Create(sURL))
   Dim oHttpWebResponse As System.Net.WebResponse = oHttpWebRequest.GetResponse()
   oStream = oHttpWebResponse.GetResponseStream
   sChunk = New System.IO.StreamReader(oStream).ReadToEnd()
   oStream.Close()
   oHttpWebResponse.Close()
   If e = 0 Then
      Return Server.HtmlEncode(sChunk)
   Else
      Return Server.HtmlDecode(sChunk)
   End If
End Function

And here's how to do it in PHP

$file = file_get_contents('http://www.yoururl.com');

*snicker*

Simple String Encryption

Public Function EncryptString(ByVal InSeed As Integer, ByVal InString As String) As String
   Dim c1 As Integer
   Dim NewEncryptString As String
   Dim EncryptSeed As Integer
   Dim EncryptChar As String

   NewEncryptString = ""
   EncryptSeed = InSeed
   For c1 = 1 To Len(InString)
      EncryptChar = Mid(InString, c1, 1)
      EncryptChar = Chr(Asc(EncryptChar) Xor EncryptSeed)
      EncryptSeed = EncryptSeed Xor c1
      NewEncryptString = NewEncryptString & EncryptChar
   Next

   EncryptString = NewEncryptString
End Function

Passing in a seed and your string will return an encrypted string. Pass in the same seed and the encrypted string again and it will return the original unencrypted string.

Wednesday, January 7, 2009

Loop Through Web AppSettings

For Each appSetting As String In ConfigurationManager.AppSettings.AllKeys
   Dim appSettingValue = ConfigurationManager.AppSettings.Get(appSetting)
Next


In this case, appSetting would be returning the key, where as appSettingValue is the value.

Friday, January 2, 2009

Use Temporary Tables in MSSQL

Create
CREATE TABLE #TempTable(FieldName1 VarChar(50), DateField1 DateTime, FieldName2 Int)
Inserting into the temp table is executed like any other table:
INSERT INTO #TempTable () VALUES ()
The table is dropped when the session is dropped. Otherwise:
DROP TABLE #TempTable

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.