Esempio n. 1
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));
                }
            }
        }
Esempio n. 2
0
        /// <summary>
        /// creates a new station as a copy of another station
        /// only Id and StationID must declared extra
        /// </summary>
        /// <param name="newId"></param>
        /// <param name="sourceSystemID"></param>
        /// <param name="sourceStation"></param>
        public EDStation(int newId, int sourceSystemID, EDStation sourceStation)
        {
            clear();

            Id       = newId;
            SystemId = sourceSystemID;
            getValues(sourceStation);
        }
Esempio n. 3
0
        /// <summary>
        /// creates a new station as a copy of another station
        /// only Id and StationID must declared extra
        /// </summary>
        /// <param name="newId"></param>
        /// <param name="sourceSystemID"></param>
        /// <param name="sourceStation"></param>
        public EDStation(int newId, int sourceSystemID, EDStation sourceStation)
        {
            clear();

            Id              = newId;
            SystemId        = sourceSystemID;
            getValues(sourceStation);
        }
Esempio n. 4
0
        internal EDStationView(EDStation Station)
        {
            InitializeComponent();

            m_Station = Station;

            showData();

            this.Show();
        }
Esempio n. 5
0
        internal EDStationView(EDStation Station)
        {

            InitializeComponent();

            m_Station = Station;

            showData();

            this.Show();
        }
Esempio n. 6
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);
        }
Esempio n. 7
0
        /// <summary>
        /// true, if all data *except the two IDs* is equal (case insensitive)
        /// </summary>
        /// <param name="eqSystem"></param>
        /// <returns></returns>
        public bool EqualsED(EDStation eqStation)
        {
            bool retValue = false;

            if (eqStation != null)
            {
                if (ObjectCompare.EqualsNullable(this.Name, eqStation.Name) &&
                    ObjectCompare.EqualsNullable(this.MaxLandingPadSize, eqStation.MaxLandingPadSize) &&
                    ObjectCompare.EqualsNullable(this.DistanceToStar, eqStation.DistanceToStar) &&
                    ObjectCompare.EqualsNullable(this.Faction, eqStation.Faction) &&
                    ObjectCompare.EqualsNullable(this.Government, eqStation.Government) &&
                    ObjectCompare.EqualsNullable(this.Allegiance, eqStation.Allegiance) &&
                    ObjectCompare.EqualsNullable(this.State, eqStation.State) &&
                    ObjectCompare.EqualsNullable(this.Type, eqStation.Type) &&
                    ObjectCompare.EqualsNullable(this.HasBlackmarket, eqStation.HasBlackmarket) &&
                    ObjectCompare.EqualsNullable(this.HasMarket, eqStation.HasMarket) &&
                    ObjectCompare.EqualsNullable(this.HasRefuel, eqStation.HasRefuel) &&
                    ObjectCompare.EqualsNullable(this.HasRepair, eqStation.HasRepair) &&
                    ObjectCompare.EqualsNullable(this.HasRearm, eqStation.HasRearm) &&
                    ObjectCompare.EqualsNullable(this.HasOutfitting, eqStation.HasOutfitting) &&
                    ObjectCompare.EqualsNullable(this.HasShipyard, eqStation.HasShipyard) &&
                    ObjectCompare.EqualsNullable(this.ImportCommodities, eqStation.ImportCommodities) &&
                    ObjectCompare.EqualsNullable(this.ExportCommodities, eqStation.ExportCommodities) &&
                    ObjectCompare.EqualsNullable(this.ProhibitedCommodities, eqStation.ProhibitedCommodities) &&
                    ObjectCompare.EqualsNullable(this.Economies, eqStation.Economies) &&
                    ObjectCompare.EqualsNullable(this.UpdatedAt, eqStation.UpdatedAt) &&
                    ObjectCompare.EqualsNullable(this.Shipyard_UpdatedAt, eqStation.Shipyard_UpdatedAt) &&
                    ObjectCompare.EqualsNullable(this.Outfitting_UpdatedAt, eqStation.Outfitting_UpdatedAt) &&
                    ObjectCompare.EqualsNullable(this.Market_UpdatedAt, eqStation.Market_UpdatedAt) &&
                    ObjectCompare.EqualsNullable(this.TypeID, eqStation.TypeID) &&
                    ObjectCompare.EqualsNullable(this.HasCommodities, eqStation.HasCommodities) &&
                    ObjectCompare.EqualsNullable(this.IsPlanetary, eqStation.IsPlanetary) &&
                    ObjectCompare.EqualsNullable(this.SellingShips, eqStation.SellingShips) &&
                    ObjectCompare.EqualsNullable(this.SellingModules, eqStation.SellingModules)
                    )
                {
                    retValue = true;
                }
            }

            return(retValue);
        }
