public DownloadProgress(ByteSize size, ByteSize downloaded, TransferState state) { Size = size; Downloaded = downloaded; State = state; Timestamp = DateTime.Now; }
public void UploadAsync(Action UploadedCallback) { State = TransferState.Running; BytesTransfer = 0; Task.Run(() => { try { List <byte> mbuffer = new List <byte>(BytebufferInitSize); while (true) { int r = filestream.ReadByte(); if (r == -1) { break; } mbuffer.Add(Convert.ToByte(r)); BytesTransfer++; } networkStream.Write(mbuffer.ToArray(), 0, BytesTransfer); State = TransferState.Finished; UploadedCallback(); } catch (Exception exc) { State = TransferState.Error; throw exc; } }); return; }
public DownloadProgress(ByteSize size, ByteSize downloaded, TransferState state) { this.Size = size; this.Downloaded = downloaded; this.State = state; this.Timestamp = DateTime.Now; }
public void UpdateTransferState(long operatorId, TransferState state) { ExceptionHelper.ThrowIfNotId(operatorId, nameof(operatorId)); ExceptionHelper.ThrowIfTrue(!Enum.IsDefined(typeof(TransferState), state), "state", "值不在范围内"); _LazyEntity.Value.transferState = (byte)state; _LazyEntity.Value.transferUpdated = DateTime.Now; _LazyEntity.Value.transferOperator = operatorId; _FootPrintRepository.SaveChanges(); }
public WorkingListViewItem(string rootfile, ListView parent, TextBox txtbtShow) { //initializing delegates mySetProgress = new SetProgress(SetProgressCore); myWriteLog = new WriteLog(WriteLogCore); myTransferState = new TransferState(TransferStateCore); myIncProgressBlock = new IncProgressBlock(IncProgressBlockCore); progressListener = new EventHandler(setProgressBlock); // feedbackListenerForLog = new EventHandler(WriteConverterLog); mySetProgressBarMove = new SetProgressBarMoveDelegate(SetProgressMoveCore); mySetProgressBarStop = new SetProgressBarMoveDelegate(SetProgressStopCore); state = new FileState(); state.StateValProgress = StateVal.STATE_READY; this.state.SourceFileName = rootfile; this.ToolTipText = rootfile; this.displayName = Path.GetFileName(rootfile); Icon icon = GetSmallIcon(rootfile); if (icon == null) { icon = IconResource.Default; } fileIcon = icon.ToBitmap(); //Create Working Thread workingThread = null; //For Status Button ListViewSubItem statusSub = this.SubItems[0]; btnItem = new UofStatusButton(this); btnItem.Tag = this.ListView; parent.Controls.Add(btnItem); ((UofListView)parent).AddControlToSubItem(btnItem, statusSub, true); //For name & Progress Bar ListViewSubItem nameSub = this.SubItems.Add(""); pgbItem = new UofProgressBar(this); pgbItem.Minimum = 1; pgbItem.Maximum = 1000; pgbItem.Step = 1; pgbItem.Tag = this.ListView; pgbItem.Showtext = displayName; parent.Controls.Add(pgbItem); ((UofListView)parent).AddControlToSubItem(pgbItem, nameSub, false); totalFiles = 0; currentFile = 0; logText = ""; // this.txtbxShow = txtbxShow; }
public void Cancle() { if(transferState==TransferState.Running) transferState = TransferState.CanceledByMyself; else if (transferState == TransferState.Wating) { transferState = TransferState.CanceledByMyself; Completed(); } }
public static async Task <HttpResponseMessage> GetTransferStateRun( [HttpTrigger(AuthorizationLevel.Function, "GET", Route = @"GetTransferState/{transfernumber}")] HttpRequestMessage req, string transfernumber, [Projection("Bank", "Transfer", "{transfernumber}", nameof(TransferState))] Projection prjTransferState) { // Set the start time for how long it took to process the message DateTime startTime = DateTime.UtcNow; #region Tracing telemetry Activity.Current.AddTag("Transfer Number", transfernumber); #endregion string result = $"No fund transfer found with the identifier : {transfernumber}"; if (null != prjTransferState) { if (await prjTransferState.Exists()) { // Run the "Transfer state" projection TransferState state = await prjTransferState.Process <TransferState>(); result = $"Transfer {transfernumber} state is {state.LastStateChange} ({state.AmountDeposited} of {state.AmountOfTransferRequested} transfered) "; return(req.CreateResponse <ProjectionFunctionResponse>(System.Net.HttpStatusCode.OK, ProjectionFunctionResponse.CreateResponse(startTime, false, result, state.CurrentSequenceNumber), FunctionResponse.MEDIA_TYPE)); } else { // No such transfer request exists result = $"Transfer {transfernumber} is not yet created - cannot retrieve a state for it"; return(req.CreateResponse <ProjectionFunctionResponse>(System.Net.HttpStatusCode.NotFound, ProjectionFunctionResponse.CreateResponse(startTime, true, result, 0), FunctionResponse.MEDIA_TYPE)); } } // If we got here no transfer was found return(req.CreateResponse <ProjectionFunctionResponse>(System.Net.HttpStatusCode.NotFound, ProjectionFunctionResponse.CreateResponse(startTime, true, result, 0), FunctionResponse.MEDIA_TYPE)); }
public FileDownLoadCompletedEventArgs(TransferState state, string parameter) { State = state; switch (State) { case TransferState.Completed: TargetFile = parameter; break; case TransferState.Error: ErrorMessage = parameter; break; } }
private TransferState Send(int length) { TransferState state = TransferState.ACK; bool? wait = null; CancellationToken cancellationToken = new CancellationToken(); Comms.com.PurgeQueue(); Comms.com.WriteBytes(hdr, 3); Comms.com.WriteBytes(payload, length); response = NAK; new Thread(() => { wait = WaitFor.SingleEvent <int>( cancellationToken, s => GetByte(s), a => Comms.com.ByteReceived += a, a => Comms.com.ByteReceived -= a, packetNum == 0 ? 8000 : 2000, () => Comms.com.WriteBytes(crc, 2)); }).Start(); while (wait == null) { EventUtils.DoEvents(); } switch (response) { case ACK: state = TransferState.ACK; break; case NAK: state = TransferState.NAK; break; case CAN: state = TransferState.CAN; break; } if (packetNum == 0) // Read 'C' from input { Comms.com.ReadByte(); } return(state); }
private void UploadFile() { try { CurrentState = TransferState.Uploading; var ftpReq = (FtpWebRequest)WebRequest.Create(_uploadFileUrl); ftpReq.Method = WebRequestMethods.Ftp.UploadFile; ftpReq.Timeout = TimeOut; ftpReq.Credentials = new NetworkCredential(_userName, _password); _progressTimer = new System.Threading.Timer(callback => { var speed = (_fileUploadedSize - _fileUploadedOldSize) / 1024F; var unit = "K"; var bigThen1K = speed > 1024; if (bigThen1K) { speed = speed / 1024; unit = "M"; } OnProgressChanged(_fileUploadedSize, string.Format("{0}{1}/s", Math.Round(speed, 1), unit)); _fileUploadedOldSize = _fileUploadedSize; }, null, 1000, 1000); using (var fs = File.OpenRead(_localFile)) { TotalFileSize = (int)fs.Length; fs.Seek(_fileUploadedSize, SeekOrigin.Begin); ftpReq.ContentOffset = _fileUploadedSize; ftpReq.KeepAlive = false; ftpReq.ReadWriteTimeout = TimeOut; ftpReq.UseBinary = true; ftpReq.UsePassive = _usePassive; using (var reqStream = ftpReq.GetRequestStream()) { var buffer = new byte[1024]; var readOffset = fs.Read(buffer, 0, buffer.Length); while (readOffset > 0) { reqStream.Write(buffer, 0, readOffset); readOffset = fs.Read(buffer, 0, buffer.Length); _fileUploadedSize += readOffset; } } } } catch (Exception e) { _exception = e; } }
/// <summary>Called when Node.Disconnect is triggered stopping /// transfer states and preventing any more transfers. </summary> /// <param name="o">Unimportant.</param> /// <param name="eargs">Unimportant.</param> protected void DepartureHandler() { lock (_transfer_sync) { if (_right_transfer_state != null) { _right_transfer_state.Interrupt(); _right_transfer_state = null; } if (_left_transfer_state != null) { _left_transfer_state.Interrupt(); _left_transfer_state = null; } } }
public async Task ConfirmTransfer(InnerTransfer transfer) { TransferState state = await FindTransferStateByName(TransferStatesEnum.NotConfirmed); if (transfer.TransferStateId == state.Id) { List <Transaction> transactions = transactionService.CreateTransactions(transfer); transactionService.AddTransactions(transactions); transfer.TransferState = await FindTransferStateByName(TransferStatesEnum.Confirmed); transfer.TransferDate = DateTime.Now; context.InnerTransfers.Update(transfer); context.SaveChanges(); } }
private void SetTransferState(TransferState value) { lock (this) { object oldValue; oldValue = m_TransferState; m_TransferState = value; SetTaskState(ToTaskState(m_TransferState)); Monitor.PulseAll(this); m_Progress.RaiseStateChanged(); } }
public Payment( string transferId, string creditCardtId, string orderId, Money amount, TransferState transferState, DateTime startedAtUtc ) { TransferId = transferId; CreditCardtId = creditCardtId; OrderId = orderId; Amount = amount; TransferState = transferState; StartedAtUtc = startedAtUtc; UpdatedAtUtc = startedAtUtc; }
private static void ReadHeader(Stream input, out int ver, out TransferState state, out Guid txid, out Salt salt) { ver = PrimitiveSerializer.Int32.ReadFrom(input); Check.Assert <InvalidDataException>(ver == VersionHeader); int istate = PrimitiveSerializer.Int32.ReadFrom(input); Check.Assert <InvalidDataException>(Enum.IsDefined(typeof(TransferState), istate)); state = (TransferState)istate; byte[] bytes = new byte[16]; Check.Assert <InvalidDataException>(bytes.Length == input.Read(bytes, 0, bytes.Length)); txid = new Guid(bytes); bytes = new byte[32]; Check.Assert <InvalidDataException>(bytes.Length == input.Read(bytes, 0, bytes.Length)); salt = Salt.FromBytes(bytes); }
public Transfer( string transferId, AccountId sourceAccountId, AccountId destinationAccountId, Money amount, TransferState transferState, string description, DateTime startedAtUtc ) { TransferId = transferId; SourceAccountId = sourceAccountId; DestinationAccountId = destinationAccountId; Amount = amount; TransferState = transferState; Description = description; StartedAtUtc = startedAtUtc; UpdatedAtUtc = startedAtUtc; }
internal void ForceComplete(TransferState state) { //正常状况下,如果已经IsPostCompleted,就不会更新Length了。 //异常情况是,当对方通知文件已经存在时,这边不管已经传输多少,直接把状态修改成Confirmed。此时界面上需要直接把进度更新成100%。 var tmp = TransferredLength; TransferredLength = Length; var delta = Length - tmp; Progressed?.Invoke(this, delta); if (Parent != null) { ((IProgressable)Parent).Progress((int)delta); } //要放在最后,因为上面Progress会引起父状态变化,而这里会导致递归检查父状态。 TransferState = state; }
private void SetTransferState(TransferState value) { lock (this) { var oldValue = this.transferState; if (this.transferState != value) { this.transferState = value; OnTransferStateChanged(new FileTransferServiceEventArgs((TransferState)oldValue, this.transferState)); SetTaskState(ToTaskState(this.transferState)); Monitor.PulseAll(this); this.progress.RaiseStateChanged(); } } }
public async Task <string> Transfer([NotNull] TransferState cmd) { var ps = cmd.CurrentSession; ConnectState.PlayOrigin = ProtoUtils.ConvertPlayOrigin(ps.PlayOrigin); ConnectState.Options = ProtoUtils.ConvertPlayerOptions(cmd.Options); var sessionId = SetContext(ps.Context); var pb = cmd.Playback; TracksKeeper.InitializeFrom(list => list.FindIndex(z => z.Uid == ps.CurrentUid), pb.CurrentTrack, cmd.Queue); ConnectState.PositionAsOfTimestamp = pb.PositionAsOfTimestamp; ConnectState.Timestamp = pb.IsPaused ? TimeProvider.CurrentTimeMillis() : pb.Timestamp; await LoadTransforming(); return(sessionId); }
public bool Upload(string path) { TransferState state = TransferState.NAK; FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read); long bytesRemaining = fileStream.Length; Comms.com.EventMode = false; Comms.com.PurgeQueue(); ClearPayload(); if (TransferInitalPacket(path, fileStream) == TransferState.ACK) { do { packetNum++; if (bytesRemaining < 1024) { ClearPayload(); } bytes = fileStream.Read(payload, 0, 1024); bytesRemaining -= bytes; DataTransferred?.Invoke(fileStream.Length, fileStream.Length - bytesRemaining); state = TransferPacket(bytes <= 128 ? 128 : 1024); } while (bytesRemaining > 0 && state == TransferState.ACK); if (state == TransferState.ACK) { hdr[0] = EOT; Comms.com.WriteBytes(hdr, 1); } } Thread.Sleep(100); Comms.com.PurgeQueue(); Comms.com.EventMode = true; return(state == TransferState.ACK); }
public void DownloadAsync(Action DownloadedCallback) { State = TransferState.Running; BytesTransfer = 0; Task.Run(() => { List <byte> mbuffer = new List <byte>(BytebufferInitSize); try { while (true) { int r = networkStream.ReadByte(); if (r < byte.MinValue || r > byte.MaxValue) { break; } mbuffer.Add(Convert.ToByte(r)); BytesTransfer++; } filestream.Write(mbuffer.ToArray(), 0, BytesTransfer); State = TransferState.Finished; DownloadedCallback(); } catch (Exception exc) { if (exc.GetType() == typeof(ObjectDisposedException)) { filestream.Write(mbuffer.ToArray(), 0, BytesTransfer); State = TransferState.Finished; DownloadedCallback(); } else { State = TransferState.Error; throw exc; } } }); return; }
public async Task <InnerTransfer> CreateInnerTransfer(Account sender, Account receiver, decimal amount, string comment, decimal?amountReceive, int?exchangeRateId, int?exchangeRateIdSecond) { TransferState state = await FindTransferStateByName(TransferStatesEnum.Confirmed); if (sender != null) { if (sender.UserInfoId == null) { state = await FindTransferStateByName(TransferStatesEnum.NotConfirmed); } if (!await accountService.IsBalanceEnough(sender.Id, amount)) { state = await FindTransferStateByName(TransferStatesEnum.BalanceNotEnough); } if (sender.Locked) { state = await FindTransferStateByName(TransferStatesEnum.AccountIsLocked); } } InnerTransfer transfer = new InnerTransfer { AccountSender = sender, AccountReceiver = receiver, Amount = amount, Comment = comment, TransferState = state, TransferDate = DateTime.Now, AmountReceive = amountReceive, ExchangeRateId = exchangeRateId, ExchangeRateIdSecond = exchangeRateIdSecond }; return(transfer); }
public void ProvinceClicked(Province p) { if (PopUp) { return; } switch (state) { case GameState.Battle: BattleState.ProvinceClicked(p, players[activePlayer]); break; case GameState.Transfer: TransferState.ProvinceClicked(p, players[activePlayer]); break; case GameState.Reinforce: ReinforceState.ProvinceClicked(p, players[activePlayer]); break; } }
internal void RightClick() { if (PopUp) { return; } switch (state) { case GameState.Battle: BattleState.RightClick(); break; case GameState.Transfer: TransferState.RightClick(); break; case GameState.Reinforce: ReinforceState.RightClick(); break; } }
//private bool _verified; /* this is a debugging aid used to ensure all messages are signed or verified */ public Message(TransferState state, Guid transferId, RSAPublicKey key, Converter <Guid, Salt> sessionSecret) { _version = VersionHeader; _state = state; _transferId = transferId; _salt = new Salt(Salt.Size.b256); _protected = new MemoryStream(); _payload = new NonClosingStream(_protected); _hash = new HashStream(new SHA256Managed()); WriteHeader(_hash); Salt secret; if (!UsesSessionKey) { // Outer encryption is straight PKI based on the remote public key _payload = key.Encrypt(_payload); _hash.ChangeStream(_payload); // Preceed the message with a new, AES key secret = new Salt(Salt.Size.b256); _hash.Write(secret.ToArray(), 0, 32); } else { secret = sessionSecret(_transferId); Check.IsEqual(32, Check.NotNull(secret).Length); } AESCryptoKey sessionKey = new AESCryptoKey( // Prefix the key with the message's salt and compute a SHA256 hash to be used as the key Hash.SHA256(_salt.GetData(secret.ToArray()).ToStream()).ToArray(), // Compute an IV for this aes key and salt combination IV(secret, _salt) ); _payload = sessionKey.Encrypt(_payload); _hash.ChangeStream(_payload); }
//private bool _verified; /* this is a debugging aid used to ensure all messages are signed or verified */ public Message(TransferState state, Guid transferId, RSAPublicKey key, Converter<Guid, Salt> sessionSecret) { _version = VersionHeader; _state = state; _transferId = transferId; _salt = new Salt(Salt.Size.b256); _protected = new MemoryStream(); _payload = new NonClosingStream(_protected); _hash = new HashStream(new SHA256Managed()); WriteHeader(_hash); Salt secret; if (!UsesSessionKey) { // Outer encryption is straight PKI based on the remote public key _payload = key.Encrypt(_payload); _hash.ChangeStream(_payload); // Preceed the message with a new, AES key secret = new Salt(Salt.Size.b256); _hash.Write(secret.ToArray(), 0, 32); } else { secret = sessionSecret(_transferId); Check.IsEqual(32, Check.NotNull(secret).Length); } AESCryptoKey sessionKey = new AESCryptoKey( // Prefix the key with the message's salt and compute a SHA256 hash to be used as the key Hash.SHA256(_salt.GetData(secret.ToArray()).ToStream()).ToArray(), // Compute an IV for this aes key and salt combination IV(secret, _salt) ); _payload = sessionKey.Encrypt(_payload); _hash.ChangeStream(_payload); }
protected static TaskState ToTaskState(TransferState transferState) { switch (transferState) { case TransferState.NotStarted: return(TaskState.NotStarted); case TransferState.Preparing: case TransferState.Comparing: case TransferState.Transferring: case TransferState.Copying: case TransferState.Tidying: return(TaskState.Running); case TransferState.Finished: return(TaskState.Finished); case TransferState.Stopped: return(TaskState.Stopped); default: return(TaskState.Unknown); } }
/// <summary> /// Create a TransferStatus object. /// </summary> /// <param name="bytesTotal">Total bytes in the requested transfer.</param> /// <param name="bytesTransfered">Total bytes sent in the requested transfer.</param> /// <param name="percentTransfered">A percentage conversion of the total data sent in the requested transfer.</param> /// <param name="transferState">The current state of the transfer</param> /// <param name="message">A message to display with the update</param> public TransferStatus(int bytesTotal, int bytesTransfered, int percentTransfered, TransferState transferState, string message = "") { BytesTotal = bytesTotal; BytesTransfered = bytesTransfered; PercentTransfered = percentTransfered; TransferState = transferState; Message = message; if (message.Length > 0) { return; } switch (transferState) { case TransferState.Failed: Message = "Unknown Failure"; break; case TransferState.Running: Message = "Currently transfer pages."; break; case TransferState.Succeeded: Message = "Transfer successfully completed."; break; case TransferState.FailedLostPackets: Message = "Too many missed packets."; break; case TransferState.FailedTimeOut: Message = "Too many packet timeouts."; break; case TransferState.FailedInvalidFile: Message = "File is not the correct format."; break; case TransferState.FailedConnection: Message = "Unable to connect to unit."; break; case TransferState.FailedInvalidFirmware: Message = "Firmware does not support this feature, please upgrade the unit firmware."; break; case TransferState.FailedInitialize: Message = "Unable to initialize transfer."; break; case TransferState.FailedStop: Message = "Unable to stop current transfer."; break; case TransferState.FailedStart: Message = "Unable to start current transfer."; break; default: break; } }
public TransferClosedEventArgs(TransferState state, long expected_bytes, long bytes_reported) { this.state = state; this.expected_bytes = expected_bytes; this.bytes_reported = bytes_reported; }
/** * <summary>This is called whenever there is a disconnect or a connect, the * idea is to determine if there is a new left or right node, if there is and * here is a pre-existing transfer, we must interupt it, and start a new * transfer.</summary> * <remarks>The possible scenarios where this would be active: * - no change on left * - new left node with no previous node (from disc or new node) * - left disconnect and new left ready * - left disconnect and no one ready * - no change on right * - new right node with no previous node (from disc or new node) * - right disconnect and new right ready * - right disconnect and no one ready * </remarks> * <param name="o">Unimportant</param> * <param name="eargs">Contains the ConnectionEventArgs, which lets us know * if this was a Structured Connection change and if it is, we should check * the state of the system to see if we have a new left or right neighbor. * </param> */ protected void ConnectionHandler(object o, EventArgs eargs) { if (!_online) { return; } ConnectionEventArgs cargs = eargs as ConnectionEventArgs; Connection old_con = cargs.Connection; //first make sure that it is a new StructuredConnection if (old_con.MainType != ConnectionType.Structured) { return; } lock (_transfer_sync) { if (!_online) { return; } ConnectionTable tab = _node.ConnectionTable; Connection lc = null, rc = null; try { lc = tab.GetLeftStructuredNeighborOf((AHAddress)_node.Address); } catch (Exception) {} try { rc = tab.GetRightStructuredNeighborOf((AHAddress)_node.Address); } catch (Exception) {} if (lc != null) { if (lc.Address != _left_addr) { if (_left_transfer_state != null) { _left_transfer_state.Interrupt(); _left_transfer_state = null; } _left_addr = lc.Address; if (Count > 0) { _left_transfer_state = new TransferState(lc, this); } } } else if (_left_addr != null) { if (_left_transfer_state != null) { _left_transfer_state.Interrupt(); _left_transfer_state = null; } _left_addr = null; } if (rc != null) { if (rc.Address != _right_addr) { if (_right_transfer_state != null) { _right_transfer_state.Interrupt(); _right_transfer_state = null; } _right_addr = rc.Address; if (Count > 0) { _right_transfer_state = new TransferState(rc, this); } } } else if (_right_addr != null) { if (_right_transfer_state != null) { _right_transfer_state.Interrupt(); _right_transfer_state = null; } _right_addr = null; } } }
/// <summary>Called when Node.Disconnect is triggered stopping /// transfer states and preventing any more transfers. </summary> /// <param name="o">Unimportant.</param> /// <param name="eargs">Unimportant.</param> protected void DepartureHandler() { lock(_transfer_sync) { if(_right_transfer_state != null) { _right_transfer_state.Interrupt(); _right_transfer_state = null; } if(_left_transfer_state != null) { _left_transfer_state.Interrupt(); _left_transfer_state = null; } } }
public TransferStateChangedEventArgs(TransferState state) { this.state = state; }
public void FillData() { /*if (!context.TypeOfDocuments.Any()) * { * TypeOfDocument pasport = new TypeOfDocument { Name = "Паспорт" }; * TypeOfDocument pasport1 = new TypeOfDocument { Name = "ВоенныйБилет" }; * TypeOfDocument pasport2 = new TypeOfDocument { Name = "СвидетельствоОрождении" }; * context.TypeOfDocuments.AddRange(pasport, pasport1, pasport2); * context.SaveChanges(); * } * * if (!context.Countries.Any()) * { * Country country = new Country { CountryName = "Кыргызстан" }; * Country country1 = new Country { CountryName = "Таджикистан" }; * Country country2 = new Country { CountryName = "Казахстан" }; * context.Countries.AddRange(country, country1, country2); * context.SaveChanges(); * } * if (!context.LegalForms.Any()) * { * LegalForm legalForm = new LegalForm { LegalFormName = "ОсОО" }; * LegalForm legalForm1 = new LegalForm { LegalFormName = "ОАО" }; * LegalForm legalForm2 = new LegalForm { LegalFormName = "ЗАО" }; * context.LegalForms.AddRange(legalForm, legalForm1, legalForm2); * context.SaveChanges(); * } * if (!context.PropertyTypes.Any()) * { * PropertyType propertyType = new PropertyType { PropertyTypeName = "Государственная" }; * PropertyType propertyType1 = new PropertyType { PropertyTypeName = "Частная" }; * PropertyType propertyType2 = new PropertyType { PropertyTypeName = "Смешанная" }; * context.PropertyTypes.AddRange(propertyType, propertyType1, propertyType2); * context.SaveChanges(); * } * if (!context.Residencies.Any()) * { * Residency residency = new Residency { ResidencyName = "Резидент" }; * Residency residency1 = new Residency { ResidencyName = "НеРезидент" }; * * context.Residencies.AddRange(residency, residency1); * context.SaveChanges(); * } * if (!context.TaxInspections.Any()) * { * TaxInspection taxInspection = new TaxInspection { TaxInspectionName = "Ленинский" }; * TaxInspection taxInspection1 = new TaxInspection { TaxInspectionName = "Свердловский" }; * TaxInspection taxInspection2 = new TaxInspection { TaxInspectionName = "Октябрьский" }; * context.TaxInspections.AddRange(taxInspection, taxInspection1, taxInspection2); * context.SaveChanges(); * }*/ if (!context.TransactionTypes.Any()) { List <TransactionType> transactions = new List <TransactionType>(); transactions.Add(TransactionType.Create(TransactionTypesEnum.Debit)); transactions.Add(TransactionType.Create(TransactionTypesEnum.Credit)); context.TransactionTypes.AddRange(transactions); context.SaveChanges(); } if (!context.ExchangeRateTypes.Any()) { ExchangeRateType exchangeRateType = ExchangeRateType.Create(ExchangeRateTypesEnum.NBKR); ExchangeRateType exchangeRateType1 = ExchangeRateType.Create(ExchangeRateTypesEnum.Market); context.ExchangeRateTypes.AddRange(exchangeRateType, exchangeRateType1); context.SaveChanges(); } if (!context.TransferStates.Any()) { context.AddRange( TransferState.Create(TransferStatesEnum.Confirmed), TransferState.Create(TransferStatesEnum.NotConfirmed), TransferState.Create(TransferStatesEnum.Canceled), TransferState.Create(TransferStatesEnum.BalanceNotEnough), TransferState.Create(TransferStatesEnum.AccountIsLocked)); context.SaveChanges(); } if (!context.TypeOfTransfers.Any()) { context.AddRange( TypeOfTransfer.Create(TypeOfTransfersEnum.InnerTransfer), TypeOfTransfer.Create(TypeOfTransfersEnum.InterBankTransfer), TypeOfTransfer.Create(TypeOfTransfersEnum.Conversion)); context.SaveChanges(); } if (!context.Currencies.Any()) { context.Currencies.Add ( new Currency { Code = "123", Name = "SOM", IsNativeCurrency = true } ); context.SaveChanges(); } if (!context.OurBank.Any()) { Currency currency = context.Currencies.FirstOrDefault(n => n.IsNativeCurrency == true); Account bankAccount = new Account { Locked = false, CurrencyId = currency.Id, Number = "1234567890123456" }; context.Accounts.Add(bankAccount); context.SaveChanges(); BankInfo bank = new BankInfo { BankName = "OurBank", Email = "*****@*****.**" }; context.BankInfos.Add(bank); OurBank ourBank = new OurBank { BIK = "123", AccountId = bankAccount.Id, BankInfoId = bank.Id }; context.OurBank.Add(ourBank); context.SaveChanges(); } if (!context.IntervalTypes.Any()) { List <IntervalType> intervalTypes = new List <IntervalType>(); intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceADay)); intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceAWeek)); intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceInTwoWeeks)); intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceAMonth)); intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceAQuarter)); intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceAHalfYear)); intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceAYear)); context.IntervalTypes.AddRange(intervalTypes); context.SaveChanges(); } if (!context.AddressTypes.Any()) { List <AddressType> addressTypes = new List <AddressType> { AddressType.Create(AddressTypesEnum.FactAddress), AddressType.Create(AddressTypesEnum.LegalAddress), AddressType.Create(AddressTypesEnum.BirthAddress) }; context.AddRange(addressTypes); context.SaveChanges(); } }
/** <summary>This is called whenever there is a disconnect or a connect, the idea is to determine if there is a new left or right node, if there is and here is a pre-existing transfer, we must interupt it, and start a new transfer.</summary> <remarks>The possible scenarios where this would be active: - no change on left - new left node with no previous node (from disc or new node) - left disconnect and new left ready - left disconnect and no one ready - no change on right - new right node with no previous node (from disc or new node) - right disconnect and new right ready - right disconnect and no one ready </remarks> <param name="o">Unimportant</param> <param name="eargs">Contains the ConnectionEventArgs, which lets us know if this was a Structured Connection change and if it is, we should check the state of the system to see if we have a new left or right neighbor. </param> */ protected void ConnectionHandler(object o, EventArgs eargs) { if(!_online) { return; } ConnectionEventArgs cargs = eargs as ConnectionEventArgs; Connection old_con = cargs.Connection; //first make sure that it is a new StructuredConnection if (old_con.MainType != ConnectionType.Structured) { return; } lock(_transfer_sync) { if(!_online) { return; } ConnectionTable tab = _node.ConnectionTable; Connection lc = null, rc = null; try { lc = tab.GetLeftStructuredNeighborOf((AHAddress) _node.Address); } catch(Exception) {} try { rc = tab.GetRightStructuredNeighborOf((AHAddress) _node.Address); } catch(Exception) {} if(lc != null) { if(lc.Address != _left_addr) { if(_left_transfer_state != null) { _left_transfer_state.Interrupt(); _left_transfer_state = null; } _left_addr = lc.Address; if(Count > 0) { _left_transfer_state = new TransferState(lc, this); } } } else if(_left_addr != null) { if(_left_transfer_state != null) { _left_transfer_state.Interrupt(); _left_transfer_state = null; } _left_addr = null; } if(rc != null) { if(rc.Address != _right_addr) { if(_right_transfer_state != null) { _right_transfer_state.Interrupt(); _right_transfer_state = null; } _right_addr = rc.Address; if(Count > 0) { _right_transfer_state = new TransferState(rc, this); } } } else if(_right_addr != null) { if(_right_transfer_state != null) { _right_transfer_state.Interrupt(); _right_transfer_state = null; } _right_addr = null; } } }
private static void ReadHeader(Stream input, out int ver, out TransferState state, out Guid txid, out Salt salt) { ver = PrimitiveSerializer.Int32.ReadFrom(input); Check.Assert<InvalidDataException>(ver == VersionHeader); int istate = PrimitiveSerializer.Int32.ReadFrom(input); Check.Assert<InvalidDataException>(Enum.IsDefined(typeof(TransferState), istate)); state = (TransferState)istate; byte[] bytes = new byte[16]; Check.Assert<InvalidDataException>(bytes.Length == input.Read(bytes, 0, bytes.Length)); txid = new Guid(bytes); bytes = new byte[32]; Check.Assert<InvalidDataException>(bytes.Length == input.Read(bytes, 0, bytes.Length)); salt = Salt.FromBytes(bytes); }
protected static TaskState ToTaskState(TransferState transferState) { switch (transferState) { case TransferState.NotStarted: return TaskState.NotStarted; case TransferState.Preparing: case TransferState.Comparing: case TransferState.Transferring: case TransferState.Copying: case TransferState.Tidying: return TaskState.Running; case TransferState.Finished: return TaskState.Finished; case TransferState.Stopped: return TaskState.Stopped; default: return TaskState.Unknown; } }
public FileTransferServiceEventArgs(TransferState lastTransferState, TransferState currentTransferState) { this.LastTransferState = lastTransferState; this.CurrentTransferState = currentTransferState; }
public static void FillData(ApplicationContext context, UserManager <User> _userManager) { if (!context.TypeOfDocuments.Any()) { TypeOfDocument pasport = new TypeOfDocument { Name = "Паспорт" }; TypeOfDocument pasport1 = new TypeOfDocument { Name = "ВоенныйБилет" }; TypeOfDocument pasport2 = new TypeOfDocument { Name = "СвидетельствоОрождении" }; context.TypeOfDocuments.AddRange(pasport, pasport1, pasport2); context.SaveChanges(); } if (!context.Countries.Any()) { Country country = new Country { CountryName = "Кыргызстан" }; Country country1 = new Country { CountryName = "Таджикистан" }; Country country2 = new Country { CountryName = "Казахстан" }; context.Countries.AddRange(country, country1, country2); context.SaveChanges(); } if (!context.LegalForms.Any()) { LegalForm legalForm = new LegalForm { LegalFormName = "ОсОО" }; LegalForm legalForm1 = new LegalForm { LegalFormName = "ОАО" }; LegalForm legalForm2 = new LegalForm { LegalFormName = "ЗАО" }; context.LegalForms.AddRange(legalForm, legalForm1, legalForm2); context.SaveChanges(); } if (!context.PropertyTypes.Any()) { PropertyType propertyType = new PropertyType { PropertyTypeName = "Государственная" }; PropertyType propertyType1 = new PropertyType { PropertyTypeName = "Частная" }; PropertyType propertyType2 = new PropertyType { PropertyTypeName = "Смешанная" }; context.PropertyTypes.AddRange(propertyType, propertyType1, propertyType2); context.SaveChanges(); } if (!context.Residencies.Any()) { Residency residency = new Residency { ResidencyName = "Резидент" }; Residency residency1 = new Residency { ResidencyName = "НеРезидент" }; context.Residencies.AddRange(residency, residency1); context.SaveChanges(); } if (!context.TaxInspections.Any()) { TaxInspection taxInspection = new TaxInspection { TaxInspectionName = "Ленинский" }; TaxInspection taxInspection1 = new TaxInspection { TaxInspectionName = "Свердловский" }; TaxInspection taxInspection2 = new TaxInspection { TaxInspectionName = "Октябрьский" }; context.TaxInspections.AddRange(taxInspection, taxInspection1, taxInspection2); context.SaveChanges(); } if (!context.TransactionTypes.Any()) { List <TransactionType> transactions = new List <TransactionType>(); transactions.Add(TransactionType.Create(TransactionTypesEnum.Debit)); transactions.Add(TransactionType.Create(TransactionTypesEnum.Credit)); context.TransactionTypes.AddRange(transactions); context.SaveChanges(); } if (!context.ExchangeRateTypes.Any()) { ExchangeRateType exchangeRateType = ExchangeRateType.Create(ExchangeRateTypesEnum.NBKR); ExchangeRateType exchangeRateType1 = ExchangeRateType.Create(ExchangeRateTypesEnum.Market); context.ExchangeRateTypes.AddRange(exchangeRateType, exchangeRateType1); context.SaveChanges(); } if (!context.TransferStates.Any()) { context.AddRange( TransferState.Create(TransferStatesEnum.Confirmed), TransferState.Create(TransferStatesEnum.NotConfirmed), TransferState.Create(TransferStatesEnum.Canceled), TransferState.Create(TransferStatesEnum.BalanceNotEnough), TransferState.Create(TransferStatesEnum.AccountIsLocked)); context.SaveChanges(); } if (!context.TypeOfTransfers.Any()) { context.AddRange( TypeOfTransfer.Create(TypeOfTransfersEnum.InnerTransfer), TypeOfTransfer.Create(TypeOfTransfersEnum.InterBankTransfer), TypeOfTransfer.Create(TypeOfTransfersEnum.Conversion)); context.SaveChanges(); } if (!context.Currencies.Any()) { context.Currencies.Add ( new Currency { Code = "123", Name = "SOM", IsNativeCurrency = true } ); context.SaveChanges(); } if (!context.OurBank.Any()) { Currency currency = context.Currencies.FirstOrDefault(n => n.IsNativeCurrency == true); Account bankAccount = new Account { Locked = false, CurrencyId = currency.Id, Number = "1234567890123456" }; context.Accounts.Add(bankAccount); context.SaveChanges(); BankInfo bank = new BankInfo { BankName = "OurBank", Email = "*****@*****.**" }; context.BankInfos.Add(bank); OurBank ourBank = new OurBank { BIK = "123", AccountId = bankAccount.Id, BankInfoId = bank.Id }; context.OurBank.Add(ourBank); context.SaveChanges(); } if (!context.IntervalTypes.Any()) { List <IntervalType> intervalTypes = new List <IntervalType>(); intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceADay)); intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceAWeek)); intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceInTwoWeeks)); intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceAMonth)); intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceAQuarter)); intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceAHalfYear)); intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceAYear)); context.IntervalTypes.AddRange(intervalTypes); context.SaveChanges(); } if (!context.Roles.Any()) { context.Roles.AddRange ( new IdentityRole { Name = "admin", NormalizedName = "ADMIN" }, new IdentityRole { Name = "user", NormalizedName = "USER" } ); context.SaveChanges(); } if (context.Users.FirstOrDefault(u => u.UserName == "Admin") == null) { var result = _userManager.CreateAsync(new User { UserName = "******", Email = "*****@*****.**", IsTwoFactorOn = false, IsPasswordChanged = true, }, "Admin123@"); if (result.Result.Succeeded) { User user = context.Users.FirstOrDefault(u => u.UserName == "Admin"); IdentityRole role = context.Roles.FirstOrDefault(r => r.Name == "Admin"); context.UserRoles.Add(new IdentityUserRole <string> { RoleId = role.Id, UserId = user.Id }); context.SaveChanges(); } } if (!context.AddressTypes.Any()) { List <AddressType> addressTypes = new List <AddressType> { AddressType.Create(AddressTypesEnum.FactAddress), AddressType.Create(AddressTypesEnum.LegalAddress), AddressType.Create(AddressTypesEnum.BirthAddress) }; context.AddRange(addressTypes); context.SaveChanges(); //List<Address> adresses = context.Addresses.ToList(); //AddressType factaddress = // context.AddressTypes.FirstOrDefault(a => a.TypeName == AddressTypesEnum.FactAddress.ToString()); //AddressType legaladdress = // context.AddressTypes.FirstOrDefault(a => a.TypeName == AddressTypesEnum.LegalAddress.ToString()); //AddressType birthaddress = // context.AddressTypes.FirstOrDefault(a => a.TypeName == AddressTypesEnum.BirthAddress.ToString()); //foreach (Address address in adresses) //{ // switch (address.TypeOfAddress) // { // case "factaddress": address.AddressType = factaddress; // break; // case "legaladdress": address.AddressType = legaladdress; // break; // case "birthaddress": address.AddressType = birthaddress; // break; // } //} //context.UpdateRange(adresses); //context.SaveChanges(); } }
/// <summary> /// The handler for progress information /// </summary> /// <param name="progress">The progress object</param> private void ProgressHandler([NotNull]TransferProgress progress) { this.Information = progress.ProgressInfo; this.ProgressPercentage = progress.Percentage; if (progress.State != this.transferState) { // Force the command manager to re-query the commands. // This way the command button can see that progress state goes to "Done" and will be re-enabled. CommandManager.InvalidateRequerySuggested(); } this.transferState = progress.State; }
/* * this function is a callback function that called from WriteTimer each Interval ms * comment: sends data from buffer sendQueu */ public static void updateSender(Object sender, EventArgs e) { bool status; /* * fsm state send */ if (transferFsm == TransferState.send && System.IO.File.Exists(Util.covertChannel.useShareFile.SendAckFile)) { try { System.IO.File.Delete(Util.covertChannel.useShareFile.SendAckFile); Util.covertChannel.Statistics.UpdateLog(Statistics.LogSource.Sender, Statistics.LogInstanceType.SendAckMutex, Statistics.LogValue.Down, "Changing SendAck mutex down"); } catch { Util.covertChannel.Statistics.UpdateLog(Statistics.LogSource.Sender, Statistics.LogInstanceType.Error, Statistics.LogValue.Empty, "Error: can't Change SendAck mutex down"); //??????????? return; } /*next fsm state is idle*/ transferFsm = TransferState.idle; } /*fsm is idle and there is data to send*/ if (transferFsm == TransferState.idle && sendQueu.Count != 0 && System.IO.File.Exists(Util.covertChannel.useShareFile.SendFile) == false && System.IO.File.Exists(Util.covertChannel.useShareFile.SendAckFile) == false) { //try to send int bit = sendQueu.Peek(); if (bit == 0) { status = FileCreate(Util.covertChannel.useShareFile.Bit0File); if (status == false) { transferFsm = TransferState.idle; Util.covertChannel.Statistics.UpdateLog(Statistics.LogSource.Sender, Statistics.LogInstanceType.Error, Statistics.LogValue.Empty, "Collition Detect in bit0"); //colision detect enumerate bits return; } Util.covertChannel.Statistics.UpdateLog(Statistics.LogSource.Sender, Statistics.LogInstanceType.Transmition, Statistics.LogValue.Bit0, "Sending bit 0"); } else if (bit == 1) { status = FileCreate(Util.covertChannel.useShareFile.Bit1File); if (status == false) { transferFsm = TransferState.idle; Util.covertChannel.Statistics.UpdateLog(Statistics.LogSource.Sender, Statistics.LogInstanceType.Error, Statistics.LogValue.Empty, "Collition Detect in bit1"); //colision detect enumerate bits return; } Util.covertChannel.Statistics.UpdateLog(Statistics.LogSource.Sender, Statistics.LogInstanceType.Transmition, Statistics.LogValue.Bit1, "Sending bit 1"); } else //ignore bit { sendQueu.Dequeue(); return; } status = FileCreate(Util.covertChannel.useShareFile.SendFile); if (status == false) { //colision detect enumerate bits transferFsm = TransferState.idle; Util.covertChannel.Statistics.UpdateLog(Statistics.LogSource.Sender, Statistics.LogInstanceType.Error, Statistics.LogValue.Empty, "Collition Detect in send"); if (bit == 0) { System.IO.File.Delete(Util.covertChannel.useShareFile.Bit0File); } else { System.IO.File.Delete(Util.covertChannel.useShareFile.Bit1File); } return; } sendQueu.Dequeue(); Util.covertChannel.Statistics.UpdateLog(Statistics.LogSource.Sender, Statistics.LogInstanceType.SendMutex, Statistics.LogValue.Up, "Changing send Mutex to up"); Util.covertChannel.Statistics.bitSentCount++; if (bit == 0) { Util.covertChannel.Statistics.zeroBitSendCount++; } /*next state is send*/ transferFsm = TransferState.send; } }
/// <summary> /// 结束发送 /// </summary> /// <param name="transferState"></param> internal void CompletSend(TransferState transferState) { this.Children.Remove(bar); TextBlock txt = new TextBlock(); if (transferState == TransferState.Running) txt.Text = "已发送文件"; else if (transferState == TransferState.CanceledByMyself) txt.Text = "已取消发送"; else if (transferState == TransferState.CanceledByTheOther) txt.Text = "对方已取消接收"; else if (transferState == TransferState.RefusedByTheOther) txt.Text = "对方拒绝接收"; //else if(transferState==TransferState) Grid.SetRow(txt, 1); Grid.SetColumn(txt, 1); this.Children.Add(txt); this.cancleBtn.Text = "移除"; }
protected void SetTransferState(TransferState state, string message = "") { _currentTransferMessage = message; _currentTransferState = state; RunPercentUpdate(); }