Jun 092010
 

Bit.ly API documentation http://code.google.com/p/bitly-api/wiki/ApiDocumentation.

Get your API Key http://bit.ly/account/your_api_key
(You will need to create an account if you do not already have one).

$url_to_shorten = urlencode("http://www.youtube.com/watch?v=F-QA2rkpBSY");
 
$bitly_key = "R_86df2938479233454a0a29";   # Replace this with your API key
$bitly_acc = "Your Acount Name";   # Replace this with your bit.ly username
$bitly_qry = "login=$bitly_acc&apiKey=$bitly_key";
$bitly_url = "http://api.bit.ly/v3/shorten?$bitly_qry&longurl=[url]&format=json";
$bitly_url = str_replace('[url]',$url_to_shorten,$bitly_url);
 
$short_json = file_get_contents($bitly_url);
$short_array = json_decode($short_json);
 
echo "Short link is: ".$short_array->data->url;

The use of json_decode limits this to PHP 5.2.0 or better. If you are using anything less check with your host, you may find it can be enabled directly through your control panel.

May 312010
 

uhit.us

The following discusses where and why I created another url shortening service.  Not mandatory reading at all, just an FYI as to why I closed the original website running the code in 1999.

Don’t frame my page
Some time ago I wrote an application that placed any link within a frame.  Although this was pre-blogging era it wasn’t long before I felt the wrath of webmasters who considered framing their site as content theft.

The process had not been succesful so the idea was dropped.  Instead I modified the code so that the links already added would redirect on a 301 move permanent header.

After a few weeks I announced I would shut the site down soon.  One user emailed me and asked how much for a copy of the code.  I gave it to him for $100.

The end of a business
A couple of years later he got back to me and asked for another copy.  His host shut him down and would not give him access to his site or data and he didn’t have a backup.  He told me the reason given was “spamvertising”.   Although obvious now it didn’t mean anything to me in 1999.

I rented dedicated servers from The Planet at the time who also happened to be his hosts up-line.  After a few calls we managed to have the code released and he got his database back.  Stats showed that one link had received several hundred visits and referrers were all email clients.  So in short, his shortening service had been scuppered by a spammer.

After a further discussion he decided not to start again.  I explained why the host had shut him down – the fear of losing their entire business to the spam police who would continue relentlessly to complain without caring how much damage they did to legitimate business.  It seemed pointless to build a business that would be so vulnerable.

The beginning of a new business
A couple of years later saw the release of tinyurl.com.  I watched the business with interest and expected it would disappear but then twitter happened and tinyurl.com along with a raft of others became popular.  This signalled a change in mood and an understanding on the part of the spam police.  I soon favoured bit.ly and built applications using their api.  While their statistics are great I decided I needed more flexibility with the api and the only way to do that was create my own.  Thus uhit.us was created.

api Another shortening serviceThe uhit.us api
At the base of the table after authorising with twitter you will see an api link.  Click it and you will find everything you need, except an explanation, which if you need then its probably not the kind of api you need anyway :)

 Posted by at 5:33 pm
Feb 102010
 

A TED talk from Pranav Mistry on the thrilling potential of sixth sense demonstrates a brand new interface between man and machine that makes Minority Report look out of date.

At first you might think this is something you have seen before but five minutes into the video and it becomes clear this is something new for 2010.

Expected to be on sale next month for around $300, not bad for something that turns a plain piece of paper into a powerful computer.

More details can be found on Pranav’s Website.

Feb 092010
 

Creating webparts in Visual Studio 2008 for SharePoint 2007 can be messy and the effort required is not indicative of the ease you would expect from a product like SharePoint. There are tools to help such as VseWSS and developers at Codeplex have created several solutions such as wspbuilder.  But have you checked out recent Visual Studio 2010 beta releases yet?

If you have then you probably eyed with envy the project templates for SharePoint 2010.  Developing Webparts is now a snap.  Developing, testing and deployment is done at white-knuckle speed and debugging SharePoint in 2010 works like any other Visual Studio application.

With a little hacking you can use Visual Studio 2010 to build SharePoint 2007 webparts.  Here’s what you do.

