Ejemplo n.º 1
0
        public static DateTime GetAverageDate(HistoricalEvent he)
        {
            DateTime dt1 = new DateTime(he.Events_Year_from, he.Events_Month_from, he.Events_Day_from, he.Events_H_from, he.Events_M_from, 0);
            DateTime dt2 = new DateTime(he.Events_Year_to, he.Events_Month_to, he.Events_Day_to, he.Events_H_to, he.Events_M_to, 0);

            return(GetAverageDate(dt1, dt2));
        }
Ejemplo n.º 2
0
        public void HistoricalEvent_ChangeHFStateXML_Parses()
        {
            var world = LoadingWorld.GetTestWorld();
            var xdoc  = new XDocument(new XElement("historical_event",
                                                   new XElement("id", 0),
                                                   new XElement("year", 1),
                                                   new XElement("seconds72", -1),
                                                   new XElement("type", "change hf state"),
                                                   new XElement("hfid", 264),
                                                   new XElement("state", "settled"),
                                                   new XElement("site_id", -1),
                                                   new XElement("subregion_id", 4),
                                                   new XElement("feature_layer_id", -1),
                                                   new XElement("coords", "20,16")
                                                   )
                                      );


            var historicalevent = HistoricalEvent.Create(xdoc, world);

            Assert.AreEqual(historicalevent.Id, 0);
            Assert.AreEqual(historicalevent.Year, 1);
            Assert.AreEqual(HistoricalEvent.Types[historicalevent.Type], "change hf state");
            Assert.IsInstanceOfType(historicalevent, typeof(HE_ChangeHFState));
            var changehfstateEvent = historicalevent as HE_ChangeHFState;

            Assert.AreEqual(changehfstateEvent.HfId, 264);
            Assert.AreEqual(HE_ChangeHFState.States[changehfstateEvent.State.Value], "settled");
            Assert.IsNull(changehfstateEvent.SiteId);
            Assert.AreEqual(changehfstateEvent.SubregionId.Value, 4);
            Assert.IsNull(changehfstateEvent.FeatureLayerId);
            Assert.AreEqual(changehfstateEvent.Coords, new Point(20, 16));
        }
Ejemplo n.º 3
0
        private static TEvent MaterializeEvent <TEvent>(HistoricalEvent historicalEvent) where TEvent : EventBase
        {
            var type   = Type.GetType(historicalEvent.EventType, true);
            var @event = (TEvent)JsonConvert.DeserializeObject(historicalEvent.ContentJson, type, GlobalSettings.EventSerializerSettings);

            @event.Id           = historicalEvent.Id;
            @event.TimestampUtc = historicalEvent.TimestampUtc;

            return(@event);
        }
        public void GenerateEvent(int year, HistoricalEvent.EventType type, List <HistoricalFigure> relatedFigs, string desc)
        {
            HistoricalEvent histEvent = new HistoricalEvent();

            histEvent.year           = year;
            histEvent.type           = type;
            histEvent.relatedFigures = relatedFigs;
            histEvent.description    = desc;

            importantEvents.Add(histEvent);
        }
Ejemplo n.º 5
0
 public HistoricalEvent GetPreviousEvent(HistoricalEvent referenceEvt)
 {
     for (int i = 1; i < Event.Count; i++)
     {
         if (Event[i] == referenceEvt)
         {
             return(Event[i - 1]);
         }
     }
     return(null);
 }
Ejemplo n.º 6
0
 public HistoricalEvent GetNextEvent(HistoricalEvent referenceEvt)
 {
     for (int i = 0; i < Event.Count - 1; i++)
     {
         if (Event[i] == referenceEvt)
         {
             return(Event[i + 1]);
         }
     }
     return(null);
 }
Ejemplo n.º 7
0
        public String GetEventType(HistoricalEvent hevent)
        {
            String st = String.Empty;

            if (hevent.EventKeywords != null && hevent.EventKeywords.Length > 0)
            {
                foreach (KeyWord kw in hevent.EventKeywords)
                {
                    st = String.Format("{0},{1}", st, kw.KeyWordDescription);
                }
                st = st.Substring(1, st.Length - 1);
            }
            return(st);
        }
        public virtual async Task MarkOneAsRead(T1 id)
        {
            var entity = await _repository.GetByIdAsync <T1, T2>(id);

            var historicalEvent = new HistoricalEvent
            {
                Action     = HistoricalActions.Read.ToString(),
                EntityId   = entity.Id.ToString(),
                EntityName = entity.GetType().FullName
            };

            await _repository.CreateAsync <Guid, HistoricalEvent>(historicalEvent);

            await _repository.SaveChangesAsync();
        }
