Listed below are some of my recent findings for the best JavaScript Clipboard and Flash Detection scripts for web developers.

Clipboard Plugins

Developers can provide end-users the ability to copy text to their clipboard (eg. mimic Ctrl+C action).

ZeroClipboard
This is the most active clipboard project available.  Most robust, lots of options and active community.
http://code.google.com/p/zeroclipboard

Example of ZeroClipboard with multiple per page
http://www.webmasterworld.com/javascript/3901742.htm

zClip jQuery Plugin
zClip Wraps the ZeroClipboard functionality into jQuery and is worth checking out for those using jQuery and seeking a quick clipboard implementation:
http://www.steamdev.com/zclip/

jQuery Clipboard
Another (older) clipboard plugins for jQuery.  These only work prior to the "actionable-effect requirement" in Adobe 10 and works completely differently. *This won’t work with the latest Flash versions*
http://plugins.jquery.com/project/copy
http://plugins.jquery.com/project/clipboard

Detecting Flash

Easily identify if the end-user has Flash capabilities installed on their web browser.

Flash Detect (JavaScript Flash Detection Library)
Doesn’t seem to require a separate SWF file.  Small and easy to implement.
http://www.featureblend.com/javascript-flash-detection-library.html

SWFObject
Another good options for Flash Detection that is very reliable.
http://code.google.com/p/swfobject/wiki/whats_new

Some example code can be found here:
http://stackoverflow.com/questions/159261/cross-browser-flash-detection-in-javascript

jQuery Flash Plugin
Used for embedding Flash movies but also has detection.
http://jquery.lukelutman.com/plugins/flash/

Using ShareThis and want to have a customized version of multiple share buttons on one page?  The ShareThis API developer docs section would have you include a hefty piece of JavaScript wherever you wanted the ShareThis object to occur.  That is not only messy, but not very practical.  I was shocked I couldn’t find anyone that had posted a jQuery tidbit to fix this.  I found one attempt posted in their forums, but no final solution.  The solution below is based on the previous finding and this forum thread.

Be sure to read the developer docs and include the correct ShareThis widget JS file with your publisher Id prior to this code [ something like http://w.sharethis.com/widget/?tabs=web%2Cpost%2Cemail&charset=utf-8&style=default&publisher=(pub-id) ]

What I’ve done is loop through any cases where the sharethis class is present.  Inside the link include all the necessary information in data-* attributes that we pull out using jQuery.

<script type="text/javascript">
$(document).ready(function () {
  SHARETHIS.onReady();
  $("a.sharethis").each(function (index) {
    var id = $(this).attr('data-id');
    var purl = 'http://mydomain.com/posts/' + id
    var ptitle = $(this).attr('data-title');
    var thisobj = SHARETHIS.addEntry({ title: ptitle, url: purl }, { button: false });
    thisobj.attachButton(document.getElementById("sharethis-" + id));
  });
});
</script>

Example customized ShareThis Link

<a class="sharethis" data-id="(uniqueid)" data-title="The Title of This Post" id="sharethis-(uniqueid)">Share</a>

I searched around "Googled around" for a nice jQuery Tag editor, and it took me going through quite a few plugins before I found one that had everything I wanted… which included Autocomplete functionality using jQuery UI core. It looks nice, uses built-in Autocomplete, and has all the tag editor features.  I must note that it works a little different then almost all other tag editor plugins I’ve seen in terms of work flow.  It considers “remove from list” and “delete from list” two separate functions (read this).  This can be very useful, or merely extra work, depending on your implementation on the back-end. Currently it is being actively developed by Oliver Albrecht (aka @webworka) and hopefully it stays in active development! 

jQuery Tagedit
Demo: http://tagedit.webwork-albrecht.de
Code: https://github.com/webworka/Tagedit

image

I’m using it in the revamp for the CouponFollow website which I hope to push into private beta before the end of the month, and roll live shortly after.  I’ll likely use this plugin in future projects as well.

Here are some others that I liked but didn’t make the final cut for this project.

jQuery Tag It!
Link: http://levycarneiro.com/projects/tag-it/example.html
Code: http://github.com/levycarneiro/tag-it
My Notes: Very simple, autocomplete using jQuery UI.  Tagedit is based on this one.

jQuery Tag Editor
Link: http://blog.crazybeavers.se/wp-content/Demos/jquery.tag.editor/
My Notes: Good but no autoComplete. Some CSS overflow issues with large amount of tags.

jQuery Tag Suggestion
Link: http://remysharp.com/2007/12/28/jquery-tag-suggestion/
My Notes:  Good, simple.  Slick auto-complete, but no spacing support.  Older, not actively developed?

I recently had issues where Google was seeing misspellings of a domain names as different websites themselves, and possibly as duplicate content.  The domains were bound to the same web application in IIS and I wanted to fix this without editing the source of the web application itself.

I had a few options, one of which is to use Cantonal URLs, but that would involve editing the web app to some degree.  So before going that way, I wanted to start making permanent redirects to the correct website URL.  The quickest approach I could think of was to create a global redirect as a new web application and reassign all the domain name bindings needed.  So I created a simple MVC 3 Web Application called GlobalPermanentRedirect which effectively takes any page and redirects the path / query to domain specified in the appSettings.

The code is very simple, however I got stumped for a few minutes with Routing, as I forgot about the catch-all parameter using *.  Here’s the code, it’s really only about three lines.

In the routing area (Global.ascx) register the route:

routes.MapRoute(
   "Default", // Route name
   "{*path}", // catch all urls
   new { controller = "Redirect", action = "Index" } // Parameter defaults
);

Create a controller called RedirectController.cs with the following line of code:

public ActionResult Index()
{
	return RedirectPermanent(ConfigurationManager.AppSettings["BaseUrl"] + Request.Url.PathAndQuery.ToString());
}

In web.Config under appSettings:

<add value="http://www.yourmainsite.com" key="BaseUrl" />

Upgrade from ASP.NET MVC 1 to MVC 3

Posted: 31st March 2011 by marc in Programming
Tags: , , , , ,

I came across the need to upgrade from MVC 1 to MVC 3, skipping MVC 2 altogether.  Currently, it doesn’t seem like there are any formal directions coming from Microsoft.  However, I found instructions mentioned in this StackOverflow question.

It appears, as of now, there is a two step process to migrate from MVC 1 to MVC 3:
1) Migrate from ASP.NET MVC 1 to MVC 2 (using this tool)
2) Migrate from ASP.NET MVC 2 to MVC 3 (using this tool)

