Пример #1
1
        public static NameValueCollection Parse(Stream stream)
        {
            Dictionary<string, string[]> form = new Dictionary<string, string[]>();
            UTF8Encoding encoding = new UTF8Encoding(false);

            return HttpUtility.ParseQueryString(encoding.GetString(stream.ReadAllBytes()),encoding);
        }
        public AssemblyDebugParser(Stream?peStream, Stream pdbStream)
        {
            Stream inputStream;

            if (!PdbConverter.IsPortable(pdbStream))
            {
                if (peStream == null)
                {
                    throw new ArgumentNullException(nameof(peStream), "Full PDB's require the PE file to be next to the PDB");
                }

                if (!AppCompat.IsSupported(RuntimeFeature.DiaSymReader))
                {
                    throw new PlatformNotSupportedException("Windows PDB cannot be processed on this platform.");
                }

                // Full PDB. convert to ppdb in memory

                _pdbBytes          = pdbStream.ReadAllBytes();
                pdbStream.Position = 0;
                _peBytes           = peStream.ReadAllBytes();
                peStream.Position  = 0;

                _temporaryPdbStream = new MemoryStream();
                PdbConverter.Default.ConvertWindowsToPortable(peStream, pdbStream, _temporaryPdbStream);
                _temporaryPdbStream.Position = 0;
                peStream.Position            = 0;
                inputStream = _temporaryPdbStream;
                _pdbType    = PdbType.Full;
            }
            else
            {
                inputStream        = pdbStream;
                _pdbType           = PdbType.Portable;
                _pdbBytes          = pdbStream.ReadAllBytes();
                pdbStream.Position = 0;
            }



            _readerProvider = MetadataReaderProvider.FromPortablePdbStream(inputStream);
            _reader         = _readerProvider.GetMetadataReader();

            if (peStream != null)
            {
                _peReader    = new PEReader(peStream);
                _ownPeReader = true;
            }
        }
Пример #3
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="game"></param>
        /// <param name="stream"></param>
        /// <param name="requestedType"></param>
        /// <param name="assetPath"></param>
        /// <returns></returns>
        public override object Load( Game game, Stream stream, Type requestedType, string assetPath )
        {
            var bytes = stream.ReadAllBytes();

            if (assetPath.ToLowerInvariant().Contains("|default")) {
                return Encoding.Default.GetString( bytes );
            }

            if (assetPath.ToLowerInvariant().Contains("|utf8")) {
                return Encoding.UTF8.GetString( bytes );
            }

            if (assetPath.ToLowerInvariant().Contains("|utf7")) {
                return Encoding.UTF7.GetString( bytes );
            }

            if (assetPath.ToLowerInvariant().Contains("|utf32")) {
                return Encoding.UTF32.GetString( bytes );
            }

            if (assetPath.ToLowerInvariant().Contains("|ascii")) {
                return Encoding.ASCII.GetString( bytes );
            }

            return Encoding.Default.GetString( bytes );
        }
Пример #4
0
    public override void OnResultExecuted(ResultExecutedContext context)
    {
        try
        {
            var request = (RestLogEntity)context.HttpContext.Items.GetOrThrow(typeof(RestLogEntity).FullName !) !;
            request.EndDate = Clock.Now;

            Stream memoryStream = RestoreOriginalStream(context);

            if (context.Exception == null)
            {
                memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
                request.ResponseBody = Encoding.UTF8.GetString(memoryStream.ReadAllBytes());
            }

            if (context.Exception != null)
            {
                request.Exception = context.Exception.LogException()?.ToLite();
            }

            using (ExecutionMode.Global())
                request.Save();
        }
        catch (Exception e)
        {
            e.LogException();
        }
    }
Пример #5
0
        public void AssertEqual(Stream actual, string fileName)
        {
            var actualBytes = actual.ReadAllBytes();

            File.WriteAllBytes(Path.Combine(actualResultBasePath, fileName), actualBytes);

            var expectedResourceKey = testType.Namespace + ".Expected." + fileName;
            var expectedStream      = testType.Assembly.GetManifestResourceStream(expectedResourceKey);

            if (expectedStream == null)
            {
                Assert.Fail("Could not find the expected result for {0}", fileName);
                return;
            }

            if (fileName.EndsWith(".png"))
            {
                FileEqualityComparer.AssertEqualImages(expectedStream.ReadAllBytes(), actualBytes);
            }
            else if (fileName.EndsWith(".svg") || fileName.EndsWith(".html"))
            {
                FileEqualityComparer.AssertEqualText(expectedStream.ReadAllBytes(), actualBytes);
            }
            else
            {
                FileEqualityComparer.AssertEqualBinary(expectedStream.ReadAllBytes(), actualBytes);
            }
        }
