WebForm_InitCallback is not defined

This error eventually pops up, if you use the AjaxControlToolkit Rating Control. The Rating Control just doesn’t work, nothing happens when you click on it or hover over it. You find a couple of threads about it in Google but none of them helped me. I completly rewrote my web.config, removed all HttpModules, checked my Rewrite Logic for possible .axd lockups and nothing helped. That’s the exact error:

WebForm_InitCallback is not defined
Vote.aspx
Line 226

Line 226 says WebForm_InitCallback();Sys.Application.initialize();.

After wasting about 4 hours I checked out the CSS definitions which are being used by the Rating Control:

 StarCssClass="ratingStar"
                    WaitingStarCssClass="waitRatingStar"
                    FilledStarCssClass="filledRatingStar"
                    EmptyStarCssClass="emptyRatingStar"  

I checked the path to the images set in those 3 CSS definitions and noticed that waitRatingStar was pointing to an invalid path – a non existing image. After fixing that path the error was gone!

Like so many times a trivial fault can cost you lots of time – and the error which is being thrown by this fault unfortunately really doesn’t point you into the direction of a missing image. Hopefully this saves someone else searching time on this ;).

Codeparser – implenting custom BB Codes the easy way

*** NOTE – The author discontinued this tool ***

BBCodes are well known through forum communities and is the abbreviation for Bulletin Board Code. The tags are usually indicated by rectangular brackets surrounding a keyword, the use of it is to make text formatting possible without having to write HTML. It’s safer, comfortable and easy to implent.

Every tag is being translated into markup language that web browsers understand, this is where Codeparser.NET joins the game:

codeparser.net is a free .NET based and highly configurable parser for BBCode. Since it is a component, it can be integrated with Windows as well as with web applications and web services.

It’s pretty easy to implent and you will find some pre-made examples for parsing Smilies, Lists, Links, Code and much more. Alternative replacements, syntax highlighting, invalid tag configuration, expression replacements, things you don’t want to miss when dealing with BBCodes. I recently used it for two ASP.NET Web Applications, it’s pretty straight forward. Define some rules, save them as parser.xml, create the parser object and just starting parsing:

parser.Parse(txt);

If you use the dll for communities there’s just one thing to look after, people forget closing specific tags sometimes which will lead to an exception at the moment. One of the developer, Golo Roden, already told me that they are working on a better solution for this in a future version, for now just use a try/catch block if you deal with user input and do not validate the proper tag closings yourself:

    protected string ParseText(string txt)
    {
        try
        {
            return parser.Parse(txt);
        }
        catch
        {
            return txt;
        }
    }

Here is a example of a parser.xml which is parsing Links and text formattings:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <parser>
    <throwExceptionOnInvalidTag value="False" />
  </parser>
  <tags>
    <tag name="url" replacement="&lt;a href=&quot;{1}&quot;&gt;{0}&lt;/a&gt;"
     alternativeReplacement="&lt;a href=&quot;{0}&quot;&gt;{0}&lt;/a&gt;" />
    <tag name="mail" replacement="&lt;a href=&quot;mailto:{1}&quot;&gt;{0}&lt;/a&gt;" />
    <tag name="email" replacement="&lt;a href=&quot;mailto:{1}&quot;&gt;{0}&lt;/a&gt;" />
    <tag name="b" replacement="&lt;span style=&quot;font-weight:bold;&quot;&gt;{0}&lt;/span&gt;" />
    <tag name="i" replacement="&lt;span style=&quot;font-style:italic;&quot;&gt;{0}&lt;/span&gt;" />
    <tag name="u" replacement="&lt;span style=&quot;text-decoration:underline;&quot;&gt;{0}&lt;/span&gt;" />
    <tag name="quote" replacement="&lt;table border=&quot;0&quot; cellpadding=&quot;8&quot; cellspacing=&quot;0&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class=&quot;alt2&quot; style=&quot;border: 1px inset ;&quot;&gt;{0}&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;" />
  </tags>
</configuration>

