Profile

Click to view full profile
Hi, I'm Veerapat Sriarunrungrueang, an expert in technology field, especially full stack web development and performance testing.This is my coding diary. I usually develop and keep code snippets or some tricks, and update to this diary when I have time. Nowadays, I've been giving counsel to many well-known firms in Thailand.
view more...

Friday, November 30, 2012

Simple HTTP POST Server / Client with Python

Continue from the last post, it's about simple HTTP server with Python. Today, I will explain more about create POST server with Python. From last time to response GET request, we need to override do_GET in class SimpleHTTPRequestHandler. Similarly, to response POST request, we just override do_POST method. However, to receive parameters from POST there are 2 popular formats: url-encode, and multipart as I described in my previous post

In this post I will describe only url-encode. It's like encrypt the data in url format before sending to the server. So, your data will be like "{key1}={value1}&{key2}={value2} ...:". Basically, it's not that difficult with Python because all we need, are already had.

HTTP POST Client:
import urllib, urllib2

uri = 'http://localhost:8000'
name = "Mark"
# Encode data in base64 string
encode = name.encode('base64')
params = { 'name' : encode }
# Pack key-value pairs in form of url-encode format
data = urllib.urlencode(params)

# urlopen with data will use POST method by default
p = urllib2.urlopen(uri, data)
print p.read()
HTTP POST Server:
import SimpleHTTPServer
import SocketServer
import cgi
from base64 import decodestring

# Server port
PORT = 8000

class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
  
        def do_POST(self):
                # Use cgi module to retrieve data from POST as a form
                form = cgi.FieldStorage(
                        fp=self.rfile,
                        headers=self.headers,
                        environ={'REQUEST_METHOD':'POST',
                                 'CONTENT_TYPE':self.headers['Content-Type'],
                                 })
                # We can get value from the form key like we did in dictionary class
                encode = form['name'].value
                # Decide the value from base64 string
                decode = decodestring(encode)
                self.wfile.write('Hello, ' + decode + '.')
                
Handler = ServerHandler

# Initialize server object
httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()

Wednesday, November 28, 2012

Simple HTTP Server with Python

To create HTTP server in Python, we need to bind to a port & IP address, listen to that port for responding requests. To do that, we can use built-in module named BaseHTTPServer to handle HTTP requests. The main methods are do_GET and do_HEAD, we will need them to construct our header and body.

Here is a server code:
import SimpleHTTPServer
import SimpleHTTPServer
import SocketServer

# Server port
PORT = 8000

class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

 def _writeheaders(self):
  self.send_response(200)
  self.send_header('Content-type', 'text/html')
  self.end_headers()

 def do_GET(self):
  # Handle GET request
  self._writeheaders()
  self.wfile.write("""
  <html><head><title>Simple Server with Python</title></head>
   <body>
    Hello World!!!!
   </body>
  </html>""")

Handler = ServerHandler

# Initialize server object
httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()
For handling POST request, just create do_POST method in ServerHandler class. I will explain more in the next post. For this post, just want to ground the basic HTTP server knowledge.

References:

Nokia Lumia 920 Test Drive - 25-27 Nov 2012


In Thailand, Nokia open the campaign Test Drive that allows people to book and play Nokia Lumia 920 for 3 days. It's an amazing product. If you're looking for a new phone within 22k baht with full features and services. Lumia 920 is one of smart choice. It has a nice color: grey, white, red, yellow. For my first touch, I feel that it is a hi-end product and designed for human. It looks natural, and solid. I don't need any cover and screen protector at all, if I do, I feel like I'm hiding the coolest thing in Lumia 920. I have tried to test in many real usage situations to test user experience when using Lumia 920.

First thing that impressed me is the display. With Pure Motion HD+ technology and IPS, the display is very seamless to real world compared to the real objects. For me, the first sight I saw the tile screen in demo phone. I had thought that it is a mock up phone, but, actually it is a real phone!!! It is a kind of shocked, I can't distinguish between real and mock up phones. Moreover, it has a large display, you can read e-books from kindle app comfortably with amazing display.

Second test is battery, Nokia Lumia 920 comes with 2000 mAh. I opened 3G all day, and play the phone only movement (morning, noon, evening). It still remained 50%. So, I think Nokia provides battery size for using it at least one day without charging. However, If you manage wisely, I think it can continue to the end of a next day too.

