Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Articles
Search: 

Bonnie Berent's Tips
Bonnie DeWitt, June 1, 2006
Great tips for .NET developers
Summary
Great tips for .NET developers
Description

Reading XML with XmlDocument
One of the gotchas that seem to trip people up when reading Xml Nodes is resolving the namespace. The XML file that I'm trying to parse looks like this:
<Message xmlns="http://www.connectpas.com/webservice/0-20041220"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" parseonly="false" ConfigId="004287">
	<CallHeader>
		<CallId>{05199945-4C3A-4F5E-B0D8-B9BE49BFDBA3}</CallId>
		<SentDateTime>2005-08-18T16:29:29</SentDateTime>
		<ServerName>GAINESVILLE</ServerName>
		<From>
			<Company>
				<CompanyId>031989</CompanyId>
				<CompanyPassword>{0D17}</CompanyPassword>
			</Company>
			<User>
				<UserId>TestUser</UserId>
				<UserPassword>ActiV8</UserPassword>
			</User>
		</From>
	</CallHeader>
	<Response xsi:type="Response_Type">
		<ResponseHeader>
			<ResponseServerName>PCWS_SERVER</ResponseServerName>
			<ResponseTime>2005-08-18T15:28:27</ResponseTime>
		</ResponseHeader>
		<Status>
			<Severity>InputContentError</Severity>
			<Level>LogRequest</Level>
			<Code>51053</Code>
			<Description>Invalid CardNumber.
                         CardNumber has an invalid length.</Description>
			<Action>Please correct and resubmit.</Action>
		</Status>
	</Response>
</Message>


OK, so now I want to retrieve the NodeList for Status. If I try the following code, it shows a count of zero, meaning my NodeList retrieval didn't work:
	string StrXml = "TestXMLNodes.xml";

	//Create Xml Dom Instance
	XmlDocument ODoc = new XmlDocument();
	XmlNodeList ONodeList;
	ODoc.Load(StrXml);

	ONodeList = ODoc.SelectNodes("/Message/Response/Status");

	MessageBox.Show(ONodeList.Count.ToString());


So, what did I leave out? The namespace needs to be resolved. The correct code looks like this:
	string StrXml = "TestXMLNodes.xml";

	//Create Xml Dom Instance
	XmlDocument ODoc = new XmlDocument();
	XmlNodeList ONodeList;
	ODoc.Load(StrXml);

	//Create an XmlNamespaceManager for resolving namespaces.
	XmlNamespaceManager nsmgr = new XmlNamespaceManager(ODoc.NameTable);
	nsmgr.AddNamespace("junk", "http://www.connectpas.com/webservice/0-20041220");

	ONodeList = ODoc.SelectNodes("/junk:Message/junk:Response/junk:Status", nsmgr);

	MessageBox.Show(ONodeList.Count.ToString());

from a solution provided by Viv Phillips in Message #1043422

Data Relations with Multiple Columns
The DataRelation class has a constructor that accepts arrays of DataColumn objects so that you can have a relationship with values from multiple columns.
	Dim oParentCols, oChildCols As DataColumn()
	With MyDs.Tables("ParentTable")
		oParentCols = New DataColumn() {.Columns("code"), .Columns("Item")}
	End With
	With MyDs.Tables("ChildTable")
		oChildCols = New DataColumn() {.Columns("code"), .Columns("Item")}
	End With

	'Create the new DataRelation.
	Dim oRelation As DataRelation
	oRelation = New DataRelation("MyRelationOnCodeItem", oParentCols, oChildCols)
	MyDs.Relations.Add(oRelation)

from a solution provided by Kevin Goff in Message #1067531

Tracking User Timeouts in ASP.NET
Create a table in SQL Server that tracks logins and logouts. The table should have columns for a 20-byte hash, an original login datetime column, a timestamp or datetime column for "last hit", and a bit for tracking whether the row is a login or a logout message. Optionally, the table can perform double duty as a web page access and troubleshooting log. The columns can be expanded to include a username, a varchar for a function/method name, a web page name, timestamp, etc...

Use forms authentication on your web site.

Create a new class that implements IPrincipal and IIdentity that contains a property that is a hash of the username, password, and timestamp.

In the global.asax.vb, after authenticating the user, generate the hash and insert a new row in your LOGIN table. The hash is the primary key (or candidate key if you must have an int identity column as the PK).

Subclass the Page class and add a readonly property called "LoginKey" that will hold the hashed value. Back the property with session or viewstate. In my framework, this same class is also used to check authentication and authorization every time the page loads, but this is optional.

Pass the login key to every call to the Data layer. Every function/method in the data layer first checks with the LOGIN table to make sure that the user is logged in (a "login" message matching the loginkey exists and a corresponding "logout" message does not).

As the table is being checked, update the "last hit" column.

If the login row does not exist or if the user is already logged out, throw an exception.

You custom Page class will trap the exception and redirect to the login page.

Create a SQL Server job that runs every 2-3 minutes. This job will go through the login table and insert logout rows when it finds a "last hit" that is older than whatever your chosen timeout is. At the same time, you can delete or archive old rows.

That's it in a nutshell (some details have been left out for brevity's sake).

from a solution provided by Keith Payne in Message #1038867

