/// <summary> /// Get Dublin Core metadata using MetadataUtility class. /// Feature is supported in version 18.5 or greater of the API /// </summary> public static void GetDublinCoreMetadata() { try { string[] files = Directory.GetFiles(XMPFilesDirectory); foreach (string file in files) { try { DublinCoreMetadata dublinCoreMetadata = (DublinCoreMetadata)MetadataUtility.ExtractSpecificMetadata(file, MetadataType.DublinCore); if (dublinCoreMetadata != null) { Console.WriteLine(dublinCoreMetadata.Creator); Console.WriteLine(dublinCoreMetadata.Format); Console.WriteLine(dublinCoreMetadata.Subject); } } catch { Console.WriteLine("Could not load {0}", file); } } } catch (Exception) { throw; } }
/// <summary> /// Removes GPS data and updates the image files in a directory /// </summary> public void RemoveExifLocation() { // Map directory in source folder string sourceDirectoryPath = Common.MapSourceFilePath(this.CleanerPath); // get array of file in specific directory string[] files = Directory.GetFiles(sourceDirectoryPath); foreach (string path in files) { // get EXIF data if exists ExifMetadata exifMetadata = (ExifMetadata)MetadataUtility.ExtractSpecificMetadata(path, MetadataType.EXIF); if (exifMetadata != null) { ExifInfo exifInfo = exifMetadata.Data; if (exifInfo.GPSData != null) { // set altitude, latitude and longitude to null values exifInfo.GPSData.Altitude = null; exifInfo.GPSData.Latitude = null; exifInfo.GPSData.LatitudeRef = null; exifInfo.GPSData.Longitude = null; exifInfo.GPSData.LongitudeRef = null; } // and update file MetadataUtility.UpdateMetadata(path, exifMetadata); } } Console.WriteLine("Press any key to exit."); }
public void UpdateXMPData() { try { //ExStart:UpdateXMP // path to the modified file string filePath = "Images/Jpeg/sample.jpg"; // get xmp wrapper XmpPacketWrapper xmpWrapper = MetadataUtility.ExtractXmpPackage(filePath); // if wrapper is null if (xmpWrapper == null) { // create it xmpWrapper = new XmpPacketWrapper(); } // create package XmpPackage addingSchema = new XmpPackage("rs", "http://www.metadataworkinggroup.com/schemas/regions/"); // set date property addingSchema.AddValue("rs:createdDate", DateTime.UtcNow); // set string property addingSchema.AddValue("rs:File", "File name"); //initialze unordered xmp array XmpArray managersArray = new XmpArray(XmpArrayType.UNORDERED); managersArray.AddItem("Joe Doe"); managersArray.AddItem("Adam White"); // set array property addingSchema.SetArray("rs:managers", managersArray); // initialize xmp language alternative LangAlt availableDays = new LangAlt(); // add first value for 'en-us' language availableDays.AddLanguage("en-us", "Tue"); // add second value for 'en-us' languge availableDays.AddLanguage("en-us", "Fri"); // set LangAlt property addingSchema.SetLangAlt("rs:days", availableDays); // update xmp wrapper with new schema xmpWrapper.AddPackage(addingSchema); // create XmpMetadata with updated wrapper XmpMetadata xmpMetadata = new XmpMetadata(); xmpMetadata.XmpPacket = xmpWrapper; // update XMP MetadataUtility.UpdateMetadata(filePath, xmpMetadata); //ExEnd:UpdateXMP } catch (Exception exp) { } }
/// <summary> /// Shows how to read APEV2 tags in MP3 format /// Feature is supported in version 17.9.0 or greater of the API /// </summary> public static void ReadApev2Tag() { //ExStart:ReadApev2TagMp3 // initialize Mp3Format. If file is not Mp3 then appropriate exception will throw. using (Mp3Format mp3Format = new Mp3Format(Common.MapSourceFilePath(filePath))) { // get APEv2 tag Apev2Metadata apev2 = mp3Format.APEv2; //NOTE: please remember you may use different approaches to getting metadata // second approach apev2 = (Apev2Metadata)MetadataUtility.ExtractSpecificMetadata(Common.MapSourceFilePath(filePath), MetadataType.APEv2); // check if APEv2 tag is presented if (apev2 != null) { // Display tag properties Console.WriteLine("Album: {0}", apev2.Album); Console.WriteLine("Artist: {0}", apev2.Artist); Console.WriteLine("Comment: {0}", apev2.Comment); Console.WriteLine("Genre: {0}", apev2.Genre); Console.WriteLine("Title: {0}", apev2.Title); Console.WriteLine("Track: {0}", apev2.Track); } } //ExEnd:ReadApev2TagMp3 }
protected PropertyService <TEntity> Property <TProp>(Expression <Func <TEntity, TProp> > prop) { var property = _properties.Find(p => p.Name == MetadataUtility.PropName(prop)); var propertyService = PropertyService <TEntity> .Create(property); return(propertyService); }
protected Association <TEntity> Associate <TProperty>( Expression <Func <TEntity, TProperty> > association) { return(new Association <TEntity>() { AssociationProperty = MetadataUtility.PropName(association) }); }
void SaveWarehouseMap() { dynamic rootdata = new JObject(); rootdata.Name = "我的仓库"; rootdata.FormatVersion = "1.0"; rootdata = CreateMapJson(rootnode, rootdata); MetadataUtility.SaveMetadata(Constrants.WAREHOUSE_MAP_STORE_STR, rootdata); }
void RenderWarehouseMap() { rootnode.Items.Clear(); dynamic jo = MetadataUtility.LoadMetadata(Constrants.WAREHOUSE_MAP_STORE_STR); if (jo != null) { rootnode.Header = jo.Name; RenderWarehouseSubNode(rootnode, jo); } }
protected EntityConfiguration() { _properties = new List <Property>(); typeof(TEntity).GetProperties(BindingFlags.Public | BindingFlags.Instance) .ToList() .ForEach(prop => _properties.Add(new Property { Name = prop.Name, Title = prop.Name, Type = MetadataUtility.PropType(prop) })); }
public void TestInitialize() { this.orgProxy = new MOrganizationServiceProxy(); orgProxy.BehaveAsDefaultValue(); BCrmWebSvc.MockCrmSvc(orgProxy); BCrmWebSvc.MockDoLogin(); BCrmWebSvc.MockOrganizationVersion(); crmaction = new CrmServiceClient(this.orgProxy); MDynamicEntityUtility.AllInstances.GetAttributeDataByEntityStringGuidStringArray = (dynamicEntUtl, str, inguid, arrstr) => { return(new List <AttributeData>()); }; MetadataUtility.ClearCachedEntityMetadata("account"); }
/// <summary> /// Reads MPEG audio information /// </summary> /// public static void ReadMPEGAudioInfo() { try { //ExStart:ReadMPEGAudioInfo // get MPEG audio info MpegAudio audioInfo = (MpegAudio)MetadataUtility.ExtractSpecificMetadata(Common.MapSourceFilePath(filePath), MetadataType.MpegAudio); // another approach is to use Mp3Format directly: // init Mp3Format class // Mp3Format mp3Format = new Mp3Format((Common.MapSourceFilePath(filePath)); // get MPEG audio info // MpegAudio audioInfo = mp3Format.AudioDetails; // display MPEG audio version Console.WriteLine("MPEG audio version: {0}", audioInfo.MpegAudioVersion); // display layer version Console.WriteLine("Layer version: {0}", audioInfo.LayerVersion); // display header offset Console.WriteLine("Header offset: {0}", audioInfo.HeaderPosition); // display bitrate Console.WriteLine("Bitrate: {0}", audioInfo.Bitrate); // display frequency Console.WriteLine("Frequency: {0}", audioInfo.Frequency); // display channel mode Console.WriteLine("Channel mode: {0}", audioInfo.ChannelMode); // display original bit Console.WriteLine("Is original: {0}", audioInfo.IsOriginal); // display protected bit Console.WriteLine("Is protected: {0}", audioInfo.IsProtected); //ExEnd:ReadMPEGAudioInfo } catch (Exception ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// Read ImageCover using Metadata Utility /// Feature is supported in version 18.4 or greater of the API /// </summary> public static void ReadImageCoverMetadataUtility() { try { //Read DublinCore Metadata ThumbnailMetadata thumbnailMetadata = (ThumbnailMetadata)MetadataUtility.ExtractSpecificMetadata(Common.MapSourceFilePath(filePath), MetadataType.Thumbnail); if (thumbnailMetadata != null) { // get Mime Type Console.WriteLine(thumbnailMetadata.MimeType); // get Length Console.WriteLine(thumbnailMetadata.ImageData.Length); } } catch (Exception exp) { Console.WriteLine(exp.Message); } }
/// <summary> ///Retrieves MIME type of the specific file or file stream. /// </summary> /// <param name="directory">Directory Path</param> public static void GetMimeType(string directory) { try { //ExStart: MIMETypeDetection // get all files inside directory string[] files = Directory.GetFiles(Common.MapSourceFilePath(directory)); foreach (string path in files) { // get MIME type string string mimeType = MetadataUtility.GetMimeType(path); Console.WriteLine("File: {0}, MIME type: {1}", Path.GetFileName(path), mimeType); } //ExEnd: MIMETypeDetection } catch (Exception exp) { Console.WriteLine("Exception occurred: " + exp.Message); } }
//ExEnd:FormatRecognizer //ExStart:MetadataComparer /// <summary> /// Compares and finds metadata difference of two files /// </summary> /// <param name="filePath1">First file path</param> /// <param name="filePath2">Second file path</param> public static void CompareFilesMetadata(string filePath1, string filePath2) { try { // path to the document filePath1 = Common.MapSourceFilePath(filePath1); // path to the compared document filePath2 = Common.MapSourceFilePath(filePath2); // get diffences between metadata MetadataPropertyCollection diffenceProperties = MetadataUtility.CompareDoc(filePath1, filePath2); // go through collection and show differences foreach (MetadataProperty property in diffenceProperties) { Console.WriteLine("Property = {0}, value = {1}", property.Name, property.Value); } } catch (Exception exp) { Console.WriteLine(exp.Message); } }
public async Task <Song> PostAsync(IFormFile file, int accountID, int storageID) { Song song = null; switch (storageID) { case (int)StorageType.Dropbox: { var accountStorage = _dbContext.AccountStorages.Find(accountID, (int)StorageType.Dropbox); DropboxJson dbxJson = JsonConvert.DeserializeObject <DropboxJson>(accountStorage.JsonData); using var dbx = new DropboxClient(dbxJson.JwtToken); var uploaded = await dbx.Files.UploadAsync( "/" + file.FileName, WriteMode.Add.Instance, strictConflict : true, body : file.OpenReadStream()); song = new Song() { AccountID = accountID, FileName = file.FileName, StorageSongID = uploaded.Id, StorageID = storageID, Playlists = new List <Playlist>() }; break; } case (int)StorageType.GoogleDrive: { using var s = new FileStream("googleDriveSecrets.json", FileMode.Open, FileAccess.Read); UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(s).Secrets, _gdScopes, accountID.ToString(), CancellationToken.None, _GDdataStore); using var gdService = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Garmusic", }); var ids = gdService.Files.GenerateIds(); ids.Count = 1; Google.Apis.Drive.v3.Data.File f = new Google.Apis.Drive.v3.Data.File(); f.Id = (await ids.ExecuteAsync()).Ids[0]; f.Name = file.FileName; await gdService.Files.Create(f, file.OpenReadStream(), "audio/mpeg").UploadAsync(); song = new Song() { AccountID = accountID, FileName = file.FileName, StorageSongID = f.Id, StorageID = storageID, Playlists = new List <Playlist>() }; break; } } using Stream stream = file.OpenReadStream(); MetadataUtility.FillMetadata(song, stream); await PostAsync(song); await SaveAsync(); return(song); }
public object Metadatas() { return(MetadataUtility.GetAllMetadata()); }
private void openToolStripMenuItem_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { tabMetadataTypes.TabPages.Clear(); DataSet ds; using (StreamReader streamReader = new StreamReader(openFileDialog.FileName)) { try { ds = ExportFacade.ExportToDataSet(streamReader.BaseStream); } catch (GroupDocs.Metadata.Exceptions.InvalidFormatException) { MessageBox.Show(@"This format is not supported"); return; } catch (GroupDocs.Metadata.Exceptions.GroupDocsException ex) { MessageBox.Show(string.Format("Error: {0}", ex.Message)); return; } } propertiesEditor = null; saveMetadata.FileName = openFileDialog.FileName; if (ds.Tables.Count == 0) { MessageBox.Show(@"Metadata not found"); } else { for (int i = 0; i < ds.Tables.Count; i++) { DataTable table = ds.Tables[i]; Control child; string tabName; switch (table.TableName.ToLower()) { case "xmp": tabName = "XMP metadata"; XmpPacketWrapper xmpPacket = MetadataUtility.ExtractXmpPackage(openFileDialog.FileName); ucXmpTree xmpTree = new ucXmpTree(); xmpTree.LoadControl(xmpPacket); ResizeControl(xmpTree); child = xmpTree; break; case "pdf": case "doc": case "xls": case "ppt": tabName = "Document properties"; MetadataPropertyCollection properties = MetadataUtility.ExtractDocumentProperties(openFileDialog.FileName); propertiesEditor = new ucPropertiesEditor(); ResizeControl(propertiesEditor); propertiesEditor.LoadControl(properties); child = propertiesEditor; break; default: tabName = string.Format("{0} metadata", table.TableName); DataGridView gridView = new DataGridView(); ResizeControl(gridView); gridView.DataSource = table; child = gridView; break; } tabMetadataTypes.TabPages.Add(tabName); TabPage addedTab = tabMetadataTypes.TabPages[i]; //addedTab.Anchor = AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Top; addedTab.Controls.Add(child); } tabMetadataTypes.Visible = true; } } }
/** * Writes the daventure data into the given file. * * @param folderName * Folder where to write the data * @param adventureData * Adventure data to write in the file * @param valid * True if the adventure is valid (can be executed in the * engine), false otherwise * @return True if the operation was succesfully completed, false otherwise */ public static bool writeData(string folderName, AdventureDataControl adventureData, bool valid) { bool dataSaved = false; // Create the necessary elements for building the DOM doc = new XmlDocument(); // Delete the previous XML files in the root of the project dir //DirectoryInfo projectFolder = new DirectoryInfo(folderName); //if (projectFolder.Exists) //{ // foreach (FileInfo file in projectFolder.GetFiles()) // { // file.Delete(); // } // foreach (DirectoryInfo dir in projectFolder.GetDirectories()) // { // dir.Delete(true); // } //} // Add the special asset files // TODO AssetsController.addSpecialAssets(); /** ******* START WRITING THE DESCRIPTOR ********* */ // Pick the main node for the descriptor XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "no"); //XmlDocumentType typeDescriptor = doc.CreateDocumentType("game-descriptor", "SYSTEM", "descriptor.dtd", null); doc.AppendChild(declaration); //doc.AppendChild(typeDescriptor); if (!valid) { DOMWriterUtility.DOMWrite(doc, adventureData, new DescriptorDOMWriter.InvalidAdventureDataControlParam()); } else { DOMWriterUtility.DOMWrite(doc, adventureData); } doc.Save(folderName + "/descriptor.xml"); /** ******** END WRITING THE DESCRIPTOR ********** */ /** ******* START WRITING THE CHAPTERS ********* */ // Write every chapter //XmlDocumentType typeChapter; int chapterIndex = 1; foreach (Chapter chapter in adventureData.getChapters()) { doc = new XmlDocument(); declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "no"); //typeChapter = doc.CreateDocumentType("eAdventure", "SYSTEM", "eadventure.dtd", null); doc.AppendChild(declaration); //doc.AppendChild(typeChapter); DOMWriterUtility.DOMWrite(doc, chapter); doc.Save(folderName + "/chapter" + chapterIndex++ + ".xml"); } /** ******** END WRITING THE CHAPTERS ********** */ /** ******* START WRITING THE METADATA ********* */ // Pick the main node for the descriptor var metadata = adventureData.getImsCPMetadata(); if (metadata != null) { var xmlMetadata = SerializeToXmlElement(new XmlDocument(), metadata); doc = new XmlDocument(); xmlMetadata = MetadataUtility.CleanXMLGarbage(doc, xmlMetadata); doc.AppendChild(xmlMetadata); doc.Save(folderName + "/imscpmetadata.xml"); } /** ******** END WRITING THE CHAPTERS ********** */ dataSaved = true; return(dataSaved); }
//ExEnd:ApplyLicense public static string CleanFile(string filePath) { try { try { //Apply license... ApplyLicense(); } catch (Exception exp) { MessageBox.Show("In Licence: " + exp.Message); } try { //Recognize format of file... FormatBase format = FormatFactory.RecognizeFormat(filePath); if (format.Type.ToString().ToLower() == "doc" || format.Type.ToString().ToLower() == "docx") { // initialize DocFormat... DocFormat docFormat = format as DocFormat; if (docFormat != null) { // get document properties... DocMetadata properties = new DocMetadata(); properties = docFormat.DocumentProperties; //Remove custom properties... foreach (KeyValuePair <string, PropertyValue> keyValuePair in properties) { if (!properties.IsBuiltIn(keyValuePair.Key)) { properties.Remove(keyValuePair.Key); } } //Reset built-in properties... properties.Author = ""; properties.Category = ""; properties.Comments = ""; properties.Company = ""; properties.ContentStatus = ""; properties.HyperlinkBase = ""; properties.Keywords = ""; properties.Manager = ""; properties.Title = ""; //Update metadata if file... MetadataUtility.UpdateMetadata(filePath, properties); } return("1"); } else if (format.Type.ToString().ToLower() == "xls" || format.Type.ToString().ToLower() == "xlsx") { //Initialize XlsFormat... XlsFormat xlsFormat = format as XlsFormat; if (xlsFormat != null) { //Get document properties... XlsMetadata properties = xlsFormat.DocumentProperties; //Remove custom properties... foreach (KeyValuePair <string, PropertyValue> keyValuePair in properties) { if (!properties.IsBuiltIn(keyValuePair.Key)) { properties.Remove(keyValuePair.Key); } } //Reset built-in properties... properties.Author = ""; properties.Category = ""; properties.Comments = ""; properties.Company = ""; properties.HyperlinkBase = ""; properties.Keywords = ""; properties.Manager = ""; properties.Title = ""; properties.Subject = ""; //Update metadata in files... MetadataUtility.UpdateMetadata(filePath, properties); } return("1"); } else if (format.Type.ToString().ToLower() == "ppt" || format.Type.ToString().ToLower() == "pptx") { //Initialize PptFormat... PptFormat pptFormat = format as PptFormat; if (pptFormat != null) { //Get document properties... PptMetadata properties = pptFormat.DocumentProperties; //Remove custom properties foreach (KeyValuePair <string, PropertyValue> keyValuePair in properties) { if (!properties.IsBuiltIn(keyValuePair.Key)) { properties.Remove(keyValuePair.Key); } } //Reset built-in properties... properties.Author = ""; properties.Category = ""; properties.Comments = ""; properties.Company = ""; properties.Keywords = ""; properties.Manager = ""; properties.Title = ""; properties.Subject = ""; //Update metadata of file... MetadataUtility.UpdateMetadata(filePath, properties); } return("1"); } else if (format.Type.ToString().ToLower() == "pdf") { // initialize PdfFormat... PdfFormat pdfFormat = format as PdfFormat; if (pdfFormat != null) { // get document properties... PdfMetadata properties = pdfFormat.DocumentProperties; // Remove custom properties... foreach (KeyValuePair <string, PropertyValue> keyValuePair in properties) { if (!properties.IsBuiltIn(keyValuePair.Key)) { properties.Remove(keyValuePair.Key); } } //Reset built-in properties... properties.Author = ""; properties.CreatedDate = DateTime.MinValue; properties.Keywords = ""; properties.ModifiedDate = DateTime.MinValue; properties.Subject = ""; properties.TrappedFlag = false; properties.Title = ""; //Update metadata of file... MetadataUtility.UpdateMetadata(filePath, properties); } return("1"); } else if (format.Type.ToString().ToLower() == "jpeg" || format.Type.ToString().ToLower() == "jpg") { //Get EXIF data if exists ExifMetadata exifMetadata = (ExifMetadata)MetadataUtility.ExtractSpecificMetadata(filePath, MetadataType.EXIF); //Get XMP data if exists XmpMetadata xmpMetadata = (XmpMetadata)MetadataUtility.ExtractSpecificMetadata(filePath, MetadataType.XMP); if (exifMetadata != null) { //Remove exif info... ExifInfo exifInfo = exifMetadata.Data; if (exifInfo.GPSData != null) { // set altitude, latitude and longitude to null values exifInfo.GPSData.Altitude = null; exifInfo.GPSData.Latitude = null; exifInfo.GPSData.LatitudeRef = null; exifInfo.GPSData.Longitude = null; exifInfo.GPSData.LongitudeRef = null; } exifInfo.BodySerialNumber = ""; exifInfo.CameraOwnerName = ""; exifInfo.CFAPattern = new byte[] { 0 }; } else { exifMetadata = new ExifMetadata(); } try { //Remove XMP data... XmpPacketWrapper xmpPacket = xmpMetadata.XmpPacket; if (xmpPacket != null) { if (xmpPacket.ContainsPackage(Namespaces.DublinCore)) { // if not - add DublinCore schema xmpPacket.AddPackage(new DublinCorePackage()); DublinCorePackage dublinCorePackage = (DublinCorePackage)xmpPacket.GetPackage(Namespaces.DublinCore); dublinCorePackage.Clear(); xmpMetadata.XmpPacket = xmpPacket; } } } catch { } //Update Exif info... try { MetadataUtility.UpdateMetadata(filePath, exifMetadata); } catch { } //Update XMP data... try { MetadataUtility.UpdateMetadata(filePath, xmpMetadata); } catch { } //Remove custom metadata if any... MetadataUtility.CleanMetadata(filePath); return("1"); } else if (format.Type.ToString().ToLower() == "png") { //Get XMP data... XmpMetadata xmpMetadata = (XmpMetadata)MetadataUtility.ExtractSpecificMetadata(filePath, MetadataType.XMP); try { //Remove XMP metadata... XmpPacketWrapper xmpPacket = xmpMetadata.XmpPacket; if (xmpPacket != null) { if (xmpPacket.ContainsPackage(Namespaces.DublinCore)) { // if not - add DublinCore schema xmpPacket.AddPackage(new DublinCorePackage()); DublinCorePackage dublinCorePackage = (DublinCorePackage)xmpPacket.GetPackage(Namespaces.DublinCore); dublinCorePackage.Clear(); xmpMetadata.XmpPacket = xmpPacket; //Update XMP metadata in file... MetadataUtility.UpdateMetadata(filePath, xmpMetadata); //Clean custom metadata if any... MetadataUtility.CleanMetadata(filePath); } } } catch { } return("1"); } else if (format.Type.ToString().ToLower() == "gif") { //Initialie GifFormat... GifFormat gifFormat = new GifFormat(filePath); //Check if Xmp supported... if (gifFormat.IsSupportedXmp) { //Get XMP data... XmpMetadata xmpMetadata = (XmpMetadata)MetadataUtility.ExtractSpecificMetadata(filePath, MetadataType.XMP); try { XmpPacketWrapper xmpPacket = xmpMetadata.XmpPacket; if (xmpPacket != null) { if (xmpPacket.ContainsPackage(Namespaces.DublinCore)) { // if not - add DublinCore schema xmpPacket.AddPackage(new DublinCorePackage()); DublinCorePackage dublinCorePackage = (DublinCorePackage)xmpPacket.GetPackage(Namespaces.DublinCore); dublinCorePackage.Clear(); xmpMetadata.XmpPacket = xmpPacket; //Update Xmp data in file... MetadataUtility.UpdateMetadata(filePath, xmpMetadata); //Clean custom metadata if any... MetadataUtility.CleanMetadata(filePath); } } } catch { } } return("1"); } else { return("Format not supported."); } } catch (Exception exp) { MessageBox.Show("Exception: " + exp.Message); return(exp.Message); } } catch (Exception exp) { return(exp.Message); } }
/// <summary> /// Stream HTTP Radio /// </summary> private static void StreamHttpRadio(EventState state, CancellationToken token) { try { var request = (HttpWebRequest)WebRequest.Create(state.Url); request.Headers.Add("icy-metadata", "1"); request.ReadWriteTimeout = 10 * 1000; request.Timeout = 10 * 1000; using (var response = (HttpWebResponse)request.GetResponse()) { // Trigger on stream started state.EventHandlers.StreamStartedEventHandlers.Invoke(state, new StreamStartedEventArg()); // Get the position of metadata var metaInt = 0; if (!string.IsNullOrEmpty(response.GetResponseHeader("icy-metaint"))) { metaInt = Convert.ToInt32(response.GetResponseHeader("icy-metaint")); } using (var socketStream = response.GetResponseStream()) { try { var buffer = new byte[(uint)Math.Pow(2, 14)]; var metadataLength = 0; var streamPosition = 0; var bufferPosition = 0; var readBytes = 0; var metadataSb = new StringBuilder(); // Loop forever while (!token.IsCancellationRequested) { if (bufferPosition >= readBytes) { if (socketStream != null) { readBytes = socketStream.Read(buffer, 0, buffer.Length); } bufferPosition = 0; } if (readBytes <= 0) { // Stream ended state.EventHandlers.StreamEndedEventHandlers.Invoke(state, new StreamEndedEventArg()); break; } if (metadataLength == 0) { if (metaInt == 0 || streamPosition + readBytes - bufferPosition <= metaInt) { streamPosition += readBytes - bufferPosition; ProcessStreamData(state, buffer, ref bufferPosition, readBytes - bufferPosition); continue; } ProcessStreamData(state, buffer, ref bufferPosition, metaInt - streamPosition); metadataLength = Convert.ToInt32(buffer[bufferPosition++]) * 16; // Check if there's any metadata, otherwise skip to next block if (metadataLength == 0) { streamPosition = Math.Min(readBytes - bufferPosition, metaInt); ProcessStreamData(state, buffer, ref bufferPosition, streamPosition); continue; } } // Get the metadata and reset the position while (bufferPosition < readBytes) { metadataSb.Append(Convert.ToChar(buffer[bufferPosition++])); metadataLength--; // ReSharper disable once InvertIf if (metadataLength == 0) { var metadata = metadataSb.ToString(); streamPosition = Math.Min(readBytes - bufferPosition, metaInt); ProcessStreamData(state, buffer, ref bufferPosition, streamPosition); // Trigger song change event state.EventHandlers.MetadataChangedHandlers.Invoke(state, new MetadataChangedEventArg { SongMetadata = MetadataUtility.ParseMetadata(metadata) }); // Increment the count state.Count++; metadataSb.Clear(); break; } } } } catch (Exception e) { // Invoke on stream ended state.EventHandlers.StreamEndedEventHandlers.Invoke(state, new StreamEndedEventArg()); state.EventHandlers.StreamFailedHandlers.Invoke(state, new StreamFailedEventArg { Exception = e, Message = "Stream loop threw an exception" }); } } } } catch (Exception e) { // Invoke on stream ended state.EventHandlers.StreamFailedHandlers.Invoke(state, new StreamFailedEventArg { Exception = e, Message = "Stream threw an exception" }); } }