示例#1
0
        public static IAppBuilder ContentLength(this IAppBuilder builder)
        {
            return builder.Transform((response, respond, fault) => {
                var status = response.Item1;
                var headers = response.Item2;
                var body = response.Item3;
                if (!ExcludeStatusesStartingWith.Any(i => status.StartsWith(i)) &&
                    !headers.ContainsKey("content-length") &&
                    !headers.ContainsKey("transfer-encoding") &&
                    body != null)
                {
                    var buffer = new DataBuffer();

                    body((data, ack) => {
                        buffer.Add(data);
                        return false;
                    },
                    fault,
                    () => {
                        headers["Content-Length"] = buffer.GetCount().ToString();
                        respond(Tuple.Create<string, IDictionary<string, string>, BodyDelegate>(status, headers, (onNext, onError, onComplete) => {
                            buffer.Each(d => onNext(new ArraySegment<byte>(d), null));
                            onComplete();
                            return null;
                        }));
                    });
                }
                else
                    respond(response);
            });
        }
示例#2
0
        public static AppDelegate Middleware(AppDelegate app)
        {
            return
                (env, result, fault) =>
                    app(
                        env,
                        (status, headers, body) =>
                        {
                            if (IsStatusWithNoNoEntityBody(status) ||
                                headers.ContainsKey("Content-Length") ||
                                headers.ContainsKey("Transfer-Encoding"))
                            {
                                result(status, headers, body);
                            }
                            else
                            {
                                var token = CancellationToken.None;
                                object obj;
                                if (env.TryGetValue(typeof(CancellationToken).FullName, out obj) && obj is CancellationToken)
                                    token = (CancellationToken)obj;

                                var buffer = new DataBuffer();
                                body(
                                    buffer.Add,
                                    ex =>
                                    {
                                        buffer.End(ex);
                                        headers["Content-Length"] = new[] { buffer.GetCount().ToString() };
                                        result(status, headers, buffer.Body);
                                    },
                                    token);
                            }
                        },
                        fault);
        }
示例#3
0
        public void SetData(DataBuffer data)
        {
            if (data == null)
                throw new ArgumentNullException("data");

            this.SetDataInternal(data, 0, data.Length, GLContext.DynamicDraw);
        }
示例#4
0
 private DataBuffer AddNewBuffer()
 {
     DataBuffer item = new DataBuffer();
     this.buffers.Add(item);
     this.currentBufferIndex = this.buffers.Count - 1;
     return item;
 }
示例#5
0
 public static AppDelegate Middleware(AppDelegate app)
 {
     return
         (call, callback) =>
             app(
                 call,
                 (result, error) =>
                 {
                     if (error != null ||
                         IsStatusWithNoNoEntityBody(result.Status) ||
                         result.Headers.ContainsKey("Content-Length") ||
                         result.Headers.ContainsKey("Transfer-Encoding"))
                     {
                         callback(result, error);
                     }
                     else
                     {
                         var buffer = new DataBuffer();
                         result.Body.Invoke(
                             buffer.Add,
                             ex =>
                             {
                                 buffer.End(ex);
                                 result.Headers.SetHeader("Content-Length", buffer.GetCount().ToString());
                                 result.Body = buffer.Body;
                                 callback(result, null);
                             },
                             call.CallDisposed);
                     }
                 });
 }
 public TileForm(DataBuffer rawTSABuffer)
 {
     InitializeComponent();
     this.rawTSABuffer = rawTSABuffer;
     toolStripShortCutKey = Keys.T;
     toolStripName = "Tile Control";
     this.Text = toolStripName;
 }
示例#7
0
        public StaticVertexBuffer(GraphicsContext graphics, VertexElement[] vertexElements, DataBuffer data)
            : base(graphics)
        {
            if (vertexElements == null)
                throw new ArgumentNullException("vertexElements");

            this.SetVertexDescription(vertexElements);
            this.SetDataInternal(data, 0, data.Length, GLContext.StaticDraw);
        }
示例#8
0
        public override bool Initialize()
        {
            if (this.Bitstream.Length < 44)
                throw new NotImplementedException();

            //this.header = new WAVBitstreamHeader();
            DataBuffer buffer = new DataBuffer(12);
            throw new NotImplementedException();
        }
        static DataBuffer CreateBody(string[] body)
        {
            var bodyBuffer = new DataBuffer();

            foreach (var b in body)
                bodyBuffer.Add(new ArraySegment<byte>(Encoding.ASCII.GetBytes(b)));

            return bodyBuffer;
        }
示例#10
0
 public PlayerDetector(int width, int height, CoordinateConverter mapper, int bufferSize = 1)
 {
     this.width = width;
       this.height = height;
       this.mapper = mapper;
       DepthPlayerMask = new Image<Gray, Byte>(width, height);
       ColorPlayerMask = new Image<Gray, Byte>(width, height);
       DepthImage = new Image<Gray, Byte>(width, height);
       dataBuffer = new DataBuffer(bufferSize);
 }
示例#11
0
        public ModelTransform(DataBuffer stream)
        {
            int anInt341 = stream.ReadByte();
            anIntArray342 = new int[anInt341];
            anIntArrayArray343 = new int[anInt341][];
            for (int j = 0; j < anInt341; j++)
                anIntArray342[j] = stream.ReadByte();

            for (int k = 0; k < anInt341; k++)
            {
                int l = stream.ReadByte();
                anIntArrayArray343[k] = new int[l];
                for (int i1 = 0; i1 < l; i1++)
                    anIntArrayArray343[k][i1] = stream.ReadByte();

            }
        }
        public static Bitmap imageLoader(GBAROM ROM, int imageOffset, int paletteOffset, int width, int height, bool isImageCompressed, bool isPaletteCompressed, bool transparent, GraphicsMode mode)
        {
            DataBuffer rawGraphics = new DataBuffer(0x8000);
            DataBuffer rawPalette = new DataBuffer(0x100);
            if (isImageCompressed)
            {
                rawGraphics.ReadCompressedData(ROM, imageOffset);
            }
            else
            {
                int gfxlength = GBAGraphics.RawGraphicsLength(new Size(width * 8, height * 8), mode);
                rawGraphics.ReadData(ROM, imageOffset, gfxlength);
            }

            if (isPaletteCompressed)
            {
                rawPalette.ReadCompressedData(ROM, paletteOffset);
            }
            else
            {
                rawPalette.ReadData(ROM, paletteOffset, 0x200);
            }

            byte[] graphics = rawGraphics.ToArray();
            int bitsPerPixel = GBAGraphics.BitsPerPixel(mode);

            int length = Math.Min(bitsPerPixel * width * height / 8, graphics.Length);
            Color[] palette;

            if (rawPalette.Length > 0 && paletteOffset != 0)
                palette = GBAPalette.ToPalette(rawPalette.ToArray(), 0, rawPalette.Length / 2);
            else
            {
                palette = new Color[16];
                for (int i = 0; i < palette.Length; i++)
                    palette[i] = Color.FromArgb(i * (256 / palette.Length), i * (256 / palette.Length), i * (256 / palette.Length));
            }

            int empty;
            if(transparent)
                palette[0] = Color.FromArgb(0, palette[0]);
            return GBAGraphics.ToBitmap(graphics, length, 0, palette, width, mode, out empty);
        }
		/// <summary>
		/// Reads data from a BerkeleyDb store entry.
		/// </summary>
		/// <param name="typeId">The type of the store accessed.</param>
		/// <param name="key">The key of the store entry accessed.</param>
		/// <returns>A <see cref="Stream"/> that accesses
		/// the entry data via unmanaged memory allocated from BerkeleyDb.</returns>
		/// <remarks>
		/// <para>Return value is null if</para>
		/// <para>Entry is not found in store.</para>
		/// <para>-or-</para>
		/// <para><paramref name="typeId"/> isn't valid.</para>
		/// <para>-or-</para>
		/// <para>A <see cref="BdbException"/> was thrown from the underlying store
		/// (Exception is logged but not rethrown).</para>
		/// </remarks>
		public Stream GetEntryStream(short typeId, DataBuffer key)
		{
			return GetEntryStream(typeId, key, GetOptions.Default);
		}
		/// <summary>
		/// Reads data from a BerkeleyDb store entry.
		/// </summary>
		/// <param name="typeId">The type of the store accessed.</param>
		/// <param name="key">The key of the store entry accessed.</param>
		/// <param name="options">The options for the read.</param>
		/// <returns>A <see cref="Stream"/> that accesses
		/// the entry data via unmanaged memory allocated from BerkeleyDb.</returns>
		/// <exception cref="ArgumentOutOfRangeException">
		/// <para><paramref name="options"/> has a negative offset.</para>
		/// </exception>
		/// <remarks>
		/// <para>Return value is null if</para>
		/// <para>Entry is not found in store.</para>
		/// <para>-or-</para>
		/// <para><paramref name="typeId"/> isn't valid.</para>
		/// <para>-or-</para>
		/// <para>A <see cref="BdbException"/> was thrown from the underlying store
		/// (Exception is logged but not rethrown).</para>
		/// </remarks>
		public Stream GetEntryStream(short typeId, DataBuffer key,
			GetOptions options)
		{
			return GetEntryStream(typeId, key.GetObjectId(), key, options);
		}
