Archive

Author Archive

GIF Proxy – Convert GIF to JPG (for Silverlight)

Categories: Uncategorized

CrossDomain.xml proxy

Ever tried to request a url in Silverlight, or WP7 to be stopped because you need to have a crossdomain.xml file installed in the root of the server.

Here’s a solution, a crossdomain.xml proxy.

Call http://<url>/CrossDomainProxy.aspx?url=http://YOURDOMAIN/YOURSCRIPT

and http://<url>/CrossDomain.xml is set to accept all hosts and requests.

Therefore even if there is not a CrossDomain.xml policy file on your server, you can use this proxy to bypass that.

Please, if you use this, give this blog a link back!, and a thank you would be nice!

Categories: Uncategorized

Find All Websites on a Webserver in C#

This is a handy script that can tell you how many sites are hosted on an IP address.  It uses  the Bing API, so it basically asks bing if it knows of sites on that IP address. This means that they have to be listed in bing, i.e. with public access.

 

 

 public static int SitesOnIP(string ip)
        {
            string url = "http://api.search.live.net/json.aspx?";
            url += "Appid=92B665B5421E197DC762503859279DFEBBE0B998";
            url += "&query=IP:" + ip;
            url += "&sources=web&web.count=50";
            // "Web":{"Total":31900
            string strRegex = @"Web....Total..(?<Count>\d+)";
            WebClient web = new WebClient();
            string strJson = web.DownloadString(url);
            string strCount = Regex.Match(strJson, strRegex).Groups["Count"].Value;
            return Convert.ToInt32(strCount);
        }
Categories: Uncategorized

A better XML to JSON proxy

I was looking for a generic way to convert XML to JSON, and I came across this GAE version http://jsonproxy.appspot.com/proxy, however, I noted that it only converted the first node of any tree to JSON, so it missed out most of the data contained in the XML.

Lets say,  we wanted to load exchange rates into a mobile app running Javascript (read phonegap /Wrtkit /Webos), an XML feed can be found at http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml (European central bank), but it’s easier to work with JSON than XML in Javascript. If you use the GAE (google app engine) version, then you only get USD, so I wanted to write my own proxy to fix this.

So, with the help of a free .NET Hosting account from brinkster Which worked an absolute charm – I didn’t have to put load on my own server to run this!. I installed my own XML-To-JSON Proxy:

I’ve fixed this, in a C# Implementation:

http://<url>/default.aspx?url=http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml

vs

http://jsonproxy.appspot.com/proxy?url=http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml

(obviously, you need to urlencode any querystring parameters after the URL in both cases)

Categories: Uncategorized

Using JSONP to show books from the Google API.

JSONP is one of the few technologies that allows cross-site scripting (XSS), whether this is by design or an oversight, here is an example of a Google Book Search using JSONP

<html>
  <head>
    <title>Books API Example</title>
  </head>
  <body>
    <div id="content"></div>
    <script>
      function handleResponse(response) {
	  html = "";
      for (var i = 0; i < response.items.length; i++) {
        var item = response.items[i];
        // in production code, item.text should have the HTML entities escaped.
		html += "<hr><img src=" + item.volumeInfo.imageLinks.thumbnail + ">";
		html += "<br>" + item.volumeInfo.title;
		html += "<br>Written by ";
		for(var author in item.volumeInfo.authors)
		{
			html+= item.volumeInfo.authors[author] + " ";
		}
		html += "<br>Published by " + item.volumeInfo.publisher;
		html += "<br>Published on " + item.volumeInfo.publishedDate;
		if (item.volumeInfo.pageCount != undefined)
		{
			html += "<br>Pages " + item.volumeInfo.pageCount;
		}
		for (var identifier in item.volumeInfo.industryIdentifiers)
		{
			var isbn = item.volumeInfo.industryIdentifiers[identifier];
			if (isbn.type=="ISBN_10")
			{
				html += "<br><a href=http://www.amazon.com/exec/obidos/ASIN/" + isbn.identifier+ "/httpnetwoprog-20>";
				html += "Buy at Amazon USA</a>";
				html += "<br><a href=http://www.amazon.co.uk/exec/obidos/ASIN/" + isbn.identifier+ "/wwwxamlnet-21>";
				html += "Buy at Amazon UK</a>";
			}
		}
	  }
	  document.getElementById("content").innerHTML = html;
    }
    </script>
    <script src="https://www.googleapis.com/books/v1/volumes?q=harry+potter&callback=handleResponse"></script>
  </body>
</html>

 

Categories: Uncategorized

Free SQL server database

Categories: Uncategorized

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