Simple Hello World

  1. Open up Visual Studio 2010 and create a new “Visual Webpart”
  2. VisualWebPart1UserControl.ascx will open automatically. To which we  add:
<asp:Label ID="Label1" runat="server" Text="Hello World">
</asp:Label>
  1. On Lines 2,3,4,7 change the Assembly version to 12.0.0.0
  2. Build > Package

This will create a wsp file containing a webpart that will run in SharePoint 2007 only.

Most of the time changing the assembly reference within the ascx file is all you need to do.  If you inherit a class within the Microsoft.SharePoint namespace you will need to replace the default reference to Microsoft.SharePoint version 14 with the older SharePoint 2007 version 12 library.

Dec 302009
 

Sales and support monitoring tool for WHMCS

A growing sales and support requirement inevitably leads to more hands on keyboards which is also the most expensive side of technology, so anything that can help better utilise the human resources already available can be a godsend.

whmcs monitoring tool WHMCS Support Monitoring System Tray Application

WHMCS support module has matured to something very usable, with two caveats.  First it seems a shame the authors have not heeded the calls for the ability to send rich media replies and thus incorporate videos and images in predefined replies.  Their excuse that you can send a link to those if you wish is nothing short of lame, even worse they site “security issues” as the reason when the real reason is surely they just cannot be bothered (after all, if they have customers that agree with them, how difficult would it be to supply the solution as an option).

But I’m not here to rip them a new one, their latest release is truly fantastic and better than any other host billing system I have used, it makes Modern Billing look tedious and infezible (which indeed it is).  Utilising their API and the includes/hooks folder enables unlimited customisation, indeed I have bent it to supplying electronic products and license management with great results.

The second caveat is the lack of an alert system.  Up until recently I used a very old Kayako support system but the balance of power is back in WHMCS court except that Kayako had a simple “flashing beeping” thingy that would notify you when a new ticket or customer reply had been received.  It was a basic product and rather featureless yet it did an important job and as I missed it so much decided to write one for WHMCS.

download WHMCS Support Monitoring System Tray Application

Ticket Review (setup.msi) Windows Setup MSI, download and double click.

Ticket Review (manual) Zip file contains program EXE, a php file and readme.txt with instructions for manual installation.

Installation Instructions

Ticket Review monitors up to two support departments in WHMCS and alerts you of a new ticket by changing the color of the system tray icon and optionally playing a wav file too.  Ticket Review can be used by an unlimited number of sales and support staff.

1.  Unzip and place files in a directory.
2.  Upload ticketreview.php to your WHMCS install direcory on your host webserver.

Configuration

To configure your application double click the Ticket Review.exe  When you first run the application you need to complete some of the fields.  The Tickets Link is the URL to your WHMCS and will look something like this:-

http://yourdomain.com/client/ticketreview.php

If you only have one support ticket department you need only complete the Red Department Id.  We operate two departments and allocate the Red to Sales and the Green to Support.

How to find the Department Id

Login to WHMCS as admin, the select Support Departments from the Setup dropdown.  Hover your mouse over the edit icon and a link is displayed in the status bar, at the end of the link there is &id= the number following this is your department id.

How to add sound

Sometimes it is useful to add sound, if you don’t want it just leave the WAV fields blank.  Google for fancy wavs to produce bings or bongs or whatever takes your fancy, I prefer to hear a voice telling me whether a sales or support ticket is in and use ATT’s Text to Speech demo tool to create a WAV which can be found here:-

http://www2.research.att.com/~ttsweb/tts/demo.php

What next?

After setup you should create a couple of test tickets to make sure it all works.  If it doesn’t check the link to the PHP file is correct and try running it directly in your browser to make sure there are no errors.

What is supposed to happen?

When a new sales or support ticket arrives the icon will begin to flash.  If you have added a wav that will be played each time the application checks and finds a ticket that needs your attention.  This will probably get a little annoying after a while so you can delay the check by 5 minutes by double clicking the system tray icon (which will also stop flashing).  The idea is this application will bug you until you answer your ticket!  But you can delay that nuisance for 5 minutes as often as you like!

Support

