|
10:7 AM Saturday Sep 30, 2006
Comments: 0
Do you use source control on your personal stuff? I used to use cvs, then switched to subversion, and next was sourcegear vault. Since rebuilding my dev machines back in feb I haven't been using source control on my personal projects and recently that has caused me some grief. So installed sourcegear vault, personal single user license is free so there's no reason not to try it out if you value your own code. This also comes in handy when I'm switching between my laptop and my desktop machines. Just this morning I tried something out with some code for panteravb, didn't like it after a few revisions, so I rolled back to the one I liked, no sweat.
9:38 PM Thursday Sep 28, 2006
Comments: 0
Oh ya, mark your calendars. Killswitch Engage will be releasing their next album on Nov 21. If you haven't heard of Killswitch Engage then either you live under a rock or I am a loser metal head...WAIT! don't answer that.(and judging from the page extension, they are fans of dot net...or...they have no idea what dot net is and they hired some cool developers who do)
8:3 PM Thursday Sep 28, 2006
Comments: 0
Not your typical scope creep. But something closer to my personal todo list. I have sooo many things I want to do. It's funny really. I bought Getting Things Done and the helper book, and never had enough time to finish them. I have tons of code I need to post, tons of article ideas I need to get written up, a gazillion tools and utility ideas that need to be realized, and always I end up with not enough time on my hands. In less than 4 weeks, kid # 2, Emmitt will be coming into this world and then it's game over, no more sleep for daddy :( Currently, I get up by 4am every day. I'm a type 1 diabetic and need to make sure I have enough fuel in my system for my workout, so I get up and eat, then run 5 to 7 miles and follow that up with weights. I'm usually eating breakfast by 7am, and get to work between 7:30 and 8. I usually make it until 4 or 5 in the afternoon at the day job then split for home. Now it's time to play with my first kid, Riley. She goes to bed by 7pm, so from 5ish to 7 it's dinner and play time. Then we clean the house a little bit, and I can sit down to figure out what needs to get done. I start with my blogs that I read, there's not that many but I can spend at least an hour reading through those. Then I finally I settle down to some code. That's usually where I get stuck. I'm writing my own blog tool so I can try out some concepts, like build providers and castle project's active record. I have a dedicated linux box running ubuntu that's sitting there waiting to be used and abused.I have books(both geek and non-geek) to read. Plenty of new .NET 2.0(and now 3.0, jeez) concepts to wade through. I usually get done muckin around with stuff between 10 and 12 and start the same thing over in the morning. I guess this entry is not helping getting any more things done, but now I feel better.
8:44 PM Tuesday Sep 26, 2006
Comments: 0
Ok, I've realized that I worry too much about the quality of my code. I wanted to post my demo for the ActiveRecordBuildProvider sooner than later and then realized a couple of things. First of all it depended on the CodeSmith schemaexplorer assembly to aid in walking the database objects. I couldn't post that since it's not open source. So then I started rolling my own schemaexplorer and came up with some really lame solutions; plus, I really wasn't interested in writing my own schema explorer, there are smarter people than me writing better code that I'd rather buy. That said I also did not want to publish code with a database dependency either. I went back and forth on this one, until I decided that if you're already using castle project activerecord then you probably already have a database to connect to and the dependency would not be a problem. I only realized this after running through some mockup DataTable examples that I did not like at all so I pulled those out. The concept here is exactly the same as the SubSonic project(which is too cool for words, you just gotta try it). The only difference is that I probably spent a lot less time on it(hence the lame quality of my code) and I use the castle project activerecord implementation.
Here is the zip that includes version 0.0.0.0001 of an idea I wanted to code up. Since I am a big fan of eating my own dog food, this site uses the exact same code as presented in the download.
6:22 PM Sunday Sep 24, 2006
Comments: 0
I never thought I'd get a lappie but today I did. Today, while walking through Sam's club, I saw it, a 17 inch wide screen that was calling my name. My requirements were simple, 17 inch screen and at least 1 gig of ram, the one I got has 2 gigs of ram and an NVidia 7600 with 256 megs of memory. 2 100 gig hard drives and all of the devices I could imagine; many of which I don't even know what they're for since I'm a lappie Noob. Media Center edition of Windows is actually pretty cool; I have remotes and devices galore for this thing, the first order of business was to play my Killswitch Engage video, loud. My kid started banging her head, it was good times. Also just noticed that apparently I have developed the editor interface for a 21inch monitor running at a way higher resolution than this laptop has cuz I'm having to do a whole lot of scrolling which is very annoying.
7:13 PM Thursday Sep 21, 2006
Comments: 0
BuildProviders are new in .NET 2.0, and are one of the coolest features in the framework. I was first introduced to the concept when I was messing around with SubSonic(aka ActionPack). If you have not played with SubSonic yet, it's over here and very well worth your time. SubSonic leverages BuildProviders by using them to inspect a specified database schema and generates all of the compiled data layer code using the ActiveRecord pattern. The most important and coolest thing about this, is that your data access code is live and any change to a database object is immediately recognized the next time you build a project.
I've been digging into the ActiveRecord implementation that the Castle Project has created and is built on top of NHibernate. It's a great model to use for your data layer but you still have to code up your entities, albeit with very little code, but it's still a step I could do without. Last night I built a very simple BuildProvider that generates those entities. I used the SchemaExplorer assembly that ships with CodeSmith to inspect the database. Spinning through each table that I need generated, I generate the entity classes using the CodeDom inside of my BuildProvider. I generate partial classes so that I'm allowed to add custom functionality that does not get stepped on during every build.
Here's the schema to a table named customers:
Now assuming the BuildProvider is configured properly, all you need to do is compile your project and the following class will be generated, compiled, and available for your using pleasure:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ActiveRecordGenerator {
using System;
[ActiveRecord("customer")]
public partial class Customer : Castle.ActiveRecord.ActiveRecordBase {
private Int32 _id = 0;
private String _firstname;
private String _lastname;
private String _phonenumber;
private DateTime _createdate;
public Customer() {
}
[PrimaryKey(PrimaryKeyType.Native, "customer_id")]
public Int32 ID {
get {
return this._id;
}
set {
this._id = value;
}
}
[Property("first_name")]
public String FirstName {
get {
return this._firstname;
}
set {
this._firstname = value;
}
}
[Property("last_name")]
public String LastName {
get {
return this._lastname;
}
set {
this._lastname = value;
}
}
[Property("phone_number")]
public String PhoneNumber {
get {
return this._phonenumber;
}
set {
this._phonenumber = value;
}
}
[Property("create_date")]
public DateTime CreateDate {
get {
return this._createdate;
}
set {
this._createdate = value;
}
}
}
}
I grabbed that code from a testing harness, using the System.Web.Compilation.BuildProvider you won't actually see that code, it gets compiled. All you get to do is use the code like this:

I still think it's funny, that the codegen sticks in the comment This code was generated by a tool.That gets me every time...I need to clean up the code a little more tonight but hopefully I'll have it posted.
9:36 PM Tuesday Sep 19, 2006
Comments: 0
I'm a big fan of the concept of unobtrusive javascript. That's why I use prototype and scriptaculous and event-selectors to name a few. Yesterday I came across Unobtrusive Table Sort Script and this thing frickin rocks. Reference the tablesort.js script, add any class="sortable" to any column header(must be a th tag) that is sortable and you're done. Start sorting. Here is an example of how to hook that up:
<html>
<head>
<script src="/path/to/tablesort.js"></script>
</head>
<body>
<table>
<tr>
<th class="sortable">MySortableColumn</th>
</tr>
<tr><td>Some Data</td></tr>
<tr><td>Some More Data</td></tr>
<tr><td>Some Other Data</td></tr>
</table>
</body>
</html>
There are plenty more examples here. If you're looking for a simple solution that "just works", check out Unobtrusive Table Sort Script.
9:16 PM Monday Sep 18, 2006
Comments: 0
I had a need to write a bunch of html, a whole page actually, programmatically. No user controls, just old school html. What a pain in the ass. I thought about the System.Web.UI.HtmlTextWriter, however that turned out to be a gynormous headache due to the amount of typing involved. So then I thought I'd be the clever guy and use an System.Xml.XmlDocument. That sucked too, for the same reasons. What do I end up with? My good friend the System.Text.StringBuilder. She may not know what html is, or xml or nodes or stylesheets or scripts, but she can whip up simple html easier than the rest. I didn't go down the path of using xsl stylesheets and System.Xml.Xsl.XslTransform for .NET 1.1, or the new and improved System.Xml.Xsl.XslCompiledTransform for .NET 2.0, that seems like overkill and I also want to display formatted code which sometimes is a pain(escaping and what have you).
I am still looking for a better solution, an easier one. I am generating this html from an assembly and it's based on what's inside of the assembly, so simple is key. I've had a need in the past to make ajax calls to .NET stuff on the backend but sometimes hooking it up was a little bumpy. So I'm playing around with a new thing that initially designed to demonstrate how to easily integrate prototype and .net but now I'm expanding this to include some unit testing and documentation generated from the assembly at runtime. Here is a demo.
7:39 PM Monday Sep 11, 2006
Comments: 0
Here's a generic version of a Pluck method: public class PluckableList<T> : List<T>{
public Array Pluck(string propertyName){
Type type = typeof(T);
PropertyInfo property = type.GetProperty(propertyName);
Array result = Array.CreateInstance(property.PropertyType, this.Count);
for(int i=0;i<this.Count;i++){
result.SetValue(type.InvokeMember(propertyName, BindingFlags.GetProperty,
null, this[i], null), i);
}
return result;
}
}
5:30 PM Monday Sep 11, 2006
Comments: 0
Today I came across a situation I find often enough to make me look for something a little slicker. Let's say you have a collection of objects, Person objects, and you want to call a method but it accepts an integer array of id's. Each Person instance has an ID property, and looks like this: public class Person{
private string _firstName = "";
public string FirstName{
get{ return _firstName; }
set{ _firstName = value; }
}
private string _lastName = "";
public string LastName{
get{ return _lastName; }
set{ _lastName = value; }
}
private int _id = 0;
public int ID{
get{ return _id; }
set{ _id = value; }
}
public Person(string firstName, string lastName, int id){
this._firstName = firstName;
this._lastName = lastName;
this._id = id;
}
}I usually end up doing something like this: PersonCollection peeps = new PersonCollection();
//add some Person instances to the collection
int[] ids = new int[peeps.Count];
for(int i=0;i<peeps.Count;i++){
ids[i] = peeps[i].ID;
}
//call some method that accepts the int array
someMethod(ids);The prototype javascript library adds a method to Arrays named pluck that's pretty handy for grabbing the value of a property off of every instance in an Array. I wanted that for my C# code so here's my version of pluck for C#: public Array Pluck(string propertyName){
Type type = typeof(Person);
PropertyInfo property = type.GetProperty(propertyName);
Array result = Array.CreateInstance(property.PropertyType, this.Count);
for(int i=0;i<this.Count;i++){
result.SetValue(type.InvokeMember(propertyName, BindingFlags.GetProperty,
null, this[i], null), i);
}
return result;
}Assuming we have the Person class defined like above, we might have PersonCollection class defined like so: public class PersonCollection : CollectionBase{
public Person this[int index]{
get{ return this.List[index] as Person; }
set{ this.List[index] = value; }
}
public Person Add(string firstName, string lastName, int id){
Person result = new Person(firstName, lastName, id);
this.List.Add(result);
return result;
}
public Array Pluck(string propertyName){
Type type = typeof(Person);
PropertyInfo property = type.GetProperty(propertyName);
Array result = Array.CreateInstance(property.PropertyType, this.Count);
for(int i=0;i<this.Count;i++){
result.SetValue(type.InvokeMember(propertyName, BindingFlags.GetProperty,
null, this[i], null), i);
}
return result;
}
}Using the Pluck method: public class Program{
static void Main(string[] args){
try{
PersonCollection peeps = new PersonCollection();
peeps.Add("Chris", "Carter", 666);
peeps.Add("Anja", "Carter", 1);
peeps.Add("Riley", "Carter", 2);
string[] firstNames = (string[])peeps.Pluck("FirstName");
foreach(string firstName in firstNames){
Console.WriteLine(firstName);
}
int[] ids = (int[])peeps.Pluck("ID");
foreach(int id in ids){
Console.WriteLine(id);
}
}catch(Exception ex){
Console.WriteLine(ex.ToString());
}
Console.WriteLine("Done...");
Console.ReadLine();
}
}Click here for the whole example, you can stick this right into Snippet Compiler and hit run to see it in action.
8:49 PM Saturday Sep 9, 2006
Comments: 0
...how is it that an article entitled Script.aculo.us, Prototype and Asp.Net: Best Friends Forever (via DotNetSlackers) attempts to suggest how well ASP.NET and great JavaScript libraries work with each other but does not demonstrate anything supporting this? I'm a huge fan of prototype and scriptaculous, if you haven't heard of them, go there now, download them, and see the power of those libraries for yourself. There's more to using ASP.NET with prototype and scriptaculous than just getting the ClientID off of the server control so you can interact with them in javascript, that step has been needed since day one of ASP.NET. You can't discuss how the JavaScript libraries get along and then skip talking about AJAX and how those libraries can use ASP.NET on the backend. A good example of of this interaction is an autosave feature that I implented today for my blog tool. I use FreeTextBox and wanted to save what I'm typing every so often but didn't want the hassle of clicking save. In a matter of minutes I was able to implement this using prototype and overriding the OnInit method of my ASP.NET page. I have a checkbox that toggles the autosave feature. When it's checked, a PeriodicalExecuter fires evey 30 seconds and saves whatever I'm typing using the Ajax.Request class from the prototype library. It posts a request to the original page. OnInit is overridden to check whether a request has been made to autosave. This is indicated by requesting the page like this, TargetPage.aspx?op=autosave, and then on the backend testing for the op variable in the querystring. The server side code looks like this, if (!String.IsNullOrEmpty(Request.QueryString["op"])){
Post post = Post.Find(System.Convert.ToInt32(Request.Form["id"]));
if (post != null){
post.Published = System.Convert.ToBoolean(Request["published"]);
post.Content = Request["content"];
post.Title = Request["title"];
post.Save();
Response.ContentType = "text/plain";
Response.Write(DateTime.Now.ToString());
Response.End();
}
}The javascript on the client side was a breeze, Event.observe('chkAutoSave', 'click', chkAutoSaveclick, false);
var watcher;
function chkAutoSaveclick(event){
var chk = Event.element(event);
if (chk.checked)
watcher = new PeriodicalExecuter(autosave, 30);
else
if(watcher) watcher.stop();
}
function autosave(){
var url = "TargetPage.aspx?op=autosave";
var p = $H();
p["id"] = $F('<%= hidPostID.ClientID %>');
p["title"] = $F('<%= txtTitle.ClientID %>');
p["published"] = $('<%= chkPublished.ClientID %>').checked;
p["content"] = FTBAPI['<%= txtContent.ClientID %>'].GetHtml();
new Ajax.Request(url,{
method: 'post',
parameters: p.toQueryString(),
onComplete: function(request){
$('status').innerHTML = "Auto Saved at " + request.responseText;
}
});
}This shows how JavaScript can work well with ASP.NET. There are some great resources on the prototype library. Sergio Pereira has written some fantastic documentation on a pretty much undocumented library. Justin Palmer has a wealth of information on this topic as well. I have a lot of examples of using prototype and scriptaculous along with ASP.NET server side functionality that I will be posting. The following is a simplified version of the autosave concept, click here to see it in action. <%@ Page Language="C#" %>
<script runat="server">
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
string op = Request.QueryString["op"];
if (!String.IsNullOrEmpty(op) && op == "autosave")
{
//save stuff here
Response.ContentType = "text/plain";
Response.Write(DateTime.Now.ToString());
Response.End();
}
}
</script>
<html>
<head>
<script src="../scripts/prototype.js"></script>
</head>
<body>
<form runat="server">
AutoSave: <input type="checkbox" id="chkAutoSave" /><br />
Name: <input type="text" id="txtName" /><br />
<em id="status"></em>
</form>
</body>
</html>
<script>
Event.observe('chkAutoSave', 'click', chkAutoSaveclicked);
var watcher;
function chkAutoSave_clicked(event){
var chk = Event.element(event);
if (chk.checked)
watcher = new PeriodicalExecuter(autosave, 5);
else
if (watcher) watcher.stop();
}
function autosave(){
var params = $H();
params["name"] = $F('txtName');
new Ajax.Request('PrototypePlusAspNet.aspx?op=autosave', {
method: 'post',
parameters: params.toQueryString(),
onComplete: function(request){
$('status').innerHTML = request.responseText;
}
});
}
</script>
8:13 PM Saturday Sep 9, 2006
Comments: 0
Tonight, I sat down with a six pack of Harp Lager, Chris Sells' book Windows Forms 2.0 Programming, and watched a great flick, Kiss Kiss Bang Bang. I had not heard of the movie, but it was good, a little off beat and kept my attention for most of the time. I didn't get too far in the book and finished 5/6 of my beer. I have a race tomorrow up in Nederland, CO, it's a 10k, and will be the last one for a bit since little Emmitt will be arriving soon and my spare time will go bye bye :) I also just found a bug in my super spectacular blog software; I just noticed that I now have 4 entries titled 'Kiss Kiss Bang Bang'...dammit!
6:5 AM Saturday Sep 9, 2006
Comments: 0
The script.aculo.us Ajax.Autocompleter is simple. Lately I've been using a generic WebHandler to deliver results to the autocompleter and this is working well. Here is a simple example(SimpleAutoCompleter.html).
The html for the textbox is usually something like this:
<input type="text" id="names" />
<div id="name_choices" class="autocomplete"></div>
The javascript that kicks off the whole thing:
new Ajax.Autocompleter('names', 'name_choices', 'FindNames.ashx', {paramName:'frag'});
...where 'names' is the id of the text input field, 'name_choices' is the div containing the choices and is populated with the content returned from the webhandler, {paramName:'frag'} tells the Ajax.Autocompleter to 'post' a form variable named 'frag' to the webhandler containing the contents of the input box with the id 'names'.
Next we need to style the drop down menu:
* { font-family:Georgia;font-size:12px;}
div.autocomplete {
position:absolute;
border:1px solid #888;
margin:0;
padding:0;
}
div.autocomplete ul {
list-style-type:none;
margin:0;
padding:0;
}
div.autocomplete ul li.selected { background-color: #ffb;}
div.autocomplete ul li {
list-style-type:none;
display:block;
padding:2px;
height:14px;
cursor:pointer;
}
The webhandler(FindNames.ashx) that returns the results, returns <ul> and <li> tags with the results:
<%@ WebHandler Language="C#" Class="FindNames" %>
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
public class FindNames : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string fragment = context.Request.Form["frag"];
context.Response.ContentType = "text/html";
List<string> names =
new List<string>(new string[] { "Chris", "Christian",
"Christy", "Christina", "Christmas" });
List<string> matches = names.FindAll(delegate(string name)
{
return name.StartsWith(fragment, StringComparison.OrdinalIgnoreCase);
});
context.Response.Write("<ul>");
foreach (string match in matches)
{
context.Response.Write(String.Format("<li>{0}</li>", match));
}
context.Response.Write("</ul>");
}
public bool IsReusable {
get {
return false;
}
}
}
8:48 PM Friday Sep 8, 2006
Comments: 0
10:29 PM Tuesday Sep 5, 2006
Comments: 0
I love squishyWARE's SyntaxHighlighter. However, I do have needs to html-ify many other things that squishyWARE does not support. Wilco Bauwer has a great tool for syntax highlighting that I like better, compare for yourself: squishyWARE:
var Person = Class.create();
Person.prototype = {
initialize: function(name){
this.name = name;
}
}Wilco'svar Person = Class.create();
Person.prototype = {
initialize: function(name){
this.name = name;
}
}
7:49 PM Tuesday Sep 5, 2006
Comments: 0
The Prototype JavaScript library kicks ass. Period. It lacks documentation but there are many out there doing there best to help. This site has rounded up a good collection of intros and reference material for the Prototype library. It has become an automatic include in any pages requiring much client interaction.
I've used WebHandlers to help with processing Ajax requests on the server side when using the Prototype framework. Most of the time it involves just parsing the QueryString to determine what the request is and then passing it on to whatever needs to do the job. The demo has some very basic code in it to show how easy it can be to implement Ajax functionality. You can click on the demo link and view source to see the code for the html page. The following is the code for the WebHandler:
using System;
using System.Threading;
using System.Web;
public class SimpleAjaxRequestHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string op = context.Request.QueryString["op"] ?? "default";
string result = "";
switch (op.ToLower())
{
case "sayhello":
Thread.Sleep(3000);
result = "The server says hi!";
break;
case "default":
default:
result = "This is some default response";
break;
}
context.Response.ContentType = "text/plain";
context.Response.Write(result);
}
public bool IsReusable {
get {
return false;
}
}
}
5:57 PM Monday Sep 4, 2006
Comments: 0
I love living in Fort Collins, CO. Since today was a holiday, we needed something to do. We ended up starting the day by working out. Early in the mornings around here, there are many hot air balloons taking off and it's pretty cool to watch, I'd love to take my kid up in one, she always freaks out(in a good way) over any kind of balloon. At the City Park in downtown FC they have a mini train for little kids and their parents, so we took the little one on there and it was a hoot, we had to drag her away screaming(seriously, she was screaming).
Later in the day we were bored and needed somethin to do so we took a little 40 minute drive up to Poudre Canyon, and was able to walk along the river; that just seemed too cool, 40 minutes and voila, we're up in the mountains.
Fort Collins also makes some great brews. New Belgium Brewery is awesome, they make great beers and have an awesome tasting room. Odell's is great too, my favorite is their Cutthroat Porter.
10:55 PM Saturday Sep 2, 2006
Comments: 0
Very cool. I added the 'my del.icio.us ajax' section to the left by adding a little bit of javascript and grabbing a JSON feed from del.icio.us. They send back an object populated with all of the links, which you can request by tag. I use this url for the datasource of the links, http://del.icio.us/feeds/json/chrcar01/ajax. Nice and simple.
|
|