Things to be wary of…

  • ASP.NET MVC 3 Application Upgrade tool is not compatible with VS 2008
  • It may compile, but jQuery version changes could still break your app on the client-side

I haven’t tried it myself just yet.  Based on what I’ve read, in theory, it should work, but there will likely be minor annoyances and issues to clean up.  If it seems to work the first time, something is really wrong! :)

I’ll post a follow-up once I give it a go.

I was just about to search for a good Url regular expression to check input validation, when I remembered a recent blog post by @srkirkland mentioning Data Annotation Extensions (github).  This extension package allows for additional common use data annotations, such as URL, Email, Credit Card, etc in any .NET 4.0 project. It has been released as a NuGet package so you can easily implement it in your solution in just a click.

The catch was that I’m using SubSonic 3.0.  I love SubSonic, but I couldn’t think of an easy way to implement Data Annotations in conjunction with it.   So… I searched Stackoverflow like usual, and found a couple good posts.  The short of it is to create an additional TT file that creates buddy classes.

Here is the walkthrough: http://subsonicproject.com/docs/User_talk:Minus4

Note that the MetaGenerator TT file referred to in the above post must be created manually by you and is not included with SubSonic by default.  Actually you could call it whatever you like.  The code is included in the posted link above.

In my MetaGenerator.TT (download) I added an extra line to the includes:

using DataAnnotationsExtensions;

Once saved, right click the file and select “Run Custom Tool” to generate the .cs (MetaGenerator.cs) file.  Open that up and start adding your Data Annotations, and if you’ve so chosen, the Data Annotations Extensions as well.

3981c3cea7f7d772348901dc4b8d9ec0

I guess the only “gotcha” here is that if change your DB schema and you re-run the custom tool (TT file), it will wipe any custom input you’ve created.  Perhaps there is a work around for that?

Some have recently posted that a pitfall of the Amazon Simple Email Service is that you can’t setup it up to work through a traditional SMTP as you can with other services such as SendGrid.  While Amazon SES doesn’t provide a SMTP wrapper, Amazon points out that it can be used with some modifications to your existing MTA.  From the Amazon Developer Docs:

Q: Can my existing SMTP applications deliver email via Amazon SES?
Yes. The Amazon SES Developer Guide provides instructions for configuring common mail transfer agents (MTAs) to use Amazon SES as their email transport. By following these instructions, you can create a private SMTP relay for use with any existing SMTP client software.

