public void ProcessAllEvents(bool updateTime, double phase) { this.phase = phase; if (updateTime) { Interlocked.Increment(ref time); } if (time > 0) { if (calendar.CountOfEvents > 0) { DebuggerIX.WriteLine(DebuggerTag.SimulationNotableEvents, "[EventProcessing|Player" + playerNumber() + "]", "=== Time: " + time.ToString() + " ==="); } else { DebuggerIX.WriteLine(DebuggerTag.SimulationNotableEvents, "[EventProcessing|Player" + playerNumber() + "]", "=== Time: " + time.ToString() + " === | Empty calendar"); } while ((ud = calendar.First(time)) != null) { DebuggerIX.WriteLine(DebuggerTag.SimulationProcessedEvents, (ud.Value.who == null ? "NULL" : ud.Value.who.Name), ud.Value.ToString()); if (ud.Value.who == null || ud.Value.who.ProcessEvent(time, ud.Value) == false) { this.ProcessEvent(ud.Value); } } gameVariant.CheckRound(time); } }
public void Setup() { if (Complexity == "Simple") { _ev = TestData.SimpleEventInstance(); } else { _ev = TestData.ComplexEventInstance(); } // BTDB Setup _eventSerializer = new EventSerializer(); _eventDeserializer = new EventDeserializer(); var meta = _eventSerializer.Serialize(out _, _ev).ToAsyncSafe(); _eventSerializer.ProcessMetadataLog(meta); _eventDeserializer.ProcessMetadataLog(meta); _btdbSerializedData = _eventSerializer.Serialize(out _, _ev).ToAsyncSafe(); BtdbByteSize = _btdbSerializedData.Length; _eventDeserializer.Deserialize(out object obj, _btdbSerializedData); obj.Should().BeEquivalentTo(_ev); // ProtoBuf Setup _serializer = ModelFactory.CreateModel(); _eventType = typeof(Event); _memStream = new MemoryStream(); _serializer.Serialize(_memStream, _ev); ProtoBufByteSize = (int)_memStream.Length; _memStream.Position = 0; _serializer.Deserialize(_memStream, null, _eventType).Should().BeEquivalentTo(_ev); BtdbSerialization(); BtdbDeserialization(); ProtoBufSerialization(); ProtoBufDeserialization(); }
public async Task <IActionResult> UpdateEventInfo(UpdatedEventInfoDto updatedEventInfoDto) { IDatabaseContext context = _getDatabaseContext(); Event? @event = await context.Events .Include(e => e.Organizer) .Include(e => e.EventParticipations) .ThenInclude(ep => ep.Participant) .FirstOrDefaultAsync(e => e.Id == updatedEventInfoDto.EventId); if (@event == null) { return(BadRequest(RequestStringMessages.EventNotFound)); } if (@event.OrganizerId != HttpContext.GetUserId()) { _logger.LogInformation("{0}(): Tried to update event {1}, which he's not organizing", nameof(UpdateEventInfo), @event.Id); return(BadRequest(RequestStringMessages.OrganizerRequired)); } @event.Title = updatedEventInfoDto.Title; @event.MeetingPlace = updatedEventInfoDto.MeetingPlace; @event.Description = updatedEventInfoDto.Description; @event.IsPrivate = updatedEventInfoDto.IsPrivate; @event.ReminderTimeWindowInHours = updatedEventInfoDto.ReminderTimeWindowInHours; @event.SummaryTimeWindowInHours = updatedEventInfoDto.SummaryTimeWindowInHours; await context.SaveChangesAsync(); _auditLogger.LogInformation("{0}(): Updated event {1}", nameof(UpdateEventInfo), @event.Id); await _notificationService.NotifyEventUpdatedAsync(@event); return(Ok()); }
public ActionResult Index(string url, string token, RequestMsgType requestType, Event?eventType, bool testConcurrence, int testConcurrenceCount, bool testEncrypt, string encodingAESKey, string appId) { using (MemoryStream ms = new MemoryStream()) { var requestMessaageDoc = GetrequestMessaageDoc(/*url, token,*/ requestType, eventType); requestMessaageDoc.Save(ms); ms.Seek(0, SeekOrigin.Begin); string msgSigature = null; var timeStamp = SystemTime.NowTicks.ToString(); var nonce = (SystemTime.NowTicks * 2).ToString(); string encryptTypeAll = null; string openIdAll = null; //对请求消息进行加密 if (testEncrypt) { try { var openId = requestMessaageDoc.Root.Element("FromUserName").Value; var toUserName = requestMessaageDoc.Root.Element("ToUserName").Value; WXBizMsgCrypt msgCrype = new WXBizMsgCrypt(token, encodingAESKey, appId); string finalResponseXml = null; var ret = msgCrype.EncryptRequestMsg(requestMessaageDoc.ToString(), timeStamp, nonce, toUserName, ref finalResponseXml, ref msgSigature); if (ret == 0) { requestMessaageDoc = XDocument.Parse(finalResponseXml);//赋值最新的加密信息 openIdAll = $"openid={openId}"; encryptTypeAll = "&encrypt_type=aes"; } } catch (Exception ex) { var data = new { Success = false, LoadTime = "N/A", Result = "发生错误:" + ex.ToString() }; return(Json(data, new JsonSerializerSettings() { ContractResolver = new DefaultContractResolver() })); throw; } //Senparc.CO2NET.Trace.SenparcTrace.SendCustomLog("模拟测试-加密消息:", requestMessaageDoc?.ToString()); } var sigature = CheckSignature.GetSignature(timeStamp, nonce, token); url += url.Contains("?") ? "&" : "?"; url += $"signature={sigature}&timeStamp={timeStamp}&nonce={nonce}&msg_signature={msgSigature}{encryptTypeAll}{openIdAll}"; //参数如:signature=330ed3b64e363dc876f35e54a79e59b48739f567×tamp=1570075722&nonce=863153744&openid=olPjZjsXuQPJoV0HlruZkNzKc91E&encrypt_type=aes&msg_signature=71dc359205a4660bc3b3046b643452c994b5897d var dt1 = SystemTime.Now; try { dt1 = SystemTime.Now; if (testConcurrence) { //异步方法 testConcurrenceCount = testConcurrenceCount > 30 ? 30 : testConcurrenceCount;//设定最高限额 //模拟并发请求 List <Task <string> > taskList = new List <Task <string> >(); for (int i = 0; i < testConcurrenceCount; i++) { var task = TestAsyncTask(url, token, requestMessaageDoc, autoFillUrlParameters: false, index: i, sleepMillionSeconds: 0); taskList.Add(task); } Task.WaitAll(taskList.ToArray(), 1500 * 10); } else { //同步方法,立即发送 _responseMessageXml = MessageAgent.RequestXml(null, url, token, requestMessaageDoc.ToString(), autoFillUrlParameters: false); } if (string.IsNullOrEmpty(_responseMessageXml)) { _responseMessageXml = "返回消息为空,可能已经被去重。\r\nMsgId相同的连续消息将被自动去重。"; } var cache = CacheStrategyFactory.GetObjectCacheStrategyInstance(); var data = new { Success = true, LoadTime = SystemTime.DiffTotalMS(dt1, "f4"), Result = _responseMessageXml, CacheType = cache.GetType().Name, ConcurrenceCount = testConcurrenceCount }; return(Json(data, new JsonSerializerSettings() { ContractResolver = new DefaultContractResolver() })); } catch (Exception ex) { var msg = string.Format("{0}\r\n{1}\r\n{2}", ex.Message, null, ex.InnerException != null ? ex.InnerException.Message : null); return(Json(new { Success = false, Result = msg }, new JsonSerializerSettings() { ContractResolver = new DefaultContractResolver() })); } } }
public ChildProcess(string exe, string args = "", string input = "", bool throwExceptionOnExitError = false, int timeout = ThreadObj.Infinite) { this.timeout = timeout; Str.NormalizeString(ref args); ProcessStartInfo info = new ProcessStartInfo() { FileName = IO.InnerFilePath(exe), Arguments = args, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = !Str.IsEmptyStr(input), }; ThreadObj?t = null; using (Process p = Process.Start(info) !) { this.proc = p; if (timeout != ThreadObj.Infinite) { timeout_thread_event = new Event(); t = new ThreadObj(timeout_thread); } if (Str.IsEmptyStr(input) == false) { p.StandardInput.Write(input); p.StandardInput.Flush(); p.StandardInput.Close(); } stdout = p.StandardOutput.ReadToEnd(); stderr = p.StandardError.ReadToEnd(); p.WaitForExit(); finished = true; if (timeout_thread_event != null) { timeout_thread_event.Set(); } if (t != null) { t.WaitForEnd(); } if (killed) { if (Str.IsEmptyStr(stderr)) { stderr = $"Process run timeout ({timeout._ToString3()} msecs)."; } } exitcode = p.ExitCode; if (throwExceptionOnExitError) { if (exitcode != 0) { throw new ApplicationException($"ChildProcess: '{exe}': exitcode = {exitcode}, errorstr = {stderr._OneLine()}"); } } } }
public async Task <IActionResult> InviteParticipants(InviteParticipantsDto inviteParticipantsDto) { IDatabaseContext context = _getDatabaseContext(); Event? @event = await context.Events .Include(e => e.Organizer) .Include(e => e.EventInvitations) .Include(e => e.EventParticipations) .ThenInclude(ep => ep.Participant) .FirstOrDefaultAsync(e => e.Id == inviteParticipantsDto.EventId); if (@event == null) { return(BadRequest(RequestStringMessages.EventNotFound)); } User currentUser = await HttpContext.GetCurrentUserAsync(context); if (@event.Organizer != currentUser) { _logger.LogInformation("{0}(): Tried to add appointments to the event {1}, which he's not organizing", nameof(InviteParticipants), @event.Id); return(BadRequest(RequestStringMessages.OrganizerRequired)); } var mailInvites = new List <(string email, EventInvitation invite)>(); var userInvites = new List <(User user, EventInvitation invite)>(); foreach (string emailAddress in inviteParticipantsDto.EmailAddresses) { // Create new invite var invite = new EventInvitation { Requested = DateTime.UtcNow, Event = @event }; context.EventInvitations.Add(invite); // Check if a profile with this email exists User?existingUser = await context.Users.FirstOrDefaultAsync(u => u.Email == emailAddress); if (existingUser == null) { // No user exists mailInvites.Add((emailAddress, invite)); } else { // User with mail exists => Check if he's already part of the event if (@event.EventParticipations.Any(e => e.Participant.Email == emailAddress)) { return(BadRequest($"Die E-Mail-Adresse {emailAddress} nimmt bereits am Event teil")); } userInvites.Add((existingUser, invite)); } } await context.SaveChangesAsync(); await _notificationService.SendInvitationLinkAsync(userInvites, mailInvites); return(Ok()); }
// Lists the next several night events to occur on or after the given // date, up to the given limit, optionally of a given type. public static List <Prediction> ListNextEventsFromDate (WorldDate fromDate, uint limit, Event?onlyType = null) { Utilities.CheckWorldReady(); // Logic from StardewValley.Utility.<>c.<pickFarmEvent>b__146_0() // as implemented in Stardew Predictor by MouseyPounds. List <Prediction> predictions = new List <Prediction> (); for (int days = fromDate.TotalDays; predictions.Count < limit && days < fromDate.TotalDays + Utilities.MaxHorizon; ++days) { WorldDate tonight = Utilities.TotalDaysToWorldDate(days); WorldDate tomorrow = Utilities.TotalDaysToWorldDate(days + 1); // No event if there is a wedding tomorrow. foreach (Farmer farmer in Game1.getAllFarmers()) { Friendship spouse = farmer.GetSpouseFriendship(); if (spouse != null && spouse.WeddingDate == tomorrow) { continue; } } Event @event = Event.None; Random rng = new Random(((int)Game1.uniqueIDForThisGame / 2) + days + 2); if (days == 29) { @event = Event.Earthquake; } // Ignoring the possibility of bundle completion here. else if (rng.NextDouble() < 0.01 && tomorrow.Season != "winter") { @event = Event.Fairy; } else if (rng.NextDouble() < 0.01) { @event = Event.Witch; } else if (rng.NextDouble() < 0.01) { @event = Event.Meteorite; } else if (rng.NextDouble() < 0.01 && tomorrow.Year > 1) { @event = Event.StrangeCapsule; } else if (rng.NextDouble() < 0.01) { @event = Event.StoneOwl; } if (@event == Event.None || (onlyType != null && @event != onlyType)) { continue; } predictions.Add(new Prediction { date = tonight, @event = @event }); } return(predictions); }
/// <summary> /// Add a notification receiver for the given event type /// </summary> /// <param name="listener">The listener to add the receivers to</param> /// <param name="notificationReceiver">The notification receiver that will be invoked when a notification of the given event type is received</param> /// <param name="forEventType">The event type used to filter the received notifications</param> public static void AddNotificationReceiver(this IMessagingHubListener listener, INotificationReceiver notificationReceiver, Event?forEventType = null) { listener.AddNotificationReceiver(notificationReceiver, n => Task.FromResult(forEventType == null || n.Event == forEventType)); }
/// <summary> /// Set Event field</summary> /// <param name="event_">Nullable field value to be set</param> public void SetEvent(Event?event_) { SetFieldValue(0, 0, event_, Fit.SubfieldIndexMainField); }
public ActionResult Index(string url, string token, RequestMsgType requestType, Event?eventType) { using (MemoryStream ms = new MemoryStream()) { var requestMessaageDoc = GetrequestMessaageDoc(url, token, requestType, eventType); requestMessaageDoc.Save(ms); ms.Seek(0, SeekOrigin.Begin); var responseMessageXml = MessageAgent.RequestXml(null, url, token, requestMessaageDoc.ToString()); return(Content(responseMessageXml)); } }
public EventObject(Event?ev, List <UInt256>?topics) { Event = ev; Topics = topics; }
public EventObject(Event?ev) { Event = ev; }
/// <summary> /// Attempts to remove and return the object at the beginning of the <see cref="ConcurrentQueue{T}"/>. /// </summary> /// <param name="event"> /// When this method returns, if the operation was successful, <paramref name="event"/> contains the /// object removed. If no object was available to be removed, the value is unspecified. /// </param> /// <returns> /// true if an element was removed and returned from the beginning of the <see cref="ConcurrentQueue{T}"/> successfully; otherwise, false. /// </returns> public bool TryDequeue([NotNullWhen(true)] out Event? @event) => _events.TryDequeue(out @event);
/// <summary> /// Tries to get an event by it's <see cref="id" />. /// </summary> /// <param name="id">The identifier.</param> /// <param name="event">The event.</param> /// <returns><see langword="true" /> if found, <see langword="false" /> otherwise.</returns> public static bool TryGet(int id, [MaybeNullWhen(false)] out Event? @event) => s_all.TryGetValue(id, out @event);
public override void Characters(char[] characters, int start, int length) { _textElementIdx++; if (_flush) { FlushBlock(); _flush = false; } if (_inIgnorableElement != 0) { return; } char c; bool startWhitespace = false; bool endWhitespace = false; if (length == 0) { return; } int end = start + length; for (int i = start; i < end; i++) { if (char.IsWhiteSpace(characters[i])) { characters[i] = ' '; } } while (start < end) { c = characters[start]; if (c == ' ') { startWhitespace = true; start++; length--; } else { break; } } while (length > 0) { c = characters[start + length - 1]; if (c == ' ') { endWhitespace = true; length--; } else { break; } } if (length == 0) { if (startWhitespace || endWhitespace) { if (!_sbLastWasWhitespace) { _textBuffer.Append(' '); _tokenBuffer.Append(' '); } _sbLastWasWhitespace = true; } else { _sbLastWasWhitespace = false; } _lastEvent = Event.WHITESPACE; return; } if (startWhitespace) { if (!_sbLastWasWhitespace) { _textBuffer.Append(' '); _tokenBuffer.Append(' '); } } if (_blockTagLevel == -1) { _blockTagLevel = _tagLevel; } _textBuffer.Append(characters, start, length); _tokenBuffer.Append(characters, start, length); if (endWhitespace) { _textBuffer.Append(' '); _tokenBuffer.Append(' '); } _sbLastWasWhitespace = endWhitespace; _lastEvent = Event.CHARACTERS; _currentContainedTextElements.Set(_textElementIdx, true); }
/// <summary> /// Add a notification receiver for the given event type /// </summary> /// <param name="listener">The listener to add the receivers to</param> /// <param name="onNotificationReceived">A callback method that will be invoked when a notification of the given event type is received</param> /// <param name="forEventType">The event type used to filter the received notifications</param> public static void AddNotificationReceiver(this IMessagingHubListener listener, Func <Notification, CancellationToken, Task> onNotificationReceived, Event?forEventType = null) { listener.AddNotificationReceiver(new LambdaNotificationReceiver(onNotificationReceived), n => Task.FromResult(forEventType == null || n.Event == forEventType)); }
public ActionResult Index(string url, string token, RequestMsgType requestType, Event?eventType) { using (MemoryStream ms = new MemoryStream()) { var requestMessaageDoc = GetrequestMessaageDoc(url, token, requestType, eventType); requestMessaageDoc.Save(ms); ms.Seek(0, SeekOrigin.Begin); var responseMessageXml = MessageAgent.RequestXml(null, url, token, requestMessaageDoc.ToString()); if (string.IsNullOrEmpty(responseMessageXml)) { responseMessageXml = "返回消息为空,可能已经被去重。\r\nMsgId相同的连续消息将被自动去重。"; } return(Content(responseMessageXml)); } }
static void Main(string[] args) { string header = "Zombiebot v1.2"; Console.Title = header; Console.WriteLine(header); string name = "Zombies - Infection"; // Default name for the Abyxa server. string region = "us"; // Default region for the Abyxa server. bool local = false; // Determines if the Abyxa website is on the local server. Event? owevent = null; // The current overwatch event ScreenshotMethods screenshotMethod = ScreenshotMethods.BitBlt; // Parse config file string[] config = null; string filecheck = Extra.GetExecutingDirectory() + "config.txt"; // File location of config file. try { config = System.IO.File.ReadAllLines(filecheck); } catch (Exception ex) { if (ex is System.IO.DirectoryNotFoundException || ex is System.IO.FileNotFoundException) { Console.WriteLine("Could not find configuration file at '{0}', using default settings.", filecheck); } else { Console.WriteLine("Error getting configuration file at '{0}', using default settings.", filecheck); } } if (config != null) { for (int i = 0; i < config.Length; i++) // For each line in the config file { string line = config[i].Trim(' '); if (line.Length >= 2) { if (line[0] == '/' && line[1] == '/') { continue; } } // Remove any text after "//" int index = line.IndexOf("//"); if (index > 0) { line = line.Substring(0, index); } // Split line at "=" string[] lineSplit = line.Split(new string[] { "=" }, 2, StringSplitOptions.RemoveEmptyEntries); // Trim whitespace for (int lsi = 0; lsi < lineSplit.Length; lsi++) { lineSplit[lsi] = lineSplit[lsi].Trim(' '); } if (lineSplit.Length > 1) { switch (lineSplit[0]) { case "local": { if (bool.TryParse(lineSplit[1], out bool set)) { local = set; } } break; case "minimumPlayers": { if (int.TryParse(lineSplit[1], out int set) && set >= 0 && set <= 7) { minimumPlayers = set; } } break; case "name": { name = lineSplit[1]; } break; case "region": { if (lineSplit[0] == "region" && ValidRegions.Contains(lineSplit[1])) { region = lineSplit[1]; } } break; case "DefaultMode": { if (Enum.TryParse(lineSplit[1], out JoinType jointype)) { Join = jointype; } } break; case "Event": { if (Enum.TryParse(lineSplit[1], out Event setowevent)) { owevent = setowevent; } } break; case "ScreenshotMethod": { if (Enum.TryParse(lineSplit[1], out ScreenshotMethods set)) { screenshotMethod = set; } } break; case "version": { if (Int32.TryParse(lineSplit[1], out int set)) { if (set == 0 || set == 1) { version = set; } } } break; } } } } if (Join == null) { string joinmode = Extra.ConsoleInput("Abyxa or server browser (\"abyxa\"/\"sb\"/\"private\"): ", "abyxa", "sb", "private"); if (joinmode == "abyxa") { Join = JoinType.Abyxa; } else if (joinmode == "sb") { Join = JoinType.ServerBrowser; } else if (joinmode == "private") { Join = JoinType.Private; } } IntPtr useHwnd = new IntPtr(); while (true) { Process[] overwatchProcesses = Process.GetProcessesByName("Overwatch"); if (overwatchProcesses.Length == 0) { Console.WriteLine("No Overwatch processes found, press enter to recheck."); Console.ReadLine(); continue; } else if (overwatchProcesses.Length == 1) { useHwnd = overwatchProcesses[0].MainWindowHandle; break; } else if (overwatchProcesses.Length > 1) { Console.Write("Click on the Overwatch window to use... "); bool lookingForWindow = true; while (lookingForWindow) { IntPtr hwnd = Extra.GetForegroundWindow(); overwatchProcesses = Process.GetProcessesByName("Overwatch"); for (int i = 0; i < overwatchProcesses.Length; i++) { if (overwatchProcesses[i].MainWindowHandle == hwnd) { Console.WriteLine("Overwatch window found."); useHwnd = hwnd; lookingForWindow = false; break; } } System.Threading.Thread.Sleep(500); } break; } } Console.WriteLine("Press return to start."); Console.ReadLine(); Console.WriteLine("Starting..."); cg = new CustomGame(useHwnd, screenshotMethod); // Set the mode enabled if (version == 0) { cg.ModesEnabled = new ModesEnabled() { Elimination = true }; maps = ElimMaps; mapsSend = ElimMapsSend; } else if (version == 1) { cg.ModesEnabled = new ModesEnabled() { TeamDeathmatch = true }; maps = DmMaps; mapsSend = DmMapsSend; } // Set event if (owevent == null) { cg.CurrentOverwatchEvent = cg.GetCurrentOverwatchEvent(); } else { cg.CurrentOverwatchEvent = (Event)owevent; } cg.Command.ListenTo.Add("$VOTE", true); cg.Command.SameExecutorCommandUpdate = true; cg.Chat.BlockGeneralChat = true; a = null; if (Join == JoinType.Abyxa) { a = new Abyxa(name, region, local); a.SetMinimumPlayerCount(minimumPlayers); cg.GameSettings.SetJoinSetting(Deltin.CustomGameAutomation.Join.InviteOnly); } Setup(); while (true) { bool pregame = Pregame(); if (pregame) { Ingame(); } else { Setup(); } } }
/// <summary> /// 获取请求XML /// </summary> /// <returns></returns> private XDocument GetrequestMessaageDoc(string url, string token, RequestMsgType requestType, Event?eventType) { RequestMessageBase requestMessaage = null; switch (requestType) { case RequestMsgType.Text: requestMessaage = new RequestMessageText() { Content = Request.Form["Content"], }; break; case RequestMsgType.Location: requestMessaage = new RequestMessageLocation() { Label = Request.Form["Label"], Location_X = double.Parse(Request.Form["Location_X"]), Location_Y = double.Parse(Request.Form["Location_Y"]), Scale = int.Parse(Request.Form["Scale"]) }; break; case RequestMsgType.Image: requestMessaage = new RequestMessageImage() { PicUrl = Request.Form["PicUrl"], }; break; case RequestMsgType.Voice: requestMessaage = new RequestMessageVoice() { Format = Request.Form["Format"], Recognition = Request.Form["Recognition"], }; break; case RequestMsgType.Video: requestMessaage = new RequestMessageVideo() { MsgId = long.Parse(Request.Form["MsgId"]), ThumbMediaId = Request.Form["ThumbMediaId"], }; break; //case RequestMsgType.Link: // break; case RequestMsgType.Event: if (eventType.HasValue) { RequestMessageEventBase requestMessageEvent = null; switch (eventType.Value) { //case Event.ENTER: // break; case Event.LOCATION: requestMessageEvent = new RequestMessageEvent_Location() { Latitude = long.Parse(Request.Form["Event.Latitude"]), Longitude = long.Parse(Request.Form["Event.Longitude"]), Precision = double.Parse(Request.Form["Event.Precision"]) }; break; case Event.subscribe: requestMessageEvent = new RequestMessageEvent_Subscribe() { EventKey = Request.Form["Event.EventKey"] }; break; case Event.unsubscribe: requestMessageEvent = new RequestMessageEvent_Unsubscribe(); break; case Event.CLICK: requestMessageEvent = new RequestMessageEvent_Click() { EventKey = Request.Form["Event.EventKey"] }; break; case Event.scan: requestMessageEvent = new RequestMessageEvent_Scan() { EventKey = Request.Form["Event.EventKey"], Ticket = Request.Form["Event.Ticket"] }; break; case Event.VIEW: requestMessageEvent = new RequestMessageEvent_View() { EventKey = Request.Form["Event.EventKey"] }; break; case Event.MASSSENDJOBFINISH: requestMessageEvent = new RequestMessageEvent_MassSendJobFinish() { FromUserName = "******", //系统指定 ErrorCount = int.Parse(Request.Form["Event.ErrorCount"]), FilterCount = int.Parse(Request.Form["Event.FilterCount"]), SendCount = int.Parse(Request.Form["Event.SendCount"]), Status = Request.Form["Event.Status"], TotalCount = int.Parse(Request.Form["Event.TotalCount"]) }; break; default: throw new ArgumentOutOfRangeException("eventType"); } requestMessaage = requestMessageEvent; } else { throw new ArgumentOutOfRangeException("eventType"); } break; default: throw new ArgumentOutOfRangeException("requestType"); } requestMessaage.CreateTime = DateTime.Now; requestMessaage.FromUserName = requestMessaage.FromUserName ?? "FromUserName(OpenId)";//用于区别不同的请求用户 requestMessaage.ToUserName = "******"; return(requestMessaage.ConvertEntityToXml()); }
public ActionResult Index(string url, string token, RequestMsgType requestType, Event? eventType, bool testConcurrence, int testConcurrenceCount) { using (MemoryStream ms = new MemoryStream()) { var requestMessaageDoc = GetrequestMessaageDoc(url, token, requestType, eventType); requestMessaageDoc.Save(ms); ms.Seek(0, SeekOrigin.Begin); var responseMessageXml = MessageAgent.RequestXml(null, url, token, requestMessaageDoc.ToString()); if (string.IsNullOrEmpty(responseMessageXml)) { responseMessageXml = "返回消息为空,可能已经被去重。\r\nMsgId相同的连续消息将被自动去重。"; } try { DateTime dt1 = DateTime.Now; if (testConcurrence) { testConcurrenceCount = testConcurrenceCount > 30 ? 30 : testConcurrenceCount;//设定最高限额 //模拟并发请求 List<Task<string>> taskList = new List<Task<string>>(); for (int i = 0; i < testConcurrenceCount; i++) { var task = Task.Factory.StartNew(() => TestAsyncTask(url, token, requestMessaageDoc)); taskList.Add(task); } Task.WaitAll(taskList.ToArray(), 1000 * 10); } DateTime dt2 = DateTime.Now; return Json(new { Success = true, LoadTime = (dt2 - dt1).TotalMilliseconds.ToString("##.####"), Result = responseMessageXml }); } catch (Exception ex) { var msg = string.Format("{0}\r\n{1}\r\n{2}", ex.Message, null, ex.InnerException != null ? ex.InnerException.Message : null); return Json(new { Success = false, Result = msg }); } } }
private async Task ReactionAdded(Cacheable <IUserMessage, ulong> message, ISocketMessageChannel channel, SocketReaction reaction) { try { if (!this.messageEventLookup.ContainsKey(message.Id.ToString())) { return; } // don't mark yourself as attending! if (reaction.UserId == Program.DiscordClient.CurrentUser.Id) { return; } string eventId = this.messageEventLookup[message.Id.ToString()]; Event? evt = await EventsDatabase.Load(eventId); if (evt is null) { // this event was deleted while the notification was up. // we need to detect this case in the 'Update' loop to clear old notifications. // but for now, we'll handle it when someone reacts. this.messageEventLookup.Remove(message.Id.ToString()); await channel.DeleteMessageAsync(message.Value); return; } if (evt.Notify == null) { return; } Event.Instance.Attendee?attendee = evt.GetAttendee(reaction.UserId); if (attendee == null) { attendee = new Event.Instance.Attendee(); attendee.UserId = reaction.UserId.ToString(); evt.Notify.Attendees.Add(attendee); await EventsDatabase.Save(evt); } if (Emotes.IsEmote(reaction.Emote, Emotes.Bell)) { ////ReminderService.SetReminder(evt, attendee); evt.ToggleAttendeeReminder(reaction.UserId); await EventsDatabase.Save(evt); } else { (string display, int index) = GetStatus(reaction.Emote); if (index < 0) { return; } evt.SetAttendeeStatus(reaction.UserId, index); await EventsDatabase.Save(evt); } await evt.Notify.Post(evt); RestUserMessage userMessage = (RestUserMessage)await channel.GetMessageAsync(message.Id); SocketUser user = Program.DiscordClient.GetUser(reaction.UserId); await userMessage.RemoveReactionAsync(reaction.Emote, user); } catch (Exception ex) { Log.Write(ex); } }
// Lists the next several night events to occur on or after the given // date, up to the given limit, optionally of a given type. public static List <Prediction> ListNextEventsFromDate(SDate fromDate, uint limit, Event?onlyType = null) { Utilities.CheckWorldReady(); if (!IsAvailable) { throw new UnavailableException("night events"); } // Logic from StardewValley.Utility.pickFarmEvent // as implemented in Stardew Predictor by MouseyPounds. List <Prediction> predictions = new (); for (int days = fromDate.DaysSinceStart; predictions.Count < limit && days < fromDate.DaysSinceStart + Utilities.MaxHorizon; ++days) { SDate tonight = SDate.FromDaysSinceStart(days); SDate tomorrow = SDate.FromDaysSinceStart(days + 1); // No event if there is a wedding tomorrow. foreach (Farmer farmer in Game1.getAllFarmers()) { Friendship spouse = farmer.GetSpouseFriendship(); if (spouse != null && spouse.WeddingDate == tomorrow.ToWorldDate()) { continue; } } Event @event = Event.None; Random rng = new (((int)Game1.uniqueIDForThisGame / 2) + days + 1); if (days == 29) { @event = Event.Earthquake; } // Ignoring the possibility of a WorldChangeEvent here. else if (rng.NextDouble() < 0.01 && tomorrow.Season != "winter") { @event = Event.Fairy; } else if (rng.NextDouble() < 0.01) { @event = Event.Witch; } else if (rng.NextDouble() < 0.01) { @event = Event.Meteorite; } else if (rng.NextDouble() < 0.005) { @event = Event.StoneOwl; } else if (rng.NextDouble() < 0.008 && tomorrow.Year > 1 && !Utility.doesMasterPlayerHaveMailReceivedButNotMailForTomorrow("Got_Capsule")) { @event = Event.StrangeCapsule; } if (@event == Event.None || (onlyType != null && @event != onlyType)) { continue; } predictions.Add(new Prediction { date = tonight, @event = @event }); } return(predictions); }
/// <summary> /// 获取请求XML /// </summary> /// <returns></returns> private XDocument GetrequestMessaageDoc(string url, string token, RequestMsgType requestType, Event? eventType) { RequestMessageBase requestMessaage = null; switch (requestType) { case RequestMsgType.Text: requestMessaage = new RequestMessageText() { Content = Request.Form["Content"], }; break; case RequestMsgType.Location: requestMessaage = new RequestMessageLocation() { Label = Request.Form["Label"], Location_X = double.Parse(Request.Form["Location_X"]), Location_Y = double.Parse(Request.Form["Location_Y"]), Scale = int.Parse(Request.Form["Scale"]) }; break; case RequestMsgType.Image: requestMessaage = new RequestMessageImage() { PicUrl = Request.Form["PicUrl"], }; break; case RequestMsgType.Voice: requestMessaage = new RequestMessageVoice() { Format = Request.Form["Format"], Recognition = Request.Form["Recognition"], }; break; case RequestMsgType.Video: requestMessaage = new RequestMessageVideo() { MsgId = long.Parse(Request.Form["MsgId"]), ThumbMediaId = Request.Form["ThumbMediaId"], }; break; //case RequestMsgType.Link: // break; case RequestMsgType.Event: if (eventType.HasValue) { RequestMessageEventBase requestMessageEvent = null; switch (eventType.Value) { //case Event.ENTER: // break; case Event.LOCATION: requestMessageEvent = new RequestMessageEvent_Location() { Latitude = long.Parse(Request.Form["Event.Latitude"]), Longitude = long.Parse(Request.Form["Event.Longitude"]), Precision = double.Parse(Request.Form["Event.Precision"]) }; break; case Event.subscribe: requestMessageEvent = new RequestMessageEvent_Subscribe() { EventKey = Request.Form["Event.EventKey"], Ticket = Request.Form["Event.Ticket"] }; break; case Event.unsubscribe: requestMessageEvent = new RequestMessageEvent_Unsubscribe(); break; case Event.CLICK: requestMessageEvent = new RequestMessageEvent_Click() { EventKey = Request.Form["Event.EventKey"] }; break; case Event.scan: requestMessageEvent = new RequestMessageEvent_Scan() { EventKey = Request.Form["Event.EventKey"], Ticket = Request.Form["Event.Ticket"] }; break; case Event.VIEW: requestMessageEvent = new RequestMessageEvent_View() { EventKey = Request.Form["Event.EventKey"] }; break; case Event.MASSSENDJOBFINISH: requestMessageEvent = new RequestMessageEvent_MassSendJobFinish() { FromUserName = "******",//系统指定 ErrorCount = int.Parse(Request.Form["Event.ErrorCount"]), FilterCount = int.Parse(Request.Form["Event.FilterCount"]), SentCount = int.Parse(Request.Form["Event.SentCount"]), Status = Request.Form["Event.Status"], TotalCount = int.Parse(Request.Form["Event.TotalCount"]) }; break; case Event.TEMPLATESENDJOBFINISH: requestMessageEvent = new RequestMessageEvent_TemplateSendJobFinish() { FromUserName = "******",//系统指定 MsgID = long.Parse(Request.Form["Event.MsgID"]), Status = Request.Form["Event.Status"], }; break; case Event.scancode_push: requestMessageEvent = new RequestMessageEvent_Scancode_Push() { FromUserName = "******",//系统指定 EventKey = Request.Form["Event.EventKey"], ScanCodeInfo = new ScanCodeInfo() { ScanResult = Request.Form["Event.ScanResult"], ScanType = Request.Form["Event.ScanType"], } }; break; case Event.scancode_waitmsg: requestMessageEvent = new RequestMessageEvent_Scancode_Waitmsg() { FromUserName = "******",//系统指定 EventKey = Request.Form["Event.EventKey"], ScanCodeInfo = new ScanCodeInfo() { ScanResult = Request.Form["Event.ScanResult"], ScanType = Request.Form["Event.ScanType"], } }; break; case Event.pic_sysphoto: var sysphotoPicMd5Sum = Request.Form["Event.PicMd5Sum"]; PicItem sysphotoPicItem = new PicItem() { item = new Md5Sum() { PicMd5Sum = sysphotoPicMd5Sum } }; List<PicItem> sysphotoPicItems = new List<PicItem>(); sysphotoPicItems.Add(sysphotoPicItem); requestMessageEvent = new RequestMessageEvent_Pic_Sysphoto() { FromUserName = "******",//系统指定 EventKey = Request.Form["Event.EventKey"], SendPicsInfo = new SendPicsInfo() { Count = Request.Form["Event.Count"], PicList = sysphotoPicItems } }; break; case Event.pic_photo_or_album: var photoOrAlbumPicMd5Sum = Request.Form["Event.PicMd5Sum"]; PicItem photoOrAlbumPicItem = new PicItem() { item = new Md5Sum() { PicMd5Sum = photoOrAlbumPicMd5Sum } }; List<PicItem> photoOrAlbumPicItems = new List<PicItem>(); photoOrAlbumPicItems.Add(photoOrAlbumPicItem); requestMessageEvent = new RequestMessageEvent_Pic_Sysphoto() { FromUserName = "******",//系统指定 EventKey = Request.Form["Event.EventKey"], SendPicsInfo = new SendPicsInfo() { Count = Request.Form["Event.Count"], PicList = photoOrAlbumPicItems } }; break; case Event.pic_weixin: var weixinPicMd5Sum = Request.Form["Event.PicMd5Sum"]; PicItem weixinPicItem = new PicItem() { item = new Md5Sum() { PicMd5Sum = weixinPicMd5Sum } }; List<PicItem> weixinPicItems = new List<PicItem>(); weixinPicItems.Add(weixinPicItem); requestMessageEvent = new RequestMessageEvent_Pic_Sysphoto() { FromUserName = "******",//系统指定 EventKey = Request.Form["Event.EventKey"], SendPicsInfo = new SendPicsInfo() { Count = Request.Form["Event.Count"], PicList = weixinPicItems } }; break; case Event.location_select: requestMessageEvent = new RequestMessageEvent_Location_Select() { FromUserName = "******",//系统指定 EventKey = Request.Form["Event.EventKey"], SendLocationInfo = new SendLocationInfo() { Label = Request.Form["Event.Label"], Location_X = Request.Form["Event.Location_X"], Location_Y = Request.Form["Event.Location_Y"], Poiname = Request.Form["Event.Poiname"], Scale = Request.Form["Event.Scale"], } }; break; default: throw new ArgumentOutOfRangeException("eventType"); } requestMessaage = requestMessageEvent; } else { throw new ArgumentOutOfRangeException("eventType"); } break; default: throw new ArgumentOutOfRangeException("requestType"); } requestMessaage.MsgId = long.Parse(Request.Form["MsgId"]); requestMessaage.CreateTime = DateTime.Now; requestMessaage.FromUserName = requestMessaage.FromUserName ?? "FromUserName(OpenId)";//用于区别不同的请求用户 requestMessaage.ToUserName = "******"; return requestMessaage.ConvertEntityToXml(); }
public async Task <IActionResult> RemoveFromEvent(RemoveFromEventDto removeFromEventDto) { IDatabaseContext context = _getDatabaseContext(); User userToRemove = await context.Users.FindAsync(removeFromEventDto.UserId); if (userToRemove == null) { return(BadRequest(RequestStringMessages.UserNotFound)); } Event? @event = await context.Events .Include(e => e.Organizer) .Include(e => e.EventParticipations) .FirstOrDefaultAsync(e => e.Id == removeFromEventDto.EventId); if (@event == null) { return(BadRequest(RequestStringMessages.EventNotFound)); } int currentUserId = HttpContext.GetUserId(); bool changingOtherUser = currentUserId != userToRemove.Id; if (changingOtherUser && (@event.OrganizerId != currentUserId)) { _logger.LogInformation("{0}(): Tried to remove user {1} from then event {2}, which he's not organizing", nameof(RemoveFromEvent), userToRemove.Id, @event.Id); return(BadRequest(RequestStringMessages.OrganizerRequired)); } EventParticipation participation = @event.EventParticipations.FirstOrDefault(e => e.ParticipantId == userToRemove.Id); if (participation == null) { return(BadRequest(RequestStringMessages.UserNotPartOfEvent)); } // Remove event participation context.EventParticipations.Remove(participation); // Remove appointment participations within the event List <AppointmentParticipation> appointmentParticipations = await context.AppointmentParticipations .Where(a => (a.ParticipantId == removeFromEventDto.UserId) && (a.Appointment.EventId == removeFromEventDto.EventId)) .Include(ap => ap.Appointment) .ToListAsync(); List <Appointment> appointmentsWithAcceptedResponse = appointmentParticipations .Where(ap => ap.AppointmentParticipationAnswer == AppointmentParticipationAnswer.Accepted) .Select(ap => ap.Appointment) .ToList(); context.AppointmentParticipations.RemoveRange(appointmentParticipations); await context.SaveChangesAsync(); // Handle notifications if (changingOtherUser) { _auditLogger.LogInformation("{0}(): The organizer removed the user {1} from the event {2}", nameof(RemoveFromEvent), userToRemove.Id, @event.Id); await _notificationService.NotifyOrganizerUpdatedUserInfoAsync(@event, userToRemove, "Der Organisator hat Sie vom Event entfernt."); } else { _auditLogger.LogInformation("{0}(): Left the event {1}", nameof(RemoveFromEvent), @event.Id); } foreach (Appointment appointment in appointmentsWithAcceptedResponse) { await _notificationService.SendLastMinuteChangeIfRequiredAsync(appointment); } return(Ok()); }
public ActionResult GetRequestMessageXml(string url, string token, RequestMsgType requestType, Event? eventType) { var requestMessaageDoc = GetrequestMessaageDoc(url, token, requestType, eventType); return Content(requestMessaageDoc.ToString()); }
public void DebugDrawHUD(SpriteBatch spriteBatch, int y) { foreach (ScriptedEvent scriptedEvent in activeEvents.Where(ev => !ev.IsFinished && ev is ScriptedEvent).Cast <ScriptedEvent>()) { DrawEventTargetTags(spriteBatch, scriptedEvent); } GUI.DrawString(spriteBatch, new Vector2(10, y), "EventManager", Color.White, Color.Black * 0.6f, 0, GUI.SmallFont); GUI.DrawString(spriteBatch, new Vector2(15, y + 20), "Event cooldown: " + (int)Math.Max(eventCoolDown, 0), Color.White, Color.Black * 0.6f, 0, GUI.SmallFont); GUI.DrawString(spriteBatch, new Vector2(15, y + 35), "Current intensity: " + (int)Math.Round(currentIntensity * 100), Color.Lerp(Color.White, GUI.Style.Red, currentIntensity), Color.Black * 0.6f, 0, GUI.SmallFont); GUI.DrawString(spriteBatch, new Vector2(15, y + 50), "Target intensity: " + (int)Math.Round(targetIntensity * 100), Color.Lerp(Color.White, GUI.Style.Red, targetIntensity), Color.Black * 0.6f, 0, GUI.SmallFont); GUI.DrawString(spriteBatch, new Vector2(15, y + 65), "AvgHealth: " + (int)Math.Round(avgCrewHealth * 100), Color.Lerp(GUI.Style.Red, GUI.Style.Green, avgCrewHealth), Color.Black * 0.6f, 0, GUI.SmallFont); GUI.DrawString(spriteBatch, new Vector2(15, y + 80), "AvgHullIntegrity: " + (int)Math.Round(avgHullIntegrity * 100), Color.Lerp(GUI.Style.Red, GUI.Style.Green, avgHullIntegrity), Color.Black * 0.6f, 0, GUI.SmallFont); GUI.DrawString(spriteBatch, new Vector2(15, y + 95), "FloodingAmount: " + (int)Math.Round(floodingAmount * 100), Color.Lerp(GUI.Style.Green, GUI.Style.Red, floodingAmount), Color.Black * 0.6f, 0, GUI.SmallFont); GUI.DrawString(spriteBatch, new Vector2(15, y + 110), "FireAmount: " + (int)Math.Round(fireAmount * 100), Color.Lerp(GUI.Style.Green, GUI.Style.Red, fireAmount), Color.Black * 0.6f, 0, GUI.SmallFont); GUI.DrawString(spriteBatch, new Vector2(15, y + 125), "EnemyDanger: " + (int)Math.Round(enemyDanger * 100), Color.Lerp(GUI.Style.Green, GUI.Style.Red, enemyDanger), Color.Black * 0.6f, 0, GUI.SmallFont); #if DEBUG if (PlayerInput.KeyDown(Microsoft.Xna.Framework.Input.Keys.LeftAlt) && PlayerInput.KeyHit(Microsoft.Xna.Framework.Input.Keys.T)) { eventCoolDown = 1.0f; } #endif if (intensityGraph == null) { intensityGraph = new Graph(); targetIntensityGraph = new Graph(); } intensityGraphUpdateInterval = 5.0f; if (Timing.TotalTime > lastIntensityUpdate + intensityGraphUpdateInterval) { intensityGraph.Update(currentIntensity); targetIntensityGraph.Update(targetIntensity); lastIntensityUpdate = (float)Timing.TotalTime; } Rectangle graphRect = new Rectangle(15, y + 150, 150, 50); GUI.DrawRectangle(spriteBatch, graphRect, Color.Black * 0.5f, true); intensityGraph.Draw(spriteBatch, graphRect, 1.0f, 0.0f, Color.Lerp(Color.White, GUI.Style.Red, currentIntensity)); targetIntensityGraph.Draw(spriteBatch, graphRect, 1.0f, 0.0f, Color.Lerp(Color.White, GUI.Style.Red, targetIntensity) * 0.5f); GUI.DrawLine(spriteBatch, new Vector2(graphRect.Right, graphRect.Y + graphRect.Height * (1.0f - eventThreshold)), new Vector2(graphRect.Right + 5, graphRect.Y + graphRect.Height * (1.0f - eventThreshold)), Color.Orange, 0, 1); y = graphRect.Bottom + 20; int x = graphRect.X; if (isCrewAway && crewAwayDuration < settings.FreezeDurationWhenCrewAway) { GUI.DrawString(spriteBatch, new Vector2(x, y), "Events frozen (crew away from sub): " + ToolBox.SecondsToReadableTime(settings.FreezeDurationWhenCrewAway - crewAwayDuration), Color.LightGreen * 0.8f, null, 0, GUI.SmallFont); y += 15; } else if (crewAwayResetTimer > 0.0f) { GUI.DrawString(spriteBatch, new Vector2(x, y), "Events frozen (crew just returned to the sub): " + ToolBox.SecondsToReadableTime(crewAwayResetTimer), Color.LightGreen * 0.8f, null, 0, GUI.SmallFont); y += 15; } else if (eventCoolDown > 0.0f) { GUI.DrawString(spriteBatch, new Vector2(x, y), "Event cooldown active: " + ToolBox.SecondsToReadableTime(eventCoolDown), Color.LightGreen * 0.8f, null, 0, GUI.SmallFont); y += 15; } else if (currentIntensity > eventThreshold) { GUI.DrawString(spriteBatch, new Vector2(x, y), "Intensity too high for new events: " + (int)(currentIntensity * 100) + "%/" + (int)(eventThreshold * 100) + "%", Color.LightGreen * 0.8f, null, 0, GUI.SmallFont); y += 15; } foreach (EventSet eventSet in pendingEventSets) { if (Submarine.MainSub == null) { break; } GUI.DrawString(spriteBatch, new Vector2(x, y), "New event (ID " + eventSet.DebugIdentifier + ") after: ", Color.Orange * 0.8f, null, 0, GUI.SmallFont); y += 12; if (eventSet.PerCave) { GUI.DrawString(spriteBatch, new Vector2(x, y), " submarine near cave", Color.Orange * 0.8f, null, 0, GUI.SmallFont); y += 12; } if (eventSet.PerWreck) { GUI.DrawString(spriteBatch, new Vector2(x, y), " submarine near the wreck", Color.Orange * 0.8f, null, 0, GUI.SmallFont); y += 12; } if (eventSet.PerRuin) { GUI.DrawString(spriteBatch, new Vector2(x, y), " submarine near the ruins", Color.Orange * 0.8f, null, 0, GUI.SmallFont); y += 12; } if (roundDuration < eventSet.MinMissionTime) { GUI.DrawString(spriteBatch, new Vector2(x, y), " " + (int)(eventSet.MinDistanceTraveled * 100.0f) + "% travelled (current: " + (int)(distanceTraveled * 100.0f) + " %)", ((Submarine.MainSub == null || distanceTraveled < eventSet.MinDistanceTraveled) ? Color.Lerp(GUI.Style.Yellow, GUI.Style.Red, eventSet.MinDistanceTraveled - distanceTraveled) : GUI.Style.Green) * 0.8f, null, 0, GUI.SmallFont); y += 12; } if (CurrentIntensity < eventSet.MinIntensity || CurrentIntensity > eventSet.MaxIntensity) { GUI.DrawString(spriteBatch, new Vector2(x, y), " intensity between " + ((int)eventSet.MinIntensity) + " and " + ((int)eventSet.MaxIntensity), Color.Orange * 0.8f, null, 0, GUI.SmallFont); y += 12; } if (roundDuration < eventSet.MinMissionTime) { GUI.DrawString(spriteBatch, new Vector2(x, y), " " + (int)(eventSet.MinMissionTime - roundDuration) + " s", Color.Lerp(GUI.Style.Yellow, GUI.Style.Red, (eventSet.MinMissionTime - roundDuration)), null, 0, GUI.SmallFont); } y += 15; if (y > GameMain.GraphicsHeight * 0.9f) { y = graphRect.Bottom + 35; x += 250; } } GUI.DrawString(spriteBatch, new Vector2(x, y), "Current events: ", Color.White * 0.9f, null, 0, GUI.SmallFont); y += 15; foreach (Event ev in activeEvents.Where(ev => !ev.IsFinished || PlayerInput.IsShiftDown())) { GUI.DrawString(spriteBatch, new Vector2(x + 5, y), ev.ToString(), (!ev.IsFinished ? Color.White : Color.Red) * 0.8f, null, 0, GUI.SmallFont); Rectangle rect = new Rectangle(new Point(x + 5, y), GUI.SmallFont.MeasureString(ev.ToString()).ToPoint()); Rectangle outlineRect = new Rectangle(rect.Location, rect.Size); outlineRect.Inflate(4, 4); if (PinnedEvent == ev) { GUI.DrawRectangle(spriteBatch, outlineRect, Color.White); } if (rect.Contains(PlayerInput.MousePosition)) { GUI.MouseCursor = CursorState.Hand; GUI.DrawRectangle(spriteBatch, outlineRect, Color.White); if (ev != PinnedEvent) { DrawEvent(spriteBatch, ev, rect); } else if (PlayerInput.SecondaryMouseButtonHeld() || PlayerInput.SecondaryMouseButtonDown()) { PinnedEvent = null; } if (PlayerInput.PrimaryMouseButtonHeld() || PlayerInput.PrimaryMouseButtonDown()) { PinnedEvent = ev; } } y += 18; if (y > GameMain.GraphicsHeight * 0.9f) { y = graphRect.Bottom + 35; x += 250; } } }