コード例 #1
0
ファイル: EpgClass.cs プロジェクト: huha001/TvWishList
      public bool SearchEPG(bool view_only_mode)
      {
          Log.Info("[TvWishList]:SearchEPG started with view_only_mode=" + view_only_mode.ToString(), (int)LogSetting.DEBUG);
          VIEW_ONLY_MODE = view_only_mode;
          myTvWishes = new TvWishProcessing();
          // load globals from data base
          TvBusinessLayer layer = new TvBusinessLayer();
          Setting setting;
          
          /*
          //Debug only
          Log.Debug("Debug Schedules:");
          foreach (Schedule myschedule in Schedule.ListAll())
          {
              outputscheduletoresponse(myschedule, (int)LogSetting.DEBUG);
          }
          //end debug  
          */

          lng.ReadLanguageFile();
          Log.Debug("language file read");

          try
          {
              setting = layer.GetSetting("TvWishList_Debug", "false");

              if (BoolConversion(setting.Value,false))
              {
                  DEBUG = true;
              }
              else
              {
                  DEBUG = false;
              }
              Log.DebugValue = DEBUG;

              //TV User Folder
              setting = layer.GetSetting("TvWishList_TV_USER_FOLDER", "NOT_FOUND");
              TV_USER_FOLDER = setting.Value;

              /*// delete later - no more needed
              filewatchermessages = TV_USER_FOLDER + @"\TvWishList\filewatchermessages.txt";
              if (File.Exists(filewatchermessages) == true)
              {
                  File.Delete(filewatchermessages);
                  LogDebug("Deleting file " + filewatchermessages, (int)LogSetting.DEBUG);
              }*/
          }
          catch
          {
              string languagetext = lng.TranslateString("Fatal error - check the log file",24 );
              labelmessage(languagetext, PipeCommands.Error);
              LogDebug("Could not read from TV database", (int)LogSetting.ERROR);
              return false;
          }




          //*****************************************************
          //Lock TvWishList with timeout error
          bool success = false;
          int seconds = 60;
          Log.Debug("Lock TvWishList EpgSearch");
          for (int i = 0; i < seconds / 10; i++)
          {
              success = myTvWishes.LockTvWishList("TvWishList EpgSearch");
              if (success)
                  break;
              System.Threading.Thread.Sleep(10000); //sleep 10s to wait for BUSY=false
              
              string languagetext = lng.TranslateString("Waiting for old jobs {0}s to finish", 1, (seconds - i * 10).ToString());
              Log.Debug(languagetext, (int)LogSetting.DEBUG);
              labelmessage(languagetext, PipeCommands.StartEpg);
          }
          if (success == false)
          {
              string languagetext = lng.TranslateString("Error: TvWishList did not finish old jobs - reboot your computer", 2);
              LogDebug(languagetext, (int)LogSetting.ERROR);
              labelmessage(languagetext, PipeCommands.Error);
              return false;
          }

          try
          {

              string languagetext = lng.TranslateString("Reading data settings", 3);
              LogDebug(languagetext, (int)LogSetting.DEBUG);
              labelmessage(languagetext, PipeCommands.StartEpg);

              //checkboxes
              Log.Debug("Reading Settings");

              setting = layer.GetSetting("TvWishList_SkipDeleted", "false");
              if (BoolConversion(setting.Value, false))
                  _skipDeleted = true;
              else
                  _skipDeleted = false;

              setting = layer.GetSetting("TvWishList_EmailReply", "true");
              if (BoolConversion(setting.Value, true))
                  _emailreply = true;
              else
                  _emailreply = false;


              setting = layer.GetSetting("TvWishList_Schedule", "true");
              if (BoolConversion(setting.Value, true))
                  _automaticrecording = true;
              else
                  _automaticrecording = false;


              setting = layer.GetSetting("TvWishList_ScheduleConflicts", "false");
              if (BoolConversion(setting.Value, false))
                  _scheduleconflicts = true;
              else
                  _scheduleconflicts = false;

              setting = layer.GetSetting("TvWishList_EmailOnlyNew", "true");
              if (BoolConversion(setting.Value, true))
                  _emailonlynew = true;
              else
                  _emailonlynew = false;

              setting = layer.GetSetting("TvWishList_DeleteTimeChanges", "true");
              if (BoolConversion(setting.Value, true))
                  _DeleteTimeChanges = true;
              else
                  _DeleteTimeChanges = false;

              setting = layer.GetSetting("TvWishList_FilterEmail", "true");
              if (BoolConversion(setting.Value, true))
                  _filter_email = true;
              else
                  _filter_email = false;

              setting = layer.GetSetting("TvWishList_FilterRecord", "true");
              if (BoolConversion(setting.Value, true))
                  _filter_scheduled = true;
              else
                  _filter_scheduled = false;

              setting = layer.GetSetting("TvWishList_FilterConflicts", "true");
              if (BoolConversion(setting.Value, true))
                  _filter_conflicts = true;
              else
                  _filter_conflicts = false;

              setting = layer.GetSetting("TvWishList_DescendingSort", "false");
              if (BoolConversion(setting.Value, true))
                  _descendingsort = true;
              else
                  _descendingsort = false;

              //textboxes
              string Emailformat = myTvWishes.loadlongsettings("TvWishList_EmailFormat");
              if (Emailformat == string.Empty)
              {
                  Emailformat = lng.TranslateString(Emailformat, 90);
              }
              Emailformat = Emailformat.Replace(@"\n", "\n");
              Emailformat = Emailformat.Replace("<br>", "\n");
              Emailformat = Emailformat.Replace("<BR>", "\n");
              string myEmailformat=Emailformat.ToString().Replace('{', '_');
              myEmailformat=myEmailformat.ToString().Replace('}', '_');
              LogDebug("Emailformat :" + myEmailformat, (int)LogSetting.DEBUG);

              //datetimeformat
              setting = layer.GetSetting("TvWishList_DateTimeFormat", "");
              string DateTimeFormat = setting.Value.ToString();
              if (DateTimeFormat == string.Empty)
              {
                  DateTimeFormat = lng.TranslateString("{1:00}/{2:00} at {3:00}:{4:00}", 91);  
              }

              string myDateformat = DateTimeFormat.ToString().Replace('{', '_');
              myDateformat = myDateformat.ToString().Replace('}', '_');
              LogDebug("DateTimeFormat=" + myDateformat, (int)LogSetting.DEBUG);

              

              //initialize messages
              string messagedata = "";
              mymessage = new XmlMessages(DateTimeFormat, Emailformat, DEBUG);
              languagetext = lng.TranslateString("Loading Messages", 4);
              Log.Debug(languagetext);
              labelmessage(languagetext, PipeCommands.StartEpg);
              if (VIEW_ONLY_MODE == true)
              {
                  messagedata = ""; //start with a clean message list for viewonlymode
              }
              else
              {
                  //mymessage.filename = TV_USER_FOLDER + @"\TvWishList\Messages.xml";
                  messagedata = myTvWishes.loadlongsettings("TvWishList_ListViewMessages");

              }
              mymessage.readxmlfile(messagedata, false);
              Log.Debug("mymessage.TvMessages.Count=" + mymessage.ListAllTvMessages().Count.ToString());
              //mymessage.logmessages();  //DEBUG ONLY

              


              setting = layer.GetSetting("TvWishList_Sort", "Start");
              string sortstring = setting.Value;
              if (sortstring == "Title")
                  _sort = (int)XmlMessages.Sorting.Title;
              else if (sortstring == "Start")
                  _sort = (int)XmlMessages.Sorting.Start;
              else if (sortstring == "Created")
                  _sort = (int)XmlMessages.Sorting.Created;
              else if (sortstring == "Genre")
                  _sort = (int)XmlMessages.Sorting.Genre;
              else if (sortstring == "Classification")
                  _sort = (int)XmlMessages.Sorting.Classification;
              else if (sortstring == "ParentalRating")
                  _sort = (int)XmlMessages.Sorting.ParentalRating;
              else if (sortstring == "StarRating")
                  _sort = (int)XmlMessages.Sorting.StarRating;
              else if (sortstring == "Type")
                  _sort = (int)XmlMessages.Sorting.Type;
              else if (sortstring == "Message")
                  _sort = (int)XmlMessages.Sorting.Message;
              else if (sortstring == "SearchString")
                  _sort = (int)XmlMessages.Sorting.SearchString;
              else if (sortstring == "EpisodeName")
                  _sort = (int)XmlMessages.Sorting.EpisodeName;
              else if (sortstring == "EpisodeNum")
                  _sort = (int)XmlMessages.Sorting.EpisodeNum;
              else if (sortstring == "EpisodeNumber")
                  _sort = (int)XmlMessages.Sorting.EpisodeNumber;
              else if (sortstring == "EpisodePart")
                  _sort = (int)XmlMessages.Sorting.EpisodePart;


              //EPG marker
              setting = layer.GetSetting("TvWishList_EpgMarker", "");
              _EpgMarker = setting.Value;
              /*if (_EpgMarker.Contains(@"|"))
              {
                  EpgMarkerExpression = true;
              }
              else
              {
                  EpgMarkerExpression = false;
              }*/

              //textboxes
              setting = layer.GetSetting("TvWishList_UserName", "");
              _TextBoxUserName = setting.Value;

              setting = layer.GetSetting("TvWishList_Password", "");
              _TextBoxPassword = setting.Value;

              setting = layer.GetSetting("TvWishList_TestReceiver", "");
              s_receiver = setting.Value;

              setting = layer.GetSetting("TvWishList_SmtpEmailAddress", "");
              _TextBoxSmtpEmailAddress = setting.Value;


              //providerdata
              setting = layer.GetSetting("TvWishList_Providers_0", "_Last Setting;;0;False");
              string[] tokenarray = setting.Value.Split(';');
              if (tokenarray.Length != 4)
              {
                  LogDebug("Provider array has invalid number of elements: " + tokenarray.Length.ToString(), (int)LogSetting.ERROR);
              }
              else
              {
                  try
                  {
                      _TextBoxSmtpServer = tokenarray[1];
                      _numericUpDownSmtpPort = Convert.ToInt32(tokenarray[2]);
                      _checkBoxSSL = Convert.ToBoolean(tokenarray[3]);
                  }
                  catch (Exception ex)
                  {
                      LogDebug("Failed converting provider data with exception: " + ex.Message, (int)LogSetting.ERROR);
                      languagetext = lng.TranslateString("Fatal error - check the log file", 24);
                      labelmessage(languagetext, PipeCommands.StartEpg); //do not stop - do not flag as error
                      Thread.Sleep(ErrorWaitTime);
                  }
              }

              //maxfound
              setting = layer.GetSetting("TvWishList_MaxFound", "100");
              try
              {
                  MAXFOUND = Convert.ToInt32(setting.Value);
              }
              catch
              {
                  LogDebug("Max Found could not be converted to number  resetting to 100", (int)LogSetting.DEBUG);
                  MAXFOUND = 100;
                  languagetext = lng.TranslateString("Fatal error - check the log file", 24);
                  labelmessage(languagetext, PipeCommands.StartEpg); //do not stop - do not flag as error
                  Thread.Sleep(ErrorWaitTime);
              }


              setting = layer.GetSetting("TvWishList_MaxTvWishId", "0");
              int maxTvWishId = 0;
              int.TryParse(setting.Value, out maxTvWishId);
              myTvWishes.MaxTvWishId = maxTvWishId;
              Log.Debug("EpgClass: MaxTvWishId=" + myTvWishes.MaxTvWishId.ToString(), (int)LogSetting.DEBUG);


              //deleteExpiration in months
              int deleteExpiration = 12;
              setting = layer.GetSetting("TvWishList_DeleteExpiration", "12");
              try
              {
                  deleteExpiration = Convert.ToInt32(setting.Value);
              }
              catch
              {
                  LogDebug("Delete Expiration could not be converted to number  resetting to 12", (int)LogSetting.ERROR);
                  deleteExpiration = 12;
                  languagetext = lng.TranslateString("Fatal error - check the log file", 24);
                  labelmessage(languagetext, PipeCommands.StartEpg); //do not stop - do not flag as error
                  Thread.Sleep(ErrorWaitTime);
              }

              //listviewdata
              setting = layer.GetSetting("TvWishList_ColumnSeparator", ";");
              TV_WISH_COLUMN_SEPARATOR = setting.Value[0];

              //default pre and post record from general recording settings
              setting = layer.GetSetting("preRecordInterval", "5");
              string prerecord = setting.Value;
              setting = layer.GetSetting("postRecordInterval", "5");
              string postrecord = setting.Value;

              myTvWishes.TvServerSettings(prerecord, postrecord, ChannelGroup.ListAll(), RadioChannelGroup.ListAll(), Channel.ListAll(), Card.ListAll(), TV_WISH_COLUMN_SEPARATOR);

              languagetext = lng.TranslateString("Loading Tv wishes", 5);
              Log.Debug(languagetext);
              labelmessage(languagetext, PipeCommands.StartEpg);
              string listviewdata = "";
              if (VIEW_ONLY_MODE == true)
              {
                  listviewdata = myTvWishes.loadlongsettings("TvWishList_OnlyView");  //never change setting name must match to MP plugin and later savelongsetting             
              }
              else
              {
                  listviewdata = myTvWishes.loadlongsettings("TvWishList_ListView");
              }
              Log.Debug("listviewdata=" + listviewdata, (int)LogSetting.DEBUG);
              myTvWishes.Clear();
              myTvWishes.LoadFromString(listviewdata, true);



              RESPONSE = "";
              //conflictprograms.Clear();

              //update messages before conflict checking of EPG data
              Log.Debug("after reading messages: TvMessages.Count=" + mymessage.ListAllTvMessages().Count.ToString());
              mymessage.updatemessages(deleteExpiration);
              Log.Debug("after update messages: TvMessages.Count=" + mymessage.ListAllTvMessages().Count.ToString());


              //Debug for foxbenw issue
              Log.Debug("Outputting all schedules before schedule processing");
              foreach (Schedule oneschedule in Schedule.ListAll())
              {
                  mymessage.outputscheduletoresponse(oneschedule, (int)LogSetting.DEBUG);
              }
              Log.Debug("End of Outputting all schedules before schedule processing");



              //#if (MP11RC || MP12)
#if (TV11 || TV12)
              // check for conflicts between epg data and schedules (only for 1.1 final lor later)

              foreach (Schedule oneschedule in Schedule.ListAll())
              {

                  LogDebug("Schedule=" + oneschedule.ProgramName, (int)LogSetting.DEBUG);
                  LogDebug("Schedule Start Time: " + oneschedule.StartTime.ToString(), (int)LogSetting.DEBUG);
                  LogDebug("Schedule End Time: " + oneschedule.EndTime.ToString(), (int)LogSetting.DEBUG);
                  LogDebug("Schedule Channel: " + oneschedule.IdChannel.ToString(), (int)LogSetting.DEBUG);
                  LogDebug("Schedule ID: " + oneschedule.IdSchedule.ToString(), (int)LogSetting.DEBUG);
                  bool EpgTimeChanged = false;
                  Program testprogram = null;
                  Schedule testschedule = oneschedule;
                  try
                  {
                      testprogram = Program.RetrieveByTitleTimesAndChannel(oneschedule.ProgramName, oneschedule.StartTime, oneschedule.EndTime, oneschedule.IdChannel);
                  }
                  catch
                  {
                      testprogram = null;
                  }

                  if (_DeleteTimeChanges == true)
                  {
                      // check for valid EPG entry

                      if (testprogram == null)
                      {
                          // check for changed time on same channel
                          IList<Program> alternativeprograms = null;
                          alternativeprograms = Program.RetrieveEveryTimeOnThisChannel(oneschedule.ProgramName, oneschedule.IdChannel);
                          if (alternativeprograms != null)
                          {
                              // search for closest program to original start time
                              double minimumdifferenz = 10000000.0; //start with largest value > 4 weeks
                              Program minprogram = null;
                              foreach (Program altprogram in alternativeprograms)
                              {
                                  LogDebug("Alternate EPG=" + altprogram.Title, (int)LogSetting.DEBUG);
                                  LogDebug("Alternate Start Time: " + altprogram.StartTime.ToString(), (int)LogSetting.DEBUG);
                                  LogDebug("Alternate End Time: " + altprogram.EndTime.ToString(), (int)LogSetting.DEBUG);

                                  double totalminutes = (altprogram.StartTime - oneschedule.StartTime).TotalMinutes;
                                  if (totalminutes < 0)
                                      totalminutes = totalminutes * (-1);



                                  LogDebug("Differenz to Schedule totalminutes=" + totalminutes.ToString(), (int)LogSetting.DEBUG);

                                  // int differenz = oneschedule.StartTime.Subtract(altprogram.StartTime).Minutes;
                                  //DateTime.Compare(oneschedule.StartTime, altprogram.StartTime);


                                  if (totalminutes < minimumdifferenz)
                                  {
                                      minimumdifferenz = totalminutes;
                                      minprogram = altprogram;
                                      
                                  }
                              }
                              LogDebug("Minimum Differenz to Schedule =  " + minimumdifferenz.ToString(), (int)LogSetting.DEBUG);


                              if (minprogram != null)
                              {
                                  //alternative program found
                                  Schedule schedule = layer.AddSchedule(minprogram.IdChannel, minprogram.Title, minprogram.StartTime, minprogram.EndTime, 0);
                                  schedule.PreRecordInterval = oneschedule.PreRecordInterval;
                                  schedule.PostRecordInterval = oneschedule.PostRecordInterval;
                                  schedule.ScheduleType = oneschedule.ScheduleType;
                                  schedule.Series = oneschedule.Series;
                                  schedule.KeepDate = oneschedule.KeepDate;
                                  schedule.KeepMethod = oneschedule.KeepMethod;
                                  schedule.RecommendedCard = oneschedule.RecommendedCard;
                                  schedule.Priority = oneschedule.Priority;
                                  schedule.Persist();
                                  LogDebug("", (int)LogSetting.INFO);
                                  LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                                  message = lng.TranslateString("Schedule {0} had no valid EPG data but could be corrected", 50, oneschedule.ProgramName);
                                  LogDebug("Scheduled New= " + schedule.ProgramName, (int)LogSetting.INFO);
                                  LogDebug("New Start Time= " + schedule.StartTime.ToString(), (int)LogSetting.INFO);
                                  LogDebug("New End Time= " + schedule.EndTime.ToString(), (int)LogSetting.INFO);
                                  LogDebug("Deleted= " + oneschedule.ProgramName, (int)LogSetting.INFO);
                                  LogDebug("Old Start Time= " + oneschedule.StartTime.ToString(), (int)LogSetting.INFO);
                                  LogDebug("OLd End Time= " + oneschedule.EndTime.ToString(), (int)LogSetting.INFO);
                                  LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);

                                  EpgTimeChanged = true;

                                  //new
                                  // try to change schedule messages if they exist from old data                                 
                                  try
                                  {
                                      int k;
                                      k = mymessage.GetTvMessageBySchedule(oneschedule,MessageType.Scheduled);
                                      LogDebug("try to change schedule message: k="+k.ToString(), (int)LogSetting.DEBUG);
                                      xmlmessage scheduledmessage = mymessage.GetTvMessageAtIndex(k);
                                      LogDebug("schedule message retrieved", (int)LogSetting.DEBUG);
                                      bool ok = mymessage.addmessage(schedule, scheduledmessage.message, MessageType.Scheduled, scheduledmessage.searchstring, (int)XmlMessages.MessageEvents.SCHEDULE_FOUND, scheduledmessage.tvwishid, string.Empty);
                                      LogDebug("ok=" + ok.ToString(), (int)LogSetting.DEBUG);

                                      if (ok)
                                        mymessage.DeleteTvMessageAt(k);

                                      /*
                                      updatedmessage.start = schedule.StartTime;
                                      updatedmessage.end = schedule.EndTime;
                                      mymessage.ReplaceTvMessageAtIndex(k, updatedmessage);*/
                                      LogDebug("new schedule message has been added", (int)LogSetting.DEBUG);
                                  }
                                  catch
                                  {
                                      LogDebug("schedule message could not be found", (int)LogSetting.DEBUG);
                                  }

                                  //add new email message if it did exist
                                  try
                                  {
                                      int k;
                                      k = mymessage.GetTvMessageBySchedule(oneschedule, MessageType.Emailed);
                                      LogDebug("try to change email message: k=" + k.ToString(), (int)LogSetting.DEBUG);
                                      xmlmessage emailmessage = mymessage.GetTvMessageAtIndex(k);
                                      LogDebug("email message retrieved", (int)LogSetting.DEBUG);
                                      bool ok = mymessage.addmessage(schedule, emailmessage.message, MessageType.Emailed, emailmessage.searchstring, (int)XmlMessages.MessageEvents.EMAIL_FOUND, emailmessage.tvwishid, string.Empty);
                                      LogDebug("ok=" + ok.ToString(), (int)LogSetting.DEBUG);
                                      if (ok)
                                        mymessage.DeleteTvMessageAt(k);

                                      LogDebug("new  email message has been added", (int)LogSetting.DEBUG);
                                  }
                                  catch
                                  {
                                      LogDebug("Email message could not be found", (int)LogSetting.DEBUG);
                                  }

                                  //end new change


                                  Log.Debug("Deleting schedule "+oneschedule.ProgramName+" with id="+oneschedule.IdSchedule.ToString());
                                  oneschedule.Delete();
                                  //delete old schedule if possible
                                  mymessage.addmessage(oneschedule, message, MessageType.Conflict, "", (int)XmlMessages.MessageEvents.NO_VALID_EPG, "-1", string.Empty);

                                  //reassign testprogram and testschedule
                                  testprogram = minprogram;
                                  testschedule = schedule;
                                  
                              }
                              else
                              {
                                  LogDebug("", (int)LogSetting.INFO);
                                  LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                                  message = lng.TranslateString("Schedule {0} has no valid EPG data - check your schedules for conflicts",51,oneschedule.ProgramName);
                                  LogDebug(message, (int)LogSetting.INFO);
                                  LogDebug("Schedule start date = " + oneschedule.StartTime.ToString() + "\n", (int)LogSetting.INFO);
                                  LogDebug("Schedule end date= " + oneschedule.EndTime.ToString() + "\n\n", (int)LogSetting.INFO);                                 
                                  LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                                  mymessage.addmessage(oneschedule, message, MessageType.Conflict, "", (int)XmlMessages.MessageEvents.NO_VALID_EPG, "-1", string.Empty);
                              }

                          }
                          else  //no alternative program does exist - email warning
                          {
                              LogDebug("", (int)LogSetting.INFO);
                              LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                              message = lng.TranslateString("Schedule {0} has no valid EPG data - check your schedules for conflicts",52,oneschedule.ProgramName);
                              LogDebug(message, (int)LogSetting.INFO);
                              LogDebug( "Schedule start date = " + oneschedule.StartTime.ToString() + "\n", (int)LogSetting.INFO);
                              LogDebug("Schedule end date= " + oneschedule.EndTime.ToString() + "\n\n", (int)LogSetting.INFO);                            
                              LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                              mymessage.addmessage(oneschedule, message, MessageType.Conflict, "", (int)XmlMessages.MessageEvents.NO_VALID_EPG, "-1", string.Empty);   //do not use -1 bug!!! 

                          }

                      }// else: Schedule does match to EPG data - check next schedule

                  }//end epg changes


                 

                  //try to reschedule if episode or description epg data and message have been changed, but only if tvwish still exists
                 
                  int i;
                  try
                  {
                      i = mymessage.GetTvMessageBySchedule(testschedule,MessageType.Scheduled); // new bugfix: must be type scheduled
                  }
                  catch
                  {
                      i = -1;
                  }

                  Log.Debug("message index i=" + i.ToString());

                  if ((i >= 0) && (testprogram != null))//scheduled message does exist for schedule and program does exist for schedule
                  {
                      try
                      {
                          xmlmessage testmessage = mymessage.GetTvMessageAtIndex(i);
                          Log.Debug("retriefed testmessage.title=" + testmessage.title);

                          //get tvwish (which can  cause exception for unvalid entries)
                          TvWish mytestwish = myTvWishes.RetrieveById(testmessage.tvwishid);
                          Log.Debug("retrieved mytestwish.name=" + mytestwish.name);

                          bool ok = episodeManagementEmptyString(testprogram.Description, testmessage.description, testprogram.EpisodePart, testmessage.EpisodePart, testprogram.EpisodeName, testmessage.EpisodeName,
                          testprogram.SeriesNum, testmessage.SeriesNum, testprogram.EpisodeNum, testmessage.EpisodeNum, mytestwish.b_episodecriteria_d, mytestwish.b_episodecriteria_n, mytestwish.b_episodecriteria_c);

                          if ((ok == false) || (EpgTimeChanged))//epg episode data or epg time did change  //new: always try to reschedule if epg time changed because simultanous change of EPG data cannot be tracked
                          {
                              //conflict message
                              testmessage.type = MessageType.Conflict.ToString();
                              LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                              message = lng.TranslateString("Epg data did change for Episode/Description or EPG Time changed- deleting current schedule and trying to reschedule",53);
                              LogDebug(message, (int)LogSetting.INFO);
                              LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);

                              testmessage.message = message;
                              mymessage.ReplaceTvMessageAtIndex(i, testmessage);

                              //delete schedule
                              Log.Debug("Deleting testschedule " + testschedule.ProgramName + " with id=" + testschedule.IdSchedule.ToString());
                              testschedule.Delete();

                              if (mytestwish.b_active == false)
                              {//need to run now again for inactive tvwish
                                  mytestwish.b_active = true;
                                  Log.Debug("Setting Tvwish active and running sql query");
                                  //search for schedules
                                  SqlQueryPrograms(ref mytestwish, i);

                                  mytestwish.b_active = false;
                                  myTvWishes.ReplaceAtIndex(i, mytestwish);
                              }
                          }


                      }
                      catch //ignore errors
                      {
                      }

                  }//end of episode changes

              } //end all schedules