Third test is sound, Nokia Lumia 920 speaker provide acceptable and loud sound but it's not good like dedicate speaker - -*. Compared to my phone (HTC One X), Lumia 920 has a louder voice. Then, I compared them with the same earphones, in my opinion, they provide the same level of voice and sound :D

Fourth test is mobility, it is a kind of big for me to bring it into a pocket properly. Also, Lumia 920 is heavier than my One X. So, it's a bit difficult to keep into a pocket for some trousers. My solution is hold it on my hand, and play during walk.

Fifth test is apps, productivity, and integration. I think Windows Phone is one of platforms which is able to let me feel comfortable and convenience to work within a few touches, compared to Android it's a bit messy like Joe Belfiore said. For me, I only concern about well-known apps e.g. foursquare, Kindle, map, Facebook, Twitter. Those are contained in Windows Phone store. So, the number of application is not a point. My point is the quality of these apps are still buggy such as Facebook notification doesn't work well as Android and iOS do. However, it has a XBox music and other interesting services included in Windows Phone features.


Sixth test is phone function. For a Nokia, they don't forget to bring the quality of basic phone features. Microphone has less noise even using the speaker mode. It also provides a good quality of respond sound especially when using a small talk.

The last test is camera, like Nokia claims, Lumia 920 provides fantastic features to take a shot such as low light - this one is very cool, however it's a bit brighter than eyes see. The panorama app is still not good, my short is blur.

In conclusion, I think Nokia Lumia 920 can be one of the best smart phones in this year, it depends on could Microsoft make Windows Phone OS more complete, and be able to fight others OSs  e.g. Apps to play with, etc.

Example pictures taken by Lumia 920:

Indoor
Outdoor with movement objects
Outdoor normal shot
Focus object
Night
Night

Night

Monday, November 26, 2012

HTTP POST data via WebClient and WebRequest

To request HTTP with POST method in .NET, there are 2 classes applicable to do that: WebClient, and WebRequest. I will describe  both ways in post. Normally to send the data back via POST method, there are 2 kinds of content-type (that I know) are url-encode, multipart. These two content types have an effect for the specific format for a receiver and how to construct a form message. In this post I will explain only url-encode. Firstly, we should know how to construct a format. For urlencode format, the format is very similar to querystring format like "{key1}={value1}&{key2}={value2}...". Moreover, we should encode the values like a GET parameter string (not necessary but for some characters, they need to).

To specific content-type for urlencode is set its value to "application/x-www-form-urlencoded".

Example 1: using WebClient
using System.Web;
...
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
     // Show a return message when upload is completed
     var result = (string)e.Result;
     MessageBox.Show(result);
}

private void Do_Something()
{
      string name = "Hello";
      string url = "<host ip>";
      var base64 = "name=" + HttpUtility.UrlEncode(result);

      var wc = new WebClient();
      wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
      wc.UploadStringCompleted += wc_UploadStringCompleted;
      wc.UploadStringAsync(new Uri(url), "POST", base64);
}
Example 2: using WebRequest
using System.Net;
...
private void Do_Something()
{
      string name = "Hello";
      string url = "<host ip>";
      var base64 = "name=" + HttpUtility.UrlEncode(result);

      var encode = Encoding.UTF8.GetBytes(base64);

      var request = WebRequest.Create(new Uri(url));
      request.Method = "POST";
      request.ContentType = "application/x-www-form-urlencoded";
      request.ContentLength = encode.Length;
      Stream dataStream = request.GetRequestStream();
      dataStream.Write(encode, 0, encode.Length);
      dataStream.Close();

      using (var response = request.GetResponse())
      {
           using (var reader = new StreamReader(response.GetResponseStream()))
           {
                // Show a response message
                string responseText = reader.ReadToEnd();
                MessageBox.Show(responseText );
            }
      }
}
The different from these 2 methods in my opinion are details for handling data i.e. We need to create delegate function for handling task when uploading is done, but WebRequest doesn't need to. Moreoever, WebClient has higher level of data sending compared to WebRequest. WebRequest need to pack data into byte array, but WebClient can send them as a pack of string directly.

Friday, November 23, 2012

What the different between Web Browser, Web Client, WebRequest, WebResponse