Пример #6
0
 protected override Task OnSetContent(Stream content)
 {
     this.content      = content.ReadAllBytes();
     HasUnsavedChanges = true;
     NotifyChanged();
     return(Task.CompletedTask);
 }
Пример #7
0
        // "id" is project ID
        public object Post(int id, AddIssueArgs args, IFile attachment = null)
        {
            return(ExecuteInUnitOfWork(() =>
            {
                Project p = ProjectRepository.Get(id);

                Issue i = new Issue(p, args.Title, args.Description, args.Severity);
                IssueRepository.Add(i);

                if (args.Attachment != null && attachment != null)
                {
                    using (Stream s = attachment.OpenStream())
                    {
                        byte[] content = s.ReadAllBytes();
                        Attachment att = new Attachment(i, args.Attachment.Title, args.Attachment.Description, content, attachment.ContentType.MediaType);
                        AttachmentRepository.Add(att);
                    }
                }

                Uri issueUrl = typeof(IssueResource).CreateUri(new { id = i.Id });

                return new OperationResult.Created {
                    RedirectLocation = issueUrl
                };
            }));
        }
Пример #8
0
 public byte[] Decompress(byte[] data)
 {
     using (var ms = new MemoryStream(data))
     {
         Stream decompStream = null;
         try
         {
             decompStream = CreateDecompressionStream(ms);
             return(decompStream.ReadAllBytes());
         }
         finally
         {
             if (decompStream != null)
             {
                 try
                 {
                     decompStream.Dispose();
                 }
                 catch
                 {
                 }
             }
         }
     }
 }
Пример #9
0
        public static string DownloadFileTemp(string fileName, out bool success)
        {
            success = false;
            var request =
                (FtpWebRequest)WebRequest.Create(String.Format("ftp://{0}/{1}", Settings.Default.FTP_Server, fileName));

            request.Method      = WebRequestMethods.Ftp.DownloadFile;
            request.Credentials = new NetworkCredential(Settings.Default.FTP_UserID, Settings.Default.FTP_Password);

            FtpWebResponse response = null;

            try
            {
                response = (FtpWebResponse)request.GetResponse();
            }
            catch (WebException)
            {
                MessageBox.Show("Kon het bestand niet ophalen van de server. Mogelijk bestaat het bestand niet.",
                                "Bestand bestaat niet", MessageBoxButton.OK, MessageBoxImage.Error);
                return(null);
            }

            string tempPath       = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + Path.GetExtension(fileName));
            Stream responseStream = response.GetResponseStream();

            File.WriteAllBytes(tempPath, responseStream.ReadAllBytes());
            Debug.WriteLine("Download Complete, status {0}", response.StatusDescription);
            response.Close();
            success = true;
            return(tempPath);
        }
        public async Task <byte[]> GetAssemblyForSpecification(string specificationId, string etag)
        {
            if (etag.IsNotNullOrWhitespace())
            {
                Stream cachedAssembly = await _specificationAssemblies.GetAssembly(specificationId, etag);

                if (cachedAssembly != null)
                {
                    return(cachedAssembly.ReadAllBytes());
                }
            }

            byte[] assembly =
                await _calculationsApiClientPolicy.ExecuteAsync(() =>
                                                                _calculationsRepository.GetAssemblyBySpecificationId(specificationId));

            if (assembly == null)
            {
                string error = $"Failed to get assembly for specification Id '{specificationId}'";

                _logger.Error(error);

                throw new RetriableException(error);
            }

            await _specificationAssemblies.SetAssembly(specificationId, new MemoryStream(assembly));


            return(assembly);
        }
Пример #11
0
 public static string GetHash(this IPackage package, IHashProvider hashProvider)
 {
     using (Stream stream = package.GetStream()) {
         byte[] packageBytes = stream.ReadAllBytes();
         return(Convert.ToBase64String(hashProvider.CalculateHash(packageBytes)));
     }
 }