This is a simple application and shouldn’t really need support.  You can probably think of hundreds of ways in which to improve the application and while I do not wish to steal your thunder I have probably thought of them too, this application is intended to just alert you of new tickets, stats and integrating with facetwitter are all cool ideas but they don’t really improve it.  However if you need a contractor to write additional features then please contact me at mwdev@ventrino.com or call UK +447850018933 and ask for Martyn

Dec 092009
 

Internal Coding Guidelines

An abridged version of Brad Abrams coding guidelines courtesy of Nigel Belham with minor layout modifications for increased clarity.

Introduction

First, read the .NET Framework Design Guidelines. Almost all naming conventions, casing rules, etc., are spelled out in this document. Unlike the Design Guidelines document, you should treat this document as a set of suggested guidelines. These generally do not affect the customer view so they are not required.

Style Guidelines

Tabs & Indenting

Tab characters (\0×09) should not be used in C# code files. All indentation should be done with 4 space characters.

Bracing

Open braces should always be at the beginning of the line after the statement that begins the block. Contents of the brace should be indented by 4 spaces. For example:

if (someExpression)
{
   DoSomething();
}
else
{
   DoSomethingElse();
}

“case” statements should be indented from the switch statement like this:

switch (someExpression)
{
 
   case 0:
      DoSomething();
      break;
 
   case 1:
      DoSomethingElse();
      break;
 
   case 2:
      {
         int n = 1;
         DoAnotherThing(n);
      }
      break;
}

Braces should never be considered optional. Even for single statement blocks, you should always use braces. This increases code readability and maintainability.

for (int i=0; i&lt;100; i++) { DoSomething(i); }

Single line statements

Single line statements can have braces that begin and end on the same line.

public class Foo
{
   int bar;
 
   public int Bar
   {
      get { return bar; }
      set { bar = value; }
   }
 
}

It is suggested that all control structures (if, while, for, etc.) use braces, but it is not required.

Commenting

Comments should be used to describe intention, algorithmic overview, and/or logical flow. It would be ideal, if from reading the comments alone, someone other than the author could understand a function’s intended behaviour and general operation. While there are no minimum comment requirements and certainly some very small routines need no commenting at all, it is hoped that most routines will have comments reflecting the programmer’s intent and approach.

Copyright notice

Each file should start with a copyright notice. To avoid errors in doc comment builds, you don’t want to use triple-slash doc comments, but using XML makes the comments easy to replace in the future. Final text will vary by product (you should contact legal for the exact text), but should be similar to:

//---------------------------------------------------------------
//
//     Copyright (c) Microsoft Corporation.  All rights reserved.
//
//---------------------------------------------------------------

Documentation Comments

All methods should use XML doc comments. For internal dev comments, the <devdoc> tag should be used.

public class Foo
{
 
/// Public stuff about the method
///
What a neat parameter!
/// Cool internal stuff!
///
public void MyMethod(int bar) {}
 
}

However, it is common that you would want to move the XML documentation to an external file – for that, use the <include> tag.

public class Foo
{
 
   ///
   ///
   public void MyMethod(int bar) {}
 
}

Comment Style

The // (two slashes) style of comment tags should be used in most situations. Where ever possible, place comments above the code instead of beside it. Here are some examples:

public class SomethingUseful
{
    private int          itemHash;            // instance member
    private static bool  hasDoneSomething;    // static member
}

Spacing

Spaces improve readability by decreasing code density. Here are some guidelines for the use of space characters within code:

  • Do use a single space after a comma between function arguments.
    Right: Console.In.Read(myChar, 0, 1);
    Wrong: Console.In.Read(myChar,0,1);
  • Do not use a space after the parenthesis and function arguments
    Right: CreateFoo(myChar, 0, 1)
    Wrong: CreateFoo( myChar, 0, 1 )
  • Do not use spaces between a function name and parenthesis.
    Right: CreateFoo()
    Wrong: CreateFoo ()
  • Do not use spaces inside brackets.
    Right: x = dataArray[index];
    Wrong: x = dataArray[ index ];
  • Do use a single space before flow control statements
    Right: while (x == y)
    Wrong: while(x==y)
  • Do use a single space before and after comparison operators
    Right: if (x == y)
    Wrong: if (x==y)

