Friday, December 9, 2011

28 Ways to Make Money with Your Website

There are several lists with “ways to make money with a website” on the Internet, but none of them seem to be complete. That is why I decided to create this one. If you know a method that is not listed below, just let us know and we’ll update it.
Notice that ways to make money with a website are different from ways to make more money from it. Methods to increase your traffic or click-through rate will help you make more money, but they do not represent a method of making money per se.
For example, one could suggest that blending AdSense ads with the content is a way to make money from a website. In reality it’s not; it’s just a way to make more money by improving your ad click-through rate. The real monetization method behind it is a PPC ad network.
The list is divided into direct and indirect methods, and examples and links are provided for each point. Enjoy!

Direct Methods

1. PPC Advertising Networks
Google AdSense is the most popular option under this category, but there are also others. Basically you need to sign up with the network and paste some code snippets on your website. The network will then serve contextual ads (either text or images) relevant to your website, and you will earn a certain amount of money for every click.
The profitability of PPC advertising depends on the general traffic levels of the website and, most importantly, on the click-through rate (CTR) and cost per click (CPC). The CTR depends on the design of the website. Ads placed abode the fold or blended with content, for instance, tend to get higher CTRs. The CPC, on the other hand, depends on the nice of the website. Mortgages, financial products and college education are examples of profitable niches (clicks worth a couple of dollars are not rare), while tech-related topics tend to receive a smaller CPC (sometimes as low as a couple of cents per click).
The source of the traffic can also affect the overall CTR rate. Organic traffic (the one that comes from search engines) tends to perform well because these visitors were already looking for something, and they tend to click on ads more often. Social media traffic, on the other hand, presents terribly low CTRs because these visitors are tech-savvy and they just ignore ads.
List of popular CPC advertising networks:
2. CPM Advertising Networks
CPM advertising networks behave pretty much as PPC networks, except that you get paid according to the number of impressions (i.e., page views) that the ads displayed on your site will generate. CPM stands for Cost per Mille, and it refers to the cost for 1,000 impressions.
A blog that generates 100,000 page views monthly displaying an advertising banner with a $1 CPM, therefore, will earn $100 monthly.
CPM rates vary with the network, the position of the ad and the format. The better the network, the higher the CPM rate (because they have access to more advertisers). The closer you put the ad to the top of the page, the higher the CPM. The bigger the format (in terms of pixels), the higher the CPM.
You can get as low as $0,10 and as high as $10 per 1,000 impressions (more in some special cases). CPM advertising tends to work well on websites with a high page views per visitor ratio (e.g., online forums, magazines and so on).
List of popular CPM advertising networks:
3. Direct Banner Advertising
Selling your own advertising space is one of the most lucrative monetization methods. First and foremost because it enables you to cut out the middleman commissions and to determine your own rates. The most popular banner formats on the web are the 728×90 leaderboard, the 120×600 skyscraper, the 300×250 rectangle and the 125×125 button.
The downside of direct banner advertising is that you need to have a big audience to get qualified advertisers, and you will need to spend time managing the sales process, the banners and the payments.
Related links:
4. Text Link Ads
After Google declared that sites selling text links without the nofollow tag would be penalized, this monetization method became less popular.
Many website owners are still using text links to monetize their sites, though, some using the nofollow tag and some not.
The advantage of this method is that it is not intrusive. One can sell text links directly through his website or use specialized networks like Text-Link-Ads and Text-Link-Brokers to automate the process.
Text link marketplaces and networks:
5. Affiliate Marketing
Affiliate marketing is a very popular practice on the Internet. Under this system you have a merchant that is willing to let other people (the affiliates) sell directly or indirectly its products and services, in exchange for a commission. Sometimes this type of advertising is also called CPA (cost per action) or CPL (cost per lead) based.
Affiliates can send potential customers to the merchant using several tools, from banners to text links and product reviews.
In order to find suitable affiliate programs you can turn to individual companies and publishers like Dreamhost and SEOBook, or join affiliate marketplaces and networks.
List of popular affiliate marketplaces and networks:
6. Monetization Widgets
The latest trend on the web are widgets that let you monetize your website. Examples include Widgetbucks and SmartLinks. Some of these services operate under a PPC scheme, others behave like text link ads, others yet leverage affiliate links.
Their main differentiator, however, is the fact that they work as web widgets, making it easier for the user to plug and play the service on its website.
List of companies that provide monetization widgets:
7. Sponsored Reviews
PayPerPost pioneered this model, with much controversy on the beginning (related to the fact that they did not require disclosure on paid posts). Soon other companies followed, most notably Sponsored Reviews and ReviewMe, refining the process and expanding the paid blogging model.
Joining one of these sponsored reviews marketplaces will give you the opportunity to write sponsored posts on a wide range of topics. Not all bloggers are willing to get paid to write about a specific product or website (because it might compromise the editorial credibility), but the ones who do are making good money out of it.
If your blog has a big audience you could also offer sponsored reviews directly, cutting off the commissions of the middleman.
List of sponsored reviews and paid blogging networks:
8. RSS Feed Ads
With the quick adoption of the RSS technology by millions of Internet users, website owners are starting to find ways to monetize this new content distribution channel.
Feedburber already has its own publisher network, and you can sign-up to start displaying CPM based advertising on your feed footer. Bidvertiser recently introduced a RSS feed ad option as well, with a PPC scheme.
Finally, some blogs are also opting to sell banners or sponsored messages on their feed directly. John Chow and Marketing Pilgrim are two examples.
Related links:
9. Sponsors for Single Columns or Events
If you website has specific columns or events (e.g., a weekly podcast, an interview series, a monthly survey, a special project) you could find companies to sponsor them individually.
This method increases the monetization options for website owner, while giving advertisers the possibility to target a more specific audience and with a reduced commitment.
Mashable illustrates the case well. They have several advertising options on the site, including the possibility to sponsor specific columns and articles, including the “Daily Poll” and the “Web 2.0 Invites.”
Problogger also runs group writing projects occasionally, and before proceeding he publicly announce the project asking for sponsors.
10.Premium Content
Some websites and blogs give away part of their content for free, and charge for access to the premium content and exclusive tools.
SEOMoz is a good example. They have a very popular blog that gives advice and information on wide range of SEO related topics. On top of that visitors can decide to become premium members. It costs $48 monthly and it grants them access to guides, tools and other exclusive material.
11. Private Forums
While the Internet is populated with free forums, there is also the possibility to create a private one where members need to pay a single or recurring fee to join.