Пример #12
0
        private ChangeTrackerResponseCode ProcessRegularStream(Stream stream, CancellationToken token)
        {
            if (_changeProcessor == null)
            {
                _changeProcessor = new ChunkedChanges(false, token);
                SetupChangeProcessorCallback();
            }

            if (stream.Length == 3)  // +1 for the first type ID
            {
                if (!_caughtUp)
                {
                    _caughtUp = true;
                    if (OnCaughtUp != null)
                    {
                        OnCaughtUp();
                    }

                    return(ChangeTrackerResponseCode.Normal);
                }
            }

            _changeProcessor.AddData(stream.ReadAllBytes());

            return(ChangeTrackerResponseCode.Normal);
        }
Пример #13
0
        // "id" is issue ID
        public object Post(int id, AddAttachmentArgs args, IFile attachment = null)
        {
            return(ExecuteInUnitOfWork(() =>
            {
                Issue issue = IssueRepository.Get(id);
                Attachment att;
                if (attachment != null)
                {
                    using (Stream s = attachment.OpenStream())
                    {
                        byte[] content = s.ReadAllBytes();
                        att = new Attachment(issue, args.Title, args.Description, content, attachment.ContentType.MediaType);
                    }
                }
                else
                {
                    att = new Attachment(issue, args.Title, args.Description, null, null);
                }

                AttachmentRepository.Add(att);

                Uri attUrl = typeof(AttachmentResource).CreateUri(new { id = att.Id });

                return new OperationResult.Created {
                    RedirectLocation = attUrl
                };
            }));
        }
Пример #14
0
        public void Boot()
        {
            byte[] bootFile;

            using (Stream systemStream = Drives.First().Value.OpenFile(FileSystemPath.Parse("/system/system.mye"), FileAccess.Read))
            {
                bootFile = systemStream.ReadAllBytes();
            }

            if (bootFile == null)
            {
                throw new Exception("No operating system found");
            }

            Assembly assembly = Assembly.Load(bootFile);

            IEnumerable <Type> osType = from t in assembly.GetTypes() where t.Name == "OperatingSystem" select t;

            if (osType.Count() > 1)
            {
                throw new Exception("Too many OSes");
            }

            IMyOS           osItem         = (IMyOS)Activator.CreateInstance(osType.First());
            IProcessManager processManager = new ProcessManager();

            osItem.Boot(this, processManager);
        }
Пример #15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="game"></param>
        /// <param name="stream"></param>
        /// <param name="requestedType"></param>
        /// <param name="assetPath"></param>
        /// <returns></returns>
        public override object Load(Game game, Stream stream, Type requestedType, string assetPath)
        {
            var bytes = stream.ReadAllBytes();

            if (assetPath.ToLowerInvariant().Contains("|default"))
            {
                return(Encoding.Default.GetString(bytes).Split(new[] { "\r\n", "\n" }, StringSplitOptions.None));
            }

            if (assetPath.ToLowerInvariant().Contains("|utf8"))
            {
                return(Encoding.UTF8.GetString(bytes).Split(new[] { "\r\n", "\n" }, StringSplitOptions.None));
            }

            if (assetPath.ToLowerInvariant().Contains("|utf7"))
            {
                return(Encoding.UTF7.GetString(bytes).Split(new[] { "\r\n", "\n" }, StringSplitOptions.None));
            }

            if (assetPath.ToLowerInvariant().Contains("|utf32"))
            {
                return(Encoding.UTF32.GetString(bytes).Split(new[] { "\r\n", "\n" }, StringSplitOptions.None));
            }

            if (assetPath.ToLowerInvariant().Contains("|ascii"))
            {
                return(Encoding.ASCII.GetString(bytes).Split(new[] { "\r\n", "\n" }, StringSplitOptions.None));
            }

            return(Encoding.Default.GetString(bytes).Split(new[] { "\r\n", "\n" }, StringSplitOptions.None));
        }
 public void ToStreamTest()
 {
     byte[] values = new byte[] { 43, 24, 255, 0, 2 };
     using Stream stream = values.ToStream();
     AssertThat(stream.ReadUInt8()).IsEqualTo(43);
     AssertThat(stream.ReadAllBytes()).ContainsExactly(values.Skip(1));
 }
