示例#1
0
 public override TemplateObject Handle(TagData data)
 {
     long eid;
     string input = data.GetModifier(0).ToLowerFast();
     if (long.TryParse(input, out eid))
     {
         Entity e = TheServer.GetEntity(eid);
         if (e != null && e is LivingEntity)
         {
             return new LivingEntityTag((LivingEntity)e).Handle(data.Shrink());
         }
     }
     else
     {
         foreach (PlayerEntity p in TheServer.Players)
         {
             if (p.Name.ToLowerFast() == input)
             {
                 return new LivingEntityTag(p).Handle(data.Shrink());
             }
         }
     }
     data.Error("Invalid living entity '" + TagParser.Escape(input) + "'!");
     return new NullTag();
 }
 public void EndSerialize(TagStructureInfo info, byte[] data, uint mainStructOffset)
 {
     _data.MainStructOffset = mainStructOffset;
     _data.Data = data;
     _cache.SetTagData(_stream, Tag, _data);
     _data = null;
 }
示例#3
0
        public override TemplateObject Handle(TagData data)
        {
            if (data.Remaining == 0)
            {
                return this;
            }
            switch (data[0])
            {
                // <--[tag]
                // @Name BulletEntityTag.damage
                // @Group General Information
                // @ReturnType NumberTag
                // @Returns the amount of damage the BulletEntity will do, not counting splash or other special damage.
                // @Example "10" .damage could return "1".
                // -->
                case "damage":
                    return new NumberTag(Internal.Damage).Handle(data.Shrink());
                // <--[tag]
                // @Name BulletEntityTag.splash_size
                // @Group General Information
                // @ReturnType NumberTag
                // @Returns the radius of the BulletEntity's splash damage area in blocks.
                // @Example "10" .splash_size could return "0".
                // -->
                case "splash_size":
                    return new NumberTag(Internal.SplashSize).Handle(data.Shrink());

                default:
                    return new PrimitiveEntityTag((PrimitiveEntity)Internal).Handle(data);
            }
        }
示例#4
0
        public override TemplateObject Handle(TagData data)
        {
            if (data.Remaining == 0)
            {
                return this;
            }
            switch (data[0])
            {
                // <--[tag]
                // @Name PrimitiveEntityTag.velocity
                // @Group General Information
                // @ReturnType LocationTag
                // @Returns the PrimitiveEntity's velocity as a LocationTag.
                // @Example "10" .velocity could return "(40, 10, 0)".
                // -->
                case "velocity":
                    return new LocationTag(Internal.GetVelocity(), null).Handle(data.Shrink());
                // <--[tag]
                // @Name PrimitiveEntityTag.scale
                // @Group General Information
                // @ReturnType LocationTag
                // @Returns the PrimitiveEntity's scale as a LocationTag.
                // @Example "5" .scale could return "(1, 1, 1)".
                // -->
                case "scale":
                    return new LocationTag(Internal.Scale, null).Handle(data.Shrink());

                default:
                    return new EntityTag((Entity)Internal).Handle(data);
            }
        }
示例#5
0
        public override TemplateObject Handle(TagData data)
        {
            if (data.Remaining == 0)
            {
                return this;
            }
            switch (data[0])
            {
                // <--[tag]
                // @Name ModelEntityTag.model
                // @Group General Information
                // @ReturnType TextTag
                // @Returns the ModelEntity's model.
                // @Example "5" .model could return "cube".
                // -->
                case "model":
                    return new TextTag(Internal.model).Handle(data.Shrink());
                // <--[tag]
                // @Name ModelEntityTag.scale
                // @Group General Information
                // @ReturnType LocationTag
                // @Returns the ModelEntity's scale as a LocationTag.
                // @Example "5" .scale could return "(1, 1, 1)".
                // -->
                case "scale":
                    return new LocationTag(Internal.scale, null).Handle(data.Shrink());

                default:
                    return new PhysicsEntityTag((PhysicsEntity)Internal).Handle(data);
            }
        }
示例#6
0
 public override TemplateObject Handle(TagData data)
 {
     if (data.Remaining == 0)
     {
         return this;
     }
     switch (data[0])
     {
         // TODO: Mode, etc.
         // <--[tag]
         // @Name RecipeTag.input
         // @Group General Information
         // @ReturnType ListTag
         // @Returns the result of this recipe.
         // @Example "blocks/grass|blocks/dirt" .result returns "blocks/dirt|".
         // -->
         case "input":
             {
                 ListTag list = new ListTag();
                 for (int i = 0; i < Internal.Input.Length; i++)
                 {
                     list.ListEntries.Add(new ItemTag(Internal.Input[i]));
                 }
                 return list.Handle(data.Shrink());
             }
         default:
             return new TextTag(ToString()).Handle(data);
     }
 }
 public CalibrationData GetClientCalibration(TagData tag)
 {
     CalibrationData result = null;
     string key = KeyFromTagData(tag);
     _calibrations.TryGetValue(key, out result);
     return result;
 }
        public ScanInventory_Form(StartAudit_Form appForm)
        {
            InitializeComponent();
            this.m_appForm = appForm;
            status = "Connect";
            this.m_UpdateReadHandler = new UpdateRead(myUpdateRead);
            this.m_UpdateStatusHandler = new UpdateStatus(myUpdateStatus);
            this.m_ReadTag = new Symbol.RFID3.TagData();

            m_ReaderAPI = m_appForm.m_ReaderAPI;
            m_ReaderAPI = new RFIDReader("127.0.0.1", 5084, 0);

            this.m_AntennaInfoForm = m_appForm.m_AntennaInfoForm;
            this.m_AntennaConfigForm = m_appForm.m_AntennaConfigForm;
            this.m_PostFilterForm = m_appForm.m_PostFilterForm;
            this.m_AccessFilterForm = m_appForm.m_AccessFilterForm;
            this.m_TriggerForm = m_appForm.m_TriggerForm;

            this.m_ReaderMgmt = new ReaderManagement();
            this.m_TagTable = new Hashtable(1023);
            this.m_AccessOpResult = new AccessOperationResult();
            this.m_IsConnected = false;
            this.m_TagTotalCount = 0;
            this.m_ReaderInitiatedDisconnectionReceived = false;
            this.m_isBeepingEnabled = true;
        }
示例#9
0
 public override TemplateObject Handle(TagData data)
 {
     if (data.Remaining == 0)
     {
         return this;
     }
     switch (data[0])
     {
         // <--[tag]
         // @Name MaterialTag.name
         // @Group General Information
         // @ReturnType TextTag
         // @Returns the material's name.
         // @Example "stone" .name returns "stone".
         // -->
         case "name":
             return new TextTag(ToString()).Handle(data.Shrink());
         // <--[tag]
         // @Name MaterialTag.speed_mod
         // @Group General Information
         // @ReturnType NumberTag
         // @Returns the material's speed modification.
         // @Example "stone" .speed_mod returns "1.1".
         // -->
         case "speed_mod":
             return new NumberTag(Internal.GetSpeedMod()).Handle(data.Shrink());
         // TODO: More tags
         default:
             return new TextTag(ToString()).Handle(data);
     }
 }
示例#10
0
        public override TemplateObject Handle(TagData data)
        {
            if (data.Remaining == 0)
            {
                return this;
            }
            switch (data[0])
            {
                // <--[tag]
                // @Name PhysicsEntityTag.mass
                // @Group General Information
                // @ReturnType NumberTag
                // @Returns the PhysicsEntity's mass.
                // @Example "10" .mass could return "40".
                // -->
                case "mass":
                    return new NumberTag(Internal.Mass).Handle(data.Shrink());
                // <--[tag]
                // @Name PhysicsEntityTag.bounciness
                // @Group General Information
                // @ReturnType NumberTag
                // @Returns the PhysicsEntity's bounciness (how much it bounces).
                // @Example "10" .bounciness could return "0.5".
                // -->
                case "bounciness":
                    return new NumberTag(Internal.GetBounciness()).Handle(data.Shrink());

                default:
                    return new EntityTag((Entity)Internal).Handle(data);
            }
        }
示例#11
0
 public override TemplateObject Handle(TagData data)
 {
     if (data.Remaining == 0)
     {
         return this;
     }
     switch (data[0])
     {
         // <--[tag]
         // @Name EntityTag.iid
         // @Group General Information
         // @ReturnType NumberTag
         // @Returns this entity's instance ID number.
         // @Example "2" .iid returns "2".
         // -->
         case "iid":
             return new NumberTag(Internal.GetInstanceID()).Handle(data.Shrink());
         // <--[tag]
         // @Name EntityTag.location
         // @Group Status
         // @ReturnType LocationTag
         // @Returns the entity's current world position.
         // @Example "2" .location returns "(5, 10, 15)".
         // -->
         case "location":
             return new LocationTag(Internal.transform.position).Handle(data.Shrink());
         default:
             return new TextTag(ToString()).Handle(data.Shrink());
     }
 }
示例#12
0
 public override TemplateObject Handle(TagData data)
 {
     if (data.Remaining == 0)
     {
         return this;
     }
     switch (data[0])
     {
         // <--[tag]
         // @Name ResourceTag.asset
         // @Group General Information
         // @ReturnType ResourceAssetTag
         // @Returns the resource asset that this resource is based off.
         // @Example "2" .asset returns "Bush_Jade".
         // -->
         case "asset":
             return new ResourceAssetTag(Internal.asset).Handle(data.Shrink());
         // <--[tag]
         // @Name ResourceTag.health
         // @Group General Information
         // @ReturnType NumberTag
         // @Returns the current health of the resource.
         // @Example "2" .health returns "1".
         // -->
         case "health":
             return new NumberTag(Internal.health).Handle(data.Shrink());
         default:
             return new EntityTag(Internal.model.gameObject).Handle(data);
     }
 }
示例#13
0
 public override TemplateObject Handle(TagData data)
 {
     if (data.Remaining == 0)
     {
         return this;
     }
     switch (data[0])
     {
         // <--[tag]
         // @Name PlayerTag.name
         // @Group General Information
         // @ReturnType TextTag
         // @Returns the player's name.
         // @Example "Fortifier" .name returns "Fortifier".
         // -->
         case "name":
             return new TextTag(Internal.Name).Handle(data.Shrink());
         // <--[tag]
         // @Name PlayerTag.health
         // @Group Status
         // @ReturnType NumberTag
         // @Returns the player's health.
         // @Example "Fortifier" .health could return "100".
         // -->
         case "health":
             return new NumberTag(Internal.Health).Handle(data.Shrink());
         // <--[tag]
         // @Name PlayerTag.is_afk
         // @Group Status
         // @ReturnType BooleanTag
         // @Returns whether the player is AFK (Away From Keyboard) currently.
         // @Other this is detected as "no input whatsoever" from the player. Any number of things could potentially knock a player out of "AFK" status.
         // -->
         case "is_afk":
             return new BooleanTag(Internal.IsAFK).Handle(data.Shrink());
         // <--[tag]
         // @Name PlayerTag.afk_time
         // @Group Status
         // @ReturnType IntegerTag
         // @Returns the amount of time the player has been AFK (Away From Keyboard) currently. This is a number in seconds.
         // @Other this is detected as "no input whatsoever" from the player. Any number of things could potentially knock a player out of "AFK" status.
         // @Example "mcmonkey" .afk_time could return "5".
         // -->
         case "afk_time":
             return new IntegerTag(Internal.TimeAFK).Handle(data.Shrink());
         // <--[tag]
         // @Name PlayerTag.held_item
         // @Group Status
         // @ReturnType ItemTag
         // @Returns the item the player is currently holding.
         // @Example "mcmonkey" .held_item could return "bullet".
         // -->
         case "held_item":
             return new ItemTag(Internal.Items.GetItemForSlot(Internal.Items.cItem)).Handle(data.Shrink());
         default:
             return new LivingEntityTag((LivingEntity)Internal).Handle(data);
     }
 }
示例#14
0
 public override TemplateObject Handle(TagData data)
 {
     if (data.Remaining == 0)
     {
         return this;
     }
     switch (data[0])
     {
         // <--[tag]
         // @Name AnimalTag.is_alive
         // @Group General Information
         // @ReturnType BooleanTag
         // @Returns whether the animal is still alive.
         // @Example "2" .is_alive returns "true".
         // -->
         case "is_alive":
             return new BooleanTag(!Internal.isDead).Handle(data.Shrink());
         // <--[tag]
         // @Name AnimalTag.name
         // @Group General Information
         // @ReturnType TextTag
         // @Returns the name of the animal's type.
         // @Example "2" .name returns "Cow".
         // -->
         case "name":
             return new TextTag(Internal.asset.name).Handle(data.Shrink());
         // <--[tag]
         // @Name AnimalTag.aid
         // @Group General Information
         // @ReturnType NumberTag
         // @Returns the animal ID number of the animal.
         // @Example "2" .aid returns "1".
         // -->
         case "aid":
             return new NumberTag(Internal.index).Handle(data.Shrink());
         // <--[tag]
         // @Name AnimalTag.health
         // @Group General Information
         // @ReturnType NumberTag
         // @Returns the animal's current health.
         // @Example "2" .health returns "96".
         // -->
         case "health":
             return new NumberTag(Internal.health).Handle(data.Shrink());
         // <--[tag]
         // <--[tag]
         // @Name AnimalTag.asset
         // @Group General Information
         // @ReturnType AnimalAssetTag
         // @Returns the animal asset that this animal is based off.
         // @Example "2" .asset returns "Cow".
         // -->
         case "asset":
             return new AnimalAssetTag(Internal.asset).Handle(data.Shrink());
         default:
             return new EntityTag(Internal.gameObject).Handle(data);
     }
 }
 public void RemoveCalibration(TagData tag)
 {
     string key = KeyFromTagData(tag);
     if (_calibrations.ContainsKey(key))
     {
         _calibrations.Remove(key);
         SaveData();
     }
 }
