Short simple procedure to clear out the textboxes and reset the dropdowns on a page. Pass in the Page.Controls for example.
Private Sub ResetForm(ByVal cc As ControlCollection)
Try
For Each c As Control In cc
If TypeOf c Is TextBox Then
CType(c, TextBox).Text = String.Empty
ElseIf TypeOf c Is DropDownList Then
CType(c, DropDownList).SelectedIndex = 0
Else
If c.HasControls Then
ResetForm(c.Controls)
End If
End If
Next
Catch ex As Exception
' log an error
End Try
End Sub
I use this blog to record programming notes from both work and personal projects. I don't put everything I do on here but when I write a handy script or figure something out that I don't want to forget for next time, I add it to this blog. Feel free to use this blog in your own projects.
Test Menu
- Commentary
- Deals
- Coupons
Mar 15, 2012
Feb 14, 2012
Simple jQuery Print Friendly Page
The following script can be used to take the content from a section of a page, in this case a div, and put the content in a new simplified window. This is one way to exclude banners and graphics or deal with page layouts that don't print well. In the first section, on document ready, the link (or whatever element you like) is selected by the id "linkPrintFriendly" and assigned a function to execute when the element is clicked. I've also made the cursor a pointer when hovering over the element. The "printfriendly" function basically grabs html from an element on the page (with the class "theelementtoprint") and puts it in a new window that is opened. In this example, I'm also hiding a table that I don't want to show in the new window.
I found a very useful example showing the code at http://jsfiddle.net
<script type="text/javascript">
$(document).ready(function () {
$("#lnkPrintFriendly").click(printfriendly);
$("#lnkPrintFriendly").css("cursor", "pointer");
});
function printfriendly() {
//open a new window or tab
var w = window.open();
//include only the content of the center div or rightnocenter div
var html = $(".theelementtoprint").html();
//provide a title
w.document.title = 'Page Title';
//put the html into the new page
$(w.document.body).html(html);
//hide the table
$(w.document).find("#tblFunctions").hide();
}
</script>
Jan 26, 2012
An Overloaded ASMX
Recently, I wanted to create an overloaded function to use in a web service. In one of the methods, an ID will be accepted as a parameter to query records matching the ID. In the other method, no ID is passed in and all records are returned. Sure, I could have have given my methods different names, but what would I learn from that? This was for an asmx.
Two areas need to be modified to have overloaded web methods.
Two areas need to be modified to have overloaded web methods.
- At the beginning of the service, change the web service binding from this:<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> to this: <WebServiceBinding(ConformsTo:=WsiProfiles.None)>
- Give the web method a message name like this: <WebMethod(MessageName:="WithID")
Dec 14, 2011
Deploying Crystal Reports for Visual Studio 2010
If you're writing an application that uses Crystal Reports for Visual Studio 2010, the steps for deploying the application and getting the report to work are not obvious. The following steps helped me with deployment.
- Download and install the Crystal Reports for Visual Studio 2010 Run-time on the server where application will be deployed.
Download is here: http://www.businessobjects.com/jump/xi/crvs2010/us2_default.asp
- Copy C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ASP.NETClientFiles
- Paste to \Inetpub\wwwroot\aspnet_client\system_web\2_0_50727 (or the asp_client folder of the default website).
These steps seem very simple, but for a while I was running the report and getting a blank window. I noticed a javascript error "bobj is undefined". That was because I hadn't done steps 2 and 3. Some searches led me an answer here: http://bytes.com/topic/net/answers/823323-crystal-report-error-bobj-undefined
Crystal Reports - Text or Text Number With Three Decimal Places
This is a Crystal Report formula field. The requirement is to display the string 'No Data' when the value is null and if it isn't null show the number with three decimal places.To display 'No Data' both parts of the if must be converted to text.
If NumericText ({SupplierStatistic.pHMin}) Then
ToText(ToNumber({SupplierStatistic.pHMin}),3)
Else
'No Data'
Nov 29, 2011
Averages with Linq
Here are two different ways to get the average using Linq. These examples use a generic list of a class that has a Temperature property:
Dim avgTemperature = (From c In lst Where c.Temperature IsNot Nothing Select c.Temperature).Average()
Dim avgTemperature = From t In lst Where t.Temperature IsNot Nothing Aggregate Temperature In lst Into Average(t.Temperature)
Dim avgTemperature = (From c In lst Where c.Temperature IsNot Nothing Select c.Temperature).Average()
Dim avgTemperature = From t In lst Where t.Temperature IsNot Nothing Aggregate Temperature In lst Into Average(t.Temperature)
Nov 28, 2011
Concatenating Static Text to an Eval Expression
This wasn't obvious to me even though it seemed basic. Full credit goes to the original post on stackoverflow.
I was using a datalist and wanted to concatenate the text "Collection Type: " before the Eval expression. The only solution I could find was to use a format string. I favored this solution instead of using the code-behind.
<asp:Label ID="CollectionTypeLabel" runat="server" text='<%#DataBinder.Eval(Container.DataItem, "CollectionType", "Collection Type: {0}")%>' />
I was using a datalist and wanted to concatenate the text "Collection Type: " before the Eval expression. The only solution I could find was to use a format string. I favored this solution instead of using the code-behind.
<asp:Label ID="CollectionTypeLabel" runat="server" text='<%#DataBinder.Eval(Container.DataItem, "CollectionType", "Collection Type: {0}")%>' />
Nov 22, 2011
Databound Checklist - Check All by Default
The following code shows an easy way to loop through the list of checkboxes and select each one:
''' <summary>
''' checks all of the checkboxes by default
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Sub chkListParameterSelections_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkListParameterSelections.DataBound
Try
For Each li As ListItem In chkListParameterSelections.Items
li.Selected = True
Next
Catch ex As Exception
ErrorLogging.LogError(ex, "ctrlStatistics.chkListParameters_DataBound")
End Try
End Sub
Nov 10, 2011
CSS Problem After IFrame Loads
Problem: The CSS is breaking in a web page that includes an iframe in IE8 when the content of the iframe loads. The page works fine in firefox and chrome. Other pages without the iframe that use the same CSS file don't have the problem.
Fix: This tag was in the head:
<meta http-equiv="X-UA-Compatible" content="IE=8" />
It was changed to:
<meta http-equiv="X-UA-Compatible" content="IE=7" />
Nov 4, 2011
Clear All Textboxes on a Web Form
For Each ctrl As Control In Form.Controls
If ctrl.GetType.Name = "TextBox" Then
Dim tb As TextBox = ctrl tb.Text = String.Empty
End If
Next
If ctrl.GetType.Name = "TextBox" Then
Dim tb As TextBox = ctrl tb.Text = String.Empty
End If
Next
Oct 5, 2011
Convert Delimited List to List(of String)
Converting a Pipe Delimited List of Values into a Generic List (of String)
Sometimes it's helpful to convert data into a different format before further processing. In this case, converting the delimited list to a generic list of string will make it more friendly for loops.Public Shared Function CreateSupplierList(strSupplierPipedList As String) As List(Of String)
Try
' split the pipe delimited list into an array and then add to a generic list
Dim strSupplierList() As String = strSupplierPipedList.Split("|")
Dim lst As New List(Of String)
For intCount = 0 To strSupplierList.Length - 1
lst.Add(strSupplierList(intCount))
Next
Return lst
Catch ex As Exception
Return New List(Of String)
End Try
End Function
Aug 18, 2011
Using Lists Instead of Paragraph Tags for Lists of Links
Instead of using multiple <p> tags for lists of links use <ul> and <li> tags!
Recently, I was revising and old web page and found some quick and easy improvements to make.
This is better J
<ul class="ul">
<li><a href="page1.htm">Page 1</a> </li>
<li><a href="page2.htm">Page 2</a> </li>
<li><a href="page4.htm">Page 3</a> </li>
<li><a href="page4.htm">Page 4</a> </li>
</ul>
Than this L
<p>
<font face="Arial, Helvetica, sans-serif" size="2"><a href="page1.htm">Page 1</a></font>
</p>
<p>
<font face="Arial, Helvetica, sans-serif" size="2"><a href="page2.htm">Page 2</a></font>
</p>
<p>
<font face="Arial, Helvetica, sans-serif" size="2"><b><a href="page3.htm">Page 3</a></b></font>
</p>
<p>
<font face="Arial, Helvetica, sans-serif" size="2"><a href="page4.htm">Page 4</a></font>
</p>
Jun 30, 2011
Force Compatibility Mode in Meta Tag
Here's a nice easy way to force the page to be loaded in IE compatibility mode.
<meta http-equiv="X-UA-Compatible" content="IE=7" />
Jun 21, 2011
Calling Existing Javascript from Code Behind
Notes on how to call an existing javascript function from the code-behind. The "confirmDelete" function below calls a jQuery dialog that will be used to delete records from a datalist. I'm running this script from the code behind because I want to populated the dialog with values from the datalist record to allow the user to view the data they are about to delete. The code at the bottom contained in the datalist ItemCommand method and runs when the e.CommandName = "Delete".
ASPX
<script type="text/javascript">
// increase the default animation speed to exaggerate the effect
$.fx.speeds._default = 400;
function confirmDelete() {
var dlgeditproduct = $(".deleteconfirmdiv").dialog({
modal: true,
width: 750,
height: 450,
autoOpen: false,
title: "Are you sure you want to delete this News Release?",
hide: "explode"
});
$(".deleteconfirmdiv").dialog("open");
dlgeditproduct.parent().appendTo(jQuery("form:first"));
};
</script>
VB
Page.ClientScript.RegisterStartupScript(Me.GetType(), "confirmdelete", "confirmDelete();", True)
ASPX
<script type="text/javascript">
// increase the default animation speed to exaggerate the effect
$.fx.speeds._default = 400;
function confirmDelete() {
var dlgeditproduct = $(".deleteconfirmdiv").dialog({
modal: true,
width: 750,
height: 450,
autoOpen: false,
title: "Are you sure you want to delete this News Release?",
hide: "explode"
});
$(".deleteconfirmdiv").dialog("open");
dlgeditproduct.parent().appendTo(jQuery("form:first"));
};
</script>
VB
Page.ClientScript.RegisterStartupScript(Me.GetType(), "confirmdelete", "confirmDelete();", True)
Jun 20, 2011
ASP.NET - Read Content of File from FileUpload Control
' this code would be on the page or control and be called on some kind of action (click etc)
Dim strFileContent As String = ReadFileToString(FileUpload.PostedFile.InputStream)
' function to return file content as string from the Stream (in this case is was an html file)
Private Shared Function ReadFileToString(ByVal streamFileContent As System.IO.Stream) As String
Try
' read the contents of the file into a string
Dim strFileContent As String = String.Empty
Using sr As IO.StreamReader = New IO.StreamReader(streamFileContent)
strFileContent = sr.ReadToEnd
End Using
Return strFileContent
Catch ex As Exception
Utilities.LogError(ex, "ParseHTML.vb.ReadFileToString")
Return String.Empty
End Try
End Function
Dim strFileContent As String = ReadFileToString(FileUpload.PostedFile.InputStream)
' function to return file content as string from the Stream (in this case is was an html file)
Private Shared Function ReadFileToString(ByVal streamFileContent As System.IO.Stream) As String
Try
' read the contents of the file into a string
Dim strFileContent As String = String.Empty
Using sr As IO.StreamReader = New IO.StreamReader(streamFileContent)
strFileContent = sr.ReadToEnd
End Using
Return strFileContent
Catch ex As Exception
Utilities.LogError(ex, "ParseHTML.vb.ReadFileToString")
Return String.Empty
End Try
End Function
May 23, 2011
Linq - Select TOP Example
An example of a linq statement that takes the first three items in the collection of listitems. I used this example when I was synchronizing different tabs of a website that each had listboxes. One of the tabs had a limit of three selected items:
Protected Sub Page_ListSync(ByVal lstSelected As List(Of ListItem), ByVal lstAvailable As List(Of ListItem))
Try
' just take the first three from selected
Dim liCollection = From li In lstSelected Select li Take 3
lstSelected = liCollection.ToList()
SRBC.RWQMN.SyncListboxes(lstSelectedStations, lstSelected, lstAvailableStations, lstAvailable)
Catch ex As Exception
SRBC.SRBCErrorLogging.LogError(ex, "ctrlStatistics.Page_ListSync")
End Try
End Sub
Protected Sub Page_ListSync(ByVal lstSelected As List(Of ListItem), ByVal lstAvailable As List(Of ListItem))
Try
' just take the first three from selected
Dim liCollection = From li In lstSelected Select li Take 3
lstSelected = liCollection.ToList()
SRBC.RWQMN.SyncListboxes(lstSelectedStations, lstSelected, lstAvailableStations, lstAvailable)
Catch ex As Exception
SRBC.SRBCErrorLogging.LogError(ex, "ctrlStatistics.Page_ListSync")
End Try
End Sub
May 4, 2011
SQL - Keep Functions Out of the Where Clause
Taking functions out of the where clause improved stored procedure performance by 2300%. In my original stored procedure with two functions in the where clause it used to take 46 seconds to complete, but by replacing the functions with the raw data value that they return, the time was reduced to just 2 seconds
Slow:
SELECT MAX(Temperature)
FROM #tblStationStatistics
WHERE StationID = A.StationID
AND Temperature BETWEEN dbo.fnGetMinThreshold('Temperature') AND dbo.fnGetMaxThreshold('Temperature')
Fast:
SELECT MAX(Temperature)
FROM #tblStationStatistics
WHERE StationID = A.StationID
AND Temperature BETWEEN -10 AND 60
Slow:
SELECT MAX(Temperature)
FROM #tblStationStatistics
WHERE StationID = A.StationID
AND Temperature BETWEEN dbo.fnGetMinThreshold('Temperature') AND dbo.fnGetMaxThreshold('Temperature')
Fast:
SELECT MAX(Temperature)
FROM #tblStationStatistics
WHERE StationID = A.StationID
AND Temperature BETWEEN -10 AND 60
SQL - Check if a Temp Table Exists
IF OBJECT_ID('tempdb..#tblRawData') IS NOT NULL
BEGIN
TRUNCATE TABLE #tblRawData
END
BEGIN
TRUNCATE TABLE #tblRawData
END
Apr 19, 2011
SQL - Check if Table Exists
IF OBJECT_ID('db..mytable') IS NOT NULL
BEGIN
TRUNCATE TABLE mytable
END
BEGIN
TRUNCATE TABLE mytable
END
Subscribe to:
Posts (Atom)