System.IO.BinaryWriter.Write(ushort)

Here are the examples of the csharp api System.IO.BinaryWriter.Write(ushort) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

828 Examples 7

19 Source : CelesteNetBinaryWriter.cs
with MIT License
from 0x0ade

public virtual void WriteSizeDummy(byte size) {
            Flush();
            SizeDummyIndex = BaseStream.Position;

            if (size == 1) {
                SizeDummySize = 1;
                Write((byte) 0);

            } else if (size == 4) {
                SizeDummySize = 4;
                Write((uint) 0);

            } else {
                SizeDummySize = 2;
                Write((ushort) 0);
            }
        }

19 Source : CelesteNetBinaryWriter.cs
with MIT License
from 0x0ade

public virtual void UpdateSizeDummy() {
            if (SizeDummySize == 0)
                return;

            Flush();
            long end = BaseStream.Position;
            long length = end - (SizeDummyIndex + SizeDummySize);

            BaseStream.Seek(SizeDummyIndex, SeekOrigin.Begin);

            if (SizeDummySize == 1) {
                if (length > byte.MaxValue)
                    length = byte.MaxValue;
                Write((byte) length);

            } else if (SizeDummySize == 4) {
                if (length > uint.MaxValue)
                    length = uint.MaxValue;
                Write((uint) length);

            } else {
                if (length > ushort.MaxValue)
                    length = ushort.MaxValue;
                Write((ushort) length);
            }

            Flush();
            BaseStream.Seek(end, SeekOrigin.Begin);
        }

19 Source : ExifWriter.cs
with MIT License
from 0xC0000054

private void WriteDirectory(BinaryWriter writer, Dictionary<ushort, MetadataEntry> tags, List<IFDEntry> entries, long ifdOffset)
        {
            writer.BaseStream.Position = ifdOffset;

            long nextIFDPointerOffset = ifdOffset + sizeof(ushort) + ((long)entries.Count * IFDEntry.SizeOf);

            writer.Write((ushort)entries.Count);

            foreach (IFDEntry entry in entries.OrderBy(e => e.Tag))
            {
                entry.Write(writer);

                if (!TagDataTypeUtil.ValueFitsInOffsetField(entry.Type, entry.Count))
                {
                    long oldPosition = writer.BaseStream.Position;

                    writer.BaseStream.Position = entry.Offset;

                    writer.Write(tags[entry.Tag].GetDataReadOnly());

                    writer.BaseStream.Position = oldPosition;
                }
            }

            writer.BaseStream.Position = nextIFDPointerOffset;
            // There is only one IFD in this directory.
            writer.Write(0);
        }

19 Source : IFDEntry.cs
with MIT License
from 0xC0000054

public void Write(System.IO.BinaryWriter writer)
        {
            writer.Write(this.Tag);
            writer.Write((ushort)this.Type);
            writer.Write(this.Count);
            writer.Write(this.Offset);
        }

19 Source : ExifWriter.cs
with MIT License
from 0xC0000054

private void WriteDirectory(BinaryWriter writer, Dictionary<ushort, MetadataEntry> tags,  List<IFDEntry> entries, long ifdOffset)
        {
            writer.BaseStream.Position = ifdOffset;

            long nextIFDPointerOffset = ifdOffset + sizeof(ushort) + ((long)entries.Count * IFDEntry.SizeOf);

            writer.Write((ushort)entries.Count);

            foreach (IFDEntry entry in entries.OrderBy(e => e.Tag))
            {
                entry.Write(writer);

                if (!TagDataTypeUtil.ValueFitsInOffsetField(entry.Type, entry.Count))
                {
                    long oldPosition = writer.BaseStream.Position;

                    writer.BaseStream.Position = entry.Offset;

                    writer.Write(tags[entry.Tag].GetDataReadOnly());

                    writer.BaseStream.Position = oldPosition;
                }
            }

            writer.BaseStream.Position = nextIFDPointerOffset;
            // There is only one IFD in this directory.
            writer.Write(0);
        }

19 Source : IFDEntry.cs
with MIT License
from 0xC0000054

public void Write(System.IO.BinaryWriter writer)
        {
            writer.Write(Tag);
            writer.Write((ushort)Type);
            writer.Write(Count);
            writer.Write(Offset);
        }

19 Source : InterpretedMotionState.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void Write(this BinaryWriter writer, InterpretedMotionState state)
        {
            var numCommands = state.Commands != null ? state.Commands.Count : 0;

            writer.Write((uint)state.Flags | (uint)numCommands << 7);

            // for MotionStance / MotionCommand, write as ushort
            if ((state.Flags & MovementStateFlag.CurrentStyle) != 0)
                writer.Write((ushort)state.CurrentStyle);

            if ((state.Flags & MovementStateFlag.ForwardCommand) != 0)
                writer.Write((ushort)state.ForwardCommand);

            if ((state.Flags & MovementStateFlag.SideStepCommand) != 0)
                writer.Write((ushort)state.SidestepCommand);

            if ((state.Flags & MovementStateFlag.TurnCommand) != 0)
                writer.Write((ushort)state.TurnCommand);

            if ((state.Flags & MovementStateFlag.ForwardSpeed) != 0)
                writer.Write(state.ForwardSpeed);

            if ((state.Flags & MovementStateFlag.SideStepSpeed) != 0)
                writer.Write(state.SidestepSpeed);

            if ((state.Flags & MovementStateFlag.TurnSpeed) != 0)
                writer.Write(state.TurnSpeed);

            if (numCommands > 0)
            {
                foreach (var motion in state.Commands)
                    writer.Write(motion);
            }

            // align to DWORD boundary
            writer.Align();
        }

19 Source : AllegianceData.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void Write(this BinaryWriter writer, AllegianceData data)
        {
            // ObjectID - characterID - Character ID
            // uint - cpCached - XP gained while logged off
            // uint - cpreplacedhed - Total allegiance XP contribution
            // uint - bitfield - AllegianceIndex
            // Gender - gender - The gender of the character (for determining replacedle)
            // HeritageGroup - hg - The heritage of the character (for determining replacedle)
            // ushort - rank - The numerical rank (1 is lowest).

            // Choose valid sections by masking against bitfield
            // uint - level

            // ushort - loyalty - Character loyalty
            // ushort - leadership - Character leadership

            // Choose based on testing bitfield == 0x4 (HasAllegianceAge)
            // True:
            // uint - timeOnline
            // uint - allegianceAge
            // False: (Not found in later retail pcaps. Probably deprecated.)
            // ulong - uTimeOnline

            // string - name

            uint characterID = 0;
            uint cpCached = 0;
            uint cpreplacedhed = 0;
            var bitfield = AllegianceIndex.HasAllegianceAge | AllegianceIndex.HasPackedLevel;
            var gender = Gender.Female;
            var hg = HeritageGroup.Aluvian;
            ushort rank = 0;
            uint level = 0;
            ushort loyalty = 0;
            ushort leadership = 0;
            ulong uTimeOnline = 0;
            uint timeOnline = 0;
            uint allegianceAge = 0;
            var name = "";

            if (data.Node != null)
            {
                var node = data.Node;
                var playerGuid = node.PlayerGuid;
                var player = PlayerManager.FindByGuid(playerGuid, out var playerIsOnline);
                
                characterID = player.Guid.Full;
                cpCached = (uint)Math.Min(player.AllegianceXPCached, uint.MaxValue);
                cpreplacedhed = (uint)Math.Min(player.AllegianceXPGenerated, uint.MaxValue);

                if (playerIsOnline)
                    bitfield |= AllegianceIndex.LoggedIn;

                if (!node.IsMonarch && node.Player.ExistedBeforeAllegianceXpChanges)
                    bitfield |= AllegianceIndex.MayPreplacedupExperience;

                gender = (Gender)player.Gender;
                hg = (HeritageGroup)player.Heritage;
                rank = (ushort)node.Rank;
                level = (uint)player.Level;
                loyalty = (ushort)player.GetCurrentLoyalty();
                leadership = (ushort)player.GetCurrentLeadership();
                
                //if (!node.IsMonarch)
                //{
                // TODO: Get/set total time sworn to patron (allegianceAge) and total in-game time since swearing to patron (timeOnline)
                //}

                name = player.Name;
                
            }

            writer.Write(characterID);
            writer.Write(cpCached);
            writer.Write(cpreplacedhed);
            writer.Write((uint)bitfield);
            writer.Write((byte)gender);
            writer.Write((byte)hg);
            writer.Write(rank);

            if (bitfield.HasFlag(AllegianceIndex.HasPackedLevel))
                writer.Write(level);

            writer.Write(loyalty);
            writer.Write(leadership);

            if (bitfield.HasFlag(AllegianceIndex.HasAllegianceAge))
            {
                writer.Write(timeOnline);
                writer.Write(allegianceAge);
            }
            else
                writer.Write(uTimeOnline);

            writer.WriteString16L(name);
        }

19 Source : AppraiseInfo.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void Write(this BinaryWriter writer, AppraiseInfo info)
        {
            writer.Write((uint)info.Flags);
            writer.Write(Convert.ToUInt32(info.Success));
            if (info.Flags.HasFlag(IdentifyResponseFlags.IntStatsTable))
                writer.Write(info.PropertiesInt);
            if (info.Flags.HasFlag(IdentifyResponseFlags.Int64StatsTable))
                writer.Write(info.PropertiesInt64);
            if (info.Flags.HasFlag(IdentifyResponseFlags.BoolStatsTable))
                writer.Write(info.PropertiesBool);
            if (info.Flags.HasFlag(IdentifyResponseFlags.FloatStatsTable))
                writer.Write(info.PropertiesFloat);
            if (info.Flags.HasFlag(IdentifyResponseFlags.StringStatsTable))
                writer.Write(info.PropertiesString);
            if (info.Flags.HasFlag(IdentifyResponseFlags.DidStatsTable))
                writer.Write(info.PropertiesDID);
            if (info.Flags.HasFlag(IdentifyResponseFlags.SpellBook))
                writer.Write(info.SpellBook);
            if (info.Flags.HasFlag(IdentifyResponseFlags.ArmorProfile))
                writer.Write(info.ArmorProfile);
            if (info.Flags.HasFlag(IdentifyResponseFlags.CreatureProfile))
                writer.Write(info.CreatureProfile);
            if (info.Flags.HasFlag(IdentifyResponseFlags.WeaponProfile))
                writer.Write(info.WeaponProfile);
            if (info.Flags.HasFlag(IdentifyResponseFlags.HookProfile))
                writer.Write(info.HookProfile);
            if (info.Flags.HasFlag(IdentifyResponseFlags.ArmorEnchantmentBitfield))
            {
                writer.Write((ushort)info.ArmorHighlight);
                writer.Write((ushort)info.ArmorColor);
            }
            if (info.Flags.HasFlag(IdentifyResponseFlags.WeaponEnchantmentBitfield))
            {
                writer.Write((ushort)info.WeaponHighlight);
                writer.Write((ushort)info.WeaponColor);
            }
            if (info.Flags.HasFlag(IdentifyResponseFlags.ResistEnchantmentBitfield))
            {
                writer.Write((ushort)info.ResistHighlight);
                writer.Write((ushort)info.ResistColor);
            }
            if (info.Flags.HasFlag(IdentifyResponseFlags.ArmorLevels))
                writer.Write(info.ArmorLevels);
        }

19 Source : CreatureProfile.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void Write(this BinaryWriter writer, CreatureProfile profile)
        {
            writer.Write((uint)profile.Flags);
            writer.Write(profile.Health);
            writer.Write(profile.HealthMax);

            // has flags & 0x8?
            if (profile.Flags.HasFlag(CreatureProfileFlags.ShowAttributes))
            {
                writer.Write(profile.Strength);
                writer.Write(profile.Endurance);
                writer.Write(profile.Quickness);
                writer.Write(profile.Coordination);
                writer.Write(profile.Focus);
                writer.Write(profile.Self);

                writer.Write(profile.Stamina);
                writer.Write(profile.Mana);
                writer.Write(profile.StaminaMax);
                writer.Write(profile.ManaMax);
            }

            // has flags & 0x1?
            if (profile.Flags.HasFlag(CreatureProfileFlags.HasBuffsDebuffs))
            {
                writer.Write((ushort)profile.AttributeHighlights);
                writer.Write((ushort)profile.AttributeColors);
            }
        }

19 Source : Enchantment.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void Write(this BinaryWriter writer, Enchantment enchantment)
        {
            writer.Write(enchantment.SpellID);
            var layer = enchantment.SpellID == (ushort)SpellId.Vitae ? (ushort)0 : enchantment.Layer; // this line is to force vitae to be layer 0 to match retail pcaps. We save it as layer 1 to make EF Core happy.
            writer.Write(layer);
            writer.Write(enchantment.SpellCategory);
            writer.Write(enchantment.HreplacedpellSetID);
            writer.Write(enchantment.PowerLevel);
            writer.Write(enchantment.StartTime);
            writer.Write(enchantment.Duration);
            writer.Write(enchantment.CasterGuid);
            writer.Write(enchantment.DegradeModifier);
            writer.Write(enchantment.DegradeLimit);
            writer.Write(enchantment.LastTimeDegraded);     // always 0 / spell economy?
            writer.Write((uint)enchantment.StatModType);
            writer.Write(enchantment.StatModKey);
            writer.Write(enchantment.StatModValue);
            if (enchantment.HreplacedpellSetID != 0)
                writer.Write(enchantment.SpellSetID);
        }

19 Source : Extensions.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void WriteString16L(this BinaryWriter writer, string data)
        {
            if (data == null) data = "";

            writer.Write((ushort)data.Length);
            writer.Write(System.Text.Encoding.GetEncoding(1252).GetBytes(data));

            // client expects string length to be a multiple of 4 including the 2 bytes for length
            writer.Pad(CalculatePadMultiple(sizeof(ushort) + (uint)data.Length, 4u));
        }

19 Source : Extensions.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void WriteUInt16BE(this BinaryWriter writer, ushort value)
        {
            ushort beValue = (ushort)((ushort)((value & 0xFF) << 8) | ((value >> 8) & 0xFF));
            writer.Write(beValue);
        }

19 Source : MotionItem.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void Write(this BinaryWriter writer, MotionItem mc)
        {
            var sequence = mc.WorldObject.Sequences;

            writer.Write((ushort)mc.MotionCommand);      // verified

            // should already be masked with 0x7FFF
            var nextSequence = sequence.GetNextSequence(SequenceType.Motion);

            if (mc.IsAutonomous)
                nextSequence[1] |= 0x80;    // if client-initiated motion, set upper bit

            writer.Write(nextSequence);

            writer.Write(mc.Speed);
        }

19 Source : MovementData.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void Write(this BinaryWriter writer, MovementData motion, bool header = true)
        {
            var wo = motion.WorldObject;
            var sequence = wo.Sequences;

            if (header)
            {
                writer.Write(sequence.GetNextSequence(SequenceType.ObjectMovement));

                if (motion.IsAutonomous)
                    writer.Write(sequence.GetCurrentSequence(SequenceType.ObjectServerControl));
                else
                    writer.Write(sequence.GetNextSequence(SequenceType.ObjectServerControl));

                writer.Write(Convert.ToByte(motion.IsAutonomous));
                writer.Align();
            }

            writer.Write((byte)motion.MovementType);
            writer.Write((byte)motion.MotionFlags);

            writer.Write((ushort)motion.CurrentStyle);    // send MotionStance as ushort

            switch (motion.MovementType)
            {
                case MovementType.Invalid:
                    writer.Write(motion.Invalid);
                    break;

                case MovementType.MoveToObject:
                    writer.Write(motion.MoveToObject);
                    break;

                case MovementType.MoveToPosition:
                    writer.Write(motion.MoveToPosition);
                    break;

                case MovementType.TurnToObject:
                    writer.Write(motion.TurnToObject);
                    break;

                case MovementType.TurnToHeading:
                    writer.Write(motion.TurnToHeading);
                    break;
            }
        }