I didn’t face any other problems after running it for about one month now, good job and I’m happy to recommend it to you guys! Head over to the -removed- homepage for more.

Grafiti CMS – a Major ASP.NET Attack on WordPress

PLEASE NOTE: This article is from 2007. Unfortunately Telligent didn’t manage it to turn this into an ASP.NET WordPress Killer.

Just released: Telligent (Creators of CommunityServer) Graffiti CMS – Beta 1, and believe me or not but I was able to set it up in about 20 seconds! This even beats the famous WordPress 5 Minutes installation. I installed it using an Access Database which is included containing some sample data. For small sites this works great, for bigger sites you want to use the SQL Server as datastorage.

The interface is pretty simple and fast, nevertheless, you probably notice some similarities to WordPress ;). It can be used for blogging, smaller content websites or even bigger projects are imaginable.

This could become the new ASP.NET WordPress.. or even more! With the power of ASP.NET it has great potential. It even has SEO friendly URLs included, out of the box of course! The functionality for tagging, categories, plugins, themes and all the stuff you need for starting through are also included.

As far as I know there will be two versions, one free version which runs on Access and one commercial version which runs on SQL Server.

Check it out, it’s really worth a try! I included some screenshots at the end of this post.

FYI: This CMS has been killed.

Grafiti Home Grafiti Site Options Grafiti Themes Grafiti Write Grafiti Write Options Grafiti Write Settings

ASP.NET Deployment – new WDP for VS2008 released

Microsoft just released the Customer Technology Preview (CTP) of Web Deployment Projects for Visual Studio 2008. It contains all the features that VS 2005 WDP release has and in addition has few other enhancements.

For example it only deletes the existing web now if the build succeeds, this will pretend breaking running IIS Applications if you used to deploy directly into the specific IIS Application folder. Additionally you can automatically create virtual Folders in IIS or replace existing ones – this works for IIS6 and IIS7.

Also nice to know is, that aspnet_merge is being automatically installed now when you install Visual Studio 2008. It’s placed in “%Program Files%\Microsoft SDKs\Windows\v6.0A\bin and of course WDP depends on it if you use the merge feature.

Get the December CTP 2007 here: VS 2008 WDP December CTP 2007.

There is no Unicode by order mark. Cannot switch to Unicode.

You were using LINQ and Visual Studio 2008 Beta 2? Switched to Visual Studio 2008 RTM and out of nowhere this error pops up? Lucky you, this one will be pretty easy to fix:

  1. Open up your DBML File.
  2. In the first line, switch the encoding from utf-16 to utf-8.

That’s it once again! I hope you enjoyed another RTM quick fix .. 😉

A group placeholder must be specified on ListView

Now this is even more tricky than An item placeholder must be specified on ListView. For Visual Studio 2008 RTM Microsoft changed the whole GroupTemplate Design structure.

This MSDN Article is covering it pretty good, here’s what you have to do if you switched from Visual Studio 2008 Beta 2 to Visual Studio 2008 RTM:

1) Remove the ItemPlaceholderID=”xx” from your ListView, it should look like that (e.g.):

<asp:ListView ID=”ListView1″ runat=”server” DataKeyNames=”picID” DataSourceID=”LinqDataSource1″ GroupItemCount=”4″>

2) Have a LayoutTemplate organized like that:

<Layouttemplate>
<table align=”center” border=”0″ cellpadding=”15″ cellspacing=”15″ id=”layoutTemplate” runat=”server”>
<tr runat=”server” id=”groupPlaceholder” />
</table>
</Layouttemplate>

3) And a GroupTemplate in that kind of style:

<GroupTemplate>
<tr runat=”server” id=”ProductsRow”>
<td runat=”server” id=”itemPlaceholder” />
</tr>
</GroupTemplate>

That’s all. If you try to set the new GroupPlaceHolderID in the ListView Tag the GroupTemplates won’t be formated correctly, I didn’t figure out why yet. This solution however is based on the MSDN Article and works.

An item placeholder must be specified on ListView – VS2008 RTM

This errors pops up as soon as you switched from Visual Studio 2008 Beta 2 to Visual Studio 2008 RTM. Here’s the exact error:

System.InvalidOperationException: An item placeholder must be specified on ListView ‘ListView1’. Specify an item placeholder by setting a control’s ID property to “itemPlaceholder”. The item placeholder control must also specify runat=”server”.

To fix this, replace every itemContainer occurrences with itemPlaceholder, recompile and it should work. Also note that the control which is targeted as itemPlaceholder does not render CSS or other attributes anymore, you have to set them on surrounding HTML tags now like a div or ul.

Visual Studio 2008 Final released!

There we go, Visual Studio 2008 Final has just been released, including the .NET Framework 3.5 Final Version.

Here are some instructions for the Install-Process from Scott Guthrie, especially if you were using VS2008 Beta 2:

People often ask me for suggestions on how best to upgrade from previous betas of Visual Studio 2008. In general I’d recommend uninstalling the Beta2 bits explicitly. As part of this you should uninstall Visual Studio 2008 Beta2, .NET Framework Beta2, as well as the Visual Studio Web Authoring Component (these are all separate installs and need to be uninstalled separately). I then usually recommend rebooting the machine after uninstalling just to make sure everything is clean before you kick off the new install. You can then install the final release of VS 2008 and .NET 3.5 on the machine.

Once installed, I usually recommend explicitly running the Tools->Import and Export Settings menu option, choosing the “Reset Settings” option, and then re-pick your preferred profile. This helps ensure that older settings from the Beta2 release are no longer around (and sometimes seems to help with performance).

Note that VS 2008 runs side-by-side with VS 2005 – so it is totally fine to have both on the same machine (you will not have any problems with them on the same box).

I really hope the final Release will fix some annoying bugs I was fighting with lately, although I expect this to be a much smoother release than Visual Studio 2005.

Quick Note to Silverlight Developers: You should wait until Microsoft released the updated Silverlight Tools for VS 2008, it’s expected within the next two weeks.

Futhermore Microsoft released a cool Training-Kit for the .NET Framework v3.5, grab it here. The Visual Studio 2008 and .NET Framework 3.5 Training Kit includes presentations, hands-on labs, and demos. This content is designed to help you learn how to utilize the Visual Studio 2008 features and a variety of framework technologies including: LINQ, C# 3.0, Visual Basic 9, WCF, WF, WPF, ASP.NET AJAX, VSTO, CardSpace, SilverLight, Mobile and Application Lifecycle Management.

BlackBerry Desktop Manager and Vista

I got my new BlackBerry Curve 8310 today and honestly already expected to experience problems when trying to run it on Windows Vista.

So here’s what you have to do to properly install the BlackBerry Desktop Manager 4.3 and your BlackBerry Device:

  1. Install the BlackBerry Desktop Manager 4.3, be sure to download the latest Version here. I’m using 4.3.0.15 (Auguest 2007)
  2. After the installation don’t reboot your PC and do not start the Desktop Manager yet
  3. Plug your BlackBerry in by using the supplied USB Cable
  4. Now the important part: Vista will tell you it found new hardware but no proper driver for it. Choose to manually search for a driver, type in C:\ and hit enter.
  5. This will occur several times, just proceed with C:\ and enter.
  6. After about 5 times you should be done, now you should be able to start the Desktop Manager and use your BlackBerry.

If you don’t do it that way, the Desktop Manager will detect your BlackBerry phone but it won’t be able to work with it, the connection will always fail when you try to use the Synchronizing Service or the Backup/Restore Manager.

Furthermore you should update your BlackBerry Device Software, for T-Mobile Germany go here to download the latest Firmware: BlackBerry Device Software Downloads. Thanks to Quintt for the comment!

Disable any LastActivityDate Updates for ASP.NET Membership

I recently built an ASP.NET Application which makes intensive use of the build in ASP.NET Membership Class. I use it to store the number of new messages for a particular user and stuff like that as it’s very comfortable to set those values:

System.Web.Profile.ProfileBase pB = System.Web.Profile.ProfileBase.Create(UserName);     pB["FriendApproval"] = ApprovalCount.ToString();
pB.Save();

I use the LastActivityDate Value to show members who have been around recently. The strange thing had been that every now and then members popped up on the top who actually haven’t been online at all.

That happens because the LastActivityDate Value is updated on every Profile Info retrieval and every Profile Info Update by default. To disable this behavior you have to modify two Stored Procedures:

aspnet_Profile_GetProperties
Remove this piece of code:

IF (@@ROWCOUNT &gt; 0)
BEGIN
UPDATE dbo.aspnet_Users
SET LastActivityDate=@CurrentTimeUtc
WHERE UserId = @UserId
END

aspnet_Profile_SetProperties
Remove or comment out this piece of code:

UPDATE dbo.aspnet_Users
SET    LastActivityDate=@CurrentTimeUtc
WHERE  UserId = @UserId 

That’s it! Of course you have to take care of updating the LastActivityDate yourself now, I recommend adding a User Control to the MasterPage, put the Stored Procedure for Updating LastActivityDate (write one) in its codebehind and cache the control for about 5 Minutes, your server will thank you later.

Follow Up: Enable ValidateRequest in ASP.NET and still read HTML

Last week I read a great post on Mad’s Blog about Re-Enable Request Validation in ASP.NET. He built a javascript function which automatically HTMLEncodes the Text on Clientside when the User hits Submit by using Tagmapping and automatically HTMLDecodes it on server-side.

By using his technique you can still benefit of the ValidateRequest Security while allowing HTML in your forms.

Now to the Follow Up: If you use ASP:Panels on your webform and you hide specific Panels which do include Textboxes to show them just on specific events you run into a Javascript Error saying tb is null. That’s because the HTML Output which is dynamically created doesn’t contain the textbox when the Panel is hidden, although ASP.NET is executing the JS Statement for those hidden textboxes anyway and that’s when the Error pops up. You can fix that pretty easy by checking if tb is null, here’s Mad’s Code containing that little fix:

public class SafeTextBox : System.Web.UI.WebControls.TextBox
{
protected override void OnLoad(System.EventArgs e)
{
base.OnLoad(e);
if (!Page.ClientScript.IsClientScriptBlockRegistered(Page.GetType(), "TextBoxEncode"))
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("function TextBoxEncode(id)");
sb.Append("{");
sb.Append("var tb = document.getElementById(id);");
sb.Append("if (tb != null){"); //fix
sb.Append("tb.value = tb.value.replace(new RegExp('<', 'g'), '<');");
sb.Append("tb.value = tb.value.replace(new RegExp('>', 'g'), '>');");
sb.Append("}");
sb.Append("}");
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "TextBoxEncode", sb.ToString(), true);
}

// Adds the function call after the form validation is called.
if (!Page.IsPostBack)
Page.Form.Attributes["onsubmit"] += "TextBoxEncode('" + ClientID + "');";
}

public override string Text
{
get { return base.Text; }
set
{
if (!string.IsNullOrEmpty(value))
base.Text = value.Replace("<", "<").Replace(">", ">");
else
base.Text = value;
}
}
}

Read Mad’s full article on how to implent this technique and be sure to turn ValidateRequest back on!

Validate your Redirects!

I usually keep an eye on what my web applications are doing every now and then. Recently I noticed some really strange redirects being fired from one of my older projects. Like redirects to specific IP adresses or curious subdomains, rather traditional addresses for e.g. phishing attacks.

After checking my redirect logic the problem was immediately clear, I didn’t validate my redirects in any way, lazy me. The following code is offers actually a great way for people to use your brand/domain for redirects to spam sites or even phishing sites:

string RedirctURL = Request.QueryString["r"].ToString();
Response.Redirect(RedirectURL);

Now someone could easily drop his URL into the QueryString: http://www.yourdomain.com/somesite.aspx?r=http://www.the-injected-url.com. So what you should do is, check if the input really belongs to your site or is something you really want to redirect to.

If you only redirect to internal sites you can just check the string for a double slash “//”, if it occurs, deny the redirect. If you also redirect to external sites you have to use a database and save all permitted redirect URLs in there.

