CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 6 of 7 FirstFirst ... 34567 LastLast
Results 76 to 90 of 91
  1. #76
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Looking to develope skills

    Quote Originally Posted by Dragster93 View Post
    I did that because otherwise, it would say, can't implicitely convert DateTime to Int.
    You need to understand what DateTime.Now does. It makes an instance of the DateTime class and sets it to the current time. When you call Datetime.Now.Year, you are accessing the year property of the current date time instance. Since the Year property is declared as an integer, you don't need to convert it.

    Quote Originally Posted by Dragster93 View Post
    So what you're saying is that I should store the DateTime value in a variable and then use that variable rather than calling DateTime() everytime???
    Yes. Everytime you call DateTime.Now you are creating a separate datetime instance. Just call it once.

    Quote Originally Posted by Dragster93 View Post
    Yes, I understood why it's freezing, that is why I tried to use the backgroundworker to do the calcuation in background. But I seem to be having a little trouble with it. I use 'backgroundworker.dispose()' to free the resources so that if the Set Alarm button is clicked a second time to set a different time, the it shouldn't display an exception saying, "The thread is busy". But that seems to work only for the second click. If you click the third time, again the same problem occurs. I shall try using the catch and throw exception for that problem and see if it works
    You have something wrong with the background worker code. Post your background worker code.

  2. #77
    Join Date
    Dec 2009
    Posts
    109

    Re: Looking to develope skills

    Quote Originally Posted by Arjay View Post
    You need to understand what DateTime.Now does. It makes an instance of the DateTime class and sets it to the current time. When you call Datetime.Now.Year, you are accessing the year property of the current date time instance. Since the Year property is declared as an integer, you don't need to convert it.
    Now I get it! :P

    Quote Originally Posted by Arjay View Post
    You have something wrong with the background worker code. Post your background worker code.
    Sure thing. Here it is:

    Code:
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
            {
                int i = 0;
                while (i == 0)
                {
                    if (SetAlarm(Convert.ToInt32(dt_time.Value.Hour), Convert.ToInt32(dt_time.Value.Minute), Convert.ToInt32(dt_time.Value.Second)))
                    {
                        break;
                    }
                }
            }
    And I call the backgroundworker method in this way:

    Code:
    private void btn_alarm_Click(object sender, EventArgs e)
            {
                try
                {
                    backgroundWorker1.RunWorkerAsync();
                }
                catch
                {
                    backgroundWorker1.CancelAsync();
                    backgroundWorker1.RunWorkerAsync();
                }
            }

  3. #78
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Looking to develope skills

    With regard to checking the time. If the user specifies an hour and minute time string, I convert this to a datetime object (and merge it with the current year, month and day). Once I do this, I can do a simple datetime compare to see if the alarm should go off.

    So let's say the user enters "8:00 AM" into a string variable called _wakeup. The following code takes that value, turns it into a DateTime object, merges it with the current date and then stores it in the _timeNextAlarm field.

    Code:
    ///<summary>
    /// Sets the alarm time
    ///</summary>
    privatevoid SetInitialAlarmTime( )
    {
      // Parse the requested alarm time ( this arrives as std or military time, i.e. "8:00:00 AM" or "19:00:00" )
      // The date time created here will have the wrong date, so we'll need to fix that up later.
      DateTime requestedAlarm = DateTime.Parse( _wakeup );
     
      // Retrieve the current date
      DateTime dtNow = DateTime.Now;
     
      // Merge the requested time with the current date.
      requestedAlarm = newDateTime( dtNow.Year
        , dtNow.Month
        , dtNow.Day
        , requestedAlarm.Hour
        , requestedAlarm.Minute
        , requestedAlarm.Second );
     
      // Store the next alarm value. Check if we are already past the requested alarm time for the day.
      // If we are, then increment to the next day.
      _timeNextAlarm = ( requestedAlarm > dtNow )
        ? requestedAlarm.AddDays( 1 )
        : requestedAlarm;
    }
    


    Using this strategy, it's a simple matter to reset the alarm time to the next day after the alarm goes off. All you need to do is call the AddDay( ) method on _timeNextAlarm.

  4. #79
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Looking to develope skills

    Here's code that creates the polling thread and within the thread, checks every second to see if the alarm should sound.

    Code:
     
    // Event used to turn off the alarm (before it's been set)
    privateAutoResetEvent _stopEvent = newAutoResetEvent( false );
     
    // Alarm thread which checks every second if the alarm time
    // has passed in order to trigger the alarm
    privateThread _alarmThread = null;
     
    // Wait handle array. Used to hold the stop event
    privateWaitHandle [ ] _waitHandles = null;
     
    ///<summary>
    /// Sets the alarm
    ///</summary>
    publicvoid Set( )
    {
     Reset( );
     SetInitialAlarmTime( );
     CreateAlarmThread( );
    }
     
    ///<summary>
    /// Resets the alarm
    ///</summary>
    publicvoid Reset( )
    {
      if ( null != _alarmThread )
      {
        // Signal the alarm thread to exit
        _stopEvent.Set( );
     
        // Close the thread reference
        _alarmThread = null;
      }
    }
     
    ///<summary>
    /// Creates and starts the alarm thread
    ///</summary>
    privatevoid CreateAlarmThread( )
    {
      if ( _waitHandles == null )
      {
        _waitHandles = newWaitHandle [ ] { _stopEvent };
      }
     
      _alarmThread = newThread( newThreadStart( AlarmThreadProc ) );
      _alarmThread.IsBackground = true;
      _alarmThread.Start( );
    }
     
    ///<summary>
    /// Alarm thread procedure. Waits the desired time interval (1 sec)
    /// before checking if the alarm should be triggered. Also
    /// waits on a stop event, so the user can cancel the alarm
    ///</summary>
    privatevoid AlarmThreadProc( )
    {
      while ( true )
      {
        switch ( WaitHandle.WaitAny( _waitHandles, 1000, false ) )
        {
        // Stop event signalled; exit thread
        case 0:
          return;
     
        // Polling expired, check if alarm time has passed
        caseWaitHandle.WaitTimeout:
     
          if ( CheckAndIncrementNextAlarmTime( DateTime.Now ) )
          {
            RingAlarm( );
          }
          break;
        }
      }
    }
     
    ///<summary>
    /// Checks if the current time has passed the next scheduled alarm time.
    /// If it has, increments the alarm time to the next day and returns true.
    ///</summary>
    ///<param name="dtNow">Current time</param>
    ///<returns>True to ring alarm; false otherwise</returns>
    privatebool CheckAndIncrementNextAlarmTime( DateTime dtNow )
    {
      bool ringAlarm = false;
    
     
      // Check if the current time has passed the scheduled alarm time
      if ( _timeNextAlarm < dtNow )
      {
        _timeNextAlarm = _timeNextAlarm.AddDays( 1 );
        ringAlarm = true;
      }
      return ringAlarm;
    }
     
    


  5. #80
    Join Date
    Dec 2009
    Posts
    109

    Re: Looking to develope skills

    I'm sorry but can you explain this small snippet to me??

    Code:
    _timeNextAlarm = ( requestedAlarm > dtNow )
        ? requestedAlarm.AddDays( 1 )
        : requestedAlarm;
    I can't understand the syntax of this particular snippet.
    And, should '_timeNextAkarm' be a DateTime object or a string???

  6. #81
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Looking to develope skills

    Quote Originally Posted by Dragster93 View Post
    I'm sorry but can you explain this small snippet to me??

    Code:
    _timeNextAlarm = ( requestedAlarm > dtNow )
        ? requestedAlarm.AddDays( 1 )
        : requestedAlarm;

    I'm using the conditional or ternary operator.

    http://msdn.microsoft.com/en-us/library/ty67wk28(VS.80).aspx

    Essentially it's the same as writing:

    Code:
     
    if ( requestedAlarm > dtNow )
    {
      _timeNextAlarm = requestedAlarm.AddDays( 1 );
    }
    else
    {
      _timeNextAlarm = requestedAlarm;
    }
    Quote Originally Posted by Dragster93 View Post
    And, should '_timeNextAkarm' be a DateTime object or a string???
    In general, for a class to be assigned to another class, the class being assigned to needs to have an assignment operator defined that is capable of converting the class doing the assigning. That means if the _timeNextAlarm object were a string, the string class would need to have an assignment operator that can take a DateTime object. The string class doesn't have any such operator defined. Therefore, _timeNextAlarm is a DateTime object. Also, you'll see in other parts of the code where I call _timeNextAlarm.AddDays( 1 ), so an AddDays( ) method would indicate that it's a DateTime object.

    Tip: Deciding on the type of variable used to store and pass around is a very important programming consideration. Many beginning programmers [over] use strings to store data, where they really should be using a data type that more closely matches what they are storing.

    For example, you can store the age of a person in a string, but you probably would want to use a different type like an integer because you can't perform math operations on a string. If I want to averages the ages for a list of persons and the ages are stored as strings, then I'm going to need to convert the string to integers first. If you choose your type carefully, then you end up with the least amount of conversions.

    I chose the DateTime type because I now have all the methods and properties of a DateTime type at my disposal (such as the AddDays( 1 )). Had I stored the DateTime as a string, then a simple operation such as Adding a day to the current datetime would be a major undertaking for me to have to code up because I would have to account for end of month, end of year, and other special cases. By using the proper DateTime type, adding a day to the current day is a simple method call (and the DateTime class handles the complexity under the covers).

  7. #82
    Join Date
    Dec 2009
    Posts
    109

    Re: Looking to develope skills

    Quote Originally Posted by Arjay View Post
    I'm using the conditional or ternary operator.

    http://msdn.microsoft.com/en-us/library/ty67wk28(VS.80).aspx

    Essentially it's the same as writing:

    Code:
     
    if ( requestedAlarm > dtNow )
    {
      _timeNextAlarm = requestedAlarm.AddDays( 1 );
    }
    else
    {
      _timeNextAlarm = requestedAlarm;
    }
    In general, for a class to be assigned to another class, the class being assigned to needs to have an assignment operator defined that is capable of converting the class doing the assigning. That means if the _timeNextAlarm object were a string, the string class would need to have an assignment operator that can take a DateTime object. The string class doesn't have any such operator defined. Therefore, _timeNextAlarm is a DateTime object. Also, you'll see in other parts of the code where I call _timeNextAlarm.AddDays( 1 ), so an AddDays( ) method would indicate that it's a DateTime object.

    Tip: Deciding on the type of variable used to store and pass around is a very important programming consideration. Many beginning programmers [over] use strings to store data, where they really should be using a data type that more closely matches what they are storing.

    For example, you can store the age of a person in a string, but you probably would want to use a different type like an integer because you can't perform math operations on a string. If I want to averages the ages for a list of persons and the ages are stored as strings, then I'm going to need to convert the string to integers first. If you choose your type carefully, then you end up with the least amount of conversions.

    I chose the DateTime type because I now have all the methods and properties of a DateTime type at my disposal (such as the AddDays( 1 )). Had I stored the DateTime as a string, then a simple operation such as Adding a day to the current datetime would be a major undertaking for me to have to code up because I would have to account for end of month, end of year, and other special cases. By using the proper DateTime type, adding a day to the current day is a simple method call (and the DateTime class handles the complexity under the covers).
    Thank You so much for explaining that to me! =)
    It really helped! =)

  8. #83
    Join Date
    Dec 2009
    Posts
    109

    Re: Looking to develope skills

    I'm sorry but this is gonna sound a lil stupid!
    Your ? condition says

    Code:
    _timeNextAlarm = ( requestedAlarm > dtNow )
        ? requestedAlarm.AddDays( 1 )
        : requestedAlarm;
    it the 'requestedAlarm' time is more than 'dtNow' time, that means the time is yet to come... then why would we add another day to it?

  9. #84
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Looking to develope skills

    Quote Originally Posted by Dragster93 View Post
    I'm sorry but this is gonna sound a lil stupid!
    Your ? condition says

    Code:
    _timeNextAlarm = ( requestedAlarm > dtNow )
        ? requestedAlarm.AddDays( 1 )
        : requestedAlarm;
    it the 'requestedAlarm' time is more than 'dtNow' time, that means the time is yet to come... then why would we add another day to it?
    That would be a bug. It should be.
    Code:
    _timeNextAlarm = ( requestedAlarm < dtNow )
        ? requestedAlarm.AddDays( 1 )
        : requestedAlarm;

  10. #85
    Join Date
    Dec 2009
    Posts
    109

    Re: Looking to develope skills

    Also, I couldn't understand this SWITCH:

    Code:
    while ( true )
      {
        switch ( WaitHandle.WaitAny( _waitHandles, 1000, false ) )
        {
        // Stop event signalled; exit thread
        case 0:
          return;
     
        // Polling expired, check if alarm time has passed
        caseWaitHandle.WaitTimeout:
     
          if ( CheckAndIncrementNextAlarmTime( DateTime.Now ) )
          {
            RingAlarm( );
          }
          break;
        }
    }
    I've worked with switch cases before but it was usually between a choice of numbers like 1-9 or something like that. Could you explain this to me?
    And, WHILE (which object returns TRUE)?
    Last edited by Dragster93; December 31st, 2009 at 07:11 PM.

  11. #86
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Looking to develope skills

    Quote Originally Posted by Dragster93 View Post
    Also, I couldn't understand this SWITCH:

    Code:
    while ( true )
      {
        switch ( WaitHandle.WaitAny( _waitHandles, 1000, false ) )
        {
        // Stop event signalled; exit thread
        case 0:
          return;
     
        // Polling expired, check if alarm time has passed
        caseWaitHandle.WaitTimeout:
     
          if ( CheckAndIncrementNextAlarmTime( DateTime.Now ) )
          {
            RingAlarm( );
          }
          break;
        }
    }
    I've worked with switch cases before but it was usually between a choice of numbers like 1-9 or something like that. Could you explain this to me?
    And, WHILE (which object returns TRUE)?
    A switch statement does act on numbers (and other types) and I'm waiting on two numbers. I'm waiting on 0, which is the index to the stop event object specified in the wait handle array and on WaitHandle.WaitTimeout which is defined as 258. To help understand this, look in Msdn for WaitHandle.WaitAny. It will explain the method and it's the return values. Essentially, I use this function as a timer function. Waiting on the stop event allows me to signal the thread to exit (which is a clean way of getting a thread to exit). I specify a timeout value, so that WaitAny returns on the timeout which I use to check if the alarm should be sounded.

    while( true ) just means to loop indefinitely. We want to do this because we'll be checking whether to ring the alarm on the timeout and only want to exit the loop (and the thread) if the stop event is called.

    Keep in mind that this approach is roughly equivalent to:

    Code:
     
    while ( true )
    {
      if( WaitHandle.WaitAny( _waitHandles ) == 0 )
      {
        // Stop event signalled; exit thread
        return;
      }
     
      if ( CheckAndIncrementNextAlarmTime( DateTime.Now ) )
      {
        RingAlarm( );
      }
     
      Threading.Sleep( timeout );
    }
    However, the switch approach yields more immediate response as the timeout value get longer. In other words, if I'm trying the exit the thread by setting the stop event and have a timeout of 2 minutes, I may have to wait up to two minutes for the thread to exit. This is because I could be sitting in the Sleep( ) method before I get back around to checking if the stop event has been set.

    With the switch statement, the response time isn't dependent on the timeout time because the WaitAny method does the waiting for you and will return immediately when the stop event has been set (regardless of whether the timeout has expired).

    One major distinction of this code over your original code is that this code essentially puts the thread to sleep while waiting (which is extremely important). Your original code simply spun and kept calling your check method. Had your code been run, you would have noticed that the cpu usage would have gone through the roof.

  12. #87
    Join Date
    Dec 2009
    Posts
    109

    Re: Looking to develope skills

    Thank you for explaining that! =)
    Ok, I've typed down the coding as per to what all you told me to type. It runs fine. Only thing is, if the time is set to a time in the future (like it should be) the alarm (which is a MessageBox) keeps getting triggered every second, whether the time has been reached.....OR NOT!!!

    This is what my code looks like:
    Code:
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private AutoResetEvent stopThread = new AutoResetEvent(false);
            private Thread alarmThread = null;
            private WaitHandle[] waitHandles = null;
    
            private void btn_setalarm_Click(object sender, EventArgs e)
            {
                Reset();
                CreateAlarmThread();
                
            }
    
            private void Reset()
            {
                if (null != alarmThread)
                {
                    //Signaling the stopThread
                    stopThread.Set();
    
                    //Close thread referrence
                    alarmThread = null;
                }
            }
    
            private void AlarmThreadProcedure()
            {
                while (true)
                {
                    switch(WaitHandle.WaitAny(waitHandles,1000,false))
                    {
                            //Stop event signalled. Exit thread.
                        case 0:
                            return;
    
                            //Polling thread expired. Check if alarm time has passed.
                        case WaitHandle.WaitTimeout:
    
                            if (CheckAndIncrementNextAlarmTime())
                            {
                                MessageBox.Show("Alarm");
                            }
                            break;
                    }
                }
            }
    
            private void CreateAlarmThread()
            {
                if (waitHandles == null)
                {
                    waitHandles = new WaitHandle[] { stopThread };
                }
                alarmThread = new Thread(new ThreadStart(AlarmThreadProcedure));
                alarmThread.IsBackground = true;
                alarmThread.Start();
            }
            
            private bool CheckAndIncrementNextAlarmTime()
            {
                bool ringAlarm=false;
                //Time selected by the user
                DateTime setAlarm = DateTime.Parse(dt_alarm.Value.ToString());
    
                //Current time
                DateTime dt_now = DateTime.Now;
    
                //Merge the 'selected' and 'current' times
                setAlarm = new DateTime(dt_now.Year
                    , dt_now.Month
                    , dt_now.Day
                    , setAlarm.Hour
                    , setAlarm.Minute
                    , setAlarm.Second);
    
                //Store the next time value. If date has already been passed, increment next day.
                DateTime timeNextAlarm = new DateTime();
                if (setAlarm < dt_now)
                {
                    timeNextAlarm = setAlarm.AddDays(1);
                }
                else
                {
                    timeNextAlarm = setAlarm;
                    ringAlarm = true;
                }
                return ringAlarm;
            }
        }
    }
    I know it's me who has done something wrong but I just can't seem to find the bug! I read the code several times, but still nothing. When you're free, could you just have a look at my code?

  13. #88
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Looking to develope skills

    You didn't copy the code as I typed it. Take another look at the code in my responses of #78 and #79. I have an InitializeAlarmTime( ) method which you need to call in your SetAlarm button handler:

    Code:
     
    private void btn_setalarm_Click(object sender, EventArgs e)
    {
      Reset();
     
      SetInitialAlarmTime( );
    
      CreateAlarmThread( );            
    }
    Then compare your CheckAndIncrementNextAlarmTime( ) method with mine. You'll see that mine is simpler and that you've merged the functionality of SetInitialAlarmTime( ) with CheckAndIncrementNextAlarmTime( ).

    All the check method should do is check to see if the alarm time has passed. If it has, it sets the day to the next and returns true. Your check method keeps initializing the time from your text box. It shouldn't do this.

    Btw, if you aren't doing so, you need to start using the debugger. You can set a breakpoint in the while( true ) loop by pressing F9. Then each time through the loop, you can check the values _nextTimeAlarm and other values. This will help you figure out what is going wrong.
    Last edited by Arjay; December 31st, 2009 at 09:54 PM.

  14. #89
    Join Date
    Apr 2006
    Posts
    220

    Re: Looking to develope skills

    Dragster93 !

    To be a good programmer you should have a good grip on algorithms. Do you know what an algorithm is !

    Secondly, after reading all the replies I have come to the conclusion that your basic programming skills are not well developed yet, and you are trying to go for big things. You should buy some beginner level C# programming book and read it thoroughly and solve the given exercises at the end of each chapter.

    Although the work you are doing with the help of forum members is not bad at all, but you should know the basic syntax of any certain language to be able to code in it.

    in the meantime, let me think some other advice for you...

  15. #90
    Join Date
    Apr 2006
    Posts
    220

    Re: Looking to develope skills

    This guy here has the same problem as of you..

    http://www.codeguru.com/forum/showthread.php?t=490415

Page 6 of 7 FirstFirst ... 34567 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured