A technical blog about programming and technology.

Friday, December 21, 2007

Generating html with Xlinq?

As web developers we have, at some point in our careers generated html on the server.  It always gets messy especially when your are generating a table from data. Its always done with messy strings! What about setting attributes...   string row = "<td class=\"name\">" + value + "</td>" .. what a pain.
Xlinq is new in .NET 3.5 (The X stands for XML), you can read more about it here. I found(i think) a much better way to generate html on the server using asp.net. I needed to make an ajax call to the server that returned a filtered and paged table based on the parameters I passed.

Here is a screen shot of what the code looked like:

image

And generating the rows of the table:

image

The helper methods, Html.AsLink creates html markup("<a href...") as an XElement otherwise the special characters are escaped.

Pretty neat huh?

Thursday, November 15, 2007

Update, Silverlight 1.1 and Senior Design

So it's been a few months since I posted . I've have a very successful summer and I'll be joining Microsoft next year after I graduate. What's new? Well first things first my senior design project has changed from language design to a programming contest website... Pretty drastic, I know. I've been active with my school's ACM programming contest team for the last 3 years and we thought it would be cool to host an "Online Judge" at our school. So what exactly is an "Online Judge"? Sites like Topcoder, SPOJ, and ACM TJU that have automated judging software; users sign up and submit problems, compete in online contests, share knowledge of algorithms, design etc...

We aim to have a mixture of features from the sites mentioned above, but also have a stronger community. The site is currently live at http://fudge.fit.edu, but is password protected for now, we plan to have open beta testing in a few months. 
We currently accept submission in the following languages:

  • GNU C\C++
  • Java 1.5
  • C#
  • VB.NET
  • Python

With plans to add Haskell, Ruby, Perl and PHP in the near future.

We have, 3 computers that support the fudge framework and website, MILK, SUGAR and BUTTER, the compilation machine, web server and database respectively. The database is SQL Server 2005 running on Windows 2003 server.  Fudge is developed in Visual Studio 2008 Beta 2 using  ASP.NET and C# 3.0. For source control we are using TFS 2008 Beta 2.

The Fudge website uses the Fudge Framework. The framework acts as a service provider to pluggable modules. It handles uploading source code, remote compilation, and remote execution. The judging module, for instance, provides a bridge between the website and the framework. Source code are update the to the database, and a judge request is sent to the module. The module then uses the framework capabilities to compile the code, and runs test cases. The results are the saved to the database. In the near future, the framework will also provide a database interface, allowing modules not to establish specific connections and execute queries.

So where does the Silverlight come in? Topcoder has a java applet, which can be used to do practice problems and is used in actual contests. The applet allows users to code directly in the online arena, submit problems, run sample test cases, and chat.

In the last 2 weeks I've been working in Silverlight 1.1 alpha to try to make an online IDE for the fudge website. With the current bits in the alpha, this is a pretty tough to task to achieve,  i.e lack of textbox control, and many other useful controls.

The first version of the IDE control was an attempt to get it working initially, so the code was pretty disorganized:
you can view a demo here.

The second attempt was to create a base textbox control and derive other controls from it so I could find bugs when trying to use the textbox in other scenarios. Here is a demo of a command prompt control that derives from the TextBox control.

The control is still being refractored and optimized but you can take a look at its current state here.
Features missing are:

  • Page up
  • Page down
  • Selection
  • Copy and Paste in firefox

Saturday, August 4, 2007

Anonymous types and Page Methods

I've been playing with asp.net Ajax for the last couple of days in VS Orcas beta 1(haven't downloaded Beta 2 as yet), and I wondered if it was possible to return an anonymous type to JavaScript using the PageMethods feature. This is a very useful for web scenarios, for example you may want to return a list of tuples and bind a list of key and value pairs to a drop down list. Surprisingly it just works.

 

public class Person {
public string Name { get; set; }
public int Age { get; set; }
public int Id { get; set; }
}

public static List GetPersons() {
return new List { new Person { Name = "David", Age = 20, Id=1 }, new Person { Name = "John", Age = 10,Id=2 },
new Person { Name = "Harry", Age = 30,Id=3 }, new Person { Name = "Peter", Age = 40,Id=4 }, new Person { Name = "Jodi", Age = 15,Id=5 }};
}

[WebMethod]
public static object GetData() {
return from p in GetPersons()
where p.Age >= 20
select new { p.Id, p.Name };
}

On the server side the static method that is exposed to JavaScript is marked with the WebMethod attribute. The return type of the method is object since we can't name the return type. The result of the query expression is an IEnumerable< class { int Id; string Name }>, on the JavaScript side we get a collection of these nameless types that we can iterate over and populate a drop down list. Try it out, I thought it was very cool they way we could leverage new C# 3 features to enhance other programming domains.


 

