Tag Archive > c

Mouse Prank in C++

» 07 July 2012 » In C/C++, Programming » 3 Comments

Hooray for the new post. This post was actually a draft way back 2011. But hopefully, i’ll be motivated and keep on posting. I have many tricks to share!

Several years ago, me and my mates were having fun writing prank codes. I can barely remember them all, but here’s one.

One of the main reason why to code is fun. Of course, we all do want to have some fun. I’ll show and explain how to write a simple C++ program that will add weight to the cursor, making it difficult to use. Here’s the function that does the trick:

void heavyCursor(int weight) {
	POINT cPos;

	while (1) {
		GetCursorPos (&cPos);
		int x = cPos.x;
		int y = cPos.y;

		y += weight;

		SetCursorPos(x,y);
		Sleep(5);
	}
}

To clarify, yes it is an endless loop. This code will continually add points in the y axis and resets the cursor position in the screen. This will be fun, but very hard to stop. Sometimes it’s fun watching your friend struggle on reaching Task Manager just to stop this little program.

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

C# Basic HTTP Request Class

» 11 March 2011 » In C#, Programming » 7 Comments

Most of my clients, want me to do things with a Graphical User Interface. For this, I only have on language in mind, C#. And many of my client-related projects includes getting information from webpages, logging in, gathering data, etc. It’s very hard to repeat code over and over again with the HttpWebRequest and HttpWebResponse class. For this, I created a simple class that does GET and POST neatly and can handle cookies. Please do note that I didn’t reinvent the wheel on this one. This is just a collection of mostly used functions to make them reusable in many of my (and could be your) projects.

A simple HTTP GET request looks like this:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://ruel.me");
request.CookieContainer = cJar;
request.UserAgent = UserAgent;
request.KeepAlive = false;
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string response = sr.ReadToEnd();

And I think it’s fairly unacceptable to repeat this code over and over again in a single project. So yes, there should be a class made for this (together with the POST request).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace BasicReq
{
    /// <summary>
    /// A simple basic class for HTTP Requests.
    /// </summary>
    class BReq
    {
        /// <summary>
        /// UserAgent to be used on the requests
        /// </summary>
        public string UserAgent = @"Mozilla/5.0 (Windows; Windows NT 6.1) AppleWebKit/534.23 (KHTML, like Gecko) Chrome/11.0.686.3 Safari/534.23";
        
        /// <summary>
        /// Cookie Container that will handle all the cookies.
        /// </summary>
        private CookieContainer cJar;

        /// <summary>
        /// Performs a basic HTTP GET request.
        /// </summary>
        /// <param name="url">The URL of the request.</param>
        /// <returns>HTML Content of the response.</returns>
        public string HttpGet(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.CookieContainer = cJar;
            request.UserAgent = UserAgent;
            request.KeepAlive = false;
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream());
            return sr.ReadToEnd();
        }

        /// <summary>
        /// Performs a basic HTTP POST request
        /// </summary>
        /// <param name="url">The URL of the request.</param>
        /// <param name="post">POST Data to be passed.</param>
        /// <param name="refer">Referrer of the request</param>
        /// <returns>HTML Content of the response.</returns>
        public string HttpPost(string url, string post, string refer = "")
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.CookieContainer = cJar;
            request.UserAgent = UserAgent;
            request.KeepAlive = false;
            request.Method = "POST";
            request.Referer = refer;

            byte[] postBytes = Encoding.ASCII.GetBytes(post);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postBytes.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();
            
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream());
            
            return sr.ReadToEnd();
        }

        /// <summary>
        /// Creates an HTML file from the string.
        /// </summary>
        /// <param name="html">HTML String.</param>
        public void DebugHtml(string html)
        {
            StreamWriter sw = new StreamWriter("debug.html");
            sw.Write(html);
            sw.Close();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="BReq"/> class.
        /// </summary>
        public BReq()
        {
            cJar = new CookieContainer();
        }

        /// <summary>
        /// Releases unmanaged resources and performs other cleanup operations before the
        /// <see cref="BReq"/> is reclaimed by garbage collection.
        /// </summary>
        ~BReq()
        {
            // Nothing here
        }
    }
}