示例#16
0
 public override TemplateObject Handle(TagData data)
 {
     if (data.Remaining == 0)
     {
         return this;
     }
     switch (data[0])
     {
         // <--[tag]
         // @Name VehicleTag.name
         // @Group General Information
         // @ReturnType TextTag
         // @Returns the name of the vehicle's type.
         // @Example "2" .name returns "APC_Forest".
         // -->
         case "name":
             return new TextTag(Internal.asset.name).Handle(data.Shrink());
         // <--[tag]
         // @Name VehicleTag.vid
         // @Group General Information
         // @ReturnType NumberTag
         // @Returns the vehicle ID number of the vehicle.
         // @Example "2" .vid returns "1".
         // -->
         case "vid":
             return new NumberTag(Internal.id).Handle(data.Shrink());
         // <--[tag]
         // @Name VehicleTag.asset
         // @Group General Information
         // @ReturnType VehicleAssetTag
         // @Returns the vehicle asset that this vehicle is based off.
         // @Example "2" .asset returns "APC_Forest".
         // -->
         case "asset":
             return new VehicleAssetTag(Internal.asset).Handle(data.Shrink());
         // <--[tag]
         // @Name VehicleTag.health
         // @Group General Information
         // @ReturnType NumberTag
         // @Returns the current health of the vehicle.
         // @Example "2" .health returns "99".
         // -->
         case "health":
             return new NumberTag(Internal.health).Handle(data.Shrink());
         // <--[tag]
         // @Name VehicleTag.id
         // @Group General Information
         // @ReturnType NumberTag
         // @Returns the current amount of fuel in the vehicle.
         // @Example "2" .fuel returns "67".
         // -->
         case "fuel":
             return new NumberTag(Internal.fuel).Handle(data.Shrink());
         default:
             return new EntityTag(Internal.gameObject).Handle(data);
     }
 }
 public override TemplateObject Handle(TagData data)
 {
     EffectAssetTag atag = EffectAssetTag.For(data.GetModifier(0));
     if (atag == null)
     {
         return new TextTag("&{NULL}").Handle(data.Shrink());
     }
     return atag.Handle(data.Shrink());
 }
 public override TemplateObject Handle(TagData data)
 {
     OfflinePlayerTag ptag = OfflinePlayerTag.For(Utilities.StringToULong(data.GetModifier(0)));
     if (ptag == null)
     {
         return new TextTag("&{NULL}").Handle(data.Shrink());
     }
     return ptag.Handle(data.Shrink());
 }
 public override TemplateObject Handle(TagData data)
 {
     ColorTag ctag = ColorTag.For(data.GetModifierObject(0));
     if (ctag == null)
     {
         return new TextTag("&{NULL}");
     }
     return ctag.Handle(data.Shrink());
 }
 public override TemplateObject Handle(TagData data)
 {
     if (data.Remaining == 0)
     {
         return this;
     }
     switch (data[0])
     {
         // <--[tag]
         // @Name ItemAssetTag.name
         // @Group General Information
         // @ReturnType TextTag
         // @Returns the name of the item asset.
         // @Example "Rifle_Maple" .name returns "Rifle_Maple".
         // -->
         case "name":
             return new TextTag(Internal.name).Handle(data.Shrink());
         // <--[tag]
         // @Name ItemAssetTag.formatted_name
         // @Group General Information
         // @ReturnType TextTag
         // @Returns the formatted name of the item asset, as in how players see the name.
         // @Example "Rifle_Maple" .formatted_name returns "Maple Rifle".
         // -->
         case "formatted_name":
             return new TextTag(Internal.itemName).Handle(data.Shrink());
         // <--[tag]
         // @Name ItemAssetTag.description
         // @Group General Information
         // @ReturnType TextTag
         // @Returns the description of the item asset.
         // @Example "Rifle_Maple" .description returns "Maple rifle chambered in Rifle ammunition.".
         // -->
         case "description":
             return new TextTag(Internal.itemDescription).Handle(data.Shrink());
         // <--[tag]
         // @Name ItemAssetTag.is_pro
         // @Group General Information
         // @ReturnType BooleanTag
         // @Returns whether the item asset is considered pro.
         // @Example "Rifle_Maple" .is_pro returns "false".
         // -->
         case "is_pro":
             return new BooleanTag(Internal.isPro).Handle(data.Shrink());
         // <--[tag]
         // @Name ItemAssetTag.id
         // @Group General Information
         // @ReturnType NumberTag
         // @Returns the internal ID of the item asset.
         // @Example "Rifle_Maple" .id returns "474".
         // -->
         case "id":
             return new NumberTag(Internal.id).Handle(data.Shrink());
         default:
             return new TextTag(ToString()).Handle(data);
     }
 }
示例#21
0
 /// <summary>
 /// Builds a memory map for a tag.
 /// </summary>
 /// <param name="data">The tag data to build a memory map for.</param>
 /// <returns>The built map.</returns>
 private static MemoryMap BuildTagMap(TagData data)
 {
     // Create a memory map with a boundary at each fixup target
     // and at the main structure
     var result = new MemoryMap(0, (uint)data.Data.Length);
     result.AddBoundary(data.MainStructOffset);
     result.AddBoundaries(data.PointerFixups.Select(f => f.TargetOffset));
     return result;
 }
 public override TemplateObject Handle(TagData data)
 {
     string iname = data.GetModifier(0);
     WorldObjectAssetTag itag = WorldObjectAssetTag.For(iname);
     if (itag == null)
     {
         return new TextTag("&{NULL}").Handle(data.Shrink());
     }
     return itag.Handle(data.Shrink());
 }
 public override TemplateObject Handle(TagData data)
 {
     string pname = data.GetModifier(0);
     PlayerTag ptag = PlayerTag.For(pname);
     if (ptag == null)
     {
         return new TextTag("&{NULL}").Handle(data.Shrink());
     }
     return ptag.Handle(data.Shrink());
 }
 public override TemplateObject Handle(TagData data)
 {
     string lname = data.GetModifier(0);
     LocationTag ltag = LocationTag.For(lname);
     if (ltag == null)
     {
         return new TextTag("&{NULL}").Handle(data.Shrink());
     }
     return ltag.Handle(data.Shrink());
 }
示例#25
0
 public override TemplateObject Handle(TagData data)
 {
     string lname = data.GetModifier(0);
     LocationTag ltag = LocationTag.For(TheServer, data, lname);
     if (ltag == null)
     {
         data.Error("Invalid location '" + TagParser.Escape(lname) + "'!");
         return new NullTag();
     }
     return ltag.Handle(data.Shrink());
 }
示例#26
0
 public override TemplateObject Handle(TagData data)
 {
     TemplateObject rdata = data.GetModifierObject(0);
     RecipeTag rtag = RecipeTag.For(TheServer, data, rdata);
     if (rtag == null)
     {
         data.Error("Invalid recipe '" + TagParser.Escape(rdata.ToString()) + "'!");
         return new NullTag();
     }
     return rtag.Handle(data.Shrink());
 }
示例#27
0
 public TagLayoutGuess Analyze(TagData data)
 {
     _tagMap = BuildTagMap(data);
     _dataFixupsByWriteOffset = data.PointerFixups.ToDictionary(f => f.WriteOffset);
     _resourceFixupsByWriteOffset = new HashSet<uint>(data.ResourcePointerOffsets);
     using (var reader = new BinaryReader(new MemoryStream(data.Data)))
     {
         reader.BaseStream.Position = data.MainStructOffset;
         return AnalyzeStructure(reader, 1);
     }
 }
示例#28
0
 public override TemplateObject Handle(TagData data)
 {
     string rname = data.GetModifier(0);
     World w = TheServer.GetWorld(rname);
     if (w != null)
     {
         return new WorldTag(w);
     }
     data.Error("Invalid world '" + TagParser.Escape(rname) + "'!");
     return new NullTag();
 }
示例#29
0
 public TagData ReadLogFile(FileInfo file)
 {
     var channeldata = new TagData();
     foreach (var line in File.ReadLines(file.FullName))
         //Parse the string
     {
         string[] words = line.Split(',');
         channeldata.Data.Add(new DataSample() {ActualValue = words[1], Time = Convert.ToDateTime(words[0])});
     }
     return channeldata;
 }
示例#30
0
 public override TemplateObject Handle(TagData data)
 {
     TemplateObject pname = data.GetModifierObject(0);
     ItemTag ptag = ItemTag.For(TheServer, pname);
     if (ptag == null)
     {
         data.Error("Invalid player '" + TagParser.Escape(pname.ToString()) + "'!");
         return new NullTag();
     }
     return ptag.Handle(data.Shrink());
 }
示例#31
0
        /// <summary>
        /// Read Notify event handler.
        /// Gets the TagID and calls the callback function attached to the wrapper instance.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void Events_ReadNotify(object sender, Events.ReadEventArgs args)
        {
            try
            {
                if (_callback == null)
                {
                    return;
                }

                TagData tagData = args.ReadEventData.TagData;
                if (tagData != null && tagData.OpStatus == ACCESS_OPERATION_STATUS.ACCESS_SUCCESS)
                {
                    this._callback(tagData.TagID);
                    //Log("Handled RFID Reader Tag Event");
                }

                //purge tags in reader queue
                _reader.Actions.PurgeTags();
            }
            catch (Exception)
            {
                //Log("Error reading tag");
            }
        }
示例#32
0
        static void AddKillOp()
        {
            // Create a tag operation sequence.
            TagOpSequence seq = new TagOpSequence();

            // Apply the target tag to the tag operation sequence.
            seq.TargetTag = target;

            // Define a tag kill operation.
            TagKillOp killOp = new TagKillOp();

            // Specify the kill password for this tag.
            // The kill password cannot be zero.
            killOp.KillPassword = TagData.FromHexString(KILL_PW);

            // Add this tag write op to the tag operation sequence.
            seq.Ops.Add(killOp);

            // Add the tag operation sequence to the reader.
            reader.AddOpSequence(seq);

            // Start the reader
            reader.Start();
        }
示例#33
0
        public static LocationTag For(Server tserver, TagData dat, string input)
        {
            string[] spl = input.Split(',');
            Location coord;

            if (spl.Length < 3)
            {
                dat.Error("Invalid LocationTag input!");
            }
            coord.X = NumberTag.For(dat, spl[0]).Internal;
            coord.Y = NumberTag.For(dat, spl[1]).Internal;
            coord.Z = NumberTag.For(dat, spl[2]).Internal;
            World w = null;

            if (spl.Length >= 4)
            {
                w = tserver.GetWorld(spl[3]);
                if (w == null)
                {
                    dat.Error("Invalid world for LocationTag input!");
                }
            }
            return(new LocationTag(coord, w));
        }
示例#34
0
        /// <summary>Create tag in tag storage from given TagData</summary>
        /// <param name="data"></param>
        /// <returns></returns>
        protected virtual ID CreateTag(TagData data)
        {
            var template       = new TemplateItem(Database.GetItem(BucketConfigurationSettings.TagRepositoryId));
            var repositoryItem = Context.ContentDatabase.GetItem(_tagRepositoryId);

            if (repositoryItem == null)
            {
                return(null);
            }
            var name = ItemUtil.ProposeValidItemName(RemoveDiacritics(data.TagName), "tag");

            using (new SecurityDisabler())
            {
                var tagItem = repositoryItem.Add(name, template);
                if (name == data.TagName)
                {
                    return(tagItem.ID);
                }
                tagItem.Editing.BeginEdit();
                tagItem.Fields["__Display Name"].Value = data.TagName;
                tagItem.Editing.EndEdit();
                return(tagItem.ID);
            }
        }
示例#35
0
        static void BulkRead(TagData accessPassword, MemoryBank bank, ushort wordPointer, ushort wordCount)
        {
            TagOpSequence seq;
            TagReadOp     op;

            // Initialize variables
            tagData        = "";
            numOpsExecuted = 0;
            numOpsAdded    = 0;

            // Each TagReadOp can only access up to 32 words.
            // So, we need to break this read up into multiple operations.
            while (wordCount > 0)
            {
                // Define a new tag operation sequence.
                seq = new TagOpSequence();

                // Define a tag read operation
                op = new TagReadOp();
                op.AccessPassword = accessPassword;
                op.MemoryBank     = bank;
                op.WordPointer    = wordPointer;
                op.WordCount      = (wordCount < 32) ? wordCount : (ushort)32;

                // Add the read op to the operation sequence
                seq.Ops.Add(op);

                // Adjust the word count and pointer for the next reader operation
                wordCount   -= op.WordCount;
                wordPointer += op.WordCount;

                // Add the operation sequence to the reader
                reader.AddOpSequence(seq);
                numOpsAdded++;
            }
        }
