Example #1
0
        /// <summary>
        /// true, if all data *except the ID* is equal (case insensitive)
        /// </summary>
        /// <param name="eqSystem"></param>
        /// <returns></returns>
        public bool EqualsED(EDSystem eqSystem)
        {
            bool retValue = false;

            if (eqSystem != null)
            {
                if (ObjectCompare.EqualsNullable(this.Name, eqSystem.Name) &&
                    ObjectCompare.EqualsNullable(this.X, eqSystem.X) &&
                    ObjectCompare.EqualsNullable(this.Y, eqSystem.Y) &&
                    ObjectCompare.EqualsNullable(this.Z, eqSystem.Z) &&
                    ObjectCompare.EqualsNullable(this.Faction, eqSystem.Faction) &&
                    ObjectCompare.EqualsNullable(this.Population, eqSystem.Population) &&
                    ObjectCompare.EqualsNullable(this.Government, eqSystem.Government) &&
                    ObjectCompare.EqualsNullable(this.Allegiance, eqSystem.Allegiance) &&
                    ObjectCompare.EqualsNullable(this.State, eqSystem.State) &&
                    ObjectCompare.EqualsNullable(this.Security, eqSystem.Security) &&
                    ObjectCompare.EqualsNullable(this.PrimaryEconomy, eqSystem.PrimaryEconomy) &&
                    ObjectCompare.EqualsNullable(this.Power, eqSystem.Power) &&
                    ObjectCompare.EqualsNullable(this.PowerState, eqSystem.PowerState) &&
                    ObjectCompare.EqualsNullable(this.NeedsPermit, eqSystem.NeedsPermit) &&
                    ObjectCompare.EqualsNullable(this.UpdatedAt, eqSystem.UpdatedAt) &&
                    ObjectCompare.EqualsNullable(this.Simbad_Ref, eqSystem.Simbad_Ref))
                {
                    retValue = true;
                }
            }

            return(retValue);
        }
Example #2
0
        /// <summary>
        /// check if the stations of two stations are equal if the system
        /// exists in the EDDB data and in the own data
        /// </summary>
        /// <param name="ownSystem">system from own data</param>
        /// <param name="existingEDDNSystem">system from EDDB data</param>
        /// <param name="SystemCanBeDeleted">normally true, except there are differences between at least one stations.
        /// if so the system must be hold as reference. If a own data station is 100% equal (e.g. Commoditynames and other strings
        /// are not casesensitive compared) to the eddb station it will automatically deleted</param>
        private void checkStations(EDSystem ownSystem, EDSystem existingEDDNSystem, ref bool SystemCanBeDeleted, ref bool StationsChanged)
        {
            // own system can be deleted if the stations are equal, too
            List <EDStation> ownSystemStations = getStations(ownSystem.Name, enDataType.Data_Own);

            for (int j = 0; j < ownSystemStations.Count(); j++)
            {
                EDStation ownStation          = ownSystemStations[j];
                EDStation existingEDDNStation = getSystemStation(ownSystem.Name, ownSystemStations[j].Name);

                if (existingEDDNStation != null)
                {
                    if (existingEDDNStation.EqualsED(ownStation))
                    {
                        // no favour to hold it anymore
                        m_Stations[(int)enDataType.Data_Own].Remove(ownStation);
                        StationsChanged = true;
                    }
                    else
                    {
                        // copy the values and hold it
                        existingEDDNStation.getValues(ownStation);
                        SystemCanBeDeleted = false;
                    }
                }
                else
                {
                    // station is in EDDB not existingClassification, so we'll hold the station
                    SystemCanBeDeleted = false;
                    int newStationIndex = m_Stations[(int)enDataType.Data_Merged].Max(X => X.Id) + 1;

                    m_Stations[(int)enDataType.Data_Merged].Add(new EDStation(newStationIndex, existingEDDNSystem.Id, ownStation));
                }
            }
        }
Example #3
0
        private EDStation getSystemStation(string Systemname, string StationName)
        {
            EDStation wantedStation = null;
            EDSystem  wantedSystem  = getSystem(Systemname);

            if (wantedSystem != null)
            {
                wantedStation = m_Stations[(int)enDataType.Data_Merged].Find(x => (x.SystemId == wantedSystem.Id) && (x.Name.Equals(StationName)));
            }

            return(wantedStation);
        }
Example #4
0
        /// <summary>
        /// go and get station clones from the own data for a new station
        /// and adds them to the merged data
        /// </summary>
        /// <param name="systemFirstTimeVisited">new created system in merged data </param>
        private void copyStationsForNewSystem(EDSystem newSystem)
        {
            // get the list from own data with the name of the new station
            // (it's ok because it must be the same name)
            List <EDStation> ownSystemStations = getStations(newSystem.Name, enDataType.Data_Own);

            // get the gighest index
            int newStationIndex = m_Stations[(int)enDataType.Data_Merged].Max(X => X.Id);

            for (int j = 0; j < ownSystemStations.Count(); j++)
            {
                newStationIndex++;
                m_Stations[(int)enDataType.Data_Merged].Add(new EDStation(newStationIndex, newSystem.Id, ownSystemStations[j]));
            }
        }
Example #5
0
            /// <summary>
        /// returns a station in a system by name
        /// </summary>
        /// <param name="Systemname"></param>
        /// <param name="Locationname"></param>
        /// <returns></returns>
        /// <param name="System"></param>
        public EDStation getStation(string systemName, string stationName, out EDSystem System)
        {
            EDStation retValue;

            EDSystem SystemData = m_Systems[(int)enDataType.Data_Merged].Find(x => x.Name==systemName);

            if (SystemData != null)
                retValue = m_Stations[(int)enDataType.Data_Merged].Find(x => x.SystemId==SystemData.Id && x.Name.Equals(stationName, StringComparison.InvariantCultureIgnoreCase));
            else
                retValue = null;

            System = SystemData;

            return retValue;
        }
Example #6
0
        /// <summary>
        /// get all stations for a system from a particular list
        /// </summary>
        /// <param name="Systemname"></param>
        /// <returns></returns>
        public List <EDStation> getStations(string Systemname, enDataType wantedType)
        {
            List <EDStation> retValue;

            EDSystem SystemData = m_Systems[(int)wantedType].Find(x => x.Name == Systemname);

            if (SystemData != null)
            {
                retValue = m_Stations[(int)wantedType].FindAll(x => x.SystemId == SystemData.Id);
            }
            else
            {
                retValue = new List <EDStation>();
            }

            return(retValue);
        }
Example #7
0
        /// <summary>
        /// returns a station in a system by name
        /// </summary>
        /// <param name="Systemname"></param>
        /// <param name="Locationname"></param>
        /// <returns></returns>
        /// <param name="System"></param>
        public EDStation getStation(string systemName, string stationName, out EDSystem System)
        {
            EDStation retValue;

            EDSystem SystemData = m_Systems[(int)enDataType.Data_Merged].Find(x => x.Name == systemName);

            if (SystemData != null)
            {
                retValue = m_Stations[(int)enDataType.Data_Merged].Find(x => x.SystemId == SystemData.Id && x.Name.Equals(stationName, StringComparison.InvariantCultureIgnoreCase));
            }
            else
            {
                retValue = null;
            }

            System = SystemData;

            return(retValue);
        }
Example #8
0
        /// <summary>
        /// get coordinates of a system
        /// </summary>
        /// <param name="Systemname"></param>
        /// <returns></returns>
        public Point3D getSystemCoordinates(string Systemname)
        {
            Point3D retValue = null;

            if (!String.IsNullOrEmpty(Systemname))
            {
                if (!m_cachedLocations.TryGetValue(Systemname, out retValue))
                {
                    EDSystem mySystem = m_Systems[(int)enDataType.Data_Merged].Find(x => x.Name.Equals(Systemname, StringComparison.InvariantCultureIgnoreCase));

                    if (mySystem != null)
                    {
                        retValue = mySystem.SystemCoordinates();
                        m_cachedLocations.Add(Systemname, retValue);
                    }
                }
            }

            return(retValue);
        }
