public MainWindow() { InitializeComponent(); currentJournal = new Journal("My Journal"); dataGrid_JournalEntries.ItemsSource = currentJournal.Entries; }
public static List<Journal> getAllLogs(String filter) { String where = ""; if (!String.IsNullOrEmpty(filter)) { where = " where " + filter; } string sql = @"SELECT [category.description] as category,[log.description] as description,[when] FROM [log] INNER JOIN [category] ON log.category_id=category.id" + where + " ORDER BY [when] desc"; ContentProvider provider = ContentProvider.getInstance(); DataTable dt = provider.query(sql); List<Journal> logs = new List<Journal>(); for (int i = 0; i < dt.Rows.Count; i++) { DataRow row = dt.Rows[i]; Journal log = new Journal(); log.when = row["when"].ToString(); log.category = row["category"].ToString(); log.description = row["description"].ToString(); logs.Add(log); } return logs; }
public void cannot_be_marked_as_verified_if_IsValid_is_false() { var journal = new Journal(_today, "Hotel Jezzera"); Assert.IsFalse(journal.IsValid); Assert.Throws<InValidJournalCannotBeVerifiedException>(() => journal.IsLocked = true); }
public IEnumerable<Journal> ParseJournal(XElement recordElement) { var regularJournal = new Journal { Title = recordElement.Element("Title").Value, ISSN = recordElement.Element("ISSN").Value, Link = recordElement.Element("JournalWebsiteURL").Value, Publisher = ParsePublisher(recordElement), Country = ParseCountry(recordElement), Languages = this.ParseLanguages(recordElement), Subjects = this.ParseSubjects(recordElement), DataSource = JournalsImportSource.Ulrichs.ToString(), OpenAccess = IsOpenAccessJournal(recordElement) }; yield return regularJournal; foreach (var alternateEditionElement in GetAlternateEditionElements(recordElement)) { yield return new Journal { Title = regularJournal.Title, ISSN = alternateEditionElement.Element("ISSN").Value, Link = regularJournal.Link, Publisher = ParsePublisher(recordElement), Country = ParseCountry(recordElement), Languages = this.ParseLanguages(recordElement), Subjects = this.ParseSubjects(recordElement), DataSource = JournalsImportSource.Ulrichs.ToString(), OpenAccess = IsOpenAccessJournal(recordElement) }; } }
public void cannot_change_attribtes_when_journal_has_been_verified() { var journal = new Journal(_today, "Morrisons"); var t1 = new Transaction(journal, TransactionDirection.Out, amount: 9.99M, account: _creditCard); var t2 = new Transaction(journal, TransactionDirection.In, amount: 8.545M, account: _groceries); new Transaction(journal, TransactionDirection.In, amount: 1.445M, account: _toiletries); journal.IsLocked = true; Assert.Throws<VerifiedJournalCannotBeModifiedException>(() => journal.Date = DateTime.Now); Assert.AreEqual(_today, journal.Date); Assert.Throws<VerifiedJournalCannotBeModifiedException>(() => journal.Description = "Morrisons 2"); Assert.AreEqual("Morrisons", journal.Description); Assert.Throws<VerifiedJournalCannotBeModifiedException>(() => journal.DeleteTransaction(t1)); Assert.IsTrue(journal.Transactions.Contains(t1)); Assert.Throws<VerifiedJournalCannotBeModifiedException>(() => new Transaction(journal, TransactionDirection.In)); Assert.AreEqual(3, journal.Transactions.Count); Assert.Throws<TransactionIsLockedAndCannotBeModifiedException>(() => t1.Amount = 2M); Assert.AreEqual(9.99M, t1.Amount); Assert.Throws<TransactionIsLockedAndCannotBeModifiedException>(() => t1.Account = _toiletries); Assert.AreEqual(_creditCard, t1.Account); Assert.Throws<TransactionIsLockedAndCannotBeModifiedException>(() => t1.Note = "New note"); Assert.AreEqual("", t1.Note); Assert.Throws<TransactionIsLockedAndCannotBeModifiedException>(() => t2.Direction = TransactionDirection.Out); Assert.AreEqual(TransactionDirection.In, t2.Direction); }
public ActionResult AcceptInvite(int notificationId) { var notify = NotificationsController.Instance.GetNotification(notificationId); ParseKey(notify.Context); var controller = new SocialEventsController(); var objEvent = controller.GetEvent(_eventId, UserInfo.UserID, UserInfo.Profile.PreferredTimeZone); if (objEvent == null) { return Json(new { Result = "error" }); } var objGuest = new EventGuestInfo { EventId = objEvent.EventId, UserId = UserInfo.UserID, Email = UserInfo.Email, InvitedOnDate = objEvent.CreatedOnDate, RepliedOnDate = DateTime.Now, RSVPStatus = (int)Constants.AttendingStatus.Yes }; controller.UpdateGuestStatus(objGuest); var url = DotNetNuke.Common.Globals.NavigateURL(_tabId, "", "eventid=" + objEvent.EventId); if (objEvent.GroupId > Null.NullInteger) url = DotNetNuke.Common.Globals.NavigateURL(_tabId, "", "eventid=" + objEvent.EventId, "groupid=" + objEvent.GroupId); var cntJournal = new Journal(); cntJournal.AddSocialEventAttendToJournal(objGuest, objEvent.Name, objEvent.GroupId, _tabId, objEvent.PortalId, objGuest.UserId, url); NotificationsController.Instance.DeleteNotificationRecipient(notificationId, UserInfo.UserID); return Json(new { Result = "success" }); }
/// <summary> /// Returns whether a transfer is allowed to succeed or not. /// </summary> public static bool TransferMaySucceed(XBankAccount FromAccount, XBankAccount ToAccount, Money MoneyNeeded, Journal.BankAccountTransferOptions Options) { if (FromAccount == null || ToAccount == null) { return false; } return ((FromAccount.IsSystemAccount || FromAccount.IsPluginAccount || ((Options & Journal.BankAccountTransferOptions.AllowDeficitOnNormalAccount) == Journal.BankAccountTransferOptions.AllowDeficitOnNormalAccount)) || (FromAccount.Balance >= MoneyNeeded && MoneyNeeded > 0)); }
private static void AddPupilAction(Journal journal) { string name, inputAge; int age; Pupil pupil; Console.Clear(); Console.WriteLine("Adding new pupil."); Console.WriteLine("================="); Console.Write("Enter pupil name: "); name = Console.ReadLine(); Console.Write("Enter pupil age (between {0} and {1}): ", Pupil.PUPIL_MIN_AGE, Pupil.PUPIL_MAX_AGE); inputAge = Console.ReadLine(); if (!int.TryParse(inputAge, out age)) age = 0; try { pupil = journal.AddPupil(name, age); Console.WriteLine("\nPupil {0} successfully added.", pupil.Name); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } catch(Exception e) { StandartMessage.DisplayError(e.Message); } }
private void AddJournalToInternalCollection(Journal journal) { var journalVM = new JournalViewModel(journal, _journalRepository, _accountRepository, false); journalVM.RequestDelete += DeleteJournal; _journalVMs.Add(journalVM); }
static public void DoTests() { Journal j = new Journal(); j.InitAll(); j.JOURNAL1(); j.JOURNAL2(); }
public void Approve(int MLJRecordID, int userID) { using (MLJRecordAccessClient _MLJAccessClient = new MLJRecordAccessClient(EndpointName.MLJRecordAccess)) { //First get all JournalCollection in this period MLJRecord _MLJ = new MLJRecordCollection(_MLJAccessClient.QueryByRecordID(MLJRecordID))[0]; //New Record Record _re = new Record(); _re.Period = _MLJ.Period; _re.RecordStatus = RecordStatus.Normal; _re.Type = RecordType.WinAndLoss; foreach (MLJJournal _MLJjur in _MLJ.MLJJournalCollection) { Journal _jur = new Journal(); decimal _baseamount = _MLJjur.Mon + _MLJjur.Tue + _MLJjur.Wed + _MLJjur.Thu + _MLJjur.Fri + _MLJjur.Sat + _MLJjur.Sun; _jur.BaseAmount = _baseamount; _jur.BaseCurrency = _MLJjur.BaseCurrency; _jur.ExchangeRate = _MLJjur.ExchangeRate; _jur.SGDAmount = _baseamount * _MLJjur.ExchangeRate; _jur.EntityID = _MLJjur.EntityID; _jur.EntryUser.UserID = userID; _re.JournalCollection.Add(_jur); } //Second insert Record using (RecordAccessClient _RecordClient = new RecordAccessClient(EndpointName.RecordAccess)) { _RecordClient.Insert(_re, _re.JournalCollection.ToArray()); } //Third Change MLJ_Record Status _MLJAccessClient.ChangeStatus(MLJRecordID, RecordStatus.Confirm, userID); } }
public static long ComputeTotal(Journal journal, DateTimeOffset? firstTimestamp = null, DateTimeOffset? lastTimestamp = null, Func<Transaction, bool> predicate = null) { var total = 0L; journal.Replay(firstTimestamp, lastTimestamp, predicate) .Subscribe(transaction => total = transaction.Execute(total)); return total; }
//Constructor public MainWindow() { InitializeComponent(); currentJournal = new Journal("MyJournal"); dataGrid_JournalEntries.ItemsSource = currentJournal.Entries; label_fileName.Content = fileName; }
void OnRequestAddJournal() { var newJournal = new Journal(DateTime.Today); AddJournalToInternalCollection(newJournal); _template.AddJournal(newJournal); _templateRepository.Save(_template); base.OnPropertyChanged("Journals"); }
private Journal MappingJournalModelToJournal(JournalModel journalModel) { Journal journal = new Journal(); journal.cropid = journalModel.CropId; journal.dateentered = journalModel.DateEntered; journal.description = journalModel.Description; journal.journalimage = journalModel.Photo; return journal; }
public void can_remove_a_journal_from_a_Template() { var template = new Template(); var journal = new Journal(_today, "Rent"); template.AddJournal(journal); template.RemoveJournal(journal); Assert.AreEqual(0, template.Journals.Count); Assert.IsFalse(template.Journals.Contains(journal)); }
public void cannot_update_or_edit_transaction_if_it_belongs_to_a_locked_Journal() { var journal2 = new Journal(3, DateTime.Today); var tran1 = new Transaction(journal2, TransactionDirection.In, _account, 10M, "Stylophone"); new Transaction(journal2, TransactionDirection.Out, _account, 10M); journal2.IsLocked = true; Assert.Throws<TransactionIsLockedAndCannotBeModifiedException>(() => tran1.Direction = TransactionDirection.Out); Assert.Throws<TransactionIsLockedAndCannotBeModifiedException>(() => tran1.Account = _account2); Assert.Throws<TransactionIsLockedAndCannotBeModifiedException>(() => tran1.Amount = 100.99M); Assert.Throws<TransactionIsLockedAndCannotBeModifiedException>(() => tran1.Note = ""); }
/// <summary> /// Default messages sent to players when a transaction happens within SEconomy. /// </summary> protected void BankAccount_BankTransferCompleted(object s, Journal.BankTransferEventArgs e) { TSPlayer sender, receiver; if (e.ReceiverAccount == null || (e.TransferOptions & Journal.BankAccountTransferOptions.SuppressDefaultAnnounceMessages) == Journal.BankAccountTransferOptions.SuppressDefaultAnnounceMessages) { return; } sender = TShockAPI.TShock.Players.FirstOrDefault(i => i != null && i.UserAccountName == e.SenderAccount.UserAccountName); receiver = TShockAPI.TShock.Players.FirstOrDefault(i => i != null && i.UserAccountName == e.ReceiverAccount.UserAccountName); if ((e.TransferOptions & Journal.BankAccountTransferOptions.IsPlayerToPlayerTransfer) == Journal.BankAccountTransferOptions.IsPlayerToPlayerTransfer) { if ((e.TransferOptions & Journal.BankAccountTransferOptions.AnnounceToReceiver) == Journal.BankAccountTransferOptions.AnnounceToReceiver && e.ReceiverAccount != null && receiver != null) { receiver.SendMessage(string.Format(SEconomyPlugin.Locale.StringOrDefault(16, "You {3} {0} from {1}. Transaction # {2}"), e.Amount.ToLongString(), sender != null ? sender.Name : SEconomyPlugin.Locale.StringOrDefault(17, "The server"), e.TransactionID, e.Amount > 0 ? SEconomyPlugin.Locale.StringOrDefault(18, "received") : SEconomyPlugin.Locale.StringOrDefault(19, "sent")), Color.Orange); } if ((e.TransferOptions & Journal.BankAccountTransferOptions.AnnounceToSender) == Journal.BankAccountTransferOptions.AnnounceToSender && sender != null) { sender.SendMessage(string.Format(SEconomyPlugin.Locale.StringOrDefault(16, "You {3} {0} from {1}. Transaction # {2}"), e.Amount.ToLongString(), receiver.Name, e.TransactionID, e.Amount > 0 ? SEconomyPlugin.Locale.StringOrDefault(19, "sent") : SEconomyPlugin.Locale.StringOrDefault(18, "received")), Color.Orange); } //Everything else, including world to player, and player to world. } else { if ((e.TransferOptions & Journal.BankAccountTransferOptions.IsPayment) == Journal.BankAccountTransferOptions.IsPayment) { if ((e.TransferOptions & Journal.BankAccountTransferOptions.AnnounceToSender) == Journal.BankAccountTransferOptions.AnnounceToSender && sender != null) { sender.SendMessage(string.Format(SEconomyPlugin.Locale.StringOrDefault(20, "You {0} {1}{2}"), e.Amount > 0 ? SEconomyPlugin.Locale.StringOrDefault(21, "paid") : SEconomyPlugin.Locale.StringOrDefault(22, "got paid"), e.Amount.ToLongString(), !string.IsNullOrEmpty(e.TransactionMessage) ? SEconomyPlugin.Locale.StringOrDefault(25, " for ") + e.TransactionMessage : ""), Color.Orange); } if ((e.TransferOptions & Journal.BankAccountTransferOptions.AnnounceToReceiver) == Journal.BankAccountTransferOptions.AnnounceToReceiver && receiver != null) { receiver.SendMessage(string.Format(SEconomyPlugin.Locale.StringOrDefault(20, "You {0} {1}{2}"), e.Amount > 0 ? SEconomyPlugin.Locale.StringOrDefault(22, "got paid") : SEconomyPlugin.Locale.StringOrDefault(22, "paid"), e.Amount.ToLongString(), !string.IsNullOrEmpty(e.TransactionMessage) ? SEconomyPlugin.Locale.StringOrDefault(25, " for ") + e.TransactionMessage : ""), Color.Orange); } } else { if ((e.TransferOptions & Journal.BankAccountTransferOptions.AnnounceToSender) == Journal.BankAccountTransferOptions.AnnounceToSender && sender != null) { sender.SendMessage(string.Format(SEconomyPlugin.Locale.StringOrDefault(20, "You {0} {1}{2}"), e.Amount > 0 ? SEconomyPlugin.Locale.StringOrDefault(23, "lost") : SEconomyPlugin.Locale.StringOrDefault(24, "gained"), e.Amount.ToLongString(), !string.IsNullOrEmpty(e.TransactionMessage) ? SEconomyPlugin.Locale.StringOrDefault(25, " for ") + e.TransactionMessage : ""), Color.Orange); } if ((e.TransferOptions & Journal.BankAccountTransferOptions.AnnounceToReceiver) == Journal.BankAccountTransferOptions.AnnounceToReceiver && receiver != null) { receiver.SendMessage(string.Format(SEconomyPlugin.Locale.StringOrDefault(20, "You {0} {1}{2}"), e.Amount > 0 ? SEconomyPlugin.Locale.StringOrDefault(24, "gained") : SEconomyPlugin.Locale.StringOrDefault(23, "lost"), e.Amount.ToLongString(), !string.IsNullOrEmpty(e.TransactionMessage) ? SEconomyPlugin.Locale.StringOrDefault(25, " for ") + e.TransactionMessage : ""), Color.Orange); } } } }
public override void onLoad() { dispatcher = new RService(); _journal = new Journal() { FileName = DirectoryHelper.GetJournalFileName(), MaxFileSize = 50, MaxBackupFiles = 10 }; rpm = new RPackageManager(dispatcher, _journal);//30Jan2014 }
public RPackageManager(RService dispatcher, Journal journal) { _journal = journal; _dispatcher = dispatcher; //can be executed once here and then no need to use it methods below. string errmsg = _dispatcher.EvaluateNoReturn("library(tools)"); if (errmsg != null && errmsg.Trim().Length < 1) //error occurred { } }
/// <summary> /// Constructs a new BankAccount from the supplied database object. /// </summary> public BankAccount(Journal.XBankAccount Account) { // this.DatabaseBankAccount = Account; _flags = Account.Flags; this.BankAccountK = Account.BankAccountK; this.BankAccountName = Account.UserAccountName; this.WorldID = Account.WorldID; //refresh the balance from the database, money will be set when the async I/O finishes //this.DatabaseBankAccount.GetBalanceFromDatabaseAsync().ContinueWith((balanceResult) => { // _money = balanceResult.Result; //}); }
public void can_add_a_journal_to_a_template() { var template = new Template(); var journal1 = new Journal(_today, "Rent"); var journal2 = new Journal(_today, "Credit Card Bill"); template.AddJournal(journal1); template.AddJournal(journal2); Assert.AreEqual(2, template.Journals.Count); Assert.IsTrue(template.Journals.Contains(journal1)); Assert.IsTrue(template.Journals.Contains(journal2)); }
/// <summary> /// Updates the bank account flags from a database. Called when enabled changes, etc. /// </summary> internal async Task<Journal.BankAccountFlags?> UpdateFlagsAsync(Journal.BankAccountFlags NewFlags) { int numberOfRecordsUpdated = await SEconomyPlugin.Database.AsyncConnection.ExecuteAsync("update bankaccount set flags = @0 where bankaccountk = @1", NewFlags, this.BankAccountK); // number of rows affected if (numberOfRecordsUpdated == 1) { this.Flags = NewFlags; return NewFlags; } //In a lambda there is no way for it to infer what type (null) is to anything other than object. //We just help it along a bit by telling it we're talking about a nullable return (BankAccountFlags?)null; }
public void TestPerformanceBatchSize(Tuple<int, int, int, int> testCase) { var total = (long) testCase.Item1*(testCase.Item1 + 1)/2*testCase.Item2; using (var journal = new Journal(TestDirectory, batchSize: testCase.Item4)) { var addingElapsedByThreadId = new ConcurrentDictionary<long, List<TimeSpan>>(); Parallel.For(1, testCase.Item1 + 1, new ParallelOptions { MaxDegreeOfParallelism = testCase.Item3 }, value => { var addingElapsed = StopWatchUtil.Measure(() => { var tasks = Enumerable.Range(1, testCase.Item2) .Select(_ => { return journal.AddAsync(new Transaction(Operation.Deposit, value)); }) .ToArray(); Task.WaitAll(tasks); }); addingElapsedByThreadId.AddOrUpdate( Thread.CurrentThread.ManagedThreadId, key => { return new List<TimeSpan> {addingElapsed}; }, (key, list) => { list.Add(addingElapsed); return list; }); }); var computingElapsed = StopWatchUtil.Measure(() => { Assert.AreEqual(total, TransactionsHelper.ComputeTotal(journal)); }); using ( var fileStream = new FileStream( Path.Combine(TestContext.CurrentContext.TestDirectory, GetType().FullName + ".txt"), FileMode.Append)) { using (var streamWriter = new StreamWriter(fileStream)) { streamWriter.WriteLine("***" + testCase + "***"); streamWriter.WriteLine("timestamp=" + DateTimeOffset.UtcNow); streamWriter.WriteLine("threads=" + addingElapsedByThreadId.Keys.Count); streamWriter.WriteLine("addingMS=" + addingElapsedByThreadId.Values.Sum( v => v.Sum(timeSpan => timeSpan.TotalMilliseconds))); streamWriter.WriteLine("computingMS=" + computingElapsed.TotalMilliseconds); journal.DumpStatistic(streamWriter.WriteLine); } } } }
public async Task TestHelloWorld() { using (var journal = new Journal(TestDirectory)) { await journal.AddAsync("Hello"); await journal.AddAsync(" "); await journal.AddAsync("World"); await journal.AddAsync("!"); var message = string.Empty; journal.Replay<string>().Subscribe(item => message += item); Assert.AreEqual("Hello World!", message); } }
void Start() { audio = GetComponent<AudioScript>(); // initialize start characters here currentDayNum = 1; nextDeathIn = 5; // TODO: replace with Constructor if Journal is no gameobject journal = FindObjectOfType<Journal>(); journal.gameObject.SetActive(false); FindObjectOfType<InterfaceController>().HideRoomStats(); List<string> playerNames = loadPlayerNames(); selectedRoom = GameObject.Find("Start (2,3)").GetComponent<Room>(); List<int> usedIndizes = new List<int>(); for (int i = 0; i < 6; i++) { int randomInt = UnityEngine.Random.Range(0, playerNames.Count); Character testCharacter = Instantiate(character_prefab); testCharacter.CharName = playerNames[randomInt]; playerNames.RemoveAt(randomInt); selectedRoom.Characters.Add(testCharacter); do { randomInt = UnityEngine.Random.Range(0, playerHeads.Length); } while (usedIndizes.Contains(randomInt)); usedIndizes.Add(randomInt); testCharacter.Portrait = playerHeads[randomInt]; testCharacter.Face = playerFaces[randomInt]; characters.Add(testCharacter); } selectedRoom.drawPeople(); foreach (Room i in FindObjectsOfType<Room>()) { i.BlackSmog.SetActive(true); i.gameObject.SetActive(false); } selectedRoom.SelectBubble.SetActive(true); selectedRoom.discoverNeighbors(); activeRooms.Add(selectedRoom); FindObjectOfType<InterfaceController>().SetRoomMembers(selectedRoom.Characters); }
//TODO might have gone a bit crazy with the VerifyJournal public Transaction( Journal journal, TransactionDirection direction, Account account = null, Decimal amount = 0M, string note = "" ) { _journal = journal; journal.AddTransaction(this); Direction = direction; Account = account; Amount = amount; Note = note; }
public void TestBatch() { using (var journal = new Journal(TestDirectory, batchSize: 100)) { var t1 = journal.AddAsync(new Transaction(Operation.Deposit, 1)); var t2 = journal.AddAsync(new Transaction(Operation.Deposit, 2)); Thread.Sleep(200); var t3 = journal.AddAsync(new Transaction(Operation.Deposit, 3)); Task[] tasks = {t1, t2, t3}; Task.WaitAll(tasks); Assert.IsTrue(t1.Result == t2.Result); Assert.IsTrue(t1.Result < t3.Result); Assert.AreEqual(6, TransactionsHelper.ComputeTotal(journal)); } }
public IEnumerable<Journal> ParseJournal(XElement recordElement) { var regularJournal = new Journal { Title = recordElement.Element("title")?.Value, ISSN = ParseIssn(recordElement), Link = recordElement.Element("homepage_url")?.Value, Publisher = ParsePublisher(recordElement), Subjects = ParseSubjects(recordElement), DataSource = JournalsImportSource.JournalTOCs.ToString(), OpenAccess = IsOpenAccessJournal(recordElement), Country = new Country { Name = "" } }; yield return regularJournal; }
public void can_emit_xml_describing_Template() { var date = new DateTime(2011, 5, 24); var journal = new Journal(3, date, "Rent"); var template = new Template(); template.AddJournal(journal); const string expected = @"<template> <journal id=""3"" date=""2011-05-24T00:00:00"" description=""Rent"" isVerified=""false""> <transactions /> </journal> </template>"; var actual = template.EmitXml().ToString(); Assert.AreEqual(expected, actual); }
protected override void OnExit(ExitEventArgs e) { Journal.Shutdown(); base.OnExit(e); }
private void Checking() { // Check AFK if (Journal.Contains(true, "afk", "AFK", "kontrola", "GM", "gm")) { System.Media.SoundPlayer my_wave_file = new System.Media.SoundPlayer(AlarmPath); my_wave_file.Play(); UO.Wait(200); } // Check Light if (Journal.Contains(true, "Je spatne videt.") || World.Player.Layers[Layer.LeftHand].Graphic.Equals(0x0A18)) { World.Player.Layers[Layer.LeftHand].Use(); UO.Wait(200); if (World.Player.Layers[Layer.LeftHand].Graphic.Equals(0x0A15)) { World.Player.Backpack.AllItems.FindType(0x0A18).Use(); } } // Skill delay if (Journal.Contains(true, "Jeste nemuzes pouzit skill")) { SkillDelay = true; } // Check Weight if (World.Player.Weight > (World.Player.Strenght * 4 + 15)) { MaxedWeight = true; } // No Ore if (Journal.Contains(true, " no logs", " blow ", " prilis daleko.", " moc daleko.", "too far", "Tam nedosahnes.", " immune ", " cannot reach")) { NoLog = true; } // Incoming Ore if (Journal.Contains(true, "You put ")) //, calls[1], calls[2], calls[3], calls[4])) { string type = "_"; if (Journal.Contains(true, " Copper ")) { type = "Copper"; } else if (Journal.Contains(true, " Iron ")) { type = "Iron"; } else if (Journal.Contains(true, " Kremicity ")) { type = "Kremicity"; } else if (Journal.Contains(true, " Verite ")) { type = "Verite"; } else if (Journal.Contains(true, " Valorite ")) { type = "Valorite"; } else if (Journal.Contains(true, " Obsidian ")) { type = "Obsidian"; } else if (Journal.Contains(true, " Adamantium ")) { type = "Adamantium"; } var temp2 = OnLogAdded; if (temp2 != null && type != "_") { foreach (EventHandler <OnLogAddedArgs> ev in temp2.GetInvocationList()) { ev.BeginInvoke(null, new OnLogAddedArgs() { Type = type }, null, null); } } } Journal.Clear(); Journal.ClearAll(); }
public GetStateRequestBuilder(string password, string terminalKey, Journal journal) : base(password, terminalKey, journal) { }
/// <summary> /// Ported from draft_t::insert /// </summary> public Xact Insert(Journal journal) { if (Tmpl == null) { return(null); } if (Tmpl.PayeeMask == null) { throw new RuntimeError(RuntimeError.ErrorMessageXactCommandRequiresAtLeastAPayee); } Xact matching = null; Xact added = new Xact(); Xact xact = Lookup.LookupProbableAccount(Tmpl.PayeeMask.ToString(), journal.Xacts.Reverse()).Item1; if (xact != null) { Logger.Current.Debug("draft.xact", () => String.Format("Found payee by lookup: transaction on line {0}", xact.Pos.BegLine)); matching = xact; } else { matching = journal.Xacts.LastOrDefault(x => Tmpl.PayeeMask.Match(x.Payee)); if (matching != null) { Logger.Current.Debug("draft.xact", () => String.Format("Found payee match: transaction on line {0}", matching.Pos.BegLine)); } } if (!Tmpl.Date.HasValue) { added.Date = TimesCommon.Current.CurrentDate; Logger.Current.Debug("draft.xact", () => "Setting date to current date"); } else { added.Date = Tmpl.Date; Logger.Current.Debug("draft.xact", () => String.Format("Setting date to template date: {0}", Tmpl.Date)); } added.State = ItemStateEnum.Uncleared; if (matching != null) { added.Payee = matching.Payee; //added->code = matching->code; //added->note = matching->note; Logger.Current.Debug("draft.xact", () => String.Format("Setting payee from match: {0}", added.Payee)); } else { added.Payee = Tmpl.PayeeMask.ToString(); Logger.Current.Debug("draft.xact", () => String.Format("Setting payee from template: {0}", added.Payee)); } if (!String.IsNullOrEmpty(Tmpl.Code)) { added.Code = Tmpl.Code; Logger.Current.Debug("draft.xact", () => String.Format("Now setting code from template: {0}", added.Code)); } if (!String.IsNullOrEmpty(Tmpl.Note)) { added.Note = Tmpl.Note; Logger.Current.Debug("draft.xact", () => String.Format("Now setting note from template: {0}", added.Note)); } if (!Tmpl.Posts.Any()) { if (matching != null) { Logger.Current.Debug("draft.xact", () => "Template had no postings, copying from match"); foreach (Post post in matching.Posts) { added.AddPost(new Post(post) { State = ItemStateEnum.Uncleared }); } } else { throw new RuntimeError(String.Format(RuntimeError.ErrorMessageNoAccountsAndNoPastTransactionMatchingSmth, Tmpl.PayeeMask.ToString())); } } else { Logger.Current.Debug("draft.xact", () => "Template had postings"); bool anyPostHasAmount = Tmpl.Posts.Any(p => (bool)p.Amount); if (anyPostHasAmount) { Logger.Current.Debug("draft.xact", () => " and at least one has an amount specified"); } foreach (DraftXactPostTemplate post in Tmpl.Posts) { Post newPost = null; Commodity foundCommodity = null; if (matching != null) { if (post.AccountMask != null) { Logger.Current.Debug("draft.xact", () => "Looking for matching posting based on account mask"); Post x = matching.Posts.FirstOrDefault(p => post.AccountMask.Match(p.Account.FullName)); if (x != null) { newPost = new Post(x); Logger.Current.Debug("draft.xact", () => String.Format("Founding posting from line {0}", x.Pos.BegLine)); } } else { if (post.From) { Post x = matching.Posts.LastOrDefault(p => p.MustBalance); if (x != null) { newPost = new Post(x); Logger.Current.Debug("draft.xact", () => "Copied last real posting from matching"); } } else { Post x = matching.Posts.FirstOrDefault(p => p.MustBalance); if (x != null) { newPost = new Post(x); Logger.Current.Debug("draft.xact", () => "Copied first real posting from matching"); } } } } if (newPost == null) { newPost = new Post(); Logger.Current.Debug("draft.xact", () => "New posting was NULL, creating a blank one"); } if (newPost.Account == null) { Logger.Current.Debug("draft.xact", () => "New posting still needs an account"); if (post.AccountMask != null) { Logger.Current.Debug("draft.xact", () => "The template has an account mask"); Account acct = journal.FindAccountRe(post.AccountMask.ToString()); if (acct != null) { Logger.Current.Debug("draft.xact", () => "Found account as a regular expression"); } else { acct = journal.FindAccount(post.AccountMask.ToString()); if (acct != null) { Logger.Current.Debug("draft.xact", () => "Found (or created) account by name"); } } // Find out the default commodity to use by looking at the last // commodity used in that account foreach (Xact j in journal.Xacts.Reverse()) { Post x = j.Posts.FirstOrDefault(p => p.Account == acct && !(p.Amount == null || p.Amount.IsEmpty)); if (x != null) { newPost = new Post(x); Logger.Current.Debug("draft.xact", () => "Found account in journal postings, setting new posting"); break; } } newPost.Account = acct; Logger.Current.Debug("draft.xact", () => String.Format("Set new posting's account to: {0}", acct.FullName)); } else { if (post.From) { newPost.Account = journal.FindAccount("Liabilities:Unknown"); Logger.Current.Debug("draft.xact", () => "Set new posting's account to: Liabilities:Unknown"); } else { newPost.Account = journal.FindAccount("Expenses:Unknown"); Logger.Current.Debug("draft.xact", () => "Set new posting's account to: Expenses:Unknown"); } } } if (newPost.Account == null) { throw new InvalidOperationException("assert(new_post->account)"); } if (newPost != null && !(newPost.Amount == null || newPost.Amount.IsEmpty)) { foundCommodity = newPost.Amount.Commodity; if (anyPostHasAmount) { newPost.Amount = new Amount(); Logger.Current.Debug("draft.xact", () => "New posting has an amount, but we cleared it"); } else { anyPostHasAmount = true; Logger.Current.Debug("draft.xact", () => "New posting has an amount, and we're using it"); } } if ((bool)post.Amount) { newPost.Amount = post.Amount; Logger.Current.Debug("draft.xact", () => "Copied over posting amount"); if (post.From) { newPost.Amount.InPlaceNegate(); Logger.Current.Debug("draft.xact", () => "Negated new posting amount"); } } if ((bool)post.Cost) { if (post.Cost.Sign < 0) { throw new ParseError(ParseError.ParseError_PostingCostMayNotBeNegative); } post.Cost.InPlaceUnround(); if (post.CostOperator == "@") { // For the sole case where the cost might be uncommoditized, // guarantee that the commodity of the cost after multiplication // is the same as it was before. Commodity costCommodity = post.Cost.Commodity; post.Cost = post.Cost.Multiply(newPost.Amount); post.Cost.SetCommodity(costCommodity); } else if (newPost.Amount.Sign < 0) { newPost.Cost.InPlaceNegate(); } newPost.Cost = post.Cost; Logger.Current.Debug("draft.xact", () => "Copied over posting cost"); } if (foundCommodity != null && !(newPost.Amount == null) && !(newPost.Amount.IsEmpty) && !(newPost.Amount.HasCommodity)) { newPost.Amount.SetCommodity(foundCommodity); Logger.Current.Debug("draft.xact", () => String.Format("Set posting amount commodity to: {0}", newPost.Amount.Commodity)); newPost.Amount = newPost.Amount.Rounded(); Logger.Current.Debug("draft.xact", () => String.Format("Rounded posting amount to: {0}", newPost.Amount)); } added.AddPost(newPost); newPost.Account.AddPost(newPost); newPost.State = ItemStateEnum.Uncleared; Logger.Current.Debug("draft.xact", () => "Added new posting to derived entry"); } } if (!journal.AddXact(added)) { throw new RuntimeError(RuntimeError.ErrorMessageFailedToFinalizeDerivedTransactionCheckCommodities); } return(added); }
//--------------------------------------------------------------------------------------------- public void TrainTamingRecusive(int maxTries, params string[] positionsDefinition) { Robot r = new Robot(); r.UseTryGoOnly = true; r.UseMinWait = true; r.UseRun = true; r.SearchSuqareSize = 450; this.doneList = new List <Serial>(); string[] locations = positionsDefinition; foreach (string loc in locations) { string[] options = loc.Split('|'); int button = -1; string bookType = "r"; if (!String.IsNullOrEmpty(options[0]) && Regex.IsMatch(options[0], "(?<booktype>[a-z])(?<button>\\d{1,2})")) { Match m = Regex.Match(options[0], "(?<booktype>[a-z])(?<button>\\d{1,2})"); bookType = m.Groups["booktype"].Value.ToLower(); button = Int32.Parse(m.Groups["button"].Value); } if (button > -1) { string book = "RuneBookUse"; if (bookType == "t") { Phoenix.Runtime.RuntimeCore.Executions.Execute(Phoenix.Runtime.RuntimeCore.ExecutableList["TravelBookUse"], 1); UO.Wait(1000); book = "TravelBookUse"; } else if (bookType == "c") { Phoenix.Runtime.RuntimeCore.Executions.Execute(Phoenix.Runtime.RuntimeCore.ExecutableList["CestovniKnihaUse"], 1); UO.Wait(1000); book = "CestovniKnihaUse"; } bool teleported = false; while (!teleported) { UO.DeleteJournal(); Phoenix.Runtime.RuntimeCore.Executions.Execute(RuntimeCore.ExecutableList[book], button); Game.Wait(500); if (!World.Player.Hidden) { UO.UseSkill("Hiding"); } UO.Print("Cekam na kop.. nehybat"); if (Journal.WaitForText(true, 2000, "Nesmis vykonavat zadnou akci")) { Game.CurrentGame.CurrentPlayer.SwitchWarmode(); Game.Wait(1000); } else if (Journal.WaitForText(true, 120000, "You have been teleported")) { teleported = true; } if (Game.CurrentGame.WorldSave()) { UO.Print("WS opakovani kopu za 45s"); Game.Wait(45000); if (bookType == "t") { Phoenix.Runtime.RuntimeCore.Executions.Execute(Phoenix.Runtime.RuntimeCore.ExecutableList["TravelBookUse"], 1); UO.Wait(1000); } Game.Wait(500); } } } for (int i = 1; i < options.Length; i++) { if (UO.Dead) { return; } string[] parm = options[i].Split('.'); string x = parm[0]; string[] y = parm[1].Split(new string[] { "//" }, StringSplitOptions.RemoveEmptyEntries); string placeName = ""; if (y.Length > 1) { placeName = y[1]; } UOPositionBase pos = new UOPositionBase(ushort.Parse(x), ushort.Parse(y[0]), (ushort)0); int distance = parm.Length > 2 ? UOExtensions.Utils.ToNullInt(parm[2]).GetValueOrDefault(1) : 1; int gotries = parm.Length > 3 ? UOExtensions.Utils.ToNullInt(parm[3]).GetValueOrDefault(1000) : 1000; Game.PrintMessage("GoTo: " + pos); if (r.GoTo(pos, distance, gotries)) { Game.PrintMessage("In position: " + pos); if (parm[parm.Length - 1].ToLower() == "opendoor") { ItemHelper.OpenDoorAll(); Game.Wait(); if (World.Player.Layers[Layer.OuterTorso].Exist) { World.Player.Layers[Layer.OuterTorso].Move(1, World.Player.Backpack); Game.Wait(); } } List <UOCharacter> characters = new List <UOCharacter>(); characters.AddRange(World.Characters); characters.Sort(delegate(UOCharacter char1, UOCharacter char2) { return(char1.Distance.CompareTo(char2.Distance)); }); foreach (UOCharacter character in characters) { if (UO.Dead) { return; } Game.Wait(50); if (character.Distance < 6 && character.Serial != World.Player.Serial && !doneList.Contains(character.Serial) && character.Model != 0x0190 && character.Model != 0x0191 && character.Model != 0x0192) { SkillValue atSkill = SkillsHelper.GetSkillValue("Animal Taming"); bool isBird = character.Model == 0x0006; World.Player.PrintMessage(isBird + " / " + atSkill.Value); if (isBird && atSkill.RealValue > 450) { World.Player.PrintMessage("Try Kill."); UO.Cast(StandardSpell.Harm, character.Serial); Game.Wait(3000); if (character.Exist) { UO.Cast(StandardSpell.Harm, character.Serial); Game.Wait(2500); } //World.Player.PrintMessage("Try Kill result: " + KillCharacter(character)); } else { this.TameCharacter(character, maxTries); doneList.Add(character); } //if (!isBird || atSkill.RealValue < 450) //{ //} //else //{ //} } } } //else // Phoenix.Runtime.RuntimeCore.Executions.Terminate(musicRun.ManagedThreadId); } } if (UO.Dead) { return; } TrainTamingRecusive(maxTries, positionsDefinition); }
private void btnSearch_Click(object sender, EventArgs e) { Journal journal = new Journal(); dgvJournal.DataSource = journal.Select().Tables[0]; }
public void MakeMythSphere(int amount) { Game.PrintMessage("Vyber container s Myth wire a Gold wire"); UOItem containerWireFrom = new UOItem(UIManager.TargetObject()); Game.PrintMessage("Vyber container s Fairy Dustama"); UOItem containerFDFrom = new UOItem(UIManager.TargetObject()); Game.PrintMessage("Vyber container se Soul Shardama"); UOItem containerSSFrom = new UOItem(UIManager.TargetObject()); Game.PrintMessage("Vyber container s Iron ingy"); UOItem containerIngyFrom = new UOItem(UIManager.TargetObject()); Game.PrintMessage("Vyber container, kam to chces dat"); UOItem containerTo = new UOItem(UIManager.TargetObject()); int count = 0; while (count < amount) { UO.DeleteJournal(); containerWireFrom.AllItems.FindType(0x1876, 0x052D).Move(15, World.Player.Backpack); // presun Myth wire Game.Wait(); containerWireFrom.AllItems.FindType(0x1878, 0x0000).Move(15, World.Player.Backpack); // presun Golden wire Game.Wait(); containerFDFrom.AllItems.FindType(0x103D, 0x0B52).Move(1, World.Player.Backpack); // presun FD Game.Wait(); containerSSFrom.AllItems.FindType(0x0FC4, 0x0498).Move(1, World.Player.Backpack); // presun SS Game.Wait(); containerIngyFrom.AllItems.FindType(0x1BEF, 0x0000).Move(5, World.Player.Backpack); // presun Iron ingu Game.Wait(); UO.UseType(0x1BEF, 0x0000); UO.WaitMenu("Blacksmithing", "Tools", "Tools", "Mytheril Sphere"); if (Journal.WaitForText(true, 8000, "You have failed to make anything", "You can't make anything", "You put")) { if (Journal.Contains("You put")) { count += 1; World.Player.Backpack.AllItems.FindType(0x0E2D, 0x0B8A).Move(1, containerTo); Game.Wait(500); } if (Journal.Contains("You can't make anything")) { Game.PrintMessage("Nemas suroviny"); break; } } Game.PrintMessage("Vyrobeno sphere: " + count); } Game.PrintMessage("MakeMythSphere - End"); }
public async Task Post([FromForm] ArticleModel articleModel) { if (Request.ContentLength > 0 && Request.Form.Files.Count > 0) { File _file = new File { Name = await Classes.FileSave.Save(Request.Form.Files[0], 5).ConfigureAwait(false), Type = 6, CreateDate = GetDate, StatusId = 1, UserId = User_Id }; await aztuAkademik.File.AddAsync(_file).ConfigureAwait(false); await aztuAkademik.SaveChangesAsync().ConfigureAwait(false); await Classes.TLog.Log("File", "", _file.Id, 1, User_Id, IpAdress, AInformation).ConfigureAwait(false); articleModel.Article.FileId = _file.Id; } if (!string.IsNullOrEmpty(articleModel.Journal)) { Journal journal = new Journal { Name = articleModel.Journal, Indexed = articleModel.Indexed, CreateDate = GetDate, StatusId = 1 }; await aztuAkademik.Journal.AddAsync(journal).ConfigureAwait(false); await aztuAkademik.SaveChangesAsync().ConfigureAwait(false); await Classes.TLog.Log("Journal", "", journal.Id, 1, User_Id, IpAdress, AInformation).ConfigureAwait(false); articleModel.Article.Journal = journal.Id; } articleModel.Article.CreateDate = GetDate; articleModel.Article.CreatorId = User_Id; await aztuAkademik.Article.AddAsync(articleModel.Article).ConfigureAwait(false); await aztuAkademik.SaveChangesAsync().ConfigureAwait(false); await Classes.TLog.Log("Article", "", articleModel.Article.Id, 1, User_Id, IpAdress, AInformation).ConfigureAwait(false); articleModel.Urls.ForEach(x => { x.ArticleId = articleModel.Article.Id; x.CreateDate = GetDate; }); await aztuAkademik.Urls.AddRangeAsync(articleModel.Urls).ConfigureAwait(false); await aztuAkademik.SaveChangesAsync().ConfigureAwait(false); await Classes.TLog.Log("URLS", "", articleModel.Urls.Select(x => x.Id).ToArray(), 1, User_Id, IpAdress, AInformation).ConfigureAwait(false); RelArticleResearcher relArticleResearcher; if (articleModel.Researchers.Internals != null) { for (int i = 0; i < articleModel.Researchers.Internals.Count; i++) { relArticleResearcher = new RelArticleResearcher { ArticleId = articleModel.Article.Id, IntAuthorId = articleModel.Researchers.Internals[i].Id, CreateDate = GetDate, StatusId = 1, Type = articleModel.Researchers.Internals[i].Type }; await aztuAkademik.RelArticleResearcher.AddAsync(relArticleResearcher).ConfigureAwait(false); await aztuAkademik.SaveChangesAsync().ConfigureAwait(false); await Classes.TLog.Log("RelArticleResearcher", "", relArticleResearcher.Id, 1, User_Id, IpAdress, AInformation).ConfigureAwait(false); } } if (articleModel.Researchers.Externals != null) { for (int i = 0; i < articleModel.Researchers.Externals.Count; i++) { relArticleResearcher = new RelArticleResearcher { ArticleId = articleModel.Article.Id, ExtAuthorId = articleModel.Researchers.Externals[i].Id, CreateDate = GetDate, StatusId = 1, Type = articleModel.Researchers.Externals[i].Type }; await aztuAkademik.RelArticleResearcher.AddAsync(relArticleResearcher).ConfigureAwait(false); await aztuAkademik.SaveChangesAsync().ConfigureAwait(false); await Classes.TLog.Log("RelArticleResearcher", "", relArticleResearcher.Id, 1, User_Id, IpAdress, AInformation).ConfigureAwait(false); } } }
/// <summary> /// TBD /// </summary> /// <param name="toSequenceNr">TBD</param> public void DeleteMessages(long toSequenceNr) { Journal.Tell(new DeleteMessagesTo(PersistenceId, toSequenceNr, Self)); }
public void Reset(Journal journal) { Xacts = new List <Xact>(journal.Xacts); }
public XactsIterator(Journal journal) { Reset(journal); }
private bool EndOfTurnDamageCriteria(DealDamageAction dda) { return(dda.DamageSource != null && dda.DamageSource.Card != null && dda.DamageSource.IsSameCard(base.Card) && dda.OriginalAmount == 2 && dda.OriginalDamageType == DamageType.Psychic && dda.CardSource.Card == base.Card && Journal.GetCardPropertiesBoolean(base.Card, DidDestroyToReduce) == true); }
public int UpsertJournalForUser(int userId, int journalId, Journal journal) { return(_journalDM.UpsertJournalForUser(userId, journalId, journal)); }
private void Dispatcher_ShutdownStarted(object sender, EventArgs e) { Journal.Shutdown(); }
private void Current_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { e.Handled = true; Journal.WriteLog(e.Exception, JournalEntryType.Error); }
internal BrowserJournal(Journal journal, Uri baseUri) { _journal = journal; _baseUri = baseUri; }
public void MakeMagicSphere(int amount) { Game.PrintMessage("Vyber container s Gold ingots a Shadow ingots"); UOItem containerIngyFrom = new UOItem(UIManager.TargetObject()); Game.PrintMessage("Vyber container se Saphires a Diamants"); UOItem containerSperkyFrom = new UOItem(UIManager.TargetObject()); Game.PrintMessage("Vyber container se Silver wires a Iron wires"); UOItem containerWiresFrom = new UOItem(UIManager.TargetObject()); Game.PrintMessage("Vyber container s Dark hides"); UOItem containerHidyFrom = new UOItem(UIManager.TargetObject()); Game.PrintMessage("Vyber container, kam to chces dat"); UOItem containerTo = new UOItem(UIManager.TargetObject()); int count = 0; while (count < amount) { UO.DeleteJournal(); containerIngyFrom.AllItems.FindType(0x1BE9, 0x0000).Move(10, World.Player.Backpack); // presun Gold ingots Game.Wait(); containerIngyFrom.AllItems.FindType(0x1BEF, 0x0770).Move(5, World.Player.Backpack); // presun Shadow ingots Game.Wait(); containerSperkyFrom.AllItems.FindType(0x0F11, 0x0000).Move(2, World.Player.Backpack); // presun Saphires Game.Wait(); containerSperkyFrom.AllItems.FindType(0x0F26, 0x0000).Move(2, World.Player.Backpack); // presun Diamants Game.Wait(); containerWiresFrom.AllItems.FindType(0x1877, 0x0000).Move(20, World.Player.Backpack); // presun Silver wires Game.Wait(); containerWiresFrom.AllItems.FindType(0x1876, 0x0000).Move(20, World.Player.Backpack); // presun Iron wires Game.Wait(); if (World.Player.Backpack.Items.Count(0x1078, 0x0615) < 1) { containerHidyFrom.AllItems.FindType(0x1078, 0x0615).Move(2, World.Player.Backpack); // presun 2 Dark hidu, potreba jen 1, v IFu kvuli bugu ve hre - neumi vzit z tezkyho stacku 1 item kvuli vaze Game.Wait(); } UO.UseType(0x1EBC, 0x0000); UO.WaitMenu("Tinkering", "Special Items", "Special Items", "Magic Sphere"); if (Journal.WaitForText(true, 8000, "You have failed to make anything", "You can't make anything", "You put")) { if (Journal.Contains("You put")) { count += 1; World.Player.Backpack.AllItems.FindType(0x0E2E, 0x0B77).Move(1, containerTo); Game.Wait(500); } if (Journal.Contains("You can't make anything")) { Game.PrintMessage("Nemas suroviny"); break; } } Game.PrintMessage("Vyrobeno sphere: " + count); } Game.PrintMessage("MakeMagicSphere - End"); }
/// <summary> Called by the browser to serialize the entire journal or just the index of /// the current entry. The second case is when an internal Journal update needs to be /// reflected in the TravelLog. /// </summary> /// <param name="arg"> true is the entire Journal is to serialized </param> private object _GetSaveHistoryBytesDelegate(object arg) { bool entireJournal = (bool)arg; SaveHistoryReturnInfo info = new SaveHistoryReturnInfo(); // DevDiv 716414 / DevDiv2 196517 & 224724: // Checking _serviceProvider for null due to COM reentrancy issues observed by customers. // Users who perform frequent refreshes may experience shutdown while we are still starting up and are not fully initialized. // The ServiceProvider field is one of the last things to be set during initialization, so if this is null // we know that we have not finished initialization much less run the app and thus have no need to save history. if (_serviceProvider == null) { return(null); } // When we are here, the browser has just started to shut down, so we should only check // whether the application object is shutting down. if (Application.IsApplicationObjectShuttingDown == true) { return(null); } Invariant.Assert(_rbw.Value != null, "BrowserJournalingError: _rbw should not be null"); Journal journal = _rbw.Value.Journal; Invariant.Assert(journal != null, "BrowserJournalingError: Could not get internal journal for the window"); JournalEntry entry; if (entireJournal) // The application is about to be shut down... { NavigationService topNavSvc = _rbw.Value.NavigationService; try { topNavSvc.RequestCustomContentStateOnAppShutdown(); } catch (Exception e) { if (CriticalExceptions.IsCriticalException(e)) { throw; } } journal.PruneKeepAliveEntries(); // Since the current page is not added to the journal until it is replaced, // we add it here explicitly to the internal Journal before serializing it. entry = topNavSvc.MakeJournalEntry(JournalReason.NewContentNavigation); if (entry != null && !entry.IsAlive()) { if (entry.JEGroupState.JournalDataStreams != null) { entry.JEGroupState.JournalDataStreams.PrepareForSerialization(); } journal.UpdateCurrentEntry(entry); } else // Maybe the current content is null or a PageFunction doesn't want to be journaled. { // Then the previous navigable page, if any, should be remembered as current. entry = journal.GetGoBackEntry(); // i. _LoadHistoryStreamDelegate() has a similar special case. } } else { // (Brittle) Assumption: GetSaveHistoryBytes() is called after the current entry has // been updated in the internal journal but before the new navigation is committed. // This means journal.CurrentEntry is what was just added (or updated). // Note that it would be wrong to call topNavSvc.MakeJournalEntry() in this case because // the navigation that just took place may be in a different NavigationService (in a // frame), and here we don't know which one it is. entry = journal.CurrentEntry; // The entry may be null here when the user has selected "New Window" or pressed Ctrl+N. // In this case the browser calls us on IPersistHistory::Save and then throws that data // away. Hopefully at some point in the future that saved data will be loaded in the new // window via IPersistHistory::Load. This unusual behavior is tracked in bug 1353584. } if (entry != null) { info.title = entry.Name; info.entryId = entry.Id; } else { info.title = _rbw.Value.Title; } // We only use the base URI here because the travel log will validate a file URI when making a PIDL. // We use the URI stored in the JournalEntry, and the travel log doesn't care what the URI is, so // duplicates don't matter. info.uri = BindUriHelper.UriToString(Uri); MemoryStream saveStream = new MemoryStream(); saveStream.Seek(0, SeekOrigin.Begin); if (entireJournal) { //Save the Journal and BaseUri also. We don't need BaseUri except for the xaml case //since this is set specially for the container case (ssres scheme). Exe case //will pretty much set it to the exe path. For the xaml case it is set to the path //of the first uri(eg BaseDir\page1.xaml) that was navigated to. //BaseDir/Subdir/page2.xaml is also considered to be in the same extent and when //we navigate back to the app from a webpage, the baseUri should still be BaseDir //not BaseDir/Subdir. We were setting the BaseDir from JournalEntry.Uri but we may //end up setting BaseUri to BaseDir/Subdir which is not the same. So explicitly //persist BaseUri as well BrowserJournal browserJournal = new BrowserJournal(journal, BindUriHelper.BaseUri); new SecurityPermission(SecurityPermissionFlag.SerializationFormatter).Assert(); try { saveStream.WriteByte(BrowserJournalHeader); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(saveStream, browserJournal); } catch (Exception e) { if (CriticalExceptions.IsCriticalException(e)) { throw; } // The application is shutting down and the exception would not be reported anyway. // This is here to help with debugging and failure analysis. Invariant.Assert(false, "Failed to serialize the navigation journal: " + e); } finally { CodeAccessPermission.RevertAll(); } } else { saveStream.WriteByte(JournalIdHeader); WriteInt32(saveStream, info.entryId); } info.saveByteArray = saveStream.ToArray(); ((IDisposable)saveStream).Dispose(); return(info); }
public FinishAuthorizeRequestBuilder(string password, string terminalKey, Journal journal) : base(password, terminalKey, journal) { }
public void LootGround(LootType lootType, bool lootAll) { //List<UOItem> searchItems = new List<UOItem>(); List <UOItem> ground = new List <UOItem>(); ground.AddRange(World.Ground.ToArray()); List <UOItem> search = new List <UOItem>(); int done = 0; int toDo = 0; int bodies = 0; List <Serial> bpkState = ItemHelper.ContainerState(World.Player.Backpack); foreach (UOItem item in ground) { if (item.Graphic == 0x2006) { bodies++; if (cutedBodies.Contains(item.Serial)) { done++; } else { toDo++; if (item.Distance <= 6) { search.Add(item); } } } } for (int i = 0; i < search.Count; i++)//(UOItem item in search) { UOItem item = search[i]; Game.PrintMessage(String.Format("Try Loot Body [{0}/{1}]", i + 1, search.Count), Game.Val_LightGreen); if (!item.Opened) { Journal.Clear(); item.Use(); if (Journal.WaitForText(true, 250, "You can't reach that")) { UO.PrintObject(item.Serial, Game.Val_LightGreen, "[Can't reach]"); continue; } } List <UOItem> items = new List <UOItem>(); items.AddRange(item.Items.ToArray()); bool hasLootBag = items.Count(si => si.Graphic == 0x0E76 && si.Color == 0x049A) > 0; if (!hasLootBag) { foreach (UOItem bag in items.Where(b => b.Graphic == 0x0E76)) { if (String.IsNullOrEmpty(bag.Name)) { bag.Click(); Game.Wait(175); if ((bag.Name + String.Empty).ToLower().StartsWith("loot")) { hasLootBag = true; break; } } } } //Notepad.WriteLine("LootManual: " + item.Description); //Notepad.WriteLine("LootManual hasLootBag: " + hasLootBag); //Notepad.WriteLine("LootManual items: " + items.Count); //return; if (hasLootBag || lootAll || item.Distance <= 1) //item.Items.FindType(0x0E76, 0x049A).Exist)// lootbag { UO.PrintObject(item.Serial, Game.Val_LightGreen, "[Looting...]"); if (DwarfKnife.Exist && (hasLootBag || item.Distance <= 1) && !lootAll)//TODO predelat nejak jinak, ted kvuly tamingu aby to nelotovalo maso a kuze { toDo--; done++; foreach (UOItem lootItem in items) { if (Loot.IsLootItem(lootItem)) { lootItem.Move(65000, LootBag); Game.Wait(300); } } DwarfKnife.Use(); UO.WaitTargetObject(item); Game.Wait(350); items = new List <UOItem>(); items.AddRange(item.Items.ToArray()); } if (item.Exist) { foreach (UOItem lootItem in items) { if (Loot.IsLootItem(lootItem) || lootAll) { lootItem.Move(60000, LootBag); Game.Wait(425); } } } } //cutedBodies.Add(item.Serial); } World.Player.PrintMessage(String.Format("Bodies remain [{0}]", toDo), Game.Val_LightGreen); foreach (UOItem item in World.Ground) { if (item.Distance <= 6 && item.Graphic == 0x0E76 && item.Color == 0x049A)//IsLootItem(item))//jen lootbag { item.Move(60000, LootBag); Game.Wait(425); } } List <Serial> bpkAfterLoot = ItemHelper.ContainerState(World.Player.Backpack); List <Serial> diff = ItemHelper.ContainerStateDiff(bpkState, bpkAfterLoot); Game.PrintMessage("Diff... " + diff.Count); if (LootBag.Serial != World.Player.Backpack.Serial) { foreach (Serial lootedItem in diff) { UOItem item = new UOItem(lootedItem); if (item.Container == World.Player.Backpack.Serial) { if (item.Move(65000, LootBag)) { Game.PrintMessage("LootItem Moved to Bag..."); } Game.Wait(); } } } }
protected override void Context() { base.Context(); _journal = new Journal(); }
public void Action(Player player) { text = "Пропусти хід - пуста клітинка. Нічого не відбулося"; Journal.getInstance().LogNow(player, text); }
public void TrainAlchemyMag(string name, string quality) { Game.PrintMessage("TrainAlchemyMag"); Potion potion = PotionCollection.Potions.GetItemByName(name); PotionQuality pq = Potion.ParsePQOrDefault(quality, PotionQuality.Lesser); Game.PrintMessage("Vyber zdrojovy konterjner s regy:"); UOItem container = new UOItem(UIManager.TargetObject()); ItemHelper.EnsureContainer(container); decimal okCount = 0; decimal count = 0; while (!UO.Dead && World.Player.Backpack.AllItems.FindType(Reagent.Nightshade.Graphic, Reagent.Nightshade.Color).Exist&& World.Player.Backpack.AllItems.FindType(Reagent.BlackPearl.Graphic, Reagent.BlackPearl.Color).Exist ) { while (World.Player.Mana > 10) { if (World.Player.Hits < 40) { while (World.Player.Hits < World.Player.Strenght) { UOItem banda = World.Ground.FindType(0x0E21);//bandy if (!banda.Exist) { return; } UO.WaitTargetSelf(); banda.Use(); Game.Wait(2500); } } UO.Cast(StandardSpell.MagicArrow, Aliases.Self); Game.Wait(1500); } while (World.Player.Hits < World.Player.Strenght) { UOItem banda = World.Ground.FindType(0x0E21);//bandy if (!banda.Exist) { break; } UO.WaitTargetSelf(); banda.Use(); Game.Wait(2500); } //UOItem mrKad = new UOItem(World.Player.Backpack.Items.FindType(Potion.KadGraphic, Potion.ManaRefresh.TopKadColor)); //UOItem tmrKad = new UOItem(World.Player.Backpack.Items.FindType(Potion.KadGraphic, Potion.TotalManaRefresh.TopKadColor)); //if (mrKad.Exist || tmrKad.Exist) //{ // Game.CurrentGame.CurrentPlayer.GetSkillInstance<Alchemy>().DrinkPotion("Total Mana Refresh"); // Game.Wait(); //} //else { while (GetMixureReagent(container, potion, pq) && World.Player.Mana < World.Player.Intelligence) { FillKadRecursive(potion, pq); if (!MixurePotion(potion, pq)) { break; } else { count++; if (Journal.Contains(true, "You pour")) { okCount++; } decimal okDivide = (okCount / count); decimal okPerc = okDivide * 100; int regAmount = potion.GetAmountOrDefault(pq); decimal pricePerPcs = (1 / (okDivide > 0 ? (okCount / count) : 1)) * (decimal)regAmount * 5.0m;// Game.PrintMessage("Ks: " + okCount + " / " + String.Format("{0:n} %", okPerc) + " Prc: " + String.Format("{0:n} gp", pricePerPcs)); } } } } Game.PrintMessage("TrainAlchemyMag END"); }
/// <summary> /// Adds new document to the database. /// </summary> /// <param name="document">Document, which is going to be added.</param> public static void AddDocument(IDocument document) { if (document == null) { throw new ArgumentNullException("Invalid document!"); } var type = document.GetType(); using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("LibraryDB"))) { if (type == typeof(AVMaterial)) { AVMaterial temp = document as AVMaterial; connection.Execute("dbo.spAudioVideos_AddAV @Title, @Authors, @KeyWords, @CoverURL, @Price", new { Title = temp.Title, Authors = temp.Authors, KeyWords = temp.KeyWords, CoverURL = temp.CoverURL, Price = temp.Price }); } else if (type == typeof(Book)) { Book temp = document as Book; connection.Execute("dbo.spBooks_AddBook @Title, @Authors, @Publisher, @Edition, @Year, @IsBestseller, @KeyWords, @CoverURL, @Price", new { Title = temp.Title, Authors = temp.Authors, Publisher = temp.Publisher, Edition = temp.Edition, Year = temp.Year, IsBestseller = temp.IsBestseller, KeyWords = temp.KeyWords, CoverURL = temp.CoverURL, Price = temp.Price }); } else if (type == typeof(InnerMaterial)) { InnerMaterial temp = document as InnerMaterial; connection.Execute("dbo.spInnerMaterials_AddInnerMaterial @Title, @Authors, @Type, @Room, @Level, @KeyWords, @CoverURL", new { Title = temp.Title, Authors = temp.Authors, Type = temp.Type, Room = temp.Room, Level = temp.Level, KeyWords = temp.KeyWords, CoverURL = temp.CoverURL }); } else if (type == typeof(Journal)) { Journal temp = document as Journal; connection.Execute("dbo.spJournals_AddJournal @Title, @Authors, @Publisher, @Issue, @PublicationDate, @KeyWords, @CoverURL, @Price", new { Title = temp.Title, Authors = temp.Authors, Publisher = temp.Publisher, Issue = temp.Issue, PublicationDate = temp.PublicationDate, KeyWords = temp.KeyWords, CoverURL = temp.CoverURL, Price = temp.Price }); } else if (type == typeof(Article)) { Article temp = document as Article; connection.Execute("dbo.spJournalArticles_AddJournalArticle @Title, @Authors, @JournalId, @KeyWords, @CoverURL", new { Title = temp.Title, Authors = temp.Authors, KeyWords = temp.KeyWords, JournalId = temp.JournalId, CoverURL = temp.CoverURL }); } } }
private object _LoadHistoryStreamDelegate(object arg) { Journal journal = null; JournalEntry entry = null; LoadHistoryStreamInfo info = (LoadHistoryStreamInfo)arg; if (IsShutdown() == true) { return(null); } // Reset the memory stream pointer back to the begining and get the persisted object info.loadStream.Seek(0, System.IO.SeekOrigin.Begin); object journaledObject = DeserializeJournaledObject(info.loadStream); //This is the very first load from history, so need to set the BaseUri and StartupUri. if (info.firstLoadFromHistory) { // The journal does not get saved on Ctrl+N. Because of this, // here we can get just an index, like in the 'else' case below. if (!(journaledObject is BrowserJournal)) { return(null); } BrowserJournal browserJournal = (BrowserJournal)journaledObject; journal = browserJournal.Journal; entry = journal.CurrentEntry; if (entry == null) // See special case in _GetSaveHistoryBytesDelegate(). { entry = journal.GetGoBackEntry(); // could still be null } //This will create the frame to use for hosting { NavigationService navigationService = null; navigationService = _rbw.Value.NavigationService; } _rbw.Value.SetJournalForBrowserInterop(journal); //This should already be set for the container and exe cases. The former //sets it to the transformed ssres scheme and we don't want to overwrite it. if (BindUriHelper.BaseUri == null) { BindUriHelper.BaseUri = browserJournal.BaseUri; } //CHECK: For xaml case, what should we set as the Startup Uri ? We set it the initial //uri we started with, should this be changed to creating the window explicitly //and navigating the window instead of setting the StartupUri? //(Application.Current as Application).StartupUri = entry.Uri; Debug.Assert(Application.Current != null, "BrowserJournalingError: Application object should already be created"); if (entry != null) { //Prevent navigations to StartupUri for history loads by canceling the StartingUp event Application.Current.Startup += new System.Windows.StartupEventHandler(this.OnStartup); _rbw.Value.JournalNavigationScope.NavigateToEntry(entry); } //else: fall back on navigating to StartupUri } else { if (!(journaledObject is int)) { return(null); } journal = _rbw.Value.Journal; int index = journal.FindIndexForEntryWithId((int)journaledObject); Debug.Assert(journal[index].Id == (int)journaledObject, "BrowserJournalingError: Index retrieved from journal stream does not match index of journal entry"); // Check whether the navigation is canceled. if (!_rbw.Value.JournalNavigationScope.NavigateToEntry(index)) { // When the navigation is canceled, we want to notify browser to prevent the internal journal from // getting out of sync with the browser's. // The exception will be caught by the interop layer and browser will cancel the navigation as a result. // If the navigation is initiated pragmatically by calling GoBack/Forward (comparing to user initiated // by clicking the back/forward button), this will result in a managed exception at the call to ibcs.GoBack() // in rbw.GoBackOverride(). rbw catches the exception when this happens. throw new OperationCanceledException(); } } return(null); }
/// <summary> /// Processes a loaded snapshot, if any. A loaded snapshot is offered with a <see cref="SnapshotOffer"/> /// message to the actor's <see cref="ReceiveRecover"/>. Then initiates a message replay, either starting /// from the loaded snapshot or from scratch, and switches to <see cref="RecoveryStarted"/> state. /// All incoming messages are stashed. /// </summary> /// <param name="maxReplays">Maximum number of messages to replay</param> private EventsourcedState RecoveryStarted(long maxReplays) { // protect against snapshot stalling forever because journal overloaded and such var timeout = Extension.JournalConfigFor(JournalPluginId).GetTimeSpan("recovery-event-timeout", null, false); var timeoutCancelable = Context.System.Scheduler.ScheduleTellOnceCancelable(timeout, Self, new RecoveryTick(true), Self); bool RecoveryBehavior(object message) { Receive receiveRecover = ReceiveRecover; switch (message) { case IPersistentRepresentation representation when IsRecovering: return(receiveRecover(representation.Payload)); case SnapshotOffer offer: return(receiveRecover(offer)); case RecoveryCompleted _: return(receiveRecover(RecoveryCompleted.Instance)); default: return(false); } } return(new EventsourcedState("recovery started - replay max: " + maxReplays, () => true, (receive, message) => { try { switch (message) { case LoadSnapshotResult res: { timeoutCancelable.Cancel(); if (res.Snapshot != null) { var offer = new SnapshotOffer(res.Snapshot.Metadata, res.Snapshot.Snapshot); var seqNr = LastSequenceNr; try { LastSequenceNr = res.Snapshot.Metadata.SequenceNr; if (!base.AroundReceive(RecoveryBehavior, offer)) { LastSequenceNr = seqNr; Unhandled(offer); } } catch (Exception ex) { try { OnRecoveryFailure(ex); } finally { Context.Stop(Self); } ReturnRecoveryPermit(); } } ChangeState(Recovering(RecoveryBehavior, timeout)); Journal.Tell(new ReplayMessages(LastSequenceNr + 1L, res.ToSequenceNr, maxReplays, PersistenceId, Self)); break; } case LoadSnapshotFailed failed: timeoutCancelable.Cancel(); try { OnRecoveryFailure(failed.Cause); } finally { Context.Stop(Self); } ReturnRecoveryPermit(); break; case RecoveryTick tick when tick.Snapshot: try { OnRecoveryFailure( new RecoveryTimedOutException( $"Recovery timed out, didn't get snapshot within {timeout.TotalSeconds}s.")); } finally { Context.Stop(Self); } ReturnRecoveryPermit(); break;
public IActionResult UpsertJournalForUser([FromRoute] int userId, [FromRoute] int journalId, [FromBody] Journal journal) { JournalService journalService = new JournalService(Settings.GetSection("AppSettings").GetSection("DefaultConnectionString").Value); int rowsAffected = journalService.UpsertJournalForUser(userId, journalId, journal); return(Ok(rowsAffected)); }
public async Task UpdateJournalAsync(Journal journal) { _context.Journals.Update(journal); await _context.SaveChangesAsync(); }
private string GetJournalHeader(Journal journal) { return($"{journal.Group.Title} ({journal.SubGroup}) {journal.Subject.ShortTitle}"); }
public void Action(Player player) { text = "'It`s a trap!': Співчуваю, ви пошкодилися у пастці! -1 НР"; player.Injure(); Journal.getInstance().LogNow(player, text); }