#endif

              //Debug for foxbenw issue
              Log.Debug("Outputting all schedules before tvwish processing");
              foreach (Schedule oneschedule in Schedule.ListAll())
              {
                  mymessage.outputscheduletoresponse(oneschedule, (int)LogSetting.DEBUG);
              }
              Log.Debug("End of Outputting all schedules before tvwish processing");




              // start processing all TvWishes


              TvWish mywish = null;

              for (int i = 0; i < myTvWishes.ListAll().Count; i++)
              {
                  mywish = myTvWishes.GetAtIndex(i);

                  if (DEBUG)
                  {
                      Log.Debug("Before Query:");
                      myTvWishes.DebugTvWish(mywish);
                  }


                  if ((mywish.name == "") && (mywish.searchfor == "") && (mywish.episodename == "") && (mywish.episodenumber == "") && (mywish.episodepart == ""))
                  {
                      Log.Debug("Skipping tvwish with id=" + mywish.tvwishid.ToString());
                      continue;
                  }

                  languagetext = lng.TranslateString("Searching for {0}", 6,mywish.name);
                  labelmessage(languagetext, PipeCommands.StartEpg);

                  //remove leading and ending spaces of tv wish
                  Log.Debug("(before removing spaces: mywish.searchfor="+mywish.searchfor);
                  if (mywish.searchfor.Length > 0)
                  {
                    while (mywish.searchfor[0] == ' ')
                    {
                        mywish.searchfor = mywish.searchfor.Substring(1, mywish.searchfor.Length - 1);
                        if (mywish.searchfor.Length == 0)
                            break;
                    }
                    while (mywish.searchfor[mywish.searchfor.Length - 1] == ' ')
                    {
                        mywish.searchfor = mywish.searchfor.Substring(0, mywish.searchfor.Length - 1);
                        if (mywish.searchfor.Length == 0)
                            break;
                    }

                  }
                  Log.Debug("(after removing spaces: mywish.searchfor=" + mywish.searchfor);
                  //search for recordings and add messages only in email mode
                  DateTime start = DateTime.Now; //DEBUG PERFORMANCE

                  if (VIEW_ONLY_MODE == false) //recording first to identify existing recordings
                      SqlQueryRecordings(mywish, i);

                  DateTime end = DateTime.Now; //DEBUG PERFORMANCE
                  Log.Debug("SQL query recordings time=" + end.Subtract(start).TotalSeconds.ToString()); //DEBUG PERFORMANCE

                  //search for schedules

                  start = DateTime.Now; //DEBUG PERFORMANCE
                  SqlQueryPrograms(ref mywish, i);
                  end = DateTime.Now; //DEBUG PERFORMANCE
                  Log.Debug("SQL query programs time=" + end.Subtract(start).TotalSeconds.ToString()); //DEBUG PERFORMANCE

                  myTvWishes.ReplaceAtIndex(i, mywish);

                  /*
                  if (DEBUG)
                  {
                      Log.Debug("After Query:");
                      myTvWishes.DebugTvWish(mywish);
                  }*/

                  

              }  //end all Tvwishes




              //check for remaining schedule conflicts


