System.IO.MemoryStream.GetBuffer()

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

801 Examples 7

19 Source : Protocol16SerializerTest.cs
with MIT License
from 0blu

private void ToString(Stream s)
        {
            MemoryStream ms = new MemoryStream();
            s.Position = 0;
            s.CopyTo(ms);
            string d = "";
            for (int i = 0; i < ms.Length; i++)
            {
                d += "0x" + ms.GetBuffer()[i].ToString("X2") + ", ";
            }
            Console.WriteLine(d);
        }

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

public void SplitBytes() {
            Flush();

            int pos = (int) Stream.Position;
            if (LastSplitPosition == pos)
                return;

            DataInternalBlob.Part part = Blob.PartNext();
            part.Bytes = Stream.GetBuffer();
            part.BytesIndex = LastSplitPosition;
            part.BytesCount = pos - LastSplitPosition;
            LastSplitPosition = pos;
        }

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

public static byte[] ToBytes(this Stream stream) {
            if (stream is MemoryStream ms)
                return ms.ToArray();

            long length;
            if (stream.CanSeek) {
                try {
                    length = stream.Length - stream.Position;
                } catch {
                    length = 0;
                }
            } else {
                length = 0;
            }

            if (length != 0) {
                byte[] data = new byte[length];
                using (ms = new MemoryStream(data, 0, (int) length, true, true)) {
                    stream.CopyTo(ms);
                }
                return data;
            }

            using (ms = new()) {
                stream.CopyTo(ms);
                length = ms.Position;
                ms.Seek(0, SeekOrigin.Begin);
                byte[] buffer = ms.GetBuffer();
                if (buffer.Length != length)
                    buffer = ms.ToArray();
                return buffer;
            }
        }

19 Source : IDistributedCacheExtensions.cs
with MIT License
from 2881099

public static byte[] Serialize(object value) {
			if (value == null) return null;
			using (MemoryStream ms = new MemoryStream()) {
				IFormatter formatter = new BinaryFormatter();
#pragma warning disable SYSLIB0011 // 类型或成员已过时
                formatter.Serialize(ms, value);
#pragma warning restore SYSLIB0011 // 类型或成员已过时
                return ms.GetBuffer();
			}
		}

19 Source : DataBaseInfo.cs
with MIT License
from 2881099

void Save()
        {
            using (MemoryStream ms = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(ms, this);
                File.WriteAllBytes(path, ms.GetBuffer());
            }
        }

19 Source : RdpPacket.cs
with BSD 3-Clause "New" or "Revised" License
from 3gstudent

public void InsertByte(byte value)
        {
            long position = this.Position;
            this.Seek(0L, SeekOrigin.End);
            this.WriteByte(0);
            byte[] sourceArray = this.GetBuffer();
            Array.Copy(sourceArray, (int) position, sourceArray, ((int) position) + 1, (int) ((sourceArray.Length - position) - 1L));
            this.Position = position;
            this.WriteByte(value);
        }

19 Source : Helpers.cs
with MIT License
from 404Lcc

internal static byte[] GetBuffer(MemoryStream ms)
        {
#if COREFX
            ArraySegment<byte> segment;
            if(!ms.TryGetBuffer(out segment))
            {
                throw new InvalidOperationException("Unable to obtain underlying MemoryStream buffer");
            } else if(segment.Offset != 0)
            {
                throw new InvalidOperationException("Underlying MemoryStream buffer was not zero-offset");
            } else
            {
                return segment.Array;
            }
#elif PORTABLE || PROFILE259
			return ms.ToArray();
#else
            return ms.GetBuffer();
#endif
        }

19 Source : RoslynUtil.cs
with MIT License
from 404Lcc

public static bool BuildDll(string csprojName, string path, BuildType buildType, bool isUseDefine)
        {
            bool isDebug = buildType == BuildType.Debug ? true : false;
            //项目相关所有宏
            List<string> defineList = new List<string>();
            //项目相关所有dll
            List<string> dllFilePathList = new List<string>();
            //项目本身cs文件
            List<string> csFilePathList = ReadCSPROJ(csprojName, ref defineList, ref dllFilePathList);
            List<Microsoft.Codereplacedysis.SyntaxTree> csFileList = new List<Microsoft.Codereplacedysis.SyntaxTree>();
            List<MetadataReference> dllFileList = new List<MetadataReference>();
            CSharpParseOptions parseOptions;
            //宏是否开启
            if (isUseDefine)
            {
                parseOptions = new CSharpParseOptions(LanguageVersion.Latest, preprocessorSymbols: defineList);
            }
            else
            {
                parseOptions = new CSharpParseOptions(LanguageVersion.Latest);
            }
            //增加dll文件
            foreach (string item in dllFilePathList)
            {
                PortableExecutableReference dll = MetadataReference.CreateFromFile(item);
                if (dll == null)
                {
                    continue;
                }
                dllFileList.Add(dll);
            }
            //增加cs文件
            foreach (string item in csFilePathList)
            {
                if (File.Exists(item))
                {
                    Microsoft.Codereplacedysis.SyntaxTree cs = CSharpSyntaxTree.ParseText(FileUtil.Getreplacedet(item).GetString(), parseOptions, item, Encoding.UTF8);
                    if (cs == null)
                    {
                        continue;
                    }
                    csFileList.Add(cs);
                }
            }
            //设置编译参数
            CSharpCompilationOptions compilationOptions;
            if (isDebug)
            {
                compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Debug, warningLevel: 4, allowUnsafe: true);
            }
            else
            {
                compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release, warningLevel: 4, allowUnsafe: true);
            }
            string replacedemblyName = Path.GetFileNameWithoutExtension(path);
            //开始编译
            CSharpCompilation compilation = CSharpCompilation.Create(replacedemblyName, csFileList, dllFileList, compilationOptions);
            EmitResult result;
            if (isDebug)
            {
                string pdbPath = path.Replace(".dll", ".pdb");
                EmitOptions emitOptions = new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb, pdbFilePath: pdbPath);
                using (MemoryStream dllStream = new MemoryStream())
                {
                    using (MemoryStream pdbStream = new MemoryStream())
                    {
                        result = compilation.Emit(dllStream, pdbStream, options: emitOptions);
                        FileUtil.Savereplacedet(path, dllStream.GetBuffer());
                        FileUtil.Savereplacedet(pdbPath, pdbStream.GetBuffer());
                    }
                }
            }
            else
            {
                result = compilation.Emit(path);
            }
            if (result.Success)
            {
                LogUtil.Log("编译成功");
            }
            else
            {
                List<Diagnostic> failureList = (from diagnostic in result.Diagnostics where diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error select diagnostic).ToList();
                foreach (Diagnostic item in failureList)
                {
                    LogUtil.Log(item.ToString());
                }
            }
            return result.Success;
        }

19 Source : DefatultAlipayHelper.cs
with MIT License
from 52ABP

private async Task<FTFOutput> FTFGenQRCode(AlipayTradePrecreateContentBuilder input, string asyncNotifyUrl, Action<AlipayF2FPrecreateResult> loopQueryAction, FTFConfig fTFConfig)
        {
            // 参数检测
            var isAsyncNotify = !asyncNotifyUrl.IsNullOrWhiteSpace();
            if (!isAsyncNotify && loopQueryAction == null)
            {
                throw new NullReferenceException("轮询模式下 loopQueryAction 不能为空!");
            }
            // 收款账号检测,如果为空则默认填入全局配置的Uid
            if (input.seller_id.IsNullOrWhiteSpace())
            {
                input.seller_id = this._alipayService.Options.Uid;
            }



            Bitmap bitmap = null;
            MemoryStream memoryStream = null;
            var message = string.Empty;

            //推荐使用轮询撤销机制,不推荐使用异步通知,避免单边账问题发生。
            AlipayF2FPrecreateResult precreateResult = null;
            // 异步通知
            if (isAsyncNotify)
            {
                precreateResult = await _alipayF2FService.TradePrecreateAsync(input, asyncNotifyUrl);

            }// 同步轮询
            else
            {
                precreateResult = await _alipayF2FService.TradePrecreateAsync(input);
            }

            switch (precreateResult.Status)
            {
                case F2FResultEnum.SUCCESS:
                    // 将链接用二维码工具生成二维码打印出来,顾客可以用支付宝钱包扫码支付。
                    bitmap = RenderQrCode(precreateResult.response.QrCode);
                    // 同步轮询模式,触发轮询回调函数
                    if (!isAsyncNotify)
                    {
                        loopQueryAction.Invoke(precreateResult);
                    }
                    break;
                case F2FResultEnum.FAILED:
                    message = $"生成二维码失败: {precreateResult.response.Body}";
                    break;

                case F2FResultEnum.UNKNOWN:
                    message = "生成二维码失败:" + (precreateResult.response == null ? "配置或网络异常,请检查后重试" : "系统异常,请更新外部订单后重新发起请求");
                    break;
            }

            // 如果位图为空,则生成错误提示二维码
            if (bitmap == null)
            {
                bitmap = new Bitmap(fTFConfig == null ? this._fTFConfig?.QRCodeGenErrorImageFullPath : fTFConfig.QRCodeGenErrorImageFullPath);
            }

            // 转换成字节数组
            memoryStream = new MemoryStream();
            bitmap.Save(memoryStream, ImageFormat.Png);
            var imgBuffer = memoryStream.GetBuffer();

            // 释放资源
            memoryStream.Dispose();
            bitmap.Dispose();

            return new FTFOutput()
            {
                QRCodeImageBuffer = imgBuffer,
                IsSuccess = precreateResult.Status == F2FResultEnum.SUCCESS,
                Message = message
            };
        }

19 Source : AppenderBaseTests.cs
with MIT License
from Abc-Arbitrage

public override string ToString()
                => _encoding.GetString(_stream.GetBuffer(), 0, (int)_stream.Length);

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

public uint CalculateHash32()
        {
            var bytes = headerBytes.GetBuffer();

            return Hash32.Calculate(bytes, (int)headerBytes.Length);
        }

19 Source : AudioFile.cs
with MIT License
from adlez27

public void Read ()
        {
            if (File.Exists(FullName) && !recorded)
            {
                byte[] rawBytes = File.ReadAllBytes(FullName);
                data = new ArraySegment<byte>(rawBytes, 46, rawBytes.Length - 46).ToList();
                stream = Breplaced.CreateStream(rawBytes, 0, rawBytes.Length, BreplacedFlags.Mono);
            }
            else if (recorded)
            {
                byte[] reRead;
                var format = new WaveFormat(44100, 16, 1);
                using (MemoryStream ms = new MemoryStream())
                using (WaveFileWriter wfw = new WaveFileWriter(ms, format))
                {
                    wfw.Write(Data, Data.Length * 2);
                    reRead = ms.GetBuffer();
                }
                stream = Breplaced.CreateStream(reRead, 0, reRead.Length, BreplacedFlags.Mono);
            }
        }

19 Source : ExcelExporter.cs
with Mozilla Public License 2.0
from agebullhu

public byte[] ExportExcel(string name,string path)
        {
            _book = new XSSFWorkbook(path);
            var sheet = _book.CreateSheet(name);
            ExportExcel(sheet);
            using (var mem = new MemoryStream())
            {
                _book.Write(mem);
                return mem.GetBuffer();
            }
        }

19 Source : ExcelExporter.cs
with Mozilla Public License 2.0
from agebullhu

public byte[] ExportExcel(Expression<Func<TData, bool>> lambda, string name = "Sheet1")
        {
            _book = new XSSFWorkbook();
            var sheet = _book.CreateSheet(name);
            ExportExcel(sheet, lambda);
            using (var mem = new MemoryStream())
            {
                _book.Write(mem);
                return mem.GetBuffer();
            }
        }

19 Source : ExcelExporter.cs
with Mozilla Public License 2.0
from agebullhu

public byte[] ExportExcel(string name,string path)
        {
            Book = new XSSFWorkbook(path);
            var sheet = Book.CreateSheet(name);
            ExportExcel(sheet);
            using (var mem = new MemoryStream())
            {
                Book.Write(mem);
                return mem.GetBuffer();
            }
        }

19 Source : ExcelExporter.cs
with Mozilla Public License 2.0
from agebullhu

public byte[] ExportExcel(Expression<Func<TData, bool>> lambda, string name = "Sheet1")
        {
            Book = new XSSFWorkbook();
            var sheet = Book.CreateSheet(name);
            ExportExcel(sheet, lambda);
            using (var mem = new MemoryStream())
            {
                Book.Write(mem);
                return mem.GetBuffer();
            }
        }

19 Source : IOHelper.cs
with Mozilla Public License 2.0
from agebullhu

public static T XMLDeSerializer<T>(string args)
        {
            if (string.IsNullOrWhiteSpace(args) || args[0] != '<')
            {
                return default(T);
            }
            byte[] buffers;
            long len;
            using (var ms = new MemoryStream())
            {
                var sw = new StreamWriter(ms);
                sw.Write(args);
                sw.Flush();
                len = ms.Position;
                buffers = ms.GetBuffer();
            }
            using (var reader = XmlDictionaryReader.CreateTextReader(buffers, 0, (int)len, new XmlDictionaryReaderQuotas()))
            {
                var ds = new DataContractSerializer(typeof(T));
                var re = (T)ds.ReadObject(reader, false);
                return re;
            }
        }

19 Source : JsonFsCheck.cs
with BSD 3-Clause "New" or "Revised" License
from agocke

[Fact]
        public async Task CheckPrimitiveEquivalentsAsync()
        {
            // Generates test cases, each of which has multiple generated clreplacedes
            var testCases = Gen.Sample(4, 100, Gen.Sized(TestTypeGenerators.GenTypeDef));
            var wrappers = new MemberDeclarationSyntax[testCases.Length];
            int wrapperIndex = 0;
            foreach (var type in testCases)
            {
                var clreplacedDecls = ToMembers((TestTypeDef)type);
                // Wrap the clreplacedes used by each test case in an outer clreplaced to
                // prevent name collision
                wrappers[wrapperIndex] = ClreplacedDeclaration(
                    attributeLists: default,
                    modifiers: TokenList(Token(SyntaxKind.PartialKeyword)),
                    identifier: Identifier("TestCase" + wrapperIndex),
                    typeParameterList: null,
                    baseList: null,
                    constraintClauses: default,
                    members: List(clreplacedDecls)).NormalizeWhitespace();
                wrapperIndex++;
            }

            var serializeStatements = new List<string>();
            serializeStatements.Add("var results = new List<(string, string)>();");
            serializeStatements.Add("var options = new System.Text.Json.JsonSerializerOptions() { IncludeFields = true };");
            for (int i = 0; i < wrappers.Length; i++)
            {
                var localName = "t" + i;
                serializeStatements.Add($"var {localName} = new TestCase{i}.Clreplaced0();");
                serializeStatements.Add($@"results.Add(
(Serde.Json.JsonSerializer.Serialize({localName}),
 System.Text.Json.JsonSerializer.Serialize({localName}, options)));");
            }
            serializeStatements.Add("return results;");

            var body = string.Join(Environment.NewLine, serializeStatements);
            var mainTree = SyntaxFactory.ParseSyntaxTree($@"
using System;
using System.Collections.Generic;

public static clreplaced Runner
{{
    public static List<(string Serde, string SystemText)> Run()
    {{
        {body}
    }}
}}");

            var allTypes = SyntaxTree(CompilationUnit(
                externs: default,
                usings: List(new [] {
                    UsingDirective(IdentifierName("System")),
                    UsingDirective(QualifiedName(
                        QualifiedName(IdentifierName("System"), IdentifierName("Collections")),
                        IdentifierName("Generic"))),
                    UsingDirective(IdentifierName("Serde"))
                    }),
                attributeLists: default,
                List(wrappers)).NormalizeWhitespace());

            var comp = CSharpCompilation.Create(
               Guid.NewGuid().ToString("N"),
               syntaxTrees: new[] { mainTree, allTypes },
               references: (await Config.LatestTfRefs.ResolveAsync(null, default))
                    .Append(MetadataReference.CreateFromFile(typeof(Serde.ISerialize).replacedembly.Location)),
               new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            var driver = CSharpGeneratorDriver.Create(new Generator());
            driver.RunGeneratorsAndUpdateCompilation(
                comp,
                out var newComp,
                out var diagnostics);

            replacedert.Empty(diagnostics);

            var peStream = new MemoryStream();
            var result = newComp.Emit(peStream,
                pdbStream: null,
                xmlDoreplacedentationStream: null,
                win32Resources: null,
                manifestResources: null,
                options: s_emitOptions,
                cancellationToken: default);

            replacedert.True(result.Success,
                string.Join(Environment.NewLine, result.Diagnostics.Select(d => d.GetMessage())));
            var loaded = replacedembly.Load(peStream.GetBuffer());
            var testResults = (List<(string Serde, string SystemText)>)loaded.GetType("Runner")!.GetMethod("Run")!.Invoke(null, null)!;
            foreach (var (serde, systemText) in testResults)
            {
                replacedert.Equal(systemText, serde);
            }
        }

19 Source : IconFile.cs
with MIT License
from ahopper

static public void SaveToICO(Drawing drawing, List<int> sizes, string filename)
        {
            int headerLen = 6 + sizes.Count * 16;
            using (var icoStream = new MemoryStream())
            {
                //write ICONDIR
                icoStream.WriteByte(0);
                icoStream.WriteByte(0);
                icoStream.WriteByte(1);
                icoStream.WriteByte(0);
                icoStream.WriteByte((byte)sizes.Count);
                icoStream.WriteByte(0);
                
                icoStream.Position = headerLen;
                
                for (int i =0; i< sizes.Count; i++)
                {
                    var start = icoStream.Position;
                    SaveDrawing(drawing, sizes[i], icoStream);
                    var end = icoStream.Position;
                    int pngLen = (int)(end - start);
               
                    icoStream.Position = 6 + i * 16;
                    icoStream.WriteByte((byte)sizes[i]);
                    icoStream.WriteByte((byte)sizes[i]);
                    icoStream.WriteByte(0);
                    icoStream.WriteByte(0);
                    icoStream.WriteByte(0);
                    icoStream.WriteByte(0);
                    icoStream.WriteByte(0);
                    icoStream.WriteByte(32);

                    icoStream.WriteByte((byte)(pngLen & 0xff));
                    icoStream.WriteByte((byte)((pngLen >> 8) & 0xff)); 
                    icoStream.WriteByte((byte)((pngLen >> 16) & 0xff));
                    icoStream.WriteByte((byte)(pngLen >> 24));
                   
                    icoStream.WriteByte((byte)(start & 0xff)); 
                    icoStream.WriteByte((byte)((start >> 8) & 0xff));
                    icoStream.WriteByte((byte)((start >> 16) & 0xff));
                    icoStream.WriteByte((byte)(start >> 24));
           
                    icoStream.Position=end;
                }
                using(var icoFile=File.Create(filename))
                {
                    icoFile.Write(icoStream.GetBuffer(), 0, (int)icoStream.Position);
                }
            }
        }

19 Source : IconFile.cs
with MIT License
from ahopper

static public void SaveToICNS(Drawing drawing, List<int> sizes, string filename)
        {
            int headerLen = 8;
            int fileLen = headerLen;
            using (var icoStream = new MemoryStream())
            {
                icoStream.WriteByte(0x69);
                icoStream.WriteByte(0x63);
                icoStream.WriteByte(0x6e);
                icoStream.WriteByte(0x73);
                
                icoStream.Position = headerLen;

                for (int i = 0; i < sizes.Count; i++)
                {
                    var start = icoStream.Position;
                    icoStream.Position += 8;
                    SaveDrawing(drawing, sizes[i], icoStream);
                    var end = icoStream.Position;
                    int pngLen = (int)(end - start);
                    fileLen += pngLen;

                    icoStream.Position = start;
                    string iconType;
                    switch(sizes[i])
                    {
                        case 16: iconType = "icp4"; break;
                        case 32: iconType = "icp5"; break;
                        case 64: iconType = "icp6"; break;
                        case 128: iconType = "ic07"; break;
                        case 256: iconType = "ic08"; break;
                        case 512: iconType = "ic09"; break;
                        default: throw new Exception($"Unsupported icns size {sizes[i]}");
                    }
                    icoStream.Write(ASCIIEncoding.ASCII.GetBytes(iconType));

                    icoStream.WriteByte((byte)(pngLen >> 24));
                    icoStream.WriteByte((byte)((pngLen >> 16) & 0xff));
                    icoStream.WriteByte((byte)((pngLen >> 8) & 0xff));
                    icoStream.WriteByte((byte)(pngLen & 0xff));
                    
                    icoStream.Position = end;
                }
                icoStream.Position = 4;

                icoStream.WriteByte((byte)(fileLen >> 24));
                icoStream.WriteByte((byte)((fileLen >> 16) & 0xff));
                icoStream.WriteByte((byte)((fileLen >> 8) & 0xff));
                icoStream.WriteByte((byte)(fileLen & 0xff));
                
                using (var icoFile = File.Create(filename))
                {
                    icoFile.Write(icoStream.GetBuffer(), 0, fileLen);
                }
            }
        }

19 Source : Crypto.cs
with BSD 3-Clause "New" or "Revised" License
from airzero24

private static void ExportPublicKey(RSACryptoServiceProvider csp, TextWriter outputStream)
        {
            var parameters = csp.ExportParameters(false);
            using (var stream = new MemoryStream())
            {
                var writer = new BinaryWriter(stream);
                writer.Write((byte)0x30); // SEQUENCE
                using (var innerStream = new MemoryStream())
                {
                    var innerWriter = new BinaryWriter(innerStream);
                    innerWriter.Write((byte)0x30); // SEQUENCE
                    EncodeLength(innerWriter, 13);
                    innerWriter.Write((byte)0x06); // OBJECT IDENTIFIER
                    var rsaEncryptionOid = new byte[] { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01 };
                    EncodeLength(innerWriter, rsaEncryptionOid.Length);
                    innerWriter.Write(rsaEncryptionOid);
                    innerWriter.Write((byte)0x05); // NULL
                    EncodeLength(innerWriter, 0);
                    innerWriter.Write((byte)0x03); // BIT STRING
                    using (var bitStringStream = new MemoryStream())
                    {
                        var bitStringWriter = new BinaryWriter(bitStringStream);
                        bitStringWriter.Write((byte)0x00); // # of unused bits
                        bitStringWriter.Write((byte)0x30); // SEQUENCE
                        using (var paramsStream = new MemoryStream())
                        {
                            var paramsWriter = new BinaryWriter(paramsStream);
                            EncodeIntegerBigEndian(paramsWriter, parameters.Modulus); // Modulus
                            EncodeIntegerBigEndian(paramsWriter, parameters.Exponent); // Exponent
                            var paramsLength = (int)paramsStream.Length;
                            EncodeLength(bitStringWriter, paramsLength);
                            bitStringWriter.Write(paramsStream.GetBuffer(), 0, paramsLength);
                        }
                        var bitStringLength = (int)bitStringStream.Length;
                        EncodeLength(innerWriter, bitStringLength);
                        innerWriter.Write(bitStringStream.GetBuffer(), 0, bitStringLength);
                    }
                    var length = (int)innerStream.Length;
                    EncodeLength(writer, length);
                    writer.Write(innerStream.GetBuffer(), 0, length);
                }

                var base64 = Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length).ToCharArray();
                outputStream.WriteLine("-----BEGIN PUBLIC KEY-----");
                for (var i = 0; i < base64.Length; i += 64)
                {
                    outputStream.WriteLine(base64, i, Math.Min(64, base64.Length - i));
                }
                outputStream.WriteLine("-----END PUBLIC KEY-----");
            }
        }

19 Source : Map.cs
with MIT License
from AliFlux

public void AddImage(string id, MemoryStream stream)
        {
            AddImage(id, Convert.ToBase64String(stream.GetBuffer()));
        }

19 Source : DefaultBinaryFormatterSerializer.cs
with MIT License
from AlphaYu

public ArraySegment<byte> SerializeObject(object obj)
        {
            using (var ms = new MemoryStream())
            {
                new BinaryFormatter().Serialize(ms, obj);
                return new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length);
            }
        }