In looking at the Amazon SES Developer Guide, they currently have examples of how to setup either Postfix or Sendmail software to use Amazon SES, and suggest adapting the examples to work with other agents.

If you want to test sending Amazon email in your own mock environment (or have an extreme situation that I don’t want to know about) below is how to setup a Mock SMTP Server and use it to test sending mail via local SMTP using the Amazon SES SendRawEmail API call.

There are a number of open source Mock SMTP servers available.  For this demo I chose the Antix Mail SMTP Impostor.  It seemed to have a good bit accomplished, while not being overly complex (brief writeup here by @LeeDumond).   You can download the source code from here:  http://ssfd.codeplex.com/

Once you’ve got the source code loaded up, Open FileMessageStorage.cs (in the Antix.Mail.Smtp.Impostor project).  Add a reference to the Amazon .NET SDK.

Next find the Store() function.  This function is used to store Mock emails locally on the hard drive.  Insert the following code to actually send the email out via Amazon SES.

//Send msg via Amazon SES
AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient("accessKey", "secretKey");
SendRawEmailRequest rawObj = new SendRawEmailRequest();
rawObj.RawMessage = GetRawMessageFromString(message.Data);
rawObj.Source = message.From.Address;
foreach (MailAddress addressTo in message.To)
{
	rawObj.Destinations.Add(addressTo.Address);
}
client.SendRawEmail(rawObj); 

Remember to include the namespaces

using Amazon.SimpleEmail.Model;
using Amazon.SimpleEmail;

That’s it!  Now you can create a sample Console App or even Outlook to use your localhost to test sending emails via local SMTP.  I’m not sure if anyone would ever want to do this, but it was a fun exercise for me.

At the MvcConf 2 Andrew Davey (@andrewdavey) presented a neat emailing utility for ASP.NET MVC 3 called Postal that allows for using View Engines to ease the creation of email templates, and also takes care of sending the emails out.  During the session someone raised the question about sending through third-party services, namely Amazon Simple Email Service.  Since Postal relies on .NET’s SmtpMail, there wasn’t a straight forward solution.  This following post is about a hack I built to get around this… until something better crops up.  It’s certainly not the most efficient way, but it does work.

What You’ll Need

Postal – lets you create emails using regular MVC views.  Use NuGet to get the package and get started instantly.

Amazon Simple Email Service -  a highly scalable and cost-effective bulk and transactional email-sending service for businesses and developers.  Download and install the Amazon SDK and reference the DLL in your project.

Here’s what I hacked together for now which I just called MailExtensions:

SendEmailBySES – Handles everything from the dynamic Postal view to sending the message via Amazon SES.

public static void SendEmailBySES(dynamic email) {
	//Create Amazon SES client instance
	AmazonSimpleEmailServiceClient client
		= new AmazonSimpleEmailServiceClient("accessKey", "secretKey");
	//create postal service instance
	IEmailService service = new EmailService(ViewEngines.Engines);
	//create the mail message
	MailMessage msg = service.CreateMailMessage(email);
	//convert MailMessage object to Amazon SES SendEmailRequest object
	SendEmailRequest mailObj = ConvertFromMailMessage(msg);
	//Send the email via SES
	dynamic response = client.SendEmail(mailObj);
}

ConvertFromMailMessage – Converts a MailMessage object to an Amazon SES SendEmailRequest object.

The code for this is a bit longer and more hacky so just download it instead.  You can download the source here.

NOTE: If you aren’t setup with Amazon SES you’ll have to signup up, and then need to verify your email addresses initially and go through the sandbox.  Then you’ll have to apply for production.  Below is a snippet to verify your email address through the API:

public static void VeryifySESEmail(string addy)
{
	VerifyEmailAddressRequest verRequest = new VerifyEmailAddressRequest();
	verRequest.EmailAddress = addy;
	VerifyEmailAddressResponse verResponse = client.VerifyEmailAddress(verRequest);
}

Transitioning to MVC3 has been a great experience so far.  Changing from <%= to @ has been a dream come true.  It might not seem like it since its only a couple characters, but seriously, it works much better, and I can already see the cut down in coding time. 