示例#36
0
        /// <summary>
        /// 将源码编译成js代码
        /// </summary>
        /// <param name="filename">文件名称</param>
        /// <param name="source">源码</param>
        /// <param name="isCreateFile">是否产生编译后的文件,如果产生文件,则文件产生的目录为Host的根路径下的Compiled/View/</param>
        /// <param name="outfilepath">产生编译后的js文件的存放路径,只有在isCreateFile=true的时候有效</param>
        /// <returns></returns>
        public string Compile(string filename, string source, bool isCreateFile)
        {
            var rtn = "";
            var p   = new TagParameter();
            var d   = new TagData();

            p.RootPath       = _context.RootPath;
            p.CommonLibPath  = _context.CommonLibPath;
            p.RunTimeLibPath = _context.RunTimeLibPath;
            p.Text           = source;
            p.SetValue("__tags__", _context.AllTags);
            ModuleProxyManager.Call <HostViewProxy, TagParameter, TagData>(p, d);
            rtn = d.ParsedText;
            if (isCreateFile)
            {
                if (!Directory.Exists(p.RunTimeLibPath + HostJsConstants.VIEW_PATH))
                {
                    Directory.CreateDirectory(p.RunTimeLibPath + HostJsConstants.VIEW_PATH);
                }
                var path = p.RunTimeLibPath + HostJsConstants.VIEW_PATH + filename + ".hjs";
                File.WriteAllText(path, rtn, Encoding.UTF8);
            }
            return(rtn);
        }
示例#37
0
        protected override int write(TagData tag, BinaryWriter w, string zone)
        {
            int result = 6;

            w.Write(Utils.BuildStrictLengthStringBytes(tag.Title, 32, 0, Encoding.UTF8));
            w.Write(Utils.BuildStrictLengthStringBytes(tag.Album, 32, 0, Encoding.UTF8));
            w.Write(Utils.BuildStrictLengthStringBytes(tag.Copyright, 32, 0, Encoding.UTF8));
            string str = "";

            if (AdditionalFields.ContainsKey("EMULATOR"))
            {
                str = AdditionalFields["EMULATOR"];
            }
            w.Write(Utils.BuildStrictLengthStringBytes(str, 32, 0, Encoding.UTF8));
            str = "";
            if (AdditionalFields.ContainsKey("DUMPER"))
            {
                str = AdditionalFields["DUMPER"];
            }
            w.Write(Utils.BuildStrictLengthStringBytes(str, 32, 0, Encoding.UTF8));
            w.Write(Utils.BuildStrictLengthStringBytes(tag.Comment, 256, 0, Encoding.UTF8));

            return(result);
        }
示例#38
0
        public void processTag(TagData tag)
        {
            bool   isFound    = false;
            string tagID      = tag.TagID;
            string tagIDshort = tagID.Substring(tag.TagID.Length - 8);


            lock (_TagTable.SyncRoot)
            {
                isFound = _TagTable.ContainsKey(tagID);
            }

            if (!isFound)
            {
                lock (_TagTable.SyncRoot)
                {
                    _TagTable.Add(tagID, tag);
                }

                _Tags.Push(tagIDshort);

                updateListView();
            }
        }
示例#39
0
        private void UpdateRecord(MusicRecord record, TagData tag)
        {
            switch (record)
            {
            case MusicRecord.SongTitle:
            case MusicRecord.ArtistName:
            case MusicRecord.AlbumTitle:
            case MusicRecord.TrackTitle:
            case MusicRecord.Filename:
                if (tag is TagDataString stringTagData)
                {
                    RequestHandler.UpdateRecord(Data, record, stringTagData.NewValue);
                }
                break;

            case MusicRecord.AlbumYear:
            case MusicRecord.TrackNumber:
            case MusicRecord.DiscNumber:
                if (tag is TagDataInt intTagData)
                {
                    RequestHandler.UpdateRecord(Data, record, intTagData.NewInt);
                }
                break;

            case MusicRecord.RecordingType:
                if (tag is TagDataEnum recordingTypeTagData)
                {
                    RequestHandler.UpdateRecord(Data, record, recordingTypeTagData.NewInt);
                }
                break;

            case MusicRecord.MAX:
            default:
                throw new Exception($"Invalid MusicRecord for Updating: {record}");
            }
        }
示例#40
0
        private void initSampleTestData()
        {
            notEmptyFile = notEmptyFile_sample;

            testData = new TagData();

            testData.AdditionalFields = new List <MetaFieldInfo>();
            testData.AdditionalFields.Add(new MetaFieldInfo(MetaDataIOFactory.TAG_ANY, "sample.manufacturer", "1"));
            testData.AdditionalFields.Add(new MetaFieldInfo(MetaDataIOFactory.TAG_ANY, "sample.product", "2"));
            testData.AdditionalFields.Add(new MetaFieldInfo(MetaDataIOFactory.TAG_ANY, "sample.period", "3"));
            testData.AdditionalFields.Add(new MetaFieldInfo(MetaDataIOFactory.TAG_ANY, "sample.MIDIUnityNote", "4"));
            testData.AdditionalFields.Add(new MetaFieldInfo(MetaDataIOFactory.TAG_ANY, "sample.MIDIPitchFraction", "5"));
            testData.AdditionalFields.Add(new MetaFieldInfo(MetaDataIOFactory.TAG_ANY, "sample.SMPTEFormat", "24"));
            testData.AdditionalFields.Add(new MetaFieldInfo(MetaDataIOFactory.TAG_ANY, "sample.SMPTEOffset.Hours", "-1"));
            testData.AdditionalFields.Add(new MetaFieldInfo(MetaDataIOFactory.TAG_ANY, "sample.SMPTEOffset.Minutes", "10"));
            testData.AdditionalFields.Add(new MetaFieldInfo(MetaDataIOFactory.TAG_ANY, "sample.SMPTEOffset.Seconds", "20"));
            testData.AdditionalFields.Add(new MetaFieldInfo(MetaDataIOFactory.TAG_ANY, "sample.SMPTEOffset.Frames", "30"));
            testData.AdditionalFields.Add(new MetaFieldInfo(MetaDataIOFactory.TAG_ANY, "sample.SampleLoop[0].CuePointId", "11"));
            testData.AdditionalFields.Add(new MetaFieldInfo(MetaDataIOFactory.TAG_ANY, "sample.SampleLoop[0].Type", "1"));
            testData.AdditionalFields.Add(new MetaFieldInfo(MetaDataIOFactory.TAG_ANY, "sample.SampleLoop[0].Start", "123"));
            testData.AdditionalFields.Add(new MetaFieldInfo(MetaDataIOFactory.TAG_ANY, "sample.SampleLoop[0].End", "456"));
            testData.AdditionalFields.Add(new MetaFieldInfo(MetaDataIOFactory.TAG_ANY, "sample.SampleLoop[0].Fraction", "8"));
            testData.AdditionalFields.Add(new MetaFieldInfo(MetaDataIOFactory.TAG_ANY, "sample.SampleLoop[0].PlayCount", "2"));
        }
