private void GetSingleUseProduct(SingleUseProduct product) { SingleUseProducts.Add(product); OnPropertyChanged(nameof(SingleUseProducts)); ChangeView?.Invoke("ViewServiceDone", false); }
private void GotoMainMenuFunc() { ChangeView?.Invoke("ViewMenuWindow", false); Clear(); }
public void ConsensusService_SingleNodeActors_OnStart_PrepReq_PrepResponses_Commits() { var mockWallet = new Mock <Wallet>(); mockWallet.Setup(p => p.GetAccount(It.IsAny <UInt160>())).Returns <UInt160>(p => new TestWalletAccount(p)); Console.WriteLine($"\n(UT-Consensus) Wallet is: {mockWallet.Object.GetAccount(UInt160.Zero).GetKey().PublicKey}"); var mockContext = new Mock <ConsensusContext>(mockWallet.Object, Blockchain.Singleton.Store); mockContext.Object.LastSeenMessage = new int[] { 0, 0, 0, 0, 0, 0, 0 }; var timeValues = new[] { new DateTime(1980, 06, 01, 0, 0, 1, 001, DateTimeKind.Utc), // For tests, used below new DateTime(1980, 06, 01, 0, 0, 3, 001, DateTimeKind.Utc), // For receiving block new DateTime(1980, 05, 01, 0, 0, 5, 001, DateTimeKind.Utc), // For Initialize new DateTime(1980, 06, 01, 0, 0, 15, 001, DateTimeKind.Utc), // unused }; for (int i = 0; i < timeValues.Length; i++) { Console.WriteLine($"time {i}: {timeValues[i].ToString()} "); } ulong defaultTimestamp = 328665601001; // GMT: Sunday, June 1, 1980 12:00:01.001 AM // check basic ConsensusContext // mockConsensusContext.Object.block_received_time.ToTimestamp().Should().Be(4244941697); //1968-06-01 00:00:01 // ============================================================================ // creating ConsensusService actor // ============================================================================ int timeIndex = 0; var timeMock = new Mock <TimeProvider>(); timeMock.SetupGet(tp => tp.UtcNow).Returns(() => timeValues[timeIndex]); //.Callback(() => timeIndex = timeIndex + 1); //Comment while index is not fixed TimeProvider.Current = timeMock.Object; TimeProvider.Current.UtcNow.ToTimestampMS().Should().Be(defaultTimestamp); //1980-06-01 00:00:15:001 //public void Log(string message, LogLevel level) //create ILogPlugin for Tests /* * mockConsensusContext.Setup(mr => mr.Log(It.IsAny<string>(), It.IsAny<LogLevel>())) * .Callback((string message, LogLevel level) => { * Console.WriteLine($"CONSENSUS LOG: {message}"); * } * ); */ // Creating a test block Header header = new Header(); TestUtils.SetupHeaderWithValues(header, UInt256.Zero, out UInt256 merkRootVal, out UInt160 val160, out ulong timestampVal, out uint indexVal, out Witness scriptVal); header.Size.Should().Be(105); Console.WriteLine($"header {header} hash {header.Hash} {header.PrevHash} timestamp {timestampVal}"); timestampVal.Should().Be(defaultTimestamp); TestProbe subscriber = CreateTestProbe(); TestActorRef <ConsensusService> actorConsensus = ActorOfAsTestActorRef <ConsensusService>( Akka.Actor.Props.Create(() => (ConsensusService)Activator.CreateInstance(typeof(ConsensusService), BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { subscriber, subscriber, mockContext.Object }, null)) ); var testPersistCompleted = new Blockchain.PersistCompleted { Block = new Block { Version = header.Version, PrevHash = header.PrevHash, MerkleRoot = header.MerkleRoot, Timestamp = header.Timestamp, Index = header.Index, NextConsensus = header.NextConsensus, Transactions = new Transaction[0] } }; Console.WriteLine("\n=========================="); Console.WriteLine("Telling a new block to actor consensus..."); Console.WriteLine("will trigger OnPersistCompleted without OnStart flag!"); // OnPersist will not launch timer, we need OnStart actorConsensus.Tell(testPersistCompleted); Console.WriteLine("\n=========================="); Console.WriteLine("\n=========================="); Console.WriteLine("will start consensus!"); actorConsensus.Tell(new ConsensusService.Start { IgnoreRecoveryLogs = true }); Console.WriteLine("Waiting for subscriber recovery message..."); // The next line force a waits, then, subscriber keeps running its thread // In the next case it waits for a Msg of type LocalNode.SendDirectly // As we may expect, as soon as consensus start it sends a RecoveryRequest of this aforementioned type var askingForInitialRecovery = subscriber.ExpectMsg <LocalNode.SendDirectly>(); Console.WriteLine($"Recovery Message I: {askingForInitialRecovery}"); // Ensuring cast of type ConsensusPayload from the received message from subscriber ConsensusPayload initialRecoveryPayload = (ConsensusPayload)askingForInitialRecovery.Inventory; // Ensuring casting of type RecoveryRequest RecoveryRequest rrm = (RecoveryRequest)initialRecoveryPayload.ConsensusMessage; rrm.Timestamp.Should().Be(defaultTimestamp); Console.WriteLine("Waiting for backupChange View... "); var backupOnAskingChangeView = subscriber.ExpectMsg <LocalNode.SendDirectly>(); var changeViewPayload = (ConsensusPayload)backupOnAskingChangeView.Inventory; ChangeView cvm = (ChangeView)changeViewPayload.ConsensusMessage; cvm.Timestamp.Should().Be(defaultTimestamp); cvm.ViewNumber.Should().Be(0); cvm.Reason.Should().Be(ChangeViewReason.Timeout); Console.WriteLine("\n=========================="); Console.WriteLine("will trigger OnPersistCompleted again with OnStart flag!"); actorConsensus.Tell(testPersistCompleted); Console.WriteLine("\n=========================="); // Disabling flag ViewChanging by reverting cache of changeview that was sent mockContext.Object.ChangeViewPayloads[mockContext.Object.MyIndex] = null; Console.WriteLine("Forcing Failed nodes for recovery request... "); mockContext.Object.CountFailed.Should().Be(0); mockContext.Object.LastSeenMessage = new int[] { -1, -1, -1, -1, -1, -1, -1 }; mockContext.Object.CountFailed.Should().Be(7); Console.WriteLine("\nWaiting for recovery due to failed nodes... "); var backupOnRecoveryDueToFailedNodes = subscriber.ExpectMsg <LocalNode.SendDirectly>(); var recoveryPayload = (ConsensusPayload)backupOnRecoveryDueToFailedNodes.Inventory; rrm = (RecoveryRequest)recoveryPayload.ConsensusMessage; rrm.Timestamp.Should().Be(defaultTimestamp); Console.WriteLine("will tell PrepRequest!"); mockContext.Object.PrevHeader.Timestamp = defaultTimestamp; mockContext.Object.PrevHeader.NextConsensus.Should().Be(UInt160.Parse("0xbdbe3ca30e9d74df12ce57ebc95a302dfaa0828c")); var prepReq = mockContext.Object.MakePrepareRequest(); var ppToSend = (PrepareRequest)prepReq.ConsensusMessage; // Forcing hashes to 0 because mempool is currently shared ppToSend.TransactionHashes = new UInt256[0]; ppToSend.TransactionHashes.Length.Should().Be(0); actorConsensus.Tell(prepReq); Console.WriteLine("Waiting for something related to the PrepRequest...\nNothing happens...Recovery will come due to failed nodes"); var backupOnRecoveryDueToFailedNodesII = subscriber.ExpectMsg <LocalNode.SendDirectly>(); var recoveryPayloadII = (ConsensusPayload)backupOnRecoveryDueToFailedNodesII.Inventory; rrm = (RecoveryRequest)recoveryPayloadII.ConsensusMessage; Console.WriteLine("\nFailed because it is not primary and it created the prereq...Time to adjust"); prepReq.ValidatorIndex = 1; //simulating primary as prepreq creator (signature is skip, no problem) // cleaning old try with Self ValidatorIndex mockContext.Object.PreparationPayloads[mockContext.Object.MyIndex] = null; actorConsensus.Tell(prepReq); var OnPrepResponse = subscriber.ExpectMsg <LocalNode.SendDirectly>(); var prepResponsePayload = (ConsensusPayload)OnPrepResponse.Inventory; PrepareResponse prm = (PrepareResponse)prepResponsePayload.ConsensusMessage; prm.PreparationHash.Should().Be(prepReq.Hash); // Simulating CN 3 actorConsensus.Tell(GetPayloadAndModifyValidator(prepResponsePayload, 2)); // Simulating CN 5 actorConsensus.Tell(GetPayloadAndModifyValidator(prepResponsePayload, 4)); // Simulating CN 4 actorConsensus.Tell(GetPayloadAndModifyValidator(prepResponsePayload, 3)); var onCommitPayload = subscriber.ExpectMsg <LocalNode.SendDirectly>(); var commitPayload = (ConsensusPayload)onCommitPayload.Inventory; Commit cm = (Commit)commitPayload.ConsensusMessage; // Original Contract Contract originalContract = Contract.CreateMultiSigContract(mockContext.Object.M, mockContext.Object.Validators); Console.WriteLine($"\nORIGINAL Contract is: {originalContract.ScriptHash}"); originalContract.ScriptHash.Should().Be(UInt160.Parse("0xbdbe3ca30e9d74df12ce57ebc95a302dfaa0828c")); mockContext.Object.Block.NextConsensus.Should().Be(UInt160.Parse("0xbdbe3ca30e9d74df12ce57ebc95a302dfaa0828c")); Console.WriteLine($"ORIGINAL BlockHash: {mockContext.Object.Block.Hash}"); Console.WriteLine($"ORIGINAL Block NextConsensus: {mockContext.Object.Block.NextConsensus}"); //Console.WriteLine($"VALIDATOR[0] {mockContext.Object.Validators[0]}"); //Console.WriteLine($"VALIDATOR[0]ScriptHash: {mockWallet.Object.GetAccount(mockContext.Object.Validators[0]).ScriptHash}"); KeyPair[] kp_array = new KeyPair[7] { UT_Crypto.generateKey(32), // not used, kept for index consistency, didactically UT_Crypto.generateKey(32), UT_Crypto.generateKey(32), UT_Crypto.generateKey(32), UT_Crypto.generateKey(32), UT_Crypto.generateKey(32), UT_Crypto.generateKey(32) }; for (int i = 0; i < mockContext.Object.Validators.Length; i++) { Console.WriteLine($"{mockContext.Object.Validators[i]}"); } mockContext.Object.Validators = new ECPoint[7] { mockContext.Object.Validators[0], kp_array[1].PublicKey, kp_array[2].PublicKey, kp_array[3].PublicKey, kp_array[4].PublicKey, kp_array[5].PublicKey, kp_array[6].PublicKey }; Console.WriteLine($"Generated keypairs PKey:"); for (int i = 0; i < mockContext.Object.Validators.Length; i++) { Console.WriteLine($"{mockContext.Object.Validators[i]}"); } // update Contract with some random validators var updatedContract = Contract.CreateMultiSigContract(mockContext.Object.M, mockContext.Object.Validators); Console.WriteLine($"\nContract updated: {updatedContract.ScriptHash}"); // Forcing next consensus var originalBlockHashData = mockContext.Object.Block.GetHashData(); mockContext.Object.Block.NextConsensus = updatedContract.ScriptHash; mockContext.Object.Block.Header.NextConsensus = updatedContract.ScriptHash; mockContext.Object.PrevHeader.NextConsensus = updatedContract.ScriptHash; var originalBlockMerkleRoot = mockContext.Object.Block.MerkleRoot; Console.WriteLine($"\noriginalBlockMerkleRoot: {originalBlockMerkleRoot}"); var updatedBlockHashData = mockContext.Object.Block.GetHashData(); Console.WriteLine($"originalBlockHashData: {originalBlockHashData.ToScriptHash()}"); Console.WriteLine($"updatedBlockHashData: {updatedBlockHashData.ToScriptHash()}"); Console.WriteLine("\n\n=========================="); Console.WriteLine("\nBasic commits Signatures verification"); // Basic tests for understanding signatures and ensuring signatures of commits are correct on tests var cmPayloadTemp = GetCommitPayloadModifiedAndSignedCopy(commitPayload, 1, kp_array[1], updatedBlockHashData); Crypto.VerifySignature(originalBlockHashData, cm.Signature, mockContext.Object.Validators[0].EncodePoint(false)).Should().BeFalse(); Crypto.VerifySignature(updatedBlockHashData, cm.Signature, mockContext.Object.Validators[0].EncodePoint(false)).Should().BeFalse(); Crypto.VerifySignature(originalBlockHashData, ((Commit)cmPayloadTemp.ConsensusMessage).Signature, mockContext.Object.Validators[1].EncodePoint(false)).Should().BeFalse(); Crypto.VerifySignature(updatedBlockHashData, ((Commit)cmPayloadTemp.ConsensusMessage).Signature, mockContext.Object.Validators[1].EncodePoint(false)).Should().BeTrue(); Console.WriteLine("\n=========================="); Console.WriteLine("\n=========================="); Console.WriteLine("\nCN2 simulation time"); actorConsensus.Tell(cmPayloadTemp); Console.WriteLine("\nCN3 simulation time"); actorConsensus.Tell(GetCommitPayloadModifiedAndSignedCopy(commitPayload, 2, kp_array[2], updatedBlockHashData)); Console.WriteLine("\nCN4 simulation time"); actorConsensus.Tell(GetCommitPayloadModifiedAndSignedCopy(commitPayload, 3, kp_array[3], updatedBlockHashData)); // ============================================= // Testing commit with wrong signature not valid // It will be invalid signature because we did not change ECPoint Console.WriteLine("\nCN7 simulation time. Wrong signature, KeyPair is not known"); actorConsensus.Tell(GetPayloadAndModifyValidator(commitPayload, 6)); Console.WriteLine("\nWaiting for recovery due to failed nodes... "); var backupOnRecoveryMessageAfterCommit = subscriber.ExpectMsg <LocalNode.SendDirectly>(); var rmPayload = (ConsensusPayload)backupOnRecoveryMessageAfterCommit.Inventory; RecoveryMessage rmm = (RecoveryMessage)rmPayload.ConsensusMessage; // ============================================= mockContext.Object.CommitPayloads[0] = null; Console.WriteLine("\nCN5 simulation time"); actorConsensus.Tell(GetCommitPayloadModifiedAndSignedCopy(commitPayload, 4, kp_array[4], updatedBlockHashData)); Console.WriteLine($"\nFocing block PrevHash to UInt256.Zero {mockContext.Object.Block.GetHashData().ToScriptHash()}"); mockContext.Object.Block.PrevHash = UInt256.Zero; // Payload should also be forced, otherwise OnConsensus will not pass commitPayload.PrevHash = UInt256.Zero; Console.WriteLine($"\nNew Hash is {mockContext.Object.Block.GetHashData().ToScriptHash()}"); Console.WriteLine($"\nForcing block VerificationScript to {updatedContract.Script.ToScriptHash()}"); mockContext.Object.Block.Witness = new Witness { }; mockContext.Object.Block.Witness.VerificationScript = updatedContract.Script; Console.WriteLine($"\nUpdating BlockBase Witness scripthash is {mockContext.Object.Block.Witness.ScriptHash}"); Console.WriteLine($"\nNew Hash is {mockContext.Object.Block.GetHashData().ToScriptHash()}"); Console.WriteLine("\nCN6 simulation time"); // Here we used modified mockContext.Object.Block.GetHashData().ToScriptHash() for blockhash actorConsensus.Tell(GetCommitPayloadModifiedAndSignedCopy(commitPayload, 5, kp_array[5], mockContext.Object.Block.GetHashData())); Console.WriteLine("\nWait for subscriber Local.Node Relay"); var onBlockRelay = subscriber.ExpectMsg <LocalNode.Relay>(); Console.WriteLine("\nAsserting time was Block..."); var utBlock = (Block)onBlockRelay.Inventory; Console.WriteLine($"\nAsserting block NextConsensus..{utBlock.NextConsensus}"); utBlock.NextConsensus.Should().Be(updatedContract.ScriptHash); Console.WriteLine("\n=========================="); // ============================================================================ // finalize ConsensusService actor // ============================================================================ Console.WriteLine("Finalizing consensus service actor and returning states."); TimeProvider.ResetToDefault(); //Sys.Stop(actorConsensus); }
// Metody umożliwiające przepływ danych pomiędzy podformularzami a głównym formularzem dodawania wizyty private void GetClient(Client client) { CurrentClient = client; OnPropertyChanged(nameof(CurrentClient)); ChangeView?.Invoke("ViewServiceDone", false); }
protected virtual void OnChangeView(ChangeViewEventArgs e) { ChangeView?.Invoke(this, e); }
private async void SwitchViewModel(ViewType type, object args = null) { switch (type) { case ViewType.Home: CurrentViewModel = homeViewModel; homeViewModel.CheckInitialized(); break; case ViewType.Follow: CurrentViewModel = followViewModel; followViewModel.CheckInitialized(); break; case ViewType.SpecialTopic: CurrentViewModel = specialTopicViewModel; specialTopicViewModel.CheckInitialized(); break; case ViewType.Friends: CurrentViewModel = friendsViewModel; await friendsViewModel.CheckInitialized(); break; case ViewType.UserCenter: CurrentViewModel = userCenterViewModel; MessengerInstance.Send(new UserItem() { UserId = GlobalValue.CurrentUserContext.Slug, BackView = ViewType.None }); break; case ViewType.Like: CurrentViewModel = likeViewModel; likeViewModel.CheckInitialized(); break; case ViewType.Login: CurrentViewModel = loginViewModel; break; case ViewType.About: CurrentViewModel = aboutViewModel; aboutViewModel.RefreshSetting(); break; case ViewType.Article: ChangeView info = args as ChangeView; CurrentViewModel = articleViewModel; MessengerInstance.Send(new ArticleItem() { NoteId = info.Context.ToString(), BackView = info.FromView }); break; case ViewType.OtherUser: ChangeView userinfo = args as ChangeView; CurrentViewModel = userCenterViewModel; MessengerInstance.Send(new UserItem() { UserId = userinfo.Context.ToString(), BackView = userinfo.FromView }); break; default: break; } }
public ActionResult Submit(ChangeView changeView) { Provider.SubmitChange(changeView); changeView = Provider.GetChange(changeView.ID); return View("Details", changeView); }
private void Start() { view = GameObject.FindObjectOfType <ChangeView>(); }
private void GetNewProduct(object product) { NewProducts.Add(product as SingleUseProduct); OnPropertyChanged(nameof(NewProducts)); ChangeView?.Invoke("ViewDeliveryAdd", false); }
void Start() { viewpoint = ChangeView.ViewFlagPoint(); }
///<summary> ///添加: ///</summary> /// <param name="model">要添加的model</param> /// <returns>受影响的行数</returns> public Result <int> AddChange(ChangeView model, List <Base_Files> fileList = null) { Result <int> result = new Result <int>(); try { Epm_Change change = new Epm_Change(); List <Epm_ChangeCompany> companys = new List <Epm_ChangeCompany>(); model.Id = change.Id; ViewToEmp(model, out change, out companys); bool dConfig = DataOperateBusiness <Epm_Change> .Get().Count(i => i.ProjectId == change.ProjectId && i.State != (int)ApprovalState.ApprSuccess) > 0; if (dConfig) { throw new Exception("已存在该项目的变更申请!"); } var dictionaryList = DataOperateBasic <Base_TypeDictionary> .Get().GetList(t => t.Type == DictionaryType.ChangeRatio.ToString() && t.No == "ReduceRatio").ToList().FirstOrDefault(); if (change.ChangeAmount < 0 && change.State == (int)ApprovalState.WaitAppr) { int ratio = Convert.ToInt32(dictionaryList.Name); if ((-change.ChangeAmount) < change.TotalAmount * ((decimal)ratio / 100)) { change.State = (int)ApprovalState.ApprSuccess; model.State = (int)ApprovalState.ApprSuccess; } } var rows = DataOperateBusiness <Epm_Change> .Get().Add(change); DataOperateBusiness <Epm_ChangeCompany> .Get().AddRange(companys); //新增附件 AddFilesByTable(change, fileList); result.Data = rows; result.Flag = EResultFlag.Success; WriteLog(BusinessType.Change.GetText(), SystemRight.Add.GetText(), "新增: " + model.Id); if (model.State == (int)ApprovalState.ApprSuccess) { var project = DataOperateBusiness <Epm_Project> .Get().GetList(t => t.Id == model.ProjectId).FirstOrDefault(); if (project != null) { project.Amount = model.TotalAmount + model.ChangeAmount; DataOperateBusiness <Epm_Project> .Get().Update(project); } } if (model.State == (int)ApprovalState.WaitAppr) { if (companys.Any() && companys.Count > 0) { for (int i = 0; i < companys.Count; i++) { var comID = companys[i].CompanyId; var temp = DataOperateBusiness <Epm_ProjectStateTrack> .Get().GetList(t => t.CompanyId == comID).FirstOrDefault(); if (temp != null) { temp.Qty = (Convert.ToInt32(temp.Qty) + 1).ToString(); DataOperateBusiness <Epm_ProjectStateTrack> .Get().Update(temp); } } } WriteLog(BusinessType.Change.GetText(), SystemRight.Add.GetText(), "生成消息: " + model.Id); var project = DataOperateBusiness <Epm_Project> .Get().GetModel(model.ProjectId.Value); #region 生成待办 List <Epm_Approver> list = new List <Epm_Approver>(); Epm_Approver app = new Epm_Approver(); app.Title = CurrentUserName + "提交了变更申请,待审核"; app.Content = CurrentUserName + "提交了变更申请,待审核"; app.SendUserId = CurrentUserID.ToLongReq(); app.SendUserName = CurrentUserName; app.SendTime = DateTime.Now; app.LinkURL = string.Empty; app.BusinessTypeNo = BusinessType.Change.ToString(); app.Action = SystemRight.Add.ToString(); app.BusinessTypeName = BusinessType.Change.GetText(); app.BusinessState = (int)(ApprovalState.WaitAppr); app.BusinessId = model.Id; app.ApproverId = project.PMId; app.ApproverName = project.PMName; app.ProjectId = model.ProjectId; app.ProjectName = project.Name; list.Add(app); AddApproverBatch(list); WriteLog(BusinessType.Change.GetText(), SystemRight.Add.GetText(), "提交变更生成待办: " + model.Id); #endregion #region 消息 var waitSend = GetWaitSendMessageList(model.ProjectId.Value); foreach (var send in waitSend) { Epm_Massage modelMsg = new Epm_Massage(); modelMsg.ReadTime = null; modelMsg.RecId = send.Key; modelMsg.RecName = send.Value; modelMsg.RecTime = DateTime.Now; modelMsg.SendId = CurrentUserID.ToLongReq(); modelMsg.SendName = CurrentUserName; modelMsg.SendTime = DateTime.Now; modelMsg.Title = CurrentUserName + "提交了变更申请,待审核"; modelMsg.Content = CurrentUserName + "提交了变更申请,待审核"; modelMsg.Type = 2; modelMsg.IsRead = false; modelMsg.BussinessId = model.Id; modelMsg.BussinesType = BusinessType.Change.ToString(); modelMsg.ProjectId = model.ProjectId.Value; modelMsg.ProjectName = model.ProjectName; modelMsg = base.SetCurrentUser(modelMsg); modelMsg = base.SetCreateUser(modelMsg); DataOperateBusiness <Epm_Massage> .Get().Add(modelMsg); } #endregion #region 发送短信 //Dictionary<string, string> parameterSms = new Dictionary<string, string>(); //parameterSms.Add("UserName", CurrentUserName); //WriteSMS(project.PMId.Value, 0, MessageStep.ChangeAdd, parameterSms); #endregion } } catch (Exception ex) { result.Data = -1; result.Flag = EResultFlag.Failure; result.Exception = new ExceptionEx(ex, "AddChange"); } return(result); }