Archive

Archive for May, 2011

Send an SMS from Windows Phone 7 (WP7/Silverlight)

This is a simple piece of code that allows you send an SMS from Windows Phone 7 with Silverlight
The XAML is as follows

 
    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <TextBlock Height="30" HorizontalAlignment="Left" Margin="29,35,0,0" Name="lblFromName" Text="From (Name)" VerticalAlignment="Top" />
            <TextBox Height="80" HorizontalAlignment="Left" Margin="170,6,0,0" Name="tbFromName" Text="" VerticalAlignment="Top" Width="259" />
            <TextBlock Height="30" HorizontalAlignment="Left" Margin="29,112,0,0" Name="lblFromNumber" Text="From (Number)" VerticalAlignment="Top" />
            <TextBox Height="80" HorizontalAlignment="Left" Margin="170,92,0,0" Name="tbFromNumber" Text="00" VerticalAlignment="Top" Width="259" />
            <TextBlock Height="30" HorizontalAlignment="Left" Margin="29,205,0,0" Name="lblToName" Text="To (Name)" VerticalAlignment="Top" />
            <TextBox Height="80" HorizontalAlignment="Left" Margin="170,178,0,0" Name="tbToName" Text="" VerticalAlignment="Top" Width="259" />
            <TextBlock Height="30" HorizontalAlignment="Left" Margin="33,289,0,0" Name="lblToNumber" Text="To (Number)" VerticalAlignment="Top" />
            <TextBox Height="80" HorizontalAlignment="Left" Margin="170,264,0,0" Name="tbToNumber" Text="00" VerticalAlignment="Top" Width="259" />
            <Button Content="Send SMS" Height="93" HorizontalAlignment="Left" Margin="170,570,0,0" Name="btnSendSMS" VerticalAlignment="Top" Width="239" Click="btnSendSMS_Click" />
            <TextBlock Height="44" HorizontalAlignment="Left" Margin="31,369,0,0" Name="textBlock1" Text="Message" VerticalAlignment="Top" Width="199" />
            <TextBox Height="166" HorizontalAlignment="Left" Margin="33,397,0,0" Name="tbMessage" Text="" VerticalAlignment="Top" Width="374" TextChanged="tbMessage_TextChanged" />
        </Grid>

Then the code behind btnSendSMS_Click is

     private void btnSendSMS_Click(object sender, RoutedEventArgs e)
        {
            var strFromName = tbFromName.Text;
            var strToName = tbToName.Text;
            var strFromNumber = tbFromNumber.Text;
            var strToNumber = tbToNumber.Text;
            var strMessage = tbMessage.Text;
            // Validation
            if (!strToNumber.StartsWith("00") || !strFromNumber.StartsWith("00"))
            {
                MessageBox.Show("Mobile numbers must be written in international format, for example 0044 for the UK, followed by the mobile phone number, without the first zero");
                return;
            }
            if (strFromName.Length  11)
            {
                MessageBox.Show("Use your real name or else the reciepient may not recognize the sender, your name should be between 3 and 11 letters long");
                return;
            }
            if (strFromNumber == strToNumber)
            {
                MessageBox.Show("You cannot send a text message to yourself");
                return;
            }
            if (strMessage.Length < 3)
            {
                MessageBox.Show("Your message is blank, please type a message");
                return;
            }
            sendSmsSoapClient sms = new sendSmsSoapClient();
            sms.SendSmsCompleted +=
                new EventHandler(sms_SendSmsCompleted);
            try
            {
                sms.SendSmsAsync(strFromName, strFromNumber, strToNumber, strMessage, "xx-xx");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SMS failed to send due to: " + ex.Message);
            }
        }

        void sms_SendSmsCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                MessageBox.Show("SMS Sent successfully");
            }
            else
            {
                MessageBox.Show("SMS not sent due to " + e.Error.Message);
            }
        }

Then you need a web service reference to http://www.freebiesms.co.uk/sendsms.asmx called “webservice”

Tip: If you use AffiliateSendSMS API call rather than SendSMS, then you can get paid via your affiliate account on FreebieSMS! 🙂

Categories: Uncategorized

A HTTP Proxy in Python for Google AppEngine

Labnol’s AppEngine Proxy is useful for viewing other pages requested via Google AppEngine, however, it does change the HTML, and doesn’t handle POST data. This is a code example in Google AppEngine Python showing how to implement a HTTP proxy in a similar way to Labnol.

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util

import urllib2
import urllib
import re
import array
import urllib2


class MainHandler(webapp.RequestHandler):
	def get(self):	
		#self.response.out.write('[GET] The URL Requested was ' + self.request.query_string)
		response = urllib2.open(self.request.query_string)
		html = response.read()
		self.response.out.write(html)

	def post(self):	
		#self.response.out.write('[POST] The URL Requested was ' + self.request.query_string + "
