Ejemplo n.º 1
0
        public void AnalyzeFile(string filename)
        {
            System.IO.StreamReader sr = null;
            try
            {
                for (int i = 0; i < 30; i++)
                {
                    try
                    {
                        sr = new System.IO.StreamReader(filename, Encoding.Default);
                        break;
                    }
                    catch (Exception ee)
                    {
                        System.Diagnostics.Debug.WriteLine(ee.Message);
                        System.Threading.Thread.Sleep(1000);
                    }
                }
                if (sr == null)
                {
                    throw new ApplicationException("Could not open input file, copy error?");
                }
                string header = sr.ReadLine();

                if (header == null)
                {
                    return;
                }

                string[] fields        = header.Split(SplitChars);
                bool     isOs2010Files = fields[0].StartsWith("OS", StringComparison.Ordinal);

                /*Detect OS format*/
                int fldID;
                int fldSI;
                int fldFName;
                int fldEName;
                int fldClub;
                int fldClass;
                int fldStart;
                int fldTime;
                int fldStatus;
                int fldFirstPost;
                int fldLeg;
                int fldFinish;
                int fldTxt1, fldTxt2, fldTxt3;
                int fldTotalTime;
                OxTools.DetectOxCSVFormat(OxTools.SourceProgram.OS, fields, out fldID, out fldSI, out fldFName, out fldEName, out fldClub, out fldClass, out fldStart, out fldTime, out fldStatus, out fldFirstPost, out fldLeg, out fldFinish, out fldTxt1, out fldTxt2, out fldTxt3, out fldTotalTime);

                if (fldID == -1 || fldSI == -1 || fldFName == -1 || fldEName == -1 || fldClub == -1 || fldClass == -1 ||
                    fldStart == -1 || fldTime == -1 ||
                    fldStart == -1 || fldFirstPost == -1 || fldLeg == -1)
                {
                    throw new System.IO.IOException("Not OS-formatted file!");
                }

                string tmp;
                var    teamStartTimes = new Dictionary <string, int>();
                var    teamStatuses   = new Dictionary <string, int>();
                while ((tmp = sr.ReadLine()) != null)
                {
                    string[] parts = tmp.Split(SplitChars);

                    /* check so that the line is not incomplete*/
                    int id = Convert.ToInt32(parts[fldLeg]) * 1000000 + Convert.ToInt32(parts[fldID]);

                    string name  = parts[fldFName].Trim('\"') + " " + parts[fldEName].Trim('\"');
                    string club  = parts[fldClub].Trim('\"');
                    string Class = parts[fldClass].Trim('\"') + "-" + parts[fldLeg].Trim('\"');
                    int    leg   = Convert.ToInt32(parts[fldLeg].Trim('\"'));
                    int    start = strTimeToInt(parts[fldStart]);
                    int    time  = strTimeToInt(parts[fldTime]);

                    int status = 9;
                    try
                    {
                        status = Convert.ToInt32(parts[fldStatus]);
                        if (status == 0 && time < 0)
                        {
                            status = 9;
                        }
                    }
                    catch
                    {
                    }

                    int totalTime   = -1;
                    int totalStatus = status;

                    if (isOs2010Files)
                    {
                        if (fldTotalTime != -1)
                        {
                            //OK We have a totaltimefield..
                            //If totaltime set, use it as time (and status is status)
                            //Else, check if runner on course (status == 0 and FinishTime is empty => Status = 9)
                            //Else, something is not right, set status if <> 0, else set mp

                            if (!string.IsNullOrEmpty(parts[fldTotalTime]))
                            {
                                totalTime = strTimeToInt(parts[fldTotalTime]);
                            }
                            else if (status == 9)
                            {
                                //Runner still on course
                            }
                            else
                            {
                                totalStatus = status != 0 ? status : 3;
                                totalTime   = -3;
                            }
                        }
                        else
                        {
                            string key = parts[fldClass].Trim('\"') + ";" + club;
                            if (!teamStartTimes.ContainsKey(key))
                            {
                                teamStartTimes.Add(key, start);
                            }
                            else if (teamStartTimes[key] > start)
                            {
                                teamStartTimes[key] = start;
                            }

                            if (teamStatuses.ContainsKey(key))
                            {
                                int earlierStatus = teamStatuses[key];
                                if (status == 0 && earlierStatus != 0)
                                {
                                    totalStatus = earlierStatus;
                                }
                            }
                            else if (status != 0)
                            {
                                teamStatuses.Add(key, status);
                            }

                            if (time >= 0)
                            {
                                totalTime = strTimeToInt(parts[fldFinish]) - teamStartTimes[key];
                            }
                        }
                    }



                    var splittimes = new List <ResultStruct>();
                    /*parse splittimes*/
                    var codes = new List <int>();
                    for (int i = fldFirstPost; i < parts.Length - 4; i++)
                    {
                        if (parts[i + 1].Length == 0 ||
                            parts[i + 2].Length == 0)
                        {
                            i += 3;
                            continue;
                        }
                        var s = new ResultStruct();
                        try
                        {
                            i++;
                            s.ControlCode = Convert.ToInt32(parts[i]);

                            if (s.ControlCode == 999 && status == 0)
                            {
                                i++;
                                if (time == -1)
                                {
                                    time = strTimeToInt(parts[i]);
                                }
                                i++;
                            }
                            else
                            {
                                s.ControlCode += 1000;
                                while (codes.Contains(s.ControlCode))
                                {
                                    s.ControlCode += 1000;
                                }
                                codes.Add(s.ControlCode);
                                i++;
                                s.Time = strTimeToInt(parts[i]);
                                i++;
                                s.Place = 0;
                                try
                                {
                                    s.Place = Convert.ToInt32(parts[i]);
                                }
                                catch
                                { }

                                splittimes.Add(s);
                            }
                        }
                        catch
                        {
                        }
                    }
                    FireOnResult(new RelayResult
                    {
                        ID            = id,
                        LegNumber     = leg,
                        RunnerName    = name,
                        RunnerClub    = club,
                        Class         = Class,
                        StartTime     = start,
                        Time          = time,
                        Status        = status,
                        SplitTimes    = splittimes,
                        OverallTime   = totalTime,
                        OverallStatus = totalStatus
                    });
                }
            }
            catch (Exception ee)
            {
                FireLogMsg("ERROR in OSParser: " + ee.Message);
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }
        }
