Archive

Archive for the ‘Development’ Category

How to: Allow hyphens in URL’s using ASP.NET MVC 2

February 6th, 2010

If you wan’t to allow hyphens in your URL’s you will need to change the way the routing works in your Global.asax file.

First create a new class which extends the MvcRouteHandler and place this in the Global.asax file after the main MvcApplication class.

C#:

public class HyphenatedRouteHandler : MvcRouteHandler{
	protected override IHttpHandler  GetHttpHandler(RequestContext requestContext)
	{
		requestContext.RouteData.Values["controller"] = requestContext.RouteData.Values["controller"].ToString().Replace("-", "_");
		requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"].ToString().Replace("-", "_");
		return base.GetHttpHandler(requestContext);
	}
}

VB:

Public Class HyphenatedRouteHandler
    Inherits MvcRouteHandler
 
    Protected Overrides Function GetHttpHandler(ByVal requestContext As System.Web.Routing.RequestContext) As System.Web.IHttpHandler
        requestContext.RouteData.Values("controller") = requestContext.RouteData.Values("controller").ToString.Replace("-", "_")
        requestContext.RouteData.Values("action") = requestContext.RouteData.Values("action").ToString.Replace("-", "_")
        Return MyBase.GetHttpHandler(requestContext)
    End Function
 
End Class

Then you need to replace the routes.MapRoute with an equivalent routes.Add specifying the new handler as the MapRoute does not allow you to specify a custom route handler.

C#:

routes.Add(
	new Route("{controller}/{action}/{id}", 
		new RouteValueDictionary(
			new { controller = "Default", action = "Index", id = "" }),
			new HyphenatedRouteHandler())
);

VB:

routes.Add(New Route("{controller}/{action}/{id}", 
	New RouteValueDictionary(New With {.controller = "Home", .action = "Index", .id = ""}), 
		New HyphenatedRouteHandler()))

I hope this is useful, any questions feel free to get in touch.

Would like to say thanks to John from here for answering the original question on Stackoverflow

Author: Zero7Web Categories: .NET Tags: , , , , ,

ASP.NET MVC 2 RC 2 Released

February 5th, 2010

Today ASP.NET MVC 2 RC2 has been released.

To download it click here

It seems there are only a few changes to this release which you can find here: Release Notes

A few words from Phil Haack’s blog:

The biggest change in this release was described by Brad Wilson in his blog post on Input Validation vs. Model Validation in ASP.NET MVC. Also included in this release are an assortment of bug fixes and performance improvements.

The window to provide feedback on this release is going to be very short as we are closing in on the RTM. If you want to provide input into this release, please do take the bits for a spin as soon as possible. I’m pretty excited about this release as I can see the end of the tunnel fast approaching. :)

At this point, we’ll only be taking recall class bugs for ASP.NET MVC 2. All other bug reports will be filed against ASP.NET MVC 3. Sometime in the near future, I’ll start sharing some of our planning around that. How exciting!

Author: Zero7Web Categories: Development, General Tags: , ,

Facebook launch HipHop, a sourcecode-converter from php to c++

February 3rd, 2010

Yesterday Facebook launched HipHop, a converter from php to c++ so your apps can run twice as fast due to them being compiled not interpreted.

Today I’m excited to share the project a small team of amazing people and I have been working on for the past two years; HipHop for PHP. With HipHop we’ve reduced the CPU usage on our Web servers on average by about fifty percent, depending on the page. Less CPU means fewer servers, which means less overhead. This project has had a tremendous impact on Facebook. We feel the Web at large can benefit from HipHop, so we are releasing it as open source this evening in hope that it brings a new focus toward scaling large complex websites with PHP. While HipHop has shown us incredible results, it’s certainly not complete and you should be comfortable with beta software before trying it out. – Haiping Zhao (Facebook)

HipHop is for scaling large multiserver high traffic sites like Facebook. In your regular application, you will get no great advantage from it. It is definately something to be aware of but it does make you think if your trying to compile PHP using a tool like this why not develop in C# (ASP.NET MVC 2 maybe?) that is compiled anyway?

Author: Zero7Web Categories: Development Tags: , , , ,

What are RSS and Atom Feeds and how do I create them?

November 25th, 2009

What are feeds?

Really Simple Syndication (RSS) and Atom feeds are different formats used to publish updates or changes such as new blog entries, news entries or user activity in a standard format. The feed is basically an XML document containing certain information about the updated content.

What information do they contain?

