CodeCampOz 2010 bits and pieces

So I got to day one of codecamp this year (family things on during day two). I was once again impressed by the lineup and the quality of presentations and have managed to find quite a few links/presentations:

DDD and UNIT OF WORK

http://omarbesiso.typepad.com/the-archidev/2010/11/codecampoz-2010.html

UNIT TESTING

http://blog.rajsoftware.com/post/2010/11/28/Automating-QUnit-and-JSTestDriver-within-VS2010.aspx

IOC

http://justinbozonier.posterous.com/breaking-up-with-ioc (not a presentation but good related article)

BDD

http://davidburela.wordpress.com/2010/11/23/community-report-code-camp-oz-2010liam-mclennan-on-bdd/

TFS 2010 Build Automation

http://notgartner.wordpress.com/2010/11/28/version-control-build-automation-guidelines/

General Sites:

http://codecampoz.com/

Dom

 

Advertisement

Tutorial: Building a simple CRUD application using ASP.NET Webforms, Code First EF 4 and SQL CE 4

Introduction

The following shows how easy it is to create simple web sites using the new Code First Entity Framework, SQL Compact Edition and Web Forms. It must be said that a number of parts of this solution are still beta, so expect the unexpected.

I won’t go into either Code First Entity Framework or SQL Compact Edition but check out Scott Guthrie’s(see references) articles as they are fabulous on both topics.

I am using Webforms initially because I find it a very quick building simple sites using ASP.NET webform controls.

The site I am starting to build in this article is a sporting website for social teams. We are only going to see the very simple aspects of the Person management, but I will add more features in future articles as I switch to MVC.

I’ll add the source code link up soon.

What you will get out of this

  1. An understanding of how easy it is to use Code First Entity Framework;
  2. How easy it is to use the integrated SQL Server
  3. How easy CRUD facility can be built with existing Webform controls

You will need:

  1. Visual Studio 2010 Professional or higher (C#)
  2. Microsoft ADO.NET Entity Framework Feature CTP4  http://www.microsoft.com/downloads/en/details.aspx?FamilyID=4e094902-aeff-4ee2-a12d-5881d4b0dd3e&displaylang=en and
  3. Microsoft SQL Server CE 4.0 CTP http://www.microsoft.com/downloads/en/details.aspx?FamilyID=0d2357ea-324f-46fd-88fc-7364c80e4fdb&displaylang=en

I will hopefully host this solution soon and will post its link when it is up. So here we go.

Building the Application:

  • Start Visual Studio and create a new ASP.NET Web Application project called TeamWebSite
  • After the following line:

<asp:Content ID=”BodyContent” runat=”server” ContentPlaceHolderID=”MainContent”>

  • Add the following:
    <h2>
       Demo Team Site
    </h2>
    <p>
        <asp:ObjectDataSource ID="dsPlayer" runat="server" SelectMethod="GetAllPlayers"
        TypeName="TeamWebSite.Data.Player" DeleteMethod="DeletePlayer"
            UpdateMethod="EditPlayer">
            <DeleteParameters>
                <asp:Parameter Name="PlayerID" Type="Int32" />
            </DeleteParameters>
            <UpdateParameters>
                <asp:Parameter Name="PlayerID" Type="Int32" />
                <asp:Parameter Name="PlayerName" Type="String" />
                <asp:Parameter Name="PlayerDescription" Type="String" />
                <asp:Parameter Name="PlayerAge" Type="Int32" />
            </UpdateParameters>
        </asp:ObjectDataSource>
        <asp:GridView ID="gvPlayer" runat="server" AllowPaging="True"
        DataSourceID="dsPlayer" AutoGenerateColumns="False" DataKeyNames="PlayerID">
            <Columns>
                <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
                <asp:BoundField DataField="PlayerID" HeaderText="PlayerID"
                    SortExpression="PlayerID" />
                <asp:BoundField DataField="PlayerName" HeaderText="PlayerName"
                    SortExpression="PlayerName" />
                <asp:BoundField DataField="PlayerDescription" HeaderText="PlayerDescription"
                    SortExpression="PlayerDescription" />
                <asp:BoundField DataField="PlayerAge" HeaderText="PlayerAge"
                    SortExpression="PlayerAge" />
            </Columns>
        </asp:GridView>
        <asp:Button ID="AddPerson" runat="server" Text="Add"
        onclick="AddPerson_Click" />
    </p>

Ok so this is pretty simple, just two main controls. First of all the datasource. This is the object datasource for the page and all we specify is the type (or class) it is using for this datasource and then specifies the Type, the methods (edit and delete) and the parameters. The other control is the good old Gridview and as you can see we just ensure it specifies  AutoPaging, AutogenerateColumns and the datakey (we need this so that the delete command can use the PlayerID to delete).

  • Replace the following code behind of Default.aspx.cs with:
using System;

namespace TeamWebSite
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void AddPerson_Click(object sender, EventArgs e)
        {
            Response.Redirect("AddPerson.aspx");
        }
    }
}

