Monday, December 12, 2011

C++ and Boost thread.

This is a class I think someone may find very entertaining one day, it fits a modest need to do something asynchronously, why not take a look?

If you want to use it for something it will need to be adjusted slightly as it is taken from my project Xinmapper hosted on sourceforge.

[code]

#pragma once
#include "stdafx.h"
#include "Mapper.h"
#include "XInputTranslater.h"
#include "XInputBoostMouse.h"
#include "PlayerInfo.h"

class InputPoller
{
 typedef boost::mutex::scoped_lock lock;
public:
 const int THREAD_DELAY;
 boost::shared_ptr<boost::thread> thread;
protected:
 volatile bool isThreadRunning;
 volatile bool isStopRequested;
 XINPUT_STATE local_state;
 boost::mutex stateMutex;
 
 PlayerInfo *p;
 Mapper *m;
 XInputTranslater *t;
 XInputBoostMouse *mse;

protected://member functions
 void startThread()
 {
  if( ! this->isThreadRunning )
  {
   this->isStopRequested =(false);
   this->isThreadRunning =(true);
   this->thread = boost::shared_ptr<boost::thread>
    (new boost::thread(boost::bind(&InputPoller::workThread,this)));
  }
 }

 void requestStop(){
  if( this->thread != nullptr ){
   if(! this->isThreadRunning )
    return;
   this->isStopRequested =(true);
  }
 }

 void stopThread(){
  if(this->thread != nullptr){
   if(! this->isThreadRunning )
    return;
   this->isStopRequested =(true);
   this->thread->join();
   this->isThreadRunning =(false);
  }
 }
  
 virtual void workThread()
 {
  while( ! this->isStopRequested )
  {
   DWORD error = XInputGetState(p->player_id, &local_state);
   if( error != ERROR_SUCCESS )
    break;
   mse->ProcessState(local_state);
   m->ProcessActionDetails( t->ProcessState(local_state) );
   Sleep(THREAD_DELAY);
  }
  this->isThreadRunning = false;
 }

public://public member functions
 InputPoller(PlayerInfo *playerInfo, Mapper *mapper, XInputTranslater *trans, XInputBoostMouse *mouse)
  : THREAD_DELAY(10), p(playerInfo), m(mapper), t(trans), mse(mouse)
 {
  isThreadRunning = false;
  isStopRequested = false;
  lock(stateMutex);
  memset(&local_state,0,sizeof(XINPUT_STATE));
 }
  
 //This function does block when it is called by default.
 virtual ~InputPoller(){
  if( this->thread != nullptr ){
   this->isStopRequested = true;
   this->thread->join();
  }
 }

 bool Start()
 {
  this->startThread();
  return this->isThreadRunning;
 }

 bool Stop()
 {
  this->stopThread();
  return this->isThreadRunning;
 }
 bool IsRunning()
 {
  return this->isThreadRunning;
 }
 bool IsControllerConnected()
 {
  XINPUT_STATE ss = {0};
  return XInputGetState(p->player_id, &ss) == ERROR_SUCCESS;
 }
};
[/code]
Also you may notice I've made good use of protected members as well as virtual functions.  Happy coding!

Saturday, October 22, 2011

C# Web Browser Automation

There are tons of approaches to most programming tasks, and web browser automation is no exception.
But, with C# there are some facilities provided to make it a lot easier than you may at first suspect.

The WebBrowser class:
http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.aspx

The webbrowser class is basically Microsoft IE embedded in your application, not a bad thing if you need a webbrowser!

Inside the webbrowser class is a "Document" property composed of multiple HtmlElements,
http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.document.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.htmlelement.aspx

Now, the easiest way to use this to our advantage is to use Google chrome, and right click on the element you want to work with (on the browser page) and select "inspect element".

Many times elements include an "id=" section, which be used like so:

HtmlElement he = WebBrowser.Document.GetElementById("loginbutton");

and these elements can be used to our advantage:

he.InvokeMember("click");
he.InnerText = "Something";

This post is by no means complete but does provide a very simple way to easily get started !

Monday, August 22, 2011

A more durable screen capture class!