Also, don’t be tricked by using System.URI.AbsolutePath, because Firefox and IE will transform an invalid URL to a valid URL:

// Returns "//www.url-to-injected-site.com/badstuff.aspx" which will work in FireFox and IE!
Uri link1 = new Uri("http://www.url-to-injected-site.com//www.url-to-injected-site.com/badstuff.aspx");

As you probably know you should always validate external inputs, don’t be lazy or you will be sorry later..

Tips for avoiding Spam Filters with System.Net.Mail

I recently noticed that automatic mails sent by one of my online shops were flagged as spam when using GMX, GMail or generally mail services which are using SpamAssassin to filter out spam.

Sending out plain text-mails is old and rusty, if you want to deliver pretty mails to your customers you have to use HTML, unfortunately there is no way around it, but how to make sure that those pretty HTML mails actually reach the customer? Spam filters like SpamAssassin treat HTML Mails as potentially dangerous, so you have to use HTML very carefully.

If you do use HTML Mails you have to create two kinds of Bodys, one HTML Mail Body and one PlainText Mail Body. I show you how to do this in C# / ASP.NET 2.0 by using the built-in System.Net.Mail Class after some general advices.

Here are some recommendations for a automatic HTML mails which are being sent out a hundred times per day:

  • Don’t forget to add <html><body>Your HTML Text/Code</body></html> to your HTML-Text-String
  • Try to stick with 1-3 Images in total. For example your Logo, a header background and a photo of the particular product.
  • Use HTML Tags with care. Set a good looking font like Arial, create listings, link tags, bold and italic texts and restrict yourself to create a well formed/layouted text, which is most important. Don’t even think about implenting an embed or object tag for including flash videos or anything like that.

SpamAssassin checks a lot of factors and is using a point-system for filtering out spam, here is a little snippet:

1.723 MSGID_FROM_MTA_ID
0.001 HTML_MESSAGE
5.000 BAYES_99
0.177 MIME_HTML_ONLY
1.047 HTML_IMAGE_ONLY_16
0.629 FORGED_OUTLOOK_HTML

The heaviest impact is BAYES_99, if your text sounds spammy, you are spam flagged. If you e.g. sell Viagra you shouldn’t list the product name in your confirmation mail ;-). Another example is MIME_HTML_ONLY, this hits your mail if you only supply HTML Text, without a seperated PlainText. I won’t explain every function in detail here, if you follow this HowTo you likely won’t run into any problems.

Let’s have a look on how to properly send a HTML Mail with the System.Net.Mail Class, in this case it is sending the Mail via Google Apps / GMail:

public void ExecuteHtmlSendMail(string FromAddress, string ToAddress, string BodyText, string Subject)
{
MailMessage mailMsg = new MailMessage();

mailMsg.From = new MailAddress(FromAddress);
mailMsg.To.Add(new MailAddress(ToAddress));
mailMsg.Subject = Subject;
mailMsg.BodyEncoding = System.Text.Encoding.GetEncoding(“utf-8″);

System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString
(System.Text.RegularExpressions.Regex.Replace(BodyText, @”<(.|\n)*?>”, string.Empty), null, “text/plain”);
System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(BodyText, null, “text/html”);

mailMsg.AlternateViews.Add(plainView);
mailMsg.AlternateViews.Add(htmlView);

// Smtp configuration
SmtpClient smtp = new SmtpClient();
smtp.Host = “smtp.gmail.com”;

smtp.Credentials = new System.Net.NetworkCredential(“username”, “password”);
smtp.EnableSsl = true;

smtp.Send(mailMsg);
}

What’s important here: Setting the correct Encoding, in my case utf-8. Create a plainView and htmlView of the mail message. For the plainView I used a simple Regex statement for stripping out the HTML Tags. Add the plainView and htmlView to the AlternateViews Class of the Mail Message and finally send the mail, in my case via SSL, if you don’t know whether you have an Mailserver with SSL capabilities just ask your provider.