The “feed”, “web feed” or “channel” includes full or summarised text, plus metadata such as published date, category and authorship.

Should I use RSS or Atom?

RSS is more widely used as it was around first although the Atom feed standards seen to have a better structure I personally would stick with RSS 2.0 as it will work on all readers and software, and people are familiar with the term RSS.

Why should I use a feed on my website?

Web feeds make it easy to inform people of changes to your website. Anyone interested in your feed can subscribe to it via an RSS reader which can then keep track of updates for you. You can use fees in outlook, through the browser or through many desktop applications available.

How can I create a feed?

I will talk you through a very basic example of a feed to get you started but if your interested in taking it further you should read the RSS 2.0 specs and also those for Atom feeds.

You can either generate the feed manually or dynamically, but either way the end result will be structured the same.

Below is an example of a RSS document (XML).

<rss version="2.0">
 <channel>
  <title>Social Addict Feed</title>
  <description>This shows the latest updates on socialaddict.co.uk</description>
  <link>http://www.socialaddict.co.uk</link>
   <item>
    <title>HOUSJUNKI :: BOXING DAY :: 26.12.09 :: CLUB.V</title>
    <link>http://www.socialaddict.co.uk/events/single-event?eID=91</link>
    <description>Event added: HOUSJUNKI :: BOXING DAY :: 26.12.09 :: CLUB.V @ Club Venus by andoi - Sat 21st Nov 2009 8:19pm</description>
    <category>EVENT</category>
    <pubDate>Sat, 21 Nov 2009 20:19:40 +0000</pubDate>
    <copyright>(c) Social Addict 2009</copyright>
   </item>
 </channel>
</rss>

Creating a static feed

Simply take the code you have produced like above and save it as an XML document, rss.xml will be fine and then upload to your website. You take give out a direct link to the feed or if you would like users of the website to pick up that it exists automatically then simply add the following code into the head area of the HTML code.

<link rel="alternate" type="application/rss+xml" title="RSS Feed" href="rss.xml" />

Dynamically creating a feed using PHP

If you have a dynamic (database driven) website then it would make more sense to dynamically generate the feed.

We have recently made a feed for a client site ( www.socialaddict.co.uk/rss ) and we had to bring together the data from several different tables and merge them so the feed could take all updates into account.

We used the RSS2Writer class to generate the XML document which simplies the use of the PHP XMLWriter object. Grab yourself a copy of the class and you can use the example below to help get you started.

This is assuming you have a mySQL database with a table called “updates” and it contains:

`title` VARCHAR
`category` VARCHAR
`info` VARCHAR
`url` VARCHAR
`created` DATETIME

<?php
try {
 
   // Create RSS writer
  include('includes/RSS2Writer.php');
   $rss = new rss2writer('Social Addict Feed', 'This shows the latest updates on    socialaddict.co.uk', 'http://www.socialaddict.co.uk');
 
    // Create Database connection
    $dbh = new PDO('mysql:host=localhost;dbname=test', 'username, 'password'); // put your database details in here
    // Get data and iterate through it
    foreach($dbh->query('SELECT `title`,`category`,`info`,`url`,`created` from updates') as $feed) {
 
        // Get each feed item information
	$rss->addItem($feed['title'], $feed['info'], $feed['url'], true);
	$rss->addElement('category', $feed['category']);
	$rss->addElement('pubDate', date("r",strtotime($feed['created'])));
	$rss->addElement('copyright', '(c) Social Addict 2009');
	$rss->closeItem();
 
    }
    $dbh = null;
 
    // Set header type to XML
    header('Content-type: text/xml');
 
   //$rss->writeToFile('rss.xml'); //write the xml output to file (optional)
   echo $rss->getXML(); // Output XML to browser / screen
 
// Catch any errors
} catch (PDOException $e) {
    print "An error occured: " . $e->getMessage() . "<br/>";
    die();
}
?>

Any questions are welcome, and we also help people out where we can.

Author: Zero7Web Categories: Development Tags: , , , , ,

How to: detect URLs in text and convert to html links (PHP using regular expressions)

October 14th, 2009

I was trying to find a way of picking up URLs from user’s posts and converting them to HTML links. I found a few examples on the net that didn’t work for multiple URLs so I thought i would post a simple solution.

I have used the PHP preg_replace function

1
2
3
4
5
6
7
8
9
10
11
<?php
// The Regular Expression filter
$pattern = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
 
//example text
$text="Example user text with a URL http://www.zero7web.com , second link http://www.didsburydesign.co.uk";
// convert URLs into Links
$text= preg_replace($pattern, "<a href=\"\\0\"?phpMyAdmin=uMSzDU7o3aUDmXyBqXX6JVQaIO3 rel=\"nofollow\">\\0</a>", $text);
 
echo $text;
?>

This will match all the URL’s in the text and not just the first one like so many of the example on the web seem to do!!

I will post a C# .net version of this as a follow up in the next day or so.

All comments welcome.

How To: Make a website that allows for multiple languages

April 24th, 2009

So you have an old website or even a current one and you not have the need for several languages because of the traffic your getting. There are many ways of doing this and im giving a fairly simplistic method (simple is not a bad thing in this case). I will be doing this tutorial in a few programming languages but i will first show you in PHP as its my favourite :)

