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); }
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 static PushChunksRequestMessage Deserialize(byte[] bytes) { Guid requestID; Guid chunks; using (System.IO.MemoryStream MS = new System.IO.MemoryStream (bytes, false)) { using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) { requestID = new Guid (BR.ReadBytes (16)); chunks = new Guid (BR.ReadBytes (16)); } } return new PushChunksRequestMessage (requestID, chunks); }
public static ChunkRangesRequest Deserialize(byte[] bytes) { Tuple<byte[],byte[]>[] ranges; using (System.IO.MemoryStream MS = new System.IO.MemoryStream (bytes,false)) { using (System.IO.BinaryReader BR= new System.IO.BinaryReader(MS)) { ranges = new Tuple<byte[], byte[]>[BR.ReadInt32 ()]; for (int n = 0; n != ranges.Length; n++) { ranges [n] = new Tuple<byte[], byte[]> (BR.ReadBytes (BR.ReadInt32 ()), BR.ReadBytes (BR.ReadInt32 ())); } } return new ChunkRangesRequest (ranges); } }
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; }
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); }
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++)); }
public ActionResult Create([Bind(Include = "ProductId,Name,LatName,Price")] Product product, HttpPostedFileBase upload) { try { if (ModelState.IsValid) { if (upload != null && upload.ContentLength > 0) { var img = new File { FileName = System.IO.Path.GetFileName(upload.FileName), ContentType = upload.ContentType, FileType =(int) ViewModels.Enums.FileType.Cover }; using (var reader = new System.IO.BinaryReader(upload.InputStream)) { img.Content = reader.ReadBytes(upload.ContentLength); } product.Files = new List<File> { img }; } db.Products.Add(product); db.SaveChanges(); return RedirectToAction("Index"); } }catch(Exception e) { Console.WriteLine(e.StackTrace); ModelState.AddModelError("", "Unable to save changes."); } return View(product); }
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(); }
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); }
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); } }
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; } }
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); } }
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 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); }
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); }
public ActionResult Create([Bind(Include = "LastName,FirstMidName,EnrollmentDate")] Student student, 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); } student.Files = new List<File> { avatar }; } db.Students.Add(student); db.SaveChanges(); return RedirectToAction("Index"); } } catch (DataException /* dex */) { //Log the error (uncomment dex variable name and add a line here to write a log. ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); } return View(student); }
public override byte[] Read(long ID) { System.IO.FileStream fs = null; System.IO.BinaryReader r = null; try { string path = BuildFilePath(ID); if (!System.IO.File.Exists(path)) return null; fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read); r = new System.IO.BinaryReader(fs); int len = (int)fs.Length; byte [] b = r.ReadBytes(len); return b; } finally { if (r != null) r.Close(); if (fs != null) fs.Close(); } }
static byte[] GetResourceFile(string partialPath) { var assembly = System.Reflection.Assembly.GetExecutingAssembly(); var targetResouceName = assembly.GetManifestResourceNames(). FirstOrDefault(f => f.Contains(partialPath)); using (var resource = assembly.GetManifestResourceStream(targetResouceName)) { if (resource == null) { var error = string.Format("No se encontro el Certificado en Recursos . target resource : {0}", targetResouceName); throw new Exception(error); } byte[] b; using (var br = new System.IO.BinaryReader(resource)) { b = br.ReadBytes((int)resource.Length); } return b; } }
public ActionResult Create([Bind(Include = "Id,Title,Created,Category,Description")] Portfolio portfolio, HttpPostedFileBase upload) { if (ModelState.IsValid) { if (upload != null && upload.ContentLength > 0) { var photo = new File { FileName = System.IO.Path.GetFileName(upload.FileName), FileType = FileType.Photo, ContentType = upload.ContentType }; using (var reader = new System.IO.BinaryReader(upload.InputStream)) { photo.Content = reader.ReadBytes(upload.ContentLength); } portfolio.Files = new List<File> { photo }; } db.Portfolio.Add(portfolio); db.SaveChanges(); return RedirectToAction("Index"); } return View(portfolio); }
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); }
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 = "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(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); }
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); }
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(); } }
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 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); }
public ViewResult CreateNote(Note note, Location location, HttpPostedFileBase upload) { if (upload != null) { var file = new File { FileName = upload.FileName, ContentType = upload.ContentType }; using (var reader = new System.IO.BinaryReader(upload.InputStream)) { file.Content = reader.ReadBytes(upload.ContentLength); } note.File = file; } note.UserId = this.User.Identity.GetUserId(); note.CreationDate = DateTime.Now; note.CreationLocation = LocationUtil.ParseLocation(location); this.noteService.CreateNote(note); return this.View("FinishNoteCreation", note); }
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); }
public void Load(System.IO.BinaryReader br) { //Read tile definition mapper (oldId -> newId) byte[] mapTileDefinitionMapper = new byte[byte.MaxValue]; int definitions = br.ReadInt32(); for (int i = 0; i < definitions; i++) { byte oldType = br.ReadByte(); string id = br.ReadString(); byte newType = 0; foreach (TileDefinition td in tileDefinitions) { if (td.id == id) { newType = td.tileType; break; } } mapTileDefinitionMapper[oldType] = newType; } //Read map size //This is read in CubeWorld.Load() //int sizeXbits = br.ReadInt32(); //int sizeYbits = br.ReadInt32(); //int sizeZbits = br.ReadInt32(); //Create empty world //The world is already created in CubeLoad.Load() //Create(tileDefinitions, sizeXbits, sizeYbits, sizeZbits); //Read tiles byte[] tileBytes = br.ReadBytes(sizeX * sizeY * sizeZ * 4); Tile tile = new Tile(); for (int n = tiles.Length - 1; n >= 0; n--) { tile.tileType = mapTileDefinitionMapper[tileBytes[(n << 2) | 0]]; tile.luminance = tileBytes[(n << 2) | 1]; tile.extra = tileBytes[(n << 2) | 2]; tile.extra2 = tileBytes[(n << 2) | 3]; tiles[n] = tile; } //Read dynamic tiles int nDyanamicTiles = br.ReadInt32(); for (int n = 0; n < nDyanamicTiles; n++) { int objectId = br.ReadInt32(); TilePosition pos = SerializationUtils.ReadTilePosition(br); int timeout = br.ReadInt32(); DynamicTile dynamicTile = new DynamicTile(world, pos, true, objectId); //TODO: Get gravity attribute from somewhere if (true) { dynamicTile.AddComponent(new TileComponentGravity()); } dynamicTiles[pos] = dynamicTile; if (timeout > 0) { dynamicTile.timeout = timeout; dynamicTilesTimeout[pos] = dynamicTile; } world.cwListener.CreateObject(dynamicTile); } //Read top positions topPositions = br.ReadBytes(sizeX * sizeZ); if (world.gameplay.useEnqueueTileUpdates) { EnqueueTilesWithRules(); } enqueueTileUpdates = world.gameplay.useEnqueueTileUpdates; updateLighting = true; reportTileInvalidated = true; if (world.gameplay.useEnqueueTileUpdates) { UpdateTiles(); } //The read tiles already have the light information updated //LightModelAmbient.InitLuminance(this); //LightModelLightSource.InitLuminance(this); }
public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl, HttpPostedFileBase upload) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Manage")); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } var user = new ApplicationUser() { UserName = model.Email, Email = model.Email, Name = model.Name, Gender = model.Gender, DateofBirth = model.DateofBirth }; IdentityResult result = await UserManager.CreateAsync(user); 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); } user.Files = new List <File> { avatar }; } if (result.Succeeded) { var roleStore = new RoleStore <IdentityRole>(context); var roleManager = new RoleManager <IdentityRole>(roleStore); await roleManager.CreateAsync(new IdentityRole { Name = "Normal" }); // var currentUser = UserManager.FindByName(user.UserName); var roleresult = UserManager.AddToRole(user.Id, "Normal"); result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInAsync(user, isPersistent : false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // SendEmail(user.Email, callbackUrl, "Confirm your account", "Please confirm your account by clicking this link"); return(RedirectToLocal(returnUrl)); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return(View(model)); }
} //}}} // LOAD public void Load_ProfileList() // {{{ { //{{{ // TODO: JSON instead of XML // TODO: list existing files instead of storing profile names string caller = "Load_ProfileList"; if (DX1Utility.Debug) { log(caller); } //}}} // [user_Dx1Profiles_dat_pathName] {{{ ProfileList = new List <string>(); string user_Dx1Profiles_dat_pathName = Globals.UserProfileFolder + "Dx1Profiles.dat"; if (DX1Utility.Debug) { log(".. loading [" + user_Dx1Profiles_dat_pathName + "]"); } //}}} // Return [a profile List from USER FOLDER FILE] {{{ System.IO.FileStream fs = null; try { if (System.IO.File.Exists(user_Dx1Profiles_dat_pathName)) { fs = new System.IO.FileStream(user_Dx1Profiles_dat_pathName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read); System.IO.BinaryReader br = new System.IO.BinaryReader(fs); long byteCount = new System.IO.FileInfo(user_Dx1Profiles_dat_pathName).Length; byte[] byteArray = br.ReadBytes((Int32)byteCount); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); IFormatter formatter = new BinaryFormatter(); stream.Position = 0; List <string> list = (List <string>)formatter.Deserialize(stream); stream.Close(); ProfileList = list; }//}}} // Or .. [ MENU_GLOBAL_PROFILE ] {{{ else { // create a new profile List List <string> list = new List <string>(); // add Default Global profile init_keyMapList(); CurrentProfileName = Globals.MENU_GLOBAL_PROFILE; list.Add(CurrentProfileName); //ProfileManager.SaveProfile(CurrentProfileName, keyMapList); ProfileList = list; }//}}} // Exception .. [EMPTY LIST] {{{ } catch (SerializationException ex) { log("*** " + caller + "(" + user_Dx1Profiles_dat_pathName + ") WRONG VERSION: " + ex.Message); } catch (Exception ex) { log("*** " + caller + "(" + user_Dx1Profiles_dat_pathName + ") Exception:\n" + ex); } finally { if (fs != null) { fs.Close(); } } //}}} } //}}}
/// <summary> /// Unserializes a BinaryStream into the Attributes of this Instance /// </summary> /// <param name="reader">The Stream that contains the FileData</param> protected override void Unserialize(System.IO.BinaryReader reader) { duff = false; this.e = null; count = reader.ReadUInt32(); try { reffiles = new Interfaces.Files.IPackedFileDescriptor[count == 0xffff0001 ? reader.ReadUInt32() : count]; for (int i = 0; i < reffiles.Length; i++) { SimPe.Packages.PackedFileDescriptor pfd = new SimPe.Packages.PackedFileDescriptor(); pfd.Group = reader.ReadUInt32(); pfd.Instance = reader.ReadUInt32(); pfd.SubType = (count == 0xffff0001) ? reader.ReadUInt32() : 0; pfd.Type = reader.ReadUInt32(); reffiles[i] = pfd; } uint nn = reader.ReadUInt32(); index = new uint[nn]; blocks = new IRcolBlock[index.Length]; for (int i = 0; i < index.Length; i++) { index[i] = reader.ReadUInt32(); } for (int i = 0; i < index.Length; i++) { uint id = index[i]; IRcolBlock wrp = ReadBlock(id, reader); if (wrp == null) { break; } blocks[i] = wrp; } if (!fast) { long size = reader.BaseStream.Length - reader.BaseStream.Position; if (size > 0) { oversize = reader.ReadBytes((int)size); } else { oversize = new byte[0]; } } } catch (Exception e) { duff = true; this.e = e; //SimPe.Helper.ExceptionMessage(e); } finally { } }
public ActionResult Create(AdmissionVM viewModel, HttpPostedFileBase StudentImage, HttpPostedFileBase Document) { using (var dbTransaction = db.Database.BeginTransaction()) { try { #region validation //if (!ModelState.IsValid) //{ // var studentClass = db.StudentClass.Select(c => new // { // Id = c.Id, // Name = c.ClassName.Name + " || " + c.Shift.Name + " ||" + c.Section.Name // }).OrderBy(o => o.Name).ToList(); // ViewBag.SessionId = new SelectList(db.Session, "Id", "Name"); // ViewBag.GuardianTypeId = new SelectList(db.GuardianType, "Id", "Name"); // ViewBag.StudentClassId = new SelectList(studentClass, "Id", "Name"); // ViewBag.GroupId = new SelectList(db.Group, "Id", "Name"); // return View(); //} #endregion #region Create Students var student = new Student { Name = viewModel.StudentName, FatherName = viewModel.FatherName, MotherName = viewModel.MotherName, DateOfBirth = viewModel.DateOfBirth, Email = viewModel.StudentEmail, PresentAddress = viewModel.PresentAddress, ParmanentAddress = viewModel.ParmanentAddress, Religion = viewModel.Religion, Gender = viewModel.Gender }; if (StudentImage != null && StudentImage.ContentLength > 0) { using (var reader = new System.IO.BinaryReader(StudentImage.InputStream)) { student.Image = reader.ReadBytes(StudentImage.ContentLength); } } db.Student.Add(student); db.SaveChanges(); int studentId = student.Id; #endregion #region Create Guardian if (viewModel.GuardianName != null) { var guardian = new Guardian { Name = viewModel.GuardianName, Email = viewModel.GuardianEmail, Phone = viewModel.GuardianPhone, NID = viewModel.NID, GuardianTypeId = viewModel.GuardianTypeId, StudentId = studentId }; db.Guardian.Add(guardian); db.SaveChanges(); } #endregion #region Create Admission if (viewModel.SessionId != 0) { var admission = new Admission { AdmissionDate = viewModel.AdmissionDate, SessionId = viewModel.SessionId, PreviousSchool = viewModel.PreviousSchool, PreviousSchoolAddrs = viewModel.PreviousSchoolAddrs, StudentClassId = viewModel.StudentClassId, GroupId = viewModel.GroupId, StudentId = studentId }; if (Document != null && Document.ContentLength > 0) { using (var reader = new System.IO.BinaryReader(Document.InputStream)) { admission.PreviousSchoolDocument = reader.ReadBytes(Document.ContentLength); } } db.Admission.Add(admission); db.SaveChanges(); } #endregion #region update Admission Account if (viewModel.ClassFeeId != 0) { var amount = db.ClassFee.Where(i => i.Id == viewModel.ClassFeeId).Select(a => a.AdmissionFee).FirstOrDefault(); var prevBalance = db.AccountList.Where(n => n.Name == "Admission").Select(c => c.CurrentBalance).FirstOrDefault(); var newBalance = prevBalance + amount; ap.UpdateAccountListBalance(1000, newBalance); } #endregion dbTransaction.Commit(); return(RedirectToAction("Index", "Students")); } catch (Exception ex) { #region catch string abc = ex.Message + ex.InnerException; dbTransaction.Rollback(); var studentClass = db.StudentClass.Select(c => new { Id = c.Id, Name = c.ClassName.Name + " || " + c.Shift.Name + " ||" + c.Section.Name }).OrderBy(o => o.Name).ToList(); ViewBag.SessionId = new SelectList(db.Session, "Id", "Name"); ViewBag.GuardianTypeId = new SelectList(db.GuardianType, "Id", "Name"); ViewBag.StudentClassId = new SelectList(studentClass, "Id", "Name"); ViewBag.GroupId = new SelectList(db.Group, "Id", "Name"); return(RedirectToAction("Create")); #endregion } } }
private async void CreateFileByGroup() { string path; List <Group> groups = await new GroupHelper(httpc).GetUserGroups(currentUser); foreach (Group group in groups) { List <File> files = new List <File>(); files = await new FileHelper(httpc).GetGroupFiles(group); path = System.IO.Path.Combine(folderLocation, group.Name); System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(path); System.IO.FileInfo[] localFiles = di.GetFiles("*"); List <string> localfileNames = new List <string>(); List <string> remotefileNames = new List <string>(); foreach (File f in files) { remotefileNames.Add(f.Name); } foreach (System.IO.FileInfo fi in localFiles) { localfileNames.Add(fi.Name); } //Verication si on a des nouveua file local foreach (System.IO.FileInfo file in localFiles) { if (!remotefileNames.Contains(file.Name)) { System.IO.FileStream fs = file.OpenRead(); byte[] fileContent; using (System.IO.BinaryReader sr = new System.IO.BinaryReader(fs)) { long numByte = file.Length; fileContent = sr.ReadBytes((int)numByte); } await new FileHelper(httpc).CreateFile(file.Name, fileContent, group.Id); fs.Close(); } } //Delete /* List<File> filesToDelete = new List<File>(); * foreach (File file in files) * { * if (!localfileNames.Contains(file.Name)) * { * filesToDelete.Add(file); * } * } * * foreach(File fileToDelete in filesToDelete) * { * await new FileHelper(httpc).DeleteFile(fileToDelete.Id); * }*/ } groups = await new GroupHelper(httpc).GetUserGroups(currentUser); foreach (Group group in groups) { path = System.IO.Path.Combine(folderLocation, group.Name); System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(path); System.IO.FileInfo[] localFiles = di.GetFiles("*"); List <string> localfileNames = new List <string>(); foreach (System.IO.FileInfo fi in localFiles) { fi.Delete(); } path = System.IO.Path.Combine(folderLocation, group.Name); List <File> files = await new FileHelper(httpc).GetGroupFiles(group); Debug.WriteLine("Salut la gang"); foreach (File file in files) { string filePath = System.IO.Path.Combine(path, file.Name); Debug.WriteLine("Salut la gang 22222"); Debug.WriteLine(filePath); try { System.IO.FileStream fstream = System.IO.File.Create(filePath); byte[] data = System.Convert.FromBase64String(file.Content); fstream.Write(data, 0, data.Length); fstream.Close(); } catch { } //TODO write file.data dans le fstream } } }
public static async Task <ShaderDescription> ReadAndCompileShader(this AssetsDirectoryBase assetsDirectory, GraphicsContext graphicsContext, string hlslFileName, string translateFileName, ShaderStages stage, string entryPoint, CompilerParameters compileParameters) { GraphicsBackend backend = graphicsContext.BackendType; string source; byte[] bytecode = null; switch (backend) { case GraphicsBackend.DirectX11: case GraphicsBackend.DirectX12: source = await assetsDirectory.ReadAsStringAsync($"Shaders/HLSL/{hlslFileName}.fx"); bytecode = graphicsContext.ShaderCompile(source, entryPoint, stage, compileParameters).ByteCode; break; case GraphicsBackend.OpenGL: source = await assetsDirectory.ReadAsStringAsync($"Shaders/GLSL/{translateFileName}.glsl"); bytecode = graphicsContext.ShaderCompile(source, entryPoint, stage, compileParameters).ByteCode; break; case GraphicsBackend.OpenGLES: source = await assetsDirectory.ReadAsStringAsync($"Shaders/ESSL/{translateFileName}.essl"); bytecode = graphicsContext.ShaderCompile(source, entryPoint, stage, compileParameters).ByteCode; break; case GraphicsBackend.Metal: source = await assetsDirectory.ReadAsStringAsync($"Shaders/MSL/{translateFileName}.msl"); bytecode = graphicsContext.ShaderCompile(source, entryPoint, stage, compileParameters).ByteCode; break; case GraphicsBackend.Vulkan: var stream = assetsDirectory.Open($"Shaders/VK/{translateFileName}.spirv"); using (System.IO.BinaryReader br = new System.IO.BinaryReader(stream)) { bytecode = br.ReadBytes((int)stream.Length); } break; default: throw new Exception($"Backend not found {backend}"); } ShaderDescription description = new ShaderDescription(stage, entryPoint, bytecode); return(description); }
private RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey) { byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; // --------- Set up stream to decode the asn.1 encoded RSA private key ------ System.IO.MemoryStream mem = new System.IO.MemoryStream(privkey); System.IO.BinaryReader binr = new System.IO.BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading byte bt = 0; ushort twobytes = 0; int elems = 0; try { twobytes = binr.ReadUInt16(); if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) { binr.ReadByte(); //advance 1 byte } else if (twobytes == 0x8230) { binr.ReadInt16(); //advance 2 bytes } else { return(null); } twobytes = binr.ReadUInt16(); if (twobytes != 0x0102) //version number { return(null); } bt = binr.ReadByte(); if (bt != 0x00) { return(null); } //------ all private key components are Integer sequences ---- elems = GetIntegerSize(binr); MODULUS = binr.ReadBytes(elems); elems = GetIntegerSize(binr); E = binr.ReadBytes(elems); elems = GetIntegerSize(binr); D = binr.ReadBytes(elems); elems = GetIntegerSize(binr); P = binr.ReadBytes(elems); elems = GetIntegerSize(binr); Q = binr.ReadBytes(elems); elems = GetIntegerSize(binr); DP = binr.ReadBytes(elems); elems = GetIntegerSize(binr); DQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr); IQ = binr.ReadBytes(elems); Console.WriteLine("showing components .."); if (verbose) { showBytes("\nModulus", MODULUS); showBytes("\nExponent", E); showBytes("\nD", D); showBytes("\nP", P); showBytes("\nQ", Q); showBytes("\nDP", DP); showBytes("\nDQ", DQ); showBytes("\nIQ", IQ); } // ------- create RSACryptoServiceProvider instance and initialize with public key ----- RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSAParameters RSAparams = new RSAParameters(); RSAparams.Modulus = MODULUS; RSAparams.Exponent = E; RSAparams.D = D; RSAparams.P = P; RSAparams.Q = Q; RSAparams.DP = DP; RSAparams.DQ = DQ; RSAparams.InverseQ = IQ; RSA.ImportParameters(RSAparams); return(RSA); } catch (Exception) { return(null); } finally { binr.Close(); } }
public ActionResult Edit([Bind(Include = "ReagentId,LotNumber,ExpiryDate,SupplierName,ReagentName,IdCode,Grade,GradeAdditionalNotes")] StockReagentEditViewModel stockreagent, HttpPostedFileBase uploadCofA, HttpPostedFileBase uploadMSDS) { var errors = ModelState.Values.SelectMany(v => v.Errors); if (ModelState.IsValid) { var user = _uow.GetCurrentUser(); var invRepo = _uow.InventoryItemRepository; InventoryItem invItem = invRepo.Get() .Where(item => item.StockReagent != null && item.StockReagent.ReagentId == stockreagent.ReagentId) .FirstOrDefault(); StockReagent updateReagent = invItem.StockReagent; updateReagent.LotNumber = stockreagent.LotNumber; updateReagent.LastModifiedBy = user.UserName; updateReagent.Grade = stockreagent.Grade; updateReagent.GradeAdditionalNotes = stockreagent.GradeAdditionalNotes; updateReagent.ExpiryDate = stockreagent.ExpiryDate; updateReagent.DateModified = DateTime.Today; updateReagent.ReagentName = stockreagent.ReagentName; _uow.StockReagentRepository.Update(updateReagent); //_uow.Commit(); if (uploadCofA != null) { var cofa = new CertificateOfAnalysis() { FileName = uploadCofA.FileName, ContentType = uploadCofA.ContentType, DateAdded = DateTime.Today }; using (var reader = new System.IO.BinaryReader(uploadCofA.InputStream)) { cofa.Content = reader.ReadBytes(uploadCofA.ContentLength); } stockreagent.CertificateOfAnalysis = cofa; //add certificate analysis invItem.CertificatesOfAnalysis.Add(cofa); } if (uploadMSDS != null) { var msds = new MSDS() { FileName = uploadMSDS.FileName, ContentType = uploadMSDS.ContentType, DateAdded = DateTime.Today }; using (var reader = new System.IO.BinaryReader(uploadMSDS.InputStream)) { msds.Content = reader.ReadBytes(uploadMSDS.ContentLength); } stockreagent.MSDS = msds; var msdsRepo = new MSDSRepository(); var oldSDS = msdsRepo.Get() .Where(item => item.InventoryItem.StockReagent != null && item.InventoryItem.StockReagent.ReagentId == stockreagent.ReagentId) .First(); oldSDS.Content = msds.Content; oldSDS.FileName = msds.FileName; oldSDS.ContentType = msds.ContentType; oldSDS.DateAdded = DateTime.Today; msdsRepo.Update(oldSDS); } invItem.SupplierName = stockreagent.SupplierName; invRepo.Update(invItem); _uow.Commit(); return(RedirectToAction("Details", new { id = stockreagent.ReagentId })); } return(View(stockreagent)); }
public ActionResult Topup([Bind(Include = "ReagentId,NewMSDSNotes,NewLotNumber,NewExpiryDate,NewDateReceived,IsExpiryDateBasedOnDays,DaysUntilExpired,CatalogueCode")] StockReagentTopUpViewModel model, HttpPostedFileBase uploadCofA, HttpPostedFileBase uploadMSDS) { var reagent = _uow.StockReagentRepository.Get(model.ReagentId); if (reagent == null) { return(HttpNotFound()); } if (!ModelState.IsValid) { //handle error var errors = ModelState.Values.SelectMany(v => v.Errors); return(View(SetTopupReagent(model, reagent))); } var user = _uow.GetCurrentUser(); var invRepo = _uow.InventoryItemRepository; var department = user.Department; var numOfItems = invRepo.Get().Count(); model.NumberOfBottles = reagent.InventoryItems.Where(item => item.CatalogueCode.Equals(reagent.CatalogueCode)).First().NumberOfBottles; //upload CofA and MSDS if (uploadCofA != null) { var cofa = new CertificateOfAnalysis() { FileName = uploadCofA.FileName, ContentType = uploadCofA.ContentType, DateAdded = DateTime.Today }; using (var reader = new System.IO.BinaryReader(uploadCofA.InputStream)) { cofa.Content = reader.ReadBytes(uploadCofA.ContentLength); } //model.CertificateOfAnalysis = cofa; reagent.InventoryItems.Where(item => item.CatalogueCode.Equals(reagent.CatalogueCode)).First().CertificatesOfAnalysis.Add(cofa); } if (uploadMSDS != null) { var msds = new MSDS() { FileName = uploadMSDS.FileName, ContentType = uploadMSDS.ContentType, DateAdded = DateTime.Today, MSDSNotes = model.MSDSNotes }; using (var reader = new System.IO.BinaryReader(uploadMSDS.InputStream)) { msds.Content = reader.ReadBytes(uploadMSDS.ContentLength); } //model.MSDS = msds; //reagent.InventoryItems.Where(item => item.CatalogueCode.Equals(model.CatalogueCode)).First().MSDS.Add(msds); var msdsRepo = _uow.MSDSRepository; var oldSDS = msdsRepo.Get() .Where(item => item.InventoryItem.StockReagent != null && item.InventoryItem.StockReagent.CatalogueCode == reagent.CatalogueCode) .First(); oldSDS.Content = msds.Content; oldSDS.FileName = msds.FileName; oldSDS.ContentType = msds.ContentType; oldSDS.DateAdded = DateTime.Today; msdsRepo.Update(oldSDS); } //write record(s) to the db var result = CheckModelState.Invalid;//default to invalid to expect the worst //set new propeties to create new entity based on old StockReagent newReagent = null; if (model.NumberOfBottles > 1) { for (int i = 1; i <= model.NumberOfBottles; i++) { newReagent = new StockReagent() { ExpiryDate = model.NewExpiryDate, IdCode = department.Location.LocationCode + "-" + (numOfItems + 1) + "-" + model.NewLotNumber + "/" + i,//append number of bottles LotNumber = model.NewLotNumber, DateCreated = DateTime.Today, CreatedBy = user.UserName, CatalogueCode = reagent.CatalogueCode, Grade = reagent.Grade, GradeAdditionalNotes = reagent.GradeAdditionalNotes, DateModified = null, DaysUntilExpired = model.DaysUntilExpired, LastModifiedBy = null, ReagentName = reagent.ReagentName, //InventoryItems = reagent.InventoryItems, DateOpened = null, DateReceived = model.NewDateReceived }; //reagent.InventoryItems.Add(reagent.InventoryItems.Where(x => x.CatalogueCode.Equals(model.CatalogueCode)).First()); _uow.StockReagentRepository.Create(newReagent); result = _uow.Commit(); //creation wasn't successful - break from loop and let switch statement handle the problem if (result != CheckModelState.Valid) { break; } } } else { newReagent = new StockReagent() { ExpiryDate = model.NewExpiryDate, IdCode = department.Location.LocationCode + "-" + (numOfItems + 1) + "-" + model.NewLotNumber,//only 1 bottle, no need to concatenate LotNumber = model.NewLotNumber, DateCreated = DateTime.Today, CreatedBy = user.UserName, CatalogueCode = reagent.CatalogueCode, Grade = reagent.Grade, GradeAdditionalNotes = reagent.GradeAdditionalNotes, DateModified = null, DaysUntilExpired = model.DaysUntilExpired, LastModifiedBy = null, ReagentName = reagent.ReagentName, InventoryItems = reagent.InventoryItems, DateOpened = null, DateReceived = model.NewDateReceived }; //reagent.InventoryItems.Add(inventoryItem); _uow.StockReagentRepository.Create(newReagent); result = _uow.Commit(); } switch (result) { case CheckModelState.Invalid: ModelState.AddModelError("", "The creation of " + reagent.ReagentName + " failed. Please double check all inputs and try again."); return(View(SetTopupReagent(model, reagent))); case CheckModelState.DataError: ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists please contact your system administrator."); return(View(SetTopupReagent(model, reagent))); case CheckModelState.Error: ModelState.AddModelError("", "There was an error. Please try again."); return(View(SetTopupReagent(model, reagent))); case CheckModelState.Valid: //save pressed return(RedirectToAction("Index")); default: ModelState.AddModelError("", "An unknown error occurred."); return(View(SetTopupReagent(model, reagent))); } }
public ActionResult Create([Bind(Include = "CatalogueCode,MSDSNotes,SupplierName,ReagentName,StorageRequirements,Grade,UsedFor,LotNumber,GradeAdditionalNotes,NumberOfBottles,ExpiryDate,InitialAmount,DateReceived,IsExpiryDateBasedOnDays,DaysUntilExpired,OtherUnitExplained")] StockReagentCreateViewModel model, string[] Unit, HttpPostedFileBase uploadCofA, HttpPostedFileBase uploadMSDS, string submit) { //model isn't valid, return to the form if (!ModelState.IsValid) { return(View(SetStockReagent(model))); } var invRepo = _uow.InventoryItemRepository; //catalogue code must be unique - let's verify bool doesCatalogueCodeExist = invRepo.Get() .Any(item => item.CatalogueCode != null && item.CatalogueCode.Equals(model.CatalogueCode)); if (doesCatalogueCodeExist) { ModelState.AddModelError("", "The Catalogue Code provided is not unique. If the Catalogue Code provided is in fact correct, add the item as a new Lot Number under the existing Catalogue Code."); return(View(SetStockReagent(model))); } //last line of defense for number of bottles if (model.NumberOfBottles == 0) { model.NumberOfBottles = 1; } model.InitialAmountUnits = Unit[0]; if (Unit.Length > 1) { model.InitialAmountUnits += "/" + Unit[1]; } var devicesUsed = Request.Form["Devices"]; var deviceRepo = _uow.DeviceRepository; if (devicesUsed == null) { ModelState.AddModelError("", "You must select a device that was used."); return(View(SetStockReagent(model))); } if (devicesUsed.Contains(",")) { model.DeviceOne = deviceRepo.Get().Where(item => item.DeviceCode.Equals(devicesUsed.Split(',')[0])).FirstOrDefault(); model.DeviceTwo = deviceRepo.Get().Where(item => item.DeviceCode.Equals(devicesUsed.Split(',')[1])).FirstOrDefault(); } else { model.DeviceOne = deviceRepo.Get().Where(item => item.DeviceCode.Equals(devicesUsed.Split(',')[0])).FirstOrDefault(); } var user = _uow.GetCurrentUser(); var numOfItems = invRepo.Get().Count(); if (uploadCofA != null) { var cofa = new CertificateOfAnalysis() { FileName = uploadCofA.FileName, ContentType = uploadCofA.ContentType, DateAdded = DateTime.Today }; using (var reader = new System.IO.BinaryReader(uploadCofA.InputStream)) { cofa.Content = reader.ReadBytes(uploadCofA.ContentLength); } model.CertificateOfAnalysis = cofa; } if (uploadMSDS != null) { var msds = new MSDS() { FileName = uploadMSDS.FileName, ContentType = uploadMSDS.ContentType, DateAdded = DateTime.Today, MSDSNotes = model.MSDSNotes }; using (var reader = new System.IO.BinaryReader(uploadMSDS.InputStream)) { msds.Content = reader.ReadBytes(uploadMSDS.ContentLength); } model.MSDS = msds; } InventoryItem inventoryItem = new InventoryItem() { CatalogueCode = model.CatalogueCode.ToUpper(), Department = user.Department, UsedFor = model.UsedFor, Type = "Reagent", StorageRequirements = model.StorageRequirements, SupplierName = model.SupplierName, NumberOfBottles = model.NumberOfBottles, InitialAmount = model.InitialAmount.ToString() + " " + model.InitialAmountUnits, OtherUnitExplained = model.OtherUnitExplained, FirstDeviceUsed = model.DeviceOne, SecondDeviceUsed = model.DeviceTwo }; inventoryItem.MSDS.Add(model.MSDS); inventoryItem.CertificatesOfAnalysis.Add(model.CertificateOfAnalysis); //getting the enum result //CheckModelState result = CheckModelState.Invalid;//default to invalid to expect the worst StockReagent reagent = new StockReagent() { LotNumber = model.LotNumber, IdCode = user.Department.Location.LocationCode + "-" + (numOfItems + 1) + "-" + model.LotNumber + "/" + model.NumberOfBottles,//append number of bottles ReagentName = model.ReagentName, Grade = model.Grade, GradeAdditionalNotes = model.GradeAdditionalNotes, DateReceived = model.DateReceived, DateOpened = null, DaysUntilExpired = model.DaysUntilExpired, ExpiryDate = model.ExpiryDate, DateCreated = DateTime.Today, CreatedBy = user.UserName, DateModified = null, CatalogueCode = model.CatalogueCode.ToUpper() }; reagent.InventoryItems.Add(inventoryItem); _uow.StockReagentRepository.Create(reagent); var result = _uow.Commit(); //if (model.NumberOfBottles > 1) { // for (int i = 1; i <= model.NumberOfBottles; i++) { // reagent = new StockReagent() { // LotNumber = model.LotNumber, // IdCode = department.Location.LocationCode + "-" + (numOfItems + 1) + "-" + model.LotNumber + "/" + i,//append number of bottles // ReagentName = model.ReagentName, // Grade = model.Grade, // GradeAdditionalNotes = model.GradeAdditionalNotes, // DateReceived = model.DateReceived, // DateOpened = null, // DaysUntilExpired = model.DaysUntilExpired, // ExpiryDate = model.ExpiryDate, // DateCreated = DateTime.Today, // CreatedBy = user.UserName, // DateModified = null, // CatalogueCode = model.CatalogueCode // }; // reagent.InventoryItems.Add(inventoryItem); // result = repo.Create(reagent); // //creation wasn't successful - break from loop and let switch statement handle the problem // if (result != CheckModelState.Valid) { break; } // } //} else { // reagent = new StockReagent() { // LotNumber = model.LotNumber, // IdCode = department.Location.LocationCode + "-" + (numOfItems + 1) + "-" + model.LotNumber,//only 1 bottle, no need to concatenate // ReagentName = model.ReagentName, // Grade = model.Grade, // GradeAdditionalNotes = model.GradeAdditionalNotes, // DateReceived = model.DateReceived, // DateOpened = null, // DaysUntilExpired = model.DaysUntilExpired, // ExpiryDate = model.ExpiryDate, // DateCreated = DateTime.Today, // CreatedBy = user.UserName, // DateModified = null, // CatalogueCode = model.CatalogueCode // }; // reagent.InventoryItems.Add(inventoryItem); // result = repo.Create(reagent); //} switch (result) { case CheckModelState.Invalid: ModelState.AddModelError("", "The creation of " + reagent.ReagentName + " failed. Please double check all inputs and try again."); return(View(SetStockReagent(model))); case CheckModelState.DataError: ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists please contact your system administrator."); return(View(SetStockReagent(model))); case CheckModelState.Error: ModelState.AddModelError("", "There was an error. Please try again."); return(View(SetStockReagent(model))); case CheckModelState.Valid: if (!string.IsNullOrEmpty(submit) && submit.Equals("Save")) { //save pressed return(RedirectToAction("Index")); } else { //save & new pressed return(RedirectToAction("Create")); } default: ModelState.AddModelError("", "An unknown error occurred."); return(View(SetStockReagent(model))); } }
private void Read(long Position) { System.IO.BinaryReader reader = new System.IO.BinaryReader(m_FileStream); reader.BaseStream.Position = Position; List <Folder> folders = new List <Folder>(); sPk2EntryBlock entryBlock = (sPk2EntryBlock)BufferToStruct(m_Blowfish.Decode(reader.ReadBytes(Marshal.SizeOf(typeof(sPk2EntryBlock)))), typeof(sPk2EntryBlock)); for (int i = 0; i < 20; i++) { sPk2Entry entry = entryBlock.Entries[i]; //..... switch (entry.Type) { case 0: //Null Entry break; case 1: //Folder if (entry.Name != "." && entry.Name != "..") { Folder folder = new Folder(); folder.Name = entry.Name; folder.Position = BitConverter.ToInt64(entry.g_Position, 0); folders.Add(folder); m_Folders.Add(folder); m_CurrentFolder.SubFolders.Add(folder); } break; case 2: //File File file = new File(); file.Position = entry.Position; file.Name = entry.Name; file.Size = entry.Size; file.ParentFolder = m_CurrentFolder; m_Files.Add(file); m_CurrentFolder.Files.Add(file); break; } } if (entryBlock.Entries[19].NextChain != 0) { Read(entryBlock.Entries[19].NextChain); } foreach (Folder folder in folders) { m_CurrentFolder = folder; if (folder.Files == null) { folder.Files = new List <File>(); } if (folder.SubFolders == null) { folder.SubFolders = new List <Folder>(); } Read(folder.Position); } }
public ActionResult Create([Bind(Include = "Title,Content")] NewsStory newsStory, HttpPostedFileBase image) { if (ModelState.IsValid) { if (image != null && image.ContentLength > 0) { //Creating new Image entity var newsImage = new Image { ImageName = System.IO.Path.GetFileName(image.FileName), }; //Setting ImageContent as a byte array of the image file using (var reader = new System.IO.BinaryReader(image.InputStream)) { newsImage.ImageContent = reader.ReadBytes(image.ContentLength); } //Resizing the image WebImage resizedImage = new WebImage(newsImage.ImageContent); resizedImage.Resize(300, 200, false); newsImage.ImageContent = resizedImage.GetBytes(); newsStory.Image = newsImage; } //Creating a List to hold the KeyWord objects that are going to be associated with the current NewsStory List <KeyWord> allkeywords = new List <KeyWord>(); var inputKeywords = Request["KeyWords"]; var keywords = inputKeywords.Split(',').Select(p => p.Trim()); foreach (var word in keywords) { KeyWord keyword = new KeyWord(); keyword.keyWordContent = word; bool exists = db.KeyWords.AsEnumerable().Where(c => c.keyWordContent.Equals(word)).Count() > 0; /*Checking if the keyword already exists in the KeyWords DB table * and if exists, mapping the current NewsStory to the existing keywords*/ if (exists) { var existingkeys = db.KeyWords.Where(c => c.keyWordContent.Equals(word)).ToList(); foreach (var kw in existingkeys) { allkeywords.Add(kw); } } else { allkeywords.Add(keyword); } } newsStory.KeyWords = allkeywords; newsStory.DateCreated = DateTime.Now; newsStory.UserId = User.Identity.GetUserId(); db.NewsStories.Add(newsStory); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(newsStory)); }
static byte[] GetFileAsByteArray(string filePath) { System.IO.FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fileStream); return(binaryReader.ReadBytes((int)fileStream.Length)); }
/// <summary> /// 读指定长度字节 /// </summary> /// <param name="count"></param> /// <returns></returns> public byte[] ReadBytes(int count) { byte[] result = reader.ReadBytes(count); return(result); }
/// <summary> /// /// </summary> /// <param name="br"></param> /// <returns>Un-signed 16-bit integer</returns> static public ushort ReadUInt16(System.IO.BinaryReader br) { return(System.Convert.ToUInt16(Reverse(br.ReadBytes(2)))); }
private void OnProcessRequest(object sender, Chromium.Event.CfxProcessRequestEventArgs e) { readResponseStreamOffset = 0; var request = e.Request; var callback = e.Callback; var uri = new Uri(request.Url); requestUrl = request.Url; var fileName = string.IsNullOrEmpty(domain) ? string.Format("{0}{1}", uri.Authority, uri.AbsolutePath) : uri.AbsolutePath; if (fileName.StartsWith("/") && fileName.Length > 1) { fileName = fileName.Substring(1); } var mainAssembly = resourceAssembly; var endTrimIndex = fileName.LastIndexOf('/'); if (endTrimIndex > -1) { var tmp = fileName.Substring(0, endTrimIndex); tmp = tmp.Replace("-", "_"); fileName = string.Format("{0}{1}", tmp, fileName.Substring(endTrimIndex)); } var resourcePath = string.Format("{0}.{1}", mainAssembly.GetName().Name, fileName.Replace('/', '.')); Assembly satelliteAssembly = null; try { satelliteAssembly = mainAssembly.GetSatelliteAssembly(System.Threading.Thread.CurrentThread.CurrentCulture); } catch { } var resourceNames = mainAssembly.GetManifestResourceNames().Select(x => new { TargetAssembly = mainAssembly, Name = x, IsSatellite = false }); if (satelliteAssembly != null) { string HandleCultureName(string name) { var cultureName = System.Threading.Thread.CurrentThread.CurrentCulture.Name; var fileInfo = new System.IO.FileInfo(name); return($"{System.IO.Path.GetFileNameWithoutExtension(fileInfo.Name)}.{cultureName}{fileInfo.Extension}"); } resourceNames = resourceNames.Union(satelliteAssembly.GetManifestResourceNames().Select(x => new { TargetAssembly = satelliteAssembly, Name = HandleCultureName(x), IsSatellite = true })); } var resource = resourceNames.SingleOrDefault(p => p.Name.Equals(resourcePath, StringComparison.CurrentCultureIgnoreCase)); var manifestResourceName = resourcePath; if (resource != null && resource.IsSatellite) { var fileInfo = new System.IO.FileInfo(manifestResourceName); manifestResourceName = $"{System.IO.Path.GetFileNameWithoutExtension(System.IO.Path.GetFileNameWithoutExtension(fileInfo.Name))}{fileInfo.Extension}"; } if (resource != null && resource.TargetAssembly.GetManifestResourceStream(manifestResourceName) != null) { using (var reader = new System.IO.BinaryReader(resource.TargetAssembly.GetManifestResourceStream(manifestResourceName))) { var buff = reader.ReadBytes((int)reader.BaseStream.Length); webResource = new WebResource(buff, CfxRuntime.GetMimeType(System.IO.Path.GetExtension(fileName).TrimStart('.'))); reader.Close(); if (!browser.webResources.ContainsKey(requestUrl)) { browser.SetWebResource(requestUrl, webResource); } } callback.Continue(); e.SetReturnValue(true); } else { Console.WriteLine($"[错误嵌入资源]:\t{requestUrl}"); callback.Continue(); e.SetReturnValue(false); } }
private static unsafe byte[] MurmurHash3_x64_128(System.IO.Stream stream, uint seed) { const ulong c1 = 0x87c37b91114253d5; const ulong c2 = 0x4cf5ad432745937f; ulong h1 = seed; ulong h2 = seed; ulong len = 0; using (var reader = new System.IO.BinaryReader(stream)) { byte[] chunk = reader.ReadBytes(16); while (chunk.Length > 0) { ulong k1 = 0; ulong k2 = 0; switch (chunk.Length) { // Body case 16: k1 = chunk[0] | ((ulong)chunk[1]) << 8 | ((ulong)chunk[2]) << 16 | ((ulong)chunk[3]) << 24 | ((ulong)chunk[4]) << 32 | ((ulong)chunk[5]) << 40 | ((ulong)chunk[6]) << 48 | ((ulong)chunk[7]) << 56; k2 = chunk[8] | ((ulong)chunk[9]) << 8 | ((ulong)chunk[10]) << 16 | ((ulong)chunk[11]) << 24 | ((ulong)chunk[12]) << 32 | ((ulong)chunk[13]) << 40 | ((ulong)chunk[14]) << 48 | ((ulong)chunk[15]) << 56; k1 *= c1; k1 = rotl64(k1, 31); k1 *= c2; h1 ^= k1; h1 = rotl64(h1, 27); h1 += h2; h1 = h1 * 5 + 0x52dce729; k2 *= c2; k2 = rotl64(k2, 33); k2 *= c1; h2 ^= k2; h2 = rotl64(h2, 31); h2 += h1; h2 = h2 * 5 + 0x38495ab5; break; // Tail case 15: k2 ^= ((ulong)chunk[14]) << 48; goto case 14; case 14: k2 ^= ((ulong)chunk[13]) << 40; goto case 13; case 13: k2 ^= ((ulong)chunk[12]) << 32; goto case 12; case 12: k2 ^= ((ulong)chunk[11]) << 24; goto case 11; case 11: k2 ^= ((ulong)chunk[10]) << 16; goto case 10; case 10: k2 ^= ((ulong)chunk[9]) << 8; goto case 9; case 9: k2 ^= ((ulong)chunk[8]) << 0; k2 *= c2; k2 = rotl64(k2, 33); k2 *= c1; h2 ^= k2; goto case 8; case 8: k1 ^= ((ulong)chunk[7]) << 56; goto case 7; case 7: k1 ^= ((ulong)chunk[6]) << 48; goto case 6; case 6: k1 ^= ((ulong)chunk[5]) << 40; goto case 5; case 5: k1 ^= ((ulong)chunk[4]) << 32; goto case 4; case 4: k1 ^= ((ulong)chunk[3]) << 24; goto case 3; case 3: k1 ^= ((ulong)chunk[2]) << 16; goto case 2; case 2: k1 ^= ((ulong)chunk[1]) << 8; goto case 1; case 1: k1 ^= ((ulong)chunk[0]) << 0; k1 *= c1; k1 = rotl64(k1, 31); k1 *= c2; h1 ^= k1; break; } len += (uint)chunk.Length; chunk = reader.ReadBytes(16); } } // Finalization h1 ^= len; h2 ^= len; h1 += h2; h2 += h1; h1 = fmix64(h1); h2 = fmix64(h2); h1 += h2; h2 += h1; var result = new byte[16]; fixed(byte *ptr = result) { ((ulong *)ptr)[0] = h1; ((ulong *)ptr)[1] = h2; } return(result); }
private PluginInfo GetPluginInfo(System.IO.FileInfo plugin) { var pi = new PluginInfo() { Present = true, Name = plugin.Name, Size = plugin.Length, }; byte[] record; byte[] data; using (var fs = plugin.OpenRead()) { using (var br = new System.IO.BinaryReader(fs, Encoding.UTF8)) { record = br.ReadBytes(24); var TES4 = Encoding.UTF8.GetString(record, 0, 4); // First four bytes as chars should be TES4 if (TES4 != "TES4") { throw new ApplicationException("Not a valid Plugin"); } var dataSize = BitConverter.ToUInt32(record, 4); var flags = BitConverter.ToUInt32(record, 8); if ((flags & 0x00000200) > 0) { pi.Type = "ESL"; } else if ((flags & 0x00000001) > 0) { pi.Type = "ESM"; } else { pi.Type = "ESP"; } data = br.ReadBytes(Convert.ToInt32(dataSize)); } } var idx = 0; var masters = new List <string>(); while (idx < data.Length) { var field = Encoding.UTF8.GetString(data, idx, 4); var fDataSize = BitConverter.ToUInt16(data, idx + 4); idx += 6; switch (field) { case "HEDR": var numbRecords = BitConverter.ToInt32(data, idx + 4); pi.NumberOfRecords = numbRecords; break; case "CNAM": case "SNAM": case "MAST": var end = Array.FindIndex(data, idx, b => b == 0); var text = Encoding.UTF8.GetString(data, idx, end - idx); if (field == "CNAM") { pi.Author = text; } if (field == "SNAM") { pi.Description = text; } if (field == "MAST") { masters.Add(text); } break; default: break; } idx += fDataSize; } pi.Masters = masters.ToArray(); return(pi); }
private void Unserialize(System.IO.BinaryReader reader) { array = reader.ReadBytes(8); }
/// <summary> /// Unserializes a BinaryStream into the Attributes of this Instance /// </summary> /// <param name="reader">The Stream that contains the FileData</param> protected override void Unserialize(System.IO.BinaryReader reader) { ver = reader.ReadUInt16(); subver = reader.ReadUInt16(); sz.Width = reader.ReadInt32(); sz.Height = reader.ReadInt32(); type = (LotType)reader.ReadByte(); roads = reader.ReadByte(); rotation = (Rotation)reader.ReadByte(); unknown_0 = reader.ReadUInt32(); lotname = StreamHelper.ReadString(reader); description = StreamHelper.ReadString(reader); unknown_1 = new List <float>(); int len = reader.ReadInt32(); for (int i = 0; i < len; i++) { this.unknown_1.Add(reader.ReadSingle()); } if (subver >= (UInt16)LtxtSubVersion.Voyage) { unknown_3 = reader.ReadSingle(); } else { unknown_3 = 0; } if (subver >= (UInt16)LtxtSubVersion.Freetime) { unknown_4 = reader.ReadUInt32(); } else { unknown_4 = 0; } if (ver >= (UInt16)LtxtVersion.Apartment || subver >= (UInt16)LtxtSubVersion.Apartment) { unknown_5 = reader.ReadBytes(14); } else { unknown_5 = new byte[0]; } int y = reader.ReadInt32(); int x = reader.ReadInt32(); loc = new Point(x, y); elevation = reader.ReadSingle(); lotInstance = reader.ReadUInt32(); orient = (LotOrientation)reader.ReadByte(); texture = StreamHelper.ReadString(reader); unknown_2 = reader.ReadByte(); if (ver >= (int)LtxtVersion.Business) { owner = reader.ReadUInt32(); } else { owner = 0; } if (ver >= (UInt16)LtxtVersion.Apartment || subver >= (UInt16)LtxtSubVersion.Apartment) { int count; apartmentBase = reader.ReadUInt32(); unknown_6 = reader.ReadBytes(9); subLots = new List <SubLot>(); count = reader.ReadInt32(); for (int i = 0; i < count; i++) { subLots.Add(new SubLot(reader)); } unknown_7 = new List <uint>(); count = reader.ReadInt32(); for (int i = 0; i < count; i++) { unknown_7.Add(reader.ReadUInt32()); } } else { apartmentBase = 0; unknown_6 = new byte[0]; subLots = new List <SubLot>(); unknown_7 = new List <uint>(); } followup = reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position)); }
public byte[] ReadBytes(int count) { return(Reader.ReadBytes(count)); }
public ActionResult Create(DocumentViewModel document, HttpPostedFileBase upload) { var tempEntity = new DocumentEntity() { Id = document.assignedEntity.Id, returnTarget = document.assignedEntity.returnTarget, EntityName = document.assignedEntity.EntityName, returnId = document.assignedEntity.returnId, EntityType = document.assignedEntity.EntityType, DocumentTypeName = document.assignedEntity.DocumentTypeName }; document.assignedEntity = tempEntity; var addDocument = new Document() { //Id = document.Id, DocumentTypeId = document.DocumentTypeId, DocumentContent = document.DocumentContent, DocumentName = document.DocumentName, DueDate = document.DueDate, UploadDate = DateTime.Now }; if (upload != null && upload.ContentLength > 0) { try { if (ModelState.IsValid) { if (upload != null && upload.ContentLength > 0) { addDocument.DocumentName = System.IO.Path.GetFileName(upload.FileName); addDocument.FileType = upload.ContentType; using (var reader = new System.IO.BinaryReader(upload.InputStream)) { addDocument.Content = reader.ReadBytes(upload.ContentLength); } } db.Documents.Add(addDocument); db.SaveChanges(); var user = User.Identity.GetUserId(); if (document.assignedEntity.EntityType == "Course") { var courseDocument = new CourseDocument() { DocumentId = addDocument.Id, AssignDate = DateTime.Now, OwnerId = User.Identity.GetUserId(), CourseId = document.assignedEntity.Id }; db.CourseDocuments.Add(courseDocument); db.SaveChanges(); } else if (document.assignedEntity.EntityType == "Module") { var moduleDocument = new ModuleDocument() { DocumentId = addDocument.Id, AssignDate = DateTime.Now, OwnerId = User.Identity.GetUserId(), ModuleId = document.assignedEntity.Id }; db.ModuleDocuments.Add(moduleDocument); db.SaveChanges(); } else if (document.assignedEntity.EntityType == "Activity") { var activityDocument = new ActivityDocument() { DocumentId = addDocument.Id, AssignDate = DateTime.Now, OwnerId = User.Identity.GetUserId(), ActivityId = document.assignedEntity.Id }; db.ActivityDocuments.Add(activityDocument); db.SaveChanges(); } return(RedirectToAction("Details", "Courses", new { id = document.assignedEntity.returnId, redirect = document.assignedEntity.returnTarget })); } } catch { //Log the error (uncomment dex variable name and add a line here to write a log. ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); } } ViewBag.DocumentTypeId = new SelectList(db.DocumentTypes, "Id", "DocumentTypeName", document.DocumentTypeId); return(View(document)); }
public ActionResult Edit([Bind(Include = "DocNo,OrganName,Date,Subject,ActName,StartDate,EndDate,Place,StdBudget,OthName,OthBudget,Total,Act1,Act2,Act3,Act4,Act5,Act6,Result1,Comment1,Result1Date,Result2,Comment2,Result2Date,Result3,Comment3,Result3Date,Result4,Comment4,Result4Date,Result5,Comment5,Result5Date,Result6,Comment6,Result6Date,Result7,Comment7,Result7Date,Remark")] Proposal proposal, HttpPostedFileBase upload, string id) { 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); } proposal.Files = new List <File> { avatar }; } } if (proposal.Result1 == "Edit" || proposal.Result1 == "Reject") { proposal.Remark = proposal.Remark + " " + Session["Position"] + " >>>>>>> " + " [" + proposal.Result1Date + "] " + proposal.Result1 + " Comment : " + proposal.Comment1; } if (proposal.Result2 == "Edit" || proposal.Result2 == "Reject") { proposal.Remark = proposal.Remark + " " + Session["Position"] + " >>>>>>> " + " [" + proposal.Result2Date + "] " + proposal.Result2 + " Comment : " + proposal.Comment2; } if (proposal.Result3 == "Edit" || proposal.Result3 == "Reject") { proposal.Remark = proposal.Remark + " " + Session["Position"] + " >>>>>>> " + " [" + proposal.Result3Date + "] " + proposal.Result3 + " Comment : " + proposal.Comment3; } if (proposal.Result4 == "Edit" || proposal.Result4 == "Reject") { proposal.Remark = proposal.Remark + " " + Session["Position"] + " >>>>>>> " + " [" + proposal.Result4Date + "] " + proposal.Result4 + " Comment : " + proposal.Comment4; } if (proposal.Result5 == "Edit" || proposal.Result5 == "Reject") { proposal.Remark = proposal.Remark + " " + Session["Position"] + " >>>>>>> " + " [" + proposal.Result5Date + "] " + proposal.Result5 + " Comment : " + proposal.Comment5; } if (proposal.Result6 == "Edit" || proposal.Result6 == "Reject") { proposal.Remark = proposal.Remark + " " + Session["Position"] + " >>>>>>> " + " [" + proposal.Result6Date + "] " + proposal.Result6 + " Comment : " + proposal.Comment6; } if (proposal.Result7 == "Edit" || proposal.Result7 == "Reject") { proposal.Remark = proposal.Remark + " " + Session["Position"] + " >>>>>>> " + " [" + proposal.Result7Date + "] " + proposal.Result7 + " Comment : " + proposal.Comment7; } db.Entry(proposal).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } catch (RetryLimitExceededException /* dex */) { //Log the error (uncomment dex variable name and add a line here to write a log. ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); } return(View(proposal)); }
/// <summary> /// Automatically reads 4 bytes from the reader and reverses them. /// </summary> /// <param name="br">The reader</param> /// <returns>Unsigned 32-bit integer</returns> static public uint ReadUInt32(System.IO.BinaryReader br) { return(System.Convert.ToUInt32(Reverse(br.ReadBytes(4)))); }
// load logs internal static void LoadLogs() { string File = OpenBveApi.Path.CombineFile(Program.FileSystem.SettingsFolder, "logs.bin"); try { using (System.IO.FileStream Stream = new System.IO.FileStream(File, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { using (System.IO.BinaryReader Reader = new System.IO.BinaryReader(Stream, System.Text.Encoding.UTF8)) { byte[] Identifier = new byte[] { 111, 112, 101, 110, 66, 86, 69, 95, 76, 79, 71, 83 }; const short Version = 1; byte[] Data = Reader.ReadBytes(Identifier.Length); for (int i = 0; i < Identifier.Length; i++) { if (Identifier[i] != Data[i]) { throw new System.IO.InvalidDataException(); } } short Number = Reader.ReadInt16(); if (Version != Number) { throw new System.IO.InvalidDataException(); } Game.LogRouteName = Reader.ReadString(); Game.LogTrainName = Reader.ReadString(); Game.LogDateTime = DateTime.FromBinary(Reader.ReadInt64()); Options.Current.CurrentGameMode = (Options.GameMode)Reader.ReadInt16(); Game.BlackBoxEntryCount = Reader.ReadInt32(); Game.BlackBoxEntries = new Game.BlackBoxEntry[Game.BlackBoxEntryCount]; for (int i = 0; i < Game.BlackBoxEntryCount; i++) { Game.BlackBoxEntries[i].Time = Reader.ReadDouble(); Game.BlackBoxEntries[i].Position = Reader.ReadDouble(); Game.BlackBoxEntries[i].Speed = Reader.ReadSingle(); Game.BlackBoxEntries[i].Acceleration = Reader.ReadSingle(); Game.BlackBoxEntries[i].ReverserDriver = Reader.ReadInt16(); Game.BlackBoxEntries[i].ReverserSafety = Reader.ReadInt16(); Game.BlackBoxEntries[i].PowerDriver = (Game.BlackBoxPower)Reader.ReadInt16(); Game.BlackBoxEntries[i].PowerSafety = (Game.BlackBoxPower)Reader.ReadInt16(); Game.BlackBoxEntries[i].BrakeDriver = (Game.BlackBoxBrake)Reader.ReadInt16(); Game.BlackBoxEntries[i].BrakeSafety = (Game.BlackBoxBrake)Reader.ReadInt16(); Game.BlackBoxEntries[i].EventToken = (Game.BlackBoxEventToken)Reader.ReadInt16(); } Game.ScoreLogCount = Reader.ReadInt32(); Game.ScoreLogs = new Game.ScoreLog[Game.ScoreLogCount]; Game.CurrentScore.Value = 0; for (int i = 0; i < Game.ScoreLogCount; i++) { Game.ScoreLogs[i].Time = Reader.ReadDouble(); Game.ScoreLogs[i].Position = Reader.ReadDouble(); Game.ScoreLogs[i].Value = Reader.ReadInt32(); Game.ScoreLogs[i].TextToken = (Game.ScoreTextToken)Reader.ReadInt16(); Game.CurrentScore.Value += Game.ScoreLogs[i].Value; } Game.CurrentScore.Maximum = Reader.ReadInt32(); Identifier = new byte[] { 95, 102, 105, 108, 101, 69, 78, 68 }; Data = Reader.ReadBytes(Identifier.Length); for (int i = 0; i < Identifier.Length; i++) { if (Identifier[i] != Data[i]) { throw new System.IO.InvalidDataException(); } } Reader.Close(); } Stream.Close(); } } catch { Game.LogRouteName = ""; Game.LogTrainName = ""; Game.LogDateTime = DateTime.Now; Game.BlackBoxEntries = new Game.BlackBoxEntry[256]; Game.BlackBoxEntryCount = 0; Game.ScoreLogs = new Game.ScoreLog[64]; Game.ScoreLogCount = 0; } }
public ActResource(string name, System.IO.Stream stream) : base(name, true) { int currentStreamPosition = (int)stream.Position; System.IO.BinaryReader reader = new System.IO.BinaryReader(stream, Encoding.ASCII); ActHeader header; header.Magic = reader.ReadUInt32(); if (header.Magic != 0x41435448) { throw new Resource.InvalidResourceFileFormat("Invalid ACT file header"); } header.Version1 = reader.ReadUInt16(); header.Version2 = reader.ReadUInt16(); header.NumFrames = reader.ReadUInt32(); header.NumMeshes = reader.ReadUInt32(); header.DataSize = reader.ReadUInt32(); header.ModelName = Gk3Main.Utils.ConvertAsciiToString(reader.ReadBytes(32)); _modelName = header.ModelName; _numMeshes = header.NumMeshes; _numFrames = header.NumFrames; _frames = new ActFrame[header.NumFrames * _numMeshes]; // read the offsets uint[] offsets = new uint[header.NumFrames]; for (int i = 0; i < header.NumFrames; i++) { offsets[i] = reader.ReadUInt32(); } for (uint i = 0; i < header.NumFrames; i++) { stream.Seek(currentStreamPosition + offsets[i], System.IO.SeekOrigin.Begin); uint frameSize; if (i == header.NumFrames - 1) { frameSize = header.DataSize - offsets[i]; } else { frameSize = offsets[i + 1] - offsets[i]; } readFrame(reader, i, frameSize); } // now we have all the frames loaded from the ACT file, // so now it's time to convert the frame data into a more // usable layout _animationFrames = new MeshAnimationFrame[_numMeshes][]; for (uint i = 0; i < _numMeshes; i++) { // count the active frames uint numActiveFramesThisMesh = 0; for (uint j = 0; j < _numFrames; j++) { if (_frames[j * _numMeshes + i].Active) { numActiveFramesThisMesh++; } } // create the frames _animationFrames[i] = new MeshAnimationFrame[numActiveFramesThisMesh]; uint currentFrame = 0; for (uint j = 0; j < _numFrames; j++) { if (_frames[j * _numMeshes + i].Active) { _animationFrames[i][currentFrame].Time = _millisecondsPerFrame * j; _animationFrames[i][currentFrame].Transform = _frames[j * _numMeshes + i].Transform; if (_frames[j * _numMeshes + i].Vertices != null) { _animationFrames[i][currentFrame].Vertices = _frames[j * _numMeshes + i].Vertices.ToArray(); } if (_frames[j * _numMeshes + i].BoundingBox != null) { _animationFrames[i][currentFrame].BoundingBox = _frames[j * _numMeshes + i].BoundingBox; } currentFrame++; } } } }
private void readMeshFrame(System.IO.BinaryReader reader, uint frameNum, uint meshIndex, uint sectionLength) { long end = reader.BaseStream.Position + sectionLength; uint frameIndex = frameNum * _numMeshes + meshIndex; while (reader.BaseStream.Position < end) { ActSubsectionHeader subsection; subsection.Type = reader.ReadByte(); subsection.DataSize = reader.ReadUInt32(); if (subsection.Type == (byte)ActSubsectionType.Group) { ushort groupIndex = reader.ReadUInt16(); ushort numVertices = reader.ReadUInt16(); float[] vertices = new float[numVertices * 3]; for (ushort j = 0; j < numVertices; j++) { vertices[j * 3 + 0] = reader.ReadSingle(); vertices[j * 3 + 1] = reader.ReadSingle(); vertices[j * 3 + 2] = reader.ReadSingle(); } _frames[frameIndex].Active = true; if (_frames[frameIndex].Vertices == null) { _frames[frameIndex].Vertices = new List <FrameSectionVertices>(); } FrameSectionVertices sectionVertices; sectionVertices.SectionIndex = groupIndex; sectionVertices.Vertices = vertices; _frames[frameIndex].Vertices.Add(sectionVertices); } else if (subsection.Type == (byte)ActSubsectionType.DeltaGroup) { ushort groupIndex = reader.ReadUInt16(); ushort numVertices = reader.ReadUInt16(); byte[] bitfield = reader.ReadBytes(numVertices / 4 + 1); float[] vertices = new float[numVertices * 3]; for (ushort j = 0; j < numVertices; j++) { int type = getDeltaType(j, bitfield); if (type == (int)VertexChangeType.None) { // nothing } else if (type == (int)VertexChangeType.Short) { vertices[j * 3 + 0] = uncompress(reader.ReadByte()); vertices[j * 3 + 1] = uncompress(reader.ReadByte()); vertices[j * 3 + 2] = uncompress(reader.ReadByte()); } else if (type == (int)VertexChangeType.Long) { vertices[j * 3 + 0] = uncompress(reader.ReadUInt16()); vertices[j * 3 + 1] = uncompress(reader.ReadUInt16()); vertices[j * 3 + 2] = uncompress(reader.ReadUInt16()); } else if (type == (int)VertexChangeType.Absolute) { vertices[j * 3 + 0] = reader.ReadSingle(); vertices[j * 3 + 1] = reader.ReadSingle(); vertices[j * 3 + 2] = reader.ReadSingle(); } } convertDeltaVerticesToAbsolute(vertices, (int)meshIndex, groupIndex, (int)frameNum); _frames[frameIndex].Active = true; if (_frames[frameIndex].Vertices == null) { _frames[frameIndex].Vertices = new List <FrameSectionVertices>(); } FrameSectionVertices sectionVertices; sectionVertices.SectionIndex = groupIndex; sectionVertices.Vertices = vertices; _frames[frameIndex].Vertices.Add(sectionVertices); } else if (subsection.Type == (byte)ActSubsectionType.Transform) { // read the 4x3 transform matrix float[] transform = new float[4 * 3]; transform[0] = reader.ReadSingle(); transform[1] = reader.ReadSingle(); transform[2] = reader.ReadSingle(); transform[3] = reader.ReadSingle(); transform[4] = reader.ReadSingle(); transform[5] = reader.ReadSingle(); transform[6] = reader.ReadSingle(); transform[7] = reader.ReadSingle(); transform[8] = reader.ReadSingle(); transform[9] = reader.ReadSingle(); transform[10] = reader.ReadSingle(); transform[11] = reader.ReadSingle(); _frames[frameIndex].Active = true; _frames[frameIndex].Transform = new FrameTransformation(transform); } else if (subsection.Type == (byte)ActSubsectionType.BoundingBox) { _frames[frameIndex].Active = true; _frames[frameIndex].BoundingBox = new float[6]; // read the bounding box _frames[frameIndex].BoundingBox[0] = reader.ReadSingle(); _frames[frameIndex].BoundingBox[1] = reader.ReadSingle(); _frames[frameIndex].BoundingBox[2] = reader.ReadSingle(); _frames[frameIndex].BoundingBox[3] = reader.ReadSingle(); _frames[frameIndex].BoundingBox[4] = reader.ReadSingle(); _frames[frameIndex].BoundingBox[5] = reader.ReadSingle(); } else { throw new Exception("Invalid subsection type found"); } } }
private void bEdit_Click(object sender, EventArgs e) { if (dataGridView1.SelectedRows.Count == 0) { return; } int i = (int)dataGridView1.SelectedRows[0].Tag; switch (mode) { case Mode.Arrays: { DataType[] types = new DataType[connection.ArrayLengths[i]]; int[] lenType = new int[connection.ArrayLengths[i]]; string[] strings = new string[connection.ArrayLengths[i]]; connection.WriteDataType(DataTypeSend.GetArray); // code connection.WriteInt(i); // index int lenData = 0; for (int j = 0; j < strings.Length; j++) { types[j] = (DataType)connection.ReadInt(); lenType[j] = connection.ReadInt(); // len data of type lenData += lenType[j]; } byte[] buf = connection.ReadBytes(lenData); // read data BinaryReader br = new BinaryReader(new MemoryStream(buf)); for (int j = 0; j < strings.Length; j++) { switch (types[j]) { case DataType.None: br.BaseStream.Position += 4; break; case DataType.Int: strings[j] = br.ReadInt32().ToString(); break; case DataType.Float: strings[j] = br.ReadSingle().ToString(); break; case DataType.String: byte[] bytes = br.ReadBytes(lenType[j]); strings[j] = System.Text.Encoding.ASCII.GetString(bytes, 0, Array.IndexOf <byte>(bytes, 0)); break; } } br.Close(); strings = EditorWindow.ShowEditor(this, null, types, strings, connection.ArrayIsMap[i]); if (strings != null) // save { MemoryStream ms = new MemoryStream(lenData); BinaryWriter bw = new BinaryWriter(ms); for (int j = 0; j < strings.Length; j++) { switch (types[j]) { case DataType.None: bw.BaseStream.Position += 4; break; case DataType.Int: bw.Write(int.Parse(strings[j])); break; case DataType.Float: bw.Write(float.Parse(strings[j])); break; case DataType.String: byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strings[j]); if (bytes.Length < lenType[j]) { bw.Write(bytes); } else { bw.Write(bytes, 0, lenType[j] - 1); } bw.Write((byte)0); break; } } // send data to sfall connection.WriteDataType(DataTypeSend.SetArray); connection.WriteInt(i); // index connection.WriteInt(lenData); connection.WriteBytes(ms.GetBuffer(), 0, lenData); bw.Close(); } } break; case Mode.Critters: { DataType[] types = new DataType[33]; string[] strings = new string[33]; string[] names = new string[33]; connection.WriteDataType(DataTypeSend.RetrieveCritter); connection.WriteInt(i); BinaryReader br = new BinaryReader(new System.IO.MemoryStream(connection.ReadBytes(33 * 4))); for (int j = 0; j < 33; j++) { types[j] = DataType.Int; strings[j] = br.ReadInt32().ToString(); } br.Close(); names[0] = " ID"; names[1] = " Tile"; names[6] = " Current frame"; names[7] = " Rotation"; names[8] = " FID"; names[9] = " Flags"; names[10] = " Elevation"; names[11] = " Inventory count"; names[13] = " Inventory pointer"; names[14] = " Reaction"; names[15] = " Combat state"; names[16] = " Current AP"; names[17] = " Combat flags"; names[18] = " Last Turn Damage"; names[19] = " AI Packet"; names[20] = " Team"; names[21] = " Who hit me"; names[22] = " HP"; names[23] = " Rads"; names[24] = " Poison"; names[25] = " Proto ID"; names[26] = " Combat ID"; names[29] = " Outline flags"; names[30] = " Script ID"; names[32] = " Script index"; strings = EditorWindow.ShowEditor(this, names, types, strings); if (strings != null) { MemoryStream ms = new MemoryStream(33 * 4); BinaryWriter bw = new BinaryWriter(ms); for (int j = 0; j < 33; j++) { bw.Write(int.Parse(strings[j])); } connection.WriteDataType(DataTypeSend.SetCritter); connection.WriteInt(i); connection.WriteBytes(ms.GetBuffer(), 0, 33 * 4); bw.Close(); } } break; } }
/// <summary>Loads a wave/riff audio file from a stream. Resource file can be passed as the stream.</summary> private static byte[] LoadWave(System.IO.Stream stream, out int channels, out int bits, out int rate) { if (stream == null) { throw new ArgumentNullException("stream"); } // ReSharper disable UnusedVariable using (var reader = new System.IO.BinaryReader(stream)) { //RIFF header var signature = new string(reader.ReadChars(4)); if (signature != "RIFF") { throw new NotSupportedException("Specified stream is not a wave file."); } int riffChunckSize = reader.ReadInt32(); var format = new string(reader.ReadChars(4)); if (format != "WAVE") { throw new NotSupportedException("Specified stream is not a wave file."); } //WAVE header var formatSignature = new string(reader.ReadChars(4)); if (formatSignature != "fmt ") { throw new NotSupportedException("Specified wave file is not supported."); } int formatChunkSize = reader.ReadInt32(); int audioFormat = reader.ReadInt16(); int numChannels = reader.ReadInt16(); int sampleRate = reader.ReadInt32(); int byteRate = reader.ReadInt32(); int blockAlign = reader.ReadInt16(); int bitsPerSample = reader.ReadInt16(); var dataSignature = new string(reader.ReadChars(4)); //check if the data dignature for this chunk is LIST headers, can happen with .wav files from web, or when converting other formats such as .mp3 to .wav using tools such as audacity //if this happens, the extra header info can be cleared using audacity, export to wave and select 'clear' when the extra header info window appears //see http://www.lightlink.com/tjweber/StripWav/WAVE.html if (dataSignature == "LIST") { throw new NotSupportedException("Specified wave file contains LIST headers (author, copyright etc)."); } if (dataSignature != "data") { throw new NotSupportedException("Specified wave file is not supported."); } int dataChunkSize = reader.ReadInt32(); channels = numChannels; bits = bitsPerSample; rate = sampleRate; return(reader.ReadBytes((int)reader.BaseStream.Length)); } // ReSharper restore UnusedVariable }