Trouble Finding a Date



  • We work in a field that ... oh ... how do you say ... doesn't quite list "suave" as a top characteristic of its members. Worse yet, we're governed by the Steve Rule (you know, the one that goes something like in a random sample of programmers, there will be more named Steve then there will be females), which makes it even harder for us to find that significant other. After looking at how Sunny Nagi's predecessor would get the current date, the only thing I can possibly fathom is that he must have been subconsciously expressing his frustration in getting a date in real-life ....

    Dim notemessage, current_msg, complete_message, thedate, staffemail As String
    

    Dim sqlcmd As New SqlClient.SqlCommand("SELECT thedate=CONVERT(varchar(30),getdate()) ", SqlConn)
    Dim sqladp As New SqlDataAdapter(sqlcmd)
    Dim dsData As New DataSet

    SqlConn.Open

    sqladp.Fill(dsData)

    ' *** Get the date
    Dim drow As DataRow
    For Each drow In dsData.Tables(0).Rows
    thedate = drow("thedate")
    Exit For
    Next

    SqlConn.Close

    complete_message = thedate & " - " & notemessage & " - CUS "



  • Querying the database to get the current date... yep, that's a definite WTF.



  • You can't possibly mean that programs could determine the date PRIOR to SQL Server's creation.



  • Maybe the database server has the most accurate/reliable time?




  • What if the SQL server is very far away from the application?



  • I've never felt the need to comment before .. but that's
    fabulous!  He's either the kind of person to copypaste his way
    through life or is just too obstinate to lower himself to anything
    easier .. bizarre



  • Hello....The real WTF is that they are using a dataset to get a single value out of the database. Can anyone say ExecuteScalar?



  • Yeah, this is insane.  DateTime.Now anyone?



  • Obviously, this is an application relying on some server process, and
    it needs to know the date on the SQL Server, not on the local machine.
    Since this application will be deployed worldwide, it's impossible to
    know whether the SQL Server is on the same side of the International
    Date Line as the client, and so you have to query the server to find
    out.



  • Sweet![<:o)]

    Now THIS is a WTF!

     

     



  • even if we assume the database server is local to the webserver, perhaps he doesn't want to reformat the output of DateTime.Now
    to whatever the getdate() format is using DateTimeFormat. Of course,
    using the for loop to walk through a recordset containing one record
    appears to be the real WTF.



  • In addition to using the DB to return the current date, what is especially great about this one is he is also further misusing the DB layer to do formatting on the date returned, by converting it to a varchar !



  • Correct me if I'm wrong, but in VB isn't

    Dim a, b, c as integer

    The equivalent of

    Dim a as variant
    Dim b as variant
    Dim c as integer

    ?



  • Oh, yes, and an extra 5 points off for concatenating strings instead of using StringBuilder. [H]



  • @pjabbott said:

    Correct me if I'm wrong, but in VB isn't

    Dim a, b, c as integer

    The equivalent of

    Dim a as variant
    Dim b as variant
    Dim c as integer

    ?

    No, they fixed that in VB.NET.



  • @pjabbott said:

    Oh, yes, and an extra 5 points off for concatenating strings instead of using StringBuilder. [H]

    StringBuilder should be used for repetion, if you are manipulating a string over and over and over.  For things like this, there is absolutely no reason to use a stringBuilder -- in fact, using StringBuilder, which is more of a heavyweight class than string, probably would make things slightly *slower* if it has any effect at all.

    A common beginner mistake is that programmers see concatenation anywhere and they think "concatenation? I must use a stringbuilder!" and they make things more complicated than they need to be.



  • @Jeff S said:

    @pjabbott said:

    Correct me if I'm wrong, but in VB isn't

    Dim a, b, c as integer

    The equivalent of

    Dim a as variant
    Dim b as variant
    Dim c as integer

    ?

    No, they fixed that in VB.NET.

    To clarify ...Dim a,b,c As Integer

    VB6: Declares "c" as an Integer, "a" and "b" as Variant

    VB.NET: Declares all as Integer

    < Edited thx to Erik Juhlin >



  • @Anonymous said:

    Obviously, this is an application relying on some server process, and it needs to know the date on the SQL Server, not on the local machine. Since this application will be deployed worldwide, it's impossible to know whether the SQL Server is on the same side of the International Date Line as the client, and so you have to query the server to find out.

    I've seen things like this (not exactly but similar) in client applications.  There is no way to determine whether the client's machine has the proper date.

    Let's say your application won't let certain records be updated after a certain period of time (there are other probably better ways to do this but bear with me.)  Time on users machine is wrong. User goes in and updates the document even though the time period is over.



  • @Anonymous said:

    Obviously, this is an application relying on some server process, and it needs to know the date on the SQL Server, not on the local machine. Since this application will be deployed worldwide, it's impossible to know whether the SQL Server is on the same side of the International Date Line as the client, and so you have to query the server to find out.

    ...and this would be why we have UTC time.  For .Net, this is simple as DateTime.UtcNow.

    When in doubt, RTFM.



  • It was mentioned earlier, but it is worth repeating: the other WTF is working with DataAdapter, DataSet, DataTable, and DataRow objects when a simple ExecuteScalar() is all that is needed to return a single value from a command object in ADO.NET.

    By the way, great intro as usual Alex ! 



  • Oh, one more thing: I like the "loop" that takes the first value and then just exits ....

     

     



  • @Anonymous said:

    ...and this would be why we have UTC time.  For .Net, this is simple as DateTime.UtcNow.

    When in doubt, RTFM.

    Is there a way to make sure the client machine's time clock is set to the correct time?



  • This is valid if the DB has the time that's critical to the rest of the system, and since you normally do things like insert a record using getDate(), then all those dates, etc, have the DB's time.

    Once, I took over a system that assumed everything was in pacific time, which was fine until part of it was moved into central time...

    Also- -FREQUENTLY- clocks skew too much and you can't rely on IT to get their act together, so you pick a time authority like the most important DB and get on with it.

    The WTF is why there isn't a function that he's calling rather than just inlining the qry, etc. And a comment would be cool too.



  • Should read- "asking the DB for the current date/time is valid in some scenarios"...

    (couldn't edit my previous post)

    The rest of the code, I won't vouch for.



  • Please don't hurt me, but I actually wrote something just like this at a previous job. I think it was in VB 4.0 16-bit.

    There was a rounding issue with some (very large) dollar amounts. Whenever I would do a certain calculation in VB, the result would always be off by a penny. I did days and days of research on the problem. I don't remember the specifics of the problem, but I'm sure others here have heard of this issue, because it was a result of how certain Base-10 numbers become repeating decimals when stored in binary.

    Anyway, VB 4 had this issue. But after a while, I realised SQL Server 6.5 did not have this issue. So finally, I used ODBC API functions to connect to SQL Server, perform the calculation there, and return the result.

    God. I'm just waiting for someone at my former company to submit that WTF to this site.

     



  • @memorex said:

    Also- -FREQUENTLY- clocks skew too much and you
    can't rely on IT to get their act together, so you pick a time
    authority like the most important DB and get on with it.


    Don't you know IT staff have more important things to do than to walk
    around the office, setting computer clocks to the right time?




  • @A Wizard A True Star said:

    Please don't hurt me, but I actually wrote something just like this at a previous job. I think it was in VB 4.0 16-bit.

    There was a rounding issue with some (very large) dollar amounts. Whenever I would do a certain calculation in VB, the result would always be off by a penny. I did days and days of research on the problem. I don't remember the specifics of the problem, but I'm sure others here have heard of this issue, because it was a result of how certain Base-10 numbers become repeating decimals when stored in binary.

    Anyway, VB 4 had this issue. But after a while, I realised SQL Server 6.5 did not have this issue. So finally, I used ODBC API functions to connect to SQL Server, perform the calculation there, and return the result.

    God. I'm just waiting for someone at my former company to submit that WTF to this site.

    Sun didn't write the above so you softies can read it without asking your dark overlord for permission.



  • @loneprogrammer said:

    @memorex said:
    Also- -FREQUENTLY- clocks skew too much and you can't rely on IT to get their act together, so you pick a time authority like the most important DB and get on with it.

    Don't you know IT staff have more important things to do than to walk around the office, setting computer clocks to the right time?

    Geez, what the hell is this NTP thingy?  I turned it off on all my rooters because it didn't look important. But, why won't my Windows stations syncronize with the time server? [:P] </SARCASM>



  • @loneprogrammer said:

    Don't you know IT staff have more important things to do than to walk around the office, setting computer clocks to the right time?

    Like writing excellent code like this?  Maybe people like Sunny's predecessor would have contributed more to his company's success if he actually was in charge of manually synchronizing everyone's computer clock!



  • @cm5400 said:

    Geez, what the hell is this NTP thingy?  I turned it off on all my rooters because it didn't look important. But, why won't my Windows stations syncronize with the time server? [:P] </SARCASM>

    In case anyone didn't get that cm5400 was joking: there is a protocol for getting the time across a network. Unsurprisingly it's called Network Time Protocol [NTP]. The full NTP is really for synchronising among multiple computers to get sub-second accuracy - it's massive overkill for synchronising a workstation to a time source. There's a simplified version called Simple Network Time Protocol [SNTP] for this purpose - it simply clarifies the meaning of various fields in the protocol.

    I recently implemented an SNTP client for Windows CE. It took less than 800 lines of C++ code, and that included correcting to the device's configured time zone and correcting for daylight savings time. This wouldn't have been necessary except for the fact that CE's automatic DST correction feature doesn't work reliably - sometimes it doesn't apply a DST offset when it should do.

    Windows 2000 and later come with an SNTP client. On Win2k, it's not configured; on XP and 2003 it defaults to requesting the time from time.windows.com.

    The Kerberos authentication protocol used in Active Directory domains requires that client machines have as small as possible time offset from the server - this allows the protocol to have short-lived validity on packets, preventing captured packets from being replayed. In a domain, by default, workstations and member servers get their time from the domain controller. The IT department should ensure that the DCs are synchronised with an external source.

    In a standalone environment, you often find that your ISP provides an NTP server. To configure XP or 2003 to use a specific server, use the w32tm utility with the /config flag.



  • @Mike Dimmick said:

    The full NTP is really for synchronising
    among multiple computers to get sub-second accuracy - it's massive
    overkill for synchronising a workstation to a time source.


    If you have ever gotten the message from make(1) that says "file has
    modification time in the future" you would know sub-second accuracy is
    NOT overkill for a workstation.




  • I haven't seen anyone so far mention that he also was using a for each to loop through the rows... hello? How many rows do you expect from a "select value" statement?

    I just love that he used a DataSet (and thus also SqlDataAdapter) instead of just using a SqlDataReader.

    So let's not just get the current date the most difficult way possible let's also waste time (connecting to sql) and use extra memory(DataSet and DataAdapter).

     



  • A list of WTFs found so far:

    • Querying a database to find out the date
    • Returning it as a VARCHAR
    • Using a DataSet instead of output variables or ExecuteScalar
    • Using a for loop that terminates on the first iteration
    • Not closing the connection as early as it could be?
    • Not setting a value to notemessage


  • @Mike Dimmick said:

    In case anyone didn't get that cm5400 was
    joking: there is a protocol for getting the time across a network.
    Unsurprisingly it's called Network Time Protocol [NTP]. The full NTP is
    really for synchronising among multiple computers to get sub-second
    accuracy - it's massive overkill for synchronising a workstation to a
    time source. There's a simplified version called Simple Network Time
    Protocol [SNTP] for this purpose - it simply clarifies the meaning of
    various fields in the protocol.


    I was going to rant this, glad someone did it first and in more detail. =D



    The only thing I wish to add is that not all ISP NTP servers are
    created equal (shock!), so the most reliable option would be
    pool.ntp.org or one of its subdomains.



    The only reason I researched this is that for some crazy reason the DCs
    in my domain keep jumping ahead an hour, which cascades to the servers
    and workstations. I fixed it for a while by disabling NTP... until I
    made a new DC. Whoops, all the servers and workstations went crazy
    again.



  • omfg, so much for using html view in firefox. It dumped everything I
    typed after switching back. And that link is supposed to be
    http://www.pool.ntp.org.



    I was saying, I'd have used the router, except even with NTP it keeps time worse than my old 486.



    And yeah, using a dataset is goofy, but at least it just runs a
    function. If I was making it, I'd have had a cron job update the
    database every second by adding a row with the current time, then using
    the dataset to access it all (converting to formatted varchar in the
    process) and skip to the last row. Network traffic++ and DBM stress
    test all in one. =D



  • @Anonymous said:

    A list of WTFs found so far:

    • Querying a database to find out the date
    • Returning it as a VARCHAR
    • Using a DataSet instead of output variables or ExecuteScalar
    • Using a for loop that terminates on the first iteration
    • Not closing the connection as early as it could be?
    • Not setting a value to notemessage

    Also:

    • There is a resource leak if an exception is thrown after the connection is opened
    • My ex-manager was called "Steve". She's called "Steph" now . . . WTF! [:|]


  • <FONT style="BACKGROUND-COLOR: #e9e9e9">The road to hell is paved...</FONT>

    <FONT style="BACKGROUND-COLOR: #e9e9e9">Obviously, the client time cannot be relied upon in this developer's scenario. I have seen client installations gone buck wild, where users are free to change their system date to whatever they want, whenever they want. If this happens, you are hosed with Date.Now(). You'll get customers signing up in 1969, and payments that don't get batched until 2009. In these Wild, Wild West scenarios, the only thing to do is let SQL Server put in the date. The client time will be of no use. Perhaps a time server at the site could be relied upon, and all clients call GetTime() from a hosted component, but the bottom line is that some yahoo's local box time is probably meaningless.</FONT>

    Now, the whole ridiculous approach is the real WTF. What's really needed here is a simple stored procedure call for whatever he's inserting, and the stored procedure would be written to use GETDATE() on SQL Server 7.0 or CURRENT_TIMESTAMP, preferably, on SQL Server 2000.

    Mr. Angry DBA



  • I have seen too many WTF with regard to ADO.NET. There are lots of developers just being downright abusive to poor ol' .NET



    The first WTF is getting the current date from the database server.
    Especially if the database is on the same box as the web server (pretty
    common). If the database is not on the same box, the web server and the
    database server should have their times synchronised



    The second WTF is needlessly converting the date to varchar inside SQL
    Server. If the developer needs to display the date in a certain format,
    he has to "re-parse" the string to the DateTime type and then use the
    ToString to get the correct string format.



    Please repeat after me. We shall remember to use the CultureInfo object.



    The third WTF is abject failure to use the ExecuteScalar.



    But what I personnaly find objectionable is the naming conventions. It seems this VB.NET programmer is stuck in the days of VB



    The best approach is obviously:

    Dim currentDateTime As DateTime = Now



    and assuming the code still goes ahead (with serious misgivings)

    ===========================================



    Dim connection As New SqlConnection(...)

    Dim dateCommand As New SqlCommand("SELECT GetDate()",connection)

    connection.Open()

    Dim currentDateTime As DateTime = DirectCast(dateCommand.ExecuteScalar(),DateTime)

    connection.Close()

    dateCommand.Dispose()

    Dim completeMessage As String = currentDateTime.ToString("MM dd yyyy") & " - " & noteMessage & " - CUS"



  • I can't understand why he didn't just fire up a new process of cmd.exe
    sending DATE /T as the command to run, and capturing/parsing the
    results from the output. It would have been much more performant and
    scalable!




  • @Alex Papadimoulis said:

    in a random sample of programmers, there will be more named Steve then there will be females





    Ouch (emphasis added).  :p



  • Let me clear something for everyone..



    This page is hosted on same network as SQL Server. So they both have same system date and time :)



  • @b1xml2 said:



    Please repeat after me. We shall remember to use the CultureInfo object.

    [snip]

    Dim completeMessage As String = currentDateTime.ToString("MM dd yyyy") & " - " & noteMessage & " - CUS"
    Do as I say, not as I do.



  • @Anonymous said:

    Obviously, this is an application relying on some server process, and it needs to know the date on the SQL Server, not on the local machine. Since this application will be deployed worldwide, it's impossible to know whether the SQL Server is on the same side of the International Date Line as the client, and so you have to query the server to find out.

    Sure, but why not use NTP...? [;)] Guess this was the quick fix when DateTime.Now didn't work as expected.



  • @Mike Dimmick said:

    @cm5400 said:

    Geez, what the hell
    is this NTP thingy?  I turned it off on all my rooters
    because it didn't look important. But, why won't my Windows
    stations syncronize with the time server? [:P]

    In case anyone didn't get that cm5400 was joking: there is a protocol for getting the time across a network. Unsurprisingly it's called Network Time Protocol [NTP]. The full NTP is really for synchronising among multiple computers to get sub-second accuracy - it's massive overkill for synchronising a workstation to a time source. There's a simplified version called Simple Network Time Protocol [SNTP] for this purpose - it simply clarifies the meaning of various fields in the protocol.

    I recently implemented an SNTP client for Windows CE. It took less than 800 lines of C++ code, and that included correcting to the device's configured time zone and correcting for daylight savings time. This wouldn't have been necessary except for the fact that CE's automatic DST correction feature doesn't work reliably - sometimes it doesn't apply a DST offset when it should do.

    Windows 2000 and later come with an SNTP client. On Win2k, it's not configured; on XP and 2003 it defaults to requesting the time from time.windows.com.

    The Kerberos authentication protocol used in Active Directory domains requires that client machines have as small as possible time offset from the server - this allows the protocol to have short-lived validity on packets, preventing captured packets from being replayed. In a domain, by default, workstations and member servers get their time from the domain controller. The IT department should ensure that the DCs are synchronised with an external source.

    In a standalone environment, you often find that your ISP provides an NTP server. To configure XP or 2003 to use a specific server, use the w32tm utility with the /config flag.



    Can I just say thank you for a great summary of NTP and what it's used for?  In my current shop our network time was off for over a year and no one could seem to fix it (hey, I am a coder--I can't be trusted with such things).  I wish our IT people read WTF.  Actually I wish they would stop doing WTFs.  Actually I wish that at work I wasn't lumped in with the "IT" department....

    <sigh>
    </sigh>


  • @loneprogrammer said:



    If you have ever gotten the message from make(1) that says "file has
    modification time in the future" you would know sub-second accuracy is
    NOT overkill for a workstation.






    When would this ever be an issue, assuming that you use some sort of VCS?



  • I do it myself, but in .NET you don't have to open and close the
    connection manually when using the fill method.  The fill methos
    does it for you.

    If you need an accurate date the workstation won't do so getting it
    from the database would be better, but the loop isn't that great (I did
    it myself once, but I was still learning :-)).



    In Oracle I used the TO_CHAR method so you could give it back in a nice
    format (if you only have to display why use a DateTime :-))

    A DataReader or a ExecuteScalar would be better, but he could have used a DataSet out of habit.



    He seems to be missing a dal component.  He creates a new Command,
    Adapter and DataSet to get a date?  A lot of overkill if you ask
    me, what about O-O and incapsulation?  Incapsulate your Adapter,
    connections, ... and re-use it...



  • You are wrong Alex.

    In VB6 a and b will be Variants and c an Integer.

    Just try this:
    Dim a, b, c As Integer
    MsgBox TypeName(a)
    MsgBox TypeName(b)
    MsgBox TypeName(c)



  • This inconvenienced a couple of billion of electrons  -  but then using something simple such as DateTime.Date is very boring ...



  • Todays WTF isn't what the fuck...

    it's what to fuck



  • @Jeff S said:

    Oh, one more thing: I like the "loop" that takes the first value and then just exits ....

     



    In PL/SQL, this is not uncommon, because it requires less typing; especially when a special order by clause is necessary to get the first record.
    For example,


    begin
      for r in (select * from foo order by bar) loop
        process_foo(r);
        exit;
      end loop;
    end;


    the "proper" way, avoiding the loop-exit-construct:

    declare
      cursor c is select * from foo order by bar;
      r c%rowtype;
    begin
      open c;
      fetch c into r;
      close c;
      process_foo(r);
    end;

    Some people might try the shortcut

    declare
      r foo%rowtype;
    begin
      select * into r from foo where rownum=1 order by bar;
      process_foo(r);
    end;

    but this will not work correctly, since "where rownum=1" is processed before the "order by" clause, so "order by" won't be effective.

Log in to reply
 

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.