Exemple #1
0
        public static void split(string input_path, string dir_path, int nb)
        {
            System.IO.FileStream inf = new System.IO.FileStream(input_path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader reader = new System.IO.BinaryReader(inf);
            System.IO.BinaryWriter[] writers = new System.IO.BinaryWriter[nb];
            for (int x = 0; x < nb; x++)
            {
                writers[x] = new System.IO.BinaryWriter(new System.IO.FileStream(dir_path + "/part_" + (x + 1) + ".ACDC",
                                                                    System.IO.FileMode.Create,
                                                                    System.IO.FileAccess.Write));

            }
            int i = 0;
            while (reader.PeekChar() != -1)
            {

                writers[i % nb].Write(reader.ReadChar());

                i++;
            }
            for (int j=0; j<nb; j++)
            {
                writers[j].Close();
            }
            
        }
Exemple #2
0
        public byte[] FileToByteArray(string _FileName)
        {
            byte[] _Buffer = null;

            try
            {

                // Open file for reading
                System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);

                // attach filestream to binary reader
                System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);

                // get total byte length of the file
                long _TotalBytes = new System.IO.FileInfo(_FileName).Length;

                // read entire file into buffer
                _Buffer = _BinaryReader.ReadBytes((Int32)(_TotalBytes));
                // close file reader
                _FileStream.Close();
                _FileStream.Dispose();
                _BinaryReader.Close();
            }

            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
            }

            return _Buffer;
        }
        /// <summary>
        /// 根据文件的前2个字节进行判断文件类型  ---说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
        /// </summary>
        /// <param name="hpf"></param>
        /// <param name="code">文件的前2个字节转化出来的小数</param>
        /// <returns></returns>
        public bool CheckUploadByTwoByte(HttpPostedFile hpf, Int64 code)
        {
            System.IO.FileStream fs = new System.IO.FileStream(hpf.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
            string fileclass = "";
            byte buffer;
            try
            {
                buffer = r.ReadByte();
                fileclass = buffer.ToString();
                buffer = r.ReadByte();
                fileclass += buffer.ToString();

            }
            catch
            {

            }
            r.Close();
            fs.Close();
            //
            //if (fileclass == code.ToString())
            //{
            //    return true;
            //}
            //else
            //{
            //    return false;
            //}
            return (fileclass == code.ToString());
        }
Exemple #4
0
        public ActionResult Create([Bind(Include = "GameID,GameName,Official,Website,CoverArt,Genre,Description,Approved")] Game game, HttpPostedFileBase upload)
        {
            if (ModelState.IsValid)
            {
                if (upload != null && upload.ContentLength > 0)
                {
                    var art = new CoverArt
                    {
                        FileName = System.IO.Path.GetFileName(upload.FileName),
                        ContentType = upload.ContentType
                    };
                    using (var reader = new System.IO.BinaryReader(upload.InputStream))
                    {
                        art.Image = reader.ReadBytes(upload.ContentLength);
                    }
                    game.CoverArt = art;
                }

                db.Games.Add(game);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(game);
        }
Exemple #5
0
        public static FullAnimation From3DMAXStream(System.IO.Stream stream, SkeletonExtended skeleton, bool reverse)
        {
            Matrix[][] Frames;
            var clip = new FullAnimation();
            var reader = new System.IO.BinaryReader(stream);
            var start = reader.ReadInt32();
            var end = reader.ReadInt32();
            var length = end - start + 1;
            clip.BonesCount = reader.ReadInt32();
            var counter = reader.ReadInt32();
            Frames = new Matrix[length][];
            for (int i = 0; i < length; i++)
                Frames[i] = new Matrix[clip.BonesCount];
            for (int i = 0; i < clip.BonesCount; i++)
                for (int j = 0; j < length; j++)
                    Frames[j][i] = reader.ReadMatrix();
            //теперь надо вычислить дельты
            //(идёт загрузка экспортированного из макса)
            for (int i = 0; i < clip.BonesCount; i++)
                for (int @in = 0; @in < length; @in++)
                    Frames[@in][i] = skeleton.baseskelet.bones[i].BaseMatrix * Frames[@in][i];

            if (reverse)
            {
                //Matrix[][] FramesTmp = new Matrix[length][];
                Frames = Frames.Reverse().ToArray();
            }
            Matrix[][] relatedMatrices = Animation.GetRelatedMatrices(Frames, skeleton.baseskelet);
            DecomposedMatrix[][] decomposedMatrices = GetDecomposedMatrices(skeleton.baseskelet, relatedMatrices);

            clip.matrices = decomposedMatrices;
            return clip;
        }
 public async Task<ActionResult> CreateProduct([Bind(Include = "ProductName, ProductDesc, ProductPrice")] Products product, HttpPostedFileBase upload)
 {
     try
     {
         if (ModelState.IsValid)
         {
             if (upload != null && upload.ContentLength > 0)
             {
                 var avatar = new File
                 {
                     FileName = System.IO.Path.GetFileName(upload.FileName),
                     FileType = FileType.Avatar,
                     ContentType = upload.ContentType
                 };
                 using (var reader = new System.IO.BinaryReader(upload.InputStream))
                 {
                     avatar.Content = reader.ReadBytes(upload.ContentLength);
                 }
                 product.Files = new List<File> { avatar };
             }
             db.Products.Add(product);
             await db.SaveChangesAsync();
             return RedirectToAction("Index");
         }
     }
     catch (RetryLimitExceededException /* dex */)
     {
         ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
     }
     return View(product);
 }
 public ActionResult Create([Bind(Include = "ProductId,ProductTitle,ProductDescription,ProductPrice,CategoryId")] Product product, HttpPostedFileBase upload)
 {
     try {
         if (ModelState.IsValid)
         {
             if (upload != null && upload.ContentLength > 0)
             {
                 var image = new File
                 {
                     FileName = System.IO.Path.GetFileName(upload.FileName),
                     FileType = FileType.Image,
                     ContentType = upload.ContentType
                 };
                 using (var reader = new System.IO.BinaryReader(upload.InputStream))
                 {
                     image.Content = reader.ReadBytes(upload.ContentLength);
                 }
                 product.Files = new List<File> { image };
             }
             db.Products.Add(product);
             db.SaveChanges();
             return RedirectToAction("Index");
         }
     }
     catch (RetryLimitExceededException)
     {
         ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
     }
     ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "CategoryName", product.CategoryId);
     return View(product);
 }
		protected void filAddExtension_Upload(object sender, FileUploadEventArgs e)
		{
			//get the uploaded file and its metadata
			HttpPostedFile postedFile = e.PostedFile;
			string filepath = postedFile.FileName;
			string filename = filepath.Substring(filepath.LastIndexOf('\\') + 1);

			if (ValidateFile(filename))
			{
				//separate the file extension from the filename
				string fileExt = System.IO.Path.GetExtension(filename);
				string fileNameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(filename);

				int contentLength = postedFile.ContentLength;
				string contentType = postedFile.ContentType;

				System.IO.BinaryReader reader = new System.IO.BinaryReader(postedFile.InputStream);
				byte[] bytes = new byte[contentLength];
				reader.Read(bytes, 0, contentLength);

				//store the file into the data store
				Utility.DocumentStorage documentStorageObject = Utility.DocumentStorage.GetDocumentStorageObject(_itatSystem.DocumentStorageType);
				documentStorageObject.RootPath = _itatSystem.DocumentStorageRootPath;
				string objectId = documentStorageObject.SaveDocument(fileNameWithoutExt, fileExt, bytes);

				//add metadata about the extension to the template object
				Business.Extension extension = new Kindred.Knect.ITAT.Business.Extension();
				extension.FileName = filename;
				extension.ObjectID = objectId;
				_template.Extensions.Add(extension);

				//update the form
				InitializeForm(_template.Extensions.Count - 1);  //select newly added row (last row in the grid)
			}
		}
        public ActionResult Create([Bind(Include = "ID,Title,Genre,ReleaseDate,Length,Directors,Actor,Intro,TrailerURL")] Movie movie, HttpPostedFileBase upload)
        {
            if (ModelState.IsValid)
            {
                // Upload Picture
                if (upload != null && upload.ContentLength > 0)
                {
                    var picture = new File
                    {
                        FileName = System.IO.Path.GetFileName(upload.FileName),
                        ContentType = upload.ContentType
                    };
                    using (var reader = new System.IO.BinaryReader(upload.InputStream))
                    {
                        picture.Content = reader.ReadBytes(upload.ContentLength);
                    }
                    movie.Files = new List<File> { picture };
                }
                else
                {
                    // Mặc định up hình ở đây.
                }
                db.Movies.Add(movie);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(movie);
        }
        public ActionResult Create([Bind(Include = "ID,Title,Body,Date,Type,ContentType")] Tutorial tutorial, HttpPostedFileBase upload)
        {
            string userid = User.Identity.GetUserId();
            var currentuser = db.Users.SingleOrDefault(u => u.Id == userid);

            if (ModelState.IsValid)
            {

                if (upload != null && upload.ContentLength > 0)
                {
                    var pic = new FileMain
                    {
                        FileName = System.IO.Path.GetFileName(upload.FileName),
                        FileType = FileType.Pic,
                        ContentType = upload.ContentType
                    };
                    using (var reader = new System.IO.BinaryReader(upload.InputStream))
                    {
                        pic.Content = reader.ReadBytes(upload.ContentLength);
                    }
                    tutorial.FileMains = new List<FileMain> { pic };
                }

                tutorial.User = currentuser;
                tutorial.Date = DateTime.Now;

                db.Tutorials.Add(tutorial);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(tutorial);
        }
Exemple #11
0
        public ActionResult Create([Bind(Include = "Id,IdUser,ProductName,Description,Status,RegisterDate")] Products products, HttpPostedFileBase upload)
        {
            if (ModelState.IsValid)
            {
                if (upload != null && upload.ContentLength > 0)
                {
                    var avatar = new File
                    {
                        FileName = System.IO.Path.GetFileName(upload.FileName),
                        FileType = FileType.Imagen,
                        ContentType = upload.ContentType
                    };
                    using (var reader = new System.IO.BinaryReader(upload.InputStream))
                    {
                        avatar.Content = reader.ReadBytes(upload.ContentLength);
                    }
                    products.Files = new List<File> { avatar };
                }
                products.IdUser = User.Identity.GetUserId();
                products.RegisterDate = @DateTime.Now;
                products.Status = "Activo";
                db.Products.Add(products);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(products);
        }
Exemple #12
0
        public ActionResult Create(OfferViewModel offerVM, HttpPostedFileBase uploadBanner)
        {
            if (this.ModelState.IsValid)
            {

                Offer offer = GetOffer(offerVM);

                if (offer.Type == OfferType.Banner)
                {
                    if (uploadBanner != null && uploadBanner.ContentLength > 0)
                    {
                        var newBanner = new Banner(offer)
                        {
                            FileName = System.IO.Path.GetFileName(uploadBanner.FileName),
                            ContentType = uploadBanner.ContentType
                        };

                        using (var reader = new System.IO.BinaryReader(uploadBanner.InputStream))
                        {
                            newBanner.Content = reader.ReadBytes(uploadBanner.ContentLength);
                        }

                        this.db.Banners.Add(newBanner);
                        this.db.SaveChanges();
                        return this.RedirectToAction("Index");
                    }
                }

                this.db.Offers.Add(offer);
                this.db.SaveChanges();
                return this.RedirectToAction("Index");
            }

            return this.View(offerVM);
        }
Exemple #13
0
		public static void DeserializeVoxelAreaData (byte[] bytes, VoxelArea target) {
			
			Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile();
			System.IO.MemoryStream stream = new System.IO.MemoryStream();
			stream.Write(bytes,0,bytes.Length);
			stream.Position = 0;
			zip = Ionic.Zip.ZipFile.Read(stream);
			System.IO.MemoryStream stream2 = new System.IO.MemoryStream();
			
			zip["data"].Extract (stream2);
			stream2.Position = 0;
			System.IO.BinaryReader reader = new System.IO.BinaryReader(stream2);
			
			int width = reader.ReadInt32();
			int depth = reader.ReadInt32();
			if (target.width != width) throw new System.ArgumentException ("target VoxelArea has a different width than the data ("+target.width + " != " + width + ")");
			if (target.depth != depth) throw new System.ArgumentException ("target VoxelArea has a different depth than the data ("+target.depth + " != " + depth + ")");
			LinkedVoxelSpan[] spans = new LinkedVoxelSpan[reader.ReadInt32()];
			
			for (int i=0;i<spans.Length;i++) {
				spans[i].area = reader.ReadInt32();
				spans[i].bottom = reader.ReadUInt32();
				spans[i].next = reader.ReadInt32();
				spans[i].top = reader.ReadUInt32();
			}
			target.linkedSpans = spans;
		}
Exemple #14
0
        public ActionResult Create([Bind(Include = "CarTypeId,CarCode,DailyPrice,DailyLatePrice")] CarType carType, HttpPostedFileBase upload)
        {
            if (ModelState.IsValid)
            {
                if (upload != null && upload.ContentLength > 0)
                {
                    var carImage = new File
                    {
                        FileName = System.IO.Path.GetFileName(upload.FileName),
                        FileType = FileType.CarImage,
                        ContentType = upload.ContentType
                    };
                    using (var reader = new System.IO.BinaryReader(upload.InputStream))
                    {
                        carImage.Content = reader.ReadBytes(upload.ContentLength);
                    }
                    carType.Files = new List<File> { carImage };
                }
                db.CarTypes.Add(carType);
                db.SaveChanges();
                TempData["Added"] = carType.CarCode + " Added";
                return RedirectToAction("Index");
            }

            return View(carType);
        }
        public static void Load()
        {
            IO.Log.Write("    Loading CampaingProgresss...");
            levelsCompleted.Clear();

            System.IO.BinaryReader br = new System.IO.BinaryReader(new System.IO.FileStream("Saves/progress.lpg",
                System.IO.FileMode.Open));

            String s = "";
            int l = 0;
            while (br.PeekChar() > -1)
            {
                s = br.ReadString();
                l = br.ReadInt32();
                byte[] d = new byte[l];
                for (int j = 0; j < l; j++)
                {
                    d[j] = br.ReadByte();
                }
                levelsCompleted.Add(s, d);
            }

            br.Close();
            IO.Log.Write("    Loading complete");
        }
        public ActionResult Create([Bind(Include = "Id,Description,Codigo,IdCategory,IdMarca,IdMoneda")] product product, List<HttpPostedFileBase> fileUpload)
        {
            if (ModelState.IsValid)
            {
                db.products.Add(product);
                db.SaveChanges();
                int id = product.Id;

                for (int i = 0; i < fileUpload.Count; i++)
                {
                    ImgProduct image = new ImgProduct
                    {
                        Name = System.IO.Path.GetFileName(fileUpload[i].FileName),
                        Id = id
                    };
                    using (var reader = new System.IO.BinaryReader(fileUpload[i].InputStream))
                    {
                        image.Image = reader.ReadBytes(fileUpload[i].ContentLength);
                        image.IdProduct = product.Id;
                        db.ImgProducts.Add(image);
                        db.SaveChanges();
                    }
                }

                ViewBag.IdCategory = new SelectList(db.Categories, "Id", "Description");
                ViewBag.IdMarca = new SelectList(db.Marcas, "Id", "Description", product.IdMarca);
                ViewBag.IdMoneda = new SelectList(db.Monedas, "Id", "Description", product.IdMoneda);
                return RedirectToAction("Index");
            }

            return View(product);
        }
Exemple #17
0
        public ActionResult Create(StudentAward studentAward)
        {
            try
            {
                if (Request.Files.Count == 1)
                {
                    var file = Request.Files[0];

                    if (file != null && file.ContentLength > 0)
                    {

                        using (var reader = new System.IO.BinaryReader(file.InputStream))
                        {
                            studentAward.Photo = reader.ReadBytes(file.ContentLength);
                        }
                    }
                }
                _ctx.StudentAwards.Add(studentAward);
                _ctx.SaveChanges();
                return RedirectToAction("List", new RouteValueDictionary(
               new { controller = "StudentAward", action = "List", StudentId = studentAward.Student_ID }));
            }
            catch
            {
                return View();
            }
        }
Exemple #18
0
        public ActionResult Create([Bind(Include = "IDPublicacion,IDMarca,IDModelo,Precio,IDColor,IDTipoCombustible,IDTipoVehiculo,IDCondicion,IDUser,WDate,Status")] Publicacion publicacion, HttpPostedFileBase upload)
        {
            if (ModelState.IsValid)
            {
                if (upload != null && upload.ContentLength > 0)
                {
                    var avatar = new File
                    {
                        FileName = System.IO.Path.GetFileName(upload.FileName),
                        FileType = FileType.Avatar,
                        ContentType = upload.ContentType
                    };
                    using (var reader = new System.IO.BinaryReader(upload.InputStream))
                    {
                        avatar.Content = reader.ReadBytes(upload.ContentLength);
                    }
                    publicacion.Files = new List<File> { avatar };
                }
                db.Publicaciones.Add(publicacion);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.IDColor = new SelectList(db.Colores, "IDColor", "colorDesc", publicacion.IDColor);
            ViewBag.IDCondicion = new SelectList(db.Condiciones, "IDCondicion", "condicionDesc", publicacion.IDCondicion);
            ViewBag.IDMarca = new SelectList(db.Marcas, "IDMarca", "marcaDesc", publicacion.IDMarca);
            ViewBag.IDModelo = new SelectList(db.Modelos, "IDModelo", "modeloDesc", publicacion.IDModelo);
            ViewBag.IDTipoCombustible = new SelectList(db.TipoCombustibles, "IDTipoCombustible", "tipoCombustibledesc", publicacion.IDTipoCombustible);
            ViewBag.IDTipoVehiculo = new SelectList(db.TiposVehiculos, "IDTipoVehiculo", "tipoVehiculodesc", publicacion.IDTipoVehiculo);
            return View(publicacion);
        }
        public static MidiData parse(FileStream input_file_stream)
        {
            var input_binary_reader = new BinaryReader(input_file_stream);

            HeaderChunk header_chunk;
            ushort number_of_tracks;
            {
                var header_chunk_ID = stringEncoder.GetString(input_binary_reader.ReadBytes(4));
                var header_chunk_size = BitConverter.ToInt32(input_binary_reader.ReadBytes(4).Reverse().ToArray<byte>(), 0);
                var header_chunk_data = input_binary_reader.ReadBytes(header_chunk_size);

                var format_type = BitConverter.ToUInt16(header_chunk_data.Take(2).Reverse().ToArray<byte>(), 0);
                number_of_tracks = BitConverter.ToUInt16(header_chunk_data.Skip(2).Take(2).Reverse().ToArray<byte>(), 0);
                var time_division = BitConverter.ToUInt16(header_chunk_data.Skip(4).Take(2).Reverse().ToArray<byte>(), 0);

                header_chunk = new HeaderChunk(format_type, time_division);
            }

            var tracks =
                Enumerable.Range(0, number_of_tracks)
                .Select(track_number =>
                {
                    var track_chunk_ID = stringEncoder.GetString(input_binary_reader.ReadBytes(4));
                    var track_chunk_size = BitConverter.ToInt32(input_binary_reader.ReadBytes(4).Reverse().ToArray<byte>(), 0);
                    var track_chunk_data = input_binary_reader.ReadBytes(track_chunk_size);

                    return Tuple.Create(track_chunk_size, track_chunk_data);
                }).ToList()
                .Select(raw_track => new TrackChunk(parse_events(raw_track.Item2, raw_track.Item1)));

            return new MidiData(header_chunk, tracks);
        }
Exemple #20
0
        private void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
                HttpWebResponse response;

                // End the get response operation
                response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
                System.IO.Stream streamResponse = response.GetResponseStream();

                System.IO.BinaryReader inputstream = new System.IO.BinaryReader(streamResponse);

                if (inputstream.BaseStream.Length > 0)
                {
                    byte[] responsebytes = new byte[inputstream.BaseStream.Length];
                    int totalRead = 0;
                    while (totalRead < inputstream.BaseStream.Length)
                    {
                        responsebytes[totalRead++] = inputstream.ReadByte();
                    }

                    ArraySegment<byte> raw = new ArraySegment<byte>(responsebytes, 0, totalRead);
                    PCOSMessageBase msg = PCOSMsgFactory.Parse(raw);

                    OnPingPongResponse(this, new PingPongEventArgs(msg));
                }
                streamResponse.Close();
                inputstream.Close();
                response.Close();
            }
            catch (WebException e)
            {
            }
        }
        public ActionResult Create([Bind(Include = "Id,Name,Description,Logo,IdEmpresa")] marca marca , List<HttpPostedFileBase> fileUpload)
        {
            if (ModelState.IsValid)
            {
                db.marcas.Add(marca);
                db.SaveChanges();
                int id = marca.Id;

                for (int i = 0; i < fileUpload.Count ; i++)
                {
                    imageMarca image = new imageMarca
                    {
                        Name = System.IO.Path.GetFileName(fileUpload[i].FileName),
                        IdMarca = id
                    };
                    using (var reader = new System.IO.BinaryReader(fileUpload[i].InputStream))
                    {
                        image.Imagen = reader.ReadBytes(fileUpload[i].ContentLength);
                        image.Id = marca.Id;
                        db.imageMarcas.Add(image);
                        db.SaveChanges();
                    }
                }
                    



                return RedirectToAction("Index");
            }

            ViewBag.IdEmpresa = new SelectList(db.empresas, "Id", "Name", marca.IdEmpresa);
            return View(marca);
        }
Exemple #22
0
        public ActionResult Create([Bind(Include = "JeepId,JeepName,ModelYear,Package,Model,Cylendars,Doors,color")] Jeep jeep, HttpPostedFileBase upload)
        {
            if (ModelState.IsValid)
            {
                if (upload != null && upload.ContentLength > 0)
                {
                    var avatar = new File
                    {
                        FileName = System.IO.Path.GetFileName(upload.FileName),
                        FileType = FileType.Avatar,
                        ContentType = upload.ContentType
                    };
                    using (var reader = new System.IO.BinaryReader(upload.InputStream))
                    {
                        avatar.Content = reader.ReadBytes(upload.ContentLength);
                    }
                    jeep.Files = new List<File> { avatar };
                }
                db.Jeeps.Add(jeep);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(jeep);
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     try
     {
         //if (this.Request.HttpMethod != "POST")
         //{
         //    this.Response.Write("Request method must be POST");
         //    return;
         //}
         // handle as image
         //string device = this.Request.Form["deviceid"].ToString();
         using (SmartCityEntities ctx = new SmartCityEntities())
         {
             SampledImage sImage = new SampledImage();
             sImage.device_id = Convert.ToInt32(this.Request.QueryString["device"]);
             sImage.image_timestamp = DateTime.Now;
             System.IO.BufferedStream bufRead = new System.IO.BufferedStream(this.Request.Files[0].InputStream);
             System.IO.BinaryReader binaryRead = new System.IO.BinaryReader(bufRead);
             sImage.imagesample = binaryRead.ReadBytes(this.Request.Files[0].ContentLength);
             ctx.SampledImage.Add(sImage);
             ctx.SaveChanges();
         }
         return;
     }
     catch (Exception ex)
     {
         this.Response.Write(ex.ToString());
         return;
     }
 }
Exemple #24
0
        public void Parse(Header header, byte[] data)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
            {
                using (System.IO.BinaryReader br = new System.IO.BinaryReader(ms))
                {
                    _authCode = br.ReadInt32();
                    _accountId = br.ReadUInt32();
                    _userLevel = br.ReadUInt32();
                    _lastLoginIP = br.ReadUInt32();
                    _lastLoginTime = br.ReadBytes(26);
                    _sex = br.ReadByte();

                    _serverList = new Dictionary<string, Server>();
                    for (int i = (int)ms.Position; i < header.Size; i += 32)
                    {
                        Server s = new Server();
                        s.IP = string.Format("{0}.{1}.{2}.{3}", br.ReadByte(), br.ReadByte(), br.ReadByte(), br.ReadByte());
                        s.Port = br.ReadInt16();
                        s.Name = br.ReadBytes(22).NullByteTerminatedString();
                        s.Type = br.ReadInt16();
                        s.UserCount = br.ReadInt16();
                        _serverList.Add(s.Name, s);
                    }
                }
            }
        }
        public ActionResult Create([Bind(Include = "SlideId,SlideLink,SlideDescription")] Slide slide, HttpPostedFileBase upload)
        {
            try {
                if (ModelState.IsValid)
                {
                    if (upload != null && upload.ContentLength > 0)
                    {
                        var img = new SlideImg
                        {
                            SlideImgName = System.IO.Path.GetFileName(upload.FileName),
                            FileType = FileType.Image,
                            SlideImgContentType = upload.ContentType
                        };
                        using (var reader = new System.IO.BinaryReader(upload.InputStream))
                        {
                            img.SlideImgContent = reader.ReadBytes(upload.ContentLength);
                        }
                        slide.SlideImg = new List<SlideImg> { img };
                    }
                    db.Slides.Add(slide);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }

                return View(slide);
            }
            catch (RetryLimitExceededException)
            {
                {
                    ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
                }
                return View(slide);
            }
        }
        public ActionResult ProfilePage(HttpPostedFileBase upload)
        {
            ViewBag.Message = "Your contact page.";
            string userid = User.Identity.GetUserId();
            var currentuser = db.Users.SingleOrDefault(u => u.Id == userid);

            if (upload != null && upload.ContentLength > 0)
            {
                if (currentuser.Files.Any(f => f.FileType == FileType.Avatar))
                {
                    db.Files.Remove(currentuser.Files.First(f => f.FileType == FileType.Avatar));
                }
                var avatar = new File
                {
                    FileName = System.IO.Path.GetFileName(upload.FileName),
                    FileType = FileType.Avatar,
                    ContentType = upload.ContentType
                };
                using (var reader = new System.IO.BinaryReader(upload.InputStream))
                {
                    avatar.Content = reader.ReadBytes(upload.ContentLength);
                }
                currentuser.Files = new List<File> { avatar };
            }

            db.Entry(currentuser).State = EntityState.Modified;
            db.SaveChanges();

            return View(currentuser);
        }
        protected void btnfileupload_Click(object sender, EventArgs e)
        {
            if (fileImage.HasFile)
            {
                System.IO.Stream fs = fileImage.PostedFile.InputStream;
                System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
                Byte[] bytesPhoto = br.ReadBytes((Int32)fs.Length);
                string base64String = Convert.ToBase64String(bytesPhoto, 0, bytesPhoto.Length);
                imgPhoto.ImageUrl = "data:image/png;base64," + base64String;
                imgPhoto.Visible = true;
                string fileName = fileImage.PostedFile.FileName;
                fileImage.SaveAs(Server.MapPath("~/Images/" + fileName));
                using (var db = new BadCostumesEntities ())
                {
                    var newCostume = new Costume();
                    newCostume.Participant = Request.QueryString["Participant"]; //this has to be the id
                    newCostume.ParticipantId = Convert.ToInt32( Request.QueryString["Participant"]); //this has to be the id
                    newCostume.Image = fileName;
                    newCostume.Votes = "1";
                    db.Costumes.Add(newCostume);
                    db.SaveChanges();
                }
                string gotourl = string.Format("~/SiteParticipant.aspx?Participant={0}", Request.QueryString["Participant"]);
                Response.Redirect(gotourl);

            }
        }
Exemple #28
0
        public void Populate(int iOffset, bool useMemoryStream)
        {
            this.isNulledOutReflexive = false;
            System.IO.BinaryReader BR = new System.IO.BinaryReader(map.SelectedMeta.MS);
            //set offsets
            BR.BaseStream.Position = iOffset + this.chunkOffset;
            this.offsetInMap = iOffset + this.chunkOffset;
            // If we need to read / save tag info directly to file...
            if (!useMemoryStream)
            {
                map.OpenMap(MapTypes.Internal);
                BR = map.BR;
                BR.BaseStream.Position = this.offsetInMap;
            }
            else
                this.offsetInMap += map.SelectedMeta.offset;

            if (this.entUnicode)
            {
                this.value = Encoding.Unicode.GetString(BR.ReadBytes(this.length));
            }
            else
            {
                this.value = new String(BR.ReadChars(this.length));
            }
            this.value = this.value.TrimEnd('\0');
            //this.RemoveNullCharFromValue();
            this.textBox1.Text = this.value;
            this.textBox1.Size = this.textBox1.PreferredSize;
            this.textBox1.Width += 5;

            // ...and then close the file once we are done!
            if (!useMemoryStream)
                map.CloseMap();
        }
Exemple #29
0
 ////////////////////////////////////////////////////////////////////////////
 //--------------------------------- REVISIONS ------------------------------
 // Date       Name                 Tracking #         Description
 // ---------  -------------------  -------------      ----------------------
 // 21JUN2009  James Shen                 	          Initial Creation
 ////////////////////////////////////////////////////////////////////////////
 /**
  * constructor.
  */
 protected Section(BinaryReader reader,
         long offset, long size)
 {
     this._offset = offset;
     this._reader = reader;
     this._size = size;
 }
		public UncompressedCollection(int imgWid, int imgHei, System.IO.Stream inFile, Palette pal)
		{
			System.IO.BinaryReader sr = new System.IO.BinaryReader(inFile);
			int i=0;
			while(sr.BaseStream.Position<sr.BaseStream.Length)
				Add(new XCImage(sr.ReadBytes(imgWid*imgHei),imgWid,imgHei,pal,i++));
		}
Exemple #31
0
        public override void Read(System.IO.BinaryReader br, int len, int[] blockSizes = null)
        {
            long p = br.BaseStream.Position;

            int OutlineID = br.ReadInt32();

            Debug.WriteLine(String.Format("Outline ID:{0:d}", OutlineID));

            int lt = 0x4, ct = 0x6, jt = 0x8, lw = 0xc, st = 0x10, ang = 0x14, varo = 0x1c, lc = 0x4c, dash = 0x68, arrw = 0x80;

            if (Parent.Version >= 13)
            {
                int flag = br.ReadInt32();
                int off  = 0;
                if (flag == 5)
                {
                    off = 107;
                }
                else if (Parent.Version >= 16)
                {
                    off = 51;
                }
                lt   = 0x18 + off;
                ct   = 0x1a + off;
                jt   = 0x1c + off;
                lw   = 0x1e + off;
                st   = 0x22 + off;
                ang  = 0x24 + off;
                varo = 0x28 + off;
                lc   = 0x58 + off;
                dash = 0x74 + off;
                arrw = 0x8a + off;
            }
            else if (Parent.Version < 6)
            {
                lw   = 0xa;
                st   = 0xc;
                ang  = 0xe;
                lc   = 0x10;
                dash = 0x26;
            }
            br.BaseStream.Position = p + lt;
            short  ltype = br.ReadInt16();
            String ltxt  = "Non-scalable";

            if ((ltype & 0x20) == 0x20)
            {
                ltxt = "Scalable";
            }
            if ((ltype & 0x10) == 0x10)
            {
                ltxt += ", Behind fill";
            }
            if ((ltype & 0x80) == 0x80)
            {
                ltxt += ", Share Attrs";
            }
            if ((ltype & 0x4) == 0x4)
            {
                ltxt += ", Dashed";
            }

            Debug.WriteLine(String.Format("Line Type {0:d} {1:s}", ltype, ltxt));
            br.BaseStream.Position = p + ct;
            Debug.WriteLine(String.Format("Caps Type {0:d}", br.ReadByte()));
            br.BaseStream.Position = p + jt;
            Debug.WriteLine(String.Format("Join Type {0:d}", br.ReadByte()));
            br.BaseStream.Position = p + lw;
            Debug.WriteLine(String.Format("LineWidth {0:f}", br.ReadInt32() / 10000.0));

            br.BaseStream.Position = p;
            base.Read(br, len, blockSizes);
        }
Exemple #32
0
        public static JSONNode Deserialize(System.IO.BinaryReader aReader)
        {
            JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();

            switch (type)
            {
            case JSONBinaryTag.Array:
            {
                int       count = aReader.ReadInt32();
                JSONArray tmp   = new JSONArray();
                for (int i = 0; i < count; i++)
                {
                    tmp.Add(Deserialize(aReader));
                }
                return(tmp);
            }

            case JSONBinaryTag.Class:
            {
                int       count = aReader.ReadInt32();
                JSONClass tmp   = new JSONClass();
                for (int i = 0; i < count; i++)
                {
                    string key = aReader.ReadString();
                    var    val = Deserialize(aReader);
                    tmp.Add(key, val);
                }
                return(tmp);
            }

            case JSONBinaryTag.Value:
            {
                return(new JSONData(aReader.ReadString()));
            }

            case JSONBinaryTag.IntValue:
            {
                return(new JSONData(aReader.ReadInt32()));
            }

            case JSONBinaryTag.DoubleValue:
            {
                return(new JSONData(aReader.ReadDouble()));
            }

            case JSONBinaryTag.BoolValue:
            {
                return(new JSONData(aReader.ReadBoolean()));
            }

            case JSONBinaryTag.FloatValue:
            {
                return(new JSONData(aReader.ReadSingle()));
            }

            default:
            {
                throw new Exception("Error deserializing JSON. Unknown tag: " + type);
            }
            }
        }
Exemple #33
0
 //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'"
 public override void  readExternal(System.IO.BinaryReader in_Renamed, PrototypeFactory pf)
 {
     a = (XPathExpression)ExtUtil.read(in_Renamed, new ExtWrapTagged(), pf);
 }
Exemple #34
0
 public Float2(System.IO.BinaryReader br)
 {
     x = br.ReadSingle();
     y = br.ReadSingle();
 }
Exemple #35
0
 public override void LoadState(System.IO.BinaryReader stream)
 {
     base.LoadState(stream);
     stream.Read(RAM, 0, RAM.Length);
 }
 public void Read(System.IO.BinaryReader r)
 {
     sb = new StringBuilder();
     sb.Append(r.ReadString());
 }
Exemple #37
0
 public override void ReceiveExtraAI(System.IO.BinaryReader reader)
 {
     this.target = reader.Read();
 }
Exemple #38
0
        public ActionResult SurveyFeedbackForm(FormCollection formCollection)
        {
            using (MovingTacticsEntities db = new MovingTacticsEntities())
            {
                int ResponseID       = 0;
                int SurveyResponseId = 0;
                var x = Request.Form["SurveyId"];//Getting Survey Id from the form hidden field.

                #region Survey Responses
                SurveyResponses surveyResponses = new SurveyResponses
                {
                    SurveyId    = Int32.Parse(x.ToString()),
                    MemberId    = GlobalMTHelper.GetMemberId(),
                    DateCreated = DateTime.Now.ToLongDateString(),
                    TimeCreated = DateTime.Now.ToLongTimeString(),
                };

                db.SurveyResponses.Add(surveyResponses);
                db.SaveChanges();
                SurveyResponseId = surveyResponses.SurveyResponseId;
                #endregion

                for (int i = 1; i < formCollection.Keys.Count; i++)
                {
                    #region Getting Values for each question in the form collection and taking them one by one
                    var formTest = formCollection.GetValues(i);
                    var formKey  = formCollection.GetKey(i);
                    //string value = formCollection[i];
                    //string[] variable = value.Split(',');
                    #endregion

                    #region Check If theres a comment value in Array
                    var option = formTest.Count() > 1 ? formTest[1].ToString() == string.Empty ? null : formTest[1].ToString() : null;
                    #endregion

                    #region Storing the responses for each question
                    Response response = new Response
                    {
                        QuestionId       = Convert.ToInt32(formKey),
                        MemberId         = GlobalMTHelper.GetMemberId(),
                        SurveyId         = Int32.Parse(x.ToString()),
                        ResponseValue    = formTest[0].ToString(),
                        Comment          = option,
                        YesQuestionCount = 10,
                        DateCreated      = DateTime.Now.ToLongDateString(),
                        SurveyResponseId = SurveyResponseId
                    };
                    db.Responses.Add(response);
                    db.SaveChanges();
                    ResponseID = response.ResponseId;
                    #endregion

                    #region Checking File count According to question
                    var FileCount  = Request.Files.GetMultiple(formKey).Count();
                    var CheckFiles = Request.Files.GetMultiple(formKey);
                    #endregion

                    #region Media
                    // the count of the files and looping it
                    for (int v = 0; v < FileCount; v++)
                    {
                        //going through each file and checking if its null
                        var file = CheckFiles[v];
                        if (file != null && file.ContentLength > 0)
                        {
                            #region Saving media files for each response question
                            SurveyMedia media = new SurveyMedia
                            {
                                QuestionId  = Convert.ToInt32(formKey),
                                MemberId    = GlobalMTHelper.GetMemberId(),
                                SurveyId    = Int32.Parse(x.ToString()),
                                ResponseId  = ResponseID,
                                DateCreated = DateTime.Now.ToLongDateString()
                            };

                            using (var reader = new System.IO.BinaryReader(file.InputStream))
                            {
                                media.MediaContent = reader.ReadBytes(file.ContentLength);
                            }

                            db.SurveyMedias.Add(media);
                            db.SaveChanges();
                            #endregion
                        }
                    }
                    #endregion
                }
                return(RedirectToAction("Index"));
            }
        }
Exemple #39
0
 protected override void Read(uint Length, System.IO.BinaryReader Reader, ConstantPool Pool)
 {
     Value = Pool[Reader.ReadUInt16BE()];
 }
Exemple #40
0
 internal override void Read(System.IO.BinaryReader reader)
 {
     throw new NotImplementedException();
 }
Exemple #41
0
 protected override void DecoderData(System.IO.BinaryReader br)
 {
 }
Exemple #42
0
        public static int Load(string path)
        {
            var LoadedEntries = new Dictionary <ulong, byte[]>();
            var count         = 0;

            using (var fl = new System.IO.BinaryReader(System.IO.File.Open(path, System.IO.FileMode.Open)))
            {
                long pos = 0;
                var  len = fl.BaseStream.Length;
                while (pos != len)
                {
                    var thisEntry = FromByteArray <OffsetEntry>(fl.ReadBytes(OffsetEntrySize));
                    LoadedEntries[thisEntry.KeyHash] = fl.ReadBytes(thisEntry.Capacity);
                    pos += OffsetEntrySize + thisEntry.Capacity;
                    count++;
                }
            }
            using (new CustomMutex(650))
            {
                using (var strm = MMFile.CreateViewAccessor())
                {
                    var       signature      = strm.ReadInt32(0);
                    const int startingOffset = 2 * sizeof(int);
                    int       currentOffset;
                    if (signature == 0x34CFABC0)
                    {
                        currentOffset = strm.ReadInt32(sizeof(int));
                    }
                    else
                    {
                        strm.Write(0, 0x34CFABC0);
                        strm.Write(sizeof(int), startingOffset);
                        currentOffset = startingOffset;
                    }
                    var thisOffset = startingOffset;
                    while (thisOffset != currentOffset)
                    {
                        var buff = new byte[OffsetEntrySize];
                        strm.ReadArray(thisOffset, buff, 0, OffsetEntrySize);
                        var entry = FromByteArray <OffsetEntry>(buff);
                        if (entry.Type != EntryType.Invalid && LoadedEntries.ContainsKey(entry.KeyHash))
                        {
                            if (LoadedEntries[entry.KeyHash].Length <= entry.Capacity)
                            {
                                strm.WriteArray(
                                    thisOffset + OffsetEntrySize, LoadedEntries[entry.KeyHash], 0,
                                    LoadedEntries[entry.KeyHash].Length <= entry.Capacity
                                        ? LoadedEntries[entry.KeyHash].Length
                                        : entry.Capacity);
                                LoadedEntries.Remove(entry.KeyHash);
                            }
                            else
                            {
                                var overwriteEntry = entry;
                                overwriteEntry.Type = EntryType.Invalid;
                                strm.WriteArray(
                                    thisOffset, ToByteArray(overwriteEntry, OffsetEntrySize), 0, OffsetEntrySize);
                            }
                        }
                        thisOffset += OffsetEntrySize + entry.Capacity;
                    }

                    foreach (var needtoload in LoadedEntries)
                    {
                        OffsetEntry newEntry;
                        newEntry.KeyHash  = needtoload.Key;
                        newEntry.Capacity = needtoload.Value.Length;
                        newEntry.Type     = EntryType.Basic;
                        strm.WriteArray(currentOffset, ToByteArray(newEntry, OffsetEntrySize), 0, OffsetEntrySize);
                        strm.WriteArray(currentOffset + OffsetEntrySize, needtoload.Value, 0, newEntry.Capacity);
                        strm.Write(sizeof(int), currentOffset + OffsetEntrySize + newEntry.Capacity);
                    }
                }
            }
            return(count);
        }
Exemple #43
0
 private ByteBuffer()
 {
     stream = new System.IO.MemoryStream();
     reader = new System.IO.BinaryReader(stream);
     writer = new System.IO.BinaryWriter(stream);
 }
Exemple #44
0
        public Texture2D(AssetPreloadData preloadData, bool readSwitch)
        {
            var sourceFile = preloadData.sourceFile;
            var a_Stream   = preloadData.sourceFile.a_Stream;

            a_Stream.Position = preloadData.Offset;

            if (sourceFile.platform == -2)
            {
                a_Stream.ReadUInt32();
                sourceFile.ReadPPtr();
                sourceFile.ReadPPtr();
            }

            m_Name              = a_Stream.ReadAlignedString(a_Stream.ReadInt32());
            m_Width             = a_Stream.ReadInt32();
            m_Height            = a_Stream.ReadInt32();
            m_CompleteImageSize = a_Stream.ReadInt32();
            m_TextureFormat     = a_Stream.ReadInt32();

            if (sourceFile.version[0] < 5 || (sourceFile.version[0] == 5 && sourceFile.version[1] < 2))
            {
                m_MipMap = a_Stream.ReadBoolean();
            }
            else
            {
                dwFlags      += 0x20000;
                dwMipMapCount = a_Stream.ReadInt32();//is this with or without main image?
                dwCaps       += 0x400008;
            }

            m_IsReadable  = a_Stream.ReadBoolean(); //2.6.0 and up
            m_ReadAllowed = a_Stream.ReadBoolean(); //3.0.0 and up
            a_Stream.AlignStream(4);

            m_ImageCount       = a_Stream.ReadInt32();
            m_TextureDimension = a_Stream.ReadInt32();
            //m_TextureSettings
            m_FilterMode = a_Stream.ReadInt32();
            m_Aniso      = a_Stream.ReadInt32();
            m_MipBias    = a_Stream.ReadSingle();
            m_WrapMode   = a_Stream.ReadInt32();

            if (sourceFile.version[0] >= 3)
            {
                m_LightmapFormat = a_Stream.ReadInt32();
                if (sourceFile.version[0] >= 4 || sourceFile.version[1] >= 5)
                {
                    m_ColorSpace = a_Stream.ReadInt32();
                }                                                                                                      //3.5.0 and up
            }

            image_data_size = a_Stream.ReadInt32();

            if (image_data_size == 0 && sourceFile.version[0] >= 5 && sourceFile.version[1] >= 3)
            {
                m_offset        = a_Stream.ReadInt32();
                image_data_size = a_Stream.ReadInt32();
                int resourceFileNameSize = a_Stream.ReadInt32();
                m_source = a_Stream.ReadAlignedString(resourceFileNameSize);
                m_source = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(sourceFile.filePath), m_source);
            }

            if (m_MipMap)
            {
                dwFlags      += 0x20000;
                dwMipMapCount = Convert.ToInt32(Math.Log(Math.Max(m_Width, m_Height)) / Math.Log(2));
                dwCaps       += 0x400008;
            }

            if (readSwitch)
            {
                image_data = new byte[image_data_size];

                if (m_source == null)
                {
                    a_Stream.Read(image_data, 0, image_data_size);
                }
                else if (System.IO.File.Exists(m_source))
                {
                    image_data = new byte[image_data_size];
                    using (System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.OpenRead(m_source)))
                    {
                        reader.BaseStream.Position = m_offset;
                        reader.Read(image_data, 0, image_data_size);
                        reader.Close();
                    }
                }

                switch (m_TextureFormat)
                {
                case 1:     //Alpha8
                {
                    dwFlags2      = 0x2;
                    dwRGBBitCount = 0x8;
                    dwRBitMask    = 0x0;
                    dwGBitMask    = 0x0;
                    dwBBitMask    = 0x0;
                    dwABitMask    = 0xFF;
                    break;
                }

                case 2:                            //A4R4G4B4
                {
                    if (sourceFile.platform == 11) //swap bytes for Xbox confirmed, PS3 not encountered
                    {
                        for (int i = 0; i < (image_data_size / 2); i++)
                        {
                            byte b0 = image_data[i * 2];
                            image_data[i * 2]     = image_data[i * 2 + 1];
                            image_data[i * 2 + 1] = b0;
                        }
                    }
                    else if (sourceFile.platform == 13)         //swap bits for android
                    {
                        for (int i = 0; i < (image_data_size / 2); i++)
                        {
                            byte[] argb = BitConverter.GetBytes((BitConverter.ToInt32((new byte[4] {
                                    image_data[i * 2], image_data[i * 2 + 1], image_data[i * 2], image_data[i * 2 + 1]
                                }), 0)) >> 4);
                            image_data[i * 2]     = argb[0];
                            image_data[i * 2 + 1] = argb[1];
                        }
                    }

                    dwFlags2      = 0x41;
                    dwRGBBitCount = 0x10;
                    dwRBitMask    = 0xF00;
                    dwGBitMask    = 0xF0;
                    dwBBitMask    = 0xF;
                    dwABitMask    = 0xF000;
                    break;
                }

                case 3:     //B8G8R8 //confirmed on X360, iOS //PS3 unsure
                {
                    for (int i = 0; i < (image_data_size / 3); i++)
                    {
                        byte b0 = image_data[i * 3];
                        image_data[i * 3] = image_data[i * 3 + 2];
                        //image_data[i * 3 + 1] stays the same
                        image_data[i * 3 + 2] = b0;
                    }

                    dwFlags2      = 0x40;
                    dwRGBBitCount = 0x18;
                    dwRBitMask    = 0xFF0000;
                    dwGBitMask    = 0xFF00;
                    dwBBitMask    = 0xFF;
                    dwABitMask    = 0x0;
                    break;
                }

                case 4:     //G8R8A8B8 //confirmed on X360, iOS
                {
                    for (int i = 0; i < (image_data_size / 4); i++)
                    {
                        byte b0 = image_data[i * 4];
                        image_data[i * 4] = image_data[i * 4 + 2];
                        //image_data[i * 4 + 1] stays the same
                        image_data[i * 4 + 2] = b0;
                        //image_data[i * 4 + 3] stays the same
                    }

                    dwFlags2      = 0x41;
                    dwRGBBitCount = 0x20;
                    dwRBitMask    = 0xFF0000;
                    dwGBitMask    = 0xFF00;
                    dwBBitMask    = 0xFF;
                    dwABitMask    = -16777216;
                    break;
                }

                case 5:     //B8G8R8A8 //confirmed on X360, PS3, Web, iOS
                {
                    for (int i = 0; i < (image_data_size / 4); i++)
                    {
                        byte b0 = image_data[i * 4];
                        byte b1 = image_data[i * 4 + 1];
                        image_data[i * 4]     = image_data[i * 4 + 3];
                        image_data[i * 4 + 1] = image_data[i * 4 + 2];
                        image_data[i * 4 + 2] = b1;
                        image_data[i * 4 + 3] = b0;
                    }

                    dwFlags2      = 0x41;
                    dwRGBBitCount = 0x20;
                    dwRBitMask    = 0xFF0000;
                    dwGBitMask    = 0xFF00;
                    dwBBitMask    = 0xFF;
                    dwABitMask    = -16777216;
                    break;
                }

                case 7:     //R5G6B5 //confirmed switched on X360; confirmed on iOS
                {
                    if (sourceFile.platform == 11)
                    {
                        for (int i = 0; i < (image_data_size / 2); i++)
                        {
                            byte b0 = image_data[i * 2];
                            image_data[i * 2]     = image_data[i * 2 + 1];
                            image_data[i * 2 + 1] = b0;
                        }
                    }

                    dwFlags2      = 0x40;
                    dwRGBBitCount = 0x10;
                    dwRBitMask    = 0xF800;
                    dwGBitMask    = 0x7E0;
                    dwBBitMask    = 0x1F;
                    dwABitMask    = 0x0;
                    break;
                }

                case 10:                           //DXT1
                {
                    if (sourceFile.platform == 11) //X360 only, PS3 not
                    {
                        for (int i = 0; i < (image_data_size / 2); i++)
                        {
                            byte b0 = image_data[i * 2];
                            image_data[i * 2]     = image_data[i * 2 + 1];
                            image_data[i * 2 + 1] = b0;
                        }
                    }

                    if (m_MipMap)
                    {
                        dwPitchOrLinearSize = m_Height * m_Width / 2;
                    }
                    dwFlags2      = 0x4;
                    dwFourCC      = 0x31545844;
                    dwRGBBitCount = 0x0;
                    dwRBitMask    = 0x0;
                    dwGBitMask    = 0x0;
                    dwBBitMask    = 0x0;
                    dwABitMask    = 0x0;
                    break;
                }

                case 12:                           //DXT5
                {
                    if (sourceFile.platform == 11) //X360, PS3 not
                    {
                        for (int i = 0; i < (image_data_size / 2); i++)
                        {
                            byte b0 = image_data[i * 2];
                            image_data[i * 2]     = image_data[i * 2 + 1];
                            image_data[i * 2 + 1] = b0;
                        }
                    }

                    if (m_MipMap)
                    {
                        dwPitchOrLinearSize = m_Height * m_Width / 2;
                    }
                    dwFlags2      = 0x4;
                    dwFourCC      = 0x35545844;
                    dwRGBBitCount = 0x0;
                    dwRBitMask    = 0x0;
                    dwGBitMask    = 0x0;
                    dwBBitMask    = 0x0;
                    dwABitMask    = 0x0;
                    break;
                }

                case 13:     //R4G4B4A4, iOS (only?)
                {
                    for (int i = 0; i < (image_data_size / 2); i++)
                    {
                        byte[] argb = BitConverter.GetBytes((BitConverter.ToInt32((new byte[4] {
                                image_data[i * 2], image_data[i * 2 + 1], image_data[i * 2], image_data[i * 2 + 1]
                            }), 0)) >> 4);
                        image_data[i * 2]     = argb[0];
                        image_data[i * 2 + 1] = argb[1];
                    }

                    dwFlags2      = 0x41;
                    dwRGBBitCount = 0x10;
                    dwRBitMask    = 0xF00;
                    dwGBitMask    = 0xF0;
                    dwBBitMask    = 0xF;
                    dwABitMask    = 0xF000;
                    break;
                }

                case 28:     //DXT1 Crunched
                case 29:     //DXT1 Crunched
                    break;

                case 30:     //PVRTC_RGB2
                {
                    pvrPixelFormat = 0x0;
                    break;
                }

                case 31:     //PVRTC_RGBA2
                {
                    pvrPixelFormat = 0x1;
                    break;
                }

                case 32:     //PVRTC_RGB4
                {
                    pvrPixelFormat = 0x2;
                    break;
                }

                case 33:     //PVRTC_RGBA4
                {
                    pvrPixelFormat = 0x3;
                    break;
                }

                case 34:     //ETC_RGB4
                {
                    pvrPixelFormat = 0x16;
                    break;
                }

                case 47:     //ETC2_RGBA8
                {
                    pvrPixelFormat = 0x17;
                    break;
                }
                }
            }
            else
            {
                preloadData.InfoText   = "Width: " + m_Width.ToString() + "\nHeight: " + m_Height.ToString() + "\nFormat: ";
                preloadData.exportSize = image_data_size;

                switch (m_TextureFormat)
                {
                case 1: preloadData.InfoText += "Alpha8"; preloadData.extension = ".dds"; preloadData.exportSize += 128; break;

                case 2: preloadData.InfoText += "ARGB 4.4.4.4"; preloadData.extension = ".dds"; preloadData.exportSize += 128; break;

                case 3: preloadData.InfoText += "BGR 8.8.8"; preloadData.extension = ".dds"; preloadData.exportSize += 128; break;

                case 4: preloadData.InfoText += "GRAB 8.8.8.8"; preloadData.extension = ".dds"; preloadData.exportSize += 128; break;

                case 5: preloadData.InfoText += "BGRA 8.8.8.8"; preloadData.extension = ".dds"; preloadData.exportSize += 128; break;

                case 7: preloadData.InfoText += "RGB 5.6.5"; preloadData.extension = ".dds"; preloadData.exportSize += 128; break;

                case 10: preloadData.InfoText += "DXT1"; preloadData.extension = ".dds"; preloadData.exportSize += 128; break;

                case 12: preloadData.InfoText += "DXT5"; preloadData.extension = ".dds"; preloadData.exportSize += 128; break;

                case 13: preloadData.InfoText += "RGBA 4.4.4.4"; preloadData.extension = ".dds"; preloadData.exportSize += 128; break;

                case 28: preloadData.InfoText += "DXT1 Crunched"; preloadData.extension = ".crn"; break;

                case 29: preloadData.InfoText += "DXT5 Crunched"; preloadData.extension = ".crn"; break;

                case 30: preloadData.InfoText += "PVRTC_RGB2"; preloadData.extension = ".pvr"; preloadData.exportSize += 52; break;

                case 31: preloadData.InfoText += "PVRTC_RGBA2"; preloadData.extension = ".pvr"; preloadData.exportSize += 52; break;

                case 32: preloadData.InfoText += "PVRTC_RGB4"; preloadData.extension = ".pvr"; preloadData.exportSize += 52; break;

                case 33: preloadData.InfoText += "PVRTC_RGBA4"; preloadData.extension = ".pvr"; preloadData.exportSize += 52; break;

                case 34: preloadData.InfoText += "ETC_RGB4"; preloadData.extension = ".pvr"; preloadData.exportSize += 52; break;

                case 47: preloadData.InfoText += "ETC2_RGB8"; preloadData.extension = ".pvr"; preloadData.exportSize += 52; break;

                default: preloadData.InfoText += "unknown"; preloadData.extension = ".tex"; break;
                }

                switch (m_FilterMode)
                {
                case 0: preloadData.InfoText += "\nFilter Mode: Point "; break;

                case 1: preloadData.InfoText += "\nFilter Mode: Bilinear "; break;

                case 2: preloadData.InfoText += "\nFilter Mode: Trilinear "; break;
                }

                preloadData.InfoText += "\nAnisotropic level: " + m_Aniso.ToString() + "\nMip map bias: " + m_MipBias.ToString();

                switch (m_WrapMode)
                {
                case 0: preloadData.InfoText += "\nWrap mode: Repeat"; break;

                case 1: preloadData.InfoText += "\nWrap mode: Clamp"; break;
                }

                if (m_Name != "")
                {
                    preloadData.Text = m_Name;
                }
                else
                {
                    preloadData.Text = preloadData.TypeString + " #" + preloadData.uniqueID;
                }
                preloadData.subItems.AddRange(new string[] { preloadData.TypeString, preloadData.exportSize.ToString() });
            }
        }
Exemple #45
0
 //UPGRADE_TODO: Class 'java.io.DataInputStream' was converted to 'System.IO.BinaryReader' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataInputStream'"
 public virtual void  readExternal(System.IO.BinaryReader in_Renamed, PrototypeFactory pf)
 {
     Value = ExtUtil.readDate(in_Renamed);
 }
Exemple #46
0
 internal void BinaryReaderRead(System.IO.BinaryReader br)
 {
     FrameCount = br.ReadInt16();
     AngleCount = br.ReadInt16();
     ShapeId    = br.ReadInt16();
 }
Exemple #47
0
        /// <summary>
        /// Unserializes a BinaryStream into the Attributes of this Instance
        /// </summary>
        /// <param name="reader">The Stream that contains the FileData</param>
        protected void UnserializeXml(System.IO.BinaryReader reader)
        {
            reader.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
            System.IO.StreamReader sr = new System.IO.StreamReader(reader.BaseStream);
            string s = sr.ReadToEnd();

            s = s.Replace("& ", "&amp; ");
            System.IO.StringReader strr    = new System.IO.StringReader(s);
            System.Xml.XmlDocument xmlfile = new XmlDocument();
            xmlfile.Load(strr);

            XmlNodeList XMLData = xmlfile.GetElementsByTagName("cGZPropertySetString");
            ArrayList   list    = new ArrayList();

            //Process all Root Node Entries
            for (int i = 0; i < XMLData.Count; i++)
            {
                XmlNode node = XMLData.Item(i);

                foreach (XmlNode subnode in node)
                {
                    CpfItem item = new CpfItem();

                    if (subnode.LocalName.Trim().ToLower() == "anyuint32")
                    {
                        item.Datatype = Data.MetaData.DataTypes.dtUInteger;
                        if (subnode.InnerText.IndexOf("-") != -1)
                        {
                            item.UIntegerValue = (uint)Convert.ToInt32(subnode.InnerText);
                        }
                        else if (subnode.InnerText.IndexOf("0x") == -1)
                        {
                            item.UIntegerValue = Convert.ToUInt32(subnode.InnerText);
                        }
                        else
                        {
                            item.UIntegerValue = Convert.ToUInt32(subnode.InnerText, 16);
                        }
                    }
                    else if ((subnode.LocalName.Trim().ToLower() == "anyint32") || (subnode.LocalName.Trim().ToLower() == "anysint32"))
                    {
                        item.Datatype = Data.MetaData.DataTypes.dtInteger;
                        if (subnode.InnerText.IndexOf("0x") == -1)
                        {
                            item.IntegerValue = Convert.ToInt32(subnode.InnerText);
                        }
                        else
                        {
                            item.IntegerValue = Convert.ToInt32(subnode.InnerText, 16);
                        }
                    }
                    else if (subnode.LocalName.Trim().ToLower() == "anystring")
                    {
                        item.Datatype    = Data.MetaData.DataTypes.dtString;
                        item.StringValue = subnode.InnerText;
                    }
                    else if (subnode.LocalName.Trim().ToLower() == "anyfloat32")
                    {
                        item.Datatype    = Data.MetaData.DataTypes.dtSingle;
                        item.SingleValue = Convert.ToSingle(subnode.InnerText, System.Globalization.CultureInfo.InvariantCulture);
                    }
                    else if (subnode.LocalName.Trim().ToLower() == "anyboolean")
                    {
                        item.Datatype = Data.MetaData.DataTypes.dtBoolean;
                        if (subnode.InnerText.Trim().ToLower() == "true")
                        {
                            item.BooleanValue = true;
                        }
                        else if (subnode.InnerText.Trim().ToLower() == "false")
                        {
                            item.BooleanValue = false;
                        }
                        else
                        {
                            item.BooleanValue = (Convert.ToInt32(subnode.InnerText) != 0);
                        }
                    }
                    else if (subnode.LocalName.Trim().ToLower() == "#comment")
                    {
                        continue;
                    }

                    /*else
                     * {
                     *      item.Datatype = (Data.MetaData.DataTypes)Convert.ToUInt32(subnode.Attributes["type"].Value, 16);
                     * }*/

                    try
                    {
                        item.Name = subnode.Attributes["key"].Value;
                        list.Add(item);
                    }
                    catch {}
                }
            }            //for i

            items = new CpfItem[list.Count];
            list.CopyTo(items);
        }
Exemple #48
0
 public static JSONNode LoadFromStream(System.IO.Stream aData)
 {
     using (var R = new System.IO.BinaryReader(aData)) {
         return(Deserialize(R));
     }
 }
Exemple #49
0
 public void Deserialize(System.IO.BinaryReader br, short command)
 {
     X = br.ReadSingle();
     Y = br.ReadSingle();
 }
        protected override void DataUpdate()
        {
            System.IO.BinaryReader BSReader = new System.IO.BinaryReader(ByteStream);
            ByteStream.Position = 0;
            SubModels           = BSReader.ReadInt32();
            SubModel            = new _SubModel[SubModels];

            for (int i = 0; i < SubModels; i++)
            {
                _SubModel withBlock = SubModel[i];
                withBlock.Vertexes  = BSReader.ReadInt32();
                withBlock.BlockSize = BSReader.ReadUInt32();
                withBlock.k         = BSReader.ReadUInt16();
                withBlock.c         = BSReader.ReadUInt16();
                int cnt, offset;
                cnt                 = 0;
                offset              = (int)ByteStream.Position;
                withBlock.Null1     = BSReader.ReadUInt32();
                withBlock.Something = BSReader.ReadUInt32();
                withBlock.Null2     = BSReader.ReadUInt32();
                while ((cnt < withBlock.Vertexes) && (ByteStream.Position < offset + withBlock.BlockSize))
                {
                    var withBlock1 = new _Group();
                    Array.Resize(ref withBlock1.UV, 0);
                    Array.Resize(ref withBlock1.Shit, 0);
                    withBlock1.SomeNum1 = BSReader.ReadUInt32();
                    withBlock1.Vertexes = BSReader.ReadByte();
                    cnt += withBlock1.Vertexes;
                    withBlock1.Some80h    = BSReader.ReadByte();
                    withBlock1.Null1      = BSReader.ReadUInt16();
                    withBlock1.SomeNum2   = BSReader.ReadUInt32();
                    withBlock1.SomeNum3   = BSReader.ReadUInt32();
                    withBlock1.Null2      = BSReader.ReadUInt32();
                    withBlock1.Signature1 = BSReader.ReadUInt32();
                    withBlock1.SomeShit1  = BSReader.ReadUInt32();
                    withBlock1.SomeShit2  = BSReader.ReadUInt32();
                    withBlock1.SomeShit3  = BSReader.ReadUInt32();
                    withBlock1.Signature2 = BSReader.ReadUInt32();
                    uint head = BSReader.ReadUInt32();
                    while (head != 335544320)
                    {
                        switch (head & 255)
                        {
                        case 3:
                        {
                            withBlock1.VertHead = head;
                            withBlock1.Vertex   = new Position3[withBlock1.Vertexes];
                            for (int j = 0; j <= withBlock1.Vertexes - 1; j++)
                            {
                                withBlock1.Vertex[j].X = BSReader.ReadSingle();
                                withBlock1.Vertex[j].Y = BSReader.ReadSingle();
                                withBlock1.Vertex[j].Z = BSReader.ReadSingle();
                            }

                            break;
                        }

                        case 4:
                        {
                            withBlock1.WeightHead = head;
                            withBlock1.Weight     = new _Weight[withBlock1.Vertexes];
                            for (int j = 0; j <= withBlock1.Vertexes - 1; j++)
                            {
                                withBlock1.Weight[j].X        = BSReader.ReadSingle();
                                withBlock1.Weight[j].Y        = BSReader.ReadSingle();
                                withBlock1.Weight[j].Z        = BSReader.ReadSingle();
                                withBlock1.Weight[j].SomeByte = BSReader.ReadByte();
                                withBlock1.Weight[j].CONN     = BSReader.ReadByte();
                                withBlock1.Weight[j].Null1    = BSReader.ReadUInt16();
                            }

                            break;
                        }

                        case 5:
                        {
                            withBlock1.UVHead = head;
                            withBlock1.UV     = new Position3[withBlock1.Vertexes];
                            for (int j = 0; j <= withBlock1.Vertexes - 1; j++)
                            {
                                withBlock1.UV[j].X = BSReader.ReadSingle();
                                withBlock1.UV[j].Y = BSReader.ReadSingle();
                                withBlock1.UV[j].Z = BSReader.ReadSingle();
                            }

                            break;
                        }

                        case 6:
                        {
                            withBlock1.ShiteHead = head;
                            withBlock1.Shit      = new uint[withBlock1.Vertexes];
                            for (int j = 0; j <= withBlock1.Vertexes - 1; j++)
                            {
                                withBlock1.Shit[j] = BSReader.ReadUInt32();
                            }
                            break;
                        }
                        }
                        head = BSReader.ReadUInt32();
                    }
                    withBlock1.EndSignature1 = head;
                    withBlock1.EndSignature2 = BSReader.ReadUInt32();
                    withBlock1.leftovers     = new byte[] { };
                    _Groups.Add(withBlock1);
                }
                withBlock.Group = _Groups.ToArray();
                Array.Resize(ref withBlock.Group[withBlock.Group.Length - 1].leftovers, (int)(withBlock.BlockSize + offset - ByteStream.Position));
                withBlock.Group[withBlock.Group.Length - 1].leftovers = BSReader.ReadBytes((int)(withBlock.BlockSize + offset - ByteStream.Position));

                SubModel[i] = withBlock;
            }
            _Groups.Clear();
        }
Exemple #51
0
        private void ListenThreadEntrypoint()
        {
            System.IO.MemoryStream ms     = new System.IO.MemoryStream();
            System.IO.BinaryReader reader = new System.IO.BinaryReader(ms);
            try
            {
                this.ClientConnection         = new TcpClient(this.Host, this.Port);
                this.ClientConnection.NoDelay = true;

                lock (StateSyncObject)
                    Writer = new System.IO.BinaryWriter(this.ClientConnection.GetStream());

                //Thread.Sleep(3000);

                SendPacket(new PacketHeader(0, PayloadType.ClientConnection), new ClientConnectionPayload(ClientConnectionPayload.CurrentVersionMajor, ClientConnectionPayload.CurrentVersionMinor));
                int read = 1;
                while (read > 0)
                {
                    ms.SetLength(4);
                    ms.Position = 0;
                    while (ms.Position < 4)
                    {
                        read         = this.ClientConnection.GetStream().Read(ms.GetBuffer(), (int)ms.Position, (int)ms.Length - (int)ms.Position);
                        ms.Position += read;
                        if (read <= 0)
                        {
                            break;
                        }
                    }
                    if (read <= 0)
                    {
                        break;
                    }

                    //ms.SetLength(read);
                    ms.Position = 0;
                    PacketHeader header = new PacketHeader(reader);
                    ms.Position = 0;

                    if (header.PayloadLength > 0)
                    {
                        ms.SetLength(header.PayloadLength);
                        while (ms.Position < header.PayloadLength)
                        {
                            read         = this.ClientConnection.GetStream().Read(ms.GetBuffer(), (int)ms.Position, (int)ms.Length - (int)ms.Position);
                            ms.Position += read;
                            if (read <= 0)
                            {
                                break;
                            }
                        }
                        ms.Position = 0;
                        if (read <= 0)
                        {
                            break;
                        }
                    }

                    if (header.Type == PayloadType.ServerDisconnect)
                    {
                        break;
                    }
                    else
                    {
                        HandlePacket(header, reader);
                    }
                    ms.Position = 0;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception in ListenThreadEntrypoint: " + ex.ToString());
            }
            if (!this.IsConnected)
            {
                this.ConnectedEvent.Set();
            }
            this.ClientConnection?.Close();
            this.ClientConnection?.Dispose();
            System.Diagnostics.Debug.WriteLine("Connection closed.");
            this.IsConnected = false;
            //this.ServerDisconnect?.Invo
            //EventContext.Send((state) => { this.ServerDisconnect?.Invoke(null, null); }, null);
            lock (VMSyncObject)
            {
                VMState = null;
            }
            this.ServerDisconnect?.Invoke(this, new EventArgs());
            this.ShutdownEvent.Set();
            ms.Dispose();
            reader.Dispose();
        }
Exemple #52
0
	public void FromBinary(System.IO.BinaryReader reader)
	{
		distance_w_i = (ushort)IPAddress.NetworkToHostOrder(reader.ReadInt16());
		signal_strength = (ushort)IPAddress.NetworkToHostOrder(reader.ReadInt16());
	}
Exemple #53
0
        public virtual void Read(System.IO.Stream stream)
        {
            var r = new System.IO.BinaryReader(stream);

            Read(r);
        }
Exemple #54
0
        public void Populate(int iOffset, bool useMemoryStream)
        {
            this.isNulledOutReflexive = false;
            System.IO.BinaryReader BR = new System.IO.BinaryReader(meta.MS);
            //set offsets
            BR.BaseStream.Position = iOffset + this.chunkOffset;
            this.offsetInMap       = iOffset + this.chunkOffset;
            // If we need to read / save tag info directly to file...
            if (!useMemoryStream)
            {
                map.OpenMap(MapTypes.Internal);
                BR = map.BR;
                BR.BaseStream.Position = this.offsetInMap;
            }
            else
            {
                this.offsetInMap += meta.offset;
            }

            if (doesHaveTagType)
            {
                int nullCheck = BR.ReadInt32();
                if (nullCheck != -1)
                {
                    BR.BaseStream.Position -= 4;
                    char[] temptype = BR.ReadChars(4);
                    Array.Reverse(temptype);
                    this.tagType = new string(temptype);
                }
                else
                {
                    this.tagType = "null";
                }
            }
            else
            {
                this.tagType = "null";
            }


            int tempint = BR.ReadInt32();

            // ...and then close the file once we are done!
            if (!useMemoryStream)
            {
                map.CloseMap();
            }
            this.tagIndex = map.Functions.ForMeta.FindMetaByID(tempint);
            if (this.tagIndex != -1)
            {
                this.tagType = map.MetaInfo.TagType[this.tagIndex];
                this.tagName = map.FileNames.Name[this.tagIndex];
            }
            else
            {
                this.tagName = "null";
            }
            this.identInt32 = tempint;

            this.UpdateIdentBoxes();
        }
Exemple #55
0
 public TransformData(System.IO.BinaryReader reader)
 {
     position = reader.ReadVector3();
     rotation = reader.ReadEulerAngle();
 }
Exemple #56
0
 protected virtual void Read(System.IO.BinaryReader r)
 {
     throw new NotImplementedException();
 }
 /// <summary>
 /// Creates an instance of the object from
 /// a binary stream.
 /// </summary>
 /// <param name="reader">Binary reader</param>
 public CslaClaimsPrincipal(System.IO.BinaryReader reader)
     : base(reader)
 {
 }
Exemple #58
0
 public Human(System.IO.BinaryReader reader, bool sentFromServer)
     : base(reader, sentFromServer)
 {
 }
Exemple #59
0
 protected virtual System.Security.Claims.ClaimsIdentity CreateClaimsIdentity(System.IO.BinaryReader reader)
 {
     throw null;
 }
Exemple #60
0
 public override void LoadState(System.IO.BinaryReader stream)
 {
     base.LoadState(stream);
     lockchr = stream.ReadBoolean();
 }