Tag Archive > csharp

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: , , , , , , , ,

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: , , , , , ,

Basic Threading in C#

» 26 October 2011 » In C#, Programming » 5 Comments

Threading is a great way to make your application smoother. A single thread in a C# application, is an independent execution path that can run simultaneously with the main application thread. Of course, C# supports multithreading. And to use the threading namespace, you can directly call it from System.Threading, or import it:

using System.Threading;

Without this, a basic HTTP request makes your application unavailable in a span of time. And if you are using a progress bar, you won’t see it updating (since the application is unresponsive at this state).

Single Thread

The most basic way to implement this, is by using the Thread class. An example:

Thread tMain = new Thread(new ThreadStart(someMethod));
tMain.Start();

Wherein someMethod is a void function that contains the code you want to execute. With this, the thread will execute in parallel with the main thread. The only drawback, is you cannot modify controls created in the main thread like you normally use to. This will result into a Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on exception. The solution is pretty simple:

// Won't Work
textBox1.Text = "Hello";

// Will Work
this.Invoke(new MethodInvoker(delegate { textBox1.Text = "Hello"; }));

This approach functions just the same as a BackgroundWorker instance.

Powertip: You can disable all the controls in your form painlessly without setting the Enabled property of each control (imagine having 20+ controls in your form).

private void controlsEnableToggle(bool val)
{
	foreach (Control c in this.Controls)
	{
		c.Enabled = val;
	}
}

Multiple Threads

Dealing with multiple repetitive tasks with a single line of execution is painful, especially in large numbers. C# supports multithreading. This means, we can initiate as many threads as we like, and it will do the job. So how to do that? A simple for-loop.

for (int i = 0; i < 10; i++) {
	Thread tMain = new Thread(new ThreadStart(someMethod));
	tMain.Start();
}

The above code works, but what if we need to supply parameters to our method?

// .NET 2
for (int i = 0; i < 10; i++) {
	Thread tMain = new Thread(new ParameterizedThreadStart(someMethod));
	tMain.Start(param);
}

// .NET 3.5 & 4
for (int i = 0; i < 10; i++) {
	Thread tMain = new Thread(unused => someMethod(param));
	tMain.Start();
}

Pausing and Stopping Threads

Whenever you close a form, the main thread will stop, but the threads you created are not. Thus, the process is still alive. To stop this, you can just go to the task manager, and end the process from there. But that’s not user-friendly.

You cannot actually stop or pause threads immediately. You can never tell what the thread is doing, and terminating them abnormally may cause side effects. For this, ManualResetEvent is used.

ManualResetEvent pauseEvent = new ManualResetEvent(true);
ManualResetEvent stopEvent = new ManualResetEvent(false);

The bool values passed to the constructor indicates whether the initial state of the instance is signaled or not. This is pretty easy to use.

ManualResetEvent pauseEvent = new ManualResetEvent(true);
ManualResetEvent stopEvent = new ManualResetEvent(false);

private void someMethod(string param) {
	// Stops the thread
	if (stopEvent.WaitOne(0))
		return;
		
	// Pauses the thread
	pause Event.WaitOne(Timeout.Infinite);
		
	// Your code
	
}

To change the signaled state of these events, we will use Reset and Set methods. Here’s how to use them in relation to the above code:

// Stops the threads
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
	stopEvent.Set();
}

// Pauses the threads
private void Button1_Click(object sender, EventArgs e)
{
	pauseEvent.Reset();
}

// Resumes the threads
private void Button2_Click(object sender, EventArgs e)
{
	pauseEvent.Set();
}

You can choose how you will use the methods, the above is just an example.

Continue reading...

Tags: , , ,

Downloading Facebook Albums with C#

» 30 March 2011 » In C#, Open-Source, Programming, Releases » 3 Comments

If you can remember, I already posted a script that does the same job (downloading facebook albums) written in Perl. Sadly, the script doesn’t work anymore, and because of the bad practices I have applied to it, I felt lazy updating. So instead, I created another project. This time, it’s on C#. So the project has a GUI, which most of the users will love.

I actually started this 20 days ago. I didn’t have the chance to work on this until yesterday night. What it does is pretty simple. It uses the Facebook Graph API, so there would be a great, great chance that this will not fail. So let us take a look at the process.

ADown Flowchart

ADown Flowchart

To be honest, this is the first time I used a flowchart on my projects. At first I was not convinced by this, but then I just realized this is one of the best ways to explain how a process takes action.

I also used an external JSON parser (since most of what I found are serializers). Credits goes here for the parser.

Here’s the screenshot of the GUI:

ADown Screenshot

ADown Screenshot

There are some notes I have to mention:

  • Downloading speed will depend on the connection speed
  • The download folder by default is in the Documents folder named ‘ADown’
  • Each picture will be named based on the Photo ID in the Graph API

And of course, the features:

  • Threaded
  • Verbose
  • Uses Facebook Graph API
  • Able to change download folder
  • Creates a folder for every album
  • Accepts the Album URL (easy copy-paste)

If you have no permission in that album (although it’s visible to you in Facebook) you won’t be able to access it in the Graph API. An example would be a public album of someone who’s not in your friend list.

The source code of course is freely available at github and released under BSD 3-clause license. Help me maintain it, by forking. :)

The executable file is also available, that is if you do not have a VS2010 installed. You need to install .NET Framework 4 first. Download the executable file here.

That’s all for this project, please leave comments if you have something in mind. Thank you.

Continue reading...

Tags: , , , , , , , ,