Here's a more durable (not exactly performance-tuned) screen capture class that I think someone will be pleased to find someday, it also does quality reduction (and thus file-size) for the Jpeg file format.  Pretty neat.

GetScreen.cs
[code]
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.IO;

namespace ScreenCapture
{
    
    public class GetScreen
    {
        private Graphics gfx;
        private Bitmap bmp;
        private Point zero;
        private Size resolution;
        private Size imgSz;

        public GetScreen()
        {
            zero = new Point(0, 0);
            resolution = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                Screen.PrimaryScreen.Bounds.Height,
                PixelFormat.Format32bppArgb);
            gfx = Graphics.FromImage(bmp);
            imgSz = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
        }
        ~GetScreen()
        {
            bmp.Dispose();
            gfx.Dispose();
        }
        public Bitmap GetWholeScreen()
        {
            gfx.CopyFromScreen(zero, zero, resolution);
            return new Bitmap(bmp, imgSz);
        }
        public Bitmap GetImageCopy(Point topLeft, Size widthHeight)
        {
            gfx.CopyFromScreen(zero, zero, resolution);
            return bmp.Clone(new Rectangle(topLeft, widthHeight), PixelFormat.DontCare);
        }
        public void SaveBitmapAsJpeg(Bitmap someBitmap, long qualityPercentage, string fileName)
        {
            if (someBitmap == null || fileName == null)
            {
                throw new ArgumentNullException();
            }
            if (qualityPercentage > 100 || qualityPercentage < 0)
            {
                throw new ArgumentException("Argument qualityPercentage was out of bounds.  0-100 is supported.");
            }
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType == "image/jpeg")
                {
                    ici = codec;
                    break;
                }
            }
            EncoderParameters ep = new EncoderParameters();
            //0 = lowest quality, 100 = highest.
            ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)qualityPercentage);
            someBitmap.Save(fileName, ici, ep);
        }
        public void SaveBitmapAsJpeg(Bitmap someBitmap, long qualityPercentage, Stream st)
        {
            if (someBitmap == null || st == null)
            {
                throw new ArgumentNullException();
            }
            if (qualityPercentage > 100 || qualityPercentage < 0)
            {
                throw new ArgumentException("Argument qualityPercentage was out of bounds.  0-100 is supported.");
            }
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType == "image/jpeg")
                {
                    ici = codec;
                    break;
                }
            }
            EncoderParameters ep = new EncoderParameters();
            //0 = lowest quality, 100 = highest.
            ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)qualityPercentage);
            someBitmap.Save(st, ici, ep);
        }

    }
}
[/code]


I also had time to make a demo using the class, it wasn't specifically for the blog but it may be interesting for a spare minute or so.

http://www.mediafire.com/?v0lhcfznb1oz0wt

Tuesday, July 26, 2011

C# Code snippet, paste to DataGridView !

