Android

 

So it took me 2 hours (downloads on 2mbps included) to create an Android app in eclipse.

Wonder is that something I should be proud of giving I’ve been in software for nearly 15 years now…. 2 hours for a hello world… 

image

Listening to .net rocks and Xamarin podcast got me thinking, I really should see what’s involved in creating an Android app, after all I’m a registered Microsoft and Apple developer, I can create Wp7 apps in my sleep, I’ve even flirted with iOS, why not give Google and Android a shot.

I was going to install MonoDroid for VS2010, but hey i’m doing a hello world, no need for all this cross platformability. I’ve been doing a fair bit of java lately and eclipse doesn’t frighten me anymore so I just downloaded and installed the tools, and created the above app.. baby steps..

Any downsides? yes,, Now I wanna buy a Android tablet Who me?.

EF 4.1 Code First Database re-create

 

If you’ve upgraded to Entity Framework 4.1 you may have noticed the following no longer compiles. (the line of code that causes the database to drop and recreate on schema change).

image

Solution

DbDatabase.SetInitializer(new DropCreateDatabaseIfModelChanges<TCF.Models.TCFContext>());

 

image

HTML 5 Audio

 

So does your browser support the html5 audio tag when it comes to MP3s?

Browsers in order of my preference

 

IE9 – Nope

image

 

Firefox 5 – Nope, Moreover doesn't gracefully degrade to my fallback text!

image

 

Chrome 13 – Sure

image

 

Safari 5 – Arguably the best default experience

image