Esempio n. 8
0
        /// <summary>
        /// copy the values from another station exept for the ID
        /// </summary>
        /// <param name="ValueStation"></param>
        public void getValues(EDStation ValueStation, bool getAll = false)
        {
            if (getAll)
            {
                Id       = ValueStation.Id;
                SystemId = ValueStation.SystemId;
            }

            Name = ValueStation.Name;
            MaxLandingPadSize = ValueStation.MaxLandingPadSize;
            DistanceToStar    = ValueStation.DistanceToStar;
            Faction           = ValueStation.Faction;
            Government        = ValueStation.Government;
            Allegiance        = ValueStation.Allegiance;
            State             = ValueStation.State;
            Type           = ValueStation.Type;
            HasBlackmarket = ValueStation.HasBlackmarket;
            HasMarket      = ValueStation.HasMarket;
            HasRefuel      = ValueStation.HasRefuel;
            HasRepair      = ValueStation.HasRepair;
            HasRearm       = ValueStation.HasRearm;
            HasOutfitting  = ValueStation.HasOutfitting;
            HasShipyard    = ValueStation.HasShipyard;

            ImportCommodities     = ValueStation.ImportCommodities.CloneN();
            ExportCommodities     = ValueStation.ExportCommodities.CloneN();
            ProhibitedCommodities = ValueStation.ProhibitedCommodities.CloneN();
            Economies             = ValueStation.Economies.CloneN();

            UpdatedAt            = ValueStation.UpdatedAt;
            Shipyard_UpdatedAt   = ValueStation.Shipyard_UpdatedAt;
            Outfitting_UpdatedAt = ValueStation.Outfitting_UpdatedAt;
            Market_UpdatedAt     = ValueStation.Market_UpdatedAt;
            TypeID         = ValueStation.TypeID;
            HasCommodities = ValueStation.HasCommodities;
            IsPlanetary    = ValueStation.IsPlanetary;
            SellingShips   = ValueStation.SellingShips.CloneN();
            SellingModules = ValueStation.SellingModules.CloneN();
        }
Esempio n. 9
0
        /// <summary>
        /// returns distance of a station to the star
        /// </summary>
        /// <param name="Systemname"></param>
        /// <param name="Locationname"></param>
        /// <returns></returns>
        public Int32 getStationDistance(string systemName, string stationName)
        {
            Int32 Distance = 0;

            if (!m_cachedStationDistances.TryGetValue(systemName + "|" + stationName, out Distance))
            {
                EDStation retValue = getStation(systemName, stationName);

                if ((retValue != null) && (retValue.DistanceToStar != null))
                {
                    Distance = (int)(retValue.DistanceToStar);
                }
                else
                {
                    Distance = -1;
                }

                m_cachedStationDistances.Add(systemName + "|" + stationName, Distance);
            }

            return(Distance);
        }
Esempio n. 10
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);        
        }
Esempio n. 11
0
        /// <summary>
        /// creates a list of "EDStations" with price listings from csv-array in EDDB format
        /// </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_EDDB(String[] CSV_Strings)
        {
            List<EDStation> foundValues                     = new List<EDStation>();
            Dictionary<Int32, Int32> foundIndex             = new Dictionary<Int32, Int32>();
            Dictionary<String, Int32> foundSystemIndex      = new Dictionary<String, Int32>();
            Int32 LastID                                    = 0;
            EDSystem LastSystem                             = null;
            Int32 currentID                                 = 0;
            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), NewLine= true};
                sendProgressEvent(eva);

                foreach (String CSV_String in CSV_Strings)
	            {

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

                        currentID = currentRow.StationId;

                        if(LastID != currentID)
                        {
                            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;

                        }

                        currentStation.addListing(currentRow);
                    }
                
                    eva = new ProgressEventArgs() { Info="converting data...", CurrentValue=currentItem, TotalValue=CSV_Strings.GetUpperBound(0)};
                    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), ForceRefresh=true};
                sendProgressEvent(eva);

                return foundValues;

            }
            catch (Exception ex)
            {
                throw new Exception("Error while getting station values from CSV-String", ex);
            }
        }
