/// <summary> /// Initializes a new instance of the <see cref="DirectorEventAttribute" /> class. /// Defines what type of event this will be recognized as in the director when it tells the factory to create a list of /// all known events it can call and sort by. /// </summary> /// <param name="eventCategory">The event Category.</param> /// <param name="eventExecutionType">The event Execution Type.</param> public DirectorEventAttribute( EventCategory eventCategory, EventExecution eventExecutionType = EventExecution.RandomOrManual) { EventCategory = eventCategory; EventExecutionType = eventExecutionType; }
public static bool IsEventOfType(EventType ev, EventCategory category) { if ((category == EventCategory.goXXX && ( ev == EventType.goDown || ev == EventType.goUp || ev == EventType.goLeft || ev == EventType.goRight) ) || (category == EventCategory.movingXXX && ( ev == EventType.wentDown || ev == EventType.wentUp || ev == EventType.wentLeft || ev == EventType.wentRight) ) || (category == EventCategory.movement && ( EventTypeLib.IsEventOfType(ev, EventCategory.goXXX) || EventTypeLib.IsEventOfType(ev, EventCategory.movingXXX)) ) ) { return true; } else { return false; } }
public EventCategorySingleViewModel(string category, HttpServerUtilityBase server) { _server = server; category = formatCategoryString(category); //ImageList = getImageList(); using (var context = new DataContext()) { var tomorrow = DateTime.Now.Date; TheCategory = context.EventCategories.FirstOrDefault(x => x.CategoryName == category); EventRoll = context.Events.Where(x => x.MainCategory == category && x.IsActive == true && DateTime.Compare(x.EndDate.Value, tomorrow) >= 0).ToList(); // Set a random picture on the eventRoll if none is currently set //foreach (var event in EventRoll) //{ // if (String.IsNullOrEmpty(event.ImageUrl)) // { // event.ImageUrl = getRandomImage(); // } //} } }
public JsonResult AddCategory(string name) { var result = new JsonResult(); if (!String.IsNullOrEmpty(name)) { using (var context = new DataContext()) { var newCategory = new EventCategory { CategoryName = name, CreateDate = DateTime.Now, IsActive = true }; context.EventCategories.Add(newCategory); context.SaveChanges(); result.Data = new { id = newCategory.EventCategoryId }; return result; } } return result; }
public static void RemoveEventFilter(EventCategory eventCategory, IEventListener eventFilter) { EventInfo eventInfo = GetEventInfo(eventCategory); if (eventInfo.EventFilter == eventFilter) { eventInfo.EventFilter = null; } }
public ActionResult CreateEventCategory(EventCategory type) { if (ModelState.IsValid) { db.EventCategories.Add(type); db.SaveChanges(); return RedirectToAction("EventCategory"); } return View(type); }
public void RegisterEvent(EventCategory eventCategory, string action, string eventName) { try { GoogleAnalytics.EasyTracker.GetTracker().SendEvent(EventCategories[eventCategory], action, eventName, 0); } catch (Exception) { } }
public Crew(RawCrew rawCrew, EventCategory eventCategory, CrewOverride crewOverride, IClub boatingLocation, int startNumber, IEnumerable<IClub> clubs) { _rawCrew = rawCrew; _eventCategory = eventCategory; _categories = new Dictionary<ICategory, int>(); _crewOverride = crewOverride; _athletes = new List<IAthlete>(); _startNumber = startNumber; _boatingLocation = boatingLocation; if (boatingLocation != null) boatingLocation.AddBoatingCrew (this); _clubs = clubs.ToList (); }
private void SetRiskIndex() { EventCategory cat = dictionaryComboBoxCategory.SelectedItem as EventCategory; EventClass eventClass = dictionaryComboEventClass.SelectedItem as EventClass; if (cat != null && eventClass != null) { textBoxRiskIndex.Text = eventClass.Weight + cat.ShortName + (eventClass.Weight * cat.Weight); } else { textBoxRiskIndex.Text = ""; } }
public Crew(RawCrew rawCrew, EventCategory eventCategory, CrewOverride crewOverride, IClub boatingLocation, int startNumber, IEnumerable <IClub> clubs) { _rawCrew = rawCrew; _eventCategory = eventCategory; _categories = new Dictionary <ICategory, int>(); _crewOverride = crewOverride; _athletes = new List <IAthlete>(); _startNumber = startNumber; _boatingLocation = boatingLocation; if (boatingLocation != null) { boatingLocation.AddBoatingCrew(this); } _clubs = clubs.ToList(); }
private void displayCategory(EventCategory category) { if (category == null) { txtName.Text = ""; txtName.Enabled = false; cmdSave.Enabled = false; } else { txtName.Text = category.Name; txtName.Enabled = true; cmdSave.Enabled = true; } }
public void ConfigurePush(EventCategory eventCategory, PushSetting setting) { if (eventCategory == EventCategory.Appointment) { AppointmentEvent = setting; } else if (eventCategory == EventCategory.Interaction) { InteractionEvent = setting; } else if (eventCategory == EventCategory.System) { SystemEvent = setting; } }
private void OnCastingValidityUpdated(EventCategory category) { if (m_spellsPerCategoryInvalidatingStatus.TryGetValue(category, out List <int> value)) { foreach (int item in value) { if (m_playerStatus.TryGetSpell(item, out SpellStatus spellStatus)) { SpellStatusData data = default(SpellStatusData); CastValidityHelper.RecomputeSpellCost(spellStatus, ref data); CastValidityHelper.RecomputeSpellCastValidity(spellStatus.ownerPlayer, spellStatus, ref data); EnqueueSpellStatusData(spellStatus.instanceId, data); } } } }
private List <EventCategory> ConvertEventCategoryResponse(List <EventCategoryResponse> input) { List <EventCategory> output = new List <EventCategory>(); foreach (EventCategoryResponse e in input) { EventCategory eve = new EventCategory() { Id = e.Id, Name = e.Description }; output.Add(eve); } return(output); }
public ActionResult Delete(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } EventCategory eventCategory = Db.EventCategories.Find(id); if (eventCategory == null) { return(HttpNotFound()); } Db.EventCategories.Remove(eventCategory); Db.SaveChanges(); return(RedirectToAction("Index")); }
/// <summary> /// <para>Begins an asynchronous send to the get events route.</para> /// </summary> /// <param name="limit">The maximal number of results to return per call. Note that /// some calls may not return <paramref name="limit" /> number of events, and may even /// return no events, even with `has_more` set to true. In this case, callers should /// fetch again using <see /// cref="Dropbox.Api.TeamLog.Routes.TeamLogTeamRoutes.GetEventsContinueAsync" /// />.</param> /// <param name="accountId">Filter the events by account ID. Return only events with /// this account_id as either Actor, Context, or Participants.</param> /// <param name="time">Filter by time range.</param> /// <param name="category">Filter the returned events to a single category. Note that /// category shouldn't be provided together with event_type.</param> /// <param name="eventType">Filter the returned events to a single event type. Note /// that event_type shouldn't be provided together with category.</param> /// <param name="callback">The method to be called when the asynchronous send is /// completed.</param> /// <param name="callbackState">A user provided object that distinguished this send /// from other send requests.</param> /// <returns>An object that represents the asynchronous send request.</returns> public sys.IAsyncResult BeginGetEvents(uint limit = 1000, string accountId = null, global::Dropbox.Api.TeamCommon.TimeRange time = null, EventCategory category = null, EventTypeArg eventType = null, sys.AsyncCallback callback = null, object callbackState = null) { var getTeamEventsArg = new GetTeamEventsArg(limit, accountId, time, category, eventType); return(this.BeginGetEvents(getTeamEventsArg, callback, callbackState)); }
// GET: EventCategory/Delete/5 public ActionResult Delete(Nullable <int> id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Db db = new Db(DbServices.ConnectionString); EventCategory eventCategory = EventCategoryServices.Get(id.Value, db); if (eventCategory == null) { return(HttpNotFound()); } return(View(eventCategory)); }
public string AddCategory(EventCategory eventCategory) { using (var context = new NCContext.NCContext()) { if (eventCategory != null) { context.EventCategories.Add(eventCategory); context.SaveChanges(); return("true"); } else { return("Name Field is Required"); } } }
public ActionResult Update(int id) { if (Session["AdminId"] == null) { return(RedirectToAction("Index", "Login")); } EventCategory eventCategory = db.EventCategories.Find(id); if (eventCategory == null) { return(HttpNotFound()); } return(View(eventCategory)); }
private void cmdAdd_Click(object sender, EventArgs e) { EventCategory newCategory; newCategory = new EventCategory(); newCategory.Name = "Untitled Category"; newCategory.Url = siteList.GetSelectedSite(); _db.ORManager.SaveOrUpdate(newCategory); lstCategories.Items.Add(new ListItem(newCategory.Name, newCategory.Id.ToString())); //Select the new item lstCategories.SelectedIndex = lstCategories.Items.Count - 1; displayCategory(newCategory); }
public IActionResult ProcessCreateEventCategoryForm(AddEventCategoryViewModel addEventCategoryViewModel) { if (ModelState.IsValid) { EventCategory newCategory = new EventCategory { Name = addEventCategoryViewModel.Name }; context.Categories.Add(newCategory); context.SaveChanges(); return(Redirect("/EventCategory")); } return(View("Create", addEventCategoryViewModel)); }
/// <summary> /// Base logging implementation /// </summary> /// <param name="message">Message to be logged</param> /// <param name="ex">Exception to be logged, null can be passed if there are no exception details</param> /// <param name="level">Level to be used for the logged message</param> /// <param name="category">Category to be used for the logged message</param> static void LogBase(string message, Exception ex, EventLevel level, EventCategory category) { var msg = string.Format("{0} {1}: {2}", category.ToString().PadRight(15), level.ToString().PadRight(15), message); if (ex != null) { msg += "\r\nEXCEPTION: " + ex; } // Log to Console Console.WriteLine(msg); // Log to Debug Debug.WriteLine(msg); // TODO: Log to other logging providers here }
public IActionResult EditCategory(long Id) { EventCategory category = eventRepository.GetEventCategoryById(Id); if (category == null) { ViewBag.ErrorMessage = $"Unknown event category resource"; return(View("error")); } EditEventCategoryViewModel model = new EditEventCategoryViewModel { Title = category.Title, Id = category.Id }; return(PartialView("EditCategory", model)); }
public IActionResult Create(AddEventCategoryViewModel viewModel) { if (ModelState.IsValid) { EventCategory newEventCategory = new EventCategory { Name = viewModel.Name }; _context.Categories.Add(newEventCategory); _context.SaveChanges(); return(Redirect("/EventCategory")); } return(View(viewModel)); }
public IActionResult EditCategory(EditEventCategoryViewModel model) { EventCategory category = eventRepository.GetEventCategoryById(model.Id); if (category != null && ModelState.IsValid) { category.Title = model.Title; eventRepository.UpdateEventCategory(category); eventRepository.Save(); TempData["category-updated"] = $"The Category, { category.Title }, was updated successfully"; return(Json(new { success = true })); } else { return(PartialView("EditCategory", model)); } }
public static EventCategorieDTO Convert(this EventCategory eventcategorie) { return(new EventCategorieDTO { ItemId = eventcategorie.ItemId, IsDeleted = eventcategorie.IsDeleted, Updated = eventcategorie.Updated, CorrectorId = eventcategorie.CorrectorId, Weight = eventcategorie.Weight, MinCompareOp = eventcategorie.MinCompareOperation?.ItemId, EventCountMinPeriod = eventcategorie.EventCountMinPeriod, MinReportPeriod = eventcategorie.MinReportPeriod?.ConvertToByteArray(), MaxCompareOp = eventcategorie.MaxCompareOperation?.ItemId, EventCountMaxPeriod = eventcategorie.EventCountMaxPeriod, MaxReportPeriod = eventcategorie.MinReportPeriod?.ConvertToByteArray() }); }
public IActionResult Edit(EventCategoryEditViewModel viewModel) { if (!ModelState.IsValid) { return(View(viewModel)); } EventCategory editedEventCategory = new EventCategory() { Id = viewModel.Id, Name = viewModel.Name, StatusId = viewModel.StatusId, }; _eventCategoryService.Edit(editedEventCategory); return(RedirectToAction("Index", "EventCategory")); }
public static List <EventType> GetEventCategoryTypes(EventCategory eventCategory) { var types = new List <EventType>(); if (eventCategory == EventCategory.Interaction) { types = new List <EventType> { EventType.ReplyPost, EventType.LikePost, EventType.ForwardPost, EventType.SharePost, EventType.ReplyComment, EventType.LikeComment, EventType.Follow, EventType.ApplyJoinCircle, EventType.JoinCircle, EventType.CircleOwnerChanged, EventType.AtUserInPost, EventType.ApplyJoinCircleAccepted }; } else if (eventCategory == EventCategory.Appointment) { types = new List <EventType> { EventType.CancelOrder, EventType.RejectOrder }; } else if (eventCategory == EventCategory.System) { types = new List <EventType> { EventType.DeletePost, EventType.IdAuthenticated, EventType.IdRejected, EventType.UserOrgAuthFailed, EventType.UserOrgAuthSuccess, EventType.FeedbackCreated }; } return(types); }
public void TraceEventProcessed(long commitLogPosition, PartitionEvent evt, EventCategory category, double startedTimestamp, double finishedTimestamp, bool replaying) { if (this.logLevelLimit <= LogLevel.Information) { long nextCommitLogPosition = ((evt as PartitionUpdateEvent)?.NextCommitLogPosition) ?? 0L; double queueLatencyMs = evt.IssuedTimestamp - evt.ReceivedTimestamp; double fetchLatencyMs = startedTimestamp - evt.IssuedTimestamp; double latencyMs = finishedTimestamp - startedTimestamp; if (this.logger.IsEnabled(LogLevel.Information)) { var details = string.Format($"{(replaying ? "Replayed" : "Processed")} {(evt.NextInputQueuePosition > 0 ? "external" : "internal")} {category}"); this.logger.LogInformation("Part{partition:D2}.{commitLogPosition:D10} {details} {event} eventId={eventId} pos=({nextCommitLogPosition},{nextInputQueuePosition}) latency=({queueLatencyMs:F0}, {fetchLatencyMs:F0}, {latencyMs:F0})", this.partitionId, commitLogPosition, details, evt, evt.EventIdString, nextCommitLogPosition, evt.NextInputQueuePosition, queueLatencyMs, fetchLatencyMs, latencyMs); } this.etw?.PartitionEventProcessed(this.account, this.taskHub, this.partitionId, commitLogPosition, category.ToString(), evt.EventIdString, evt.ToString(), nextCommitLogPosition, evt.NextInputQueuePosition, queueLatencyMs, fetchLatencyMs, latencyMs, replaying, TraceUtils.ExtensionVersion); } }
public List <EventCategory> GetEventCategory(string tableName) { List <EventCategory> list = null; string procName = $"[dbo].[{tableName}_SelectAll]"; _data.ExecuteCmd(procName, inputParamMapper : null, singleRecordMapper : delegate(IDataReader reader, short set) { EventCategory lookUp = MapEventCategory(reader); if (list == null) { list = new List <EventCategory>(); } list.Add(lookUp); }); return(list); }
public static void TriggerBlockman(EventCategory type, Vector2 position, GameObject prefab, bool fromPlayer) { if (type == EventCategory.BlockMan) { var blockman = Instantiate(prefab); Destroy(blockman.GetComponent <SpriteRenderer> ()); blockman.GetComponent <Citizen> ().CreateSpecial(Special.SpecialType.Blockman); var blockmanScript = blockman.AddComponent <Citizen_Blockman> (); blockmanScript.RunningSpeed = 16; blockmanScript.WalkingSpeed = 8; blockmanScript.CurrentMoveSpeed = blockmanScript.WalkingSpeed; blockman.transform.position = position; } }
public IActionResult ProcessCreateEventCategoryForm(AddEventCategoryViewModel addEventCategoryViewModel) { if (ModelState.IsValid) { EventCategory newEventCategory = new EventCategory { // directly assign properties to EventCategory Model using ViewModel Name = addEventCategoryViewModel.Name }; // EventData.Add(newEvent); context.Categories.Add(newEventCategory); context.SaveChanges(); return(Redirect("/EventCategory")); } return(View("Create", addEventCategoryViewModel)); //TODO review this }
/// <summary> /// Calls all events of a specified type, then rolls the dice to determine if any of the events should trigger. /// </summary> /// <param name="gameEntity">Game entity that will be effected by the event.</param> /// <param name="eventCategory">Event type to trigger.</param> public void TriggerEventByType(IEntity gameEntity, EventCategory eventCategory) { // Roll the dice to determine if an event is triggered. if (GameCore.Instance.Random.Next(100) > 5) { return; } // Create a random event based on a given event type enumerable. var randomEvent = _eventFactory.CreateRandomByType(eventCategory); // Check that the created event exists, then invoke it. if (randomEvent == null) { return; } ExecuteEvent(gameEntity, randomEvent); }
/// <summary> /// Add a new eventlog record coming from a user instance /// </summary> /// <param name="user">Identifier of the user in charge</param> /// <param name="db">Database object on which the log will be executed</param> /// <param name="categoryName">Event Category Name</param> /// <param name="sourceName">Event Source Name</param> /// <param name="statusName">Event Status Name</param> /// <param name="formatter">XML formatter</param> /// <param name="handler">A handler that defines the behaviour when the method fails to insert the EventLog to the Database</param> /// <returns>The inserted EvantLog</returns> internal static EventLog Log(int user, Db db, string categoryName, string sourceName, string statusName, XmlFormatterBase formatter, ILogErrorHandler handler = null) { EventLog eventLog = new EventLog(); try { EventCategory eventCategory = EventCategoryServices.GetByNameFirstOrNull(categoryName, db); if (eventCategory == null) { eventCategory = EventCategoryServices.GetByNameFirstOrNull("Uncategorized", db); } EventSource eventSource = EventSourceServices.GetByNameFirstOrNull(sourceName, db); if (eventSource == null) { eventSource = EventSourceServices.GetByNameFirstOrNull("Uncategorized", db); } EventStatus eventStatus = EventStatusServices.GetByNameFirstOrNull(statusName, db); if (eventStatus == null) { eventStatus = EventStatusServices.GetByNameFirstOrNull("Error", db); } eventLog.EventCategory = eventCategory.Id; eventLog.EventSource = eventSource.Id; eventLog.EventStatus = eventStatus.Id; eventLog.Date = DateTime.Now; if (eventCategory.Name == "Uncategorized") { formatter = new UncategorizedXmlFormatter(categoryName, formatter.Parameters); } eventLog.Parameters = formatter.ToString(); eventLog.User = user; eventLog = EventLogServices.Insert(eventLog, db); } catch (Exception ex) { if (handler == null) { handler = new DefaultLogErrorHandler(); } handler.Handle(eventLog, ex); } return(eventLog); }
public static SystemEventType GetStatusEventType(EventCategory category) { if (category == EventCategory.ComponentInternalStatus) { return(ComponentInternalStatus); } if (category == EventCategory.ComponentExternalStatus) { return(ComponentExternalStatus); } if (category == EventCategory.ComponentEventsStatus) { return(ComponentEventsStatus); } if (category == EventCategory.ComponentUnitTestsStatus) { return(ComponentUnitTestsStatus); } if (category == EventCategory.ComponentMetricsStatus) { return(ComponentMetricsStatus); } if (category == EventCategory.ComponentChildsStatus) { return(ComponentChildsStatus); } if (category == EventCategory.UnitTestResult) { return(UnitTestResult); } if (category == EventCategory.UnitTestStatus) { return(UnitTestStatus); } //if (category == EventCategory.MetricResult) //{ // return MetricResult; //} if (category == EventCategory.MetricStatus) { return(MetricStatus); } throw new Exception("Неизвестное значение EventCategory: " + category); }
protected EventType GetOrCreateEventType( Guid accountId, EventCategory category, string systemName, string displayName, Guid componentTypeId, string typeCode) { var type = new EventType() { Category = category, SystemName = systemName, DisplayName = displayName, Code = typeCode }; type = Context.EventTypeService.GetOrCreate(type, accountId); return(type); }
/// <summary> /// Reads the RSS feed specified and inserts the new RSS items into the /// database. /// </summary> /// <param name="url"> /// The URL of the RSS feed. /// </param> /// <param name="db"> /// The connection to the database where the new RSS items /// should be recorded. /// </param> /// <param name="eventCategory"> /// The <see cref="EventCategory"/> that the RSS events belong. /// </param> /// <remarks> /// Feeds are cached to avoid reading the same RSS feed too often. /// </remarks> public static void ProcessFeed(string url, Database db, EventCategory eventCategory) { RssFeedProcessor feedProcessor; if (_cachedFeeds.ContainsKey(url.ToLower())) { _log.DebugFormat("Found RSS feed {0} in cached list.", url); feedProcessor = _cachedFeeds[url.ToLower()]; } else { _log.DebugFormat("RSS feed {0} not found in cached list. Creating new feed and reading.", url); feedProcessor = new RssFeedProcessor(url, db); _cachedFeeds.Add(url, feedProcessor); feedProcessor.Read(); } feedProcessor.AddEventsTo(eventCategory); }
public void LogOpsError(ClaimsPrincipal userContext, string target, EventCategory category) { AppConfig appConfig = configurationRepository.GetAppConfig(); if (appConfig.OperationsLoggingState == OperationsLoggingState.Errors) { AuditEvent auditEvent = new AuditEvent { Id = Guid.NewGuid(), Target = target, EventCategory = category, UserId = userContext.GetUserId(), UserDisplay = userContext.GetName(), Time = DateTime.Now, EventResult = EventResult.Error }; Task.Run(() => auditRepository.InsertAuditEvent(auditEvent)); } }
// POST api/News public HttpResponseMessage PostEvent(string id, EventApi newapi) { AccountApiKey apiUser = GetAccount(); EventSourceType eventsType = db.EventSourceTypes.Where(a => a.Title == "API").Single(); EventSource eventsSource = db.EventSources.Where(a => a.CompanyId == apiUser.CompanyId).Where(a => a.EventSourceTypeId == eventsType.EventSourceTypeId).Single(); Event newEvent = new Event(); EventCategory eventCategory = new EventCategory(); Language lang = new Language(); try { eventCategory = db.EventCategories.Where(a => a.Title == newapi.Category).Single(); lang = db.Language.Where(a => a.Culture == newapi.Language).Single(); } catch (Exception err) { return Request.CreateResponse(HttpStatusCode.NotFound); } newEvent.StartTime = newapi.StartTime; newEvent.EndTime = newapi.StartTime.AddMinutes((double)newapi.DurationM); newEvent.CompanyId = apiUser.CompanyId; newEvent.EventCategoryId = eventCategory.EventCategoryId; newEvent.SourceId = id; EventDetail eventDetails = new EventDetail(); eventDetails.Description = newapi.Description; eventDetails.LanguageId = lang.LanguageId; eventDetails.Summary = newapi.Summary; eventDetails.EventId = newEvent.EventId; if (ModelState.IsValid) { db.Events.Add(newEvent); db.EventDetail.Add(eventDetails); db.SaveChanges(); return Request.CreateResponse(HttpStatusCode.Created); } else { return Request.CreateResponse(HttpStatusCode.BadRequest); } }
/// <summary>Gathers all of the events by specified type and picks one of them at random to return.</summary> /// <param name="eventCategory">Enum value of the type of event such as medical, person, vehicle, etc.</param> /// <returns>Created event product based on enum value.</returns> public EventProduct CreateRandomByType(EventCategory eventCategory) { // Query all of the reference event types that match the given enumeration value. var groupedEventList = new List<Type>(); foreach (var type in EventReference) if (type.Key.Category.Equals(eventCategory) && (type.Key.ExecutionType == EventExecution.RandomOrManual)) groupedEventList.Add(type.Value); // Check to make sure there is at least one type of event of this type. if (groupedEventList.Count <= 0) return null; // Roll the dice against the event reference ceiling count to see which one we use. var diceRoll = GameSimulationApp.Instance.Random.Next(groupedEventList.Count); // Create the event we decided to execute from these types of event types. var randomEvent = CreateInstance(groupedEventList[diceRoll]); // Clear the temporary list we made to get by category and return create event instance. groupedEventList.Clear(); return randomEvent; }
public static void LogVerbose(string message, EventCategory category) { InitializeBehaviour(); Internal.TraceVerbose((int)category, "{0,-15}: {1}", category, message); }
private bool WriteToEventLog(string logName, string eventSource, int eventId, EventLogEntryType eventLevel, EventCategory eventCategory, object[] insertionStrings) { try { using (EventLog operationalLog = new EventLog(logName)) { operationalLog.Source = eventLogSource; operationalLog.WriteEvent(new EventInstance(eventId, (int)eventCategory, eventLevel), insertionStrings); } return true; } catch { //TODO: could not log to event log. Do we need to do anything? return false; } }
/// <summary> /// Gathers all of the events by specified type and then rolls the virtual dice to determine if any of the events in /// the enumeration should trigger. /// </summary> /// <param name="sourceEntity">Entities which will be affected by event if triggered.</param> /// <param name="eventCategory">Event type the dice will be rolled against and attempted to trigger.</param> public void TriggerEventByType(IEntity sourceEntity, EventCategory eventCategory) { // Roll the dice here to determine if the event is triggered at all. var diceRoll = GameSimulationApp.Instance.Random.Next(100); if (diceRoll > 0) return; // Create a random event by type enumeration, event factory will randomly pick one for us based on the enum value. var randomEventProduct = _eventFactory.CreateRandomByType(eventCategory); // Check to make sure the event returned actually exists. if (randomEventProduct == null) return; // Invokes the event which will give it full control over simulation. ExecuteEvent(sourceEntity, randomEventProduct); }
public static void AddEventProcessor(EventCategory eventCategory, IEventProcessor eventProcessor) { EventInfo eventInfo = GetEventInfo(eventCategory); eventInfo.EventProcessor = eventProcessor; }
/// <summary> /// Write an event to the log. Convenience wrapper for WriteEvent. /// Difference from WriteEvent is that this method transforms Exceptions to events via Exception.ToString(). /// </summary> /// <param name="eventSource">Event source name</param> /// <param name="eventId">Event id</param> /// <param name="eventLevel">Severity level of the event</param> /// <param name="eventCategory">Event category. Possible values are in EventCategory enumeration - Administrative, Operational, Analytic, Debug, APIUsage</param> /// <param name="insertionStrings">A list of objects to be used to create the event message.</param> public bool WriteException(string eventSource, int eventId, EventLogEntryType eventLevel, EventCategory eventCategory, params object[] insertionStrings) { for (int i = 0; i < insertionStrings.Length; i++) { if (insertionStrings[i] is Exception) { Exception e = (Exception)insertionStrings[i]; insertionStrings[i] = String.Format("message = {0}", e.ToString()); } } return WriteEvent(eventSource, eventId, eventLevel, eventCategory, insertionStrings); }
private static EventInfo GetEventInfo(EventCategory category) { /// What we need here is hashtable. Until we get one, we have this implementation where we browse through /// registered eventInfos and attempt retrieving matchine one. /// EventInfo eventInfo = null; for (int i = 0; i < _eventInfoTable.Count; i++) { if (((EventInfo)_eventInfoTable[i]).Category == category) { eventInfo = (EventInfo)_eventInfoTable[i]; break; } } if (eventInfo == null) { eventInfo = new EventInfo(); eventInfo.Category = category; _eventInfoTable.Add(eventInfo); } return eventInfo; }
public static void AddEventFilter(EventCategory eventCategory, IEventListener eventFilter) { EventInfo eventInfo = GetEventInfo(eventCategory); eventInfo.EventFilter = eventFilter; eventFilter.InitializeForEventSource(); }
public ActionResult EditEventCategory(EventCategory type) { if (ModelState.IsValid) { db.Entry(type).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("EventCategory"); } return View(type); }
public static void RemoveEventProcessor(EventCategory eventCategory, IEventProcessor eventProcessor) { EventInfo eventInfo = GetEventInfo(eventCategory); if (eventInfo.EventProcessor == eventProcessor) { eventInfo.EventProcessor = null; } }
/// <summary> /// Base logging implementation /// </summary> /// <param name="message">Message to be logged</param> /// <param name="ex">Exception to be logged, null can be passed if there are no exception details</param> /// <param name="level">Level to be used for the logged message</param> /// <param name="category">Category to be used for the logged message</param> static void LogBase(string message, Exception ex, EventLevel level, EventCategory category) { var msg = string.Format("{0} {1}: {2}", category.ToString().PadRight(15), level.ToString().PadRight(15), message); if (ex != null) msg += "\r\nEXCEPTION: " + ex; // Log to Console Console.WriteLine(msg); // Log to Debug Debug.WriteLine(msg); // TODO: Log to other logging providers here }
/// <summary> /// Logs warning message to the event log. /// </summary> /// <param name="message">Message to be logged</param> /// <param name="ex">Exception to be logged, null can be passed if there are no exception details</param> /// <param name="category">Category to be used for the logged message</param> public static void LogWarning(string message, Exception ex, EventCategory category) { LogBase(message, ex, EventLevel.Warning, category); }
/// <summary> /// Logs verbose message to event log. /// </summary> /// <param name="message">Message to be logged</param> /// <param name="category">Category to be used for the logged message</param> public static void LogVerbose(string message, EventCategory category) { LogBase(message, null, EventLevel.Verbose, category); }
/// <summary> /// Logs information message to the event log. /// </summary> /// <param name="message">Message to be logged</param> /// <param name="category">Category to be used for the logged message</param> public static void LogInformation(string message, EventCategory category) { LogBase(message, null, EventLevel.Information, category); }
/// <summary> /// Logs error message to the event log. /// </summary> /// <param name="message">Message to be logged</param> /// <param name="ex">Exception to be logged, null can be passed if there are no exception details</param> /// <param name="category">Category to be used for the logged message</param> public static void LogError(string message, Exception ex, EventCategory category) { LogBase(message, ex, EventLevel.Error, category); }
public TraceEvent( object eventId, TraceEventType type, ApplicationLifeCycleType lifeCycleType, EventCategory category, string message, ContextIdentifier contextIdentifier, object context ) : this() { try { EventIdText = eventId.ToString(); EventId = Convert.ToInt32(eventId); } catch (Exception e) { EventId = 0; // TODO: Add loggin of that as a warning! (SD) } _type = type; _lifeCycleType = lifeCycleType; // This conversion is done here in order to de-couple all // possible enumeration types that can be encountered here. // This is done according to the fact that other app domains // would need to know them then, and it is not the point. Message = (string.IsNullOrEmpty(message)) ? eventId.ToString() : message; ContextIdentifier = contextIdentifier ?? new ContextIdentifier(); _category = category; Context = context; }
public static void LogInformation(string message, EventCategory category) { InitializeBehaviour(); Internal.TraceInformation(20 + (int)category, "{0,-15}: {1}", category, message); }
public static void LogError(string message, Exception ex, EventCategory category) { InitializeBehaviour(); Internal.TraceError(50 + (int)category, "{0,-15}: {1}\r\nEXCEPTION: {2}", category, message, ex); }
// PUT api/News/5 public HttpResponseMessage PutEvent(string id, EventApi newapi) { AccountApiKey apiUser = GetAccount(); EventSourceType eventsType = db.EventSourceTypes.Where(a => a.Title == "API").Single(); EventSource eventsSource = db.EventSources.Where(a => a.CompanyId == apiUser.CompanyId).Where(a => a.EventSourceTypeId == eventsType.EventSourceTypeId).Single(); Event newEvent = new Event(); EventCategory eventCategory = new EventCategory(); Language lang = new Language(); try { newEvent = db.Events.Include("EventDetails").Where(a => a.CompanyId == apiUser.CompanyId).Where(c => c.EventSourceId == eventsSource.EventSourceId).Where(b => b.SourceId == id).Single(); eventCategory = db.EventCategories.Where(a => a.Title == newapi.Category).Single(); lang = db.Language.Where(a => a.Culture == newapi.Language).Single(); } catch (Exception err) { return Request.CreateResponse(HttpStatusCode.NotFound); } newEvent.StartTime = newapi.StartTime; newEvent.EndTime = newapi.StartTime.AddMinutes((double)newapi.DurationM); EventDetail eventDetails = new EventDetail(); var eventDetailCnt = (from a in newEvent.EventDetails where a.LanguageId == lang.LanguageId select a); if (eventDetailCnt.Count() == 1) eventDetails = eventDetailCnt.First(); eventDetails.Description = newapi.Description; eventDetails.LanguageId = lang.LanguageId; eventDetails.Summary = newapi.Summary; eventDetails.EventId = newEvent.EventId; if (ModelState.IsValid) { //db.Entry(news).State = EntityState.Modified; try { if (eventDetailCnt.Count() == 0) db.EventDetail.Add(eventDetails); db.SaveChanges(); } catch (DbUpdateConcurrencyException) { return Request.CreateResponse(HttpStatusCode.NotFound); } return Request.CreateResponse(HttpStatusCode.OK); } else { return Request.CreateResponse(HttpStatusCode.BadRequest); } }
/// <summary> /// Write an event to the log. /// </summary> /// <param name="eventSourceName">Event source name</param> /// <param name="eventId">Event id</param> /// <param name="eventLevel">Severity level of the event</param> /// <param name="eventCategory">Event category. Possible values are in EventCategory enumeration - Administrative, Operational, Analytic, Debug, APIUsage</param> /// <param name="description">The list of messages to be logged.</param> /// <returns>a Status Reply object suitable for being returned from the WCF service, giving info about the event written</returns> private static StatusReplyDC WriteEvent(string eventSourceName, int eventId, EventLogEntryType eventLevel, EventCategory eventCategory, object[] insertionStrings) { StatusReplyDC result = new StatusReplyDC { Errorcode = eventId, ErrorGuid = string.Format("{0}\r\n\r\n{1}", SprocValues.LOG_LOCATION + ":" + eventSourceName, insertionStrings.ToList() .Aggregate((first, last) => string.Format("{0}\r\n{1}", first, last)) .ToString()), }; LogClient.Source = SprocValues.DAL_CALLER_INFO; LogClient.Log = SprocValues.LOG_LOCATION; LogClient.WriteEvent(new EventInstance(eventId, (int)eventCategory, eventLevel), insertionStrings); return result; }
/// <summary> /// Write an event to the log. This class uses a message resource file to use insertion strings into message description templates in the message resource file. /// </summary> /// <param name="eventSource">Event source.</param> /// <param name="eventId">Event id</param> /// <param name="eventLevel">Severity level of the event</param> /// <param name="eventCategory">Event category. Possible values are in EventCategory enumeration - Administrative, Operational, Analytic, Debug, APIUsage</param> /// <param name="insertionStrings">A list of objects to be used to create the event message. /// </param> public bool WriteEvent(string eventSource, int eventId, EventLogEntryType eventLevel, EventCategory eventCategory, params object[] insertionStrings) { try { // see if a category and severity is defined in the configuration file. // An entry in the config file overwrites the user supplied value. ErrorCodeEventCategoryConfigSection errorCodeConfigSection = ErrorCodeEventCategoryConfigSection.Current; if (errorCodeConfigSection != null && errorCodeConfigSection.ErrorCodes[eventId] != null) { eventCategory = errorCodeConfigSection.ErrorCodes[eventId].Category; string severity = errorCodeConfigSection.ErrorCodes[eventId].Severity; switch (severity.ToLower()) { case "error": eventLevel = EventLogEntryType.Error; break; case "warning": eventLevel = EventLogEntryType.Warning; break; case "information": eventLevel = EventLogEntryType.Information; break; case "successaudit": eventLevel = EventLogEntryType.SuccessAudit; break; case "failureaudit": eventLevel = EventLogEntryType.FailureAudit; break; default: // if no value specified, we will use use-supplied value break; } } } catch (Exception ex) { // Catching "Exception" to prevent the application from crashing during the configuration reading. // Log the exception and get out. if reading the configuration file gives error, use the user-supplied values. WriteToEventLog(eventLogName, EventSource.LogWriterError.ToString(), EventCode.WebServiceLayerEvent.Error.ErrorCodeToEventCategoryMappingConfigNotFound, EventLogEntryType.Error, EventCategory.Administrative, new string[] { ex.ToString() }); } int msgLevel; switch (eventLevel) { case EventLogEntryType.FailureAudit: case EventLogEntryType.Error: msgLevel = 0; break; case EventLogEntryType.Warning: msgLevel = 1; break; default: msgLevel = 2; break; } int logLevel = defaultLevel; string level = logSettings.Settings[LogSettingKey.GetLogLevelKey(eventSource)].Value; if (!String.IsNullOrWhiteSpace(level)) { logLevel = int.TryParse(level, out logLevel) ? logLevel : defaultLevel; } if (logLevel < msgLevel) { return true; } return WriteToEventLog(eventLogName, eventSource, eventId, eventLevel, eventCategory, insertionStrings); }