Wednesday, January 30, 2008

FormView Oddities and Using EditItemTemplate to Insert

Every now and then I come across those weird, annoying issues with ASP.NET which very few people seem to have had, and no one seems to have an answer.  It's especially frustrating because I can spend hours (I've spent 4 hours today tracking this one down) trying to figure out what's going on.  Maybe one of the gifts of being a programmer comes the ability to spend 4 hours researching, testing, and focusing on one problem.

In any case, we use FormViews pretty regularly in our ASP.NET applications.  For those who don't know, a FormView is very similar to the DataGrid and GridView controls.  You can place your form fields in either an ItemTemplate, EditItemTemplate or IntertItemTemplate.  This lets you bind the FormView to a DataSource and simple use Bind() to populate the values and update them back into the database.  We've been able to create pages with no, or very, very little code in the code behind using this method, and after a bit of a learning curve I definitely think this is the way to go for building sites.

Our only complaint is that you essentially duplicate form fields for each template.  For example, you may want to make the user name field read-only in the EditItemTemplate, but editable in the InsertItemTmplate. 

We (well, my wife anyway. . . Why are women always smarter than men?) came up with a solution where you can use the EditItemTemplate for both updates and inserts.  Essentially the SelectCommand will always return a row, even if the primary key value passed in is null/0.

So, we'll have a FormView for adding and editing builders which looks like this:

FormView

With the aspx code having:

   1:      <asp:FormView ID="fvContactInfo" runat="server" DataSourceID="odsContact" DataKeyNames="BusinessID,UserName"


   2:          DefaultMode="Edit" Width="100%">


   3:          <EditItemTemplate>


   4:              <%-- Business Name --%>


   5:              <div class="inputRow">


   6:                  <asp:Label ID="lblBusinessName" runat="server" Text="Business Name" CssClass="inputLabel"


   7:                      AssociatedControlID="txbBusinessName" />


   8:              </div>


   9:              <div class="inputRow">


  10:                  <asp:TextBox ID="txbBusinessName" runat="server" MaxLength="150" Text='<%#Bind("BusinessName") %>'


  11:                      CssClass="inputBox oneColumn" />


  12:                  <asp:RequiredFieldValidator ID="rqvBusinessName" ValidationGroup="CreateUserWizard1"


  13:                      runat="server" ControlToValidate="txbBusinessName" ErrorMessage="Business Name is required."


  14:                      Text="*" ToolTip="Business Name is required." />


  15:              </div>


  16:              <%-- Buttons --%>


  17:              <div class="inputRow" id="rowButtons" runat="server">


  18:                  <asp:Button ID="btnSave" runat="server" Text="Save" CommandName="Update" />


  19:                  <asp:Button ID="btnBack" runat="server" Visible="false" Text="Go back" />


  20:              </div>


  21:          </EditItemTemplate>


  22:      </asp:FormView>


  23:   


  24:  <%-- Data Source --%>


  25:  <asp:ObjectDataSource ID="odsContact" runat="server" SelectMethod="GetData" TypeName="BCDatasetTableAdapters.BusinessTableAdapter"


  26:      UpdateMethod="Update">


  27:      <SelectParameters>


  28:          <asp:Parameter Name="UserName" Type="String" />


  29:      </SelectParameters>


  30:      <UpdateParameters>


  31:          <asp:Parameter Name="BusinessName" Type="String" />


  32:          <asp:Parameter Name="UserName" Type="String" />


  33:          <asp:Parameter Name="BusinessID" Type="Int32" />


  34:      </UpdateParameters>


  35:  </asp:ObjectDataSource>




And a simple SQL procedure:




   1:  CREATE PROCEDURE [dbo].[sp_bc_BusinessSelect]


   2:  (


   3:      @UserName nvarchar(256)


   4:  )


   5:  AS


   6:      SET NOCOUNT ON;


   7:  BEGIN


   8:      IF @UserName is null 


   9:          BEGIN    


  10:              SELECT 


  11:                  TOP 1


  12:                  -1 BusinessID, 


  13:                  null BusinessName, 


  14:                  '' UserName


  15:              FROM


  16:                  bc_Business


  17:          END


  18:      ELSE


  19:          BEGIN


  20:              SELECT     


  21:                  TOP 1 


  22:                  IsNull(bc_Business.BusinessID, -1) BusinessID, 


  23:                  bc_Business.BusinessName


  24:                  bc_Business.UserName


  25:              FROM         


  26:                  bc_Business 


  27:              WHERE 


  28:                  UserName = @UserName


  29:              ORDER BY 


  30:                  BusinessName


  31:          END


  32:  END




While this is pretty straightforward, there is one problem which came up today.  When there are no builders at all in the builder table, the stored procedure will not return any rows (including the blank row your FormView expects).



That's really due to the fact that in lines 15 and 16 I specify a FROM table, though it's always possible that table is empty.  A better solution is to rewrite the query to look like this:




IF @UserName is null 


        BEGIN    


            SELECT 


                TOP 1


                -1 BusinessID, 


                null BusinessName, 


                '' UserName


        END


    ELSE



What's actually interesting is how the FormView handles the child controls in the Edit template when no data is returned.  When you attempt to run the following code:




   1:  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load


   2:   


   3:      odsContact.SelectParameters("UserName").DefaultValue = UserName


   4:      CType(fvContactInfo.FindControl("lblBusinessName"), Label).Text = "Enter new business name here:"


   5:   


   6:  End Sub




You would expect line 4 to return either a reference to the label or, at worst, Nothing for the control, even if you place it in the FormViews DataBound or Unload event.



You actually receive an error that the FormView itself fvContactInfo threw a NullReferenceException.  Whenever you are binding a FormView to have the Edit mode handle both inserts and updates.



Accounting for the return of a blank row though, this is a great method to reduce the need to duplicate form fields in all templates.  The same template above which used Edit, Item and Insert templates would look similar to the following:




   1:  <asp:FormView ID="fvContactInfo" runat="server" DataSourceID="odsContact" DataKeyNames="BusinessID"


   2:      DefaultMode="Edit" Width="100%">


   3:      <EditItemTemplate>


   4:          Business Name:


   5:          <asp:TextBox ID="BusinessNameTextBox" runat="server" Text='<%# Bind("BusinessName") %>'>


   6:          </asp:TextBox><br />


   7:          User Name:


   8:          <asp:Label ID="UserNameLabel" runat="server" Text='<%# Bind("UserName") %>'>


   9:          </asp:Label><br />


  10:          <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update"


  11:              Text="Update">


  12:          </asp:LinkButton>


  13:          <asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel"


  14:              Text="Cancel">


  15:          </asp:LinkButton>


  16:      </EditItemTemplate>


  17:      <InsertItemTemplate>


  18:          Business Name:


  19:          <asp:TextBox ID="BusinessNameTextBox" runat="server" Text='<%# Bind("BusinessName") %>'>


  20:          </asp:TextBox><br />


  21:          User Name:


  22:          <asp:TextBox ID="UserNameTextBox" runat="server" Text='<%# Bind("User Name") %>'>


  23:          </asp:TextBox><br />


  24:          <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert"


  25:              Text="Insert">


  26:          </asp:LinkButton>


  27:          <asp:LinkButton ID="InsertCancelButton" runat="server" CausesValidation="False" CommandName="Cancel"


  28:              Text="Cancel">


  29:          </asp:LinkButton>


  30:      </InsertItemTemplate>


  31:      <ItemTemplate>


  32:          BusinessName:


  33:          <asp:Label ID="BusinessNameLabel" runat="server" Text='<%# Bind("BusinessName") %>'>


  34:          </asp:Label><br />


  35:          UserName:


  36:          <asp:Label ID="UserNameLabel" runat="server" Text='<%# Bind("UserName") %>'></asp:Label><br />


  37:          <asp:LinkButton ID="EditButton" runat="server" CausesValidation="False" CommandName="Edit"


  38:              Text="Edit">


  39:          </asp:LinkButton>


  40:      </ItemTemplate>


  41:  </asp:FormView>




Which quickly becomes a nightmare to update.  Have fun!



Peace,

+Tom

Thursday, January 24, 2008

Opinions

I'm working on a new project doing something I've rarely done before and feeling a bit out of my element.  When I'm in meetings I find myself trying to sound more intelligent about the material than I am. 

I recognize that I'm trying to impress the manager and even the person I'm leading to convince them that I really can get the job done, when really I wonder if I'm trying to convince myself.  More than anything though I find myself incredibly focused on trying to get their approval and impress them with the work I've done.

Looking at this a bit more objectively I'm finding that the importance of someone's opinion of me seems to be inversely proportional to the closeness of the relationship I have with the person.

RelationshipOpinion

For example, when the project manager calls to ask me to do something I tend to take a break from what I was doing and complete the task right away.  When I get home at night and Erin asks me to do something it my very well go in one ear and out the other.  At the very least I'll finish what I'm doing before taking care of what she'd like.

Another good example comes from reading books.  Whenever I read a book, especially a non-fiction book, the author becomes an expert in the field and what they are saying is almost irrefutable.  It hasn't been until the last few years that I've begun to break through that idea, though I still fall victim to it a lot.  On the flip side, if a friend of mine tells me some piece of information or useful fact I don't believe it until I've verified it in some other way.  Until it's been backed up, it's not true.

As we get to know a person better we tend to understand what they are thinking and what they hold important.  As an acquaintance becomes a friend we figure out that they don't really care whether our hair is a mess or not.

When I first met my wife I couldn't dress well enough.  I didn't try to be obvious about it, but I sure tried to dress well whenever I know I was going to see her (as the song says, "I'd get dressed up to go watch TV with her").  As time went by I realized that she cared about me regardless of how I looked, and I realized it was ok to not get all dressed up just to go hang out somewhere last minute.  Then we got married and it's become ok for me to wear jeans with holes and pajamas with frayed cuffs.

I wonder what would happen if we flipped those priorities.  What if we relaxed around those people we barely know and may come across as uptight to.  What if we trusted the people we love instead of needing to verify what they say?

What if I acted on a request from my wife before that of my boss?

What would the world look like if the opinion of an individual increased as our closeness to the individual increased?

Maybe I could get away with wearing holey jeans more often.

Peace,
+Tom

Wednesday, January 16, 2008

Best Daughter Ever

Rachel's hair getting cut Last night Rachel, our 3 1/2 year old, did something I couldn't be more proud of.  She decided to give up her long flowing hair and donate it to those in need.

Rachel had begun thinking about donating her hair back in November, but after talking it through with family decided she wasn't ready to cut all of her hair off.  We still talked about donating it on and off, but had decided to let it go until Rachel brought it up again.

Rachel with hair pins after getting her hair cut. Last week we talked about how mommy and daddy were going to get their hair cut the next day, and Rachel asked if she could go see Jodie and get her hair cut short and donate the hair.  She was actually in tears when we told her Jodie didn't have any space left for that day, and we had to call that minute to see when we could schedule an appointment.

Over the weekend we continued to make sure Rachel really wanted to cut her hair and donate it.  It's one of those things that you can't do part way.  Rachel gets a pony tail in her hair and in one cut it's gone (well, two cuts, we did two pony tails).  Erin was pretty sure Rachel would realize what was happening too late and be in tears. 

Rachel holding her two pony tails after getting them cut. I think there was a little bit of projection there.  Once the hair was cut Erin looked like she was close to tears.  Rachel, on the other hand, had a great time.  She was immensely happy and stayed incredibly still while Jodie cut her hair.

The next day Rachel ran into school showing everyone her pony tails and talk about how she is going to donate them.

She didn't shed a tear, even the next day.  She's even pointed out multiple times the biggest benefit of getting her hair cut, that it won't hurt to get it brushed any more.  Personally, I loved that it took all of 1 minute to brush her hair, and had no knots at all.

This was a decision both Erin and I took some time to come to.  We'd been getting irritated at how much complaining we received brushing her hair.  That's balanced with the fact that Erin enjoyed putting it in a bun or french braid.  We also wondered if we were assuming too much responsibility and understanding in Rachel, a three year old.

That got me wondering what other sort of decisions we try to make on our own, assuming others aren't ready to make them.  What decisions do we put off ourselves because we think the consequences will be too big?  Sometimes we need to let our own assumptions go and simply take the leap.

Rachel and Jodie after the haircut

In the end, while I miss her long hair a tiny bit, I love that it was Rachel's decision to cut and donate it, and that she is happy to have short hair.  She looks great!

Rachel after haircut with a comb in her hair

Peace,
+Tom

Friday, January 11, 2008

Ponderables - Cylons, Base Ships and Gravity

Why is it that the Cylons have gravity on their base stars?  Especially on the old series where they are all complete robots.  Wouldn't it be cheaper to let them just float where they need to go, or use magnets in their feet?

No need to build ladders or anything.

In that same vein, why is there oxygen?  Though maybe they just pump that in whenever they have humans on board.

Something to think about all day, huh?

Peace,
+Tom

Writers Strike

I just came across this video and it's pretty freaking hilarious.  I can't help but laugh out loud.  You should definitely check it out.  The creativity of some people is just amazing.

Oh yeah, and I miss my TV!  Thank goodness there's Netflix, TiVo and my Wii games to catch up on.

Some of the other stuff from thegeniuses is pretty awesome too.  I love the iPhone Shuffle video, my friend Mason needs one of them.

Peace,
+Tom

Wednesday, January 9, 2008

Strengths

StrengthsFinder This evening we're kicking off a month of identifying and putting our strengths to work for bible study.  Since I'm asking all the teens to take a strengths test, I figured it was only fair to do one for myself.  If you haven't checked out StrengthsFinder, it's pretty good.

While I prefer to book written by Marcus Buckingham, they have updated the test and unfortunately you need to buy a different book for the updated test.  In the end it means you almost need both books, since Marcus' book does a much better job explaining what strengths are and why it's important to focus more on them and less on our weaknesses.

That being said, I'd really recommend you get the StrengthsFinder 2.0 book and Marcus Buckingham's recent book Go, Put Your Strengths to Work, since it describes why strengths are important in there.  If anyone else is up for taking the test just let me know, I'll buy the book for you.

In any case, here are my top 5 strengths, in no particular order.  What do you think, are these my strengths?  Is something missing?

Positivity
You are generous with praise, quick to smile, and always on the lookout for the positive in the situation. Some call you lighthearted. Others just wish that their glass were as full as yours seems to be. But either way, people want to be around you. Their world looks better around you because your enthusiasm is contagious. Lacking your energy and optimism, some find their world drab with repetition or, worse, heavy with pressure. You seem to find a way to lighten their spirit. You inject drama into every project. You celebrate every achievement. You find ways to make everything more exciting and more vital. Some cynics may reject your energy, but you are rarely dragged down. Your Positivity won’t allow it. Somehow you can’t quite escape your conviction that it is good to be alive, that work can be fun, and that no matter what the setbacks, one must never lose one’s sense of humor.

Woo
Woo stands for winning others over. You enjoy the challenge of meeting new people and getting them to like you. Strangers are rarely intimidating to you. On the contrary, strangers can be energizing. You are drawn to them. You want to learn their names, ask them questions, and find some area of common interest so that you can strike up a conversation and build rapport. Some people shy away from starting up conversations because they worry about running out of things to say. You don’t. Not only are you rarely at a loss for words; you actually enjoy initiating with strangers because you derive satisfaction from breaking the ice and making a connection. Once that connection is made, you are quite happy to wrap it up and move on. There are new people to meet, new rooms to work, new crowds to mingle in. In your world there are no strangers, only friends you haven’t met yet—lots of them.

Connectedness
Things happen for a reason. You are sure of it. You are sure of it because in your soul you know that we are all connected. Yes, we are individuals, responsible for our own judgments and in possession of our own free will, but nonetheless we are part of something larger. Some may call it the collective unconscious. Others may label it spirit or life force. But whatever your word of choice, you gain confidence from knowing that we are not isolated from one another or from the earth and the life on it. This feeling of Connectedness implies certain responsibilities. If we are all part of a larger picture, then we must not harm others because we will be harming ourselves. We must not exploit because we will be exploiting ourselves. Your awareness of these responsibilities creates your value system. You are considerate, caring, and accepting. Certain of the unity of humankind, you are a bridge builder for people of different cultures. Sensitive to the invisible hand, you can give others comfort that there is a purpose beyond our humdrum lives. The exact articles of your faith will depend on your upbringing and your culture, but your faith is strong. It sustains you and your close friends in the face of life’s mysteries.

Strategic
The Strategic theme enables you to sort through the clutter and find the best route. It is not a skill that can be taught. It is a distinct way of thinking, a special perspective on the world at large. This perspective allows you to see patterns where others simply see complexity. Mindful of these patterns, you play out alternative scenarios, always asking, “What if this happened? Okay, well what if this happened?” This recurring question helps you see around the next corner. There you can evaluate accurately the potential obstacles. Guided by where you see each path leading, you start to make selections. You discard the paths that lead nowhere. You discard the paths that lead straight into resistance. You discard the paths that lead into a fog of confusion. You cull and make selections until you arrive at the chosen path—your strategy. Armed with your strategy, you strike forward. This is your Strategic theme at work: “What if?” Select. Strike.


Empathy
You can sense the emotions of those around you. You can feel what they are feeling as though their feelings are your own. Intuitively, you are able to see the world through their eyes and share their perspective. You do not necessarily agree with each person’s perspective. You do not necessarily feel pity for each person’s predicament—this would be sympathy, not Empathy. You do not necessarily condone the choices each person makes, but you do understand. This instinctive ability to understand is powerful. You hear the unvoiced questions. You anticipate the need. Where others grapple for words, you seem to find the right words and the right tone. You help people find the right phrases to express their feelings—to themselves as well as to others. You help them give voice to their emotional life. For all these reasons other people are drawn to you.

Peace,
+Tom

Tuesday, January 8, 2008

So Long Joe

Coach Joe Gibbs by littlerottenrobinI got a message early this morning and just finished an article from the Washington Post that Joe Gibbs Resigns as Redskins Head Coach.  I'm really going to miss having Gibbs around, watching the plays seemed fun and there's been a lot of stuff this season I hadn't seen before.

That being said, I'm glad he's making the decision to leave on his own.  It's so much worse when the coach is forced to resign or tries to keep the job going after they've lost the heart.

I met Raleigh McKenzie during the Redskins player of the year dinner back in December.  He was sitting beside me at our dinner table and we ended up talking for quite a while.

While others at the table talked to him about football and the good ol' days, he and I talked more about his kids and his career right now.

He's working as a 4th grade teacher and loves his class.  He also coaches the Herndon high school football team, his son's football team and his daughter's basketball team, I think.  It's been a while and some of the details are getting a little fuzzy.

I was struck by the way that, while Raleigh ended his NFL career with a different team (Green Bay Packers), he returned to Washington to retire as a Redskin because of the fans' commitment to the team.  He's also made a life after football which continues to use his strengths.  That made me more excited than anything he said about football.

Just as Raleigh has moved on from football and made a life anyone would be proud of, I'm excited to see Joe Gibbs recognize what is important to him and decide to give up something he lives for something he loves even more.

He'll be in my prayers.

Peace,
+Tom

Saturday, January 5, 2008

Cool Company Names

I love coming up with new ideas.  How cool would it be to see companies with these names?

Sorry, we're out

For any company that delivers or does on-site work like Nails on the Run.

Let it go

For any company that helps to organize life or even a psychologist tag line.

Peace,
+Tom

Until Tomorrow

I've been listening to a bunch of different, and excellent, podiobooks I've found on podiobooks.com.  I definitely recommend checking the site out and seeing what's there.  One of the authors I came across is Lisa Wright and her Wrightales.  In Between the Darkness and the Dawn the following quote comes in:

Armonk: I'll wait until tomorrow.

But tomorrow's at best a maybe.  More often a maybe not.

I'm beginning to recognize how much I plan to do while letting the doing of things slip by.  It's time to recognize that tomorrow is at best a maybe.

Peace,
+Tom