Pinging Technorati
17 November 2008 Tips
Bubble
Copy and paste the code below into your App_Code folder. To do this  right click App_Code choose Add New Item > Class  choose vb as the language and name the class PingTechnorati or something similar.
Next set the blog URL to your own blog address and the blogName to the information entered into the <title> tag in the <head> section of your blog HTML or  if you're generating the title dynamically Page.Title in the Page_Load event of your default page.
 
Imports Microsoft.VisualBasic
Imports System.Net
Imports System.Xml
Imports system.IO
 
Public Class PingTechnorati
   Public Shared Sub PingSites()
 
    Dim pingURL As String = "http://rpc.technorati.com/rpc/ping"
    Dim blogURL As String = "blogURL"
    Dim blogName As String = "blogName"
   
   Dim technoratiPing As HttpWebRequest = CType   (WebRequest.Create(pingURL), HttpWebRequest)
        technoratiPing.Method = "POST"
        technoratiPing.ContentType = "text/xml"
        Dim streamPingRequest As Stream = CType(technoratiPing.GetRequestStream, Stream)
        Dim xmlPing As XmlTextWriter = New XmlTextWriter(streamPingRequest, System.Text.Encoding.UTF8)
        xmlPing.WriteStartDocument()
        xmlPing.WriteStartElement("methodCall")
        xmlPing.WriteElementString("methodName", "weblogUpdates.ping")
        xmlPing.WriteStartElement("params")
        xmlPing.WriteStartElement("param")
        xmlPing.WriteElementString("value", "blogName")
        xmlPing.WriteEndElement()
        xmlPing.WriteStartElement("param")
        xmlPing.WriteElementString("value", "blogURL")
        xmlPing.WriteEndElement()
        xmlPing.WriteEndElement()
        xmlPing.WriteEndElement()
        xmlPing.Close()
 
  Dim technoratiPingResponse As HttpWebResponse = CType(technoratiPing.GetResponse, HttpWebResponse)
        Dim streamPingResponse As StreamReader = New StreamReader(technoratiPingResponse.GetResponseStream)
        Dim strResult As String = streamPingResponse.ReadToEnd
        streamPingResponse.Close()
        technoratiPingResponse.Close()
      
    End Sub
End Class
 
Next simply call the method in your submit event for blog enteries.
 
Protected Sub btnPost_Click(ByVal sender As Object, ByVal  e As e System.EventArgs) Handles bntPost.Click
 
      PingTechnorati.PingSites()
 
So now every time you post an article to your blog Technorati is automatically pinged.
 
 
Flash in valid xhtml
15 November 2008 Tips
Bubble
Using the <embed> element in your markup will cause validation to fail. Instead use the <object> element.
 
<object
type="application/x-shockwave-flash"
data="movie.swf"
width="425" height="344">
<param name="movie" value="movie.swf" />
</object>
 
 
Url Rewriters
12 November 2008 Tips
Bubble
If like me you decide to use Friendly URLs you will at some point need to download and inplement a URL Rewriter.
 
For example say you have a blog article called Url Rewriter,  passing title as the parameter in the querystring the url would be
 
http://www.yoursite.com/article.aspx?Title= Url%20Rewriter.
 
Converting this 'dirty' url to the more friendly
 
http://www.yoursite.com/article/url-rewriter.aspx
 
will result in problems when trying to locate the article in the database. The title field actually holds Url Rewriter and not url-rewriter and therfore the article will not be found.
 
The open source URL Rewriter is avalilable for download from
 
 
Simply download the source files and follow the online instructions. In all probability you will need to create and register a Custom Transform.
 
To create a custom transform class to transform hyphens back to spaces right click App_Code > Add New Item > Class. Name the class something like HyphenToSpace and choose vb as the language. Copy and paste the code below:
 
Imports Microsoft.VisualBasic
Imports System
Imports System.Web
Imports Intelligencia.UrlRewriter.Utilities

