示例#1
0
        public WebBoolResult AddScheduleDetailed(int channelId, string title, DateTime startTime, DateTime endTime, WebScheduleType scheduleType, int preRecordInterval, int postRecordInterval, string directory, int priority)
        {
            try
            {
                Log.Debug("Adding schedule on channel {0} for {1}, {2} till {3}, type {4}", channelId, title, startTime, endTime, scheduleType);
                ScheduleRecordingType scheduleRecType = (ScheduleRecordingType)scheduleType;
                Schedule schedule = _tvBusiness.AddSchedule(channelId, title, startTime, endTime, (int)scheduleRecType);

                schedule.ScheduleType       = (int)scheduleRecType;
                schedule.PreRecordInterval  = preRecordInterval >= 0 ? preRecordInterval : Int32.Parse(_tvBusiness.GetSetting("preRecordInterval", "5").Value);
                schedule.PostRecordInterval = postRecordInterval >= 0 ? postRecordInterval : Int32.Parse(_tvBusiness.GetSetting("postRecordInterval", "5").Value);

                if (!String.IsNullOrEmpty(directory))
                {
                    schedule.Directory = directory;
                }

                if (priority >= 0)
                {
                    schedule.Priority = priority;
                }

                schedule.Persist();
                _tvControl.OnNewSchedule();
                return(true);
            }
            catch (Exception ex)
            {
                Log.Warn("Failed to add schedule", ex);
                return(false);
            }
        }
示例#2
0
 public override bool CreateScheduleByTime(IChannel channel, DateTime from, DateTime to, out ISchedule schedule)
 {
     TvDatabase.Schedule tvSchedule = _tvBusiness.AddSchedule(channel.ChannelId, "Manual", from, to, (int)ScheduleRecordingType.Once);
     tvSchedule.PreRecordInterval  = Int32.Parse(_tvBusiness.GetSetting("preRecordInterval", "5").Value);
     tvSchedule.PostRecordInterval = Int32.Parse(_tvBusiness.GetSetting("postRecordInterval", "5").Value);
     tvSchedule.Persist();
     _tvControl.OnNewSchedule();
     schedule = tvSchedule.ToSchedule();
     return(true);
 }
示例#3
0
        public bool CreateSchedule(IProgram program, ScheduleRecordingType recordingType, out ISchedule schedule)
        {
#if TVE3
            TvDatabase.Schedule tvSchedule = _tvBusiness.AddSchedule(program.ChannelId, program.Title, program.StartTime, program.EndTime, (int)recordingType);
            tvSchedule.ScheduleType       = (int)recordingType;
            tvSchedule.PreRecordInterval  = Int32.Parse(_tvBusiness.GetSetting("preRecordInterval", "5").Value);
            tvSchedule.PostRecordInterval = Int32.Parse(_tvBusiness.GetSetting("postRecordInterval", "5").Value);
            tvSchedule.Persist();
            _tvControl.OnNewSchedule();
            schedule = tvSchedule.ToSchedule();
            return(true);
#else
            IScheduleService scheduleService = GlobalServiceProvider.Instance.Get <IScheduleService>();
            Schedule         tvschedule      = ScheduleFactory.CreateSchedule(program.ChannelId, program.Title, program.StartTime, program.EndTime);
            tvschedule.PreRecordInterval  = ServiceAgents.Instance.SettingServiceAgent.GetValue("preRecordInterval", 5);
            tvschedule.PostRecordInterval = ServiceAgents.Instance.SettingServiceAgent.GetValue("postRecordInterval", 5);
            tvschedule.ScheduleType       = (int)recordingType;
            scheduleService.SaveSchedule(tvschedule);
            schedule = tvschedule.ToSchedule();
            return(true);
#endif
        }
示例#4
0
        public override async Task <AsyncResult <ISchedule> > CreateScheduleByTimeAsync(IChannel channel, DateTime from, DateTime to, ScheduleRecordingType recordingType)
        {
            await _initComplete.Task;

            TvBusinessLayer layer = new TvBusinessLayer();

            TvDatabase.Schedule tvSchedule = layer.AddSchedule(channel.ChannelId, "Manual", from, to, (int)recordingType);
            tvSchedule.PreRecordInterval  = Int32.Parse(layer.GetSetting("preRecordInterval", "5").Value);
            tvSchedule.PostRecordInterval = Int32.Parse(layer.GetSetting("postRecordInterval", "5").Value);
            tvSchedule.Persist();
            RemoteControl.Instance.OnNewSchedule();
            var schedule = tvSchedule.ToSchedule();

            return(new AsyncResult <ISchedule>(true, schedule));
        }
示例#5
0
        public override Task <AsyncResult <ISchedule> > CreateScheduleDetailedAsync(IChannel channel, string title, DateTime from, DateTime to, ScheduleRecordingType recordingType, int preRecordInterval, int postRecordInterval, string directory, int priority)
        {
            TvDatabase.Schedule tvSchedule = _tvBusiness.AddSchedule(channel.ChannelId, title, from, to, (int)recordingType);
            tvSchedule.PreRecordInterval  = preRecordInterval >= 0 ? preRecordInterval : Int32.Parse(_tvBusiness.GetSetting("preRecordInterval", "5").Value);
            tvSchedule.PostRecordInterval = postRecordInterval >= 0 ? postRecordInterval : Int32.Parse(_tvBusiness.GetSetting("postRecordInterval", "5").Value);
            if (!String.IsNullOrEmpty(directory))
            {
                tvSchedule.Directory = directory;
            }
            if (priority >= 0)
            {
                tvSchedule.Priority = priority;
            }
            tvSchedule.Persist();
            _tvControl.OnNewSchedule();
            var schedule = tvSchedule.ToSchedule();

            return(Task.FromResult(new AsyncResult <ISchedule>(true, schedule)));
        }
示例#6
0
        public override void handleCommand(string command, string[] arguments, ref TvControl.User me)
        {
            //TvEngine.PowerScheduler.WaitableTimer tveps;
            TvBusinessLayer layer     = new TvBusinessLayer();
            int             schedtype = (int)TvDatabase.ScheduleRecordingType.Once;
            Schedule        newSchedule;

            DateTime startTime = new DateTime(2009, 11, 23, 10, 00, 00);
            DateTime endTime   = new DateTime(2009, 11, 23, 11, 15, 00);

            try
            {
                newSchedule = layer.AddSchedule(32, "Marcel test", startTime, endTime, schedtype);
                newSchedule.Persist();
                Console.WriteLine("Schedule added: " + newSchedule.IdChannel.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        private void importButton_Click(object sender, EventArgs e)
        {
            bool importtv          = imCheckTvChannels.Checked;
            bool importtvgroups    = imCheckTvGroups.Checked;
            bool importradio       = imCheckRadioChannels.Checked;
            bool importradiogroups = imCheckRadioGroups.Checked;
            bool importschedules   = imCheckSchedules.Checked;

            openFileDialog1.CheckFileExists  = true;
            openFileDialog1.DefaultExt       = "xml";
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.Title            = "Load channels, channel groups and schedules";
            openFileDialog1.InitialDirectory = String.Format(@"{0}\Team MediaPortal\MediaPortal TV Server",
                                                             Environment.GetFolderPath(
                                                                 Environment.SpecialFolder.CommonApplicationData));
            openFileDialog1.FileName     = "export.xml";
            openFileDialog1.AddExtension = true;
            openFileDialog1.Multiselect  = false;
            if (openFileDialog1.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }
            NotifyForm dlg = new NotifyForm("Importing tv channels...", "This can take some time\n\nPlease be patient...");

            try
            {
                dlg.Show();
                dlg.WaitForDisplay();
                CountryCollection collection = new CountryCollection();
                TvBusinessLayer   layer      = new TvBusinessLayer();
                bool mergeChannels           = false; // every exported channel will be imported on its own.
                int  channelCount            = 0;
                int  scheduleCount           = 0;
                int  tvChannelGroupCount     = 0;
                int  radioChannelGroupCount  = 0;

                if (layer.Channels.Count > 0 && (importtv || importradio))
                {
                    // rtv: we could offer to set a "merge" property here so tuningdetails would be updated for existing channels.
                    if (
                        MessageBox.Show(
                            "Existing channels detected! \nIf you continue to import your old backup then all identically named channels will be treated equal - there is a risk of duplicate entries. \nDo you really want to go on?",
                            "Channels found", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel)
                    {
                        return;
                    }
                    else
                    {
                        mergeChannels = true;
                    }
                }

                XmlDocument doc = new XmlDocument();
                Log.Info("TvChannels: Trying to import channels from {0}", openFileDialog1.FileName);
                doc.Load(openFileDialog1.FileName);
                XmlNodeList channelList           = doc.SelectNodes("/tvserver/channels/channel");
                XmlNodeList tvChannelGroupList    = doc.SelectNodes("/tvserver/channelgroups/channelgroup");
                XmlNodeList radioChannelGroupList = doc.SelectNodes("/tvserver/radiochannelgroups/radiochannelgroup");
                XmlNodeList scheduleList          = doc.SelectNodes("/tvserver/schedules/schedule");
                if (channelList != null)
                {
                    foreach (XmlNode nodeChannel in channelList)
                    {
                        try
                        {
                            Channel     dbChannel;
                            XmlNodeList tuningList   = nodeChannel.SelectNodes("TuningDetails/tune");
                            XmlNodeList mappingList  = nodeChannel.SelectNodes("mappings/map");
                            bool        grabEpg      = (GetNodeAttribute(nodeChannel, "GrabEpg", "True") == "True");
                            bool        isRadio      = (GetNodeAttribute(nodeChannel, "IsRadio", "False") == "True");
                            bool        isTv         = (GetNodeAttribute(nodeChannel, "IsTv", "True") == "True");
                            DateTime    lastGrabTime = DateTime.ParseExact(GetNodeAttribute(nodeChannel, "LastGrabTime", "01.01.1900"),
                                                                           "yyyy-M-d H:m:s", CultureInfo.InvariantCulture);
                            int      sortOrder        = Int32.Parse(GetNodeAttribute(nodeChannel, "SortOrder", "0"));
                            int      timesWatched     = Int32.Parse(GetNodeAttribute(nodeChannel, "TimesWatched", "0"));
                            DateTime totalTimeWatched =
                                DateTime.ParseExact(GetNodeAttribute(nodeChannel, "TotalTimeWatched", "01.01.1900"), "yyyy-M-d H:m:s",
                                                    CultureInfo.InvariantCulture);
                            bool   visibileInGuide = (GetNodeAttribute(nodeChannel, "VisibleInGuide", "True") == "True");
                            bool   FreeToAir       = (GetNodeAttribute(nodeChannel, "FreeToAir", "True") == "True");
                            string displayName     = GetNodeAttribute(nodeChannel, "DisplayName", "Unkown");

                            // Only import TV or radio channels if the corresponding checkbox was checked
                            if ((isTv && !importtv) || (isRadio && !importradio))
                            {
                                continue;
                            }

                            channelCount++;

                            // rtv: since analog allows NOT to merge channels we need to take care of this. US users e.g. have multiple stations named "Sport" with different tuningdetails.
                            // using AddChannel would incorrectly "merge" these totally different channels.
                            // see this: http://forum.team-mediaportal.com/1-0-rc1-svn-builds-271/importing-exported-channel-list-groups-channels-39368/
                            Log.Info("TvChannels: Adding {0}. channel: {1}", channelCount, displayName);
                            IList <Channel> foundExistingChannels = layer.GetChannelsByName(displayName);
                            if (mergeChannels && (foundExistingChannels != null && foundExistingChannels.Count > 0))
                            {
                                dbChannel = foundExistingChannels[0];
                            }
                            else
                            {
                                dbChannel = layer.AddNewChannel(displayName);
                            }

                            dbChannel.GrabEpg          = grabEpg;
                            dbChannel.IsRadio          = isRadio;
                            dbChannel.IsTv             = isTv;
                            dbChannel.LastGrabTime     = lastGrabTime;
                            dbChannel.SortOrder        = sortOrder;
                            dbChannel.TimesWatched     = timesWatched;
                            dbChannel.TotalTimeWatched = totalTimeWatched;
                            dbChannel.VisibleInGuide   = visibileInGuide;
                            dbChannel.DisplayName      = displayName;
                            dbChannel.Persist();

                            //
                            // chemelli: When we import channels we need to add those to the "AllChannels" group
                            //
                            if (isTv)
                            {
                                layer.AddChannelToGroup(dbChannel, TvConstants.TvGroupNames.AllChannels);
                            }
                            else
                            {
                                layer.AddChannelToRadioGroup(dbChannel, TvConstants.RadioGroupNames.AllChannels);
                            }

                            foreach (XmlNode nodeMap in mappingList)
                            {
                                int     idCard   = Int32.Parse(nodeMap.Attributes["IdCard"].Value);
                                XmlNode nodeCard =
                                    doc.SelectSingleNode(String.Format("/tvserver/servers/server/cards/card[@IdCard={0}]", idCard));
                                Card dbCard = layer.GetCardByDevicePath(nodeCard.Attributes["DevicePath"].Value);
                                if (dbCard != null)
                                {
                                    layer.MapChannelToCard(dbCard, dbChannel, false);
                                }
                            }
                            foreach (XmlNode nodeTune in tuningList)
                            {
                                int    bandwidth          = Int32.Parse(nodeTune.Attributes["Bandwidth"].Value);
                                int    channelNumber      = Int32.Parse(nodeTune.Attributes["ChannelNumber"].Value);
                                int    channelType        = Int32.Parse(nodeTune.Attributes["ChannelType"].Value);
                                int    countryId          = Int32.Parse(nodeTune.Attributes["CountryId"].Value);
                                int    diseqc             = Int32.Parse(nodeTune.Attributes["Diseqc"].Value);
                                bool   fta                = (nodeTune.Attributes["FreeToAir"].Value == "True");
                                int    frequency          = Int32.Parse(nodeTune.Attributes["Frequency"].Value);
                                int    majorChannel       = Int32.Parse(nodeTune.Attributes["MajorChannel"].Value);
                                int    minorChannel       = Int32.Parse(nodeTune.Attributes["MinorChannel"].Value);
                                int    modulation         = Int32.Parse(nodeTune.Attributes["Modulation"].Value);
                                string name               = nodeTune.Attributes["Name"].Value;
                                int    networkId          = Int32.Parse(nodeTune.Attributes["NetworkId"].Value);
                                int    pmtPid             = Int32.Parse(nodeTune.Attributes["PmtPid"].Value);
                                int    polarisation       = Int32.Parse(nodeTune.Attributes["Polarisation"].Value);
                                string provider           = GetNodeAttribute(nodeTune, "Provider", "");
                                int    serviceId          = Int32.Parse(nodeTune.Attributes["ServiceId"].Value);
                                int    switchingFrequency = Int32.Parse(nodeTune.Attributes["SwitchingFrequency"].Value);
                                int    symbolrate         = Int32.Parse(nodeTune.Attributes["Symbolrate"].Value);
                                int    transportId        = Int32.Parse(nodeTune.Attributes["TransportId"].Value);
                                int    tuningSource       = Int32.Parse(GetNodeAttribute(nodeTune, "TuningSource", "0"));
                                int    videoSource        = Int32.Parse(GetNodeAttribute(nodeTune, "VideoSource", "0"));
                                int    audioSource        = Int32.Parse(GetNodeAttribute(nodeTune, "AudioSource", "0"));
                                bool   isVCRSignal        = (GetNodeAttribute(nodeChannel, "IsVCRSignal", "False") == "True");
                                int    SatIndex           = Int32.Parse(GetNodeAttribute(nodeTune, "SatIndex", "-1"));
                                int    InnerFecRate       = Int32.Parse(GetNodeAttribute(nodeTune, "InnerFecRate", "-1"));
                                int    band               = Int32.Parse(GetNodeAttribute(nodeTune, "Band", "0"));
                                int    pilot              = Int32.Parse(GetNodeAttribute(nodeTune, "Pilot", "-1"));
                                int    rollOff            = Int32.Parse(GetNodeAttribute(nodeTune, "RollOff", "-1"));
                                string url                = GetNodeAttribute(nodeTune, "Url", "");
                                int    bitrate            = Int32.Parse(GetNodeAttribute(nodeTune, "Bitrate", "0"));

                                switch (channelType)
                                {
                                case 0: //AnalogChannel
                                    AnalogChannel analogChannel = new AnalogChannel();
                                    analogChannel.ChannelNumber = channelNumber;
                                    analogChannel.Country       = collection.Countries[countryId];
                                    analogChannel.Frequency     = frequency;
                                    analogChannel.IsRadio       = isRadio;
                                    analogChannel.IsTv          = isTv;
                                    analogChannel.Name          = name;
                                    analogChannel.TunerSource   = (TunerInputType)tuningSource;
                                    analogChannel.AudioSource   = (AnalogChannel.AudioInputType)audioSource;
                                    analogChannel.VideoSource   = (AnalogChannel.VideoInputType)videoSource;
                                    analogChannel.IsVCRSignal   = isVCRSignal;
                                    layer.AddTuningDetails(dbChannel, analogChannel);
                                    Log.Info("TvChannels: Added tuning details for analog channel: {0} number: {1}", name, channelNumber);
                                    break;

                                case 1: //ATSCChannel
                                    ATSCChannel atscChannel = new ATSCChannel();
                                    atscChannel.MajorChannel    = majorChannel;
                                    atscChannel.MinorChannel    = minorChannel;
                                    atscChannel.PhysicalChannel = channelNumber;
                                    atscChannel.FreeToAir       = fta;
                                    atscChannel.Frequency       = frequency;
                                    atscChannel.IsRadio         = isRadio;
                                    atscChannel.IsTv            = isTv;
                                    atscChannel.Name            = name;
                                    atscChannel.NetworkId       = networkId;
                                    atscChannel.PmtPid          = pmtPid;
                                    atscChannel.Provider        = provider;
                                    atscChannel.ServiceId       = serviceId;
                                    atscChannel.TransportId     = transportId;
                                    atscChannel.ModulationType  = (ModulationType)modulation;
                                    layer.AddTuningDetails(dbChannel, atscChannel);
                                    Log.Info("TvChannels: Added tuning details for ATSC channel: {0} number: {1} provider: {2}", name,
                                             channelNumber, provider);
                                    break;

                                case 2: //DVBCChannel
                                    DVBCChannel dvbcChannel = new DVBCChannel();
                                    dvbcChannel.ModulationType       = (ModulationType)modulation;
                                    dvbcChannel.FreeToAir            = fta;
                                    dvbcChannel.Frequency            = frequency;
                                    dvbcChannel.IsRadio              = isRadio;
                                    dvbcChannel.IsTv                 = isTv;
                                    dvbcChannel.Name                 = name;
                                    dvbcChannel.NetworkId            = networkId;
                                    dvbcChannel.PmtPid               = pmtPid;
                                    dvbcChannel.Provider             = provider;
                                    dvbcChannel.ServiceId            = serviceId;
                                    dvbcChannel.SymbolRate           = symbolrate;
                                    dvbcChannel.TransportId          = transportId;
                                    dvbcChannel.LogicalChannelNumber = channelNumber;
                                    layer.AddTuningDetails(dbChannel, dvbcChannel);
                                    Log.Info("TvChannels: Added tuning details for DVB-C channel: {0} provider: {1}", name, provider);
                                    break;

                                case 3: //DVBSChannel
                                    DVBSChannel dvbsChannel = new DVBSChannel();
                                    dvbsChannel.DisEqc             = (DisEqcType)diseqc;
                                    dvbsChannel.Polarisation       = (Polarisation)polarisation;
                                    dvbsChannel.SwitchingFrequency = switchingFrequency;
                                    dvbsChannel.FreeToAir          = fta;
                                    dvbsChannel.Frequency          = frequency;
                                    dvbsChannel.IsRadio            = isRadio;
                                    dvbsChannel.IsTv                 = isTv;
                                    dvbsChannel.Name                 = name;
                                    dvbsChannel.NetworkId            = networkId;
                                    dvbsChannel.PmtPid               = pmtPid;
                                    dvbsChannel.Provider             = provider;
                                    dvbsChannel.ServiceId            = serviceId;
                                    dvbsChannel.SymbolRate           = symbolrate;
                                    dvbsChannel.TransportId          = transportId;
                                    dvbsChannel.SatelliteIndex       = SatIndex;
                                    dvbsChannel.ModulationType       = (ModulationType)modulation;
                                    dvbsChannel.InnerFecRate         = (BinaryConvolutionCodeRate)InnerFecRate;
                                    dvbsChannel.BandType             = (BandType)band;
                                    dvbsChannel.Pilot                = (Pilot)pilot;
                                    dvbsChannel.Rolloff              = (RollOff)rollOff;
                                    dvbsChannel.LogicalChannelNumber = channelNumber;
                                    layer.AddTuningDetails(dbChannel, dvbsChannel);
                                    Log.Info("TvChannels: Added tuning details for DVB-S channel: {0} provider: {1}", name, provider);
                                    break;

                                case 4: //DVBTChannel
                                    DVBTChannel dvbtChannel = new DVBTChannel();
                                    dvbtChannel.BandWidth            = bandwidth;
                                    dvbtChannel.FreeToAir            = fta;
                                    dvbtChannel.Frequency            = frequency;
                                    dvbtChannel.IsRadio              = isRadio;
                                    dvbtChannel.IsTv                 = isTv;
                                    dvbtChannel.Name                 = name;
                                    dvbtChannel.NetworkId            = networkId;
                                    dvbtChannel.PmtPid               = pmtPid;
                                    dvbtChannel.Provider             = provider;
                                    dvbtChannel.ServiceId            = serviceId;
                                    dvbtChannel.TransportId          = transportId;
                                    dvbtChannel.LogicalChannelNumber = channelNumber;
                                    layer.AddTuningDetails(dbChannel, dvbtChannel);
                                    Log.Info("TvChannels: Added tuning details for DVB-T channel: {0} provider: {1}", name, provider);
                                    break;

                                case 5: //Webstream
                                    layer.AddWebStreamTuningDetails(dbChannel, url, bitrate);
                                    break;

                                case 7: //DVBIPChannel
                                    DVBIPChannel dvbipChannel = new DVBIPChannel();
                                    dvbipChannel.FreeToAir            = fta;
                                    dvbipChannel.Frequency            = frequency;
                                    dvbipChannel.IsRadio              = isRadio;
                                    dvbipChannel.IsTv                 = isTv;
                                    dvbipChannel.LogicalChannelNumber = channelNumber;
                                    dvbipChannel.Name                 = name;
                                    dvbipChannel.NetworkId            = networkId;
                                    dvbipChannel.PmtPid               = pmtPid;
                                    dvbipChannel.Provider             = provider;
                                    dvbipChannel.ServiceId            = serviceId;
                                    dvbipChannel.TransportId          = transportId;
                                    dvbipChannel.Url = url;
                                    layer.AddTuningDetails(dbChannel, dvbipChannel);
                                    Log.Info("TvChannels: Added tuning details for DVB-IP channel: {0} provider: {1}", name, provider);
                                    break;
                                }
                            }
                        }
                        catch (Exception exc)
                        {
                            Log.Error("TvChannels: Failed to add channel - {0}", exc.Message);
                        }
                    }
                }

                if (tvChannelGroupList != null && importtvgroups)
                {
                    // Import tv channel groups
                    foreach (XmlNode nodeChannelGroup in tvChannelGroupList)
                    {
                        try
                        {
                            tvChannelGroupCount++;
                            string       groupName      = nodeChannelGroup.Attributes["GroupName"].Value;
                            int          groupSortOrder = Int32.Parse(nodeChannelGroup.Attributes["SortOrder"].Value);
                            ChannelGroup group          = null;
                            if (groupName == TvConstants.TvGroupNames.AllChannels)
                            {
                                group = layer.GetGroupByName(groupName) ??
                                        new ChannelGroup(groupName, groupSortOrder);
                            }
                            else
                            {
                                group = layer.GetGroupByName(groupName, groupSortOrder) ??
                                        new ChannelGroup(groupName, groupSortOrder);
                            }
                            group.Persist();
                            XmlNodeList mappingList = nodeChannelGroup.SelectNodes("mappings/map");
                            foreach (XmlNode nodeMap in mappingList)
                            {
                                IList <Channel> channels  = layer.GetChannelsByName(nodeMap.Attributes["ChannelName"].Value);
                                int             sortOrder = Int32.Parse(GetNodeAttribute(nodeMap, "SortOrder", "9999"));
                                if (channels != null && channels.Count > 0)
                                {
                                    Channel channel = channels[0];
                                    if (!channel.GroupNames.Contains(group.GroupName))
                                    {
                                        GroupMap map = new GroupMap(group.IdGroup, channel.IdChannel, sortOrder);
                                        map.Persist();
                                    }
                                    else
                                    {
                                        foreach (GroupMap map in channel.ReferringGroupMap())
                                        {
                                            if (map.IdGroup == group.IdGroup)
                                            {
                                                map.SortOrder = sortOrder;
                                                map.Persist();
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception exg)
                        {
                            Log.Error("TvChannels: Failed to add group - {0}", exg.Message);
                        }
                    }
                }

                if (radioChannelGroupList != null && importradiogroups)
                {
                    // Import radio channel groups
                    foreach (XmlNode nodeChannelGroup in radioChannelGroupList)
                    {
                        try
                        {
                            radioChannelGroupCount++;
                            string            groupName      = nodeChannelGroup.Attributes["GroupName"].Value;
                            int               groupSortOrder = Int32.Parse(nodeChannelGroup.Attributes["SortOrder"].Value);
                            RadioChannelGroup group          = layer.GetRadioChannelGroupByName(groupName) ??
                                                               new RadioChannelGroup(groupName, groupSortOrder);
                            group.Persist();
                            XmlNodeList mappingList = nodeChannelGroup.SelectNodes("mappings/map");
                            foreach (XmlNode nodeMap in mappingList)
                            {
                                IList <Channel> channels  = layer.GetChannelsByName(nodeMap.Attributes["ChannelName"].Value);
                                int             sortOrder = Int32.Parse(GetNodeAttribute(nodeMap, "SortOrder", "9999"));
                                if (channels != null && channels.Count > 0)
                                {
                                    Channel channel = channels[0];
                                    if (!channel.GroupNames.Contains(group.GroupName))
                                    {
                                        RadioGroupMap map = new RadioGroupMap(group.IdGroup, channel.IdChannel, sortOrder);
                                        map.Persist();
                                    }
                                    else
                                    {
                                        foreach (RadioGroupMap map in channel.ReferringRadioGroupMap())
                                        {
                                            if (map.IdGroup == group.IdGroup)
                                            {
                                                map.SortOrder = sortOrder;
                                                map.Persist();
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception exg)
                        {
                            Log.Error("Radio Channels: Failed to add group - {0}", exg.Message);
                        }
                    }
                }

                if (scheduleList != null && importschedules)
                {
                    // Import schedules
                    foreach (XmlNode nodeSchedule in scheduleList)
                    {
                        try
                        {
                            int idChannel = -1;

                            string programName = nodeSchedule.Attributes["ProgramName"].Value;
                            string channel     = nodeSchedule.Attributes["ChannelName"].Value;
                            if (!string.IsNullOrEmpty(channel))
                            {
                                IList <Channel> channels = layer.GetChannelsByName(channel);
                                if (channels != null && channels.Count > 0)
                                {
                                    idChannel = channels[0].IdChannel;
                                }
                            }
                            DateTime startTime = DateTime.ParseExact(nodeSchedule.Attributes["StartTime"].Value, "yyyy-M-d H:m:s",
                                                                     CultureInfo.InvariantCulture);
                            DateTime endTime = DateTime.ParseExact(nodeSchedule.Attributes["EndTime"].Value, "yyyy-M-d H:m:s",
                                                                   CultureInfo.InvariantCulture);
                            int      scheduleType = Int32.Parse(nodeSchedule.Attributes["ScheduleType"].Value);
                            Schedule schedule     = layer.AddSchedule(idChannel, programName, startTime, endTime, scheduleType);

                            schedule.ScheduleType = scheduleType;
                            schedule.KeepDate     = DateTime.ParseExact(nodeSchedule.Attributes["KeepDate"].Value, "yyyy-M-d H:m:s",
                                                                        CultureInfo.InvariantCulture);
                            schedule.PreRecordInterval  = Int32.Parse(nodeSchedule.Attributes["PreRecordInterval"].Value);
                            schedule.PostRecordInterval = Int32.Parse(nodeSchedule.Attributes["PostRecordInterval"].Value);
                            schedule.Priority           = Int32.Parse(nodeSchedule.Attributes["Priority"].Value);
                            schedule.Quality            = Int32.Parse(nodeSchedule.Attributes["Quality"].Value);
                            schedule.Directory          = nodeSchedule.Attributes["Directory"].Value;
                            schedule.KeepMethod         = Int32.Parse(nodeSchedule.Attributes["KeepMethod"].Value);
                            schedule.MaxAirings         = Int32.Parse(nodeSchedule.Attributes["MaxAirings"].Value);
                            schedule.RecommendedCard    = Int32.Parse(nodeSchedule.Attributes["RecommendedCard"].Value);
                            schedule.ScheduleType       = Int32.Parse(nodeSchedule.Attributes["ScheduleType"].Value);
                            schedule.Series             = (GetNodeAttribute(nodeSchedule, "Series", "False") == "True");
                            if (idChannel > -1)
                            {
                                schedule.Persist();
                                scheduleCount++;
                                Log.Info("TvChannels: Added schedule: {0} on channel: {1}", programName, channel);
                            }
                            else
                            {
                                Log.Info("TvChannels: Skipped schedule: {0} because the channel was unknown: {1}", programName, channel);
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Error("TvChannels: Failed to add schedule - {0}", ex.Message);
                        }
                    }
                }

                dlg.Close();
                Log.Info(
                    "TvChannels: Imported {0} channels, {1} tv channel groups, {2} radio channel groups and {3} schedules",
                    channelCount, tvChannelGroupCount, radioChannelGroupCount, scheduleCount);
                MessageBox.Show(
                    String.Format("Imported {0} channels, {1} tv channel groups, {2} radio channel groups and {3} schedules",
                                  channelCount, tvChannelGroupCount, radioChannelGroupCount, scheduleCount));
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Error while importing:\n\n" + ex + " " + ex.StackTrace);
            }
            finally
            {
                dlg.Close();
                OnSectionActivated();
            }
        }
示例#8
0
      public bool addsingleschedule(Program oneprogram, ref TvWish mywish, int counter)
      {

          /*
          string programName = oneprogram.Title;
          string description = oneprogram.Description;
          Int32 idChannel = oneprogram.IdChannel;
          DateTime startTime = oneprogram.StartTime;
          DateTime endTime = oneprogram.EndTime;
          */

          
          TvBusinessLayer layer = new TvBusinessLayer();

          
#if(TV100)
          IList allschedules = Schedule.ListAll();
#elif(TV101 || TV11 || TV12)
          IList<Schedule> allschedules = Schedule.ListAll();
#endif
          int allschedules_before = allschedules.Count;
         
          // add new schedule
          Schedule schedule = null;
           
          try
          {
              schedule = layer.AddSchedule(oneprogram.IdChannel, oneprogram.Title, oneprogram.StartTime, oneprogram.EndTime, 0);
              schedule.PreRecordInterval = mywish.i_prerecord;
              schedule.PostRecordInterval = mywish.i_postrecord;
              schedule.ScheduleType = 0;
              schedule.Series = mywish.b_series;

              if (mywish.useFolderName == lng.TranslateString("Automatic", 2853)) //automatic seriesname with MP management
              {

#if (TV12 || TV11)
                  if ((oneprogram.EpisodePart != string.Empty) || (oneprogram.EpisodeName != string.Empty) || (oneprogram.SeriesNum != string.Empty) || (oneprogram.EpisodeNum != string.Empty))
#else
                  if ((oneprogram.SeriesNum != string.Empty) || (oneprogram.EpisodeNum != string.Empty))
#endif


                  {
                      schedule.Series = true;
                      LogDebug("schedule.Series changed to true for automatic", (int)LogSetting.DEBUG);
                  }
                  else
                  {
                      schedule.Series = false;
                      LogDebug("schedule.Series changed to false for automatic", (int)LogSetting.DEBUG);
                  }
                  
              }
            
              LogDebug("schedule.Series=" + schedule.Series.ToString(), (int)LogSetting.DEBUG);

              schedule.KeepDate = mywish.D_keepuntil;
              schedule.KeepMethod = mywish.i_keepmethod;
              schedule.MaxAirings = mywish.i_keepepisodes;             
              schedule.RecommendedCard = mywish.i_recommendedcard;
              schedule.Priority = mywish.i_priority;
              schedule.Persist();

              
              
          }
          catch
          {
              LogDebug("", (int)LogSetting.INFO);
              LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
              message = lng.TranslateString("Failed to add program {0}",60,oneprogram.Title);
              LogDebug(message, (int)LogSetting.INFO);
              LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
              mymessage.addmessage(oneprogram, message, MessageType.Conflict, mywish.name, (int)XmlMessages.MessageEvents.FAILED_ADDING, mywish.tvwishid, string.Empty);
              return false;

          }
          LogDebug("schedule created", (int)LogSetting.DEBUG);
          if (schedule == null)
          {
              LogDebug("", (int)LogSetting.INFO);
              LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
              message = lng.TranslateString("Failed to create schedule for program {0}", 61, oneprogram.Title);
              LogDebug(message, (int)LogSetting.INFO);
              LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
              mymessage.addmessage(oneprogram, message, MessageType.Conflict, mywish.name, (int)XmlMessages.MessageEvents.FAILED_CREATE, mywish.tvwishid, string.Empty);
              return false;
          }

          #region schedule exists
          int allschedules_after = Schedule.ListAll().Count;
          LogDebug("allschedule", (int)LogSetting.DEBUG);
          if (allschedules_after == allschedules_before)  //fatal BUG fixed:     &&(VIEW_ONLY_MODE==false)  existing schedule can be deleted afterewards
          {
              LogDebug("", (int)LogSetting.INFO);
              LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
              message = lng.TranslateString("Program: {0} already scheduled", 62, oneprogram.Title);
              LogDebug(message, (int)LogSetting.INFO);
              LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);

              //  old: mymessage.addmessage(schedule, message, mywish.t_action, mywish.name, (int)XmlMessages.MessageEvents.SCHEDULE_FOUND, mywish.tvwishid);  //only added if no other message did exist before do not change
              mymessage.addmessage(schedule, message, MessageType.Conflict, mywish.name, (int)XmlMessages.MessageEvents.FAILED_ADDING, mywish.tvwishid, string.Empty);
              
              //outputscheduletoresponse(schedule, (int)LogSetting.INFO);
              return false;
          }
          #endregion schedule exists

          #region filter days
          LogDebug("start filterfunctions", (int)LogSetting.DEBUG);
          // filter function only use schedules starting after after_days and ending before before_days
          if ((mywish.i_afterdays > -1) && (mywish.i_beforedays > -1))
          {


              LogDebug("after_days= " + mywish.i_afterdays.ToString(), (int)LogSetting.DEBUG);
              LogDebug("before_days= " + mywish.i_beforedays.ToString(), (int)LogSetting.DEBUG);

              Int32 start_day = (int)oneprogram.StartTime.DayOfWeek;           
              //changed to usage of start time only !!!!!!!!!!!!!!!
              //Int32 end_day = (int)endTime.DayOfWeek;
              Int32 end_day = (int)oneprogram.StartTime.DayOfWeek;
              LogDebug("start_day= " + start_day, (int)LogSetting.DEBUG);
              LogDebug("end_day= " + end_day, (int)LogSetting.DEBUG);

              if (mywish.i_beforedays >= mywish.i_afterdays)
               /*
                      ------I-------------------------------------------------I------
               *          after                                            before
               *                          start              end
               *                          
               *    start >= after  &&  end <= before  &&  end >= start
               *       
               */
              
              { //use regular timeinterval from after_days till before_days
                  if ((start_day < mywish.i_afterdays) || (end_day > mywish.i_beforedays) || (end_day < start_day))

                  {
                      LogDebug("", (int)LogSetting.INFO);
                      LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                      message =lng.TranslateString("Skipping program {0} because it is not between {1} and {2}",63, oneprogram.Title, ((DayOfWeek)mywish.i_afterdays).ToString() , ((DayOfWeek)mywish.i_beforedays).ToString());                                       
                      LogDebug(message, (int)LogSetting.INFO);
                      LogDebug("\nStart=" + oneprogram.StartTime.ToString(), (int)LogSetting.INFO);    
                      LogDebug("End=" + oneprogram.EndTime.ToString(), (int)LogSetting.INFO);
                      LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);

                      mymessage.addmessage(oneprogram, message, MessageType.Conflict, mywish.name, (int)XmlMessages.MessageEvents.FILTER_MISMATCH, mywish.tvwishid, string.Empty);
                      schedule.Delete();
                      return false;
                  }

              }
              else if (mywish.i_beforedays < mywish.i_afterdays)
              /*                                    0:0
                      -----I-------------------------I------------------------I------
               *          after                                            before
               *          
               *     1)    I    start        end     I                        I               start >= after   &&   end >= after   &&   end >= start
               *          
               *          
               *     2)    I                         I       start     end    I                start <=before   &&   end <= before  &&   end >= start
               *     
               *     3)    I    start                I       end              I                start >= after   &&   end <= before  &&   end <= start
               *                          
               *    
               *       
               */
              {  //use timeinterval from before_days till after_days
                  bool doublecheck = false;
                  if (((start_day >= mywish.i_afterdays) && (end_day >= mywish.i_afterdays) && (end_day >= start_day)) || ((start_day <= mywish.i_beforedays) && (end_day <= mywish.i_beforedays) && (end_day >= start_day)) || ((start_day >= mywish.i_afterdays) && (end_day <= mywish.i_beforedays) && (end_day <= start_day)))
                  {
                      doublecheck = true;
                  }

                  if (((start_day < mywish.i_afterdays) || (end_day < mywish.i_afterdays) || (end_day < start_day)) && ((start_day > mywish.i_beforedays) || (end_day > mywish.i_beforedays) || (end_day < start_day)) && ((start_day < mywish.i_afterdays) || (end_day > mywish.i_beforedays)))
                  {
                      if (doublecheck == true)
                      {
                          LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.ERROR);
                          LogDebug("doublecheck failed check equation for days - please post logfile and contact huha", (int)LogSetting.ERROR);
                          LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.ERROR);
                      }
                      LogDebug("", (int)LogSetting.INFO);
                      LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                      message = lng.TranslateString("Skipping program {0} because it is not between {1} and {2}",63, oneprogram.Title, ((DayOfWeek)mywish.i_afterdays).ToString() , ((DayOfWeek)mywish.i_beforedays).ToString() );
                      LogDebug(message, (int)LogSetting.INFO);
                      LogDebug("\nStart=" + oneprogram.StartTime.ToString(), (int)LogSetting.INFO);                     
                      LogDebug("End=" + oneprogram.EndTime.ToString(), (int)LogSetting.INFO);
                      LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                      mymessage.addmessage(oneprogram, message, MessageType.Conflict, mywish.name, (int)XmlMessages.MessageEvents.FILTER_MISMATCH, mywish.tvwishid, string.Empty);
                      
                      schedule.Delete();
                      return false;
                  }
              }// if (before_days == after_days) do nothing
          }
          #endregion filter days

          #region filter time
          LogDebug("afterhours filter", (int)LogSetting.DEBUG);
          // filter function only use schedules starting after hh:mm and ending before hh:mm
          if ((mywish.i_aftertime > -1) && (mywish.i_beforetime > -1))
          {

              int start_time_minutes_all = oneprogram.StartTime.Hour * 60 + oneprogram.StartTime.Minute;
              int end_time_minutes_all = start_time_minutes_all;

              LogDebug("after_minutes= " + mywish.i_aftertime, (int)LogSetting.DEBUG);
              LogDebug("before_minutes= " + mywish.i_beforetime, (int)LogSetting.DEBUG);
              LogDebug("start_time_minutes= " + start_time_minutes_all, (int)LogSetting.DEBUG);
              LogDebug("end_time_minutes= " + end_time_minutes_all, (int)LogSetting.DEBUG);

              if (mywish.i_beforetime >= mywish.i_aftertime)
              /*
                      ------I-------------------------------------------------I------
               *          after                                            before
               *                          start              end
               *                          
               *    start >= after  &&  end <= before  &&  end >= start
               *       
               */
              { //use regular timeinterval from after_minutes till before_minutes
                  if ((start_time_minutes_all < mywish.i_aftertime) || (end_time_minutes_all > mywish.i_beforetime) || (end_time_minutes_all < start_time_minutes_all))  
                  
                  {

                      LogDebug("", (int)LogSetting.INFO);
                      LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                      message = lng.TranslateString("Skipping program {0} because it is not between {1} and {2}",64, oneprogram.Title, mywish.aftertime , mywish.beforetime);
                      message+="\nStart=" + oneprogram.StartTime.ToString();
                      LogDebug(message, (int)LogSetting.INFO);
                      LogDebug("End=" + oneprogram.EndTime.ToString(), (int)LogSetting.INFO);
                      LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                      mymessage.addmessage(oneprogram, message, MessageType.Conflict, mywish.name, (int)XmlMessages.MessageEvents.FILTER_MISMATCH, mywish.tvwishid, string.Empty);
                      
                      schedule.Delete();
                      return false;
                  }

              }
              else if (mywish.i_beforetime < mywish.i_aftertime)
              /*                                    0:0
                      -----I-------------------------I------------------------I------
               *          after                                            before
               *          
               *     1)    I    start        end     I                        I               start >= after   &&   end >= after   &&   end >= start
               *          
               *          
               *     2)    I                         I       start     end    I                start <=before   &&   end <= before  &&   end >= start
               *     
               *     3)    I    start                I       end              I                start >= after   &&   end <= before  &&   end <= start
               *                          
               *    
               *       
               */
              {  //use timeinterval from after_minutes till 23:59 and from 00:00 till before_minutes
                  bool doublecheck = false;
                  if (((start_time_minutes_all >= mywish.i_aftertime) && (end_time_minutes_all >= mywish.i_aftertime) && (end_time_minutes_all >= start_time_minutes_all)) || ((start_time_minutes_all <= mywish.i_beforetime) && (end_time_minutes_all <= mywish.i_beforetime) && (end_time_minutes_all >= start_time_minutes_all)) || ((start_time_minutes_all >= mywish.i_aftertime) && (end_time_minutes_all <= mywish.i_beforetime) && (end_time_minutes_all <= start_time_minutes_all)))
                  {
                      doublecheck = true;
                  }
                  //if (((start_time_minutes_all < mywish.i_aftertime) && (start_time_minutes_all > mywish.i_beforetime)) || ((end_time_minutes_all > mywish.i_beforetime) && (end_time_minutes_all < mywish.i_aftertime)))
                  if ( ( (start_time_minutes_all < mywish.i_aftertime)||(end_time_minutes_all < mywish.i_aftertime)||(end_time_minutes_all < start_time_minutes_all) ) && ( (start_time_minutes_all > mywish.i_beforetime)||(end_time_minutes_all > mywish.i_beforetime)||(end_time_minutes_all < start_time_minutes_all) ) && ( (start_time_minutes_all < mywish.i_aftertime)||(end_time_minutes_all > mywish.i_beforetime) ) )
                  {
                      if (doublecheck == true)
                      {
                          LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.ERROR);
                          LogDebug("doublecheck failed check equation for minutes - please post logfile and contact huha", (int)LogSetting.ERROR);
                          LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.ERROR);
                      }
                      LogDebug("", (int)LogSetting.INFO);
                      LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                      message = lng.TranslateString("Skipping program {0} because it is not between {1} and {2}",64,oneprogram.Title, mywish.aftertime , mywish.beforetime);
                      message+="\nStart=" + oneprogram.StartTime.ToString();
                      LogDebug(message, (int)LogSetting.INFO);
                      LogDebug("End=" + oneprogram.EndTime.ToString(), (int)LogSetting.INFO);
                      LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                      mymessage.addmessage(oneprogram, message, MessageType.Conflict, mywish.name, (int)XmlMessages.MessageEvents.FILTER_MISMATCH, mywish.tvwishid, string.Empty);                      
                      
                      schedule.Delete();
                      return false;
                  }
              }// if (before_minutes == after_minutes) do nothing
          }
          #endregion filter time

          #region within next hours
          LogDebug("start WithinNextHours", (int)LogSetting.DEBUG);
          if (mywish.i_withinNextHours > 0)
          {
              DateTime myNextDateTime = DateTime.Now;
              myNextDateTime = myNextDateTime.AddHours(mywish.i_withinNextHours);

              if (oneprogram.StartTime > myNextDateTime)
              {
                  LogDebug("", (int)LogSetting.INFO);
                  LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                  lng.TranslateString(message = "Skipping program {0} because it is not within the next {1} hours", 65, oneprogram.Title,mywish.i_withinNextHours.ToString());
                  message+="\nStart=" + oneprogram.StartTime.ToString();
                  LogDebug(message, (int)LogSetting.INFO);
                  LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                  mymessage.addmessage(oneprogram, message, MessageType.Conflict, mywish.name, (int)XmlMessages.MessageEvents.FILTER_MISMATCH, mywish.tvwishid, string.Empty);                      
                      
                  schedule.Delete();
                  return false;
              }
          }
          #endregion within next hours

          #region channelfilter
          LogDebug("start channelfilter", (int)LogSetting.DEBUG);
          //filter one specific channel
          if (mywish.channel != "")
          {
              Channel channel = null;
              string channelname = "";
              try  //must use try due to in bug in map.ReferencedChannelGroup() - caused exception before
              {
                  //search for TV group match
                  channel = schedule.ReferencedChannel();
                  channelname = channel.DisplayName;
              }
              catch
              {
                  LogDebug("", (int)LogSetting.INFO);
                  LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                  LogDebug("Error: could not retrieve channel name for program " + schedule.ProgramName, (int)LogSetting.INFO);
                  LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                  channelname = "";
              }
              LogDebug("channelname=" + channelname, (int)LogSetting.DEBUG);
              LogDebug("channelfilter=" + mywish.channel, (int)LogSetting.DEBUG);

              if ((mywish.channel != channelname)&&(mywish.channel != lng.TranslateString("Any",4100)))
              {
                  LogDebug("", (int)LogSetting.INFO);
                  LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                  message = lng.TranslateString("Skipping program {0} because it does not match the required channel filter {1}",66, oneprogram.Title, mywish.channel);                
                  LogDebug(message, (int)LogSetting.INFO);
                  LogDebug("\nChannelname=" + channelname, (int)LogSetting.INFO);
                  LogDebug("\nStart=" + oneprogram.StartTime.ToString(), (int)LogSetting.INFO);
                  LogDebug("End=" + oneprogram.EndTime.ToString(), (int)LogSetting.INFO);
                  LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                  mymessage.addmessage(oneprogram, message, MessageType.Conflict, mywish.name, (int)XmlMessages.MessageEvents.FILTER_MISMATCH, mywish.tvwishid, string.Empty);                      
                  
                  schedule.Delete();
                  return false;
              }
          }
          #endregion channelfilter

#if (TV12)
          #region filter episode part
          //filter episode part
          LogDebug("start filterepisode part", (int)LogSetting.DEBUG);
          if (mywish.episodepart != "")
          {
              if (mywish.episodepart.ToUpper() != oneprogram.EpisodePart.ToUpper())
              {
                  LogDebug("", (int)LogSetting.INFO);
                  LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                  message = lng.TranslateString("Skipping program {0} because it does not match the required episode part {1}",67,oneprogram.Title,mywish.episodepart);
                  LogDebug(message, (int)LogSetting.INFO);
                  LogDebug("\nStart=" + oneprogram.StartTime.ToString(), (int)LogSetting.INFO);
                  LogDebug("\nEnd=" + oneprogram.EndTime.ToString(), (int)LogSetting.INFO);
                  LogDebug("\nEpisodepart=" + oneprogram.EpisodePart, (int)LogSetting.INFO);                 
                  LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                  mymessage.addmessage(oneprogram, message, MessageType.Conflict, mywish.name, (int)XmlMessages.MessageEvents.FILTER_MISMATCH, mywish.tvwishid, string.Empty);

                  schedule.Delete();
                  return false;
              }
          }
          #endregion filter episode part

          #region filter episode name
          //filter episode name
          LogDebug("start filterepisodename", (int)LogSetting.DEBUG);
          if (mywish.episodename != "")
          {
              if (mywish.episodename.ToUpper() != oneprogram.EpisodeName.ToUpper())
              {
                  LogDebug("", (int)LogSetting.INFO);
                  LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                  message = lng.TranslateString("Skipping program {0} because it does not match the required episode name {1}",68, oneprogram.Title, mywish.episodename);
                  LogDebug(message, (int)LogSetting.INFO);
                  LogDebug("\nStart=" + oneprogram.StartTime.ToString(), (int)LogSetting.INFO);
                  LogDebug("\nEnd=" + oneprogram.EndTime.ToString(), (int)LogSetting.INFO);
                  LogDebug("\nEpisodeName=" + oneprogram.EpisodeName, (int)LogSetting.INFO);                
                  LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                  mymessage.addmessage(oneprogram, message, MessageType.Conflict, mywish.name, (int)XmlMessages.MessageEvents.FILTER_MISMATCH, mywish.tvwishid, string.Empty);
                  
                  schedule.Delete();
                  return false;
              }
          }
          #endregion filter episode name

          

          #region filter series number
          //filter series number
          LogDebug("start filterseries", (int)LogSetting.DEBUG);
          if ((mywish.seriesnumber != "") && (oneprogram.SeriesNum != ""))
          {
              try
              {
                  string[] tokens = oneprogram.SeriesNum.Split('\\','/');
                  Log.Debug("tokens[0]=" + tokens[0]);

                  int programNumber = -1;
                  int.TryParse(tokens[0], out programNumber);
                  Log.Debug("programNumber=" + programNumber.ToString());
                  //process expressions
                  bool expression = false;
                  string[] expressionArray = mywish.seriesnumber.Split(',');
                  foreach (string myExpression in expressionArray)
                  {
                      if (myExpression.Contains("-") == true)
                      {
                          string[] numberarray = myExpression.Split('-');
                          Log.Debug("numberarray.Length=" + numberarray.Length.ToString());
                          if (numberarray.Length == 2)
                          {
                              if ((numberarray[0] == string.Empty) || (numberarray[1] == string.Empty))
                              {  // a- or -a
                                  Log.Debug("a- or -a case");
                                  string temp = myExpression.Replace("-", string.Empty);

                                  int maxValue = 0;
                                  int.TryParse(temp, out maxValue);
                                  Log.Debug("Expression = " + mywish.seriesnumber + " maxValue=" + maxValue.ToString());
                                  if (programNumber <= maxValue)
                                  {
                                      expression = true;
                                      Log.Debug("Found match in expression " + myExpression);
                                      break;
                                  }    
                              }
                              else //a-b
                              {
                                  int minValue = 0;
                                  int.TryParse(numberarray[0], out minValue);
                                  Log.Debug("Expression = " + mywish.seriesnumber + " minValue=" + minValue.ToString());

                                  int maxValue = 0;
                                  int.TryParse(numberarray[1], out maxValue);
                                  Log.Debug("Expression = " + mywish.seriesnumber + " maxValue=" + maxValue.ToString());

                                  if ((programNumber >= minValue) && (programNumber <= maxValue))
                                  {
                                      expression = true;
                                      Log.Debug("Found match in expression " + myExpression);
                                      break;
                                  }
                              }
                          }
                          else
                          {
                              Log.Error("Ignoring invalid expression " + myExpression);
                              break;
                          }                        
                      }
                      else if (myExpression.Contains("+") == true)
                      {
                          string temp = myExpression.Replace("+", string.Empty);
                          int minValue = 0;
                          int.TryParse(temp, out minValue);
                          Log.Debug("Expression = " + mywish.seriesnumber + " minValue=" + minValue.ToString());
                          if (programNumber >= minValue)
                          {
                              expression = true;
                              Log.Debug("Found match in expression " + myExpression);
                              break;
                          }                          
                      }                      
                      else
                      {
                          int minValue = 0;
                          int.TryParse(myExpression, out minValue);
                          Log.Debug("Expression = " + mywish.seriesnumber + " intValue=" + minValue.ToString());
                          if (programNumber == minValue)
                          {
                              expression = true;
                              Log.Debug("Found match in expression " + myExpression);
                              break;
                          }                          
                      }
                  }

                  if (expression == false) //skip incorrect numbers
                  {
                      LogDebug("", (int)LogSetting.INFO);
                      LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                      message = lng.TranslateString("Skipping program {0} because it is not matching the required series number {1}",69, oneprogram.Title,mywish.seriesnumber);
                      LogDebug(message, (int)LogSetting.INFO);
                      LogDebug("Start=" + oneprogram.StartTime.ToString(), (int)LogSetting.INFO);
                      LogDebug("End=" + oneprogram.EndTime.ToString(), (int)LogSetting.INFO);
                      LogDebug("Seriesnumber=" + oneprogram.SeriesNum, (int)LogSetting.INFO);                     
                      LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                      mymessage.addmessage(oneprogram, message, MessageType.Conflict, mywish.name, (int)XmlMessages.MessageEvents.FILTER_MISMATCH, mywish.tvwishid, string.Empty);

                      schedule.Delete();
                      return false;
                  }
              }
              catch (Exception exc)
              {
                  //ignore errors
                  LogDebug("Exception in filter series number - Message=" + exc.Message, (int)LogSetting.ERROR);
                  string 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);
              }
          }
          #endregion filter series number


          #region filter episode number
          //filter episode number
          LogDebug("start filter episode number", (int)LogSetting.DEBUG);
          if ((mywish.episodenumber != "") && (oneprogram.EpisodeNum != ""))
          {
              try
              {
                  string[] tokens = oneprogram.EpisodeNum.Split('\\', '/');
                  Log.Debug("tokens[0]=" + tokens[0]);
                  int programNumber = 0;
                  int.TryParse(tokens[0], out programNumber);
                  Log.Debug("programNumber=" + programNumber.ToString());
                  //process expressions
                  bool expression = false;
                  string[] expressionArray = mywish.episodenumber.Split(',');
                  foreach (string myExpression in expressionArray)
                  {
                      if (myExpression.Contains("-") == true)
                      {
                          string[] numberarray = myExpression.Split('-');
                          if (numberarray.Length == 2)
                          {
                              if ((numberarray[0] == string.Empty) || (numberarray[1] == string.Empty))
                              {  // a- or -a
                                  Log.Debug("a- or -a case");
                                  string temp = myExpression.Replace("-", string.Empty);

                                  int maxValue = 0;
                                  int.TryParse(temp, out maxValue);
                                  Log.Debug("Expression = " + mywish.episodenumber + " maxValue=" + maxValue.ToString());
                                  if (programNumber <= maxValue)
                                  {
                                      expression = true;
                                      Log.Debug("Found match in expression " + myExpression);
                                      break;
                                  }
                              }
                              else //a-b
                              {
                                  int minValue = 0;
                                  int.TryParse(numberarray[0], out minValue);
                                  Log.Debug("Expression = " + mywish.episodenumber + " minValue=" + minValue.ToString());

                                  int maxValue = 0;
                                  int.TryParse(numberarray[1], out maxValue);
                                  Log.Debug("Expression = " + mywish.episodenumber + " maxValue=" + maxValue.ToString());

                                  if ((programNumber >= minValue) && (programNumber <= maxValue))
                                  {
                                      expression = true;
                                      Log.Debug("Found match in expression " + myExpression);
                                      break;
                                  }
                              }
                          }
                          else
                          {
                              Log.Error("Ignoring invalid expression " + myExpression);
                              break;
                          }
                      }                      
                      else if (myExpression.Contains("+") == true)
                      {
                          string temp = myExpression.Replace("+", string.Empty);
                          int minValue = 0;
                          int.TryParse(temp, out minValue);
                          Log.Debug("Expression = " + mywish.episodenumber + " intValue2=" + minValue.ToString());
                          if (programNumber >= minValue)
                          {                       
                              expression = true;
                              Log.Debug("Found match in expression " + myExpression);
                              break;
                          }
                      }
                      else
                      {
                          int minValue = 0;
                          int.TryParse(myExpression, out minValue);
                          Log.Debug("Expression = " + mywish.episodenumber + " intValue=" + minValue.ToString());
                          if (programNumber == minValue)
                          {
                              expression = true;
                              Log.Debug("Found match in expression " + myExpression);
                              break;
                          }
                      }
                  }

                  if (expression == false) //skip incorrect numbers
                  {
                      LogDebug("", (int)LogSetting.INFO);
                      LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                      message = lng.TranslateString("Skipping program {0} because it is not matching the required episode number {1}",70, oneprogram.Title, mywish.episodenumber);
                      LogDebug(message, (int)LogSetting.INFO);
                      LogDebug("Start=" + oneprogram.StartTime.ToString(), (int)LogSetting.INFO);
                      LogDebug("End=" + oneprogram.EndTime.ToString(), (int)LogSetting.INFO);
                      LogDebug("Episodenumber=" + oneprogram.EpisodeNum, (int)LogSetting.INFO);                     
                      LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                      mymessage.addmessage(oneprogram, message, MessageType.Conflict, mywish.name, (int)XmlMessages.MessageEvents.FILTER_MISMATCH, mywish.tvwishid, string.Empty);

                      schedule.Delete();
                      return false;
                  }
              }
              catch (Exception exc)
              {
                  //ignore errors
                  LogDebug("Exception in filter episode number - Message=" + exc.Message, (int)LogSetting.ERROR);
                  string 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);
              }
          }
          #endregion filter episode number


#endif

          
          //start checking for repeated and convert to upper
          string programNameRpt = ProcessEpgMarker(oneprogram.Title);
          string descriptionRpt = ProcessEpgMarker(oneprogram.Description);

          /*string programNameRpt = oneprogram.Title.ToUpper();
          try
          {
              programNameRpt = programNameRpt.Replace(_EpgMarker.ToUpper(), "");
          }
          catch
          {
              //ignore errors
          }
          string descriptionRpt = oneprogram.Description.ToUpper();
          
          try
          {
              descriptionRpt = descriptionRpt.Replace(_EpgMarker.ToUpper(), "");
          }
          catch
          {
              //ignore errors
          }*/

          
          LogDebug("programNameRpt=" + programNameRpt, (int)LogSetting.DEBUG);
          LogDebug("descriptionRpt=" + descriptionRpt, (int)LogSetting.DEBUG);

          #region recording exist
          //check for existing recording of same title and description 
          if (mywish.b_skip == true)
          {

              
              foreach (Recording onerecording in Recording.ListAll())
              {
                  Log.Debug("Recording=" + onerecording.Title);
                  string recordedTitle = ProcessEpgMarker(onerecording.Title);
                  string recordedDescription = ProcessEpgMarker(onerecording.Description);

                  /*string recordedTitle = onerecording.Title.ToUpper();
                  try
                  {
                      recordedTitle = recordedTitle.Replace(_EpgMarker.ToUpper(), "");
                  }
                  catch
                  {
                      //ignore errors
                  }
                  string recordedDescription = onerecording.Description.ToUpper();
                  try
                  {
                      recordedDescription = recordedDescription.Replace(_EpgMarker.ToUpper(), "");
                  }
                  catch
                  {
                      //ignore errors
                  }*/
                  //LogDebug("recordedDescription=" + recordedDescription, (int)LogSetting.DEBUG);
                  //LogDebug("descriptionRpt=" + descriptionRpt, (int)LogSetting.DEBUG);


                  if (recordedTitle != programNameRpt)
                      continue;        //new: added for speedup do not do episodemanagament if title does not match
                  

#if(TV100 || TV101)
                  //bool ok = episodeManagement(recordedDescription, descriptionRpt, "", "", "", "", "", oneprogram.SeriesNum, "", oneprogram.EpisodeNum, _episode_d, local_episode_n, local_episode_m);
                  bool ok = episodeManagement(recordedDescription, descriptionRpt, "", "", "", "", "", oneprogram.SeriesNum, "", oneprogram.EpisodeNum, mywish.b_episodecriteria_d, mywish.b_episodecriteria_n, mywish.b_episodecriteria_c);
                  
#elif(TV11)
                  //bool ok = episodeManagement(recordedDescription, descriptionRpt, onerecording.EpisodePart, oneprogram.EpisodePart, onerecording.EpisodeName, oneprogram.EpisodeName, onerecording.SeriesNum, oneprogram.SeriesNum, onerecording.EpisodeNum, oneprogram.EpisodeNum, _episode_d, local_episode_n, local_episode_m);
                  bool ok = episodeManagement(recordedDescription, descriptionRpt, onerecording.EpisodePart, oneprogram.EpisodePart, onerecording.EpisodeName, oneprogram.EpisodeName, onerecording.SeriesNum, oneprogram.SeriesNum, onerecording.EpisodeNum, oneprogram.EpisodeNum, mywish.b_episodecriteria_d, mywish.b_episodecriteria_n, mywish.b_episodecriteria_c);
                  
#elif(TV12)

                  //bool ok = episodeManagement(recordedDescription, descriptionRpt, onerecording.EpisodePart, oneprogram.EpisodePart, onerecording.EpisodeName, oneprogram.EpisodeName, onerecording.SeriesNum, oneprogram.SeriesNum, onerecording.EpisodeNum, oneprogram.EpisodeNum, mywish.b_episodecriteria_a, mywish.b_episodecriteria_d, mywish.b_episodecriteria_p, mywish.b_episodecriteria_n, mywish.b_episodecriteria_c);
                  bool ok = episodeManagement(recordedDescription, descriptionRpt, onerecording.EpisodePart, oneprogram.EpisodePart, onerecording.EpisodeName, oneprogram.EpisodeName, onerecording.SeriesNum, oneprogram.SeriesNum, onerecording.EpisodeNum, oneprogram.EpisodeNum, mywish.b_episodecriteria_d, mywish.b_episodecriteria_n, mywish.b_episodecriteria_c);
                  
#endif                    

                  if ((VIEW_ONLY_MODE == false) && (recordedTitle == programNameRpt) && (ok == true))
                  {
                      //check for preferred group

                      
                      bool old1 = IsChannelInGroup(onerecording.IdChannel, mywish.preferredgroup);
                      bool old2 = IsRadioChannelInGroup(onerecording.IdChannel, mywish.preferredgroup);
                      bool new1 = IsChannelInGroup(oneprogram.IdChannel, mywish.preferredgroup);
                      bool new2 = IsRadioChannelInGroup(oneprogram.IdChannel, mywish.preferredgroup);
                      bool expression = (!new1 && !new2) || old1 || old2;

                      Log.Debug("old1=" + old1.ToString(), (int)LogSetting.DEBUG);
                      Log.Debug("old2=" + old2.ToString(), (int)LogSetting.DEBUG);
                      Log.Debug("new1=" + new1.ToString(), (int)LogSetting.DEBUG);
                      Log.Debug("new2=" + new2.ToString(), (int)LogSetting.DEBUG);
                      Log.Debug("expression=" + expression.ToString(), (int)LogSetting.DEBUG);
                      Log.Debug("mywish.b_includeRecordings=" + mywish.b_includeRecordings.ToString(), (int)LogSetting.DEBUG);
                      
                      if (!mywish.b_includeRecordings || (mywish.preferredgroup==lng.TranslateString("All Channels",4104)) || expression)  //preferred group only if includeRecordings==true
                      {
                          LogDebug("", (int)LogSetting.INFO);
                          LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO); //do not send reply mail for already scheduled movies
                          message = lng.TranslateString("Program: {0} already recorded",71,oneprogram.Title);
                          LogDebug(message, (int)LogSetting.INFO);
                          LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                          outputscheduletoresponse(schedule, (int)LogSetting.INFO);
                          mymessage.addmessage(oneprogram, message, MessageType.Conflict, mywish.name, (int)XmlMessages.MessageEvents.ALREADY_RECORDED, mywish.tvwishid, string.Empty);
                  
                          schedule.Delete();
                          return false;
                      }
                      else
                      {
                          LogDebug("", (int)LogSetting.INFO);
                          LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO); //do not send reply mail for already scheduled movies
                          LogDebug("Warning: Program: " + oneprogram.Title + " already recorded, but not in preferred group - will try again", (int)LogSetting.INFO);
                          LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                                                   
                      }
                  }
              }
          }
          #endregion recording exist

          #region skip deleted entries in messages
          //skip deleted entries in messages if found again
          if ((mywish.b_skip == true) && (_skipDeleted == true))
          {
              foreach (xmlmessage singlemessage in mymessage.ListAllTvMessages())
              {
                  if (singlemessage.type == MessageType.Deleted.ToString())
                  {
                      string title = ProcessEpgMarker(singlemessage.title);
                      string messageDescription = ProcessEpgMarker(singlemessage.description);
                      
                      
                      /*string title = singlemessage.title.ToUpper();
                      try
                      {
                          title = title.Replace(_EpgMarker.ToUpper(), "");
                      }
                      catch
                      {
                          //ignore errors
                      }
                      string messageDescription = singlemessage.description.ToUpper();
                      try
                      {
                          messageDescription = messageDescription.Replace(_EpgMarker.ToUpper(), "");
                      }
                      catch
                      {
                          //ignore errors
                      }*/
                      //LogDebug("onerecording.Description=" + onerecording.Description, (int)LogSetting.DEBUG);
                      //LogDebug("onerecording.Description=" + onerecording.Description, (int)LogSetting.DEBUG);

                      if (title != programNameRpt)
                          continue;   //new. added for speedup - ignore if title does not match and do not do episodemanagement


#if(TV100 || TV101)
                      //bool ok = episodeManagement(messageDescription, descriptionRpt, "", "", "", "", "", oneprogram.SeriesNum, "", oneprogram.EpisodeNum, _episode_d, local_episode_n, local_episode_m);
                      bool ok = episodeManagement(messageDescription, descriptionRpt,  "", "", "", "", "", oneprogram.SeriesNum, "", oneprogram.EpisodeNum, mywish.b_episodecriteria_d, mywish.b_episodecriteria_n, mywish.b_episodecriteria_c);


#elif(TV11)
                      //bool ok = episodeManagement(messageDescription, descriptionRpt, singlemessage.EpisodePart, oneprogram.EpisodePart, singlemessage.EpisodeName, oneprogram.EpisodeName, singlemessage.SeriesNum, oneprogram.SeriesNum, singlemessage.EpisodeNum, oneprogram.EpisodeNum, _episode_d, local_episode_n, local_episode_m);
                      bool ok = episodeManagement(messageDescription, descriptionRpt, singlemessage.EpisodePart, oneprogram.EpisodePart, singlemessage.EpisodeName, oneprogram.EpisodeName, singlemessage.SeriesNum, oneprogram.SeriesNum, singlemessage.EpisodeNum, oneprogram.EpisodeNum, mywish.b_episodecriteria_d, mywish.b_episodecriteria_n, mywish.b_episodecriteria_c);

#elif(TV12)
                      //bool ok = episodeManagement(messageDescription, descriptionRpt, singlemessage.EpisodePart, oneprogram.EpisodePart, singlemessage.EpisodeName, oneprogram.EpisodeName, singlemessage.SeriesNum, oneprogram.SeriesNum, singlemessage.EpisodeNum, oneprogram.EpisodeNum, mywish.b_episodecriteria_a, mywish.b_episodecriteria_d, mywish.b_episodecriteria_p, mywish.b_episodecriteria_n, mywish.b_episodecriteria_c);
                      bool ok = episodeManagement(messageDescription, descriptionRpt, singlemessage.EpisodePart, oneprogram.EpisodePart, singlemessage.EpisodeName, oneprogram.EpisodeName, singlemessage.SeriesNum, oneprogram.SeriesNum, singlemessage.EpisodeNum, oneprogram.EpisodeNum, mywish.b_episodecriteria_d, mywish.b_episodecriteria_n, mywish.b_episodecriteria_c);

#endif

                      if ((VIEW_ONLY_MODE == false) && (title == programNameRpt) && (ok == true))
                      {
                          LogDebug("", (int)LogSetting.INFO);
                          LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO); //do not send reply mail for already scheduled movies
                          message = lng.TranslateString("Program: {0} has been already deleted and is skipped",72,oneprogram.Title);
                          LogDebug(message, (int)LogSetting.INFO);
                          LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                          outputscheduletoresponse(schedule, (int)LogSetting.INFO);
                          mymessage.addmessage(oneprogram, message, MessageType.Conflict, mywish.name, (int)XmlMessages.MessageEvents.REPEATED_FOUND, mywish.tvwishid, string.Empty);

                          schedule.Delete();
                          return false;
                      }
                  }

              }
          }//end skip deleted entries in messages if found again
          #endregion skip deleted entries in messages

          #region skip entries from the past
          //skip entries from the past
          if ((schedule.StartTime < DateTime.Now) && (schedule.ScheduleType == 0) && (VIEW_ONLY_MODE == false)) //old date, but only for type "ONCE" and Email/Recording mode  
          {

              LogDebug("", (int)LogSetting.INFO);
              LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
              message = lng.TranslateString("Start time of program {0} is in the past - will skip schedule",73,oneprogram.Title);
              LogDebug(message, (int)LogSetting.INFO);
              LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
              mymessage.addmessage(oneprogram, message, MessageType.Conflict, mywish.name, (int)XmlMessages.MessageEvents.FILTER_MISMATCH, mywish.tvwishid, string.Empty);

              schedule.Delete();
              return false;
          }
          #endregion skip entries from the past

          Schedule nonPreferredGroupSchedule = null;

          #region Check for repeated schedules (1st)
          if ((mywish.b_skip == true)&&(VIEW_ONLY_MODE == false)) // 1st
          {//Check for repeated schedules of same title and description
              foreach (Schedule myschedule in allschedules)
              {
                  string myscheduleProgramName = ProcessEpgMarker(myschedule.ProgramName);
                  

                  /*string myscheduleProgramName = myschedule.ProgramName.ToUpper();
                  try
                  {
                      myscheduleProgramName = myscheduleProgramName.Replace(_EpgMarker.ToUpper(), "");
                  }
                  catch
                  {
                      //ignore errors
                  }*/

                  //check for identical description
                  LogDebug("check for identical description", (int)LogSetting.DEBUG);
                  //retrieve Program from Schedule
#if(TV100 || TV101)
                          Program myprogram = Program.RetrieveByTitleAndTimes(myschedule.ProgramName, myschedule.StartTime, myschedule.EndTime);
#elif(TV11 || TV12)
                  Program myprogram = Program.RetrieveByTitleTimesAndChannel(myschedule.ProgramName, myschedule.StartTime, myschedule.EndTime, myschedule.IdChannel);
#endif

                  if (myprogram != null)
                  {
                      string myprogramDescription = ProcessEpgMarker(myprogram.Description);
                      /*string myprogramDescription = myprogram.Description.ToUpper();
                      try
                      {
                          myprogramDescription = myprogramDescription.Replace(_EpgMarker.ToUpper(), "");
                      }
                      catch
                      {
                          //ignore errors
                      }*/

                      //compare episodes


#if(TV100 || TV101)
                      bool ok = episodeManagement(myprogramDescription, descriptionRpt, "", "", "", "", myprogram.SeriesNum, oneprogram.SeriesNum, myprogram.EpisodeNum, oneprogram.EpisodeNum, mywish.b_episodecriteria_d, mywish.b_episodecriteria_n, mywish.b_episodecriteria_c);


#elif(TV11)
                      bool ok = episodeManagement(myprogramDescription, descriptionRpt, myprogram.EpisodePart, oneprogram.EpisodePart, myprogram.EpisodeName, oneprogram.EpisodeName, myprogram.SeriesNum, oneprogram.SeriesNum, myprogram.EpisodeNum, oneprogram.EpisodeNum, mywish.b_episodecriteria_d, mywish.b_episodecriteria_n, mywish.b_episodecriteria_c);

#elif(TV12)
                      bool ok = episodeManagement(myprogramDescription, descriptionRpt, myprogram.EpisodePart, oneprogram.EpisodePart, myprogram.EpisodeName, oneprogram.EpisodeName, myprogram.SeriesNum, oneprogram.SeriesNum, myprogram.EpisodeNum, oneprogram.EpisodeNum, mywish.b_episodecriteria_d, mywish.b_episodecriteria_n, mywish.b_episodecriteria_c);

#endif

                      if ((VIEW_ONLY_MODE == false) && (ok == true) && (myprogram.Title.ToUpper() == oneprogram.Title.ToUpper()) )  //old bug fixed need to compare title!!!
                      {//schedules do match -> repeated schedule  

                          Log.Debug("mywish.preferredgroup=" + mywish.preferredgroup, (int)LogSetting.DEBUG);

                          bool old1 = IsChannelInGroup(myschedule.IdChannel, mywish.preferredgroup);
                          bool old2 = IsRadioChannelInGroup(myschedule.IdChannel, mywish.preferredgroup);
                          bool new1 = IsChannelInGroup(oneprogram.IdChannel, mywish.preferredgroup);
                          bool new2 = IsRadioChannelInGroup(oneprogram.IdChannel, mywish.preferredgroup);
                          bool expression = (!new1 && !new2) || old1 || old2;

                          Log.Debug("old1=" + old1.ToString(), (int)LogSetting.DEBUG);
                          Log.Debug("old2=" + old2.ToString(), (int)LogSetting.DEBUG);
                          Log.Debug("new1=" + new1.ToString(), (int)LogSetting.DEBUG);
                          Log.Debug("new2=" + new2.ToString(), (int)LogSetting.DEBUG);
                          Log.Debug("expression=" + expression.ToString(), (int)LogSetting.DEBUG);

                          if ((mywish.preferredgroup == lng.TranslateString("All Channels",4104)) || expression)
                          {
                              LogDebug("", (int)LogSetting.INFO);
                              LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                              message = lng.TranslateString("Repeated Schedule {0} found  - skipping",74,oneprogram.Title);
                              LogDebug(message, (int)LogSetting.INFO);
                              LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                              LogDebug("Old Schedule:", (int)LogSetting.INFO);
                              outputscheduletoresponse(myschedule, (int)LogSetting.INFO);
                              mymessage.addmessage(oneprogram, message, MessageType.Conflict, mywish.name, (int)XmlMessages.MessageEvents.REPEATED_FOUND, mywish.tvwishid, string.Empty);

                              schedule.Delete();
                              return false;
                          }
                          else
                          {
                              LogDebug("", (int)LogSetting.INFO);
                              LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                              LogDebug("Repeated Schedule " + oneprogram.Title + " found with same title, but not in preferred group - will try again", (int)LogSetting.INFO);
                              LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);


                              if ((_automaticrecording == true) && (mywish.action != lng.TranslateString("Email",2701)) && (mywish.action != lng.TranslateString("View",2703))) //schedule new recording
                              {
                                  
                                  Log.Debug("Storing as nonPreferredGroupSchedule old schedule not in preferred group");
                                  nonPreferredGroupSchedule = myschedule;  //will be deleted later
                                  
                              }
                          }

                      }//end schedules do match -> repeated schedule

                  }//end (myprogram != null)

              }//end all schedules loop
              
          }//end skip repeated schedules
          #endregion Check for repeated schedules (1st)

          #region Check For Conflicts  (2nd)
          // Check for conflicts (2nd)
          LogDebug("check for conflicts", (int)LogSetting.DEBUG);
          if ((VIEW_ONLY_MODE == false)&& (_scheduleconflicts == false))  //scheduleconflicts = true will trigger priority processing
          {
              
#if(MPTV2)
              IList<Schedule> conflict_schedules = Schedule.GetConflictingSchedules(schedule);
#else
              IList<Schedule> conflict_schedules = GetAllConflictSchedules(schedule, nonPreferredGroupSchedule);
#endif
              int conflict_count = conflict_schedules.Count;

              if (conflict_count > 0) 
              {
                  LogDebug("", (int)LogSetting.INFO);
                  LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO); //do not send reply mail for already scheduled movies
                  message = lng.TranslateString("Program: {0} has conflicts and will not be scheduled",75,oneprogram.Title);
                  LogDebug(message, (int)LogSetting.INFO);
                  LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                  outputscheduletoresponse(schedule, (int)LogSetting.INFO);
                  //conflictprograms.Add(oneprogram);
                  mymessage.addmessage(oneprogram, message, MessageType.Conflict, mywish.name, (int)XmlMessages.MessageEvents.MANUAL_CONFLICT, mywish.tvwishid, string.Empty);

                  Log.Debug("Schedule number before deleting"+Schedule.ListAll().Count.ToString());

                  schedule.Delete();

                  
                  Log.Debug("Schedule number after deleting" + Schedule.ListAll().Count.ToString());

                  return false;
              }
          }
          #endregion Check For Conflicts  (2nd)

          #region PriorityProcessing (3rd)
          //priority processing 3rd if schedule conflicts==true, must come after conflicts
          LogDebug("start priorityprocessing", (int)LogSetting.DEBUG);
          if ((_scheduleconflicts == true) && (_automaticrecording == true) && (mywish.action != lng.TranslateString("Email", 2701)) && (VIEW_ONLY_MODE == false)) 
          {
              
              IList<Schedule> allconflicts = GetAllConflictSchedules(schedule, nonPreferredGroupSchedule);

              LogDebug("allconflicts.Count=" + allconflicts.Count.ToString(), (int)LogSetting.DEBUG);
              while (allconflicts.Count > 0)  //loop until all conflicts are resolved
              {
                  bool foundflag = false;
                  foreach (Schedule conflictschedule in allconflicts)  //only one conflict will be removed (break statements prevents complete loop)
                  {
                      LogDebug("schedule.Priority=" + schedule.Priority.ToString(), (int)LogSetting.DEBUG);
                      LogDebug("conflictschedule.ProgramName=" + conflictschedule.ProgramName.ToString(), (int)LogSetting.DEBUG);
                      LogDebug("conflictschedule.Priority=" + conflictschedule.Priority.ToString(), (int)LogSetting.DEBUG);

                      if (conflictschedule.Priority < schedule.Priority)
                      {
                          //delete conflicting schedule and send message
                          LogDebug("", (int)LogSetting.INFO);
                          LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                          message = lng.TranslateString("Deleting schedule {0} because of lower priority",76,conflictschedule.ProgramName);
                          LogDebug(message, (int)LogSetting.INFO);
                          LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                          mymessage.addmessage(conflictschedule, message, MessageType.Conflict, mywish.name, (int)XmlMessages.MessageEvents.LOW_PRIORITY_DELETE, mywish.tvwishid, string.Empty);


                          

                          //checked above to avoid email or viewonly
                          Log.Debug("Changing message for old schedule to conflict");
                          int index = mymessage.GetTvMessageBySchedule(conflictschedule,MessageType.Scheduled);
                          if (index >= 0)
                          {
                              xmlmessage changemessage = mymessage.GetTvMessageAtIndex(index);
                              changemessage.message = "Deleting schedule with lower priority";
                              changemessage.type = MessageType.Conflict.ToString();
                              mymessage.ReplaceTvMessageAtIndex(index, changemessage);
                          }

                          Log.Debug("Deleting schedule with lower priority");
                          conflictschedule.Delete();
                          mywish.i_scheduled--;
                          foundflag = true;
                          break; //only one conflict deletion should fix it
                      }
                  }//end loop all conflicting schedules for priority processing
                  if (foundflag == false) //skip schedule due to not high enough priority
                  {
                      LogDebug("", (int)LogSetting.INFO);
                      LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                      message = lng.TranslateString("Schedule {0} has not enough priority to delete conflicts - skipping",77,oneprogram.Title);
                      LogDebug(message, (int)LogSetting.INFO);
                      LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.INFO);
                      outputprogramresponse(oneprogram, (int)LogSetting.INFO);

                      mymessage.addmessage(oneprogram, message, MessageType.Conflict, mywish.name, (int)XmlMessages.MessageEvents.LOW_PRIORITY_DELETE, mywish.tvwishid, string.Empty);

                      schedule.Delete();
                      return false;
                  }
                  
                  //check for additional conflicts and rerun loop
                  allconflicts = GetAllConflictSchedules(schedule, nonPreferredGroupSchedule);
                  
              }//end conflicts do exist for priority processing  while (allconflicts.Count > 0)

          } //end priority processing
          #endregion PriorityProcessing (3rd)

          #region delete nonpreferred group schedule (4th)
          //delete nonpreferred schedule as it is now sure that the preferred group schedule will be scheduled
          if (nonPreferredGroupSchedule != null)
          {
              //delete message for nonpreferred group schedule
              Log.Debug("Changing message for old schedule to conflict");
              int index = mymessage.GetTvMessageBySchedule(nonPreferredGroupSchedule,MessageType.Scheduled);
              if (index >= 0)
              {
                  xmlmessage changemessage = mymessage.GetTvMessageAtIndex(index);
                  changemessage.message = lng.TranslateString("Better Schedule Found In Preferred Group",78);
                  changemessage.type = MessageType.Conflict.ToString();
                  mymessage.ReplaceTvMessageAtIndex(index, changemessage);
              }

              LogDebug("Deleting nonPreferredGroupSchedule title=" + nonPreferredGroupSchedule.ProgramName, (int)LogSetting.DEBUG);
              nonPreferredGroupSchedule.Delete();
              mywish.i_scheduled--;

          }
          #endregion delete nonpreferred schedule (4th)

          //do not insert new code here 

          #region success: schedule and/or email
          //success: schedule and/or email         
          if ((_automaticrecording == true) && (mywish.action != lng.TranslateString("Email", 2701)) && (mywish.action != lng.TranslateString("View", 2703))) //schedule new recording
          {
              LogDebug("", (int)LogSetting.INFO);
              LogDebug("*******************************************************************************\n", (int)LogSetting.INFO);
              message = lng.TranslateString("TvWishList found program from Tv Wish [{0}]: {1}\nTvWishList did schedule the program", 79, (counter + 1).ToString(), mywish.name);
              LogDebug(message, (int)LogSetting.INFO);
              LogDebug("*******************************************************************************\n", (int)LogSetting.INFO);
              


              

              mymessage.addmessage(schedule, message, mywish.t_action, mywish.name, (int)XmlMessages.MessageEvents.SCHEDULE_FOUND, mywish.tvwishid, string.Empty);
              outputscheduletoresponse(schedule, (int)LogSetting.DEBUG);
              LogDebug("End of new schedule", (int)LogSetting.INFO);
              //mywish.i_scheduled++;


              if (mywish.i_keepuntil > 0) //handle days for keepuntil and convert back to date after schedule has been found
              {
                  schedule.KeepDate = DateTime.Now.AddDays(mywish.i_keepuntil);
                  schedule.Persist();
              }


              if (mywish.b_useFoldername)  //add folder move of recording
              {
                  if ((schedule.ProgramName.Contains(@"\")) || (mywish.name.Contains(@"\")))
                  {
                      LogDebug("", (int)LogSetting.ADDRESPONSE);
                      LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.ADDRESPONSE);
                      LogDebug("Failed to add folder " + schedule.ProgramName + " because program and name must not contain \" \\\"", (int)LogSetting.ADDRESPONSE);
                      LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.ADDRESPONSE);
                  }
                  else
                  {

                      //create new xml file for renaming recorded filename
                      try
                      {
                          XmlDocument xmlDoc = new XmlDocument();
                          string filename = TV_USER_FOLDER + @"\TvWishList\" + FileRenameXML;

                          try
                          {
                              xmlDoc.Load(filename);
                          }
                          catch (System.IO.FileNotFoundException)
                          {
                              XmlTextWriter xmlWriter = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
                              xmlWriter.Formatting = Formatting.Indented;
                              xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
                              xmlWriter.WriteStartElement("AllJobs");
                              xmlWriter.Close();
                              xmlDoc.Load(filename);
                          }

                          XmlNode alljobs = xmlDoc.DocumentElement;
                          //XmlNode alljobs = xmlDoc.SelectSingleNode("/AllJobs");
                          XmlNode node = xmlDoc.CreateElement("Job");
                          AddAttribute(node, "ScheduleName", schedule.ProgramName);
                          AddAttribute(node, "Folder", mywish.name);

                          //episode mode with separate folder has been disabled above already

                          Double number = Convert.ToDouble(schedule.PreRecordInterval) * (-1);
                          DateTime absoluteStartTime = oneprogram.StartTime.AddMinutes(number);
                          AddAttribute(node, "Start", absoluteStartTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture));
                          LogDebug("Start=" + absoluteStartTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture), (int)LogSetting.DEBUG);

                          number = Convert.ToDouble(schedule.PostRecordInterval);
                          DateTime absoluteEndTime = oneprogram.EndTime.AddMinutes(number);
                          AddAttribute(node, "End", absoluteEndTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture));
                          LogDebug("End=" + absoluteEndTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture), (int)LogSetting.DEBUG);

                          AddAttribute(node, "idChannel", schedule.IdChannel.ToString());

                          alljobs.AppendChild(node);


                          xmlDoc.Save(filename);
                      }
                      catch (Exception exc)
                      {
                          LogDebug("Could not update " + TV_USER_FOLDER + @"\TvWishList\" + FileRenameXML, (int)LogSetting.ERROR);
                          LogDebug("Exception message was " + exc.Message, (int)LogSetting.ERROR);
                          string 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);
                      }
                  }
              }


          }
          else
          {
              if (mymessage.existsmessage(schedule, mywish.t_action) == false)  //new reminder - send email
              {
                  LogDebug("", (int)LogSetting.INFO);
                  LogDebug("*******************************************************************************\n", (int)LogSetting.INFO);
                  message = lng.TranslateString("TvWishList found program from Tv Wish [{0}]: {1}\nTvWishList did not schedule but is reminding you of the program", 80, (counter + 1).ToString(), mywish.name);
                  LogDebug("*******************************************************************************\n", (int)LogSetting.INFO);
                  LogDebug(message, (int)LogSetting.INFO);
                  schedule.ScheduleType = 9;  //bug in 1.2.0.15
                  mymessage.addmessage(schedule, message, mywish.t_action, mywish.name, (int)XmlMessages.MessageEvents.EMAIL_FOUND, mywish.tvwishid, string.Empty);
                  outputscheduletoresponse(schedule, (int)LogSetting.DEBUG);
                  schedule.ScheduleType = 0; //end bug 1.2.0.15
                  LogDebug("End of reminder a", (int)LogSetting.DEBUG);
                  schedule.Delete();
                  //mywish.i_scheduled++;

              }
              else //message does exist already - do not send email but return
              {
                  LogDebug("", (int)LogSetting.DEBUG);
                  LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.DEBUG);
                  LogDebug("Message does exist already - not included in email", (int)LogSetting.DEBUG);
                  LogDebug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", (int)LogSetting.DEBUG);
                  outputscheduletoresponse(schedule, (int)LogSetting.DEBUG);
                  LogDebug("End of old reminder b", (int)LogSetting.DEBUG);
                  schedule.Delete();

              }
          }
          #endregion success: schedule and/or email

          return true;
      }
示例#9
0
      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;
      }