19 Source : AllegianceHierarchy.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void Write(this BinaryWriter writer, AllegianceHierarchy hierarchy)
        {
            // ushort - recordCount - Number of character allegiance records
            // ushort - oldVersion = 0x000B - Defines which properties are available. 0x000B seems to be the latest version which includes all properties.
            // Dictionary<ObjectID, AllegianceOfficerLevel> - officers - Taking a guess on these values. Guessing they may only be valid for Monarchs
            //                                                           A list of officers and their officer levels?
            // List<string> - officerreplacedles - Believe these may preplaced in the current officer replacedle list. Guessing they may only be valid on Monarchs.
            // uint - monarchBroadcastTime - May only be valid for Monarchs/Speakers?
            // uint - monarchBroadcastsToday - May only be valid for Monarchs/Speakers?
            // uint - spokesBroadcastTime - May only be valid for Monarchs/Speakers?
            // uint - spokesBroadcastsToday - May only be valid for Monarchs/Speakers?
            // string - motd - Text for current Message of the Day. May only be valid for Monarchs/Speakers?
            // string - motdSetBy - Who set the current Message of the Day. May only be valid for Monarchs/Speakers?
            // uint - chatRoomID - allegiance chat channel number
            // Position - bindpoint - Location of monarchy bindpoint
            // string - allegianceName - The name of the allegiance.
            // uint - nameLastSetTime - Time name was last set. Seems to count upward for some reason.
            // bool - isLocked - Whether allegiance is locked.
            // int - approvedVreplacedal - ??
            // AllegianceData - monarchData - Monarch's data

            // records: vector of length recordCount - 1
            // ObjectID - treeParent - The ObjectID for the parent character to this character. Used by the client to decide how to build the display in the Allegiance tab. 1 is the monarch.
            // AllegianceData - allegianceData

            // recordCount = Monarch + Patron + Vreplacedals?
            // 2 in data for small allegiances?
            ushort recordCount = 0;
            ushort oldVersion = 0x000B;
            var officers = new Dictionary<ObjectGuid, AllegianceOfficerLevel>();
            var officerreplacedles = new List<string>();
            uint monarchBroadcastTime = 0;
            uint monarchBroadcastsToday = 0;
            uint spokesBroadcastTime = 0;
            uint spokesBroadcastsToday = 0;
            var motd = "";
            var motdSetBy = "";
            uint chatRoomID = 0;
            var bindPoint = new Position();
            var allegianceName = "";
            uint nameLastSetTime = 0;
            bool isLocked = false;
            int approvedVreplacedal = 0;
            AllegianceData monarchData = null;
            List<Tuple<ObjectGuid, AllegianceData>> records = null;

            var allegiance = hierarchy.Profile.Allegiance;
            var node = hierarchy.Profile.Node;

            if (allegiance != null && node != null)
            {
                // only send these to monarch?
                //foreach (var officer in allegiance.Officers)
                    //officers.Add(officer.Key, (AllegianceOfficerLevel)officer.Value.Player.AllegianceOfficerRank);

                // not in retail packets, breaks decal
                /*if (allegiance.HasCustomreplacedles)
                {
                    officerreplacedles.Add(allegiance.GetOfficerreplacedle(AllegianceOfficerLevel.Speaker));
                    officerreplacedles.Add(allegiance.GetOfficerreplacedle(AllegianceOfficerLevel.Seneschal));
                    officerreplacedles.Add(allegiance.GetOfficerreplacedle(AllegianceOfficerLevel.Castellan));
                }*/

                allegianceName = allegiance.AllegianceName ?? allegiance.Monarch.Player.Name;
                //motd = allegiance.AllegianceMotd ?? "";
                //motdSetBy = allegiance.AllegianceMotdSetBy ?? "";
                motd = "";          // fixes decal AllegianceUpdate parsing
                motdSetBy = "";
                chatRoomID = allegiance.Biota.Id;

                if (allegiance.Sanctuary != null)
                    bindPoint = allegiance.Sanctuary;

                // aclogview (verify):
                // i == 0 : monarch (no guid)
                // i == 1 : patron
                // i == 2 : peer?
                // i  > 2 : vreplacedals

                // peers = others with the same patron?

                recordCount = 1;    // monarch
                if (node.Patron != null && !node.Patron.IsMonarch)  // patron
                    recordCount++;
                if (!node.IsMonarch)    // self
                    recordCount++;
                if (node.TotalVreplacedals > 0)  // vreplacedals
                {
                    recordCount += (ushort)node.TotalVreplacedals;
                }
                //Console.WriteLine("Records: " + recordCount);

                // monarch
                monarchData = new AllegianceData(allegiance.Monarch);

                if (recordCount > 1)
                {
                    records = new List<Tuple<ObjectGuid, AllegianceData>>();

                    // patron
                    if (node.Patron != null && !node.Patron.IsMonarch)
                    {
                        records.Add(new Tuple<ObjectGuid, AllegianceData>(node.Monarch.PlayerGuid, new AllegianceData(node.Patron)));
                    }

                    // self
                    if (!node.IsMonarch)
                        records.Add(new Tuple<ObjectGuid, AllegianceData>(node.Patron.PlayerGuid, new AllegianceData(node)));

                    // vreplacedals
                    if (node.TotalVreplacedals > 0)
                    {
                        foreach (var vreplacedal in node.Vreplacedals.Values)
                            records.Add(new Tuple<ObjectGuid, AllegianceData>(node.PlayerGuid, new AllegianceData(vreplacedal)));
                    }
                }
            }

            writer.Write(recordCount);
            writer.Write(oldVersion);
            writer.Write(officers);
            writer.Write(officerreplacedles);
            writer.Write(monarchBroadcastTime);
            writer.Write(monarchBroadcastsToday);
            writer.Write(spokesBroadcastTime);
            writer.Write(spokesBroadcastsToday);
            writer.WriteString16L(motd);
            writer.WriteString16L(motdSetBy);
            writer.Write(chatRoomID);
            writer.Write(bindPoint);
            writer.WriteString16L(allegianceName);
            writer.Write(nameLastSetTime);
            writer.Write(Convert.ToUInt32(isLocked));
            writer.Write(approvedVreplacedal);

            if (monarchData != null)
                writer.Write(monarchData);

            if (records != null)
                writer.Write(records);
        }

19 Source : FellowshipLockData.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void Write(this BinaryWriter writer, Dictionary<string, FellowshipLockData> fellowshipLocks)
        {
            writer.Write((ushort)fellowshipLocks.Count);
            writer.Write(NumBuckets);
            foreach (var kvp in fellowshipLocks)
            {
                writer.WriteString16L(kvp.Key);
                writer.Write(kvp.Value);
            }
        }

19 Source : LayeredSpell.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void Write(this BinaryWriter writer, LayeredSpell spell)
        {
            writer.Write(spell.SpellId);
            writer.Write(spell.Layer);
        }

19 Source : LayeredSpell.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void Write(this BinaryWriter writer, PropertiesEnchantmentRegistry enchantment)
        {
            writer.Write((ushort)enchantment.SpellId);
            writer.Write(enchantment.LayerId);
        }

19 Source : PackableHashTable.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void WriteHeader(BinaryWriter writer, int count, int numBuckets)
        {
            writer.Write((ushort)count);
            writer.Write((ushort)numBuckets);
        }

19 Source : PHashTable.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static void WriteHeader(BinaryWriter writer, uint count)
        {
            var numBits = GetNumBits(count);
            var numBuckets = 1 << ((int)numBits - 1);

            writer.Write((ushort)count);
            writer.Write((ushort)numBuckets);
        }