Example #9
0
        /// <summary>
        /// copy the values from another system exept for the ID
        /// </summary>
        /// <param name="ValueStation"></param>
        public void getValues(EDSystem ownSystem, bool getAll = false)
        {
            if (getAll)
            {
                Id = ownSystem.Id;
            }

            Name           = ownSystem.Name;
            X              = ownSystem.X;
            Y              = ownSystem.Y;
            Z              = ownSystem.Z;
            Faction        = ownSystem.Faction;
            Population     = ownSystem.Population;
            Government     = ownSystem.Government;
            Allegiance     = ownSystem.Allegiance;
            State          = ownSystem.State;
            Security       = ownSystem.Security;
            PrimaryEconomy = ownSystem.PrimaryEconomy;
            Power          = ownSystem.Power;
            PowerState     = ownSystem.PowerState;
            NeedsPermit    = ownSystem.NeedsPermit;
            UpdatedAt      = ownSystem.UpdatedAt;
            Simbad_Ref     = ownSystem.Simbad_Ref;
        }
Example #10
0
 /// <summary>
 /// imports the data from the list of systems
 /// </summary>
 /// <param name="fileName"></param>
 public Dictionary<Int32, Int32> ImportSystems_Own(EDSystem System, Boolean OnlyAddUnknown = false, Boolean setVisitedFlag = false)
 {
     try
     {
         List<EDSystem> SystemList = new List<EDSystem>() {System};
         return ImportSystems_Own(ref SystemList, OnlyAddUnknown, setVisitedFlag);
     }
     catch (Exception ex)
     {
         throw new Exception("Error in <ImportSystems_Own> from single station", ex);
     }
 }
Example #11
0
        /// <summary>
        /// true, if all data *except the ID* is equal (case insensitive)
        /// </summary>
        /// <param name="eqSystem"></param>
        /// <returns></returns>
        public bool EqualsED(EDSystem eqSystem)
        {
            bool retValue = false;

            if (eqSystem != null)
            {
                if (ObjectCompare.EqualsNullable(this.Name, eqSystem.Name) &&
                    ObjectCompare.EqualsNullable(this.X, eqSystem.X) &&
                    ObjectCompare.EqualsNullable(this.Y, eqSystem.Y) &&
                    ObjectCompare.EqualsNullable(this.Z, eqSystem.Z) &&
                    ObjectCompare.EqualsNullable(this.Faction, eqSystem.Faction) &&
                    ObjectCompare.EqualsNullable(this.Population, eqSystem.Population) &&
                    ObjectCompare.EqualsNullable(this.Government, eqSystem.Government) &&
                    ObjectCompare.EqualsNullable(this.Allegiance, eqSystem.Allegiance) &&
                    ObjectCompare.EqualsNullable(this.State, eqSystem.State) &&
                    ObjectCompare.EqualsNullable(this.Security, eqSystem.Security) &&
                    ObjectCompare.EqualsNullable(this.PrimaryEconomy, eqSystem.PrimaryEconomy) &&
                    ObjectCompare.EqualsNullable(this.Power, eqSystem.Power) &&
                    ObjectCompare.EqualsNullable(this.PowerState, eqSystem.PowerState) &&
                    ObjectCompare.EqualsNullable(this.NeedsPermit, eqSystem.NeedsPermit) &&
                    ObjectCompare.EqualsNullable(this.UpdatedAt, eqSystem.UpdatedAt) &&
                    ObjectCompare.EqualsNullable(this.Simbad_Ref, eqSystem.Simbad_Ref))
                    retValue = true;
            }

            return retValue;             
        }
Example #12
0
 /// <summary>
  /// creates a new system as a copy of another system
  /// only the id must declared extra
 /// </summary>
 /// <param name="newSystemIndex"></param>
 /// <param name="ownSystem"></param>
 public EDSystem(int newId, EDSystem sourceSystem)
 {
     clear();
     Id              = newId;
     getValues(sourceSystem);   
 }
Example #13
0
        /// <summary>
        /// copy the values from another system exept for the ID
        /// </summary>
        /// <param name="ValueStation"></param>
        public void getValues(EDSystem ownSystem, bool getAll=false)
        {
            if(getAll)
                Id = ownSystem.Id;

            Name            = ownSystem.Name;
            X               = ownSystem.X;
            Y               = ownSystem.Y;
            Z               = ownSystem.Z;
            Faction         = ownSystem.Faction;
            Population      = ownSystem.Population;
            Government      = ownSystem.Government;
            Allegiance      = ownSystem.Allegiance;
            State           = ownSystem.State;
            Security        = ownSystem.Security;
            PrimaryEconomy  = ownSystem.PrimaryEconomy;
            Power           = ownSystem.Power;
            PowerState      = ownSystem.PowerState;
            NeedsPermit     = ownSystem.NeedsPermit;
            UpdatedAt       = ownSystem.UpdatedAt;
            Simbad_Ref      = ownSystem.Simbad_Ref;
        }
Example #14
0
        /// <summary>
        /// creates a list of "EDStations" with price listings from csv-array
        /// </summary>
        /// <param name="CSV_Strings"></param>
        /// <returns></returns>
        public List<EDStation> fromCSV(String[] CSV_Strings, ref List<EDSystem> foundSystems)
        {
            List<EDStation> foundValues                     = new List<EDStation>();
            Dictionary<String, Int32> foundIndex            = new Dictionary<String, Int32>();
            Dictionary<String, Int32> foundSystemIndex      = new Dictionary<String, Int32>();
            String LastID                                   = "";
            EDSystem LastSystem                             = null;
            String currentID                                = "";
            EDStation currentStation                        = null;
            Int32 Index                                     = 0;

            try
            {
                if(foundSystems != null)
                    foundSystems.Clear();
                else
                    foundSystems = new List<EDSystem>();

                foreach (String CSV_String in CSV_Strings)
                {

                    if(!String.IsNullOrEmpty(CSV_String.Trim()))
                    {
                        CsvRow currentRow           = new CsvRow(CSV_String);

                        currentID = currentRow.StationID;

                        if(!LastID.Equals(currentID, StringComparison.InvariantCultureIgnoreCase))
                        {
                            if(currentStation != null)
                                currentStation.ListingExtendMode = false;

                            if(foundIndex.TryGetValue(currentID, out Index))
                                currentStation = foundValues[Index];
                            else
                            {
                                currentStation  = new EDStation(currentRow);

                                foundValues.Add(currentStation);
                                foundIndex.Add(currentID, foundValues.Count-1);
                            }
                            LastID = currentRow.StationID;

                            currentStation.ListingExtendMode = true;

                            if((LastSystem == null) || (!LastSystem.Name.Equals(currentRow.SystemName, StringComparison.InvariantCultureIgnoreCase)))
                            {
                                if(foundSystemIndex.TryGetValue(currentRow.SystemName, out Index))
                                    LastSystem = foundSystems[Index];
                                else
                                {
                                    LastSystem  = new EDSystem();
                                    LastSystem.Name = currentRow.SystemName;

                                    if(LastSystem.Id == 0)
                                        LastSystem.Id = currentStation.SystemId;

                                    foundSystems.Add(LastSystem);
                                    foundSystemIndex.Add(currentRow.SystemName, foundSystems.Count-1);
                                }
                            }
                        }

                        currentStation.addListing(currentRow);
                    }
                }

                if(currentStation != null)
                    currentStation.ListingExtendMode = false;

                return foundValues;

            }
            catch (Exception ex)
            {
                throw new Exception("Error while getting station values from CSV-String", ex);
            }
        }