Пример #17
0
        private async void UploadProfilePictureBtn_OnClicked(object sender, EventArgs e)
        {
            (sender as Button).IsEnabled = false;

            Stream stream = await _photoPickerService.GetImageStreamAsync();

            if (stream != null)
            {
                UserImage.Source = ImageSource.FromStream(() => stream);

                byte[] userProfilePic = stream.ReadAllBytes();


                ClientUpdateRequest request = new ClientUpdateRequest();
                request.ProfilePicture = userProfilePic;
                if (await _clientService.Update <ClientModel>(APIService.LoggedUserId, request) != null)
                {
                    await LoadClientProfilePicture();

                    await Helper.LoadUserImage(_clientService, userImg);

                    await model.Init();
                    await DisplayAlert("Success", "Profile picture successfully added!", "OK");
                }
                else
                {
                    await DisplayAlert("Error", "Unexpected error has occured. Please try again later!", "OK");
                }
            }

            (sender as Button).IsEnabled = true;
        }
Пример #18
0
        internal static byte[] GetRequestDataPacket(Stream stream, int packetIndex)
        {
            using (var returnStream = new MemoryStream())
            {
                var position = (int)returnStream.Position;
                returnStream.WriteByte((Constants.DEFAULT_CHANNEL >> 8) & 0xff);
                returnStream.WriteByte(Constants.DEFAULT_CHANNEL & 0xff);
                returnStream.WriteByte(Constants.TAG_APDU);
                returnStream.WriteByte((byte)((packetIndex >> 8) & 0xff));
                returnStream.WriteByte((byte)(packetIndex & 0xff));

                if (packetIndex == 0)
                {
                    returnStream.WriteByte((byte)((stream.Length >> 8) & 0xff));
                    returnStream.WriteByte((byte)(stream.Length & 0xff));
                }

                var headerLength = (int)(returnStream.Position - position);
                var blockLength  = Math.Min(Constants.LEDGER_HID_PACKET_SIZE - headerLength, (int)stream.Length - (int)stream.Position);

                var packetBytes = stream.ReadAllBytes(blockLength);

                returnStream.Write(packetBytes, 0, packetBytes.Length);

                while ((returnStream.Length % Constants.LEDGER_HID_PACKET_SIZE) != 0)
                {
                    returnStream.WriteByte(0);
                }

                return(returnStream.ToArray());
            }
        }
Пример #19
0
        /// <summary>
        /// Reads a single char from the stream.
        /// </summary>
        /// <param name="stream">The stream to read from.</param>
        /// <param name="encoding">The encoding of the string.</param>
        /// <returns>First char on the stream.</returns>
        public static string ReadString(this Stream stream, Encoding encoding)
        {
            if (encoding is null)
            {
                throw new ArgumentNullException(nameof(encoding));
            }

            return(encoding.GetString(stream.ReadAllBytes()));
        }
Пример #20
0
        public T Deserialize <T>(Stream input)
        {
            // hex > bytes > json str > obj
            var hex   = Encoding.UTF8.GetString(input.ReadAllBytes());
            var bytes = hex.Split(' ')
                        .Select(item => Convert.ToByte(item, 16)).ToArray();

            return(JsonConvert.DeserializeObject <T>(Encoding.UTF8.GetString(bytes), this.settings));
        }
Пример #21
0
        public static void CopyStream(Stream src, Stream target)
        {
            src.Position    = 0;
            target.Position = 0;
            var buffer = src.ReadAllBytes();

            target.Write(buffer, 0, buffer.Length);
            target.Flush();
        }
Пример #22
0
        public static Texture2D GetTextureFromStream(Stream stream)
        {
            Texture2D texture2D = new Texture2D(1, 1, TextureFormat.ARGB32, mipmap: false);

            texture2D.LoadImage(stream.ReadAllBytes());
            texture2D.wrapMode = TextureWrapMode.Clamp; // for cursor.
            texture2D.Apply(false, false);
            return(texture2D);
        }
Пример #23
0
 public BinaryFile(Stream stream, bool leaveOpen = false)
 {
     Path  = string.Empty;
     Bytes = stream.ReadAllBytes();
     if (!leaveOpen)
     {
         stream.Dispose();
     }
 }