19 Source : PacketHeaderOptional.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void Unpack(BinaryReader reader, PacketHeader header)
        {
            Header = header;
            Size = (uint)reader.BaseStream.Position;
            BinaryWriter writer = new BinaryWriter(headerBytes);

            if (header.HasFlag(PacketHeaderFlags.ServerSwitch)) // 0x100
            {
                writer.Write(reader.ReadBytes(8));
            }

            if (header.HasFlag(PacketHeaderFlags.RequestRetransmit)) // 0x1000
            {
                if (reader.BaseStream.Length < reader.BaseStream.Position + 4) { IsValid = false; return; }
                uint retransmitCount = reader.ReadUInt32();
                writer.Write(retransmitCount);
                RetransmitData = new List<uint>();
                for (uint i = 0u; i < retransmitCount; i++)
                {
                    if (reader.BaseStream.Length < reader.BaseStream.Position + 4) { IsValid = false; return; }
                    uint sequence = reader.ReadUInt32();
                    writer.Write(sequence);
                    RetransmitData.Add(sequence);
                }
            }

            if (header.HasFlag(PacketHeaderFlags.RejectRetransmit)) // 0x2000
            {
                if (reader.BaseStream.Length < reader.BaseStream.Position + 4) { IsValid = false; return; }
                uint count = reader.ReadUInt32();
                writer.Write(count);
                for (int i = 0; i < count; i++)
                {
                    if (reader.BaseStream.Length < reader.BaseStream.Position + 4) { IsValid = false; return; }
                    writer.Write(reader.ReadBytes(4));
                }
            }

            if (header.HasFlag(PacketHeaderFlags.AckSequence)) // 0x4000
            {
                if (reader.BaseStream.Length < reader.BaseStream.Position + 4) { IsValid = false; return; }
                AckSequence = reader.ReadUInt32();
                writer.Write(AckSequence);
            }

            if (header.HasFlag(PacketHeaderFlags.LoginRequest)) // 0x10000
            {
                long position = reader.BaseStream.Position;
                long length = reader.BaseStream.Length - position;
                if (length < 1) { IsValid = false; return; }
                byte[] loginBytes = new byte[length];
                reader.BaseStream.Read(loginBytes, (int)position, (int)length);
                writer.Write(loginBytes);
                reader.BaseStream.Position = position;
            }

            if (header.HasFlag(PacketHeaderFlags.WorldLoginRequest)) // 0x20000
            {
                if (reader.BaseStream.Length < reader.BaseStream.Position + 8) { IsValid = false; return; }
                long position = reader.BaseStream.Position;
                writer.Write(reader.ReadBytes(8));
                reader.BaseStream.Position = position;
            }

            if (header.HasFlag(PacketHeaderFlags.ConnectResponse)) // 0x80000
            {
                long position = reader.BaseStream.Position;
                if (reader.BaseStream.Length < reader.BaseStream.Position + 8) { IsValid = false; return; }
                writer.Write(reader.ReadBytes(8));
                reader.BaseStream.Position = position;
            }

            if (header.HasFlag(PacketHeaderFlags.CICMDCommand)) // 0x400000
            {
                if (reader.BaseStream.Length < reader.BaseStream.Position + 8) { IsValid = false; return; }
                writer.Write(reader.ReadBytes(8));
            }

            if (header.HasFlag(PacketHeaderFlags.TimeSync)) // 0x1000000
            {
                if (reader.BaseStream.Length < reader.BaseStream.Position + 8) { IsValid = false; return; }
                TimeSynch = reader.ReadDouble();
                writer.Write(TimeSynch);
            }

            if (header.HasFlag(PacketHeaderFlags.Ecreplacedquest)) // 0x2000000
            {
                if (reader.BaseStream.Length < reader.BaseStream.Position + 4) { IsValid = false; return; }
                EcreplacedquestClientTime = reader.ReadSingle();
                writer.Write(EcreplacedquestClientTime);
            }

            if (header.HasFlag(PacketHeaderFlags.Flow)) // 0x8000000
            {
                if (reader.BaseStream.Length < reader.BaseStream.Position + 6) { IsValid = false; return; }
                FlowBytes = reader.ReadUInt32();
                FlowInterval = reader.ReadUInt16();
                writer.Write(FlowBytes);
                writer.Write(FlowInterval);
            }

            Size = (uint)reader.BaseStream.Position - Size;
        }

19 Source : HeaderChunk.cs
with GNU General Public License v3.0
from Aekras1a

internal void WriteData(DarksVMRuntime rt)
        {
            var stream = new MemoryStream();
            var writer = new BinaryWriter(stream);

            writer.Write((uint) 0x68736966);
            writer.Write(rt.Descriptor.Data.refMap.Count);
            writer.Write(rt.Descriptor.Data.strMap.Count);
            writer.Write(rt.Descriptor.Data.sigs.Count);

            foreach(var refer in rt.Descriptor.Data.refMap)
            {
                writer.WriteCompressedUInt(refer.Value);
                writer.WriteCompressedUInt(GetCodedToken(refer.Key.MDToken));
            }

            foreach(var str in rt.Descriptor.Data.strMap)
            {
                writer.WriteCompressedUInt(str.Value);
                writer.WriteCompressedUInt((uint) str.Key.Length);
                foreach(var chr in str.Key)
                    writer.Write((ushort) chr);
            }

            foreach(var sig in rt.Descriptor.Data.sigs)
            {
                writer.WriteCompressedUInt(sig.Id);
                if(sig.Method != null)
                {
                    var entry = rt.methodMap[sig.Method].Item2;
                    var entryOffset = entry.Content[0].Offset;
                    Debug.replacedert(entryOffset != 0);
                    writer.Write(entryOffset);

                    var key = (uint) rt.Descriptor.Random.Next();
                    key = (key << 8) | rt.Descriptor.Data.LookupInfo(sig.Method).EntryKey;
                    writer.Write(key);
                }
                else
                {
                    writer.Write(0u);
                }

                writer.Write(sig.FuncSig.Flags);
                writer.WriteCompressedUInt((uint) sig.FuncSig.ParamSigs.Length);
                foreach(var paramType in sig.FuncSig.ParamSigs) writer.WriteCompressedUInt(GetCodedToken(paramType.MDToken));
                writer.WriteCompressedUInt(GetCodedToken(sig.FuncSig.RetType.MDToken));
            }

            data = stream.ToArray();
            Debug.replacedert(data.Length == Length);
        }

19 Source : Pack.cs
with Apache License 2.0
from aequabit

public byte[] Serialize(params object[] data)
    {
        MemoryStream Stream = new MemoryStream();
        BinaryWriter Writer = new BinaryWriter(Stream, Encoding.UTF8);
        byte Current = 0;

        Writer.Write(Convert.ToByte(data.Length));

        for (int I = 0; I <= data.Length - 1; I++)
        {
            Current = Table[data[I].GetType()];
            Writer.Write(Current);

            switch (Current)
            {
                case 0:
                    Writer.Write((bool)data[I]);
                    break;
                case 1:
                    Writer.Write((byte)data[I]);
                    break;
                case 2:
                    Writer.Write(((byte[])data[I]).Length);
                    Writer.Write((byte[])data[I]);
                    break;
                case 3:
                    Writer.Write((char)data[I]);
                    break;
                case 4:
                    Writer.Write(((char[])data[I]).ToString());
                    break;
                case 5:
                    Writer.Write((decimal)data[I]);
                    break;
                case 6:
                    Writer.Write((double)data[I]);
                    break;
                case 7:
                    Writer.Write((int)data[I]);
                    break;
                case 8:
                    Writer.Write((long)data[I]);
                    break;
                case 9:
                    Writer.Write((sbyte)data[I]);
                    break;
                case 10:
                    Writer.Write((short)data[I]);
                    break;
                case 11:
                    Writer.Write((float)data[I]);
                    break;
                case 12:
                    Writer.Write((string)data[I]);
                    break;
                case 13:
                    Writer.Write((uint)data[I]);
                    break;
                case 14:
                    Writer.Write((ulong)data[I]);
                    break;
                case 15:
                    Writer.Write((ushort)data[I]);
                    break;
                case 16:
                    Writer.Write(((System.DateTime)data[I]).ToBinary());
                    break;
            }
        }

        Writer.Close();
        return Stream.ToArray();
    }