SEO Blackhat
charges $100 monthly from its members, and they have thousands of them. Obviously in order to charge such a price for a forum membership you need to provide real value for the members (e.g., secret techniques, tools, and so on).
Performancing also launched a private forum recently, focused on the networking aspect. It is called The Hive, and the monthly cost is $10.
These are just two examples. There are many possibilities to create a private and profitable forum, you just need to find an appealing angle that will make it worth for the members.
List of popular forum software:
12. Job Boards
All the popular blogs are trying to leverage job boards to make some extra income. Guy Kawasaki, ReadWriteWeb, Problogger… you name it.
Needless to say that in order to create an active and profitable job board you need first to have a blog focused on a specific niche, and a decent amount traffic.
The advantage of this method is that it is passive. Once you have the structure in place, the job listings will come naturally, and you can charge anywhere from $10 up to $100 for each.
List of popular job board software:
13. Marketplaces
Sitepoint is the online marketplace by excellence. Some websites and blogs, however, are trying to replicate that model on a smaller scale.
Depending on your niche, a market place that allows your visitors to buy, sell and trade products could work well. Over the time you could start charging a small fee for new product listings.
The problem with this method is that there are no standard software on the web, so you would need to hire a coder to get a marketplace integrated into your website.
You can see an example of a marketplaces being used on EasyWordpress and on Mashable.
14. Paid Surveys and Polls
There are services that will pay you money to run a small survey or poll on your website. The most popular one is called Vizu Answers.
Basically you need to sign up with them, and select the kind of polls that you want to run your site. Most of these services operate under a CPM model.
15. Selling or Renting Internal Pages
Million Dollar Wiki made this concept popular, but it was being used on the web for a long time around (check Pagerank10.co.uk for instance).
These websites sell for a single fee or rent for a recurring fee internal pages on their domain. Usually they have either high Pagerak or high traffic, so that people purchasing a page will be able to benefit in some way.
Implementing this method on a small blog would be difficult, but the concept is interesting and could be explored further.
16. Highlighted Posts from Sponsors
Techmeme probably pioneered this idea, but somehow it has not spread to other websites. The tech news aggregator displays editorial posts on the left column, and on the sidebar they have a section titled “Techmeme Sponsor Posts.”
On that section posts from the blog of the advertisers get highlighted, sending qualified traffic their way. Considering that the monthly cost for one spot is $5000 and that they have around 6 sponsors at any given time, it must be working well.
17. Donations
Placing a “Donate” link or button on a website can be an efficient way to earn money, especially if your blog is on a niche where readers learn and gain value from your content.
Personal development and productivity blogs, for instance, tend to perform well with donation based systems (one good example being Steve Pavlina).
A small variation of this method appeared sometime ago with the Buy Me a Beer plugin. This WordPress plugin enables you to insert a customized message at the bottom of each article, asking the readers to chip in for a beer or coffee.
18. In-text Adverting
In-text adverting networks like Kontera and Vibrant Media will place sponsored links inside your text. These links come with a double underline to differentiate them from normal links, and once the user rolls the mouse over the link the advertising will pop. Should the user click on it the site owner will make some money.
Some people make good money with this method, but others refrain from using it due to its intrusiveness. It is also interesting to note that very few mainstream websites have experimented with in-text advertising.
19. Pop-ups and Pop-unders
Pop-ups are a common yet annoying form of advertising on the Internet. If you are just trying to make a much money as possible from your website, you could experiment with them.
If you are trying to grow the traffic and generate loyal visitors, however, you probably should stay away from them. Just consider the hundreds of pop-up blockers out there: there is a reason why they are so popular.
Ad networks that use pop-ups:
20. Audio Ads
Also called PPP (Pay Per Play), this advertising method was introduce by Net Audio Ads. the concept is pretty simple: play a small audio advertising (usually 5 seconds) every time a visitor enters into your website. The user should not be able to stop it, creating a 100% conversion rate based on unique visitors.
The company is still rolling tests, but some users are reporting to get from a $4 to a $6 CPM. Regardless of the pay rate, though, this is a very intrusive form of advertising, so think twice before using it.
21. Selling the Website
Selling your website could be your last resource, but it has the potential to generate a big sum of money in a short period of time.
Market places on online forums like DigitalPoint and Sitepoint are always active with website buyers and sellers. Keep in mind that they most used parameter to determine the value of a website is the monthly revenue that it generates, multiplied by a certain number (the multiplier can be anything from 5 to 30, depending on the expectations of the seller, on the quality of the site, on the niche and other factors).
Some people also make money trading and flipping websites. They either create them from scratch or buy existing ones, and after some revamping they sell them for a profit.
Related links:

Indirect Methods

22. Selling an Ebook
Perhaps one of the oldest money making strategies on the web, using a website to promote a related ebook is a very efficient way to generate revenue.
You could either structure the website around the book itself, like SEOBook.com, or launch the ebook based on the success of the website, like FreelanceSwitch did we the book How to be a Rockstar Freelancer.
Related links:
23. Selling a Hardcover Book
Many authors and journalists leverage their blogs or websites to sell copies of hardcover books. Examples include Guy Kawasaki, Seth Godin and Malcolm Gladwell.
While most of these people were already renowned authors before they created their website, one could also follow the other way around. Lorelle VanFossen did exactly that with her Blogging Tips book. First she built her authority on the subject via her blog, and afterwards she published the book.
List of self publishing and publishing services:
24. Selling Templates or WordPress Themes
As more and more people decide to get an online presence, website templates and WordPress themes become hotter and hotter.
On this segment you have mainstream websites like TemplateMonster, as well as individual designers who decide to promote and sell their work independently.
Brian Gardner and Unique Blog Designs are two examples of websites that make money with the sales of premium and custom WordPress themes.
25. Offering Consulting and Related Services
Depending on your niche, you could make money by offering consulting and related services. If you are also the author of your blog, the articles and information that you will share will build your profile and possibly certify your expertise on that niche, making it easier to gain customers.
Chris Garrett used a similar strategy. First he created a highly influential blog on the blogging and new media niche, and afterwards he started offering consulting services to clients with related problems and needs.
26. Creating an Email List or Newsletter
Email lists and newsletters represent one of the most powerful marketing and money making tools on the Internet. They offer incredible conversion rates, and the possibility to call people to action in a very efficient way.
Creating a big list is a difficult task though, so if you have a popular website you could leverage it to increase the number of subscribers on your list.
Yaro Starak is a famous Internet marketer, and if you visit his blog you will notice that right on top he has a section encouraging visitors to subscribe to his email newsletter. Yaro generates five figures in revenues each month from his email newsletters, proving that this method works.
List of software to manage email newsletters:
27. Mentoring programs
People are willing to pay for someone or something that will teach them and give them knowledge (as opposed to mere information). Education is one of the biggest industries in the world, and the online landscape behaves in a similar way.
Creating a mentoring program related to the niche of your website could be very profitable if you manage to structure and promote it adequately. There is a wide range of media and tools that you can use to deliver the information, from text articles to audio and video lessons.
Brian Clark leveraged the success of Copyblogger to launch a mentoring program teaching people how to build membership and how to sell content online. The program is titled Teaching Sells, and it costs $97 monthly. Sounds expensive, but they have over 1,000 members.
28. Creating a conference around the website
If your website takes off and becomes an authority on its niche, you could create a conference around it. Depending on the size of your audience, the event could attract thousands of people, and you could make money directly from conference passes and sponsors.
Search Engine Land, for instance, created a series of conferences that visit several cities on the United States and on other countries as well. The conferences are called Search Marketing Expo, and the tickets and passes cost thousands of dollars.