<script type="text/javascript">
function populate() {
PageMethods.GetData(function(res) {
var list = $get('list');
var options = "";
for(var idx in res) {
options += "<option value='" + res[idx].Id + "'>" + res[idx].Name + "</option>";
}
list.innerHTML = "<select onchange='showValue(this)'>" + options + "</select>";
});
}

function showValue(list) {
alert("Id = " + list.options[list.selectedIndex].value);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager EnablePageMethods="true" runat="server">
</asp:ScriptManager>
<div>
<a href="javascript:populate()">Populate Drop Down</a> <br />
<div id="list" />
</div>
</form>
</body>
</html>



Technorati tags: , , ,

Wednesday, June 27, 2007

Experimental Language?

After exploring ideas about my senior design project, a friend and I have come up with an idea to produce a programming language. I know your probably like.. yea right do we really need another language? But its clear that there is always room for innovation in programming languages and language design in general. So far we've decided that it's going to be a .NET language and it's going to be C style. One very interesting idea I had was based on a statement I read in C# Team Wes Dyer's Blog, "One of the criticisms leveled at design patterns is that they are simply formalisms to address weaknesses in programming languages.  They require the human compiler to generate code whenever a specific recurring problem is encountered that cannot be solved directly with language support" you can read the post here. This makes me think, "how would a language be if it was based purely on syntactic sugar?" There will still be support for doing stuff "manually" for those die-hard programmers, but the majority of developers out there, want to be productive; this is a major strength of C# and Java (Not dissing C++ :)).  Managed code is more "manageable" in general. The LINQ project was a major effort to bridge the gap between data and the programming language. The convenience of not having to worry about memory allocations, and cleanup is nice. Most programmers want to avoid all the plumbing to achieve a task; they want good libraries and a good language that supports those. So our attempt will be to based the programming language on the developer, and make a new and familiar syntax for expressing algorithms.

Friday, June 8, 2007

Microsoft Surface

I haven't posted anything in a while cause I've been busy with work. Its fun up here in Redmond and I'm really enjoying my internship as a developer.

So the Microsoft surface is the next big thing. Its pretty amazing, reminds me of minority report. We see all these futuristic movies and ideas of what technology might be like in the future and it seems we are getting closer every day.. take a look Microsoft Surface

Tuesday, May 15, 2007

I've Arrived!!

Finally after a great weeks vacation home, I've arrived in Seattle. I'm staying in a studio apartment in downtown Bellevue. The Xbox is setup, I have wireless Internet, a bed, kitchen and bathroom, what more could you ask for. Tomorrow is my first day of work and I look forward to it.

Saturday, May 5, 2007

Finals are over!

Thank god finals are over, I'm packing my stuff getting ready for my one week vacation in paradise (Barbados).  Its been a grueling week and I'm just happy to spend this week relaxing, not thinking about having to study until work starts. I'll have some interesting things to post during the summer hopefully :D. Two of my friends were successful in the first round of Microsoft interviews and are getting a free trip to Seattle so I hope to see them when I am there and wish them the best of luck.

Monday, April 30, 2007

Finals Begin!

It's finals week here at Florida Tech. Today was the start of hell week for me. I took my Formal Languages exam today, so 1 down! but 5 more left :S. I'm going back home Saturday to spend about 9 days with my girlfriend and family. After the ten days I leave for Seattle. This summer I'm going back to Microsoft to do another internship with the ASP.NET developer team. Wish me luck this week!!!

Coding in Haskell

Programming Language class is alot of fun (sometimes). I spent part of the weekend studying for exams and playing with haskell. I realized I missed one part of the assignment after I submitted, but it was an interesting formatting issue. What's most interesting about functional languages is how concise the code is for some complex problem. Consider the following problem:

I have a list of strings and I want to put an element o after every n elements in the list, then convert the list to one space delimited string.

Lets try to do it in C++ :

string insertEvery(int n, string o, vector<string> & vs) {
string res = "";
int pos = 0;
for(vector<string>::iterator it = vs.begin(); it != vs.end(); ++it) {
res += *it;
if(++pos % n == 0) {
res += " " + o + " ";
}
else {
res += " ";
}
}
return res;
}
Next up C# (Kind of a different approach):
string insertEvery(int n, string o, List<string> list) {		
for (int i = n; i < list.Count; i+=n) {
list.Insert( i++, o );
}
return string.Join( " ", list.ToArray() ).Replace( " " + o + " ", o );
}
And the winner...Haskell :
insertEvery n y [] = []
insertEvery n y x = (take n x) ++ [y] ++ insertEvery n y (drop n x)
insertEveryToString n y x = concat $ intersperse " " $ insertEvery n y x
I love the concise function definitions. Thinking totally recursive is hard at first, but once you get it everything just pieces together...

Saturday, April 28, 2007

Microsoft Interviews

Last week , a couple of my friends had Microsoft phone interviews. Since I got my internship last summer, they have been coming to me for advice and interview "training". In coming up with some questions to give my friends, I remembered the isPalindrome function I saw a while back and came up with this question:

	bool isPalindrome(int x) {
}
x is guaranteed to be a positive number, and single digit numbers are palindromes.  By the way converting to a string is not an option :D nice try.

Monday, April 23, 2007

Software Engineering Project

My team for the Software Engineering class had to develop a website. check it out.

Saturday, April 21, 2007

Windows Systems Programming

My last assignment was Dll Injection. We had to take a random process ID and if the application had winsock loaded, we were to intercept functions connect, recv, send, and closesocket and print the parameters.

After trying various methods and failing, e.g overwriting the IAT(Import Address Table) etc. I deceided to go the hard ,fickle way.

Here was the process described by a Microsoft research paper i found.

Create 2 functions,  a Trampoline function and a Detour function.

  • Create a Trampoline function
  • Copy the first 5 bytes of the real function to the Trampoline function
  • Add an unconditional jmp to the 6th byte of the real function
  • Overwrite the real function with an unconditional jmp to your Detour function.
  • At the end of your Detour function jump to the trampoline function.

Sounds kinda confusing. If you think that's bad look some of the code i wrote.

void CopyToTrampoline( LPVOID lpTargetFunction,  LPVOID lpTrampoline , int offset ) {
DWORD old;

PBYTE pbActual = (PBYTE)lpTargetFunction;
PBYTE pbTramp = (PBYTE)lpTrampoline;

//make page writable
VirtualProtect( lpTrampoline, 5 + offset, PAGE_WRITECOPY, &old );

for(int i = 0; i < offset; ++i) {
*pbTramp++ = *pbActual++;
}
pbActual = (PBYTE)lpTargetFunction;

//set jump
*pbTramp++ = 0xe9;

*((DWORD*)pbTramp) = (pbActual + offset) - (pbTramp + 4);

//restore protections
VirtualProtect( lpTrampoline, 5 + offset, PAGE_EXECUTE, &old);
}

void Redirect(PVOID lpTargetFunction, PVOID lpDetourFuntion) {
DWORD old;

VirtualProtect( lpTargetFunction, 5, PAGE_WRITECOPY, &old);
//copy unconditional jump
*((PBYTE)lpTargetFunction) = 0xe9;

//copy the next 4 bytes
*((DWORD*)((PBYTE)lpTargetFunction+1)) = PtrToUlong(lpDetourFuntion) - (PtrToUlong(lpTargetFunction) + 5);

//restore
VirtualProtect( lpTargetFunction, 5, PAGE_EXECUTE, &old);
}


The worst thing about getting help online if when they show you a function but not how to use it, but i will not do the same :).

	
void Intercept(PVOID lpTargetFunction, PVOID lpTrampoline, LPVOID lpDetourFuntion, int offset) {

CopyToTrampoline( lpTargetFunction, lpTrampoline , offset);

Redirect( lpTargetFunction, lpDetourFuntion );
// Flush the instruction cache to make sure
// the modified code is executed.
FlushInstructionCache(GetCurrentProcess(), NULL, NULL);

}