19 Source : ResourceHeader.cs
with GNU General Public License v3.0
from ahmed605

public void Write(BinaryWriter bw)
        {
            bw.Write( MagicValue );
            bw.Write( (uint)Type );
            bw.Write( Flags );
            bw.Write( (ushort)CompressCodec );
        }

19 Source : WaveHeader.cs
with GNU General Public License v3.0
from ahmed605

public virtual void Write(BinaryWriter bw)
        {
            bw.Write(RiffChunkID);
            bw.Write(RiffChunkSize);
            bw.Write(Format);

            bw.Write(FmtChunkID);
            bw.Write(FmtChunkSize);
            bw.Write(AudioFormat);
            bw.Write(NumChannels);
            bw.Write(SampleRate);
            bw.Write(ByteRate);
            bw.Write(BlockAlign);
            bw.Write(BitsPerSample);

            if (ExtraDataSize > 0)
            {
                bw.Write(ExtraDataSize);
                bw.Write(ValidBitsPerSample);
                bw.Write((int) AvailableChannelMask);
                bw.Write(FormatGuid[0]);
                bw.Write(FormatGuid[1]);
                bw.Write(FormatGuid[2]);
                bw.Write(FormatGuid[3]);
            }

            bw.Write(DataChunkID);
            bw.Write(DataChunkSize);
        }

19 Source : IconFactory.cs
with MIT License
from AlexGyver

public void Write(BinaryWriter bw) {
        bw.Write(Size);
			  bw.Write(Width);
			  bw.Write(Height);
			  bw.Write(Planes);
			  bw.Write(BitCount);
			  bw.Write(Compression);
			  bw.Write(SizeImage);
			  bw.Write(XPelsPerMeter);
			  bw.Write(YPelsPerMeter);
			  bw.Write(ClrUsed);
			  bw.Write(ClrImportant);
      }

19 Source : IconFactory.cs
with MIT License
from AlexGyver

public void Write(BinaryWriter bw) {
        bw.Write(Reserved);
        bw.Write(Type);
        bw.Write(Count);
        for (int i = 0; i < Entries.Length; i++)
          Entries[i].Write(bw);
      }

19 Source : IconFactory.cs
with MIT License
from AlexGyver

public void Write(BinaryWriter bw) {
        bw.Write(Width);
        bw.Write(Height);
        bw.Write(ColorCount);
        bw.Write(Reserved);
        bw.Write(Planes);
        bw.Write(BitCount);
        bw.Write(BytesInRes);
        bw.Write(ImageOffset);
      }

19 Source : OxyImage.cs
with MIT License
from AlexGyver

public static OxyImage FromArgb(int width, int height, byte[] pixelData, int dpi = 96)
        {
            var ms = new MemoryStream();
            var w = new BinaryWriter(ms);

            const int OffBits = 14 + 108;
            var size = OffBits + pixelData.Length;

            // Bitmap file header (14 bytes)
            w.Write((byte)'B');
            w.Write((byte)'M');
            w.Write((uint)size);
            w.Write((ushort)0);
            w.Write((ushort)0);
            w.Write((uint)OffBits);

            // Bitmap V4 info header (108 bytes)
            WriteBitmapV4Header(w, width, height, 32, pixelData.Length, dpi);

            // Pixel array (from bottom-left corner)
            w.Write(pixelData);

            return new OxyImage(ms.ToArray());
        }

19 Source : OxyImage.cs
with MIT License
from AlexGyver

public static OxyImage FromIndexed8(
            int width, int height, byte[] indexedPixelData, OxyColor[] palette, int dpi = 96)
        {
            if (indexedPixelData.Length != width * height)
            {
                throw new ArgumentException("Length of data is not correct.", "indexedPixelData");
            }

            if (palette.Length == 0)
            {
                throw new ArgumentException("Palette not defined.", "palette");
            }

            var ms = new MemoryStream();
            var w = new BinaryWriter(ms);

            var offBits = 14 + 40 + (4 * palette.Length);
            var size = offBits + indexedPixelData.Length;

            // Bitmap file header (14 bytes)
            w.Write((byte)'B');
            w.Write((byte)'M');
            w.Write((uint)size);
            w.Write((ushort)0);
            w.Write((ushort)0);
            w.Write((uint)offBits);

            // Bitmap info header
            WriteBitmapInfoHeader(w, width, height, 8, indexedPixelData.Length, dpi, palette.Length);

            // Color table
            foreach (var color in palette)
            {
                w.Write(color.B);
                w.Write(color.G);
                w.Write(color.R);
                w.Write(color.A);
            }

            // Pixel array (from bottom-left corner)
            w.Write(indexedPixelData);

            return new OxyImage(ms.ToArray());
        }

19 Source : OxyImage.cs
with MIT License
from AlexGyver

public static OxyImage FromArgbX(int width, int height, byte[] pixelData, int dpi = 96)
        {
            var ms = new MemoryStream();
            var w = new BinaryWriter(ms);

            const int OffBits = 14 + 40;
            var size = OffBits + pixelData.Length;

            // Bitmap file header (14 bytes)
            w.Write((byte)'B');
            w.Write((byte)'M');
            w.Write((uint)size);
            w.Write((ushort)0);
            w.Write((ushort)0);
            w.Write((uint)OffBits);

            // Bitmap info header
            WriteBitmapInfoHeader(w, width, height, 32, pixelData.Length, dpi);

            // Pixel array (from bottom-left corner)
            w.Write(pixelData);

            return new OxyImage(ms.ToArray());
        }

19 Source : OxyImage.cs
with MIT License
from AlexGyver

private static void WriteBitmapInfoHeader(
            BinaryWriter w, int width, int height, int bitsPerPixel, int length, int dpi, int colors = 0)
        {
            // Convert resolution to pixels per meter
            var ppm = (uint)(dpi / 0.0254);

            w.Write((uint)40);
            w.Write((uint)width);
            w.Write((uint)height);
            w.Write((ushort)1);
            w.Write((ushort)bitsPerPixel);
            w.Write((uint)0);
            w.Write((uint)length);
            w.Write(ppm);
            w.Write(ppm);
            w.Write((uint)colors);
            w.Write((uint)colors);
        }

19 Source : OxyImage.cs
with MIT License
from AlexGyver

private static void WriteBitmapV4Header(
            BinaryWriter w, int width, int height, int bitsPerPixel, int length, int dpi, int colors = 0)
        {
            // Convert resolution to pixels per meter
            var ppm = (uint)(dpi / 0.0254);

            w.Write((uint)108);
            w.Write((uint)width);
            w.Write((uint)height);
            w.Write((ushort)1);
            w.Write((ushort)bitsPerPixel);
            w.Write((uint)3);
            w.Write((uint)length);
            w.Write(ppm);
            w.Write(ppm);
            w.Write((uint)colors);
            w.Write((uint)colors);

            // Write the channel bit masks
            w.Write(0x00FF0000);
            w.Write(0x0000FF00);
            w.Write(0x000000FF);
            w.Write(0xFF000000);

            // Write the color space
            w.Write((uint)0x206E6957);
            w.Write(new byte[3 * 3 * 4]);

            // Write the gamma RGB
            w.Write((uint)0);
            w.Write((uint)0);
            w.Write((uint)0);
        }

19 Source : DoomMapSetIO.cs
with GNU General Public License v3.0
from anotak