Ejemplo n.º 2
0
        public void AnalyzeFile(string filename)
        {
            System.IO.StreamReader sr =null;
            try
            {
                for (int i = 0; i < 30; i++)
                {
                    try
                    {
                        sr = new System.IO.StreamReader(filename, Encoding.Default);
                        break;
                    }
                    catch (Exception ee)
                    {
                        System.Diagnostics.Debug.WriteLine(ee.Message);
                        System.Threading.Thread.Sleep(1000);
                    }
                }
                if (sr == null)
                    throw new ApplicationException("Could not open input file, copy error?");
                string header = sr.ReadLine();

                if (header == null)
                {
                    return;
                }

                string[] fields = header.Split(SplitChars);
                bool isOs2010Files = fields[0].StartsWith("OS", StringComparison.Ordinal);

                /*Detect OS format*/
                int fldID;
                int fldSI;
                int fldFName;
                int fldEName;
                int fldClub;
                int fldClass;
                int fldStart;
                int fldTime;
                int fldStatus;
                int fldFirstPost;
                int fldLeg;
                int fldFinish;
                int fldTxt1, fldTxt2, fldTxt3;
                int fldTotalTime;
                OxTools.DetectOxCSVFormat(OxTools.SourceProgram.OS, fields, out fldID, out fldSI, out fldFName, out fldEName, out fldClub, out fldClass, out fldStart, out fldTime, out fldStatus, out fldFirstPost, out fldLeg, out fldFinish, out fldTxt1, out fldTxt2, out fldTxt3, out fldTotalTime);

                if (fldID == -1 || fldSI == -1 || fldFName == -1 || fldEName == -1 || fldClub == -1 || fldClass == -1
                    || fldStart == -1 || fldTime == -1
                    || fldStart == -1 || fldFirstPost == -1 || fldLeg == -1)
                {
                    throw new System.IO.IOException("Not OS-formatted file!");
                }

                string tmp;
                var teamStartTimes = new Dictionary<string, int>();
                var teamStatuses = new Dictionary<string, int>();
                while ((tmp = sr.ReadLine()) != null)
                {
                    string[] parts = tmp.Split(SplitChars);

                    /* check so that the line is not incomplete*/
                    int id = Convert.ToInt32(parts[fldLeg])*1000000 + Convert.ToInt32(parts[fldID]);

                    string name = parts[fldFName].Trim('\"') + " " + parts[fldEName].Trim('\"');
                    string club = parts[fldClub].Trim('\"');
                    string Class = parts[fldClass].Trim('\"') + "-" + parts[fldLeg].Trim('\"');
                    int leg = Convert.ToInt32(parts[fldLeg].Trim('\"'));
                    int start = strTimeToInt(parts[fldStart]);
                    int time = strTimeToInt(parts[fldTime]);

                    int status = 9;
                    try
                    {
                        status = Convert.ToInt32(parts[fldStatus]);
                        if (status == 0 && time < 0)
                            status = 9;

                    }
                    catch
                    {
                    }

                    int totalTime = -1;
                    int totalStatus = status;

                    if (isOs2010Files)
                    {
                        if (fldTotalTime != -1)
                        {
                            //OK We have a totaltimefield..
                            //If totaltime set, use it as time (and status is status)
                            //Else, check if runner on course (status == 0 and FinishTime is empty => Status = 9)
                            //Else, something is not right, set status if <> 0, else set mp

                            if (!string.IsNullOrEmpty(parts[fldTotalTime]))
                            {
                                totalTime = strTimeToInt(parts[fldTotalTime]);
                            }
                            else if (status == 9)
                            {
                                //Runner still on course
                            }
                            else
                            {
                                totalStatus = status != 0 ? status : 3;
                                totalTime = -3;
                            }
                        }
                        else
                        {
                            string key = parts[fldClass].Trim('\"') + ";" + club;
                            if (!teamStartTimes.ContainsKey(key))
                            {
                                teamStartTimes.Add(key, start);
                            }
                            else if (teamStartTimes[key] > start)
                            {
                                teamStartTimes[key] = start;
                            }

                            if (teamStatuses.ContainsKey(key))
                            {
                                int earlierStatus = teamStatuses[key];
                                if (status == 0 && earlierStatus != 0)
                                    totalStatus = earlierStatus;
                            }
                            else if (status != 0)
                            {
                                teamStatuses.Add(key, status);
                            }

                            if (time >= 0)
                            {
                                totalTime = strTimeToInt(parts[fldFinish]) - teamStartTimes[key];
                            }
                        }
                    }

                    var splittimes = new List<ResultStruct>();
                    /*parse splittimes*/
                    var codes = new List<int>();
                    for (int i = fldFirstPost; i < parts.Length - 4; i++)
                    {
                        if (parts[i + 1].Length == 0
                            || parts[i + 2].Length == 0)
                        {
                            i += 3;
                            continue;
                        }
                        var s = new ResultStruct();
                        try
                        {
                            i++;
                            s.ControlCode = Convert.ToInt32(parts[i]);

                            if (s.ControlCode == 999 && status == 0)
                            {
                                i++;
                                if (time == -1)
                                    time = strTimeToInt(parts[i]);
                                i++;
                            }
                            else
                            {

                                s.ControlCode += 1000;
                                while (codes.Contains(s.ControlCode))
                                {
                                    s.ControlCode += 1000;
                                }
                                codes.Add(s.ControlCode);
                                i++;
                                s.Time = strTimeToInt(parts[i]);
                                i++;
                                s.Place = 0;
                                try
                                {
                                    s.Place = Convert.ToInt32(parts[i]);
                                }
                                catch
                                { }

                                splittimes.Add(s);
                            }
                        }
                        catch
                        {
                        }

                    }
                    FireOnResult(new RelayResult
                    {
                        ID = id,
                        LegNumber = leg,
                        RunnerName = name,
                        RunnerClub = club,
                        Class = Class,
                        StartTime = start,
                        Time = time,
                        Status = status,
                        SplitTimes = splittimes,
                        OverallTime = totalTime,
                        OverallStatus = totalStatus
                    });
                }
            }
            catch (Exception ee)
            {
                FireLogMsg("ERROR in OSParser: " + ee.Message);
            }
            finally
            {
                if (sr != null)
                    sr.Close();
            }
        }