Esempio n. 12
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);
            }
        }
Esempio n. 13
0
        /// <summary>
        /// copies the commodities data from a "EDStation"-object to "tb_______Commodity"-table
        /// </summary>
        /// <param name="StationObject"></param>
        /// <param name="EconomyRow"></param>
        private void CopyEDStationCommodityToDataRow(EDStation StationObject, dsEliteDB Data, ref UInt32 AutoIndex)
        {
            Int32 i;
            String[] currentCommodityCollection = null;
            String currentCommodityAttribute = null;

            try
            {
               
                var existingClassification      =  ((dsEliteDB.tbcommodityclassificationRow[])Data.tbcommodityclassification.Select("station_id = " + StationObject.Id)).ToList();
                var newCommodityClassification  = new Dictionary<String, List<String>>();

                // collect classification data
                for(i=0 ; i<=2 ; i++)
                {
                    switch (i)
                    {
                    	case 0:
                    		currentCommodityCollection  = StationObject.ImportCommodities;
                            currentCommodityAttribute   = "import";
                    		break;
                    	case 1:
                    		currentCommodityCollection  = StationObject.ExportCommodities;
                            currentCommodityAttribute   = "export";
                    		break;
                    	case 2:
                    		currentCommodityCollection  = StationObject.ProhibitedCommodities;
                            currentCommodityAttribute   = "prohibited";
                    		break;
                    }

                    foreach (var Commodity in currentCommodityCollection)
	                {
                        // cyxle throught the <Attribute>-commodities from the station
                        List<String> currentClassification;
		                if(!newCommodityClassification.TryGetValue(Commodity, out currentClassification))
                        {
                            // this commodity is not registered at all
                            var newCL = new List<String>() {currentCommodityAttribute};
                            newCommodityClassification.Add(Commodity, newCL);
                        }
                        else
                        {
                            // this commodity is already registered
                            if(!currentClassification.Contains(currentCommodityAttribute))
                            {
                                // but not yet for this classification
                                currentClassification.Add(currentCommodityAttribute);
                            }
                        }
	                }
                }

                // process classification data
                foreach (var Classification in newCommodityClassification)
                {
                    // get the current commodity id
                    Int32  CommodityID = (Int32)DBConvert.From(BaseTableNameToID("commodity", Classification.Key));
                    UInt32 CClassifID;

                    // and check, if the commodity is already added to station
                    var Found = from dsEliteDB.tbcommodityclassificationRow relevantCommodity in existingClassification
                                where  ((relevantCommodity.RowState      != DataRowState.Deleted) 
                                     && (relevantCommodity.commodity_id  == CommodityID))
                                select relevantCommodity;

                    // if it's not existing, insert commodity
                    if(Found.Count() == 0)
                    {
                        var newRow = (dsEliteDB.tbcommodityclassificationRow)Data.tbcommodityclassification.NewRow();

                        newRow.id           = AutoIndex;
                        newRow.station_id   = StationObject.Id;
                        newRow.commodity_id = CommodityID;

                        Data.tbcommodityclassification.Rows.Add(newRow);

                        CClassifID          = newRow.id;
                        AutoIndex          += 1;
                    }
                    else
                    {
                        // memorize the id and remove commodity from list to mark it as "found"
                        CClassifID = Found.First().id;
                        existingClassification.Remove(Found.First());
                        //Debug.Print("removed " + Classification.Key);
                    }

                    var existingAttributes    =  ((dsEliteDB.tbcommodity_has_attributeRow[])Data.tbcommodity_has_attribute.Select("tbcommodityclassification_id   = " + CClassifID)).ToList();

                    // now check the attributes for this commodity
                    foreach (var Attribute in Classification.Value)
                    {
                        // get the current attribute id
                        Int32 AttributeID = (Int32)DBConvert.From(BaseTableNameToID("attribute", Attribute));    

                        // and check, if the attribute is already added to classification
                        var FoundCC = from dsEliteDB.tbcommodity_has_attributeRow relevantCommodity in existingAttributes
                                    where   relevantCommodity.RowState        != DataRowState.Deleted
                                         && relevantCommodity.tbAttribute_id  == AttributeID
                                    select relevantCommodity;

                        // if it's not existing, insert attribute
                        if(FoundCC.Count() == 0)
                        {
                            var newRow = (dsEliteDB.tbcommodity_has_attributeRow)Data.tbcommodity_has_attribute.NewRow();

                            newRow.tbAttribute_id               = AttributeID;
                            newRow.tbCommodityClassification_id = CClassifID;

                            Data.tbcommodity_has_attribute.Rows.Add(newRow);
                        }
                        else
                        {
                            // remove attribute from list to mark it as "found"
                            existingAttributes.Remove(FoundCC.First());
                        }
                    }

                    // remove all old, not more existing attributes
                    foreach (DataRow RemovedRow in existingAttributes)
                        Data.tbcommodity_has_attribute.Rows.Remove(RemovedRow);    

                }

                // remove all old, not more existing classification
                foreach (DataRow RemovedRow in existingClassification)
                    Data.tbcommodityclassification.Rows.Remove(RemovedRow);    

            }
            catch (Exception ex)
            {
                throw new Exception("Error while copying station commodity data", ex);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// copy the values from another station exept for the ID
        /// </summary>
        /// <param name="ValueStation"></param>
        public void getValues(EDStation ValueStation, bool getAll = false)
        {
            if (getAll)
            {
                Id          = ValueStation.Id;
                SystemId    = ValueStation.SystemId;
            }

            Name                  = ValueStation.Name;
            MaxLandingPadSize     = ValueStation.MaxLandingPadSize;
            DistanceToStar        = ValueStation.DistanceToStar;
            Faction               = ValueStation.Faction;
            Government            = ValueStation.Government;
            Allegiance            = ValueStation.Allegiance;
            State                 = ValueStation.State;
            Type                  = ValueStation.Type;
            HasBlackmarket        = ValueStation.HasBlackmarket;
            HasMarket             = ValueStation.HasMarket;
            HasRefuel             = ValueStation.HasRefuel;
            HasRepair             = ValueStation.HasRepair;
            HasRearm              = ValueStation.HasRearm;
            HasOutfitting         = ValueStation.HasOutfitting;
            HasShipyard           = ValueStation.HasShipyard;

            ImportCommodities     = ValueStation.ImportCommodities.CloneN();
            ExportCommodities     = ValueStation.ExportCommodities.CloneN();
            ProhibitedCommodities = ValueStation.ProhibitedCommodities.CloneN();
            Economies             = ValueStation.Economies.CloneN();

            UpdatedAt             = ValueStation.UpdatedAt;             
            Shipyard_UpdatedAt    = ValueStation.Shipyard_UpdatedAt;    
            Outfitting_UpdatedAt  = ValueStation.Outfitting_UpdatedAt;  
            Market_UpdatedAt      = ValueStation.Market_UpdatedAt;      
            TypeID                = ValueStation.TypeID;                
            HasCommodities        = ValueStation.HasCommodities;        
            IsPlanetary           = ValueStation.IsPlanetary;           
            SellingShips          = ValueStation.SellingShips.CloneN();          
            SellingModules        = ValueStation.SellingModules.CloneN();        

        }
Esempio n. 15
0
        /// <summary>
        /// copies the data from a "EDStation"-object to a Datarow from table "tbStations"
        /// </summary>
        /// <param name="SystemObject"></param>
        /// <param name="SystemRow"></param>
        private void CopyEDStationToDataRow(EDStation StationObject, DataRow StationRow, Boolean OwnData = false, int? StationID = null, Boolean insertUnknown = false)
        {
            try
            {

                StationRow["id"]                    = StationID == null ? DBConvert.From(StationObject.Id) : StationID;
                StationRow["stationname"]           = DBConvert.From(StationObject.Name);
                StationRow["system_id"]             = DBConvert.From(StationObject.SystemId);
                StationRow["max_landing_pad_size"]  = DBConvert.From(StationObject.MaxLandingPadSize);
                StationRow["distance_to_star"]      = DBConvert.From(StationObject.DistanceToStar);
                StationRow["faction"]               = DBConvert.From(StationObject.Faction);
                StationRow["government_id"]         = DBConvert.From(BaseTableNameToID("government", StationObject.Government, insertUnknown));
                StationRow["allegiance_id"]         = DBConvert.From(BaseTableNameToID("allegiance", StationObject.Allegiance, insertUnknown));
                StationRow["state_id"]              = DBConvert.From(BaseTableNameToID("state", StationObject.State, insertUnknown));
                StationRow["stationtype_id"]        = DBConvert.From(BaseTableNameToID("stationtype", StationObject.Type, insertUnknown));
                StationRow["has_blackmarket"]       = DBConvert.From(StationObject.HasBlackmarket);
                StationRow["has_market"]            = DBConvert.From(StationObject.HasMarket);
                StationRow["has_refuel"]            = DBConvert.From(StationObject.HasRefuel);
                StationRow["has_repair"]            = DBConvert.From(StationObject.HasRepair);
                StationRow["has_outfitting"]        = DBConvert.From(StationObject.HasOutfitting);
                StationRow["has_shipyard"]          = DBConvert.From(StationObject.HasShipyard);
                StationRow["updated_at"]            = DBConvert.From(DateTimeOffset.FromUnixTimeSeconds(StationObject.UpdatedAt).DateTime);
                StationRow["is_changed"]            = OwnData ? DBConvert.From(1) : DBConvert.From(0);
                StationRow["visited"]               = DBConvert.From(0);
                StationRow["shipyard_updated_at"]   = DBConvert.From(DateTimeOffset.FromUnixTimeSeconds(StationObject.Shipyard_UpdatedAt.GetValueOrDefault()).DateTime);
                StationRow["outfitting_updated_at"] = DBConvert.From(DateTimeOffset.FromUnixTimeSeconds(StationObject.Outfitting_UpdatedAt.GetValueOrDefault()).DateTime);
                StationRow["market_updated_at"]     = DBConvert.From(DateTimeOffset.FromUnixTimeSeconds(StationObject.Market_UpdatedAt.GetValueOrDefault()).DateTime);
                StationRow["type_id"]               = DBConvert.From(StationObject.TypeID);
                StationRow["has_commodities"]       = DBConvert.From(StationObject.HasCommodities); 
                StationRow["is_planetary"]          = DBConvert.From(StationObject.IsPlanetary);

            }
            catch (Exception ex)
            {
                throw new Exception("Error while copying station data", ex);
            }
        }
Esempio n. 16
0
 /// <summary>
 /// imports the "own" station data from the list of stations
 /// </summary>
 /// <param name="fileName"></param>
 public void ImportStations_Own(EDStation Station, Boolean OnlyAddUnknown = false, Boolean setVisitedFlag = false)
 {
     try
     {
         ImportStations_Own(new List<EDStation>() {Station}, new Dictionary<Int32, Int32>(), OnlyAddUnknown, setVisitedFlag);
     }
     catch (Exception ex)
     {
         throw new Exception("Error in <ImportSystems_Own> from single station", ex);
     }
 }
Esempio n. 17
0
        /// <summary>
        /// true, if all data *except the two IDs* is equal (case insensitive)
        /// </summary>
        /// <param name="eqSystem"></param>
        /// <returns></returns>
        public bool EqualsED(EDStation eqStation)
        {
            bool retValue = false;

            if(eqStation != null)
            {


                if (ObjectCompare.EqualsNullable(this.Name, eqStation.Name) &&
                    ObjectCompare.EqualsNullable(this.MaxLandingPadSize, eqStation.MaxLandingPadSize) && 
                    ObjectCompare.EqualsNullable(this.DistanceToStar, eqStation.DistanceToStar) && 
                    ObjectCompare.EqualsNullable(this.Faction, eqStation.Faction) && 
                    ObjectCompare.EqualsNullable(this.Government, eqStation.Government) && 
                    ObjectCompare.EqualsNullable(this.Allegiance, eqStation.Allegiance) && 
                    ObjectCompare.EqualsNullable(this.State, eqStation.State) && 
                    ObjectCompare.EqualsNullable(this.Type, eqStation.Type) && 
                    ObjectCompare.EqualsNullable(this.HasBlackmarket, eqStation.HasBlackmarket) && 
                    ObjectCompare.EqualsNullable(this.HasMarket, eqStation.HasMarket) && 
                    ObjectCompare.EqualsNullable(this.HasRefuel, eqStation.HasRefuel) &&
                    ObjectCompare.EqualsNullable(this.HasRepair, eqStation.HasRepair) && 
                    ObjectCompare.EqualsNullable(this.HasRearm, eqStation.HasRearm) &&
                    ObjectCompare.EqualsNullable(this.HasOutfitting, eqStation.HasOutfitting) &&
                    ObjectCompare.EqualsNullable(this.HasShipyard, eqStation.HasShipyard) &&
                    ObjectCompare.EqualsNullable(this.ImportCommodities, eqStation.ImportCommodities) &&
                    ObjectCompare.EqualsNullable(this.ExportCommodities, eqStation.ExportCommodities) &&
                    ObjectCompare.EqualsNullable(this.ProhibitedCommodities, eqStation.ProhibitedCommodities) &&
                    ObjectCompare.EqualsNullable(this.Economies, eqStation.Economies) &&
                    ObjectCompare.EqualsNullable(this.UpdatedAt, eqStation.UpdatedAt) &&             
                    ObjectCompare.EqualsNullable(this.Shipyard_UpdatedAt, eqStation.Shipyard_UpdatedAt) &&
                    ObjectCompare.EqualsNullable(this.Outfitting_UpdatedAt, eqStation.Outfitting_UpdatedAt) &&  
                    ObjectCompare.EqualsNullable(this.Market_UpdatedAt, eqStation.Market_UpdatedAt) &&      
                    ObjectCompare.EqualsNullable(this.TypeID, eqStation.TypeID) &&                
                    ObjectCompare.EqualsNullable(this.HasCommodities, eqStation.HasCommodities) &&        
                    ObjectCompare.EqualsNullable(this.IsPlanetary, eqStation.IsPlanetary) &&           
                    ObjectCompare.EqualsNullable(this.SellingShips, eqStation.SellingShips) &&          
                    ObjectCompare.EqualsNullable(this.SellingModules, eqStation.SellingModules)        
                    )
                        retValue = true;

            }

            return retValue;             
        }
Esempio n. 18
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);
            }
        }