Often times during your journey as a C# programmer it will be necessary to copy and paste data from Excel spreadsheets.  Here's a code snippet to paste data into a DataGridView.

        private void PasteClipboard(DataGridView dgv)
        {
            try
            {
                DataGridViewRow selectedRow;
                /* Find first selected cell's row (or first selected row). */
                if (dgv.SelectedRows.Count > 0)
                    selectedRow = dgv.SelectedRows[0];
                else if (dgv.SelectedCells.Count > 0)
                    selectedRow = dgv.SelectedCells[0].OwningRow;
                else
                    return;
                /* Get clipboard Text */
                string clipText = Clipboard.GetText();
                /* Get Rows ( newline delimited ) */
                string[] rowLines = Regex.Split(clipText, "\r\n");
                foreach (string row in rowLines)
                {
                    /* Get Cell contents ( tab delimited ) */
                    string[] cells = Regex.Split(row, "\t");
                    DataGridViewRow r = new DataGridViewRow();
                    foreach (string sc in cells)
                    {
                        DataGridViewTextBoxCell c = new DataGridViewTextBoxCell();
                        c.Value = sc;
                        r.Cells.Add(c);
                    }
                    dgv.Rows.Insert(selectedRow.Index, r);
                    this.toolStripStatusLabel1.Text = "Data has been pasted.";
                }


            }
            catch (System.ArgumentException ex)
            {
                MessageBeep(MB_ICONEXCLAMATION);
                this.toolStripStatusLabel1.Text = ex.Message;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

Friday, July 15, 2011

C++ Pointers and References

#include <iostream>
using namespace std;

int main()
{
int someInt = 0; //<-- memory allocated and initialized to 0.
cout << &someInt << endl;//<-- print the address of someInt
//^^ It really prints the address of the base of the allocated section of memory.
int *dynamicInt = new int(0);//<-- memory allocated (on the heap) and initalized to 0.
cout << dynamicInt << endl;//<-- print the address of dynamicInt

//Assign both sections of memory the value of 1.
someInt = 1;
*dynamicInt = 1;//<-- here the pointer is "de-referenced"

cout << "someInt = " << someInt << endl;
cout << "dynamicInt = " << *dynamicInt << endl;


//Create a reference to both.
int &someRef = someInt;//<-- disregard the syntax with regard to the address
int &otherRef = *dynamicInt;//


//Modify both with the reference.
someRef = 2;
otherRef = 2;

cout <<  "someRef = " << someRef << endl;
cout << "otherRef = " << otherRef << endl;




delete dynamicInt;//<-- free dynamically allocated memory.

cout << "Press ENTER to continue." << endl;
cin.get();
return 0;
}

Thursday, June 30, 2011

C# Application Settings

Application Settings are a pretty cool feature and very simple to use with Visual Studio 2010, so first of all simply, what are they?

Application Settings allow you to abstract the details of storing data between program sessions.  Basically what this means is, you can add program settings and save their values so that the next time the program is run the setting will be remembered.  A similar feature is adding and using resources, but we'll be modifying our Application Settings ;)

Step 1.
Create a new Windows Forms Application.


Step 2.
Open the Settings file in the solution explorer pane.

Step 3.
Add a boolean setting, we will be using it in the next step.  At this step I should probably point out that we will want to be working with a "User" scope setting, as it we can modify it's value.  Application scope settings are more appropriate for program strings, like error messages or text blocks and other static items.  If you prefer the long version, please see the MSDN link at the bottom of this post.

Step 4.
Now then, the real magic.  Add a CheckBox control to the form, and view it's properties.  Go ahead and link the Toggle setting to "checked" as shown in the picture.


Step 5.
You may have already noticed if you have built and ran your application that your settings are not yet preserved, but why!?  Truth be told you must tell the settings when to save their state.

Fortunately, this is a very easy thing to do, so stick with me and I'll get to it.
Select the main form window, and add an event handler (by double-clicking)
for the FormClosing event, this is to save our program settings before the
application exits.


Step 6.
Now the fun part, the one that teaches you how to use the settings in your code!
In the event handler function body, add the following code:

Properties.Settings.Default.Save();

You may also notice a member of concern is: Properties.Settings.Default.Toggle

Alright, that's all folks.

Tuesday, June 21, 2011

Synchronous WebBrowser control navigating

For the random people that stumble upon this blog, this article relates to the .NET framework's "WebBrowser" class which basically allows a programmer to use internet explorer within his application.  In fact, you can create 10 instances of IE and programmatically make them perform a task, if you want to.
http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.aspx

This is some high-level goodness provided by programming languages like C# and Visual Basic, aka the butter-knife of programming languages.  You might enjoy this humerous photo:


Often times subscribing to an event just isn't synchronous enough, one common case is navigating to a web page using the WebBrowser control.

To make it behave synchronously, this snippet is of use:


this.webBrowser.Navigate(url);
while (this.webBrowser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}

Friday, June 10, 2011

Artificial Neural Networks

I've recently came across a collection of interesting articles on artificial neural networks, so I thought I'd share the wealth!

This article is pretty good, and is geared toward someone with no experience with ANNs at all.  It will provide you with at least some glossed-over theory on the ANN, and maybe more.  It's worth checking out.
http://www.codeproject.com/KB/recipes/brainnet.aspx

This pdf looks pretty good too, http://arxiv.org/ftp/cs/papers/0308/0308031.pdf

I recommend reading and understanding one article in it's entirety before moving on to another.

As always, stay tuned.

Friday, June 3, 2011

C++ Casting

I wrote a little demo to better describe casting to someone on a programming forum, and I thought it was pretty informative so here it is:

[code]
#include <iostream>
#include <limits>
#include <bitset>
#include <cassert>
#include <string>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
assert(sizeof(short) == 2);
assert(sizeof(signed char) == 1);

string bigBitString =
"0111111100000000";
string smallBitString =
"00000000";

bitset<16> big;
bitset<8> small;

for(string::size_type i = 0; i < bigBitString.size(); i++)
{
     big[i] = bigBitString[i] ==
'1' ? 1 : 0;
}


for(string::size_type i = 0; i < smallBitString.size(); i++)
{
     small[i] = smallBitString[i] ==
'1' ? 1 : 0;
}

short sBig = (short)big.to_ulong();
signed char cSmall = (signed char)small.to_ulong();

cout <<
"Sizeof short: " << sizeof(short) << endl;
cout <<
"Sizeof signed char: " << sizeof(signed char) << endl;
cout <<
"Short bits: " << big.to_string() << endl;
cout <<
"Signed char bits: " << small.to_string() << endl;

signed char casted = (signed char) big.to_ulong();

bitset<8> castedBits(casted);

cout <<
"Signed char bits after down-casting: " << castedBits.to_string() << endl;

cin.get();
return 0;
}
[/code]

I also wrote a small C++ string class demo, if you don't know what C++ strings are, you should definitely play around with this:

[code]
#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
using namespace std;

int main()
{

string cppString = "Hello World.";
cppString = "No error, no confusing C functions.";
getline(cin,cppString);//No buffer overflow from too much input.

//Use much like an array.
for( std::string::size_type i = 0; i < cppString.size(); i++ )
cppString[i] = 'x';

cppString += " -- Simple string concatenation too.";

//Usable with the C++ STL algorithms.
random_shuffle(cppString.begin(), cppString.end());

cout << "Can still get a C string if you REALLY want to also." 
<< endl << cppString.c_str() << endl;

//Easily convert from string to int/floating point type.
int someInt = 0;
cin >> cppString;
if((stringstream(cppString) >> someInt).fail())
cout << "Invalid number, woops!";
else
cout << someInt << endl << "Just your lucky number." << endl;
}
[/code]

Tuesday, May 31, 2011

C++ Lambdas.

lambda functions enable us to not only write functions in the middle of others, but to more importantly pass expressions as arguments to a function.

The documentation for lambdas on the internet is sparse, so bear with me if there is a mistake here or there.

Some simple examples of their use:



#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;



bool IsEqualWithoutCase( string first, string second ){
auto upper = [] ( string::value_type &ch ) { ch = toupper(ch) }; //<-- lambda
for_each( first.begin(), first.end(), upper );
for_each( second.begin(), second.end(), upper );
return first == second;
}


int main()
{
string input, comp = "Hello World";
getline(cin,input);
cout << (IsEqualWithoutCase(input,comp) ? "That is correct." : "Wrong answer.") << endl;
}

Saturday, May 28, 2011

Project: "EasyScreen2011"

So since I feel like this feature should be built into Windows anyway, I've decided to make a small application that allows me to select a region of the screen and take a screenshot of it.  For this project I have chosen C# as my language, and it uses a windows low-level keyboard/mouse hook library located here.

I am very pleased with C# libraries for now, they are much less of a hassle to use than many C++ libraries (which are often gigantic).  The library is used because of the amount of pInvoking required to use the Windows API functions to add hooks.

For this project I have chosen to use the library in a DLL.  It also features error notification via a balloon tip from the system tray where it resides.



The current build isn't without it's flaws, but they are for the most part, at least, obvious.




Who knows, you may find it more useful than you ever thought you would ;)
I have uploaded my program for download from here.  
Currently to use the application you hold Ctrl + Shift and select an area of the screen with your mouse.