19 Source : MinisignPublicKeyDictionary.cs
with GNU General Public License v3.0
from Amebis

public void WriteXml(XmlWriter writer)
        {
            foreach (var el in this)
            {
                writer.WriteStartElement("PublicKey");
                using (var s = new MemoryStream(42))
                {
                    using (var w = new BinaryWriter(s))
                    {
                        w.Write('E');
                        w.Write('d');
                        w.Write(el.Key);
                        w.Write(el.Value);
                    }
                    writer.WriteBase64(s.GetBuffer(), 0, (int)s.Length);
                }
                writer.WriteEndElement();
            }
        }

19 Source : HttpConnection.cs
with MIT License
from andruzzzhka

public RequestStream GetRequestStream (long contentLength, bool chunked)
    {
      lock (_sync) {
        if (_socket == null)
          return null;

        if (_inputStream != null)
          return _inputStream;

        var buff = _requestBuffer.GetBuffer ();
        var len = (int) _requestBuffer.Length;
        var cnt = len - _position;
        disposeRequestBuffer ();

        _inputStream = chunked
                       ? new ChunkedRequestStream (
                           _stream, buff, _position, cnt, _context
                         )
                       : new RequestStream (
                           _stream, buff, _position, cnt, contentLength
                         );

        return _inputStream;
      }
    }

19 Source : ResponseStream.cs
with MIT License
from andruzzzhka

private void flushBody (bool closing)
    {
      using (_body) {
        var len = _body.Length;
        if (len > Int32.MaxValue) {
          _body.Position = 0;
          var buffLen = 1024;
          var buff = new byte[buffLen];
          var nread = 0;
          while ((nread = _body.Read (buff, 0, buffLen)) > 0)
            _writeBody (buff, 0, nread);
        }
        else if (len > 0) {
          _writeBody (_body.GetBuffer (), 0, (int) len);
        }
      }

      _body = !closing ? new MemoryStream () : null;
    }

19 Source : ResponseStream.cs
with MIT License
from andruzzzhka

private bool flushHeaders (bool closing)
    {
      using (var buff = new MemoryStream ()) {
        var headers = _response.WriteHeadersTo (buff);
        var start = buff.Position;
        var len = buff.Length - start;
        if (len > 32768)
          return false;

        if (!_response.SendChunked && _response.ContentLength64 != _body.Length)
          return false;

        _write (buff.GetBuffer (), (int) start, (int) len);
        _response.CloseConnection = headers["Connection"] == "close";
        _response.HeadersSent = true;
      }

      return true;
    }

19 Source : HttpConnection.cs
with MIT License
from andruzzzhka

private static void onRead (IAsyncResult asyncResult)
    {
      var conn = (HttpConnection) asyncResult.AsyncState;
      if (conn._socket == null)
        return;

      lock (conn._sync) {
        if (conn._socket == null)
          return;

        var nread = -1;
        var len = 0;
        try {
          var current = conn._reuses;
          if (!conn._timeoutCanceled[current]) {
            conn._timer.Change (Timeout.Infinite, Timeout.Infinite);
            conn._timeoutCanceled[current] = true;
          }

          nread = conn._stream.EndRead (asyncResult);
          conn._requestBuffer.Write (conn._buffer, 0, nread);
          len = (int) conn._requestBuffer.Length;
        }
        catch (Exception ex) {
          if (conn._requestBuffer != null && conn._requestBuffer.Length > 0) {
            conn.SendError (ex.Message, 400);
            return;
          }

          conn.close ();
          return;
        }

        if (nread <= 0) {
          conn.close ();
          return;
        }

        if (conn.processInput (conn._requestBuffer.GetBuffer (), len)) {
          if (!conn._context.HasError)
            conn._context.Request.FinishInitialization ();

          if (conn._context.HasError) {
            conn.SendError ();
            return;
          }

          HttpListener lsnr;
          if (!conn._listener.TrySearchHttpListener (conn._context.Request.Url, out lsnr)) {
            conn.SendError (null, 404);
            return;
          }

          if (conn._lastListener != lsnr) {
            conn.removeConnection ();
            if (!lsnr.AddConnection (conn)) {
              conn.close ();
              return;
            }

            conn._lastListener = lsnr;
          }

          conn._context.Listener = lsnr;
          if (!conn._context.Authenticate ())
            return;

          if (conn._context.Register ())
            conn._contextRegistered = true;

          return;
        }

        conn._stream.BeginRead (conn._buffer, 0, _bufferLength, onRead, conn);
      }
    }

19 Source : ActorHelper.cs
with MIT License
from AnotherEnd15

public static object ToActorMessage(this MemoryStream memoryStream)
        {
            ushort opcode = BitConverter.ToUInt16(memoryStream.GetBuffer(), 8);
            Type type = OpcodeTypeComponent.Instance.GetType(opcode);

            if (opcode < MessageSerializeHelper.PbMaxOpcode)
            {
                return ProtobufHelper.FromBytes(type, memoryStream.GetBuffer(), 10, (int)memoryStream.Length - 10);
            }
            
            if (opcode >= MessageSerializeHelper.JsonMinOpcode)
            {
                return JsonHelper.FromJson(type, memoryStream.GetBuffer().ToStr(10, (int)(memoryStream.Length - 10)));
            }
            return MongoHelper.FromBson(type, memoryStream.GetBuffer(), 10, (int)memoryStream.Length - 10);
        }

