Ejemplo n.º 1
0
        public static GTSLocationMessageCollection CreateGTSLocationMessages(Guid userId)
        {
            GTSLocationMessageCollection collection = new GTSLocationMessageCollection();

            GPSTrackerEntities1 dbContext = new GPSTrackerEntities1();



            IQueryable <TrackerUser> trackers = dbContext.TrackerUser.Where(m => m.UserId == userId);

            foreach (TrackerUser _tu in trackers)
            {
                IQueryable <LocationMessages> _messages =
                    dbContext.LocationMessages.Where(p => p.TrackerId == _tu.TrackerId);

                // need to get object representing the tracker information
                Trackers _trackerInfo = dbContext.Trackers.Where(p => p.Id == _tu.TrackerId).First();

                if (_messages.Count() > 0)
                {
                    DateTime         _maxTime = _messages.Max(p => p.ServerTime);
                    LocationMessages _message = _messages.Where(p => p.ServerTime == _maxTime).First();
                    collection.Add(CreateLocationMessage(_message, _trackerInfo));
                }
            }

            return(collection);
        }
Ejemplo n.º 2
0
        public void Read()
        {
            if (File.Exists(TrackersXML))
            {
                object obj = new object();
                try
                {
                    using (FileStream fs = new FileStream(TrackersXML, FileMode.Open, FileAccess.Read))
                    {
                        XmlSerializer xs = new XmlSerializer(Trackers.GetType());
                        obj = xs.Deserialize(fs);
                        fs.Close();
                    }

                    if (obj != null)
                    {
                        Trackers = (List <Tracker>)obj;
                    }

                    Debug.WriteLine("Done reading trackers.xml");
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Failed to deserialize. Reason: " + e.Message);
                }
            }
        }
Ejemplo n.º 3
0
        public T AddObjectToTracking <T>(T item)
            where T : IObjectId
        {
            if (item != null)
            {
                var type = item.GetType();
                if (TrackableTypes.ContainsKey(type))
                {
                    var key = item.GetHashCode();

                    if (Trackers.ContainsKey(item.Id))
                    {
                        return((T)Trackers[item.Id].LiveObj);
                    }
                    else
                    {
                        this.Set(type).AddToLoaded(item);
                        var currentTracker = new Tracker <T>(item);
                        this.Trackers.Add(item.Id, currentTracker);
                        return(item);
                    }
                }
            }
            return(default(T));
        }
Ejemplo n.º 4
0
 public void ChangeTracker(Trackers t)
 {
     try
     {
         switch (t)
         {
             case Trackers.FreeTrack:
                 {
                     Debug.Log("KerbTrack: Using FreeTrack");
                     tracker = new FreeTrackTracker();
                     break;
                 }
             case Trackers.TrackIR:
                 {
                     Debug.Log("KerbTrack: Using TrackIR");
                     tracker = new TrackIRTracker();
                     break;
                 }
             case Trackers.OculusRift:
                 {
                     Debug.Log("KerbTrack: Using Oculus Rift");
                     tracker = new OVRTracker();
                     break;
                 }
         }
     }
     catch (Exception)
     {
         trackerEnabled = false;
         throw;
     }
 }
        public TrackingInstance(ILogger <TrackingInstance> logger, ITrackingConfigFactory trackingConfigFactory, ISentimentAnalysis sentiment, ITrackingManager manager, ITwitPersistency persistency)
        {
            if (trackingConfigFactory == null)
            {
                throw new ArgumentNullException(nameof(trackingConfigFactory));
            }

            this.sentiment   = sentiment ?? throw new ArgumentNullException(nameof(sentiment));
            this.manager     = manager ?? throw new ArgumentNullException(nameof(manager));
            this.persistency = persistency ?? throw new ArgumentNullException(nameof(persistency));
            this.logger      = logger ?? throw new ArgumentNullException(nameof(logger));
            Trackers         = trackingConfigFactory.GetTrackers();
            foreach (var tracker in Trackers.Where(item => !item.IsKeyword))
            {
                if (users.Contains(tracker.Keyword))
                {
                    logger.LogWarning("Keyword is already added {0}", tracker.Keyword);
                    continue;
                }

                users.Add(tracker.Keyword);
            }

            Languages = trackingConfigFactory.GetLanguages();
        }