Pretty simple. Here we are just adding a click event handler to move to a new page  and now let’s add the only other page we need.

  • Add to the project a new item: web form using master page  called AddPerson.aspx and select the master page: Site.master
  • Add the following between the <content> </content> tags:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AddPerson.aspx.cs" Inherits="TeamWebSite.AddPerson" MasterPageFile="~/Site.Master" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <div>
        <asp:ObjectDataSource ID="dsPerson" runat="server" InsertMethod="CreatePlayer"
            SelectMethod="GetAllPlayers" TypeName="TeamWebSite.Data.Player">
        </asp:ObjectDataSource>
        <asp:FormView ID="fvPerson" runat="server" DataSourceID="dsPerson"
            DefaultMode="Insert" oniteminserted="fvPerson_ItemInserted" >
            <InsertItemTemplate>
                Name:
                <br />
                <asp:TextBox ID="PlayerNameTextBox" runat="server"
                    Text='<%# Bind("PlayerName") %>' />
                <asp:RequiredFieldValidator ID="rfPlayerName" runat="server" ControlToValidate="PlayerNameTextBox" ErrorMessage="Enter Name"></asp:RequiredFieldValidator>
                <br />
                Description:
                <br />
                <asp:TextBox ID="PlayerDescriptionTextBox" runat="server"
                    Text='<%# Bind("PlayerDescription") %>' />
                <br />
                Age:
                <br />
                <asp:TextBox ID="PlayerAgeTextBox" runat="server"
                    Text='<%# Bind("PlayerAge") %>' />
                <br />
                <asp:RequiredFieldValidator ID="rfPlayerAge" runat="server" ErrorMessage="Enter Age" ControlToValidate="PlayerAgeTextBox" ></asp:RequiredFieldValidator>
                <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True"
                    CommandName="Insert" Text="Insert" />
                &nbsp;<asp:LinkButton ID="InsertCancelButton" runat="server"
                    CausesValidation="False" CommandName="Cancel" Text="Cancel" />
            </InsertItemTemplate>
        </asp:FormView>
        <asp:ValidationSummary ID="vsPerson" runat="server" />
    </div>
</asp:Content>

You should see that again, there are two main controls on the page:

1.Object Datasource – again we are just pointing to the type and specifying the insert command.

2.FormView – Here we specify the datasource above and then create the markup with in the InsertItem template that allows us to create the container for all the controls we will use on the AddPerson.aspx page (see figure 2)

  • Now just add the following as code behind
using System.Web.UI.WebControls;

namespace TeamWebSite
{
    public partial class AddPerson : System.Web.UI.Page
    {

        protected void fvPerson_ItemInserted(object sender, FormViewInsertedEventArgs e)
        {
            Response.Redirect("Default.aspx");
        }
    }
}

So nothing major here just a redirect back to the default when we have inserted the row.

Now we can add the class holding our crud goodliness:

  • Add a class to the Project and call it TeamSite.cs

 

  • Add the following references to the project: C:Program Files (x86)Microsoft ADO.NET Entity Framework Feature CTP4BinariesMicrosoft.Data.Entity.CTP.dll and C:Program FilesMicrosoft SQL Server Compact Editionv4.0DesktopSystem.Data.SqlServerCe.dll
  • Replace the code with:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Data.Entity.Infrastructure;

