Short Domain Name Finder

This is a short url finder I created.
It checks to see if the domain is available remembers.

Short Domain Name Finder

There is a python script in the background that populates a mysql database which displays it with php.

Installing Diaspora on Ubuntu on VirtualBox

Installing Diaspora on Ubuntu on VirtualBox

I wrote up a little howto on the Diaspora git hub:
https://github.com/diaspora/diaspora/wiki/Installing-Diaspora-on-Ubuntu-on-VirtualBox

Sending Email with PHP, Gmail or Google Apps, Mail, and PEAR on Ubuntu

First Install Pear, Mail, Mail Mime, Net SMTP. Restart Apache:

sudo apt-get install php-pear
sudo pear install mail
sudo pear install mail_mime
sudo pear install Net_SMTP
sudo /etc/init.d/apache2 restart

Here is the PHP code I used to send an email:

try {
	require_once "Mail.php";
 
	$from = "[email protected]";
	$to = "{$email}";
	$subject = "Hi!";
	$body = "Hi,\n\nHow are you?";
 
	$host = "ssl://smtp.gmail.com";
	$port = "465";
	$username = "[email protected]"; //This can also be a Google Apps account
	$password = "PASSWORD";
 
	$headers = array ('From' => $from,
	  'To' => $to,
	  'Subject' => $subject);
	$smtp = Mail::factory('smtp',
	  array ('host' => $host,
		'port' => $port,
		'auth' => true,
		'username' => $username,
		'password' => $password));
 
	$mail = $smtp->send($to, $headers, $body);
 
	if (PEAR::isError($mail)) {
	  echo("<p>" . $mail->getMessage() . "</p>");
	 } else {
	  echo("<p>Message successfully sent!</p>");
	 }
} catch (Exception $e) {
	echo 'Caught exception: ',  $e->getMessage(), "\n";
}

Converting a Magnet Link into a Torrent

UPDATE – 2012-04-30 – User Faless on GitHub has added a good bit of functionality. Check it out.

For some reason, my version of the rtorrent client on ubuntu does not open magnet files. So, I wanted to see if there was a way to create torrent files from magnet files. I couldn’t find a good example, so I wrote my own.

This will convert a magnet link into a .torrent file:

First, make sure your system has Python and the Python Library:

sudo apt-get install python-libtorrent

Then, you can run the following code by calling this command:

python Magnet2Torrent.py

File Magnet2Torrent.py:

'''
Created on Apr 19, 2012
@author: dan
'''
 
if __name__ == '__main__':
    import libtorrent as lt
    import time
 
    TorrentFilePath = "/home/dan/torrentfiles/" + str(time.time()) + "/"
    TorrentFilePath2 = "/home/dan/torrentfiles/" + str(time.time()) + "/" + str(time.time()) + ".torrent"
    ses = lt.session()
    #ses.listen_on(6881, 6891)
    params = {
        'save_path': TorrentFilePath,
        'duplicate_is_error': True}
    link = "magnet:?xt=urn:btih:599e3fb0433505f27d35efbe398225869a2a89a9&dn=ubuntu-10.04.4-server-i386.iso&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.ccc.de%3A80"
    handle = lt.add_magnet_uri(ses, link, params)
#    ses.start_dht()
    print 'saving torrent file here : ' + TorrentFilePath2 + " ..."
    while (not handle.has_metadata()):
        time.sleep(.1)
 
    torinfo = handle.get_torrent_info()
 
    fs = lt.file_storage()
    for file in torinfo.files():
        fs.add_file(file)
    torfile = lt.create_torrent(fs)
    torfile.set_comment(torinfo.comment())
    torfile.set_creator(torinfo.creator())
 
    f = open(TorrentFilePath2 + "torrentfile.torrent", "wb")
    f.write(lt.bencode(torfile.generate()))
    f.close()
    print 'saved and closing...'
 
#Uncomment to Download the Torrent:
#    print 'starting torrent download...'
 
#    while (handle.status().state != lt.torrent_status.seeding):
#        s = handle.status()
#        time.sleep(55)
#        print 'downloading...'

This will create a folder inside of ‘/home/dan/torrentfiles/’ with a structure like:

/home/dan/torrentfiles/545465456.12/545465456.12.torrent

I added this to GitHub if you want to Fork it.
https://github.com/danfolkes/Magnet2Torrent

ENJOY!

Web Service using JSONP from External Domain – PHP – JQuery

You may want to look at this previous post where I setup a PHP Webservice that uses JSON PDO – Accessed by JQuery AJAX

OK, so this code will use php to generate the JSON code that will get delivered over the internet to the JSONP (JSON Padding) client on an external domain. This allows your webservice to be available too whoever wants to call it.

Here is the PHP Code: (Not all of it, but enough to get the idea)

