public async Task <ActionResult> GetPaket(int id)
        {
            var paket = await _context.Packets.FirstOrDefaultAsync(s => s.Id == id);

            if (paket == null)
            {
                return(StatusCode(404));
            }

            List <LangcontentDto> langcontent = await _context.LanguageContexts.Where(s => s.Key == paket.NameKey).Select(s => new LangcontentDto
            {
                Languagename = s.LangUnicode,
                Content      = s.Context
            }).ToListAsync();

            PacketDto selectedpacket = new PacketDto()
            {
                Id           = paket.Id,
                HumanContent = paket.HumanCount,
                Price        = paket.Price,
                Content      = langcontent,
                ModulId      = JsonConvert.DeserializeObject <List <int> >(paket.Content)
            };

            return(Ok(selectedpacket));
        }
        public async Task <ActionResult> EditPacket(int id, [FromBody] PacketDto _packetDto)
        {
            if (id != _packetDto.Id)
            {
                return(BadRequest());
            }

            var editedpacket = await _context.Packets.FirstOrDefaultAsync(s => s.Id == id);

            if (editedpacket == null)
            {
                return(NotFound());
            }

            editedpacket.Price                 = _packetDto.Price;
            editedpacket.HumanCount            = _packetDto.HumanContent;
            editedpacket.Content               = JsonConvert.SerializeObject(_packetDto.ModulId);
            _context.Entry(editedpacket).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (Exception)
            {
                throw;
            }

            var deletetcontent = await _context.LanguageContexts.Where(s => s.Key == editedpacket.NameKey).ToListAsync();

            foreach (var item in deletetcontent)
            {
                _context.LanguageContexts.Remove(item);
                await _context.SaveChangesAsync();
            }

            for (int i = 0; i < _packetDto.Content.Count; i++)
            {
                LanguageContext newContent = new LanguageContext()
                {
                    Key         = editedpacket.NameKey,
                    LangUnicode = _packetDto.Content[i].Languagename,
                    Context     = _packetDto.Content[i].Content
                };
                _context.LanguageContexts.Add(newContent);
            }
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                throw;
            }

            return(Ok());
        }
        private async Task SendHelperAsync(Guid destination, MessageDto message, bool reliable)
        {
            var packetDto = PacketDto.Create(identity.Id, destination, message, reliable);
            var ms        = outboundPacketMemoryStreamPool.TakeObject();

            ms.SetLength(0);
            try {
                await AsyncSerialize.ToAsync(ms, packetDto).ConfigureAwait(false);
            } catch (NotSupportedException) {
                // surpassed memory stream buffer size.
                if (!reliable)
                {
                    throw new InvalidOperationException("Attempted to send nonreliable buffer surpassing transport buffer size");
                }

                ms.SetLength(0);
                outboundPacketMemoryStreamPool.ReturnObject(ms);
                await SendReliableMultipartPacketAsync(destination, packetDto).ConfigureAwait(false);

#if DEBUG
                Interlocked.Increment(ref DebugRuntimeStats.out_rs_done);
#endif
                return;
            }

            if (reliable)
            {
                var completionSignal       = new AsyncLatch();
                var acknowlewdgementSignal = acknowledgementCoordinator.Expect(packetDto.Id);
                unhandledSendRequestQueue.Enqueue(
                    new SendRequest {
                    DataBufferPool        = outboundPacketMemoryStreamPool,
                    Data                  = ms,
                    DataOffset            = 0,
                    DataLength            = (int)ms.Position,
                    IsReliable            = true,
                    AcknowledgementSignal = acknowlewdgementSignal,
                    AcknowledgementGuid   = packetDto.Id,
                    CompletionSignal      = completionSignal
                });
                workSignal.Set();
                await completionSignal.WaitAsync().ConfigureAwait(false);
            }
            else
            {
                unhandledSendRequestQueue.Enqueue(
                    new SendRequest {
                    DataBufferPool = outboundPacketMemoryStreamPool,
                    Data           = ms,
                    DataOffset     = 0,
                    DataLength     = (int)ms.Position,
                    IsReliable     = false
                });
                workSignal.Set();
            }
        }
        private async Task SendReliableMultipartPacketAsync(Guid destination, PacketDto packet)
        {
            using (var ms = new MemoryStream()) {
                await AsyncSerialize.ToAsync(ms, packet).ConfigureAwait(false);

                var payloadSize = ms.Position;

                // message id necessary for reassembly of chunks
                var multiPartMessageId = Guid.NewGuid();

                var chunkCount = (int)((payloadSize - 1) / UdpConstants.kMultiPartChunkSize + 1);
                var chunks     = Util.Generate(
                    chunkCount,
                    chunkIndex => {
                    var startIndexInclusive = UdpConstants.kMultiPartChunkSize * chunkIndex;
                    var endIndexExclusive   = Math.Min(payloadSize, startIndexInclusive + UdpConstants.kMultiPartChunkSize);
                    return(new MultiPartChunkDto {
                        Body = ms.GetBuffer(),
                        BodyLength = (int)(endIndexExclusive - startIndexInclusive),
                        BodyOffset = startIndexInclusive,
                        MultiPartMessageId = multiPartMessageId,
                        ChunkCount = chunkCount,
                        ChunkIndex = chunkIndex
                    });
                });
                logger.Info($"Splitting large payload into {chunks.Length} chunks.");

                await Task.WhenAll(
                    Util.Generate(
                        chunkCount,
                        i => SendReliableAsync(destination, MessageDto.Create(identity.Id, destination, chunks[i]))
                        )).ConfigureAwait(false);

                //            const int kConcurrencyLimit = 32;
                ////            var sync = new AsyncSemaphore(kConcurrencyLimit);
                //            for (var i = 0; i < chunkCount; i++) {
                ////               await sync.WaitAsync().ConfigureAwait(false);
                //               var chunkMessage = MessageDto.Create(identity.Id, destination, chunks[i]);
                ////               Go(async () => {
                //               SendReliableAsync(destination, chunkMessage).Forget();
                //.ConfigureAwait(false);
                //                  sync.Release();
                //               }).Forget();
            }
        }
        public async Task <ActionResult> CreatePacket([FromBody] PacketDto _packetDto)
        {
            string keystring = DateTime.Now.ToString().GetHashCode().ToString("x");

            Packet newpacket = new Packet()
            {
                NameKey    = DateTime.Now.ToString() + keystring,
                Price      = _packetDto.Price,
                HumanCount = _packetDto.HumanContent,
                Content    = JsonConvert.SerializeObject(_packetDto.ModulId)
            };

            try
            {
                _context.Add(newpacket);
                await _context.SaveChangesAsync();
            }
            catch (Exception)
            {
                throw;
            }

            var createdPaket = _context.Packets.FirstOrDefault(s => s.Id == newpacket.Id);

            if (createdPaket == null)
            {
                return(BadRequest());
            }


            foreach (var item in _packetDto.Content)
            {
                LanguageContext newContent = new LanguageContext()
                {
                    Key         = newpacket.NameKey,
                    LangUnicode = item.Languagename,
                    Context     = item.Content
                };
                _context.LanguageContexts.Add(newContent);
                await _context.SaveChangesAsync();
            }

            return(StatusCode(201));
        }
        public async Task SendBroadcastAsync(MessageDto message)
        {
            var packet = PacketDto.Create(
                identity.Id,
                Guid.Empty,
                message,
                false);

            var ms = broadcastOutboundMemoryStreamPool.TakeObject();

            ms.SetLength(0);
            try {
                await AsyncSerialize.ToAsync(ms, packet).ConfigureAwait(false);
            } catch (NotSupportedException) {
                throw new InvalidOperationException("Broadcast message would surpass Courier Maximum UDP Transport Size");
            }

            udpClient.Broadcast(
                ms, 0, (int)ms.Position,
                () => {
                ms.SetLength(0);
                broadcastOutboundMemoryStreamPool.ReturnObject(ms);
            });
        }