private void WriteLinedefs(MapSet map, int position, IDictionary maplumps, IDictionary<Sidedef, int> sidedefids, IDictionary<Vertex, int> vertexids)
		{
			MemoryStream mem;
			BinaryWriter writer;
			Lump lump;
			ushort sid;
			int insertpos;
			int flags;
			
			// Create memory to write to
			mem = new MemoryStream();
			writer = new BinaryWriter(mem, WAD.ENCODING);

			// Go for all lines
			foreach(Linedef l in map.Linedefs)
			{
				// Convert flags
				flags = 0;
				foreach(KeyValuePair<string, bool> f in l.Flags)
				{
					int fnum;
					if(f.Value && int.TryParse(f.Key, out fnum)) flags |= fnum;
				}

				// Write properties to stream
				writer.Write((UInt16)vertexids[l.Start]);
				writer.Write((UInt16)vertexids[l.End]);
				writer.Write((UInt16)flags);
				writer.Write((UInt16)l.Action);
				writer.Write((UInt16)l.Tag);

				// Front sidedef
				if(l.Front == null) sid = ushort.MaxValue;
					else sid = (UInt16)sidedefids[l.Front];
				writer.Write(sid);

				// Back sidedef
				if(l.Back == null) sid = ushort.MaxValue;
					else sid = (UInt16)sidedefids[l.Back];
				writer.Write(sid);
			}

			// Find insert position and remove old lump
			insertpos = MapManager.RemoveSpecificLump(wad, "LINEDEFS", position, MapManager.TEMP_MAP_HEADER, maplumps);
			if(insertpos == -1) insertpos = position + 1;
			if(insertpos > wad.Lumps.Count) insertpos = wad.Lumps.Count;

			// Create the lump from memory
			lump = wad.Insert("LINEDEFS", insertpos, (int)mem.Length);
			lump.Stream.Seek(0, SeekOrigin.Begin);
			mem.WriteTo(lump.Stream);
			mem.Flush();
		}

19 Source : DoomMapSetIO.cs
with GNU General Public License v3.0
from anotak

private void WriteSidedefs(MapSet map, int position, IDictionary maplumps, IDictionary<Sector, int> sectorids)
		{
			MemoryStream mem;
			BinaryWriter writer;
			Lump lump;
			int insertpos;

			// Create memory to write to
			mem = new MemoryStream();
			writer = new BinaryWriter(mem, WAD.ENCODING);

			// Go for all sidedefs
			foreach(Sidedef sd in map.Sidedefs)
			{
				// Write properties to stream
				writer.Write((Int16)sd.OffsetX);
				writer.Write((Int16)sd.OffsetY);
				writer.Write(Lump.MakeFixedName(sd.HighTexture, WAD.ENCODING));
				writer.Write(Lump.MakeFixedName(sd.LowTexture, WAD.ENCODING));
				writer.Write(Lump.MakeFixedName(sd.MiddleTexture, WAD.ENCODING));
				writer.Write((UInt16)sectorids[sd.Sector]);
			}

			// Find insert position and remove old lump
			insertpos = MapManager.RemoveSpecificLump(wad, "SIDEDEFS", position, MapManager.TEMP_MAP_HEADER, maplumps);
			if(insertpos == -1) insertpos = position + 1;
			if(insertpos > wad.Lumps.Count) insertpos = wad.Lumps.Count;

			// Create the lump from memory
			lump = wad.Insert("SIDEDEFS", insertpos, (int)mem.Length);
			lump.Stream.Seek(0, SeekOrigin.Begin);
			mem.WriteTo(lump.Stream);
			mem.Flush();
		}

19 Source : DoomMapSetIO.cs
with GNU General Public License v3.0
from anotak

private void WriteSectors(MapSet map, int position, IDictionary maplumps)
		{
			MemoryStream mem;
			BinaryWriter writer;
			Lump lump;
			int insertpos;

			// Create memory to write to
			mem = new MemoryStream();
			writer = new BinaryWriter(mem, WAD.ENCODING);

			// Go for all sectors
			foreach(Sector s in map.Sectors)
			{
				// Write properties to stream
				writer.Write((Int16)s.FloorHeight);
				writer.Write((Int16)s.CeilHeight);
				writer.Write(Lump.MakeFixedName(s.FloorTexture, WAD.ENCODING));
				writer.Write(Lump.MakeFixedName(s.CeilTexture, WAD.ENCODING));
				writer.Write((Int16)s.Brightness);
				writer.Write((UInt16)s.Effect);
				writer.Write((UInt16)s.Tag);
			}

			// Find insert position and remove old lump
			insertpos = MapManager.RemoveSpecificLump(wad, "SECTORS", position, MapManager.TEMP_MAP_HEADER, maplumps);
			if(insertpos == -1) insertpos = position + 1;
			if(insertpos > wad.Lumps.Count) insertpos = wad.Lumps.Count;

			// Create the lump from memory
			lump = wad.Insert("SECTORS", insertpos, (int)mem.Length);
			lump.Stream.Seek(0, SeekOrigin.Begin);
			mem.WriteTo(lump.Stream);
			mem.Flush();
		}

19 Source : HexenMapSetIO.cs
with GNU General Public License v3.0
from anotak

private void WriteThings(MapSet map, int position, IDictionary maplumps)
		{
			MemoryStream mem;
			BinaryWriter writer;
			Lump lump;
			int insertpos;
			int flags;
			
			// Create memory to write to
			mem = new MemoryStream();
			writer = new BinaryWriter(mem, WAD.ENCODING);
			
			// Go for all things
			foreach(Thing t in map.Things)
			{
				// Convert flags
				flags = 0;
				foreach(KeyValuePair<string, bool> f in t.Flags)
				{
					int fnum;
					if(f.Value && int.TryParse(f.Key, out fnum)) flags |= fnum;
				}

				// Write properties to stream
				// Write properties to stream
				writer.Write((UInt16)t.Tag);
				writer.Write((Int16)t.Position.x);
				writer.Write((Int16)t.Position.y);
				writer.Write((Int16)t.Position.z);
				writer.Write((Int16)t.AngleDoom);
				writer.Write((UInt16)t.Type);
				writer.Write((UInt16)flags);
				writer.Write((Byte)t.Action);
				writer.Write((Byte)t.Args[0]);
				writer.Write((Byte)t.Args[1]);
				writer.Write((Byte)t.Args[2]);
				writer.Write((Byte)t.Args[3]);
				writer.Write((Byte)t.Args[4]);
			}
			
			// Find insert position and remove old lump
			insertpos = MapManager.RemoveSpecificLump(wad, "THINGS", position, MapManager.TEMP_MAP_HEADER, maplumps);
			if(insertpos == -1) insertpos = position + 1;
			if(insertpos > wad.Lumps.Count) insertpos = wad.Lumps.Count;
			
			// Create the lump from memory
			lump = wad.Insert("THINGS", insertpos, (int)mem.Length);
			lump.Stream.Seek(0, SeekOrigin.Begin);
			mem.WriteTo(lump.Stream);
		}

19 Source : HexenMapSetIO.cs
with GNU General Public License v3.0
from anotak

private void WriteLinedefs(MapSet map, int position, IDictionary maplumps, IDictionary<Sidedef, int> sidedefids, IDictionary<Vertex, int> vertexids)
		{
			MemoryStream mem;
			BinaryWriter writer;
			Lump lump;
			ushort sid;
			int insertpos;
			int flags;
			
			// Create memory to write to
			mem = new MemoryStream();
			writer = new BinaryWriter(mem, WAD.ENCODING);

			// Go for all lines
			foreach(Linedef l in map.Linedefs)
			{
				// Convert flags
				flags = 0;
				foreach(KeyValuePair<string, bool> f in l.Flags)
				{
					int fnum;
					if(f.Value && int.TryParse(f.Key, out fnum)) flags |= fnum;
				}

				// Add activates to flags
				flags |= (l.Activate & manager.Config.LinedefActivationsFilter);
				
				// Write properties to stream
				writer.Write((UInt16)vertexids[l.Start]);
				writer.Write((UInt16)vertexids[l.End]);
				writer.Write((UInt16)flags);
				writer.Write((Byte)l.Action);
				writer.Write((Byte)l.Args[0]);
				writer.Write((Byte)l.Args[1]);
				writer.Write((Byte)l.Args[2]);
				writer.Write((Byte)l.Args[3]);
				writer.Write((Byte)l.Args[4]);

				// Front sidedef
				if(l.Front == null) sid = ushort.MaxValue;
					else sid = (UInt16)sidedefids[l.Front];
				writer.Write(sid);

				// Back sidedef
				if(l.Back == null) sid = ushort.MaxValue;
					else sid = (UInt16)sidedefids[l.Back];
				writer.Write(sid);
			}

			// Find insert position and remove old lump
			insertpos = MapManager.RemoveSpecificLump(wad, "LINEDEFS", position, MapManager.TEMP_MAP_HEADER, maplumps);
			if(insertpos == -1) insertpos = position + 1;
			if(insertpos > wad.Lumps.Count) insertpos = wad.Lumps.Count;

			// Create the lump from memory
			lump = wad.Insert("LINEDEFS", insertpos, (int)mem.Length);
			lump.Stream.Seek(0, SeekOrigin.Begin);
			mem.WriteTo(lump.Stream);
		}