19 Source : InnerMessageDispatcher.cs
with MIT License
from AnotherEnd15

public void Dispatch(Session session, MemoryStream memoryStream)
        {
            ushort opcode = 0;
            try
            {
                long actorId = BitConverter.ToInt64(memoryStream.GetBuffer(), Packet.ActorIdIndex);
                opcode = BitConverter.ToUInt16(memoryStream.GetBuffer(), Packet.OpcodeIndex);
                Type type = null;
                object message = null;
#if SERVER   

                // 内网收到外网消息,有可能是gateUnit消息,还有可能是gate广播消息
                if (OpcodeTypeComponent.Instance.IsOutrActorMessage(opcode))
                {
                    InstanceIdStruct instanceIdStruct = new InstanceIdStruct(actorId);
                    instanceIdStruct.Process = Game.Options.Process;
                    long realActorId = instanceIdStruct.ToLong();
                    
                    
                    Enreplacedy enreplacedy = Game.EventSystem.Get(realActorId);
                    if (enreplacedy == null)
                    {
                        type = OpcodeTypeComponent.Instance.GetType(opcode);
                        message = MessageSerializeHelper.DeserializeFrom(opcode, type, memoryStream);
                        Log.Error($"not found actor: {session.DomainScene().Name}  {opcode} {realActorId} {message}");
                        return;
                    }
                    
                    if (enreplacedy is Session gateSession)
                    {
                        // 发送给客户端
                        memoryStream.Seek(Packet.OpcodeIndex, SeekOrigin.Begin);
                        gateSession.Send(0, memoryStream);
                        return;
                    }
                }
#endif
                        
                        
                type = OpcodeTypeComponent.Instance.GetType(opcode);
                message = MessageSerializeHelper.DeserializeFrom(opcode, type, memoryStream);

                if (message is IResponse iResponse && !(message is IActorResponse))
                {
                    session.OnRead(opcode, iResponse);
                    return;
                }

                OpcodeHelper.LogMsg(session.DomainZone(), opcode, message);

                // 收到actor消息,放入actor队列
                switch (message)
                {
                    case IActorRequest iActorRequest:
                    {
                        InstanceIdStruct instanceIdStruct = new InstanceIdStruct(actorId);
                        int fromProcess = instanceIdStruct.Process;
                        instanceIdStruct.Process = Game.Options.Process;
                        long realActorId = instanceIdStruct.ToLong();
                        
                        void Reply(IActorResponse response)
                        {
                            Session replySession = NetInnerComponent.Instance.Get(fromProcess);
                            // 发回真实的actorId 做查问题使用
                            replySession.Send(realActorId, response);
                        }

                        InnerMessageDispatcherHelper.HandleIActorRequest(opcode, realActorId, iActorRequest, Reply);
                        return;
                    }
                    case IActorResponse iActorResponse:
                    {
                        InstanceIdStruct instanceIdStruct = new InstanceIdStruct(actorId);
                        instanceIdStruct.Process = Game.Options.Process;
                        long realActorId = instanceIdStruct.ToLong();
                        InnerMessageDispatcherHelper.HandleIActorResponse(opcode, realActorId, iActorResponse);
                        return;
                    }
                    case IActorMessage iactorMessage:
                    {
                        InstanceIdStruct instanceIdStruct = new InstanceIdStruct(actorId);
                        instanceIdStruct.Process = Game.Options.Process;
                        long realActorId = instanceIdStruct.ToLong();
                        InnerMessageDispatcherHelper.HandleIActorMessage(opcode, realActorId, iactorMessage);
                        return;
                    }
                    default:
                    {
                        MessageDispatcherComponent.Instance.Handle(session, opcode, message);
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error($"InnerMessageDispatcher error: {opcode}\n{e}");
            }
        }

19 Source : OuterMessageDispatcher.cs
with MIT License
from AnotherEnd15

public void Dispatch(Session session, MemoryStream memoryStream)
		{
			ushort opcode = BitConverter.ToUInt16(memoryStream.GetBuffer(), Packet.KcpOpcodeIndex);
			Type type = OpcodeTypeComponent.Instance.GetType(opcode);
			object message = MessageSerializeHelper.DeserializeFrom(opcode, type, memoryStream);

			if (message is IResponse response)
			{
				session.OnRead(opcode, response);
				return;
			}

			OpcodeHelper.LogMsg(session.DomainZone(), opcode, message);
			
			DispatchAsync(session, opcode, message).Coroutine();
		}

19 Source : MessageSerializeHelper.cs
with MIT License
from AnotherEnd15

public static object DeserializeFrom(ushort opcode, Type type, MemoryStream memoryStream)
        {
            if (opcode < PbMaxOpcode)
            {
                return ProtobufHelper.FromStream(type, memoryStream);
            }
            
            if (opcode >= JsonMinOpcode)
            {
                return JsonHelper.FromJson(type, memoryStream.GetBuffer().ToStr((int)memoryStream.Position, (int)(memoryStream.Length - memoryStream.Position)));
            }
#if NOT_CLIENT
            return MongoHelper.FromStream(type, memoryStream);
#else
            throw new Exception($"client no message: {opcode}");
#endif
        }

19 Source : MessageSerializeHelper.cs
with MIT License
from AnotherEnd15

public static (ushort, MemoryStream) MessageToStream(object message, int count = 0)
        {
            MemoryStream stream = GetStream(Packet.OpcodeLength + count);

            ushort opcode = OpcodeTypeComponent.Instance.GetOpcode(message.GetType());
            
            stream.Seek(Packet.OpcodeLength, SeekOrigin.Begin);
            stream.SetLength(Packet.OpcodeLength);
            
            stream.GetBuffer().WriteTo(0, opcode);
            
            MessageSerializeHelper.SerializeTo(opcode, message, stream);
            
            stream.Seek(0, SeekOrigin.Begin);
            return (opcode, stream);
        }

19 Source : MessageSerializeHelper.cs
with MIT License
from AnotherEnd15

public static (ushort, MemoryStream) MessageToStream(long actorId, object message, int count = 0)
        {
            int actorSize = sizeof (long);
            MemoryStream stream = GetStream(actorSize + Packet.OpcodeLength + count);

            ushort opcode = OpcodeTypeComponent.Instance.GetOpcode(message.GetType());
            
            stream.Seek(actorSize + Packet.OpcodeLength, SeekOrigin.Begin);
            stream.SetLength(actorSize + Packet.OpcodeLength);

            // 写入actorId
            stream.GetBuffer().WriteTo(0, actorId);
            stream.GetBuffer().WriteTo(actorSize, opcode);
            
            MessageSerializeHelper.SerializeTo(opcode, message, stream);
            
            stream.Seek(0, SeekOrigin.Begin);
            return (opcode, stream);
        }

19 Source : KChannel.cs
with MIT License
from AnotherEnd15

public void HandleRecv(byte[] date, int offset, int length)
		{
			if (this.IsDisposed)
			{
				return;
			}

			this.IsConnected = true;
			
			Kcp.KcpInput(this.kcp, date, offset, length);
			this.Service.AddToUpdateNextTime(0, this.Id);

			while (true)
			{
				if (this.IsDisposed)
				{
					break;
				}
				int n = Kcp.KcpPeeksize(this.kcp);
				if (n < 0)
				{
					break;
				}
				if (n == 0)
				{
					this.OnError((int)SocketError.NetworkReset);
					break;
				}

				MemoryStream ms = MessageSerializeHelper.GetStream(n);
				
				ms.SetLength(n);
				ms.Seek(0, SeekOrigin.Begin);
				byte[] buffer = ms.GetBuffer();
				int count = Kcp.KcpRecv(this.kcp, buffer, n);
				if (n != count)
				{
					break;
				}

				switch (this.Service.ServiceType)
				{
					case ServiceType.Inner:
						ms.Seek(Packet.ActorIdLength + Packet.OpcodeLength, SeekOrigin.Begin);
						break;
					case ServiceType.Outer:
						ms.Seek(Packet.OpcodeLength, SeekOrigin.Begin);
						break;
				}
				this.lastRecvTime = this.Service.TimeNow;
				this.OnRead(ms);
			}
		}

19 Source : KChannel.cs
with MIT License
from AnotherEnd15

private void KcpSend(KcpWaitPacket kcpWaitPacket)
		{
			if (this.IsDisposed)
			{
				return;
			}

			MemoryStream memoryStream = kcpWaitPacket.MemoryStream;
			if (this.Service.ServiceType == ServiceType.Inner)
			{
				memoryStream.GetBuffer().WriteTo(0, kcpWaitPacket.ActorId);
			}

			int count = (int) (memoryStream.Length - memoryStream.Position);
			Kcp.KcpSend(this.kcp, memoryStream.GetBuffer(), (int)memoryStream.Position, count);
			this.Service.AddToUpdateNextTime(0, this.Id);
		}

19 Source : TChannel.cs
with MIT License
from AnotherEnd15

public void Send(long actorId, MemoryStream stream)
		{
			if (this.IsDisposed)
			{
				throw new Exception("TChannel已经被Dispose, 不能发送消息");
			}

			switch (this.Service.ServiceType)
			{
				case ServiceType.Inner:
				{
					int messageSize = (int) (stream.Length - stream.Position);
					if (messageSize > ushort.MaxValue * 16)
					{
						throw new Exception($"send packet too large: {stream.Length} {stream.Position}");
					}

					this.sendCache.WriteTo(0, messageSize);
					this.sendBuffer.Write(this.sendCache, 0, PacketParser.InnerPacketSizeLength);

					// actorId
					stream.GetBuffer().WriteTo(0, actorId);
					this.sendBuffer.Write(stream.GetBuffer(), (int)stream.Position, (int)(stream.Length - stream.Position));
					break;
				}
				case ServiceType.Outer:
				{
					ushort messageSize = (ushort) (stream.Length - stream.Position);

					this.sendCache.WriteTo(0, messageSize);
					this.sendBuffer.Write(this.sendCache, 0, PacketParser.OuterPacketSizeLength);
					
					this.sendBuffer.Write(stream.GetBuffer(), (int)stream.Position, (int)(stream.Length - stream.Position));
					break;
				}
			}
			

			if (!this.isSending)
			{
				//this.StartSend();
				this.Service.NeedStartSend.Add(this.Id);
			}
		}

19 Source : OuterMessageDispatcher.cs
with MIT License
from AnotherEnd15

public void Dispatch(Session session, MemoryStream memoryStream)
        {
            ushort opcode = BitConverter.ToUInt16(memoryStream.GetBuffer(), Packet.KcpOpcodeIndex);
            Type type = OpcodeTypeComponent.Instance.GetType(opcode);
            object message = MessageSerializeHelper.DeserializeFrom(opcode, type, memoryStream);

            if (TimeHelper.ClientFrameTime() - this.lastMessageTime > 3000)
            {
                Log.Info($"可能导致卡死的消息: {this.LastMessage}");
            }

            this.lastMessageTime = TimeHelper.ClientFrameTime();
            this.LastMessage = message;
            
            if (message is IResponse response)
            {
                session.OnRead(opcode, response);
                return;
            }

            OpcodeHelper.LogMsg(session.DomainZone(), opcode, message);
            // 普通消息或者是Rpc请求消息
            MessageDispatcherComponent.Instance.Handle(session, opcode, message);
        }

19 Source : Helpers.cs
with MIT License
from AnotherEnd15

internal static byte[] GetBuffer(MemoryStream ms)
        {
#if COREFX
            if(!ms.TryGetBuffer(out var segment))
            {
                throw new InvalidOperationException("Unable to obtain underlying MemoryStream buffer");
            } else if(segment.Offset != 0)
            {
                throw new InvalidOperationException("Underlying MemoryStream buffer was not zero-offset");
            } else
            {
                return segment.Array;
            }
#elif PORTABLE || PROFILE259
            return ms.ToArray();
#else
            return ms.GetBuffer();
#endif
        }

19 Source : ColladaLoader.Classes.cs
with MIT License
from ansel86castro

public unsafe void AddNormal(byte* vertexData, int index)
        {
            var buffer = _vertexBufferData.GetBuffer();
            using ArrayPtr arrayPtr = new ArrayPtr(buffer);

            var source = new BufferView<Vector3>(vertexData, _vd, VertexSemantic.Normal, 0, 1);                       
            var dest = new BufferView<Vector3>(arrayPtr.Pointer, _vd, VertexSemantic.Normal, 0, _count);

            dest[index] += source[0];
            dest[index] = Vector3.Normalize(dest[index]);

        }

19 Source : EndianBinaryWriterTest.cs
with Apache License 2.0
from apache

void writeString16TestHelper(char[] input, byte[] expect)
        {
            MemoryStream stream = new MemoryStream();
            EndianBinaryWriter writer = new EndianBinaryWriter(stream);

            String str = new String(input);

            writer.WriteString16(str);

            byte[] result = stream.GetBuffer();

            replacedert.AreEqual(result[0], 0x00);
            replacedert.AreEqual(result[1], expect.Length);

            for (int i = 4; i < expect.Length; ++i)
            {
                replacedert.AreEqual(result[i], expect[i - 2]);
            }
        }

19 Source : EndianBinaryWriterTest.cs
with Apache License 2.0
from apache

void writeString32TestHelper(char[] input, byte[] expect)
        {
            MemoryStream stream = new MemoryStream();
            EndianBinaryWriter writer = new EndianBinaryWriter(stream);

            String str = new String(input);

            writer.WriteString32(str);

            byte[] result = stream.GetBuffer();

            replacedert.AreEqual(result[0], 0x00);
            replacedert.AreEqual(result[1], 0x00);
            replacedert.AreEqual(result[2], 0x00);
            replacedert.AreEqual(result[3], expect.Length);

            for (int i = 4; i < expect.Length; ++i)
            {
                replacedert.AreEqual(result[i], expect[i - 4]);
            }
        }

19 Source : AgeScript.cs
with MIT License
from arcusmaximus

public void WritePatched(IEnumerable<ScriptString> strings, ScriptLocation location)
        {
            using (Stream inputStream = new MemoryStream(_scenario))
            using (Stream outputStream = File.Open(location.ToFilePath(), FileMode.Create, FileAccess.ReadWrite))
            {
                BinaryPatcher patcher = new BinaryPatcher(inputStream, outputStream, AgeDisreplacedembler.AddressToOffset, AgeDisreplacedembler.OffsetToAddress);
                patcher.CopyUpTo(_stringTableOffset);

                MemoryStream stringsStream = new MemoryStream();
                using (IEnumerator<ScriptString> stringEnumerator = strings.GetEnumerator())
                {
                    for (int i = 0; i < _textRanges.Count; i++)
                    {
                        string text;
                        if (IsEmptyString(_textRanges[i]))
                            text = string.Empty;
                        else if (!stringEnumerator.MoveNext())
                            throw new InvalidDataException("Too few strings in translation file");
                        else
                            text = stringEnumerator.Current.Text;

                        patcher.PatchInt32(_textAddressOffsets[i], AgeDisreplacedembler.OffsetToAddress(_stringTableOffset + (int)stringsStream.Length));
                        WriteString(stringsStream, text);
                    }

                    if (stringEnumerator.MoveNext())
                        throw new InvalidDataException("Too many strings in translation file");
                }

                patcher.ReplaceBytes(_arrayTableOffset - _stringTableOffset, stringsStream.GetBuffer(), 0, (int)stringsStream.Length);

                patcher.CopyUpTo(_scenario.Length);

                patcher.PatchAddress(0x28);
                patcher.PatchAddress(0x30);
                patcher.PatchAddress(0x38);
                foreach (int offset in _arrayAddressOffsets)
                {
                    patcher.PatchAddress(offset);
                }
            }
        }

19 Source : CbgEncoder.cs
with MIT License
from arcusmaximus

private static void WriteHuffmanWeights(HuffmanTree tree, BinaryWriter writer)
        {
            MemoryStream plainStream = new MemoryStream();
            BinaryWriter plainWriter = new BinaryWriter(plainStream);
            for (int i = 0; i < 256; i++)
            {
                plainWriter.WriteVariableLength(tree.Codes[i].Weight);
            }

            byte[] plainWeights = plainStream.GetBuffer();
            KeyGenerator key = new KeyGenerator();
            byte sum = 0;
            byte xor = 0;
            for (int i = 0; i < plainStream.Length; i++)
            {
                byte b = plainWeights[i];
                sum += b;
                xor ^= b;
                writer.Write((byte)(b + key.Next()));
            }

            writer.BaseStream.Position = 0x28;
            writer.Write((int)plainStream.Length);
            writer.Write(sum);
            writer.Write(xor);

            writer.BaseStream.Position = writer.BaseStream.Length;
        }

19 Source : ImageFormats.cs
with GNU General Public License v3.0
from arklumpus

public unsafe static void SavePNG(byte* image, int width, int height, bool hasAlpha, Stream fs, FilterModes filter, int threadCount = 0)
        {
            if (threadCount == 0)
            {
                threadCount = filter == FilterModes.Adaptive ? Math.Max(1, Math.Min(width / 600, Environment.ProcessorCount - 2)) : 1;
            }

            //Header
            fs.Write(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, 0, 8);

            //IHDR chunk
            fs.WriteInt(13);
            using (MemoryStream ihdr = new MemoryStream(13))
            {
                ihdr.WriteASCIIString("IHDR");
                ihdr.WriteInt(width);
                ihdr.WriteInt(height);
                ihdr.WriteByte(8); //Bit depth
                
                if (hasAlpha)
                {
                    ihdr.WriteByte(6); //Colour type
                }
                else
                {
                    ihdr.WriteByte(2); //Colour type
                }
                
                ihdr.WriteByte(0); //Compression method
                ihdr.WriteByte(0); //Filter method
                ihdr.WriteByte(0); //Interlace

                ihdr.Seek(0, SeekOrigin.Begin);
                ihdr.CopyTo(fs);

                fs.WriteUInt(CRC32.ComputeCRC(ihdr));
            }

            //IDAT chunk
            IntPtr filteredImage;
            
            if (threadCount > 1)
            {
                filteredImage = FilterImageData(image, width, height, hasAlpha ? 4 : 3, FilterModes.Adaptive, threadCount);
            }
            else
            {
                filteredImage = FilterImageData(image, width, height, hasAlpha ? 4 : 3, FilterModes.Adaptive);
            }
            
            using (MemoryStream compressedImage = StreamUtils.ZLibCompress(filteredImage, height * (width * (hasAlpha ? 4 : 3) + 1)))
            {
                compressedImage.Seek(0, SeekOrigin.Begin);
                fs.WriteUInt((uint)compressedImage.Length);
                fs.WriteASCIIString("IDAT");
                compressedImage.Seek(0, SeekOrigin.Begin);
                compressedImage.CopyTo(fs);

                fs.WriteUInt(CRC32.ComputeCRC(compressedImage.GetBuffer(), (int)compressedImage.Length, new byte[] { 73, 68, 65, 84 }));
            }

            Marshal.FreeHGlobal(filteredImage);

            //IEND chunk
            fs.WriteInt(0);
            fs.WriteASCIIString("IEND");
            fs.Write(new byte[] { 0xAE, 0x42, 0x60, 0x82 }, 0, 4);

        }

19 Source : ExportableGridView.cs
with MIT License
from aspose-pdf

protected void ExportButton_Click(object sender, EventArgs e)
        {
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            if (ExportDataSource != null)
            {
                this.AllowPaging = false;
                this.DataSource = ExportDataSource;
                this.DataBind();
            }

            this.RenderBeginTag(hw);
            this.HeaderRow.RenderControl(hw);
            foreach (GridViewRow row in this.Rows)
            {
                row.RenderControl(hw);
            }
            this.FooterRow.RenderControl(hw);
            this.RenderEndTag(hw);

            string heading = string.IsNullOrEmpty(ExportFileHeading) ? string.Empty : ExportFileHeading;

            string pageSource = "<html><head></head><body>" + heading + sw.ToString() + "</body></html>";

            // Check for license and apply if exists
            if (File.Exists(LicenseFilePath))
            {
                License license = new License();
                license.SetLicense(LicenseFilePath);
            }

            string fileName = System.Guid.NewGuid() + ".pdf";

            Aspose.Pdf.Doreplacedent pdf;
            HtmlLoadOptions htmlLoadOptions = new HtmlLoadOptions();
            MemoryStream outputstream = new MemoryStream();
            htmlLoadOptions.InputEncoding = "UTF-8";

            if (ExportInLandscape)
            {
                htmlLoadOptions.PageInfo.Width = 800;
                htmlLoadOptions.PageInfo.Height = 600;
            }

            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(pageSource)))
            {
                pdf = new Doreplacedent(stream, htmlLoadOptions);
            }

            if (!string.IsNullOrEmpty(ExportOutputPathOnServer) && Directory.Exists(ExportOutputPathOnServer))
            {
                try
                {
                    pdf.Save(ExportOutputPathOnServer + "\\" + fileName);
                }
                catch (Exception) { }
            }

            pdf.Save(outputstream);
            byte[] bytes = outputstream.GetBuffer();
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "application/pdf";
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
            HttpContext.Current.Response.BinaryWrite(bytes);
            HttpContext.Current.Response.End();
        }

