Archive for the '.Net' Category

ASP Net – Parser Error – Could not load type ‘xxx.global’

I started getting this error out of the blue and it was brutal. All dlls were compiled through VS 2008 and everything ran fine locally, but, as soon as I loaded the dll to the hosted server, the error appeared. I looked through hundreds of posts, but nothing would resolve the issue. I couldn’t even create a one page web site.

I ended up doing a fresh install on VS 2008 on a separate machine and that dll worked. I then did a XP repair on the initial machine and created a new user profile. Using the new profile, I could compile a dll that would work. When I logged into the old profile the error came back.

In this instance, something got screwed up in the initial profile that must have been causing a version conflict or some other issue. Not really sure how it happened, but I am glad it is over.

Set gridview header color in css

Setting a gridview header forecolor is pretty straight forward. One thing to keep in mind is that enabling sorting makes the header element = A, so you need to have an A class in your css.


.dgrHeader
{
color:Red;
text-align:left;
height:10px;
}
 
.dgrHeader a:link, .dgrHeader a:visited, .dgrHeader a:active
{
color:rgb(102,102,102);
text-align:left;
height:10px;
}


After your css is configured, you can either set the property programatically:

 
grdTemp.HeaderStyle.CssClass = "dgrHeader"

or in the grid itself:


<HeaderStyle CssClass="dgrheader" />

Collection was modified; enumeration operation may not execute.

Certain collections blow out when you use a for each loop, as the change in value results in the item dropping out of the collection.

This code resulted in the above error as it caused the CheckNodes collection to change.


For Each node As TreeNode In TreeView1.CheckedNodes
    node.Checked = False
Next

Re-writing the code as so works fine:


Dim y As Integer = TreeView1.CheckedNodes.Count
While y > 0
    TreeView1.CheckedNodes.Item(0).Checked = False
    y -= 1
End While

recreate designer.vb

After adding the AJAX control toolkit, the designer.vb page stopped staying in synch when I would add and delete controls.

Even though there were no compile errors and all the toolkit controls rendered fine in VS 2008, the designer file needed a reference to the AJAX toolkit in the project. I had only placed the reference in the actual page.

To regenerate designer.vb:

Delete the designer.vb page, right click on the aspx page and choose Convert to Web Application.

showModalDialog and ASP .Net

This type of error can get you wound up. I was using showModalDialog to open a new window and return values from a list. Every time I hit OK or Cancel, a new window would be spawned.

Turned out to be a simple fix. Just add the line below into the <HEAD> section of the page being opened.

<base target=_self>

.Net treeview selecting nodes

The treeview control has a lot going for it, but it is lacking any sort of ability to maintain state of the currently selected node. This becomes an issue when you want to change/maintain a property on a selected node.

An example would be a treeview of urls where you want to set the backcolor of the selected node after navigating to the new page.

The only way I found to resolve this issue is to store the node.valuepath in a session variable and reselect it during the page_load event.

First, make sure none of your urls are in the NavigateUrl property. This puts the treeview into “Navigation” mode and results in the OnSelectedNodeChanged event not firing. Urls go in the Value property.

Be sure to change your treeview PathSeparator to something like “|” or something other than the default “/”. If you forget to change the default value, it will cause all sorts of problems when using FindNode.

Next, add some code to catch the selectednode.valuepath


Private Sub TreeView1_SelectedNodeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TreeView1.SelectedNodeChanged
Session("selected") = TreeView1.SelectedNode.ValuePath
Response.Redirect(TreeView1.SelectedNode.Value, "false")
End Sub

Finally, add code to the pageload or init event:


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Session("selected") <> "" Then
TreeView1.FindNode(Session("selected")).Select()
End If
End Sub

Multiple IIS sites on XP Pro

You can configure multiple IIS sites in XP Pro, but you can only have one running at a time. Not sure why the MMC won’t let you do it, but there is an easy work around.

From the \Inetpub\Adminscripts directory

Find out what the highest numbered site is:

adsutil.vbs ENUM /P W3SVC

To create a new site:

adsutil.vbs COPY W3SVC/1 W3SVC/x

where x is the # of the new site

Here are the detailed instructions.

I have found this to be useful when testing .Net apps without wanting to launch studio.

ObjectDataSource configuration

When you have a gridview bound to an ObjectDataSource, you have to be sure to pass the fields defined in the gridview’s DataKeyNames section to your Delete and Update methods.

Otherwise, you will get an error similar to:

ObjectDataSource 'objDSStatus' could not find a non-generic method 'DeleteContactStatus' that has parameters: ContactStatusId, ContactStatusTypeId.

In this instance I had DataKeyNames=”ContactStatusId, ContactStatusTypeId”, but the DeleteContactStatus method only contained ContactStatusId – the actual primary key.

Also be sure OldValuesParameterFormatString=”{0}”

You don’t need to configure the DeleteParameters in the ObjectDataSource properties as the defined DataKeyNames are passed automatically.

Here is the update code that worked:

  1. Public Sub DeleteContactStatus(_
  2. ByVal ContactStatusId As Integer, _
  3. ByVal ContactStatusTypeId As Integer)
  4.  
  5. Dim arrParams(0) As SqlParameter
  6.  
  7. arrParams(0) = New SqlParameter("@iContactStatusId", ContactStatusId)
  8.  
  9. strSql = "Delete From ContactStatus " & _
  10. "Where ContactStatusId = @iContactStatusId"
  11.  
  12. SqlHelper.ExecuteNonQuery(cn, CommandType.Text, strSql, arrParams)
  13. End Sub

web.config and WebConfigurationManager

The 2.0 framework obsoletes many methods from 1.1.

A line like:

System.Configuration.ConfigurationSettings.AppSettings(“DocumentDirectory”)

results in a compiler warning.

Public Shared ReadOnly Property AppSettings() As System.Collections.Specialized.NameValueCollection' is obsolete: 'This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings'.

The new method is in the System.Web.Configuration namespace and is called WebConfigurationManager.

WebConfigurationManager.AppSettings(“DocumentDirectory”)

CSS items shows up as errors

After I brought a css file in as a theme, I ended up with dozens of errors on a rebuild. Even though HTML/CSS validation was set to Warning in Options, I had to uncheck the option, close the dialog, re-open the dialog, re-check, then re-start VS. CSS issues now no longer prevent a build.

Detailed description and screen shots can be found here:

http://www.west-wind.com/WebLog/posts/194167.aspx

Download files in ASP .Net

This is a useful function for downloading files. I use it a lot when downloading files from protected directories.

  1. Public Shared Function DownloadFile( _
  2. ByVal Server As HttpServerUtility, _
  3. ByVal Response As HttpResponse, _
  4. ByVal strFileName As String) As Boolean
  5.  
  6. Const adTypeBinary = 1
  7. Dim strSql As String
  8. Dim strFilePath, strFileSize, strDownloadFileName, strFileType As String
  9. Dim objFileInfo As FileInfo
  10.  

Remove HTML tags

RegEx can be a bit complex, but it sure can do a lot with just a few params. This function will strip all html tags in a string and return the enclosed data. | is the default delimiter.

  1. Public Shared Function RemoveHTMLTags( _
  2. ByVal strText As String, _
  3. Optional ByVal strDelimiter As String = "|") _
  4. As String
  5.  
  6. Return Regex.Replace(strText, "<(.|\n)+?>", strDelimiter)
  7. End Function
  8.  
  9. strData = RemoveHTMLTags("<td>1</td><td>2</td><td>3</td>")
  10.  
  11. strData equals "1|2|3"

Mutiple random numbers in VB .Net

The .Net Random class works well on its own, if you just need one random number. By default it uses the system time for the seed value. Where problems occur is when you need multiple random numbers inside a loop.

When I called Random.Next within the loop, it would always return the same number, as the seed value was always the same, even using the millisecond property of Now().