I found the answer from stack overflow. He said as the following description:
WebBrowser is actually in the System.Windows.Forms namespace and is a visual control that you can add to a form. It is primarily a wrapper around the Internet Explorer browser (MSHTML). It allows you to easily display and interact programmatically with a web page. You call the Navigate method passing a web URL, wait for it to complete downloading and display and then interact with the page using the object model it provides.

HttpWebRequest is a concrete class that allows you to request in code any sort of file over HTTP. You usually receive it as a stream of bytes. What you do with it after that is up to your application.

HttpWebResponse allows you to process the response from a web server that was previously requested using HttpWebRequest.

WebRequest and WebResponse are the abstract base classes that the HttpWebRequest and HttpWebResponse inherit from. You can't create these directly. Other classes that inherit from these include Ftp and File classes.

WebClient I have always seen as a nice helper class that provides simpler ways to, for example, download or upload a file from a web url. (eg DownloadFile and DownloadString methods). I have heard that it actually uses HttpWebRequest / HttpWebResponse behind the scenes for certain methods.

If you need more fine grained control over web requests and responses, HttpWebRequest / HttpWebResponse are probably the way to go. Otherwise WebClient is generally simpler and will do the job.
In my opinion, I prefer to use WebClient because it's much more higher level, and easy to use in case we need to specific setting parameters. However, if I only use it for crawl data, mostly I just use WebRequest because it's short, and simple don't need to have delegate for async function.

Reference: http://stackoverflow.com/questions/1780679/net-webbrowser-webclient-webrequest-httpwebrequest-argh

