Split text in two columns in VB.NET

This is a function code snippet to split a text in to two or more columns in VB.NET.

It is converted from my previous posted: Split text into multiple columns in PHP

InputString – String to be split into columns
Columns – Number of columns
SplitString – String to look for to not split midtext etc

Example of how to use:
[code lang=”vb”]
Dim strColumns As String() = SplitIntoColumns(strText, 2, "<h2>")
strText = "<table><tr><td>" & strColumns(0) & "</td><td>" & strColumns(1) & "</td></tr></table>"

Code snippet:
[code lang=”vb”]
Function SplitIntoColumns(ByVal InputString As String, ByVal Columns As Integer, ByVal SplitString As String) As String()

‘ Source: http://blog.tjitjing.com

‘ Splits a string into x number of columns and returns result as an array of columns

‘ Parameters:
‘ $InputString String to be split into columns
‘ $Columns Number of columns
‘ $SplitString String to look for to not split midtext etc

‘ Change history:
‘ 2011-02-04/Max Version 1
‘ 2011-05-16/Max Version 1.2

Dim Output() As String
ReDim Output(0 To Columns – 1)

‘ Find middle of text
Dim ColLength As Integer = Len(InputString) / Columns

‘ Split into columns
Dim ColCount As Integer
Dim Pos As Integer, LastPos As Integer = 0
For ColCount = 1 To Columns

‘ Find $SplitString, position to cut
Pos = -1
If (LastPos + ColLength) < InputString.Length Then
Pos = InputString.IndexOf(SplitString, LastPos + ColLength)
End If
If Pos = -1 Then Pos = InputString.Length

‘ Cut out column
Output(ColCount – 1) = Mid(InputString, LastPos + 1, Pos – LastPos)

LastPos = Pos

Next ColCount

Return Output

End Function


[Edit: Updated function]

.NET Client Side Field Validation not working

This was driving me nuts earlier today, so this post is a kind of reminder to myself not to forget this again:

When using Routing in .NET 4 always remember to add exceptions for axd files!

In my case I could not get standard .Net Field Validation to work client side. It was simply failing, not firing up, kaputt!

This was an old Web Site project that I had not touched in over a year. The last few days I have upgraded it from .NET 2.0 to 4.0, upgraded the Visual Studio solution from VS2008 to VS2010, made a lot of functionality and programming changes and only today discovered that Field Validation was not working anymore 🙁
I tried to trace my steps but I had just made too many changes to figure out just what was causing this.

I spent hours testing and googling. I made the simplest pages with a single RequiredFieldValidator. I played around with ValidationGroup, EnableClientScript and all the properties you can think of, changed just about everything in web.config etc etc. But I could not get it to work in this particular Web Site project. Finally I used the Chrome built-in Developer Tool and saw a few lines like this:

Failed to load resource: the server responded with a status of 404 (Not Found)

WebResource.axd is basically Javascript libraries that contains .NET functions for things like Field Navigation, Tree View and Ajax.
Anyway, once I found this I spent another hour or so googling and testing before I finally remembered I had just implemented Routing the other day, added the ignore exception mentioned above and – bingo it was working again. 🙂

In a way something good came out of this because, when client side validation fails it will rely only on server side validation and that means another thing you should never forget – to always add at the top of your button click event:
[code]If Not Page.IsValid Then Exit Sub[/code]
I had forgot this, which meant that when my client side field validation – which I had relied on in the past – did not work, my script just kept going even though the fields did not validate. Of course, forgetting this opens up for all kinds of attacks from users who simply block javascript.

(I’m sure all this is already in some best practice document somewhere)

How to remove characters to avoid .NET Request Validation Error (A potentially dangerous Request.Path value was detected from the client)

In .NET Framework 4 url checking – request validation – is different from .Net 2.0. This is the error you will see when you hit this:

Server Error in ‘/’ Application.
A potentially dangerous Request.Path value was detected from the client

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: A potentially dangerous Request.Path value was detected from the client

If you have control over the url, you can avoid using disallowed characters. The default characters that are being checked for are:
< > * % & : \\

If you set your url’s programtically, e.g. from info in a database, simply do replace on these characters into something allowed.
For example (VB.NET):
strUrl = strUrl.Replace("&", "-")

Another method is to revert back to .NET 2.0 request validation and/or change the characters that are being validated. This can be done by changing the following in the web.config file:
<httpRuntime requestValidationMode="2.0" requestPathInvalidCharacters="*,%,:" />

I however, prefer the first method as request validation is a good thing: the purpose is to secure your site from injection attacks.

More info:
HttpRuntimeSection.RequestValidationMode Property
HttpRuntimeSection.RequestPathInvalidCharacters Property

ASP.NET Routing gives 404 error

I really like the new .NET 4 (3.5) routing, it is very simple and straight forward to implement – just add some MapPageRoute to your global.asax and then some RouteData.Values to your aspx files 🙂

Anyway it was simple until last night when I was adding routing to an old VB.NET WebSite project. I just could not get it to work, I kept getting HTTP 404 errors:

Error Summary
HTTP Error 404.0 – Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

