Wednesday, 22 June 2011

Access computer behind router over the internet


Here's a few notes which I find useful for accessing my system over the internet from an external location.

Is the remote system behind a router?
If so, use the router's IP address. Either go to whatismyip.com, or get the router's IP Address from the router control panel (typically 192.168.1.1). This will be the IP address you will use to access the system.

Enabling remote access
Enable remote access to the system. For windows, its usually at "Right Click My Computer > Properties > Remote/Remote Settings". Here you can also configure who is allowed to access the system.

Systems behind a router
Setup port forwarding to the system in question. Find your local IP address (usually 192.168.x.x) and forward the necessary ports to this system. I.e. for HTTP, use port 80. So when you visit the router's IP address over HTTP (http://externalRouterIP), it will forward the request to your machine. Another useful one is 3389 for remote desktop.
Optional: It may be useful to set a static IP for your system. This ensures that your internal IP address stays the same. If your router software does not support this, you can figure your own in Network Settings under the Control Panel in Windows.

Tuesday, 21 June 2011

SVN: Setting up SubVersion server on Windows


Here is a great article on how to setup SVN server on a windows machine.

http://www.codinghorror.com/blog/2008/04/setting-up-subversion-on-windows.html

Monday, 20 June 2011

SEO - Search Engine Optimization


Here's a good post on hoe to use an SEO tool to crawl your website for SEO improvements.
The tool installs itself into most web servers and is free to download!

Description
The IIS Search Engine Optimization (SEO) Toolkit helps Web developers, hosting providers, and Web server administrators to improve their Web site’s relevance in search results by recommending how to make the site content more search engine-friendly. The IIS SEO Toolkit includes the Site Analysis module, the Robots Exclusion module, and the Sitemaps and Site Indexes module, which let you perform detailed analysis and offer recommendations and editing tools for managing your Robots and Sitemaps files.

Article and Download
http://weblogs.asp.net/scottgu/archive/2009/06/03/iis-search-engine-optimization-toolkit.aspx

Wednesday, 15 June 2011

C# - Simple TripleDES Encryption with or without hashing


This class below enables simple encryption and decryption of text strings. It uses the TripleDES algorithms and you can chose weather to use MD5 hash against the key.
Simply change the value of the encryptionKey to whatever you want the key to be.


C# Source code
// <copyright file="EncryptionHelper.cs" company="GinkoSolutions.com">
// Copyright (c) 2011 All Right Reserved
// </copyright>
// <author>Sean Greasley</author>
// <email>sean@ginkosolutions.com</email>
// <summary>Enables simple TripleDES encryption with or without hashing</summary>
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Security.Cryptography;
 
/// <summary>
/// Enables simple TripleDES encryption with or without hashing
/// </summary>
public class EncryptionHelper
{
    /// <summary>
    /// Encryption key. Used to encrypt and decrypt.
    /// </summary>
    private static readonly string encryptionKey = "YOURSECRETKEY";
 
    public EncryptionHelper() {}
 