示例#15
0
 public Particle(ClientWrapper client, DataBuffer buffer) : base(client, buffer)
 {
     SendId = 0x2A;
 }
示例#16
0
 public SpawnObject(ClientWrapper client, DataBuffer buffer) : base(client, buffer)
 {
     SendId = 0x0E;
 }
示例#17
0
        /// <summary>
        ///  将到组件实体中的数据载入假结构体中
        /// </summary>
        /// <param name="com">unity组件</param>
        /// <param name="buffer">数据缓存器</param>
        /// <returns></returns>
        public unsafe override FakeStruct LoadFromObject(Component com, DataBuffer buffer)
        {
            var trans = com as Transform;

            if (trans == null)
            {
                return(null);
            }
            FakeStruct       fake = new FakeStruct(buffer, UITransfromData.ElementSize);
            UITransfromData *td   = (UITransfromData *)fake.ip;

            td->insID            = trans.GetInstanceID();
            td->localEulerAngles = trans.localEulerAngles;
            td->localPosition    = trans.localPosition;
            td->localScale       = trans.localScale;
            td->name             = buffer.AddData(trans.name);
            td->tag = buffer.AddData(trans.tag);
            var coms = com.GetComponents <Component>();

            td->type  = gameobjectBuffer.GetTypeID(coms);
            td->layer = trans.gameObject.layer;
            List <Int16> tmp = new List <short>();

            for (int i = 0; i < coms.Length; i++)
            {
                if (coms[i] is UIHelper)
                {
                    (coms[i] as UIHelper).ToBufferData(buffer, td);
                }
                else
                if (!(coms[i] is Transform))
                {
                    Int32 type = gameobjectBuffer.GetTypeIndex(coms[i]);
                    if (type >= 0)
                    {
                        var loader = gameobjectBuffer.GetDataLoader(type);
                        if (loader != null)
                        {
                            var fs = loader.LoadFromObject(coms[i], buffer);
                            tmp.Add((Int16)buffer.AddData(fs));
                        }
                        else
                        {
                            tmp.Add(0);
                        }
                        tmp.Add((Int16)type);
                        var scr = coms[i] as UIElement;
                        if (scr != null)
                        {
                            td->size  = scr.SizeDelta;
                            td->pivot = scr.Pivot;
                        }
                    }
                }
            }
            td->coms = buffer.AddData(tmp.ToArray());
            int c = trans.childCount;

            if (c > 0)
            {
                Int16[] buf = new short[c];
                for (int i = 0; i < c; i++)
                {
                    var fs = LoadFromObject(trans.GetChild(i), buffer);
                    buf[i] = (Int16)buffer.AddData(fs);
                }
                td->child = buffer.AddData(buf);
            }
            return(fake);
        }