namespace TeamWebSite.Data
{
    public class TeamWebSite : DbContext
    {
        //EF Container 
        public DbSet<Player> players
        {
            get;
            set;
        }
    }

    //Standard old POCO class
    public class Player
    {
        public Player() { }

        public int PlayerID { getset; }

        public string PlayerName { getset; }
        public string PlayerDescription { getset; }
        public int PlayerAge { getset; }

        //Standard Select
        public List<Player> GetAllPlayers()
        {
            TeamWebSite db = new TeamWebSite();
            return db.players.ToList<Player>();
        }

        //Insert
        public void CreatePlayer(string PlayerName, string PlayerDescription, int PlayerAge)
        {
            TeamWebSite db = new TeamWebSite();
            db.players.Add(new Player { PlayerName = PlayerName, PlayerDescription = PlayerDescription, PlayerAge = PlayerAge });
            db.SaveChanges();
        }

        //Edit
        public void EditPlayer(int PlayerID,string PlayerName, string PlayerDescription, int PlayerAge)
        {
            TeamWebSite db = new TeamWebSite();
            Player p = db.players.SingleOrDefault(player => player.PlayerID == PlayerID);
            if (p != null)
            {
                p.PlayerName = PlayerName;
                p.PlayerAge = PlayerAge;
                p.PlayerID = PlayerID;
                db.SaveChanges();
            }
            else
            {
                throw new ApplicationException("Can not find the player");
            }
        }

        //Delete
        public void DeletePlayer(int PlayerID)
        {
            TeamWebSite db = new TeamWebSite();
            Player p = db.players.SingleOrDefault(player => player.PlayerID == PlayerID);
            if (p != null)
            {
                db.players.Remove(p);
                db.SaveChanges();
            }
            else
            {
                throw new ApplicationException("Can not find the player");
            }
        }
    }

    //Called by Global.asax to reload the database in a situation when the model changes from 
    //the physical DB
    public class WebSiteInitializer :RecreateDatabaseIfModelChanges<TeamWebSite>
    {
        protected override void Seed(TeamWebSite context)
        {
            var Players = new List<Player>
            {
                new Player { PlayerID= 1, PlayerName="John", PlayerAge=31, PlayerDescription="older player" },
                new Player { PlayerID=2, PlayerName="sTEVE" , PlayerAge=23, PlayerDescription="asdasd" }
            };
            Players.ForEach(d => context.players.Add(d));
        }
    }
}

OK so it might look like a lot but break it down and it’s not very complicated at all. There are 3 classes (Yes we should have them in separate files but to keep things all in one page for brevity I am being very very bad). The three classes:

TeamWebSite – inherits from DBContext (part of the EF framework), publishes our main property: public DbSet<Player> players.

Person – standard basic old POCO class. Nothing really special.

WebSiteInitializer – class that we hook to from global.asax to make sure we keep the EF datamodel synced with the database.

  • Add the connection string to web.config  by adding the following within the <connectionstrings> tags:
 <add name="TeamWebSite" connectionString="Data Source=C:tempTeamWebSite.sdf" providerName="System.Data.SqlServerCe.4.0"/>

Make sure the directory exists for the datasource!!!

One last thing – one of the realities of code first is that you need to be able to maintain the link between the datamodel and the database at all times. When this synchronisation is broken you’ll get errors. Our workaround for this is to go back to a base set of data – for prototypying scenarios this should be fine.

  • Edit the global.asax and add the following using:

 

using System.Data.Entity.Infrastructure;

 

  • replace Application_Start with:
 void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            Database.SetInitializer<TeamWebSite.Data.TeamWebSite>(new TeamWebSite.Data.WebSiteInitializer());
        }

Having a look at the application :

 

  • Now start up the application (F5) and you should see:


  • Click Add you’ll see:

  • Saving a record and you’ll see:

Figure 3. The list of players after we have added a player

In Conclusion:

So this was pretty simple but I think you get the idea that you have quickly built, a simple, self contained CRUD web application, using a range of new tools.

I’ll continue in this series with an improved version of the tool built in MVC 3.0

Stay tuned

Dom

References:

http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx

http://weblogs.asp.net/scottgu/archive/2010/06/30/new-embedded-database-support-with-asp-net.aspx

Being a better developer PART 3 (How to become a better developer)

The Big Question (How to become a better developer?)

So, I asked my colleagues (all devs/architects of some form) what advice they would have for the graduate/newbie who wanted to become a solid developer. Again, I have collected the responses and in the (pretty much ) raw form are the glorious responses:

The Responses:

ask questions (don’t assume)

take responsibility every job u do is a important as the last one.

report back  to your mentor / team leader on a daily basis.

Avoid the temptation to distrust everything and roll your own. Have a desire to grok popular software components.

Work like your arse is on fire!

I would say one key to becoming a solid developer is to ensure that you as a developer learn to communicate effectively with both business and technical team members to ensure you are building what has been specified or is required. You can have all the technical skills in the world but if you’re not building what’s required, there is a lot of wastedtime and effort.

“If I had to give only one advice on how to become is by practice as practice makes a man perfect and how about if the practiceis on real live cutting edge technology, i.e. open source project. First download it from codeplex or github and have open earsfor the two open source website. It is not that we are microsoft shop do just restrict yourself to codeplex. Second once you start getting comfortable by reading code, start contributing to the open source.Download tfs plugin and svn for codeplex and github. Pick up an interesting topic like a cross between design patterns and tool that does auto integration or code generation or plugs itself into framework and does some magic.” Prashant Brall (2010)

Get a Mentor.Get code reviews from the Mentor.

Maybe really great developers are born. The 7 phases of advice that follows is for the rests of us: 1.Understand your weaknesses. 2. ?* 3.Work at your weaknesses.4. Practice. 5.Email/Chat/Talk to other developers to get feedback. 6. Watch the Karate Kid 1 (learn never to give up) and 7. If you don’t drink coffee, start.

*like the underpants gnomes I don’t believe in phase 2

In Conclusion

So thats it. This little series is now over. Big thanks to my gang of coders/architects/gurus (those happy to be named):

Cheers

Dom

Being a better developer Part2 (What makes a solid developer)

Introduction

In the first part of this series I indicated I would be asking some of my developer colleagues to give me a few points on what it takes to be a solid developer (Not SOLID as in the OO principles by Robert C Martin). Originally, I thought I would summarise the responses into a short essay, but the quality of the responses was too good, so instead I have just grouped them into broad categories. Also, I think its important to pick up some of the trends from the responses so if you see an item that has been repeated you’ll probably get the idea that it’s a significant issues for a number of developers. Some minor editing and formatting has taken place.

Learning

Humility & Growth – that might sound like I’m being a bit hypocritical 🙂 but at the end of the day you need to learn from people who know more about any number of subjects than you. It might be new tech like mvc, generics or just business process.  It might be in-house tech that the junior guy you work with knows back to front.  But most of all be prepared to go back to square one and adopt new techniques like you did when you were starting out.

Objectivity – the ability to stand back and look at a solution from somebody else’s viewpoint – maybe that the business stakeholder or another team.  A good developer will and should eventually be a good analyst / designer so think outside your problem and assess downstream impacts and risk.  A problem thought through and solved is much cheaper than a problem built, tested and solved.

Stay Sharp : Invest time in and out of work hours in monitoring the industry trends and cutting-edge releases (both source e.g. MS/java/jquery etc) and peers (e.g. New Sites, apps and other public release).  You might not get to use it in the short term but when the time comes to offer up new tech you’ll be ready

Ability and willingness to learn.

Be a good listener.

Develop and Maintain Knowledge.

Work out who are good programmers, watch what good programmers do, Learn their patterns and practice their technique

Being Practical

