Category > Programming

Android and CLI

» 17 May 2013 » In Android, Programming » No Comments

Yesterday our training involved Android together with the command line interface. There’s not much chat, but overall, I can say that IDEs are optional. Really, I’m considering using command line on (almost) all my development environments.

I’ve learned android over a year ago, and it was just yesterday when I learned how compilation on android works (or at least the basic level). The most important thing I’ve learned yesterday is, command line should be for beginners. But in most points, command line is perfect on all levels. In beginners’ context, they can understand how things really work. IDEs hide most key parts in building, compilation, and interpretation. And in the professional context, command line gives complete control to the developer.

Thing is, it just sank into my brains.

Surely when a developer gets used to IDEs, he/she will be dependent on auto-complete, intellisense, error highlights, auto-debugs, etc. And when you take away those tools (hence IDEs) from that developer, without behind-the-scenes knowledge, he/she will be useless.

– Markku (Our finnish training instructor)

That’s all for this rant about IDEs and CLI. For my parting, here’s the script I wrote yesterday for CLI android building. (Credit goes to the training about Linux and scripting last week)

#!/bin/sh

# Version: 051613001

# This is used for debugging APKs. This command should be ran in the root directory of the project
# The name of the apk file is < ProjectName >-debug.apk and inside the bin directory

# Firstly, run ant debug
ant debug

# Get the project name and instantiate the apk file path
pname=$( pwd | awk -F/ '{ print $NF }' )
apk=bin/$pname-debug.apk

