using System; using System.Collections.Generic; using System.Data.SqlClient; using log4net; namespace bsmd.pasttrack.service { public class Service : IService { private readonly static ILog _log = LogManager.GetLogger(typeof(Service)); public Pasttrack[] GetPasttrack(string lookup, string mins) { List aList = new List(); if (!string.IsNullOrEmpty(lookup)) { if (lookup.Length == 9) { if (Int32.TryParse(lookup, out int mmsi_val) && Int32.TryParse(mins, out int mins_val)) { try { SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString); con.Open(); string cmdText = string.Format("select Latitude, Longitude, Heading, Timestamp from aisposreport where mmsi=@MMSI And timestamp > DATEADD(MINUTE, @MIN, GETDATE()) order by timestamp desc"); SqlCommand cmd = new SqlCommand(cmdText, con); cmd.Parameters.AddWithValue("@MMSI", mmsi_val); cmd.Parameters.AddWithValue("@MIN", -mins_val); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Pasttrack p = new Pasttrack { Latitude = (double)reader.GetInt32(0) / 600000.0, Longitude = (double)reader.GetInt32(1) / 600000.0, Heading = reader.GetInt32(2), Timestamp = reader.GetDateTime(3) }; aList.Add(p); } reader.Close(); con.Close(); } catch (SqlException ex) { _log.ErrorFormat("Error on data query: {0}", ex.ToString()); } } else { _log.WarnFormat("invalid parameters: mins {0} mmsi {1}", mins, lookup); } } else if(lookup.Length == 7) { if (Int32.TryParse(lookup, out int imo_val) && Int32.TryParse(mins, out int mins_val)) { try { SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString); con.Open(); string cmdText = string.Format("select Latitude, Longitude, Heading, Timestamp from aisposreport JOIN aisstaticdata ON aisposreport.MMSI = aisstaticdata.mmsi where imoNumber = @IMO AND timestamp > DATEADD(MINUTE, @MIN, GETDATE()) order by timestamp desc"); SqlCommand cmd = new SqlCommand(cmdText, con); cmd.Parameters.AddWithValue("@IMO", imo_val); cmd.Parameters.AddWithValue("@MIN", -mins_val); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Pasttrack p = new Pasttrack { Latitude = (double)reader.GetInt32(0) / 600000.0, Longitude = (double)reader.GetInt32(1) / 600000.0, Heading = reader.GetInt32(2), Timestamp = reader.GetDateTime(3) }; aList.Add(p); } reader.Close(); con.Close(); } catch (SqlException ex) { _log.ErrorFormat("Error on data query: {0}", ex.ToString()); } } else { _log.WarnFormat("invalid parameters: mins {0} mmsi {1}", mins, lookup); } } else { _log.WarnFormat("invalid parameters: mins {0} mmsi {1}", mins, lookup); } } _log.InfoFormat("Result pasttrack array contains {0} elems", aList.Count); return aList.ToArray(); } } }