Browsing Category: .NET

Fun with DateTime

Monday, November 17th, 2008

The results of my messing around with .NET DateTime. Hope this is useful for someone else!

using System;
namespace ConsoleApplication1
{
   class Program
   {
      static void Main(string[] args)
      {
      // fun with DateTime
      // right now, including the time
      Console.WriteLine(DateTime.Now);

      // today's date, no time (midnite)
      Console.WriteLine(DateTime.Today);

      // stripping a time off a DateTime (so it's midnite, useful for database queries)
      DateTime startDate = DateTime.Parse("10/31/2008 5:25 pm"); // pretend this came from a database or something
      Console.WriteLine(startDate); // see the time displayed
      startDate = startDate.Date; // this is just the date portion with no time
      Console.WriteLine(startDate); // see, just has the date now

      // difference, in number of days, between two dates, human-logic, that is, the 5th is 2 days after the 3rd, no matter what time it was
      DateTime endDate = DateTime.Parse("11/03/2008 4:25 pm"); // pretend this came from a database or something, too
      int days = (startDate.Date - endDate.Date).Duration().Days; // absolute value, order of start and end dates is not important
      Console.WriteLine(days);
      int days2 = (startDate.Date - endDate.Date).Days; // real value, order of start and end dates IS important
      Console.WriteLine(days2);

      // difference between dates with time portion, such as .25 hours (time and attendance, payroll)
      startDate = DateTime.Parse("11/17/2008 8:00 am");
      endDate = DateTime.Parse("11/17/2008 4:45 pm");
      TimeSpan interval = endDate - startDate; // order matters
      Console.WriteLine(interval);

      // hey, don't we get a lunch break?
      DateTime startLunch = DateTime.Parse("11/17/2008 12:00 pm");
      DateTime endLunch = DateTime.Parse("11/17/2008 12:25 pm");
      TimeSpan lunchInterval = endLunch - startLunch; 
      Console.WriteLine(interval - lunchInterval); // 20 minutes of overtime! (yeah, right)

      Console.Read();
      }
   }
}

ASP.NET: Adding onclick to GridView rows

Friday, October 24th, 2008
asp.net c#

I’ve seen this question posed in a few different forms. One guy wanted to have the user click on a GridView row and have a new window open with an external URL. Another wanted the click to pass a bound ID to the new window. Someone else wanted to have the click fire off a third party script.

You can either wait until the whole thing is loaded, then iterate through the rows, or you can attach a script during the binding. Most GridViews are databound at some point, and it’s quicker to just use that event than to iterate through who knows how many rows after the fact.

Here is an example ASP.NET GridView and SqlDataSource (using Northwind).

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID"
 DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound">
 <Columns>
 <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" InsertVisible="False"
 ReadOnly="True" SortExpression="CategoryID" />
 <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" />
 <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
 </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
 SelectCommand="SELECT [CategoryID], [CategoryName], [Description] FROM [Categories]">
</asp:SqlDataSource>

Here is how you could attach a script that opens an arbitrary URL when the user clicks the row. My example passes the (data bound) category name to Google as a search.


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
 string script = String.Format("window.open('http://www.google.com/search?q={0}')", ((DataRowView)e.Row.DataItem)["CategoryName"]);
 e.Row.Attributes.Add("onclick", script);
 }
}

Here is how you could open a new window and pass the GridView row’s DataKey to it. This example has just the one key, CategoryId.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
 string url = System.Web.VirtualPathUtility.ToAbsolute("~/Default9.aspx") + "?CategoryId=" +
 Server.UrlEncode(Convert.ToString(GridView1.DataKeys[e.Row.DataItemIndex].Value));
 string script = "window.open('" + url + "')";
 e.Row.Attributes.Add("onclick", script);
 }
}

C#.NET: Difference between | and || (bitwise vs conditional OR)

Wednesday, October 15th, 2008

We have a new coder at work who is in love with the Boolean inclusive OR operator (pipe symbol | or as I have called it until now, bitwise OR), and he uses it for conditional expressions. I knew there had to be a difference between | and the conditional OR operator ||, but I wasn’t sure what it was. The code seemed to work fine, but it was nagging me.

So I finally got around to looking it up.

A behavior that I take for granted in C# is the result of using the conditional operators (two pipe symbols ||  or 2 ampersand symbols && ) with boolean expressions. For an OR, the first expression that evaluates to true stops the evaluations. For AND, the first one that evaluates to false stops them.

This makes a big difference when doing checking for nulls or other conditions that would cause runtime exceptions without having to nest the checks.

This code runs fine, even with no dataset.


DataSet ds = null;
// code here to load dataset, etc

if (ds != null && 
    ds.Tables != null &&
    ds.Tables[0] != null &&
    ds.Tables.Count > 0)
{
   //do something with the table
}

This code throws a runtime exception, because ds is null, so you get a NullReferenceException when it proceeds to go on and hit ds.Tables.


DataSet ds = null;
// code here to load dataset, etc
if (ds != null & 
   ds.Tables != null &
   ds.Tables[0] != null &
   ds.Tables.Count > 0)
{
  //do something with the table
}

As an aside, I believe the default for VB.NET OR and AND is to evaluate all sides all the time as Boolean Inclusive, since I’ve been flummoxed by null reference exceptions I didn’t expect when trying similar coding. One of these days I’ll look that up, too.  =)

Got more tips or goodies for us? Please share them in the comments!

ASP.NET to officially support jQuery

Wednesday, October 1st, 2008

Check it out - a blog post from Scott indicates that .NET, and Visual Studio, will support jQuery!

Scott says

“I’m excited today to announce that Microsoft will be shipping jQuery with Visual Studio going forward. We will distribute the jQuery JavaScript library as-is, and will not be forking or changing the source from the main jQuery branch. The files will continue to use and ship under the existing jQuery MIT license.”

This is exciting news for developers, as jQuery will help fill the noticable gap in ASP.NET to be truly client rich. I know things I’d like to do, such as supporting dragging and dropping of elements in a grid (a la Netflix queue), are not possible with the out-of-the-box version of Studio / ASP.NET.

I’ve played with ASP.NET AJAX, but found the performance to suck, and the component set to be ugly and difficult to style. At work, we use a popular third party component set called Infragistics, and their components do perform well, but they are not free. I’m excited to hear about jQuery support because I think it will really open up the playing field for those who can’t afford third-party component sets.

Do you use jQuery? What do you think of it? Does it perform well? Do you think it will take off for the .NET world?

ASP.NET: What To Do If You’re A n00b

Monday, September 29th, 2008

If you’re reading this article, either you’ve already started coding ASP.NET pages or you’re thinking about learning it. There’s a lot to know in the .NET world. Few of us are truly experts, even if we hold certifications. I’m always learning something new, and I’ve been developing with .NET for 3 years now.

There is so much to know and there are so many sources of knowledge, that it can seem like a daunting task to jump in and start doing useful things. Your mind might spin, and you don’t know where to start. No worries, there is a method to the madness. Grab an IDE, a practice database, and start reading…

Getting an IDE

Get Visual Studio (costs money, sometimes provided by your company) or Visual Web Developer Express (free download here from Microsoft). I don’t know any serious ASP.NET developer who isn’t using one of those tools, so anyone offering you help will assume you have one. I’m sorry, but Dreamweaver sucks for .NET development. If you were using it for classic ASP, you’ll want to ditch it for ASP.NET.

When you get Studio or Web Developer Express, you’ll be prompted to download and install the .NET Framework if you haven’t yet done so.

Get a database to query

You can download SQL Server Express edition from Microsoft for free. Grab the AdventureWorks database as well as the older Northwind database. While Northwind was written for SQL Server 2000, it mounts just fine for 2005, and its data structure is far simpler and easier for a new person to work with.

Actually, I’m not new and I still prefer Northwind for its simplicity, as I usually use it for testing and learning .NET things, not database things. If you want to be a DBA, use AdventureWorks. If you want to learn to code .NET, use Northwind.

Learning the .NET platform

Now that you have the basic developer tools, you’re ready to dive in and learn to code.

  1. Read the basic tutorials on the ASP.NET QuickStart guide. Read it all at a high level first and let it sink in. After reading and digesting, go back through them again and actually follow with Visual Studio or Visual Web Developer Express to make them work.
  2. Check out the beginner tutorials on w3schools.com
  3. Get familiar with the MSDN documentation. You should know how to check out members, methods, properties, and events for the objects you use. For example, if you need to know how to get a record count when you’re using SqlDataReader, you pop over to the documentation and look up the class. If you look under Members, you will see a RecordsAffected member; click on that link and scroll down to Remarks, you will see details on how it works, and a caveat that it only works after all rows are read and the reader has been closed.
    I believe that learning to read and use the MSDN documentation is the single most important skill you will need in order to develop with .NET.
  4. Visit the walkthroughs on MSDN. There are thousands of walkthroughs, so you’re sure to find some that apply to what you need to do. Nearly all ASP.NET sites deal with CRUD operations with a database, so be sure to check out the Basic Data Access in Web Pages walkthrough.
    If you find yourself thinking that a particular task you’re trying to accomplish is far too complicated you’re probably doing it wrong. Check these walkthroughs to make sure you’re Keeping It Simple.
  5. Start lurking on forums.asp.net. The forums are a GREAT place to learn. I don’t know about you, but I have a hell of a time coming up with problems to solve, especially since I know how to do the basics already. I learn by doing, so I need a task to complete. As you lurk, see how many of the questions you can figure out the answers to. Try to solve the problems yourself, even if you never post a thing. Follow the answers given by others.
  6. Get RSS feeds / bookmarks of your favorite developer sites. Some of my favorites, in no particular order: Code Junkies, The Daily WTF, DevX, CodingHorror, StackOverflow, Digg.com Programming, ITToolbox,  and C# Corner.

Do you have any more pointers to share with us? Sites that helped you learn and grow as a developer? Share them in the comments! Did you find this article helpful? I write these in order to help my fellow developers, so if you found it helpful, I’d love it if you shared it and passed it along. Thanks!