# Get the package name from AndroidManifest.xml
pack=$( cat AndroidManifest.xml | grep package | awk -F\" '{ print $2 }' )

# Get the first occurrence of the Activity
act=$( cat AndroidManifest.xml | grep 'activity android:name' | awk -F\" '{ print $2 }' | head -1 )

# Make sure the execution was successful first
if [ $? -eq 0 ]; then	

	# Check for the APK in bin directory
	if [ -f $apk ]; then
		# If found, install the file
		adb -d install -r $apk

		# Run the apk inside the application
		adb shell am start -n $pack/$pack.$act
		
		# Filter logcat to show the App's logs
		adb logcat ActivityManager:I $pname:D *:S
	else
		echo "[ERR] "APK $apk does not exist. > /dev/stderr
	fi
fi

For today, we’ll deal with bloody Objective-C.

Continue reading...

Tags: , , , , , , ,

Detecting Storage of Modern Smartphones

» 05 May 2013 » In C#, Programming, Technology » No Comments

I got my Nexus 4 few weeks ago. It has no micro-SD card slot, but this is not a rant about the lack of storage scalability. When you plug modern smartphones into a Windows machine, you’ll get a Portable Device label. What does it mean? It’s technically not a Removable Device.

Drives and Devices

Display of drives and devices connected to the computer

Please do note that this is not only a case for modern smartphones. Same applies for different devices such as portable media players (MP3 players, etc.)

The problem with this is, the device is not treated as a drive, so codes like this won’t show information about such devices.

foreach (DriveInfo dinfo in DriveInfo.GetDrives())
{
    Console.WriteLine(dinfo.RootDirectory);
}

Based on the above image, this code will only output:

C:\
D:\
E:\
F:\
G:\
H:\

It would be so much pain if I will be writing an automated process application that does something with the smartphone’s storage. But there must be a way, right?

If you are using VS, this will help you, open up your reference manager, and add these COM references.

Portable Device API

Portable Device API

But there’s another problem. This will only detect one device. Luckily we can edit the assembly, but first set Embed Interop Assembly on both interops to False

Embed Interop Assemblies

Embed Interop Assemblies

Now, go to your project’s folder, and navigate to \obj\Debug. Make sure the assemblies are inside that folder. Copy the full path, and open up Developer Command Prompt for VSXXXX where XXXX is your VS version.

Developer Command Prompt

Developer Command Prompt

Change the working directory to the path you copied earlier, and using ildasm, disassemble Interop.PortableDeviceApiLib.dll.

ildasm Interop.PortableDeviceApiLib.dll /out:papi.il

The MSIL Disassembler is a companion tool to the MSIL Assembler (Ilasm.exe). Ildasm.exe takes a portable executable (PE) file that contains Microsoft intermediate language (MSIL) code and creates a text file suitable as input to Ilasm.exe.

We’ve just disassembled Interop.PortableDeviceApiLib.dll, and now you can edit it with your favorite text editor. This is the line we’re looking for:

GetDevices([in][out] string&  marshal( lpwstr)

We need to change every occurrence of that to:

GetDevices([in][out] string[]  marshal(lpwstr[])

Short Explanation: We just changed the first parameter’s data type from a string reference, to an array of strings. This way, we can retrieve many devices.

Lastly, re-assemble the interop:

ilasm papi.il /dll /output="<obj Path>\Interop.PortableDeviceApiLib.dll"

For the code:

uint devNum = 1;
PortableDeviceManagerClass devM = new PortableDeviceManagerClass();
devM.GetDevices(null, ref devNum);
if (devNum > 0)
{
    string[] dId = new string[devNum];
    devM.GetDevices(dId, ref devNum);

    for (int dx = 0; dx < devNum; dx++)
    {
        Console.WriteLine("Device " + dx + 1 + " : " + dId[dx]);
    }
}

It will output lines like:

Device 1 : \\?\usb#vid_18d1&pid_4ee2&mi_00#6&68a019c&1&0000#{6ac27878-a6fa-4155-ba85-f98f491d4f33}

You can then use \\?\usb#vid_18d1&pid_4ee2&mi_00#6&68a019c&1&0000#{6ac27878-a6fa-4155-ba85-f98f491d4f33}, copy it and paste it on explorer’s address bar. Works like charm!

Continue reading...

Tags: , , , , , , , ,

Professional Career

» 22 April 2013 » In Life, Programming, Web Development » No Comments

Few days from now, I will be starting my professional career. To be honest, I’m pretty much excited. I will be working for a big telecommunications company in my country, and I’ll probably do some web development related work during my stay. This is very new to me, and the work would probably require team-oriented skills, which I currently lack.

Expectations

There will be some training involved, so apparently, a bond of one or two years will be included in the contract which I will be signing soon. It’s pretty rough, but will surely be worth the experience I will be receiving.

About the salary, I’m really happy about it. It’s not far from my dream salary, but who cares, I’m still a fresh graduate. I ended up offered 200% more of what I expected. It’s pretty satisfying considering the amount of work I can offer back to the company. The taxes hurt though.

Professionalism

Being a freelancer since 2007, I’ve learned to interact with different kind of people. I can speak publicly well too, and I consider myself a capable leader. Interacting with my colleagues will surely be the hardest part. I’ve been on the solo-fly all my coding life, and I barely worked with people in the same level. To be honest, I’d rather write the codes myself. I know this is bad, so I gotta patch up somehow. Careers are meant to progress, it doesn’t stay at one point for a very long period of time.

Challenges

Attendance, is probably my greatest challenge. I’m known for my laziness, and tardiness. I set times and dates on my appointments and I still find my self late for at least an hour. Now, I think I need to wake up early enough that I will have extra time for coffee in the office. That’s pretty ideal, and I hope to execute it well.

Thinking outside the box will surely be a drag. Though I am capable of doing (well some may say ‘amazing’) things that will qualify, but I need to surpass the my limits everyday.

Next

It’s almost near. I’m expected to start on the first business day of May. As I’ve said, it’s pretty exciting. Cheers!

Continue reading...

Tags: , , , , ,

Reviving Upscreen – A Screenshot Utility

» 19 July 2012 » In C#, Open-Source, Programming, Releases » 2 Comments

Not so long ago, I started Upscreen for Min.us API. I used C++ with minimal 3rd party libraries, and got it working for few weeks. But then it became unstable and I didn’t have the time to update it (my apologies). So now, I revived the project and used imgur API instead. It was smooth, and I’m considering adding an option to upload to min.us (I love them too!).

The hotkey I originally used was Win + PrntScrn, but for some reason, I cannot register the hotkey on Windows 8. So to be safe, Ctrl + Shift + PrntScrn was used.

The good thing about using C# is, I didn’t have to go with the trouble of accessing the clipboard within the Win32 API. It can be done via Clipboard class.

if (Clipboard.ContainsImage())
{
    Image img = Clipboard.GetImage();
    img.Save(tmpName);
    PostToImgur(tmpName);
}

Upscreen is mainly built for uploading screenshots, but it can be used on any other image. Just place the image in the clipboard, then hit the hotkey.

Code is available at GitHub.

Continue reading...

Tags: , , , , ,

Committing Sensitive Data

» 18 July 2012 » In C#, Git, Open-Source, Programming, Security » 2 Comments

I spent the whole night trying to figure out how to revert commits, and remove my sensitive information from my public repositories. This helped me realized how important it is to learn and practice git.

I mostly do open source projects on C#, and I always put to-change data like API keys in app.config. At first, I thought I was on the safe road, while making git ignore changes from my app.config file.

git update-index --assume-unchanged app.config

But then I was wrong. I am actually partially on the safe road.

Several hours ago, while working on a project, I noticed that Settings.settings and Settings.Designer.cs updates whenever I change something in my settings variables. Upon looking at the contents of the files, panic filled my soul and I just realized that it’s not just app.config that I should be untracking.

I furiously searched for a way to resolve this issue, and thinking that I have to go over one commit at a time, I started to think that I made a very huge mistake. I have a database connection string and my personal phone number in two separate projects in GitHub.

Luckily I found this article. Without further munching, I applied the commands to every repository I have, wherein I used app.config to store sensitive data.

Afterwards, I ran the command I used with app.config on Settings.settings and Settings.Designer.cs. Now I am both ashamed to be in such situation, and happy to learn something new.

Continue reading...

Tags: , , , , , ,

Extending SMS Capabilities

» 16 July 2012 » In C#, Life, Open-Source, Programming » 3 Comments

I live in a place where wireless access points are few, mobile internet is expensive, but SMS is unlimited. Of course, I use SMS for communicating with my friends, family, girlfriend, colleagues, and for business. Then, one day it came to my mind, why not communicate with my personal computer?

My father brought home a USB dongle (Huawei E220), I unlocked it, and tried a sim card, and it worked! Now this, is what my computer will be using as a receiver. At first, it’s very frustrating to install the drivers for this dongle. Modern ones are just smooth on PnP (Plug ‘n Play) features. It took me a while to find out that I need to reconfigure the driver Windows installed by default.

Setting Up

Now it’s connected. But I need a way to make it receive SMS, and save it somehow. Then I stumbled upon Gammu luckily, it supports E220(see all supported devices). The configuration file is given, and pretty elementary.

[gammu]
port = COM6
connection = at19200
model = at

You just need to replace COM6 with the COM port you have in your device manager.

Device Manager

COM Port used by the USB Dongle

And then, I intend to install gammu as a service. Luckily an SMS daemon is included, and using the previous gammu configuration:

[smsd]
logfile=C:\smsd\smsd.log
service=files
inboxpath=C:\SMSData\data\


[gammu]
port = COM6
connection = at19200
model = at

[include_numbers]
+000000000000

You can change the paths as you wish, but make sure your number is included in the [include_numbers] section. This is a nice feature that will block unwanted texts from other numbers.

Not that it’s all set, run the daemon and make it install itself as a service, then start the service.

gammu-smsd -i -c C:\smsd\gammu-smsdrc

It will now run automatically with windows. Your USB dongle must be connected all the time to your computer.

Processing Received Messages

Now here’s a tricky but fun part. How will you process the incoming messages? Notice that I used the Files mode instead of using DBMS to receive SMS message. This is because, I need to constantly check if there’s a new message, and checking the database tables every now and then for 24/7 is painful. So in files, we’re gonna use a Timer? No! Of course, we’re not using methods that will cause heavy CPU load.

Using the FileSystemWatcher class, we can check, in real-time, if there’s a new file created in a given directory. This is perfect, because gammu’s SMS daemon creates a new text file, with the message in it, in the specified directory we included in the configuration file.

if (!fpath.Equals(""))
    watcher.Path = fpath + @"\";

watcher.Filter = "*.txt";
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = listenToolStripMenuItem.Checked;

Whenever a file is created inside the specified directory, it will execute the code inside the OnChanged() method. From this, we can process the content of each file and read them.

But not so fast. Sadly(although this seems like a right way), gammu splits the messages by 67 characters. Meaning, if your message exceeds 67 characters, it will be split into several files. For instance:

IN20120716_121927_00_+000000000000_00.txt
IN20120716_121927_00_+000000000000_00.txt
IN20120716_121930_00_+000000000000_01.txt

These are files the dongle received at one point in time. But they really are just 2 separate messages. How? If you look into the last two digits on the filename, it will tell you the sequence of the messages. 00 means the beginning of the message, if followed by another 00, it’s a new message. But if it’s followed by 01, it’s to be appended, and must be read as part two of the first one.

It took me sometime to figure out how to combine them into one. I can only receive one at a time, but the parts came both together with a very tiny interval. By this, I came up with a solution that will use a Timer.

timer.Enabled = false;
timer.Interval = 1000;
timer.Tick += new EventHandler(timer_Tick);

I allotted two seconds to wait for upcoming possible parts, then process them and verify if they really are parts of a long message.

private void OnChanged(object sender, FileSystemEventArgs e)
{
    if (timer.Enabled)
    {
        tmp.Add(e.FullPath);
    }
    else
    {
        tmp = new List<string>();
        this.Invoke(new MethodInvoker(delegate
        {
            timer.Enabled = true;
            timer.Start();
        }));
        tmp.Add(e.FullPath);
    }            
}

private void timer_Tick(object sender, EventArgs e)
{
    secs++;
    if (secs >= 2)
    {
        timer.Enabled = false;
        secs = 0;
        procList(tmp);
    }
}

private void procList(List<string> lst)
{
    List<string> data = new List<string>();
    string xdata = "";
    bool app = true;
    int prev = -1;
    foreach (string fp in lst)
    {
        if (Regex.IsMatch(fp, @"_(d{2})\.txt$"))
        {
            Match m = Regex.Match(fp, @"_(d{2})\.txt$");
            int x = Int32.Parse(m.Groups[1].Value);
            if (x - prev != 1)
            {
                app = false;
                prev = -1;
            }
            else
            {
                prev = x;
            }
        }
        string datum = readContent(fp);
        if (app)
        {
            xdata += datum;
        }
        else
        {
            data.Add(xdata);
            xdata = datum;
        }
    }
    data.Add(xdata);
    foreach (string d in data)
    {
        processData(d);
    }
            
}

It’s a pretty long process, and it took me hours to figure out what to do. But after that, it’s time to add some modules to boost its functionality.

Making Things Functional

As for now, I only have the twitter module working.

private void processData(string data)
{
    Command cmd = parseString(data);

    switch (cmd.id)
    {
        case "tweet":
            tServ.SendTweet(cmd.arg);
            break;
        case "google":
            // Google processing here
            break;
    }
}

private Command parseString(string str)
{
    Command cmd = new Command();
    if (str.Contains(' '))
    {
        cmd.id = str.Split(' ').FirstOrDefault();
        cmd.arg = str.Remove(0, cmd.id.Length + 1);
    }
    return cmd;
}
// ... 
class Command
{
    public string id;
    public string arg;
}

I have plenty of ideas in mind. I am currently working on a google module, then a file-search module for my computer, and many more. In the mean time, you can watch the development process and add your own modules as well. Fork it in GitHub.

I will update if I have something new. Cheers!

I named this project after Parker, my favorite Leverage character.

Continue reading...

Tags: , , , , , ,