Posts Tagged ‘IdeaPipe’

June 6th, 2008

MVC + Facebook == Wonderful Development Platform

Just recently I started experimenting with the ASP.NET MVC Framework and the Facebook Development Platform, it has been a very bumpy road, but I have ironed out some major issues that I would like to share with you today. I will start with a little history of what I am trying to do. For about a month and a half I have had one of my IdeaPipe interns, Dimitry, experimenting with creating a FBML (Facebook Meta Language) Application with MVC. MVC is an ideal platform for FBML because with MVC you have total control over your markup which is needed to have a lean FBML application. I am not going to go in to the differences of developing an FBML vs IFrame Facebook Application, because that information is easily found with a Google Search. What I am going to talk about is the hurdles I overcame and the custom software I had to develop to get MVC working smoothly with Facebook.

In my last post on the subject I was using the Facebook Developer Toolkit, however because of various implementation problems that were at the foundation of the software when working with MVC, I moved to Facebook.NET which is a object based model for implementing the Facebook Session instead of an inheritance model. What you will need in order to get started is:

One of the problems I ran into was creating a Facebook Session from my Action Method. To remedy this issue I created a FacebookAttribute that is an ActionFilterAttribute and a FacebookWebSession based off of the work done on Facebook.NET.

FacebookAttribute

The FacebookAttribute is added to your Action Methods and will look like the following:

[Facebook(ApplicationName = "IdeaPipe")]
public ActionResult SomeAction(FacebookService facebookService, FacebookSession facebookSession, int myOtherVariables)
{ … }

As you can see the FacebookAttribute just attaches to the Action Method and you just have to specify your ApplicationName that you want to instantiate. The FacebookAttribute also passes in a FacebookService and FacebookSession object for use in your method. The other keys get set in your Web.Config as any standard Facebook.NET application would.

<facebook>
    <application name="IdeaPipe" apiKey="1234" secret="5678" type="GlobalApplication" />
</facebook>

The magic behind this attribute is pretty simple.

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
	FacebookApplicationSettings settings = FacebookSection.GetApplication(ApplicationName);

	ApplicationKey = ApplicationKey ?? settings.ApiKey;
	Secret = Secret ?? settings.Secret;

	FacebookWebSession session = new FacebookWebSession(ApplicationKey, Secret);
	session.Initialize(HttpContext.Current);

	FacebookService service = new FacebookService(session);

	if (filterContext.ActionParameters.ContainsKey(ActionParameterFacebookSession))
		filterContext.ActionParameters[ActionParameterFacebookSession] = session;

	if (filterContext.ActionParameters.ContainsKey(ActionParameterFacebookService))
		filterContext.ActionParameters[ActionParameterFacebookService] = service;
}

Download: FacebookAttribute.cs

FacebookWebSession

The FacebookWebSession was developed out of necessity because the only other FacebookSession objects in Facebook.NET are strongly tied to a WebForms Control that couldn’t be created as easily as I did in the FacebookAttribute. I am going to fore go the source code since much of this is a copy, paste, and rearrange from the Facebook.NET source. Plus much of it is just boring if-then-else statements that go on for awhile and just do a technical setup from the query string fields.

Download: FacebookWebSession.cs

FacebookSection

This is the file that I had to change the one method from internal to public so that I could get the information contained in the Web.Config configuration for my application. Note this file will not be necessary in the future if my changes get accepted in to the Facebook.NET source tree.

This file replaces the \Web\Configuration\FacebookSection.cs of the Facebook.NET source.

Download: FacebookSection.cs
Download: Facebook.NET Binaries For MVC

So that is all that you should need in order to start working with Facebook Applications in MVC. Note that it is still a good idea to include the FacebookApplication control on your pages because it is still needed. The primary goal of the source code above was to allow the use the the FacebookSession in the Action methods. If you have any questions please post them below.

Tags: , ,

Posted in ASP.NET, C#, How To, Programming | kick it on DotNetKicks.com | Bookmark | View blog reactions | 5 Comments »

June 5th, 2008

Give Your ASP.NET Applications Velocity

Scaling ASP.NET Application just got easier with a new technology that Microsoft has just released that they have dubbed codename “Velocity”. This product is still in the early stages of development, but it is meant as a direct competitor against memcached. If you are not familiar with memcached, here is how it is described in Wikipedia:

memcached (pronunciation: mem-cache-dee) is a general-purpose distributed memory caching system that was originally developed by Danga Interactive for LiveJournal, but is now used by many other sites. It is often used to speed up dynamic database-driven websites by caching data and objects in memory to reduce the number of times the database must be read. Memcached is distributed under a permissive free software license.