Пример #24
0
 public BMWebException(WebException ex, Uri uri)
     : base(ex, createMsg(ex, uri))
 {
     using (Stream strm = ex.Response.GetResponseStream())
     {
         ResponseText = Encoding.UTF8.GetString(strm.ReadAllBytes());
     }
     Logs.ErrorLog.Log(_LogType.ltError, Message);
     Logs.ErrorLog.Log(_LogType.ltError, "Response status={0}, Response text={1}", ex.Status, ResponseText);
 }
Пример #25
0
        public static IBuffer ToIBuffer(this Stream stream)
        {
            if (stream == null)
            {
                return(null);
            }
            var buf = stream.ReadAllBytes();

            return(CryptographicBuffer.CreateFromByteArray(buf));
        }
Пример #26
0
        private static Assembly CreateAssembly(string resourceName)
        {
            // Load a pre-generated assembly containing compiled calculations. This was generated by using the system and copying the base64 encoded assembly from cosmos
            Assembly assembly = Assembly.GetExecutingAssembly();

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            {
                return(Assembly.Load(stream.ReadAllBytes()));
            }
        }
Пример #27
0
 private static async Task CreateThumbnailImageAsync(Stream inputStream, string thumbnailPath)
 {
     await Task.Factory.StartNew(() => {
         using (FileStream fileStream = new FileStream(thumbnailPath, FileMode.CreateNew)) {
             inputStream.Seek(0, SeekOrigin.Begin);
             var thumbnailBytes = ImageHelper.ResizeByteArrayImage(inputStream.ReadAllBytes(), 130, 130, false);
             fileStream.Write(thumbnailBytes, 0, thumbnailBytes.Length);
         }
     });
 }
Пример #28
0
        public byte[] ReadXNBResource(string resource)
        {
            using (MemoryStream ms = new MemoryStream(ReadResource(resource)))
            {
                using (BinaryReader xnbReader = new BinaryReader(ms))
                {
                    int  num1 = (int)xnbReader.ReadByte();
                    byte num2 = xnbReader.ReadByte();
                    byte num3 = xnbReader.ReadByte();
                    byte num4 = xnbReader.ReadByte();

                    if (num1 != 88 || num2 != (byte)78 ||
                        (num3 != (byte)66 || !TargetPlatformIdentifiers.Contains((char)num4)))
                    {
                        throw new ContentLoadException(
                                  "Asset does not appear to be a valid XNB file. Did you process your content for Windows?");
                    }

                    byte num5  = xnbReader.ReadByte();
                    int  num6  = (int)xnbReader.ReadByte();
                    bool flag1 = (uint)(num6 & 128) > 0U;
                    bool flag2 = (uint)(num6 & 64) > 0U;

                    if (num5 != (byte)5 && num5 != (byte)4)
                    {
                        throw new ContentLoadException("Invalid XNB version");
                    }

                    int    num7    = xnbReader.ReadInt32();
                    Stream stream1 = (Stream)null;

                    if (flag1 | flag2)
                    {
                        int decompressedSize = xnbReader.ReadInt32();

                        if (flag1)
                        {
                            int compressedSize = num7 - 14;
                            stream1 = (Stream) new LzxDecoderStream(ms, decompressedSize, compressedSize);
                        }
                        else if (flag2)
                        {
                            stream1 = (Stream) new Lz4DecoderStream(ms, long.MaxValue);
                        }
                    }
                    else
                    {
                        stream1 = ms;
                    }

                    //return new ContentReader(this, stream1, originalAssetName, (int) num5, recordDisposableObject);
                    return(stream1.ReadAllBytes());
                }
            }
        }
Пример #29
0
        private ChangeTrackerResponseCode ProcessGzippedStream(Stream stream, CancellationToken token)
        {
            if (_changeProcessor == null)
            {
                _changeProcessor = new ChunkedChanges(true, token);
                SetupChangeProcessorCallback();
            }

            _changeProcessor.AddData(stream.ReadAllBytes());
            return(ChangeTrackerResponseCode.Normal);
        }