19 Source : HexenMapSetIO.cs
with GNU General Public License v3.0
from anotak

private void WriteSidedefs(MapSet map, int position, IDictionary maplumps, IDictionary<Sector, int> sectorids)
		{
			MemoryStream mem;
			BinaryWriter writer;
			Lump lump;
			int insertpos;

			// Create memory to write to
			mem = new MemoryStream();
			writer = new BinaryWriter(mem, WAD.ENCODING);

			// Go for all sidedefs
			foreach(Sidedef sd in map.Sidedefs)
			{
				// Write properties to stream
				writer.Write((Int16)sd.OffsetX);
				writer.Write((Int16)sd.OffsetY);
				writer.Write(Lump.MakeFixedName(sd.HighTexture, WAD.ENCODING));
				writer.Write(Lump.MakeFixedName(sd.LowTexture, WAD.ENCODING));
				writer.Write(Lump.MakeFixedName(sd.MiddleTexture, WAD.ENCODING));
				writer.Write((UInt16)sectorids[sd.Sector]);
			}

			// Find insert position and remove old lump
			insertpos = MapManager.RemoveSpecificLump(wad, "SIDEDEFS", position, MapManager.TEMP_MAP_HEADER, maplumps);
			if(insertpos == -1) insertpos = position + 1;
			if(insertpos > wad.Lumps.Count) insertpos = wad.Lumps.Count;

			// Create the lump from memory
			lump = wad.Insert("SIDEDEFS", insertpos, (int)mem.Length);
			lump.Stream.Seek(0, SeekOrigin.Begin);
			mem.WriteTo(lump.Stream);
		}

19 Source : HexenMapSetIO.cs
with GNU General Public License v3.0
from anotak

private void WriteSectors(MapSet map, int position, IDictionary maplumps)
		{
			MemoryStream mem;
			BinaryWriter writer;
			Lump lump;
			int insertpos;

			// Create memory to write to
			mem = new MemoryStream();
			writer = new BinaryWriter(mem, WAD.ENCODING);

			// Go for all sectors
			foreach(Sector s in map.Sectors)
			{
				// Write properties to stream
				writer.Write((Int16)s.FloorHeight);
				writer.Write((Int16)s.CeilHeight);
				writer.Write(Lump.MakeFixedName(s.FloorTexture, WAD.ENCODING));
				writer.Write(Lump.MakeFixedName(s.CeilTexture, WAD.ENCODING));
				writer.Write((Int16)s.Brightness);
				writer.Write((UInt16)s.Effect);
				writer.Write((UInt16)s.Tag);
			}

			// Find insert position and remove old lump
			insertpos = MapManager.RemoveSpecificLump(wad, "SECTORS", position, MapManager.TEMP_MAP_HEADER, maplumps);
			if(insertpos == -1) insertpos = position + 1;
			if(insertpos > wad.Lumps.Count) insertpos = wad.Lumps.Count;

			// Create the lump from memory
			lump = wad.Insert("SECTORS", insertpos, (int)mem.Length);
			lump.Stream.Seek(0, SeekOrigin.Begin);
			mem.WriteTo(lump.Stream);
		}

19 Source : SerializerStream.cs
with GNU General Public License v3.0
from anotak

public void rwString(ref string v)
		{
			ushort index;
			if(stringstable.ContainsKey(v))
				index = stringstable[v];
			else
				index = stringstable[v] = (ushort)stringstable.Count;
			writer.Write(index);
		}

19 Source : SerializerStream.cs
with GNU General Public License v3.0
from anotak

public void rwUShort(ref ushort v) { writer.Write(v); }

19 Source : SerializerStream.cs
with GNU General Public License v3.0
from anotak

public void wString(string v)
		{
			ushort index;
			if(stringstable.ContainsKey(v))
				index = stringstable[v];
			else
				index = stringstable[v] = (ushort)stringstable.Count;
			writer.Write(index);
		}

19 Source : SerializerStream.cs
with GNU General Public License v3.0
from anotak

public void wUShort(ushort v) { writer.Write(v); }

19 Source : DoomMapSetIO.cs
with GNU General Public License v3.0
from anotak

private void WriteThings(MapSet map, int position, IDictionary maplumps)
		{
			MemoryStream mem;
			BinaryWriter writer;
			Lump lump;
			int insertpos;
			int flags;
			
			// Create memory to write to
			mem = new MemoryStream();
			writer = new BinaryWriter(mem, WAD.ENCODING);
			
			// Go for all things
			foreach(Thing t in map.Things)
			{
				// Convert flags
				flags = 0;
				foreach(KeyValuePair<string, bool> f in t.Flags)
				{
					int fnum;
					if(f.Value && int.TryParse(f.Key, out fnum)) flags |= fnum;
				}

				// Write properties to stream
				writer.Write((Int16)t.Position.x);
				writer.Write((Int16)t.Position.y);
				writer.Write((Int16)t.AngleDoom);
				writer.Write((UInt16)t.Type);
				writer.Write((UInt16)flags);
			}
			
			// Find insert position and remove old lump
			insertpos = MapManager.RemoveSpecificLump(wad, "THINGS", position, MapManager.TEMP_MAP_HEADER, maplumps);
			if(insertpos == -1) insertpos = position + 1;
			if(insertpos > wad.Lumps.Count) insertpos = wad.Lumps.Count;
			
			// Create the lump from memory
			lump = wad.Insert("THINGS", insertpos, (int)mem.Length);
			lump.Stream.Seek(0, SeekOrigin.Begin);
			mem.WriteTo(lump.Stream);
			mem.Flush();
		}

19 Source : extensions.cs
with Apache License 2.0
from AntonioDePau

public static void Write(this Stream stream, ushort value) => new BinaryWriter(stream).Write(value);

19 Source : PdbCustomDebugInfoWriter.cs
with GNU General Public License v3.0
from anydream