") args = self.request.arguments() strPostdata = "" for arg in args: strPostdata = strPostdata + arg + "=" + self.request.get(arg) + "&" #self.response.out.write("[POST] The data was:" + strPostdata) request = urllib2.Request(self.request.query_string) request.add_data(str(strPostdata)) response = urllib2.urlopen(request) html = response.read() self.response.out.write(unicode(html,"latin1")) def main(): application = webapp.WSGIApplication([('/', MainHandler)], debug=True) util.run_wsgi_app(application) if __name__ == '__main__': main()
Categories: Uncategorized

What IP address does Google AppEngine make requests from?

If you make a HTTP request from an AppEngine App, you will find that the IP address is different from the IP address of the URL the app is hosted on.

Here is a trick, host a proxy on your AppEngine Account, (see http://www.labnol.org/internet/setup-proxy-server/12890/ for steps), then make a request to http://whatismyipaddress.com/ via the proxy, like this:

https://mirrorrr.appspot.com/whatismyipaddress.com

And you get this response:

IP Information: 74.125.75.4
ISP: Google
Organization: Google
Proxy: Network Sharing Device
City: New York
Region: New York
Country: United States

This does change based on different accounts, I’ve also seen 74.125.114.82, but the 74.125 prefix seems
stable.

Categories: Uncategorized

Downcasting using Reflection C#

You cannot cast an object to a derived type in C#, this is called downcasting.

I.e.

class MyBase {}
class MyDerived : MyBase {}

MyBase SomeBase = new MyBase();
MyDerived SomeDerived = (MyDerived)SomeBase;

Will fail, as will

MyDerived SomeDerived = SomeBase as MyDerived

– Which will set SomeDerived to Null.

A way around this is to use reflection:

    public MyDerived(MyBase baseClass)
    {
        foreach (PropertyInfo piBase in typeof(MyBase).GetProperties())
        {
            PropertyInfo piThis = GetType().GetProperty(piBase.Name);
            piThis.SetValue(this, piBase.GetValue(baseClass, null), null);
        }
    }
Categories: Uncategorized

Calling Python from C#

Here is a simple example of how to call an IronPython function from C#

Here is the PY file: (With URL & Regex removed)

import urllib2
import re
import array

def getRoutes():
    strRouteRegex = '(?<From>[A-Z]{3})...\d+..iata...=..(?<To>[A-Z]{3})'
    httpRequest = urllib2.urlopen("http://www.somewebsite.com/")
    html = httpRequest.read()
    routesArray = []
    for m in re.finditer(strRouteRegex, html):
        route = FlightRoute()
        route.depart = m.group('From')
        route.arrive = m.group('To')
        routesArray.append(route)
    return routesArray;

class FlightRoute:
    depart = ''
    arrive = ''

And here is the C# calling code – This requires the .NET 4 to handle the dynamic types.

using System;
using System.Collections.Generic;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

namespace CSPY
{
    class Program
    {
        static void Main(string[] args)
        {
            const string strPy = @"C:\research\Program.py";
            ScriptEngine engine = Python.CreateEngine();
            var lPath = new List<string> {@"c:\Program Files\IronPython 2.7\Lib"};
            engine.SetSearchPaths(lPath);
            ScriptRuntime scripting = engine.Runtime;
            dynamic runtime = scripting.UseFile(strPy);
            dynamic routes = runtime.getRoutes();
            foreach(dynamic route in routes)
            {
                Console.WriteLine(route.depart + " -> " + route.arrive);
            }
            Console.Read();
        }
    }
}
Useful?
Categories: Uncategorized

Load Image as Base64 string

In JavaScript you can display an image like this <img src=”data:image/jpg;base64,…”> where “…” is the base64 encoded version of the image. Here is some C# Code that can convert an image on-disk to this Base64 string format

     FileInfo fi = new FileInfo(strFileName);
     FileStream fs = new FileStream(strFileName, FileMode.Open, FileAccess.Read,FileShare.None);
     byte[] rawData = new byte[fi.Length];
     fs.Read(rawData, 0, (int)fi.Length);
     string strBase64 = Convert.ToBase64String(rawData);
     Response.Write("data:image/jpg;base64," + strBase64);
     fs.Close();
Categories: Uncategorized

PuTTY / SSH on Palm WebOS

Shown opposite is a screenshot of an application that I’ve developed for Palm / WebOS using PhoneGap that enables you connect to a Linux server via SSH (PuTTY) from your Palm Phone.

How it works, is that you have to first install a piece of software called MobilePutty that you can download from http://bit.ly/puttyformobile , this application must be installed and run on a Windows PC. On this program, you enter the Host IP address, username and password of your Linux Server. And a PuTTY terminal window will appear.

From your phone, you can then enter in the host name, username and password, and you will be relayed screenshots of the PuTTY terminal to your phone. You can also send commands to your PuTTY terminal, in order to interact with your linux server. You can also open up any other terminal-style program, such as windows command prompt, and remotely control your home PC from your phone, without having to worry about firewalls etc.

This application works best over WiFi broadband, be very patient if you are using GPRS.

Categories: Uncategorized

PuTTY/SSH on your Nokia Phone

Shown opposite is a screenshot of an application that I’ve developed for Nokia / OVI using WRTKIT that enables you connect to a Linux server via SSH (PuTTY) from your Nokia Phone.

How it works, is that you have to first install a piece of software called MobilePutty that you can download from http://bit.ly/puttyformobile , this application must be installed and run on a Windows PC. On this program, you enter the Host IP address, username and password of your Linux Server. And a PuTTY terminal window will appear.

From your phone, you can then enter in the host name, username and password, and you will be relayed screenshots of the PuTTY terminal to your phone. You can also send commands to your PuTTY terminal, in order to interact with your linux server. You can also open up any other terminal-style program, such as windows command prompt, and remotely control your home PC from your phone, without having to worry about firewalls etc.

This application works best over WiFi broadband, be very patient if you are using GPRS.

Categories: Uncategorized

90 Days free pluralsight training

Pluralsight provides high-quality training solutions for Microsoft .NET developers that can fit any schedule or budget. The revolutionary training library provides developers with instant access to a rich collection of online training courses delivered by industry authorities. Through this special DreamSpark offer you will receive a FREE 90-day subscription to all of the courses found in the Pluralsight On-Demand! training library. Happy learning!

To get started follow these steps:

  1. Sign in with your Windows Live ID.
  2. If you haven’t done so already, click on Get Verified and follow the steps to verify your academic status.
  3. Click on “Get Key” above and copy the single-use key provided.
  4. Navigate to training.pluralsight.com/Dreamspark
  5. On the right hand side of the page paste the key you received in the “code” box, and complete the User Information form below it.
  6. Click “Submit” and get instant access to Pluralsight’s online training library!
Categories: Uncategorized

Free Microsoft Certification exam

STUDENTS! Get a FREE Microsoft Certification Exam Voucher Code –and a head start on your IT career.

While supplies last!

These days, the job market can be a tough ride—but it doesn’t have to be. Boost your resume by getting Microsoft Certified. A Microsoft Certification can help validate your technical skills and show hiring managers you have the right stuff for the job. And right now, you can get a voucher code to take a FREE Microsoft Certification Exam.

Like new jobs, these codes are in limited supply so don’t wait!

Please select “Get Key” above to get your voucher code, then follow the steps below to redeem it.

Voucher Redemption Instructions

NOTE: This offer is for select exams (with 072 prefix) for students globally who have valid student identification (not available in India and China). Each voucher code can only be redeemed once. Once the code has been redeemed, it cannot be used again. Students must redeem and take exams by June 30, 2011. This offer is non-transferable and cannot be combined with any other offer. This offer expires when supply is depleted and is not redeemable for cash.

Once you have your free exam voucher code, follow the instructions below on how to redeem it:

  • Prometric is Microsoft’s Exam Delivery Provider
  • Go to Prometric’s website:
    • Click on the “Start” icon located in the “Get Started” section
    • Select “Schedule an Appointment”
    • Select your Country and State (if applicable)
    • Click Next
    • Next to Client, select Microsoft
    • Next to Program, select Microsoft (072)
    • Click Next
  • Please read the page titled Microsoft Certified Exam Provider
    • Click Next
  • Select the exam number and the exam language for the exam you would like to take
    • Click Next
  • Select the test center location where you would like to take the exam by clicking on Schedule an Appointment next to the location that is nearest you
  • When the next page appears you have the option of either logging in, if you have been to the site before or you can register as a new user
    • NOTE if you are a new user – PLEASE enter a VALID EMAIL ADDRESS for Prometric and Microsoft.
      • All information for the Microsoft Certification Program will be sent via email and without a valid email address, you will not receive access to the MCP Secure site or be able to order your Welcome Kit when you achieve your certification
  • Once you are logged in, you will then be able to select a date and time for your appointment, select a date and time
    • Click Next
  • Under Payment Information in the box that states Promotion Code or Voucher click Yes
    • Next to Discount Type select Voucher Number
    • Next to Voucher Number / Promotion Code – enter the code number you have been provided
    • Click Validate – if the voucher has not been used you will be automatically directed back to the Payment Information Page
    • Validate your email address and click on the radio button I agree (as long as you agree to the terms of the privacy notice)
    • Click Commit Registration
  • A Confirmation Page will come up, please print this page for your records and ensure you have noted the date and time for your exam
  • When you go to the testing center to take your exam, you must have valid student identification with a photograph. You will not be allowed to take your exam without student identification with photo.

IMPORTANT:

  • Your code can be redeemed for one Microsoft Certification exam.
  • This offer is only applicable to students, and is worldwide (offer not valid in China and India).
  • Students must have a valid student identification card with photo in order to take the exam. Students without a valid student ID card will have to pay full professional price for the exam.
  • You must use the code and take your exam by June 30, 2011.
NOTE: This offer is for select exams (with 072 prefix) for students globally who have valid student identification (not available in India and China). Each  voucher code can only be redeemed once. Once the code has been redeemed, it cannot be used again. Students must redeem and take exams by June 30, 2011. This offer is non-transferable and cannot be combined with any other offer. This offer expires when supply is depleted and is not redeemable for cash.
Good luck on your exam!
Categories: Uncategorized