My brain hurts from watching the MvcConf live webcast sessions most of the day yesterday, and Pluralsight MVC3 videos today (free until 9PM tonight).  Scott Guthrie did a great job on the Keynote at MvcConf and all the presentations I watched were well done.  I feel like I went to school the last couple days, and actually it felt pretty good.  Below are my notes from the PluralSight videos, highlighting things I wanted to remember about Razor and MVC3:

  • Razor – A general purpose templating engine
  • Data Annotations – Attributes that can be applied to properties of models can be used for Data Validation (both client / server-side)  eg. [Required] or [Range(1,4)]
  • ModelState.IsValid – Checks model validation
  • ClientValidationEnabled – flag in appSettings that determines if validation is handled on client-side (via jQuery) or server-side
  • UnobstrusiveJavaScriptEnabled – flag for ?
  • Implicit to Explicit Code Nuggets – You can use @(variable) to ensure the code is explcit and kept seperate from any following text
  • Transitioning from Razor to Text – Using <text> tags … You can use the <text></text> tags to help the Razor parser when it gets tripped up in coding blocks
  • @Html.Raw – Do not html encode the code.
  • @Html.Partial – Returns string instead of writing directly to Response (Reminder: Partial views vs jQuery templates – usages, SEO, etc)
  • @RenderSection – Sections that can be defined within each view.  Using required:false lets you make defining sections optional
  • IsSectionDefined – Lets you check if a section is defined within a view.  This is useful when you want to add default content when a section isn’t defined within a view.
  • _ViewStart.cshtml – Lets you define code before every View renders
  • system.web.webPages.razor – Dedicated section for Razor in the Web.Config file found within the Views folder

Action Filters

Can be placed at the ActionResult or Or can be placed at the controller level

  • [HandleError] – Allows pre/post processing to an action Friendly error view instead of yellow-screen of death
  • [Authorize] – Requires authorization to proceed

Global Action Filters

  • New in MVC3 – Ability to apply Global Action Filters
  • Register Global filters during application startup
  • - eg. GlobalFilters.Filters.Add(new HandleErrorAttribute());

Caching

  • New in MVC3?  Caching can now be applied to child actions.  Useful for caching on partial views.
  • [OutputCache(Duration=10)] – Set time for caching
  • [ChildActionOnly] – Ensure someone doesn’t make a direct request to this action

ViewBag vs ViewData

  • ViewData is  dictionary of name/value pairs
  • ViewBag is a dynamic

New Action Results in MVC3

  • HttpNotFoundResult (404)
  • HttpRedirectResult (301 permenanent redirect)
  • HttpStatusCodeResult

RequestValidation

  • [ValidateInput(false)] – Turns off all verification to ActionResult.  All or nothing approach, which can be problematic and hazardous.
  • [AllowHtml] – New in MVC3 a granular verification for view model which can be attributed to properties

Models Overview

  • Data Annotations – Required, StringLength, RegularExpression, Range
  • Client Validation – Improvements in MVC3
  • Remote Validation – New in MVC3 invokes server-side code, eg. validation that requires database information
  • Self Validation – View model object itself

Data Annotations – New

  • [Compare("varToCompare")] – New in .NET 4, allows to compare two properties
  • A second new one is … ?

Client Validation

  • @Html.EnableClientValidation
  • @Html.EnableUnobstrusiveJavaScript

Remote Validation

  • [Remote("ControllerAction", Named Parms)]

Setting up the FQL Console on Windows

Posted: 7th February 2011 by marc in Programming
Tags: , ,

Recently I came across a FQL test console that runs locally for running tests against the Facebook Query Language (FQL).  It is useful for testing purposes when developing a Facebook application.  After the download and setup it simply didn’t work properly.  Below are the changes I made to the fqlconsole.bat which seemed to make it function correctly:

set FQLCONSOLE=.
set LIB="%FQLCONSOLE%/libs"
set JARS=%LIB%/jetty-6.1.19.jar;%LIB%/jetty-util-6.1.19.jar;%LIB%/servlet-api-2.5-20081211.jar;%LIB%/start-6.1.19.jar
set JHOME=C:\"Program Files"\Java\jdk1.6.0_23\bin\java -classpath

start %JHOME% "%JARS%" org.mortbay.start.Main jetty.xml

Note: If you copy the code above, ensure you enter the correct path to the JDK. 

I also added the following to the jetty.xml under the DefaultHandler item entry:

<Item>

  <New id="RequestLog" class="org.mortbay.jetty.handler.RequestLogHandler"/>

</Item>

Here’s a screenshot of what it looks like:

image

Link to GIT: http://github.com/splix/fqlconsole