Naming

Follow all .NET Framework Design Guidelines for both internal and external members. Highlights of these include:

  • Do not use Hungarian notation
  • Do not use a prefix for member variables (_, m_, s_, etc.). If you want to distinguish between local and member variables you should use “this.” in C# and “Me.” in VB.NET.
  • Do use camelCasing for member variables
  • Do use camelCasing for parameters
  • Do use camelCasing for local variables
  • Do use PascalCasing for function, property, event, and class names
  • Do prefix interfaces names with “I”
  • Do not prefix enums, classes, or delegates with any letter

The reasons to extend the public rules (no Hungarian, no prefix for member variables, etc.) is to produce a consistent source code appearance. In addition a goal is to have clean readable source. Code legibility should be a primary goal.

Naming Conventions

Interop Classes

Classes that are there for interop wrappers (DllImport statements) should follow the naming convention below:

  • NativeMethods – No suppress unmanaged code attribute, these are methods that can be used anywhere because a stack walk will be performed.
  • UnsafeNativeMethods – Has suppress unmanaged code attribute. These methods are potentially dangerous and any caller of these methods must do a full security review to ensure that the usage is safe and protected as no stack walk will be performed.
  • SafeNativeMethods – Has suppress unmanaged code attribute. These methods are safe and can be used fairly safely and the caller isn’t needed to do full security reviews even though no stack walk will be performed.
class NativeMethods
{
   private NativeMethods() {}
 
   [DllImport(“user32”)]
   internal static extern void FormatHardDrive(string driveName);
}
 
[SuppressUnmanagedCode]
class UnsafeNativeMethods
{
   private UnsafeNativeMethods() {}
 
   [DllImport(“user32”)]
   internal static extern void CreateFile(string fileName);
}
 
[SuppressUnmanagedCode]
class SafeNativeMethods
{
   private SafeNativeMethods() {}
 
   [DllImport(“user32”)]
   internal static extern void MessageBox(string text);
}

All interop classes must be private, and all methods must be internal. In addition a private constructor should be provided to prevent instantiation.

File Organization

  • Source files should contain only one public type, although multiple internal classes are allowed
  • Source files should be given the name of the public class in the file
  • Directory names should follow the namespace for the class

For example, I would expect to find the public class “System.Windows.Forms.Control” in “System\Windows\Forms\Control.cs”…

  • Classes member should be alphabetized, and grouped into sections (Fields, Constructors, Properties, Events, Methods, Private interface implementations, Nested types)
  • Using statements should be inside the namespace declaration.
namespace MyNamespace
{
 
using System;
 
public class MyClass : IFoo
{
 
      // fields
      int foo;
 
      // constructors
      public MyClass() {}
 
      // properties
      public int Foo { get {} set {} }
 
      // events
      public event EventHandler FooChanged { add {} remove {} }
 
      // methods
      void DoSomething() {}
      void FindSomethind() {}
 
//private interface implementations
   void IFoo.DoSomething() { DoSomething(); }
 
// nested types
   class NestedType {}
 
}
 
}
 Posted by at 2:24 pm  Tagged with:
Jan 022009
 

If you would like to redirect browsers based on their IP the following method can be used to handle multiple IP’s.  You can choose to redirect entire networks or a single ip.

<?php
//array of ip's you wish to block.  Note that you can block an
//entire class by replacing it with 0, so to block a class c
//(254 computers) use something like 123.123.123.0
$blockIP = array('123.123.123.0','100.100.100.101');
 
$remote = explode('.',$_SERVER['REMOTE_ADDR']);
foreach($blockIP as $ip) {
  $goodIP = false;
	for($i=0;$i<4;$i++) {
    $ipSeg = explode('.',$ip);
    if($remote[$i] == $ipSeg[$i] || $ipSeg[$i] == '0') {
      //segment qualifies
      $goodIP = true;
    } else {
      //ip no good so move to the next
      $goodIP = false;
      continue 2;
    }
  }
  if($goodIP) {
    //ip passes so no need to check the rest
    $blockThisIP = $ip;
    break;
  }
 
}
//for convenience test $blockThisIP and process here
//replace www.crayola.com with the place you wish to
//send ip's too
if($blockThisIP) {
  //php header method - can only use this if the page
  //has not begin to display in the browser
  header('Location: http://www.crayola.com');
 
  //javascript redirection - use this method if browser has
  //begun to display page
  echo "<script type=\"text/javascript\">
  window.location = \"http://www.crayola.com\";</script>";
}
?>
 Posted by at 9:12 am  Tagged with:
Aug 252008
 

Most of our hosting servers run Centos Linux but we have Windows servers too and a problem common to both is the occasional high volume of traffic generated by non organic growth.  I don’t mean that someones blog hits the front page of digg, rather a malicious or DDOS attack against a website.  On shared hosting this will effect all sites on the server.  There are bandwidth control tools for both operating systems but they all come at a price to CPU or wallet or both.  I have tried all I could find and none of them have been effective.

Some datacenters offer solutions which usually require traffic being filtered before it reaches your server.  This has obvious advantages but comes with one major drawback and that is you have lost control of your network and are relying on unknown parameters setup by your datacenter, and this can result in false positives which may include potential business for your customers

Liquidweb are the only datacenter I have used to date that rely on monitoring service to alert them of a problem plus a human to decide the appropriate reaction.  As they will notify you of changes made or any IP’s blocked you can recover the situation if they block access incorrectly.  This is as close to remaining in control and could be enough for your needs.

Another way is to utilise services built-in to the operating system.  In the attached autoban.zip file I have prepared bash and php files which placed into a cron monitors connections by count and rejects those who try to open too many.  You can also ban countries from accessing your website too.  Parameters allow you to choose how long the ban should be for and you can set levels so that should someone repeatedly be trying to attack the server their ban can be extended.  I find a 1 hour ban followed by a 3 hour, then 6 hour and then a 31 day ban completely eradicates Denial of Service Attacks.

autoban

You will need root access to the server, see readme.txt for instructions.

Jul 242008
 

On more than one occasion these characters  have turned up just when everything else seems fine.  Known as a “BOM” or Byte Order Mark they can be extremely annoying.

What is  ???

 is often seen at the top left corner of a web page.  When you open the source file and compare that to the output source you will not find , so what causes  to appear in your file?

The reason is your editor has saved the file as UTF-8.  With the ever increasing complexity of character encoding some editors ignore your settings and update your configuration to use UTF-8. Even if you have been using ASCII without any trouble since 1982!

The Fix

Change the character encoding of your page.  With most editors all you need to do is select properties and then choose ASCII then save the file.

Changing the meta tag alone is not enough, with extended attributes on files now no one can be sure where a browser or whatever reader your using will use to determine how to display it.

Fix Update – 2nd August 2011

Remarkable that two years on from this post many commercial editors still cause problems. A friend told me the BOM is not supposed to be used in web files saved as UTF-8. Ever. He sent me this link as his reference from W3 http://www.w3.org/International/questions/qa-byte-order-mark.

How to fix Microsoft Exprfession

Expression introduced the BOM in 2.00 and since 4.00 you can switch the BOM off which has been the default for PHP files, to fix the rest go Tools -> Page Editor Options -> Authoring and uncheck the rest.

remove bom from web files Three little characters  designed to make your life hell

Jul 072008
 

To remove stuff such as punction and spaces (or anything you want) from a text box before sending to the server for validation you can use code like this, first the HTML:-

<input
name="name"
onblur="this.value = entrycheck(this.value);"
type="text"
size="20">

And then the following Javascript will remove invalid characters when the user moves to another field:-

<script type="text/javascript">
function namecheck(theInput) {
  var valid = 'abcdefghijklmnopqrstuvwxyz1234567890';
  var test ='';
  var ret ='';
  for(i=0;i<theInput.length;i++) {
    test = theInput.substr(i,1);
    if(valid.indexOf(test.toLowerCase()) != -1) {
      ret = ret + test;
    }
  }
  return ret;
}
</script>

In this example I just want digits and characters. If you want to add certain punctuation such as stops and commas just add them to the valid variable.