Detailed Error Information
Module IIS Web Core
Notification MapRequestHandler
Handler StaticFile
Error Code 0x80070002

Finally I figured out that I had some stuff missing in my web.config to get this to work, ie making sure the routing module runs.
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />

or use this:

<modules runAllManagedModulesForAllRequests="true"/>
This is probably not a problem for new projects created in Visual Studio 2010 but obviously my old web.config needed some fixing.

Thanks to this blog post by Ashic Mahtab.

ASP.NET 4.0 Chart Control Problems on IIS7

I have been playing around with the ASP.NET 4.0 Chart Controls for a new web site (Bilvärdet.se – used car price statistics)

When deploying it to IIS7 on my Windows Server 2008 I ran in to a few problems:

1) I did not have .NET 4.0 Framework installed on the server

🙂 It turns out .NET 4.0 Framework is an optional update in Windows Update and for some reason that I could not figure out failed to install (error code: 80200053) Solution that worked: Manually installed it. I had to use a tool that was new to me, the Microsoft Web Platform Installer (Web PI). Seems to be a cool tool to download, install and configure all sorts of software (incl WordPress, Dupral, Joomla) on Windows, will check this out in more detail in the future.
Don’t forget to change the Application Pool for your Web Site/Web Application in IIS Manager to use .NET Framework 4.0

2) Next problem, error message: An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

This turned out to be a few lines of code in web.config that seems to be needed on my development machine (Windows7 and Visual Studio 2010) but causes problems on IIS7.

Just removed this section from production web.config on server and it worked:

[code lang=”xml”]<httpHandlers>
<add path="ChartImg.axd" verb="GET,HEAD,POST"
System.Web.DataVisualization, Version=, Culture=neutral,
PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers> [/code]

Thanks to Michael Narinsky for pointing this out.

3) Image file directory problems

First error message: Invalid temp directory in chart handler configuration c:\TempImageFiles\

Solution: Changed dir in ChartImageHandler app settings in web.config

[code lang=”xml”]<appSettings>
<add key="ChartImageHandler" value="storage=file;timeout=20;dir=c:\TempImageFiles\;"/>
</appSettings> [/code]

Then this error message: The temp directory in chart handler configuration is not accessible c:\xxx\images\

Followed error message suggestion and added access rights to directory (Properties – Security tab) for user NETWORK SERVICE

[Update: Other error message that can appear:
a) “Access to the path ‘C:\xxx\images\charts\chart.png’ is denied.” – this is the same as above, add rights for NETWORK SERVICE
b) “Could not find a part of the path ‘C:\xxx\images\charts\chart.png’.” – make sure directory exists or create it]

4) Charts not rendering with ASP.NET Routing

I’m using ASP.NET 4.0 Routing but this seems to be something Charts are not working well with. Charts are showing up as broken links. If you are using routing, you need to make sure ChartImg.axd is ignored. Add Ignore (or IgnoreRoute) and – this took me quite some time to figure out – make sure you add these before any MapPageRoute or it will not work!

This is what I added in VB.NET, add one line per level in virtual/route folder structure – first line is for root, second line for one subdirectory level, third line for two subdirectory levels.

[code lang=”vb”]routes.Ignore("ChartImg.axd/{*pathInfo}")

Thanks to Simon Steele.

BTW – Another nice link about ASP.NET Chart Control

BC30560: ‘MySqlConnection’ is ambiguous in the namespace ‘MySql.Data.MySqlClient’.

I got this error in one of my ASP.NET web sites after uploading a new version:

BC30560: ‘MySqlConnection’ is ambiguous in the namespace ‘MySql.Data.MySqlClient’.

It worked fine on my development machine but not on the production server. I could not figure out what it was for quite some time. Turned out I had added the mysql.dll to bin directory of my project and at the same time was referencing a shared (GAC) version of the same dll. I had made this and some other changes on the development machine that I had forgot about. The only thing that differed from the development and production machines was the web.config which I obviously did not check well enough.

Posting this here if someonelse or myself makes this stupid mistake again…

Convert Accented Characters to ASCII

It is pretty simple in .NET to convert Western Unicode (non-ASCII, accented, diacritics) to ASCII, but regardless I had a hard time figuring it out it so I’m posting here for my own future reference.

[code lang=”vb”]
Dim strTest as String = "Any string containing accented characters, e.g. åäöéèêÅÄÖÉÈÊ"
strTest = System.Text.Encoding.ASCII.GetString(System.Text.Encoding.GetEncoding(1251).GetBytes(strTest))

Punycode in VB.NET for IDN domains

On one of my web sites I noticed that IDN (Internationalized Domain Names) don’t work when I do Response.Redirect in VB.NET.

IDNs are used to allow accented and other special international characters (non-Ascii) to be used in domain names. Since Domain Name Servers (DNS) only support Ascii, any IDN is encoded in Punycode.

To encode a string as Punycode in VB.NET simply do this:

Dim strUrl As String = “http://idn-example-åäö.com”
Dim idn As System.Globalization.IdnMapping = New System.Globalization.IdnMapping
strUrl = idn.GetAscii(strUrl)