Ejemplo n.º 6
0
        public async Task LoadRemoteAsync()
        {
            ChangeTracker.AutoDetectChangesEnabled = false;

            await Guilds
            .LoadAsync()
            .ConfigureAwait(false);

            await Channels
            .LoadAsync()
            .ConfigureAwait(false);

            await Games
            .LoadAsync()
            .ConfigureAwait(false);

            await Trackers
            .Where(t => t.State != TrackerState.Dead)
            .LoadAsync()
            .ConfigureAwait(false);

            await Races
            .Include(r => r.Entrants)
            .Include(r => r.Announcements)
            .Where(r => r.IsActive)
            .LoadAsync()
            .ConfigureAwait(false);
        }
Ejemplo n.º 7
0
        public async Task <int> SaveChanges()
        {
            var count      = 0;
            var allInserts = Trackers.Where(tracker => tracker.Value.State == State.Added).Select(tracker => tracker.Value).ToList();

            var groupedBulkInserts = allInserts.GroupBy(b => b.Type);

            foreach (var group in groupedBulkInserts)
            {
                var method = typeof(MongoContext).GetTypeInfo().GetMethod(nameof(InsertBatch), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                method = method.MakeGenericMethod(group.Key);
                var   task = (Task)method.Invoke(this, new[] { group });
                await task;
                count += group.Count();
            }


            var saveChangesMethod = typeof(MongoContext).GetTypeInfo().GetMethod(nameof(SaveChangesGeneric), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            foreach (var trackerKeyValuePair in Trackers)
            {
                var genericSaveChangesMethod = saveChangesMethod.MakeGenericMethod(trackerKeyValuePair.Value.Type);
                var task = (Task <bool>)genericSaveChangesMethod.Invoke(this, new[] { trackerKeyValuePair.Value });
                if (await task)
                {
                    count++;
                }
            }

            return(count);
        }
Ejemplo n.º 8
0
        public static List <GTSLocationMessageLite> GetTrackerInfoByDate(
            string id, DateTime sdateTime, DateTime edateTime)
        {
            List <GTSLocationMessageLite> collection = new List <GTSLocationMessageLite>();

            GPSTrackerEntities1 dbContext = new GPSTrackerEntities1();

            DateTime defaultDateTime = new DateTime(1900, 01, 01);

            sdateTime = sdateTime == DateTime.MinValue ? defaultDateTime : sdateTime;
            edateTime = edateTime == DateTime.MinValue ? defaultDateTime : edateTime;

            // used >= sdateTime here so that the system will update time when tracking with the javascript
            // may want to implement this differently for efficiency
            IOrderedQueryable <LocationMessages> messages =
                dbContext.LocationMessages.Where(m => m.TrackerId == id &&
                                                 (sdateTime == defaultDateTime || m.ServerTime >= sdateTime) &&
                                                 (edateTime == defaultDateTime || m.ServerTime < edateTime))
                .OrderBy(message => message.ServerTime);

            // need to get object representing the tracker information
            Trackers _trackerInfo = dbContext.Trackers.Where(p => p.Id == id).First();


            foreach (LocationMessages message in messages)
            {
                collection.Add(CreateLocationMessageLite(message));
            }

            return(collection);
        }
Ejemplo n.º 9
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = (_projectsService != null ? _projectsService.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (_navigationService != null ? _navigationService.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (DetailCommand != null ? DetailCommand.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (EditCommand != null ? EditCommand.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Identify != null ? StringComparer.CurrentCulture.GetHashCode(Identify) : 0);
         hashCode = (hashCode * 397) ^ Id;
         hashCode = (hashCode * 397) ^ (Name != null ? StringComparer.CurrentCulture.GetHashCode(Name) : 0);
         hashCode = (hashCode * 397) ^ (Identifier != null ? StringComparer.CurrentCulture.GetHashCode(Identifier) : 0);
         hashCode = (hashCode * 397) ^ (Description != null ? StringComparer.CurrentCulture.GetHashCode(Description) : 0);
         hashCode = (hashCode * 397) ^ (Parent != null ? Parent.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (HomePage != null ? StringComparer.CurrentCulture.GetHashCode(HomePage) : 0);
         hashCode = (hashCode * 397) ^ CreatedOn.GetHashCode();
         hashCode = (hashCode * 397) ^ UpdatedOn.GetHashCode();
         hashCode = (hashCode * 397) ^ (int)Status;
         hashCode = (hashCode * 397) ^ IsPublic.GetHashCode();
         hashCode = (hashCode * 397) ^ InheritMembers.GetHashCode();
         hashCode = (hashCode * 397) ^ (Trackers != null ? Trackers.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (CustomFields != null ? CustomFields.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (IssueCategories != null ? IssueCategories.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (EnabledModules != null ? EnabledModules.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (TimeEntryActivities != null ? TimeEntryActivities.GetHashCode() : 0);
         return(hashCode);
     }
 }
Ejemplo n.º 10
0
        public bool Add(string trackerId, string mileageCount, string maintenanceNote)
        {
            try
            {
                //dirty
                GPSTrackerEntities1 context = new GPSTrackerEntities1();

                Maintenance m = context.Maintenance.CreateObject();

                m.trackerId        = trackerId;
                m.mileage          = Double.Parse(mileageCount);
                m.notes            = maintenanceNote;
                m.dateTimeRecorded = DateTime.Now;


                // Need to update table and last set location message?
                Trackers _tracker = context.Trackers.Where(t => t.Id == trackerId).FirstOrDefault();
                _tracker.Mileage = double.Parse(mileageCount);


                context.Maintenance.AddObject(m);
                context.SaveChanges();
                return(true);
            }
            catch (System.Exception ex)
            {
                return(false);
            }
        }
Ejemplo n.º 11
0
        public async Task <RouteInfo> GetRouteInfo(List <Locations> locations, Trackers Tracker)
        {
            RouteInfo routeInfo = new RouteInfo();

            if (locations.Count > 0)
            {
                Locations lastLocation  = locations.OrderBy(x => x.Date).Last();
                Locations firstLocation = locations.OrderBy(x => x.Date).First();
                routeInfo.Imei          = Tracker.Imei;
                routeInfo.GpsName       = Tracker.Name;
                routeInfo.GpsStatus     = Tracker.Status;
                routeInfo.Battery       = lastLocation.Battery ?? "No available info";
                routeInfo.LastDate      = lastLocation.Date.Value.ToString();
                routeInfo.LastLatitude  = lastLocation.Latitude.ToString().Replace(",", ".");
                routeInfo.LastLongitude = lastLocation.Longitude.ToString().Replace(",", ".");

                TimeSpan diff = gpsTimeHelper.GetElapsedTime(locations);
                routeInfo.ElapsedTime = diff.Days.ToString() + " days, " + diff.Hours + " hours, " + diff.Minutes + " minutes";

                routeInfo.GoogleDistance = await distanceMatrix.CalculateDistanceAsync(firstLocation.Latitude.ToString().Replace(",", ".") + "," + firstLocation.Longitude.ToString().Replace(",", "."), routeInfo.LastLatitude + "," + routeInfo.LastLongitude);

                routeInfo.Distance = gpsDistanceHelper.CalculateDistance(locations).ToString();

                foreach (var loc in locations)
                {
                    LatLng latLng = new LatLng {
                        Latitude = loc.Latitude.ToString().Replace(",", "."), Longitude = loc.Longitude.ToString().Replace(",", ".")
                    };
                    routeInfo.LatLngList.Add(latLng);
                }
            }

            return(routeInfo);
        }
Ejemplo n.º 12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="other"></param>
        /// <returns></returns>
        public bool Equals(Project other)
        {
            if (other == null)
            {
                return(false);
            }

            return(Id == other.Id &&
                   string.Equals(Identifier, other.Identifier, StringComparison.OrdinalIgnoreCase) &&
                   string.Equals(Description, other.Description, StringComparison.OrdinalIgnoreCase) &&
                   (Parent != null ? Parent.Equals(other.Parent) : other.Parent == null) &&
                   string.Equals(HomePage, other.HomePage, StringComparison.OrdinalIgnoreCase) &&
                   CreatedOn == other.CreatedOn &&
                   UpdatedOn == other.UpdatedOn &&
                   Status == other.Status &&
                   IsPublic == other.IsPublic &&
                   InheritMembers == other.InheritMembers &&
                   (Trackers != null ? Trackers.Equals <ProjectTracker>(other.Trackers) : other.Trackers == null) &&
                   (CustomFields != null ? CustomFields.Equals <IssueCustomField>(other.CustomFields) : other.CustomFields == null) &&
                   (IssueCategories != null ? IssueCategories.Equals <ProjectIssueCategory>(other.IssueCategories) : other.IssueCategories == null) &&
                   (EnabledModules != null ? EnabledModules.Equals <ProjectEnabledModule>(other.EnabledModules) : other.EnabledModules == null) &&
                   (TimeEntryActivities != null ? TimeEntryActivities.Equals <ProjectTimeEntryActivity>(other.TimeEntryActivities) : other.TimeEntryActivities == null) &&
                   (DefaultAssignee != null ? DefaultAssignee.Equals(other.DefaultAssignee) : other.DefaultAssignee == null) &&
                   (DefaultVersion != null ? DefaultVersion.Equals(other.DefaultVersion) : other.DefaultVersion == null));
        }
Ejemplo n.º 13
0
        private void LoadTrackers()
        {
            foreach (var tracker in Settings.GlobalSettings.Data.Trackers)
            {
                switch (tracker.Type)
                {
                case TrackerType.GitHub:
                    Trackers.Add(new GithubTaskTracker(tracker.Address));
                    break;

                case TrackerType.Jira:
                    Trackers.Add(new JiraTaskTracker(tracker.Address));
                    break;
                }
            }

            if (Trackers.Count == 0)
            {
                Trackers.Add(new GithubTaskTracker("https://github.com/bombomby/optick"));
            }

            var targetTracker = Settings.GlobalSettings.Data.ActiveTracker;

            if (targetTracker != null)
            {
                Tracker = Trackers.FirstOrDefault(t => t.Address == targetTracker.Address && t.TrackerType == targetTracker.Type);
            }

            if (Tracker == null && Trackers.Count > 0)
            {
                Tracker = Trackers[0];
            }
        }
Ejemplo n.º 14
0
        private static GTSLocationMessage getLastLocationMessageWithTrackerInfo(Trackers _tracker)
        {
            GPSTrackerEntities1 context = new GPSTrackerEntities1();
            GTSLocationMessage  retVal  = null;
            LocationMessages    message;

            try
            {
                //try to get the Location Message that's listed as the last known
                if (_tracker.LastLocationId.HasValue)
                {
                    message = context.LocationMessages.Where(m => m.Id == _tracker.LastLocationId.Value).First();
                    retVal  = CreateLocationMessage(message, _tracker);
                }
                else
                {
                    message = context.LocationMessages.Where(m => m.TrackerId == _tracker.Id)
                              .OrderByDescending(x => x.ServerTime).FirstOrDefault();
                    if (message != null)
                    {
                        retVal = CreateLocationMessage(message, _tracker);
                        //Update the Tracker object so that we know the last Location Id
                        if (retVal != null)
                        {
                            UpdateTrackerInformation(retVal);
                        }
                    }
                }
            }
            catch
            {
            }

            return(retVal);
        }
Ejemplo n.º 15
0
        private BoggleTracker CreateTracker(IBogglePlayer player, BoggleBoard board)
        {
            BoggleTracker tracker = new BoggleTracker(player.Id, board);

            Trackers.Add(tracker);
            return(tracker);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Needs to be updated to update general tracking information
        /// </summary>
        /// <param name="?"></param>
        public static void UpdateTrackerInformation(LocationMessages message)
        {
            GPSTrackerEntities1 context = new GPSTrackerEntities1();

            Trackers _tracker =
                context.Trackers.Where(t => t.Id == message.TrackerId).FirstOrDefault();

            _tracker.LastUpdate = DateTime.Now;
            _tracker.LastLat    = (new Latitude()
            {
                Degrees = message.LatDegrees, Minutes = message.LatMinutes, Seconds = message.LatSeconds, Heading = message.LatitudeHeading[0]
            }).Decimal;
            _tracker.LastLon    = (new Longitude()
            {
                Degrees = message.LngDegrees, Minutes = message.LngMinutes, Seconds = message.LngSeconds, Heading = message.LongitudeHeading[0]
            }).Decimal;

            if (message.Id != 0)
            {
                _tracker.LastLocationId = message.Id;
            }


            context.SaveChanges();
        }
        public void Add(TranslationJob job)
        {
            var lines = new TranslationLineTracker(job);

            Trackers.Add(lines);
            TotalLinesCount += lines.LinesCount;
        }
Ejemplo n.º 18
0
        /// <summary>
        /// All static classes and singletons meant for global
        /// usage are activated here. Some areas depend on these classes having their
        /// data loaded before the program starts (e.g., OdometerTracker), so it
        /// is very important that they are called here. All static classes should at
        /// the bare minimum implement an empty Activate() method to ensure their
        /// constructors are called
        /// </summary>
        private void ActivateStaticClasses()
        {
            EventBridge.Initialize();
            DiagnosticsParser.Initialize();
            CanMessageHandler.Initialize();
            ConfigManager.LoadConfiguration();
            DiagnosticLogger.Initialize();
            RawLogger.Initialize();
            PIDValueStager.Initialize();
            _EngineDataParser = new EngineDataParser();
            _Acceleration     = new Acceleration();
            _Trackers         = new Trackers();
            ChassisParameters.Initialize();
            var engineFilePointer = new FileOpener(ConfigManager.Settings.Contents.engineFilePath);

            if (engineFilePointer.Exists())
            {
                EngineSpec.SetEngineFile(engineFilePointer.absoluteFilepath);
            }
            else
            {
                MessageBox.Show("No engine files can be found. Horsepower and Torque settings will be inaccurate");
            }
            SPNDefinitions.Activate();      //in VMSpc/Parsers/J1939/SPNDefinitions.cs - Defines every SPN object
            //Odometer.Activate();
            //ParamData.Activate();
            TireManager.Initialize();
            CommunicationManager.Initialize();
            DayNightManager.Initialize();
        }
Ejemplo n.º 19
0
 public TrackingSummary(IEnumerable <Tracker> trackers, string name)
 {
     Name         = name;
     Trackers     = trackers.Where(t => t.StoppedAt.HasValue).OrderByDescending(t => t.StartedAt).ToList();
     TotalSeconds = Convert.ToInt32(Trackers
                                    .Select(t => (t.StoppedAt.Value - t.StartedAt).TotalSeconds)
                                    .Sum());
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Get the next page of shipments based on the original parameters used to generate the list
        /// </summary>
        /// <param name="client">Easy post client to use</param>
        /// <returns>A new ShipmentList instance.</returns>
        public async Task <TrackerList> Next(
            IEasyPostClient client)
        {
            var options = Options ?? new TrackerListOptions();

            options.BeforeId = Trackers.Last().Id;
            return(await client.ListTrackers(options));
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Checks to see if the data coming in is for an actual tracker of ours
        /// </summary>
        /// <param name="trackerId"></param>
        /// <returns></returns>
        public static bool TrackerExist(string trackerId)
        {
            GPSTrackerEntities1 context = new GPSTrackerEntities1();

            //get the Tracker (this is probably done elsewhere, so it's an extra hit, but it's less work than currently being done
            Trackers _tracker = context.Trackers.Where(t => t.Id == trackerId).FirstOrDefault();

            return(_tracker != null);
        }
Ejemplo n.º 22
0
 public void DeleteTracker()
 {
     if (SelectedTracker != null)
     {
         var tr = SelectedTracker;
         Trackers.Remove(tr);
         toRm.Add(tr.ID);
         toAdd.Remove(tr.announce);
     }
 }
Ejemplo n.º 23
0
        internal virtual ChangeNotificationTracker GetTracker(ModelProperty modelProperty, bool createNew)
        {
            ChangeNotificationTracker tracker = null;

            if (!this.Trackers.TryGetValue(modelProperty, out tracker) && createNew)
            {
                tracker = new ChangeNotificationTracker(this, modelProperty);
                Trackers.Add(modelProperty, tracker);
            }
            return(tracker);
        }
Ejemplo n.º 24
0
        public static Trackers GetTracker()
        {
            Trackers tracker = new Trackers()
            {
                Imei    = "1",
                Name    = "Name",
                Status  = "123",
                Battery = "20%"
            };

            return(tracker);
        }
Ejemplo n.º 25
0
        public virtual bool InsertTracker(ICoordinate coordinate, int index)
        {
            Trackers.Insert(index, new TrackerFeature(this, new Point(coordinate), index, null));

            TargetFeature.Geometry = GeometryHelper.InsertCurvePoint(TargetFeature.Geometry, coordinate, index);

            foreach (var topologyRule in FeatureRelationEditors)
            {
                topologyRule.UpdateRelatedFeatures(SourceFeature, TargetFeature.Geometry, SelectedTrackerIndices.ToList());
            }

            return(true);
        }
Ejemplo n.º 26
0
        public bool CompleteRegistration(string fname, string lname, string phonenumber, string passcode)
        {
            bool retval = true;
            GPSTrackerEntities1 context = new GPSTrackerEntities1();

            LR_Passcode pass = context.LR_Passcode.Where(p => p.phonenumber == phonenumber).FirstOrDefault();

            retval = pass != null && pass.Passcode.Trim() == passcode.Trim();

            if (retval)
            {
                Trackers newTracker = context.Trackers.Where(t => t.Id == phonenumber).FirstOrDefault();
                // test that this works if tracker does not exist and if it does exist
                if (newTracker == null)
                {
                    newTracker = new Trackers();
                    context.Trackers.AddObject(newTracker);
                    newTracker.Id = phonenumber;
                }

                newTracker.Name   = fname + " " + lname;
                newTracker.Type   = "TYPMB";
                newTracker.Status = "LR002";

                // Create or overwrite LimerInfo for user
                LR_LimerInfo _info = context.LR_LimerInfo.Where(p => p.TrackerId == phonenumber).FirstOrDefault();

                if (_info == null)
                {
                    _info = new LR_LimerInfo();
                    context.LR_LimerInfo.AddObject(_info);
                    _info.TrackerId = phonenumber;
                }

                _info.Vibe    = 1;
                _info.Status  = 3;
                _info.Message = "Hey, I'm on LimeR!!!";

                try
                {
                    context.SaveChanges();
                }
                catch (System.Exception e)
                {
                    ExceptionHandler.HandleGeneralException(e);
                    retval = false;
                }
            }
            return(retval);
        }
Ejemplo n.º 27
0
        public async Task GetRouteInfo_PassGpsLocations_GetCorrectRouteInfoObject()
        {
            //Arrange
            Trackers         tracker           = TrackersListStub.GetTracker();
            List <Locations> locations         = LocationsListStub.GetLocationsList().Where(x => x.Imei == tracker.Imei).ToList();
            GpsService       gpsService        = GetGpsService();
            RouteInfo        expectedRouteInfo = GetExpectedRouteInfo();

            //Act
            RouteInfo routeInfo = await gpsService.GetRouteInfo(locations, tracker);

            //Assert
            Assert.AreEqual(expectedRouteInfo, routeInfo);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Converts the torrent to a <see cref="BDictionary"/>.
        /// </summary>
        /// <returns></returns>
        public virtual BDictionary ToBDictionary()
        {
            var torrent = new BDictionary();

            var trackerCount = Trackers.Flatten().Count();

            if (trackerCount > 0)
            {
                torrent[TorrentFields.Announce] = new BList(Trackers.First().Select(x => new BString(x, Encoding)));
            }

            if (trackerCount > 1)
            {
                torrent[TorrentFields.AnnounceList] = new BList(Trackers.Select(x => new BList(x, Encoding)));
            }

            if (Encoding != null)
            {
                torrent[TorrentFields.Encoding] = new BString(Encoding.WebName.ToUpper(), Encoding);
            }

            if (Comment != null)
            {
                torrent[TorrentFields.Comment] = new BString(Comment, Encoding);
            }

            if (CreatedBy != null)
            {
                torrent[TorrentFields.CreatedBy] = new BString(CreatedBy, Encoding);
            }

            if (CreationDate != null)
            {
                torrent[TorrentFields.CreationDate] = (BNumber)CreationDate;
            }

            var info = CreateInfoDictionary(Encoding);

            if (info.Any())
            {
                torrent[TorrentFields.Info] = info;
            }

            if (ExtraFields != null)
            {
                torrent.MergeWith(ExtraFields, ExistingKeyAction.Merge);
            }

            return(torrent);
        }
Ejemplo n.º 29
0
        public int AddTracker(int trackerId)
        {
            var tracker = new Tracker()
            {
                TrackerId = trackerId
            };

            lock (lockObj) {
                Trackers.Add(tracker);

                SaveChanges();
            }
            return(tracker.TrackerId);
        }
Ejemplo n.º 30
0
        void ParseTrackers()
        {
            string[] addresses = VotingsUser.Trackers.Split('\n');

            foreach (var line in addresses)
            {
                var parts = line.Split(':');

                IPAddress addr = new IPAddress(0);
                /*int port = 0;*/
                if (parts.Length >= 1 && IPAddress.TryParse(parts[0], out addr) /*&& int.TryParse(parts[1], out port)*/)
                {
                    EndPoint endPoint = new IPEndPoint(addr, CommonHelpers.TrackerPort);

                    Tracker tracker = new Tracker(endPoint, Trackers);

                    //перенаправляем события трекера вне
                    tracker.OnRequestBlocksMessage += (s, e) =>
                    {
                        OnRequestBlocksMessage?.Invoke(s, e);
                    };

                    tracker.OnRequestTransactionsMessage += (s, e) =>
                    {
                        OnRequestTransactionsMessage?.Invoke(s, e);
                    };

                    tracker.OnBlocksMessage += (s, e) =>
                    {
                        OnBlocksMessage?.Invoke(s, e);
                    };

                    tracker.OnTransactionsMessage += (s, e) =>
                    {
                        OnTransactionsMessage?.Invoke(s, e);
                    };


                    //получение пиров
                    tracker.OnPeersMessageFromPeer    += OnPeersMessage;
                    tracker.OnPeersMessageFromTracker += OnPeersMessage;

                    //коннект через трекер
                    tracker.OnConnectToPeerWithTrackerMessage += OnConnectToPeerWithTrackerMessage;

                    Trackers.Add(tracker);
                }
            }
        }
Ejemplo n.º 31
0
        public async Task TryDeleteLoggedDayAsync_ExistingId_DoesNotDeleteTracker()
        {
            // arrange
            var service = new TrackerLogService(_database, _logger);
            int id      = 1;

            // act
            var trackerId = LoggedDays.First(day => day.Id == id).TrackerId;
            await service.TryDeleteLoggedDayAsync(id);

            var tracker = Trackers.FirstOrDefault(t => t.Id == trackerId);

            // assert
            Assert.NotNull(tracker);
        }
Ejemplo n.º 32
0
 public string GetTrackerName(Trackers t)
 {
     return Enum.GetName(t.GetType(), t);
 }