示例#18
0
        public PackageFactory(ClientWrapper client, DataBuffer buffer)
        {
            #region Handshaking

            PingPackages.Add(new Handshake(client, buffer));

            #endregion

            #region Login

            LoginPackages.Add(new LoginStart(client, buffer));
            LoginPackages.Add(new EncryptionRequest(client, buffer));
            LoginPackages.Add(new EncryptionResponse(client, buffer));
            LoginPackages.Add(new LoginSucces(client, buffer));

            LoginPackages.Add(new Disconnect(client, buffer));
            LoginPackages.Add(new SetCompression(client, buffer));

            #endregion

            #region Status

            StatusPackages.Add(new Request(client, buffer));          // Accounts for client Response packet
            StatusPackages.Add(new Ping(client, buffer));             // Accounts for client Pong packet

            #endregion

            #region Play

            PlayPackages.Add(new BlockChange(client, buffer));
            PlayPackages.Add(new ChangeGameState(client, buffer));
            PlayPackages.Add(new ChunkData(client, buffer));
            PlayPackages.Add(new CollectItem(client, buffer));
            PlayPackages.Add(new DestroyEntities(client, buffer));
            PlayPackages.Add(new EntityEquipment(client, buffer));
            PlayPackages.Add(new EntityHeadLook(client, buffer));
            PlayPackages.Add(new EntityLook(client, buffer));
            PlayPackages.Add(new EntityMetadata(client, buffer));
            PlayPackages.Add(new EntityRelativeMove(client, buffer));
            PlayPackages.Add(new EntityTeleport(client, buffer));
            PlayPackages.Add(new EntityVelocity(client, buffer));
            PlayPackages.Add(new JoinGame(client, buffer));
            PlayPackages.Add(new MapChunkBulk(client, buffer));
            PlayPackages.Add(new OpenSignEditor(client, buffer));
            PlayPackages.Add(new OpenWindow(client, buffer));
            PlayPackages.Add(new Particle(client, buffer));
            PlayPackages.Add(new PlayerListHeaderFooter(client, buffer));
            PlayPackages.Add(new PlayerListItem(client, buffer));
            PlayPackages.Add(new Respawn(client, buffer));
            PlayPackages.Add(new SetSlot(client, buffer));
            PlayPackages.Add(new SoundEffect(client, buffer));
            PlayPackages.Add(new SpawnObject(client, buffer));
            PlayPackages.Add(new SpawnPlayer(client, buffer));
            PlayPackages.Add(new SpawnPosition(client, buffer));
            PlayPackages.Add(new TimeUpdate(client, buffer));
            PlayPackages.Add(new UpdateHealth(client, buffer));

            PlayPackages.Add(new ClickWindow(client, buffer));
            PlayPackages.Add(new ClientSettings(client, buffer));
            PlayPackages.Add(new ClientStatus(client, buffer));
            PlayPackages.Add(new CreativeInventoryAction(client, buffer));
            PlayPackages.Add(new EntityAction(client, buffer));
            PlayPackages.Add(new PlayerBlockPlacement(client, buffer));
            PlayPackages.Add(new PlayerDigging(client, buffer));
            PlayPackages.Add(new PlayerLook(client, buffer));
            PlayPackages.Add(new PlayerPacket(client, buffer));
            PlayPackages.Add(new PlayerPosition(client, buffer));
            PlayPackages.Add(new UseEntity(client, buffer));
            PlayPackages.Add(new WindowItems(client, buffer));

            PlayPackages.Add(new Animation(client, buffer));
            PlayPackages.Add(new ChatMessage(client, buffer));
            PlayPackages.Add(new CloseWindow(client, buffer));
            PlayPackages.Add(new ConfirmTransaction(client, buffer));
            PlayPackages.Add(new HeldItemChange(client, buffer));
            PlayPackages.Add(new KeepAlive(client, buffer));
            PlayPackages.Add(new PlayerAbilities(client, buffer));
            PlayPackages.Add(new PlayerPositionAndLook(client, buffer));
            PlayPackages.Add(new PluginMessage(client, buffer));
            PlayPackages.Add(new TabComplete(client, buffer));
            PlayPackages.Add(new UpdateSign(client, buffer));

            #endregion

            _client = client;
            _buffer = buffer;
        }
		/// <summary>
		/// Gets whether a BerkeleyDb store entry exists.
		/// </summary>
		/// <param name="typeId">The type of the store accessed.</param>
		/// <param name="objectId">The object id used for store access.</param>
		/// <param name="key">The key of the store entry accessed.</param>
		/// <returns>Whether the entry exists.</returns>
		/// <remarks>
		/// <para>Return value is <see langword="false"/> if:</para>
		/// <para><paramref name="typeId"/> isn't valid.</para>
		/// <para>-or-</para>
		/// <para>The entry specified by <paramref name="key"/> didn't exist within
		/// the store.</para>
		/// <para>-or-</para>
		/// <para>A <see cref="BdbException"/> was thrown from the underlying store
		/// (Exception is logged but not rethrown).</para>
		/// </remarks>
		public bool EntryExists(short typeId, int objectId, DataBuffer key)
		{
			if (!CanProcessMessage(typeId)) return false;
			DebugLog("EntryExists()", typeId, objectId);
			Database db = GetDatabase(typeId, objectId);
			var ret = db.Exists(key, ExistsOpFlags.Default);
			try
			{
				switch (ret)
				{
					case DbRetVal.SUCCESS:
						return true;
					case DbRetVal.NOTFOUND:
					case DbRetVal.KEYEMPTY:
						return false;
					default:
						throw new ApplicationException(string.Format(
							"EntryExists got unexpected value {0}", ret));
				}
			}
			catch (BdbException ex)
			{
				HandleBdbError(ex, db);
				return false;
			}
			catch (Exception ex)
			{
				ErrorLog("EntryExists()", ex);
				throw;
			}
		}
        /// <summary>
        /// Convienence method that takes an array of data buffers, each representing a vertex element (in the order
        /// declared by the vertex declaration), and writes all of the data to the vertex buffer. The buffers must match
        /// the vertex declaration as well as the byte sizes of each element and all be of the same length.
        /// </summary>
        /// <param name="data">Array of databuffers representing the vertex data.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if data is null.</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">Thrown if the number of buffers do not match the number
        /// of vertex elements, or if the number of vertices in each buffer does not match the vertex count,
        /// or if there is a byte size mismatch of any kind.</exception>
        public override void SetInterleavedData(params DataBuffer[] data)
        {
            if (_buffer == null || _buffer.Disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            if (data == null || data.Length == 0)
            {
                throw new ArgumentNullException("data", "Data cannot be null.");
            }

            VertexDeclaration vertexDecl = base.VertexDeclaration;
            int vertexCount = base.VertexCount;

            //Verify if the incoming vertex streams match right with the supplied vertex declaration
            VertexElement[] elems = vertexDecl.VertexElements;
            if (elems.Length != data.Length)
            {
                throw new ArgumentOutOfRangeException("data", "Number of vertex streams do not match up the number of declared vertex elements.");
            }

            int totalSizeInBytes = 0;
            int vertexStride     = 0;

            for (int i = 0; i < data.Length; i++)
            {
                DataBuffer    db           = data[i];
                VertexElement element      = elems[i];
                int           vSizeInBytes = db.ElementSizeInBytes;
                int           vCount       = db.SizeInBytes / vSizeInBytes;

                if (vCount != vertexCount)
                {
                    throw new ArgumentOutOfRangeException("data", "Vertex count mismatch, buffers must be of same length.");
                }
                if (vSizeInBytes != VertexDeclaration.GetVertexElementSize(element.Format))
                {
                    throw new ArgumentOutOfRangeException("data", "Supplied vertex buffer element size mismatch with actual vertex element size.");
                }

                totalSizeInBytes += db.SizeInBytes;
                vertexStride     += vSizeInBytes;
                db.Position       = 0;
            }

            if (totalSizeInBytes != vertexDecl.VertexStride * vertexCount)
            {
                throw new ArgumentOutOfRangeException("data", "Vertex data must match the size of the vertex buffer in bytes!");
            }

            CreateStaging();

            try {
                using (SDX.DataStream interleaved = _staging.Map(D3D.MapMode.Write, D3D.MapFlags.None)) {
                    byte[] vertex = new byte[vertexStride];
                    for (int i = 0; i < vertexCount; i++)
                    {
                        int startIndex = 0;
                        for (int j = 0; j < data.Length; j++)
                        {
                            DataBuffer db          = data[j];
                            int        elementSize = db.ElementSizeInBytes;
                            db.Get(vertex, startIndex, elementSize);
                            startIndex += elementSize;
                        }
                        interleaved.Write(vertex, 0, vertexStride);
                    }
                    _staging.Unmap();
                    //Copy entire resource
                    _graphicsDevice.CopyResource(_staging, _buffer);
                }
            } catch (Exception e) {
                throw new TeslaException("Error writing to D3D10 Buffer.", e);
            }
        }
        /// <summary>
        /// Creates a new instance of <see cref="D3D10VertexBufferImplementation"/> initialized with the interleaved data.
        /// </summary>
        /// <param name="renderer">The D3D10 renderer.</param>
        /// <param name="decl">The vertex declaration.</param>
        /// <param name="usage">The resource usage.</param>
        /// <param name="data">The interleaved data.</param>
        /// <exception cref="Tesla.Core.TeslaException">Thrown if creating the underlying D3D10 buffer or writing to it failed.</exception>
        internal D3D10VertexBufferImplementation(D3D10Renderer renderer, VertexDeclaration decl, ResourceUsage usage, DataBuffer data)
            : base(decl, usage, data)
        {
            _renderer       = renderer;
            _graphicsDevice = _renderer.GraphicsDevice;

            //Determine appropiate buffer, let any exceptions bubble up.
            try {
                using (SDX.DataStream ds = new SDX.DataStream(data.ByteDataCopy, true, false)) {
                    //Now create and populate appropiate D3D10 buffer
                    if (base.BufferUsage == ResourceUsage.Static)
                    {
                        D3D.ResourceUsage  rUsage    = D3D.ResourceUsage.Default;
                        D3D.CpuAccessFlags cpuAccess = D3D.CpuAccessFlags.None;
                        _buffer = new D3D.Buffer(_graphicsDevice, ds, new D3D.BufferDescription(data.SizeInBytes, rUsage, D3D.BindFlags.VertexBuffer, cpuAccess, D3D.ResourceOptionFlags.None));
                    }
                    else if (base.BufferUsage == ResourceUsage.Dynamic)
                    {
                        D3D.ResourceUsage  rUsage    = D3D.ResourceUsage.Dynamic;
                        D3D.CpuAccessFlags cpuAccess = D3D.CpuAccessFlags.Write;
                        _buffer = new D3D.Buffer(_graphicsDevice, ds, new D3D.BufferDescription(data.SizeInBytes, rUsage, D3D.BindFlags.VertexBuffer, cpuAccess, D3D.ResourceOptionFlags.None));
                    }
                }

                //Add to tracker
                _renderer.Resources.AddTrackedObject(_buffer.ComPointer, this);
            } catch (Exception e) {
                Dispose();
                throw new TeslaException("Error creating D3D10 buffer: \n" + e.Message, e);
            }
        }
示例#22
0
 private unsafe void resizeBuffer(int newSize)
 {
     _complexInputBuffer  = DataBuffer.Create(newSize, sizeof(Complex));
     _complexOutputBuffer = DataBuffer.Create((int)(newSize / _decimationFactor), sizeof(Complex));
 }
示例#23
0
    public static Class156 IHeader2(ulong ulong_0, DataBuffer dataBuffer_0, DataFragmentType enum8_0)
    {
        DataFragmentBody class2 = new DataFragmentBody(ulong_0, dataBuffer_0, enum8_0);

        return(new Class156(new IHeader1(2, byte_0, (ushort)class2.BodyTotalLength), class2));
    }
示例#24
0
 public override int GetLength(DataBuffer buffer)
 {
     return(sizeof(float) * 3);
 }
示例#25
0
 /// <summary>
 /// Implementation Reference RFC 1183
 /// </summary>
 /// <param name="buffer"></param>
 public RPRecord(DataBuffer buffer)
 {
     responsibleMailbox = buffer.ReadDomainName();
     textDomain         = buffer.ReadDomainName();
 }
		/// <summary>
		/// Writes data to a BerkeleyDb store entry.
		/// </summary>
		/// <param name="typeId">The type of the store accessed.</param>
		/// <param name="key">The key of the store entry accessed.</param>
		/// <param name="buffer">The buffer supplying the write data.</param>
		/// <param name="options">The options for the read.</param>
		/// <returns>Whether the write succeeded.</returns>
		/// <exception cref="ArgumentOutOfRangeException">
		/// <para><paramref name="options"/> has a negative offset.</para>
		/// </exception>
		/// <remarks>
		/// <para><see cref="DataBuffer.GetHashCode"/> of <paramref name="key"/> is used
		/// as the object id.</para>
		/// <para>Return value is <see langword="false"/> if:</para>
		/// <para><paramref name="typeId"/> isn't valid.</para>
		/// <para>-or-</para>
		/// <para>A <see cref="BdbException"/> was thrown from the underlying store
		/// (Exception is logged but not rethrown).</para>
		/// </remarks>
		public bool SaveEntry(short typeId, DataBuffer key, DataBuffer buffer,
			PutOptions options)
		{
			return SaveEntry(typeId, key.GetObjectId(), key, buffer, options);
		}
		/// <summary>
		/// Deletes a BerkeleyDb store entry.
		/// </summary>
		/// <param name="typeId">The type of the store accessed.</param>
		/// <param name="objectId">The object id used for store access.</param>
		/// <param name="key">The key of the store entry accessed.</param>
		/// <returns>Whether the deletion succeeded.</returns>
		/// <remarks>
		/// <para>Return value is <see langword="false"/> if:</para>
		/// <para><paramref name="typeId"/> isn't valid.</para>
		/// <para>-or-</para>
		/// <para>The entry specified by <paramref name="key"/> didn't exist within
		/// the store.</para>
		/// <para>-or-</para>
		/// <para>A <see cref="BdbException"/> was thrown from the underlying store
		/// (Exception is logged but not rethrown).</para>
		/// </remarks>
		public bool DeleteEntry(short typeId, int objectId, DataBuffer key)
		{
			if (!CanProcessMessage(typeId)) return false;
			DebugLog("DeleteEntry()", typeId, objectId);
			Database db = GetDatabase(typeId, objectId);
			try
			{
				return db.Delete(key, DeleteOpFlags.Default);
			}
			catch (BdbException ex)
			{
				HandleBdbError(ex, db);
				return false;
			}
			catch (Exception ex)
			{
				ErrorLog("DeleteEntry()", ex);
				throw;
			}
		}
示例#28
0
 public bool SendData(DataBuffer data) => _dataChannel.Send(new DataChannel.Buffer(ByteBuffer.Wrap(data.Data), data.IsBinary));
		/// <summary>
		/// Gets the length of a BerkeleyDb store entry.
		/// </summary>
		/// <param name="typeId">The type of the store accessed.</param>
		/// <param name="objectId">The object id used for store access.</param>
		/// <param name="key">The key of the store entry accessed.</param>
		/// <returns>The length of the entry.</returns>
		/// <remarks>
		/// <para>Return value is negative if:</para>
		/// <para><paramref name="typeId"/> isn't valid.</para>
		/// <para>-or-</para>
		/// <para>The entry specified by <paramref name="key"/> didn't exist within
		/// the store.</para>
		/// <para>-or-</para>
		/// <para>A <see cref="BdbException"/> was thrown from the underlying store
		/// (Exception is logged but not rethrown).</para>
		/// </remarks>
		public int GetEntryLength(short typeId, int objectId, DataBuffer key)
		{
			if (!CanProcessMessage(typeId)) return -1;
			DebugLog("GetEntryLength()", typeId, objectId);
			Database db = GetDatabase(typeId, objectId);
			try
			{
				return db.GetLength(key, GetOpFlags.Default);
			}
			catch (BdbException ex)
			{
				HandleBdbError(ex, db);
				return -1;
			}
			catch (Exception ex)
			{
				ErrorLog("GetEntryLength()", ex);
				throw;
			}
		}
        private static int DoMonsterDamageModifiers(int damage, MapleCharacter chr, MapleMonster mobFrom, int mobFromOID)
        {
            if (damage == 0) //guard/miss etc
            {
                Buff buff = chr.GetBuff(Priest.HOLY_MAGIC_SHELL);
                if (buff != null)
                {
                    buff.Stacks -= 1;
                    if (buff.Stacks == 0)
                    {
                        chr.CancelBuff(Priest.HOLY_MAGIC_SHELL);
                    }
                }
            }
            #region Spearman
            if (chr.IsSpearman)
            {
                if (chr.Job >= JobConstants.BERSERKER)
                {
                    if (chr.Job == JobConstants.DARKKNIGHT)
                    {
                        byte evilEyeRevengeLevel = chr.GetSkillLevel(DarkKnight.REVENGE_OF_THE_EVIL_EYE);
                        if (evilEyeRevengeLevel > 0 && !chr.HasSkillOnCooldown(DarkKnight.REVENGE_OF_THE_EVIL_EYE))
                        {
                            MapleSummon evilEye     = chr.GetSummon(Spearman.EVIL_EYE);
                            Buff        evilEyebuff = chr.GetBuff(Spearman.EVIL_EYE);
                            if (evilEye != null && evilEyebuff != null && evilEyebuff.Stacks != Berserker.EVIL_EYE_OF_DOMINATION)
                            {
                                SkillEffect effect       = DataBuffer.GetCharacterSkillById(DarkKnight.REVENGE_OF_THE_EVIL_EYE).GetEffect(evilEyeRevengeLevel);
                                int         summonDamage = (int)((effect.Info[CharacterSkillStat.damage] / 100.0) * chr.Stats.GetDamage());
                                int         healHp       = (int)((effect.Info[CharacterSkillStat.x] / 100.0) * summonDamage);
                                chr.AddHP(healHp);
                                //instant KO:
                                if (!mobFrom.IsBoss && summonDamage < mobFrom.HP)
                                {
                                    if (Functions.MakeChance(effect.Info[CharacterSkillStat.z]))
                                    {
                                        summonDamage = mobFrom.HP;
                                    }
                                }
                                evilEye.AttackMonster(summonDamage, 0x84, mobFrom);
                                chr.AddCooldownSilent(DarkKnight.REVENGE_OF_THE_EVIL_EYE, (uint)effect.Info[CharacterSkillStat.cooltime] * 1000, DateTime.UtcNow, false);
                            }
                        }
                        if (chr.HasBuff(DarkKnight.FINAL_PACT2))
                        {
                            return(0); //Invincible
                        }
                    }
                    Buff crossSurgeBuff = chr.GetBuff(Berserker.CROSS_SURGE);
                    if (crossSurgeBuff != null)
                    {
                        int absorbPercent = crossSurgeBuff.Effect.Info[CharacterSkillStat.y];
                        int absorb        = (int)((chr.Stats.MaxHp - chr.Hp) * (absorbPercent / 100.0));
                        absorb  = Math.Min(absorb, crossSurgeBuff.Effect.Info[CharacterSkillStat.z]); //normally z = 4000
                        damage -= absorb;
                    }
                }
            }
            #endregion
            #region Magician
            else if (chr.IsMagician)
            {
                Buff buff = chr.GetBuff(Magician.MAGIC_GUARD);
                if (buff != null)
                {
                    if (chr.Mp > 0)
                    {
                        int absorb = (int)((buff.Effect.Info[CharacterSkillStat.x] / 100.0) * damage);
                        if (chr.Mp < absorb)
                        {
                            absorb = chr.Mp;
                        }
                        chr.AddMP(-absorb);
                        damage -= absorb;
                    }
                }
            }
            #endregion
            #region Bandit
            else if (chr.IsBandit)
            {
                Buff mesoGuard = chr.GetBuff(Bandit.MESOGUARD);
                if (mesoGuard != null)
                {
                    double absorb            = 0.5;
                    double mesoLoss          = mesoGuard.Effect.Info[CharacterSkillStat.x] / 100.0;
                    double mesoLossReduction = 0.0;
                    byte   MesoMasteryLevel  = chr.GetSkillLevel(ChiefBandit.MESO_MASTERY);
                    if (MesoMasteryLevel > 0)
                    {
                        SkillEffect effect = DataBuffer.GetCharacterSkillById(ChiefBandit.MESO_MASTERY).GetEffect(MesoMasteryLevel);
                        absorb           += effect.Info[CharacterSkillStat.v] / 100.0;
                        mesoLossReduction = effect.Info[CharacterSkillStat.v] / 100.0;
                    }
                    int damageAbsorbed = (int)(damage * absorb);
                    if (damageAbsorbed > 0)
                    {
                        int mesoUse = (int)(damageAbsorbed * mesoLoss);
                        mesoUse -= (int)(mesoUse * mesoLossReduction);
                        if (chr.Mesos >= mesoUse)
                        {
                            chr.Inventory.RemoveMesos(mesoUse, false);
                            damage -= damageAbsorbed;
                            int mesoDrops = Functions.Random(1, 4);
                            for (int i = 0; i < mesoDrops; i++)
                            {
                                chr.Map.SpawnMesoMapItem(1, chr.Position, chr.Map.GetDropPositionBelow(chr.Position, chr.Position), false, MapleDropType.Player, chr);
                            }
                        }
                    }
                }
            }
            #endregion
            #region Luminous
            else if (chr.IsLuminous)
            {
                Buff oldBuff = chr.GetBuff(Luminous2.BLACK_BLESSING);
                if (oldBuff != null)
                {
                    int remove = (int)(damage * 0.7);
                    damage -= remove;
                    if (oldBuff.Stacks < 2)
                    {
                        chr.CancelBuff(Luminous2.BLACK_BLESSING);
                    }
                    else
                    {
                        chr.CancelBuffSilent(Luminous2.BLACK_BLESSING);
                        Buff newBuff = new Buff(oldBuff.SkillId, oldBuff.Effect, oldBuff.Duration, chr);
                        newBuff.Stacks = oldBuff.Stacks - 1;
                        chr.GiveBuff(newBuff);
                    }
                }
                byte skillLevel = 0;
                if ((skillLevel = chr.GetSkillLevel(Luminous1.STANDARD_MAGIC_GUARD)) > 0)
                {
                    SkillEffect effect  = DataBuffer.GetCharacterSkillById(Luminous1.STANDARD_MAGIC_GUARD).GetEffect(skillLevel);
                    double      percent = effect.Info[CharacterSkillStat.x] / 100.0;
                    int         absorb  = (int)(percent * damage);
                    if (chr.Mp >= absorb)
                    {
                        chr.AddMP(absorb);
                        damage -= absorb;
                    }
                }
            }
            #endregion

            return(damage);
        }
示例#31
0
 /// <summary>
 /// Implementation Reference RFC 1183
 /// </summary>
 /// <param name="buffer"></param>
 public IsdnRecord(DataBuffer buffer)
 {
     isdnAddress = buffer.ReadCharString();
     subAddress  = buffer.ReadCharString();
 }
示例#32
0
 public override int GetLength(DataBuffer data)
 {
     return(sizeof(byte) * 4);
 }
示例#33
0
 public TabComplete(ClientWrapper client, DataBuffer buffer) : base(client, buffer)
 {
     ReadId = 0x14;
     SendId = 0x3A;
 }
示例#34
0
 public DefaultStrategy()
 {
     _buffer = new DataBuffer();
 }
示例#35
0
    // Update is called once per frame
    void Update()
    {
        //鼠标右键按下
        if (Input.GetMouseButton((int)EMouseButton.E_MOUSE_RIGHT))
        {
            DataBuffer buf = new DataBuffer();
            buf.WriteByte(0);
            evtCtx.FireEvent(this, GameEventType.EVT_INPUT_MOUSE_BUTTON_DOWN, new GameEvtArg(buf));
        }
        //鼠标右键弹起
        if (Input.GetMouseButtonUp((int)EMouseButton.E_MOUSE_RIGHT))
        {
            DataBuffer buf = new DataBuffer();
            buf.WriteByte(0);
            evtCtx.FireEvent(this, GameEventType.EVT_INPUT_MOUSE_BUTTON_UP, new GameEvtArg(buf));
        }
        float deltaX = Input.GetAxis("Mouse X");
        float deltaY = Input.GetAxis("Mouse Y");

        {
            DataBuffer buf = new DataBuffer();
            buf.WriteFloat(deltaX);
            buf.WriteFloat(deltaY);
            evtCtx.FireEvent(this, GameEventType.EVT_INPUT_MOUSE_MOVE, new GameEvtArg(buf));
        }
        KeyCode code = KeyCode.None;

        if (Input.GetKeyDown(KeyCode.W))
        {
            code = KeyCode.W;
            DataBuffer buf = new DataBuffer();
            buf.WriteInt((int)code);
            evtCtx.FireEvent(this, GameEventType.EVT_INPUT_KEYBOARD_KEY_DOWN, new GameEvtArg(buf));
        }
        if (Input.GetKeyDown(KeyCode.S))
        {
            code = KeyCode.S;
            DataBuffer buf = new DataBuffer();
            buf.WriteInt((int)code);
            evtCtx.FireEvent(this, GameEventType.EVT_INPUT_KEYBOARD_KEY_DOWN, new GameEvtArg(buf));
        }
        if (Input.GetKeyDown(KeyCode.A))
        {
            code = KeyCode.A;
            DataBuffer buf = new DataBuffer();
            buf.WriteInt((int)code);
            evtCtx.FireEvent(this, GameEventType.EVT_INPUT_KEYBOARD_KEY_DOWN, new GameEvtArg(buf));
        }
        if (Input.GetKeyDown(KeyCode.D))
        {
            code = KeyCode.D;
            DataBuffer buf = new DataBuffer();
            buf.WriteInt((int)code);
            evtCtx.FireEvent(this, GameEventType.EVT_INPUT_KEYBOARD_KEY_DOWN, new GameEvtArg(buf));
        }

        if (Input.GetKeyUp(KeyCode.W))
        {
            code = KeyCode.W;
            DataBuffer buf = new DataBuffer();
            buf.WriteInt((int)code);
            evtCtx.FireEvent(this, GameEventType.EVT_INPUT_KEYBOARD_KEY_UP, new GameEvtArg(buf));
        }
        if (Input.GetKeyUp(KeyCode.S))
        {
            code = KeyCode.S;
            DataBuffer buf = new DataBuffer();
            buf.WriteInt((int)code);
            evtCtx.FireEvent(this, GameEventType.EVT_INPUT_KEYBOARD_KEY_UP, new GameEvtArg(buf));
        }
        if (Input.GetKeyUp(KeyCode.A))
        {
            code = KeyCode.A;
            DataBuffer buf = new DataBuffer();
            buf.WriteInt((int)code);
            evtCtx.FireEvent(this, GameEventType.EVT_INPUT_KEYBOARD_KEY_UP, new GameEvtArg(buf));
        }
        if (Input.GetKeyUp(KeyCode.D))
        {
            code = KeyCode.D;
            DataBuffer buf = new DataBuffer();
            buf.WriteInt((int)code);
            evtCtx.FireEvent(this, GameEventType.EVT_INPUT_KEYBOARD_KEY_UP, new GameEvtArg(buf));
        }
    }
        private void HandleAuthInfo(ParseData data)
        {
            try
            {
                DataReader dr = new DataReader(data.Data);
                if (m_pingPck != null)
                {
                    Send(m_pingPck);
                    m_pingPck = null;
                }
                m_received0x50 = true;

                m_loginType          = dr.ReadUInt32();
                m_srvToken           = dr.ReadUInt32();
                m_udpVal             = dr.ReadUInt32();
                m_mpqFiletime        = dr.ReadInt64();
                m_versioningFilename = dr.ReadCString();
                m_usingLockdown      = m_versioningFilename.StartsWith("LOCKDOWN", StringComparison.OrdinalIgnoreCase);

                int    crResult = -1, exeVer = -1;
                string exeInfo = null;

                if (!m_usingLockdown)
                {
                    m_valString = dr.ReadCString();
                    int mpqNum = CheckRevision.ExtractMPQNumber(m_versioningFilename);
                    crResult = CheckRevision.DoCheckRevision(m_valString, new string[] { m_settings.GameExe, m_settings.GameFile2, m_settings.GameFile3 }, mpqNum);
                    exeVer   = CheckRevision.GetExeInfo(m_settings.GameExe, out exeInfo);
                }
                else
                {
                    m_ldValStr = dr.ReadNullTerminatedByteArray();
                    string dllName = m_versioningFilename.Replace(".mpq", ".dll");

                    BnFtpVersion1Request req = new BnFtpVersion1Request(m_settings.Client, m_versioningFilename, null);
                    req.Server        = m_settings.Gateway.ServerHost;
                    req.LocalFileName = Path.Combine(Path.GetTempPath(), m_versioningFilename);
                    req.ExecuteRequest();

                    string ldPath = null;
                    using (MpqArchive arch = MpqServices.OpenArchive(req.LocalFileName))
                    {
                        if (arch.ContainsFile(dllName))
                        {
                            ldPath = Path.Combine(Path.GetTempPath(), dllName);
                            arch.SaveToPath(dllName, Path.GetTempPath(), false);
                        }
                    }

                    m_ldDigest = CheckRevision.DoLockdownCheckRevision(m_ldValStr, new string[] { m_settings.GameExe, m_settings.GameFile2, m_settings.GameFile3 },
                                                                       ldPath, m_settings.ImageFile, ref exeVer, ref crResult);
                }

                m_prodCode = m_settings.Client;

                if (m_prodCode == "WAR3" ||
                    m_prodCode == "W3XP")
                {
                    m_w3srv = dr.ReadByteArray(128);

                    if (!NLS.ValidateServerSignature(m_w3srv, RemoteEP.Address.GetAddressBytes()))
                    {
                        OnError(new ErrorEventArgs(ErrorType.Warcraft3ServerValidationFailure, Strings.War3ServerValidationFailed, false));
                        //Close();
                        //return;
                    }
                }

                BattleNetClientResources.IncomingBufferPool.FreeBuffer(data.Data);

                CdKey key1, key2 = null;
                key1 = new CdKey(m_settings.CdKey1);
                if (m_prodCode == "D2XP" || m_prodCode == "W3XP")
                {
                    key2 = new CdKey(m_settings.CdKey2);
                }

                m_clientToken = unchecked ((uint)new Random().Next());

                byte[] key1Hash = key1.GetHash(m_clientToken, m_srvToken);
                if (m_warden != null)
                {
                    try
                    {
                        if (!m_warden.InitWarden(BitConverter.ToInt32(key1Hash, 0)))
                        {
                            m_warden.UninitWarden();
                            OnError(new ErrorEventArgs(ErrorType.WardenModuleFailure, "The Warden module failed to initialize.  You will not be immediately disconnected; however, you may be disconnected after a short period of time.", false));
                            m_warden = null;
                        }
                    }
                    catch (Win32Exception we)
                    {
                        OnError(new ErrorEventArgs(ErrorType.WardenModuleFailure, "The Warden module failed to initialize.  You will not be immediately disconnected; however, you may be disconnected after a short period of time.", false));
                        OnError(new ErrorEventArgs(ErrorType.WardenModuleFailure, string.Format(CultureInfo.CurrentCulture, "Additional information: {0}", we.Message), false));
                        m_warden.UninitWarden();
                        m_warden = null;
                    }
                }

                BncsPacket pck0x51 = new BncsPacket((byte)BncsPacketId.AuthCheck);
                pck0x51.Insert(m_clientToken);
                pck0x51.Insert(exeVer);
                pck0x51.Insert(crResult);
                if (m_prodCode == "D2XP" || m_prodCode == "W3XP")
                {
                    pck0x51.Insert(2);
                }
                else
                {
                    pck0x51.Insert(1);
                }
                pck0x51.Insert(false);
                pck0x51.Insert(key1.Key.Length);
                pck0x51.Insert(key1.Product);
                pck0x51.Insert(key1.Value1);
                pck0x51.Insert(0);
                pck0x51.Insert(key1Hash);
                if (key2 != null)
                {
                    pck0x51.Insert(key2.Key.Length);
                    pck0x51.Insert(key2.Product);
                    pck0x51.Insert(key2.Value1);
                    pck0x51.Insert(0);
                    pck0x51.Insert(key2.GetHash(m_clientToken, m_srvToken));
                }

                if (m_usingLockdown)
                {
                    pck0x51.InsertByteArray(m_ldDigest);
                    pck0x51.InsertByte(0);
                }
                else
                {
                    pck0x51.InsertCString(exeInfo);
                }

                pck0x51.InsertCString(m_settings.CdKeyOwner);

                Send(pck0x51);
            }
            catch (Exception ex)
            {
                OnError(new ErrorEventArgs(ErrorType.General, "There was an error while initializing your client.  Refer to the exception message for more information.\n" + ex.ToString(), true));
                Close();
            }
        }
示例#37
0
 public static void LoadModel(byte[] abyte0, int j)
 {
     if (aModelHeaderArray1661 == null)
         aModelHeaderArray1661 = new ModelHeader[10000];
     if (abyte0 == null)
     {
         ModelHeader class21 = aModelHeaderArray1661[j] = new ModelHeader();
         class21.anInt369 = 0;
         class21.anInt370 = 0;
         class21.anInt371 = 0;
         return;
     }
     DataBuffer stream = new DataBuffer(abyte0);
     stream.Location = abyte0.Length - 18;
     ModelHeader class21_1 = aModelHeaderArray1661[j] = new ModelHeader();
     class21_1.aByteArray368 = abyte0;
     class21_1.anInt369 = stream.ReadShort();
     class21_1.anInt370 = stream.ReadShort();
     class21_1.anInt371 = stream.ReadByte();
     int k = stream.ReadByte();
     int l = stream.ReadByte();
     int i1 = stream.ReadByte();
     int j1 = stream.ReadByte();
     int k1 = stream.ReadByte();
     int l1 = stream.ReadShort();
     int i2 = stream.ReadShort();
     int j2 = stream.ReadShort();
     int k2 = stream.ReadShort();
     int l2 = 0;
     class21_1.anInt372 = l2;
     l2 += class21_1.anInt369;
     class21_1.anInt378 = l2;
     l2 += class21_1.anInt370;
     class21_1.anInt381 = l2;
     if (l == 255)
         l2 += class21_1.anInt370;
     else
         class21_1.anInt381 = -l - 1;
     class21_1.anInt383 = l2;
     if (j1 == 1)
         l2 += class21_1.anInt370;
     else
         class21_1.anInt383 = -1;
     class21_1.anInt380 = l2;
     if (k == 1)
         l2 += class21_1.anInt370;
     else
         class21_1.anInt380 = -1;
     class21_1.anInt376 = l2;
     if (k1 == 1)
         l2 += class21_1.anInt369;
     else
         class21_1.anInt376 = -1;
     class21_1.anInt382 = l2;
     if (i1 == 1)
         l2 += class21_1.anInt370;
     else
         class21_1.anInt382 = -1;
     class21_1.anInt377 = l2;
     l2 += k2;
     class21_1.anInt379 = l2;
     l2 += class21_1.anInt370 * 2;
     class21_1.anInt384 = l2;
     l2 += class21_1.anInt371 * 6;
     class21_1.anInt373 = l2;
     l2 += l1;
     class21_1.anInt374 = l2;
     l2 += i2;
     class21_1.anInt375 = l2;
     l2 += j2;
 }
		/// <summary>
		/// Reads data from a BerkeleyDb store entry.
		/// </summary>
		/// <param name="typeId">The type of the store accessed.</param>
		/// <param name="objectId">The object id used for store access.</param>
		/// <param name="key">The key of the store entry accessed.</param>
		/// <param name="options">The options for the read.</param>
		/// <returns>A <see cref="Stream"/> that accesses
		/// the entry data via unmanaged memory allocated from BerkeleyDb.</returns>
		/// <exception cref="ArgumentOutOfRangeException">
		/// <para><paramref name="options"/> has a negative offset.</para>
		/// </exception>
		/// <remarks>
		/// <para></para>
		/// <para>Return value is null if</para>
		/// <para>Entry is not found in store.</para>
		/// <para>-or-</para>
		/// <para><paramref name="typeId"/> isn't valid.</para>
		/// <para>-or-</para>
		/// <para>A <see cref="BdbException"/> was thrown from the underlying store
		/// (Exception is logged but not rethrown).</para>
		/// </remarks>
		public Stream GetEntryStream(short typeId, int objectId,
			DataBuffer key, GetOptions options)
		{
			options.AssertValid("options");
			if (!CanProcessMessage(typeId)) return null;
			DebugLog("GetEntry()", typeId, objectId);
			Database db = GetDatabase(typeId, objectId);
			try
			{
				return db.Get(key, options.Offset, options.Length, options.Flags);
			}
			catch (BdbException ex)
			{
				HandleBdbError(ex, db);
				return null;
			}
			catch (Exception ex)
			{
				ErrorLog("GetEntry()", ex);
				throw;
			}
		}
示例#39
0
        /// <summary>
        /// Executes the BnFTP request, downloading the file to where <see cref="BnFtpRequestBase.LocalFileName">LocalFileName</see>
        /// specifies, and closes the connection.
        /// </summary>
        /// <remarks>
        /// <para>By default, <c>LocalFileName</c> is the same name as the remote file, which will cause the file
        /// to be saved in the local application path.  The desired location of the file must be set before
        /// <b>ExecuteRequest</b> is called.</para>
        /// </remarks>
        /// <exception cref="IOException">Thrown if the local file cannot be written.</exception>
        /// <exception cref="SocketException">Thrown if the remote host closes the connection prematurely.</exception>
        public override void ExecuteRequest()
        {
            DataBuffer buffer = new DataBuffer();

            buffer.InsertInt16((short)(33 + FileName.Length));
            buffer.InsertInt16(0x0100);
            buffer.InsertDwordString("IX86");
            buffer.InsertDwordString(Product);
            if (m_ad)
            {
                buffer.InsertInt32(m_adId);
                buffer.InsertDwordString(m_adExt);
            }
            else
            {
                buffer.InsertInt64(0);
            }
            // currently resuming is not supported
            buffer.InsertInt32(0);
            if (FileTime.HasValue)
            {
                buffer.InsertInt64(FileTime.Value.ToFileTimeUtc());
            }
            else
            {
                buffer.InsertInt64(0);
            }
            buffer.InsertCString(FileName);

            Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            sck.Connect(Server, 6112);
            sck.Send(new byte[] { 2 });
            sck.Send(buffer.UnderlyingBuffer, 0, buffer.Count, SocketFlags.None);

            byte[] hdrLengthBytes = new byte[2];
            sck.Receive(hdrLengthBytes, 2, SocketFlags.None);

            int hdrLen = BitConverter.ToInt16(hdrLengthBytes, 0);

            Debug.WriteLine(hdrLen, "Header Length");
            byte[] hdrBytes = new byte[hdrLen - 2];
            sck.Receive(hdrBytes, hdrLen - 2, SocketFlags.None);
            DataReader rdr = new DataReader(hdrBytes);

            rdr.Seek(2);
            int fileSize = rdr.ReadInt32();

            this.FileSize = fileSize;
            rdr.Seek(8);
            long   fileTime = rdr.ReadInt64();
            string name     = rdr.ReadCString();

            if (string.Compare(name, FileName, StringComparison.OrdinalIgnoreCase) != 0 || FileSize == 0)
            {
                throw new FileNotFoundException(Resources.bnftp_filenotfound);
            }
            Debug.WriteLine(fileSize, "File Size");

            byte[] data = ReceiveLoop(sck, fileSize);
            sck.Close();

            FileStream fs = new FileStream(LocalFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);

            fs.SetLength(fileSize);
            fs.Write(data, 0, fileSize);
            fs.Flush();
            fs.Close();
            DateTime time = DateTime.FromFileTimeUtc(fileTime);

            File.SetLastWriteTimeUtc(LocalFileName, time);
        }
示例#40
0
 public virtual void Cmd(DataBuffer dat)
 {
 }
示例#41
0
 public void SetStreamSource(int streamNumber, DataBuffer streamData, int offsetInBytes, int stride)
 {
     int res = Interop.Calli(comPointer, streamNumber,(streamData == null)?IntPtr.Zero:streamData.comPointer,offsetInBytes, stride,(*(IntPtr**)comPointer)[100]);
     if( res < 0 ) { throw new SharpDXException( res ); }
 }
示例#42
0
 protected override void ReadData(DataBuffer buf, FileFormat fmt)
 {
     Type   = (PoolType)buf.ReadInt32();
     Handle = buf.ReadInt32();
 }
示例#43
0
        public Model(int i)
        {
            ID = i;
            aBoolean1659 = false;
            ModelHeader class21 = aModelHeaderArray1661[i];
            VertexCount = class21.anInt369;
            TriangleCount = class21.anInt370;
            anInt1642 = class21.anInt371;
            vertices_x = new int[VertexCount];
            vertices_y = new int[VertexCount];
            vertices_z = new int[VertexCount];
            anIntArray1631 = new int[TriangleCount];
            anIntArray1632 = new int[TriangleCount];
            anIntArray1633 = new int[TriangleCount];
            anIntArray1643 = new int[anInt1642];
            anIntArray1644 = new int[anInt1642];
            anIntArray1645 = new int[anInt1642];
            if (class21.anInt376 >= 0)
                anIntArray1655 = new int[VertexCount];
            if (class21.anInt380 >= 0)
                anIntArray1637 = new int[TriangleCount];
            if (class21.anInt381 >= 0)
                anIntArray1638 = new int[TriangleCount];
            else
                anInt1641 = -class21.anInt381 - 1;
            if (class21.anInt382 >= 0)
                anIntArray1639 = new int[TriangleCount];
            if (class21.anInt383 >= 0)
                anIntArray1656 = new int[TriangleCount];
            anIntArray1640 = new int[TriangleCount];
            DataBuffer stream = new DataBuffer(class21.aByteArray368);
            stream.Location = class21.anInt372;
            DataBuffer stream_1 = new DataBuffer(class21.aByteArray368);
            stream_1.Location = class21.anInt373;
            DataBuffer stream_2 = new DataBuffer(class21.aByteArray368);
            stream_2.Location = class21.anInt374;
            DataBuffer stream_3 = new DataBuffer(class21.aByteArray368);
            stream_3.Location = class21.anInt375;
            DataBuffer stream_4 = new DataBuffer(class21.aByteArray368);
            stream_4.Location = class21.anInt376;
            int k = 0;
            int l = 0;
            int i1 = 0;
            for (int j1 = 0; j1 < VertexCount; j1++)
            {
                int k1 = stream.ReadByte();
                int i2 = 0;
                if ((k1 & 1) != 0)
                    i2 = stream_1.ReadSmart();
                int k2 = 0;
                if ((k1 & 2) != 0)
                    k2 = stream_2.ReadSmart();
                int i3 = 0;
                if ((k1 & 4) != 0)
                    i3 = stream_3.ReadSmart();
                vertices_x[j1] = k + i2;
                vertices_y[j1] = l + k2;
                vertices_z[j1] = i1 + i3;
                k = vertices_x[j1];
                l = vertices_y[j1];
                i1 = vertices_z[j1];
                if (anIntArray1655 != null)
                    anIntArray1655[j1] = stream_4.ReadByte();
            }

            stream.Location = class21.anInt379;
            stream_1.Location = class21.anInt380;
            stream_2.Location = class21.anInt381;
            stream_3.Location = class21.anInt382;
            stream_4.Location = class21.anInt383;
            for (int l1 = 0; l1 < TriangleCount; l1++)
            {
                anIntArray1640[l1] = stream.ReadShort();
                if (anIntArray1637 != null)
                    anIntArray1637[l1] = stream_1.ReadByte();
                if (anIntArray1638 != null)
                    anIntArray1638[l1] = stream_2.ReadByte();
                if (anIntArray1639 != null)
                    anIntArray1639[l1] = stream_3.ReadByte();
                if (anIntArray1656 != null)
                    anIntArray1656[l1] = stream_4.ReadByte();
            }

            stream.Location = class21.anInt377;
            stream_1.Location = class21.anInt378;
            int j2 = 0;
            int l2 = 0;
            int j3 = 0;
            int k3 = 0;
            for (int l3 = 0; l3 < TriangleCount; l3++)
            {
                int i4 = stream_1.ReadByte();
                if (i4 == 1)
                {
                    j2 = stream.ReadSmart() + k3;
                    k3 = j2;
                    l2 = stream.ReadSmart() + k3;
                    k3 = l2;
                    j3 = stream.ReadSmart() + k3;
                    k3 = j3;
                    anIntArray1631[l3] = j2;
                    anIntArray1632[l3] = l2;
                    anIntArray1633[l3] = j3;
                }
                if (i4 == 2)
                {
                    l2 = j3;
                    j3 = stream.ReadSmart() + k3;
                    k3 = j3;
                    anIntArray1631[l3] = j2;
                    anIntArray1632[l3] = l2;
                    anIntArray1633[l3] = j3;
                }
                if (i4 == 3)
                {
                    j2 = j3;
                    j3 = stream.ReadSmart() + k3;
                    k3 = j3;
                    anIntArray1631[l3] = j2;
                    anIntArray1632[l3] = l2;
                    anIntArray1633[l3] = j3;
                }
                if (i4 == 4)
                {
                    int k4 = j2;
                    j2 = l2;
                    l2 = k4;
                    j3 = stream.ReadSmart() + k3;
                    k3 = j3;
                    anIntArray1631[l3] = j2;
                    anIntArray1632[l3] = l2;
                    anIntArray1633[l3] = j3;
                }
            }

            stream.Location = class21.anInt384;
            for (int j4 = 0; j4 < anInt1642; j4++)
            {
                anIntArray1643[j4] = stream.ReadShort();
                anIntArray1644[j4] = stream.ReadShort();
                anIntArray1645[j4] = stream.ReadShort();
            }
        }
示例#44
0
 protected override void WriteData(DataBuffer buf, FileFormat fmt)
 {
     buf.Write((int)Type);
     buf.Write(Handle);
 }
		/// <summary>
		/// Reads data from a BerkeleyDb store entry.
		/// </summary>
		/// <param name="typeId">The type of the store accessed.</param>
		/// <param name="objectId">The object id used for store access.</param>
		/// <param name="key">The key of the store entry accessed.</param>
		/// <param name="buffer">The buffer to which the read data is written.</param>
		/// <param name="options">The options for the read.</param>
		/// <returns>The length of the entry in the store.</returns>
		/// <exception cref="ArgumentOutOfRangeException">
		/// <para><paramref name="buffer"/> has an <see cref="DataBuffer.IsWritable"/> of
		/// <see langword="false"/>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="options"/> has a negative offset.</para>
		/// </exception>
		/// <remarks>
		/// <para>If the entry is longer than <paramref name="buffer"/>, then
		/// <paramref name="buffer"/> is written to its full capacity, but the
		/// entry length is still returned.
		/// </para>
		/// <para>Return value is negative if</para>
		/// <para>Entry is not found in store.</para>
		/// <para>-or-</para>
		/// <para><paramref name="typeId"/> isn't valid.</para>
		/// <para>-or-</para>
		/// <para>A <see cref="BdbException"/> was thrown from the underlying store
		/// (Exception is logged but not rethrown).</para>
		/// </remarks>
		public int GetEntry(short typeId, int objectId, DataBuffer key, DataBuffer buffer,
			GetOptions options)
		{
			if (!buffer.IsWritable) throw new ArgumentOutOfRangeException("buffer");
			options.AssertValid("options");
			if (!CanProcessMessage(typeId)) return -1;
			DebugLog("GetEntry()", typeId, objectId);
			Database db = GetDatabase(typeId, objectId);
			try
			{
				return db.Get(key, options.Offset, buffer, options.Flags);
			}
			catch (BdbException ex)
			{
				HandleBdbError(ex, db);
				return -1;
			}
			catch (Exception ex)
			{
				ErrorLog("GetEntry()", ex);
				throw;
			}
		}
示例#46
0
        private static string ReadFlag(DataBuffer table, int itemOffset, BdatMember member, BdatMember flagsMember)
        {
            uint flags = uint.Parse(ReadValue(table, itemOffset + flagsMember.MemberPos, flagsMember.ValType));

            return(((flags & member.FlagMask) != 0).ToString());
        }
		/// <summary>
		/// Reads data from a BerkeleyDb store entry.
		/// </summary>
		/// <param name="typeId">The type of the store accessed.</param>
		/// <param name="key">The key of the store entry accessed.</param>
		/// <param name="buffer">The buffer to which the read data is written.</param>
		/// <param name="options">The options for the read.</param>
		/// <returns>The length of the entry in the store.</returns>
		/// <exception cref="ArgumentOutOfRangeException">
		/// <para><paramref name="buffer"/> has an <see cref="DataBuffer.IsWritable"/> of
		/// <see langword="false"/>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="options"/> has a negative offset.</para>
		/// </exception>
		/// <remarks>
		/// <para><see cref="DataBuffer.GetHashCode"/> of <paramref name="key"/> is used
		/// as the object id.</para>
		/// <para>If the entry is longer than <paramref name="buffer"/>, then
		/// <paramref name="buffer"/> is written to its full capacity, but the
		/// entry length is still returned.
		/// </para>
		/// <para>Return value is negative if</para>
		/// <para>Entry is not found in store.</para>
		/// <para>-or-</para>
		/// <para><paramref name="typeId"/> isn't valid.</para>
		/// <para>-or-</para>
		/// <para>A <see cref="BdbException"/> was thrown from the underlying store
		/// (Exception is logged but not rethrown).</para>
		/// </remarks>
		public int GetEntry(short typeId, DataBuffer key, DataBuffer buffer,
			GetOptions options)
		{
			return GetEntry(typeId, key.GetObjectId(), key, buffer, options);
		}
示例#48
0
 public void Clear_buffer()
 {
     buffer = new DataBuffer();
 }
		/// <summary>
		/// Reads data from a BerkeleyDb store entry.
		/// </summary>
		/// <param name="typeId">The type of the store accessed.</param>
		/// <param name="key">The key of the store entry accessed.</param>
		/// <param name="buffer">The buffer to which the read data is written.</param>
		/// <returns>The length of the entry in the store.</returns>
		/// <exception cref="ArgumentOutOfRangeException">
		/// <para><paramref name="buffer"/> has an <see cref="DataBuffer.IsWritable"/> of
		/// <see langword="false"/>.</para>
		/// </exception>
		/// <remarks>
		/// <para><see cref="DataBuffer.GetHashCode"/> of <paramref name="key"/> is used
		/// as the object id.</para>
		/// <para>If the entry is longer than <paramref name="buffer"/>, then
		/// <paramref name="buffer"/> is written to its full capacity, but the
		/// entry length is still returned.
		/// </para>
		/// <para>Return value is negative if</para>
		/// <para>Entry is not found in store.</para>
		/// <para>-or-</para>
		/// <para><paramref name="typeId"/> isn't valid.</para>
		/// <para>-or-</para>
		/// <para>A <see cref="BdbException"/> was thrown from the underlying store
		/// (Exception is logged but not rethrown).</para>
		/// </remarks>
		public int GetEntry(short typeId, DataBuffer key, DataBuffer buffer)
		{
			return GetEntry(typeId, key, buffer, GetOptions.Default);
		}
示例#50
0
 public OpenSignEditor(ClientWrapper client, DataBuffer buffer) : base(client, buffer)
 {
     SendId = 0x36;
 }
		/// <summary>
		/// Writes data to a BerkeleyDb store entry.
		/// </summary>
		/// <param name="typeId">The type of the store accessed.</param>
		/// <param name="objectId">The object id used for store access.</param>
		/// <param name="key">The key of the store entry accessed.</param>
		/// <param name="buffer">The buffer supplying the write data.</param>
		/// <param name="options">The options for the read.</param>
		/// <returns>Whether the write succeeded.</returns>
		/// <exception cref="ArgumentOutOfRangeException">
		/// <para><paramref name="options"/> has a negative offset.</para>
		/// </exception>
		/// <remarks>
		/// <para>Return value is <see langword="false"/> if:</para>
		/// <para><paramref name="typeId"/> isn't valid.</para>
		/// <para>-or-</para>
		/// <para>A <see cref="BdbException"/> was thrown from the underlying store
		/// (Exception is logged but not rethrown).</para>
		/// </remarks>
		public bool SaveEntry(short typeId, int objectId, DataBuffer key, DataBuffer buffer,
			PutOptions options)
		{
			options.AssertValid("options");
			if (!CanProcessMessage(typeId)) return false;
			DebugLog("SaveEntry()", typeId, objectId);
			Database db = GetDatabase(typeId, objectId);
			try
			{
				var size = db.Put(key, options.Offset, options.Length, buffer,
					options.Flags);
				if (size != buffer.ByteLength)
					throw new BdbException((int)DbRetVal.LENGTHMISMATCH, string.Format(
						"Expected save length of {0}, got {1}", buffer.ByteLength,
						size));
			}
			catch (BdbException ex)
			{
				HandleBdbError(ex, db);
				return false;
			}
			catch (Exception ex)
			{
				ErrorLog("SaveEntry()", ex);
				throw;
			}
			return true;
		}
示例#52
0
 public void SendMessage(object recipientKey, DataBuffer data)
 {
     (recipientKey as DirectClientProvider).ReceiveMessage(data);
     DataSent?.Invoke(this, new ProviderDataEventArgs(recipientKey, false, null, data.GetLength()));
 }
		/// <summary>
		/// Writes data to a BerkeleyDb store entry.
		/// </summary>
		/// <param name="typeId">The type of the store accessed.</param>
		/// <param name="key">The key of the store entry accessed.</param>
		/// <param name="buffer">The buffer supplying the write data.</param>
		/// <returns>Whether the write succeeded.</returns>
		/// <remarks>
		/// <para><see cref="DataBuffer.GetHashCode"/> of <paramref name="key"/> is used
		/// as the object id.</para>
		/// <para>Return value is <see langword="false"/> if:</para>
		/// <para><paramref name="typeId"/> isn't valid.</para>
		/// <para>-or-</para>
		/// <para>A <see cref="BdbException"/> was thrown from the underlying store
		/// (Exception is logged but not rethrown).</para>
		/// </remarks>
		public bool SaveEntry(short typeId, DataBuffer key, DataBuffer buffer)
		{
			return SaveEntry(typeId, key, buffer, PutOptions.Default);
		}
示例#54
0
        public void ReceiveMessage(DirectClientProvider client, DataBuffer data)
        {
            DataBuffer d = new DataBuffer(data.ToBytes());

            DataReceived?.Invoke(this, new ProviderDataEventArgs(client, true, d, d.GetLength()));
        }
		/// <summary>
		/// Deletes a BerkeleyDb store entry.
		/// </summary>
		/// <param name="typeId">The type of the store accessed.</param>
		/// <param name="key">The key of the store entry accessed.</param>
		/// <returns>Whether the deletion succeeded.</returns>
		/// <remarks>
		/// <para><see cref="DataBuffer.GetHashCode"/> of <paramref name="key"/> is used
		/// as the object id.</para>
		/// <para>Return value is <see langword="false"/> if:</para>
		/// <para><paramref name="typeId"/> isn't valid.</para>
		/// <para>-or-</para>
		/// <para>The entry specified by <paramref name="key"/> didn't exist within
		/// the store.</para>
		/// <para>-or-</para>
		/// <para>A <see cref="BdbException"/> was thrown from the underlying store
		/// (Exception is logged but not rethrown).</para>
		/// </remarks>
		public bool DeleteEntry(short typeId, DataBuffer key)
		{
			return DeleteEntry(typeId, key.GetObjectId(), key);
		}
示例#56
0
        private void ReceiveData(IAsyncResult ar)
        {
            var state = (StateObject)ar.AsyncState;

            if (!Clients.ContainsKey(state.Id))
            {
                return;
            }

            LastData[state.Id] = DateTime.UtcNow;

            Int32 receive = 0;

            try {
                receive = state.Connection.EndReceive(ar);
            } catch { }

            if (receive > 0)
            {
                state.Data.Append(state.Buffer);
                state.Received += receive;
                var temp = new DataBuffer();
                temp.FromArray(state.Data.ToArray());
                var alength = temp.ReadInt32();
                if ((state.Received - 4) >= alength)
                {
                    var work = true;
                    while (work)
                    {
                        var calc = new DataBuffer();
                        calc.FromArray(state.Data.ToArray());
                        var length = calc.ReadInt32();
                        if (state.Data.Length() - 4 >= length)
                        {
                            var buffer = new DataBuffer();
                            buffer.FromArray(state.Data.ToArray().Skip(4).Take(length).ToArray());
                            var data = state.Data.ToArray().Skip(4 + length).Take(state.Received - (4 + length)).ToArray();
                            state.Data.FromArray(data);
                            state.Buffer = data;
                            this.PacketHandler(state.Id, buffer);
                        }
                        else
                        {
                            var newstate = new StateObject();
                            newstate.Id         = state.Id;
                            newstate.Connection = state.Connection;
                            newstate.Data       = new DataBuffer();
                            try {
                                state.Connection.BeginReceive(newstate.Buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(ReceiveData), newstate);
                            } catch { }
                            work = false;
                        }
                    }
                }
                else
                {
                    try {
                        state.Connection.BeginReceive(state.Buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(ReceiveData), state);
                    } catch { }
                }
            }
        }
		/// <summary>
		/// Gets whether a BerkeleyDb store entry exists.
		/// </summary>
		/// <param name="typeId">The type of the store accessed.</param>
		/// <param name="key">The key of the store entry accessed.</param>
		/// <returns>Whether the entry exists.</returns>
		/// <remarks>
		/// <para><see cref="DataBuffer.GetHashCode"/> of <paramref name="key"/> is used
		/// as the object id.</para>
		/// <para>Return value is <see langword="false"/> if:</para>
		/// <para><paramref name="typeId"/> isn't valid.</para>
		/// <para>-or-</para>
		/// <para>The entry specified by <paramref name="key"/> didn't exist within
		/// the store.</para>
		/// <para>-or-</para>
		/// <para>A <see cref="BdbException"/> was thrown from the underlying store
		/// (Exception is logged but not rethrown).</para>
		/// </remarks>
		public bool EntryExists(short typeId, DataBuffer key)
		{
			return EntryExists(typeId, key.GetObjectId(), key);
		}
示例#58
0
 public EncryptionResponse(ClientWrapper client, DataBuffer buffer) : base(client, buffer)
 {
     ReadId = 0x01;
 }
		/// <summary>
		/// Gets the length of a BerkeleyDb store entry.
		/// </summary>
		/// <param name="typeId">The type of the store accessed.</param>
		/// <param name="key">The key of the store entry accessed.</param>
		/// <returns>The length of the entry.</returns>
		/// <remarks>
		/// <para><see cref="DataBuffer.GetHashCode"/> of <paramref name="key"/> is used
		/// as the object id.</para>
		/// <para>Return value is negative if:</para>
		/// <para><paramref name="typeId"/> isn't valid.</para>
		/// <para>-or-</para>
		/// <para>The entry specified by <paramref name="key"/> didn't exist within
		/// the store.</para>
		/// <para>-or-</para>
		/// <para>A <see cref="BdbException"/> was thrown from the underlying store
		/// (Exception is logged but not rethrown).</para>
		/// </remarks>
		public int GetEntryLength(short typeId, DataBuffer key)
		{
			return GetEntryLength(typeId, key.GetObjectId(), key);
		}
 /// <summary>
 /// Queues a new buffer to the queue of buffers
 /// </summary>
 private void QueueNewBuffer()
 {
     this.bufferToAppendTo = new DataBuffer();
     this.bufferQueue.Enqueue(this.bufferToAppendTo);
 }