    /// <summary>
    /// Encrypt text string
    /// </summary>
    /// <param name="toEncrypt">The string of data to encrypt</param>
    /// <param name="useHashing">Weather hashing is used or not</param>
    /// <returns>An encrypted string</returns>
    public static string Encrypt(string toEncrypt, bool useHashing)
    {
        byte[] keyArray;
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
 
        // If hashing use get hashcode regards to your key
        if (useHashing)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(encryptionKey));
            hashmd5.Clear();
        }
        else
            keyArray = UTF8Encoding.UTF8.GetBytes(encryptionKey);
 
        // Set the secret key for the tripleDES algorithm
        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        tdes.Key = keyArray;
        tdes.Mode = CipherMode.ECB;
        tdes.Padding = PaddingMode.PKCS7;
 
        // Transform the specified region of bytes array to resultArray
        ICryptoTransform cTransform = tdes.CreateEncryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        tdes.Clear();
 
        // Return the encrypted data into unreadable string format
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }
 
    /// <summary>
    /// Decrypts a text string
    /// </summary>
    /// <param name="cipherString">The encrypted string</param>
    /// <param name="useHashing">Weather hashing is used or not</param>
    /// <returns>Decrypted text string</returns>
    public static string Decrypt(string cipherString, bool useHashing)
    {
        byte[] keyArray;
        byte[] toEncryptArray = Convert.FromBase64String(cipherString.Replace(' ', '+'));
 
        if (useHashing)
        {
            // If hashing was used get the hash code with regards to your key
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(encryptionKey));
            hashmd5.Clear();
        }
        else
        {
            // If hashing was not implemented get the byte code of the key
            keyArray = UTF8Encoding.UTF8.GetBytes(encryptionKey);
        }
 
        // Set the secret key for the tripleDES algorithm
        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        tdes.Key = keyArray;
        tdes.Mode = CipherMode.ECB;
        tdes.Padding = PaddingMode.PKCS7;
 
        ICryptoTransform cTransform = tdes.CreateDecryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        tdes.Clear();
 
        // Return the Clear decrypted TEXT
        return UTF8Encoding.UTF8.GetString(resultArray);
    }
}

Facebook Connect - Post to wall feed


After using Facebook Connect for a while, you can soon find out how shoddy the documentation is. There seem to be about 5000 half-written API's, most out of date and even the Facebook API documentation is barely holding itself together.

Anyway, here's a small JS snippet on how to post to a user's wall. The user must first allow the application pushing rights, or an error will occur.

I have already written a great blog entry on getting started with Facebook Connect, check it out here!


Pre-requisites
- Check out the above link if you have no idea how to get started!
- Allow pushing rights (publish_stream)
- Ensure your already dealing with an authentication session (I have added the code to ensure you already have a valid session in the code below)


Javascript Code
FB.getLoginStatus(function (response) {
    if (response.session) {
 
        var params = {};
        params['message'] = 'This is the main message';
        params['name'] = 'This is the name of the link';
        params['description'] = 'This is the link description';
        params['link'] = 'http://www.URLToNavigateTo.com';
        params['picture'] = 'http://www.FULLpathtoimage.com/image.png'; // 90x90 px
        params['caption'] = 'Small caption appearing under the link';
 
 
        FB.api('/me/feed', 'post', params, function (response) {
            if (!response || response.error) {
                // Error occured posting to the fb wall
            }
        });
 
    } else {
        // User isn't authenticated with facebook
    }
});



This will produce the following result...

Tuesday, 14 June 2011

ASP.NET C# 4.0 - Facebook Connect Example


Facebook connect example

This is a full example written in ASP.NET 4.0 and Javascript. It uses the Facebook Connect client-side library to authenticate and register uses into a database. This minimalist example explains how to easily integrate Facebook Connect into existing or new web applications.

Technologies used:
- ASP.NET/C#
- Javascript/JQuery
- AJAX
- SQL Server Compact
- Entity Framework
- LINQ

Setup Instructions
1. Add the Developer application to your facebook account and create a new facebook application.

Make sure you run the server on port "8080"... Facebook won't argue with this.
(Note: If you use any other port, other than the standard web traffic ports [80/8080],
then Facebook will throw a blank proxy dialog at you, with no kind of helpful error messages!
The URL will contain something like "xd_proxy"...so make sure it's set at 8080!

The settings you can use are as follows...
[Web Site] > [Site URL] > http://localhost:8080/
[Web Site] > [Site Domain] > localhost
[Facebook Integration] > [Canvas URL] > http://localhost:8080/
[Facebook Integration] > [Tab URL] > http://localhost:8080/
[Advanced] > [Sandbox Mode] > Enable [Note: Must only use developer accounts to test with! or you will get errors]


2. Enter application details into Web.config.

3. Enjoy!


Download
Download Source Files Here

Friday, 10 June 2011

CSS: Aligning form fields on a page


In the following example, I have used ASP.NET controls as I have lifted this from a project I have been working on.
If you are not familiar with ASP.NET, when the browser renders these server controls, the controls are rendered down to simple HTML tags:

label (asp:Label)
input (asp:TextBox)
span (asp:RequiredFieldValidator))



