General Programming


29
Dec 11

Life cycle model of Windows Phone apps and Tombstoning

Life cycle of program instances differ greatly between desktop and mobile and Windows Phone is no exclusion.Its essential to understand the application life cycle model before writing apps. Of course there are quite a few article explaining this but none pointing out the difference between SDK7.0 and SDK7.1. This article, briefly lets you understand the different states and the life cycle model changes between SDK7.0 and SDK7.1.

States

In Windows Phone (WP), every app goes thru’ three different states after its instantiated. Continue reading →


29
Dec 11

Starting off with Windows Phone 7 Programming

Windows Phone 7

Windows Phone 7 - Wikipedia

As I had mentioned earlier that I am planning to start off with Windows 8 programming, I also thought it would be logical to start off with Windows Phone 7 programming. I know, Windows Phone 7 has got nothing to do with Windows 8 programming, except for the UI and thats the reason. User Experience is really important, especially for handheld devices.

Here are a few things you need  before you kick start with Windows Phone 7 programming.

  • .NET and Visual Studio – you ought to be familiar with .net and Visual Studio.
  • WPF (xaml to be precise) – at least the fundamentals. The book that I have linked underneath lets you learn the basics but still I suggest a book that talks just about xaml (?!?).
  • **Silverlight – not necessarily; ifyou know WPF, well, thats enough.
  • Visual Studio 2010 with SP1 and Windows Phone 7.1 SDK.
  • Book or some kind of tutorial – obviously we start off with a book. Programming Windows Phone 7 by Charles Petzold is what I am currently learning.
  • Windows Phone – even though you get an emulator with Visual Studio Windows Phone 7 SDK, the emulator is every simple and you might not find it useful if you are planing to write complex applications involving multi touch gestures, notifications, etc.

I just started off with Windows Phone 7 programming last week and is really cool. I am finding it very simple as I have been working on .NET, C# and WPF for quite some time now. If you are new to WPF, I suggest you learn it and get acclimatized to the XAML fundamentals and syntax before you start off with WP7 programming. I will also try and write about things which I find notifiable, out here.

So long, lets write some Windows Phone apps ;-)


18
Dec 11

Windows 8 – Build

Windows 8

Windows 8

Windows 8. I tried out the OS last month; pretty neat. So now, I am planning to start off with the app development.

This is where I am gonna start from. Hoping to write more soon.


8
Jan 11

From .net to iOS

Its been a week since I started off with application development using iOS. So far the experiences has been awesome. So if you want to write programs for iPhone/iPod/iPad, all you gotta do is,

  1. Get a Mac. You cannot develop apps from your pc. I tried using virtual machine, but it is NOT POSSIBLE AT ALL. Forget about your pc. Go get your mac !!
  2. Once you have your mac, navigate to http://developer.apple.com. You have so many resources out there which should get you on board immediately

Tips for beginners,

  • Development Center – is really neat and way ahead than MSDN
  • Programming Paradigm – is MVC and should be familiar if you were programming for quite a while
  • IDE – XCode and InterfaceBuilder are the IDEs with which you write programs for iOS. Thou’ they are not as good as Visual Studio, they are pretty good for beginners
  • Programming Language – ObjectiveC – so far is the biggest challenge for me. If you are new to this, you will find it to be really weird
  • Unmanaged Code – if you are a .net programmer with no experience writing C/C++ programs, you should be extra careful in here
  • Tutorials and Samples – development center has got everything for you. Do not worry about this

Overall, the experience is good and exciting so far.


27
Nov 10

Visual Studio Equivalent

For those who wish to write c# code and cannot afford to buy Visual Studio, you have “Sharp Develop“, a open source comparable to Visual Studio.

One more happy news, they even have a WPF designer is a quite awesome. Give it a try


13
Jan 10

DoUNo: MDI in WPF

WPF, out of the box doesn’t have provision for MDI windows. The reason is quite simple, MDI windows are outdated and most of the applications have been using tabbed documents, proving they are really easy to use. Although the framework is flexible enough for you to make such a feature, its better to move to tab based interface.


6
Dec 09

Mashing Twitter and FSO

I really love Twitter and it didn’t make any sense to me to shell out a rupee for every tweet sent through my Airtel Mobile. Moreover, I am on one of those monthly booster packs which allows you to send 22000 text messages for free. I simply had to exploit this by setting up my own little ‘OC’ twitter forwarder written in python. (I know of smstweet.in service but I am still charged 1.50 for every tweet I send)

Its insanely simple to write such a ‘forwarder’ in python using the services provided by the FSO (freesmartphone.org) Framework,

  1. Send messages to your old/unused number whose SIM is in the Freerunner (or any other device supported by the FSO framework)
  2. Handle the incoming messages and use python-twitter API (or) raw urllib2 to post updates. Of course, the device should be connected to the internet, you can tether this device to an old unused computer. Simply put, the Freerunner should be able to access the internet.

I know this is dumb given cheap GPRS and all, but what the heck; Sundays _are_ reserved for dumb things and I wanted to show off how easy it is to develop and conjure up simple but powerful scripts using open hackable hardware like the Freerunner. So take off your pedantic hats ;)

Here is the actual python code,

#!/usr/bin/env python
# Written By Sudharshan S, http://sudharsh.wordpress.com
 
import dbus
import time
import logging
import twitter
 
import gobject
from gobject import MainLoop
 
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop (set_as_default = True)
 
# Use OAUTH?
USERNAME = "username"
PASSWORD = "password"
 
log = logging.getLogger("TweetForwarder")
 