So basically it allows you to create a distributed memory cache across your server farm, that allows any computer in the server farm to access the data in the cache. So there is no more issues with storing session data on server farms, or worrying about setting up common SQL stores of temporary data. This is also very practical for reducing database stress on Web 2.0 sites, many of the top Web 2.0 sites use this to reduce reads on the database.   The biggest user of memcached to date is Facebook.  This diagram below gives a basic idea of how distributed caching works.

Diagram of Velocity

There have been many Open Source projects for getting memcached working on C#, and most have been pretty successful, but because memcached was designed for the UNIX environment, porting memcached to a Windows Service has always lagged behind the actual releases of the required libraries to get memcached working. Enter Velocity, as the Velocity team describes:

Velocity is intended to provide distributed caching (in memory) for all .NET applications – from enterprise scale to web-scale. We believe that there are many applications that need a distributed caching mechanism, and that there is, therefore, a need for distributed caching as a core part of the .NET platform. We expect to have more integrated support for this functionality with other parts of the .NET platform in our upcoming releases.

There is also a pretty nice Velocity writeup on MSDN that goes in depth about how Velocity works as well as providing some basic code examples on how to get data into and out of your Velocity Cache. The current set of features looks pretty nice, and I can’t wait for Velocity to become more stable so I can introduce it in to the IdeaPipe mix.

Here is a breif overview of the Current Features:

  1. Support for different cache types, partitioned and local
  2. Support for different client types, simple and routing
  3. Load Balancing & Dynamic Scaling
  4. ASP.Net Integration, currently there is only a Session Provider
  5. Key and Tag based Access

And Beyond

  1. Availability - support for Failover when machines go down
  2. Replicated Cache - another cache type
  3. Embedded Topology - run the cache embedded within you application instead of as a cache service
  4. Notifications - Get notified when a object in the cache is updated
  5. Consistency Models - Support for both weak and strong consistency when doing reads/writes
  6. Native client access to the cache service (E.g - PHP, C++ etc)
  7. Manageability & Administration

Tags: , , , , , ,

Posted in ASP.NET, C#, Review | kick it on DotNetKicks.com | Bookmark | View blog reactions | 5 Comments »

May 27th, 2008

ASP.NET MVC Preview 3 Released

The ASP.NET MVC Team has released an refresh of MVC. To all those that are interested the new Preview Release is posted at:

http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=13792

The new release contains many new features over the 2nd Preview Release and the Interim Release from a month a half ago. In this post I am going to outline the features that are new from the Interim Release to Preview Release 3.

Action Method and Result Changes

As you remember from the previous release, you are now required to return an ActionResult. Many of the ActionResults were renamed to the following types:

  • ViewResult: Renders the specified view to the response.
  • EmptyResult: Does nothing. Returned if the action method must return a null result.
  • RedirectResult: Performs an HTTP redirect to the specified URL.
  • RedirectToRouteResult: Given some routing values, uses the routing API to determine the URL and then redirects to that URL.
  • JsonResult: Serializes the specified ViewData object to JSON format.
  • ContentResult: Writes the specified text content to the response.

There were also new helper methods added to the Controller class for these new ActionResult types.

  • View: Returns a ViewResult instance.
  • Redirect: Redirects to the specified URL. Returns a RedirectResult instance.
  • RedirectToAction: Accepts an action (and optionally a controller) and redirects to another controller action. Returns a RedirectToRouteResult instance.
  • RedirectToRoute: Redirects to a URL that is determined by the routing API. For example, this method lets you specify a named route. Returns a RedirectToRouteResult instance.
  • Json: Returns a JsonResult instance.
  • Content: Sends text content to the response. Returns a ContentResult instance.

One of the more interesting ActionResults is the JsonResult which returns a serialized form of your ViewData object using the JavaScriptSerializer class. I don’t know why they didn’t use the DataContractJsonSerializer, but the team probably had their reasons.

View Data Changes

There is also the addition of implicit conversion for Action methods that return anything other than an ActionResult.

If an action method returns null (or has a return type of void), the action invoker implicitly provides an EmptyResult instance, which does nothing. If an action method returns anything other than an ActionResult instance, the action invoker calls ToString(CultureInfo.InvariantCulture) on the instance and then wraps the return value with a ContentResult object, which writes the content to the response.

A Model property was added to ViewDataDictionary. For ViewDataDictionary, the type of this property is System.Object. For ViewDataDictionary<T>, the type of this property is T.