Using this construct you send out your HTML Mails as HTML Mail and Plaintext Mail and SpamAssassin is going to like you for that.

I use gmx.net for testing my mails as they are using a pretty well configured SpamAssassin and you can easily see the spam-flags by checking out the Header of the mail (also possible with GMail and hopefully every other mail application out there). An example of this:

X-GMX-Antispam: 5 (HTML_IMAGE_ONLY_12,HTML_MESSAGE,HTML_MIME_NO_HTML_TAG,MIME_HTML_ONLY)
X-GMX-UID: UNbaLmk4ZDI4zQ9QSmY2gY1xemhmY8Gs

A Spam-Score of 5 (=treated as Spam) and it’s telling me that I didn’t supply a PlainText Version of the Mail, after including that one all errors were gone.

Hope this saves some headaches 😉

kick it on DotNetKicks.com

Silverlight 1.0 released

ScottGu just announced the Silverlight 1.0 Release on his blog for Windows and MAC. Silverlight 1.0 is focused on enabling rich media scenarios in a browser. Head over to this blog for more info on this and to see some deployed Silverlight 1.0 examples.

I already jumped on the Silverlight 1.1 train as it features full .NET Language support. The good news are that the MS Silverlight team can completly focus themselves on the v1.1 Release now.

vBulletin still the best ASP.NET Forum Software

I’m building a pretty big ASP.NET Application at the moment for the gaming sector which needs to have a forum for discussions about site related stuff, games and all kind of topics.

I would really like to use an ASP.NET Forum, but after one week of crawling through every available ASP.NET Forum out there I came to the conclusion that vBulletin (PHP) still offers the best features you need for a successful community in that kind of genre.

Yet Another Forum
Version: 1.9.0
Date: Tuesday, October 10, 2006

Last update in the year 2006, I won’t need to comment this any further. Honorable try to build a free .NET Forum but unfortunately it seems like people are not motivated to continue it anymore.

CommunityServer 2007

Actually the best currently available forum, although it’s a complete Community with Blogs, Gallery and Downloads. I prefered the splitted versions some years ago, now it’s one big package. What I miss here is: Support. The public forums are missing essential support by experienced CommunityServer Users and Developers. Another point is the missing SEO capabilities. Since CS 2.1 and CS 2007 they became much better regarding SearchEngineFriendly URLs but there are still big drawbacks. The Forum doesn’t feature the words of the title in the URL and duplicate content is being generated due to multiple URLs pointing to the same page – an example would be the profile link:

When viewing a forum the Link to the Profile looks like that:
http://communityserver.org/user/Profile.aspx?UserID=XXX

Inside a thread it looks like that:
http://communityserver.org/members/UserName.aspx

I’m running the Trial Edition of CommunityServer at the moment and was almost ready to buy the full version, but after starting more than 3 threads in their forum which all ended up with no reply I changed my mind. Maybe you got more luck if you buy Gold Support, but for me the first impression matters. If I post a question over at the vBulletin Forums I usually got an answer in less than 1 hour without any kind of Gold Support. And instead of about 2000$ for CommunityServer I just paid around 140$ for a vBulletin licence. CommunityServer is rich on features but vBulletin has such a big modding Community and therefore ends up with even more features. For SEO vBSEO is all you ever need.

Even worse is that there are almost no converters available for CommunityServer, if you’d like to switch FROM vBulletin to CommunityServer start looking for a CommunityServer AND vBulletin specialist.

All other ASP.NET Forums besides CommunityServer and YAF are not even worth mentioning. I would recommend CS 2007 as decent Blogging Solution, but once again you can just buy the whole package here which leads to an overpriced WebBlog-System if you ask me.

I (have to) stick with vBulletin

It’s sad, but true. I keep on building all kind of bridges between my ASP.NET Application and the PHP vBulletin and I eventually dig into the vBulletin MySQL database directly.

Check the comments on this post for more info on this.

PS: Of course vBulletin is not an ASP.NET Forum as written in the title, but I still use it as Forum for all my ASP.NET Applications and that’s why I’ve chosen such an evil title.