class TweetForwarder:
 
   """Process Incoming messages and update twitter status
      if the message startswith 'tweet'
   """
 
   def __init__(self, username, password):
       log.warning("Starting up....")
       self.twitter_api = twitter.Api(username=username, password=password)
 
       # Get proxies and add signal handlers
       bus = dbus.SystemBus()
       _usage = bus.get_object("org.freesmartphone.ousaged",
                               "/org/freesmartphone/Usage")
       _proxy = bus.get_object("org.freesmartphone.ogsmd", \
                               "/org/freesmartphone/GSM/Device")
       self.usage_iface = dbus.Interface(_usage, "org.freesmartphone.Usage")
       self.usage_iface.RequestResource('GSM')
       self.sms_iface = dbus.Interface (_proxy, "org.freesmartphone.GSM.SMS")
       self.sms_iface.connect_to_signal ("IncomingMessage", self.onIncomingMessage)
 
   def onIncomingMessage(self, sender, message, kwargs):
       log.warning("Received SMS from %s:%s" % (sender, message))
       # We don't ALL messages to this number to be tweeted
       if message.strip().startswith("tweet "):
           log.warning("Trying to update status : %s" % message[6:].strip())
           self.twitter_api.PostUpdate(message[6:])
           log.warning("Updated Status")
 
   def run(self):
       loop = MainLoop()
       loop.run()
 
if __name__ == "__main__":
    logging.basicConfig()
    server = TweetForwarder(USERNAME, PASSWORD)
    server.run()
--

Make sure you have python-netclient and python-json installed on your Freerunner. These can be installed using the ‘opkg install’ command.

The script and the accompanying dependency can be downloaded from here. Just change the USERNAME and PASSWORD accordingly after scp’ing the tarball to your device.

Some useful links,

[1]: The FSO API reference

[2]: DBus Tutorial


6
Nov 09

DoUNo: Setting expectations on nullable type, NMock2

Ever had a problem of setting an expectation for nullable objects?

If you wanna return false when .HasValue of a nullable object is called, then you cannot do it with the normal expect statement. Rather, try not returning any values, because NMock2 returns default value of HasValue (False) if nothing is set as return values in expect statements.

Here is a sample,

public interface IProduct  //Interface that has a nullable member
{
  int? ProductNo  //Member that I wanna test and I wish to test the scenario in which this will be null
  {
    get;
  }
}
IProduct aProduct= myMockery.NewMock<IProduct>();
//Stub.On(aProduct).GetProperty("ProductNo").Will(Return.Value(default(int?));  //this statement produces a runtime exception, so we have to use the following instead
Stub.On(aProduct).GetProperty("ProductNo");  //no return value is set, nmock2 returns false when .HasValue is queries

Hope this helped you.

Sudarsan Srinivasan
- on behalf of my friends (they found this hack :P )


31
Aug 09

Accessing Command Prompt from C#

Recently, I wanted to write a program in c# that should start the command prompt in the background (it should not show the cmd window), give inputs from my C# program and get the results redirected back to my C# application. I was googling around a bit and then came up with a solution.

Its damn simple. Usually to start any process from C# applications, we use the Process object. The process object has two properties called StandardInput and StandardOutput. These properties will allow the C# application to get the input stream of the process that needs to be started. So to mock inputs and outputs, we need to do the following,

Process aProcess = new Process();
ProcessStartInfo aStartInfo = new ProcessStartInfo();
aStartInfo.FileName = Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\cmd.exe";
aProcess.StartInfo = aStartInfo;
aProcess.StandardInput.WriteLine("dir");  //will open a cmd process and feed the command "dir" to it

By this way you could give inputs to a process that you start from C#. What if you wanna see output of the cmd prompt in your own prompt ?? For this we use the StandardOutput property. But there is yet another simple way to get the output from the command prompt. This is done by subscribing for the event, OutputDataReceived.

aProcess.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived);
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
  textBox1.AppendText(e.Data);
  textBox1.AppendText(Environment.NewLine);
}

Note: These ways are possible only if,

aProcess.RedirectStandardOutput = true;
aProcess.UseShellExecute = false;
aProcess.BeginOutputReadLine();

are set to the mentioned values. BeginOutputReadLine method will start async read operations from the C# application stream instead of the standard input devices. So next time you wanna clone a command prompt, start the cmd process and give your own look and feel to it.


5
Jul 09

Give your boss the illusion of managing you… with pidgin and dbus

Dilbert.com

Oh yeah!. With the power of DBus and libpurple APIs it is possible to give your boss the illusion of managing you. Just run the following script (under WTFPL). Tested with jabber accounts in a live office environment :P .

#!/usr/bin/env python
# By Sudharshan S, released under WTFPL
 
import dbus
import gobject
import time
 
class PointyHairedBoss:
 
    def __init__(self, boss_id, source, frequency=30):
        self.boss_id = boss_id
        self.source = source
        self.frequency = frequency
        bus = dbus.SessionBus()
        _pidgin_proxy = bus.get_object("im.pidgin.purple.PurpleService", \
                                                       "/im/pidgin/purple/PurpleObject")
        self.purple = dbus.Interface (_pidgin_proxy, "im.pidgin.purple.PurpleService")
        # FIXME:
        account_id = self.purple.PurpleAccountsGetAllActive()[0]
        self.boss_conversation = self.purple.PurpleConversationNew(1, account_id, self.boss_id)
        self.boss_im = self.purple.PurpleConvIm(self.boss_conversation)
        print self.boss_im
 
    def start_nonsense(self):
        question_list = open(self.source)
        for q in question_list:
            self.purple.PurpleConvImSend(self.boss_im, q)
            time.sleep(self.frequency)
 
if __name__ == "__main__":
   # Change the jabber id and the path to your questions, with an optional frequency
   o = PointyHairedBoss("foo@gmail.com", "questions")
   o.start_nonsense()