byte[] Write(IList<PdbCustomDebugInfo> customDebugInfos) {
			if (customDebugInfos.Count == 0)
				return null;
			if (customDebugInfos.Count > byte.MaxValue) {
				Error("Too many custom debug infos. Count must be <= 255");
				return null;
			}

			writer.Write((byte)CustomDebugInfoConstants.Version);
			writer.Write((byte)customDebugInfos.Count);
			writer.Write((ushort)0);

			for (int i = 0; i < customDebugInfos.Count; i++) {
				var info = customDebugInfos[i];
				if (info == null) {
					Error("Custom debug info is null");
					return null;
				}
				if ((uint)info.Kind > byte.MaxValue) {
					Error("Invalid custom debug info kind");
					return null;
				}

				var recordPos = writer.BaseStream.Position;
				writer.Write((byte)CustomDebugInfoConstants.RecordVersion);
				writer.Write((byte)info.Kind);
				writer.Write((ushort)0);
				writer.Write((uint)0);

				int count, j, k;
				uint token;
				switch (info.Kind) {
				case PdbCustomDebugInfoKind.UsingGroups:
					var usingRec = info as PdbUsingGroupsCustomDebugInfo;
					if (usingRec == null) {
						Error("Unsupported custom debug info type {0}", info.GetType());
						return null;
					}
					count = usingRec.UsingCounts.Count;
					if (count > ushort.MaxValue) {
						Error("UsingCounts contains more than 0xFFFF elements");
						return null;
					}
					writer.Write((ushort)count);
					for (j = 0; j < count; j++)
						writer.Write(usingRec.UsingCounts[j]);
					break;

				case PdbCustomDebugInfoKind.ForwardMethodInfo:
					var fwdMethodRec = info as PdbForwardMethodInfoCustomDebugInfo;
					if (fwdMethodRec == null) {
						Error("Unsupported custom debug info type {0}", info.GetType());
						return null;
					}
					token = GetMethodToken(fwdMethodRec.Method);
					if (token == 0)
						return null;
					writer.Write(token);
					break;

				case PdbCustomDebugInfoKind.ForwardModuleInfo:
					var fwdModRec = info as PdbForwardModuleInfoCustomDebugInfo;
					if (fwdModRec == null) {
						Error("Unsupported custom debug info type {0}", info.GetType());
						return null;
					}
					token = GetMethodToken(fwdModRec.Method);
					if (token == 0)
						return null;
					writer.Write(token);
					break;

				case PdbCustomDebugInfoKind.StateMachineHoistedLocalScopes:
					var smLocalScopesRec = info as PdbStateMachineHoistedLocalScopesCustomDebugInfo;
					if (smLocalScopesRec == null) {
						Error("Unsupported custom debug info type {0}", info.GetType());
						return null;
					}
					count = smLocalScopesRec.Scopes.Count;
					writer.Write(count);
					for (j = 0; j < count; j++) {
						var scope = smLocalScopesRec.Scopes[j];
						if (scope.IsSynthesizedLocal) {
							writer.Write(0);
							writer.Write(0);
						}
						else {
							writer.Write(GetInstructionOffset(scope.Start, nullIsEndOfMethod: false));
							writer.Write(GetInstructionOffset(scope.End, nullIsEndOfMethod: true) - 1);
						}
					}
					break;

				case PdbCustomDebugInfoKind.StateMachineTypeName:
					var smTypeRec = info as PdbStateMachineTypeNameCustomDebugInfo;
					if (smTypeRec == null) {
						Error("Unsupported custom debug info type {0}", info.GetType());
						return null;
					}
					var type = smTypeRec.Type;
					if (type == null) {
						Error("State machine type is null");
						return null;
					}
					WriteUnicodeZ(MetadataNameToRoslynName(type.Name));
					break;

				case PdbCustomDebugInfoKind.DynamicLocals:
					var dynLocListRec = info as PdbDynamicLocalsCustomDebugInfo;
					if (dynLocListRec == null) {
						Error("Unsupported custom debug info type {0}", info.GetType());
						return null;
					}
					count = dynLocListRec.Locals.Count;
					writer.Write(count);
					for (j = 0; j < count; j++) {
						var dynLoc = dynLocListRec.Locals[j];
						if (dynLoc == null) {
							Error("Dynamic local is null");
							return null;
						}
						if (dynLoc.Flags.Count > 64) {
							Error("Dynamic local flags is longer than 64 bytes");
							return null;
						}
						var name = dynLoc.Name;
						if (name == null)
							name = string.Empty;
						if (name.Length > 64) {
							Error("Dynamic local name is longer than 64 chars");
							return null;
						}
						if (name.IndexOf('\0') >= 0) {
							Error("Dynamic local name contains a NUL char");
							return null;
						}

						for (k = 0; k < dynLoc.Flags.Count; k++)
							writer.Write(dynLoc.Flags[k]);
						while (k++ < 64)
							writer.Write((byte)0);
						writer.Write(dynLoc.Flags.Count);

						if (dynLoc.Local == null)
							writer.Write(0);
						else
							writer.Write(dynLoc.Local.Index);

						for (k = 0; k < name.Length; k++)
							writer.Write((ushort)name[k]);
						while (k++ < 64)
							writer.Write((ushort)0);
					}
					break;

				case PdbCustomDebugInfoKind.EditAndContinueLocalSlotMap:
					var encLocalMapRec = info as PdbEditAndContinueLocalSlotMapCustomDebugInfo;
					if (encLocalMapRec == null) {
						Error("Unsupported custom debug info type {0}", info.GetType());
						return null;
					}
					writer.Write(encLocalMapRec.Data);
					break;

				case PdbCustomDebugInfoKind.EditAndContinueLambdaMap:
					var encLambdaRec = info as PdbEditAndContinueLambdaMapCustomDebugInfo;
					if (encLambdaRec == null) {
						Error("Unsupported custom debug info type {0}", info.GetType());
						return null;
					}
					writer.Write(encLambdaRec.Data);
					break;

				case PdbCustomDebugInfoKind.TupleElementNames:
					var tupleListRec = info as PdbTupleElementNamesCustomDebugInfo;
					if (tupleListRec == null) {
						Error("Unsupported custom debug info type {0}", info.GetType());
						return null;
					}
					count = tupleListRec.Names.Count;
					writer.Write(count);
					for (j = 0; j < count; j++) {
						var tupleInfo = tupleListRec.Names[j];
						if (tupleInfo == null) {
							Error("Tuple name info is null");
							return null;
						}
						writer.Write(tupleInfo.TupleElementNames.Count);
						for (k = 0; k < tupleInfo.TupleElementNames.Count; k++)
							WriteUTF8Z(tupleInfo.TupleElementNames[k]);

						if (tupleInfo.Local == null) {
							writer.Write(-1);
							writer.Write(GetInstructionOffset(tupleInfo.ScopeStart, nullIsEndOfMethod: false));
							writer.Write(GetInstructionOffset(tupleInfo.ScopeEnd, nullIsEndOfMethod: true));
						}
						else {
							writer.Write(tupleInfo.Local.Index);
							writer.Write(0L);
						}
						WriteUTF8Z(tupleInfo.Name);
					}
					break;

				default:
					var unkRec = info as PdbUnknownCustomDebugInfo;
					if (unkRec == null) {
						Error("Unsupported custom debug info clreplaced {0}", info.GetType());
						return null;
					}
					writer.Write(unkRec.Data);
					break;
				}

				var pos = writer.BaseStream.Position;
				var recLen = (pos - recordPos);
				var alignedLen = (recLen + 3) & ~3;
				if (alignedLen > uint.MaxValue) {
					Error("Custom debug info record is too big");
					return null;
				}
				writer.BaseStream.Position = recordPos + 3;
				if (info.Kind <= PdbCustomDebugInfoKind.DynamicLocals)
					writer.Write((byte)0);
				else
					writer.Write((byte)(alignedLen - recLen));
				writer.Write((uint)alignedLen);

				writer.BaseStream.Position = pos;
				while (writer.BaseStream.Position < recordPos + alignedLen)
					writer.Write((byte)0);
			}

			return memoryStream.ToArray();
		}

19 Source : ColumnInfo.cs
with GNU General Public License v3.0
from anydream

public void Write(BinaryWriter writer, uint value) {
			switch (size) {
			case 1: writer.Write((byte)value); break;
			case 2: writer.Write((ushort)value); break;
			case 4: writer.Write(value); break;
			default: throw new InvalidOperationException("Invalid column size");
			}
		}

19 Source : PdbCustomDebugInfoWriter.cs
with GNU General Public License v3.0
from anydream

void WriteUnicodeZ(string s) {
			if (s == null) {
				Error("String is null");
				return;
			}

			if (s.IndexOf('\0') >= 0) {
				Error("String contains a NUL char: {0}", s);
				return;
			}

			for (int i = 0; i < s.Length; i++)
				writer.Write((ushort)s[i]);
			writer.Write((ushort)0);
		}

See More Examples