private async Task SetRolePermissions(ChannelContext channel, OverwritePermissions permissions, SocketRole role) { var channelSocket = (IGuildChannel)await this._discordClientChannelsService.GetChannel(channel.Id); if (channelSocket == null) { Log.Warning("{channel} after casting to IGuildChannel is null", channel.Name); return; } if (channelSocket.PermissionOverwrites.Any(x => x.TargetId == role.Id)) { Log.Warning("Channel {channel} has already assigned this role {roleName}", channel.Name, role.Name); return; } await channelSocket.AddPermissionOverwriteAsync(role, permissions); Log.Information("{roleName} set for {channel}", role.Name, channel.Name); }
private void BeginOpenChannel(ChannelContext channelContext) { Contract.Assert(channelContext != null); Contract.Assert(channelContext.Channel != null); try { IAsyncResult result = channelContext.Channel.BeginOpen(_onOpenChannelComplete, channelContext); if (result.CompletedSynchronously) { OpenChannelComplete(result); } } catch (Exception e) { FaultTask(channelContext.Server._openTaskCompletionSource, e); } }
private void UpdateChannelGroupSelection(IChannel channel) { if (channel == null) { return; } lock (CurrentGroupChannels.SyncRoot) foreach (ChannelProgramListItem currentGroupChannel in CurrentGroupChannels) { currentGroupChannel.Selected = ChannelContext.IsSameChannel(currentGroupChannel.Channel, channel); } CurrentGroupChannels.FireChange(); SetCurrentChannelGroup(); SetCurrentChannel(); }
private static void CloseChannelComplete(IAsyncResult result) { ChannelContext channelContext = (ChannelContext)result.AsyncState; Contract.Assert(channelContext != null); try { channelContext.Channel.EndClose(result); } catch { } finally { CloseNextChannel(channelContext.Server); } }
private async Task RunChat() { var roomName = "test"; await Task.Delay(1000); await Console.Out.WriteLineAsync("\nPlease enter a room name, then press Enter.").ConfigureAwait(false); var text = (await Console.In.ReadLineAsync().ConfigureAwait(false)).Trim(); if (text.Length > 0) { roomName = text; } var memberNames = new List <string>(); while (true) { await Console.Out.WriteLineAsync("Enter a member name, then press Enter. Empty name will end this step."); text = (await Console.In.ReadLineAsync().ConfigureAwait(false)).Trim(); if (text.Length == 0) { if (memberNames.Count > 0) { break; } } else if (!memberNames.Contains(text)) { memberNames.Add(text); } } await memberNames.ForEachAsync(async mn => { using (var ctx = new ChannelContext(_channel)) { await RunChat(ctx, roomName, mn).ConfigureAwait(false); } }); }
static async Task RunChat(ChannelContext ctx) { // create room var client = ctx.CreateClient <IChatRoomService>(); var room = await client.CreateNewRoom("test", "A"); var waiter = (await client.OnJoin()).ResponseStream.ForEachAsync(xs => { Console.WriteLine(xs); }); await client.Join(room.Id, "B"); //var result = await await client.SendMessage(room.Id, "foo bar baz"); // Console.WriteLine("Send success:" + result); await waiter; }
private void BeginReceiveRequestContext(ChannelContext context) { Contract.Assert(context != null); if (context.Channel.State != CommunicationState.Opened) { return; } IAsyncResult result = BeginTryReceiveRequestContext( context, _onReceiveRequestContextComplete ); if (result.CompletedSynchronously) { ReceiveRequestContextComplete(result); } }
/// <summary> /// Tries to find the current channel in the current group and makes sure it will be inside the visible area. /// </summary> private void SetInitialViewOffset() { int currentChannelIndex = 0; foreach (var channelsProgram in ChannelsPrograms.OfType <ChannelProgramListItem>()) { if (ChannelContext.IsSameChannel(channelsProgram.Channel, ChannelContext.Instance.Channels.Current)) { if (currentChannelIndex >= _numberOfRows) { _channelViewOffset = currentChannelIndex - _numberOfRows + 1; } break; } currentChannelIndex++; } _lastFocusedRow = currentChannelIndex - _channelViewOffset; SetFocusTime(DateTime.Now); }
public static async Task GetAndSaveEpg(string url, bool saveList = true) { try { List <ChProgram> list; using (var httpClient = new System.Net.Http.HttpClient()) { var stream = await httpClient.GetStreamAsync(url); StreamReader reader = new StreamReader(stream); list = LoadStream(reader).ToList(); } if (list == null || list.Count == 0) { throw new Exception("Lista invalida"); } var lista = new ListContainer { Type = ListType.EPG, Url = url }; using (var db = new ChannelContext()) { var all = from c in db.Programs select c; db.Programs.RemoveRange(all); db.Programs.AddRange(list); if (saveList) { db.ListContainer.Add(lista); } db.SaveChanges(); } } catch (Exception ex) { throw ex; } }
protected async Task UpdateChannels() { UpdateGuiProperties(); bool isOneSelected = false; lock (_channelList.SyncRoot) { _channelList.Clear(); foreach (IChannel channel in ChannelContext.Instance.Channels) { // Use local variable, otherwise delegate argument is not fixed IChannel currentChannel = channel; bool isCurrentSelected = ChannelContext.IsSameChannel(currentChannel, _lastTunedChannel); isOneSelected |= isCurrentSelected; ChannelProgramListItem item = new ChannelProgramListItem(currentChannel, null) { Programs = new ItemsList { GetNoProgramPlaceholder(channel.ChannelId), GetNoProgramPlaceholder(channel.ChannelId) }, Command = new AsyncMethodDelegateCommand(() => Tune(currentChannel)), Selected = isCurrentSelected }; item.AdditionalProperties["CHANNEL"] = channel; _channelList.Add(item); } } // Adjust channel list position ChannelContext.Instance.Channels.MoveTo(c => ChannelContext.IsSameChannel(c, _lastTunedChannel)); // If the current watched channel is not part of the channel group, set the "selected" property to first list item to make sure focus will be set to the list view if (!isOneSelected && _channelList.Count > 0) { _channelList.First().Selected = true; } // Load programs asynchronously, this increases performance of list building await GetNowAndNextProgramsList_Async(); CurrentGroupChannels.FireChange(); }
private static void BeginCloseChannel(ChannelContext channelContext) { Contract.Assert(channelContext != null); try { IAsyncResult result = channelContext.Channel.BeginClose( _onCloseChannelComplete, channelContext ); if (result.CompletedSynchronously) { CloseChannelComplete(result); } } catch { CloseNextChannel(channelContext.Server); } }
static async Task TestHeartbeat(Channel channel) { await channel.ConnectAsync(); Console.WriteLine("Client -> Server, " + await new PingClient(channel).Ping() + "ms"); Console.WriteLine("Client -> Server, " + await new PingClient(channel).Ping() + "ms"); var cc = new ChannelContext(channel); cc.RegisterDisconnectedAction(() => { Console.WriteLine("disconnected detected!"); }); await cc.WaitConnectComplete(); Console.ReadLine(); //cc.Dispose(); await new PingClient(channel).Ping(); Console.ReadLine(); }
private async Task <HttpResponseMessage> SendAsync( ChannelContext channelContext, RequestContext requestContext ) { HttpRequestMessage request = null; try { request = CreateHttpRequestMessage(requestContext); } catch { return(new HttpResponseMessage(HttpStatusCode.BadRequest)); } // Submit request up the stack try { HttpResponseMessage response = await channelContext.Server.SendAsync( request, channelContext.Server._cancellationTokenSource.Token ); if (response == null) { response = request.CreateResponse(HttpStatusCode.InternalServerError); } return(response); } catch (OperationCanceledException operationCanceledException) { return(request.CreateErrorResponse( HttpStatusCode.ServiceUnavailable, SRResources.RequestCancelled, operationCanceledException )); } }
public async Task ScanChannelHistory(DiscordServerContext server, ChannelContext channel, DateTime?startTime = null) // startTime ->->-> now { const int LIMIT = 20000; // low limit to use props of startTime optimization if (channel.Name.Contains("logs")) { return; } Log.Information("Reading channel {channel} ", channel.ToJson()); startTime ??= DateTime.UnixEpoch; var messages = await this.ReadMessagesAsync(server, channel, limit : 1).ToListAsync(); if (!messages.Any() || this.LastMessageIsOlderThanStartTime(messages, startTime.Value)) { Log.Information("Channel: {channel} has no new messages", channel.Name); return; } var lastMessageId = 0UL; do { messages = await this.ReadMessagesAsync(server, channel, LIMIT, lastMessageId).ToListAsync(); if (!messages.Any()) { break; } lastMessageId = messages.Last().Id; await this.SaveMessages(messages, channel.Id); if (this.LastMessageIsOlderThanStartTime(messages, startTime.Value)) { break; } } while (messages.Count == LIMIT); Log.Information("Channel: {channel} read and saved", channel.Name); }
public void Tune(IChannel channel) { // Specical case of this model, which is also used as normal backing model for OSD, where no WorkflowManager action was performed. if (!_isInitialized) { InitModel(); } // Avoid subsequent tune requests to same channel, it will only cause delays. if (ChannelContext.IsSameChannel(channel, _tvHandler.GetChannel(SlotIndex))) { return; } // Invoke event handler before pausing to avoid flashing of pause symbol SlotPlayer?.OnBeginZap?.Invoke(this, EventArgs.Empty); SlotPlayer?.Pause(); // Set the current index of the tuned channel if (ChannelContext.Instance.Channels.MoveTo(c => ChannelContext.IsSameChannel(c, channel))) { _zapChannelIndex = ChannelContext.Instance.Channels.CurrentIndex; // Needs to be the same to start zapping from current offset } else { _zapChannelIndex = 0; } BeginZap(); if (_tvHandler.StartTimeshift(SlotIndex, channel)) { _lastTunedChannel = channel; EndZap(); Update(); UpdateChannelGroupSelection(channel); } // Notify end of zapping SlotPlayer?.OnEndZap?.Invoke(this, EventArgs.Empty); }
private async Task <int> InvokeListenersAsync <TListener, TEnvelope>( TEnvelope envelope, ISenderChannel channel, CancellationToken cancellationToken) where TEnvelope : Envelope, new() where TListener : IEnvelopeListener <TEnvelope> { using var scope = _serviceScopeFactory.CreateScope(); var channelContext = new ChannelContext(channel, _channelProvider); var contextProvider = scope.ServiceProvider.GetRequiredService <ChannelContextProvider>(); contextProvider.SetContext(channelContext); try { var listeners = scope .ServiceProvider .GetServices <TListener>() ?.Where(l => l.Filter(envelope)) .ToArray(); if (listeners != null && listeners.Length > 0) { await Task.WhenAll( listeners .Select(l => Task.Run(() => l.OnEnvelopeAsync(envelope, cancellationToken), cancellationToken))); return(listeners.Length); } } catch (Exception ex) { _logger.LogError(ex, "{EnvelopeType} processing failed", typeof(TEnvelope).Name); } return(0); }
public void Tune(IChannel channel) { // Avoid subsequent tune requests to same channel, it will only cause delays. if (ChannelContext.IsSameChannel(channel, _lastTunedChannel)) { return; } // Specical case of this model, which is also used as normal backing model for OSD, where no WorkflowManager action was performed. if (!_isInitialized) { InitModel(); } if (SlotPlayer != null) { SlotPlayer.Pause(); } // Set the current index of the tuned channel if (ChannelContext.Instance.Channels.MoveTo(c => ChannelContext.IsSameChannel(c, channel))) { _zapChannelIndex = ChannelContext.Instance.Channels.CurrentIndex; // Needs to be the same to start zapping from current offset } else { _zapChannelIndex = 0; } BeginZap(); if (_tvHandler.StartTimeshift(SlotIndex, channel)) { _lastTunedChannel = channel; EndZap(); Update(); UpdateChannelGroupSelection(channel); } }
private void ReceiveRequestContextComplete(IAsyncResult result) { Contract.Assert(result != null); ChannelContext channelContext = (ChannelContext)result.AsyncState; Contract.Assert(channelContext != null); System.ServiceModel.Channels.RequestContext requestContext; if (EndTryReceiveRequestContext(result, out requestContext)) { if (requestContext != null) { Interlocked.Increment(ref _requestsOutstanding); if (TryIncreaseWindowSize()) { // Spin off an additional BeginReceiveRequest to increase the window size by 1 BeginReceiveRequestContext(channelContext); } ProcessRequestContext(channelContext, requestContext); } } }
internal static ChannelContext GetNextContext(NettyNetwork network) { var contexts = GetContexts(network.Id).OrderBy(c => c.ChannelId).ToList(); if (!contexts.Any()) { return(null); } ChannelContext context = null; while (true) { if (contexts.Count == 0) { break; } var index = IdCreator.CreateNextId() % contexts.Count; context = contexts[index]; if (context.Handler.IsClient) { throw new NotSupportedException("This method does not supported a client network search, you can using GetSingleContext."); } if (context.ChannelHanderContext.Channel.Active) { break; } else { context = null; contexts.RemoveAt(index); } } return(context); }
private static IAsyncResult BeginTryReceiveRequestContext( ChannelContext channelContext, AsyncCallback callback ) { Contract.Assert(channelContext != null); Contract.Assert(callback != null); try { return(channelContext.Channel.BeginTryReceiveRequest( _receiveTimeout, callback, channelContext )); } catch (CommunicationObjectAbortedException) { return(new CompletedAsyncResult <bool>(true, callback, channelContext)); } catch (CommunicationObjectFaultedException) { return(new CompletedAsyncResult <bool>(true, callback, channelContext)); } catch (CommunicationException) { return(new CompletedAsyncResult <bool>(false, callback, channelContext)); } catch (TimeoutException) { return(new CompletedAsyncResult <bool>(false, callback, channelContext)); } catch { return(new CompletedAsyncResult <bool>(false, callback, channelContext)); } }
private void SaveCurrentItemCategory() { var item = (Channel)grd.SelectedItem; if (item != null) { if (item.Category == null) { item.Category = 1; } else { item.Category = null; } using (var db = new ChannelContext()) { db.Channels.Update(item); db.SaveChanges(); } showMessage(string.Format(resouces.GetString("fav_added"), item.Title), 2000); } }
private void BeginNextRequest(ChannelContext context) { if (TryDecreaseWindowSize()) { // Decrease the window size by 1 by avoiding calling BeginReceiveRequest return; } BeginReceiveRequestContext(context); }
private void BeginReceiveRequestContext(ChannelContext context) { Contract.Assert(context != null); if (context.Channel.State != CommunicationState.Opened) { return; } IAsyncResult result = BeginTryReceiveRequestContext(context, _onReceiveRequestContextComplete); if (result.CompletedSynchronously) { ReceiveRequestContextComplete(result); } }
private static IAsyncResult BeginTryReceiveRequestContext(ChannelContext channelContext, AsyncCallback callback) { Contract.Assert(channelContext != null); Contract.Assert(callback != null); try { return channelContext.Channel.BeginTryReceiveRequest(_receiveTimeout, callback, channelContext); } catch (CommunicationObjectAbortedException) { return new CompletedAsyncResult<bool>(true, callback, channelContext); } catch (CommunicationObjectFaultedException) { return new CompletedAsyncResult<bool>(true, callback, channelContext); } catch (CommunicationException) { return new CompletedAsyncResult<bool>(false, callback, channelContext); } catch (TimeoutException) { return new CompletedAsyncResult<bool>(false, callback, channelContext); } catch { return new CompletedAsyncResult<bool>(false, callback, channelContext); } }
public Repository(ChannelContext context) { this.context = context; }
void MacroRun(ChannelContext channel) { bool deferWait = channel.deferWait; for (;;) { var macroPtrOff = (int)(channel.macroOffset + 4 * channel.macroStep - _resource.mdatOffset); ++channel.macroStep; switch (_resource.mdatAlloc[macroPtrOff]) { case 0x00: // Reset + DMA Off. Parameters: deferWait, addset, vol ClearEffects(channel); // same as 0x13 // TODO: implement PArameters DisableChannel(channel.paulaChannel); channel.deferWait = deferWait = (_resource.mdatAlloc[macroPtrOff + 1] != 0); if (deferWait) { // if set, then we expect a DMA On in the same tick. channel.period = 4; //Paula::setChannelPeriod(channel.paulaChannel, channel.period); SetChannelSampleLen(channel.paulaChannel, 1); // in this state we then need to allow some commands that normally // would halt the macroprogamm to continue instead. // those commands are: Wait, WaitDMA, AddPrevNote, AddNote, SetNote, <unknown Cmd> // DMA On is affected aswell // TODO remember time disabled, remember pending dmaoff?. } if (_resource.mdatAlloc[macroPtrOff + 2] != 0 || _resource.mdatAlloc[macroPtrOff + 3] != 0) { channel.volume = (sbyte)((_resource.mdatAlloc[macroPtrOff + 2] != 0 ? 0 : channel.relVol * 3) + _resource.mdatAlloc[macroPtrOff + 3]); SetChannelVolume(channel.paulaChannel, (byte)channel.volume); } continue; // FT case 0x13: // DMA Off. Parameters: deferWait, addset, vol // TODO: implement PArameters DisableChannel(channel.paulaChannel); channel.deferWait = deferWait = (_resource.mdatAlloc[macroPtrOff + 1] != 0); if (deferWait) { // if set, then we expect a DMA On in the same tick. channel.period = 4; //Paula::setChannelPeriod(channel.paulaChannel, channel.period); SetChannelSampleLen(channel.paulaChannel, 1); // in this state we then need to allow some commands that normally // would halt the macroprogamm to continue instead. // those commands are: Wait, WaitDMA, AddPrevNote, AddNote, SetNote, <unknown Cmd> // DMA On is affected aswell // TODO remember time disabled, remember pending dmaoff?. } if (_resource.mdatAlloc[macroPtrOff + 2] != 0 || _resource.mdatAlloc[macroPtrOff + 3] != 0) { channel.volume = (sbyte)((_resource.mdatAlloc[macroPtrOff + 2] != 0 ? 0 : channel.relVol * 3) + _resource.mdatAlloc[macroPtrOff + 3]); SetChannelVolume(channel.paulaChannel, (byte)channel.volume); } continue; case 0x01: // DMA On // TODO: Parameter macroPtr[1] - en-/disable effects channel.dmaIntCount = 0; if (deferWait) { // TODO // there is actually a small delay in the player, but I think that // only allows to clear DMA-State on real Hardware } SetChannelPeriod(channel.paulaChannel, (short)channel.period); EnableChannel(channel.paulaChannel); channel.deferWait = deferWait = false; continue; case 0x02: // Set Beginn. Parameters: SampleOffset(L) channel.addBeginLength = 0; channel.sampleStart = _resource.mdatAlloc.ToInt32BigEndian(macroPtrOff) & 0xFFFFFF; SetChannelSampleStart(channel.paulaChannel, GetSamplePtr(channel.sampleStart)); continue; case 0x03: // SetLength. Parameters: SampleLength(W) channel.sampleLen = _resource.mdatAlloc.ToUInt16BigEndian(macroPtrOff + 2); SetChannelSampleLen(channel.paulaChannel, channel.sampleLen); continue; case 0x04: // Wait. Parameters: Ticks to wait(W). // TODO: some unknown Parameter? (macroPtr[1] & 1) channel.macroWait = _resource.mdatAlloc.ToUInt16BigEndian(macroPtrOff + 2); break; case 0x10: // Loop Key Up. Parameters: Loopcount, MacroStep(W) if (channel.keyUp) continue; // same as 0x05 if (channel.macroLoopCount != 0) { if (channel.macroLoopCount == 0xFF) channel.macroLoopCount = _resource.mdatAlloc[macroPtrOff + 1]; channel.macroStep = _resource.mdatAlloc.ToUInt16BigEndian(macroPtrOff + 2); } --channel.macroLoopCount; continue; // FT case 0x05: // Loop. Parameters: Loopcount, MacroStep(W) if (channel.macroLoopCount != 0) { if (channel.macroLoopCount == 0xFF) channel.macroLoopCount = _resource.mdatAlloc[macroPtrOff + 1]; channel.macroStep = _resource.mdatAlloc.ToUInt16BigEndian(macroPtrOff + 2); } --channel.macroLoopCount; continue; case 0x06: // Jump. Parameters: MacroIndex, MacroStep(W) // channel.macroIndex = macroPtr[1] & (kMaxMacroOffsets - 1); channel.macroOffset = _resource.macroOffset[_resource.mdatAlloc[macroPtrOff + 1] & (MaxMacroOffsets - 1)]; channel.macroStep = _resource.mdatAlloc.ToUInt16BigEndian(macroPtrOff + 2); channel.macroLoopCount = 0xFF; continue; case 0x07: // Stop Macro channel.macroRun = false; --channel.macroStep; return; case 0x08: // AddNote. Parameters: Note, Finetune(W) SetNoteMacro(channel, channel.note + _resource.mdatAlloc[macroPtrOff + 1], _resource.mdatAlloc.ToUInt16BigEndian(macroPtrOff + 2)); break; case 0x09: // SetNote. Parameters: Note, Finetune(W) SetNoteMacro(channel, _resource.mdatAlloc[macroPtrOff + 1], _resource.mdatAlloc.ToUInt16BigEndian(macroPtrOff + 2)); break; case 0x0A: // Clear Effects ClearEffects(channel); continue; case 0x0B: // Portamento. Parameters: count, speed channel.portaSkip = _resource.mdatAlloc[macroPtrOff + 1]; channel.portaCount = 1; // if porta is already running, then keep using old value if (channel.portaDelta == 0) channel.portaValue = channel.refPeriod; channel.portaDelta = _resource.mdatAlloc.ToUInt16BigEndian(macroPtrOff + 2); continue; case 0x0C: // Vibrato. Parameters: Speed, intensity channel.vibLength = _resource.mdatAlloc[macroPtrOff + 1]; channel.vibCount = (byte)(_resource.mdatAlloc[macroPtrOff + 1] / 2); channel.vibDelta = (sbyte)_resource.mdatAlloc[macroPtrOff + 3]; // TODO: Perhaps a bug, vibValue could be left uninitialized if (channel.portaDelta == 0) { channel.period = channel.refPeriod; channel.vibValue = 0; } continue; case 0x0D: // Add Volume. Parameters: note, addNoteFlag, volume if (_resource.mdatAlloc[macroPtrOff + 2] == 0xFE) { SetNoteMacro(channel, channel.note + _resource.mdatAlloc[macroPtrOff + 1], 0); } channel.volume = (sbyte)(channel.relVol * 3 + _resource.mdatAlloc[macroPtrOff + 3]); continue; case 0x0E: // Set Volume. Parameters: note, addNoteFlag, volume if (_resource.mdatAlloc[macroPtrOff + 2] == 0xFE) { SetNoteMacro(channel, channel.note + _resource.mdatAlloc[macroPtrOff + 1], 0); } channel.volume = (sbyte)_resource.mdatAlloc[macroPtrOff + 3]; continue; case 0x0F: // Envelope. Parameters: speed, count, endvol channel.envDelta = _resource.mdatAlloc[macroPtrOff + 1]; channel.envCount = channel.envSkip = _resource.mdatAlloc[macroPtrOff + 2]; channel.envEndVolume = (sbyte)_resource.mdatAlloc[macroPtrOff + 3]; continue; case 0x11: // Add Beginn. Parameters: times, Offset(W) channel.addBeginLength = channel.addBeginCount = _resource.mdatAlloc[macroPtrOff + 1]; channel.addBeginDelta = _resource.mdatAlloc.ToInt16BigEndian(macroPtrOff + 2); channel.sampleStart += channel.addBeginDelta; SetChannelSampleStart(channel.paulaChannel, GetSamplePtr(channel.sampleStart)); continue; case 0x12: // Add Length. Parameters: added Length(W) channel.sampleLen = (ushort)(channel.sampleLen + _resource.mdatAlloc.ToInt16BigEndian(macroPtrOff + 2)); SetChannelSampleLen(channel.paulaChannel, channel.sampleLen); continue; case 0x14: // Wait key up. Parameters: wait cycles if (channel.keyUp || channel.macroLoopCount == 0) { channel.macroLoopCount = 0xFF; continue; } else if (channel.macroLoopCount == 0xFF) channel.macroLoopCount = _resource.mdatAlloc[macroPtrOff + 3]; --channel.macroLoopCount; --channel.macroStep; return; case 0x15: // Subroutine. Parameters: MacroIndex, Macrostep(W) channel.macroReturnOffset = channel.macroOffset; channel.macroReturnStep = channel.macroStep; channel.macroOffset = (_resource.macroOffset[_resource.mdatAlloc[macroPtrOff + 1] & (MaxMacroOffsets - 1)]); channel.macroStep = _resource.mdatAlloc.ToUInt16BigEndian(macroPtrOff + 2); // TODO: MI does some weird stuff there. Figure out which varioables need to be set continue; case 0x16: // Return from Sub. channel.macroOffset = channel.macroReturnOffset; channel.macroStep = channel.macroReturnStep; continue; case 0x17: // Set Period. Parameters: Period(W) channel.refPeriod = _resource.mdatAlloc.ToUInt16BigEndian(macroPtrOff + 2); if (channel.portaDelta == 0) { channel.period = channel.refPeriod; //Paula::setChannelPeriod(channel.paulaChannel, channel.period); } continue; case 0x18: { // Sampleloop. Parameters: Offset from Samplestart(W) // TODO: MI loads 24 bit, but thats useless? ushort temp = /* ((int8)macroPtr[1] << 16) | */ _resource.mdatAlloc.ToUInt16BigEndian(macroPtrOff + 2); if (_resource.mdatAlloc[macroPtrOff + 1] != 0 || ((temp & 1) != 0)) Debug.WriteLine("Tfmx: Problematic value for sampleloop: {0:X6}", (_resource.mdatAlloc[macroPtrOff + 1] << 16) | temp); channel.sampleStart += temp & 0xFFFE; channel.sampleLen -= (ushort)(temp / 2) /* & 0x7FFF */; SetChannelSampleStart(channel.paulaChannel, GetSamplePtr(channel.sampleStart)); SetChannelSampleLen(channel.paulaChannel, channel.sampleLen); continue; } case 0x19: // Set One-Shot Sample channel.addBeginLength = 0; channel.sampleStart = 0; channel.sampleLen = 1; SetChannelSampleStart(channel.paulaChannel, GetSamplePtr(0)); SetChannelSampleLen(channel.paulaChannel, 1); continue; case 0x1A: // Wait on DMA. Parameters: Cycles-1(W) to wait channel.dmaIntCount = (ushort)(_resource.mdatAlloc.ToUInt16BigEndian(macroPtrOff + 2) + 1); channel.macroRun = false; SetChannelDmaCount(channel.paulaChannel); break; /* case 0x1B: // Random play. Parameters: macro/speed/mode warnMacroUnimplemented(macroPtr, 0); continue;*/ case 0x1C: // Branch on Note. Parameters: note/macrostep(W) if (channel.note > _resource.mdatAlloc[macroPtrOff + 1]) channel.macroStep = _resource.mdatAlloc.ToUInt16BigEndian(macroPtrOff + 2); continue; case 0x1D: // Branch on Volume. Parameters: volume/macrostep(W) if (channel.volume > _resource.mdatAlloc[macroPtrOff + 1]) channel.macroStep = _resource.mdatAlloc.ToUInt16BigEndian(macroPtrOff + 2); continue; /* case 0x1E: // Addvol+note. Parameters: note/CONST./volume warnMacroUnimplemented(macroPtr, 0); continue;*/ case 0x1F: // AddPrevNote. Parameters: Note, Finetune(W) SetNoteMacro(channel, channel.prevNote + _resource.mdatAlloc[macroPtrOff + 1], _resource.mdatAlloc.ToUInt16BigEndian(macroPtrOff + 2)); break; case 0x20: // Signal. Parameters: signalnumber, value(W) if (_playerCtx.signal != null) _playerCtx.signal(_resource.mdatAlloc[macroPtrOff + 1], _resource.mdatAlloc.ToUInt16BigEndian(macroPtrOff + 2)); continue; case 0x21: // Play macro. Parameters: macro, chan, detune NoteCommand(channel.note, _resource.mdatAlloc[macroPtrOff + 1], (byte)((channel.relVol << 4) | _resource.mdatAlloc[macroPtrOff + 2]), _resource.mdatAlloc[macroPtrOff + 3]); continue; // 0x22 - 0x29 are used by Gem`X // 0x30 - 0x34 are used by Carribean Disaster default: Debug.WriteLine("Tfmx: Macro {0:XX} not supported", _resource.mdatAlloc[macroPtrOff]); break; } if (!deferWait) return; } }
public ChannelService(ChannelContext context, TagContext tagContext, UserManager <LoginUser> userManager) { _context = context; _tagContext = tagContext; _userManager = userManager; }
private static void ProcessRequestContext(ChannelContext channelContext, System.ServiceModel.Channels.RequestContext requestContext) { Contract.Assert(channelContext != null); Contract.Assert(requestContext != null); // Get the HTTP request from the WCF Message HttpRequestMessage request = requestContext.RequestMessage.ToHttpRequestMessage(); if (request == null) { throw Error.InvalidOperation(SRResources.HttpMessageHandlerInvalidMessage, requestContext.RequestMessage.GetType()); } // create principal information and add it the request for the windows auth case SecurityMessageProperty property; if (request.Properties.TryGetValue <SecurityMessageProperty>(SecurityKey, out property)) { ServiceSecurityContext context = property.ServiceSecurityContext; if (context != null && context.PrimaryIdentity != null) { WindowsIdentity windowsIdentity = context.PrimaryIdentity as WindowsIdentity; if (windowsIdentity != null) { Thread.CurrentPrincipal = new WindowsPrincipal(windowsIdentity); } } } // Submit request up the stack try { HttpResponseMessage responseMessage = null; channelContext.Server.SendAsync(request, channelContext.Server._cancellationTokenSource.Token) .Then(response => { responseMessage = response ?? request.CreateResponse(HttpStatusCode.OK); }) .Catch(info => { // REVIEW: Shouldn't the response contain the exception so it can be serialized? responseMessage = request.CreateResponse(HttpStatusCode.InternalServerError); return(info.Handled()); }) .Finally(() => { if (responseMessage == null) // No Then or Catch, must've been canceled { responseMessage = request.CreateResponse(HttpStatusCode.ServiceUnavailable); } Message reply = responseMessage.ToMessage(); BeginReply(new ReplyContext(channelContext, requestContext, reply)); }); } catch { // REVIEW: Shouldn't the response contain the exception so it can be serialized? HttpResponseMessage response = request.CreateResponse(HttpStatusCode.InternalServerError); Message reply = response.ToMessage(); BeginReply(new ReplyContext(channelContext, requestContext, reply)); } }
private static void ProcessRequestContext(ChannelContext channelContext, System.ServiceModel.Channels.RequestContext requestContext) { Contract.Assert(channelContext != null); Contract.Assert(requestContext != null); // Get the HTTP request from the WCF Message HttpRequestMessage request = requestContext.RequestMessage.ToHttpRequestMessage(); if (request == null) { throw Error.InvalidOperation(SRResources.HttpMessageHandlerInvalidMessage, requestContext.RequestMessage.GetType()); } // create principal information and add it the request for the windows auth case SecurityMessageProperty property = request.GetSecurityMessageProperty(); if (property != null) { ServiceSecurityContext context = property.ServiceSecurityContext; if (context != null && context.PrimaryIdentity != null) { WindowsIdentity windowsIdentity = context.PrimaryIdentity as WindowsIdentity; if (windowsIdentity != null) { Thread.CurrentPrincipal = new WindowsPrincipal(windowsIdentity); } } } // Submit request up the stack try { HttpResponseMessage responseMessage = null; channelContext.Server.SendAsync(request, channelContext.Server._cancellationTokenSource.Token) .Then(response => { responseMessage = response ?? request.CreateResponse(HttpStatusCode.OK); }) .Catch(info => { // REVIEW: Shouldn't the response contain the exception so it can be serialized? responseMessage = request.CreateResponse(HttpStatusCode.InternalServerError); return info.Handled(); }) .Finally(() => { if (responseMessage == null) // No Then or Catch, must've been canceled { responseMessage = request.CreateResponse(HttpStatusCode.ServiceUnavailable); } Message reply = responseMessage.ToMessage(); BeginReply(new ReplyContext(channelContext, requestContext, reply)); }); } catch { // REVIEW: Shouldn't the response contain the exception so it can be serialized? HttpResponseMessage response = request.CreateResponse(HttpStatusCode.InternalServerError); Message reply = response.ToMessage(); BeginReply(new ReplyContext(channelContext, requestContext, reply)); } }
static void ClearEffects(ChannelContext channel) { channel.addBeginLength = 0; channel.envSkip = 0; channel.vibLength = 0; channel.portaDelta = 0; }
private void ProcessRequestContext(ChannelContext channelContext, RequestContext requestContext) { Contract.Assert(channelContext != null); Contract.Assert(requestContext != null); HttpRequestMessage request = null; try { // Get the HTTP request from the WCF Message request = requestContext.RequestMessage.ToHttpRequestMessage(); if (request == null) { throw new InvalidOperationException(string.Format("Could not obtain an HTTP request from message of type '{0}'.", requestContext.RequestMessage.GetType())); } // Add information about whether the request is local or not request.Properties.Add(HttpPropertyKeys.IsLocalKey, new Lazy<bool>(() => IsLocal(requestContext.RequestMessage))); // Submit request up the stack HttpResponseMessage responseMessage = null; channelContext.Server.SendAsync(request, channelContext.Server._cancellationTokenSource.Token) .ContinueWith(t => { responseMessage = t.Result; if (t.IsCanceled || channelContext.Server._cancellationTokenSource.Token.IsCancellationRequested) { responseMessage = request.CreateResponse(HttpStatusCode.InternalServerError); CancelTask(channelContext.Server._openTaskCompletionSource); } if (t.IsFaulted) { try { responseMessage = request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception); } catch (Exception e) { FaultTask(channelContext.Server._openTaskCompletionSource, e); } } if (responseMessage != null) { Message reply = responseMessage.ToMessage(); BeginReply(new ReplyContext(channelContext, requestContext, reply)); if (!t.IsCompleted) CompleteTask(channelContext.Server._openTaskCompletionSource); } }); } catch (Exception e) { HttpResponseMessage response = request != null ? request.CreateErrorResponse(HttpStatusCode.InternalServerError, e) : new HttpResponseMessage(HttpStatusCode.BadRequest); Message reply = response.ToMessage(); BeginReply(new ReplyContext(channelContext, requestContext, reply)); } }
static void HaltMacroProgramm(ChannelContext channel) { channel.macroRun = false; channel.dmaIntCount = 0; }
void SetNoteMacro(ChannelContext channel, int note, int fineTune) { var noteInt = noteIntervalls[note & 0x3F]; var finetune = (ushort)(fineTune + channel.fineTune + (1 << 8)); channel.refPeriod = (ushort)((uint)noteInt * finetune >> 8); if (channel.portaDelta == 0) channel.period = channel.refPeriod; }
internal static Task SetRolePermissions(ChannelContext channel, DiscordServerContext server, ChangedPermissions permissions, UserRole role) { return(_discordClient.RolesService.SetRolePermissions(channel, server, permissions, role)); }
static void UnlockMacroChannel(ChannelContext channel) { channel.customMacro = 0; channel.customMacroIndex = 0; channel.customMacroPrio = 0; channel.sfxLocked = false; channel.sfxLockTime = -1; }
private static void BeginCloseChannel(ChannelContext channelContext) { Contract.Assert(channelContext != null); try { IAsyncResult result = channelContext.Channel.BeginClose(_onCloseChannelComplete, channelContext); if (result.CompletedSynchronously) { CloseChannelComplete(result); } } catch { CloseNextChannel(channelContext.Server); } }
/// <summary> /// Initializes a new instance of the <see cref="RequireContextAttribute"/> class. /// </summary> /// <param name="context">The context.</param> public RequireContextAttribute(ChannelContext context) { this.Context = context; }
static void InitMacroProgramm(ChannelContext channel) { channel.macroStep = 0; channel.macroWait = 0; channel.macroRun = true; channel.macroSfxRun = 0; channel.macroLoopCount = 0xFF; channel.dmaIntCount = 0; channel.deferWait = false; channel.macroReturnOffset = 0; channel.macroReturnStep = 0; }
void Effects(ChannelContext channel) { // addBegin if (channel.addBeginLength != 0) { channel.sampleStart += channel.addBeginDelta; SetChannelSampleStart(channel.paulaChannel, GetSamplePtr(channel.sampleStart)); if ((--channel.addBeginCount) == 0) { channel.addBeginCount = channel.addBeginLength; channel.addBeginDelta = -channel.addBeginDelta; } } // vibrato if (channel.vibLength != 0) { channel.vibValue += channel.vibDelta; if (--channel.vibCount == 0) { channel.vibCount = channel.vibLength; channel.vibDelta = (sbyte)-channel.vibDelta; } if (channel.portaDelta == 0) { // 16x16 bit multiplication, casts needed for the right results channel.period = (ushort)(((uint)channel.refPeriod * (ushort)((1 << 11) + channel.vibValue)) >> 11); } } // portamento if (channel.portaDelta != 0 && (--channel.portaCount) == 0) { channel.portaCount = channel.portaSkip; bool resetPorta = true; ushort period = channel.refPeriod; ushort portaVal = channel.portaValue; if (period > portaVal) { portaVal = (ushort)(((uint)portaVal * (ushort)((1 << 8) + channel.portaDelta)) >> 8); resetPorta = (period <= portaVal); } else if (period < portaVal) { portaVal = (ushort)(((uint)portaVal * (ushort)((1 << 8) - channel.portaDelta)) >> 8); resetPorta = (period >= portaVal); } if (resetPorta) { channel.portaDelta = 0; channel.portaValue = (ushort)(period & 0x7FF); } else channel.period = channel.portaValue = (ushort)(portaVal & 0x7FF); } // envelope if (channel.envSkip != 0 && channel.envCount-- == 0) { channel.envCount = channel.envSkip; sbyte endVol = channel.envEndVolume; sbyte volume = channel.volume; bool resetEnv; if (endVol > volume) { volume += (sbyte)channel.envDelta; resetEnv = endVol <= volume; } else { volume -= (sbyte)channel.envDelta; resetEnv = volume <= 0 || endVol >= volume; } if (resetEnv) { channel.envSkip = 0; volume = endVol; } channel.volume = volume; } // Fade if (_playerCtx.fadeDelta != 0 && (--_playerCtx.fadeCount) == 0) { _playerCtx.fadeCount = _playerCtx.fadeSkip; _playerCtx.volume += _playerCtx.fadeDelta; if (_playerCtx.volume == _playerCtx.fadeEndVolume) _playerCtx.fadeDelta = 0; } // Volume var finVol = (byte)(_playerCtx.volume * channel.volume >> 6); SetChannelVolume(channel.paulaChannel, finVol); }
private void BeginNextRequest(ChannelContext context) { if (ShouldIncreaseWindowSize()) { // This boolean avoids us calling BeginReceiveRequestContext under a lock bool windowSizeIncreased = false; // If we can't get the lock, just keep the window size the same // It's better to keep the window size the same than risk affecting performance by waiting on a lock // And if the lock is taken, some other thread is already updating the window size to a better value if (Monitor.TryEnter(_windowSizeLock)) { try { // Recheck that we should increase the window size to guard for changes between the time we take the lock and the time we increase the window size if (ShouldIncreaseWindowSize()) { // Increase Window Size _windowSize++; windowSizeIncreased = true; } } finally { Monitor.Exit(_windowSizeLock); } } if (windowSizeIncreased) { // Spin off an additional BeginReceiveRequest to increase the window size by 1 BeginReceiveRequestContext(context); } } else if (ShouldDecreaseWindowSize()) { // If we can't get the lock, just keep the window size the same // It's better to keep the window size the same than risk affecting performance by waiting on a lock // And if the lock is taken, some other thread is already updating the window size to a better value if (Monitor.TryEnter(_windowSizeLock)) { try { // Recheck that we should decrease the window size to guard for changes between the time we take the lock and the time we increase the window size if (ShouldDecreaseWindowSize()) { // Decrease the window size by 1 by avoiding calling BeginReceiveRequest _windowSize--; return; } } finally { Monitor.Exit(_windowSizeLock); } } } BeginReceiveRequestContext(context); }
private void ProcessRequestContext(ChannelContext channelContext, System.ServiceModel.Channels.RequestContext requestContext) { Contract.Assert(channelContext != null); Contract.Assert(requestContext != null); HttpRequestMessage request = null; try { // Get the HTTP request from the WCF Message request = requestContext.RequestMessage.ToHttpRequestMessage(); if (request == null) { throw Error.InvalidOperation(SRResources.HttpMessageHandlerInvalidMessage, requestContext.RequestMessage.GetType()); } // create principal information and add it the request for the windows auth case SetCurrentPrincipal(request); // Add the retrieve client certificate delegate to the property bag to enable lookup later on request.Properties.Add(HttpPropertyKeys.RetrieveClientCertificateDelegateKey, _retrieveClientCertificate); // Add information about whether the request is local or not request.Properties.Add(HttpPropertyKeys.IsLocalKey, new Lazy<bool>(() => IsLocal(requestContext.RequestMessage))); // Submit request up the stack HttpResponseMessage responseMessage = null; channelContext.Server.SendAsync(request, channelContext.Server._cancellationTokenSource.Token) .Then(response => { responseMessage = response ?? request.CreateResponse(HttpStatusCode.InternalServerError); }) .Catch(info => { responseMessage = request.CreateErrorResponse(HttpStatusCode.InternalServerError, info.Exception); return info.Handled(); }) .Finally(() => { if (responseMessage == null) // No Then or Catch, must've been canceled { responseMessage = request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, SRResources.RequestCancelled); } Message reply = responseMessage.ToMessage(); BeginReply(new ReplyContext(channelContext, requestContext, reply)); }); } catch (Exception e) { HttpResponseMessage response = request != null ? request.CreateErrorResponse(HttpStatusCode.InternalServerError, e) : new HttpResponseMessage(HttpStatusCode.BadRequest); Message reply = response.ToMessage(); BeginReply(new ReplyContext(channelContext, requestContext, reply)); } }
public Repository() { context = new ChannelContext(); DbSet = context.Set <T>(); }
/// <summary> /// Initializes a new instance of the <see cref="ChannelContext"/> class. /// </summary> /// <param name="channelContext">The channel context to associate with this reply context.</param> /// <param name="requestContext">The request context to associate with this reply context.</param> /// <param name="reply">The reply to associate with this reply context.</param> public ReplyContext(ChannelContext channelContext, RequestContext requestContext, Message reply) { Contract.Assert(channelContext != null); Contract.Assert(requestContext != null); Contract.Assert(reply != null); ChannelContext = channelContext; RequestContext = requestContext; Reply = reply; }
static ChannelContext[] CreateChannelContexts() { var channelCtx = new ChannelContext[NumVoices]; for (int i = 0; i < channelCtx.Length; i++) { channelCtx[i] = new ChannelContext(); } return channelCtx; }
public DataController(ILogger <DataController> logger, ChannelContext ctx) { Logger = logger; Ctx = ctx; }
// async void is OK here. This is a fire and forget method and any exceptions that occur will be turned into // HTTP responses that get sent back to clients. private async void ProcessRequestContext(ChannelContext channelContext, RequestContext requestContext) { Contract.Assert(channelContext != null); Contract.Assert(requestContext != null); HttpResponseMessage response = await SendAsync(channelContext, requestContext); Message reply = response.ToMessage(); BeginReply(new ReplyContext(channelContext, requestContext, reply)); }
public override async void Input(ChannelContext context, SayInput input) { Console.WriteLine($"The client say:{input.TalkContent}"); await context.OutputAsync(new SayOutput { TalkContent = $"I am server,hi client." }); }
private async Task<HttpResponseMessage> SendAsync(ChannelContext channelContext, RequestContext requestContext) { HttpRequestMessage request = null; try { request = CreateHttpRequestMessage(requestContext); } catch { return new HttpResponseMessage(HttpStatusCode.BadRequest); } // Submit request up the stack try { HttpResponseMessage response = await channelContext.Server.SendAsync(request, channelContext.Server._cancellationTokenSource.Token); if (response == null) { response = request.CreateResponse(HttpStatusCode.InternalServerError); } return response; } catch (OperationCanceledException operationCanceledException) { return request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, SRResources.RequestCancelled, operationCanceledException); } }
internal static Task <IEnumerable <Message> > GetMessages(DiscordServerContext server, ChannelContext channel, int limit, ulong fromMessageId = 0, bool goBefore = true) { return(_discordClient.ChannelsService.GetMessages(server, channel, limit, fromMessageId, goBefore)); }
//------------------------------------------------------------------------------------------------------------------------ public bool serverNegotiation(Yodiwo.YPChannel.Channel channel) { var resp = channel.SendRequest<AudioAuthenticationResponse>(new AudioAuthenticationRequest()); if (resp == null) return false; else { //handle response if (!audiopipes.ContainsKey(resp.audiotoken)) return false; else { //create context var ctx = new ChannelContext() { audioInfo = audiopipes[resp.audiotoken], }; channel.Tags.Add(typeof(ChannelContext), ctx); ctx.Receiving = true; return true; } } }