Thursday, December 8, 2011

Installing WordPress on SQL Server

Before you read this article, please note: the easiest way to install WordPress on SQL Server or SQL Azure is to use the Getting Started page. If you’re still having trouble or want more details, read on!
These instructions assume you’re installing WordPress on Windows 7 or Windows Server 2008 or 2008 R2. If you’re installing WordPress in a Windows share hosting environment, many of these same concepts apply.
Here’s a summary of the steps:

1. Install the Prerequisites

Use the Microsoft Web Platform Installer. Be sure you have:
  • II7 or above (Windows Vista, Windows 7, Windows Server 2008, Windows Server 2008 R2)
  • PHP 5.2 or above
  • SQL Server Express 2008 w/Tools or above
  • PHP Driver for SQL Server v1.1 or above
  • URL Rewrite 2.0 or above

Get Products with Web Platform Installer

Click here to install all these products with the Web Platform Installer.image
Click on the Get the Microsoft Web Platform button and accept the prompts to install WPI.
image
Click on the bar at the top of the browser to install the add-on.
image
Follow the onscreen prompts and grant permission for the site to open WPI.
image
image
Once the Web Platform Installer downloads and installs all the prerequisites, it will prompt you to configure your SQL Server Express install.
image
Choosing Mixed Mode Authentication and providing an (sa) password will make your web development easiest.
The Web Platform Installer will now download all the bits and prerequisites.
image
Once the download is complete, it will automatically install and configure the software.
image
image
Now you’re ready to run web applications on the Microsoft Web Platform.

2. Configure a Database

In this step, you’ll create a database and a database user for your WordPress install.
Start by running SQL Server Management Studio from your start menu.
image
You’ll be prompted to log on to SQL Server.
image
Connect to your database using Windows Authentication and .SQLExpress for the Server name.
image
Create a new database Login by expanding the Security. Right click on Logins to select New Login.
image
Supply a Login name; select SQL Server authentication; provide a Password and uncheck User must change password at next login. You can leave the rest of the defaults.
Now you need to create a database.
image
Create a new Database by right clicking on Databases to select New Database.
image
Enter a Database name and specify the Login name of the user you created above.
Now you’re ready to proceed with the WordPress install.

3. Download the WordPress on SQL Server Distribution

Go to the Download page and select the standard or Multi-User Distribution from the box on the right side of the page.
image
This will take you to the SourceForge download page for the current version.
image
If you try to save the ZIP file directly to your IIS directory, you’ll probably get a permissions error like below.
image
Save the ZIP somewhere else on your machine, extract the files and copy them into the C:inetpubwwwrootwp-sqlsrv folder.
image
image
image

4. Configure IIS

The most common issue I’ve discovered involves WordPress’ use of HTTP errors.

Enable IIS Detailed Error Messages

When trying to install WordPress for the first time,you might get an IIS 500—an internal server error that says,“There is a problem with the resource you are looking for, and it cannot be displayed”.
image
WordPress is designed to throw an HTTP 500 error if a wp-config.php file is not detected. The problem is that the default install of IIS 7 is overriding HTTP errors for external users as to now show detailed information about the server.
You can temporarily override this behavior during the installation process by telling IIS to show Detailed errors. Do this by creating a web.config file in the root of your WordPress install with the following content:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <httpErrors errorMode="Detailed"/>
    </system.webServer>
</configuration>

Grant IIS Write Permissions to WordPress Folder

Next, you need to ensure your IIS has write permissions to your WordPress installation folder.
NOTE: If IIS does not have write permissions to your WordPress folder you will get caught in a loop where you enter your database credentials then get taken back to the initial installation screen.
By default IIS runs as IUSR so you must add this user with Write permission through Windows Explorer.  Browse to the installation folder, right click on the wp-sqlsrv folder and select the Security tab.
image
Click the Edit button, select Add, then type IUSR for Enter the object names to select.  Click on Check Names and IUSR should now be underlined.
image
When you click OK the top window will close.  Make sure to give this user Write permissions by selecting the checkbox.
image

5. Install WordPress on SQL Server

Browse to the root of your WordPress install, which in my case is http://localhost/wp-sqlsrv/.
image
Follow the prompts until you’re asked for database information.
image
Specify the Database Name, User Name and Password you created while configuring the database. For the default SQL Server Express install, you will enter .SQLExpress for the Database Host.
Select the sqlsrv driver for Database Type. This will use the PHP Driver for SQL Server, which was developed and maintained by the SQL Server team.
You should see the screen below, with an option to Run the install.
image
If you don’t see this screen and are taken back to the first screen of the install, that means your web server doesn’t have permission to write to the directory
image
You can get information on IIS security here.
If the install is moving forward, you’ll just need to enter your blog information and receive the admin password.
image
Now WordPress should be up and running on SQL Server!
image
The last step is to update your web.config to remove the IIS Detailed errors and enable URL Rewrite.

6. Remove IIS Detailed Errors and Configure URL Rewrite

Remove detailed IIS error messages and add URL Rewrite rules by replacing the contents of your web.config with the following contents:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="wordpress" patternSyntax="Wildcard">
                    <match url="*"/>
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>
                    </conditions>
                    <action type="Rewrite" url="index.php"/>
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>
Now enjoy using WordPress on SQL Server!

Monday, December 5, 2011

iPad Programming Tutorial – Hello World++

Introduction

Now, that the iPad has been released, I’m sure you are all scrambling for ideas on how to snag a piece of the maket in the imminent gold rush.  iCodeBlog is going to help you on your journey with a series of iPad tutorials to come.
Since the iPad uses the same SDK as the iPhone, all of the code under the hood is almost identical.  Actually, when looking at the new and changed API classes, you will realize that most of them are user interface related.  This is good news for us since we have already been coding iPhone.
While this tutorial is called “Hello World”, it is really much more than that.  I assume you already have working knowledge of iPhone/Objective-C programming.

What We Will Be Creating

In today’s tutorial, I will be showing you how to create an iPad project that uses the UISplitViewController to display content in 2 separate panes.  We will also be touching on some of the new design/UI patterns and giving an overall introduction to iPad programming.
The project will be based on one of my earliest tutorials that displayed a list of fruit in a UITableView and drilled down when they were selected.  We will be expanding on that example and creating something that will look like this.

It uses a UISplitViewController to display a UITableView on the left and a UIView with a UIImageView subview on the right.  This project is actually quite simple to create as the template code provides much of the code we need to get started.

Getting Started

1. Make sure you have downloaded the 3.2 SDK form http://developer.apple.com/iphone/.  The iPad simulator will come with this download.
2. Download the resources needed for this project and unzip them iPadHelloWorldResources.zip . (contains image files and a plist we will be using to load the images)

Creating The Project

Starting a project for the iPad is no different than starting one for the iPhone.  When you open XCode and select File->New Project, you should notice the addition of a Split View-Based Application.  Select this and name it iPadHelloWorld.

This will create a basic application with a UITableView on the left and a UIView on the right.  It will even populate the table with some sample elements.  It will add the following files to your project.

