private static async Task Run() { var configLoader = new AprsConfigProvider(); var config = await configLoader.LoadAsync(); var streamListener = new StreamProvider(config); var aircraftProvider = new AircraftProvider(config); await aircraftProvider.Initialize(); streamListener.Stream .Subscribe(line => { var result = StreamConversionService.ConvertData(line); if (result != null) { Console.WriteLine(result); Console.WriteLine(aircraftProvider.Load(result.AircraftId)); } else { Console.WriteLine($"Not parsable: {line}"); } }); await streamListener.Stream; }
public InvokerService(string serviceName, StreamProvider provider, bool forceExit = false, Action <string> postRun = null) : this(serviceName, provider, forceExit = false) { ServiceName = serviceName; StreamProvider = provider; _force = forceExit; PostRun = postRun; }
private void RenderPdf(StreamProvider streams, Action <StreamProvider> postAction) { var reportPath = Path.Combine(ReportsPath, (string)reports.SelectedItem); var pdfSettings = (ISettings)propertyGrid.SelectedObject; var export = radioButton1.Checked ? _arPdf : _sharpPdf; Cursor = Cursors.WaitCursor; Enabled = false; var thread = new Thread(_ => { try { using (var report = new PageReport(new FileInfo(reportPath))) report.Document.Render(export, streams, pdfSettings.GetSettings()); postAction(streams); } catch (Exception ex) { BeginInvoke( new MethodInvoker(() => { MessageBox.Show(this, string.Format(Resources.ErrorMessage, ex.Message), Text, MessageBoxButtons.OK, MessageBoxIcon.Error); })); } finally { BeginInvoke(new MethodInvoker(() => { Enabled = true; })); BeginInvoke(new MethodInvoker(() => { Cursor = Cursors.Default; })); } }); thread.Start(); }
/// <summary> /// Render report to source C# code with given settings /// </summary> /// <param name="report"></param> /// <param name="streams"></param> /// <param name="settings"></param> public void Render(IReport report, StreamProvider streams, NameValueCollection settings) { if (report == null) { throw new ArgumentNullException("report"); } _report = report; foreach (IReportItem ri in report.Body.ReportItems) { ReportItemBase dataItem; var cri = ri as ICustomReportItemAdapter; if (cri != null) { dataItem = cri.OriginalReportItem as ReportItemBase; } else { dataItem = ri as ReportItemBase; } if (dataItem != null) { RenderDataItem(dataItem); } } }
IProcessor CreateProcessor(StreamProvider provider) { switch (provider) { case StreamProvider.YouTube: return(new YouTubeStreamProcessor(downloader)); case StreamProvider.Twitch: return(new TwitchProcessor()); case StreamProvider.SeeNow: return(new SeeNowProcessor(downloader)); case StreamProvider.TvSportHd: return(new TvSportHdProcessor()); case StreamProvider.AntenaPlay: return(new AntenaPlayProcessor()); case StreamProvider.OkLive: return(new OkLiveProcessor(downloader)); default: return(new OtherProcessor(downloader)); } }
/// <summary> /// Enumerate through the lines of the algoseek files. /// </summary> /// <param name="file">BZ File for AlgoSeek</param> /// <param name="symbolMultipliers">Symbol price multiplier</param> /// <param name="symbolFilter">Symbol filter to apply, if any</param> public AlgoSeekFuturesReader(string file, Dictionary <string, decimal> symbolMultipliers, HashSet <string> symbolFilter = null) { var streamProvider = StreamProvider.ForExtension(Path.GetExtension(file)); _stream = streamProvider.Open(file).First(); _streamReader = new StreamReader(_stream); _symbolFilter = symbolFilter; _symbolMultipliers = symbolMultipliers.ToDictionary(); _symbolProperties = SymbolPropertiesDatabase.FromDataFolder(); // detecting column order in the file var headerLine = _streamReader.ReadLine(); if (!string.IsNullOrEmpty(headerLine)) { var header = headerLine.ToCsv(); _columnTimestamp = header.FindIndex(x => x == "Timestamp"); _columnTicker = header.FindIndex(x => x == "Ticker"); _columnType = header.FindIndex(x => x == "Type"); _columnSide = header.FindIndex(x => x == "Side"); _columnSecID = header.FindIndex(x => x == "SecurityID"); _columnQuantity = header.FindIndex(x => x == "Quantity"); _columnPrice = header.FindIndex(x => x == "Price"); _columnsCount = new[] { _columnTimestamp, _columnTicker, _columnType, _columnSide, _columnSecID, _columnQuantity, _columnPrice }.Max(); } //Prime the data pump, set the current. Current = null; MoveNext(); }
private IEnumerable <TObject> GetRecordsInternal(TParam parameters) { IEnumerable <TObject> records; if (ProgressManager.GetRecordsWithVariableProgress) { records = GetResultsWithVariableProgress(() => GetFilteredObjects(parameters)); } else if (ProgressManager.GetResultsWithProgress) { records = GetResultsWithProgress(() => GetFilteredObjects(parameters)); } else { if (StreamProvider.StreamResults || StreamProvider.ForceStream) { records = StreamProvider.StreamResultsWithProgress(parameters, Count, () => GetFilteredObjects(parameters)); } else { records = GetFilteredObjects(parameters); } } records = PostProcessRecords(records); return(records); }
/// <summary> /// Enumerate through the lines of the algoseek files. /// </summary> /// <param name="file">BZ File for algoseek</param> /// <param name="date">Reference date of the folder</param> public AlgoSeekOptionsReader(string file, DateTime date, HashSet <string> symbolFilter = null) { _date = date; _underlyingCache = new Dictionary <string, Symbol>(); var streamProvider = StreamProvider.ForExtension(Path.GetExtension(file)); _stream = streamProvider.Open(file).First(); _streamReader = new StreamReader(_stream); _symbolFilter = symbolFilter; // detecting column order in the file var headerLine = _streamReader.ReadLine(); if (!string.IsNullOrEmpty(headerLine)) { var header = headerLine.ToCsv(); _columnTimestamp = header.FindIndex(x => x == "Timestamp"); _columnTicker = header.FindIndex(x => x == "Ticker"); _columnType = header.FindIndex(x => x == "Type"); _columnSide = header.FindIndex(x => x == "Side"); _columnPutCall = header.FindIndex(x => x == "PutCall"); _columnExpiration = header.FindIndex(x => x == "Expiration"); _columnStrike = header.FindIndex(x => x == "Strike"); _columnQuantity = header.FindIndex(x => x == "Quantity"); _columnPremium = header.FindIndex(x => x == "Premium"); _columnExchange = header.FindIndex(x => x == "Exchange"); _columnsCount = Enumerable.Max(new[] { _columnTimestamp, _columnTicker, _columnType, _columnSide, _columnPutCall, _columnExpiration, _columnStrike, _columnQuantity, _columnPremium, _columnExchange }); } //Prime the data pump, set the current. Current = null; MoveNext(); }
private static async Task <Stream> StartTorrenting(Options cliOptions) { var engine = new ClientEngine(); WriteLine("MonoTorrent -> Loading torrent file..."); var torrent = Torrent.Load(new Uri(cliOptions.Torrent), Path.Combine(Environment.CurrentDirectory, "video.torrent")); WriteLine("MonoTorrent -> Creating a new StreamProvider..."); var provider = new StreamProvider(engine, cliOptions.Path, torrent); if (cliOptions.Verbose) { provider.Manager.PeerConnected += (o, e) => WriteLine($"MonoTorrent -> Connection succeeded: {e.Peer.Uri}"); provider.Manager.ConnectionAttemptFailed += (o, e) => WriteLine($"MonoTorrent -> Connection failed: {e.Peer.ConnectionUri} - {e.Reason} - {e.Peer.AllowedEncryption}"); } WriteLine("MonoTorrent -> Starting the StreamProvider..."); await provider.StartAsync(); WriteLine("MonoTorrent -> Creating a stream from the torrent file..."); var stream = await provider.CreateStreamAsync(provider.Manager.Torrent.Files[0]); return(stream); }
private IEnumerable <TObject> GetObjectsWhenStreaming(TParam parameters) { if (Count != null && filters != null) { int previousCount; Func <int> getCount; if (StreamProvider.StreamCount != null) { previousCount = StreamProvider.StreamCount.Value; getCount = () => previousCount; } else { getCount = () => ((IStreamableCmdlet <PrtgTableCmdlet <TObject, TParam>, TObject, TParam>) this).GetStreamTotalObjects(parameters); } StreamProvider.SetStreamCount(parameters, Count); var iterator = new TakeIterator <TObject, TParam>( StreamProvider.StreamCount.Value, parameters, (p, c) => StreamProvider.StreamRecords <TObject>(p, Count, c), getCount, PostProcessRecords, SortReturnedRecordsRunner ); return(iterator); } return(StreamProvider.StreamRecords <TObject>(parameters, Count)); }
public async Task <List <string> > PostAsync() { if (Request.Content.IsMimeMultipartContent()) { string uploadPath = HttpContext.Current.Server.MapPath("~/uploads"); StreamProvider streamProvider = new StreamProvider(uploadPath); await Request.Content.ReadAsMultipartAsync(streamProvider); List <string> messages = new List <string>(); foreach (var file in streamProvider.FileData) { FileInfo fi = new FileInfo(file.LocalFileName); messages.Add("File uploaded as " + fi.FullName + " (" + fi.Length + " bytes)"); } return(messages); } else { HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Request!"); throw new HttpResponseException(response); } }
public async Task <IEnumerable <Upload> > UploadFile(HttpRequestMessage request) { var provider = new CustomMultipartFormDataProvider(AppConfig.GetUploadDirectory()); var stream = StreamProvider.GetStreamContent(request); await stream.ReadAsMultipartAsync(provider); var files = new List <Upload>(); var uploads = provider.FileData.Select(s => new Upload { Name = s.Headers.ContentDisposition.FileName.Replace("\"", ""), ContentType = s.Headers.ContentType.MediaType.Replace("\"", ""), Path = Path.GetDirectoryName(s.LocalFileName), CreateDate = DateTime.Now }); foreach (var u in uploads) { var upload = _context.Uploads.Add(u); var result = await _context.SaveChangesAsync(); files.Add(upload); } return(files); }
public override void Execute(string line, StreamProvider streams, MusicManager musicManager) { long id; if (!long.TryParse(Regex.Match(line, RegexPattern).Groups["trackId"].Value, out id)) { streams.SendLine("getFile:invalidparameter"); return; } var track = Utilities.GetTrackByAuthenticationCode(id, musicManager.Playlists); if (track == null) { streams.SendLine("getFile:tracknotfound"); return; } var localTrack = track as LocalTrack; if (localTrack == null) { streams.SendLine("getFile:trackisstream"); return; } if (!localTrack.TrackExists) { streams.SendLine("getFile:tracknotexists"); return; } streams.SendLine("getFile:ok"); using (var fs = new FileStream(localTrack.TrackInformation.FullName, FileMode.Open, FileAccess.Read)) { var binaryWriter = streams.BinaryWriter; var totalLength = (int)fs.Length; binaryWriter.Write(totalLength); int noOfPackets = (int)Math.Ceiling((double)fs.Length / BufferSize); for (int i = 0; i < noOfPackets; i++) { int currentPacketLength; if (totalLength > BufferSize) { currentPacketLength = BufferSize; totalLength -= currentPacketLength; } else { currentPacketLength = totalLength; } var sendingBuffer = new byte[currentPacketLength]; fs.Read(sendingBuffer, 0, currentPacketLength); binaryWriter.Write(sendingBuffer, 0, sendingBuffer.Length); } } }
public override void Execute(string line, StreamProvider streams, MusicManager musicManager) { var xmls = new XmlSerializer(typeof(List <NormalPlaylist>)); using (var stringWriter = new StringWriter()) using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Encoding = Encoding.UTF8 })) { var playlists = musicManager.Playlists.ToList(); foreach (var playlist in playlists) { foreach (var track in playlist.Tracks.Where(track => !track.TrackExists)) { playlist.Tracks.Remove(track); } } xmls.Serialize(xmlWriter, playlists); var binaryWriter = streams.BinaryWriter; var bytesToSend = Encoding.UTF8.GetBytes(stringWriter.ToString()); binaryWriter.Write(bytesToSend.Length); binaryWriter.Write(bytesToSend); binaryWriter.Flush(); } }
public async Task <IHttpActionResult> UploadArticleMultimedia() { string articlefilePath = Utilities.IsProduction == true ? Utilities.ArticlefilePathProd : Utilities.ArticlefilePathDev; if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType)); } var UploadFilePath = CreateContractFile(); StreamProvider streamProvider = new StreamProvider(UploadFilePath); var result = await Request.Content.ReadAsMultipartAsync(streamProvider); IEnumerable <string> FileDataNames = streamProvider.FileData.Select (entry => entry.LocalFileName.Replace(articlefilePath, "")); string _FileName = ""; foreach (string value in FileDataNames) { _FileName = value.Replace("\\", "//"); } if (Convert.ToInt32(result.FormData.GetValues("FileType")[0]) == 0) { throw new Exception("File Type is required.,"); } if (Convert.ToInt32(result.FormData.GetValues("LangId")[0]) == 0) { throw new Exception("Language Id is required.,"); } if (Convert.ToInt64(result.FormData.GetValues("ArticleId")[0]) == 0) { throw new Exception("Decision Id is required.,"); } if (String.IsNullOrEmpty(Convert.ToString(result.FormData.GetValues("FileName")[0]))) { throw new Exception("File Name is required.,"); } var decisionmodel = new AddUpdateArticleMultimedia(); decisionmodel.FileName = result.FormData.GetValues("FileName")[0]; decisionmodel.FileType = Convert.ToInt32(result.FormData.GetValues("FileType")[0]); decisionmodel.ArticleId = Convert.ToInt64(result.FormData.GetValues("ArticleId")[0]); decisionmodel.LangId = Convert.ToInt32(result.FormData.GetValues("LangId")[0]); decisionmodel.VideoUrl = Convert.ToInt32(result.FormData.GetValues("FileType")[0]) != 1 ? string.Empty : result.FormData.GetValues("VideoUrl")[0]; decisionmodel.FileUrl = _FileName; var map = AutoMapper.Mapper.Map <ArticleMultimedia>(decisionmodel); var output = _serviceFactory.CreateArticleService.InsertOrUpdateArticleMultimedia(map); return(Ok(output)); }
//==============================================Methoden public void Update() { Thread thread = new Thread(x => StreamProvider.UpdateChannel(this)); thread.Start(); //StreamProvider.UpdateChannel(this); OnUpdate(this, null); }
private IEnumerable <TObject> GetObjectsWhenStreaming(TParam parameters) { if (ProgressManager.WatchStream) { if (typeof(TObject) == typeof(Log)) { return((IEnumerable <TObject>) new InfiniteLogGenerator( client.GetLogs, (LogParameters)(object)parameters, ((IWatchableCmdlet)this).Interval, i => { if (Stopping) { throw new PipelineStoppedException(); } return true; }, CancellationToken, logs => (IEnumerable <Log>)PostProcessRecords((IEnumerable <TObject>)logs) )); } throw new NotImplementedException($"Don't know how to watch objects of type ({typeof(TObject).Name})"); } if (Count != null && filters != null) { int previousCount; Func <int> getCount; if (StreamProvider.StreamCount != null) { previousCount = StreamProvider.StreamCount.Value; getCount = () => previousCount; } else { getCount = () => ((IStreamableCmdlet <PrtgTableCmdlet <TObject, TParam>, TObject, TParam>) this).GetStreamTotalObjects(parameters); } StreamProvider.SetStreamCount(parameters, Count); var iterator = new TakeIterator <TObject, TParam>( StreamProvider.StreamCount.Value, parameters, (p, c) => StreamProvider.StreamRecords <TObject>(p, Count, c), getCount, PostProcessRecords, SortReturnedRecordsRunner ); return(iterator); } return(StreamProvider.StreamRecords <TObject>(parameters, Count)); }
private MessageStreamIterator(StreamProvider streamProvider, ExtensionRegistry extensionRegistry) { if (messageReader == null) { throw typeInitializationException; } this.streamProvider = streamProvider; this.extensionRegistry = extensionRegistry; }
public void Render(IReport report, StreamProvider streams, NameValueCollection settings) { ILayoutTree tree = GetLayoutTree(report, this, null); foreach (ILayoutPage page in tree.Pages) { RenderPage(page); } }
/// <summary> /// Performs enhanced record-by-record processing functionality for the cmdlet. /// </summary> protected override void ProcessRecordEx() { if (ParameterSetName == ParameterSet.Default) { Id = Sensor.Id; } IEnumerable <PSObject> records; var average = Average; if (average == null) { //Sensor is implicitly not null because Downtime is part of the Default parameter set average = Downtime ? Convert.ToInt32(Sensor.Interval.TotalSeconds) : 0; } else { if (Downtime && average == 0) { throw new InvalidOperationException($"Cannot retrieve downtime with an {nameof(Average)} of 0"); } } var parameters = new SensorHistoryParameters(Id, average.Value, StartDate, EndDate, Count); if (EndDate == null) { StreamProvider.StreamResults = false; } if (EndDate != null) { StreamProvider.ForceStream = true; records = StreamProvider.StreamResultsWithProgress(parameters, Count, () => GetFormattedRecords(parameters)); if (Count != null) { records = records.Take(Count.Value); } } else if (ProgressManager.GetRecordsWithVariableProgress) { records = GetResultsWithVariableProgress(() => GetFormattedRecords(parameters)); } else if (ProgressManager.GetResultsWithProgress) { records = GetResultsWithProgress(() => GetFormattedRecords(parameters)); } else { records = GetFormattedRecords(parameters); } WriteList(records); }
protected virtual async Task SetUnderlyingStreamAsync(CancellationToken cancellationToken) { TryDisposeUnderlyingStream(); UnderlyingStream = await StreamProvider.GetStreamAsync(Position, cancellationToken).ConfigureAwait(false); if (UnderlyingStream == null) { throw new InvalidOperationException("Failed to retrieve underlying stream"); } }
protected virtual void SetUnderlyingStream() { TryDisposeUnderlyingStream(); UnderlyingStream = StreamProvider.GetStream(Position); if (UnderlyingStream == null) { throw new InvalidOperationException("Failed to retrieve underlying stream"); } }
public async Task Inside(string[] args) { var stream = new StreamProvider(() => string.Join(TokenConfigs.SeparatorString, args).CleanString(TokenConfigs.TextStart, TokenConfigs.TextEnd), input => { Console.WriteLine(input); return(string.Empty); }); var invoker = new InvokerService("Inside", stream, true, Console.WriteLine); await invoker.Run(); { } }
private MessageStreamIterator(StreamProvider streamProvider, ExtensionRegistry extensionRegistry, int sizeLimit) { if (ReferenceEquals(defaultMessageInstance, null)) { throw new System.Reflection.TargetInvocationException(typeInitializationException); } this.streamProvider = streamProvider; this.extensionRegistry = extensionRegistry; this.sizeLimit = sizeLimit; }
public void CallStreamProvider(StreamProvider s, Episode e) { var name = e.ShowName.Replace(" ", s.SpaceSeperator) .Replace("'", ""); var url = s.Url.Replace("{show}", name) .Replace("{season}", e.SeasonNumber.ToString()) .Replace("{episode}", e.EpisodeNumber.ToString()); Process.Start(url); }
public ViewHub() { Console.WriteLine("hub created!"); //Task.Factory.StartNew(Publish); if (_streamProvider == null) { _streamProvider = new StreamProvider((res => { Clients.All.updateStockPrice(new [] { res }); })); _streamProvider.Initialize(); } }
public ActorControlService( StreamProvider streamProvider, ActorPropsFactory actorPropsFactory, ActorSystem actorSystem, GatewayConfiguration gatewayConfiguration ) { _streamProvider = streamProvider; _actorPropsFactory = actorPropsFactory; _actorSystem = actorSystem; _gatewayConfiguration = gatewayConfiguration; }
/// <summary> /// Initializes a new instance of the <see cref="LavalinkTrack"/> class. /// </summary> /// <param name="identifier">an unique track identifier</param> /// <param name="author">the name of the track author</param> /// <param name="duration">the duration of the track</param> /// <param name="isLiveStream">a value indicating whether the track is a live stream</param> /// <param name="isSeekable">a value indicating whether the track is seek-able</param> /// <param name="source">the track source</param> /// <param name="title">the title of the track</param> /// <param name="trackIdentifier"> /// the unique track identifier (Example: dQw4w9WgXcQ, YouTube Video ID) /// </param> /// <param name="provider">the stream provider (e.g. YouTube)</param> /// <exception cref="ArgumentNullException"> /// thrown if the specified <paramref name="identifier"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentNullException"> /// thrown if the specified <paramref name="trackIdentifier"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentNullException"> /// thrown if the specified <paramref name="author"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentNullException"> /// thrown if the specified <paramref name="title"/> is <see langword="null"/>. /// </exception> public LavalinkTrack(string identifier, string author, TimeSpan duration, bool isLiveStream, bool isSeekable, string?source, string title, string trackIdentifier, StreamProvider provider) { Identifier = identifier ?? throw new ArgumentNullException(nameof(identifier)); TrackIdentifier = trackIdentifier ?? throw new ArgumentNullException(nameof(trackIdentifier)); Author = author ?? throw new ArgumentNullException(nameof(author)); Title = title ?? throw new ArgumentNullException(nameof(title)); Source = source; Duration = duration; IsSeekable = isSeekable; IsLiveStream = isLiveStream; Provider = provider; }
public async Task <string> UploadUserAvatar(HttpRequestMessage request) { // Check if the request contains multipart/form-data. if (!request.Content.IsMimeMultipartContent()) { throw new ApplicationOperationException("", HttpStatusCode.UnsupportedMediaType); } try { if (CurrentUser.Avatar != null) { string deletedAvatarPath = HttpContext.Current.Server.MapPath(string.Format("~/{0}", CurrentUser.Avatar)); if (System.IO.File.Exists(deletedAvatarPath)) { // Use a try block to catch IOExceptions, to // handle the case of the file already being // opened by another process. System.IO.File.Delete(deletedAvatarPath); } } string rootAvatarFolder = HttpContext.Current.Server.MapPath("~/Content/Avatars"); var provider = new StreamProvider(rootAvatarFolder); // Read the form data await request.Content.ReadAsMultipartAsync(provider); string fileName = string.Empty; using (UoW) { var file = provider.FileData.FirstOrDefault(); if (file != null) { AppUser user = UoW.Users.GetByEmail(CurrentUser.Email); fileName = file.LocalFileName.Substring(file.LocalFileName.LastIndexOf('\\') + 1); user.Avatar = fileName; UoW.Complete(); } else { throw new ApplicationOperationException("For an avatar you need one image", HttpStatusCode.BadRequest); } } return(GetAvatarBase64(fileName)); } catch (System.Exception e) { throw new ApplicationOperationException(e.Message, HttpStatusCode.InternalServerError); } }
//TODO:Да се прегледат методите, които определят дали може да бъде обработен обекта public void SaveConfiguration(Dictionary <TParamName, object> configRepresenation, Uri resourse, string fileFormat) { if (StreamProvider == null) { throw new AccessViolationException("Stream Provider not set!"); } foreach (IConfigTarget <TParamName> s in Targets) { if (s.CanBuild(fileFormat)) { StreamProvider.SetResource(s.Build(configRepresenation), resourse); } } }
/// <summary> /// Converts gzipped backfill data. Reads all *.gz files in the raw directory and attempts to convert them /// </summary> public void ConvertHistoricalData() { foreach (var archive in _rawSourceDirectory.GetFiles("*.gz", SearchOption.TopDirectoryOnly)) { Log.Trace($"PsychSignalDataConverter.ConvertBackfill(): Begin converting historical data for file: {archive.FullName}"); using (var archiveStream = StreamProvider.ForExtension(".gz").Open(archive.FullName).First()) { Convert(archiveStream); } Log.Trace($"PsychSignalDataConverter.ConvertBackfill(): Finished converting historical data for file: {archive.FullName}"); } Dispose(); }
public override void Execute(string line, StreamProvider streams, MusicManager musicManager) { var xmls = new XmlSerializer(typeof(List<NormalPlaylist>)); using (var stringWriter = new StringWriter()) using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Encoding = Encoding.UTF8 })) { var playlists = musicManager.Playlists.ToList(); foreach (var playlist in playlists) { foreach (var track in playlist.Tracks.Where(track => !track.TrackExists)) { playlist.Tracks.Remove(track); } } xmls.Serialize(xmlWriter, playlists); var binaryWriter = streams.BinaryWriter; var bytesToSend = Encoding.UTF8.GetBytes(stringWriter.ToString()); binaryWriter.Write(bytesToSend.Length); MessageBox.Show(bytesToSend.ToString()); MessageBox.Show(Encoding.UTF8.GetString(bytesToSend)); const int bufferSize = 1024; int noOfPackets = (int)Math.Ceiling((double)bytesToSend.Length / bufferSize); int totalLength = bytesToSend.Length; for (int i = 0; i < noOfPackets; i++) { int currentPacketLength; if (totalLength > bufferSize) { currentPacketLength = bufferSize; totalLength -= currentPacketLength; } else { currentPacketLength = totalLength; } var sendingBuffer = new byte[currentPacketLength]; binaryWriter.Write(sendingBuffer, 0, sendingBuffer.Length); binaryWriter.Flush(); } } }
public override void Execute(string line, StreamProvider streams, MusicManager musicManager) { _action.Invoke(line, streams, musicManager); }
public override void Execute(string line, StreamProvider streams, MusicManager musicManager) { var command = Regex.Match(line, RegexPattern).Groups["command"].Value; MediaCommands.First(x => Regex.IsMatch(command, x.RegexPattern)).Execute(line, streams, musicManager); }