Example #15
0
        public void checkPotentiallyNewSystemOrStation(String System, String Station, Boolean setVisitedFlag = true)
        {
            String sqlString;
            Int32 SystemID;
            Int32 LocationID;
            Boolean systemFirstTimeVisited     = false;
            Boolean stationFirstTimeVisited    = false;
            Boolean isNewSystem                = false;
            Boolean isNewStation               = false;
            DataTable Data          = new DataTable();
            Boolean Visited;

            try
            {
                System  = System.Trim();
                Station = Station.Trim();

                if(!String.IsNullOrEmpty(System))
                {
                    sqlString       = "select id, visited from tbSystems where Systemname = " + DBConnector.SQLAEscape(System);
                    if(Program.DBCon.Execute(sqlString, Data) > 0)
                    {
                        // check or update the visited-flag
                        SystemID = (Int32)(Data.Rows[0]["ID"]);
                        Visited  = (Boolean)(Data.Rows[0]["visited"]);

                        if(!Visited)
                        {
                            sqlString = String.Format("insert ignore into tbVisitedSystems(system_id, time) values" +
                                                      " ({0},{1})", SystemID.ToString(),  DBConnector.SQLDateTime(DateTime.UtcNow));
                            Program.DBCon.Execute(sqlString);
                            systemFirstTimeVisited = true;
                        }
                    }
                    else
                    {
                        // add a new system
                        EDSystem newSystem      = new EDSystem();
                        newSystem.Name          = System;

                        var systemIDs           = ImportSystems_Own(newSystem, true, setVisitedFlag);

                        SystemID                = newSystem.Id;

                        isNewSystem             = true;
                        systemFirstTimeVisited  = true;
                    }

                    if(!String.IsNullOrEmpty(Station))
                    {
                        Data.Clear();

                        sqlString    = "select St.ID, St.visited from tbSystems Sy, tbStations St" +
                                       " where Sy.ID = St. System_ID" +
                                       " and   Sy.ID          = " + SystemID +
                                       " and   St.Stationname = " + DBConnector.SQLAEscape(Station);

                        if(Program.DBCon.Execute(sqlString, Data) > 0)
                        {
                            // check or update the visited-flag
                            LocationID = (Int32)(Data.Rows[0]["ID"]);
                            Visited    = (Boolean)(Data.Rows[0]["visited"]);

                            if(!Visited)
                            {
                                sqlString = String.Format("insert ignore into tbVisitedStations(station_id, time) values" +
                                                          " ({0},{1})", LocationID.ToString(), DBConnector.SQLDateTime(DateTime.UtcNow));
                                Program.DBCon.Execute(sqlString);
                                stationFirstTimeVisited = true;
                            }
                        }
                        else
                        {
                            // add a new station
                            EDStation newStation    = new EDStation();
                            newStation.Name         = Station;
                            newStation.SystemId     = SystemID;

                            ImportStations_Own(newStation, true, setVisitedFlag);

                            isNewStation              = true;
                            stationFirstTimeVisited = true;
                        }
                    }

                    if(systemFirstTimeVisited || stationFirstTimeVisited)
                    {
                        // if there's a new visitedflag set in the visited-tables
                        // then update the maintables
                        Program.Data.updateVisitedFlagsFromBase(systemFirstTimeVisited, stationFirstTimeVisited);

                        // last but not least reload the BaseTables with the new visited-information
                        if(systemFirstTimeVisited)
                            Program.Data.PrepareBaseTables(Program.Data.BaseData.tbsystems.TableName);

                        if(stationFirstTimeVisited)
                            Program.Data.PrepareBaseTables(Program.Data.BaseData.tbstations.TableName);
                    }

                    if(isNewSystem || isNewStation)
                    {
                        Program.Data.PrepareBaseTables(Program.Data.BaseData.visystemsandstations.TableName);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error while setting a visited flag", ex);
            }
        }
Example #16
0
        /// <summary>
        /// merging EDDB and own data to one big list
        /// </summary>
        public bool mergeData()
        {
            int  StartingCount;
            bool SystemCanBeDeleted = false;

            //if (false)
            //{
            //    // create some data for testing
            //    if (File.Exists(@".\m_BaseData\systems_own.json"))
            //        File.Delete(@".\m_BaseData\systems_own.json");
            //    if (File.Exists(@".\m_BaseData\stations_own.json"))
            //        File.Delete(@".\m_BaseData\stations_own.json");
            //    m_Systems[(int)enMessageInfo.Data_Merged] = new List<EDSystem>(m_Systems[(int)enMessageInfo.Data_EDDB].Where(x => x.Id <= 10));
            //    m_Stations[(int)enMessageInfo.Data_Merged] = new List<EDStation>(m_Stations[(int)enMessageInfo.Data_EDDB].Where(x => x.SystemId <= 10));
            //    saveSystemData(@".\m_BaseData\systems_own.json", enMessageInfo.Data_Merged, false);
            //    saveStationData(@".\m_BaseData\stations_own.json", enMessageInfo.Data_Merged, false);
            //}


            // get the base list from EDDB assuming it's the bigger one
            m_Systems[(int)enDataType.Data_Merged]  = cloneSystems(enDataType.Data_EDDB);
            m_Stations[(int)enDataType.Data_Merged] = cloneStations(enDataType.Data_EDDB);

            StartingCount = m_Systems[(int)enDataType.Data_Own].Count;

            for (int i = 0; i < StartingCount; i++)
            {
                SystemCanBeDeleted = true;


                EDSystem ownSystem          = m_Systems[(int)enDataType.Data_Own][StartingCount - i - 1];
                EDSystem existingEDDNSystem = getSystem(ownSystem.Name);

                //if (existingEDDNSystem != null)
                //    Debug.Print("Id=" + existingEDDNSystem.Id);
                //else
                //    Debug.Print("Id=null");

                if (existingEDDNSystem != null)
                {
                    if (existingEDDNSystem.EqualsED(ownSystem))
                    {
                        // systems are equal, check the stations
                        checkStations(ownSystem, existingEDDNSystem, ref SystemCanBeDeleted, ref m_changedStations);
                    }
                    else
                    {
                        // system is existingClassification, but there are differences -> own version has a higher priority
                        SystemCanBeDeleted = false;
                        existingEDDNSystem.getValues(ownSystem);

                        // now check the stations
                        checkStations(ownSystem, existingEDDNSystem, ref SystemCanBeDeleted, ref m_changedStations);
                    }
                }
                else
                {
                    // system is unknown in the EDDB, copy our own system into the merged list
                    SystemCanBeDeleted = false;
                    int newSystemIndex = m_Systems[(int)enDataType.Data_Merged].Max(X => X.Id) + 1;

                    // create system cloneSystems
                    EDSystem newSystem = new EDSystem(newSystemIndex, ownSystem);

                    // add it to merged data
                    m_Systems[(int)enDataType.Data_Merged].Add(newSystem);

                    // now go and get the stations
                    copyStationsForNewSystem(newSystem);
                }

                if (SystemCanBeDeleted)
                {
                    //

                    // delete the system;
                    m_Systems[(int)enDataType.Data_Own].Remove(ownSystem);
                    m_changedSystems = true;
                }
            }

            return(changedStations || changedSystems);
        }
Example #17
0
        /// <summary>
        /// changes or adds a system to the "own" list and to the merged list
        /// EDDB basedata will not be changed
        /// </summary>
        /// <param name="m_currentSystemdata">systemdata to be added</param>
        internal void ChangeAddSystem(EDSystem m_currentSystemdata, string oldSystemName = null)
        {
            EDSystem        System;
            List <EDSystem> ownSystems = getSystems(enDataType.Data_Own);
            int             newSystemIndex;

            if (String.IsNullOrEmpty(oldSystemName.Trim()))
            {
                oldSystemName = m_currentSystemdata.Name;
            }

            if (!oldSystemName.Equals(m_currentSystemdata.Name))
            {
                // changing system name
                var existing = getSystems(EDMilkyway.enDataType.Data_EDDB).Find(x => x.Name.Equals(oldSystemName, StringComparison.InvariantCultureIgnoreCase));
                if (existing != null)
                {
                    throw new Exception("It's not allowed to rename a EDDB system");
                }
            }

            // 1st put the new values into our local list
            System = ownSystems.Find(x => x.Name.Equals(oldSystemName, StringComparison.CurrentCultureIgnoreCase));
            if (System != null)
            {
                // copy new values into existingClassification system
                System.getValues(m_currentSystemdata);
            }
            else
            {
                // add as a new system to own data
                newSystemIndex = 0;

                if (ownSystems.Count > 0)
                {
                    newSystemIndex = ownSystems.Max(X => X.Id) + 1;
                }

                ownSystems.Add(new EDSystem(newSystemIndex, m_currentSystemdata));
            }

            // 2nd put the new values into our merged list
            List <EDSystem> mergedSystems = getSystems(enDataType.Data_Merged);

            System = mergedSystems.Find(x => x.Name.Equals(oldSystemName, StringComparison.CurrentCultureIgnoreCase));
            if (System != null)
            {
                // copy new values into existingClassification system
                System.getValues(m_currentSystemdata);
            }
            else
            {
                // add as a new system to own data
                newSystemIndex = 0;

                if (mergedSystems.Count > 0)
                {
                    newSystemIndex = mergedSystems.Max(X => X.Id) + 1;
                }
                mergedSystems.Add(new EDSystem(newSystemIndex, m_currentSystemdata));
            }

            if (m_cachedLocations.ContainsKey(oldSystemName))
            {
                m_cachedLocations.Remove(oldSystemName);
            }

            saveStationData(Program.GetDataPath(@"Data\stations_own.json"), EDMilkyway.enDataType.Data_Own, true);
            saveSystemData(Program.GetDataPath(@"Data\systems_own.json"), EDMilkyway.enDataType.Data_Own, true);
        }
Example #18
0
        /// <summary>
        /// go and get station clones from the own data for a new station
        /// and adds them to the merged data
        /// </summary>
        /// <param name="systemFirstTimeVisited">new created system in merged data </param>
        private void copyStationsForNewSystem(EDSystem newSystem)
        {
            // get the list from own data with the name of the new station 
            // (it's ok because it must be the same name)
            List<EDStation> ownSystemStations = getStations(newSystem.Name, enDataType.Data_Own);
                
            // get the gighest index
            int newStationIndex = m_Stations[(int)enDataType.Data_Merged].Max(X => X.Id);

            for (int j = 0; j < ownSystemStations.Count(); j++)
            {
                newStationIndex++;
                m_Stations[(int)enDataType.Data_Merged].Add(new EDStation(newStationIndex, newSystem.Id, ownSystemStations[j]));
            }
        }
Example #19
0
        /// <summary>
        /// check if the stations of two stations are equal if the system 
        /// exists in the EDDB data and in the own data
        /// </summary>
        /// <param name="ownSystem">system from own data</param>
        /// <param name="existingEDDNSystem">system from EDDB data</param>
        /// <param name="SystemCanBeDeleted">normally true, except there are differences between at least one stations.
        /// if so the system must be hold as reference. If a own data station is 100% equal (e.g. Commoditynames and other strings
        /// are not casesensitive compared) to the eddb station it will automatically deleted</param>
        private void checkStations(EDSystem ownSystem, EDSystem existingEDDNSystem, ref bool SystemCanBeDeleted, ref bool StationsChanged)
        {
            // own system can be deleted if the stations are equal, too
            List<EDStation> ownSystemStations = getStations(ownSystem.Name, enDataType.Data_Own);

            for (int j = 0; j < ownSystemStations.Count(); j++)
            {
                EDStation ownStation = ownSystemStations[j];
                EDStation existingEDDNStation = getSystemStation(ownSystem.Name, ownSystemStations[j].Name);

                if (existingEDDNStation != null)
                {
                    if (existingEDDNStation.EqualsED(ownStation))
                    {
                        // no favour to hold it anymore
                        m_Stations[(int)enDataType.Data_Own].Remove(ownStation);
                        StationsChanged = true;
                    }
                    else
                    {
                        // copy the values and hold it
                        existingEDDNStation.getValues(ownStation);
                        SystemCanBeDeleted = false;
                    }

                }
                else
                {
                    // station is in EDDB not existingClassification, so we'll hold the station
                    SystemCanBeDeleted = false;
                    int newStationIndex = m_Stations[(int)enDataType.Data_Merged].Max(X => X.Id) + 1;

                    m_Stations[(int)enDataType.Data_Merged].Add(new EDStation(newStationIndex, existingEDDNSystem.Id, ownStation));
                }
            }
        }
Example #20
0
        private void loadSystemData(string Systemname, bool isNew=false)
        {
            m_SystemLoadingValues = true;

            if (isNew)
            {
                cmbSystemsAllSystems.SelectedIndex = 0;
                m_loadedSystemdata = new EDSystem();
                m_loadedSystemdata.Name = Systemname;
                m_SystemIsNew = true;
            }
            else
            {
                cmbSystemsAllSystems.SelectedValue = Systemname;

                if (Debugger.IsAttached)
                    MessageBox.Show("TODO");
                // throw new NotImplementedException();
                //m_loadedSystemdata = _Milkyway.getSystem(Systemname);
                m_loadedSystemdata = null;
                m_SystemIsNew = false;
            }

            cmbStationStations.Items.Clear();
            cmbStationStations.Items.Add("");

            if (m_loadedSystemdata != null)
            {
                m_currentSystemdata.getValues(m_loadedSystemdata, true);

                txtSystemId.Text = m_loadedSystemdata.Id.ToString(CultureInfo.CurrentCulture);
                txtSystemName.Text = m_loadedSystemdata.Name;
                txtSystemX.Text = m_loadedSystemdata.X.ToString("0.00000", CultureInfo.CurrentCulture);
                txtSystemY.Text = m_loadedSystemdata.Y.ToString("0.00000", CultureInfo.CurrentCulture);
                txtSystemZ.Text = m_loadedSystemdata.Z.ToString("0.00000", CultureInfo.CurrentCulture);
                txtSystemFaction.Text = m_loadedSystemdata.Faction.NToString();
                txtSystemPopulation.Text = m_loadedSystemdata.Population.ToNString("#,##0.", CultureInfo.CurrentCulture);
                txtSystemUpdatedAt.Text = DateTimeOffset.FromUnixTimeSeconds(m_loadedSystemdata.UpdatedAt).DateTime.ToString(CultureInfo.CurrentUICulture);
                cbSystemNeedsPermit.CheckState = m_loadedSystemdata.NeedsPermit.toCheckState();
                cmbSystemPrimaryEconomy.Text = m_loadedSystemdata.PrimaryEconomy.NToString();
                cmbSystemSecurity.Text = m_loadedSystemdata.Security.NToString();
                cmbSystemState.Text = m_loadedSystemdata.State.NToString();
                cmbSystemAllegiance.Text = m_loadedSystemdata.Allegiance.NToString();
                cmbSystemGovernment.Text = m_loadedSystemdata.Government.NToString();

                setSystemEditable(isNew);

                if(!isNew)
                {
                    cmdSystemNew.Enabled            = true;
                    cmdSystemEdit.Enabled           = true;
                    cmdSystemSave.Enabled           = false;
                    cmdSystemCancel.Enabled         = cmdSystemSave.Enabled;

                    cmdStationNew.Enabled           = true;
                    cmdStationEdit.Enabled          = false;
                    cmdStationSave.Enabled          = false;
                    cmdStationCancel.Enabled        = cmdStationSave.Enabled;

                    cmbSystemsAllSystems.ReadOnly   = false;
                    cmbStationStations.ReadOnly     = false;
                }

                throw new NotImplementedException();
                List<EDStation> StationsInSystem = null; // _Milkyway.getStations(Systemname);
                foreach (var Station in StationsInSystem)
                {
                    cmbStationStations.Items.Add(Station.Name);
                }

                lblStationCount.Text = StationsInSystem.Count().ToString();

                cmbStationStations.SelectedIndex = 0;

            }
            else
            {
                m_currentSystemdata.clear();

                txtSystemId.Text = Program.NULLSTRING;
                txtSystemName.Text = Program.NULLSTRING;
                txtSystemX.Text = Program.NULLSTRING;
                txtSystemY.Text = Program.NULLSTRING;
                txtSystemZ.Text = Program.NULLSTRING;
                txtSystemFaction.Text = Program.NULLSTRING;
                txtSystemPopulation.Text = Program.NULLSTRING;
                txtSystemUpdatedAt.Text = Program.NULLSTRING;
                cbSystemNeedsPermit.CheckState = CheckState.Unchecked;
                cmbSystemPrimaryEconomy.Text = Program.NULLSTRING;
                cmbSystemSecurity.Text = Program.NULLSTRING;
                cmbSystemState.Text = Program.NULLSTRING;
                cmbSystemAllegiance.Text = Program.NULLSTRING;
                cmbSystemGovernment.Text = Program.NULLSTRING;

                setSystemEditable(false);

                cmdSystemNew.Enabled        = true;
                cmdSystemEdit.Enabled       = false;
                cmdSystemSave.Enabled       = false;
                cmdSystemCancel.Enabled     = cmdSystemSave.Enabled;

                cmdStationNew.Enabled       = false;
                cmdStationEdit.Enabled      = false;
                cmdStationSave.Enabled      = false;
                cmdStationCancel.Enabled    = cmdStationSave.Enabled;

                cmbSystemsAllSystems.ReadOnly = false;

                txtSystemName.ReadOnly = true;
                lblSystemRenameHint.Visible = false;

                lblStationCount.Text = "-";
            }

            m_SystemLoadingValues = false;
        }
Example #21
0
        /// <summary>
        /// changes or adds a system to the "own" list and to the merged list
        /// EDDB basedata will not be changed
        /// </summary>
        /// <param name="m_currentSystemdata">systemdata to be added</param>
        internal void ChangeAddSystem(EDSystem m_currentSystemdata, string oldSystemName=null)
        {
            EDSystem System;
            List<EDSystem> ownSystems = getSystems(enDataType.Data_Own);
            int newSystemIndex;

            if(String.IsNullOrEmpty(oldSystemName.Trim()))
                oldSystemName = m_currentSystemdata.Name;

            if(!oldSystemName.Equals(m_currentSystemdata.Name))
            {
                // changing system name
                var existing = getSystems(EDMilkyway.enDataType.Data_EDDB).Find(x => x.Name.Equals(oldSystemName, StringComparison.InvariantCultureIgnoreCase));
                if (existing != null)
                    throw new Exception("It's not allowed to rename a EDDB system");
            }

            // 1st put the new values into our local list
            System = ownSystems.Find(x => x.Name.Equals(oldSystemName, StringComparison.CurrentCultureIgnoreCase));
            if(System != null)
            { 
                // copy new values into existingClassification system
                System.getValues(m_currentSystemdata);
            }
            else
            { 
                // add as a new system to own data
                newSystemIndex = 0;

                if(ownSystems.Count > 0)
                    newSystemIndex = ownSystems.Max(X => X.Id) + 1;
                    
                ownSystems.Add(new EDSystem(newSystemIndex, m_currentSystemdata));
                
            }

            // 2nd put the new values into our merged list
            List<EDSystem> mergedSystems = getSystems(enDataType.Data_Merged);

            System = mergedSystems.Find(x => x.Name.Equals(oldSystemName, StringComparison.CurrentCultureIgnoreCase));
            if(System != null)
            { 
                // copy new values into existingClassification system
                System.getValues(m_currentSystemdata);
            }
            else
            { 
                // add as a new system to own data
                newSystemIndex = 0;

                if(mergedSystems.Count > 0)
                    newSystemIndex = mergedSystems.Max(X => X.Id) + 1;
                mergedSystems.Add(new EDSystem(newSystemIndex, m_currentSystemdata));
            }

            if(m_cachedLocations.ContainsKey(oldSystemName))
                m_cachedLocations.Remove(oldSystemName);

            saveStationData(Program.GetDataPath(@"Data\stations_own.json"), EDMilkyway.enDataType.Data_Own, true);
            saveSystemData(Program.GetDataPath(@"Data\systems_own.json"), EDMilkyway.enDataType.Data_Own, true);
        }
Example #22
0
        /// <summary>
        /// changes or adds a station to the "own" list and to the merged list
        /// EDDB basedata will not be changed
        /// </summary>
        /// <param name="m_currentSystemdata">systemdata to be added</param>
        internal void ChangeAddStation(string Systemname, EDStation m_currentStationdata, string oldStationName=null)
        {
            EDSystem System;
            EDStation Station;
            int newStationIndex;

            if(String.IsNullOrEmpty(oldStationName.Trim()))
                oldStationName = m_currentStationdata.Name;

            List<EDSystem> ownSystems       = getSystems(enDataType.Data_Own);
            List<EDStation> ownStations     = getStations(enDataType.Data_Own);

            List<EDSystem> mergedSystems    = getSystems(enDataType.Data_Merged);
            List<EDStation> mergedStations  = getStations(enDataType.Data_Merged);

            // 1st put the new values into our local list
            System = ownSystems.Find(x => x.Name.Equals(Systemname, StringComparison.CurrentCultureIgnoreCase));
            if(System == null)
            {
                // own system is not existingClassification, look for a EDDNCommunicator system
                System = mergedSystems.Find(x => x.Name.Equals(Systemname, StringComparison.CurrentCultureIgnoreCase));

                if(System == null)
                    throw new Exception("System in merged list required but not existing");
                
                // get a new local system id 
                int newSystemIndex = 0;
                if (m_Systems[(int)enDataType.Data_Own].Count > 0)
                   newSystemIndex = m_Systems[(int)enDataType.Data_Own].Max(X => X.Id) + 1;

                // and add the EDDNCommunicator system as a new system to the local list
                System = new EDSystem(newSystemIndex, System);
                ownSystems.Add(System);

                // get a new station index
                newStationIndex = 0;
                if(ownStations.Count > 0)
                    newStationIndex = ownStations.Max(X => X.Id) + 1;
                
                // add the new station in the local station dictionary
                ownStations.Add(new EDStation(newStationIndex, newSystemIndex, m_currentStationdata));
            }
            else
            { 
                // the system is existingClassification in the own dictionary 
                Station = ownStations.Find(x => (x.Name.Equals(oldStationName, StringComparison.CurrentCultureIgnoreCase)) && 
                                                (x.SystemId == System.Id));
                if(Station != null)
                { 
                    // station is already existingClassification, copy new values into existingClassification Location
                    Station.getValues(m_currentStationdata);
                }
                else
                { 
                    // station is not existingClassification, get a new station index
                    newStationIndex = 0;
                    if(ownStations.Count > 0)
                        newStationIndex = ownStations.Max(X => X.Id) + 1;
                    
                    // add the new station in the local station dictionary
                    ownStations.Add(new EDStation(newStationIndex, System.Id, m_currentStationdata));
                }
            }

            // 1st put the new values into the merged list
            System = mergedSystems.Find(x => x.Name.Equals(Systemname, StringComparison.CurrentCultureIgnoreCase));
            if(System == null)
            {
                // system is not exiting in merged list
                System = ownSystems.Find(x => x.Name.Equals(Systemname, StringComparison.CurrentCultureIgnoreCase));

                if(System == null)
                    throw new Exception("System in own list required but not existing");
                
                // get a new merged system id 
                int newSystemIndex = m_Systems[(int)enDataType.Data_Merged].Max(X => X.Id) + 1;

                // and add system to the merged list
                System = new EDSystem(newSystemIndex, System);
                mergedSystems.Add(System);

                // get a new station index
                newStationIndex = 0;
                if(mergedStations.Count > 0)
                    newStationIndex = mergedStations.Max(X => X.Id) + 1;
                
                // add the new station in the local station dictionary
                mergedStations.Add(new EDStation(newStationIndex, newSystemIndex, m_currentStationdata));
            }
            else
            { 
                // the system is existingClassification in the merged dictionary 
                Station = mergedStations.Find(x => (x.Name.Equals(oldStationName, StringComparison.CurrentCultureIgnoreCase)) && 
                                                (x.SystemId == System.Id));
                if(Station != null)
                { 
                    // station is already existingClassification, copy new values into existingClassification Location
                    Station.getValues(m_currentStationdata);
                }
                else
                { 
                    // station is not existingClassification, get a new station index
                    newStationIndex = 0;
                    if(mergedStations.Count > 0)
                        newStationIndex = mergedStations.Max(X => X.Id) + 1;
                    
                    // add the new station in the merged station dictionary
                    mergedStations.Add(new EDStation(newStationIndex, System.Id, m_currentStationdata));
                }
            }
           
            if(m_cachedStationDistances.ContainsKey(oldStationName))
                m_cachedStationDistances.Remove(oldStationName);

            saveStationData(Program.GetDataPath(@"Data\stations_own.json"), EDMilkyway.enDataType.Data_Own, true);
            saveSystemData(Program.GetDataPath(@"Data\Systems_own.json"), EDMilkyway.enDataType.Data_Own, true);        
        }
Example #23
0
 /// <summary>
 /// creates a new system as a copy of another system
 /// only the id must declared extra
 /// </summary>
 /// <param name="newSystemIndex"></param>
 /// <param name="ownSystem"></param>
 public EDSystem(int newId, EDSystem sourceSystem)
 {
     clear();
     Id = newId;
     getValues(sourceSystem);
 }
Example #24
0
        /// <summary>
        /// copies the data from a "EDSystem"-object to a Datarow from table "tbSystems"
        /// </summary>
        /// <param name="SystemObject"></param>
        /// <param name="SystemRow"></param>
        private void CopyEDSystemToDataRow(EDSystem SystemObject, DataRow SystemRow, Boolean OwnData = false, int? SystemID = null, Boolean insertUnknown = false)
        {
            try
            {

                SystemRow["id"]                     = SystemID == null ? DBConvert.From(SystemObject.Id) : SystemID;
                SystemRow["systemname"]             = DBConvert.From(SystemObject.Name);
                SystemRow["x"]                      = DBConvert.From(SystemObject.X);
                SystemRow["y"]                      = DBConvert.From(SystemObject.Y);
                SystemRow["z"]                      = DBConvert.From(SystemObject.Z);
                SystemRow["faction"]                = DBConvert.From(SystemObject.Faction);
                SystemRow["population"]             = DBConvert.From(SystemObject.Population);
                SystemRow["government_id"]          = DBConvert.From(BaseTableNameToID("government", SystemObject.Government, insertUnknown));
                SystemRow["allegiance_id"]          = DBConvert.From(BaseTableNameToID("allegiance", SystemObject.Allegiance, insertUnknown));
                SystemRow["state_id"]               = DBConvert.From(BaseTableNameToID("state", SystemObject.State, insertUnknown));
                SystemRow["security_id"]            = DBConvert.From(BaseTableNameToID("security", SystemObject.Security, insertUnknown));
                SystemRow["primary_economy_id"]     = DBConvert.From(BaseTableNameToID("economy", SystemObject.PrimaryEconomy, insertUnknown));
                SystemRow["power_id"]               = DBConvert.From(BaseTableNameToID("power", SystemObject.Power, insertUnknown));
                SystemRow["powerstate_id"]          = DBConvert.From(BaseTableNameToID("powerstate", SystemObject.PowerState, insertUnknown));
                SystemRow["needs_permit"]           = DBConvert.From(SystemObject.NeedsPermit);
                SystemRow["updated_at"]             = DBConvert.From(DateTimeOffset.FromUnixTimeSeconds(SystemObject.UpdatedAt).DateTime);
                SystemRow["is_changed"]             = OwnData ? DBConvert.From(1) : DBConvert.From(0);
                SystemRow["visited"]                = DBConvert.From(0);

            }
            catch (Exception ex)
            {
                throw new Exception("Error while copying system data", ex);
            }
        }
Example #25
0
        /// <summary>
        /// creates a list of "EDStations" with price listings from csv-array
        /// </summary>
        /// <param name="CSV_Strings">String to be converted</param>
        /// <param name="foundSystems"></param>
        /// <param name="csvRowList">for optional processing outside: a list of the data converted to CsvRow-objects</param>
        /// <returns></returns>
        public List<EDStation> fromCSV(String[] CSV_Strings, ref List<EDSystem> foundSystems, ref List<CsvRow> csvRowList)
        {
            List<EDStation> foundValues                     = new List<EDStation>();
            Dictionary<String, Int32> foundIndex            = new Dictionary<String, Int32>();
            Dictionary<String, Int32> foundSystemIndex      = new Dictionary<String, Int32>();
            String LastID                                   = "";
            EDSystem LastSystem                             = null;
            String currentID                                = "";
            EDStation currentStation                        = null;
            Int32 Index                                     = 0;
            Dictionary<String, Int32> commodityIDCache      = new Dictionary<string,Int32>();            // quick cache for finding commodity names
            Int32 currentItem                               = 0;
            ProgressEventArgs eva;

            try
            {
                eva = new ProgressEventArgs() { Info="converting data...", CurrentValue=currentItem, TotalValue=CSV_Strings.GetUpperBound(0)+1, AddSeparator = true };
                sendProgressEvent(eva);

                if(foundSystems != null)
                    foundSystems.Clear();
                else
                    foundSystems = new List<EDSystem>();


                foreach (String CSV_String in CSV_Strings)
	            {

                    if(!String.IsNullOrEmpty(CSV_String.Trim()))
                    {
		                CsvRow currentRow           = new CsvRow(CSV_String);

                        if(csvRowList != null)
                            csvRowList.Add(currentRow);

                        currentID = currentRow.StationID;

                        if(!LastID.Equals(currentID, StringComparison.InvariantCultureIgnoreCase))
                        {
                            if(currentStation != null)
                                currentStation.ListingExtendMode = false;

                            if(foundIndex.TryGetValue(currentID, out Index))
                                currentStation = foundValues[Index];
                            else
                            {
                                currentStation  = new EDStation(currentRow);

                                foundValues.Add(currentStation);
                                foundIndex.Add(currentID, foundValues.Count-1);
                            }
                            LastID = currentRow.StationID;

                            currentStation.ListingExtendMode = true;


                            if((LastSystem == null) || (!LastSystem.Name.Equals(currentRow.SystemName, StringComparison.InvariantCultureIgnoreCase)))
                            {
                                if(foundSystemIndex.TryGetValue(currentRow.SystemName, out Index))
                                    LastSystem = foundSystems[Index];
                                else
                                {
                                    LastSystem  = new EDSystem();
                                    LastSystem.Name = currentRow.SystemName;

                                    if(LastSystem.Id == 0)
                                        LastSystem.Id = currentStation.SystemId;


                                    foundSystems.Add(LastSystem);
                                    foundSystemIndex.Add(currentRow.SystemName, foundSystems.Count-1);
                                }
                            }
                        }

                        currentStation.addListing(currentRow, ref commodityIDCache);
                    }

                    eva = new ProgressEventArgs() { Info="converting data...", CurrentValue=currentItem, TotalValue=CSV_Strings.GetUpperBound(0)+1};
                    sendProgressEvent(eva);

                    if(eva.Cancelled)
                        break;

                    currentItem++;

	            }

                if(currentStation != null)
                    currentStation.ListingExtendMode = false;

                eva = new ProgressEventArgs() { Info="converting data...", CurrentValue=currentItem, TotalValue=CSV_Strings.GetUpperBound(0)+1, ForceRefresh=true};
                sendProgressEvent(eva);

                return foundValues;

            }
            catch (Exception ex)
            {
                throw new Exception("Error while getting station values from CSV-String", ex);
            }
        }
Example #26
0
        /// <summary>
        /// changes or adds a station to the "own" list and to the merged list
        /// EDDB basedata will not be changed
        /// </summary>
        /// <param name="m_currentSystemdata">systemdata to be added</param>
        internal void ChangeAddStation(string Systemname, EDStation m_currentStationdata, string oldStationName = null)
        {
            EDSystem  System;
            EDStation Station;
            int       newStationIndex;

            if (String.IsNullOrEmpty(oldStationName.Trim()))
            {
                oldStationName = m_currentStationdata.Name;
            }

            List <EDSystem>  ownSystems  = getSystems(enDataType.Data_Own);
            List <EDStation> ownStations = getStations(enDataType.Data_Own);

            List <EDSystem>  mergedSystems  = getSystems(enDataType.Data_Merged);
            List <EDStation> mergedStations = getStations(enDataType.Data_Merged);

            // 1st put the new values into our local list
            System = ownSystems.Find(x => x.Name.Equals(Systemname, StringComparison.CurrentCultureIgnoreCase));
            if (System == null)
            {
                // own system is not existingClassification, look for a EDDNCommunicator system
                System = mergedSystems.Find(x => x.Name.Equals(Systemname, StringComparison.CurrentCultureIgnoreCase));

                if (System == null)
                {
                    throw new Exception("System in merged list required but not existing");
                }

                // get a new local system id
                int newSystemIndex = 0;
                if (m_Systems[(int)enDataType.Data_Own].Count > 0)
                {
                    newSystemIndex = m_Systems[(int)enDataType.Data_Own].Max(X => X.Id) + 1;
                }

                // and add the EDDNCommunicator system as a new system to the local list
                System = new EDSystem(newSystemIndex, System);
                ownSystems.Add(System);

                // get a new station index
                newStationIndex = 0;
                if (ownStations.Count > 0)
                {
                    newStationIndex = ownStations.Max(X => X.Id) + 1;
                }

                // add the new station in the local station dictionary
                ownStations.Add(new EDStation(newStationIndex, newSystemIndex, m_currentStationdata));
            }
            else
            {
                // the system is existingClassification in the own dictionary
                Station = ownStations.Find(x => (x.Name.Equals(oldStationName, StringComparison.CurrentCultureIgnoreCase)) &&
                                           (x.SystemId == System.Id));
                if (Station != null)
                {
                    // station is already existingClassification, copy new values into existingClassification Location
                    Station.getValues(m_currentStationdata);
                }
                else
                {
                    // station is not existingClassification, get a new station index
                    newStationIndex = 0;
                    if (ownStations.Count > 0)
                    {
                        newStationIndex = ownStations.Max(X => X.Id) + 1;
                    }

                    // add the new station in the local station dictionary
                    ownStations.Add(new EDStation(newStationIndex, System.Id, m_currentStationdata));
                }
            }

            // 1st put the new values into the merged list
            System = mergedSystems.Find(x => x.Name.Equals(Systemname, StringComparison.CurrentCultureIgnoreCase));
            if (System == null)
            {
                // system is not exiting in merged list
                System = ownSystems.Find(x => x.Name.Equals(Systemname, StringComparison.CurrentCultureIgnoreCase));

                if (System == null)
                {
                    throw new Exception("System in own list required but not existing");
                }

                // get a new merged system id
                int newSystemIndex = m_Systems[(int)enDataType.Data_Merged].Max(X => X.Id) + 1;

                // and add system to the merged list
                System = new EDSystem(newSystemIndex, System);
                mergedSystems.Add(System);

                // get a new station index
                newStationIndex = 0;
                if (mergedStations.Count > 0)
                {
                    newStationIndex = mergedStations.Max(X => X.Id) + 1;
                }

                // add the new station in the local station dictionary
                mergedStations.Add(new EDStation(newStationIndex, newSystemIndex, m_currentStationdata));
            }
            else
            {
                // the system is existingClassification in the merged dictionary
                Station = mergedStations.Find(x => (x.Name.Equals(oldStationName, StringComparison.CurrentCultureIgnoreCase)) &&
                                              (x.SystemId == System.Id));
                if (Station != null)
                {
                    // station is already existingClassification, copy new values into existingClassification Location
                    Station.getValues(m_currentStationdata);
                }
                else
                {
                    // station is not existingClassification, get a new station index
                    newStationIndex = 0;
                    if (mergedStations.Count > 0)
                    {
                        newStationIndex = mergedStations.Max(X => X.Id) + 1;
                    }

                    // add the new station in the merged station dictionary
                    mergedStations.Add(new EDStation(newStationIndex, System.Id, m_currentStationdata));
                }
            }

            if (m_cachedStationDistances.ContainsKey(oldStationName))
            {
                m_cachedStationDistances.Remove(oldStationName);
            }

            saveStationData(Program.GetDataPath(@"Data\stations_own.json"), EDMilkyway.enDataType.Data_Own, true);
            saveSystemData(Program.GetDataPath(@"Data\Systems_own.json"), EDMilkyway.enDataType.Data_Own, true);
        }
Example #27
0
        private void ParseEddnJson(object text, Dictionary<string, string> headerDictionary, IDictionary<string, string> messageDictionary, bool import)
        {
            string txt = text.ToString();
            // .. we're here because we've received some data from EDDNCommunicator

            if (txt != "")
                try
                {
                    // ReSharper disable StringIndexOfIsCultureSpecific.1
                    var headerRawStart = txt.IndexOf(@"""header""") + 12;
                    var headerRawLength = txt.Substring(headerRawStart).IndexOf("}");
                    var headerRawData = txt.Substring(headerRawStart, headerRawLength);

                    var schemaRawStart = txt.IndexOf(@"""$schemaRef""") + 14;
                    var schemaRawLength = txt.Substring(schemaRawStart).IndexOf(@"""message"":");
                    var schemaRawData = txt.Substring(schemaRawStart, schemaRawLength);

                    var messageRawStart = txt.IndexOf(@"""message"":") + 12;
                    var messageRawLength = txt.Substring(messageRawStart).IndexOf("}");
                    var messageRawData = txt.Substring(messageRawStart, messageRawLength);
                    // ReSharper restore StringIndexOfIsCultureSpecific.1

                    schemaRawData = schemaRawData.Replace(@"""", "").Replace(",","");
                    var headerRawPairs = headerRawData.Replace(@"""", "").Split(',');
                    var messageRawPairs = messageRawData.Replace(@"""", "").Split(',');

                    if((Program.DBCon.getIniValue<Boolean>(IBE.MTSettings.tabSettings.DB_GROUPNAME, "UseEddnTestSchema", false.ToString(), false, true)  && (schemaRawData.IndexOf("Test", StringComparison.InvariantCultureIgnoreCase) >= 0)) ||
                       (!Program.DBCon.getIniValue<Boolean>(IBE.MTSettings.tabSettings.DB_GROUPNAME, "UseEddnTestSchema", false.ToString(), false, true) && (schemaRawData.IndexOf("Test", StringComparison.InvariantCultureIgnoreCase)  < 0)))
                    {
                        foreach (var rawHeaderPair in headerRawPairs)
                        {
                            var splitPair = new string[2];
                            splitPair[0] = rawHeaderPair.Substring(0, rawHeaderPair.IndexOf(':'));
                            splitPair[1] = rawHeaderPair.Substring(splitPair[0].Length + 1);
                            if (splitPair[0].StartsWith(" ")) splitPair[0] = splitPair[0].Substring(1);
                            if (splitPair[1].StartsWith(" ")) splitPair[1] = splitPair[1].Substring(1);
                            headerDictionary.Add(splitPair[0], splitPair[1]);
                        }

                        foreach (var rawMessagePair in messageRawPairs)
                        {
                            var splitPair = new string[2];
                            splitPair[0] = rawMessagePair.Substring(0, rawMessagePair.IndexOf(':'));
                            splitPair[1] = rawMessagePair.Substring(splitPair[0].Length + 1);
                            if (splitPair[0].StartsWith(" ")) splitPair[0] = splitPair[0].Substring(1);
                            if (splitPair[1].StartsWith(" ")) splitPair[1] = splitPair[1].Substring(1);
                            messageDictionary.Add(splitPair[0], splitPair[1]);
                        }

                        var nameAndVersion = (headerDictionary["softwareName"] + " / " + headerDictionary["softwareVersion"]);
                        if (!_eddnPublisherStats.ContainsKey(nameAndVersion))
                            _eddnPublisherStats.Add(nameAndVersion, new EddnPublisherVersionStats());

                        _eddnPublisherStats[nameAndVersion].MessagesReceived++;

                        var output = "";
                        foreach (var appVersion in _eddnPublisherStats)
                        {
                            output = output + appVersion.Key + " : " + appVersion.Value.MessagesReceived + " messages\r\n";
                        }
                        tbEddnStats.Text = output;

                        if (Debugger.IsAttached)
                            MessageBox.Show("TODO");
                        string commodity = ""; //' getLocalizedCommodity(Program.DBCon.getIniValue<String>(IBE.MTSettings.tabSettings.DB_GROUPNAME, "Language, messageDictionary["itemName"]);

                        if((cachedSystem == null) || (!messageDictionary["systemName"].Equals(cachedSystem.Name, StringComparison.InvariantCultureIgnoreCase)))
                        {
                            throw new NotImplementedException();
                            //cachedSystem = _Milkyway.getSystem(messageDictionary["Systemname"]);
                        }
                        if(cachedSystem == null)
                        {
                            cachedSystem = new EDSystem();
                            cachedSystem.Name = messageDictionary["systemName"];
                        }

                        if((cachedSystem != null) && ((cachedStation == null) || (!messageDictionary["stationName"].Equals(cachedStation.Name, StringComparison.InvariantCultureIgnoreCase))))
                        {
                            throw new NotImplementedException();
                            //cachedStation = _Milkyway.getLocation(messageDictionary["Systemname"], messageDictionary["Locationname"]);
                        }
                        if(cachedStation == null)
                        {
                            cachedStation = new EDStation();
                            cachedStation.Name = messageDictionary["stationName"];
                        }

                        if(!String.IsNullOrEmpty(commodity))
                        {

                            //System;Location;Commodity_Class;Sell;Buy;Demand;;Supply;;Date;
                            if (headerDictionary["uploaderID"] != Program.DBCon.getIniValue<String>(IBE.MTSettings.tabSettings.DB_GROUPNAME, "UserName")) // Don't import our own uploads...
                            {
                                string csvFormatted = cachedSystem.Name + ";" +
                                                      cachedStation.Name + ";" +
                                                      commodity + ";" +
                                                      (messageDictionary["sellPrice"] == "0" ? "" : messageDictionary["sellPrice"]) + ";" +
                                                      (messageDictionary["buyPrice"] == "0" ? "" : messageDictionary["buyPrice"]) + ";" +
                                                      messageDictionary["demand"] + ";" +
                                                      ";" +
                                                      messageDictionary["stationStock"] + ";" +
                                                      ";" +
                                                      messageDictionary["timestamp"] + ";"
                                                      +
                                                      "<From EDDN>" + ";";

                                if(!checkPricePlausibility(new string[] {csvFormatted}, true))
                                {
                                    if(import)
                                        throw new NotImplementedException();
                                        //ImportCsvString(csvFormatted);

                                }else{

                                    string InfoString = string.Format("IMPLAUSIBLE DATA : \"{3}\" from {0}/{1}/ID=[{2}]", headerDictionary["softwareName"], headerDictionary["softwareVersion"], headerDictionary["uploaderID"], csvFormatted );

                                    lbEddnImplausible.Items.Add(InfoString);
                                    lbEddnImplausible.SelectedIndex = lbEddnImplausible.Items.Count-1;
                                    lbEddnImplausible.SelectedIndex = -1;

                                    if(cbSpoolImplausibleToFile.Checked)
                                    {
                                        FileStream LogFileStream = null;
                                        string FileName = Program.GetDataPath("EddnImplausibleOutput.txt");

                                        if(File.Exists(FileName))
                                        {
                                            LogFileStream = File.Open(FileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                                        }
                                        else
                                        {
                                            LogFileStream = File.Create(FileName);
                                        }

                                       LogFileStream.Write(System.Text.Encoding.Default.GetBytes(InfoString + "\n"), 0, System.Text.Encoding.Default.GetByteCount(InfoString + "\n"));
                                       LogFileStream.Close();
                                    }

                                    Debug.Print("Implausible EDDN Data: " + csvFormatted);
                                }
                            }

                            if ((DateTime.Now - _lastGuiUpdate) > TimeSpan.FromSeconds(10))
                            {
                                SetupGui();
                                _lastGuiUpdate = DateTime.Now;
                            }
                        }
                        else
                        {
                            string csvFormatted = messageDictionary["systemName"] + ";" +
                                                    messageDictionary["stationName"] + ";" +
                                                    messageDictionary["itemName"] + ";" +
                                                    (messageDictionary["sellPrice"] == "0" ? "" : messageDictionary["sellPrice"]) + ";" +
                                                    (messageDictionary["buyPrice"] == "0" ? "" : messageDictionary["buyPrice"]) + ";" +
                                                    messageDictionary["demand"] + ";" +
                                                    ";" +
                                                    messageDictionary["stationStock"] + ";" +
                                                    ";" +
                                                    messageDictionary["timestamp"] + ";"
                                                    +
                                                    "<From EDDN>" + ";";
                            string InfoString = string.Format("UNKNOWN COMMODITY : \"{3}\" from {0}/{1}/ID=[{2}]", headerDictionary["softwareName"], headerDictionary["softwareVersion"], headerDictionary["uploaderID"], csvFormatted );

                            lbEddnImplausible.Items.Add(InfoString);
                            lbEddnImplausible.SelectedIndex = lbEddnImplausible.Items.Count-1;
                            lbEddnImplausible.SelectedIndex = -1;

                            if(cbSpoolImplausibleToFile.Checked)
                            {

                                FileStream LogFileStream = null;
                                string FileName = Program.GetDataPath("EddnImplausibleOutput.txt");

                                if(File.Exists(FileName))
                                {
                                    LogFileStream = File.Open(FileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                                }
                                else
                                {
                                    LogFileStream = File.Create(FileName);
                                }

                                LogFileStream.Write(System.Text.Encoding.Default.GetBytes(InfoString + "\n" ), 0, System.Text.Encoding.Default.GetByteCount(InfoString + "\n"));
                                LogFileStream.Close();
                            }

                        }
                    }
                }
                catch
                {
                    tbEDDNOutput.Text = "Couldn't parse JSON!\r\n\r\n" + tbEDDNOutput.Text;
                }
        }
Example #28
0
        /// <summary>
        /// merging EDDB and own data to one big list
        /// </summary>
        public bool mergeData()
        {
            int StartingCount;
            bool SystemCanBeDeleted = false;

            //if (false)
            //{ 
            //    // create some data for testing 
            //    if (File.Exists(@".\m_BaseData\systems_own.json"))
            //        File.Delete(@".\m_BaseData\systems_own.json");
            //    if (File.Exists(@".\m_BaseData\stations_own.json"))
            //        File.Delete(@".\m_BaseData\stations_own.json");
            //    m_Systems[(int)enMessageInfo.Data_Merged] = new List<EDSystem>(m_Systems[(int)enMessageInfo.Data_EDDB].Where(x => x.Id <= 10));
            //    m_Stations[(int)enMessageInfo.Data_Merged] = new List<EDStation>(m_Stations[(int)enMessageInfo.Data_EDDB].Where(x => x.SystemId <= 10));
            //    saveSystemData(@".\m_BaseData\systems_own.json", enMessageInfo.Data_Merged, false);
            //    saveStationData(@".\m_BaseData\stations_own.json", enMessageInfo.Data_Merged, false);
            //}
            
            
            // get the base list from EDDB assuming it's the bigger one
            m_Systems[(int)enDataType.Data_Merged] = cloneSystems(enDataType.Data_EDDB);
            m_Stations[(int)enDataType.Data_Merged] = cloneStations(enDataType.Data_EDDB);

            StartingCount =  m_Systems[(int)enDataType.Data_Own].Count;

            for (int i = 0; i < StartingCount; i++)
            {
                SystemCanBeDeleted = true;


                EDSystem ownSystem = m_Systems[(int)enDataType.Data_Own][StartingCount-i-1];
                EDSystem existingEDDNSystem = getSystem(ownSystem.Name);

                //if (existingEDDNSystem != null)
                //    Debug.Print("Id=" + existingEDDNSystem.Id);
                //else
                //    Debug.Print("Id=null");

                if (existingEDDNSystem != null)
                {

                    if (existingEDDNSystem.EqualsED(ownSystem))
                    {
                        // systems are equal, check the stations
                        checkStations(ownSystem, existingEDDNSystem, ref SystemCanBeDeleted, ref m_changedStations);
                    }
                    else
                    {
                        // system is existingClassification, but there are differences -> own version has a higher priority
                        SystemCanBeDeleted = false;
                        existingEDDNSystem.getValues(ownSystem);

                        // now check the stations
                        checkStations(ownSystem, existingEDDNSystem, ref SystemCanBeDeleted, ref m_changedStations);

                    }
                }
                else
                {
                    // system is unknown in the EDDB, copy our own system into the merged list
                    SystemCanBeDeleted = false;
                    int newSystemIndex = m_Systems[(int)enDataType.Data_Merged].Max(X => X.Id) + 1;

                    // create system cloneSystems
                    EDSystem newSystem = new EDSystem(newSystemIndex, ownSystem);

                    // add it to merged data
                    m_Systems[(int)enDataType.Data_Merged].Add(newSystem);

                    // now go and get the stations
                    copyStationsForNewSystem(newSystem);
                }

                if (SystemCanBeDeleted)
                {
                    //
                     
                    // delete the system;
                    m_Systems[(int)enDataType.Data_Own].Remove(ownSystem);
                    m_changedSystems = true;

                }
            }

            return changedStations || changedSystems;
        }