Entries Tagged 'ASP.NET' ↓
May 31st, 2008 — ASP.NET
Finally Microsoft released the long anticipated IIS7 URL Rewrite Module. It really was about time! The key features look promising:
- Rules-based URL rewriting engine
- Regular expression pattern matching
- Wildcard pattern matching
- Global and distributed rewrite rules
- Access to server variables and http headers
- Various rule actions
- Rewrite maps
- UI for managing rewrite rules
- GUI tool for importing of mod_rewrite rules
Quite comfortable that they even integrated a GUI Tool for importing Apache2 mod_rewrite rules. I’m not sure yet how strong URL Routing is, which first came up with the MVC CTPs and is now available for ASP.NET, too - I didn’t test it yet. For now I will give the new IIS7 Module a first shot as my current projects use URL Rewriting already and I think it’ll be easier to port my existing third-party URL Rewrite Engine to the new IIS7 one. I plan on not touching URL Routing until it reached the final status.
Get it here: IIS7 - using url rewrite module.
February 2nd, 2008 — ASP.NET
Just in case you never heard about SubSonic yet, it’s a kickass DAL and I use it for a lot of my projects. Currently it supports SQL Server 2000 or 2005, MySQL and or Oracle (with SQLLite, SQLCE). They also offer a nice Starter-Kit which comes pre-wired with SubSonic, Membership, AJAX, Useful Utilities, and the FCK Editor. It’s based on the .NET 2.0 Framework but it’s automatically being converted by Visual Studio 2008 in case you use v3.5 already (which I strongly recommend).

With v2.1 they shipped a new Query Tool which is now fully capable of creating more complex queries, for example:
Northwind.CustomerCollection customersByCategory = new Select()
.From<Northwind.Customer>()
.InnerJoin<Northwind.Order>()
.InnerJoin(Northwind.OrderDetail.OrderIDColumn, Northwind.Order.OrderIDColumn)
.InnerJoin(Northwind.Product.ProductIDColumn, Northwind.OrderDetail.ProductIDColumn)
.Where(“CategoryIDâ€).IsEqualTo(5)
.ExecuteAsCollection<Northwind.CustomerCollection>();
Read more about the new version here. Check it out, I don’t want to miss it anymore ;).
January 5th, 2008 — ASP.NET
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 ;).
December 22nd, 2007 — ASP.NET
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="<a href="{1}">{0}</a>"
alternativeReplacement="<a href="{0}">{0}</a>" />
<tag name="mail" replacement="<a href="mailto:{1}">{0}</a>" />
<tag name="email" replacement="<a href="mailto:{1}">{0}</a>" />
<tag name="b" replacement="<span style="font-weight:bold;">{0}</span>" />
<tag name="i" replacement="<span style="font-style:italic;">{0}</span>" />
<tag name="u" replacement="<span style="text-decoration:underline;">{0}</span>" />
<tag name="quote" replacement="<table border="0" cellpadding="8" cellspacing="0"><tbody><tr><td class="alt2" style="border: 1px inset ;">{0}</td></tr></tbody></table>" />
</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 Codeparser.NET homepage for more.
December 5th, 2007 — ASP.NET
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.

Download: Graffiti Beta 1.

December 1st, 2007 — ASP.NET
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.
November 23rd, 2007 — ASP.NET
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:
- Open up your DBML File.
- 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 .. 
November 23rd, 2007 — ASP.NET
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.
November 23rd, 2007 — ASP.NET
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.
November 19th, 2007 — ASP.NET, Development
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.
November 10th, 2007 — ASP.NET
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 > 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.
October 25th, 2007 — ASP.NET
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!
October 20th, 2007 — ASP.NET
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..
September 19th, 2007 — ASP.NET
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

August 6th, 2007 — ASP.NET
A quick example on how to use the new GroupTemplate which is being featured by the new ListView Control of the .NET Framework v3.5.
The ListView templates follow a strong hierarchy:
LayoutTemplate [root item, container for ListView rendering]
- GroupTemplate [Optional, required for tiled layout]
- >> ItemTemplate
- >> AlternatingItemTemplate
- >> EditItemTemplate
- >> InsertItemTemplate
- >> ItemSeparatorTemplate
- >> EmptyItemTemplate
- >> SelectedItemTemplate
- GroupSeparatorTemplate
and finally the EmptyDataTemplate (optional), which is only being displayed when there are no results for the DataSource. To be able to use the GroupTemplate you have to set a groupContainer and put the layoutTemplate inside the GroupTemplate Tag.
<asp:LinqDataSource ID=”LinqDataSource1″ runat=”server”
ContextTypeName=”DataClassesDataContext” TableName=”pics”>
</asp:LinqDataSource><asp:ListView ID=”ListView1″ runat=”server” DataKeyNames=”picID” DataSourceID=”LinqDataSource1″ ItemContainerID=”layoutTemplate” GroupItemCount=”2″>
<Layouttemplate>
<table id=”groupContainer” runat=”server”></table>
</Layouttemplate>
<GroupTemplate>
<tr id=”layoutTemplate” runat=”server”>
</tr>
</GroupTemplate>
<ItemTemplate>
<td>
<a href=”<%# Eval(”picFileName”) %>”> a <%# Eval(”aspnet_User.UserName”) %></a>
</td>
</ItemTemplate>
</asp:ListView>
By using the GroupTemplate you can produce tiled layouts which are e.g. needed for Image Galleries. However, as stated earlier you can only set a GroupItemCount at the moment, it would be great if we could get more options here for the final Release.
Side note:
The GroupSeparatorTemplate is displayed at the end of each GroupTemplate except the last one. The ItemSeparatorTemplate is displayed at the end of each ItemTemplate except the last one. The EmptyItemTemplate is displayed for filling up dummy columns when e.g. building a xhtml layout.