HTML/ASP.NET Code
<fieldset class="regForm">
<div class="field">
    <asp:Label ID="lblFirstName" AssociatedControlID="txtFirstName" runat="server" Text="Firstname" />
    <asp:TextBox ID="txtFirstName" runat="server" />
    <asp:RequiredFieldValidator ID="rfvFirstName" runat="server" ControlToValidate="txtFirstName" SetFocusOnError="True" ValidationGroup="vgRegister" ErrorMessage="*" />
</div>
<div class="field">
    <asp:Label ID="lblSurname" AssociatedControlID="txtSurname" runat="server" Text="Surname" />
    <asp:TextBox ID="txtSurname" runat="server" />
    <asp:RequiredFieldValidator ID="rfvSurname" runat="server" ControlToValidate="txtSurname" SetFocusOnError="True" ValidationGroup="vgRegister" ErrorMessage="*" />
</div>
<div class="field">
    <asp:Label ID="lblEmail" AssociatedControlID="txtEmailAddress" runat="server" Text="Email" />
    <asp:TextBox ID="txtEmailAddress" runat="server" />
    <asp:RequiredFieldValidator ID="rfvEmail" runat="server" ControlToValidate="txtEmailAddress" SetFocusOnError="True" ValidationGroup="vgRegister" ErrorMessage="*" />
</div>
</fieldset>



CSS Code
fieldset.regForm div {
    clear: both;
    padding-top:0.2em;
}
fieldset.regForm label {
    display:inline;
    padding-top:0.2em;
    text-align:right;
    margin-right:0.5em;
    float:left;
    width:25%;
}

ASP.NET: Quick and simple client-side validation


If you have created some server side controls, some ASP.NET validator controls to go with them, but... you would like to validate on the client, then call the function in the code snippet below from javascript.
Just remember to specify a ValidationGroup on your form fields so the JS function knows which controls to validate


Code Snippet
// By leaving the validation group parameter blank, it will
// validate the whole page, not just a target group.
if (Page_ClientValidate("ValidationGroupNameHere")) {
   // JS Code here...
}

Javascript: format() string extension for easy formatting!


Here's a simple javascript string extension for easy string formatting


Code Snippet
// Example:
//
//    var testString = "Hey {0}, this is a pretty {1} string formatter. I hope you have {2} with it!".format("guys", "cool", "fun");
//    alert(testString);
//
// String.format extension for easy formatting
String.prototype.format = function () {
    var s = this,
        i = arguments.length;
 
    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return s;
};

JQuery: Dynamically Add/Remove jquery.ui button from dialog


When using the dialog widget within the jquery.ui library, it may become necessary to add or remove buttons dynamically.
Invoking the extension methods below will allow you to achieve the desired result.


Code Snippet
Code Snippet
  1. // Example:
  2. //            $('#IDDialogDiv').dialog('addbutton', 'Name of button');
  3. //            $('#IDDialogDiv').dialog('removebutton', 'Name of button');
  4. //
  5. //
  6. // Allows simple button addition to a ui dialog
  7. $.extend($.ui.dialog.prototype, {
  8.     'addbutton': function (buttonName, func) {
  9.         var buttons = this.element.dialog('option', 'buttons');
  10.         buttons[buttonName] = func;
  11.         this.element.dialog('option', 'buttons', buttons);
  12.     }
  13. });
  14.  
  15. // Allows simple button removal from a ui dialog
  16. $.extend($.ui.dialog.prototype, {
  17.     'removebutton': function (buttonName) {
  18.         var buttons = this.element.dialog('option', 'buttons');
  19.         delete buttons[buttonName];
  20.         this.element.dialog('option', 'buttons', buttons);
  21.     }
  22. });
End of Code Snippet