The ViewData property of ViewPage<T> is no longer replaced by T. In Preview 2, the MVC framework replaced the ViewData property with the specified strongly typed view data (that is, the T in ViewPage<T>). In Preview 3, the Model property of ViewData is set to the instance of type T.

Route Changes

An IRouteConstraint interface was added.

If a constraint value is specified as a string, the string is interpreted as a regular expression. If the constraint value is specified as an instance of IRouteConstraint, route processing calls the Match method of IRouteConstraint.

A new HttpMethodConstraint type was added, which changes the way you constrain routes on the HTTP method. Unlike previous versions of ASP.NET routing, in this release, the constraint name “httpMethod” is no longer special. Instead, use the HttpMethodConstraint to add a constraint based on HTTP verbs. The following example shows how to use the HttpMethodConstraint type.

routes.MapRoute(
    "route-name",
    "{controller}/update",
    new {action = "update"},
    new {httpMethod = new HttpMethodConstraint("PUT", "POST")}
);

Other Changes

The versions of the System.Web.Abstractions and System.Web.Routing assemblies that are included with the MVC project template have been changed to version 0.0.0.0. The versions that are included in the Preview 3 release are newer than those that ship in the .NET Framework version 3.5 Service Pack 1 Beta. Therefore, they were assigned a private version number so that no conflict occurs between the assemblies in this release and the assemblies installed by the .NET Framework 3.5 SP1 Beta release.

And a ton of bug fixes

So in conclusion the ASP.NET MVC team has released another great release. Many of the new features have been on the request list of many of the active MVC developers. I still have to try out a couple of my requests to see if they are included, but I will make sure to provide a new post with those details.

Update: ScottGu has just released his notes on the MVC Preview Release 3, which I must admit are more in depth than my own.

Update 2: I have also updated IdeaPipe to reflect the latest PR3 changes. It took me about an hour to go through all my code and then test it. I am pleased to report the default page is now working, so that you don’t need the Default.aspx page anymore.

Tags: ,

Posted in ASP.NET, C#, Programming, Review | kick it on DotNetKicks.com | Bookmark | View blog reactions | 1 Comment »

May 23rd, 2008

How to create a non-Native jQuery event

Today I had the need to create a custom event using jQuery, in order to launch a customized form validation event from a global submit event. I did this so I could focus in on the first form field that had an error. My event from the global.js script, that is included on every page of IdeaPipe, looks like this:

$("form").submit(function () {
	var valid = $(this).validate();

	// if the form didn't validate then focus the input on the first error
	if (!valid)
		$(this).find(":input[error]:first”).focus();

	return valid;
});

This is pretty standard jQuery. What this code above does is set a custom function for the submit event for any <form /> tag on the page. The submit event will only be allowed to continue if a return value of true is returned from the function.

I was able to create this custom jQuery event with the following code:

jQuery.fn.extend({
	validate: function (fn) {
		if (fn) {
			return jQuery.event.add(this[0], “validate”, fn, null);
		} else {
			var ret = jQuery.event.trigger(”validate”, null, this[0], false, null);

			// if there was no return value then the even validated correctly
			if (ret === undefined)
				ret = true;

			return ret;
		}
	}
});

There are two different states to this method. Primarily because in JavaScript all parameters are optional for functions. So the two states of this function are:

  • validate(fn) - sets the event
  • validate() - fires the event

An example of setting the event is:

$("form.user-login").validate(function () {
	var userNameValid = ValidateLoginUserName();
	var passwordValid = ValidateLoginPassword();

	return userNameValid && passwordValid;
});

In this example the form is valid if both the login user name and password validate.

An example of using the event is the same as the method above.

$("form").submit(function () {
	var valid = $(this).validate();
	// do some stuff
	return valid;
});

This may not be the standard bind() and trigger() that most jQuery programmers are use to, but I needed an event that would return a value of true or false, so that I my submit event handler knows if it should focus on errors or continue the submit process.

Hope everybody finds this useful.

Tags: , ,

Posted in How To, JavaScript | kick it on DotNetKicks.com | Bookmark | View blog reactions | 1 Comment »

May 13th, 2008

2 Easy Steps To Turn Your Blog Into An OpenID Gateway

Many of you probably have heard of OpenID, but have never had a chance to use it. However, I predict that most of you reading this blog will have used it by the end of the year. I can make this prediction with an almost 100% certainty because there is a growing movement behind it that has many big players actively buying developing and integrating their platforms with the OpenID protocol. Some of the biggest players are:

  1. AOL
  2. Yahoo
  3. Google
  4. Microsoft

OpenID according to the official OpenID site is explained as the following:

OpenID eliminates the need for multiple usernames across different websites, simplifying your online experience.

You get to choose the OpenID Provider that best meets your needs and most importantly that you trust. At the same time, your OpenID can stay with you, no matter which Provider you move to. And best of all, the OpenID technology is not proprietary and is completely free.

To facilitate my prediction, of most of you using OpenID by the end of the year, I am going to give you 2 easy steps to turn your blog, or any website, in to a OpenID gateway. That will work for OpenID 1.0, 1.1, and 2.0 versions of the protocol.

The first thing you need to turn your blog into an OpenID Gateway is an account with an OpenID provider, my favorite is MyOpenID, because of the abundance of features offered, but more providers can be found on http://openid.net/get/.

The second thing is pretty easy to accomplish and just involves adding some meta data to your HTML header. Just take the following snippet and replace {youraccount.myopenid.com} with your OpenID provider URL that was provided to you (there are 3 places in the snippet to replace the URL):

  <link rel="openid.server"
        href="http://www.myopenid.com/server" />
  <link rel="openid.delegate"
        href="http://{youraccount.myopenid.com}/" />
  <link rel="openid2.local_id"
        href="http://{youraccount.myopenid.com}" />
  <link rel="openid2.provider"
        href="http://www.myopenid.com/server" />
  <meta http-equiv="X-XRDS-Location"
        content="http://www.myopenid.com/xrds?username={youraccount.myopenid.com}" />

After that is done you just need to type your blogs/websites URL in to any OpenID text box. Most of the OpenID authentication text boxes look like the following (with the little OpenID logo in the left of the text box):

You probably already have an OpenID authentication account that you can use right this moment. Some of the common ones that most internet users have and don’t even realize are (just replace {username}):

  • Yahoo: http://yahoo.com/
    Flickr: http://flickr.com/
    To enable your yahoo account to use OpenId visit http://openid.yahoo.com/
    Also while there check out their gallery of OpenID enabled applications
  • AOL: http://openid.aol.com/{username}
  • Blogger: http://{username}.blogspot.com/
  • Live Journal: http://{username}.livejournal.com/
  • WordPress: http://{username}.wordpress.com
  • Technorati: http://technorati.com/people/technorati/{username}

So have fun, and check out IdeaPipe at the end of this month, we will be officially supporting OpenID.

Tags: , ,

Posted in Portfolio, Programming, Review | kick it on DotNetKicks.com | Bookmark | View blog reactions | 4 Comments »

May 7th, 2008

Whats the idea? The reason we implemented IdeaPipe

When we first came up with the idea for IdeaPipe (no pun intended), we saw a need to fill a void in the social networking landscape. There are countless sites dedicated to connecting friends, classmates and business associates, sites that provide opinions and commentary around a specific topic and even sites that simply point to other sites, but there were few if any that enabled individuals or groups to share their ideas for the purposes of gathering feedback, collaborating or simply being heard.

There is nothing more powerful than an idea whose time has come.
-Victor Hugo

For decades, corporations have relied on costly market research initiatives to gather opinions and insights as a means of measuring customer satisfaction and developing product road maps. Each day, we see politicians like Hilary Clinton, Barack Obama and John McCain floating their ideas in the form of trial balloons only to wait on daily polls to determine voter’s reactions. By building upon this concept and giving everyone a voice, not just large corporations, we’ve created a platform that empowers individuals to have their ideas and opinions heard AND measured on everything from politics to their favorite products.

With your ideas, in concert with the collaboration of others, innovation will flourish. In fact, the world as we know it was built upon the unique ideas of individuals and it is exactly that which we hope to promote. Let’s face it… the solution to the energy crisis, global warming, and every other problem that plagues mankind, exists deep within the minds of individuals and it is our goal to assist in getting them out.

Ok, enough of the Mom and apple pie! IdeaPipe was created as a free service where individuals and/or groups can post their ideas on a variety of topics. Once posted, others will give your idea either a hype (i.e. “thumbs up”) or gripe (i.e. “thumbs down”) vote and optionally comment on the idea. For more specific information on how it works, visit our page on how it works! Sharing your ideas on IdeaPipe is a great way to:

  • Gain valuable insight into how others perceive your ideas
  • Meet and collaborate with other likeminded individuals
  • Gain customer feedback
  • Improve customer loyalty
  • Impress your friends!

IdeaPipe is available to anyone who has a thought or idea. On top of that; within the coming few weeks, we’ll be rolling out new functionality that will enable you to even create your own public or private group. Individuals or companies large and small will even be able to create their own IdeaPipe and linked to it from, Facebook, MySpace or any other web site. And yes, we’re even going to eat our own dog food! Let us know what you think the future of IdeaPipe should look like by posting your ideas about what functionality you would like to see in the future!

So create an account and get started today. Time is wasting to get your ideas heard.

Tags: ,

Posted in Personal, Portfolio, Review | kick it on DotNetKicks.com | Bookmark | View blog reactions | No Comments »

April 28th, 2008

Introducing Idea Pipe

I have been working on this new social networking website that is based around the collaboration and sharing of ideas. I have talked about this project in the past, in very vague details, but today I have decided to open the curtains and give everybody a look.

http://www.ideapipe.com

Currently there are a couple websites out there that are doing the same thing, but in a more focused way for their specific business. One of the examples of these focused websites for sharing of ideas is Dell Idea Storm. In the case of Dell each of the users go to their website and submit ideas on how they can improve Dell’s products. The platform has worked really well for Dell, they seem to be getting a positive response from their community of users. It has led to them introducing a couple of products that they probably wouldn’t have, such as Ubuntu as an alternate to Microsoft Windows, if there wasn’t such an overwhelming support for this install option.

Idea Pipe was born about 7 months ago, when I realized that this type of platform would be useful to businesses, projects, and people of all shapes and sizes. Especially the ones that wouldn’t be able to pay the Salesforce.com Tax. Idea Pipe has actually been released for about a month now, however I was waiting to announce it officially until we had support for groups. Groups are a way that anybody, with an Idea Pipe account, can create their own personalized Idea Pipe, that provides all the same features and functionality as Dell’s Idea Storm, but at no charge to the group owners.

To kick off this announcement I created a group so that my readers can share and collaborate on ideas for me to post about in the future, on this blog, that will interest you my readers: http://www.ideapipe.com/groups/coder-journal

This site is still new and like any new site you will probably have suggestions on how to improve the site or the architecture, so please submit them to: http://www.ideapipe.com/groups/pipeline

If you happen to find any bugs, please send them to bugs@ideapipe.com.

Tags:

Posted in Personal, Portfolio, Review | kick it on DotNetKicks.com | Bookmark | View blog reactions | No Comments »

April 13th, 2008

Coder Journal’s MVC Toolkit

Today I decided to release a toolkit that I have been building over the past couple of months. Most of the code in the toolkit is related to MVC. Here is a list of the features:

ActionFilterAttribute’s

  • HttpPostOnlyAttribute
    Only allows POST to be made against the action.
  • CacheAttribute
    Sets the action’s response as cacheable.
  • CompressAttribute
    Compresses the action’s response using GZip or Deflate encoding.
  • ServiceAttribute
    Marks an action as able to provide the ViewData as JSON, XML, or JSONP.
  • ServiceOnlyAttribute
    Marks an action as only able to provide the ViewData as JSON, XML, or JSONP, that means no HTML.
  • ExceptionHandlerAttribute
    Handles any exceptions thrown from an action, and redirects it to another page, or another action.
  • CaptchaAttribute
    I did a whole post on providing a CAPTCHA for your MVC action.
  • AllowedHttpMethodsAttribute
    Only the HTTP methods entered in to this filter are allowed for your action. Available HTTP methods are OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, and CONNECT.

ViewEngines’s

  • ServiceViewEngine
    This view engine provides the serialization of the ViewData to JSON, XML, or JSONP. It is set when one of the following is requested from the ServiceAttribute above.

Route’s

Method Extensions

  • Redirect extends HttpResponse
    I have had a long standing discontent with the Redirect method of the ASP.NET. I have talked about good use of HTTP Status Codes before. There are at least 3 status codes that you want to consider before choosing a response status code of 302. Just to reiterate my post on the subject use 303 to redirect from a form POST, use 307 when you want to redirect to a page that is going to change with each request, use 301 if you want to permanently redirect one URL to another.I created the, Redirect, extension method on HttpResponse so that the status code could be set for the redirect.

View Source: Coder Journal MVC Toolkit Source
Download Binary: Coder Journal MVC Toolkit Binary

Read the rest of this entry »

Tags: , ,

Posted in ASP.NET, C#, Personal | kick it on DotNetKicks.com | Bookmark | View blog reactions | 9 Comments »