#if(TV11 || TV12) //only for 1.1 final

              IList<Schedule> allschedules = Schedule.ListAll();
              IList<Card> cards = Card.ListAll();


              // initialize conflicting schedules and assign all existing schedules to cards
              List<Schedule> conflicts = new List<Schedule>();


              if (cards.Count != 0)
              {


                  //LogDebug("GetConflictingSchedules: Cards.Count =" + cards.Count.ToString(), (int)LogSetting.DEBUG);
#if (!MPTV2)
                  List<Schedule>[] cardSchedules = new List<Schedule>[cards.Count];
                  for (int i = 0; i < cards.Count; i++)
                  {
                      cardSchedules[i] = new List<Schedule>();
                  }
                  Schedule overlappingSchedule = null; 
#endif

                  bool ok = false;
                  Log.Debug("allschedules.count=" + allschedules.Count.ToString());
                  foreach (Schedule oneschedule in allschedules)
                  {
#if (MPTV2)
                      if (Schedule.GetConflictingSchedules(oneschedule).Count > 0)
                      {
                          ok = false;
                      }
                      else
                      {
                          ok = true;
                      }
                      Log.Debug("ok="+ok.ToString());
                      /*
                      Mediaportal.TV.Server.TVDatabase.Entities.Schedule onerawschedule = ServiceAgents.Instance.ScheduleServiceAgent.GetSchedule(oneschedule.IdSchedule);
                      List<Mediaportal.TV.Server.TVDatabase.Entities.Schedule> notViewableSchedules = new List<Mediaportal.TV.Server.TVDatabase.Entities.Schedule>();
                      ServiceAgents.Instance.ScheduleServiceAgent.GetConflictingSchedules(onerawschedule, out notViewableSchedules);
                      try
                      {
                          if (notViewableSchedules.Count > 0)
                          {
                              ok = false;
                          }
                          else
                          {
                              ok = true;
                          }
                      }
                      catch
                      {
                          ok = false;
                      }*/
#elif(TV110)
                      //mylayer.GetConflictingSchedules(schedule, out conflictingSchedules, out notViewableSchedules);
                      IList<Schedule> local_conflicts = GetConflictingSchedules(oneschedule);
                      try
                      {
                          if (local_conflicts.Count > 0)
                              ok = false;
                          else
                              ok = true;
                      }
                      catch
                      {
                          ok = false;
                      }
#else

                      ok = AssignSchedulesToCard(oneschedule, cardSchedules, out overlappingSchedule, DEBUG); //overlappingSchedule not used
#endif



                      if (ok == false)//conflict exists
                      {
                          LogDebug("", (int)LogSetting.INFO);
                          LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                          message = lng.TranslateString("Schedule conflict must be manually resolved",54);
                          LogDebug(message, (int)LogSetting.INFO);
                          LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                          outputscheduletoresponse(oneschedule, (int)LogSetting.INFO);
                          LogDebug("", (int)LogSetting.INFO);

                          mymessage.addmessage(oneschedule, message, MessageType.Conflict, "", (int)XmlMessages.MessageEvents.MANUAL_CONFLICT, "-1", string.Empty);  //Bug -1

                      }
                  }



              }