19 Source : Extention.Object.cs
with MIT License
from awesomedotnetcore

public static byte[] ToBytes(this object obj)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(ms, obj);
                return ms.GetBuffer();
            }
        }

19 Source : D3D9Texture.cs
with GNU Lesser General Public License v2.1
from axiom3d

[AxiomHelper( 0, 9 )]
		private MemoryStream _toMemoryStream( Stream s )
		{
			var mStream = new MemoryStream();
			mStream.SetLength( s.Length );
			s.Read( mStream.GetBuffer(), 0, (int)mStream.Length );
			mStream.Flush();
			return mStream;
		}

19 Source : D3D9Texture.cs
with GNU Lesser General Public License v2.1
from axiom3d

[OgreVersion( 1, 7, 2 )]
		private void _loadCubeTexture( D3D9.Device d3d9Device, MemoryStream[] loadedStreams )
		{
			Debug.replacedert( TextureType == TextureType.CubeMap, "this.TextureType == TextureType.CubeMap" );

			if ( GetSourceFileType() == "dds" )
			{
				// find & load resource data
				Debug.replacedert( this._loadedStreams.Length == 1 );

				var d3dUsage = D3D9.Usage.None;
				var numMips = requestedMipmapCount == (int)TextureMipmap.Unlimited ? -1 : requestedMipmapCount + 1;
				var device = D3D9RenderSystem.DeviceManager.GetDeviceFromD3D9Device( d3d9Device );
				var rkCurCaps = device.D3D9DeviceCaps;

				// check if mip map volume textures are supported
				if ( ( rkCurCaps.TextureCaps & D3D9.TextureCaps.MipCubeMap ) != D3D9.TextureCaps.MipCubeMap )
				{
					// no mip map support for this kind of textures :(
					MipmapCount = 0;
					numMips = 1;
				}

				// Determine D3D pool to use
				var pool = UseDefaultPool() ? D3D9.Pool.Default : D3D9.Pool.Managed;

				// Get or create new texture resources structure.
				var textureResources = _getTextureResources( d3d9Device );
				if ( textureResources != null )
				{
					_freeTextureResources( d3d9Device, textureResources );
				}
				else
				{
					textureResources = _allocateTextureResources( d3d9Device );
				}

				try
				{
					textureResources.CubeTexture = D3D9.CubeTexture.FromMemory( d3d9Device, loadedStreams[ 0 ].GetBuffer(),
					                                                            (int)loadedStreams[ 0 ].Length, numMips, d3dUsage,
					                                                            D3D9.Format.Unknown, pool, D3D9.Filter.Default,
					                                                            D3D9.Filter.Default, 0 // colour Key
						);
				}
				catch ( Exception ex )
				{
					freeInternalResources();
					throw new AxiomException( "Can't create cube texture.", ex );
				}

				textureResources.BaseTexture = textureResources.CubeTexture.QueryInterface<D3D9.BaseTexture>();

				var texDesc = textureResources.CubeTexture.GetLevelDescription( 0 );
				this._d3dPool = texDesc.Pool;
				// set src and dest attributes to the same, we can't know
				_setSrcAttributes( texDesc.Width, texDesc.Height, 1, D3D9Helper.ConvertEnum( texDesc.Format ) );
				_setFinalAttributes( d3d9Device, textureResources, texDesc.Width, texDesc.Height, 1,
				                     D3D9Helper.ConvertEnum( texDesc.Format ) );

				if ( hwGamma )
				{
					this._hwGammaReadSupported = _creplacedeHardwareGammaCorrection( d3d9Device, texDesc.Usage,
					                                                             D3D9.ResourceType.CubeTexture,
					                                                             texDesc.Format, false );
				}

				internalResourcesCreated = true;
			}
			else
			{
				Debug.replacedert( loadedStreams.Length == 6 );

				var ext = string.Empty;
				var pos = _name.LastIndexOf( "." );
				if ( pos != -1 )
				{
					ext = _name.Substring( pos + 1 );
				}

				var images = new List<Image>( 6 );

				for ( var i = 0; i < 6; i++ )
				{
					images.Add( Image.FromStream( loadedStreams[ i ], ext ) );
				}

				LoadImages( images.ToArray() );
			}
		}

