Google Plus invite give away

29 Comments

Would you like an invite to Google Plus, Googles new social network, the “Facebook and Twitter killer”?
I have a few invitations, post a comment here with your gmail address (currently it seems only gmail accounts are accepted, you should also have filled out your google profile)

For Swedish speakers this is another option to get a Google+ invitation: gratis

[Edit: As I understand it Google Plus is now open for all gmail accounts. I still have plenty of invites, so comment here if you want one and don't have a gmail email address]

Get root path in ASP.NET without using Tilde ~

No Comments

As you probably know you can use the tilde sign (~) in ASP.NET to get the relative path of the root of your Web Site or Web Application. But unless using the Link Server Control or similar you may need some code to convert it to a correct url or get the absolute path.

Using a Server Control – example using the HyperLink Web Server Control

MyHyperLink.NavigateUrl = "~/Products/XYZ"

Using HttpRuntime.AppDomainAppVirtualPath

strAbsoluteUrl = HttpRuntime.AppDomainAppVirtualPath & "/Products/XYZ"

Using VirtualPathUtility.ToAbsolute

strAbsoluteUrl = VirtualPathUtility.ToAbsolute("~/Products/XYZ")

Thanks to Yousef

ASP.NET 4.0: Extra space above Menu in Chrome and Safari using Menu Control

9 Comments

In Visual Studio 2010 when creating a new ASP.NET Web Site or ASP.NET Web Application you get a shell for ASP.NET 4.0 web site with a menu using the ASP.NET 4.0 Menu Control. However in Google Chrome and Safari browsers the menu will show with some extra space above it. It took plenty of googling to find the answer since google is filled with solutions for Chrome problems in ASP.NET 2.0.
Finally – the solution for .NET Framework 4.0:

Add these lines to the Site.css file (in the Styles folder of your VS 2010 project)

/* Fix for extra space above menu in Chrome and Safari */
img[alt='Skip Navigation Links'] {
    display: none;
}

An alternative is to add SkipLinkText=”" to each menu item (have not tested this)

Thanks to MattyF for the solution

Get URL without QueryString in .NET

No Comments

To get the current Url without the query in VB.NET

Request.Url.AbsoluteUri.Split("?")(0)

Split text in two columns in VB.NET

1 Comment

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

Parameters:
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:

        Dim strColumns As String() = SplitIntoColumns(strText, 2, "<h2>")
        strText = "<table><tr><td>" & strColumns(0) & "</td><td>" & strColumns(1) & "</td></tr></table>"

Code snippet:

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]

Split text into multiple columns in PHP

3 Comments

I made a Swedish shopping directory using affiliate links for a site and wanted to split it into two columns.

I wrote the following php function that can be used to split a string in two or more pieces. One parameter is at what character or string you want to split. For example if you want to split at a space to not break up words, or split at a period to not split up sentences, at certain html tags such as <h1> to keep headlines and text in same column etc.

The function returns a string array with columns.

Example how to use:

	$TextString = "some text to split")
	$Columns = SplitIntoColumns ($TextString, 2, "<h1>");
	echo ($Columns[0]);
	echo ($Columns[1]);

Function

function SplitIntoColumns ($InputString, $Columns, $SplitString) {

	// 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-01-25/Max	Version 1
	//

	// Find middle of text
	$ColLength = strlen($InputString)/$Columns;

	// Split into columns
	for($ColCount = 1; $ColCount <= $Columns; $ColCount++) {

		// Find $SplitString, position to cut
		$Pos = strpos($InputString , $SplitString , $LastPos + $ColLength);
		if ($Pos === false) {
			$Pos = strlen($InputString);
		}

		// Cut out column
		$Output[$ColCount - 1] = substr($InputString, $LastPos, $Pos - $LastPos);

		$LastPos = $Pos;
	
	}

	return $Output;

 }

[Edit: VB.NET version: Split text in two columns in VB.NET]

Search for text in multiple files

No Comments

AstroGrep is a great free and open source tool for searching for a text string in multiple files. It is a single exe file, no installation needed. Requires .NET framework.

(I’m not involved in this tool in anyway, just came across it and thought I’d share/keep for future reference)

.NET Client Side Field Validation not working

3 Comments

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!
Example:

routes.Ignore("{resource}.axd/{*pathInfo}")

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:

/WebResource.axd?d=znZdQDlEpA5JQFAVOxKRSaHvdB72R3w2rXWu-FUxJtGWwzycXLR0odYnyM26zZuWuR1yv0u-FYgtZehPCh1HbP-J7H7XaSgJhjJvniiZE7c1&t=634214740702488522
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:

If Not Page.IsValid Then Exit Sub

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)

No Comments

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

No Comments

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 0×80070002

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.

<system.webServer> 
  <modules> 
    <remove name="UrlRoutingModule-4.0" /> 
    <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" /> 
  </modules> 
</system.webServer>

or use this:

	<system.webServer> 
		<modules runAllManagedModulesForAllRequests="true"/>
	</system.webServer>

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.

Older Entries Newer Entries