Don’t be precious : Sometimes you have to sacrifice your principles to get something out the door.  Project influences will quite often not align with your idea of correct process. The good developers know which corners are being cut so they can be back filled when the time is right.

Ability to understand the needs of the business, not just what they ask for but what they NEED.

Deliver a solution that makes their lives easier. Not what is technically easiest making it hard to use while still meeting the business requirements.

Be pragmatic – not wedded to any single way of doing things. Willing to explore alternatives.

Principles

Maintain Principles.

“It’s not the tools or framework but it’s the knowledge and principle which will take you far in your career” . So dotnet may stay or may go ..maybe Adobe will be a programming platform ..may be microsoft will fail and become extinct. But if you have the right knowledge and principles then you can pick ruby on rails and will start programming in a 2 weeks. Like my great, great mentor used to say …any technology is just 2 weeks away if you put your heart and mind into it, and it just starts with a simple “Hello world”.

Be Agile : No not the programming nor the methodology but the Agile way of thinking.

Technique

Ability to write simple clean code that can be easily maintained.

Have a good eye for defensive programming – i.e. expect things to go wrong, test your input parameters etc, but be realistic about it.

Ability to make changes to an existing system without rewriting it.

Understand implications of code changes (and know when to hold back due to those implications).

Understand patterns and be able to apply them. Good programmers use them without even thinking about them.

Don’t rush.

Code consistently.

Have a basic appreciation for ‘usability’ – spends more than the 3 seconds it takes to drag buttons on a form thinking about how screens / pages hang together  and how the end user is going to interact with their software.

Know your given framework. If you are an ASP.NET developer you should know the fundamentals of .NET, Javascript, IIS, Browsers, Data Access, Stored Procs in SQL Server and ASP.NET.

A simple solution is a good solution. Keep it simple. Test it.

When given a task understand the big picture.  Research and then come back with a few key questions.

Problem Solving

Be driven by finding solutions – strive to be innovative – don’t ask the business to change their requirements because you are too lazy / not good enough  to make it work.

Take pride in your work – like a top chef who wouldn’t send out a meal they aren’t happy with, a solid developer won’t flick something to the test team without being happy that they have thoroughly tested it themselves first.

Ability to problem solve and research.

Self Awareness

Recognition that you are not the smartest guy in the room (willingness to re-use other people’s solutions).

Know your smell (and When in Rome do as Romans do).  When you are working in a team/or organisation there are times when the managers/PM’s may not appreciate your work, style, work ethic etc. You should try to detect this. When you detect this, be prepared to change (either your job or the way you work).

Team

Be a team player.

Take the role of the follower / leader (based on your role in the team).

Understand your role in the team. If you are the grunt developer on a project don’t try to take over the lead role. If something eventuates for you in a different role for another project that’s great.

Ask the right questions.

Be proactive.

Career

Challenge yourself. Get out there and work in different industries, companies and projects.

Having significant experience in multiple environments (organisations) is very significant.

Conclusion

I am planning a third and final part to this series where I ask my mates for tips on how the junior developer/graduate/newbie should enhance skills to become the solid developer.

Dom

Being a better developer Part1

So although this site is primarily about learning .Net and iPhone technologies I think its important to focus on how to improve yourself as a general developer. There are thousands of sites that focus on this and I won’t try to rehash any of that material. Instead, I will be talking to my developer mates, and summarising their views and thoughts on what it takes to be a SOLID developer and also what to do to achieve that level. Those involved have between 5 and 20 years experience in development. They are all excellent developers and all have a great understanding of development.

If you haven’t encountered this subject before check out some of the following:

www.hanselminutes.com (shows 72 and 171)

www.dotnetrocks.com (show 101)

Next in this series will be  what makes a “SOLID” developer, stay tuned.

Dom

Another plug for this developers life

I think I mentioned this site before but have to say after a few more shows I am really really impressed. It’s quite off beat look at the development industry and appart from the interesting subject matter the background music is really quite cool (come on when even a little kraftwerk is heard in the background you have to be impressed) – well I was anyway.

http://thisdeveloperslife.com/

Dom