Esempio n. 19
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);
            }
        }
Esempio n. 20
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);
        }
Esempio n. 21
0
        private void loadStationData(string Systemname, string Stationname, bool isNew=false)
        {
            m_StationLoadingValues = true;

            if (isNew)
            {
                cmbStationStations.SelectedIndex    = -1;
                m_loadedStationdata                 = new EDStation();
                m_loadedStationdata.Name            = Stationname;
                m_StationIsNew                      = true;
            }
            else
            {
                cmbStationStations.SelectedItem    = Stationname;

                if (Debugger.IsAttached)
                    MessageBox.Show("TODO");
                //m_loadedStationdata                 = _Milkyway.getLocation(Systemname, Locationname);
                m_StationIsNew                      = false;
            }

            if (m_loadedStationdata != null)
            {
                m_currentStationdata.getValues(m_loadedStationdata, true);

                txtStationId.Text = m_loadedStationdata.Id.ToString(CultureInfo.CurrentCulture);
                txtStationName.Text = m_loadedStationdata.Name.ToString();
                cmbStationMaxLandingPadSize.Text = m_loadedStationdata.MaxLandingPadSize.NToString();
                txtStationDistanceToStar.Text = m_loadedStationdata.DistanceToStar.ToNString();
                txtStationFaction.Text = m_loadedStationdata.Faction.NToString();
                cmbStationGovernment.Text = m_loadedStationdata.Government.NToString();
                cmbStationAllegiance.Text = m_loadedStationdata.Allegiance.NToString();
                cmbStationState.Text = m_loadedStationdata.State.NToString();
                cmbStationType.Text = m_loadedStationdata.Type.NToString();

                txtStationUpdatedAt.Text = DateTimeOffset.FromUnixTimeSeconds(m_loadedStationdata.UpdatedAt).DateTime.ToString(CultureInfo.CurrentUICulture);

                lbStationEconomies.Items.Clear();

                foreach (string Economy in m_loadedStationdata.Economies)
                    lbStationEconomies.Items.Add(Economy);

                cbStationHasMarket.CheckState = m_loadedStationdata.HasMarket.toCheckState();
                cbStationHasBlackmarket.CheckState = m_loadedStationdata.HasBlackmarket.toCheckState();
                cbStationHasOutfitting.CheckState = m_loadedStationdata.HasOutfitting.toCheckState();
                cbStationHasShipyard.CheckState = m_loadedStationdata.HasShipyard.toCheckState();
                cbStationHasRearm.CheckState = m_loadedStationdata.HasRearm.toCheckState();
                cbStationHasRefuel.CheckState = m_loadedStationdata.HasRefuel.toCheckState();
                cbStationHasRepair.CheckState = m_loadedStationdata.HasRepair.toCheckState();

                setStationEditable(isNew);

                if(!isNew)
                {
                    cmdStationNew.Enabled       = true;
                    cmdStationEdit.Enabled      = true;
                    cmdStationSave.Enabled      = false;
                    cmdStationCancel.Enabled    = cmdStationSave.Enabled;

                    cmbStationStations.ReadOnly = false;

                }

            //                if (_Milkyway.getStations(EDMilkyway.enDataType.Data_EDDB).Exists(x => (x.Name.Equals(m_loadedStationdata.Name, StringComparison.InvariantCultureIgnoreCase)) &&
            //                                                                                      (x.SystemId == m_loadedStationdata.SystemId)))
                if (Debugger.IsAttached)
                    MessageBox.Show("TODO");

                if(false)
                {
                    txtStationName.ReadOnly = true;
                    lblStationRenameHint.Visible = true;
                }
                else
                {
                    txtStationName.ReadOnly = false;
                    lblStationRenameHint.Visible = false;
                }

            }
            else
            {
                m_currentStationdata.clear();

                txtStationId.Text = Program.NULLSTRING;
                txtStationName.Text = Program.NULLSTRING;
                cmbStationMaxLandingPadSize.Text = Program.NULLSTRING;
                txtStationDistanceToStar.Text = Program.NULLSTRING;
                txtStationFaction.Text = Program.NULLSTRING;
                cmbStationGovernment.Text = Program.NULLSTRING;
                cmbStationAllegiance.Text = Program.NULLSTRING;
                cmbStationState.Text = Program.NULLSTRING;
                txtStationUpdatedAt.Text = Program.NULLSTRING;
                cmbStationType.Text = Program.NULLSTRING;

                lbStationEconomies.Items.Clear();

                cbStationHasMarket.CheckState = CheckState.Unchecked;
                cbStationHasBlackmarket.CheckState = CheckState.Unchecked;
                cbStationHasOutfitting.CheckState = CheckState.Unchecked;
                cbStationHasShipyard.CheckState = CheckState.Unchecked;
                cbStationHasRearm.CheckState = CheckState.Unchecked;
                cbStationHasRefuel.CheckState = CheckState.Unchecked;
                cbStationHasRepair.CheckState = CheckState.Unchecked;

                setStationEditable(false);

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

                lblStationRenameHint.Visible = false;

                cmbStationStations.Text = "";

            }

            m_StationLoadingValues = false;
        }