Convert string to byte array and byte array to string (C#)

To convert from string into byte array, we can use Encoding class to convert into specific format such as ASCII or UTF8.

Example: 
using System.Text;
...
string str = "Hello, World!!!";
byte[] byteData = Encoding.UTF8.GetBytes(str);
On the opposite way, to convert back from byte array into string, we can simply use StreamReader to read it from MemoryStream.

Example:
string output = string.Empty;
byte[] byteData = ...;
using (var memoryStream = new MemoryStream(byteData))
{
     using (var streamReader = new StreamReader(memoryStream))
     {
          output = streamReader.readToEnd();
     }
}

What is MemoryStream, and its purpose (C#)

MemoryStream represents a pure data in memory as a stream of data. It is useful to use with other types such as BinaryReader to improve performance. It can be constructed from array of bytes. To use MemoryStream, it will store in a memory which is faster than disk or network accesses, and use it as temporary data on memory.

Wednesday, November 14, 2012

Using the aria-labelledby attribute

The aria-labelledby attribute can be used for indicating label for an object which can be a list of id (separated by space). It is useful  for rich internet applications to describe objects. There are 2 sources, and 1 example websites that may helpful.

Monday, November 5, 2012

Crawl HTTP 403 Forbidden Error page (may solve)

Sometime, to crawl specific page, the web servers may block you crawl their contents using a simple method by looking at UserAgent header request from a client request. In well-known web clients like IE, FireFox, Chrome, Opera, those clients are trusted by anyone, so servers will allows them to access the contents. Specific programs, however, won't be allowed to do that just because they don't have signature for it. To solve this program, you can add UserAgent header into that program using signature from well-known web clients. In case that servers block for specific clients to prevent some bots that don't have UserAgent header,  This way is the easiest solution.

The following code is an example of adding UserAgent header in C#:
HttpWebRequest request = (HttpWebRequest)WebRequest.CreateDefault(uri);
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5";
And this is an example code for Python:
import urllib2
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
ob = opener.open('http://www.google.com/')
print ob.read()

Wednesday, October 17, 2012

Learn to code with Codeacademy

In the past to learn programming languages, we need to study from books, teachers, static website. However, today, we have a interactive website that can teach us online interactively to make us visualize how programming languages work. It's a lot easier than the past. Visit Codeacademy to start practice yourself :D

Saturday, September 29, 2012

Getting Start Windows Azure

Today, Cloud services are heavily used in many companies, which can reduce the expenses in term of hardware maintenance includes scalability problem. For the well known cloud service providers may be Amazon, Google, and Microsoft. In this post I've got Windows Azure information i.e. first step of setting up Windows Azure, and its architecture.


Another one is a link exploring cloud architecture: http://msdn.microsoft.com/en-us/magazine/hh852589.aspx.



In short, Windows Azure provides 3 types of cloud services as follows: IaaS, PaaS, SaaS while Amazon provide cloud service in the level of IaaS, and provide PaaS in Google.

Thursday, September 27, 2012

HTML5 Gaming with CreateJS

Nowadays, the JavaScript technology has moved very fast, which is now we can use it to create some games. CreateJS is a library set that consists of EaseJS, TweenJS, SoundJS, PreloadJS to do element controls, animation, sound, and resources management. It is under MIT license, so it is free to use.

The following link is a example to create a simple game using CreateJS: http://blogs.msdn.com/b/davrous/archive/2012/03/16/html5-gaming-animating-sprites-in-canvas-with-easeljs.aspx.

Download CreateJS and try it here.


Thursday, September 20, 2012

Disrupt University 1st round - 4 days workshop (TH)

The following links are about the first round of Disrupt University: Bringing Silicon Valley to Thailand brief story (in Thai contents). Personally, I had a chance to attend 2nd round of this workshop, however, due to some reasons I can't join to the course and rejected the acceptation.
  1. http://ojazzy.tumblr.com/post/27252524215/disrupt-university-1
  2. http://ojazzy.tumblr.com/post/27836116803/disrupt-university-2
  3. http://ojazzy.tumblr.com/post/28342886884/disrupt-university-3
  4. http://ojazzy.tumblr.com/post/28986929903/disrupt-university-day-4
For who don't know what Disrupt University is you can visit: http://disruptuniversity.com/.

Thursday, September 13, 2012

Get Dynamic Image in string format from Post Ajax Services

Instead of loading images via provided links, we can send images directly, and request it from ajax post channel. In order to do that, first covert image into array of bytes, then transform them into string base 64.
For example:
public JsonResult GetImage(string chartname)
{
    var chart = new Chart();
    chart.ChartAreas.Add(new ChartArea());

    var series = new Series(chartname);
    series.ChartType = SeriesChartType.Line;
    series.Points.AddXY(1, 1);
    series.Points.AddXY(2, 2);
    series.Points.AddXY(3, 3);

    chart.Series.Add(series);

    string result = null;
    byte[] bytes = null;
    using (MemoryStream stream = new MemoryStream())
    {
        chart.SaveImage(stream, ChartImageFormat.Png);
        bytes = stream.ToArray();
        result = Convert.ToBase64String(bytes);
    }
    return Json(result);
}
This example will convert chart image into PNG binary file format then convert to string base 64 before return.

For the client side, just write ajax post method, after get data insert image element into somewhere on a page.
For example:
<!DOCTYPE html>
<html>
 <head>
  <title>Image Service Index</title>
  <script type="text/javascript">
      function load() {
    $.ajax({
        type: "POST",
        data: { "chartname": "ImageServiceTest" },
     url: "@Url.Action("GetImage", "ImageService")",
     dataType: "json",
     success: function (response) {
         var chartDivId = $('#imageContent');
      // Response message will be json format if we use json as a data type
      $(chartDivId).html('<img src="data:image/png;base64,' + response + '" />');
     },
     error: function (ex) {
      debugger;
      alert(ex.status);
     }
    });
   }
   
   window.onload = load;
  </script>
 </head>
<body>
 <div id="imageContent">
 </div>
</body>
</html>
You can download full example here.
P.S. This example use ASP.NET MVC 3 for the server side, and use jQuery in the client side.

Setting Router (DD-WRT) as a client in unbridged mode

This a a Linksys router (DD-WRT), I just borrowed to configure it as a client hahaha. I mean config this router to connect main router ( has WAN) via wireless network, then make computers and client router connect together via LAN.

To set it up do as follows:
  • Change router mode (in wireless tab) to client mode, and set SSID to be the same as main router's SSID.
  • In wireless security tab (sub tab), set security mode and password to be the same as main router's also.
  • In security tab, disable firewall because it will make your setting become harder to be set. You can configure later if you want to.
  • In setup tab, change connection type to Automatic Configuration - DHCP, and disable STP.
  • Change router IP, which is different from main router IP. e.g. if your main router IP is 192.168.1.*, you can change a client router IP to 192.168.2.*. Next, use the same subnet mask.
  • Check at Use DNSMasq for DHCP.
  • Check at use DNSMasq for DNS.
  • Check at DHCP-Authoritative.
  • Set other stuffs if necessary.

Tuesday, September 11, 2012

Auto Mouse Move in C#

In .NET platform, it allows us to access a cursor of the mouse, and intercept accessibility from external environment (user input). It's quite easy to do so, just import "System.Windows.Forms", then play with Cursor class using static property "Cursor.Position". The property Position is from "System.Drawing" so you need to import this too in order to play with cursor position. The following code is an example program:
public static void Main()
{
     // Move cursor to (100, 100)
     Cursor.Position = new Point(100, 100);
}
Download full example program here.

Friday, September 7, 2012

Let's create own Evolutionary Optimization Algorithms (C#)

This post is just the same as the previous post. It's about basic algorithms in AI to solve optimization problems. In this post, I read from the same writer as previous post. He described how do we implement evolutionary algorithms and a program structure in the following link: http://msdn.microsoft.com/en-us/magazine/jj133825.aspx.

Let's create own Neuron Networks (C#)

It's a kind of fun to create own Neuron Networks. To review a school age lol (in AI class), take a look at http://msdn.microsoft.com/en-us/magazine/hh975375.aspx. He described very clear and detailed. You can follow him to create your own :D. 

The following page is a preview page that I just referred above:

Wednesday, September 5, 2012

How to Implement IDisposable correctly

Before getting to know how to implement IDisposable, must has some basic about .NET system first.

Unmanaged Code, which means the code developed outside .NET Framework is known as unmanaged code. It's not run under CLR (Common Language Runtime) such as C++ can be used to write such applications , for examples, access low level functions of the operating system. It offers the powerful features that managed code does not, and might damaging as well. Unmanaged code can be unmanged source code and unmanaged compile code, and  unmanged  code is execute with the help of wrapper classes, and caution is required (doesn't be executed by CLR). It will be compiled into machine code and executed by the OS directly.

Managed Code is the code that targets to common language runtime which is under foundation of .NET Framework. Managed Code will supply necessary things for CLR to provides services such as memory management, cross-language integration, handling security, lifetime control of objects, in short, it will look after your applications. All code based on IL (Intermediate Language) executes as managed code.

Garbage Collector will clean unused resources automatically, but can still call it explicitly. It will do finalizer in destructor of each object. The process of cleaning resources are done in a finalizer thread not a main thread.

Unmanaged Resources falls into two categories:
  1. Resources that are wrapped in a managed class (ie Bitmap, Font etc) but still need Dispose to be called to clean them up property.
  2. Resources that you allocated that are representations of native resources (ie device contexts that need to be released)
The propose of using dispose is we want to free both kinds of unmanged resources. Note that for the first kind of unmanged resources, the garbage collector will take care of them  when it have to clean them up. We only need to focus about true native resources that we have allocated (in case we have).

Monday, September 3, 2012

Quick Prototyper for Web and Mobile Apps

Take a loook at: http://www.justinmind.com/prototyper/free-edition. It's free and easy to use for prototype Mobile and Web Applications. It will be useful in case you want to show idea of your apps to others, want to make them understand look and feel of your apps in the same time, and want to avoid misunderstand and communication when deliver messages to others.

The following demo is the example of this program.

Thursday, July 26, 2012

How to temporary fix mouse cursor disappear in Google Chrome

Some of you may face this problem in Google Chrome that the mouse cursor will be dis appear when it stay idle just for seconds, and it will be appear again when it is moved. Moreover, it will be gone during drag a web content. So, this problem is very annoying. I, personally , don't know how this problem come from, but to fix this problem (may be just temporary fix) you need to kill process of plug-in "Shockwave Flash" task using Chrome Task Manager then your cursor will be like the old one you miss T^T.

Saturday, July 7, 2012

Silverlight Binding and StringFormat in XAML

This link is help a lot to know string format syntax in Silverlight Binding.

Tilt Effect in Windows Phone

Take a look at a following link, he clearly explained about the problem of tilt effect in Windows Phone Toolkit, and then how to use his effect in Windows Phone development in a pace.     

Monday, June 25, 2012

SQL Server Database Filegroup is Full; What, Why and How?

Take a look at http://learnsqlwithbru.com/2012/01/10/sql-server-database-filegroup-is-full-what-why-and-how/. The author stated it very clear. In short, the problem can be summarize into 3 cases: disable auto growth, data size is over the given limit, and not enough disk space available.

Sunday, June 17, 2012

How to configure FTP Server in Windows Server 208 R2



After that, you may need to config the Passive Port Range for FTP Service which you can follow this instruction. It will show you steps, and explain what they are.

Create Global Unique Identifier (GUID) in C#

Similar to the previous post, Microsoft introduced another standard called Global Unique Identifier to create a unique key in order to use in applications.
It is pretty much easy as following lines of code:
Guid id = new Guid();
id = Guid.NewGuid();
Console.WriteLine(id.ToString());
Now, you can enjoy creating GUID for your applications ^^.

Create Universal Unique Identifier (UUID) in Python

Most of the time when I write database related programs, I often think about how to create a good id because one of the good id characteristic is meaningless. It should has no meaning, to doesn't let anyone understand something behind this id.

In Python, we can easily create it by using uuid module that is included in Python standard library as following example:
import uuid
ob = uuid.uuid4()
print str(ob)
There are 4 kinds of uuids in Python: uuid1(), uuid3(), uuid4(), and uuid5() that you can take a look for more details at http://docs.python.org/library/uuid.html.

How to handle "The path X is already mapped in workspace Y"

Take a look at http://blogs.msdn.com/b/buckh/archive/2006/09/12/path-is-already-mapped-in-workspace.aspx.

Shortly, you have to remove Team Foundation Server cache that store at "C:\Users\{User}\AppData\Local\Microsoft\Team Foundation\3.0\Cache" named "VersionControl.config". After, you remove it, Visual Studio won't remember the map path from your local path to source control server, then you can map that path to the new server freely.

Saturday, June 16, 2012

Run another exe process in C#

Run another exe process in C# Sometimes, we may want to call other programs to do something in our program before going to do next step.
In C#, simply, by calling Process class in System.Diagnostics namespace.
This class has a lot of features as following examples:
- Enable/Disable new Window to launch new program.
- Redirect input/output and error stream to the main program.
- Run a process in synchronous or asynchronous.
- Receive arguments

Wednesday, May 30, 2012

Embed Fonts in Windows Phone

To embed external fonts into Windows Phone, it is not difficult. First, you need to have fonts (*.ttf). Then, you add it into your Windows Phone project. Next, at your font properties, copy to output directory to copy if newer. Finally, in FontFamily property of your control. Refer to your font file followed by # then a font name, which contained in your font file.
// For example my font file name is RSU_Regular.ttf, and it is under fonts folder in my project.
// Refer to font name "RSU" which contained in RSU_Regular.ttf.
<UserControl ... FontFamily="fonts/RSU_Regular.ttf#RSU" ...> 
     ... 
</UserControl>
If you want to change control's font in C# file, you can do it by:
this.FontFamily = new FontFamily("fonts/RSU_Regular.ttf#RSU");

How to generate List of Anonymous Types in C#

Normally, we can use List<T> when T is a strong type, then we can add Class T to that List. However, we can trick it by creating a method that receive generic type T, and create List of type T as a return.
// Tricky method to return anonymous List
public static CreateList<T>(T ob)
{
     var list = new List();
     return list;
}

// Create anonymous object, and let's generate our list
var person = new { Name = "Hello", Age = 10 };
var list = CreateList(person);
list.Add(person);
list.Add(new { Name="John", Age = 47 });
It is useful in some cases, but be careful that anonymous objects you created are read-only objects, we can't modify their data after we created them.

Friday, May 18, 2012

Create Chart using Chart Helper in ASP.NET MVC 3

To insert chart into a web page in ASP.NET MVC3, you can use Chart Helper which included in MVC 3. It will generate image chart dynamically that you can use generated chart to be the image soruce in image tag.
In cshtml page has an image element as follows:
<!-- It will refer to /[Name]Controller/MyChart, and send back an image chart. -->
<img src="@Url.Action("MyChart")" alt="SimpleChart" />
Under your controller class, you create a MyChart method that return String in an image format (jpg/png) as an action.
public ActionResult MyChart()
{
     var bytes = new Chart(width: 400, height: 200)
          .AddSeries(
               chartType: "bar",
               xValue: new[] { "Math", "English", "Computer", "Urdu" },
               yValues: new[] { "60", "70", "68", "88" })
          .GetBytes("png");
     return File(bytes, "image/png");
}
After that, you will get the chart image when requesting MyChart action.

Thursday, May 17, 2012

Read Excel files in .NET

First of all, some people may have a chance to work with excel files. However, to working with it for both reading and writing it has some difficulties e.g. how many ways to access excel files especially if you are not Windows users, which use Microsoft Excel in daily life. To solve this problem, what we need is a cross platform tool to access excel data.

Here, it is a tool for Excel Data Reader to read excel files in CodePlex (to use this tool in Linux, you must install Mono).

First, Know your format first, different version of Excel using different class.
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
// or
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
Second, Load it as a DataSet, also includes the feature select the first row to be the column name.
//3. DataSet - Create column names from first row (true/false)
excelReader.IsFirstRowAsColumnNames = true;
//DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
Third, Get the data from DataTable.
foreach(DataRow row in result.Rows)
{
     // Do something
}
Finally, Don't forget to free resources (IExcelDataReader is IDisposable)
excelReader.Close();
More at: http://exceldatareader.codeplex.com

There are also many ways to access Excel files. e.g. using Microsoft.Jet.OLEDB, Microsoft.Office.Interop.Excel.

For example: using Microsoft.Jet.OLEDB to access a excel file.
String filePath = "somewhere";
// Load connection string
OleDbConnection con = new OleDbConnection(String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0", filePath));
// select [column_name], ... from [sheet_name]$[range]
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$A1:C3]", con);
// Load data into DataTable
DataTable dt = new DataTable();
da.Fill(dt);

foreach (DataRow row in dt.Rows)
{
     // Do something
}

excelReader.Close();

What is the difference between a dashboard and a scorecard?

A scorecard measures performance against goals and typically display in graphic indicator to visually display the overall success and failure. It is based on key performance indicators(KPIS).

Scorecard sample
But a dashboard is a container for various types of reports, and provide high level of interactivity.

Dashboard sample

Wednesday, May 16, 2012

How to get all items in current directory in C#

To get all items in a given current directory it needs to use a combination of two methods: GetDirectories(), GetFiles(). Both of them are the static method in class Directory which return all folders, and all files in the given directory respectively.
static String[] Dir(String path)
{
     // Get all folders in a given path
     List list = Directory.GetDirectories(path).ToList();
     // Get all files in a given path then add them to the list which contains folders
     list.AddRange(Directory.GetFiles(path));
     // You may sort the result, the ordering will be similar to dir function in the command prompt
     list.Sort();
     // Get the result
     return list.ToArray();
}
To use the function you written, it is very easy to use by giving the string path to it, it will give you an result.
static void Main(string[] args)
{
     string[] filepaths = Dir(@"C:\\");
     // Show all items under your drive C.
     foreach (String filepath in filepaths)
          Console.WriteLine(filepath);
}

Monday, May 7, 2012

Interesting Blog posts about HTML5

Mostly about game development with HTML5: .
Facebook HTML5 Showcase: Facebook HTML5 Center.

p.s. If there are any more interesting blog posts about HTML5, I will add them on this post.

Sunday, April 29, 2012

Integrating HTML5 and Javascript with Windows Phone 7

Nowadays, everybody is now talking about HTML5 to be the new generation of all internet applications. It, however, still not a perfect solution for application on all devices, because it can't be integrated seamlessly with all devices when compared to native applications for specific devices. By the way, later, it is more likely that some platforms are going to move how to develop their applications to HTML5 or at least full support for it. So, Windows, from Microsoft, is one platform that is trying to change by using HTML5 and javascript to develop their applications in Windows 8, and try to support HTML5 features in all of their platforms. The question is how about the future of Windows Phone, which uses Silverlight to develop the application? Is it going to dead or changes all things to HTML5 like Windows 8 support? I really in doubt about this.

By the way, however, we still can develop Windows Phone by integrating some parts of applications to use HTML5 under the native Silverlight application. We can connect browser components like javascript and HTML files using WebBrowser class, which supports HTML5, to render web components through IsolatedStorage. The example is in  this link. It will show the sample how to integrate web components and native application seamlessly.

Finally, the advantages of doing this, which changes the way how to present the application, is we change the presentation layer (on top) to be HTML5 that supported in many platforms and may be the standard in the future. We can reuse the presentation part in other platforms, then the native application code will treated like a machine code and change javascript to working as a framework that can bridge HTML5 and native code in any platforms, it will allow the developer can write applications easier.

p.s. For games, this post is very interesting too, which uses a framework to connect between HTML5 and device itself.

Monday, April 23, 2012

The success story behind Instagram engine - What powers Instagram

There is a story of Instagram wrote on their blog. The power of Instagram engine - very fast with dozen technologies here. Meanwhile Instagram succeed in iOSs, moreover, they also have launched Android version, which Instagram needs to service much more than a million new users , with acceptable performance. Their story about keeping Instagram up for a million new users is here.

Wednesday, April 18, 2012

Windows 8 Shortcuts

Take a look at this link: http://www.addictivetips.com/windows-tips/windows-8-keyboard-shortcuts-with-screenshots/. It provides you many shortcuts for Windows 8. Windows 8 has a major changes form Windows 7, so, basically the shortcuts are changed a lot. I have been confused until now =__=".

Monday, April 16, 2012

How to change Windows 7 Logon theme

To change Windows 7 logon screen, it can be done with 2 ways: download tweak programs, and do it manually.

To use tweak program in order to change the screen, you can download Tweaks.com Logon Changer for Windows 7.
For another method, you can change it by yourself in the registry by follow the instructions on http://www.techspot.com/guides/224-change-logon-screen-windows7/ if you don't want to install add-on similar programs.

Wednesday, April 11, 2012

Android Design

Google has published the website that provide the principles for Android 4.0 to make it more standardize. Look at this site: http://developer.android.com/design/index.html.

Moreover, I also found another website http://www.androidpatterns.com/ which provide UI design principles too. It guide you and explain each design style in details. 

How to create .apk file from Eclipse and publish app to Android Market (TH)

Look at this link: http://www.unzeen.com/article/1096/ขั้นตอนการสร้างไฟล์-apk-จาก-eclipse-และนำขึ้นสู่-android-market.

Saturday, April 7, 2012

Windows Phone 7 Development for Absolute Beginners

There is a Microsoft channel provide us many tutorial series like a workshop called Windows Phone 7 Development for Absolute Beginners. This channel will guide you from the beginning to ground your knowledge then you can continue on your own.

Sunday, March 18, 2012

Recommended books for Natural Language Processing course

According to the online course of Stanford University, they suggest the following books to be used in NLP class:
It's now live, you can learn for free, the Standford Online course of Natural Language Processing!!!

Access AWS via Putty and SSH for newbie

Look at http://clouddb.info/2009/05/17/a-quick-overview-of-putty-and-ssh-for-aws-newbies/, this website will be talking about how to access AWS via Putty and SSH in Windows because Putty can't read .key file directly.

Monday, March 12, 2012

Microsoft Thailand open the course for Windows 8 Application Development

In recent days, Microsoft has launched Windows 8 Consumer Preview. This version of Windows is the combination between old fashion Windows (PC) and Mobile (Windows Phone 7) to be used in all platforms, and expand their market to tablets. As you know, Windows Phone 7 uses Metro Style for its applications. In the same ways, Windows 8 has included Metro Style mode to allow developers implement Metro applications. 

We can write Metro style apps using familiar technologies like HTML5, JavaScript, and Cascading Style Sheets, Level 3 (CSS3), or XAML, with C++, C#, or Microsoft Visual Basic code-behind. Then, Microsoft Cooperation has raised the roadshow for Windows 8 around the World. Fortunately that Thailand is one of them. They corporate with famous universities in Thailand i.e. ChiangMai University, Kasetsart University, Assumption University. You can register at here on the bottom of the page to participate this event and see the information about time for the course.

Friday, March 2, 2012

Software Engineering for Software as a Service is now open

Few weeks ago, Berkeley open the course Software Engineering for Software as a Service as an online course, which is anyone can join it here. This course is mainly focus on agile development process, cloud computing, and high productive frameworks & tools.

Wednesday, February 1, 2012

Google Voice Search for CM7 (Android)

I have used Xperia X10 so far, and I regretted an official rom for X10 every time Sony launched. So, I have changed my phone rom to be CM7 instead. It is a great rom. However, it does not include voice search, then I found the problem that it can not be found form the market. Luckily, there is a person who ripped this program from his phone and share it in xda-developer forum here http://forum.xda-developers.com/showthread.php?t=1429125. Thanks to this, my phone has got almost all of important features in Android 2.3 except the basic one - multitouch, which is the hardware problem T__T. Finally, I hope you guys enjoy using it ^^.