//Intercepting connect function in winsock
//get winsock2 module
HMODULE hWinSock = GetModuleHandleA("ws2_32.dll");
if(hWinSock) {
Intercept( connect, ConnectTrampoline, MyConnect, 5 );
}

The ConnectTrampoline and MyConnect are both naked.


Technorati tags: , , , ,

Thursday, April 19, 2007

Camping out

My school has this weird tradition, where students that wish to sign up for the on campus apartment have to "camp out" outside of the housing office until its opened. This is all because of the first come first serve policy. The signup for Southgate apartments are this Sunday, yet I am in a tent from Wednesday because of the crazy attitude of Americans wanting to be the first. This kinda thing isn't uncommon in here though. Just last year there were millions in line waiting for the playstation 3 and nintendo wii so I'm not very surprised. The tent isn't all bad though except the the fact that as summer in Florida approaches the days are getting warmer.. and by warmer I mean 25 degrees Celsius with no wind.. So I sit patiently between classes in my tent waiting until Sunday to attempt to get a single room for my last 2 semesters at Florida Tech.

Saturday, April 14, 2007

Programming the Atmel16

So like I said I got my hands wet programming an LCD. The initial code written by the computer engineers to display the characters to the screen was something like:

  UDR = 0xFE; //tell the port we want to send
