Friday, April 8, 2011
Decoding MIME Attachments in C#.NET
There were several open source examples, but the one that suited me best was this one from CodeProject:
http://www.codeproject.com/KB/cs/MIME_De_Encode_in_C_.aspx
For now, I'm just using the decoding part. But I foresee a need to do encoding pretty soon.
Monday, March 28, 2011
Retrieving Email from GMail using POP3 Programmatically with C#
Unlike regular POP3, GMail's POP3 uses SSL encryption. My limited knowledge on encryption does not extend to SSL encryption. So I did some research. The UNIX fetchmail program can retrieve GMail POP3 email with SSL encryption. But to run code after retrieving the email would require having to program with Linux and procmail. Since I mainly write in C# .NET, that was more trouble than its worth.
I eventually found my answer at Code Project -- http://www.codeproject.com/KB/IP/Pop3MailClient.aspx. Downloaded the code and it worked like a charm.
Tuesday, October 26, 2010
How to Rename Tables in Firebird
- creating a new table with a temporary name;
- populating it with data via INSERT from a SELECT of the old table;
- dropping the old table;
- creating a new table with the desired name;
- populating it with the data from the temporary table (step #2 above)
- dropping the temporary table
Friday, September 10, 2010
Request.Redirect vs. Server.Transfer in ASP.NET
Performance-wise, there is a difference. Because Request.Redirect is a request to the browser to go to another page, it involves an extra roundtrip. Depending on how fast or slow your Internet connection is, this extra trip can add a pause of a second or two while the browser fetch the new page. With Server.Transfer, the redirected page appears immediately in lieu of the originally requested page.
Tuesday, August 10, 2010
Integrating Facebook Like Button with Open Graph Protocol
Tuesday, July 27, 2010
Working with Hidden Fields in ASP.NET
Saturday, July 24, 2010
Microsoft Tags
Friday, April 30, 2010
Nokia Training on Qt

Monday, March 1, 2010
Simulating Keyboard Input with C# Part 2
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
IntPtr hWnd;
if (externalAppType == "CLASS")
hWnd = FindWindow(externalAppName, null);
else
hWnd = FindWindowByCaption(IntPtr.Zero, externalAppName);
if (hWnd != IntPtr.Zero)
{
if (SetForegroundWindow(hWnd))
{
System.Threading.Thread.Sleep(50);
System.Windows.Forms.SendKeys.SendWait(id + "{ENTER}");
}
}
Monday, February 22, 2010
Simulating Keyboard Input with C#
SetForegroundWindow(pFoundWindow);
System.Windows.Forms.SendKeys.SendWait("Hello world");
Wednesday, February 3, 2010
Getting Foreign Exchange Currency with C#
But lately, I don't find it very reliable. I would often get time-outs or errors. Also, I'm not really sure as to where it gets its exchange rates. For manual currency conversion, I prefer to use the service of XE (http://www.xe.com/). However, XE does not provide an API for getting rates. So I decided to just implement my own API by retrieving the output of XE.com and parsing it.
Luckily, its fairly simple as they display the rate right at the page's title bar. So its a simple matter of crafting the necessary HTTP GET request given the source and destination currency. Then read the page header of the response and extract the rate from the title.
Below is a snippet of my C# code:
string xeString = String.Format("http://www.xe.com/ucc/convert.cgi?Amount=1&From={0}&To={1}", srcCurrency, dstCurrency);System.Net.WebRequest wreq = System.Net.WebRequest.Create(new Uri(xeString));
System.Net.WebResponse wresp = wreq.GetResponse();
Stream respstr = wresp.GetResponseStream();
int read = respstr.Read(buf, 0, BUFFER_SIZE);
result = Encoding.ASCII.GetString(buf, 0, read);
At this point, the string result already contains the title which can look something like
XE.com: USD to EUR rate: 1.00 USD = 0.716372 EUR. As can be clearly seen, its a simple matter of parsing the title in order to get the rate.
Wednesday, September 23, 2009
Programming with Windows Media Player and C#
I'm working on a prospective project that requires me to play mp3 files on our NetMachine kiosks. Under the old Windows system, one can play WAV files by calling some internal Windows functions. I've never tried playing mp3 or wma media files from an application so I did some research. While there are 3rd party libraries available, the best option seems to be to use the interfaces exposed by Windows Media Player (WMP). Since practically all Windows PC's come equipped with some version of WMP, it is fairly safe to assume that the components can be found in all these PC's.
Adding WMP to a C# application is very simpler. Just add a reference to the file wmp.dll in your Visual Studio project. Then from within your code, just create an instance; point to the source media file; and call play():
WMPLib.WindowsMediaPlayer player = new WMPLib.WindowsMediaPlayer();
player.URL = @"c:\My Music\somesong.wma";
player.controls.play();
player.PlayStateChange += new WMPLib._WMPOCXEvents_PlayStateChangeEventHandler(player_PlayStateChange);
You can also access the playlists defined in WMP programmatically, and extract information about the media file (ex. the artist, song title, album title, etc.) through the IWMPMedia interface:
WMPLib.IWMPMedia objMedia = player.currentMedia;
listBox1.Items.Add(String.Format("[{0}] {1} by {2}",
objMedia.getItemInfo("Album"),
objMedia.getItemInfo("Title"),
objMedia.getItemInfo("Artist")));
There is a downloadable Windows Media Player SDK 10 at Microsoft. I'm not sure what more it adds to the components that are already built-in to Windows. I did not bother installing it anymore. I guess its just sample programs.
Tuesday, September 22, 2009
Programming with Multiple Monitors in Windows using C#
I have a couple of prospect projects that require the application to send 2 different outputs to 2 different monitors. While I have been curious for some time about exactly how do you install more than 1 video card/monitor onto a Windows box and extend your desktop, I've never really been pushed to find out. But because of this prospect, I assigned my tech guys to do some R&D using our notebooks.
It seems that all Notebooks have 2 x video cards built-in -- one going to the LCD display, and the other going to the external VGA port. I have always assumed that it was just 1 video card and that the VGA port is just like an "extension" of the LCD. But as it turned out, Windows treats them as 2 different video cards and you have to option of whether their output to be the same, or you want it to be in "extended desktop mode".
Detecting multiple screens under C# is very trivial. The only thing that makes it a bit tedious to work with is the fact that the Display names are null-terminated (C-style). Since C# does not work natively with null-terminated strings, you have to do a little bit of conversion to C#-style strings. The example below shows how to get device info and open a modeless window which will reside on the extended desktop.
Setting the bounds of the new window to that of the extended desktop and setting the WindowState to Maximized will cause the modeless window will eat up the entire extended desktop. Of course, this simplistic demo assumes there are only at most 2 monitors. In reality, according to other postings, Windows XP and Vista officially can support up to ten (10) video cards/monitors.
allScreens = Screen.AllScreens;
foreach (Screen screen in allScreens)
{
string deviceName;
int length = screen.DeviceName.IndexOf("\0");
if (length == -1)
deviceName = screen.DeviceName;
else
deviceName = screen.DeviceName.Substring(0, length);
}
ExtendedForm extForm = new ExtendedForm();
extForm.Show();
Then at the constructor of the Extended Window Form:
private void ExtendedForm_Load(object sender, EventArgs e)
{
Screen screen;
Screen[] allScreens = Screen.AllScreens;
if (allScreens.Length == 1)
screen = allScreens[0];
else
screen = allScreens[1];
this.Bounds = screen.Bounds;
this.WindowState = FormWindowState.Maximized;
}
Thursday, August 27, 2009
Mifare Cards Now Supported by NetSecure
The most OOP-heavy program I've ever written is our *ahem* best-selling NetSecure biometric time and attendance system. Since NetSecure aims to support as many devices as possible for identification and verification purposes, early on, I designed it to use OOP heavily. All devices I support (fingerprint scanners, RFID readers, magstripe readers, pinpads, etc.) are derived and implemented from two other layers of abstract classes. At the bottom is a generic InputDevice abstract class. Then a generic ProximityReader abstract class is derived from it. Then finally, an RFID-specific implementation like the GigaTMS' GP20/30 RFID reader is implemented.
Recently, a big client requested for support of Philips Mifare cards. I've been twiddling with the ACR120 Mifare reader for some time. I've written small programs to test its capabilities, but have never actually written a full-blown program to make use of it. I was estimating it could take me a couple of weeks to write all the code to integrate it to NetSecure.
When I finally got down to coding and followed my object models, I realized that the ACR120 reader is just like a GPxx RFID reader. So I created an ACR120MifareReader class that is derived from ProximityReader; implemented the abstract interfaces to allow the main program to connect/disconnect to it and retrieve inputs; and voila -- I was done in about an hour! Turns out that very little changes were needed on the main NetSecure code itself as most access to devices go through the class abstraction interfaces.
Friday, July 17, 2009
Visual C++ 'per-appdomain symbol error' and Compiler Warning C4394
per-appdomain symbol should not be marked with __declspec(dllimport)Visual Studio also refuse to link the application citing those cryptic unresolvable externals on the trace variable and function. Doing a Google search on the strange error revealed that there are other people who have experienced the same problem. The error does not seem to appear if the application is a console app (such as the demo SimpleCall that came with Aculab's SDK). But the moment you switch to a graphical CLI/.NET environment, it appears.
According to MSDN, the C4394 is related to variables or functions written and compiled using native C/C++. When they are linked to a program compiled in Microsoft's Intermediate Language (MSIL) format running in a .NET managed environment (CLI), the incompatibility in permission access level appears.
Somone suggested in the forum from the other guy who reported the same problem to switch from a "pure" CLR environment to a normal one. This can be achieved by changing the compiler flag from /clr:pure to just /clr. From the Visual Studio IDE, one goes to Project >> Properties >> Configuration Properties and change the Common Language Runtime support dropdown value to regular /clr instead of the default "Pure".
And what do you know? It worked! The compiler and linker errors disappeared and I was able to generate by trace logs. So its now back to trying and figure out what is wrong with my demo program. :(Wednesday, July 8, 2009
Using app.config with Visual C++/CLI
But from inside my code, calling ConfigurationManager::AppSettings does not seem to resolve to anything. I checked the output folder and did not see any application.exe.config that one normally expects from C# projects.
I did a little bit of research and found this app.config article for C++/CLI in CodeProject. It seems that the key is in the project property's post-build event. Specifically, you have to run the external command:
copy app.config "$(TargetPath).config"
This properly copies the config file to the object code output location where it can be read by the application.
The next hurdle is converting the managed System::String^ class, that is returned by the System::Configuration methods, to the old c-style null-terminated string. This one is achieved by using the System::Runtime::Interopservices::Marshal methods. The shortest way of writing this expression that I've seen is this one from MSDN.Saturday, June 20, 2009
Globe + Google Developer Workshop @ UP Technopark

The event was supposed to start at 1pm. I got there at about that time figuring that most people will be late anyway, as is typical for these events. But surprisingly, the place was packed with geeks (and I mean that in an endearing sort of way) by the time I got there. I guess geeks are more prompt with time unlike your average Filipino.
Google showed off their API's for developers to "mashup". The Globe Labs guys demoed their Location Based Service (LBS) API, and showed how it can be used to work in conjunction with the Google API to do really creative things. The Google guy also showed some really interesting developments going on at Mozilla/Firefox with respect to HTML5. New HTML elements like canvas and video allows for really interesting possibilities that should give Flash and Silverlight a run for its money in the very near future.
Amidst all the gee-whiz-bang show-and-tell, what really caught my attention was the Google Visualization API. The map that appears in Google Analytics showing where your visitors are coming from in a graphical manner, can apparently be easily used in other programs. What immediately popped to my mind is integrating it with PayEasy Admin to allow merchants to see where their payers are coming from in a visual manner. This led to my implementation of the API.
For an even simpler way of mashing up contents without any programming involved, Google Web Elements comes to the rescue. Copying-and-pasting HTML is all it takes to embed a calendar, presentation, spreadsheet, map or YouTube video to your site. Now I just have to figure out what the longitude/latitude valus of The Peak so that I can provide a map to our office from our website!
Friday, June 12, 2009
Wrestling with C++/CLI
I remember the Aculab card as a very powerful card and quite affordable for something that can do SS7. Dialogic's equivalent product (the former DataKinetics) cost considerably more especially if you factor in the cost of the software. In the case of Aculab, the software protocol stacks are free. You just buy the board. And with Linux support plus great technical support, it was a hands-down winner.
I've been studying the trial version of Prosody S, their host-based media processing (HMP) platform. The API's only support C/C++ for multi-platform portability. I was hoping they would have C# libraries but unfortunately, they did not. Their pre-sales tech guy gave me a sample in C#, but it makes direct socket calls, as opposed to, using the API function calls. So it looked really messy.
So I figured I might as well install Visual Studio's C++ and see if I can shake off my C++ cobwebs. I haven't written in C++ for probably 5 to 6 years already. And when I did write in C++, I used Borland C++Builder for Windows and the GNU C++ compiler for Linux. I never actually used Microsoft's Visual C++. I never bothered to learn the Microsoft Foundation Classes (MFC). So I figured I'm going to have a bit of an uphill climb here.
After installing VS2005's C++ support, I made it create a .NET windows app using its templates. When I saw the code, my first reaction was -- What The F***?! It looked totally alien and unlike the C++ I knew. There were new operators (the caret ^) which I'm pretty sure is not part of standard C++.
I tried copying-and-pasting some code from the Aculab examples, and the compiler gave me all sorts of error messages about converting unmanaged code to managed. The uphill climb is starting to look like an up-mountain climb. As usual, I went to Google and did some query on C++/CLI (Common Language Infrastructure). The CLI is Microsoft .NET's common managed environment for its new generation of languages. Using C# and VB.NET with CLI is really trivial. But using it with an "old", unmanaged language like C++ involves a lot of changes.
Here are some quick tutorials I found on getting up-to-date on C++/CLI:
Just converting between the old, null-terminated string (char *) in C/C++ to the managed System.String (or System::String in C++/CLI format) version involves several steps. But I guess that is really the way to go. I mean, doing Windows programming with MFC or the native Windows API calls is a worse option.
Friday, June 5, 2009
Web Sites Projects under Visual Studio 2005
The process seem to have worked as I can now view the C++ sample codes. But strangely, when I try opening some of my C# projects, Visual Studio 2005 would complain about unsupported project files. This is particularly true for my really old web/web service projects which I migrated from VS 2003 to 2005. VS2005 just doesn't seem to like their .csproj files.
After some tinkering around, I noticed that VS2005 web site/service projects do not seem to need a .csproj files. In fact, deleting the .csproj files seem to fix the problem. The project could then be added/loaded onto a VS Solution without any hassle.
On another note, I also recently installed Windows XP Service Pack 3. Although SP3 has been around for some time, I haven't really bothered to install it. Now that its installed in my system, I'm experiencing weird problems with my Virtual PC. The problem seem to specifically happen when I do large file transfers between my Virtual PC session and my host PC. It just reboots my entire machine without any warning. Grrr... the lesson is -- don't load new Microsoft service packs unless you are specifically experiencing problems that require it.