Ejemplo n.º 3
0
        public void AnalyzeFile(string filename)
        {
            System.IO.StreamReader sr = null;
            try
            {
                for (int i = 0; i < 30; i++)
                {
                    try
                    {
                        sr = new System.IO.StreamReader(filename, Encoding.Default);
                        break;
                    }
                    catch (Exception ee)
                    {
                        System.Diagnostics.Debug.WriteLine(ee.Message);
                    }
                }
                if (sr == null)
                {
                    throw new ApplicationException("Could not open input file, copy error?");
                }
                string header = sr.ReadLine();

                string[] fields = header.Split(SplitChars);

                /*Detect OE format*/
                int fldID, fldSI, fldFName, fldEName, fldClub, fldClass, fldStart, fldTime, fldStatus, fldFirstPost, fldText1, fldText2, fldText3, fldFinish, fldLeg;
                int fldTotalTime;
                OxTools.DetectOxCSVFormat(OxTools.SourceProgram.OE, fields, out fldID, out fldSI, out fldFName, out fldEName, out fldClub, out fldClass, out fldStart, out fldTime, out fldStatus, out fldFirstPost, out fldLeg, out fldFinish, out fldText1, out fldText2, out fldText3, out fldTotalTime);

                if (fldID == -1 || fldSI == -1 || fldFName == -1 || fldEName == -1 || fldClub == -1 || fldClass == -1 ||
                    fldStart == -1 || fldTime == -1 ||
                    fldStart == -1 || fldFirstPost == -1)
                {
                    throw new System.IO.IOException("Not OE-formatted file!");
                }


                if (fldID == -1 || fldSI == -1 || fldFName == -1 || fldEName == -1 || fldClub == -1 || fldClass == -1 ||
                    fldStart == -1 || fldTime == -1)
                {
                    throw new System.IO.IOException("Not OE-formatted file!");
                }

                string tmp;
                while ((tmp = sr.ReadLine()) != null)
                {
                    string[] parts = tmp.Split(SplitChars);

                    /* check so that the line is not incomplete*/
                    int    id    = Convert.ToInt32(parts[fldID]);
                    string name  = parts[fldFName].Trim('\"') + " " + parts[fldEName].Trim('\"');
                    string club  = parts[fldClub].Trim('\"');
                    string Class = parts[fldClass].Trim('\"');
                    int    start = strTimeToInt(parts[fldStart]);
                    int    time  = strTimeToInt(parts[fldTime]);


                    int status = 0;
                    try
                    {
                        status = Convert.ToInt32(parts[fldStatus]);
                    }
                    catch
                    {
                    }

                    var splittimes = new List <ResultStruct>();
                    /*parse splittimes*/
                    var codes = new List <int>();
                    if (fldFirstPost >= 0)
                    {
                        for (int i = fldFirstPost; i < parts.Length - 4; i++)
                        {
                            if (parts[i + 1].Length == 0 ||
                                parts[i + 2].Length == 0)
                            {
                                i += 3;
                                continue;
                            }
                            var s = new ResultStruct();
                            try
                            {
                                //s.ControlNo = Convert.ToInt32(parts[i]);
                                i++;
                                s.ControlCode = Convert.ToInt32(parts[i]);

                                if (s.ControlCode == 999)
                                {
                                    i++;
                                    if (time == -1 && status == 0)
                                    {
                                        time = strTimeToInt(parts[i]);
                                    }

                                    i++;
                                }
                                else
                                {
                                    s.ControlCode += 1000;
                                    while (codes.Contains(s.ControlCode))
                                    {
                                        s.ControlCode += 1000;
                                    }
                                    codes.Add(s.ControlCode);

                                    i++;
                                    s.Time = strTimeToInt(parts[i]);
                                    i++;

                                    if (s.Time > 0)
                                    {
                                        s.Place = 0;
                                        try
                                        {
                                            s.Place = Convert.ToInt32(parts[i]);
                                        }
                                        catch
                                        { }

                                        splittimes.Add(s);
                                    }
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                    FireOnResult(new Result {
                        ID         = id,
                        RunnerName = name,
                        RunnerClub = club,
                        Class      = Class,
                        StartTime  = start,
                        Time       = time,
                        Status     = status,
                        SplitTimes = splittimes
                    });
                }
            }
            catch (Exception ee)
            {
                FireLogMsg("ERROR in OEPArser: " + ee.Message);
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }
        }
Ejemplo n.º 4
0
        public void AnalyzeFile(string filename)
        {
            System.IO.StreamReader sr =null;
            try
            {
                for (int i = 0; i < 30; i++)
                {
                    try
                    {
                        sr = new System.IO.StreamReader(filename, Encoding.Default);
                        break;
                    }
                    catch (Exception ee)
                    {
                        System.Diagnostics.Debug.WriteLine(ee.Message);
                    }
                }
                if (sr == null)
                    throw new ApplicationException("Could not open input file, copy error?");
                string header = sr.ReadLine();

                string[] fields = header.Split(SplitChars);

                /*Detect OE format*/
                int fldID, fldSI, fldFName, fldEName, fldClub, fldClass, fldStart, fldTime, fldStatus, fldFirstPost, fldText1, fldText2, fldText3, fldFinish, fldLeg;
                int fldTotalTime;
                OxTools.DetectOxCSVFormat(OxTools.SourceProgram.OE, fields, out fldID, out fldSI, out fldFName, out fldEName, out fldClub, out fldClass, out fldStart, out fldTime, out fldStatus, out fldFirstPost, out fldLeg, out fldFinish, out fldText1, out fldText2, out fldText3, out fldTotalTime);

                if (fldID == -1 || fldSI == -1 || fldFName == -1 || fldEName == -1 || fldClub == -1 || fldClass == -1
               || fldStart == -1 || fldTime == -1
               || fldStart == -1 || fldFirstPost == -1)
                {
                    throw new System.IO.IOException("Not OE-formatted file!");
                }

                if (fldID == -1 || fldSI == -1 || fldFName == -1 || fldEName == -1 || fldClub == -1 || fldClass == -1
                    || fldStart == -1 || fldTime == -1)
                    throw new System.IO.IOException("Not OE-formatted file!");

                string tmp;
                while ((tmp = sr.ReadLine()) != null)
                {
                    string[] parts = tmp.Split(SplitChars);

                    /* check so that the line is not incomplete*/
                    int id = Convert.ToInt32(parts[fldID]);
                    string name = parts[fldFName].Trim('\"') + " " + parts[fldEName].Trim('\"');
                    string club = parts[fldClub].Trim('\"');
                    string Class = parts[fldClass].Trim('\"');
                    int start = strTimeToInt(parts[fldStart]);
                    int time = strTimeToInt(parts[fldTime]);

                    int status = 0;
                    try
                    {
                        status = Convert.ToInt32(parts[fldStatus]);
                    }
                    catch
                    {
                    }

                    var splittimes = new List<ResultStruct>();
                    /*parse splittimes*/
                    var codes = new List<int>();
                    if (fldFirstPost >= 0)
                    {
                        for (int i = fldFirstPost; i < parts.Length - 4; i++)
                        {
                            if (parts[i + 1].Length == 0
                                || parts[i + 2].Length == 0)
                            {
                                i += 3;
                                continue;
                            }
                            var s = new ResultStruct();
                            try
                            {
                                //s.ControlNo = Convert.ToInt32(parts[i]);
                                i++;
                                s.ControlCode = Convert.ToInt32(parts[i]);

                                if (s.ControlCode == 999)
                                {
                                    i++;
                                    if (time == -1 && status == 0)
                                        time = strTimeToInt(parts[i]);

                                    i++;
                                }
                                else
                                {
                                    s.ControlCode += 1000;
                                    while (codes.Contains(s.ControlCode))
                                    {
                                        s.ControlCode += 1000;
                                    }
                                    codes.Add(s.ControlCode);

                                    i++;
                                    s.Time = strTimeToInt(parts[i]);
                                    i++;

                                    if (s.Time > 0)
                                    {
                                        s.Place = 0;
                                        try
                                        {
                                            s.Place = Convert.ToInt32(parts[i]);
                                        }
                                        catch
                                        { }

                                        splittimes.Add(s);
                                    }
                                }
                            }
                            catch
                            {
                            }

                        }
                    }
                    FireOnResult(new Result{
                        ID = id,
                        RunnerName = name,
                        RunnerClub = club,
                        Class = Class,
                        StartTime = start,
                        Time = time,
                        Status = status,
                        SplitTimes = splittimes
                    });
                }
            }
            catch (Exception ee)
            {
                FireLogMsg("ERROR in OEPArser: " + ee.Message);
            }
            finally
            {
                if (sr != null)
                    sr.Close();
            }
        }
Ejemplo n.º 5
0
        private void Run()
        {
            while (m_continue)
            {
                try
                {
                    if (m_connection.State != ConnectionState.Open)
                    {
                        if (m_connection is System.Data.H2.H2Connection)
                        {
                            (m_connection as System.Data.H2.H2Connection).Open("root", "");
                        }
                        else
                        {
                            m_connection.Open();
                        }
                    }

                    string paramOper = "?";
                    if (m_connection is MySql.Data.MySqlClient.MySqlConnection)
                    {
                        paramOper = "?date";
                    }

                    /*Detect eventtype*/

                    string     scmd = "select eventForm from events where eventid = " + m_eventID;
                    IDbCommand cmd  = m_connection.CreateCommand();
                    cmd.CommandText = scmd;

                    var  form    = cmd.ExecuteScalar() as string;
                    bool isRelay = form.ToLower().Contains("relay");

                    /* detect ola version*/
                    scmd            = "select versionNumber from Version";
                    cmd             = m_connection.CreateCommand();
                    cmd.CommandText = scmd;

                    int version = Convert.ToInt32(cmd.ExecuteScalar());

                    bool isOla5 = version >= 500;


                    string baseCommand      = "select results.modifyDate, results.totalTime, results.position, persons.familyname as lastname, persons.firstname as firstname, clubs.name as clubname, eventclasses.shortName, results.runnerStatus, results.entryid, results.allocatedStartTime, results.starttime from results, entries, Persons, Clubs, raceclasses,eventclasses where raceclasses.eventClassID = eventClasses.eventClassID and results.raceClassID = raceclasses.raceclassid and raceClasses.eventRaceId = " + m_eventRaceId + " and eventclasses.eventid = " + m_eventID + " and results.entryid = entries.entryid and entries.competitorid = persons.personid and persons.clubid = clubs.clubid and results.runnerStatus != 'notActivated'  and results.modifyDate > " + paramOper;
                    string splitbaseCommand = "select splittimes.modifyDate, splittimes.passedTime, Controls.ID, results.entryid, results.allocatedStartTime, persons.familyname as lastname, persons.firstname as firstname, clubs.name as clubname, eventclasses.shortName, splittimes.passedCount from splittimes, results, SplitTimeControls, Controls, eventClasses, raceClasses, Persons, Clubs, entries where splittimes.resultraceindividualnumber = results.resultid and SplitTimes.splitTimeControlID = SplitTimeControls.splitTimeControlID and SplitTimeControls.timingControl = Controls.controlid and Controls.eventRaceId = " + m_eventRaceId + " and raceclasses.eventClassID = eventClasses.eventClassID and results.raceClassID = raceclasses.raceclassid and raceClasses.eventRaceId = " + m_eventRaceId + " and eventclasses.eventid = " + m_eventID + " and results.entryid = entries.entryid and entries.competitorid = persons.personid and persons.clubid = clubs.clubid and splitTimes.modifyDate > " + paramOper;
                    if (isOla5)
                    {
                        baseCommand      = "select results.modifyDate, results.totalTime, results.position, persons.familyname as lastname, persons.firstname as firstname, organisations.shortname as clubname, eventclasses.shortName, results.runnerStatus, results.entryid, results.allocatedStartTime, results.starttime, entries.allocationControl, entries.allocationEntryId from results, entries, Persons, organisations, raceclasses,eventclasses where raceclasses.eventClassID = eventClasses.eventClassID and results.raceClassID = raceclasses.raceclassid and raceClasses.eventRaceId = " + m_eventRaceId + " and eventclasses.eventid = " + m_eventID + " and results.entryid = entries.entryid and entries.competitorid = persons.personid and persons.defaultorganisationid = organisations.organisationid and raceClasses.raceClassStatus <> 'notUsed' and results.modifyDate > " + paramOper;
                        splitbaseCommand = "select splittimes.modifyDate, splittimes.passedTime, Controls.ID, results.entryid, results.allocatedStartTime, results.starttime, persons.familyname as lastname, persons.firstname as firstname, organisations.name as clubname, eventclasses.shortName, splittimes.passedCount,entries.allocationControl, entries.allocationEntryId from splittimes, results, SplitTimeControls, Controls, eventClasses, raceClasses, Persons, organisations, entries where splittimes.resultraceindividualnumber = results.resultid and SplitTimes.splitTimeControlID = SplitTimeControls.splitTimeControlID and SplitTimeControls.timingControl = Controls.controlid and Controls.eventRaceId = " + m_eventRaceId + " and raceclasses.eventClassID = eventClasses.eventClassID and results.raceClassID = raceclasses.raceclassid and raceClasses.eventRaceId = " + m_eventRaceId + " and eventclasses.eventid = " + m_eventID + " and results.entryid = entries.entryid and entries.competitorid = persons.personid and persons.defaultorganisationid = organisations.organisationid and raceClasses.raceClassStatus <> 'notUsed' and  splitTimes.modifyDate > " + paramOper;
                    }

                    if (isRelay)
                    {
                        baseCommand      = "select results.modifyDate,results.totalTime, results.position, persons.familyname as lastname, persons.firstname as firstname, entries.teamName as clubname, eventclasses.shortName, raceclasses.relayleg, results.runnerStatus, results.resultId as entryId, results.finishTime, results.allocatedStartTime, results.starttime, (select firststarttime from raceclasses rc where rc.eventClassId = eventclasses.EventClassID and rc.relayleg=1 and rc.eventRaceId = " + m_eventRaceId + ") as firststarttime from results, entries, Persons, raceclasses,eventclasses where raceclasses.eventClassID = eventClasses.eventClassID and results.raceClassID = raceclasses.raceclassid and raceClasses.eventRaceId = " + m_eventRaceId + " and eventclasses.eventid = " + m_eventID + " and results.entryid = entries.entryid and results.relaypersonid = persons.personid and raceClasses.raceClassStatus <> 'notUsed' and  results.modifyDate > " + paramOper;
                        splitbaseCommand = "select splittimes.modifyDate, splittimes.passedTime, Controls.ID, results.resultId as entryId, results.allocatedStartTime, persons.familyname as lastname, persons.firstname as firstname, entries.teamName as clubname, eventclasses.shortName,raceclasses.relayleg, splittimes.passedCount,results.allocatedStartTime, (select firststarttime from raceclasses rc where rc.eventClassId = eventclasses.EventClassID and rc.relayleg=1 and rc.eventRaceId = " + m_eventRaceId + ") as firststarttime  from splittimes, results, SplitTimeControls, Controls, eventClasses, raceClasses, Persons, entries where splittimes.resultraceindividualnumber = results.resultid and SplitTimes.splitTimeControlID = SplitTimeControls.splitTimeControlID and SplitTimeControls.timingControl = Controls.controlid and Controls.eventRaceId = " + m_eventRaceId + " and raceclasses.eventClassID = eventClasses.eventClassID and results.raceClassID = raceclasses.raceclassid and raceClasses.eventRaceId = " + m_eventRaceId + " and eventclasses.eventid = " + m_eventID + " and results.entryid = entries.entryid and results.relaypersonid = persons.personid and raceClasses.raceClassStatus <> 'notUsed' and splitTimes.modifyDate > " + paramOper;
                    }

                    ReadRadioControls();

                    cmd.CommandText = baseCommand;
                    IDbCommand cmdSplits = m_connection.CreateCommand();
                    cmdSplits.CommandText = splitbaseCommand;
                    IDbDataParameter param = cmd.CreateParameter();
                    param.ParameterName = "date";
                    if (m_connection is MySql.Data.MySqlClient.MySqlConnection || m_connection is System.Data.H2.H2Connection)
                    {
                        param.DbType = DbType.String;
                        param.Value  = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    }
                    else
                    {
                        param.DbType = DbType.DateTime;
                        param.Value  = DateTime.Now;
                    }


                    IDbDataParameter splitparam = cmdSplits.CreateParameter();
                    splitparam.ParameterName = "date";
                    if (m_connection is MySql.Data.MySqlClient.MySqlConnection || m_connection is System.Data.H2.H2Connection)
                    {
                        splitparam.DbType = DbType.String;
                        splitparam.Value  = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    }
                    else
                    {
                        splitparam.DbType = DbType.DateTime;
                        splitparam.Value  = DateTime.Now;
                    }

                    DateTime lastDateTime      = DateTime.Now.AddMonths(-120);
                    DateTime lastSplitDateTime = DateTime.Now.AddMonths(-120);
                    param.Value      = lastDateTime;
                    splitparam.Value = lastSplitDateTime;

                    cmd.Parameters.Add(param);
                    cmdSplits.Parameters.Add(splitparam);

                    FireLogMsg("OLA Monitor thread started");
                    IDataReader reader      = null;
                    var         runnerPairs = new Dictionary <int, RunnerPair>();
                    while (m_continue)
                    {
                        string lastRunner = "";
                        try
                        {
                            /*Kontrollera om nya klasser*/
                            /*Kontrollera om nya resultat*/
                            if (cmd is MySql.Data.MySqlClient.MySqlCommand || m_connection is System.Data.H2.H2Connection)
                            {
                                (cmd.Parameters["date"] as IDbDataParameter).Value       = lastDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
                                (cmdSplits.Parameters["date"] as IDbDataParameter).Value = lastSplitDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
                            }
                            else
                            {
                                (cmd.Parameters["date"] as IDbDataParameter).Value       = lastDateTime;
                                (cmdSplits.Parameters["date"] as IDbDataParameter).Value = lastSplitDateTime;
                            }


                            cmd.Prepare();
                            reader = cmd.ExecuteReader();
                            while (reader.Read())
                            {
                                int    time = 0, runnerID = 0, iStartTime = 0;
                                string famName = "", fName = "", club = "", classN = "", status = "";

                                try
                                {
                                    string   sModDate = Convert.ToString(reader[0]);
                                    DateTime modDate  = ParseDateTime(sModDate);
                                    lastDateTime = (modDate > lastDateTime ? modDate : lastDateTime);
                                    runnerID     = Convert.ToInt32(reader["entryid"].ToString());

                                    time = -9;
                                    if (reader["totaltime"] != null && reader["totaltime"] != DBNull.Value)
                                    {
                                        time = Convert.ToInt32(reader["totalTime"].ToString());
                                    }

                                    famName = (reader["lastname"] as string);
                                    fName   = (reader["firstname"] as string);

                                    lastRunner = (string.IsNullOrEmpty(fName) ? "" : (fName + " ")) + famName;

                                    club   = (reader["clubname"] as string);
                                    classN = (reader["shortname"] as string);
                                    status = reader["runnerStatus"] as string; // reader.GetString(7);

                                    DateTime startTime = DateTime.MinValue;

                                    if (reader["allocatedStartTime"] != null && reader["allocatedStartTime"] != DBNull.Value)
                                    {
                                        string tTime = reader["allocatedStartTime"].ToString();
                                        startTime = ParseDateTime(tTime);
                                    }
                                    if (reader["starttime"] != null && reader["starttime"] != DBNull.Value)
                                    {
                                        string tTime = reader["starttime"].ToString();
                                        startTime = ParseDateTime(tTime);
                                    }


                                    iStartTime = 0;
                                    if (startTime > DateTime.MinValue)
                                    {
                                        iStartTime = (int)(startTime.TimeOfDay.TotalSeconds * 100);
                                    }

                                    if (isRelay)
                                    {
                                        classN = classN + "-" + Convert.ToString(reader["relayLeg"]);
                                        if (reader["finishTime"] != DBNull.Value)
                                        {
                                            DateTime ft = ParseDateTime(reader["finishTime"].ToString());

                                            if (reader["firststarttime"] != DBNull.Value)
                                            {
                                                DateTime ast = ParseDateTime(reader["firststarttime"].ToString());
                                                time = (int)((ft - ast).TotalSeconds * 100);
                                            }
                                        }
                                    }
                                }
                                catch (Exception ee)
                                {
                                    FireLogMsg(ee.Message);
                                }


                                /*
                                 *  time is seconds * 100
                                 *
                                 * valid status is
                                 *  notStarted
                                 *  finishedTimeOk
                                 *  finishedPunchOk
                                 *  disqualified
                                 *  finished
                                 *  movedUp
                                 *  walkOver
                                 *  started
                                 *  passed
                                 *  notValid
                                 *  notActivated
                                 *  notParticipating
                                 */
                                //EMMAClient.RunnerStatus rstatus = EMMAClient.RunnerStatus.Passed;
                                int rstatus = 0;
                                switch (status)
                                {
                                case "started":
                                    rstatus = 9;
                                    break;

                                case "notActivated":
                                    rstatus = 10;
                                    //rstatus = EMMAClient.RunnerStatus.NotStartedYet;
                                    break;

                                case "notStarted":
                                    rstatus = 1;
                                    //rstatus = EMMAClient.RunnerStatus.NotStarted;
                                    break;

                                case "disqualified":
                                    rstatus = 4;
                                    break;

                                case "notValid":
                                    rstatus = 3;
                                    //rstatus = EMMAClient.RunnerStatus.MissingPunch;
                                    break;

                                case "notParticipating":
                                    rstatus = 999;
                                    break;

                                case "walkOver":
                                    rstatus = 11;
                                    //rstatus = EMMAClient.RunnerStatus.WalkOver;
                                    break;

                                case "movedUp":
                                    rstatus = 12;
                                    break;
                                }
                                if (rstatus != 999)
                                {
                                    var res = new Result
                                    {
                                        ID         = runnerID,
                                        RunnerName = fName + " " + famName,
                                        RunnerClub = club,
                                        Class      = classN,
                                        StartTime  = iStartTime,
                                        Time       = time,
                                        Status     = rstatus
                                    };

                                    CheckAndCreatePairRunner(isRelay, reader, runnerPairs, runnerID, res);
                                }
                            }
                            reader.Close();

                            reader = cmdSplits.ExecuteReader();
                            while (reader.Read())
                            {
                                try
                                {
                                    string   smod = Convert.ToString(reader[0]);
                                    DateTime mod;
                                    mod = ParseDateTime(smod);

                                    lastSplitDateTime = (mod > lastSplitDateTime ? mod : lastSplitDateTime);

                                    string   tTime = Convert.ToString(reader[1]);
                                    DateTime pTime;
                                    pTime = ParseDateTime(tTime);
                                    int      sCont   = reader.GetInt32(2);
                                    int      entryid = Convert.ToInt32(reader["entryid"].ToString());
                                    DateTime startTime;

                                    if (isRelay && reader["firstStartTime"] != null && reader["firstStartTime"] != DBNull.Value)
                                    {
                                        tTime     = reader["firstStartTime"].ToString();
                                        startTime = ParseDateTime(tTime);
                                    }
                                    else if (reader["allocatedStartTime"] != null && reader["allocatedStartTime"] != DBNull.Value)
                                    {
                                        tTime     = reader["allocatedStartTime"].ToString();
                                        startTime = ParseDateTime(tTime);
                                    }
                                    else if (reader["starttime"] != null && reader["starttime"] != DBNull.Value)
                                    {
                                        tTime     = reader["starttime"].ToString();
                                        startTime = ParseDateTime(tTime);
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                    int passedCount = Convert.ToInt32(reader["passedCount"].ToString());

                                    TimeSpan rTid  = pTime - startTime;
                                    double   time  = rTid.TotalMilliseconds / 10;
                                    var      times = new List <ResultStruct>();
                                    var      t     = new ResultStruct();
                                    t.ControlCode = sCont + 1000 * passedCount;
                                    t.ControlNo   = 0;
                                    t.Time        = (int)time;
                                    times.Add(t);

                                    var    sfamName = reader["lastname"] as string;
                                    var    sfName   = reader["firstname"] as string;
                                    string name     = (string.IsNullOrEmpty(sfName) ? "" : (sfName + " ")) + sfamName;

                                    var club   = reader["clubname"] as string;
                                    var classn = reader["shortname"] as string;

                                    if (isRelay)
                                    {
                                        classn = classn + "-" + Convert.ToString(reader["relayLeg"]);
                                    }

                                    var res = new Result
                                    {
                                        ID         = entryid,
                                        RunnerName = name,
                                        RunnerClub = club,
                                        Class      = classn,
                                        StartTime  = 0,
                                        Time       = -2,
                                        Status     = 0,
                                        SplitTimes = times
                                    };

                                    CheckAndCreatePairRunner(isRelay, reader, runnerPairs, entryid, res);
                                }
                                catch (Exception ee)
                                {
                                    FireLogMsg(ee.Message);
                                }
                            }
                            reader.Close();

                            System.Threading.Thread.Sleep(1000);
                        }
                        catch (Exception ee)
                        {
                            if (reader != null)
                            {
                                reader.Close();
                            }
                            FireLogMsg("OLA Parser: " + ee.Message + " {parsing: " + lastRunner);

                            System.Threading.Thread.Sleep(100);

                            switch (m_connection.State)
                            {
                            case ConnectionState.Broken:
                            case ConnectionState.Closed:
                                m_connection.Close();
                                m_connection.Open();
                                break;
                            }
                        }
                    }
                }
                catch (Exception ee)
                {
                    FireLogMsg("OLA Parser: " + ee.Message);
                }
                finally
                {
                    if (m_connection != null)
                    {
                        m_connection.Close();
                    }
                    FireLogMsg("Disconnected");
                    FireLogMsg("OLA Monitor thread stopped");
                }
            }
        }