Of course the UserAgent is a public variable, so you can change it anytime upon initialization. The cookie container is used only inside the class. Yes, that’s a major con, but you can freely modify it. And that means, you can only use this class on one function if you would like to retain the cookies.

There’s also a DebugHtml function that can help you log the last request (by passing the response as a parameter, outside the class).

That’s it for now, and I highly suggest we help each other improve this class by forking it. This way improvements and ideas can be added. The more the merrier! Thank you.

Forks

These people made wonderful forks!

Continue reading...

Tags: , , , , , , , ,

Victories, and Beyond

» 25 January 2011 » In C/C++, Life, Programming » 1 Comment

This time, I will be less technical. No, actually ignore the first sentence. I’ve been coding since 2007, and C was my first language. I use Turbo C back then, and it was a pretty cool compiler back then. It’s now an antique, and you can download it here.

As I was saying, I can still remember the things I’ve been coding in Turbo C. I had that Pythagorean solver, which I posted in planet-source-code. I was so proud, and I even created a general mathematical solver, for a bigger one. Oh, and do you know that I tYpE LiKe tHiS bEfoRe?. Anyway, why am I saying all this stuff? Actually I was just refreshing my memory of what I am before, and comparing it on what I am now.

For the times that have passed, coding became an art for me. It sounds silly, but true. I can safely say I’ve done more than 100 usable programs and scripts just to fulfill my hobby. I used to code for automation, and exploitation. Nobody in my family knows what I’m doing. All they can see, is me, looking at a computer screen for an average of 16+ hours a day. I never felt boredom in coding, as boredom comes when you’re out of ideas on what to code. My ideas are hard to implement. Sometimes thoughts have been passing though my brain in countless numbers of times.

So what did I do to be, here? Almost 4 years of programming experience, I never kept track of myself. Though I somewhat became a little boastful, it has changed. August, last year, I wiped out my old HDD, desperately (see my other post). Alongside with that, is the memories, and codes of my past. So basically I never got to see those stuff again, ever. On the good side, change.

Change is inevitable, this is what I hear from others. I usually, don’t care, but now it’s the opposite. Simple things change, and these leads to greater changes. And you know what? Learning a new language, changes me. When I’m introduced to C++, I was discouraged by a friend in UK. Thinking the iostream library is a bloat, I embraced the C Standard Library. Until one day, I just realized I need to go for C++.

C++ is the superset of C, and as I became open to the object oriented environment, I became open to a new environment in real life as well. Though, I do not wish to put things in detail, I can simply say that this is one of the most remarkable changes in me. And praise God for that.

Few hours ago (January 25, 2010), I won a regional C++ programming competition. Before the awarding, I was shaking because of the cold air + the excitement I felt. This, is what I can call “Victory”. And even if I lose, it still is a victorious fight. I was very grateful for what God has made me. I started this year with a brand new prayer life. And these victories I’ve been experiencing, is a way of God telling me.. “There’s more..“.

It’s not only victories that I should prepare for, failures and discouragements will arise. But, faith will still remain. And if I fall, I fall forward, plus, God will catch me. God bless.

Continue reading...

Tags: , , , , ,

Upscreen: A Screenshot Utility using the Min.us API

» 31 December 2010 » In C/C++, Open-Source, Programming, Releases » 3 Comments

It’s been a long time since I posted something, again. Well actually I was hospitalized for 6 days, from December 18 to 24. I nearly spent Christmas the hospital. And after the hospital days, I worked on 2 projects, one is paid, and the other one is this.

The Story

Min.us is a great image hosting website. And when the time they sent me their API (I asked; their API wasn’t public yet that time) I came up with an idea, and yes basically the idea is to upload the screenshot taken in a computer to the min.us image hosting. When I finished the first (paid) project, I switched to this one. And I started with finding a way to execute code when the user pressed the PrintScreen key. I thought of using Windows Hooks but later on, I found out about RegisterHotKey and used it instead. But there’s a little problem, when I registered PrintScreen as a hotkey. Just like:

RegisterHotKey(NULL, 1, NULL, 0x2C);

The normal function of the key is disabled. This is bad, and I probably really need to use a keyboard hook instead. But no, instead I changed the hotkey and set it to Win + PrintScreen.

RegisterHotKey(NULL, 1, MOD_WIN | MOD_NOREPEAT, 0x2C);

So yes, it’s working great now. Though the PrintScreen key must be pressed first to load the image to the clipboard. So if you’re going to upload a screenshot, Press PrintScreen, then Win + PrintScreen. The good thing caused by this is, you can choose what to upload, and just place it in your clipboard. Say you need to upload an image from the internet, copy it, and then press Win + PrintScreen. Sweet.

Next, I need to get the data from the clipboard, and that was easy using GetClipboardData. Then, I need to save the bitmap file from the clipboard. I had some trouble finding a way to do this, so I used a function named CreateBMPFile and CreateBitmapInfoStruct. Success, now originally I was planning to use the BMP image and upload it right away. Then I just realized, the BMP file generated was uncompressed. So I think I need to use PNG instead (No not JPG, never). For this conversion I did some research. I ended up on using the ATL image header, and the CImage class. Well basically, converting an image is just 3 lines:

void Upscreen::ConvertToPNG(LPTSTR &sourceName, LPTSTR &destName) {
	CImage img;
	img.Load(sourceName);
	img.Save(destName);
}

Now that I have my PNG image, its time to upload it. By this time, Min.us have their API published and you can view it here. I only used two methods, CreateGallery and UploadItem. And I created a C++ class for the API:

class Minus {
public:
	std::string editorId, id, readerId;

	Minus();
	virtual ~Minus();
	void CreateGallery();
	void UploadItem(std::string&);

private:
	std::string key;
};

It’s incomplete, because the other two methods wasn’t included. So basically we need to get the editor_id, reader_id, and key from the first method then use these variables on the second method. To get these variables, an HTTP GET request must be accomplished. I do not want to use too much external libraries, so I just used Winsock2. I didn’t have too much trouble performing this, and the only issue I had was separating the HTTP headers from the response body. And later on, I found out its very easy:

response = response.substr(response.find("\r\n\r\n"));

The API’s response content type is JSON. I found it hard finding a good JSON parser in C++. And I ended using JSON Spirit . The downside is, this uses Boost Headers, so both must be downloaded.

I got the variables I need, now to the HTTP POST request. This is the bloodiest part of the program. I had trouble reading the the PNG file, and used ReadFile instead. Then, I didn’t know std::string is not suitable for storing binary data. So after switching many data types, I finally decided to use just a char * pointer to hold the data. And to pass the data, I put the POST headers and the data to a std::vector variable. All went well, but I’m a having 404 error in the POST request, and the data is incomplete. I just figured out the example URL in the Min.us API documentation is wrong. The trailing slash after UploadItem is causing the 404 error, and removing it fixed the problem. The other one was caused by the Content-Length parameter. I used WireShark and LiveHTTPHeaders to trace the packets and again, some bloody debugging. Later on, I found out the number I’ve been passing exceeded by one. After this part, all went so easy. The only thing I have to deal with is validation. Whenever the clipboard has data other than an image, it crashes. So I just placed an if condition to check if the PNG data exist. Because no PNG data will be saved if there’s no valid bitmap file present.

After uploading, I used the editor_id variable and attached it to the min.us URL. And made the program open it at the default browser using ShellExecute.

Header Files

The header files I used in this project are:

#include <WinSock2.h>
#include <windows.h>
#include <atlimage.h>
#include <string>
#include <json_spirit\json_spirit_reader_template.h>

Source Code

The source code is released under the GNU GPL v3. Get it here.

Year Ends

So this became my last post for 2010. Very timely, isn’t it? Anyway, Happy New Year!

Continue reading...

Tags: , , , , , ,