예제 #1
0
        public void AddActivityFile(int activityId, ActivityFileDTO activityFile)
        {
            var activityEntity = _databaseContext.Activities
                                 .Include(a => a.Files)
                                 .FirstOrDefault(a => a.Id == activityId);

            if (activityEntity == null)
            {
                return;
            }

            var activityFileEntity = new ActivityFile
            {
                Content    = activityFile.Content,
                CreatedOn  = activityFile.CreatedOn,
                FileName   = activityFile.FileName,
                FileSize   = activityFile.FileSize,
                MimeType   = activityFile.MimeType,
                PathUrl    = activityFile.PathUrl,
                ActivityId = activityEntity.Id
            };

            activityEntity.Files.Add(activityFileEntity);

            try
            {
                _databaseContext.SaveChanges();
            }
            catch
            {
            }
        }
예제 #2
0
        internal static Activity FromPath(string filePath, Folder folder, Route route)
        {
            Activity result;

            try
            {
                ActivityFile activityFile = new ActivityFile(filePath);
                ServiceFile  srvFile      = new ServiceFile(route.RouteFolder.ServiceFile(activityFile.Activity.PlayerServices.Name));
                Consist      consist      = Consist.GetConsist(folder, srvFile.TrainConfig, false);
                Path         path         = new Path(route.RouteFolder.PathFile(srvFile.PathId));
                if (!path.IsPlayerPath)
                {
                    return(null);

                    // Not nice to throw an error now. Error was originally thrown by new Path(...);
                    throw new InvalidDataException("Not a player path");
                }
                else if (!activityFile.Activity.Header.RouteID.Equals(route.RouteID, StringComparison.OrdinalIgnoreCase))
                {
                    //Activity and route have different RouteID.
                    result = new Activity($"<{catalog.GetString("Not same route:")} {System.IO.Path.GetFileNameWithoutExtension(filePath)}>", filePath, null, null, null);
                }
                else
                {
                    result = new Activity(string.Empty, filePath, activityFile, consist, path);
                }
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch
#pragma warning restore CA1031 // Do not catch general exception types
            {
                result = new Activity($"<{catalog.GetString("load error:")} {System.IO.Path.GetFileNameWithoutExtension(filePath)}>", filePath, null, null, null);
            }
            return(result);
        }
예제 #3
0
 protected Activity(string filePath, Folder folder, Route route)
 {
     if (filePath == null)
     {
         Name = catalog.GetString("- Explore Route -");
     }
     else if (File.Exists(filePath))
     {
         var showInList = true;
         try
         {
             var actFile = new ActivityFile(filePath);
             var srvFile = new ServiceFile(System.IO.Path.Combine(System.IO.Path.Combine(route.Path, "SERVICES"), actFile.Tr_Activity.Tr_Activity_File.Player_Service_Definition.Name + ".srv"));
             // ITR activities are excluded.
             showInList  = actFile.Tr_Activity.Tr_Activity_Header.Mode != ActivityMode.IntroductoryTrainRide;
             Name        = actFile.Tr_Activity.Tr_Activity_Header.Name.Trim();
             Description = actFile.Tr_Activity.Tr_Activity_Header.Description;
             Briefing    = actFile.Tr_Activity.Tr_Activity_Header.Briefing;
             StartTime   = actFile.Tr_Activity.Tr_Activity_Header.StartTime;
             Season      = actFile.Tr_Activity.Tr_Activity_Header.Season;
             Weather     = actFile.Tr_Activity.Tr_Activity_Header.Weather;
             Difficulty  = actFile.Tr_Activity.Tr_Activity_Header.Difficulty;
             Duration    = actFile.Tr_Activity.Tr_Activity_Header.Duration;
             Consist     = new Consist(System.IO.Path.Combine(System.IO.Path.Combine(System.IO.Path.Combine(folder.Path, "TRAINS"), "CONSISTS"), srvFile.Train_Config + ".con"), folder);
             Path        = new Path(System.IO.Path.Combine(System.IO.Path.Combine(route.Path, "PATHS"), srvFile.PathID + ".pat"));
             if (!Path.IsPlayerPath)
             {
                 // Not nice to throw an error now. Error was originally thrown by new Path(...);
                 throw new InvalidDataException("Not a player path");
             }
         }
         catch
         {
             Name = "<" + catalog.GetString("load error:") + " " + System.IO.Path.GetFileNameWithoutExtension(filePath) + ">";
         }
         if (!showInList)
         {
             throw new InvalidDataException(catalog.GetStringFmt("Activity '{0}' is excluded.", filePath));
         }
         if (string.IsNullOrEmpty(Name))
         {
             Name = "<" + catalog.GetString("unnamed:") + " " + System.IO.Path.GetFileNameWithoutExtension(filePath) + ">";
         }
         if (string.IsNullOrEmpty(Description))
         {
             Description = null;
         }
         if (string.IsNullOrEmpty(Briefing))
         {
             Briefing = null;
         }
     }
     else
     {
         Name = "<" + catalog.GetString("missing:") + " " + System.IO.Path.GetFileNameWithoutExtension(filePath) + ">";
     }
     FilePath = filePath;
 }
예제 #4
0
        /// <summary>
        /// Remove ActivityFile.
        /// </summary>
        /// <param name="request">The ActivityFile Request Pivot to remove.</param>
        public void DeleteActivityFile(ActivityFileRequestPivot request)
        {
            if (request?.ActivityFilePivot == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            ActivityFile activityFile = _unitOfWork.ActivityFileRepository.GetById(request.ActivityFilePivot.ActivityFileId);

            _unitOfWork.ActivityFileRepository.Delete(activityFile);
            _unitOfWork.Save();
        }
예제 #5
0
 /// <summary>
 /// From ActivityFile To ActivityFile Pivot.
 /// </summary>
 /// <param name="activityFile">activityFile TO ASSEMBLE</param>
 /// <returns>ActivityFilePivot result.</returns>
 public static ActivityFilePivot ToPivot(this ActivityFile activityFile)
 {
     if (activityFile == null)
     {
         return(null);
     }
     return(new ActivityFilePivot
     {
         ActivityFileId = activityFile.ActivityFileId,
         Activity = activityFile.Activity.ToPivot(),
         ActivityId = activityFile.ActivityId
     });
 }
예제 #6
0
 public ActivityFileDTO Map(ActivityFile entity)
 {
     return(new ActivityFileDTO
     {
         Id = entity.Id,
         ActivityId = entity.ActivityId,
         PathUrl = entity.PathUrl,
         FileSize = entity.FileSize,
         FileName = entity.FileName,
         MimeType = entity.MimeType,
         Content = entity.Content,
         CreatedOn = entity.CreatedOn
     });
 }
예제 #7
0
        internal static Activity FromPathShallow(string filePath)
        {
            try
            {
                ActivityFile activityFile = new ActivityFile(filePath);

                return(new Activity(string.Empty, filePath, activityFile, null, null));
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch
#pragma warning restore CA1031 // Do not catch general exception types
            {
                return(null);
            }
        }
예제 #8
0
        /// <summary>
        /// Create new ActivityFile.
        /// </summary>
        /// <param name="request">The ActivityFile Request Pivot to add.</param>
        /// <returns>ActivityFile Response Pivot created.</returns>
        public ActivityFileResponsePivot CreateActivityFile(ActivityFileRequestPivot request)
        {
            if (request?.ActivityFilePivot == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            ActivityFile activityFile = request.ActivityFilePivot.ToEntity();

            _unitOfWork.ActivityFileRepository.Insert(activityFile);
            _unitOfWork.Save();
            return(new ActivityFileResponsePivot
            {
                ActivityFilePivot = activityFile.ToPivot()
            });
        }
예제 #9
0
 protected Activity(string name, string filePath, ActivityFile activityFile, Consist consist, Path path)
 {
     if (filePath == null && this is DefaultExploreActivity)
     {
         Name = catalog.GetString("- Explore Route -");
     }
     else if (filePath == null && this is ExploreThroughActivity)
     {
         Name = catalog.GetString("+ Explore in Activity Mode +");
     }
     else if (null != activityFile)
     {
         // ITR activities are excluded.
         Name = activityFile.Activity.Header.Name;
         if (activityFile.Activity.Header.Mode == ActivityMode.Introductory)
         {
             Name = "Introductory Train Ride";
         }
         Description = activityFile.Activity.Header.Description;
         Briefing    = activityFile.Activity.Header.Briefing;
         StartTime   = activityFile.Activity.Header.StartTime;
         Season      = activityFile.Activity.Header.Season;
         Weather     = activityFile.Activity.Header.Weather;
         Difficulty  = activityFile.Activity.Header.Difficulty;
         Duration    = activityFile.Activity.Header.Duration;
         Consist     = consist;
         Path        = path;
     }
     else
     {
         Name = name;
     }
     if (string.IsNullOrEmpty(Name))
     {
         Name = $"<{catalog.GetString("unnamed:")} {System.IO.Path.GetFileNameWithoutExtension(filePath)}>";
     }
     if (string.IsNullOrEmpty(Description))
     {
         Description = null;
     }
     if (string.IsNullOrEmpty(Briefing))
     {
         Briefing = null;
     }
     FilePath = filePath;
 }
예제 #10
0
        public Activity(Content content)
        {
            Debug.Assert(content.Type == ContentType.Activity);
            if (System.IO.Path.GetExtension(content.PathName).Equals(".act", StringComparison.OrdinalIgnoreCase))
            {
                var file = new ActivityFile(content.PathName);
                Name           = file.Tr_Activity.Tr_Activity_Header.Name;
                Description    = file.Tr_Activity.Tr_Activity_Header.Description;
                Briefing       = file.Tr_Activity.Tr_Activity_Header.Briefing;
                PlayerServices = new[] { String.Format("Player|{0}", file.Tr_Activity.Tr_Activity_File.Player_Service_Definition.Name) };
                if (file.Tr_Activity.Tr_Activity_File.Traffic_Definition != null)
                {
                    Services = file.Tr_Activity.Tr_Activity_File.Traffic_Definition.ServiceDefinitionList.Select((service, index) =>
                                                                                                                 String.Format("AI|{0}|{1}|{2}", service.Name, file.Tr_Activity.Tr_Activity_File.Traffic_Definition.Name, index)
                                                                                                                 );
                }
                else
                {
                    Services = new string[0];
                }
            }
            else if (System.IO.Path.GetExtension(content.PathName).Equals(".timetable_or", StringComparison.OrdinalIgnoreCase) ||
                     System.IO.Path.GetExtension(content.PathName).Equals(".timetable-or", StringComparison.OrdinalIgnoreCase))
            {
                // TODO: Make common timetable parser.
                var file = new TimetableReader(content.PathName);
                Name = content.Name;

                var services = new List <string>();
                for (var column = 0; column < file.Strings[0].Length; column++)
                {
                    if (String.IsNullOrEmpty(file.Strings[0][column]) || file.Strings[0][column].StartsWith("#"))
                    {
                        continue;
                    }

                    services.Add(file.Strings[0][column]);
                }
                PlayerServices = services;
                Services       = new string[0];
            }
        }
예제 #11
0
        public Activity(Content content)
        {
            Debug.Assert(content.Type == ContentType.Activity);
            if (System.IO.Path.GetExtension(content.PathName).Equals(".act", StringComparison.OrdinalIgnoreCase))
            {
                var file = new ActivityFile(content.PathName);
                Name           = file.Activity.Header.Name;
                Description    = file.Activity.Header.Description;
                Briefing       = file.Activity.Header.Briefing;
                PlayerServices = new[] { $"Player|{file.Activity.PlayerServices.Name}" };
                if (file.Activity.Traffic != null)
                {
                    Services = file.Activity.Traffic.Services.Select((service, index) =>
                                                                     $"AI|{service.Name}|{file.Activity.Traffic.Name}|{index}"
                                                                     );
                }
                else
                {
                    Services = Array.Empty <string>();
                }
            }
            else if (System.IO.Path.GetExtension(content.PathName).Equals(".timetable_or", StringComparison.OrdinalIgnoreCase))
            {
                // TODO: Make common timetable parser.
                var file = new TimetableReader(content.PathName);
                Name = content.Name;

                var services = new List <string>();
                for (var column = 0; column < file.Strings[0].Length; column++)
                {
                    if (String.IsNullOrEmpty(file.Strings[0][column]) || file.Strings[0][column].StartsWith("#"))
                    {
                        continue;
                    }

                    services.Add(file.Strings[0][column]);
                }
                PlayerServices = services;
                Services       = Array.Empty <string>();
            }
        }
예제 #12
0
파일: Activities.cs 프로젝트: Reve/ORTS-MG
        internal static async Task <Activity> FromPathAsync(string filePath, Folder folder, Route route, CancellationToken token)
        {
            return(await Task.Run(async() =>
            {
                Activity result;

                try
                {
                    ActivityFile activityFile = new ActivityFile(filePath);
                    ServiceFile srvFile = new ServiceFile(route.RouteFolder.ServiceFile(activityFile.Activity.PlayerServices.Name));
                    var constistTask = Consist.GetConsist(folder, srvFile.TrainConfig, false, token);
                    var pathTask = Path.FromFileAsync(route.RouteFolder.PathFile(srvFile.PathId), token);
                    await Task.WhenAll(constistTask, pathTask).ConfigureAwait(false);
                    Consist consist = await constistTask;
                    Path path = await pathTask;
                    if (!path.IsPlayerPath)
                    {
                        return null;

                        // Not nice to throw an error now. Error was originally thrown by new Path(...);
                        throw new InvalidDataException("Not a player path");
                    }
                    else if (!activityFile.Activity.Header.RouteID.Equals(route.RouteID, StringComparison.OrdinalIgnoreCase))
                    {
                        //Activity and route have different RouteID.
                        result = new Activity($"<{catalog.GetString("Not same route:")} {System.IO.Path.GetFileNameWithoutExtension(filePath)}>", filePath, null, null, null);
                    }
                    else
                    {
                        result = new Activity(string.Empty, filePath, activityFile, consist, path);
                    }
                }
                catch
                {
                    result = new Activity($"<{catalog.GetString("load error:")} {System.IO.Path.GetFileNameWithoutExtension(filePath)}>", filePath, null, null, null);
                }
                return result;
            }, token).ConfigureAwait(false));
        }
예제 #13
0
        public Service(Content content)
        {
            Debug.Assert(content.Type == ContentType.Service);
            if (System.IO.Path.GetExtension(content.PathName).Equals(".srv", StringComparison.OrdinalIgnoreCase))
            {
                var file = new ServiceFile(content.PathName);
                Name    = file.Name;
                Consist = file.Train_Config;
                Path    = file.PathID;

                Debug.Assert(content is ContentMSTSService);
                var msts    = content as ContentMSTSService;
                var actFile = new ActivityFile(content.Parent.PathName);
                if (msts.IsPlayer)
                {
                    var activityTraffic = actFile.Tr_Activity.Tr_Activity_File.Player_Service_Definition.Player_Traffic_Definition;

                    ID        = "0";
                    StartTime = MSTSTimeToDateTime(activityTraffic.Time);
                    Stops     = from stop in activityTraffic.Player_Traffic_List
                                select new Stop(stop.PlatformStartID, stop.DistanceDownPath, MSTSTimeToDateTime(stop.ArrivalTime), MSTSTimeToDateTime(stop.DepartTime));
                }
                else
                {
                    var trfFile         = new TrafficFile(msts.TrafficPathName);
                    var activityService = actFile.Tr_Activity.Tr_Activity_File.Traffic_Definition.ServiceDefinitionList[msts.TrafficIndex];
                    var trafficService  = trfFile.TrafficDefinition.TrafficItems[msts.TrafficIndex];

                    ID        = activityService.UiD.ToString();
                    StartTime = MSTSTimeToDateTime(activityService.Time);
                    Stops     = trafficService.TrafficDetails.Zip(activityService.ServiceList, (tt, stop) => new Stop(stop.PlatformStartID, stop.DistanceDownPath, MSTSTimeToDateTime(tt.ArrivalTime), MSTSTimeToDateTime(tt.DepartTime)));
                }
            }
            else if (System.IO.Path.GetExtension(content.PathName).Equals(".timetable_or", StringComparison.OrdinalIgnoreCase))
            {
                // TODO: Make common timetable parser.
                var file = new TimetableReader(content.PathName);
                Name = content.Name;

                var serviceColumn = -1;
                var consistRow    = -1;
                var pathRow       = -1;
                var startRow      = -1;
                for (var row = 0; row < file.Strings.Count; row++)
                {
                    if (file.Strings[row][0] == "#consist" && consistRow == -1)
                    {
                        consistRow = row;
                    }
                    else if (file.Strings[row][0] == "#path" && pathRow == -1)
                    {
                        pathRow = row;
                    }
                    else if (file.Strings[row][0] == "#start" && startRow == -1)
                    {
                        startRow = row;
                    }
                }
                for (var column = 0; column < file.Strings[0].Length; column++)
                {
                    if (file.Strings[0][column] == content.Name && serviceColumn == -1)
                    {
                        serviceColumn = column;
                    }
                }
                ID = serviceColumn.ToString();
                var timeRE         = new Regex(@"^(\d\d):(\d\d)(?:-(\d\d):(\d\d))?");
                var startTimeMatch = timeRE.Match(file.Strings[startRow][serviceColumn]);
                if (startTimeMatch.Success)
                {
                    StartTime = new DateTime(2000, 1, 1, int.Parse(startTimeMatch.Groups[1].Value), int.Parse(startTimeMatch.Groups[2].Value), 0);
                }
                var stops = new List <Stop>();
                for (var row = 0; row < file.Strings.Count; row++)
                {
                    if (row != startRow)
                    {
                        var timeMatch = timeRE.Match(file.Strings[row][serviceColumn]);
                        if (timeMatch.Success)
                        {
                            var arrivalTime   = new DateTime(2000, 1, 1, int.Parse(timeMatch.Groups[1].Value), int.Parse(timeMatch.Groups[2].Value), 0);
                            var departureTime = timeMatch.Groups[3].Success ? new DateTime(2000, 1, 1, int.Parse(timeMatch.Groups[3].Value), int.Parse(timeMatch.Groups[4].Value), 0) : arrivalTime;
                            // If the time is prior to this train's start time, assume it is rolling over in to "tomorrow".
                            if (arrivalTime < StartTime)
                            {
                                arrivalTime   = arrivalTime.AddDays(1);
                                departureTime = departureTime.AddDays(1);
                            }
                            stops.Add(new Stop(file.Strings[row][0].Replace(" $hold", "").Replace(" $forcehold", ""), arrivalTime, departureTime));
                        }
                    }
                }
                Stops    = stops.OrderBy(s => s.ArrivalTime);
                Consist  = file.Strings[consistRow][serviceColumn].Replace(" $reverse", "");
                Reversed = file.Strings[consistRow][serviceColumn].Contains(" $reverse");
                Path     = file.Strings[pathRow][serviceColumn];
            }
        }
예제 #14
0
        public Activity(ActivityFile activityFile, Simulator simulator)
        {
            if (null == activityFile)
            {
                throw new ArgumentNullException(nameof(activityFile));
            }

            this.simulator = simulator;  // Save for future use.
            PlayerServices sd;

            sd = activityFile.Activity.PlayerServices;
            if (sd != null)
            {
                if (sd.PlayerTraffics.Count > 0)
                {
                    ActivityTask task = null;

                    foreach (ServiceTrafficItem i in sd.PlayerTraffics)
                    {
                        PlatformItem Platform;
                        if (i.PlatformStartID < this.simulator.TrackDatabase.TrackDB.TrackItems.Length && i.PlatformStartID >= 0 &&
                            this.simulator.TrackDatabase.TrackDB.TrackItems[i.PlatformStartID] is PlatformItem)
                        {
                            Platform = this.simulator.TrackDatabase.TrackDB.TrackItems[i.PlatformStartID] as PlatformItem;
                        }
                        else
                        {
                            Trace.TraceWarning("PlatformStartID {0} is not present in TDB file", i.PlatformStartID);
                            continue;
                        }
                        if (Platform != null)
                        {
                            if (this.simulator.TrackDatabase.TrackDB.TrackItems[Platform.LinkedPlatformItemId] is PlatformItem)
                            {
                                PlatformItem Platform2 = this.simulator.TrackDatabase.TrackDB.TrackItems[Platform.LinkedPlatformItemId] as PlatformItem;
                                Tasks.Add(task = new ActivityTaskPassengerStopAt(simulator, task, i.ArrivalTime, i.DepartTime, Platform, Platform2));
                            }
                        }
                    }
                    ActivityTask = Tasks[0];
                }
            }

            // Compile list of freight events, if any, from the parsed ACT file.
            foreach (ActivityEvent activityEvent in activityFile.Activity?.Events ?? Enumerable.Empty <ActivityEvent>())
            {
                if (activityEvent is ActionActivityEvent)
                {
                    EventList.Add(new EventCategoryActionWrapper(activityEvent));
                }
                if (activityEvent is LocationActivityEvent)
                {
                    EventList.Add(new EventCategoryLocationWrapper(activityEvent));
                }
                if (activityEvent is TimeActivityEvent)
                {
                    EventList.Add(new EventCategoryTimeWrapper(activityEvent));
                }
                EventWrapper eventAdded = EventList.Last();
                eventAdded.OriginalActivationLevel = activityEvent.ActivationLevel;
                if (activityEvent.WeatherChange != null || activityEvent.Outcomes.WeatherChange != null)
                {
                    WeatherChangesPresent = true;
                }
            }

            stationStopLogActive = false;
            stationStopLogFile   = null;
        }
예제 #15
0
 /// <summary>
 /// Try to load the file.
 /// Possibly this might raise an exception. That exception is not caught here
 /// </summary>
 /// <param name="file">The file that needs to be loaded</param>
 public override void TryLoading(string file)
 {
     _ = new ActivityFile(file);
 }
예제 #16
0
        internal static Activity FromPathShallow(string filePath)
        {
            ActivityFile activityFile = new ActivityFile(filePath);

            return(new Activity(string.Empty, filePath, activityFile, null, null));
        }