Please let me know what you think !

Wednesday, May 25, 2011

CS ADTs and fun fun fun!

Of utmost importance to a C/C++ programmer are (you guessed it) pointers!  Pointers enable programmers to create interesting (and useful) data structures that are likely more commonplace in performance applications.

A list of data structures is available on Wikipedia, http://en.wikipedia.org/wiki/List_of_data_structures  for now this post will is concerned with the abstract data types.

To name a few, there exists the stack, queue, deque, list, vector, set, map, and tree.

Perhaps the simplest, can be the "list", aka the "Linked List."

Typically the linked list will feature a node type commonly represented by a structure, in which each structure contains a pointer to the next (and in the case of a doubly linked list, the previous).

http://en.wikipedia.org/wiki/Linked_list

For reference a simple node type can be in C++ as follows:


[code]
template<class NodeData>
struct Node
{
NodeData data;
Node *next;
Node() : next(nullptr) {}
};
[/code]

When creating the linked list, the first node is created with it's "next" member pointing to nothing.  Appending a node to the end will cause the first node's next pointer to point to the second node.

With this structure, one may only have a pointer to the first node and be able to access the entire list's content by "traversing" the list.

Diagram of a linked list:
[Node] -> [Node] -> [Node] -> NULL

to traverse the list is pretty simple,
Node *current = firstNode;
while( current->next != NULL )
{
current = current->next;
}
the loop ends with current pointing to the last node in the list, commonly one will see traversing the list in this manner in the destructor or a clear() member function of the class.