My solution was to multiply the Random seed (milliseconds) by the loop value which resolved the issue.

  1. Public Shared Function GetRandomNumber( _
  2. ByVal iLowerBound As Integer, _
  3. ByVal iUpperBound As Integer, _
  4. Optional ByVal iSeedMultiplier As Integer = 1) As Integer
  5.  
  6. Dim Random As New Random(Now.Millisecond * iSeedMultiplier)
  7. Return Random.Next(iLowerBound, iUpperBound + 1)
  8. End Function
  9.  
  10. Example:
  11.  
  12. For i = 1 To 5
  13. strKey = i.ToString & "|" & GetRandomNumber(1, 10, i).ToString
  14. Next

Datagrid with fixed width columns

I created a dynamic calendar using a datagrid with a width of 700px with each of the seven days set to 100px. I thought this would keep days in a fixed width column, but that was not the case.

I had to add the following to my code and then the columns stayed fixed:


dgrCalendar.Style.Add("table-layout", "fixed")

Dynamically set datagrid HeaderText

I am creating a ASP .Net page to maintain all of my lookup tables, rather than creating a separate page for every 2-4 field table.

Initially I thought I would change the headertext property during the datagrids OnItemDataBound event, checking for ListItemType.Header, etc. This proved a bit convoluted with the resolution being much simpler:

dgrLookupTable.Columns(1).HeaderText = "Source"

The ASP code looks like this:

  1. <asp:TemplateColumn SortExpression="1" HeaderText="">
  2. <HeaderStyle Width="150px"></HeaderStyle>
  3. <ItemStyle Wrap="False"></ItemStyle>
  4. <ItemTemplate>
  5. <span class="dgrOverflow">
  6. <%#Container.DataItem("1")%>
  7. </span>
  8. </ItemTemplate>
  9. <EditItemTemplate>
  10. <ASP:TextBox Size="40" id="txt1" Text='<%# Container.DataItem("1")%>' runat="server" />
  11. </EditItemTemplate>
  12. </asp:TemplateColumn>

1.1. datagrid in 2.0 .Net environment

My ISP recently migrated all 1.1 accounts to 2.0. All the 1.1 code seems to work fine. One bizarre thing was that the gridlines in all of my datagrids turned to white, which makes them invisible against a white background.

I found a couple posts that said if you made bgcolor=white, you would then be able to see the gridlines. I tried that and it did work, but obviously not a viable solution.

Turns out to be very simple. You need to set the bordercolor attribute of the datagrid in code:

dgrCalendar.Attributes.Add("bordercolor", "Black")

Initial thread

Extracting ViewState and other ASP .Net params

This is a very simple function for extracting any ASP .Net page state value such as __VIEWSTATE or __EVENTVALIDATION. These values are necessary when scraping some websites.

  1. Public Shared Function ExtractDotNetData(ByVal strData As String, ByVal strStateName As String, ByVal strDelimiter As String) As String
  2.  
  3. Dim iStateNamePosition As Integer = strData.IndexOf(strStateName)
  4. If iStateNamePosition < 0 Then Return ""
  5.  
  6. Dim iStateValuePosition As Integer = strData.IndexOf(strDelimiter, iStateNamePosition)
  7. If iStateValuePosition < 0 Then Return ""
  8.  
  9. Dim iStateStartPosition As Integer = iStateValuePosition + strDelimiter.Length
  10. Dim iStateEndPosition As Integer = strData.IndexOf("""", iStateStartPosition)
  11.  
  12. Return HttpUtility.UrlEncodeUnicode(strData.Substring(iStateStartPosition, iStateEndPosition - iStateStartPosition))
  13. End Function
  14.  
  15. strViewState = ExtractDotNetData(strResponseData, "__VIEWSTATE", "value=""")
  16. strEventValidation = ExtractDotNetData(strResponseData, "__EVENTVALIDATION", "value=""")

File permission error in .Net 2.0

If you are moving a .Net 1.1 app to a server with 2.0, you may need to add the param

<trust level="Full" originUrl="" />

to your web.config if you are doing any sort of file upload.

There may be a more elegant way, but this was the quickest resolution I could find.

« Previous Page