Пример #30
0
        public MemoryStream ReadFileAsStream(string path)
        {
            MemoryStream memoryStream;

            using (Stream stream = _fileSystem.OpenFile(FileSystemPath.Parse(path), FileAccess.Read))
            {
                memoryStream = new MemoryStream(stream.ReadAllBytes());
            }

            return(memoryStream);
        }
        public AssemblyDebugParser(Stream?peStream, Stream pdbStream)
        {
            Stream inputStream;

            if (!PdbConverter.IsPortable(pdbStream))
            {
                if (peStream == null)
                {
                    throw new ArgumentNullException(nameof(peStream), "Full PDB's require the PE file to be next to the PDB");
                }
                // Full PDB. convert to ppdb in memory

                _pdbBytes          = pdbStream.ReadAllBytes();
                pdbStream.Position = 0;
                _peBytes           = peStream.ReadAllBytes();
                peStream.Position  = 0;

                _temporaryPdbStream = new MemoryStream();
                PdbConverter.Default.ConvertWindowsToPortable(peStream, pdbStream, _temporaryPdbStream);
                _temporaryPdbStream.Position = 0;
                peStream.Position            = 0;
                inputStream = _temporaryPdbStream;
                _pdbType    = PdbType.Full;
            }
            else
            {
                inputStream        = pdbStream;
                _pdbType           = PdbType.Portable;
                _pdbBytes          = pdbStream.ReadAllBytes();
                pdbStream.Position = 0;
            }



            _readerProvider = MetadataReaderProvider.FromPortablePdbStream(inputStream);
            _reader         = _readerProvider.GetMetadataReader();

            _peReader = new PEReader(peStream !);
            //_peReader.
            _ownPeReader = true;
        }
Пример #32
0
 public void WriteFileStream(string fileName, Stream stream, Action onWrite = null)
 {
     if (ContentFolder)
     {
         throw new IOException("Unable to edit files in the content folder");
     }
     new Thread(() => {
         stream.Seek(0L, SeekOrigin.Begin);
         File.WriteAllBytes(Path.Combine(_localContentLocation, fileName), stream.ReadAllBytes());
         onWrite?.Invoke();
     }).Start();
 }
Пример #33
0
        public void CreatePackage(string apiKey, Stream packageStream, IObserver<int> progressObserver, IPackageMetadata metadata = null)
        {
            var state = new PublishState {
                PublishKey = apiKey,
                PackageMetadata = metadata,
                ProgressObserver = progressObserver
            };

            var url = new Uri(String.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}/nupkg", _baseGalleryServerUrl, CreatePackageService, apiKey));

            WebClient client = new WebClient();
            client.Proxy = _cachedProxy;
            client.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
            client.Headers[HttpRequestHeader.UserAgent] = _userAgent;
            client.UploadProgressChanged += OnUploadProgressChanged;
            client.UploadDataCompleted += OnCreatePackageCompleted;
            client.UploadDataAsync(url, "POST", packageStream.ReadAllBytes(), state);
        }
        private void CalculateDerivedDataSlowlyConsumingLotsOfMemory(LucenePackage package, Stream stream)
        {
            byte[] fileBytes;
            using (stream)
            {
                fileBytes = stream.ReadAllBytes();
            }

            package.PackageSize = fileBytes.Length;
            package.PackageHash = System.Convert.ToBase64String(HashProvider.CalculateHash(fileBytes));
            package.Created = GetZipArchiveCreateDate(new MemoryStream(fileBytes));
        }