UDR = 0x01; // clear the LCD
UDR = 'L';
delay_ms(120);
UDR = 'u';
delay_ms(120);
.... etc
This code hurt me, so I was determined to improve it :P. First of all notice the magic numbers 0xFE and 0x01, the comments do help us understand what they mean but they are not very clear. Better to do this :
 #define CLEAR(port) { port = 0xFE; port = 0x01; }
#define SETPOS(port, pos) { port = 0xFE; port = 0x80; port = pos }
...
typedef unsigned char byte;

void print_to_lcd(char* buffer) {
.... check the string size and for NULL
CLEAR(UDR); //clear LCD
SETPOS(UDR, 0) // start at first position of LCD
byte* p = (byte*)buffer; //the serial port wants bytes
while(*p) {
UDR = *p++;
delay_ms(120);
}
}
This was only the beginning improvement. Everyday programming paradigm, write a function for something we want to reuse throughout the program. Now they could just call print_to_lcd("Lunar Raiders") and we get the same effect as before with less code. But I had a funny feeling inside that I was reinventing the wheel, which is not always a bad thing, but I did a little research. They are C functions like printf, fopen ..etc that print characters or bytes to the stdout. Since the hardware has no notion of a console, maybe there was a way to redirect the stdout to mean the UDR(uart port) on the board. After a little research this is what I found:
init() {
... initialize board
// associate uart output function with stdio 
fdevopen(uart_putchar, NULL,0);
}
int uart_putchar(char c) { 
if (c == '\n')
uart_putchar('\r');
loop_until_bit_is_set(UCSRA, UDRE);
UDR = c;
return 0;
}

Knowing what to search for is sometimes harder that knowing what to do. After finding this code I could use printf("%s %d", "this is cool" ,4 + 5); and like normal and it would print to the LCD.


 


del.icio.us tags: , , ,

Senior Design Showcase

Yesterday, from 11am to 5pm seniors and juniors showed projects they were working and will be working on for the next year. Three projects in particular appealed to me. Wakeup Word Speech Recognition, Lunar Raiders Autonomous Robot, and Eye Tracking software. All three are computer engineering projects and one of the benefits of senior design at this school is the ability to cross majors to work on projects allow you to broaden you skills. Yesterday was the first time I ever programmed any piece of hardware. It was an LCD on the Lunar Raiders dev board, now I am hooked.. The speech recognition is an area of research done by Dr. Veton Kepsuka here at Florida Tech, and it still could use some work. What I would propose maybe is a generic API in .NET/C++ which allows you to easily integrate his speech into your existing program. Anyways I'll try to make my decision and see how it goes from there.

Tuesday, April 10, 2007

Senior Design Blues

It's senior year for me at university and I have to decide on a "big project" that all/most seniors complete and present before they graduate. Last Friday students starting their senior design next semester were gathered, and professors showed what "interesting" things they were doing, research wise. Its kinda hard to decide if I should try to come up with my own project or join another team. If you have any suggestions on something I can "build"(application wise) or maybe some useful device let me know.

Answer!

Yesterday a few people were asking about possible solutions to the problem. Here is my solution.

	if(!printf("hello")) {
printf("hello");
}
else {
printf("world");
}
At a glance it seems impossible. There is no way to take both paths in an if statement.Therefore we need a 
function that returns false and prints hello.
If you know C/C++ really well you'd know that printf returns the number of
characters printed to stdout and if you negate that, you get zero. I welcome any other solutions that you come up with.
printf reference

Monday, April 9, 2007

Best Google interview question

A few weeks ago, a friend approached me with a set of google interview questions. There was one that i found particularly interesting, and really creative.


	if(condition) {
printf("hello");
}
else {
printf("world");
}
What condition prints "helloworld"?
i'll post the solution tomorrow.

Friday, April 6, 2007

Top Coder Open

I've been into programming for a while, but not competitively(I mean it's not like it's a sport :) ) , until I came to this school. Topcoder is a competitive programming/development site where young or old programmers can participate in a series of contest which test different skill set. I prefer the algorithm competition. Even though my rating is not that high, I enjoy participating alot. Recently I qualified for the TCO, that's the Top Coder Open tournament. I'm really excited to be a part of this tournament with some of the worlds best programmers! I'm Round 1B on Tuesday wish me luck.

First Post

Hey guys this is my first post. Welcome to David's Place. I'm a computer scientist at Florida Institute of Technology from Barbados(not Jamaica) , its in the Caribbean for those who don't know. Its a small island most easterly of all the Caribbean.