Ejemplo n.º 9
0
        public void HistoricalEvent_NewTypeXML_Parses()
        {
            var world = LoadingWorld.GetTestWorld();
            var xdoc  = new XDocument(new XElement("historical_event",
                                                   new XElement("id", 0),
                                                   new XElement("year", 1),
                                                   new XElement("seconds72", -1),
                                                   new XElement("type", "unknown event type")
                                                   )
                                      );

            var historicalevent = HistoricalEvent.Create(xdoc, world);

            Assert.AreEqual(historicalevent.Id, 0);
            Assert.AreEqual(historicalevent.Year, 1);
            Assert.IsInstanceOfType(historicalevent, typeof(HE_UnassessedEvent));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Updates the specified identifier.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        public new virtual T Update(Guid id, T entity)
        {
            var originalEntity  = base.GetById(id);
            var historicalEvent = new HistoricalEvent
            {
                Action     = HistoricalActions.Update.ToString(),
                Changeset  = originalEntity.DetailedCompare(entity),
                EntityId   = originalEntity.Id,
                EntityName = entity.GetType().Name
            };
            var modifiedEntity = base.Update(id, entity);

            _repository.Create(historicalEvent);
            _repository.SaveChanges();

            return(modifiedEntity);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Creates the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        public new virtual T Create(T entity)
        {
            var createdEntity = base.Create(entity);

            var historicalEvent = new HistoricalEvent
            {
                Action     = HistoricalActions.Create.ToString(),
                Changeset  = new T().DetailedCompare(entity),
                EntityId   = entity.Id,
                EntityName = entity.GetType().Name
            };

            _repository.Create(historicalEvent);
            _repository.SaveChanges();
            // TODO: Do I need to call the other repo for both repositories, or do I need a UoW (bugfix created)
            return(createdEntity);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Deletes the asynchronous.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns></returns>
        public new virtual async Task <T> DeleteAsync(Guid id)
        {
            var entity = await base.DeleteAsync(id);

            // store all object in historical event
            var historicalEvent = new HistoricalEvent
            {
                Action     = HistoricalActions.Delete.ToString(),
                Changeset  = new T().DetailedCompare(entity),
                EntityId   = entity.Id,
                EntityName = entity.GetType().Name
            };
            await _repository.CreateAsync(historicalEvent);

            _repository.SaveChanges();

            return(entity);
        }
        public virtual async Task MarkAllAsRead()
        {
            // TODO: Check if the userinfo repository is available, if not, throw exception
            var entities = await _repository.GetAllAsync <T1, T2>();

            foreach (var entity in entities)
            {
                var historicalEvent = new HistoricalEvent
                {
                    Action     = HistoricalActions.Read.ToString(),
                    EntityId   = entity.Id.ToString(),
                    EntityName = entity.GetType().FullName
                };

                await _repository.CreateAsync <Guid, HistoricalEvent>(historicalEvent);
            }

            await _repository.SaveChangesAsync();
        }
        private bool IsNewStuffAvailable(T2 entity, HistoricalEvent historicalEvent)
        {
            if (!(entity is ICreatedInfo && entity is IModifiedInfo))
            {
                throw new NotSupportedException("Entity must implement ICreatedInfo and IModifiedInfo");
            }
            var modifiedInfo = entity as IModifiedInfo;
            var createdInfo  = entity as ICreatedInfo;

            var createdByMe           = modifiedInfo.ModifiedBy == null && createdInfo.CreatedBy == _userInfoRepository.GetUserInfo();
            var modifiedByMe          = modifiedInfo.ModifiedBy != null && modifiedInfo.ModifiedBy == _userInfoRepository.GetUserInfo();
            var createdOrModifiedByMe = createdByMe || modifiedByMe;

            var createdBySomeone           = modifiedInfo.ModifiedBy == null && createdInfo.CreatedBy != _userInfoRepository.GetUserInfo();
            var modifiedBySomeone          = modifiedInfo.ModifiedBy != null && modifiedInfo.ModifiedBy != _userInfoRepository.GetUserInfo();
            var createdOrModifiedBySomeone = createdBySomeone || modifiedBySomeone;

            var viewedLately = modifiedInfo.ModifiedDate == null && historicalEvent?.CreatedDate > createdInfo.CreatedDate || modifiedInfo.ModifiedDate != null && historicalEvent?.CreatedDate > modifiedInfo.ModifiedDate;

            if (!viewedLately)
            {
                if (_options.ShowMyNewStuff && createdOrModifiedByMe)
                {
                    return(true);
                }
                else if (_options.ShowMyNewStuff && createdOrModifiedBySomeone)
                {
                    return(true);
                }
                else if (!_options.ShowMyNewStuff && createdOrModifiedBySomeone)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
        /// <summary>
        /// Deletes the asynchronous.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns></returns>
        public virtual async Task <T2> DeleteAsync(T1 id)
        {
            var entity = await _service.DeleteAsync(id);

            // store all object in historical event
            var historicalEvent = new HistoricalEvent
            {
                Action    = HistoricalActions.Delete.ToString(),
                Changeset = new HistoricalChangeset()
                {
                    ObjectData = new T2().DetailedCompare(entity)
                },
                EntityId   = entity.Id.ToString(),
                EntityName = entity.GetType().FullName
            };
            await _repository.CreateAsync <Guid, HistoricalEvent>(historicalEvent);

            await _repository.SaveChangesAsync();

            return(entity);
        }
        public Changeset ExtractOneDifferentialChangeset <T2>(HistoricalEvent currentEvent, HistoricalEvent nextEvent) where T2 : class, IEntity <T1>, new()
        {
            var currentObject = JsonConvert.DeserializeObject <T2>(currentEvent.Changeset.ObjectDelta);
            var nextObject    =
                nextEvent.Action == HistoricalActions.Delete.ToString()
                    ? JsonConvert.DeserializeObject <T2>(nextEvent.Changeset?.ObjectData)
                    : JsonConvert.DeserializeObject <T2>(nextEvent.Changeset?.ObjectDelta);

            var changeset = new Changeset();

            changeset.EventDate   = nextEvent.CreatedDate.Value;
            changeset.UserId      = nextEvent.CreatedBy;
            changeset.ChangesetId = nextEvent.Changeset.Id;
            changeset.EventName   = nextEvent.Action;
            changeset.Changes     =
                currentEvent.Action != HistoricalActions.Delete.ToString() ?
                ExtractChanges(currentObject, nextObject) :
                null;

            return(changeset);
        }
        /// <summary>
        /// Creates the asynchronous.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        public virtual async Task <T2> CreateAsync(T2 entity)
        {
            var createdEntity = await _service.CreateAsync(entity);

            var historicalEvent = new HistoricalEvent
            {
                Action    = HistoricalActions.Create.ToString(),
                Changeset = new HistoricalChangeset()
                {
                    ObjectDelta = new T2().DetailedCompare(entity)
                },
                EntityId   = entity.Id.ToString(),
                EntityName = entity.GetType().FullName
            };

            await _repository.CreateAsync <Guid, HistoricalEvent>(historicalEvent);

            await _repository.SaveChangesAsync();

            return(createdEntity);
        }
Ejemplo n.º 18
0
        public void Save(EventBase @event)
        {
            if (@event == null)
            {
                throw new ArgumentNullException(nameof(@event));
            }

            var json            = JsonConvert.SerializeObject(@event, GlobalSettings.EventSerializerSettings);
            var historicalEvent = new HistoricalEvent()
            {
                Id           = @event.Id,
                TimestampUtc = @event.TimestampUtc,
                EventType    = @event.GetType().AssemblyQualifiedName,
                ContentJson  = json,
            };

            lock (_sync)
            {
                _dbContext.HistoricalEvents.Add(historicalEvent);
                _dbContext.SaveChanges();
            }
        }
        /// <summary>
        /// Updates the asynchronous.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        public virtual async Task <T2> UpdateAsync(T1 id, T2 entity)
        {
            var originalEntity = await _service.GetByIdAsync(id);

            var historicalEvent = new HistoricalEvent
            {
                Action    = HistoricalActions.Update.ToString(),
                Changeset = new HistoricalChangeset()
                {
                    ObjectData  = JsonConvert.SerializeObject(originalEntity),
                    ObjectDelta = originalEntity.DetailedCompare(entity)
                },
                EntityId   = originalEntity.Id.ToString(),
                EntityName = entity.GetType().FullName
            };
            var modifiedEntity = await _service.UpdateAsync(id, entity);

            await _repository.CreateAsync <Guid, HistoricalEvent>(historicalEvent);

            await _repository.SaveChangesAsync();

            return(modifiedEntity);
        }
Ejemplo n.º 20
0
        private Changeset ExtractOneDifferentialChangeset <TEntity>(HistoricalEvent currentEvent, HistoricalEvent nextEvent) where TEntity : class, IEntity <TId>, new()
        {
            var currentObject = JsonConvert.DeserializeObject <TEntity>(currentEvent.Changeset.ObjectDelta);
            var currentDto    = _mapper.Map <TDto>(currentObject);

            var nextObject =
                nextEvent.Action == HistoricalActions.Delete.ToString()
                    ? JsonConvert.DeserializeObject <TEntity>(nextEvent.Changeset?.ObjectData)
                    : JsonConvert.DeserializeObject <TEntity>(nextEvent.Changeset?.ObjectDelta);
            var nextDto = _mapper.Map <TDto>(currentObject);

            var changeset = new Changeset();

            changeset.EventDate   = nextEvent.CreatedDate.Value;
            changeset.UserId      = nextEvent.CreatedBy;
            changeset.ChangesetId = nextEvent.Changeset.Id;
            changeset.EventName   = nextEvent.Action;
            changeset.Changes     =
                currentEvent.Action != HistoricalActions.Delete.ToString() ?
                _historicalCrudReadService.ExtractChanges(currentDto, nextDto) :
                null;

            return(changeset);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Now at the open tag of a single object in our XML, we want to dump the entire contents into an XDocument.
        ///   If we have a historical event or historical event collection we want to use their factory methods to create a new version of those with the given XDocument.
        ///   For all other object types we want to use their constructor to make a new object of that type.
        ///   In any case we add the object after making it to the appropriate dictionary.
        /// Individual object reads are separated out to allow us to work past failing to load any specific XML item for some weird reason.
        /// </summary>
        private static void LoadItem <T>(IDictionary <int, T> WorldList, World world, XmlReader xReader) where T : XMLObject
        {
            XDocument xdoc = null;

            try
            {
                xdoc = XDocument.Load(xReader.ReadSubtree());

                if (typeof(T) == typeof(HistoricalEvent))
                {
                    var evt = HistoricalEvent.Create(xdoc, world);
                    world.HistoricalEvents.Add(evt.ID, evt);
                }
                else if (typeof(T) == typeof(HistoricalEventCollection))
                {
                    var evtcol = HistoricalEventCollection.Create(xdoc, world);
                    world.HistoricalEventCollections.Add(evtcol.ID, evtcol);
                }
                else
                {
                    var WorldObject = (T)Activator.CreateInstance(typeof(T), new object[] { xdoc, world });
                    WorldList.Add(WorldObject.ID, WorldObject);
                }
            }
            catch (OutOfMemoryException e)
            {
                Program.Log(LogType.Error, "Error reading XML item: id\n" + e.Message);


                var fi = new FileInfo(_path);
                Program.Log(LogType.Error, "XML file is" + Math.Round(fi.Length / 1024f / 1024f / 1024f, 2) + " GB");

                Program.Log(LogType.Error, string.Format("Running {0} Bit World Viewer", (Environment.Is64BitProcess ? "64" : "32")));
                Program.Log(LogType.Error, string.Format("Running {0} Bit Operating System", (Environment.Is64BitOperatingSystem ? "64" : "32")));

                if (!Environment.Is64BitOperatingSystem) //Running 32 bit OS
                {
                    Program.Log(LogType.Error, "32 Bit World Viewer does not support Huge XML files");
                }
                else if (!Environment.Is64BitProcess) //Running 32 bit app in 64 bit OS
                {
                    Program.Log(LogType.Error, "Recommend using 64 Bit World Viewer");
                }
                else
                {
                    Program.Log(LogType.Error, "Please report Log");
                }


                MemoryFailureQuitParsing = true;
            }
            catch (Exception e)
            {
                try
                {
                    if (xdoc != null)
                    {
                        int id = Int32.Parse(((XElement)xdoc.Root.Nodes().ToArray()[1]).Value);

                        if (id < 0)
                        {
                            if (xdoc.Root.Name.LocalName == "historical_event")
                            {
                                if (!workflowDetected)
                                {
                                    Program.Log(LogType.Error,
                                                "Negative ID historical event.  Likely due to dfHack Workflow, ignoring\n" + xdoc);
                                    workflowDetected = true;
                                }
                            }
                            else if (xdoc.Root.Name.LocalName == "historical_figure")
                            {
                                if (!autochopDetected)
                                {
                                    Program.Log(LogType.Error,
                                                "Negative ID historical figure detected. Likely due to autochop, ignoring\n" + xdoc);
                                    autochopDetected = true;
                                }
                            }
                            else
                            {
                                Program.Log(LogType.Error,
                                            "Negative ID " + xdoc.Root.Name.LocalName + " detected. Unknown cause, ignoring\n" + xdoc);
                            }
                        }
                        else
                        {
                            Program.Log(LogType.Error, "Error reading XML item: id\n" + e.Message);
                        }
                    }
                }
                catch (Exception)
                {
                    Program.Log(LogType.Error, "Error reading XML item: id\n" + e.Message);
                    throw;
                }
            }
        }
Ejemplo n.º 22
0
        private List <Changeset> ExtractDifferentialChanges(TId id, IOrderedEnumerable <HistoricalEvent> events, HistoricalEvent sourceEvent, TEntity sourceObject)
        {
            var differentialChangeset = new List <Changeset>();

            var currentEvent  = sourceEvent;
            var currentObject = sourceObject;
            var currentDto    = _mapper.Map <TDto>(currentObject);

            for (int i = 1; i < events.Count(); i++)
            {
                var nextEvent       = events.ToArray()[i];
                var nextEventObject = JsonConvert.DeserializeObject <TEntity>(currentEvent.Changeset.ObjectDelta);
                var nextEventDto    = _mapper.Map <TDto>(nextEventObject);
                var changeset       = new Changeset();
                changeset.EventDate   = currentEvent.CreatedDate.Value;
                changeset.UserId      = currentEvent.CreatedBy;
                changeset.ChangesetId = currentEvent.Changeset.Id;
                changeset.EventName   = currentEvent.Action;
                changeset.Changes     = _historicalCrudReadService.ExtractChanges(currentDto, nextEventDto);
                differentialChangeset.Add(changeset);

                currentObject = nextEventObject;
                currentDto    = _mapper.Map <TDto>(currentObject);
                currentEvent  = nextEvent;
            }
            // add last event to current object
            var lastChangeset = new Changeset();
            var lastEvent     = events.Last();

            lastChangeset.EventDate   = lastEvent.CreatedDate.Value;
            lastChangeset.UserId      = lastEvent.CreatedBy;
            lastChangeset.ChangesetId = lastEvent.Changeset.Id;
            lastChangeset.Changes     = lastEvent.Action != HistoricalActions.Delete.ToString() ? _historicalCrudReadService.ExtractChanges(
                _mapper.Map <TDto>(currentObject),
                _mapper.Map <TDto>(_repository.GetById <TId, TEntity>(id))) : null;
            lastChangeset.EventName = lastEvent.Action;

            differentialChangeset.Add(lastChangeset);

            return(differentialChangeset);
        }
Ejemplo n.º 23
0
        public String GetAverageDate(HistoricalEvent hevent)
        {
            DateTime dt = ADUtilities.GetAverageDate(hevent);

            return(String.Format("{0}/{1}/{2}", dt.Day, dt.Month, dt.Year));
        }