Esempio n. 22
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;
                }
        }
Esempio n. 23
0
        /// <summary>
        /// copies the economies data from a "EDStation"-object to "tbStationEconomy"-table
        /// </summary>
        /// <param name="StationObject"></param>
        /// <param name="EconomyRow"></param>
        /// <param name=""></param>
        private void CopyEDStationEconomiesToDataRows(EDStation StationObject, System.Data.DataTable EconomyTable)
        {
            try
            {

                // get all existing economies from the database (memory list)
                List<DataRow> Existing = EconomyTable.Select("station_id = " + StationObject.Id).ToList();

                foreach (String Economy in StationObject.Economies)
                {
                    // get the current new economy id
                    Int32 EconomyID = (Int32)DBConvert.From(BaseTableNameToID("economy", Economy));

                    // and check, if it is already existing
                    var Found = from DataRow relevantEconomy in Existing
                                where relevantEconomy.Field<Int32>("economy_id") == EconomyID
                                select relevantEconomy;
 
                    // if it's not existing, insert it
                    if(Found.Count() == 0)
                    {
                        DataRow newRow = EconomyTable.NewRow();

                        newRow["station_id"]        = StationObject.Id;
                        newRow["economy_id"]        = EconomyID;

                        EconomyTable.Rows.Add(newRow);

                    }
                    else
                    {
                        Existing.Remove(Found.First());
                    }
                }

                // remove all old, not more existing data
                foreach (DataRow RemovedRow in Existing)
                    EconomyTable.Rows.Remove(RemovedRow);    

            }
            catch (Exception ex)
            {
                throw new Exception("Error while copying station economy data", ex);
            }
        }