public IActionResult PostNewEntry([FromBody] NewEntry newEntry) { try { StringValues accessToken = new StringValues(); Request.Headers.TryGetValue("Authorization", out accessToken); if (accessToken.Count() == 0) { return(StatusCode(401, "Empty or no authorization header.")); } if (accessToken.FirstOrDefault().ToString() == null || accessToken.FirstOrDefault().ToString() == "") { return(StatusCode(401, "Empty or no authorization header.")); } if (_validation.CheckValidation(accessToken.ToString())) { Tuple <Games, int> tuple = _rdsLogic.PostNewEntry(newEntry); if (tuple.Item2 == 1) { return(StatusCode(409, "That game name already exists.")); } _ec2Logic.StartAutomatedTestingEC2(); return(StatusCode(201, tuple.Item1)); } return(StatusCode(403, "This is an invalid access token.")); } catch (Exception e) { _logger.LogError(e.Message, e); return(StatusCode(500, e.Message)); } }
public Entry(long journalId, NewEntry model) { JournalId = journalId; Title = model.Title; Tags = model.Tags; Body = model.Body; }
public async Task <EntryResult> AddNewEntry(NewEntry newEntry) { await _repository.AddNewPlayerIfNecessary(newEntry.Name); bool banned = await _repository.IsPlayerBanned(newEntry.Name); if (banned) { EntryResult result = new EntryResult(); result.Name = newEntry.Name; result.Banned = true; result.BestRanking = 0; result.BestScore = 0; result.Score = 0; result.Ranking = 0; return(result); } else { ScoreEntry entry = new ScoreEntry(); entry.Date = DateTime.UtcNow; entry.Name = newEntry.Name; entry.Score = newEntry.Score; entry._id = Guid.NewGuid(); return(await _repository.AddNewEntry(entry)); } }
public IActionResult PutNewEntry([FromBody] NewEntry updateEntry) { try { StringValues accessToken = new StringValues(); Request.Headers.TryGetValue("Authorization", out accessToken); if (accessToken.Count() == 0) { return(StatusCode(401, "Empty or no authorization header.")); } if (accessToken.FirstOrDefault().ToString() == null || accessToken.FirstOrDefault().ToString() == "") { return(StatusCode(401, "Empty or no authorization header.")); } if (_validation.CheckValidation(accessToken.ToString())) { _rdsLogic.PutNewEntry(updateEntry); _ec2Logic.StartAutomatedTestingEC2(); return(StatusCode(200)); } return(StatusCode(403, "This is an invalid access token.")); } catch (Exception e) { _logger.LogError(e.Message, e); return(StatusCode(500, e.Message)); } }
public IRobotLog AddEntry(RobotLogEntry entry) { MessagesList.Add(entry); NewEntry?.Invoke(this, new RobotLogNewEntryEventArgs(entry)); return(this); }
public void VerifyAddANewValueInDictionary() { var newEntry = new NewEntry("apple", "It is a fruit"); var newEntry2 = new NewEntry("pear", "It is a fruit"); var dictionary = new DictionaryClass<string, NewEntry>(); dictionary.Add(newEntry.Name, newEntry); dictionary.Add(newEntry2.Name, newEntry2); }
public ActionResult DeleteConfirmed(int id) { NewEntry newEntry = db.NewEntries.Find(id); db.NewEntries.Remove(newEntry); db.SaveChanges(); return(RedirectToAction("Index")); }
/// <summary> /// Log an arbitrary string to current log. /// </summary> /// <param name="message">The message to log. Can include newline (\n) characters to split into multiple lines.</param> /// <param name="level">The verbosity level.</param> public void Add(string message = @"", LogLevel level = LogLevel.Verbose) { #if Public if (level < LogLevel.Important) { return; } #endif #if !DEBUG if (level <= LogLevel.Debug) { return; } #endif if (!Enabled) { return; } message = ApplyFilters(message); //split each line up. string[] lines = message.TrimEnd().Replace(@"\r\n", @"\n").Split('\n'); for (int i = 0; i < lines.Length; i++) { string s = lines[i]; lines[i] = $@"{DateTime.UtcNow.ToString(NumberFormatInfo.InvariantInfo)}: {s.Trim()}"; } LogEntry entry = new LogEntry { Level = level, Target = Target, Message = message }; NewEntry?.Invoke(entry); backgroundScheduler.Add(delegate { ensureLogDirectoryExists(); if (!hasLogDirectory.Value) { return; } try { File.AppendAllLines(Filename, lines); } catch { } }); }
private void AddButton_Click(object sender, RoutedEventArgs e) { NewEntry newEntryWindow = new NewEntry(externalDataStructureList.DataStructure, (dataItem) => { externalDataStructureList.Items.Add(dataItem); Data.SaveData(); }); newEntryWindow.Owner = Window.GetWindow(this); newEntryWindow.ShowDialog(); }
public void VerifyFindAStructureWithSameHashCodeDictionary() { var dictionary = new DictionaryClass<string, NewEntry>(); var newEntry = new NewEntry("apple", "It is a fruit"); var newEntry2 = new NewEntry("tomato", "It is a vegetable"); dictionary.Add(newEntry.Name, newEntry); dictionary.Add(newEntry2.Name, newEntry2); var word = dictionary.Find(newEntry2.Name); word.ShouldEqual<NewEntry>(newEntry2); }
public void VerifyAddANewValueInEmptyDictionary() { var newEntry = new NewEntry("apple", "It is a fruit"); var newEntry2 = new NewEntry("pear", "It is a fruit"); var newEntry3 = new NewEntry("tomato", "It is a vegetable"); var dictionary = new DictionaryClass<string, NewEntry>(); dictionary.Add(newEntry.Name, newEntry); dictionary.Add(newEntry2.Name, newEntry2); dictionary.Add(newEntry3.Name, newEntry3); dictionary.Count.ShouldEqual(3); }
public ActionResult Add(NewEntry model) { var entry = AutoMapper.Mapper.Map <Entry>(model); entry.PlayerId = SessionProfile.Player.Id; _entryService.Add(entry); SessionProfile.Player = _playerService.FindById(SessionProfile.Player.Id); return(RedirectToAction("Index", "Entry")); }
public HttpStatusCode AddEntry([FromBody] NewEntry newEntry) { if (newEntry == null) { return(HttpStatusCode.BadRequest); } repository.Add(Mapper.Map <NewEntry, TimeSheetEntry>(newEntry)); return(HttpStatusCode.OK); }
public ActionResult Edit([Bind(Include = "Id,CorrelativeBill,IdItem,InQuantity,Distributor")] NewEntry newEntry) { if (ModelState.IsValid) { db.Entry(newEntry).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.IdItem = new SelectList(db.Items, "Id", "NameItem", newEntry.IdItem); return(View(newEntry)); }
private void InitializeLists() { String[] names = { "Aake", "Jamppa", "HenriLep", "Matti", "Teppo", "Seppo", "Timo", "Jari", "Ari", "Jake666" }; NewEntry entry = new NewEntry(); for (int i = 0; i < 200; i++) { entry.name = names[UnityEngine.Random.Range(0, names.Length - 1)]; entry.score = UnityEngine.Random.Range(40, 150); AddNewScoreInit(entry); } }
public void StartListener() { entryListener = instance.AddEntryListener("", (in RefEntryNotification notification) => { if (notification.Flags.HasFlag(NotifyFlags.New)) { NewEntry?.Invoke(notification.Name, notification.Entry, notification.Value.ToValue()); } else if (notification.Flags.HasFlag(NotifyFlags.Delete)) { DeletedEntry?.Invoke(notification.Name); } }, NotifyFlags.New | NotifyFlags.Delete | NotifyFlags.Immediate | NotifyFlags.Local);
// GET: NewEntries/Details/5 public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } NewEntry newEntry = db.NewEntries.Find(id); if (newEntry == null) { return(HttpNotFound()); } return(View(newEntry)); }
// GET: NewEntries/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } NewEntry newEntry = db.NewEntries.Find(id); if (newEntry == null) { return(HttpNotFound()); } ViewBag.IdItem = new SelectList(db.Items, "Id", "NameItem", newEntry.IdItem); return(View(newEntry)); }
public Games InsertArrayToColumn(Games game, NewEntry newEntry) { try { int size = newEntry.GameImg.Count(); switch (size) { case 1: game.GameImage0 = newEntry.GameImg[0]; break; case 2: game.GameImage0 = newEntry.GameImg[0]; game.GameImage1 = newEntry.GameImg[1]; break; case 3: game.GameImage0 = newEntry.GameImg[0]; game.GameImage1 = newEntry.GameImg[1]; game.GameImage2 = newEntry.GameImg[2]; break; case 4: game.GameImage0 = newEntry.GameImg[0]; game.GameImage1 = newEntry.GameImg[1]; game.GameImage2 = newEntry.GameImg[2]; game.GameImage3 = newEntry.GameImg[3]; break; case 5: game.GameImage0 = newEntry.GameImg[0]; game.GameImage1 = newEntry.GameImg[1]; game.GameImage2 = newEntry.GameImg[2]; game.GameImage3 = newEntry.GameImg[3]; game.GameImage4 = newEntry.GameImg[4]; break; default: break; } } catch (Exception e) { _logger.LogCritical(e.Message, e); } return(game); }
public Entry Add(Journal journal, NewEntry model) { if (journal is null) { throw new ArgumentNullException(nameof(journal)); } if (model is null) { throw new ArgumentNullException(nameof(model)); } var newEntry = new Entry(journal.Id, model); journal.Entries.Add(newEntry); return(newEntry); }
private void navNewEntry_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e) { dwWin2.Hide(); dwWin1.Hide(); dwWin1.Text = "New Entry123"; NewEntry frm = new NewEntry() { TopLevel = false }; radPanel1.Controls.Clear(); frm.FormBorderStyle = FormBorderStyle.None; frm.Dock = DockStyle.Fill; radPanel1.Controls.Add(frm); frm.Execute(); dwWin1.Show(); }
public void ProcessRequest_InvalidItemName_ReturnsEmptyResult(string itemName) { // arrange var blogManager = Mock.Of <IBlogManager>(); var itemManager = Mock.Of <BaseItemManager>(); var sut = new NewEntry(blogManager, itemManager, Mock.Of <IBlogSettingsResolver>()); sut.RequestContext = new ItemContext { Argument = itemName }; // act var result = sut.ProcessRequest(); // assert Assert.That(result.Value, Is.Null); }
public async Task <IActionResult> AddEntry(long journalId, [FromBody] NewEntry newEntry) { Entry entry; try { entry = await _journalService.AddEntry(journalId, newEntry); } catch (JournalNotFoundException ex) { return(NotFound(ex.Message)); } catch (Exception ex) { return(BadRequest(ex.Message)); } return(CreatedAtAction(nameof(AddEntry), entry)); }
public async Task <Entry> AddEntry(long journalId, NewEntry newEntry) { using var unitOfWork = GetUnitOfWork(); var journal = await unitOfWork .Journals.Find(j => j.Id == journalId); if (journal is null) { throw new JournalNotFoundException($"Journal not found: {journalId}"); } if (newEntry is null) { throw new ArgumentNullException(nameof(newEntry)); } var entry = _entryService.Add(journal, newEntry); await unitOfWork.Complete(); return(entry); }
public void ProcessRequest_ContextItemUnderBlog_CreatesEntryItem() { // arrange var entryTemplateId = ID.NewID; var contextItem = ItemFactory.CreateItem().Object; var blogItem = ItemFactory.CreateItem().Object; var weblogSettings = Mock.Of <IWeBlogSettings>(x => x.EntryTemplateIds == new[] { entryTemplateId }); var blogManager = Mock.Of <IBlogManager>(x => x.GetCurrentBlog(contextItem) == (BlogHomeItem)blogItem ); var newItem = ItemFactory.CreateItem().Object; var itemManager = new Mock <BaseItemManager>(); itemManager.Setup(x => x.AddFromTemplate("entry", entryTemplateId, blogItem)).Returns(newItem).Verifiable(); var settingsResolver = Mock.Of <IBlogSettingsResolver>(x => x.Resolve(It.IsAny <BlogHomeItem>()) == new BlogSettings(weblogSettings)); var sut = new NewEntry(blogManager, itemManager.Object, settingsResolver); var context = new ItemContext { Argument = "entry" }; context.PopulateContextData(contextItem, Mock.Of <RenderingParametersResolver>()); sut.RequestContext = context; // act var result = sut.ProcessRequest(); // assert itemManager.Verify(); var id = GetItemIdFromAnonymousResult(result.Value); Assert.That(id, Is.EqualTo(newItem.ID.Guid)); }
public void Entry(JournalEntry je, bool stored, bool recent) // on UI thread. hooked into journal monitor and receives new entries.. Also call if you programatically add an entry { System.Diagnostics.Debug.Assert(System.Windows.Forms.Application.MessageLoop); if (je.EventTimeUTC >= lastutc) // in case we get them fed in the wrong order, or during stored reply we have two playing, only take the latest one { System.Diagnostics.Debug.WriteLine("JE " + stored + ":" + recent + ":" + EDCommander.GetCommander(je.CommanderId).Name + ":" + je.EventTypeStr); if (je.CommanderId != currentcmdrnr) { Reset(false); currentcmdrnr = je.CommanderId; EDCommander.CurrentCmdrID = currentcmdrnr; } HistoryEntry he = HistoryEntry.FromJournalEntry(je, currenthe, false, out bool unusedjournalupdate); he.UpdateMaterials(je, currenthe); cashledger.Process(je); he.Credits = cashledger.CashTotal; he.UpdateMissionList(missionlistaccumulator.Process(je, he.System, he.WhereAmI)); currenthe = he; lastutc = je.EventTimeUTC; outfitting.Process(je); Tuple <ShipInformation, ModulesInStore> ret = shipinformationlist.Process(je, he.WhereAmI, he.System); he.UpdateShipInformation(ret.Item1); he.UpdateShipStoredModules(ret.Item2); NewEntry?.Invoke(he, stored, recent); } else { //System.Diagnostics.Debug.WriteLine("Rejected older JE " + stored + ":" + recent + ":" + EDCommander.GetCommander(je.CommanderId).Name + " " + je.EventTypeStr); } }
public void ProcessRequest_ContextItemNotUnderBlog_DoesNotCreateAnyItems() { // arrange var contextItem = ItemFactory.CreateItem().Object; var blogManager = Mock.Of <IBlogManager>(); var itemManager = new Mock <BaseItemManager>(); var sut = new NewEntry(blogManager, itemManager.Object, Mock.Of <IBlogSettingsResolver>()); var context = new ItemContext { Argument = "entry" }; context.PopulateContextData(contextItem, Mock.Of <RenderingParametersResolver>()); sut.RequestContext = context; // act var result = sut.ProcessRequest(); // assert itemManager.Verify(x => x.AddFromTemplate(It.IsAny <string>(), It.IsAny <ID>(), It.IsAny <Item>()), Times.Never); }
public ActionResult NewEntry(NewEntry entry) { if (ModelState.IsValid) { var dbEntry = new BlogEntry(); using (var db = new BlogContext()) { dbEntry.Topic = entry.Topic; dbEntry.Date = DateTime.Now; dbEntry.Author = db.Accounts.First(a => a.Name.Equals(User.Identity.Name)); db.Entries.Add(dbEntry); db.SaveChanges(); HandleParagraphs(db, dbEntry, entry.Text); HandleUploadedImage(dbEntry); HandleTags(db, dbEntry, entry.Tags); db.SaveChanges(); return(RedirectToAction("ListOfEntries", "EntriesList")); } } else { return(View(entry)); } }
private void add(string message = @"", LogLevel level = LogLevel.Verbose, bool outputToListeners = true) { if (!Enabled || level < Level) { return; } ensureHeader(); #if DEBUG if (outputToListeners) { var debugLine = $"[{Target?.ToString().ToLower() ?? Name}:{level.ToString().ToLower()}] {message}"; // fire to all debug listeners (like visual studio's output window) System.Diagnostics.Debug.Print(debugLine); // fire for console displays (appveyor/CI). Console.WriteLine(debugLine); } #endif #if Public if (level < LogLevel.Important) { return; } #endif #if !DEBUG if (level <= LogLevel.Debug) { return; } #endif message = ApplyFilters(message); //split each line up. string[] lines = message.Replace(@"\r\n", @"\n").Split('\n'); for (int i = 0; i < lines.Length; i++) { string s = lines[i]; lines[i] = $@"{DateTime.UtcNow.ToString(NumberFormatInfo.InvariantInfo)}: {s.Trim()}"; } if (outputToListeners) { NewEntry?.Invoke(new LogEntry { Level = level, Target = Target, LoggerName = Name, Message = message }); } if (Target == LoggingTarget.Information) { // don't want to log this to a file return; } lock (flush_sync_lock) { // we need to check if the logger is still enabled here, since we may have been waiting for a // flush and while the flush was happening, the logger might have been disabled. In that case // we want to make sure that we don't accidentally write anything to a file after that flush. if (!Enabled) { return; } backgroundScheduler.Add(delegate { try { using (var stream = Storage.GetStream(Filename, FileAccess.Write, FileMode.Append)) using (var writer = new StreamWriter(stream)) foreach (var line in lines) { writer.WriteLine(line); } } catch { } }); } }
/// <summary> /// Log an arbitrary string to current log. /// </summary> /// <param name="message">The message to log. Can include newline (\n) characters to split into multiple lines.</param> /// <param name="level">The verbosity level.</param> public void Add(string message = @"", LogLevel level = LogLevel.Verbose) { #if DEBUG var debugLine = $"[{Target.ToString().ToLower()}:{level.ToString().ToLower()}] {message}"; // fire to all debug listeners (like visual studio's output window) System.Diagnostics.Debug.Print(debugLine); // fire for console displays (appveyor/CI). Console.WriteLine(debugLine); #endif #if Public if (level < LogLevel.Important) { return; } #endif #if !DEBUG if (level <= LogLevel.Debug) { return; } #endif if (!Enabled) { return; } message = ApplyFilters(message); //split each line up. string[] lines = message.TrimEnd().Replace(@"\r\n", @"\n").Split('\n'); for (int i = 0; i < lines.Length; i++) { string s = lines[i]; lines[i] = $@"{DateTime.UtcNow.ToString(NumberFormatInfo.InvariantInfo)}: {s.Trim()}"; } LogEntry entry = new LogEntry { Level = level, Target = Target, Message = message }; NewEntry?.Invoke(entry); if (Target == LoggingTarget.Information) { // don't want to log this to a file return; } background_scheduler.Add(delegate { if (Storage == null) { return; } try { using (var stream = Storage.GetStream(Filename, FileAccess.Write, FileMode.Append)) using (var writer = new StreamWriter(stream)) foreach (var line in lines) { writer.WriteLine(line); } } catch { } }); }
public Tuple <Games, int> PostNewEntry(NewEntry newEntry) { Games newGame = new Games() { GameControls = newEntry.GameControls, GameCreatorName = newEntry.GameCreatorName, GameDescription = newEntry.GameDescription, GameGenreAction = newEntry.GameGenreAction, GameGenreAdventure = newEntry.GameGenreAdventure, GameGenreFighting = newEntry.GameGenreFighting, GameGenrePuzzle = newEntry.GameGenrePuzzle, GameGenreRacing = newEntry.GameGenreRacing, GameGenreRhythm = newEntry.GameGenreRhythm, GameGenreRpg = newEntry.GameGenreRpg, GameGenreShooter = newEntry.GameGenreShooter, GameGenreSports = newEntry.GameGenreSports, GameGenreStrategy = newEntry.GameGenreStrategy, GameGenreSurvival = newEntry.GameGenreSurvival, GameGenrePlatformer = newEntry.GameGenrePlatformer, GameName = newEntry.GameName, GamePath = newEntry.GamePath, GameVideolink = newEntry.GameVideoLink, GameOnArcade = false, GameStatus = "t", GameSubmissionDateUtc = DateTime.UtcNow, GameAvailableToDownload = newEntry.GameAvailableToDownload }; char[] s = new char[5]; newGame = InsertArrayToColumn(newGame, newEntry); if (_rdsData.GetGames(newGame.GameName) != null) { return(Tuple.Create <Games, int>(null, 1)); } try { _rdsData.PostGames(newGame); Games postedGame = _rdsData.GetGames(newGame.GameName); Submissions newSubmission = new Submissions() { GameId = postedGame.GameId, SubmissionDateUtc = postedGame.GameSubmissionDateUtc, SubmissionImage0 = postedGame.GameImage0, SubmissionName = postedGame.GameName, SubmissionStatus = postedGame.GameStatus, CreatorName = postedGame.GameCreatorName, CreatorEmail = newEntry.GameCreatorEmail }; _rdsData.PostSubmissions(newSubmission); TestsQueue newTestQueue = new TestsQueue() { GameId = postedGame.GameId, RetryCount = 0 }; _rdsData.PostTestsQueue(newTestQueue); Tests newTest = new Tests() { GameId = postedGame.GameId, Test5min = false, TestCloses = false, TestOpens = false, TestAttempts = 0, TestAverageRam = null, TestCloseOn3 = null, TestCloseOnEscape = null, TestFolderFileNames = null, TestNumExeFiles = null, TestPeakRam = null }; _rdsData.PostTests(newTest); return(Tuple.Create(newGame, 0)); } catch (Exception e) { _logger.LogError(e.Message, e); CleanUpOnCrash((int)newGame.GameId); throw new Exception(e.Message); } }
public IEnumerator ISendResult() { //tämä ei toimi NewEntry n = new NewEntry { name = playersName, score = playersScore }; string entryJson = JsonUtility.ToJson(n); byte[] bytes = Encoding.UTF8.GetBytes(entryJson); WWWForm form = new WWWForm(); form.AddBinaryData("body", bytes); UnityWebRequest req = UnityWebRequest.Post(www, form); req.SetRequestHeader("Content-Type", "application/json"); req.SetRequestHeader("UnityKey", "unity1234"); req.uploadHandler = new UploadHandlerRaw(bytes); req.uploadHandler.contentType = "application/json"; yield return(req.SendWebRequest()); if (req.isNetworkError || req.isHttpError) { Debug.Log(req.error); } else { string a = req.downloadHandler.text; EntryResult result = JsonUtility.FromJson <EntryResult>(a); if (result.ranking > 0) { madeItOrNotText.text = "YOU MADE IT TO THE LIST"; int startFrom; if (result.ranking < 10) { startFrom = 1; } else { startFrom = result.ranking - 4; } string searchUrl = www + "?slice=" + startFrom; UnityWebRequest webRequest = UnityWebRequest.Get(searchUrl); webRequest.SetRequestHeader("unityKey", "unity1234"); yield return(webRequest.SendWebRequest()); if (webRequest.isNetworkError || webRequest.isHttpError) { Debug.Log(webRequest.error); } else { string entryList = webRequest.downloadHandler.text; ScoreEntryArray sArray = JsonUtility.FromJson <ScoreEntryArray>("{\"entries\":" + entryList.ToString() + "}"); FillInScoreListWithEntry(sArray.entries.ToArray(), startFrom, result); } } else { madeItOrNotText.text = "Bummer... Not good enough"; HighScoresButtonPressed(); } } }
public void Build(Stream destStream) { // Check there are no duplicated indexes HashSet <int> indexSet = new HashSet <int>(); foreach (var entry in ReplacementEntries) { if (entry.Index < 0) { throw new InvalidOperationException("Entry with negative index present."); } indexSet.Add(entry.Index); } if (indexSet.Count != ReplacementEntries.Count) { throw new InvalidOperationException("Replacement entries with non-unique IDs present."); } ReplacementEntries.Sort((x, y) => x.Index.CompareTo(y.Index)); List <NewEntry> newEntries = new List <NewEntry>(); // Copy over original entries if (sourceDat != null) { for (int i = 0; i < sourceDat.EntriesCount; ++i) { var e = sourceDat.GetEntry(i); newEntries.Add(new NewEntry { OrigEntry = e, OrigIndex = i }); } } // Set replacement entries foreach (var rep in ReplacementEntries) { if (rep.Index > newEntries.Count) { throw new InvalidOperationException("Replacement entries results in incontinuity."); } var newEntry = new NewEntry { ReplacementEntry = rep }; if (rep.Index == newEntries.Count) { newEntries.Add(newEntry); } else { newEntries[rep.Index] = newEntry; } } // Update size and position uint dataOffset = 0; for (int i = 0; i < newEntries.Count; ++i) { var newEntry = newEntries[i]; newEntry.ArchEntry.Offset = dataOffset; var repEntry = newEntry.ReplacementEntry; if (repEntry == null) { newEntry.ArchEntry.Length = newEntry.OrigEntry.Length; } else { if (repEntry.SourceDat != null) { if (repEntry.SourceFile != null) { throw new InvalidOperationException("Replacement entries with both DAT and file source specified exist."); } newEntry.ArchEntry.Length = repEntry.SourceDat.GetEntry(repEntry.SourceIndex).Length; } else if (repEntry.SourceFile != null) { newEntry.ArchEntry.Length = (uint)new FileInfo(repEntry.SourceFile).Length; } else { newEntry.ArchEntry.Length = 0; newEntries.RemoveAt(i); --i; } } dataOffset += newEntry.ArchEntry.Length; } // Write file BinaryWriter bw = new BinaryWriter(destStream); bw.Write("DAT\0".ToCharArray()); bw.Write(newEntries.Count); dataOffset = (uint)(((newEntries.Count + 1) * 8 + 15) & ~15); foreach (var newEntry in newEntries) { newEntry.ArchEntry.Offset += dataOffset; newEntry.ArchEntry.Write(bw); } // Do we need to 16-byte align anything after the header? if (destStream.Position < dataOffset) { bw.Write(new byte[dataOffset - destStream.Position]); } foreach (var newEntry in newEntries) { var repEntry = newEntry.ReplacementEntry; if (repEntry == null) { bw.Write(sourceDat.GetData(newEntry.OrigIndex)); } else { if (repEntry.SourceDat != null) { bw.Write(repEntry.SourceDat.GetData(repEntry.SourceIndex)); } else { using (FileStream fs = File.OpenRead(repEntry.SourceFile)) { fs.CopyTo(destStream); } } } } }
public void FindAWordInEmptyDictionary() { var newEntry = new NewEntry("apple", "It is a fruit"); var dictionary = new DictionaryClass<string, NewEntry>(); dictionary.ContainsKey(newEntry.Name).ShouldBeFalse(); }