At the end of last year, I was torn between two modules; Artificial Intelligence, and Electronics and Interfacing. Artificial Intelligence has always been one of the areas of Computer Science I’ve been most interested in, whereas, I love playing with Electronics (let’s face it, who doesn’t?) In the end, I opted for Artificial Intelligence, as I felt I would learn more from that module, and a different type of Programming (logic) would be a new challenge, as opposed to electronics.
However, for the past few weeks, I’ve been turning up to Rob’s electronics lectures (even though they mean getting out of bed for a 9.15 every Tuesday and Thursday), and so far he hasn’t said anything. It’s great fun. The first few weeks went over the very basic physics of electricity and different things, such as current and resistance, and this morning we got to play with some real hardware. We’re using the .NET FEZ framework, and I have to say, it was really easy to get simple things working.
This morning, we got the main processor board out of the box, plugged it in, pushed an LED module into the board, and had it flashing every 1/2 a second with 2 lines of code. Lovely stuff. To make things slightly more interesting, me and Danny decided to introduce a second LED, and alternate the flashes, so one LED was lit, it would then go off, and the other would light up. We got a small rave-type mood going at half 9 in the morning!
We then introduced a button. This is where we found something quite interesting. We wrote some basic code, which would basically light the LED’s up whenever the button was pressed, and as soon as the button was no longer being held down, the LED’s would go off. In theory, anyway. What happened, however, was the exact opposite. With no button being held down, the LED’s were on, and with a button being held down, the LED’s would shut off. Very odd. It took a few minutes for us to realise that, actually, for some reason, “button.Read()” was returning true (1) when nothing was being pressed, and false (0), when something was being pressed, so we simply changed the direction of the code to look something like this:
if (!button.Read())
{
led.Write(true);
led2.Write(true);
}
else
{
led.Write(false);
led2.Write(false);
}
Small problems aside, it was real fun, and hopefully I’m going to be working on a more interesting project in the next year, involving Gadgeteer, GPS and Cellular radio transmissions. Hopefully. Fingers crossed!
All words are valuable, but some more than others. In programming, there seem to be a lot of very important words, much like any language. This time, however, I’ve got a little tip for people to avoid a particularly annoying bug I’ve just spent half an hour on.
Here’s some code (in Java):
switch(itemPosition) {
case 0:
{
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (mainFragment == null)
{
}
else {
ft.replace(R.id.content, mainFragment, null);
ft.commit();
}
}
case 1:
{
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (mediaFragment == null) {
mediaFragment = Fragment.instantiate(getApplicationContext(), MediaFragment.class.getName());
}
ft.replace(R.id.content, mediaFragment, null);
ft.commit();
}
}
Now, this doesn’t really matter much in C#, because the code wouldn’t compile. It’s missing a very important word, which should occur twice in this piece of code. It’s missing the “break;” command. The break pulls the code out of the switch statement, however, this is apparently a very easy word to forget, and I didn’t realise for a time,. What happens if you miss this word out, is that after the first case, it moves onto the next one, and executes all the code in that block, and carries on to the bottom. So I was wondering why I would be loading the mainFragment, and the mediaFragment would be displaying on my phone’s screen instead. Very annoying.
In C#, and probably some other compilers, this fails to compile. It is a built in syntax that you must end each case statement with a break, no matter what. In other languages, however, this doesn’t happen, as there may be some reason why you want to fall through all the statements. Personally, I have never found a place where I want to fall through to the bottom of the code, and I’m not sure if I ever will, but the choice is always nice.
Just a little programming tip for everyone. Remember the important words!
A few weeks ago, I downloaded and installed Windows 8, mainly because I like playing with new Operating Systems, and wanted to do some development for it. So far, my experience has been overwhelmingly positive, however, there are lots of little things in this release which I find really annoying, fiddly, and downright stupid.
This isn’t just going to be another blog post ranting about the absence of the start button, or the click icon is rounded instead of square. I actually really love the new start menu. I might be in the minority, but I think it’s laid out a lot better than the legacy start menu, more personalisable, and you can easily access the things you use the most, more so than the previous start menu, which has been around for years. As for a rounded click icon instead of a squared, I don’t really notice that too much (sorry, Rob!)
As for the “Windows 7″ side of things, I feel Microsoft have once again built on what they did in the previous release, and I’d have a very hard time criticizing it. I’ve thrown numerous different devices at it, and the it’s recognised and installed the drivers for them within seconds. The new folder view is also rather nice, with an “Office-style ribbon” at the top. It all feels very nice and natural to use.
Now come the problems. The built-in apps that are provided by Microsoft have major problems with them. First up; Xbox Music.
Xbox Music is the natural successor to Zune, really. I really loved Zune. I would have used it as my only music player in Windows 7, if only it would have supported FLAC, and synced with my MP3 player. The UI was lovely, everything just worked. The first problem I had with Xbox Music came at the very start. I was trying to add music to my library. In Zune, it was simple; Zune would scan the “My Music” library, and add everything in there. There were also options to add new folders that it would add new material to as soon as it appeared, without telling you. Really great stuff.
Xbox Music, however, just scans the “My Music” library. That’s it. There is no “Add folder to scan” option, or anything like that. As I’m using an SSD for my OS, I have my music stored on a separate drive (E:). To add this to the library was pretty simple, the same as Windows 7, however, Xbox Music still wasn’t showing anything was there. I had to physically re-boot the PC for it to realise that I wanted that included in the library too. After that, the UI has changed, I feel for the worse, but I’ll just get used to that. The deal breaker came just now, when I tried searching for a band I wanted to listen to, to find there is no search function. Or at least no search function that I can find.
I’ve also had a fairly unpleasant experience with Xbox Video, but this time it’s nothing too major, and could possibly be my slightly out-of-date GPU, but whenever I open an .avi, there is about 30 seconds where the video doesn’t render, and the video slowly staggers to catch up, which is quite annoying at times, so I’ve switched to using VLC instead. Among other reasons, it actually lets me play DVD’s.
The default pictures application also seems to be lacking the support that we’ve come to expect from Microsoft. Opening a picture does what it says on the tin, opens the picture. You can look at it, lovely. But when you want to see the next picture? You have to alt + tab out of the application, and physically open the next picture. There is no left or right arrow commands, which to me seems very strange and unfriendly to the user.
Other stock apps lack certain small things, but are fully usable. For instance, the Messaging app doesn’t support Google Talk, or group chat. It works lovely for Facebook chat, and I’m sure Windows Live, but without group chat is a bit useless, as that’s mainly what I use Facebook messaging for. The Calendar only allows one calendar per account, which is a bit of a letdown when I have about 10 different calendars on my Google account, and can only have my own calendar displayed. Hopefully this will be resolved, however, as Windows Phone 7 allows multiple calendars. The only stock app I can think of that doesn’t have an obvious issue so far is the mail program, which is rather lovely, so kudos to Microsoft for that.
Overall, Windows 8 is a rather nice Operating System, but on the “Modern Xperience” side of things, the built in apps leave a lot to be desired, when we’ve come to expect so much.
So in my last blog post, I outlined the basic steps to get some cryptography going to encrypt strings. In this post, I’m talking about C# and MySQL. First of all, to connect to a MySQL Database, you need to download the free libraries, which can be found here. After installing those, you will now be able to add the reference “MySql.Data”. The libraries are essentially an extension of the “SqlClient” libraries which are included in .NET, but which, obviously, can be used with MySQL.
After adding the reference, we need to use the add the namespace “using MySql.Data.MySqlClient” to the top of the code. MySQL, and SQL, require connection strings to connect to a server and database. In the case of this, the connection string might look something like this:
string connectionString = “server=DOMAIN_NAME.COM; database=DATABASE_NAME;uid=USER_NAME;pwd=PASSWORD”;
Obviously, there are many different types of connection string, and many different parameters you can put into a string, there’s a nice website I’ve found, which lists all of the different connection string types and examples, here.
So, to connect to a database, it’s very simple. We have our connection string, let’s put that into code:
public LoginDatabase()
{
string connectionString = "server=DOMAIN_NAME.COM; database=DATABASE_NAME; uid=USER_NAME; pwd=PASSWORD;";
connection = new MySqlConnection();
connection.ConnectionString = connectionString;
try
{
connection.Open();
}
catch (Exception e)
{
//show an error message
}
}
As you can see, the libraries are very easy to use. The hard bit is configuring the database to allow you to connect, grant all the permissions, etc. Now, if we take the example from the last blog post of a login, we have three fields we want to insert into the database; Username, Password, and Salt. Assuming I’ve already made the database, we can use an Insert to put the data in. An “Insert Into” command would look something like this:
string insertString = String.Format(“INSERT INTO User (Username, Password, Salt) VALUES (‘{0}’, ‘{1}’, ‘{2}’)”, username, password, salt);
We then take advantage of the “MySqlCommand” type in the MySql libraries to actually execute the query. Here’s some code:
public int InsertNewUser(string username, string password, string salt)
{
string insertString = String.Format("INSERT INTO User (Username, Password, Salt) VALUES ('{0}', '{1}', '{2}')", username, password, salt);
Console.WriteLine("Inserting new User: ");
Console.Write(insertString);
MySqlCommand cmd = new MySqlCommand(insertString, connection);
try
{
connection.Open();
cmd.ExecuteNonQuery();
return 1;
}
catch (Exception e)
{
//print error
return 0;
}
finally
{
connection.Close();
}
}
That’s the very basics of MySQL in C#. Have fun!
Recently, I’ve been really interested in creating secure systems, or rather, systems which seem pretty secure to me. I’ve been doing quite a bit of research around this area, and cryptography in general, to find out common practices for security, so I thought I’d share something I built today.
When you sign up to a website, or, a more probable use for this, when a system is created which requires a username and password to login, it has to store both of these somewhere, so that it can actually check if you are a real person, and you are a person who has the rights to be there. This is usually done with a database. Throughout my programming time, I’ve done quite a bit with databases, to the point where I feel like it’s one of my specialties. I don’t quite know whether this is good or bad, but it’s always good to be good (or at least decent) at something, right?
So, thinking security, I thought “login system”. Secure login system. Pretty simple stuff. Obviously, in this day and age of cyber attacks, it would be very stupid to store these details in a way that people could just execute a simple query to draw the data, for example;
SELECT Username, Password FROM Users WHERE Username = `Nick`
So we need to encrypt the password. Encryption is fairly simple these days, there are plenty of different hashing functions available for use. Personally, I chose an SHA-2 encryption method, which was developed by the NSA, and is used by them. Turns out there are lots of methods built in for cryptography in C#. To access them, simply add the “System.Security.Cryptography” namespace. Here’s the general code for encrypting a password:
public string EncodePassword(string password)
{
Byte[] originalBytes;
Byte[] encodedBytes;
SHA512 sha2;
sha2 = new SHA512CryptoServiceProvider();
originalBytes = ASCIIEncoding.Default.GetBytes(password);
encodedBytes = sha2.ComputeHash(originalBytes);
return BitConverter.ToString(encodedBytes);
}
This is quite good, and returns a string that looks something like:
B6-19-6D-DB-1B-34-3E-E6-26-6A-22-71-E9-95-48-8D-D0-D1-66-74-4B-50-9C-20-B8-5D-ED-0A-BB-AA-88-E7-91-AD-EC-17-C8-F9-AE-84-80-B7-4B-1B-4F-BD-B1-31-CE-F0-69-2E-3C-A6-E4-A0-F2-90-4D-5B-6B-00-DB-82
To get that output, the input was “hello123″. Now, this is very good, however, if I were to run “hello123″ through the algorithm again, I would get the exact same output. “hello123″ is probably quite a common password (as much as it shouldn’t be). Hackers use what are called “Rainbow Tables”, lists of common passwords to try running through the algorithm, very similar to how the bombe worked in World War 2 at Bletchley Park. To try and stop this, we add a “Salt” to the password, which is a random set of characters added to the end or beginning of a password before it is encrypted. In this case, the algorithm picks a random length between 4 and 8. Here’s the code for that bit:
public string GetSalt()
{
Byte[] saltBytes;
int minSalt = 4;
int maxSalt = 8;
Random random = new Random();
int saltSize = random.Next(minSalt, maxSalt);
saltBytes = new Byte[saltSize];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetNonZeroBytes(saltBytes);
return BitConverter.ToString(saltBytes);
}
After adding the salt to the end of the password, the same “hello123″ password gives an output of:
75-14-86-E4-41-55-37-7B-F1-07-4B-73-DC-20-8A-A7-37-19-C2-59-03-76-29-19-CD-7C-EA-BC-77-E0-52-C3-A7-63-90-68-C4-59-56-BF-62-87-FE-AF-C9-57-34-41-BF-AF-67-A2-AE-8E-09-45-2B-A2-41-CB-DC-CC-84-65
Pretty different from the original, which is great. Each time a new salt is generated, the encrypted password will change by a massive scale, too. The salt is then stored in a data row alongside the username and password.
If anyone has any questions/comments/tips, or anything I’ve got wrong, please feel free to comment. We’re all here to learn, afterall, right?
Next time I’ll discuss taking these and putting them in a MySQL database (although, again, that’s pretty simple)
So for the last week I’ve been back in Hull, and I’ve mainly been settling in and catching up with friends again. I’ve spent a lot of time with Danny and co, and I seem to have been to more Fresher events than I did last year.
Today, I went to the “Movie Buff’s Collectors Fair” in the Prospect Center, which was great. It was basically a lot of stalls selling extremely geeky things which I wanted, but couldn’t afford. It was also quite a nostalgia trip, with a lot of “I used to have that!” Luckily for my bank balance, I only bought one thing, although I could have easily spent a lot more.
One of things I nearly bought I took a picture of instead. I’ve not been a Star Trek fan for a massive amount of time, although this just looked amazing. It was right next to a Tracy Island playset, too.
What I did buy, though, was a massive box full of Star Wars Trading Cards. I got a deal and the whole box for £5, and the guy even threw in about 100 MTG cards too. I tried to count how many Star Wars ones there are, but got as far as 1,000 and wasn’t halfway through, so gave up.
I’ve also been getting back into the swing of programming properly, and have started learning some of the Windows 8 API, and more complex Android techniques. So far Windows 8 seems pretty nice to work with, but I haven’t dived fully into it yet.
Lectures start again on Monday, so I can’t wait to get back into learning properly.
I gave my Kindle such an imaginative name.
Today, a certain book, which I’m not going to name, but should be stupidly obvious, is released. It is being released in two forms; hardback and e-book. I’ve long thought books price themselves out of their own market at times, and this book is a prime example. For a day one purchase, the hardback will set you back £20. Bearing in mind this is for a 500 page fiction novel, it’s a bit of a stupid price.
Now, the e-book version, I will give credit to, because for once the digital copy is actually cheaper than the hardback, although a quick look at the RRP on the e-book copy shows it was originally marketed as the same price. One of the things that annoys me most about this age is that quite often, especially with e-books, you are expected to pay as much as, if not more than the cost of the same book in hardback. To me, this doesn’t make sense. Speaking logically, a digital copy should have far less costs involved in creating. There is no manufacturing process, no paper or ink to pay for, just space on the server, which Amazon undoubtedly take a percentage of the purchase for, and can’t really be that much, bearing in mind the file is only 700kB.
I have a feeling that this book is priced at £20 to rake money in. The author is extremely well known, and the book is somewhat hyped, and many people will buy the book without even looking into reviews, or what the actual content of the book is simply because it is the author, so for the publishers, it does make sense to charge an extortionate fee on day one, bearing in mind the number of people who will buy the book straight off the mark. However, other books aren’t this way. Publishers talk of people not buying as many books as they used to. I’d say that more people would buy books and read if the books weren’t so expensive all the time. If a new book was, say £5 instead of £10 for a paperback, it would make them much more affordable, and maybe encourage more people to do what I believe is one of the most important things in life, reading.
The low pricing strategy seems to have been part of the staggering success of the “50 shades” series. I’m not going to write my thoughts about that particular series, but it certainly showed that people are interested in reading, and people will still buy books.
Over the summer, I’ve been spending a bit of time getting to grips with good android development. One of the things I was always wary of about android is that there seemed to be now definitive style, like there is in the iOS and Windows Phone markets. With the last few releases of android, however, (namely Ice Cream Sandwich and Jelly Bean), I feel google have really improved upon this, and now have some brilliant design guidelines, and it is now much easier to create professional looking apps in a decent amount of time.
In particular, the updates to the “Action Bar”, which is displayed at the top of an app, have been remarkable. When I got my Galaxy Nexus, I noticed all the stock apps used this type of navigation, and thanks to the new design guidelines and principles put together by Google, the design of these is rather simple.
What isn’t so simple is actually finding out how to make things work, which seems to be the biggest problem with Android programming. Google give you enough to know what you should be doing, but don’t actually give you many examples of code to get you rolling. For example, this is what the guidelines tell you regarding a drop down menu:
Not very simple for someone just getting to grips with Android programming. So here’s some basic code to go along with this:
private void CreateActionBar(final Context c) {
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.Menu, android.R.layout.simple_spinner_item);
//This creates an adapter to display the string array in menu form
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//This makes it a drop-down type
ActionBar ab = getActionBar();
//Get the instantiation of the Action Bar
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
//Set the navigation mode to list
ab.setDisplayShowTitleEnabled(false);
//Don’t display the title of the app
ActionBar.OnNavigationListener mOnNavigationListener = new OnNavigationListener() {
public boolean onNavigationItemSelected(int itemPosition,
long itemId) {
Toast.makeText(c, “You selected ” + getResources().getStringArray(R.array.Menu)[itemPosition] , Toast.LENGTH_LONG).show();
return false;
}
//This listens for a navigation event. If one is found, it currently fetches the name of the position of the array navigated to and displays it as a toast. In a real app, a switch statement would probably be used to change the page
};
ab.setListNavigationCallbacks(adapter, mOnNavigationListener);
//This actually sets the navigation listener listening
}
There are some other things that need doing, for example, I added the string array into the “strings” xml file, and dynamically call that each time I need to use it, as seen at the “getResources()” call.
Just a quick blog to say a few things:
Firstly, exams are over, woo! Only had 3, but there was still the cramming of revision towards the end, particularly for the Quantitative Methods and Software Engineering modules, but I think overall things went pretty well.
I have a few projects for over the summer, and I’ll post another blog about those over the next few days, but I’ve just spent the last day(ish) trying to fix a strange bug I’ve had while trying to make a Linq Database in C#.
In Linq, there is a lovely parameter which you can set for the primary key, which makes the Database create the key. i.e, if I had 200 customers, and they all needed (of course) unique bank numbers, then, instead of my program having to find the last one, and iterate it by one, or the user actually typing out a new number, the database will just add 1 to the number of rows already in the table, so I will have 1,2,3,4,5,6, etc. all done for me, and I don’t have to worry about clashes.
(If you’re interested, then the syntax looks something like this:)
[Column(IsPrimaryKey = true, IsDbGenerated = true)]
public int xPrimaryKey
{
//accessor and mutator here }
However, this only works if it is declared as an integer. Yesterday, while I was typing up my columns, I forgot this, and declared it as a string, and that led to this nasty error message when I tried to create the database:
There was an error parsing the query. [ Token line number = 2,Token line offset = 15,Token in error = IDENTITY ]
Happy programming!
Late last year, I built a basic RSS reader app for our Scout group on Windows Phone, which was just a bit of fun on the side of everything, however, it got me thinking about actually making a proper app for them. A few conversations later, it was clear they wanted something on Android rather than Windows Phone, which was my real comfort bubble. Zoom forward to a couple of weeks ago, when I built the basic RSS functionality on Android, and a UI design (easier said than done, using Android), and it works…ish. I’m now working on getting a basic description of the article displayed under the title, which in Java is interesting.
When I read the RSS in, it’s full of html. Something along the lines of:
<p><img src> //image url</img src></p><p> </p>
Let’s take a look at how .NET handles this, using regular expressions:
//Get RSS data as an object called "value"articleString = Regex.Replace(value.ToString(), "<[^>]+>", string.Empty); //This gets rid of all the html tags
That’s rather nice. Just 1 simple method which takes in; an input, the dirty regular expression you’re looking for, and what you want to replace it with. It then spits out a string at the end free of html. Lovely!
But what about Java?
After a lot of head scratching, and a bit of googling, I realised there’s a class in Java that does similar things, but not in the same way. I spent a while figuring out exactly how to use it, and in the meantime, my TARDIS of tea went cold. But that’s irrelevant. Here’s the code:
import java.util.regex.Matcher;import java.util.regex.Pattern; //two libraries which do the regexString inputString = (data.get(position).getDescription()); //gets the text with the messy htmlPattern regex = Pattern.Compile("<[^>]+>"); //The regex we are looking for - Basically anything inside a "< >" tagMatcher regexMatcher = regex.matcher(inputString); //Finds themString resultString = regexMatcher.replaceAll(""); //Replaces them with nothing
As you can see, both do pretty much the same thing, but the C# implementation is much sleeker and nicer, using only one method for the regex, opposed to the 3 used in Java.
They both give the same result at the end, but C# wins the first round of “Java vs C#”!