#endif


              //enable html email format
              if ((mymessage.EmailFormat.StartsWith("USE_HTML")) && (mymessage.EmailFormat.Length > 7))
              {
                  mymessage.EmailFormat = mymessage.EmailFormat.Substring(8);
                  HtmlFormat = true;
              }
              else
              {
                  HtmlFormat = false;
              }

              //Send all reply mails
              //update messages was done at the beginning
              mymessage.sortmessages(_sort, _descendingsort);
              mymessage.filtermessages(_filter_email, false, _filter_conflicts, _filter_scheduled, false, false, false);
              // old: mymessage.filtermessages(_filter_email,_filter_scheduled,_filter_conflicts,false,false,false);
              RESPONSE = mymessage.emailmessages(_emailonlynew);


              //store modified listviewdata and messages back

              //update counters before saving data
              myTvWishes.UpdateCounters(mymessage.ListAllTvMessages());

              //log messages
              mymessage.logmessages();

              string listviewstring = myTvWishes.SaveToString();

              //mymessage.logmessages(); //DEBUGONLY
              string dataString = mymessage.writexmlfile(false); //write xml file to string

              //LogDebug("Updated listview string: \n" + listviewstring, (int)LogSetting.DEBUG);
              if (VIEW_ONLY_MODE == true)
              {
                  myTvWishes.save_longsetting(listviewstring, "TvWishList_OnlyView");  //do never modify keywords must match MP plugin
                  myTvWishes.save_longsetting(dataString, "TvWishList_OnlyViewMessages");
              }
              else
              {
                  myTvWishes.save_longsetting(listviewstring, "TvWishList_ListView");   //do never modify keywords must match MP plugin
                  myTvWishes.save_longsetting(dataString, "TvWishList_ListViewMessages");
              }

              Log.Debug("RESPONSE="+RESPONSE);

              if ((_emailreply == true) && (RESPONSE != "") && (VIEW_ONLY_MODE == false))
              {
                  languagetext = lng.TranslateString("Sending email to {0}", 7, s_receiver);
                  LogDebug(languagetext, (int)LogSetting.DEBUG);
                  labelmessage(languagetext, PipeCommands.StartEpg);

                  // build the email message

                  /*
                  LogDebug("_TextBoxSmtpServer " + _TextBoxSmtpServer, (int)LogSetting.DEBUG);
                  LogDebug("_TextBoxUserName " + _TextBoxUserName, (int)LogSetting.DEBUG);
                  LogDebug("_TextBoxPassword " + _TextBoxPassword, (int)LogSetting.DEBUG);
                  LogDebug("_numericUpDownSmtpPort " + _numericUpDownSmtpPort.ToString(), (int)LogSetting.DEBUG);
                  LogDebug("_checkBoxSSL " + _checkBoxSSL.ToString(), (int)LogSetting.DEBUG);*/

                  if (_TextBoxSmtpServer == "")
                  {
                      LogDebug("Error: No Smtp Server defined - check and test configuration in TV Server Configuration", (int)LogSetting.ERROR);
                      languagetext = lng.TranslateString("Error: No Smtp Server defined", 8);
                      labelmessage(languagetext, PipeCommands.Error);
                      SearchEpgExit(); //includes setting BUSY = false;
                      return false;
                  }

                  /*
                  if ((_TextBoxUserName == "") && (_useCredentials))
                  {
                      LogDebug("Error: No user name defined - check and test configuration in TV Server Configuration", (int)LogSetting.ERROR);
                      
                      languagetext = lng.TranslateString("Error: No user name defined", 9);
                      labelmessage(languagetext, PipeCommands.Error);
                      SearchEpgExit(); //includes setting BUSY = false;
                      return false;
                  }

                  if ((_TextBoxPassword == "")&& (_useCredentials))
                  {
                      LogDebug("Error: No password defined - check and test configuration in TV Server Configuration", (int)LogSetting.ERROR);
                      
                      languagetext = lng.TranslateString("Error: No password defined", 10);
                      labelmessage(languagetext, PipeCommands.Error);
                      SearchEpgExit(); //includes setting BUSY = false;
                      return false;
                  }*/


                  if (_TextBoxSmtpEmailAddress == "")
                  {
                      _TextBoxSmtpEmailAddress = _TextBoxUserName;
                  }
                  if (s_receiver == "")
                  {
                      LogDebug("Error: No receiver emailaddress defined - check and test configuration in TV Server Configuration", (int)LogSetting.ERROR);
                      languagetext = lng.TranslateString("Error: No receiver emailaddress defined", 11);
                      labelmessage(languagetext, PipeCommands.Error);
                      SearchEpgExit(); //includes setting BUSY = false;
                      return false;
                  }

                  //load last settings and store it in providerstring [0]
                  setting = layer.GetSetting("TvWishList_Providers_0", "_Last Setting;;0;False;False;;0;False");
                  string[] array = setting.Value.Split(";".ToCharArray());
                  if (array.Length != 4)
                  {
                      LogDebug("TvWishList Error: Invalid provider string: " + setting.Value + "\n Count is " + array.Length, (int)LogSetting.ERROR);
                      languagetext = lng.TranslateString("Error: Invalid provider settings", 12);
                      labelmessage(languagetext, PipeCommands.Error);
                      SearchEpgExit(); //includes setting BUSY = false;
                      return false;
                  }

                  string ServerAddress = array[1];

                  if (ServerAddress == "")
                  {
                      LogDebug("Server address not specified - aborting email check", (int)LogSetting.ERROR);
                      languagetext = lng.TranslateString("Error: Server address not specified", 13);
                      labelmessage(languagetext, PipeCommands.Error);
                      SearchEpgExit(); //includes setting BUSY = false;
                      return false;
                  }

                  //wait for internet connection
                  bool InternetConnected = false;
                  for (int i = 1; i < 30; i++) //wait up to 300s and check every 10s
                  {
                      System.Threading.Thread.Sleep(10000); //sleep 10s to wait for internet connection after standby
                      //check for existing ip address

                      try
                      {
                          IPHostEntry hostIP = Dns.GetHostEntry(ServerAddress);
                          IPAddress[] addr = hostIP.AddressList;
                          LogDebug("POP3 Server exists", (int)LogSetting.DEBUG);
                          InternetConnected = true;
                          break;
                      }
                      catch
                      {//continue loop
                          LogDebug("Waiting for internet connection in iteration " + i.ToString(), (int)LogSetting.DEBUG);
                      }


                  }
                  if (InternetConnected == false)
                  {
                      LogDebug("Failed to get internet connection", (int)LogSetting.DEBUG);
                      languagetext = lng.TranslateString("Error: Failed to get internet connection to POP3 server", 14);
                      labelmessage(languagetext, PipeCommands.Error);
                      SearchEpgExit(); //includes setting BUSY = false;
                      return false;
                  }


                  int smtpport = 0;
                  try
                  {
                      smtpport = Convert.ToInt32(_numericUpDownSmtpPort);
                  }
                  catch
                  {
                      smtpport = 0;
                  }

                  if (smtpport == 0)
                  {
                      LogDebug("Error: No smtp port defined - check and test configuration in TV Server Configuration", (int)LogSetting.ERROR);
                      languagetext = lng.TranslateString("Error: No smtp port defined", 15);
                      labelmessage(languagetext, PipeCommands.Error);
                      SearchEpgExit(); //includes setting BUSY = false;
                      return false;
                  }

                  LogDebug("_TextBoxSmtpServer:" + _TextBoxSmtpServer, (int)LogSetting.DEBUG);
                  LogDebug("smtpport:" + smtpport, (int)LogSetting.DEBUG);
                  LogDebug("_checkBoxSSL:" + _checkBoxSSL.ToString(), (int)LogSetting.DEBUG);
                  LogDebug("_TextBoxUserName:"******"_TextBoxSmtpEmailAddress:" + _TextBoxSmtpEmailAddress, (int)LogSetting.DEBUG);


                  SendTvServerEmail sendobject = new SendTvServerEmail(_TextBoxSmtpServer, smtpport, _checkBoxSSL, _TextBoxUserName, _TextBoxPassword, _TextBoxSmtpEmailAddress);
                  sendobject.Debug = DEBUG;
                  sendobject.HtmlFormat = HtmlFormat;



                  LogDebug("Send reply mail to " + s_receiver + " at " + DateTime.Now.ToString(), (int)LogSetting.DEBUG);
                  LogDebug("Subject:" + s_subject, (int)LogSetting.DEBUG);
                  LogDebug(RESPONSE, (int)LogSetting.DEBUG);
                  LogDebug("End of mail", (int)LogSetting.DEBUG);

                  bool ok = sendobject.SendNewEmail(s_receiver, s_subject, RESPONSE);

                  if (ok == true)
                  {
                      LogDebug("Sending return emails completed", (int)LogSetting.DEBUG);
                      //System.Threading.Thread.Sleep(2000); //wait 2s
                      languagetext = lng.TranslateString("Sending return emails completed", 16);
                      labelmessage(languagetext, PipeCommands.StartEpg);
                  }
                  else
                  {
                      if (_TextBoxUserName == string.Empty)
                      {
                          LogDebug("Sending return emails failed - check the username", (int)LogSetting.ERROR);
                          languagetext = lng.TranslateString("Error: Sending return emails failed - check the username", 17);
                          labelmessage(languagetext, PipeCommands.Error);
                      }
                      else if (_TextBoxPassword == string.Empty)
                      {
                          LogDebug("Sending return emails failed - check the password", (int)LogSetting.ERROR);
                          languagetext = lng.TranslateString("Error: Sending return emails failed - check the password", 18);
                          labelmessage(languagetext, PipeCommands.Error);
                      }
                      else
                      {
                          LogDebug("Sending return emails failed", (int)LogSetting.ERROR);
                          languagetext = lng.TranslateString("Error: Sending return emails failed", 19);
                          labelmessage(languagetext, PipeCommands.Error);
                      }
                      SearchEpgExit(); //includes setting BUSY = false;
                      return false;

                  }



              }

              //System.Threading.Thread.Sleep(2000); //wait 2s
              languagetext = lng.TranslateString("Ready", 20);
              labelmessage(languagetext, PipeCommands.Ready);
              Log.Info("SearchEPG ended successfully");


          }
          catch (Exception exc)
          {
              Log.Error("Error:Exception in SearchEPG: "+exc.Message);
              string languagetext = lng.TranslateString("Fatal error - check the log file",24 );
              labelmessage(languagetext, PipeCommands.Error);
              SearchEpgExit(); //includes setting BUSY = false;
              return false;
          }

          SearchEpgExit(); //includes setting BUSY = false;

          
          return true;
      }