//http://SERVER_domain.com/webservice.php
private function GetTriviaTag($row) {
	$t = new Tag();
	$t->id = $row['id'];
	$t->triviaid = $row['triviaid'];
	$t->tagid = $row['tagid'];
	return $t;
}
public function GetWhere($where) {
	$retArray;
 
	$sql = "SELECT * FROM trivia_tags WHERE {$where}";
	foreach ($this->pdo->query($sql) as $row)
	{
		$retArray[] = $this->GetTriviaTag($row);
	}
	return $retArray;
}
$where = " (1 = 1)";  // THIS WILL SELECT ALL
$tarray = GetWhere($where);
 
//OUTPUT JSON:
header('Content-type: application/json');
echo $_GET['callback'];  // <-- THIS IS IMPORTANT FOR EXTERNAL DOMAIN ACCESS!!!
echo "(" . json_encode($tarray) . ")";

And now, to access it from javascript in an external domain (non – SERVER_domain.com ):
http://CLIENT_domain.com/Test.html:

<html>
	<head>
		<title>Test</title>
		<script src="http://code.jquery.com/jquery-latest.js"></script>
	</head>
	<body>
		<div id="triviaQuestions"> loading... </div>
		<script>
			$(function() {
				// THE 'callback=?' in this request is IMPORTANT FOR EXTERNAL DOMAIN ACCESS!!!
				$.getJSON('http://SERVER_domain.com/webservice.php&callback=?', function(data) {
					var items = [];
					var htmlResult = "";
					$.each(data, function(key, val) {
						htmlResult += "<br />Q: "+ val.id +", '"+ val.question +"";
					});
					$('#triviaQuestions').html(htmlResult);
				});
			});
		</script>
	</body>
</html>

PHP Webservice that uses JSON PDO – Accessed by JQuery AJAX

You may want to look at this previous post where I setup a Web Service using JSONP from External Domain – PHP – JQuery

The HTML that calls the Javascript:

<div id="taglist"></div>
<input name="searchTags" id="searchTags" type="text" />
<input type="button" name="searchtags" onclick="getTags()" value="search"/>
<div id="tagresult">
</div>

The JavaScript (JQuery) AJAX Request and Response Processing:

function getTags()
	{
		var q = $('#searchTags').val();
		$.getJSON('ws.php?type=tag&wN=name&wO=like&wV=' + q, function(data) {
			var items = [];
			var htmlResult = "";
			$.each(data, function(key, val) {
				//As you can see, you can access the JSON (at the bottom of the page) by doing val.PROPERTYNAME:
				htmlResult += "<br />Add : <a href=\"#\" onclick=\"addTag("+ val.id +", '"+ val.getfullname +"'); return false;\">"+ val.getfullname +"</a>";
			});
			$('#tagresult').html(htmlResult);
		});
	}

PHP Code that returns JSON in the PHP file called by the AJAX: (ws.php)

	$ta = new TagAccess();
	$tarray = $ta->GetTagsWhere(" {$whereName} LIKE '%{$whereVariable}%'");
	header('Content-type: application/json');
	echo "",  json_encode($tarray), "";

The GetTagsWhere Helper Function:

    public function GetTagsWhere($where) {
    	$retArray;
 
    	$sql = "SELECT * FROM tags WHERE {$where}";
    	// THE PDO Object was created previously
	foreach ($this->pdo->query($sql) as $row)
	{
		$retArray[] = $this->GetTag($row);
	}
	return $retArray;
    }

JSON Returned:

[{"id":"4","name":"FICTION","parentid":"3","getfullname":"BOOKS > FICTION"},{"id":"5","name":"NON-FICTION","parentid":"3","getfullname":"BOOKS > NON-FICTION"}]

ASP.Net Update Panel – Javascript Event – jQuery Click

I needed to add a onclick event to a textbox in asp.net to change it to remove text from a textbox onClick when it is clicked.
The normal code would look something like this:

1
<asp:TextBox  ID="txtStoreLocatorZip" ValidationGroup="CustomerServiceEmail" runat="server" Text="Enter Zip" CssClass="txtStoreLocatorZip_CssClass" />
1
2
3
4
5
6
7
8
9
<script>
        if ($('.txtStoreLocatorZip_CssClass').val() == 'Enter Zip') {
            $('.txtStoreLocatorZip_CssClass').click(function () {
                if ($('.txtStoreLocatorZip_CssClass').val() == 'Enter Zip') {
                    $('.txtStoreLocatorZip_CssClass').val('');
                }
            });
        }
</script>

But, this won’t quite work because my textbox is in a UpdatePanel’s ContentTemplate and the javascript is not read on postback.

So, This is what I ended up doing (a simplified version):

1
2
3
4
5
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
	<ContentTemplate>
		<asp:TextBox  ID="txtStoreLocatorZip" ValidationGroup="CustomerServiceEmail" runat="server" Text="Enter Zip" CssClass="txtStoreLocatorZip_CssClass" />
	</ContentTemplate>
</asp:UpdatePanel>
1
2
3
4
5
6
7
8
9
10
11
12
<script>
	Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
	function endRequestHandler(sender, args) {
		if ($('.txtStoreLocatorZip_CssClass').val() == 'Enter Zip') {
			$('.txtStoreLocatorZip_CssClass').click(function () {
				if ($('.txtStoreLocatorZip_CssClass').val() == 'Enter Zip') {
					$('.txtStoreLocatorZip_CssClass').val('');
				}
			});
		}
	}