Namespace Intelligencia.UrlRewriter
 
    Public Class HyphenToSpace
        Implements IRewriteTransform
 
        Public Function ApplyTransform(ByVal input As String) As String Implements Intelligencia.UrlRewriter.IRewriteTransform.ApplyTransform  
          
            Return input.Replace("-", " ")
        End Function
 
        Public ReadOnly Property Name() As String Implements Intelligencia.UrlRewriter.IRewriteTransform.Name 
            Get
 
                Return "transform"
 
            End Get
 
        End Property
 
    End Class

End Namespace
 
To register the transform copy and paste the code below to your web.config file:
 
<rewriter>    
<registertransform= "Intelligencia.UrlRewriter.HyphenToSpace,App_Code" />
</rewriter>
 
Then set the rule:
 
<rewrite url="~Article/(.+).aspx" to "~/Article.aspx?Title=${transform($1)}" />
 
Note that the tilde (~) only works with sever controls
Implementing Friendly URLs
11 November 2008 Tips
Bubble
I recently decided to implement Friendly URLs on my site in a bid to follow recent trends. What I wanted was to remove  character spaces denoted by  %20 and replace them with hyphens (-). Using Server.UrlEncode simply changes the character spaces appearing in the web browser address bar to a positive sign (+).
 
Dynamic URL
http://macocz-design.com/Post.aspx?title=Impementing%20Friendly%20URLs
 
Server.UrlEncode method
http://macocz-design.com/Post.aspx?Title=Implementing+Friendly+URLs
 
Friendly URL
http://macocz-design.com/post.aspx?title=implementing-friendly-urls
 
Right click the App_Code folder > Add New Item>Class.vb
Choose appropriate name like FriendlyUrl and the language VB.
Copy and paste the following code:
 
Public Class FriendlyUrl
 
Public Shared Function GenerateUrl(ByVal strTitle As String) As String
 
strTitle = strTitle.Trim()
strTitle = strTitle.Trim("-"c)
strTitle = strTitle.ToLower()
 
Dim chars As Char() = "$%#@!*?;:~`+=()[]{}|\'<>,/^&"".".ToCharArray()
 
strTitle = strTitle.Replace("c#", "C-Sharp")
strTitle = strTitle.Replace("vb.net", "VB-Net")
strTitle = strTitle.Replace("asp.net", "Asp-Net")
strTitle = strTitle.Replace(".", "-")
For i As Integer = 0 To chars.Length - 1
Dim strChar As String = chars.GetValue(i).ToString()
If strTitle.Contains(strChar) Then
strTitle = strTitle.Replace(strChar, String.Empty)
End If
Next
strTitle = strTitle.Replace(" ", "-")
strTitle = strTitle.Trim()
strTitle = strTitle.Trim("-"c)
Return strTitle
 
End Function
 
End Class
 
Call the Function:
 
<%#FriendlyUrl.GenerateUrl(Container.DataItem("Title")) %>
 
Problem Validating An XML Feed
23 October 2008 Tips
Bubble
Using  datetime data type will cause your feed to fail validation. The trick here is to format the date to RFC822 specification by writing a funcion or subroutine.
 
   Private Shared Function GetRfc822DateString _
   (By Val dt As Date) As String
 
   Return String.Format("{0:ddd},  {0:dd} {0:MMM}  _
   {0:yyyy} {0:HH} : {0:mm} : {0:GMT", _    
   dt.ToUniversalTime())
 
Call the function
 
   xtw.WriteElementString("pubDate", GetRfc822_
   DateString(dr("Date").ToString()))
 
Another problem is that XML feeds does not support character spaces in URL's. Fortunately ASP.NET gives us the URLEncode method which converts spaces to plus signs.
 
   xtw.WriteElementString("link", _
   http://www.yoursite.com/article.aspx?Title=" & _
   Server.UrlEncode(dr("Title").ToString()))
 
To get the RSS icon to appear in the browser address bar copy and paste between the head tags of your page or master page. Make changes to the Url and Title to reflect your feed.
 
    <link rel="alternate"title=""
      href=http://www.yoursite.com/rss.aspx
      type="application/rss+xml" />
Sending Mail with ASP 2
27 August 2008 Tips
Bubble
Place three labels and three text boxes on your contact page. Name them lblName, lblEmail, lblMessage, txtName, txtEmail, txtMessage. Make sure that you select multi-line for the txtMessage. Place a button and name it btnSubmit.
 
In your web config file add the following:
 
<system.net>
<mailSettings>
<smtp from =" you @yourdomainname">
<network
            host = "mail.yourdomainname"
            port= "25"
            userName ="username"
            password ="password" />
</smtp>
</mailSettings>
</system.net>
 
In your code behind page contact.aspx.vb add the following under the btnSubmit_Click event:
 
Dim mm As New Net.mail.MailMessage(txtEmail.Text, ToAddrress)
 
mm.Body = txtName.Text + vbNewLine + txtEmail.Text + vbNewLine
+ txtMessage.Text
 
mmIsBodyHtml = False
 
Dim smtp As New Net.Mail.SmtpClient
 
smtp.Send(mm)
 
 
 
Captcha Control
17 June 2008 Tips
Captcha Image
Recently the site has been having problems with the Captcha control. The use of the Captcha for say a contact form greatly eliminates spam by presenting the user with a challenge and response test, the idea being that only humans can pass the test.
 
Unfortunately my Captcha wasn't working too well. Despite the correct code being entered a message was displayed informing the user to try again. It appeared to be a postback problem, which was resolved  by removing some data access code  from the the Page_Load event in the code behind of the Master page and placing it in the Page_PreRender event in the code behind.
 
This seems to have done the trick, my Captcha control is finally working!
Browser Viewport
12 June 2008 Tips
Bubble Image
Someone recently pointed a problem with my site. It appeared that if the clients browser viewport was less than 880px then the horizontal scrollbar that appears doesn't allow the content on the far left of the site to be brought into view. This problem seemed only to effect IE.
 
The solution:
 
Change
 
           #wrapper{margin-left:-500px;}
 
To
 
           #wrapper{margin:0 auto;}
Aggregate Count Function
05 June 2008 Tips
Bubble Image
I needed to show a count of entries against months in my archive list. My database table uses the DateTime function for the date field. This lists entries against the day, month year and time, for example 04/05/2008 03:34:45.

My previous blog entry for March showed that using

SELECT DISTINCT DateName(Month,Date) AS theMonth,
DatePart(Year,Date) AS theYear,
Month(Date) AS theMonth
FROM myTable
ORDER BY DatePart(yyyy,Date) DESC,
month(Date) DESC

listed the months in chronological order, however  I found it extremely difficult to incorporate a count using a derivedTable and still maintain a logical order for the months.

After hours of effort and research the following solution was arrived at.

SELECT dateAdd(mm,DateDiff(mm,0,date),0) AS date,
COUNT(date) From myTable
GROUP BY DateAdd(mm,DateDiff(mm,0,date),0)
ORDER BY date DESC

To format the date and only show the month and year I used

<%#Eval(“date”,”{0:y}%> (<%#Eval(“Column1”)%>
Selecting Last 100 records
26 May 2008 Tips
Bubble Image
To select just the last 100 entries from your table use

SELECT TOP 100*
The DateName function
02 March 2008 Tips
Bubble image
I wanted to include an archive list, so that a user could click a listed month and all entries for that particular month would be displayed via a Data List control. I discovered that using the DateName function I could return the specific names of the months from the DateTime value in my database table.

SELECT DISTINCT DateName(Month,Date) AS theMonth,
DatePart(Year,Date) AS theYear
FROM myTable ORDER BY theYear

This gave rise to another problem whereby the listed months were in alphabetical order and not logical order.
  • February
  • March
  • January
  • December
  • November
  • October

Rewriting the query as

SELECT DISTINCT DateName(Month,Date) AS theMonth,
DatePart(Year,Date) AS theYear,
Month(Date) AS theMonth
FROM myTable
ORDER BY DatePart(yyyy,Date) DESC,
month(Date) DESC

Gave the required result
  • March
  • February
  • January
  • December
  • November
  • October
Count aggregate
27 February 2008 Tips
Bubble image
I wanted to show the number of listings in a particular category. After some research and reading Scott Mitchell's book ASP.NET Data Web Controls, I came up with the following solution.

Code behind page under the Page_Load event

Dim cnn As New SqlConnection
cnn.ConnectionString = _
"Data Source = yourDataSource;" & _
"Initial Catalog = yourDatabase;" & _
"Integrated Security = SSPI"

Dim da As SqlDataAdapter
da = New SqlDataadapter(

SELECT category, COUNT(*)
FROM myTable
GROUP BY Category ", cnn
)

Dim ds As New DataSet
da.Fill(ds,"Category")

dlCategory.DataSource = ds
DataBind()

Then on the html page

<asp:DataList ID="dlCategory" runat="server">

<itemTemplate>
<a href ='Categories.aspx?cat=<%#  Eval("catergory")  %>'>
<%# Eval("category") %>
<%# Eval("categoryCount") %></a>
</itemTemplate>

</asp:DataList>

And so now if you look under the categories column on the right a count is displayed against each of my categories. All that remains for me to do now is an Archive and the Search
Uneven columns
22 February 2008 Tips
Bubble image
One of the problems with floating containers is that they will generally only extend to the depth of their content. Imagine therefore that you have two div's side by side within a containing div it can be very hard to create the illusion of columns using background colours alone.

The solution is to use a background image that gives the illusion of columns for the containing div. This image can be added to the containing div as a background image and repeated down the y axis.

The floating div's then sit over the top of this repeated image, and the colours will extend to the bottom of the page, no matter which column is longer.
Changing title tag dynamically
17 February 2008 Tips
Bubble image
I needed to change the title tag on the fly. The idea being that when the user clicks onto a date on the calendar control for example to pull all the posts relevant for that date, the page title above the address bar in the browser would reflect this and would help in search engine optimization. Search engines rank pages with relevant titles higher than those without relevant titles. By giving this information you are helping the search engine understand your Web page through your page title. Search engines will quickly overlook a Web page with an unrelated page title. The solution for ASP.NET 2.0 is to use Page.Title under the Page_Load event in the code behind.

Page.Title = "post " + Request.QueryString("EventDate")

http://www.velocityreviews.com/forums
Message could not be sent
14 February 2008 Tips
Bubble image

'The message could not be sent to the SMTP server.
The transport error code was 0x80040217.
The server response was not available.'


This means that username and password are incorrect.

 Mail.To = "YourName@DomainName.com"
 Mail.From = txtName.Text

 Mail.BodyFormat = MailFormat.Text
 Mail.Priority = MailPriority.Normal
 Mail.Subject = "Your Reference"

Mail.Body = "From: " + txtName.Text + vbNewLine +
"Email: " + txtEmail.Text + vbNewLine +
"Subject: " + txtSubject.Text + vbNewLine +
"Message: " + txtMessage.Text

Mail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",
"1")

Mail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusername", "YourName@DomainName.com")

Mail.Fields.Add(
"http://schemas.microsoft.com/cdo/configuration/sendpassword",
"Password")

 SmtpMail.SmtpServer = "mail.DomainName.com"
 SmtpMail.Send(Mail)

Note that System.Web.Mail is obsolete and
the alternative is System.Net.Mail

Convert System.Drawing.Color to RGB
04 February 2008 Tips
Bubble image
Use the Color.FromName method:
Drawing.Color.FromName("#f2f2f2")

http://weblogs.asp.net
The constraint cannot be enabled
02 February 2008 Tips
Bubble image
'The constraint cannot be enabled as not all the values have
corresponding parent values.'


Set the constraint in the DataRelation class to false.

ds.Relations.Add("ParentChild", _
ds.Tables("Parent").Columns ("Name"), _
dsTables("Child").Columns("Name"), False)
Must declare scalar variable
02 February 2008 Tips
Bubble image
To get the value of a QueryString field for code behind use:
    Request.QueryString("Name")

    da.SelectCommand.parameters.Add(parameter, _
    SqlDbType.DataType).value = _
    Request.QueryString("name")