Here is a brief description of each of these files:
  • iPadHelloWorldAppDelegate – This is similar to every app delegate.  If you look in the application:didFinishLaunchingWithOptions method, you will see that the UISplitViewController is being allocated with the MasterViewController and DetailViewControllers.
  • MasterViewController – A UITableViewController, nothing fancy.  It will be handling the view on the left hand side.
  • DetailViewController – This handles the content view that you see on the right hand side.  We will be updating this as the user selects different rows in the table to the left.  This simply houses a single view.
Go ahead and press Build and Run to check out the application.  If you haven’t already done so, play around with the iPad contacts and settings apps as well.
Note: When you launch the application, you will only see the main view since the simulator runs in vertical mode.  To see the views side-by-side, rotate the simulator by clicking “Hardware -> Rotate Left/Right”.  You can also press CMD->Arrow Left/Right on the keyboard.

Importing The Project Images

Once you have had some time to play with the new iPad project, you will now need to import the images needed for this project.  After downloading and unzipping the files in from this tutorial, drag them into the project folder called “Resources-iPad”.
XCode will prompt you to copy the files, check yes and click OK.

Make sure you include all 4 images files as well as the file named fruits.plist.

Displaying The List Of Fruits

Displaying our fruits list is no different than displaying data in any other UITableView.  Let’s begin by opening MasterViewController.h and adding a declaration for our fruits array.
#import
 
@class DetailViewController;
 
@interface MasterViewController : UITableViewController {
    DetailViewController *detailViewController;
    NSArray * fruits;
}
 
@property (nonatomic, retain) IBOutlet DetailViewController *detailViewController;
@property (nonatomic, retain) NSMutableArray *fruits;
 
@end
As you can see, there is nothing new here.  We simply declare our fruits array and create a property for it.
We will be loading the fruits from the plist file that you imported into your project in the last step.  Loading content from a plist file is a very quick and easy solution when you don’t require a database.
Open up MasterViewController.m and add the following line of code to your viewDidLoad method.
- (void)viewDidLoad {
    [super viewDidLoad];
    self.fruits = [[NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"fruits" ofType:@"plist"]] retain];
}
The file fruits.plist is essentially an array that has been written out to a file.  If you open it up, it looks very similar to XML.  Now that our fruits array has been populated, let’s implement each of the UITableView delegate and datasource methods to populate the table.
UITableView datasource methods
- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [fruits count];
}
 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 
    static NSString *CellIdentifier = @"CellIdentifier";
 
 // Dequeue or create a cell of the appropriate type.
 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
 
    // Get the object to display and set the value in the cell.
    cell.textLabel.text = [self.fruits objectAtIndex:indexPath.row];
    return cell;
}
Nothing special… We first tell the tableview that we want fruits.count (4 in this case) number of rows.
Next, we display the name of the fruit in each tableview cell.  If you want to learn more on UITableViews
UITableView delegate methods
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 
    /*
     When a row is selected, set the detail view controller's detail item to the item associated with the selected row.
     */
    detailViewController.detailItem = [self.fruits objectAtIndex: indexPath.row];
}
Here, we are simply setting the detailItem property of the detailViewController to the selected fruit.  We will discuss this property later in this section, but for now all you need to know is that its type is id.
At this point, go ahead and press Build and Run to see your code in action.  You should see something that looks like this:

It displays the list of fruits, but nothing happens when you select a cell (well the title of the detailView may change).
Now that we have our list of fruits displayed, we now need to implement the code to display their corresponding image.

Displaying The Fruits

Displaying the selected fruit is actually quite simple.  The first thing we need to do is add a UIImageView to our detailView.
Start by adding the IBOutlet for the image view.  Open up DetailViewController.h and add the following code:
@interface DetailViewController : UIViewController  {
 
    UIPopoverController *popoverController;
    UINavigationBar *navigationBar;
 
    id detailItem;
 
    IBOutlet UIImageView * fruitImageView;
}
 
@property (nonatomic, retain) UIPopoverController *popoverController;
@property (nonatomic, retain) IBOutlet UINavigationBar *navigationBar;
 
@property (nonatomic, retain) id detailItem;
 
@property (nonatomic, retain) IBOutlet UIImageView * fruitImageView;
 
@end
All of the code here comes with the template except the code to add the IBOutlet UIImageView.  Once you have added this open up DetailView.xib in interface builder.
Add a UIImageView on to the view and size it to 500×500.

Now, click on the File’s Owner object and open the connection inspector (Tools -> connection inspector).
Drag from your imageView IBOutlet to the UIImageView and release.  The UIImageView is now connected to your outlet.
Note: If you want the images to not skew, set the content mode of the image view (in the attributes inspector) to Aspect Fit.
Now that the imageview has been connected, it’s time to write the code that updates it.  Close Interface Builder and open the file DetailViewController.m and add the following lines to the setDetailItem method:
- (void)setDetailItem:(id)newDetailItem {
    if (detailItem != newDetailItem) {
        [detailItem release];
        detailItem = [newDetailItem retain];
 
        // Update the view.
        navigationBar.topItem.title = detailItem;
 NSString * imageName = [NSString stringWithFormat:@"%@.png",detailItem];
 [self.fruitImageView setImage:[UIImage imageNamed:imageName]];
    }
 
    if (popoverController != nil) {
        [popoverController dismissPopoverAnimated:YES];
    }
}
Most of this code has been added by the template and I won’t discuss it too much in this tutorial.  But for now, the important additions are the lines that load the image based on  the name of the fruit and the one below it that sets the image property of the image view.
There you have it! Build and go and the application should function as mentioned.  Here is another screenshot of the final product.

Another Cool Feature Of SplitViewController

When in vertical mode, the SplitViewController gives you another new UI element called the UIPopOverView.  Collin will have a tutorial up soon on this view, but the figure below shows you what I’m talking about.

When the device is vertical, it will automatically rotate your view and provide a UIPopoverView when the “Master List” button is pretty. (BTW this button is also customizable).

Sunday, December 4, 2011

HowTo: Configure WordPress To Use A Content Delivery Network (CDN)

Research shows that if your web pages take longer than 5 seconds to load, you lose 50% of your viewers and sales. You can speed up your wordpress blog by using a CDN to display content to users faster and more efficiently. You can distributes common files or content such as css, javascript, uploaded images, videos and much more through a CDN, which serves the content from the closest cdn edge server to the end-user. In this tutorial, I will explains how to configure WordPress, Apache/Lighttpd webserver, Bind dns server to use a CDN to distribute your common files such as css, js, user uploaded files and lighten load on your web server.

What Is A CDN?

A content delivery network or content distribution network (CDN) is a system of computers containing copies of data, placed at various points in a network so as to maximize bandwidth for access to the data from clients throughout the network. A client accesses a copy of the data near to the client, as opposed to all clients accessing the same central server, so as to avoid bottleneck near that server. A cdn will increase speed and efficiency for your blog.