</script>

This will add an endRequest handler to the end of the partial page postback so that you can call a nice little function at the end of it.

Hope this helps some people!

Asp.Net – Adding Parameters to CommandType.Text

This is how you add parameters to a standard CommandType.Text SQL call.

This should prevent sql injection attacks.

        Using conSQL = New SqlConnection("CONNECTION STRING TO DATABASE")
            Try
                str = "SELECT * FROM TableName where customerid = @CustomerID and CartType = @CartType"
                cmdSQL = New SqlCommand(str, conSQL)
                cmdSQL.CommandType = CommandType.Text
                cmdSQL.Parameters.AddWithValue("@CustomerID", CustomerID)
                cmdSQL.Parameters.AddWithValue("@CartType", cartType)
                cartcount = cmdSQL.ExecuteScalar()
            Catch ex As Exception
                cartcount = 0
            End Try
        End Using

Asp DropDownList – States – ListItem Example

Asp DropDownList - States - ListItem Example
Compiled List of US State Drop Downs for Asp.Net Forms:

Hope this helps!

<asp:DropDownList ID="ddlState" runat="server">
    <asp:ListItem Value="" Selected="True">Select a State</asp:ListItem>
    <asp:ListItem value="AL">Alabama</asp:ListItem>
    <asp:ListItem value="AK">Alaska</asp:ListItem>
    <asp:ListItem value="AZ">Arizona</asp:ListItem>
    <asp:ListItem value="AR">Arkansas</asp:ListItem>
    <asp:ListItem value="CA">California</asp:ListItem>
    <asp:ListItem value="CO">Colorado</asp:ListItem>
    <asp:ListItem value="CT">Connecticut</asp:ListItem>
    <asp:ListItem value="DC">D.C.</asp:ListItem>
    <asp:ListItem value="DE">Delaware</asp:ListItem>
    <asp:ListItem value="FL">Florida</asp:ListItem>
    <asp:ListItem value="GA">Georgia</asp:ListItem>
    <asp:ListItem value="HI">Hawaii</asp:ListItem>
    <asp:ListItem value="ID">Idaho</asp:ListItem>
    <asp:ListItem value="IL">Illinois</asp:ListItem>
    <asp:ListItem value="IN">Indiana</asp:ListItem>
    <asp:ListItem value="IA">Iowa</asp:ListItem>
    <asp:ListItem value="KS">Kansas</asp:ListItem>
    <asp:ListItem value="KY">Kentucky</asp:ListItem>
    <asp:ListItem value="LA">Louisiana</asp:ListItem>
    <asp:ListItem value="ME">Maine</asp:ListItem>
    <asp:ListItem value="MD">Maryland</asp:ListItem>
    <asp:ListItem value="MA">Massachusetts</asp:ListItem>
    <asp:ListItem value="MI">Michigan</asp:ListItem>
    <asp:ListItem value="MN">Minnesota</asp:ListItem>
    <asp:ListItem value="MS">Mississippi</asp:ListItem>
    <asp:ListItem value="MO">Missouri</asp:ListItem>
    <asp:ListItem value="MT">Montana</asp:ListItem>
    <asp:ListItem value="NE">Nebraska</asp:ListItem>
    <asp:ListItem value="NV">Nevada</asp:ListItem>
    <asp:ListItem value="NH">New Hampshire</asp:ListItem>
    <asp:ListItem value="NJ">New Jersey</asp:ListItem>
    <asp:ListItem value="NM">New Mexico</asp:ListItem>
    <asp:ListItem value="NY">New York</asp:ListItem>
    <asp:ListItem value="NC">North Carolina</asp:ListItem>
    <asp:ListItem value="ND">North Dakota</asp:ListItem>
    <asp:ListItem value="OH">Ohio</asp:ListItem>
    <asp:ListItem value="OK">Oklahoma</asp:ListItem>
    <asp:ListItem value="OR">Oregon</asp:ListItem>
    <asp:ListItem value="PA">Pennsylvania</asp:ListItem>
    <asp:ListItem value="RI">Rhode Island</asp:ListItem>
    <asp:ListItem value="SC">South Carolina</asp:ListItem>
    <asp:ListItem value="SD">South Dakota</asp:ListItem>
    <asp:ListItem value="TN">Tennessee</asp:ListItem>
    <asp:ListItem value="TX">Texas</asp:ListItem>
    <asp:ListItem value="UT">Utah</asp:ListItem>
    <asp:ListItem value="VT">Vermont</asp:ListItem>
    <asp:ListItem value="VA">Virginia</asp:ListItem>
    <asp:ListItem value="WA">Washington</asp:ListItem>
    <asp:ListItem value="WV">West Virginia</asp:ListItem>
    <asp:ListItem value="WI">Wisconsin</asp:ListItem>
    <asp:ListItem value="WY">Wyoming</asp:ListItem>
</asp:DropDownList>

More State Drop Downs After the fold:
Continue reading “Asp DropDownList – States – ListItem Example”