示例#41
0
        /// <summary>Returns a FunctionTag for the given text.</summary>
        /// <param name="data">The data.</param>
        /// <param name="input">The input text.</param>
        /// <returns>A TagTypeTag.</returns>
        public static FunctionTag For(TagData data, string input)
        {
            if (!input.Contains('|'))
            {
                CommandScript script = data.Engine.GetFunction(input);
                if (script == null)
                {
                    throw data.Error($"Unknown script name '{TextStyle.Separate}{input}{TextStyle.Base}'.");
                }
                return(new FunctionTag(script));
            }
            ListTag list = ListTag.For(input);

            if (list.Internal.Count < 2)
            {
                throw data.Error("Cannot construct FunctionTag with empty input.");
            }
            string type = list.Internal[0].ToString();

            if (type == "anon")
            {
                if (list.Internal.Count < 4)
                {
                    throw data.Error("Cannot construct FunctionTag without start line, name, and commandlist input.");
                }
                string        name      = list.Internal[1].ToString();
                int           startLine = (int)IntegerTag.For(list.Internal[2], data).Internal;
                string        commands  = list.Internal[3].ToString();
                CommandScript script    = ScriptParser.SeparateCommands(name, commands, data.Engine, startLine, data.DBMode);
                if (script == null)
                {
                    throw data.Error("Anonymous function failed to generate.");
                }
                script.TypeName        = CommandScript.TYPE_NAME_ANONYMOUS;
                script.IsAnonymous     = true;
                script.AnonymousString = input["anon|".Length..];
示例#42
0
        /// <summary>
        ///     Processes the hide line when line starts with.
        /// </summary>
        public static void ProcessHideLineWhenLineStartsWith(Scope scope)
        {
            var getTextAtLine     = scope.Get(GetTextAtLine);
            var textSnapshotLines = scope.Get(TextSnapshotLines);
            var currentLineIndex  = scope.Get(CurrentLineIndex);
            var options           = scope.Get(Option);
            var addTagSpan        = scope.Get(AddTagSpan);

            var startLineIndex = currentLineIndex;

            var i = currentLineIndex;

            while (LineStartsWith(scope, i, options.HideLineWhenLineStartsWith))
            {
                i++;
                scope.Update(IsAnyValueProcessed, true);
            }

            if (!scope.Get(IsAnyValueProcessed))
            {
                return;
            }

            i--; // come back to last successfull line

            var span = HideLines(textSnapshotLines, currentLineIndex, i);

            var tag = new TagData {
                Span = span
            };

            addTagSpan(new TagSpan <TagData>(span, tag));

            // focus to next not processed position
            scope.Update(CurrentLineIndex, i + 1);
        }
示例#43
0
        private int writeExtendedHeaderMeta(TagData tag, BinaryWriter w)
        {
            long   beginPos, frameSizePos, counterPos, finalFramePos;
            ushort counter;

            beginPos = w.BaseStream.Position;
            w.Write(WMA_METADATA_OBJECT_ID);
            frameSizePos = w.BaseStream.Position;
            w.Write((ulong)0);  // Frame size placeholder to be rewritten at the end of the method
            counterPos = w.BaseStream.Position;
            w.Write((ushort)0); // Counter placeholder to be rewritten at the end of the method

            counter = writeExtendedMeta(tag, w);

            // Go back to frame size locations to write their actual size
            finalFramePos = w.BaseStream.Position;
            w.BaseStream.Seek(frameSizePos, SeekOrigin.Begin);
            w.Write(Convert.ToUInt64(finalFramePos - beginPos));
            w.BaseStream.Seek(counterPos, SeekOrigin.Begin);
            w.Write(counter);
            w.BaseStream.Seek(finalFramePos, SeekOrigin.Begin);

            return(counter);
        }
示例#44
0
        protected override int write(TagData tag, BinaryWriter w, string zone)
        {
            int result = 0;

            if (zone.Equals(ZONE_HEADER))
            {
                w.Write(Utils.Latin1Encoding.GetBytes(Utils.BuildStrictLengthString(tag.Title, 32, '\0')));
                w.Write(Utils.Latin1Encoding.GetBytes(Utils.BuildStrictLengthString(tag.Album, 32, '\0')));
                w.Write(Utils.Latin1Encoding.GetBytes(Utils.BuildStrictLengthString(AdditionalFields[HEADER_DUMPERNAME.ToString()], 16, '\0')));
                w.Write(Utils.Latin1Encoding.GetBytes(Utils.BuildStrictLengthString(tag.Comment, 32, '\0')));
                w.Write(Utils.Latin1Encoding.GetBytes(AdditionalFields[HEADER_DUMPDATE.ToString()]));
                w.Write(Utils.Latin1Encoding.GetBytes(AdditionalFields[HEADER_SONGLENGTH.ToString()]));
                w.Write(Utils.Latin1Encoding.GetBytes(AdditionalFields[HEADER_FADE.ToString()]));
                w.Write(Utils.Latin1Encoding.GetBytes(Utils.BuildStrictLengthString(tag.Artist, 32, '\0')));
                result = 8;
            }
            else if (zone.Equals(ZONE_EXTENDED))
            {
                // SPC specific : are only allowed to appear in extended metadata fields that
                //   - either do not exist in header
                //   - or have been truncated when written in header
                long sizePos;

                w.Write(Utils.Latin1Encoding.GetBytes(XTENDED_TAG));
                sizePos = w.BaseStream.Position;
                w.Write(0); // Size placeholder; to be rewritten with actual value at the end of the method

                IDictionary <byte, string> map = tag.ToMap();

                // Supported textual fields
                foreach (byte frameType in map.Keys)
                {
                    foreach (byte b in extendedFrameMapping.Keys)
                    {
                        if (frameType == extendedFrameMapping[b])
                        {
                            if (map[frameType].Length > 0 && canBeWrittenInExtendedMetadata(frameType, map[frameType])) // No frame with empty value
                            {
                                writeSubChunk(w, b, map[frameType]);
                                result++;
                            }
                            break;
                        }
                    }
                }

                // Other textual fields
                foreach (MetaFieldInfo fieldInfo in tag.AdditionalFields)
                {
                    if ((fieldInfo.TagType.Equals(MetaDataIOFactory.TAG_ANY) || fieldInfo.TagType.Equals(getImplementedTagType())) && !fieldInfo.MarkedForDeletion && !fieldInfo.Zone.Equals(ZONE_HEADER) && fieldInfo.Value.Length > 0)
                    {
                        writeSubChunk(w, Byte.Parse(fieldInfo.NativeFieldCode), fieldInfo.Value);
                        result++;
                    }
                }

                int size = (int)(w.BaseStream.Position - sizePos);
                w.BaseStream.Seek(sizePos, SeekOrigin.Begin);
                w.Write(size);
            }

            return(result);
        }
示例#45
0
        protected void test_RW_Cohabitation(int tagType1, int tagType2, bool canMeta1NotExist = true)
        {
            ConsoleLogger log = new ConsoleLogger();

            // Source : empty file
            string           location         = TestUtils.GetResourceLocationRoot() + emptyFile;
            string           testFileLocation = TestUtils.CopyAsTempTestFile(emptyFile);
            AudioDataManager theFile          = new AudioDataManager(ATL.AudioData.AudioDataIOFactory.GetInstance().GetFromPath(testFileLocation));

            // Check that it is indeed tag-free
            Assert.IsTrue(theFile.ReadFromFile());

            IMetaDataIO meta1 = theFile.getMeta(tagType1);
            IMetaDataIO meta2 = theFile.getMeta(tagType2);

            Assert.IsNotNull(meta1);
            if (canMeta1NotExist)
            {
                Assert.IsFalse(meta1.Exists);
            }
            Assert.IsNotNull(meta2);
            Assert.IsFalse(meta2.Exists);

            long initialPaddingSize1 = meta1.PaddingSize;


            // Construct a new tag with the most basic options (no un supported fields, no pictures)
            TagData theTag1 = new TagData();

            theTag1.Title = "Test1";
            theTag1.Album = "Album1";

            TagData theTag2 = new TagData();

            theTag2.Title = "Test2";
            theTag2.Album = "Album2";

            // Add the new tag and check that it has been indeed added with all the correct information
            Assert.IsTrue(theFile.UpdateTagInFile(theTag1, tagType1));
            Assert.IsTrue(theFile.UpdateTagInFile(theTag2, tagType2));

            // This also tests if physical data can still be read (e.g. native tag has not been scrambled by the apparition of a non-native tag)
            Assert.IsTrue(theFile.ReadFromFile());

            meta1 = theFile.getMeta(tagType1);
            meta2 = theFile.getMeta(tagType2);

            Assert.IsNotNull(meta1);
            Assert.IsTrue(meta1.Exists);

            Assert.IsNotNull(meta2);
            Assert.IsTrue(meta2.Exists);

            Assert.AreEqual("Test1", meta1.Title);
            Assert.AreEqual("Album1", meta1.Album);

            Assert.AreEqual("Test2", meta2.Title);
            Assert.AreEqual("Album2", meta2.Album);

            Assert.IsTrue(theFile.RemoveTagFromFile(tagType1));
            Assert.IsTrue(theFile.ReadFromFile());

            meta1 = theFile.getMeta(tagType1);
            meta2 = theFile.getMeta(tagType2);

            Assert.IsNotNull(meta1);
            if (canMeta1NotExist)
            {
                Assert.IsFalse(meta1.Exists);
            }

            Assert.IsNotNull(meta2);
            Assert.IsTrue(meta2.Exists);

            Assert.AreEqual("Test2", meta2.Title);
            Assert.AreEqual("Album2", meta2.Album);

            Assert.IsTrue(theFile.RemoveTagFromFile(tagType2));
            Assert.IsTrue(theFile.ReadFromFile());

            meta1 = theFile.getMeta(tagType1);
            meta2 = theFile.getMeta(tagType2);

            Assert.IsNotNull(meta1);
            if (canMeta1NotExist)
            {
                Assert.IsFalse(meta1.Exists);
            }

            Assert.IsNotNull(meta2);
            Assert.IsFalse(meta2.Exists);

            // Restore initial padding
            TagData theTagFinal = new TagData();

            theTagFinal.PaddingSize = initialPaddingSize1;
            Assert.IsTrue(theFile.UpdateTagInFile(theTagFinal, tagType1));

            // Check that the resulting file (working copy that has been tagged, then untagged) remains identical to the original file (i.e. no byte lost nor added)
            FileInfo originalFileInfo = new FileInfo(location);
            FileInfo testFileInfo     = new FileInfo(testFileLocation);

            Assert.AreEqual(originalFileInfo.Length, testFileInfo.Length);

            string originalMD5 = TestUtils.GetFileMD5Hash(location);
            string testMD5     = TestUtils.GetFileMD5Hash(testFileLocation);

            Assert.AreEqual(originalMD5, testMD5);

            // Get rid of the working copy
            File.Delete(testFileLocation);
        }
示例#46
0
        public void test_RW_Unsupported_Empty(string fileName, bool deleteTempFile = true)
        {
            ConsoleLogger log = new ConsoleLogger();

            // Source : totally metadata-free file
            string           location         = TestUtils.GetResourceLocationRoot() + fileName;
            string           testFileLocation = TestUtils.CopyAsTempTestFile(fileName);
            AudioDataManager theFile          = new AudioDataManager(ATL.AudioData.AudioDataIOFactory.GetInstance().GetFromPath(testFileLocation));

            // Check that it is indeed tag-free
            Assert.IsTrue(theFile.ReadFromFile());

            Assert.IsNotNull(theFile.getMeta(tagType));
            IMetaDataIO meta = theFile.getMeta(tagType);

            if (canMetaNotExist)
            {
                Assert.IsFalse(meta.Exists);
            }


            bool handleUnsupportedFields   = (testData.AdditionalFields != null && testData.AdditionalFields.Count > 0);
            bool handleUnsupportedPictures = (testData.Pictures != null && testData.Pictures.Count > 0);
            char internationalChar         = supportsInternationalChars ? '父' : '!';

            // Add new unsupported fields
            TagData theTag = new TagData();

            if (handleUnsupportedFields)
            {
                theTag.AdditionalFields.Add(new MetaFieldInfo(tagType, "TEST", "This is a test " + internationalChar));
                theTag.AdditionalFields.Add(new MetaFieldInfo(tagType, "TES2", "This is another test " + internationalChar));
            }

            // Add new unsupported pictures
            PictureInfo picInfo = null;
            byte        found   = 0;

            object pictureCode1, pictureCode2;

            if (tagType.Equals(MetaDataIOFactory.TAG_APE))
            {
                pictureCode1 = "pic1";
                pictureCode2 = "pic2";
            }
            else
            {
                pictureCode1 = 23;
                pictureCode2 = 24;
            }

            if (handleUnsupportedPictures)
            {
                byte[] data = File.ReadAllBytes(TestUtils.GetResourceLocationRoot() + "_Images/pic1.jpg");
                picInfo = PictureInfo.fromBinaryData(data, PIC_TYPE.Unsupported, tagType, pictureCode1);
                theTag.Pictures.Add(picInfo);

                data    = File.ReadAllBytes(TestUtils.GetResourceLocationRoot() + "_Images/pic2.jpg");
                picInfo = PictureInfo.fromBinaryData(data, PIC_TYPE.Unsupported, tagType, pictureCode2);
                theTag.Pictures.Add(picInfo);
            }

            theFile.UpdateTagInFile(theTag, tagType);

            Assert.IsTrue(theFile.ReadFromFile(true, true));

            Assert.IsNotNull(theFile.getMeta(tagType));
            meta = theFile.getMeta(tagType);
            Assert.IsTrue(meta.Exists);

            if (handleUnsupportedFields)
            {
                Assert.AreEqual(2, meta.AdditionalFields.Count);

                Assert.IsTrue(meta.AdditionalFields.Keys.Contains("TEST"));
                Assert.AreEqual("This is a test " + internationalChar, meta.AdditionalFields["TEST"]);

                Assert.IsTrue(meta.AdditionalFields.Keys.Contains("TES2"));
                Assert.AreEqual("This is another test " + internationalChar, meta.AdditionalFields["TES2"]);
            }

            if (handleUnsupportedPictures)
            {
                Assert.AreEqual(2, meta.EmbeddedPictures.Count);
                found = 0;

                foreach (PictureInfo pic in meta.EmbeddedPictures)
                {
                    if (pic.PicType.Equals(PictureInfo.PIC_TYPE.Unsupported) &&
                        (pic.NativePicCode.Equals(pictureCode1) || (pic.NativePicCodeStr != null && pic.NativePicCodeStr.Equals(pictureCode1)))
                        )
                    {
                        using (Image picture = Image.FromStream(new MemoryStream(pic.PictureData)))
                        {
                            Assert.AreEqual(picture.RawFormat, System.Drawing.Imaging.ImageFormat.Jpeg);
                            Assert.AreEqual(600, picture.Height);
                            Assert.AreEqual(900, picture.Width);
                        }
                        found++;
                    }
                    else if (pic.PicType.Equals(PictureInfo.PIC_TYPE.Unsupported) &&
                             (pic.NativePicCode.Equals(pictureCode2) || (pic.NativePicCodeStr != null && pic.NativePicCodeStr.Equals(pictureCode2)))
                             )
                    {
                        using (Image picture = Image.FromStream(new MemoryStream(pic.PictureData)))
                        {
                            Assert.AreEqual(picture.RawFormat, System.Drawing.Imaging.ImageFormat.Jpeg);
                            Assert.AreEqual(290, picture.Height);
                            Assert.AreEqual(900, picture.Width);
                        }
                        found++;
                    }
                }

                Assert.AreEqual(2, found);
            }

            // Remove the additional unsupported field
            if (handleUnsupportedFields)
            {
                theTag = new TagData();
                MetaFieldInfo fieldInfo = new MetaFieldInfo(tagType, "TEST");
                fieldInfo.MarkedForDeletion = true;
                theTag.AdditionalFields.Add(fieldInfo);
            }

            // Remove additional picture
            if (handleUnsupportedPictures)
            {
                picInfo = new PictureInfo(tagType, pictureCode1);
                picInfo.MarkedForDeletion = true;
                theTag.Pictures.Add(picInfo);
            }

            // Add the new tag and check that it has been indeed added with all the correct information
            Assert.IsTrue(theFile.UpdateTagInFile(theTag, tagType));

            Assert.IsTrue(theFile.ReadFromFile(true, true));

            Assert.IsNotNull(theFile.getMeta(tagType));
            meta = theFile.getMeta(tagType);
            Assert.IsTrue(meta.Exists);

            if (handleUnsupportedFields)
            {
                // Additional removed field
                Assert.AreEqual(1, meta.AdditionalFields.Count);
                Assert.IsTrue(meta.AdditionalFields.Keys.Contains("TES2"));
                Assert.AreEqual("This is another test " + internationalChar, meta.AdditionalFields["TES2"]);
            }

            // Pictures
            if (handleUnsupportedPictures)
            {
                Assert.AreEqual(1, meta.EmbeddedPictures.Count);

                found = 0;

                foreach (PictureInfo pic in meta.EmbeddedPictures)
                {
                    if (pic.PicType.Equals(PictureInfo.PIC_TYPE.Unsupported) &&
                        (pic.NativePicCode.Equals(pictureCode2) || (pic.NativePicCodeStr != null && pic.NativePicCodeStr.Equals(pictureCode2)))
                        )
                    {
                        using (Image picture = Image.FromStream(new MemoryStream(pic.PictureData)))
                        {
                            Assert.AreEqual(picture.RawFormat, System.Drawing.Imaging.ImageFormat.Jpeg);
                            Assert.AreEqual(290, picture.Height);
                            Assert.AreEqual(900, picture.Width);
                        }
                        found++;
                    }
                }

                Assert.AreEqual(1, found);
            }

            // Get rid of the working copy
            if (deleteTempFile)
            {
                File.Delete(testFileLocation);
            }
        }
示例#47
0
        public void test_RW_Empty(string fileName, bool deleteTempFile = true, bool sameSizeAfterEdit = false, bool sameBitsAfterEdit = false)
        {
            ConsoleLogger log = new ConsoleLogger();

            // Source : totally metadata-free file
            string           location         = TestUtils.GetResourceLocationRoot() + fileName;
            string           testFileLocation = TestUtils.CopyAsTempTestFile(fileName);
            AudioDataManager theFile          = new AudioDataManager(ATL.AudioData.AudioDataIOFactory.GetInstance().GetFromPath(testFileLocation));


            // Check that it is indeed metadata-free
            Assert.IsTrue(theFile.ReadFromFile());

            Assert.IsNotNull(theFile.getMeta(tagType));
            if (canMetaNotExist)
            {
                Assert.IsFalse(theFile.getMeta(tagType).Exists);
            }

            long initialPaddingSize = theFile.getMeta(tagType).PaddingSize;


            char internationalChar = supportsInternationalChars ? '父' : '!';

            // Construct a new tag
            TagData theTag = new TagData();

            if (testData.Title != null)
            {
                theTag.Title = "Test !!";
            }
            if (testData.Album != null)
            {
                theTag.Album = "Album";
            }
            if (testData.Artist != null)
            {
                theTag.Artist = "Artist";
            }
            if (testData.AlbumArtist != null)
            {
                theTag.AlbumArtist = "Mike";
            }
            if (testData.Comment != null)
            {
                theTag.Comment = "This is a test";
            }
            if (testData.RecordingYear != null)
            {
                theTag.RecordingYear = "2008";
            }
            if (testData.RecordingDate != null)
            {
                theTag.RecordingDate = "2008/01/01";
            }
            if (testData.PublishingDate != null)
            {
                theTag.PublishingDate = "2007/02/02";
            }
            if (testData.Genre != null)
            {
                theTag.Genre = "Merengue";
            }
            if (testData.Rating != null)
            {
                theTag.Rating = 2.5.ToString();
            }
            if (testData.TrackNumber != null)
            {
                theTag.TrackNumber = "01";
            }
            if (testData.TrackTotal != null)
            {
                theTag.TrackTotal = "02";
            }
            if (testData.DiscNumber != null)
            {
                theTag.DiscNumber = "03";
            }
            if (testData.DiscTotal != null)
            {
                theTag.DiscTotal = "04";
            }
            if (testData.Composer != null)
            {
                theTag.Composer = "Me";
            }
            if (testData.Copyright != null)
            {
                theTag.Copyright = "a" + internationalChar + "a";
            }
            if (testData.Conductor != null)
            {
                theTag.Conductor = "John Johnson Jr.";
            }
            if (testData.Publisher != null)
            {
                theTag.Publisher = "Z Corp.";
            }
            if (testData.GeneralDescription != null)
            {
                theTag.GeneralDescription = "Description";
            }

            if (testData.AdditionalFields != null && testData.AdditionalFields.Count > 0)
            {
                theTag.AdditionalFields = new List <MetaFieldInfo>();
                foreach (MetaFieldInfo info in testData.AdditionalFields)
                {
                    theTag.AdditionalFields.Add(info);
                }
            }

            // Add the new tag and check that it has been indeed added with all the correct information
            Assert.IsTrue(theFile.UpdateTagInFile(theTag, tagType));

            Assert.IsTrue(theFile.ReadFromFile(false, true));

            Assert.IsNotNull(theFile.getMeta(tagType));
            IMetaDataIO meta = theFile.getMeta(tagType);

            Assert.IsTrue(meta.Exists);

            if (testData.Title != null)
            {
                Assert.AreEqual("Test !!", meta.Title);
            }
            if (testData.Album != null)
            {
                Assert.AreEqual("Album", meta.Album);
            }
            if (testData.Artist != null)
            {
                Assert.AreEqual("Artist", meta.Artist);
            }
            if (testData.AlbumArtist != null)
            {
                Assert.AreEqual("Mike", meta.AlbumArtist);
            }
            if (testData.Comment != null)
            {
                Assert.AreEqual("This is a test", meta.Comment);
            }
            if (!supportsDateOrYear)
            {
                if (testData.RecordingYear != null)
                {
                    Assert.AreEqual("2008", meta.Year);
                }
                if (testData.RecordingDate != null)
                {
                    DateTime date;
                    Assert.IsTrue(DateTime.TryParse("2008/01/01", out date));
                    Assert.AreEqual(date, meta.Date);
                }
                if (testData.PublishingDate != null)
                {
                    DateTime date;
                    Assert.IsTrue(DateTime.TryParse("2007/02/02", out date));
                    Assert.AreEqual(date, meta.PublishingDate);
                }
            }
            else
            {
                Assert.IsTrue(meta.Year != null || (meta.Date != null && meta.Date > DateTime.MinValue));
                if (meta.Year != null && testData.RecordingYear != null)
                {
                    Assert.AreEqual("2008", meta.Year);
                }
                if (meta.Date != null && meta.Date > DateTime.MinValue && testData.RecordingDate != null)
                {
                    DateTime date;
                    Assert.IsTrue(DateTime.TryParse("2008/01/01", out date));
                    Assert.AreEqual(date, meta.Date);
                }
            }
            if (testData.Genre != null)
            {
                Assert.AreEqual("Merengue", meta.Genre);
            }
            if (testData.Rating != null)
            {
                Assert.AreEqual((float)(2.5 / 5), meta.Popularity);
            }
            if (testData.TrackNumber != null)
            {
                Assert.AreEqual(1, meta.Track);
            }
            if (testData.TrackTotal != null)
            {
                Assert.AreEqual(2, meta.TrackTotal);
            }
            if (testData.DiscNumber != null)
            {
                Assert.AreEqual(3, meta.Disc);
            }
            if (testData.DiscTotal != null)
            {
                Assert.AreEqual(4, meta.DiscTotal);
            }
            if (testData.Composer != null)
            {
                Assert.AreEqual("Me", meta.Composer);
            }
            if (testData.Copyright != null)
            {
                Assert.AreEqual("a" + internationalChar + "a", meta.Copyright);
            }
            if (testData.Conductor != null)
            {
                Assert.AreEqual("John Johnson Jr.", meta.Conductor);
            }
            if (testData.Publisher != null)
            {
                Assert.AreEqual("Z Corp.", meta.Publisher);
            }
            if (testData.GeneralDescription != null)
            {
                Assert.AreEqual("Description", meta.GeneralDescription);
            }

            if (testData.AdditionalFields != null && testData.AdditionalFields.Count > 0)
            {
                foreach (MetaFieldInfo info in testData.AdditionalFields)
                {
                    Assert.IsTrue(meta.AdditionalFields.ContainsKey(info.NativeFieldCode));
                    Assert.AreEqual(info.Value, meta.AdditionalFields[info.NativeFieldCode]);
                }
            }

            // Remove the tag and check that it has been indeed removed
            Assert.IsTrue(theFile.RemoveTagFromFile(tagType));

            if (initialPaddingSize > 0)
            {
                TagData paddingRestore = new TagData();
                paddingRestore.PaddingSize = initialPaddingSize;
                Assert.IsTrue(theFile.UpdateTagInFile(paddingRestore, tagType));
            }

            Assert.IsTrue(theFile.ReadFromFile());

            Assert.IsNotNull(theFile.getMeta(tagType));
            if (canMetaNotExist)
            {
                Assert.IsFalse(theFile.getMeta(tagType).Exists);
            }


            // Check that the resulting file (working copy that has been tagged, then untagged) remains identical to the original file (i.e. no byte lost nor added)
            if (sameSizeAfterEdit || sameBitsAfterEdit)
            {
                FileInfo originalFileInfo = new FileInfo(location);
                FileInfo testFileInfo     = new FileInfo(testFileLocation);

                if (sameSizeAfterEdit)
                {
                    Assert.AreEqual(originalFileInfo.Length, testFileInfo.Length);
                }

                if (sameBitsAfterEdit)
                {
                    string originalMD5 = TestUtils.GetFileMD5Hash(location);
                    string testMD5     = TestUtils.GetFileMD5Hash(testFileLocation);

                    Assert.AreEqual(originalMD5, testMD5);
                }
            }

            // Get rid of the working copy
            if (deleteTempFile)
            {
                File.Delete(testFileLocation);
            }
        }
示例#48
0
        protected void test_RW_Existing(string fileName, int initialNbPictures, bool deleteTempFile = true, bool sameSizeAfterEdit = false, bool sameBitsAfterEdit = false)
        {
            ConsoleLogger log = new ConsoleLogger();

            // Source : file with existing tag incl. unsupported picture (Conductor); unsupported field (MOOD)
            string           location         = TestUtils.GetResourceLocationRoot() + fileName;
            string           testFileLocation = TestUtils.CopyAsTempTestFile(fileName);
            AudioDataManager theFile          = new AudioDataManager(ATL.AudioData.AudioDataIOFactory.GetInstance().GetFromPath(testFileLocation));

            // Add a new supported field and a new supported picture
            Assert.IsTrue(theFile.ReadFromFile());

            TagData theTag = new TagData();

            char internationalChar = supportsInternationalChars ? '父' : '!';

            TagData initialTestData = new TagData(testData);

            // These two cases cover all tag capabilities
            if (testData.Title != null)
            {
                theTag.Title = "Test !!" + internationalChar;
            }
            else if (testData.GeneralDescription != null)
            {
                theTag.GeneralDescription = "Description" + internationalChar;
            }

            if (testData.AdditionalFields != null && testData.AdditionalFields.Count > 0)
            {
                theTag.AdditionalFields = new List <MetaFieldInfo>();
                foreach (MetaFieldInfo info in testData.AdditionalFields)
                {
                    theTag.AdditionalFields.Add(info);
                    break; // 1 is enough
                }
            }
            testData = new TagData(theTag);

            PictureInfo picInfo = PictureInfo.fromBinaryData(File.ReadAllBytes(TestUtils.GetResourceLocationRoot() + "_Images/pic1.jpg"), PictureInfo.PIC_TYPE.CD);

            theTag.Pictures.Add(picInfo);


            // Add the new tag and check that it has been indeed added with all the correct information
            Assert.IsTrue(theFile.UpdateTagInFile(theTag, tagType));

            readExistingTagsOnFile(theFile, initialNbPictures + 1);
            Assert.IsNotNull(theFile.getMeta(tagType));
            IMetaDataIO meta = theFile.getMeta(tagType);

            Assert.IsTrue(meta.Exists);

            if (testData.Pictures != null && testData.Pictures.Count > 0)
            {
                int nbFound = 0;
                foreach (PictureInfo pic in meta.EmbeddedPictures)
                {
                    if (pic.PicType.Equals(PictureInfo.PIC_TYPE.CD))
                    {
                        if (tagType.Equals(MetaDataIOFactory.TAG_APE))
                        {
                            Assert.AreEqual("Cover Art (Media)", pic.NativePicCodeStr);
                        }
                        else // ID3v2 convention
                        {
                            Assert.AreEqual(0x06, pic.NativePicCode);
                        }
                        using (Image picture = Image.FromStream(new MemoryStream(pic.PictureData)))
                        {
                            Assert.AreEqual(picture.RawFormat, System.Drawing.Imaging.ImageFormat.Jpeg);
                            Assert.AreEqual(600, picture.Height);
                            Assert.AreEqual(900, picture.Width);
                        }
                        nbFound++;
                        break;
                    }
                }

                Assert.AreEqual(1, nbFound);
            }

            // Remove the additional supported field
            theTag   = new TagData(initialTestData);
            testData = new TagData(initialTestData);

            // Remove additional picture
            picInfo = new PictureInfo(PictureInfo.PIC_TYPE.CD);
            picInfo.MarkedForDeletion = true;
            theTag.Pictures.Add(picInfo);

            // Add the new tag and check that it has been indeed added with all the correct information
            Assert.IsTrue(theFile.UpdateTagInFile(theTag, tagType));

            readExistingTagsOnFile(theFile, initialNbPictures);

            // Additional removed field
            Assert.AreEqual("", theFile.getMeta(tagType).Conductor);


            // Check that the resulting file (working copy that has been tagged, then untagged) remains identical to the original file (i.e. no byte lost nor added)
            if (sameSizeAfterEdit || sameBitsAfterEdit)
            {
                FileInfo originalFileInfo = new FileInfo(location);
                FileInfo testFileInfo     = new FileInfo(testFileLocation);

                if (sameSizeAfterEdit)
                {
                    Assert.AreEqual(originalFileInfo.Length, testFileInfo.Length);
                }

                if (sameBitsAfterEdit)
                {
                    string originalMD5 = TestUtils.GetFileMD5Hash(location);
                    string testMD5     = TestUtils.GetFileMD5Hash(testFileLocation);

                    Assert.AreEqual(originalMD5, testMD5);
                }
            }

            // Get rid of the working copy
            if (deleteTempFile)
            {
                File.Delete(testFileLocation);
            }
        }
示例#49
0
文件: MP4.cs 项目: skolmer/atldotnet
        public void TagIO_RW_MP4_Unsupported_Empty()
        {
            // Source : tag-free M4A
            String           testFileLocation = TestUtils.CopyAsTempTestFile(emptyFile);
            AudioDataManager theFile          = new AudioDataManager(ATL.AudioData.AudioDataIOFactory.GetInstance().GetFromPath(testFileLocation));


            // Check that it is indeed tag-free
            Assert.IsTrue(theFile.ReadFromFile());

            Assert.IsNotNull(theFile.NativeTag);
            Assert.IsFalse(theFile.NativeTag.Exists);


            // Add new unsupported fields
            TagData theTag = new TagData();

            theTag.AdditionalFields.Add(new MetaFieldInfo(MetaDataIOFactory.TAG_NATIVE, "TEST", "This is a test 父"));
            theTag.AdditionalFields.Add(new MetaFieldInfo(MetaDataIOFactory.TAG_NATIVE, "TES2", "This is another test 父"));

            // Add new unsupported pictures
            PictureInfo picInfo = PictureInfo.fromBinaryData(
                File.ReadAllBytes(TestUtils.GetResourceLocationRoot() + "_Images/pic1.jpg"),
                PIC_TYPE.Unsupported,
                MetaDataIOFactory.TAG_NATIVE,
                "1234");

            theTag.Pictures.Add(picInfo);
            picInfo = PictureInfo.fromBinaryData(
                File.ReadAllBytes(TestUtils.GetResourceLocationRoot() + "_Images/pic2.jpg"),
                PIC_TYPE.Unsupported,
                MetaDataIOFactory.TAG_NATIVE,
                "5678");
            theTag.Pictures.Add(picInfo);


            theFile.UpdateTagInFile(theTag, MetaDataIOFactory.TAG_NATIVE);

            Assert.IsTrue(theFile.ReadFromFile(true, true));

            Assert.IsNotNull(theFile.NativeTag);
            Assert.IsTrue(theFile.NativeTag.Exists);

            Assert.AreEqual(2, theFile.NativeTag.AdditionalFields.Count);

            Assert.IsTrue(theFile.NativeTag.AdditionalFields.Keys.Contains("TEST"));
            Assert.AreEqual("This is a test 父", theFile.NativeTag.AdditionalFields["TEST"]);

            Assert.IsTrue(theFile.NativeTag.AdditionalFields.Keys.Contains("TES2"));
            Assert.AreEqual("This is another test 父", theFile.NativeTag.AdditionalFields["TES2"]);

            Assert.AreEqual(2, theFile.NativeTag.EmbeddedPictures.Count);
            byte found = 0;

            foreach (PictureInfo pic in theFile.NativeTag.EmbeddedPictures)
            {
                if (pic.PicType.Equals(PictureInfo.PIC_TYPE.Generic) && (0 == found)) // No custom nor categorized picture type in MP4
                {
                    Image picture = Image.FromStream(new MemoryStream(pic.PictureData));
                    Assert.AreEqual(picture.RawFormat, System.Drawing.Imaging.ImageFormat.Jpeg);
                    Assert.AreEqual(picture.Height, 600);
                    Assert.AreEqual(picture.Width, 900);
                    found++;
                }
                else if (pic.PicType.Equals(PictureInfo.PIC_TYPE.Generic) && (1 == found))  // No custom nor categorized picture type in MP4
                {
                    Image picture = Image.FromStream(new MemoryStream(pic.PictureData));
                    Assert.AreEqual(picture.RawFormat, System.Drawing.Imaging.ImageFormat.Jpeg);
                    Assert.AreEqual(picture.Height, 290);
                    Assert.AreEqual(picture.Width, 900);
                    found++;
                }
            }

            Assert.AreEqual(2, found);

            // Remove the additional unsupported field
            theTag = new TagData();
            MetaFieldInfo fieldInfo = new MetaFieldInfo(MetaDataIOFactory.TAG_NATIVE, "TEST");

            fieldInfo.MarkedForDeletion = true;
            theTag.AdditionalFields.Add(fieldInfo);

            // Remove additional picture
            picInfo = new PictureInfo(PictureInfo.PIC_TYPE.Generic, 1);
            picInfo.MarkedForDeletion = true;
            theTag.Pictures.Add(picInfo);

            // Add the new tag and check that it has been indeed added with all the correct information
            Assert.IsTrue(theFile.UpdateTagInFile(theTag, MetaDataIOFactory.TAG_NATIVE));

            Assert.IsTrue(theFile.ReadFromFile(true, true));

            Assert.IsNotNull(theFile.NativeTag);
            Assert.IsTrue(theFile.NativeTag.Exists);

            // Additional removed field
            Assert.AreEqual(1, theFile.NativeTag.AdditionalFields.Count);
            Assert.IsTrue(theFile.NativeTag.AdditionalFields.Keys.Contains("TES2"));
            Assert.AreEqual("This is another test 父", theFile.NativeTag.AdditionalFields["TES2"]);

            // Pictures
            Assert.AreEqual(1, theFile.NativeTag.EmbeddedPictures.Count);

            found = 0;

            foreach (PictureInfo pic in theFile.NativeTag.EmbeddedPictures)
            {
                if (pic.PicType.Equals(PictureInfo.PIC_TYPE.Generic) && (0 == found))
                {
                    Image picture = Image.FromStream(new MemoryStream(pic.PictureData));
                    Assert.AreEqual(picture.RawFormat, System.Drawing.Imaging.ImageFormat.Jpeg);
                    Assert.AreEqual(picture.Height, 290);
                    Assert.AreEqual(picture.Width, 900);
                    found++;
                }
            }

            Assert.AreEqual(1, found);


            // Get rid of the working copy
            File.Delete(testFileLocation);
        }
示例#50
0
        public void TagIO_RW_VorbisFLAC_Unsupported_Empty()
        {
            // Source : tag-free file
            String           testFileLocation = TestUtils.GetTempTestFile(emptyFile);
            AudioDataManager theFile          = new AudioDataManager(AudioData.AudioDataIOFactory.GetInstance().GetFromPath(testFileLocation));


            // Check that it is indeed tag-free
            Assert.IsTrue(theFile.ReadFromFile());

            Assert.IsNotNull(theFile.NativeTag);
            Assert.IsFalse(theFile.NativeTag.Exists);


            // Add new unsupported fields
            TagData theTag = new TagData();

            theTag.AdditionalFields.Add(new MetaFieldInfo(MetaDataIOFactory.TAG_NATIVE, "TEST", "This is a test 父"));
            theTag.AdditionalFields.Add(new MetaFieldInfo(MetaDataIOFactory.TAG_NATIVE, "TEST2", "This is another test 父"));

            // Add new unsupported pictures
            PictureInfo picInfo = new PictureInfo(Commons.ImageFormat.Jpeg, MetaDataIOFactory.TAG_NATIVE, 0x0A);

            picInfo.PictureData = File.ReadAllBytes(TestUtils.GetResourceLocationRoot() + "_Images/pic1.jpg");
            theTag.Pictures.Add(picInfo);
            picInfo             = new PictureInfo(Commons.ImageFormat.Jpeg, MetaDataIOFactory.TAG_NATIVE, 0x0B);
            picInfo.PictureData = File.ReadAllBytes(TestUtils.GetResourceLocationRoot() + "_Images/pic2.jpg");
            theTag.Pictures.Add(picInfo);


            theFile.UpdateTagInFile(theTag, MetaDataIOFactory.TAG_NATIVE);

            Assert.IsTrue(theFile.ReadFromFile(true, true));

            Assert.IsNotNull(theFile.NativeTag);
            Assert.IsTrue(theFile.NativeTag.Exists);

            Assert.AreEqual(3, theFile.NativeTag.AdditionalFields.Count); // 3 instead of 2 because of the VENDOR field... (specific to VorbisTag)

            Assert.IsTrue(theFile.NativeTag.AdditionalFields.Keys.Contains("TEST"));
            Assert.AreEqual("This is a test 父", theFile.NativeTag.AdditionalFields["TEST"]);

            Assert.IsTrue(theFile.NativeTag.AdditionalFields.Keys.Contains("TEST2"));
            Assert.AreEqual("This is another test 父", theFile.NativeTag.AdditionalFields["TEST2"]);

            Assert.AreEqual(2, theFile.NativeTag.EmbeddedPictures.Count);
            byte found = 0;

            foreach (PictureInfo pic in theFile.NativeTag.EmbeddedPictures)
            {
                if (pic.PicType.Equals(PictureInfo.PIC_TYPE.Unsupported) && pic.NativePicCode.Equals(0x0A))
                {
                    Image picture = Image.FromStream(new MemoryStream(pic.PictureData));
                    Assert.AreEqual(picture.RawFormat, System.Drawing.Imaging.ImageFormat.Jpeg);
                    Assert.AreEqual(picture.Height, 600);
                    Assert.AreEqual(picture.Width, 900);
                    found++;
                }
                else if (pic.PicType.Equals(PictureInfo.PIC_TYPE.Unsupported) && pic.NativePicCode.Equals(0x0B))
                {
                    Image picture = Image.FromStream(new MemoryStream(pic.PictureData));
                    Assert.AreEqual(picture.RawFormat, System.Drawing.Imaging.ImageFormat.Jpeg);
                    Assert.AreEqual(picture.Height, 290);
                    Assert.AreEqual(picture.Width, 900);
                    found++;
                }
            }

            Assert.AreEqual(2, found);

            // Remove the additional unsupported field
            theTag = new TagData();
            MetaFieldInfo fieldInfo = new MetaFieldInfo(MetaDataIOFactory.TAG_NATIVE, "TEST");

            fieldInfo.MarkedForDeletion = true;
            theTag.AdditionalFields.Add(fieldInfo);

            // Remove additional picture
            picInfo = new PictureInfo(Commons.ImageFormat.Jpeg, MetaDataIOFactory.TAG_NATIVE, 0x0A);
            picInfo.MarkedForDeletion = true;
            theTag.Pictures.Add(picInfo);

            // Add the new tag and check that it has been indeed added with all the correct information
            Assert.IsTrue(theFile.UpdateTagInFile(theTag, MetaDataIOFactory.TAG_NATIVE));

            Assert.IsTrue(theFile.ReadFromFile(true, true));

            Assert.IsNotNull(theFile.NativeTag);
            Assert.IsTrue(theFile.NativeTag.Exists);

            // Additional removed field
            Assert.AreEqual(2, theFile.NativeTag.AdditionalFields.Count); // 2 instead of 1 because of the VENDOR field...
            Assert.IsTrue(theFile.NativeTag.AdditionalFields.Keys.Contains("TEST2"));
            Assert.AreEqual("This is another test 父", theFile.NativeTag.AdditionalFields["TEST2"]);

            // Pictures
            Assert.AreEqual(1, theFile.NativeTag.EmbeddedPictures.Count);

            found = 0;

            foreach (PictureInfo pic in theFile.NativeTag.EmbeddedPictures)
            {
                if (pic.PicType.Equals(PictureInfo.PIC_TYPE.Unsupported) && pic.NativePicCode.Equals(0x0B))
                {
                    Image picture = Image.FromStream(new MemoryStream(pic.PictureData));
                    Assert.AreEqual(picture.RawFormat, System.Drawing.Imaging.ImageFormat.Jpeg);
                    Assert.AreEqual(picture.Height, 290);
                    Assert.AreEqual(picture.Width, 900);
                    found++;
                }
            }

            Assert.AreEqual(1, found);


            // Get rid of the working copy
            File.Delete(testFileLocation);
        }
示例#51
0
        private void tagIO_RW_VorbisFLAC_Existing(string fileName, int initialNbPictures, bool deleteTempFile = true)
        {
            ConsoleLogger log = new ConsoleLogger();

            // Source : file with existing tag incl. unsupported picture (Conductor); unsupported field (MOOD)
            string           location         = TestUtils.GetResourceLocationRoot() + fileName;
            string           testFileLocation = TestUtils.GetTempTestFile(fileName);
            AudioDataManager theFile          = new AudioDataManager(AudioData.AudioDataIOFactory.GetInstance().GetFromPath(testFileLocation));

            // Add a new supported field and a new supported picture
            Assert.IsTrue(theFile.ReadFromFile());

            TagData theTag = new TagData();

            theTag.Conductor = "John Jackman";

            PictureInfo picInfo = new PictureInfo(Commons.ImageFormat.Jpeg, PictureInfo.PIC_TYPE.CD);

            picInfo.PictureData = File.ReadAllBytes(TestUtils.GetResourceLocationRoot() + "_Images/pic1.jpg");
            theTag.Pictures.Add(picInfo);


            // Add the new tag and check that it has been indeed added with all the correct information
            Assert.IsTrue(theFile.UpdateTagInFile(theTag, MetaDataIOFactory.TAG_NATIVE));

            readExistingTagsOnFile(theFile, initialNbPictures + 1);

            // Additional supported field
            Assert.AreEqual("John Jackman", theFile.NativeTag.Conductor);

            int nbFound = 0;

            foreach (PictureInfo pic in theFile.NativeTag.EmbeddedPictures)
            {
                if (pic.PicType.Equals(PictureInfo.PIC_TYPE.CD))
                {
                    Assert.AreEqual(pic.NativePicCode, 0x06);
                    Image picture = Image.FromStream(new MemoryStream(pic.PictureData));
                    Assert.AreEqual(picture.RawFormat, System.Drawing.Imaging.ImageFormat.Jpeg);
                    Assert.AreEqual(picture.Height, 600);
                    Assert.AreEqual(picture.Width, 900);
                    nbFound++;
                    break;
                }
            }

            Assert.AreEqual(1, nbFound);

            // Remove the additional supported field
            theTag           = new TagData();
            theTag.Conductor = "";

            // Remove additional picture
            picInfo = new PictureInfo(Commons.ImageFormat.Jpeg, PictureInfo.PIC_TYPE.CD);
            picInfo.MarkedForDeletion = true;
            theTag.Pictures.Add(picInfo);

            // Add the new tag and check that it has been indeed added with all the correct information
            Assert.IsTrue(theFile.UpdateTagInFile(theTag, MetaDataIOFactory.TAG_NATIVE));

            readExistingTagsOnFile(theFile, initialNbPictures);

            // Additional removed field
            Assert.AreEqual("", theFile.NativeTag.Conductor);


            // Check that the resulting file (working copy that has been tagged, then untagged) remains identical to the original file (i.e. no byte lost nor added)
            FileInfo originalFileInfo = new FileInfo(location);
            FileInfo testFileInfo     = new FileInfo(testFileLocation);

            Assert.AreEqual(originalFileInfo.Length, testFileInfo.Length);

            /*
             * Not possible yet due to field order differences
             *
             * string originalMD5 = TestUtils.GetFileMD5Hash(location);
             * string testMD5 = TestUtils.GetFileMD5Hash(testFileLocation);
             *
             * Assert.IsTrue(originalMD5.Equals(testMD5));
             */

            // Get rid of the working copy
            if (deleteTempFile)
            {
                File.Delete(testFileLocation);
            }
        }
示例#52
0
        public override TemplateObject Handle(TagData data)
        {
            if (data.Remaining == 0)
            {
                return(this);
            }
            switch (data[0])
            {
            // <--[tag]
            // @Name ZombieTag.is_alive
            // @Group General Information
            // @ReturnType BooleanTag
            // @Returns whether the zombie is still alive.
            // @Example "2" .is_alive returns "true".
            // -->
            case "is_alive":
                return(new BooleanTag(!Internal.isDead).Handle(data.Shrink()));

            // <--[tag]
            // @Name ZombieTag.zid
            // @Group General Information
            // @ReturnType NumberTag
            // @Returns the zombie ID for this zombie in its region.
            // @Example "2" .zid returns "1".
            // -->
            case "zid":
                return(new NumberTag(Internal.id).Handle(data.Shrink()));

            // <--[tag]
            // @Name ZombieTag.region
            // @Group General Information
            // @ReturnType NumberTag
            // @Returns the zombie region this zombie belongs to.
            // @Example "2" .region returns "4"
            // -->
            case "region":
                return(new NumberTag(Internal.bound).Handle(data.Shrink()));

            // <--[tag]
            // @Name ZombieTag.specialty
            // @Group General Information
            // @ReturnType TextTag
            // @Returns this zombie's specialty. Value can be: NORMAL, MEGA, CRAWLER, SPRINTER.
            // @Example "2" .specialty returns "NORMAL".
            // -->
            case "specialty":
                return(new TextTag(Internal.speciality.ToString()).Handle(data.Shrink()));

            // <--[tag]
            // @Name ZombieTag.health
            // @Group General Information
            // @ReturnType NumberTag
            // @Returns the zombie's current health.
            // @Example "2" .health returns "96".
            // -->
            case "health":
                return(new NumberTag(Internal.health).Handle(data.Shrink()));

            // <--[tag]
            // @Name ZombieTag.max_health
            // @Group General Information
            // @ReturnType NumberTag
            // @Returns the zombie's maximum health.
            // @Example "2" .max_health returns "100".
            // -->
            case "max_health":
                return(new NumberTag(Internal.maxHealth).Handle(data.Shrink()));

            default:
                return(new EntityTag(Internal.gameObject).Handle(data));
            }
        }
示例#53
0
 /// <summary>Get a binary tag relevant to the specified input, erroring on the command system if invalid input is given (Returns null in that case).</summary>
 /// <param name="dat">The TagData used to construct this BinaryTag.</param>
 /// <param name="input">The input to create or get binary data from.</param>
 /// <returns>The binary tag.</returns>
 public static BinaryTag For(TemplateObject input, TagData dat)
 {
     return(input as BinaryTag ?? For(dat, input.ToString()));
 }
示例#54
0
文件: MP4.cs 项目: skolmer/atldotnet
        public void TagIO_RW_MP4_Chapters_QT_Create()
        {
            ConsoleLogger log = new ConsoleLogger();

            Settings.MP4_createNeroChapters = false;
            try
            {
                // Source : file without 'chpl' atom
                String           testFileLocation = TestUtils.CopyAsTempTestFile("AAC/empty.m4a");
                AudioDataManager theFile          = new AudioDataManager(ATL.AudioData.AudioDataIOFactory.GetInstance().GetFromPath(testFileLocation));

                Assert.IsTrue(theFile.ReadFromFile());

                Assert.IsNotNull(theFile.getMeta(tagType));
                Assert.IsFalse(theFile.getMeta(tagType).Exists);

                // Modify elements
                TagData theTag = new TagData();

                Dictionary <uint, ChapterInfo> expectedChaps = new Dictionary <uint, ChapterInfo>();

                theTag.Chapters = new List <ChapterInfo>();

                ChapterInfo ch = new ChapterInfo();
                ch.StartTime = 0;
                ch.Title     = "aaa";

                theTag.Chapters.Add(ch);
                expectedChaps.Add(ch.StartTime, ch);

                ch           = new ChapterInfo();
                ch.StartTime = 1230;
                ch.Title     = "aaa0";

                theTag.Chapters.Add(ch);
                expectedChaps.Add(ch.StartTime, ch);

                // Check if they are persisted properly
                Assert.IsTrue(theFile.UpdateTagInFile(theTag, MetaDataIOFactory.TAG_NATIVE));

                Assert.IsTrue(theFile.ReadFromFile(false, true));
                Assert.IsNotNull(theFile.NativeTag);
                Assert.IsTrue(theFile.NativeTag.Exists);

                Assert.AreEqual(2, theFile.NativeTag.Chapters.Count);

                // Check if values are the same
                int found = 0;
                foreach (ChapterInfo chap in theFile.NativeTag.Chapters)
                {
                    if (expectedChaps.ContainsKey(chap.StartTime))
                    {
                        found++;
                        Assert.AreEqual(expectedChaps[chap.StartTime].StartTime, chap.StartTime);
                        Assert.AreEqual(expectedChaps[chap.StartTime].Title, chap.Title);
                    }
                    else
                    {
                        System.Console.WriteLine(chap.StartTime);
                    }
                }
                Assert.AreEqual(2, found);

                // Get rid of the working copy
                File.Delete(testFileLocation);
            }
            finally
            {
                Settings.MP4_createNeroChapters = true;
            }
        }
示例#55
0
        private int writeContentDescription(TagData tag, BinaryWriter w)
        {
            long beginPos, frameSizePos, finalFramePos;

            beginPos = w.BaseStream.Position;
            w.Write(WMA_CONTENT_DESCRIPTION_ID);
            frameSizePos = w.BaseStream.Position;
            w.Write((ulong)0); // Frame size placeholder to be rewritten at the end of the method

            string title     = "";
            string author    = "";
            string copyright = "";
            string comment   = "";
            string rating    = "";

            IDictionary <byte, String> map = tag.ToMap();

            // Supported textual fields
            foreach (byte frameType in map.Keys)
            {
                if (map[frameType].Length > 0) // No frame with empty value
                {
                    if (TagData.TAG_FIELD_TITLE.Equals(frameType))
                    {
                        title = map[frameType];
                    }
                    else if (TagData.TAG_FIELD_ARTIST.Equals(frameType))
                    {
                        author = map[frameType];
                    }
                    else if (TagData.TAG_FIELD_COPYRIGHT.Equals(frameType))
                    {
                        copyright = map[frameType];
                    }
                    else if (TagData.TAG_FIELD_COMMENT.Equals(frameType))
                    {
                        comment = map[frameType];
                    }
                    else if (TagData.TAG_FIELD_RATING.Equals(frameType))
                    {
                        rating = map[frameType];
                    }
                }
            }

            // Read standard field sizes (+1 for last null characher; x2 for unicode)
            if (title.Length > 0)
            {
                w.Write((ushort)((title.Length + 1) * 2));
            }
            else
            {
                w.Write((ushort)0);
            }
            if (author.Length > 0)
            {
                w.Write((ushort)((author.Length + 1) * 2));
            }
            else
            {
                w.Write((ushort)0);
            }
            if (copyright.Length > 0)
            {
                w.Write((ushort)((copyright.Length + 1) * 2));
            }
            else
            {
                w.Write((ushort)0);
            }
            if (comment.Length > 0)
            {
                w.Write((ushort)((comment.Length + 1) * 2));
            }
            else
            {
                w.Write((ushort)0);
            }
            if (rating.Length > 0)
            {
                w.Write((ushort)((rating.Length + 1) * 2));
            }
            else
            {
                w.Write((ushort)0);
            }

            if (title.Length > 0)
            {
                w.Write(Encoding.Unicode.GetBytes(title + '\0'));
            }
            if (author.Length > 0)
            {
                w.Write(Encoding.Unicode.GetBytes(author + '\0'));
            }
            if (copyright.Length > 0)
            {
                w.Write(Encoding.Unicode.GetBytes(copyright + '\0'));
            }
            if (comment.Length > 0)
            {
                w.Write(Encoding.Unicode.GetBytes(comment + '\0'));
            }
            if (rating.Length > 0)
            {
                w.Write(Encoding.Unicode.GetBytes(rating + '\0'));
            }

            // Go back to frame size locations to write their actual size
            finalFramePos = w.BaseStream.Position;
            w.BaseStream.Seek(frameSizePos, SeekOrigin.Begin);
            w.Write(Convert.ToUInt64(finalFramePos - beginPos));
            w.BaseStream.Seek(finalFramePos, SeekOrigin.Begin);

            return(((title.Length > 0) ? 1 : 0) + ((author.Length > 0) ? 1 : 0) + ((copyright.Length > 0) ? 1 : 0) + ((comment.Length > 0) ? 1 : 0) + ((rating.Length > 0) ? 1 : 0));
        }
示例#56
0
        public void TagIO_RW_VorbisFLAC_Empty()
        {
            ConsoleLogger log = new ConsoleLogger();

            // Source : totally metadata-free OGG
            string           location         = TestUtils.GetResourceLocationRoot() + emptyFile;
            string           testFileLocation = TestUtils.GetTempTestFile(emptyFile);
            AudioDataManager theFile          = new AudioDataManager(AudioData.AudioDataIOFactory.GetInstance().GetFromPath(testFileLocation));


            // Check that it is indeed metadata-free
            Assert.IsTrue(theFile.ReadFromFile());

            Assert.IsNotNull(theFile.NativeTag);
            Assert.IsFalse(theFile.NativeTag.Exists);

            // Construct a new tag
            TagData theTag = new TagData();

            theTag.Title         = "Test !!";
            theTag.Album         = "Album";
            theTag.Artist        = "Artist";
            theTag.AlbumArtist   = "Mike";
            theTag.Comment       = "This is a test";
            theTag.RecordingYear = "2008";
            theTag.RecordingDate = "2008/01/01";
            theTag.Genre         = "Merengue";
            theTag.TrackNumber   = "01/01";
            theTag.DiscNumber    = "2";
            theTag.Rating        = 2.5.ToString();
            theTag.Composer      = "Me";
            theTag.Copyright     = "父";
            theTag.Conductor     = "John Johnson Jr.";

            // Add the new tag and check that it has been indeed added with all the correct information
            Assert.IsTrue(theFile.UpdateTagInFile(theTag, MetaDataIOFactory.TAG_NATIVE));

            Assert.IsTrue(theFile.ReadFromFile());

            Assert.IsNotNull(theFile.NativeTag);
            Assert.IsTrue(theFile.NativeTag.Exists);

            Assert.AreEqual("Test !!", theFile.NativeTag.Title);
            Assert.AreEqual("Album", theFile.NativeTag.Album);
            Assert.AreEqual("Artist", theFile.NativeTag.Artist);
            Assert.AreEqual("Mike", theFile.NativeTag.AlbumArtist);
            Assert.AreEqual("This is a test", theFile.NativeTag.Comment);
            Assert.AreEqual("2008", theFile.NativeTag.Year);
            Assert.AreEqual("Merengue", theFile.NativeTag.Genre);
            Assert.AreEqual(1, theFile.NativeTag.Track);
            Assert.AreEqual(2, theFile.NativeTag.Disc);
            Assert.AreEqual((float)(2.5 / 5), theFile.NativeTag.Popularity);
            Assert.AreEqual("Me", theFile.NativeTag.Composer);
            Assert.AreEqual("父", theFile.NativeTag.Copyright);
            Assert.AreEqual("John Johnson Jr.", theFile.NativeTag.Conductor);


            // Remove the tag and check that it has been indeed removed
            Assert.IsTrue(theFile.RemoveTagFromFile(MetaDataIOFactory.TAG_NATIVE));

            Assert.IsTrue(theFile.ReadFromFile());

            Assert.IsNotNull(theFile.NativeTag);
            Assert.IsFalse(theFile.NativeTag.Exists);


            // Check that the resulting file (working copy that has been tagged, then untagged) remains identical to the original file (i.e. no byte lost nor added)
            FileInfo originalFileInfo = new FileInfo(location);
            FileInfo testFileInfo     = new FileInfo(testFileLocation);

            Assert.AreEqual(originalFileInfo.Length, testFileInfo.Length);

            string originalMD5 = TestUtils.GetFileMD5Hash(location);
            string testMD5     = TestUtils.GetFileMD5Hash(testFileLocation);

            Assert.IsTrue(originalMD5.Equals(testMD5));

            // Get rid of the working copy
            File.Delete(testFileLocation);
        }
示例#57
0
        private int writeExtendedContentDescription(TagData tag, BinaryWriter w)
        {
            long   beginPos, frameSizePos, counterPos, finalFramePos;
            ushort counter = 0;

            beginPos = w.BaseStream.Position;
            w.Write(WMA_EXTENDED_CONTENT_DESCRIPTION_ID);
            frameSizePos = w.BaseStream.Position;
            w.Write((ulong)0);  // Frame size placeholder to be rewritten at the end of the method
            counterPos = w.BaseStream.Position;
            w.Write((ushort)0); // Counter placeholder to be rewritten at the end of the method

            IDictionary <byte, String> map = tag.ToMap();

            // Supported textual fields
            foreach (byte frameType in map.Keys)
            {
                foreach (string s in frameMapping.Keys)
                {
                    if (!embeddedFields.Contains(s) && frameType == frameMapping[s])
                    {
                        if (map[frameType].Length > 0) // No frame with empty value
                        {
                            string value = formatBeforeWriting(frameType, tag, map);

                            writeTextFrame(w, s, value);
                            counter++;
                        }
                        break;
                    }
                }
            }

            // Other textual fields
            foreach (MetaFieldInfo fieldInfo in tag.AdditionalFields)
            {
                if ((fieldInfo.TagType.Equals(MetaDataIOFactory.TAG_ANY) || fieldInfo.TagType.Equals(getImplementedTagType())) && !fieldInfo.MarkedForDeletion && (ZONE_EXTENDED_CONTENT_DESCRIPTION.Equals(fieldInfo.Zone) || "".Equals(fieldInfo.Zone)))
                {
                    writeTextFrame(w, fieldInfo.NativeFieldCode, fieldInfo.Value);
                    counter++;
                }
            }

            // Picture fields
            foreach (PictureInfo picInfo in tag.Pictures)
            {
                if (0 == picInfo.TransientFlag)
                {
                    writePictureFrame(w, picInfo.PictureData, picInfo.MimeType, picInfo.PicType.Equals(PictureInfo.PIC_TYPE.Unsupported) ? (byte)picInfo.NativePicCode : ID3v2.EncodeID3v2PictureType(picInfo.PicType), picInfo.Description);
                    counter++;
                }
            }


            // Go back to frame size locations to write their actual size
            finalFramePos = w.BaseStream.Position;
            w.BaseStream.Seek(frameSizePos, SeekOrigin.Begin);
            w.Write(Convert.ToUInt64(finalFramePos - beginPos));
            w.BaseStream.Seek(counterPos, SeekOrigin.Begin);
            w.Write(counter);
            w.BaseStream.Seek(finalFramePos, SeekOrigin.Begin);

            return(counter);
        }
示例#58
0
    /// <summary>
    /// Call the Computer Vision Service to submit the image.
    /// </summary>
    public IEnumerator AnalyseLastImageCaptured()
    {
        WWWForm webForm = new WWWForm();

        using (UnityWebRequest unityWebRequest = UnityWebRequest.Post(visionAnalysisEndpoint, webForm))
        {
            // gets a byte array out of the saved image
            imageBytes = GetImageAsByteArray(imagePath);
            unityWebRequest.SetRequestHeader("Content-Type", "application/octet-stream");
            unityWebRequest.SetRequestHeader(ocpApimSubscriptionKeyHeader, authorizationKey);

            // the download handler will help receiving the analysis from Azure
            unityWebRequest.downloadHandler = new DownloadHandlerBuffer();

            // the upload handler will help uploading the byte array with the request
            unityWebRequest.uploadHandler             = new UploadHandlerRaw(imageBytes);
            unityWebRequest.uploadHandler.contentType = "application/octet-stream";

            yield return(unityWebRequest.SendWebRequest());

            long responseCode = unityWebRequest.responseCode;

            try
            {
                string jsonResponse = null;
                jsonResponse = unityWebRequest.downloadHandler.text;

                // The response will be in Json format
                // therefore it needs to be deserialized into the classes AnalysedObject and TagData
                AnalysedObject analysedObject = new AnalysedObject();
                analysedObject = JsonUtility.FromJson <AnalysedObject>(jsonResponse);

                if (analysedObject.tags == null)
                {
                    Debug.Log("analysedObject.tagData is null");
                }
                else
                {
                    Dictionary <string, string> tagsDictionary = new Dictionary <string, string>();

                    foreach (TagData td in analysedObject.tags)
                    {
                        TagData tag = td as TagData;
                        if ("fruit".Equals(tag.name, StringComparison.OrdinalIgnoreCase))
                        {
                            tagsDictionary = new Dictionary <string, string>();
                            tagsDictionary.Add(tag.name, "calories:52kcal\nfat:0.2g\npolyunsatured fat:0.1g\ncholesterol:0mg\nsodium:1mg\npotassium:107mg\ncarbs:14g\nfood fiber:1.4g\nsugar: 10g\nproteins:0.3g");
                            break;
                        }
                        else
                        {
                            tagsDictionary.Add(tag.name, tag.confidence.ToString("0.00 \n"));
                        }
                    }

                    ResultsLabel.instance.SetTagsToLastLabel(tagsDictionary);
                }
            }
            catch (Exception exception)
            {
                Debug.Log("Json exception.Message: " + exception.Message);
            }

            yield return(null);
        }
    }
示例#59
0
文件: MP4.cs 项目: skolmer/atldotnet
        public void TagIO_RW_MP4_Chapters_QT_Edit()
        {
            ConsoleLogger log = new ConsoleLogger();

            Settings.MP4_createNeroChapters = false;
            try
            {
                // Source : MP3 with existing tag incl. chapters
                String           testFileLocation = TestUtils.CopyAsTempTestFile("AAC/chapters_QT.m4v");
                AudioDataManager theFile          = new AudioDataManager(ATL.AudioData.AudioDataIOFactory.GetInstance().GetFromPath(testFileLocation));

                // Check if the two fields are indeed accessible
                Assert.IsTrue(theFile.ReadFromFile(false, true));
                Assert.IsNotNull(theFile.NativeTag);
                Assert.IsTrue(theFile.NativeTag.Exists);

                Assert.AreEqual(4, theFile.NativeTag.Chapters.Count);

                Dictionary <uint, ChapterInfo> expectedChaps = new Dictionary <uint, ChapterInfo>();

                ChapterInfo ch = new ChapterInfo();
                ch.StartTime = 0;
                ch.Title     = "Chapter One";
                expectedChaps.Add(ch.StartTime, ch);

                ch           = new ChapterInfo();
                ch.StartTime = 1139;
                ch.Title     = "Chapter 2";
                expectedChaps.Add(ch.StartTime, ch);

                ch           = new ChapterInfo();
                ch.StartTime = 2728;
                ch.Title     = "Chapter 003";
                expectedChaps.Add(ch.StartTime, ch);

                ch           = new ChapterInfo();
                ch.StartTime = 3269;
                ch.Title     = "Chapter 四";
                expectedChaps.Add(ch.StartTime, ch);

                int found = 0;
                foreach (ChapterInfo chap in theFile.NativeTag.Chapters)
                {
                    if (expectedChaps.ContainsKey(chap.StartTime))
                    {
                        found++;
                        Assert.AreEqual(chap.StartTime, expectedChaps[chap.StartTime].StartTime);
                        Assert.AreEqual(chap.Title, expectedChaps[chap.StartTime].Title);
                    }
                    else
                    {
                        System.Console.WriteLine(chap.StartTime);
                    }
                }
                Assert.AreEqual(4, found);

                // Modify elements
                TagData theTag = new TagData();

                theTag.Chapters = new List <ChapterInfo>();
                expectedChaps.Clear();

                ch           = new ChapterInfo();
                ch.StartTime = 0;
                ch.Title     = "aaa";

                theTag.Chapters.Add(ch);
                expectedChaps.Add(ch.StartTime, ch);

                ch           = new ChapterInfo();
                ch.StartTime = 1230;
                ch.Title     = "aaa0";

                theTag.Chapters.Add(ch);
                expectedChaps.Add(ch.StartTime, ch);

                // Check if they are persisted properly
                Assert.IsTrue(theFile.UpdateTagInFile(theTag, MetaDataIOFactory.TAG_NATIVE));

                Assert.IsTrue(theFile.ReadFromFile(false, true));
                Assert.IsNotNull(theFile.NativeTag);
                Assert.IsTrue(theFile.NativeTag.Exists);

                Assert.AreEqual(2, theFile.NativeTag.Chapters.Count);

                // Check if values are the same
                found = 0;
                foreach (ChapterInfo chap in theFile.NativeTag.Chapters)
                {
                    if (expectedChaps.ContainsKey(chap.StartTime))
                    {
                        found++;
                        Assert.AreEqual(chap.StartTime, expectedChaps[chap.StartTime].StartTime);
                        Assert.AreEqual(chap.Title, expectedChaps[chap.StartTime].Title);
                    }
                    else
                    {
                        System.Console.WriteLine(chap.StartTime);
                    }
                }
                Assert.AreEqual(2, found);

                // Get rid of the working copy
                File.Delete(testFileLocation);
            }
            finally
            {
                Settings.MP4_createNeroChapters = true;
            }
        }
示例#60
0
文件: MP4.cs 项目: skolmer/atldotnet
        public void TagIO_RW_MP4_Existing()
        {
            ConsoleLogger log = new ConsoleLogger();

            // Source : MP3 with existing tag incl. unsupported picture (Cover Art (Fronk)); unsupported field (MOOD)
            String           testFileLocation = TestUtils.CopyAsTempTestFile(notEmptyFile);
            AudioDataManager theFile          = new AudioDataManager(ATL.AudioData.AudioDataIOFactory.GetInstance().GetFromPath(testFileLocation));

            // Add a new supported field and a new supported picture
            Assert.IsTrue(theFile.ReadFromFile());

            TagData theTag = new TagData();

            theTag.Conductor = "John Jackman";

            byte[]      data    = File.ReadAllBytes(TestUtils.GetResourceLocationRoot() + "_Images/pic1.png");
            PictureInfo picInfo = PictureInfo.fromBinaryData(data, PictureInfo.PIC_TYPE.Generic, MetaDataIOFactory.TAG_ANY, 14);

            theTag.Pictures.Add(picInfo);


            // Add the new tag and check that it has been indeed added with all the correct information
            Assert.IsTrue(theFile.UpdateTagInFile(theTag, MetaDataIOFactory.TAG_NATIVE));

            readExistingTagsOnFile(theFile, 2);

            // Additional supported field
            Assert.AreEqual("John Jackman", theFile.NativeTag.Conductor);

            byte nbFound = 0;

            foreach (PictureInfo pic in theFile.NativeTag.EmbeddedPictures)
            {
                if (pic.PicType.Equals(PictureInfo.PIC_TYPE.Generic) && (1 == nbFound))
                {
                    Image picture = Image.FromStream(new MemoryStream(pic.PictureData));
                    Assert.AreEqual(picture.RawFormat, System.Drawing.Imaging.ImageFormat.Png);
                    Assert.AreEqual(picture.Width, 175);
                    Assert.AreEqual(picture.Height, 168);
                }
                nbFound++;
            }

            Assert.AreEqual(2, nbFound);

            // Remove the additional supported field
            theTag           = new TagData();
            theTag.Conductor = "";

            // Remove additional picture
            picInfo = new PictureInfo(PictureInfo.PIC_TYPE.Back);
            picInfo.MarkedForDeletion = true;
            theTag.Pictures.Add(picInfo);

            // Add the new tag and check that it has been indeed added with all the correct information
            Assert.IsTrue(theFile.UpdateTagInFile(theTag, MetaDataIOFactory.TAG_NATIVE));

            readExistingTagsOnFile(theFile);

            // Additional removed field
            Assert.AreEqual("", theFile.NativeTag.Conductor);


            // Check that the resulting file (working copy that has been tagged, then untagged) remains identical to the original file (i.e. no byte lost nor added)

            /* NOT POSSIBLE YET mainly due to tag order and tag naming (e.g. "gnre" becoming "©gen") differences
             *          FileInfo originalFileInfo = new FileInfo(location);
             *          FileInfo testFileInfo = new FileInfo(testFileLocation);
             *
             *          Assert.AreEqual(originalFileInfo.Length, testFileInfo.Length);
             *
             *          string originalMD5 = TestUtils.GetFileMD5Hash(location);
             *          string testMD5 = TestUtils.GetFileMD5Hash(testFileLocation);
             *
             *          Assert.IsTrue(originalMD5.Equals(testMD5));
             */
            // Get rid of the working copy
            File.Delete(testFileLocation);
        }