For now, the implementation of many of these Computer Science data structures is left to you, there is a whole "list" of them.

Thursday, May 19, 2011

C# screen capture!

Among the many good things about C# is it's amazing library, the .NET framework.  It may seem almost alien to native programmers, and I'm thoroughly convinced trained monkeys can write C# programs--but here is a small sample of the level of abstraction provided by C# and the rich .NET framework classes.

GetScreen.cs
[file]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;


namespace ScreenCap
{
 
    public class GetScreen
    {
        private Graphics gfx;
        private Bitmap bmp;
        private Point zero;
        private Size resolution;


        public GetScreen()
        {
            zero = new Point(0, 0);
            resolution = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                Screen.PrimaryScreen.Bounds.Height,
                PixelFormat.Format32bppArgb);
            gfx = Graphics.FromImage(bmp);
        }
        ~GetScreen()
        {
            bmp.Dispose();
            gfx.Dispose();
        }
        public Bitmap GetImage()
        {
            gfx.CopyFromScreen(zero, zero, resolution);
            return new Bitmap(bmp);
        }
    }
}


[/file]

Form1.cs
[file]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace ScreenCap
{
    public partial class Form1 : Form
    {
        public GetScreen capture;
        public Form1()
        {
            InitializeComponent();
            capture = new GetScreen();
            //Assigning a snapshot to the window content.
            Graphics gfx = this.CreateGraphics();
            this.Show();//Make sure to sure the window first.
            gfx.DrawImage(capture.GetImage(), this.ClientRectangle);
        }
    }
}
[/file]

If built properly you should see a snapshot of your screen in the window, and a glimpse into the life of the army of trained monkeys writing software for Microsoft Windows.

Wednesday, May 18, 2011

STL = a pure computation library for C++ (amazing)

The C++ STL or Standard Template Library can easily be divided into two sections, algorithms and containers.
The version you will find accompanying most modern C++ compilers is based off of the SGI version of the STL which can be used alternatively.

Many programmers can find some utility in using the STL as it can make computation as easy as pie.  For example, every permutation of "abcdefghijklmnopqrstuvwxyz"




#include <iostream>
#include <string>
#include <algorithm>



int main()
{
   using namespace std;
   string input = "abcdefghijklmnopqrstuvwxyz";
   do
   {
       cout << input << "\n";
   }while( std::next_permutation(input.begin(), input.end()) );
}

Tuesday, May 17, 2011

C++ Loop construction for file input.

The following loop setup will yield the best results for file input and avoids many common mistakes that have to do with the eof() member returning true only after the eof() has been reached.




int main()
{
using namespace std;
ifstream inFile("somefile.txt");
//check for errors, etc.

string input;
while( inFile >> input ) //< -- loop
{
//Processing.
}

inFile.close();
}

Monday, May 16, 2011

DreamSpark provides free training to students.

Microsoft Dreamspark provides free training to currently enrolled students!

Among Dreamspark's free software for students, such as Visual Studio 2010 Professional, there exists now a Pluralsight-training.net trial membership for ~80 days of free training videos.

www.dreamspark.com