Process Log - TextBox or ListBox?
We've all seen apps that display a list of tasks being processed by the app. As lines are added to the list, it automatically scrolls to keep the last item visible. The question here is which methodology would be more efficient, use a textbox and append the new text to its text property and use the scrolltocaret method? Or use a listbox and add new items to the list?

The Listbox will perform better. The Textbox.Text property is a string and strings are immutable. Each time you perform an operation on a string - like append, replace, trim - .NET copies the entire string into a new buffer and returns a new string object to replace the old one.

Listbox.Items is simply a list of pointers to objects. Adding more objects means adding four bytes to the end of the list.

Here's the sample code comparing the two methodologies:
Public Class Form1
    Inherits System.Windows.Forms.Form
'blah blah blah the things the are added automatically go here
    Public Function addText(ByVal newText As String)
        'Is it first item on the list?  If so, do not add linefeed
        If TextBox1.TextLength = 0 Then
            TextBox1.Text = newText
        Else
            'I could use string builder here, but I am lazy
            TextBox1.Text = TextBox1.Text + Chr(13) + Chr(10) + newText
        End If
        TextBox1.SelectionStart = TextBox1.TextLength - 1
        TextBox1.ScrollToCaret()
    End Function
    Public Function addList(ByVal newItem As String)
        'Use the begin and end update to avoid flicker
        ListBox1.BeginUpdate()
        ListBox1.Items.Add(newItem)
        ListBox1.SetSelected(ListBox1.Items.Count - 1, True)
        ListBox1.EndUpdate()
    End Function
    Private Sub butAddLst1K_Click(ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles butAddLst1K.Click
        'Adds 1000 items to the list
        Dim t As Int16
        For t = 1 To 1000
            addList("Item #" + t.ToString())
        Next
    End Sub
    Private Sub butAddLst1_Click(ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles butAddLst1.Click
        'Adds 1000 items to the list
        addList("One more Item")
    End Sub
    Private Sub butAddTxt1K_Click(ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles butAddTxt1K.Click
        'Add 1000 'items' to the textbox
        Dim t As Int16
        For t = 1 To 1000
            addText("Item #" + t.ToString())
        Next
    End Sub

    Private Sub butAddTxt1_Click(ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles butAddTxt1.Click
        'Add 1 'item' to the textbox
        addText("One More Item")
    End Sub
end class

from a solution provided by Ric Parodi and Keith Payne in Messages #1026018, 1026245
Ric supplied the code sample, Keith supplied the answer to the question.

Bonnie DeWitt, Geneva Systems Group
Bonnie is currently one of the principals of Geneva Systems Group. Call her the Senior Software Engineer, or even call her the VP of Engineering. She has no official title at the moment. Bonnie has been writing software in various languages for about 30 years. Bonnie's current focus on C# .NET applications began in early 2002. She has been a Microsoft C# MVP since Oct 2003 and an active member of the .NET online community.
More articles from this author
Bonnie DeWitt, September 1, 2005
Great tips for .NET developers
Bonnie DeWitt, October 1, 2005
Great tips for .NET developers
Bonnie DeWitt, November 1, 2005
Great tips for .NET developers
Bonnie DeWitt, December 1, 2005
Great tips for .NET developers
Bonnie DeWitt, April 1, 2009
Great tips from the .NET developer community compiled by Bonnie Berent.
Bonnie DeWitt, February 1, 2006
Great tips for .NET developers
Bonnie DeWitt, March 1, 2006
Great tips for .NET developers
Bonnie DeWitt, April 1, 2006
Great tips for .NET developers
Bonnie DeWitt, May 1, 2006
Great tips for .NET developers
Bonnie DeWitt, July 1, 2006
Great tips for .NET developers
Bonnie DeWitt, August 1, 2006
Great tips for .NET developers
Bonnie DeWitt, September 1, 2006
Great tips for .NET developers
Bonnie DeWitt, October 1, 2006
Great tips for .NET developers
Bonnie DeWitt, November 1, 2006
Great tips for .NET developers
Bonnie DeWitt, December 1, 2006
Great tips for .NET developers
Bonnie DeWitt, January 1, 2007
Great tips for .NET developers
Bonnie DeWitt, February 1, 2007
Great tips for .NET developers.
Bonnie DeWitt, March 1, 2006
Great tips for .NET developers.
Bonnie DeWitt, April 1, 2007
Great tips for .NET developers.
Bonnie DeWitt, March 1, 2007
Good tips for .NET developers.
Bonnie DeWitt, May 1, 2007
Great tips for .NET developers.
Bonnie DeWitt, June 1, 2007
Great tips and tricks for .NET developers.
Bonnie DeWitt, July 1, 2007
Great tips for .NET developers.
Bonnie DeWitt, August 1, 2007
Great tips for .NET developers
Bonnie DeWitt, September 1, 2007
Great tips for .NET developers.
Bonnie DeWitt, February 1, 2008
Great tips from the Universal Thread .NET community.
Bonnie DeWitt, March 1, 2008
Great tips for .NET developers selected from the community by Bonnie Berent.
Bonnie DeWitt, April 1, 2008
Great tips from the .NET developer community compiled by Bonnie Berent.
Bonnie DeWitt, January 1, 2006
Great tips for .NET developers