19 Source : D3D9Texture.cs
with GNU Lesser General Public License v2.1
from axiom3d

[OgreVersion( 1, 7, 2 )]
		private void _loadVolumeTexture( D3D9.Device d3d9Device, MemoryStream[] loadedStreams )
		{
			Debug.replacedert( TextureType == TextureType.ThreeD );

			// DDS load?
			if ( GetSourceFileType() == "dds" )
			{
				// find & load resource data
				Debug.replacedert( loadedStreams.Length == 1 );

				var d3dUsage = D3D9.Usage.None;
				var numMips = requestedMipmapCount == (int)TextureMipmap.Unlimited ? -1 : requestedMipmapCount + 1;

				var device = D3D9RenderSystem.DeviceManager.GetDeviceFromD3D9Device( d3d9Device );
				var rkCurCaps = device.D3D9DeviceCaps;

				// check if mip map volume textures are supported
				if ( ( rkCurCaps.TextureCaps & D3D9.TextureCaps.MipVolumeMap ) != D3D9.TextureCaps.MipVolumeMap )
				{
					// no mip map support for this kind of textures :(
					MipmapCount = 0;
					numMips = 1;
				}

				// Determine D3D pool to use
				var pool = UseDefaultPool() ? D3D9.Pool.Default : D3D9.Pool.Managed;

				// Get or create new texture resources structure.
				var textureResources = _getTextureResources( d3d9Device );
				if ( textureResources != null )
				{
					_freeTextureResources( d3d9Device, textureResources );
				}
				else
				{
					textureResources = _allocateTextureResources( d3d9Device );
				}

				try
				{
					textureResources.VolumeTexture = D3D9.VolumeTexture.FromMemory( d3d9Device, loadedStreams[ 0 ].GetBuffer(), -1, -1,
					                                                                -1, // dims
					                                                                numMips, d3dUsage, D3D9.Format.Unknown, pool,
					                                                                D3D9.Filter.Default, D3D9.Filter.Default, 0
						// colour key
						);
				}
				catch ( Exception ex )
				{
					// romeoxbm: this statement is not present in Ogre implementation,
					// but maybe it should be..
					freeInternalResources();
					throw new AxiomException( "Can't create volume texture.", ex );
				}

				textureResources.BaseTexture = textureResources.VolumeTexture.QueryInterface<D3D9.BaseTexture>();

				// set src and dest attributes to the same, we can't know
				var texDesc = textureResources.VolumeTexture.GetLevelDescription( 0 );
				this._d3dPool = texDesc.Pool;
				// set src and dest attributes to the same, we can't know
				_setSrcAttributes( texDesc.Width, texDesc.Height, texDesc.Depth, D3D9Helper.ConvertEnum( texDesc.Format ) );
				_setFinalAttributes( d3d9Device, textureResources, texDesc.Width, texDesc.Height, texDesc.Depth,
				                     D3D9Helper.ConvertEnum( texDesc.Format ) );

				if ( hwGamma )
				{
					this._hwGammaReadSupported = _creplacedeHardwareGammaCorrection( d3d9Device, texDesc.Usage,
					                                                             D3D9.ResourceType.VolumeTexture,
					                                                             texDesc.Format, false );
				}

				internalResourcesCreated = true;
			}
			else
			{
				Debug.replacedert( loadedStreams.Length == 1 );

				var ext = string.Empty;
				var pos = _name.LastIndexOf( "." );
				if ( pos != -1 )
				{
					ext = _name.Substring( pos + 1 );
				}

				var img = Image.FromStream( loadedStreams[ 0 ], ext );

				if ( img.Height == 0 )
				{
					throw new AxiomException( "Image height == 0 in {0}", _name );
				}

				if ( img.Width == 0 )
				{
					throw new AxiomException( "Image width == 0 in {0}", _name );
				}

				if ( img.Depth == 0 )
				{
					throw new AxiomException( "Image depth == 0 in {0}", _name );
				}

				// Call internal _loadImages, not loadImage since that's external and 
				// will determine load status etc again
				LoadImages( new Image[]
				            {
				            	img
				            } );
			}
		}

See More Examples