What Are The Advantages Of Using CDN Over Central Server?

  • Speed - All common media files distributed via CDN. For example, files.cyberciti.biz configured as CDN subdomain. Everything hosted on files.cyberciti.biz is geographically closer to the end-user. If you run dns query over files.cyberciti.biz, it will return an IP geographically closer to you.
    $ host files.cyberciti.biz
    $ ping files.cyberciti.biz
  • This will increase delivery speed and avoids network congestion on your own server.
  • Security - It adds additional level of security.
  • Availability - CDNs offers 100% availability, even with large power, network or hardware outages.

Different Types Of CDNs

A CDN can use various methods to distribute your content such as:
  1. Peer to peer CDN - This is used to distribute latest episode of a soap opera (movies / TV shows) or some sort of software patch/update in short period of time to large number of users.
  2. Origin Pull CDN - This is useful to distribute small files such as javascript, css, images, text, pdf, .doc, .xls etc. This is recommended for WordPress. All content is stored on your own server called "Origin Pull Host". This host is then registered with the CDN. When the first user requests the content, it is pulled to the CDN network from your host and delivered via CDN to the closest point to that end user. The content is cached on CDN with a TTL (or max age and Etags is also used). This kind of configuration requires storage on your own server and not on the CDN server. The first requesting user has an average CDN experience, while later users have very fast user delivery experience. This is recommended for file size <= 10MB.
  3. PoP Pull CDN - You need to upload content to the CDN host server, where it is stored for delivery. This option is little expensive as you need to purchase the CDN storage with provider along with bandwidth. This is recommend for large files and video streaming etc. You need to upload files to the CDN server using FTP / SCP or API.

Content Delivery Service Providers

A list of some of the larger content delivery network providers. Do your own research before purchasing CDN service from any one of the following provider:
  • Amazon CloudFront
  • Akamai
  • CacheFly
  • EdgeCast Networks
  • Internap
  • Level 3 Communications
  • Limelight Networks

Our Sample Setup

  • Blog URL : http://nixcraft.in/ - This is hosted on your own server using Apache, Lighttpd, IIS or Nginx.
  • Origin Pull URL : http://www-origin.nixcraft.in/ - This is hosted on your own server. You need to configure your web server, wordpress and dns server to use this. This is called as "Origin Pull Host" which is a CDN method by which content is pulled from your web server.
  • CDN URL : http://files.nixcraft.in/ - This is a cdn url hosted by one of the above CDN provider. This url always point to an edge server via proprietor DNS hacks. files.nixcraft.in must be set as CNAME records which will point to domain names of CDN server.
  • CDN DNS CNAME : files.nixcraft.in.example.com - example.com is one of the above CDN provider. This is must be set as CNAME for files.nixcraft.in

Step # 1: Purchase CDN Service

The cost varies between CDN providers. Check CDN service providers website for more information. Next, you need to use service providers "control panel" to configure an "Origin Pull Host" for each domain. In other words configure files.nixcraft.in in origin pull mode. The control panel will also provide your an option to setup CDN dns CNAME. You need to use same CNAME in step # 2. Once the configuration is active and the CNAME is resolving, calls to files.nixcraft.in will be cached from www-origin.nixcraft.in.

Step # 2: Update Your DNS Server

Assuming that you are using BIND dns server edit your zone file and add entry as follows:
; CDN CNAME mapping for files.nixcraft.in
files                3660       IN CNAME files.nixcraft.in.example.com.
; Your www-origin url (note nixcraft.in is also hosted on same server IP 123.1.2.3)
www-origin      3600       IN A 123.1.2.3
Reload your named:
# rndc reload
To keep your configuration simple use same web server for origin pull domain and main domain i.e. host both www-origin.nixcraft.in and nixcraft.in on same web server. This allows you to directly upload and map files to the CDN server.
Please note that you can setup CNAME and origin host names using your ISPs DNS control panel too.

Step # 3: Configure Origin Pull Web Server

You need to configure www-origin.nixcraft.in as follows:
  • Origin pull DocumentRoot: /home/httpd/www-origin.nixcraft.in - All your .css, .js and uploaded files are hosted here.
  • Server Blog DocumentRoot: /home/httpd/nixcraft.in - All your wordpress files are hosted here.
  • MaxAge: Set cache-lifetime headers for static files for cdn network.
  • Etags: An ETag (entity tag) is part of HTTP, the protocol for the World Wide Web. It is a response header that may be returned by an HTTP/1.1 compliant web server and is used to determine change in content at a given URL. When a new HTTP response contains the same ETag as an older HTTP response, the client can conclude that the content is the same without further downloading.
Here is a sample Lighttpd lighttpd.conf entry for the same:
# Configure ETags
etag.use-inode = "enable"
etag.use-mtime = "enable"
etag.use-size = "enable"
static-file.etags = "enable"
 
###### CDN FILES via WordPress Upload ##############
$HTTP["host"]  == "www-origin.nixcraft.in"{
        server.document-root = "/home/httpd/www-origin.nixcraft.in"
        accesslog.filename         = "/var/log/lighttpd/cdn.access.log"
 #  Set max age
        $HTTP["url"] =~ "^/" {
            expire.url = ( "" => "access 60 days" )
        }
}
Here is a sample Apache httpd.conf file:
<VirtualHost www-origin.nixcraft.in>
 ServerAdmin webmaster@nixcraft.in
 DocumentRoot /home/httpd/www-origin.nixcraft.in
 ServerName files.nixcraft.in
 ServerAlias file.nixcraft.in
 ErrorLog /var/logs/httpd/cdn-error_log
 CustomLog /var/logs/httpd/cdn-access_log common
 
 # Files in this directory will be cached for 1 week only.
 # After 1 week, CDN server will check if the contents has been modified or not.
 # If not modified, Apache will send 304 "Not Modified" header
 <Directory "/userimages">
  Header set Cache-Control "max-age=604800, must-revalidate"
 </Directory>
 
 # Disable ETag as we are on cluster Apache server
 <Directory "/pdfs">
  Header unset ETag
  FileETag None
 </Directory>
 
 # Do not cache
 <Directory "/patches">
  Header Set Cache-Control "max-age=0, no-store"
 </Directory>
</VirtualHost>

