Tuesday 24 September 2013

Poll for a file in server path in c#


Sometimes we come across situations where we have to poll for a file availability in a server location.

Simple code to do it is given below :



 public  bool PollForFile(FileInfo file)
        {
            bool fileReady = false;
            while (!fileReady)
            {
                try
                {
                    //Check if file is not in use ..if it is in use then it cannot be opened,so exception will be thrown.
                    using (file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                    {
                        fileReady = true;
                        break;
                    }
                }
                catch (IOException)
                {
                    //File isn't ready yet, so we need to keep on waiting until it is.
                    fileReady = false;
                }

                //We'll want to wait a bit between polls, if the file isn't ready.
                if (!fileReady)
                {
                    Thread.Sleep(1000);
                }
            }

            return fileReady;
        }

Thursday 19 September 2013

Pick Birthdays between 2 dates irrespective of Year of Birth in C#

Many times we come across situations where we have to get birthdays of employees between 2 given dates irrespective of year of birth.

Here is a small piece of code in c# that does the trick !!


 public bool IsBirthdayBetweenDates(DateTime birthdate, DateTime beginDate, DateTime endDate)
        {
            if (birthdate != null & beginDate != null && endDate != null)
            {
                DateTime temp = birthdate.AddYears(beginDate.Year - birthdate.Year);

                if (temp < beginDate)
                {
                    temp = temp.AddYears(1);
                }
                return birthdate <= endDate && temp >= beginDate && temp <= endDate;
            }

            return false;
        }



Here  beginDate is the start date for search
endDate --> end date for search

The logic is simple,Just bring the birthdate to the year of begindate by adding years and then compare the dates.

--Deepti