I know this probably sounds like a crazy exercise, but I've been finding it very enlightening.
I've been working on the one application for about 12 months (personal project). I know exactly what I want to do with it, but because I've been exploring a stack of new technologies, I'm finiding that I'll get part of the functionality working, and then rewrite the code in a new technology stack. I've played with Rest, MVC, ADO.NET, Linq, Entity Framework, WinForms and a host of other bits. WPF is on the list to investigate once I get the functionality running the way that I want.
One nice thing about this 'playing around' is that I know the logic, the general structure, and the high level architecture. As I go along, I'm finding my code is more precise... less verbose. I hate giving out my code when I'm 'tinkering' ... it always looks like a dogs breakfast. But by the time I'm finished, it's generally pretty much to the point and clean. I remember a bug I worked on at work a few years ago, the initial code was lines and lines long. I spent about a week on it. And the end result was about 3 lines long.
Kind of makes me think that code would be so much nicer if you got to rewrite a major system after you initially built it. It probably would be more stable, more efficient, and easier to maintain.
I think this is why some artists get stuck on the same subject matter, repainting using new tools, techniques and methods. It's all about editting, revising and rethinking. I'm getting to the point now where I just want to finish to application so I can actually start using it.
Sunday, December 13, 2009
Saturday, December 12, 2009
Entity Framework query
Three examples of doing a simple select operation - one using standard entity framework, one using Linq to Entities, one using a lambda expression.
//example using entities. No filtering of the data.
var books = context.Book;foreach (var book in books)
{
Console.WriteLine("{0} {1} {2}", book.Author, book.Title, book.URL);
}
//example using Linq to entities. Adding in a where clause to filter out the data a bit
var booksLinq = from b in context.Book
where b.Author.Contains("Brown")
select b;
foreach (var item in booksLinq)
{
Console.WriteLine("{0} {1} {2}", item.Author, item.Title, item.URL);
}
//example using lambda
var booksLambda = context.Book.Where(c => c.Author.Contains("Brown"));foreach (var book in booksLambda )
{
Console.WriteLine("{0} {1} {2}", book.Author, book.Title, book.URL);
}
Saturday, October 24, 2009
Loading applications code sample
Code snippet for loading applications (This was adapted from a tutorial over at CodeProject so not even going to claim that I was the first to do this :) It's just a function I've used a few times at home). I'll be expanding it to take in a FileName as a string that will be the file I want to load, but I'm a keep it simple kind of girl. Do the basics first, get that bedded down, then add in more complexity. This is for windows apps/ console apps.
FileName is the location of the executable I want to load
i.e. FileName = @"C:\Program Files\Mobipocket.com\Mobipocket Reader\reader.exe";
private void loadApplication(string FileName)
{
Process p = null;
try
{
p = new Process();
p.StartInfo.FileName = FileName;
p.Start();
p.WaitForExit();
}
catch (Exception ex)
{
Console.WriteLine("Exception Occurred :{0},{1}",
ex.Message, ex.StackTrace.ToString());
}
FileName is the location of the executable I want to load
i.e. FileName = @"C:\Program Files\Mobipocket.com\Mobipocket Reader\reader.exe";
private void loadApplication(string FileName)
{
Process p = null;
try
{
p = new Process();
p.StartInfo.FileName = FileName;
p.Start();
p.WaitForExit();
}
catch (Exception ex)
{
Console.WriteLine("Exception Occurred :{0},{1}",
ex.Message, ex.StackTrace.ToString());
}
Outputting XML to a file
A quick way to debug XML contents (I'm using this as apart of a webservice call - where the response is long)
//Create an XML document
XmlDocument doc = new XmlDocument();//Do stuff with it (add elements, properties, nodes, update text whatever)
.... // Save the document to file so you can look at it later
doc.Save("C:\\temp.xml"); // You could also do it as - particularly if you have a long path to where you are saving your files
doc.Save(@"C:\temp.xml");//Otherwise, dump into the output window
doc.Save(Console.Out);Sunday, October 4, 2009
String formatting in ASP.NET
I'm doing some pretty basic string formatting stuff while playing with an ASP.NET MVC application. The C# syntax for string formats in ASP.NET is pretty straight forward. At the moment I'm more interested in getting the controllers working - I can play with making the view pretty later :)
String formatting allows you to render common text formats such as:
- Dates
- Currency
- alignment
- numbers such as reals, decimals, scientific formats, floats, hex
Some basic examples that I've played with are:
Purchase Price: <%= Html.Encode(String.Format("{0:c}", Model.PurchasePrice))%>
would render to the HTML page as Purchase Price: $49.95
Release Date: <%= Html.Encode(String.Format("{0:d}", Model.ReleaseDate)) %>
would render to the HTML page as Release Date: 7/11/1999
And because it's rendering in string format, if there is no string passed, then nothing is returned (it doesn't fall over). I haven't yet played with what happens if it can't format into a particular value as the data was validated before saving. But like a dutiful coder, that's what my unit tests will be for (when I wite them for this page now that the basic code is there.)
http://idunno.org/archive/2004/07/14/122.aspx has a fantastic overview of string formatting tags
Saturday, October 3, 2009
Various Links/ blog posts/ articles
Some interesting posts:
Programming for complete beginners
Talks about Microsoft's site for beginning programming
Cross Browser & Multibrowser testing using Microsoft Expression Web Support
A way of testing multiple browsers on the same OS
Performing common tasks with Linq in ASP.NET
- finding enabled text boxes
- finding long items in a drop down box
MVC & Entity Framework
Considering they're just about to release version 2 of the ASP.NET MVC framework, I'm wondering how much will change ...
Making it easy to refactor
- Providing good test names
- well named variables
- appropriate test coverage
- avoiding fragile tests
- avoiding [Setup] and [tear down]
Programming for complete beginners
Talks about Microsoft's site for beginning programming
Cross Browser & Multibrowser testing using Microsoft Expression Web Support
A way of testing multiple browsers on the same OS
Performing common tasks with Linq in ASP.NET
- finding enabled text boxes
- finding long items in a drop down box
MVC & Entity Framework
Considering they're just about to release version 2 of the ASP.NET MVC framework, I'm wondering how much will change ...
Making it easy to refactor
- Providing good test names
- well named variables
- appropriate test coverage
- avoiding fragile tests
- avoiding [Setup] and [tear down]
Saturday, September 19, 2009
casting nullable ints or int?
Hmm, love nullable types :) But sometimes they can be a little tricky. When working with Linq, you sometimes create anonymous types as a return. If the field that you bring back is a nullable column in the database, it can mean that the anonymous type created is a nullable type as well. The next computation you use can check to see if the value is null, and if it's not, assign it to a new variable. Not saying this is the best way or even the only way, but it worked for me, and I liked it :)
int value = (myNullableValue.HasValue) ? 0 : myNullableValue.Value;
What does it all mean? It's a ternary operation.
If the first value is true ((myNullableValue.HasValue) ? 0), return that, otherwise return the second expression (myNullableValue.Value)
Otherwise if you've already done a nullable check ...
int value = (int)myNullableValue;
int value = (myNullableValue.HasValue) ? 0 : myNullableValue.Value;
What does it all mean? It's a ternary operation.
If the first value is true ((myNullableValue.HasValue) ? 0), return that, otherwise return the second expression (myNullableValue.Value)
Otherwise if you've already done a nullable check ...
int value = (int)myNullableValue;
Friday, September 18, 2009
Dynamic data website error
If you get this error when setting up a dynamic website there are two things it could be:
"There are no accessible tables. Make sure that at least one data model is registered in Global.asax and scaffolding is enabled or implement custom pages"
Firstly check the Global.ascx.cs page to make sure that you've updated YourDataContext to whatever the name of your datacontext is.
Secondly make sure ScaffoldAllTable is set to True.
"There are no accessible tables. Make sure that at least one data model is registered in Global.asax and scaffolding is enabled or implement custom pages"
Firstly check the Global.ascx.cs page to make sure that you've updated YourDataContext to whatever the name of your datacontext is.
Secondly make sure ScaffoldAllTable is set to True.
model.RegisterContext(typeof(YourDataContext), new ContextConfiguration() { ScaffoldAllTables = true });
Sunday, August 30, 2009
Joins - Joining a table to itself
This is a quick sql query that you can use to join a table to itself. There are a lot of joins, the most common is used to join two related tables together, but the LEFT JOIN can be a really quick alternative to a Sub query.
I used something similar to populate a treeview that had child and parent nodes. Effectively each parent had muliple children, and I used a sql query to check the data that I wanted (I will turn this into a LINQ statement in code, rather than a stored procedure)
use category
select c.ParentID, c.ChildID, c.Description
from category c
left join category p on c.ChildID = p.ParentID and p.ChildID = c.ParentID
order by c.ParentID
More info here: http://www.w3schools.com/sql/sql_join_left.asp
I used something similar to populate a treeview that had child and parent nodes. Effectively each parent had muliple children, and I used a sql query to check the data that I wanted (I will turn this into a LINQ statement in code, rather than a stored procedure)
use category
select c.ParentID, c.ChildID, c.Description
from category c
left join category p on c.ChildID = p.ParentID and p.ChildID = c.ParentID
order by c.ParentID
More info here: http://www.w3schools.com/sql/sql_join_left.asp
Labels:
SQL
Sunday, August 23, 2009
Importing an Access database into SQL Server
I have an old application I want to rewrite. It uses an Access database and considering there's more about a 1000 records in it, I am not about to manually re-add the data. As part of the upgrade I wanted to work with SQL Server instead. So what's a quick way to upgrade?
I have Access & Microsoft SQL Server 2008 installed. I have a blank database on SQL server set up to import the data into.
If everything goes well, when you hook into SQL Server, your data will all be there!
More info from MSDN: http://msdn.microsoft.com/en-us/library/ms188032.aspx
I have Access & Microsoft SQL Server 2008 installed. I have a blank database on SQL server set up to import the data into.
- Go to Start > Microsoft SQL Server 2008> Import and Export Data. This begins a simple Wizard process
- Select the source that you want to import from (in this case Access) & browse to the location of the Access database.
Set any options like passwords. I'm doing a straight conversion into a blank database. I don't need to do any special queries, but you could specify which tables the data goes into, which tables you want to import and which ones you don't. - Click the ok button :)
If everything goes well, when you hook into SQL Server, your data will all be there!
More info from MSDN: http://msdn.microsoft.com/en-us/library/ms188032.aspx
Labels:
Access,
conversion,
SQL
Saturday, July 11, 2009
Code I love #2: regex & verbatim string literal
A really simple regular expression to strip out anything except alpha or numeric characters. In the following example \r, \n, !! and space are all non-alpha numerics.
Example characters that this could strip out
\n = new line
\r = carriage return
\" = quotation marks
\\ = Backslash
\t = tab
...
using System.Text.RegularExpressions;
....
string input = "This \r is a !! test \n";
string output = Regex.Replace(input, @"[^a-zA-Z0-9]", string.Empty);
//output = Thisisatest
By the way, using the @ symbol in fromt of a string means that you don't have to muck around with escape characters like \[]/. This is known as a verbatim string literal. Essentiall any string where you write @" at the beginning of the text in question (and close it off with ") means that all characters inside the quotation marks are treated exactly as they are typed.
Example characters that this could strip out
\n = new line
\r = carriage return
\" = quotation marks
\\ = Backslash
\t = tab
...
using System.Text.RegularExpressions;
....
string input = "This \r is a !! test \n";
string output = Regex.Replace(input, @"[^a-zA-Z0-9]", string.Empty);
//output = Thisisatest
By the way, using the @ symbol in fromt of a string means that you don't have to muck around with escape characters like \[]/. This is known as a verbatim string literal. Essentiall any string where you write @" at the beginning of the text in question (and close it off with ") means that all characters inside the quotation marks are treated exactly as they are typed.
Friday, July 10, 2009
Code I love #1: IsNullOrEmpty(string)
String.IsNullOrEmpty(string)
Back in days of yore you would need to do something like
if (String.Empty) || (string = "") || (string = null)
{
//do stuff
}
Now you can cover off all those in one hit with String.IsNullOrEmpty(string).
(And yeah, code probably is probably wrong because I try not to use them since upgrading from vb6/ .net 1.0, but you get the idea :) )
Back in days of yore you would need to do something like
if (String.Empty) || (string = "") || (string = null)
{
//do stuff
}
Now you can cover off all those in one hit with String.IsNullOrEmpty(string).
(And yeah, code probably is probably wrong because I try not to use them since upgrading from vb6/ .net 1.0, but you get the idea :) )
Wednesday, July 8, 2009
Beginnings... on Agile & bug fixing
About 5 months ago I began the way overdue transfer from VB6/ .NET 1.0/ SQL 2000 to the new and exciting world of C# & VB.NET 3.5. Of course 4.0 is just around the corner with VS2010 being released, but still, I can write about stuff I'm learning :) I'm not expecting that I'll be writing about anything majorly interesting to anyone else, and I won't really be one for answering other people's questions. The stuff I write at work is all confidential, though the stuff I'm learning working in the Microsoft SDC is majorly awesome.
http://www.betterprojects.net/2009/06/email-whiteboards-and-well-caffeinated.html
Fantastic article on project management
1. Set Your Sights - defining the goal
2. The Real Team Energizer - making information critical to the project easily available to everyone in the project
3. Don’t Rush into Commitment
4. Ask Around - see what others have tried
Interesting article on how bugs are a failure in process and 3 questions we need to ask to improve ourselves as devs: (http://secretgeek.net )
1. Is this mistake somewhere else also?
2. What next bug is hidden behind this one?
3. What should I do to prevent bugs like this?
Great quote about agile development. Maybe I should put it on a t-shirt and walk around the office? "Agile is about surfacing pain. It's not about roses, perfume, and happy candlelight dinners together. " http://codebetter.com/
NotImplementedException is an awesome way of stubbing stuff out when you haven't figured out your return statement
http://www.betterprojects.net/2009/06/email-whiteboards-and-well-caffeinated.html
Fantastic article on project management
1. Set Your Sights - defining the goal
2. The Real Team Energizer - making information critical to the project easily available to everyone in the project
3. Don’t Rush into Commitment
4. Ask Around - see what others have tried
Interesting article on how bugs are a failure in process and 3 questions we need to ask to improve ourselves as devs: (http://secretgeek.net )
1. Is this mistake somewhere else also?
2. What next bug is hidden behind this one?
3. What should I do to prevent bugs like this?
Great quote about agile development. Maybe I should put it on a t-shirt and walk around the office? "Agile is about surfacing pain. It's not about roses, perfume, and happy candlelight dinners together. " http://codebetter.com/
NotImplementedException is an awesome way of stubbing stuff out when you haven't figured out your return statement
Subscribe to:
Posts (Atom)