Пример #35
0
		/// <summary>
		/// Constrcutor
		/// </summary>
		/// <param name="device"></param>
		/// <param name="fileName"></param>
		public SpriteFont ( GraphicsDevice rs, Stream stream )
		{
			this.rs	=	rs;

			using (var br = new BinaryReader(stream)) {

				var xml = br.ReadString();
				FontFile input = FontLoader.LoadFromString( xml );

				int numGlyphs	=	input.Chars.Max( ch => ch.ID );

				//	create charInfo and kernings :
				fontInfo.kernings = new Dictionary<Tuple<char,char>, float>();
				fontInfo.charInfo = new SpriteFontInfo.CharInfo[numGlyphs+1];

				//	check one-page bitmap fonts :
				if (input.Pages.Count!=1) {
					throw new GraphicsException("Only one page of font image is supported");
				}

				//	create path for font-image :
				string fontImagePath	=	input.Pages[0].File;

				//	skip two bytes :
				var texData				=	stream.ReadAllBytes();
				fontTexture				=	new UserTexture( rs.Game.RenderSystem, texData, false );
			
				//	Fill structure :
				fontInfo.fontFace		=	input.Info.Face;
				fontInfo.baseLine		=	input.Common.Base;
				fontInfo.lineHeight		=	input.Common.LineHeight;
				fontInfo.scaleWidth		=	input.Common.ScaleW;
				fontInfo.scaleHeight	=	input.Common.ScaleH;

				float scaleWidth = fontInfo.scaleWidth;
				float scaleHeight = fontInfo.scaleHeight;

				//	process character info :
				for ( int i=0; i<input.Chars.Count; i++) {
					FontChar ch = input.Chars[i];

					int id = ch.ID;

					if (id<0) continue;

					int x = ch.X;
					int y = ch.Y;
					int xoffs = ch.XOffset;
					int yoffs = ch.YOffset;
					int w = ch.Width;
					int h = ch.Height;

					fontInfo.charInfo[ ch.ID ].validChar	=	true;
					fontInfo.charInfo[ ch.ID ].xAdvance		=	ch.XAdvance;
					fontInfo.charInfo[ ch.ID ].srcRect		=	new RectangleF(x, y, w, h);
					fontInfo.charInfo[ ch.ID ].dstRect		=	new RectangleF(xoffs, yoffs, w, h);
				}


				var letterHeights = input.Chars
						.Where( ch1 => char.IsUpper( (char)(ch1.ID) ) )
						.Select( ch2 => ch2.Height )
						.OrderBy( h => h )
						.ToList();
				CapHeight	=	letterHeights[ letterHeights.Count/2 ];



				//	process kerning info :
				for ( int i=0; i<input.Kernings.Count; i++) {
					var pair	=	new Tuple<char,char>( (char)input.Kernings[i].First, (char)input.Kernings[i].Second);
					int kerning =	input.Kernings[i].Amount;
					fontInfo.kernings.Add( pair, kerning );
				}

				SpaceWidth	=	MeasureString(" ").Width;
				LineHeight	=	MeasureString(" ").Height;
			}
		}
Пример #36
0
 public void Writefile(string filePath, Stream data)
 {
     File.WriteAllBytes(filePath, data.ReadAllBytes());
 }
Пример #37
0
 private static object DeserializeFeatureGen(Stream inputStream) {
     return inputStream.ReadAllBytes();
 }
 /// <summary>
 /// Reads an X509 certificate from the given stream
 /// </summary>
 /// <returns>The retrieved certificate</returns>
 /// <param name="stream">The stream that contains the X509 certificate data.</param>
 /// <param name="password">The password to use to open the certificate.</param>
 public static X509Certificate2 GetExistingPersistentCertificate(Stream stream, string password)
 {
     return new X509Certificate2(stream.ReadAllBytes(), password);
 }
Пример #39
0
 /// <summary>
 /// Initializes the document metadata with bytes fed from the supplied stream
 /// </summary>
 /// <param name="document"></param>
 public void SetDocument(Stream document)
 {
     SetDocument(document.ReadAllBytes());
 }
        protected virtual void CalculateDerivedData(IPackage sourcePackage, LucenePackage package, string path, Stream stream)
        {
            byte[] fileBytes;
            using (stream)
            {
                fileBytes = stream.ReadAllBytes();
            }

            package.PackageSize = fileBytes.Length;
            package.PackageHash = System.Convert.ToBase64String(HashProvider.CalculateHash(fileBytes));
            package.PackageHashAlgorithm = HashAlgorithm;
            package.LastUpdated = FileSystem.GetLastModified(path);
            package.Published = package.LastUpdated;
            package.Created = GetZipArchiveCreateDate(new MemoryStream(fileBytes));
            package.Path = path;

            package.SupportedFrameworks = sourcePackage.GetSupportedFrameworks().Select(VersionUtility.GetShortFrameworkName);

            var localPackage = sourcePackage as LocalPackage;
            if (localPackage != null)
            {
                package.Files = localPackage.GetFiles().Select(f => f.Path);
            }
        }
Пример #41
0
		public override object Load ( ContentManager content, Stream stream, Type requestedType, string assetPath )
		{
			return stream.ReadAllBytes();
		}