Step # 4: Configure WordPress To Upload Files To CDN Server

  1. Visit your wordpress dashboard url (e.g., http://nixcraft.in/wp-admin/)
  2. Click on Settings > Miscellaneous Settings
  3. Update it as follows to point out to our configuration paths and CDN domains
Fig.01: Wordrpess Miscellaneous Settings - Set CDN URLS
Fig.01: Wordrpess Miscellaneous Settings - Set CDN URLS
All your uploaded files are saved on your server at /home/httpd/www-origin.nixcraft.in directory. Which is mapped to CDN via origin pull method. In this example:
  • A user requests for http://files.nixcraft.in/uploads/2010/04/test.png
  • First pulled from http://www-origin.nixcraft.in/uploads/2010/04/test.png by your CDN server
  • It is cached at CDN server for 60 days (or as per max age rule)
  • Rest of all user gets image from the CDN server.

Step # 5: Configure WordPress Theme To Serve CSS / JS From The CDN Server

First, copy your .css, and .js files to /home/httpd/www-origin.nixcraft.in directory:
mkdir -p /home/httpd/www-origin.nixcraft.in/{css,js}
cp -av /home/httpd/nixcraft.in/wp-content/themes/mythemename/*.css /home/httpd/www-origin.nixcraft.in/css
cp -av /home/httpd/nixcraft.in/wp-content/themes/mythemename/*.js /home/httpd/www-origin.nixcraft.in/js
Finally, edit your theme (header.php and footer.php) to point to CDN location for stylesheet and/or .js files by visiting "Manage Themes" option from the wordpress dashboard:
 
<link rel="stylesheet" href="http://files.nixcraft.in/css/style.css" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="http://files.nixcraft.in/css/images.css" type="text/css" media="screen, projection" />
 

Results

The end result is pretty nice. Here are sample website load speed upgrades after using a CDN:
Fig.02: Alexa Showing Website loading speed
Fig.02: Alexa Showing Website loading speed
Fig.03: Pingdom Tools Showing Website loading speed
Fig.03: Pingdom Tools Showing Website loading speed
  • See 6 Tools To Find Out Website Load Speed

How Do I Test Images And Other Media Files Are Cached Or Not By CDN?

Use curl to test HTTP headers (look for Etags, max-age and Expires headers):
$ curl -I http://files.nixcraft.in/css/styles.css
$ curl -I http://files.nixcraft.in/uploades/2010/04/test.png

Sample outputs:
HTTP/1.1 200 OK
Content-Type: image/png
Accept-Ranges: bytes
ETag: "1482142335"
Last-Modified: Fri, 02 Apr 2010 09:11:53 GMT
Content-Length: 33143
Server: lighttpd
Cache-Control: max-age=2588785
Expires: Sun, 02 May 2010 09:13:50 GMT
Date: Fri, 02 Apr 2010 10:07:25 GMT
Connection: keep-alive

Wednesday, November 23, 2011

Getting Started with My.Blogs

Getting Started

To get started using My.Blogs, download the sample code to your local machine and extract the files associated with the sample to a directory on your local machine. Follow these steps to start using My.Blogs to work with weblog feeds programmatically.
  1. Start by opening the "\My.Blogs VS Snippet and Add In" from the code you extracted above.
  2. Double-click on My.Blogs.vsi and accept all the default options. This will install a new Template to the Add New Item dialog box called "My.Blogs".
  3. Open Visual Studio 2005 and select File|New Project. Select Visual Basic 2005 as your language, Windows for the Project Type, and Windows Application as the Template.
  4. Name your project "UsingMyBlogs."
  5. In the Solution Explorer, right click on the UsingMyBlog project and select Add|New Item...
  6. In the Templates List, scroll down until you get to My Templates and select My.Blogs. Click Add.
  7. In Solution Explorer, notice that a file called MyBlogs.vb has been added to your project.
  8. In Solution Explorer, double-click on the My Project folder and select the References tab. Note that you now have a reference to the MyBlogs.dll. This was done for you by adding the My.Blogs template to your project.
  9. If your reference was not made correctly, you'll need to set it up manually. Save the project and copy the MyBlogs.dll to the debug/bin folder and add a reference to MyBlogs.dll using the My Projects folder.
  10. Double-click on Form1.vb in the Solution Explorer to open it in the form designer.
  11. Drag a DataGridView onto Form1 and set the following properties:
    1. Name = "BlogEntries"
    2. AllowUserAddRows = False
    3. AllowUserDeleteRows = False
    4. ReadOnly = True
    5. SelectionMode = FullRowSelect
  12. Drag a button on the form under the BlogEntries DataViewGrid.
  13. Double-click the button to start writing code behind the ClickEvent.
  14. Type in the following code in the Button1_Click event handler:
    Dim MyFeed As MyBlogs.Feed
    
            MyFeed = My.Blogs.Read("http://blogs.msdn.com/vbteam/Rss.aspx")
    
            Me.BlogEntries.DataSource = MyFeed.Entries
    
  15. That's all the code you need to read from a blog feed and populate the entries into a grid. The Read method returns a Feed object that represents the entries for a given RSS/ATOM/RDF feed at a given URL. The Feed.Entries property returns a BindingList(Of FeedEntry), which allows you to bind the list directly controls like the DataGridView.
  16. Run the application. It should look like the following:
       
    Click here for larger image
    Figure 1. A simple Windows Forms Application using My.Blogs
  17. If you look at the Title column and compare it to the blog entries at http://blogs.msdn.com/vbteam/rss.aspx, you'll note that you have now loaded a live RSS feed into your sample application with three lines of code!
  18. Close the application and add another button to the form. Double-click that button and add the following code to Button2_Click:
    myFeed = My.Blogs.Read("http://blogs.msdn.com/vbteam/Rss.aspx", False, _
            New Date(2005, 7, 1))
    
        Me.EntriesGridView.DataSource = myFeed.Entries
    
  19. You can see that this overload of the Read method takes two arguments. The first is a Boolean for whether you want to download comments for each feed. The second is a date. This allows you to only retrieve entries on or after a certain date. This is useful if you are creating an application that only reads feed entries since the last time you performed a Read. Run the application and click on Button2. Your application should look like this:
       
    Click here for larger image
    Figure 2. A Simple Windows Forms Application Reading Feeds from A Date
  20. Only entries dated on or after 7/1/2005 were returned. Close the applications.
  21. Drop another button onto the form and add the following code to the Button3_Click event handler.
    Private MyFeed As MyBlogs.Feed
    
        Private Sub Button3_Click(ByVal sender As System.Object, 
    ByVal e As System.EventArgs) Handles Button3.Click
            MyFeed = My.Blogs.Read("http://blogs.msdn.com/vbteam/Rss.aspx", True)
    
            Me.BlogEntries.DataSource = MyFeed.Entries
        End Sub
    
  22. Note the promotion of MyFeeds to a module lever variable. Also note that we're using yet another overload of My.Blogs.Read that accepts the feed URL as well as a Boolean for retrieving feed comments. We've set it to True in order to retrieve comments.
  23. Add another DataGridView to Form1 and place it under the buttons. Set the following properties:
    1. Name = "BlogEntryComments"
    2. AllowUserAddRows = False
    3. AllowUserDeleteRows = False
    4. ReadOnly = True
    5. SelectionMode = FullRowSelect
  24. Right-click on Form1 and select View Code. Add a new event handler for the BlogEntries control by selecting Blog_Entries in the Class drop down and SelectionChanged in the method drop down. You should have a new event handler called BlogEntries_SelectionChanged. Add the following code:
    Dim SelectedEntry As MyBlogs.FeedEntry = 
    MyFeed.Entries(BlogEntries.CurrentRow.Index)
    
            If SelectedEntry.Comments IsNot Nothing Then
                Me.BlogEntryComments.DataSource = SelectedEntry.Comments.Entries
            End If
    
  25. Run the application. It should look like the figure below.
       
    Click here for larger image
    Figure 3: Reading Feeds and Their Comments
  26. When you select an entry in the entry grid that has comments associated with it, the comments show up in the BlogEntryComments grid. Your application is now reading blog entries and their comments from a RSS feed. Close the application.
  27. MyBlog supports posting to blogs as well. In order to post to a blog you'll need the following information:
    1. The blog URL.
    2. The ID you use to sign in to that blog.
    3. The password you use to sign in to that blog.
  28. Add another button to the form and double-click on the button to create the Button4_Click event handler. Add the following code:
    My.Blogs.PublishEntry(_
            MyBlogs.PublishFormat.CommunityServerViaMetaWebLogAPI, _
        "http://myblogserver/myblogid", "myblogid", "password", _
            "Testing via UsingMyBlogs", "This is the entry posted " + _
            "from trying out MyBlogs!")
    
        MyFeed = My.Blogs.Read("http://myblogserver/myblogid/rss.aspx", True)
    
        Me.BlogEntries.DataSource = MyFeed.Entries
    
  29. Run the application and click on Button4. When the BlogEntries DataGridView is populated, you'll see the blog entry you posted using My.Blogs. It may take a few minutes for the new post to show up. The first argument you pass to PublishEntry is a value from the PublishFormat Enum, telling My.Blogs what publish format you're going to use to post the entry. More on that later. Close the application.
  30. MyBlogs supports reading and writing OPML lists of blog feeds. OPML is an XML schema for managing outlines, such as groups of blog feed addresses. A sample OPML file, appropriately named sample.opml, is supplied in the root of the sample code. Copy it to the \bin\debug directory of UsingBlogs.
  31. Next, drop another button onto Form1 and add an event handler by double-clicking on the button.
  32. Add the following code to the Button5_Click event handler.
    Dim SampleBlogs As Generic.List(Of MyBlogs.BlogGroup) = My.Blogs.ReadOpml( _
            My.Computer.FileSystem.CurrentDirectory + "\" + "sample.opml")
    
        Dim SampleBlogInfo As MyBlogs.BlogInfo = SampleBlogs(0).Item(0)
    
        myFeed = My.Blogs.Read(SampleBlogInfo.FeedUrl)
    
        Me.EntriesGridView.DataSource = myFeed.Entries
    
  33. This code deserves some explanation. OPML files allow you to group information about blog feeds into groups. My.Blogs reflects that grouping by returning a List(Of MyBlogs.BlogGroup) that you can use to get individual instances of the MyBlogs.BlogInfo class, which provide information about an individual feed (such as its URL). The code above reads the OPML file, uses the first BlogInfo to get a feed URL and then loads the feed into the EntriesGridView.
  34. Run the application. You will see the feed entries for the first entry of the OPML file in the DataGridView. Close the application.
  35. Finally, My Blogs allows you to write OPML files as well. Drop another button onto Form1 and double-click on the form to add an event handler. Add the following code to Button6_Click.
    Dim SampleBlogs As New Generic.List(Of MyBlogs.BlogGroup)
    
            Dim MyBlogGroup As New MyBlogs.BlogGroup
            Dim MyBlogInfo As New MyBlogs.BlogInfo()
    
            MyBlogInfo.FeedUrl = "http://blogs.msdn.com/vbteam/Rss.aspx"
            MyBlogInfo.Title = "VB Team Blog"
            MyBlogInfo.Url = "http://blogs.msdn.com/vbteam"
    
            MyBlogGroup.Add(MyBlogInfo)
            SampleBlogs.Add(MyBlogGroup)
    
            My.Blogs.WriteOpml(SampleBlogs, My.Computer.FileSystem.CurrentDirectory + "\" + "WriteSample.opml")
    
  36. Just like the last example, we use a MyBlogs.BlogInfo class to store the info about a feed. We then add that BlogInfo to a BlogGroup and use the My.Blogs.WriteOpml method to write the OPML file to disk. Open the OPML file from the \bin\debug directory to get an idea of what OPML looks like.
Congratulations! In only a few minutes, and with only a few lines of code, you've used My.Blogs to write code to perform common blog feed operations in code.

Using My.Blogs Windows Form Walkthrough

Before we take a look at how My.Blogs works under the hood, let's take a look at what an application based on My.Blogs and see what it can do. Follow these steps to get started using an application based on My.Blogs.

Reading Feeds

  1. Under the directory where the sample code was unzipped, open \My.Blogs Windows Sample\MyReader.sln.
  2. Run the application.
  3. MyReader is based on a communication application starter kit included with this sample, \Misc. Sample Files\Communication Application.vsi, which allows you to quickly create applications with an Office Outlook 2003 look and feel.
  4. Start using MyReader by subscribing to some blog feeds. You can do this through an OPML file or by entering a URL for an RSS, ATOM, or RDF feed.
    1. OPML—You can load feeds from another reader by exporting an OPML file of feeds and importing it into MyReader. For example, select File/Import Subscriptions and select the path of the sample.opml file supplied in the root of the sample code directory.
    2. By URL—Select File/New Feed and enter the URL of a valid RSS, ATOM, or RDF feed (such as http://blogs.msdn.com/vbteam/rss.aspx).
  5. At this point, you should see your feed(s) in the Feeds list box. Select a feed by clicking on it in the Feeds list on the left side of the UI and then select an entry in the right side of the UI. You will see the contents of the entry in the bottom half of the entry pane.
  6. You can also group your feeds to make easier to manage. Select File/New/Group... and give the group a name. To add a feed to the group, select the group and add the feed as you did above.

Posting to Blogs

  1. To post entries to your blog, you need to provide some key information to be used by the My.Blogs code running in MyReader. Select the Blog Info... toolbar button to supply the necessary information. Enter the following information based on your blog:
    1. User ID—This is the user ID that you use to log into your blog server.
    2. Password—The password you use to log into your blog server.
    3. Publish Protocol—How you'd like to post to your blog server.
      • Community Server using a Blog URL: If you are using Community Server (http://www.telligent.com/), you can just enter your blog URL (for example http://blogs.msdn.com/vbteam) and My.Blogs will calculate the service endpoint for you. Select this option in order to post using that method.
      • Metablog API through a Service URL—If you are using a server other than Community Server that supports the MetaBlog API, enter the Metablog API service URL here. For example, http://blogs.msdn.com/metablogapi.aspx. Select this option in order to post by means of this method.
    4. Blog URL/Service URL—The URL that corresponds to the selection you made above.
    5. Blog ID—For the Metablog API selection, you need to supply the blog ID. Most often, it's the directory name of your blog. For example, if your blog is http://blogs.msdn.com/vbteam, your Blog ID would be vbteam.
  2. After providing information about your blog, you're ready to post an entry. Click the Write to Blog button. The reading pane changes into a blog entry pane. Enter the title of the entry and the content of the entry and click the Publish button. If you entered your blog information correctly, you will be able to go to the blog (or the feed if you've added it to MyReader) and see the post.
There are some other great samples included with MyBlogs. Take a deeper look at the MyReader.sln in order to see how to consume blog feed functionality in a Windows Forms application. In the "My.Blogs Web Sample" folder you'll see a sample Web site that uses My.Blogs to provide blog reading functionality to an ASP.NET 2.0 application. In the "My.Blogs Office Outlook Add-In" folder there is an example of using My.Blogs in order to provide blog functionality within Outlook 2003 using Microsoft Visual Studio 2005 Tools for the Microsoft Office System. One thing that you'll notice is that the design of My.Blogs allows each application, regardless of whether the application is a Windows Forms application, Web application, or Outlook Add-In, to provide blog feed access with some simple calls to My.Blogs.

Understading My.Blogs

In order to understand how My.Blogs works, you really need to look at three things; how My.Blogs extends the My feature, how the Blogs class provides the implementation of My.Blogs, and how publishing and reading are accomplished.

Adding Blogs to the My Feature.

If you're new to Visual Basic 2005, you're probably new to the My feature. My provides quick access to common development tasks and common information through an easy-to-use object hierarchy. The great thing about My is that you can extend it using classes of your own design.
To access the Blogs class (which provides the actual implementation) through the My feature, you need to add a key piece of code to the consuming application. In the previous sample, that key piece of code was provided in the MyBlogs.vb file when we added the MyBlogs template to the project.
Namespace My
    
    <Global.Microsoft.VisualBasic.HideModuleName()> _
    Module MyBlogs
        
        Private _blogs As New ThreadSafeObjectProvider(Of Global.MyBlogs.Blogs)

        Public ReadOnly Property Blogs() As Global.MyBlogs.Blogs
            Get
                Return _blogs.GetInstance()
            End Get
        End Property

    End Module

End Namespace
This code is pretty straightforward. Extending My is mainly a matter of adding a property to the My namespace. That property returns an instance of the Blogs class wrapped in a ThreadSafeObjectProvider, which provides a thread safe instance of Blogs to each request. See the article "Simplify Common Tasks by Customizing the My Namespace" for more details (a link to the article is provided).

The Blogs Class

Let's take a look at the Blogs class to see the actual implementation of the blog posting and feed reading functionality provided in My.Blogs. Open the "My.Blogs.sln" solution in the "My.Blogs DLL Source Code" folder. Take a look at the class diagram ClassDiagram1.cd and look at the Blogs class.
Click here for larger image
Figure 4. The Blogs Class Diagram
As you'd expect, the implementation mimics what is provided by My.Blogs. If you look at the methods themselves in code, you'll notice one thing of interest. The Blogs class uses a Factory-like pattern in order to provide the function of reading feeds using varied feed formats.
Let's take a look at the Read method. We'll examine the simplest form of the Read method, since all the other overloads follow the same pattern. Open the MyBlogs.vb file in the solution to see the Blogs class. The implementation of Read is here:
Public Function Read(ByVal Url As String) As Feed
        Return MyBlogs.Feed.Read(Url, False)
    End Function
If you follow this to the Feed class in Feed.vb, you'll note that the Feed class gets the feed XML from the URL passed to Blogs.Read() and returns an instance of a class that represents the specific feed format.
Public Shared Function Read(ByVal url As String, _
        ByVal loadComments As Boolean, ByVal subscriptionDate As Date) As Feed

        Dim format As FeedFormat
        Dim feed As Feed = Nothing
        Dim xml As XmlReader = Nothing
        Dim client As New System.Net.WebClient()

        Dim stream As IO.Stream = Nothing

        Try
            stream = client.OpenRead(url)
            xml = XmlReader.Create(stream)
            format = GetFeedFormat(xml)

            Select Case format
                Case FeedFormat.Atom
                    feed = New Atom.AtomFeed
                    feed.Load(xml)
                Case FeedFormat.RDF
                    feed = New Rdf.RdfFeed()
                    feed.Load(xml)
                Case FeedFormat.RSS
                    feed = New Rss.RssFeed()
                    feed.Load(xml, subscriptionDate)
            End Select
        Catch e As Exception
            Throw e
        Finally
            If xml IsNot Nothing Then
                xml.Close()
            End If
            If stream IsNot Nothing Then
                stream.Close()
            End If
        End Try

        If feed IsNot Nothing Then
            feed.ShouldDownloadComments = loadComments
            feed.LoadComments()
            feed.FeedUrl = url
        End If

        Return feed

    End Function
You can see the relationship between Feed and the different subclasses of Feed that provide specific feed implementations in the following diagram.
Click here for larger image
Figure 5. Feeds and FeedEntry Diagram
FeedEntry provides the implementation of individual entries in a feed and works the same way.
Extending Read to support more formats is just a matter of adding a value to the FeedFormat Enum, providing a new subclass of Feed and FeedEntry, as well as providing the specific implementation of that format.
Publish works in the same way. Here is the code from the Blogs class that provides the basic Publish implementation. When calling PublishEntry, you need to pass a value from the PublishEntry Enum so the right publish implementation class is created.
Public Sub PublishEntry(ByVal Format As PublishFormat, _
        ByVal BlogURL As String, ByVal UserName As String, _
        ByVal Password As String, ByVal Title As String, _
        ByVal Description As String)

        PublishProvider.PublishEntry(Format, BlogURL, UserName, _
            Password, Title, Description, True)
    End Sub
Again, the PublishProvider class provides the actual implementation by using the PublishFormat Enum to dictate what class is actually created to do the actual publishing.
Public Shared Sub PublishEntry(ByVal format As PublishFormat, ByVal 
Address As String, ByVal UserName As String, ByVal Password As String, 
ByVal Title As String, ByVal Description As String, ByVal IsNewEntry As Boolean)
        Dim provider As PublishProvider = PublishProvider.Create(format)
        provider.PublishEntry(Address, UserName, Password, Title, Description)
    End Sub


    Friend Shared Function Create(ByVal format As PublishFormat) As PublishProvider
        'Create http request and send it to server
        Dim provider As PublishProvider = Nothing
        Select Case format
            Case PublishFormat.Unknown
                Throw New System.Exception("PublishFormat.Unknown")
            Case PublishFormat.MetaWebLogAPI
                provider = New MetaWebLogPublishProvider()
            Case PublishFormat.CommunityServerViaMetaWebLogAPI
                provider = New MetaWebLogPublishProvider()
            Case Else
                Throw New System.Exception()
        End Select
        Return provider
    End Function
If you look at ClassDiagram1.cd again, you'll see that PublishProvider follows the same pattern as the Feed class.
Click here for larger image
Figure 6. Publish Provider Diagram
Currently, only the MetaWeblog API is supported for Telligent's Community Server using the MetaWebLogPublishProvider subclass, but you could easily extend the PublishProvider to support other APIs or other servers by providing a new subclass with a new implementation.

Conclusion

The My.Blogs sample is great from a couple of points of view. First, it provides a great example of how you can extend My to provide a very clean and intuitive way of accessing common functionality throughout your code. Second, it's a great sample application that you can easily extend in order to build a full featured blog utility, whether you want to work with blogs on your desktop, from a browser or even inside Outlook. Enjoy!