// get tracking notificatoins from the api, this notification will be further supervised by tracking app // return: List of notification on success, null on failure public async Task <List <Notification> > get_tracking_notifications() { try { string endp = $"{api_endp}/trackingnotifications"; var header = new Dictionary <string, string>() { { "Authorization", $"Token {token}" } }; List <Notification> ret = new List <Notification>(); string resp = await WRequest.get_response(endp, header, ""); var jarray = JArray.Parse(resp); foreach (var jobj in jarray) { var note = new JavaScriptSerializer().Deserialize <Notification>(jobj.ToString()); ret.Add(note); } return(ret); } catch (Exception ex) { MainApp.log_error("Loading notifications from API failed. " + ex.Message); } return(null); }
public async System.Threading.Tasks.Task <bool> login() { try { string user = MainApp.g_setting.dyn_odd_credential.user; string pwd = MainApp.g_setting.dyn_odd_credential.pwd; string res = await WRequest.get_response($"{ep}Login.asp?UserName={user}&Password={pwd}"); XDocument doc = XDocument.Parse(res); var _sid = doc.Element("Login").Element("SessionID"); if (_sid == null) { return(false); } session_id = _sid.Value; MainApp.g_working = true; return(true); } catch (Exception ex) { MainApp.g_working = false; MainApp.log_error("DynHelperError: " + ex.Message + "\n" + ex.StackTrace); return(false); } }
public static async System.Threading.Tasks.Task <string> put_response(string end_point, Object put_data, Dictionary <string, string> header = null, string data_type = "json") { try { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, end_point); if (header != null) { foreach (var pair in header) { request.Headers.Add(pair.Key, pair.Value); } } if (put_data != null) { if (data_type.ToLower() == "json") { request.Content = new StringContent(put_data.ToString(), Encoding.UTF8, "application/json");//CONTENT-TYPE header } else { request.Content = new FormUrlEncodedContent((Dictionary <string, string>)put_data); } } var response = await client.SendAsync(request); string result = await response.Content.ReadAsStringAsync(); return(result); } catch (Exception ex) { MainApp.log_error($"WRequest: {end_point} \n {put_data.ToString()} \n {data_type}\n" + ex.Message + "\n" + ex.StackTrace); return(""); } }
public void calculate_localtime(List <RaceEvent> schedule) { try { int now = -1; for (int i = 0; i < schedule.Count; i++) { if (schedule[i].Status.ToUpper() == "OPEN") { now = i; break; } } if (now == -1) { return; } if (now == 0) { now = schedule.Count - 1; } DateTime aust = DateTime.Now.Subtract(MainApp.g_time_diff); schedule[now].StartTime = DateTime.Parse(aust.ToString("yyyy-MM-dd") + " " + schedule[now].StartTime_Au); schedule[now].StartTime = schedule[now].StartTime.Add(MainApp.g_time_diff); for (int i = 0; i < now; i++) { if (string.Compare(schedule[i].StartTime_Au, schedule[now].StartTime_Au) > 0) { schedule[i].StartTime = DateTime.Parse(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") + " " + schedule[i].StartTime_Au); } else { schedule[i].StartTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + schedule[i].StartTime_Au); } schedule[i].StartTime = schedule[i].StartTime.Add(MainApp.g_time_diff); } for (int i = now + 1; i < schedule.Count; i++) { if (string.Compare(schedule[i].StartTime_Au, schedule[now].StartTime_Au) < 0) { schedule[i].StartTime = DateTime.Parse(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + " " + schedule[i].StartTime_Au); } else { schedule[i].StartTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + schedule[i].StartTime_Au); } schedule[i].StartTime = schedule[i].StartTime.Add(MainApp.g_time_diff); } } catch (Exception ex) { MainApp.log_error("DynHelperError: " + ex.Message + "\n" + ex.StackTrace); } }
public async Task <int> get_event_result(string event_id) { XDocument doc; string res; try { string endpoint = $"{ep}GetData.asp?SessionID={session_id}&Method=GetEventResults&EventID={event_id}"; res = await WRequest.get_response(endpoint); doc = XDocument.Parse(res); if (check_session(doc) == false) { if (res.Contains("Request Limit Exceeded")) { await Task.Delay(1000); return(await get_event_result(event_id)); } MainApp.log_error("Error getting event results"); MainApp.log_error(res); MainApp.g_working = false; return(-1); } IEnumerable <XElement> elems; try { elems = doc.Element("Data").Element("EventResults").Elements("Placings").Elements("Result").Elements("No"); } catch (Exception ex) { MainApp.log_error("Error parsing event results"); MainApp.log_error("DynHelperError: " + ex.Message + "\n" + ex.StackTrace); MainApp.g_working = false; return(-1); } var elem = elems.FirstOrDefault(); if (elem == null) { return(-1); } MainApp.g_working = true; return(int.Parse(elem.Value.ToString())); } catch (Exception ex) { MainApp.log_error("DynHelperError: " + ex.Message + "\n" + ex.StackTrace); MainApp.g_working = false; return(-1); } }
public void play_sound() { this.InvokeOnUiThreadIfRequired(() => { try { //m_media_player.Play(); using (var soundPlayer = new System.Media.SoundPlayer(Directory.GetCurrentDirectory() + "\\Resources\\alert.wav")) { soundPlayer.Play(); // can also use soundPlayer.PlaySync() } } catch (Exception ex) { MainApp.log_error(ex.Message); } }); }
public static async System.Threading.Tasks.Task <string> get_response(string end_point, Dictionary <string, string> header = null, string param = "", Object body = null, string data_type = "json") { try { var request = new HttpRequestMessage() { RequestUri = new Uri(end_point), }; if (header != null) { foreach (var pair in header) { request.Headers.Add(pair.Key, pair.Value); } } if (param != "") { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", param); } if (body != null) { if (data_type.ToLower() == "json") { request.Content = new StringContent(body.ToString(), Encoding.UTF8, "application/json");//CONTENT-TYPE header } else { request.Content = new FormUrlEncodedContent((Dictionary <string, string>)body); } } var response = await client.SendAsync(request); string result = await response.Content.ReadAsStringAsync(); return(result); } catch (Exception ex) { MainApp.log_error($"WRequest: {end_point} \n Token: {param}\n" + ex.Message + "\n" + ex.StackTrace); return(""); } }
public async Task <bool> update_notification(int id, Notification note) { try { string endp = $"{api_endp}/notifications/{id}"; var header = new Dictionary <string, string>() { { "Authorization", $"Token {token}" } }; var json = new JavaScriptSerializer().Serialize(note); string resp = await WRequest.put_response(endp, json, header); return(true); } catch (Exception ex) { MainApp.log_error("Updating notification failed. " + ex.Message); } return(false); }
// login using the credential given by the setting file // return: true on success false on failure public async Task <bool> login() { try { string endp = $"{api_endp}/auth"; string data = "{" + $"\"username\":\"{MainApp.g_setting.api_credential.user}\"," + $"\"password\":\"{MainApp.g_setting.api_credential.pwd}\"" + "}"; string resp = await WRequest.post_response(endp, data); var json = JObject.Parse(resp); token = json["token"].ToString(); return(true); } catch (Exception ex) { MainApp.log_error("Login failed." + ex.Message); } return(false); }
bool check_session(XDocument doc) { try { var error_node = doc.Descendants("Error").Single(); if (error_node == null) { return(false); } if (error_node.Element("ErrorTxt").Value.Trim() != "") { return(false); } return(true); } catch (Exception ex) { MainApp.log_error("DynHelperError: " + ex.Message + "\n" + ex.StackTrace); MainApp.g_working = false; return(false); } }
void init_dynamic() { panel_wait.BringToFront(); new System.Threading.Tasks.Task(async() => { try { bool _login = await m_dyn.login(); if (_login == false) { MainApp.log_info("Dynamic Odds API connection failed."); if (MessageBox.Show("Failed to log in to Dynamic Odds XML feed service.\nDo you want to continue without live alert?", "OddAlert", MessageBoxButtons.YesNo) == DialogResult.No) { Close(); return; } } play_sound(); MainApp.log_info("Dynamic Odds API connected."); m_agency_lookup = await m_dyn.get_agencies(); load_events(); this.InvokeOnUiThreadIfRequired(() => { panel_wait.SendToBack(); }); m_timer_alert.Start(); } catch (Exception ex) { MainApp.log_error("Exception in init_dynamic\n" + ex.Message + "\n" + ex.StackTrace); } }).Start(); }
public async System.Threading.Tasks.Task <Dictionary <string, string> > get_agencies() { try { Dictionary <string, string> agency = new Dictionary <string, string>(); string endpoint = $"{ep}GetData.asp?SessionID={session_id}&Method=GetBettingAgencies"; string res = await WRequest.get_response(endpoint); XDocument doc = XDocument.Parse(res); if (check_session(doc) == false) { if (res.Contains("Request Limit Exceeded")) { await Task.Delay(1000); return(await get_agencies()); } MainApp.log_error("Error getting agencies"); MainApp.log_error(res); MainApp.g_working = false; return(null); } foreach (var node in doc.Descendants("BA")) { agency.Add(node.Attribute("ID").Value, node.Element("Name").Value); } MainApp.g_working = true; return(agency); } catch (Exception ex) { MainApp.log_error("DynHelperError: " + ex.Message + "\n" + ex.StackTrace); MainApp.g_working = false; return(null); } }
private async void M_timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { try { { } if (m_dyn.Ready()) { if (m_cur_date.ToString("yyyy-MM-dd") != DateTime.Now.ToString("yyyy-MM-dd")) { load_events(); } foreach (var eve in m_event_list) { if (m_event_status[eve] == 0) { var au_now = MainApp.AuNow(); if (eve.StartTime < au_now) { m_event_status[eve] = 2; // ended continue; } m_event_status[eve] = 1; // busy new Thread(async() => { var odd_view = await m_dyn.get_runner_odds(eve.ID); // Check delta and raise the alert if (eve.OddView != null && odd_view != null) { MainApp.log_info($"Odds for {eve.State} - {eve.Venue} - {eve.EventNo} updated."); foreach (var runner in odd_view.RName) { foreach (var bookie in m_monitor_bookies) { decimal pre_price = eve.OddView.get_odd_for_bookie(bookie, runner); decimal cur_price = odd_view.get_odd_for_bookie(bookie, runner); if (pre_price < 2M || cur_price == 0) { continue; } int pre_point = PriceTable.get_point(pre_price); int cur_point = PriceTable.get_point(cur_price); int delta = cur_point - pre_point; if (delta <= -MainApp.g_setting.alert_level && -delta <= 13) { play_sound(); MainApp.log_info("Notification triggered."); int idx = odd_view.RName.IndexOf(runner); // get top prices List <KeyValuePair <string, decimal> > odd_dict = new List <KeyValuePair <string, decimal> >(); foreach (var one_bookie in odd_view.Odds) { odd_dict.Add(new KeyValuePair <string, decimal>(one_bookie.Bookie, one_bookie.Odds[idx])); } odd_dict.Sort((pair1, pair2) => - pair1.Value.CompareTo(pair2.Value)); // new notification Notification note = new Notification(); note.event_id = eve.ID; note.datetime = au_now.ToString("yyyy-MM-dd hh:mm:ss"); note.time_to_jump = eve.StartTime.Subtract(au_now).ToString("h'h 'm'm 's's'"); note.degree = delta; note.state = eve.State; note.venue = eve.Venue; note.race_number = int.Parse(eve.EventNo); note.horse_number = int.Parse(odd_view.RNo[idx]); note.horse_name = runner; note.previous_price = pre_price; note.current_price = cur_price; note.bookie = bookie; note.suggested_stake = suggest_stake(pre_price, delta); note.max_profit = note.suggested_stake * (pre_price - 1); note.top_price_1 = $"${odd_dict[0].Value} {odd_dict[0].Key}"; note.top_price_2 = $"${odd_dict[1].Value} {odd_dict[1].Key}"; note.top_price_3 = $"${odd_dict[2].Value} {odd_dict[2].Key}"; note.top_price_4 = $"${odd_dict[3].Value} {odd_dict[3].Key}"; note.status = 0; // pending note.result = "-"; add_note_to_db(note); refresh_in_delay = true; //refresh_grid(); } } } } eve.OddView = odd_view; m_event_status[eve] = 0; // idle }).Start(); } } foreach (var pair in m_event_status) { if (pair.Value == 2) { m_event_list.Remove(pair.Key); } } if (m_event_list.Count == 0) { MainApp.log_info("No active events are left today. " + m_cur_date.ToString("yyyy-MM-dd")); } } if (MainApp.g_working) { img_status.BackgroundImage = Properties.Resources.Circle_ON; } else { img_status.BackgroundImage = Properties.Resources.Circle_OFF; } } catch (Exception ex) { MainApp.log_error("Exception in timer\n" + ex.Message + "\n" + ex.StackTrace); } m_timer_alert.Start(); }
public async System.Threading.Tasks.Task <RaceEvent> get_event(RaceEvent ref_eve, string eve_id) { try { RaceEvent eve = new RaceEvent(); string endpoint = $"{ep}GetData.asp?SessionID={session_id}&Method=GetEvent&EventID={eve_id}&Runners=true"; string res = await WRequest.get_response(endpoint); XDocument doc = XDocument.Parse(res); if (check_session(doc) == false) { if (res.Contains("Request Limit Exceeded")) { await Task.Delay(1000); return(await get_event(ref_eve, eve_id)); } MainApp.g_working = false; return(null); } MainApp.g_working = true; XElement elem = null; try { elem = doc.Element("Data").Element("GetEvent").Element("Event"); } catch (Exception e) { return(null); } if (elem == null) { return(null); } eve.ID = elem.Attribute("ID").Value; eve.EventNo = elem.Element("EventNo").Value; eve.Name = elem.Element("Name").Value; eve.Distance = elem.Element("Distance").Value; eve.Track = elem.Element("Track").Value; eve.TrackRtg = elem.Element("TrackRtg").Value; eve.Starters = elem.Element("Starters").Value; eve.StartTime_Au = elem.Element("StartTime").Value; eve.Class = elem.Element("Class").Value; eve.Prizemoney = elem.Element("Prizemoney").Value; eve.Status = elem.Element("Status").Value; if (eve.Status.ToUpper() == "FINAL") { eve.Status = "PAYING"; } eve.WeatherTC = elem.Element("WeatherTC").Value; WeatherConditions con = new WeatherConditions(); con.TempC = elem.Element("WeatherCondtions").Element("TempC").Value; con.Humidity = elem.Element("WeatherCondtions").Element("Humidity").Value; con.WindSpeed = elem.Element("WeatherCondtions").Element("WindSpeed").Value; con.WindDir = elem.Element("WeatherCondtions").Element("WindDir").Value; eve.WeatherCon = con; eve.Rail = elem.Element("Rail").Value; eve.CodeAAP = elem.Element("CodeAAP").Value; eve.CodeBF = elem.Element("CodeBF").Value; eve.Runners = new List <Runner>(); foreach (var node in elem.Elements("Runner")) { Runner runner = new Runner(); runner.Name = node.Element("Name").Value; runner.Jockey = node.Element("Jockey").Value; runner.Trainer = node.Element("Trainer").Value; runner.Bar = node.Element("Bar").Value; runner.Hcp = node.Element("Hcp").Value; runner.Scr = node.Element("Scr").Value; runner.Emergency = node.Element("Emergency").Value; eve.Runners.Add(runner); } eve.Venue = ref_eve.Venue; eve.EventCode = ref_eve.EventCode; eve.Type = ref_eve.Type; eve.State = ref_eve.State; eve.StartTime = ref_eve.StartTime; eve.Date = ref_eve.Date; MainApp.g_working = true; return(eve); } catch (Exception ex) { MainApp.log_error("DynHelperError: " + ex.Message + "\n" + ex.StackTrace); MainApp.g_working = false; return(null); } }
public async System.Threading.Tasks.Task <List <RaceEvent> > get_event_schedule(DateTime date) { try { DateTime au_now = date.Subtract(MainApp.g_time_diff); List <RaceEvent> schedule = new List <RaceEvent>(); string date_str = date.ToString("yyyy-MM-dd"); string endpoint = $"{ep}GetData.asp?SessionID={session_id}&Method=GetEventSchedule&Date={date_str}&Types=R,H,G&Limit=999"; string res = await WRequest.get_response(endpoint); XDocument doc = XDocument.Parse(res); if (check_session(doc) == false) { if (res.Contains("Request Limit Exceeded")) { await Task.Delay(1000); return(await get_event_schedule(date)); } MainApp.log_error("Error getting event schedule"); MainApp.log_error(res); MainApp.g_working = false; return(null); } var all_events = doc.Descendants("Event"); foreach (var node in all_events) { RaceEvent eve = new RaceEvent(); eve.ID = node.Attribute("ID").Value; eve.Date = date; eve.EventCode = node.Attribute("EventCode").Value; eve.StartTime_Au = node.Attribute("StartTime").Value; eve.Type = node.Attribute("Type").Value; if (eve.Type == "T") { eve.Type = "H"; } eve.Venue = node.Attribute("Venue").Value; eve.EventNo = node.Attribute("EventNo").Value; eve.Status = node.Attribute("EventStatus").Value; if (eve.Status.ToUpper() == "FINAL") { eve.Status = "PAYING"; } eve.State = node.Attribute("State").Value; if (au_states.Contains(eve.State) == false || eve.Status.ToUpper() != "OPEN" || eve.Type != "R") { continue; } if (!MainApp.DEBUG && eve.StartTime_Au.CompareTo(au_now.ToString("HH:mm:ss")) < 0) { continue; } string[] fields = eve.StartTime_Au.Split(':'); eve.StartTime = new DateTime(au_now.Year, au_now.Month, au_now.Day, int.Parse(fields[0]), int.Parse(fields[1]), int.Parse(fields[2])); //MainApp.log_info(eve.ToString()); schedule.Add(eve); } MainApp.g_working = true; return(schedule); } catch (Exception ex) { MainApp.log_error("DynHelperError: " + ex.Message + "\n" + ex.StackTrace); MainApp.g_working = false; return(null); } }
public async Task <OddOverview> get_runner_odds(string event_id) { XDocument doc; string res; try { OddOverview overview = new OddOverview(); overview.EveID = event_id; string endpoint = $"{ep}GetData.asp?SessionID={session_id}&Method=GetRunnerOdds&EventID={event_id}"; res = await WRequest.get_response(endpoint); doc = XDocument.Parse(res); if (check_session(doc) == false) { if (res.Contains("Request Limit Exceeded")) { await Task.Delay(1000); return(await get_runner_odds(event_id)); } MainApp.log_error("Error getting running odds"); MainApp.log_error(res); MainApp.g_working = false; return(null); } IEnumerable <XElement> elems; try { elems = doc.Element("Data").Element("RunnerOdds").Elements(); } catch (Exception ee) { MainApp.log_error("DynHelperError: " + ee.Message + "\n" + ee.StackTrace); MainApp.g_working = false; return(null); } overview.Odds = new List <OddOneBookie>(); foreach (var elem in elems) { string name = elem.Name.ToString(); string val = elem.Value.ToString(); if (name == "RNo") { overview.RNo = new List <string>(val.Split(',')); } else if (name == "RName") { overview.RName = new List <string>(val.Split(',')); } else { string bookie; if (OddBookieMap.map.TryGetValue(name, out bookie)) { OddOneBookie odd_one = new OddOneBookie(); odd_one.OddName = name; odd_one.Bookie = bookie; odd_one.Odds = new List <decimal>(val.Split(',').Select(x => x.ToString() == "" ? 0 : decimal.Parse(x))); overview.Odds.Add(odd_one); } } } MainApp.g_working = true; return(overview); } catch (Exception ex) { MainApp.log_error("DynHelperError: " + ex.Message + "\n" + ex.StackTrace); MainApp.g_working = false; return(null); } }