Try for your self and let me know how you get on (excuse the lack of the DOCTYPE, encoding etc.

It’s quote a catchy song, you’ll miss out if your browser doesn’t support it (or you are not familiar with view source Smile )

smart_ptr in java 1.7

 

Darn it but I’ve being doing a lot of Java recently and u know what, I’m no expert but it I think I could even a raise the rating on my C.V. at this stage. My first experience of Java was reading a book back in 2001 belonging to a student friend of mine, the book was lying about so picked it up and read it over the course of a week (yes I had an early addiction to technologies even though I was living in c++ land at the time). I ended up helping with one Final year project a java applet game suite if I remember correctly and in a JBuilder IDE.

Over the years I quickly forgot about my little affair with java and got deeper into c++ which I have to say I loved, around the same time I was having another affair (yes i was a slut) with Microsoft .net beta2. I can’t put my finger exactly on why c# won out for me, but I spent the next few years working on c++ and c#, Java was just something I always left to one side. I always though hey java will be easy, I’ve programmed in c#, same concepts, and moreover I knew c++, so well then c# or java are a walk in the part; while this I guess is partially true, but you’re not prepared you for the curve/slope/cliff you’ve got to climb to learn the IDE and the libraries needed these days.

I’m currently working for a data management company our products are written in java and .net. For the first two years I managed to live in the .net world but lately and mostly due to the success of some of our newer components I’ve been doing quite a lot of java, (a lot more than I ever expected). I’ve also started reading some good books on the subject and you know what I’m as likely to start a test application in Eclipse as I am in VS2010 these days (at least as far as the product components are concerned).

So what’s changed? Well for one the java language is evolving once again which is exciting; so to continue on my smart_ptr series of posts, we can now achieve resource cleanup with java 1.7 with the AutoClosable interface.

For .net people this will be very familiar to IDisposable and the using(var x = new IDisposableDerivedType())

 

   1:  File file = new File("input.txt");
   2:   
   3:  InputStream is = null;
   4:   
   5:  try {
   6:      is = new FileInputStream(file);
   7:   
   8:      // do something with this input stream
   9:      // ...
  10:   
  11:  }
  12:  catch (FileNotFoundException ex) {
  13:      System.err.println("Missing file " + file.getAbsolutePath());
  14:  }
  15:  finally {
  16:      if (is != null) {
  17:          is.close();
  18:      }
  19:  }
  20:   
  21:  Java 7: Try with resources
  22:   
  23:  File file = new File("input.txt");
  24:   
  25:  try (InputStream is = new FileInputStream(file)) {
  26:      // do something with this input stream
  27:      // ...
  28:  }
  29:  catch (FileNotFoundException ex) {
  30:      System.err.println("Missing file " + file.getAbsolutePath());
  31:  }

 

We’re guaranteed that the

is.close(); gets called automatically for us. Have to say I'm a bit jealous that the c# team didn't think of the try() syntax over using.

 
 
 

Why I love the Task library

 

Ok, forget about mvvm, that’s not the point of this quick post…

image

Have a look at that, ain’t it a thing of beauty!?

No more having to get back onto the gui thread, even webforms people have to do it with Control.Invoke
(or sync context).

Parallel task library rocks.

var keyword comes to c++

 

Ok so it’s not the var keyword in c++, but in C++11 it’s called auto.
This is something I love in c#, life would be miserable without it Smile, it’s magnificent especially in linq, infact linq could become quite painful without it (and also dynamic comes in handy in linq).

So where’s the sample?

image

The pDc has local scope and is of type CPaintDC*.

Now don’t be confused with the other place you may have used auto, i.e. back in the early days when we used to be concerned about putting things in registers (before the compilers took over this code generation heavy lifting).
e.g. auto int i = 0;

Sample html5 canvas drawing

 

So how hard is it to draw on a html5 canvas? Well if you ever lived in a GDI+ world like I once did, then it’s pretty simple. In fact it’s somewhat familiar to silverlight/wpf people too, the parameters passed to draw a rectangle for example are , left, top, width, height. (GDI/Windows API people would me more familiar to using left,top,right,bottom (the RECT struct). Nonetheless, IMO drawing with the html5 canvas couldn’t be easier.

image

 

Here’s the code

   1:  @{
   2:      ViewBag.Title = "Home Page";
   3:  }
   4:  <h2>@ViewBag.Message</h2>
   5:   
   6:  <canvas id="canvas" width="300" height="300">
   7:      Canvas not supported
   8:  </canvas>
   9:   
  10:   
  11:  @section Scripts
  12:  {
  13:      
  14:   
  15:      <script type="application/javascript">
  16:      
  17:          $(function() {
  18:              draw();
  19:          });
  20:      </script>
  21:   
  22:      <script type="application/javascript">
  23:          function draw() {
  24:              if (Modernizr.canvas ) {
  25:                  var canvas = document.getElementById("canvas");
  26:                  var ctx = canvas.getContext("2d");
  27:   
  28:                  ctx.fillStyle = "rgb(200,0,0)";
  29:                  ctx.fillRect(10, 10, 100, 1000);
  30:              }            
  31:          }
  32:      </script>
  33:  }

That’s all you need to get started, there are some nice libraries starting to emerge that use html5 canvas (graphing etc)

scoped_ptr in C#

 

Is there a better way? Or at least a more generic way to leverage the dispose pattern? Well here’s one I thought of tonight

 

   1:      public class ScopeMngr : IDisposable
   2:      {        
   3:          private Action _dispose = null;
   4:   
   5:          public ScopeMngr(Action init, Action dispose)
   6:              : this(dispose)
   7:          {
   8:              init();            
   9:          }
  10:   
  11:          public ScopeMngr(Action dispose)
  12:          {
  13:              _dispose = dispose;
  14:          }
  15:   
  16:          public void Dispose()
  17:          {
  18:              if (_dispose != null)
  19:              {
  20:                  _dispose();
  21:                  _dispose = null;
  22:              }
  23:          }
  24:      }

Sample usage:

   1:      public partial class Form1 : Form
   2:      {
   3:          public Form1()
   4:          {
   5:              InitializeComponent();
   6:          }
   7:   
   8:          private void button1_Click(object sender, EventArgs e)
   9:          {
  10:              using (var sm = new ScopeMngr(() => Cursor = Cursors.WaitCursor, () => Cursor = Cursors.Default))
  11:              {
  12:                  Thread.Sleep(TimeSpan.FromSeconds(10));
  13:              }
  14:   
  15:              bool updating = false;
  16:              using (var sm = new ScopeMngr(() => updating = true, () => updating = false))
  17:              {
  18:                  // updating is true here
  19:                  // update the UX etc.
  20:              }
  21:              // updating is false here
  22:   
  23:          }
  24:      }

 

P.s. I know creating an object to reset a boolean is a bit of overkill, but see my comments and argument for same in my c++ post 


Enjoy.

p.s. you could also just use a try {} finally {}

C++ 11–shared_ptr

To be honest, it’s been a long time since I did any real c++, however I’ve been reading a Java book lately and it’s made me kinda lonesome for C++, the Java book goes into a lot of detail about core language structure, it’s not a book on hibernate, swing etc, just core fundamentals like differences between an internal private class or an internal private interface, static binding of fields etc. I remember when I was at the height of my c++ development career I knew the intricacies about default parameters being statically bound in polymorphic classes, I knew about private inheritance, pitfalls of overriding non virtual functions, thinking back I knew the language quite intimately. Sure in the .net world I know quite a lot of the framework and the libraries toolsets etc (because i’m a greedy little pig and want to know everything) but, I wonder do i know the c# language quite as well as I once knew c++.

As I said at the outset I’ve been away from c++ for a few years now, I think the last time I did any commercial c++ was in 2006 when I was up to my eyeballs in boost/stl/wtl/atl etc, so what’s changed? Well there’s a new standard for one, C++11. Just to keep my finger in I’ve decided to start writing a few little blog posts on the new standard, this is the first one.

In Boost we used to used shared_ptr this class template stored a pointer to a dynamically allocated object, the object pointed to was guaranteed to be deleted when the last shared_ptr pointing to it was destroyed or reset.

e.g.

#include <vector>
#include <set>
#include <iostream>
#include <algorithm>
#include <boost/shared_ptr.hpp>
 
//  The application will produce a series of
//  objects of type Foo which later must be
//  accessed both by occurrence (std::vector)
//  and by ordering relationship (std::set).
 
struct Foo
{ 
  Foo( int _x ) : x(_x) {}
  ~Foo() { std::cout << "Destructing a Foo with x=" << x << "\n"; }
  int x;
  /* ... */
};
 
typedef boost::shared_ptr<Foo> FooPtr;
 
struct FooPtrOps
{
  bool operator()( const FooPtr & a, const FooPtr & b )
    { return a->x > b->x; }
  void operator()( const FooPtr & a )
    { std::cout << a->x << "\n"; }
};
 
int main()
{
  std::vector<FooPtr>         foo_vector;
  std::set<FooPtr,FooPtrOps>  foo_set; // NOT multiset!
 
  FooPtr foo_ptr( new Foo( 2 ) );
  foo_vector.push_back( foo_ptr );
  foo_set.insert( foo_ptr );
 
  foo_ptr.reset( new Foo( 1 ) );
  foo_vector.push_back( foo_ptr );
  foo_set.insert( foo_ptr );
 
  foo_ptr.reset( new Foo( 3 ) );
  foo_vector.push_back( foo_ptr );
  foo_set.insert( foo_ptr );
 
  foo_ptr.reset ( new Foo( 2 ) );
  foo_vector.push_back( foo_ptr );
  foo_set.insert( foo_ptr );
 
  std::cout << "foo_vector:\n";
  std::for_each( foo_vector.begin(), foo_vector.end(), FooPtrOps() );
  
  std::cout << "\nfoo_set:\n"; 
  std::for_each( foo_set.begin(), foo_set.end(), FooPtrOps() );
  std::cout << "\n";
 
//  Expected output:
//
//   foo_vector:
//   2
//   1
//   3
//   2
//   
//   foo_set:
//   3
//   2
//   1
//
//   Destructing a Foo with x=2
//   Destructing a Foo with x=1
//   Destructing a Foo with x=3
//   Destructing a Foo with x=2
   
  return 0;
}

 

In c++ 11 we now get a shared pointer as part of the standard, see my example below.

image

I know there were some overheads to the boost shared pointer, memory footprint etc, (consider 1x106). of these guys in a container!. But in general shared_ptr can help you, because if you do it manually you’ll likely write slower, buggier code (or both).

Tip: Auto Logon with Windows 7 User account.

 

Ok, only you can decide if this is something you want to do, keeping in mind the security concerns.

Here’s how:

  • Press the Windows key + R on your keyboard to launch the “Run” dialog box.
  • Type in control userpasswords2 + ENTER
  • The User Accounts window will display.
  • image
  • Uncheck “Users must enter a user name and password to use this computer”
  • Click OK
  • You will then be prompted to enter the current password and confirm it.
  • After doing so, you will no longer be prompted to enter your password upon login.