void OnPageDownloaded(object sender, DownloadDataCompletedEventArgs e) { try { Log4cs.Log(e.UserState.GetType().ToString()); } catch (Exception ex) { Log4cs.Log(Importance.Debug, ex.ToString()); } }
void OnContextMenuDoubleClicked(object sender, EventArgs e) { Log4cs.Log(Importance.Debug, "Context menu icon doubleclicked..."); if (this.Visible) { HideApplication(); } else { this.Visible = true; } }
/// <summary> /// Reloads setting. Stops thread if necessary /// </summary> private void ReloadSettings() { Log4cs.Log("Reloading settings..."); Settings.Load(); // Need to reload radio station thread if ((_radioThread != null) && _radioThread.IsRunning) { _radioThread.Stop(); _radioThread.Start(Settings.RadioStations); } }
private void OnFormLoad(object sender, EventArgs e) { try { Log4cs.Log("Starting {0} (v{1})...", Settings.Name, Settings.Version); Debug("Starting {0}...", Settings.NameVersion); // In case we need only one instance of program EnsureSingleApplication(); this.Text = Settings.NameVersion; // Load configuration Settings.Load(); if ((Settings.RadioStations == null) || (Settings.RadioStations.Length < 1)) { Log4cs.Log(Importance.Error, "Radio stations are not configured properly - no stations in XML!"); MessageBox.Show("Radio stations are not configured properly, check stations.xml file!"); throw new Exception("Bad stations.xml configuration!"); } else { Debug("Got {0} configured stations to watch", Settings.RadioStations.Length); } // Creates icons using emebedded icon CreateFormIcons(); // Create context menu for tray icon MenuItem[] arMenu = this.CreateMenuItems(); if (arMenu != null) { _icon.ContextMenu = new ContextMenu(arMenu); _icon.DoubleClick += new EventHandler(OnContextMenuDoubleClicked); } // Hides application (form) if necessary //HideApplication(); } catch (ApplicationException ex) { Debug(Importance.Error, "Application already run, check logs!"); MessageBox.Show(ex.ToString(), string.Format("{0} (v{1})", Settings.Name, Settings.Version), MessageBoxButtons.OK, MessageBoxIcon.Error); this.Close(); } catch (Exception ex) { Log4cs.Log(Importance.Error, "Error loading main form!"); Log4cs.Log(Importance.Debug, ex.ToString()); MessageBox.Show("Error loading application!", string.Format("{0} (v{1})", Settings.Name, Settings.Version), MessageBoxButtons.OK, MessageBoxIcon.Error); this.Close(); } }
/// <summary> /// Ensures that application is the only. Throws ApplicationException if there is such application /// </summary> private void EnsureSingleApplication() { bool createdNew = false; Mutex mx = new Mutex(false, Settings.Name, out createdNew); Log4cs.Log(Importance.Debug, "Is mutex created: {0}", createdNew); // If application is already running if (createdNew == false) { throw new ApplicationException(Settings.Name + " application is already running!"); } }
private void OnFormClosed(object sender, FormClosedEventArgs e) { Log4cs.Log(Importance.Debug, "Firing Quit event to stop radio thread!"); AEvents.arEvents[(int)AEvents.EventsId.Quit].Set(); //if( _radioThread != null ) //{ // _radioThread.Stop(); //} if (_icon != null) { _icon.Dispose(); } }
/// <summary> /// Parses and returns Song object for specifi radio station or NULL! /// </summary> /// <param name="radio"></param> public static Song Parse(RadioStationItem radio) { Song song = new Song(); song.PlayedAt = DateTime.Now; try { //Log4cs.Log(Importance.Debug, "Radio [{1}]{0}{2}", Environment.NewLine, radio.RadioName, radio.RawStationResponse); if (!string.IsNullOrEmpty(radio.RawStationResponse)) { int offset = 0; if (!string.IsNullOrEmpty(radio.beforeTitle)) { // Use to place song title and artist position offset = radio.RawStationResponse.IndexOf(radio.beforeTitle, StringComparison.CurrentCultureIgnoreCase); } // Get song title Match m = radio.TitleRegex.Match(radio.RawStationResponse, offset); if (m.Success) { song.Title = m.Groups[radio.TitlePositon].ToString(); song.Title = StripTags(song.Title).Trim(); // TODO: clean HTML entities method song.Title = song.Title.Replace("#039;", "'"); } // Get song artist m = radio.ArtistRegex.Match(radio.RawStationResponse, offset); if (m.Success) { song.Artist = m.Groups[radio.ArtistPositon].ToString(); song.Artist = StripTags(song.Artist).Trim(); song.Artist = song.Artist.Replace("#039;", "'"); } } } catch (Exception ex) { Log4cs.Log(Importance.Error, "Error parsing response from radio station!"); Log4cs.Log(Importance.Debug, ex.ToString()); song = null; } return(song); }
private void OnFormClosing(object sender, FormClosingEventArgs e) { try { //base.OnFormClosing(e); // Hide on close if (e.CloseReason == CloseReason.UserClosing) { // TODO: Hide debug console instead of closing application //HideApplication(); //e.Cancel = true; } } catch (Exception ex) { Log4cs.Log(Importance.Error, "Error OnFormClosing!"); Log4cs.Log(Importance.Debug, ex.ToString()); } }
/// <summary> /// Starts/stops application if needed :) /// </summary> private void OnStartStopClicked(object sender, object e) { Log4cs.Log("Start/stop is clicked..."); if (_radioThread == null) { _radioThread = new PageDownloaderThread(); _radioThread.SongParsed += new SongParsedDelegate(OnSongParsed); } // Stop thread if running if (_radioThread.IsRunning) { _radioThread.Stop(); } else { // Need to run thread _radioThread.Start(Settings.RadioStations); } }
/// <summary> /// Adds song to playlist, returns whether song is new /// </summary> /// <param name="song"></param> public bool Add(Song song) { // Skip if both artist and title are empty (some kind of parsing error) if (song == null || (string.IsNullOrEmpty(song.Artist) && string.IsNullOrEmpty(song.Title))) { return(false); } Song lastSong = GetLast(song.Radio.RadioName); if ((lastSong == null) || !lastSong.Artist.Equals(song.Artist) || !lastSong.Title.Equals(song.Title)) { Log4cs.Log(Importance.Debug, "Adding new song on {0}: {1} - {2}", song.Radio.RadioName, song.Artist, song.Title); _arPlayedSongs.Add(song); return(true); } else { Log4cs.Log(Importance.Debug, "Song {0} - {1} is currently playing on {2}", song.Artist, song.Title, song.Radio.RadioName); } return(false); }
/// <summary> /// Creates context menu for tray icon /// </summary> /// <returns></returns> private MenuItem[] CreateMenuItems() { MenuItem[] arMenu = null; try { // Check if we have some radio stations int radios = Settings.RadioStations == null ? 0 : Settings.RadioStations.Length; // Got quantity of menus (+ radios if any + title) arMenu = new MenuItem[MyMenu.Size + radios + 1]; for (int i = 0; i < MyMenu.Size; i++) { arMenu[i] = new MenuItem(MyMenu.ToName(i), OnContextMenuClicked); } arMenu[MyMenu.Size] = new MenuItem("Radio stations"); arMenu[MyMenu.Size].Enabled = false; // Add radio stations to menu, if any for (int i = 0; i < radios; i++) { arMenu[MyMenu.Size + i + 1] = new MenuItem(Settings.RadioStations[i].RadioName, OnRadioStationClicked); arMenu[MyMenu.Size + i + 1].Name = Settings.RadioStations[i].RadioName; } // By default status thread is stopped, so disable "Stop" command arMenu[MyMenu.Position.Stop].Enabled = false; // Format "Version" arMenu[MyMenu.Position.Version].Text = string.Format("{0} (v{1})", Settings.Name, Settings.Version); } catch (Exception ex) { Log4cs.Log(Importance.Error, "Error creating menu items!"); Log4cs.Log(Importance.Debug, ex.ToString()); } return(arMenu); }
/// <summary> /// Handles clicks on systray icon menu /// </summary> void OnContextMenuClicked(object sender, EventArgs e) { try { switch (((MenuItem)sender).Index) { case MyMenu.Position.Start: _icon.ContextMenu.MenuItems[MyMenu.Position.Start].Enabled = false; _icon.ContextMenu.MenuItems[MyMenu.Position.Stop].Enabled = true; OnStartStopClicked(null, null); break; case MyMenu.Position.Stop: _icon.ContextMenu.MenuItems[MyMenu.Position.Start].Enabled = true; _icon.ContextMenu.MenuItems[MyMenu.Position.Stop].Enabled = false; OnStartStopClicked(null, null); break; case MyMenu.Position.Version: MessageBox.Show("iPlayNow by mr. Aleksej Vasinov", Settings.NameVersion, MessageBoxButtons.OK, MessageBoxIcon.Information); break; case MyMenu.Position.Reload: ReloadSettings(); break; default: this.Close(); break; } } catch (Exception ex) { Log4cs.Log(Importance.Error, "Error handling context menu click!"); Log4cs.Log(Importance.Debug, ex.ToString()); } }
/// <summary> /// Dowloads pages which are specified and fires event /// </summary> protected void DownloadThread(object obj) { // Use this to stop in case there are too many errors int errors = 0; int[] arEventsToWait = { (int)AEvents.EventsId.GotData , (int)AEvents.EventsId.Quit }; //WebClient[] arWeb = null; WebClient wc = new WebClient(); //wc.DownloadDataCompleted += new DownloadDataCompletedEventHandler(OnPageDownloaded); if (obj != null) { _arRadios = (RadioStationItem[])obj; Log4cs.Log("Got {0} radio stations to proceed...", _arRadios.Length); } // Which station to proceed int currentStation = 0; while (_isRunning) { try { if (currentStation >= _arRadios.Length) { currentStation = 0; } Log4cs.Log(Importance.Debug, "Downloading station #{0} from {1}...", currentStation, _arRadios[currentStation].Url); //try //{ _arRadios[currentStation].RawStationResponse = wc.DownloadString(_arRadios[currentStation].Url); _arRadios[currentStation].LastCheckedAt = DateTime.Now; Song song = GetSongTitle.Parse(_arRadios[currentStation]); if (song != null) { // Set station where song was played song.Radio = _arRadios[currentStation]; // Check if we need to notify about new song if (SongParsed != null) { SongParsed(_arRadios[currentStation], song); } } //} catch(Exception ex) //{ // Log4cs.Log(Importance.Error, "Error downloading song from {0}!", _arRadios[i].Url); // Log4cs.Log(Importance.Debug, ex.ToString()); //} // Everything goes ok errors = 0; } catch (Exception ex) { Log4cs.Log(Importance.Error, "Error downloading song title!"); Log4cs.Log(Importance.Debug, ex.ToString()); errors++; if (errors > 5) { // 5 errors continuosly, sleep for 30 second and wait for Quit if (Common.WaitMyEvents(ref AEvents.arEvents, arEventsToWait, 30000, true) == (int)AEvents.EventsId.Quit) { Log4cs.Log(Importance.Warning, "Got 5 continuosly errors and then Quit signal!"); _isRunning = false; } } else if (errors > 10) { // 5 errors continuosly, sleep for 120 second and wait for Quit if (Common.WaitMyEvents(ref AEvents.arEvents, arEventsToWait, 120000, true) == (int)AEvents.EventsId.Quit) { Log4cs.Log(Importance.Warning, "Got 10 continuosly errors and then Quit signal!"); _isRunning = false; } } } finally { // Wait for exit signal or timeout if all radios are fetched if (currentStation == _arRadios.Length - 1) { switch (Common.WaitMyEvents(ref AEvents.arEvents, arEventsToWait, 30000, true)) { //case (int)AEvents.EventsId.GotData: // Log4cs.Log(Importance.Debug, "Got data from radio station"); // break; case (int)AEvents.EventsId.Quit: Log4cs.Log("Got signal to stop, exiting downloder thread..."); _isRunning = false; break; } } // Go to next station anyway currentStation++; } } // END WHILE ( continue download ) }
/// <summary> /// Stops thread /// </summary> public void Stop() { Log4cs.Log("Stopping downloader thread..."); _isRunning = false; }
/// <summary> /// Reads and parses config file and creates task for each radio /// </summary> /// <param name="xmlConfigFile"></param> private static RadioStationItem[] LoadRadioList(string xmlConfigFile) { List <RadioStationItem> arStationsItems = new List <RadioStationItem>(); try { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xmlConfigFile); XmlElement xml = xmlDoc.DocumentElement; //XmlNode node = xml.ChildNodes[0]; if (xml.ChildNodes.Count > 0) { //arStationsItems = new RadioStationItem[xml.ChildNodes.Count]; bool isActive = false; //Log4cs.Log("There are {0}",); foreach (XmlNode radioNode in xml.ChildNodes) { RadioStationItem radio = new RadioStationItem(); //Log4cs.Log(radioNode.Name + ": " + radioNode.ChildNodes[0].Value); foreach (XmlNode var in radioNode.ChildNodes) { //Log4cs.Log(var.Name + ": " + var.ChildNodes[0].Value); switch (var.Name.ToLower()) { case "isactive": bool.TryParse(var.ChildNodes[0].Value, out isActive); radio.IsActive = isActive; break; case "title": radio.RadioName = var.ChildNodes[0].Value; break; case "titlemask": radio.TitleMask = var.ChildNodes[0].Value; break; case "titleposition": radio.ArtistPositon = Int32.Parse(var.ChildNodes[0].Value); break; case "artistemask": radio.ArtistMask = var.ChildNodes[0].Value; break; case "artistposition": radio.TitlePositon = Int32.Parse(var.ChildNodes[0].Value); break; case "url": radio.Url = var.ChildNodes[0].Value; break; case "beforetitle": if (var.HasChildNodes) { radio.beforeTitle = var.ChildNodes[0].Value; } break; default: break; } // END SWITCH } // END FOREACH ( list all item parameter ) if (radio.IsActive) { arStationsItems.Add(radio); } } // END FOREACH ( list all items ) } // END IF if (arStationsItems != null) { Log4cs.Log("Radio station list:"); for (int i = 0; i < arStationsItems.Count; i++) { Log4cs.Log("\t{0}", arStationsItems[i].ToString()); } } } catch (Exception ex) { Log4cs.Log("Error parsing " + xmlConfigFile, Importance.Error); Log4cs.Log(ex.ToString(), Importance.Debug); } return(arStationsItems.Count > 0 ? arStationsItems.ToArray() : null); }
public static void Load() { Log4cs.Log("Loading settings..."); _arRadioStations = LoadRadioList(Common.GetPath() + "stations.xml"); }