PHP METHOD

I will break this down into a few stages for you. Im going to assume that you have some header text you need to be multi lingual and the navigation links (but this is really irrelevant as you can use this method wherever you need). This is designed for the static content on your pages (i will cover a similar method for DB driven content as soon as someone requests it or i get chance!)

Breakdown of Tasks

  1. create languages folder in your web root (or wherever you want on your web server)
  2. create english.php file within that for starters
  3. create definitions within that file, one for each static piece of text
  4. create index.php and create drop down language selector
  5. include the correct language file dependant on the selected language (stored in session data)
  6. substitute your static bits of text with the relevant definition call
  7. Enjoy your multi language website :)

OK lets get started…

1. create languages folder in your web root (or wherever you want on your web server)

OK im going to recommend creating a new folder in your website root called languages. This will be used to hold all your language definition files.

2. create english.php definition file

I’m using English as my example but name this after one of the languages you require and create the blank file called english.php in the languages folder.

3. create definitions within that file, one for each static piece of text

Edit the new language files in your editor of choice and add the following code (use your own names to define areas on your site you get the idea)

1
2
3
4
<?php
define("agHeader", "Hello im a title", true);
define("agNavigationLink", "Hello im a link", true);
?>

save the file. Now make a copy of this file in the same folder and call it for example “polish.php” and keep the definition names the same THIS IS CRUCIAL. Change the values though to the new language see below for a polish example!

1
2
3
4
<?php
define("agHeader", "Czesc jestem tytuł", true);
define("agNavigationLink", "Czesc jestem hyperłączność", true);
?>

4. create index.php and create drop down language selector

Create a new index.php file outside of the language folder and within it we need to have a drop down list to select the language we require. Once this is selected we also need to store the language so that when we navigate away from the page the settings are remember. For this we will use sessions.

My Dropdown box code is like this:

1
2
3
4
5
6
7
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <select name="language">
        <option value="english"<?php if($_SESSION['language']=="english"){ echo " selected=selected"; } ?>>English</option>
        <option value="polish"<?php if($_SESSION['language']=="polish"){ echo " selected=selected"; } ?>>Polish</option>
    </select>
    <input type="submit" value="Change" name="submit" />
</form>

this will submit to itself when a language is selected and as you can see, it will automatically start at the current language using a quick check on the SESSION variable we are going to use.

5. include the correct language file dependant on the selected language

At the very top of the file i have started the session and done a couple of things. First check if the language has been posted via the form, if it has then it will be stored in a session variable. The next thing that is done is using the session data the language definition is included using a switch statement and not the form data directly for security reasons. We also use the PHP5 filter_input() function to be safe when setting the session data.

This is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
session_start();
if(isset($_POST['language'])){
$_SESSION['language']= filter_input(INPUT_POST, ‘language’, FILTER_SANITIZE_SPECIAL_CHARS); //filter the posted data just for security
}
 
switch ($_SESSION['language']) {
case “polish”:
include(”languages/polish.php”);
break;
default:
include(”languages/english.php”);
}
 
?>

6. substitute your static bits of text with the relevant definition call

Last step where you want your text to appear you simple echo out your definitions like so

1
<?php echo agHeader; ?>

7. Complete!

Thats it!! Below i’ve given a link to the example files and an online demo.

If you do download the example please comment and give feedback as i want to make my blog’s as useful as possible for everyone. If you need any more info or help just ask! I always have time for people if you are keen to learn :)

Please comment on the article and if you like it link back to me and digg it!

All feedback welcome, thank you

If you would like to download a basic example then please do so here

If you would like to view the online demo go here

If you are interested in learning more about PHP we highly recommend this book and it will really help you with your development: