/[xmltv_parser]/trunk/xmltv_parser/main.cs
ViewVC logotype

Diff of /trunk/xmltv_parser/main.cs

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

--- trunk/xmltv_parser/main.cs	2013/03/10 10:34:07	100
+++ trunk/xmltv_parser/main.cs	2013/03/22 16:41:42	248
@@ -1,5 +1,6 @@
-//#define DISABLE_RELEASE_MODE_KLOGLEVEL_DEBUG // when defined will turn off kLogLevel_Debug messages, in release mode
+#define DISABLE_RELEASE_MODE_KLOGLEVEL_DEBUG // when defined will turn off kLogLevel_Debug messages, in release mode
 //#define DISABLE_DEBUG_MODE_KLOGLEVEL_VERBOSE_DEBUG // when defined will turn off kLogLevel_VerboseDebug message, in debug mode
+//#define USE_DYNAMIC_SORTING_FILTERING_CONTROLS // when defined will setup dynamic sorting and filtering controls for XMLTV Data
 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
@@ -15,20 +16,52 @@
 using System.Runtime.Serialization.Formatters.Binary;
 using System.Threading;
 using System.Diagnostics;
+using System.Xml.Linq;
 
 namespace xmltv_parser
 {
 
     public partial class main : Form
     {
+        const long MAX_LOG_FILESIZE_IN_BYTES = 250000; //250kb max
+        void TruncateLogFile(FileInfo log_file)
+        {
+            if (!log_file.Exists)
+            {
+                gLog.CreateLog(log_file.FullName, false, LogLevel.kLogLevel_All_NoProgress, new EventHandler<LoggerOnFlushEventArgs>(Log_OnFlush));
+            }
+            else
+            {
+                if (log_file.Length > MAX_LOG_FILESIZE_IN_BYTES)
+                {
+                    string match = string.Format("{0}.*", log_file.Name);
+                    var files = Directory.GetFiles(log_file.Directory.FullName, match).ToList();
+                    files.RemoveAt(0);
+                    files.TrimExcess();
+                    int count = files.Count;
+                    if (log_file.Exists)
+                    {
+                        File.Copy(log_file.FullName, string.Format("{0}.{1}", log_file.FullName, count));
+                    }
+                    gLog.CreateLog(log_file.FullName, true, LogLevel.kLogLevel_All_NoProgress, new EventHandler<LoggerOnFlushEventArgs>(Log_OnFlush));
+                }
+                else
+                {
+                    gLog.CreateLog(log_file.FullName, false, LogLevel.kLogLevel_All_NoProgress, new EventHandler<LoggerOnFlushEventArgs>(Log_OnFlush));
+                }
+            }
+        }
+
         public main()
         {
             InitializeComponent();
             ListViewSorter Sorter = new ListViewSorter();
-            lstPrograms.ListViewItemSorter = Sorter;
+            //lstPrograms.ListViewItemSorter = Sorter;
+
             string log_path = Application.StartupPath;
             string log_filename = string.Format("{0}.log", typeof(main).Assembly.GetName().Name);
-            gLog.CreateLog(string.Format(@"{0}\{1}", log_path, log_filename), false, LogLevel.kLogLevel_All_NoProgress, new EventHandler<LoggerOnFlushEventArgs>(Log_OnFlush));
+            FileInfo log_file = new FileInfo(string.Format(@"{0}\{1}", log_path, log_filename));
+            TruncateLogFile(log_file);            
 #if DEBUG
             LogLevel gLevel = gLog.LogLevel;
 #if DISABLE_DEBUG_MODE_KLOGLEVEL_VERBOSE_DEBUG
@@ -53,38 +86,71 @@
 
             gLog.ReportProgressEvent += new EventHandler<ReportProgressEventArgs>(gLog_ReportProgress);
         }
+        #region main form events
+        private void mnuItemExit_Click(object sender, EventArgs e) { this.Close(); }
+        private void main_Load(object sender, EventArgs e) { }
+        private void main_Shown(object sender, EventArgs e) { }
+        private void mnuItemOpenXMLTVFile_Click(object sender, EventArgs e)
+        {
+            try
+            {
+                var result = xmltv_file_chooser.ShowDialog();
+                if (result != DialogResult.OK) return;
+                ClearLocalLog();
+                LoadXMLTVShcedule(xmltv_file_chooser.FileName);
+            }
+            catch (Exception ex) { gLog.Error.WriteLine(ex.ToString()); }
+        }
+        private void mnuItemOpenSavedData_Click(object sender, EventArgs e)
+        {
+            try
+            {
+                var result = xmltv_program_data_loader.ShowDialog();
+                if (result != DialogResult.OK) return;
+                string filename = xmltv_program_data_loader.FileName;
+                Thread worker = new Thread(new ParameterizedThreadStart(DeserializeDataFromFile)); worker.Start(filename);
+            }
+            catch (Exception ex) { gLog.Error.WriteLine(ex.ToString()); }
+        }
+        private void mnuItemSaveData_Click(object sender, EventArgs e)
+        {
+            try
+            {
+                var result = xmltv_program_data_saver.ShowDialog();
+                if (result != DialogResult.OK) return;
+                string filename = xmltv_program_data_saver.FileName;
+                Thread worker = new Thread(new ParameterizedThreadStart(DeserializeDataToFile)); worker.Start(filename);
+            }
+            catch (Exception ex) { gLog.Error.WriteLine(ex.ToString()); }
+        }
+        private void main_FormClosing(object sender, FormClosingEventArgs e) { try { XMLTV.Destroy(); } catch { } }
+        private void mnuItemClearLocalLog_Click(object sender, EventArgs e) { ClearLocalLog(); }
+        #endregion
 
         private void ReportProgress(int progress)
         {
             if (this.InvokeRequired)
             {
-                try
-                {
-                    this.Invoke((Action)(delegate { ReportProgress(progress); }));
-                }
+                try { this.Invoke((Action)(delegate { ReportProgress(progress); })); }
                 catch { }
                 return;
-            }          
-            progress_status.Value = progress;
+            }
+            if (progress_status != null && !this.IsDisposed)
+                progress_status.Value = progress;
         }
-        private void gLog_ReportProgress(object sender, ReportProgressEventArgs e) { ReportProgress(e.Progress); }
 
-        StringBuilder log_flusher = new StringBuilder();
+        #region gLog Events
+        private void gLog_ReportProgress(object sender, ReportProgressEventArgs e) { ReportProgress(e.Progress); }
+        #endregion
+        #region XMLT Events
+        void XMLTV_OnInstanceCreated(object sender, EventArgs e) { ReportProgress(0); CreateControls(); }
+        void LoadXMLTVShcedule(string schedule_xml) { XMLTV.Create(schedule_xml, new EventHandler<EventArgs>(XMLTV_OnInstanceCreated)); }
+        #endregion
 
-        void Log_OnFlush(object sender, LoggerOnFlushEventArgs e)
-        {
-            OnLogFlush(e.Buffer);
-        }
-        //bool txtLog_EnterMouse = false;
 
-        private void txtLog_MouseLeave(object sender, EventArgs e)
-        {
-            //txtLog_EnterMouse = false;
-        }
-        private void txtLog_MouseEnter(object sender, EventArgs e)
-        {
-            //txtLog_EnterMouse = true;
-        }
+        #region Logging Events
+        StringBuilder log_flusher = new StringBuilder();
+        void Log_OnFlush(object sender, LoggerOnFlushEventArgs e) { OnLogFlush(e.Buffer); }
         void OnLogFlush(string logmessage)
         {
             if (this.IsDisposed) { return; }
@@ -92,237 +158,382 @@
             UpdateLogOutput(logmessage);
             Application.DoEvents();
         }
-
+        private void ClearLocalLog()
+        {
+            var log_top_entry = txtLog.Lines.FirstOrDefault();
+            txtLog.Clear();
+            if (!string.IsNullOrEmpty(log_top_entry)) { txtLog.AppendText(log_top_entry); }
+        }
         void UpdateStatus(string logmessage)
         {
-            if (this.InvokeRequired)
+            try
             {
-                try
+                if (this.InvokeRequired)
                 {
-                    this.Invoke((Action)(delegate { UpdateStatus(logmessage); }));
+                    try { this.Invoke((Action)(delegate { UpdateStatus(logmessage); })); }
+                    catch { }
+                    return;
                 }
-                catch { }
-                return;
+                txtStatus.Text = logmessage.Replace(System.Environment.NewLine, "");
             }
-            txtStatus.Text = logmessage.Replace(System.Environment.NewLine, "");
+            catch (Exception ex) { gLog.Error.WriteLine(ex.ToString()); }
         }
         void UpdateLogOutput(string logmessage)
         {
-            if (this.InvokeRequired)
+            try
             {
-                try
+                if (this.InvokeRequired)
                 {
-                    this.Invoke((Action)(delegate { UpdateLogOutput(logmessage); }));
+                    try { this.Invoke((Action)(delegate { UpdateLogOutput(logmessage); })); }
+                    catch { }
+                    return;
                 }
-                catch { }
-                return;
+                txtLog.AppendText(logmessage);
+                txtLog.SelectionStart = txtLog.Text.Length; //Set the current caret position to the end
+                txtLog.ScrollToCaret(); //Now scroll it automatically
             }
-            txtLog.AppendText(logmessage);
-            txtLog.SelectionStart = txtLog.Text.Length; //Set the current caret position to the end
-            txtLog.ScrollToCaret(); //Now scroll it automatically
+            catch (Exception ex) { gLog.Error.WriteLine(ex.ToString()); }
         }
+        #endregion
 
-        //List<IXMLTVChannel> Channels;
-        List<IXMLTVProgram> Programs;
-
-        private void main_Load(object sender, EventArgs e)
+        #region Binary Data Read/Write support
+        private void DeserializeDataFromFile(object filename)
         {
-
+            if (filename == null) { throw new ArgumentNullException("filename", "cannot be null"); }
+            XMLTV.Load(filename.ToString(), new EventHandler<EventArgs>(XMLTV_OnInstanceCreated));
         }
-        private void main_Shown(object sender, EventArgs e)
+        private void DeserializeDataToFile(object filename)
         {
-
+            if (filename == null) { throw new ArgumentNullException("filename", "cannot be null"); }
+            XMLTV.Save(filename.ToString());
         }
+        #endregion
 
 
-        void LoadXMLTVShcedule(string schedule_xml)
-        {
-            XMLTV.CreateInstance(schedule_xml, new EventHandler<EventArgs>(XMLTV_OnInstanceCreated));
-        }
-
-        void XMLTV_OnInstanceCreated(object sender, EventArgs e)
+        #region CreateControls
+        void AutoResizeDataGridView()
         {
-            ReportProgress(0);
-            var instance = XMLTV.GetInstance();
-            if (instance != null)
+            //dataGrid.AutoResizeRow(2, DataGridViewAutoSizeRowMode.AllCellsExceptHeader);
+        
+            for (int i = 0; i < dataGrid.ColumnCount; i++)
             {
-                var program_count = instance.Programs.Count;
-                var program_list = instance.Programs.ToList().OrderBy(s => s.MetaData[XMLTVConstants.Programs.ProgramStart].ToString());
-                //Programs = program_list(0, program_count).ToList();
-                Programs = new List<IXMLTVProgram>(program_list.ToArray());
+                dataGrid.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
             }
-            CreateControls();
+            //for (int i = 0; i < dataGrid.RowCount; i++)
+            //{
+            //    dataGrid.AutoResizeRow(i, DataGridViewAutoSizeRowMode.AllCellsExceptHeader);
+            //}
         }
-
-
-        //void xmltv_cancelevent(object sender, CancelEventArgs e)
-        //{
-        //    if (form_closing)
-        //    {
-        //        e.Cancel = true;
-        //    }
-        //}
-
         void CreateControls()
         {
-            if (this.InvokeRequired)
-            {
-                this.Invoke((Action)(delegate { CreateControls(); }));
-                return;
-            }
-            List<ListViewItem> items = new List<ListViewItem>();
-            foreach (var program in Programs)
+            try
             {
-                IXMLTVChannel Channel = null;
-                var instance = XMLTV.GetInstance();
-                var id = program.MetaData[XMLTVConstants.Programs.ProgramChannelId].ToString();
-                Channel = instance.Channels.Find(m => m.Id == id);
-                //ListViewItem li = new ListViewItem(string.Format("{0} {1}", Channel.Number, Channel.CallSign));
-                if (Channel.MetaData.Count() == 0) { throw new ArgumentOutOfRangeException(string.Format("No metadata available for channel id: {0}", Channel.Id)); }
-                var channel_names = Channel.MetaData[XMLTVConstants.Channels.ChannelDisplayName];
-                string channel_name = string.Empty;
-                if (channel_names.Count() == 0) { throw new ArgumentOutOfRangeException(string.Format("No properties named '{0}' found for channel id: {1}", XMLTVConstants.Channels.ChannelDisplayName, Channel.Id)); }
-                else
+                if (this.InvokeRequired)
                 {
-                    var channame = channel_names.FirstOrDefault();
-                    if (channame == null) { throw new NullReferenceException(string.Format("Unable to get channel display name for channel id: {0}", Channel.Id)); }
-                    else
-                    {
-                        if (channame.Value == null) { throw new NullReferenceException(string.Format("Unable to get channel display name for channel id: {0}", Channel.Id)); }
-                        else { channel_name = channame.Value.ToString(); }
-                    }
+                    try { this.Invoke((Action)(delegate { CreateControls(); })); }
+                    catch { }
+                    return;
                 }
-                ListViewItem li = new ListViewItem(string.Format("{0}", channel_name));
-                li.Tag = program;
-                li.SubItems.Add(new ListViewItem.ListViewSubItem(li, program.MetaData[XMLTVConstants.Programs.ProgramTitle].ToString()));
-                li.SubItems.Add(new ListViewItem.ListViewSubItem(li, program.MetaData[XMLTVConstants.Programs.ProgramSubTitle].ToString()));
-                li.SubItems.Add(new ListViewItem.ListViewSubItem(li, program.MetaData[XMLTVConstants.Programs.ProgramDescription].ToString()));
-                li.SubItems.Add(new ListViewItem.ListViewSubItem(li, ((DateTime)program.MetaData[XMLTVConstants.Programs.ProgramStart]).ToString("yyyy/MM/dd hh:mm tt")));
-                li.SubItems.Add(new ListViewItem.ListViewSubItem(li, ((DateTime)program.MetaData[XMLTVConstants.Programs.ProgramStop]).ToString("yyyy/MM/dd hh:mm tt")));
-                //lstPrograms.Items.Add(li);
-                items.Add(li);
+                Type data_type;
+                object datasource = XMLTV.CreateBindingSourceFromData(XMLTV.GetPrograms(), out data_type);
+                CreatControlsFromType(data_type);                
+                dataGrid.DataSource = datasource;
+                AutoResizeDataGridView();
+                flow_datagrid_sort.Enabled = true;
+                btnSort.PerformClick();
             }
+            catch (Exception ex) { gLog.Error.WriteLine(ex.ToString()); }
+        }
 
-            lstPrograms.Items.AddRange(items.ToArray());
+
+        void CreatControlsFromType(Type data_type)
+        {
+#if USE_DYNAMIC_SORTING_FILTERING_CONTROLS
+              _CreatControlsFromType(data_type);
+#else
+            gLog.Verbose.Warn.WriteLine("Dynamic creation of sorting and filtering controls has not been enabled.");
+            gLog.Verbose.Warn.WriteLine("To enable: #define USE_DYNAMIC_SORTING_FILTERING_CONTROLS");
+#endif
+        }
+        [Conditional("USE_DYNAMIC_SORTING_FILTERING_CONTROLS")]
+        void _CreatControlsFromType(Type data_type)
+        {
+            string strType = data_type.Name;
+            switch (strType)
+            {
+                case "IChannelDefintionList": CreateChannelDefinitionControls(data_type); break;
+                case "IProgramDefinitionList": CreateProgramDefinitionControls(data_type); break;
+                case "IXMLTVSource": CreateSourceDefinitionControls(data_type); break;
+                default: CreateDefaultControls(data_type); break;
+            }
+        }
+        [Conditional("USE_DYNAMIC_SORTING_FILTERING_CONTROLS")]
+        void CreateDefaultControls(Type data_type)
+        {
+            // no default controls
+            gLog.Verbose.Warn.WriteLine("No controls have been defined for: {0}", data_type.Name);
+        }
+        [Conditional("USE_DYNAMIC_SORTING_FILTERING_CONTROLS")]
+        void CreateSourceDefinitionControls(Type data_type)
+        {
+            // no controls needed
+            gLog.Verbose.Warn.WriteLine("No controls have been defined for: {0}", data_type.Name);
+        }
+        [Conditional("USE_DYNAMIC_SORTING_FILTERING_CONTROLS")]
+        void CreateChannelDefinitionControls(Type data_type)
+        {
+            gLog.Verbose.Warn.WriteLine("No controls have been defined for: {0}", data_type.Name);
+        }
+        [Conditional("USE_DYNAMIC_SORTING_FILTERING_CONTROLS")]
+        void CreateProgramDefinitionControls(Type data_type)
+        {
+            gLog.Verbose.Warn.WriteLine("No controls have been defined for: {0}", data_type.Name);
         }
+        #endregion
 
-        private void mnuItemOpenXMLTVFile_Click(object sender, EventArgs e)
+        #region Program Entry Display        
+        private int CurrentRowIndex = -1;
+        void DisplaySelectedProgramEntry(DataGridViewRow row)
         {
-            try
+            int RowIndex = row.Index; // this is the index in the list
+
+            //if (CurrentRowIndex == -1) { AlreadyDisplayedProgramEntryForIndex = false; CurrentRowIndex = RowIndex; }
+            //if (CurrentRowIndex == RowIndex && AlreadyDisplayedProgramEntryForIndex) { 
+            bool DoDisplay = false;
+            if (CurrentRowIndex == -1)
             {
-                lstPrograms.Items.Clear();
-                //LoadXMLTVShcedule("20130307_continuum_schedule.xml");
-                var result = xmltv_file_chooser.ShowDialog();
-                if (result != DialogResult.OK) return;
-                ClearLocalLog();
-                LoadXMLTVShcedule(xmltv_file_chooser.FileName);
-                //CreateControls();
+                DoDisplay = true;
             }
-            catch (Exception ex)
+            if (CurrentRowIndex == RowIndex)
             {
-                gLog.Error.WriteLine(ex.ToString());
+                DoDisplay = false;
+            }
+            else
+            {
+                DoDisplay = true;
             }
-        }
 
-        private void mnuItemOpenSavedData_Click(object sender, EventArgs e)
-        {
-            try
+            if (DoDisplay)
             {
-                var result = xmltv_program_data_loader.ShowDialog();
-                if (result != DialogResult.OK) return;
-                string filename = xmltv_program_data_loader.FileName;
-                IXMLTVRuntimeInstance xmltv = null;
-                bool status = false;
-                xmltv = XMLTV.DeSerialize(filename, out status);
-                XMLTV.CreateFromInstance(xmltv, new EventHandler<EventArgs>(XMLTV_OnInstanceCreated));
-                if (!status)
+                 CurrentRowIndex = RowIndex;
+                List<IProgramDefinition> list = (dataGrid.DataSource as List<IProgramDefinition>);
+                if (list == null)
                 {
-                    MessageBox.Show("Failed to load data - check log", "Failed to load data", MessageBoxButtons.OK, MessageBoxIcon.Error);
+                    gLog.Warn.WriteLine("Unable to display program entry for rowindex: {0}", RowIndex);
+                   
                     return;
                 }
-                MessageBox.Show("Successfully loaded data", "Successfully loaded data", MessageBoxButtons.OK, MessageBoxIcon.Information);
-            }
-            catch (Exception ex)
-            {
-                gLog.Error.WriteLine(ex.ToString());
+                try
+                {
+                    IProgramDefinition program = list[RowIndex];
+                    ProgramEntryControl c = new ProgramEntryControl(program);
+                    c.Dock = DockStyle.Fill;
+                    split_bottom.Panel2.Controls.Clear();
+                    split_bottom.Panel2.Controls.Add(c);                    
+                }
+                catch (Exception ex)
+                {
+                    gLog.Error.WriteLine(ex.ToString());
+                }
             }
         }
-
-        private void mnuItemSaveData_Click(object sender, EventArgs e)
+        #endregion
+        #region Datasource support / events
+        private void dataGrid_SelectionChanged(object sender, EventArgs e)
         {
             try
             {
-                var result = xmltv_program_data_saver.ShowDialog();
-                if (result != DialogResult.OK) return;
-                string filename = xmltv_program_data_saver.FileName;
-                if (!XMLTV.Serialize(filename))
+                DataGridView dgv = (DataGridView)sender;
+                //var row = dgv.SelectedRows[0]; // the row that was selected
+                //var cell = dgv.SelectedCells[0];
+                DataGridViewRow row = null;
+                string data = string.Empty;
+                if (dgv.SelectedCells.Count > 0)
                 {
-                    MessageBox.Show("Failed to save data - check log", "Failed to save data", MessageBoxButtons.OK, MessageBoxIcon.Error);
-                    return;
+                    var cell = dgv.SelectedCells[0];
+                    row = dgv.Rows[cell.RowIndex];
+                }
+                if (dgv.SelectedRows.Count > 0)
+                {
+                    row = dgv.SelectedRows[0];
+                }
+
+                if (row != null)
+                {
+                    RadioButton button = GetSelectedFilteringControl();
+                    int index = GetColumnIndexForRadioButton(button);
+                    data = row.Cells[index].Value.ToString();
+                    txtFilterText.Text = data;
+                    DisplaySelectedProgramEntry(row);
                 }
-                MessageBox.Show("Successfully saved data", "Successfully saved data", MessageBoxButtons.OK, MessageBoxIcon.Information);
             }
             catch (Exception ex)
             {
-                gLog.Error.WriteLine(ex.ToString());
+                gLog.Verbose.Error.WriteLine(ex.ToString());
             }
         }
-
-        private void main_FormClosing(object sender, FormClosingEventArgs e)
+        private int GetColumnIndexForRadioButton(RadioButton radio) { return GetColumnIndex(radio.Tag as string); }
+        private int GetColumnIndex(string columnname)
         {
-            try
+            int index =0;
+            Type t = typeof(IProgramDefinition);
+
+            var props = t.GetProperties();
+            foreach (var prop in props)
             {
-                XMLTV.DestroyInstance();
+                if (prop.Name.ToLower() == columnname.ToLower()) { break; }
+                index++;
             }
-            catch { }
+            return index;
         }
-
-        private void mnuItemClearLocalLog_Click(object sender, EventArgs e)
+        #endregion
+        #region Reset event
+        private void btnResetSort_Click(object sender, EventArgs e)
         {
-            ClearLocalLog();
+            Type data_type;
+            object datasource = XMLTV.CreateBindingSourceFromData(XMLTV.GetPrograms(), out data_type);
+            dataGrid.DataSource = datasource;
+            ToggleDescedning();
         }
-        private void ClearLocalLog()
+        #endregion
+        #region Filtering events
+        private void FilterByColumn(RadioButton button)
         {
-            var log_top_entry = txtLog.Lines.FirstOrDefault();
-            txtLog.Clear();
-            if (!string.IsNullOrEmpty(log_top_entry))
+            Type data_type;
+            string column = (button.Tag as string);
+            object data = XMLTV.CreateBindingSourceFromData(XMLTV.GetPrograms(), out data_type);
+            XMLTV.CreateFilterFromDataSource(ref data, column, txtFilterText.Text);
+            dataGrid.DataSource = data;
+            dataGrid_SelectionChanged(dataGrid, new EventArgs());
+        }
+        private RadioButton GetSelectedFilteringControl()
+        {
+            bool control_selected = false;
+            RadioButton button = new RadioButton();
+            foreach (var c in grpFilter_flow.Controls)
+            {
+                button = (c as RadioButton);
+                if (button != null) { if (button.Checked) { control_selected = true; break; } }
+                else { continue; }
+            }
+            if (!control_selected)
             {
-                txtLog.AppendText(log_top_entry);
+                gLog.Verbose.Warn.WriteLine("Unkown filter value used.  Was not: channelname, title, subtitle, description, start, or stop.");
+                //throw new InvalidOperationException("No filtering control is currently selected.");
+                return button;
             }
+            else { return button; }
         }
-
-        private void mnuItemExit_Click(object sender, EventArgs e)
+        private void UpdateFilterText(RadioButton radio, DataGridView dgv)
+        {
+            if (radio.Checked)
+            {
+                int cellindex = GetColumnIndexForRadioButton(radio);
+                string t = radio.Tag as string;
+                DataGridViewRow row = null;
+                string data = string.Empty;
+                if (dgv.SelectedCells.Count > 0)
+                {
+                    var cell = dgv.SelectedCells[0];
+                    row = dgv.Rows[cell.RowIndex];
+                }
+                if (dgv.SelectedRows.Count > 0)
+                {
+                    row = dgv.SelectedRows[0];
+                }
+                data = row.Cells[cellindex].Value.ToString();
+                txtFilterText.Text = data;
+            }
+        }
+        private void btnFilter_Click(object sender, EventArgs e)
         {
-            this.Close();
+            RadioButton button = GetSelectedFilteringControl();
+            FilterByColumn(button);
         }
-
-        private void lstPrograms_SelectedIndexChanged(object sender, EventArgs e)
+        private void radio_filter_channelnumber_CheckedChanged(object sender, EventArgs e)
         {
-            IXMLTVProgram program = null;
-            var item = lstPrograms.SelectedItems[0];
-            int selected_index = lstPrograms.Items.IndexOf(item);
-            program = (item.Tag as IXMLTVProgram);
-            gLog.Debug.WriteLine("Selected ListViewItem at index: {0}", selected_index);
-            if (program == null) { return; }
-            txtStatus.Text = program.ToString();
-            //gLog.Debug.WriteLine(program.ToString());
-
+            RadioButton radio = (sender as RadioButton);
+            UpdateFilterText(radio, dataGrid);
         }
-
-        private void lstPrograms_ColumnClick(object sender, ColumnClickEventArgs e)
+        private void radio_filter_title_CheckedChanged(object sender, EventArgs e)
         {
-            if (!(lstPrograms.ListViewItemSorter is ListViewSorter)) return;
-            ListViewSorter Sorter = (ListViewSorter)lstPrograms.ListViewItemSorter;
-            Sorter.LastColumn = Sorter.CurrentColumn;
-            Sorter.CurrentColumn = e.Column;
-            if (Sorter.LastColumn == e.Column)
+            RadioButton radio = (sender as RadioButton);
+            UpdateFilterText(radio, dataGrid);
+        }
+        private void radio_filter_subtitle_CheckedChanged(object sender, EventArgs e)
+        {
+            RadioButton radio = (sender as RadioButton);
+            UpdateFilterText(radio, dataGrid);
+        }
+        private void radio_filter_description_CheckedChanged(object sender, EventArgs e)
+        {
+            RadioButton radio = (sender as RadioButton);
+            UpdateFilterText(radio, dataGrid);
+        }
+        private void radio_filter_channelname_CheckedChanged(object sender, EventArgs e)
+        {
+            RadioButton radio = (sender as RadioButton);
+            UpdateFilterText(radio, dataGrid);
+        }
+        private void radio_filter_start_CheckedChanged(object sender, EventArgs e)
+        {
+            RadioButton radio = (sender as RadioButton);
+            UpdateFilterText(radio, dataGrid);
+        }
+        private void radio_filter_stop_CheckedChanged(object sender, EventArgs e)
+        {
+            RadioButton radio = (sender as RadioButton);
+            UpdateFilterText(radio, dataGrid);
+        }
+        private void radio_filter_rating_CheckedChanged(object sender, EventArgs e)
+        {
+            RadioButton radio = (sender as RadioButton);
+            UpdateFilterText(radio, dataGrid);
+        }
+        #endregion
+        #region Sorting events
+        private bool Descending = false;
+        private void ToggleDescedning() { Descending = Descending ? false : true; }
+        private void SortByColumn(RadioButton button)
+        {
+            string column = (button.Tag as string);
+            object data = dataGrid.DataSource;
+            XMLTV.CreateSorterFromDataSource(ref data, Descending, column);
+            dataGrid.DataSource = data;
+            ToggleDescedning();
+            dataGrid_SelectionChanged(dataGrid, new EventArgs());
+        }
+        private RadioButton GetSelectedSortControl()
+        {
+            bool control_selected = false;
+            RadioButton button = new RadioButton();
+            foreach (var c in grpSort_flow.Controls)
+            {
+                button = (c as RadioButton);
+                if (button != null) { if (button.Checked) { control_selected = true; break; } }
+                else { continue; }
+            }
+            if (!control_selected)
             {
-                if (lstPrograms.Sorting == SortOrder.Ascending) { lstPrograms.Sorting = SortOrder.Descending; }
-                else { lstPrograms.Sorting = SortOrder.Ascending; }
+                gLog.Warn.WriteLine("Unkown sort value used.  Was not: channelname, title, subtitle, description, stop, or start.");
+                //throw new InvalidOperationException("No sorting control is currently selected.");
+                return button;
             }
-            else { lstPrograms.Sorting = SortOrder.Descending; }
-            lstPrograms.Sort();
+            else { return button; }
         }
+        private void btnSort_Click(object sender, EventArgs e)
+        {
+            RadioButton button = GetSelectedSortControl();
+            SortByColumn(button);
+        }
+        #endregion
+
+        private void dataGrid_Click(object sender, EventArgs e)
+        {
+            dataGrid_SelectionChanged(dataGrid, new EventArgs());
+        }
+
+       
     }
 }
 

 

  ViewVC Help
Powered by ViewVC 1.1.22