public void Update(GameTime gametime, ITransferable remoteData) { var data = (PlayerTransferableData) remoteData; Console.WriteLine(data.Position); UpdatePosition(data); UpdateAngle(data); }
public void Update(GameTime gameTime, ITransferable remoteData) { var data = (ProjectileTransferableData) remoteData; //if (!IsInScreen) //{ // IsValid = false; //} Position = data.Position; }
public Trade(int id, DateTime tradeTime, ICounterparty counterparty, ITransferable itemTraded, int quantityTraded, double itemPrice, TradeState state) { Id = id; TradeTime = tradeTime; Counterparty = counterparty; ItemTraded = itemTraded; QuantityTraded = quantityTraded; ItemPrice = itemPrice; State = state; }
public static IOrder BuildSellOrder( string orderRef, DateTime createdTime, ICounterparty createdBy, ITransferable item, int unitCount, Money unitPrice) { IOrder order = new Order(orderRef, createdTime, createdBy, OrderDirection.Sell, OrderType.LimitOrder, TimeInForce.GoodTillCancelled, item, unitCount, unitPrice); return order; }
public override BaseReference TransferTo(BaseReference reference) { IStorable storable = reference.InternalValue(); BaseReference baseReference = base.AllocateAndPin(storable, ItemSizes.SizeOf(storable)); ITransferable transferable = storable as ITransferable; if (transferable != null) { transferable.TransferTo(this); } baseReference.UnPinValue(); reference.ScalabilityCache.Free(reference); return(baseReference); }
public static byte[] Serialize(ITransferable transferable) { var json = JsonConvert.SerializeObject(transferable, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }); var data = Encoding.UTF8.GetBytes(json); var output = new MemoryStream(); using (var deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(data, 0, data.Length); } return(output.ToArray()); }
public void Transfer(ITransferable target) { if (Type() == target.Type()) { int excess = target.Add(ammo); Debug.Log("Excess: " + excess); if (excess <= 0) { Destroy(gameObject); Debug.Log("Excess <= 0, destroying"); } else { ammo = excess; } } }
public void Transfer(ITransferable receiver, decimal transferAmount) { Console.WriteLine("Transaction: account " + _accountNumber + " sending " + transferAmount + " to account " + receiver.GetAccountNumber()); Console.WriteLine("Account " + _accountNumber + " balance: " + _moneyAmount); Console.WriteLine("Account " + receiver.GetAccountNumber() + " balance: " + receiver.GetBalance()); if (transferAmount < _moneyAmount) { _moneyAmount -= transferAmount; receiver.AddMoney(transferAmount); Console.WriteLine("Account " + _accountNumber + " balance: " + _moneyAmount); Console.WriteLine("Account " + receiver.GetAccountNumber() + " balance: " + receiver.GetBalance()); Console.WriteLine("Transaction successful\n"); } else { CommandQueue commands = CommandQueue.GetInstance(); commands.AddCommand(new TransferCommand(receiver.GetAccount(), this, transferAmount)); Console.WriteLine("Transaction unsuccessful\n"); } }
public bool Send(long clientId, ITransferable packet) { TCPClientEx tcpClient = GetConnectedClient(clientId); if (tcpClient == null) { OutLogMessage(string.Format("SRV DATA SEND ERROR, client ID is invalid: {0}", clientId)); return false; } return Send(tcpClient, packet); }
public static void Write(this NetOutgoingMessage message, ITransferable data) { data.WriteToMessage(message); }
/// <summary> /// Receives data and puts it into the /// <see cref="ReceiveBuffer"/>. /// </summary> /// <param name="data">Received data.</param> /// <returns>True if the data was successfully received, /// false if not.</returns> public abstract bool Receive(ITransferable data);
/// <summary> /// This method queues an ITransferable item as first /// in the internal queue of the TransferManager. /// </summary> /// <param name="Item">An ITransferable item to be added to the queue.</param> private void QueueFirst(ITransferable Item) { lock (_InternalQueue) { _InternalQueue.AddFirst(Item); Item.TransferStatus = ExtendedTransferStatus.Queued; } }
/// <summary> /// Handler for the OnStatusChange event of a ITransferable object associated with a Page. /// </summary> /// <param name="Previous">The transfer status that the ITransferable object had before changing.</param> /// <param name="Current">The transfer status that the ITransferable object currently has.</param> public void StatusChangeHandler(ExtendedTransferStatus Previous, ExtendedTransferStatus Current, ITransferable Item) { Library.Page Page = FindByUID(Item.ExternalReference); if (Page != null) { // Then add the item to the related collection based on its current status switch (Current) { case ExtendedTransferStatus.Queued: case ExtendedTransferStatus.Transferring: case ExtendedTransferStatus.Waiting: case ExtendedTransferStatus.WaitingForRetry: case ExtendedTransferStatus.WaitingForWiFi: case ExtendedTransferStatus.WaitingForExternalPower: case ExtendedTransferStatus.WaitingForExternalPowerDueToBatterySaverMode: case ExtendedTransferStatus.WaitingForNonVoiceBlockingNetwork: case ExtendedTransferStatus.Paused: case ExtendedTransferStatus.Canceled: if (Previous == ExtendedTransferStatus.Completed) { _DownloadedPages.Remove(Page); _PendingPages.Add(Page); } else if (Previous == ExtendedTransferStatus.Failed || Previous == ExtendedTransferStatus.FailedServer) { _FailedPages.Remove(Page); _PendingPages.Add(Page); } break; case ExtendedTransferStatus.Completed: if (Previous == ExtendedTransferStatus.Failed || Previous == ExtendedTransferStatus.FailedServer) { _FailedPages.Remove(Page); _DownloadedPages.Add(Page); } else if (Previous != ExtendedTransferStatus.Completed) { _PendingPages.Remove(Page); _DownloadedPages.Add(Page); } break; case ExtendedTransferStatus.Failed: case ExtendedTransferStatus.FailedServer: if (Previous == ExtendedTransferStatus.Completed) { _DownloadedPages.Remove(Page); _FailedPages.Add(Page); } else if (Previous != ExtendedTransferStatus.Failed && Previous != ExtendedTransferStatus.FailedServer) { _PendingPages.Remove(Page); _FailedPages.Add(Page); } break; } } }
static void TransferFunds(ITransferable account) { account.Transfer(); }
public void Send(int clientId, ITransferable[] packets) { int dataSize = 0, cnt = packets.Length; if (cnt == 1) { Send(clientId, packets[0].Serialize()); return; } //Serialize all packets to one byte[][] data = new byte[cnt][]; for (int i = 0; i < cnt; i++) { byte[] byteBuffer = packets[i].Serialize(); data[i] = byteBuffer; dataSize += byteBuffer.Length; } int idx = 0; byte[] dataToSend = new byte[dataSize]; for (int i = 0; i < cnt; i++) { byte[] array = data[i]; int length = array.Length; Buffer.BlockCopy(array, 0, dataToSend, idx, length); idx += length; } //Send data Send(clientId, dataToSend); }
public Order( string orderRef, DateTime createdTime, ICounterparty createdBy, OrderDirection orderDirection, OrderType type, TimeInForce timeInForce, ITransferable item, int unitCount, Money unitPrice) { OrderRef = orderRef; CreatedTime = createdTime; CreatedBy = createdBy; Direction = orderDirection; Type = type; TimeInForce = timeInForce; Item = item; Size = unitCount; Price = unitPrice; FilledSize = 0; Status = OrderStatus.Created; Trades = new List<Trade>(); }
public bool Take(ITransferable obj) { throw new NotImplementedException(); }
public void Update(GameTime gameTime, ITransferable remoteData) { var data = (HealthTransferableData)remoteData; Value = data.Value; }
public static void PostMessage(object message, ITransferable[] transfer) { }
public bool AssignActiveWeapon(Transform newWeapon) { WeaponPickupScript pickupScript = newWeapon.GetComponent <WeaponPickupScript>(); bool activeValid = false; // Search for empty, valid slot for new weapon. foreach (int slot in pickupScript.slots) { // If active slot is among valid slots, set activeValid to true if (activeSlot.GetSiblingIndex() == slot) { activeValid = true; } Transform parentSlot = weaponPos.GetChild(slot); // Check if weapon has transferable ammo ITransferable newTransferable = newWeapon.GetComponent <ITransferable>(); // Check if current valid slot is occupied if (parentSlot.childCount != 0) { // Skip if new weapon does not have transferable ammo if (newTransferable == null) { continue; } else { // Check if weapon in valid slot has transferable ammo ITransferable parentTransferable = parentSlot.GetChild(0).GetComponent <ITransferable>(); // Check if weapon in valid slot has same type of transferable ammo if (parentTransferable == null) { continue; } if (newTransferable.Type() == parentTransferable.Type()) { // Transfer ammo to weapon in valid slot newTransferable.Transfer(parentTransferable); // FpsEvents.UpdateHeldWeapon.Invoke(); FpsEvents.FpsUpdateHud(); return(false); } else { // Different types of ammo, continue to next valid slot continue; } } } // Empty valid slot found! // Check if activeSlot has an active weapon if (activeSlot.childCount > 0) { // Deactivate active weapon activeSlot.GetChild(0).gameObject.SetActive(false); } // Assign new weapon to empty slot pickupScript.transform.SetParent(parentSlot, false); // Update activeSlot activeSlot = parentSlot; FpsEvents.FpsUpdateHud(); // Add this slot to the Q UpdateQ(slot + 1); return(true); } // If all valid slots for new weapon are filled, proceed below. // Check if activeSlot is valid slot. if (!activeValid) { // activeSlot is not a valid slot. // Deactivate active weapon activeSlot.GetChild(0).gameObject.SetActive(false); // Reassign activeSlot to first valid slot for new weapon activeSlot = weaponPos.GetChild(pickupScript.slots[0]); UpdateQ(pickupScript.slots[0] + 1); } GameObject weaponToDrop = activeSlot.GetChild(0).gameObject; // Activate activeSlot weapon. Redundant if activeSlot is a valid slot (activeValid = true) weaponToDrop.SetActive(true); weaponToDrop.GetComponent <WeaponPickupScript>().Drop(dropOffPos); // Assign new weapon to vacated activeSlot pickupScript.transform.SetParent(activeSlot, false); // FpsEvents.UpdateHeldWeapon.Invoke(); FpsEvents.FpsUpdateHud(); return(true); }
/// <summary> /// Sends the given <paramref name="data"/> /// to the <see cref="Port.ReceiveBuffer"/> /// of the <see cref="Port.ConnectedPort"/>. /// </summary> /// <param name="data">Data to send.</param> /// <returns>True if the data was successfully sent, /// false if not.</returns> public abstract bool Send(ITransferable data);
public bool Send(TCPClientEx tcpClient, ITransferable packet, object userData = null) { if (!tcpClient.Connected) { return false; } try { //Send data byte[] byteBuffer = packet.Serialize(); int dataLength = byteBuffer.Length; ((TcpClient) tcpClient).GetStream().Write(byteBuffer, 0, dataLength); //Fire DataSent event if (ClientDataSent != null) { ClientDataSent(tcpClient, packet, userData); } return true; } catch (Exception ex) { if (ClientDataSendError != null) { ClientDataSendError(tcpClient, packet, userData, ex); } } return false; }
public bool Send(ITransferable packet, object userData = null) { if (_connected == 0) { return false; } try { //Send data byte[] byteBuffer = packet.Serialize(); int dataLength = byteBuffer.Length; _networkStream.Write(byteBuffer, 0, dataLength); //Fire DataSent event if (DataSent != null) { DataSent(packet, userData); } return true; } catch (Exception ex) { if (DataSendError != null) { DataSendError(packet, userData, ex); } Disconnect(); } return false; }
public bool SendAll(ITransferable packet, object userData = null) { lock (_clientsData) { Parallel.ForEach(_connectedClients.Values, c => Send(c, packet, userData)); return true; } }
static void Main(string[] args) { try { // Create Bank Bank bank = new Bank("BankOfDotNet"); Customer customer; Account account; try { // create bank customers//////////////////////////////////////////////////////////////////////////////////////////// bank.AddCustomer("Jane", "Doe"); bank.AddCustomer("John", "Doe"); Console.WriteLine(bank.ToString()); } catch (CustomerLimitException cle) { Console.WriteLine($"Customer Limit Exception {cle.Message} "); Console.WriteLine($"Customer Count: {cle.NumOfCustomers}"); } try { // Create Customer Account//////////////////////////////////////////////////////////////////////////////////////////// customer = bank.GetCustomer("Jane", "Doe"); customer.AddAccount(new CheckingAccount(500.00, 500.00)); customer.AddAccount(new SavingsAccount(1500.00, 0.01)); customer = bank.GetCustomer("John", "Doe"); customer.AddAccount( bank.GetCustomer("Jane", "Doe") .GetAccounts().Where(a => a.GetType() == typeof(CheckingAccount)).First()); } catch (AccountLimitException ale) { Console.WriteLine($"Customer Limit Exception {ale.Message} "); Console.WriteLine($"Customer Count: {ale.NumOfAccounts}"); } bank.GenerateReport(); // Jane's Transactions Console.WriteLine(); Console.WriteLine("Getting Jane Doe's Checking Account having Overdraft Protection"); customer = bank.GetCustomer("Jane", "Doe"); account = customer.GetAccounts() .Where(a => a.GetType() == typeof(CheckingAccount)).First(); try { account.Withdraw(155.00); account.Deposit(23.50); account.Withdraw(48.75); account.Withdraw(450.00); } catch (OverdraftException odex) { Console.WriteLine($"Overdraft Exception: {odex.Message}"); Console.WriteLine($"Overdraft Deficit: {odex.DeficitAmount}"); } // John'sJs Transactions Console.WriteLine(); Console.WriteLine("Getting John Doe's Checking Account having Overdraft Protection"); customer = bank.GetCustomer("John", "Doe"); account = customer.GetAccounts() .Where(a => a.GetType() == typeof(CheckingAccount)).First(); try { account.Deposit(155.00); account.Withdraw(755.00); } catch (OverdraftException odex) { Console.WriteLine($"Overdraft Exception: {odex.Message}"); Console.WriteLine($"Overdraft Deficit: {odex.DeficitAmount}"); } finally { Console.WriteLine($"Customer { customer.LastName}, {customer.FirstName} account details"); account.Display(); } // Jane's Transactions Console.WriteLine(); Console.WriteLine("Getting Jane Doe's First Transferable Account"); customer = bank.GetCustomer("Jane", "Doe"); ITransferable transferrableAccount = customer.GetFirstTransferableAccount(); try { transferrableAccount.Transfer(account, 1000.00); } catch (OverdraftException odex) { Console.WriteLine($"Overdraft Exception: {odex.Message}"); Console.WriteLine($"Overdraft Deficit: {odex.DeficitAmount}"); } finally { Console.WriteLine($"Customer { customer.LastName}, {customer.FirstName} account details"); account.Display(); } } catch (Exception ex) { Console.WriteLine($"Bank Exception: {ex.Message}"); } }
protected virtual SocketSession Find(ITransferable info) { return(Server.Sessions .Where(x => x.Id == info.DestUserId) .FirstOrDefault()); }
/// <summary> /// This method queues an ITransferable item as last /// in the internal queue of the TransferManager. /// </summary> /// <param name="Item">An ITransferable item to be added to the queue.</param> private void Queue(ITransferable Item) { // We reset the transfer progress Item.ResetTransferProgress(); lock (_InternalQueue) { _InternalQueue.AddLast(Item); Item.TransferStatus = ExtendedTransferStatus.Queued; } // We process the internal queue to add all transfers that are pending, based on // available slots in the BackgroundTransferService queue ProcessQueue(); }
/// <summary> /// This method removes an Itransferable item from the TransferManager /// internal queue or from the BackgroundTransferService queue. /// </summary> /// <param name="Item">The ITransferable item to cancel.</param> public void Cancel(ITransferable Item) { // If the transfer is currently queued then we need to just remove // it from the internal queue. if (Item.TransferStatus == ExtendedTransferStatus.Queued) { lock (_InternalQueue) { _InternalQueue.Remove(Item); } // Now we should set the TransferStatus accordingly Item.TransferStatus = ExtendedTransferStatus.Canceled; } // Else, if the transfer is currently inside the BackgroundTransferService // queue, then we need to request its removal from there. else if (Item.TransferStatus != ExtendedTransferStatus.Queued && Item.TransferStatus != ExtendedTransferStatus.Canceled && Item.TransferStatus != ExtendedTransferStatus.Completed && Item.TransferStatus != ExtendedTransferStatus.Failed && Item.TransferStatus != ExtendedTransferStatus.FailedServer && Item.TransferStatus != ExtendedTransferStatus.None) { RemoveTransferRequest(Item.RequestId); // This will set TransferStatus accordingly } }
/// <summary> /// This method creates a BackgroundTransferRequest object based on the information /// of the ITransferable object passed as a parameter. The BackgroundTransferRequest /// is then addedd to the BackgroundTransferService queue. /// </summary> /// <param name="Item">The ITransferable item.</param> /// <returns>True, if the BackgroundTransferRequest has been created and added successfully to the BackgroundTransferService.</returns> private bool AddTransferRequest(ITransferable Item) { // A new BackgroundTransferRequest is created by passing the TransferUri of the ITransferable object. BackgroundTransferRequest TransferRequest = new BackgroundTransferRequest(Item.TransferUri); // Set the transfer properties according to the TransferSettings of the ITransferable object #region Set transfer properties TransferRequest.Method = Item.Method; // GET or POST if (TransferRequest.Method == "GET") { // The temporary transfer location for download TransferRequest.DownloadLocation = Item.TransferLocationUri; } else {// The temporary transfer location for upload TransferRequest.UploadLocation = Item.TransferLocationUri; } TransferRequest.Tag = Item.UID.ToString(); // The TransferId //TransferRequest.Headers.Add(Item.Headers); // Additional headers TransferRequest.TransferPreferences = TransferSettings.I.TransferPreferences; // Transfer preferences such as None, AllowCellular, AllowBattery, AllowCellularAndBattery. #endregion // We register the event handlers for the progress change TransferRequest.TransferProgressChanged += Item.TransferProgressChanged; // The BackgroundTransferRequest is ready to be addedd to the BackgroundTransferService queue. // Before adding, we call the ITransferable BeforeAdding() method to perform additional // operations (e.g. placing the file in the right folder). Item.OnBeforeAdd(); // Now the BackgroundTrabsferRequest is ready to be added to the BackgroundTransferService queue // A try/catch block is necessary to handle the possible exceptions TransferRequest.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(TransferRequest_TransferStatusChanged); // Transfer manager handler for status change try { BackgroundTransferService.Add(TransferRequest); // If add was successful we can retrieve the RequestId value and store it in the ITransferable object // The RequestId is generated right after the instantiation of the BackgroundTransferRequest, but to // avoid overwriting a previous value on the ITransferable object, we store it only after "Add" is // successful (which means that the same object is not currently transferring). Item.RequestId = TransferRequest.RequestId; // The BackgroundTransferRequest was successfully added to the BackgroundTransferService queue. return true; } catch (BackgroundTransferInternalException ex) { //BackgroundTransferInternalException is thrown when: // - The total request limit across all applications has been reached. // - The HTTP network provider returned an error. // - The HTTP network provider returned an error related to content-range request or response. // - The HTTP network provider returned a network-related error. // - The HTTP network provider returned a slow transfer error. // - The isolated storage provider returned an error. // In debug mode show MessageBox with exception details. if (System.Diagnostics.Debugger.IsAttached) { MessageBox.Show("I'm unable to add the background transfer request (BackgroundTransferInternalException). " + ex.Message, "Unable to start transfer", MessageBoxButton.OK); } } catch (InvalidOperationException ex) { // InvalidOperationException is thrown when: // - The request has already been submitted. // - The maximum number of requests per application has been reached. // - A request with the same DownloadLocation URI has already been submitted. // - The user has disabled background tasks in the device’s Settings. // In debug mode show MessageBox with exception details. if (System.Diagnostics.Debugger.IsAttached) { MessageBox.Show("I'm unable to add the background transfer request (InvalidOperationException). " + ex.Message, "Unable to start transfer", MessageBoxButton.OK); } } catch (SystemException ex) { //SystemException is thrown when: // - The maximum number of requests on the device has been reached. // - The underlying transport layer returned an error. // - The underlying transport layer returned an error related to the content-range request or response. // In debug mode show MessageBox with exception details. if (System.Diagnostics.Debugger.IsAttached) { MessageBox.Show("I'm unable to add the background transfer request (SystemException). " + ex.Message, "Unable to start transfer", MessageBoxButton.OK); } } catch (Exception ex) { // In debug mode show MessageBox with exception details. if (System.Diagnostics.Debugger.IsAttached) { MessageBox.Show("I'm unable to add the background transfer request (Exception). " + ex.Message, "Unable to start transfer", MessageBoxButton.OK); } } return false; }
public void Send(int clientId, ITransferable packet) { //Serialize data byte[] dataToSend = packet.Serialize(); //Send data Send(clientId, dataToSend); }
/// <summary> /// This method queues an ITransferable item, adding it as last /// in the internal queue of the TransferManager. /// </summary> /// <param name="Item">An ITransferable item to be added to the queue.</param> public void Start(ITransferable Item) { Queue(Item); }
public TransferCommand(ITransferable giver, ITransferable receiver, decimal moneyGivenDecimal) { _transferReceiver = receiver; _transferGiver = giver; _moneyGiven = moneyGivenDecimal; }
/// <summary> /// This method queues an ITransferable item, adding it as first /// in the internal queue of the TransferManager. /// </summary> /// <param name="Item">An ITransferable item to be added to the queue.</param> public void StartAsFirst(ITransferable Item) { QueueFirst(Item); }
public void TransferEmployee(ITransferable employee) { employee.Transfer(); }
/// <summary> /// This method creates a BackgroundTransferRequest object based on the information /// of the ITransferable object passed as a parameter. The BackgroundTransferRequest /// is then addedd to the BackgroundTransferService queue. /// </summary> /// <param name="Item">The ITransferable item.</param> /// <returns>True, if the BackgroundTransferRequest has been created and added successfully to the BackgroundTransferService.</returns> private bool AddTransferRequest(ITransferable Item) { //TODO: Improve validation of Item.TransferUri and Item.TransferLocationUri -> If URI is not valid then the object will not be removable // First, validate the TransferURI Uri TransferUri; if (!Uri.TryCreate(Item.TransferUrl, UriKind.Absolute, out TransferUri) || String.IsNullOrEmpty(Item.TransferUrl) || String.IsNullOrWhiteSpace(Item.TransferUrl)) { #if DEBUG // In debug mode show MessageBox with exception details. MessageBox.Show("I'm unable to add the background transfer request due to a malformed remote URI (" + Item.TransferUrl + ").", "Unable to start transfer", MessageBoxButton.OK); #endif return false; } // Second, validate the TransferLocation Uri TransferLocation; if (!Uri.TryCreate(Item.FilenameWithPath, UriKind.Relative, out TransferLocation) || String.IsNullOrEmpty(Item.FilenameWithPath) || String.IsNullOrWhiteSpace(Item.FilenameWithPath)) { #if DEBUG // In debug mode show MessageBox with exception details. MessageBox.Show("I'm unable to add the background transfer request due to a malformed local URI (" + Item.TransferLocationUri + ").", "Unable to start transfer", MessageBoxButton.OK); #endif return false; } // A new BackgroundTransferRequest is created by passing the TransferUri of the ITransferable object. BackgroundTransferRequest TransferRequest = new BackgroundTransferRequest(Item.TransferUri); // Set the transfer properties according to the TransferSettings of the ITransferable object #region Set transfer properties try { TransferRequest.Method = Item.Method; // GET or POST if (TransferRequest.Method == "GET") { // The temporary transfer location for download TransferRequest.DownloadLocation = Item.TransferLocationUri; } else {// The temporary transfer location for upload TransferRequest.UploadLocation = Item.TransferLocationUri; } } catch (ArgumentException) { #if DEBUG // In debug mode show MessageBox with exception details. MessageBox.Show("I'm unable to add the background transfer request due to a malformed local URI (" + Item.TransferLocationUri + ").", "Unable to start transfer", MessageBoxButton.OK); #endif return false; } TransferRequest.Tag = Item.UID.ToString(); // The TransferId //TransferRequest.Headers.Add(Item.Headers); // Additional headers TransferRequest.TransferPreferences = TransferSettings.I.TransferPreferences; // Transfer preferences such as None, AllowCellular, AllowBattery, AllowCellularAndBattery. #endregion // We register the event handlers for the progress change TransferRequest.TransferProgressChanged += Item.TransferProgressChanged; // The BackgroundTransferRequest is ready to be addedd to the BackgroundTransferService queue. // Before adding, we call the ITransferable BeforeAdding() method to perform additional // operations (e.g. placing the file in the right folder). Item.OnBeforeAdd(); // Now the BackgroundTrabsferRequest is ready to be added to the BackgroundTransferService queue // A try/catch block is necessary to handle the possible exceptions TransferRequest.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(TransferRequest_TransferStatusChanged); // Transfer manager handler for status change try { BackgroundTransferService.Add(TransferRequest); // If add was successful we can retrieve the RequestId value and store it in the ITransferable object // The RequestId is generated right after the instantiation of the BackgroundTransferRequest, but to // avoid overwriting a previous value on the ITransferable object, we store it only after "Add" is // successful (which means that the same object is not currently transferring). Item.RequestId = TransferRequest.RequestId; lock (this) { // We increment the internal counter _ActiveBackgroundTransfers++; } var BackgroundTransfers = BackgroundTransferService.Requests; // The BackgroundTransferRequest was successfully added to the BackgroundTransferService queue. return true; } catch (BackgroundTransferInternalException ex) { //BackgroundTransferInternalException is thrown when: // - The total request limit across all applications has been reached. // - The HTTP network provider returned an error. // - The HTTP network provider returned an error related to content-range request or response. // - The HTTP network provider returned a network-related error. // - The HTTP network provider returned a slow transfer error. // - The isolated storage provider returned an error. #if DEBUG // In debug mode show MessageBox with exception details. MessageBox.Show("I'm unable to add the background transfer request (BackgroundTransferInternalException). " + ex.Message, "Unable to start transfer", MessageBoxButton.OK); #endif } catch (InvalidOperationException ex) { // InvalidOperationException is thrown when: // - The request has already been submitted. // - The maximum number of requests per application has been reached. // - A request with the same DownloadLocation URI has already been submitted. // - The user has disabled background tasks in the device’s Settings. #if DEBUG // In debug mode show MessageBox with exception details. MessageBox.Show("I'm unable to add the background transfer request (InvalidOperationException). " + ex.Message, "Unable to start transfer", MessageBoxButton.OK); #endif } catch (SystemException ex) { //SystemException is thrown when: // - The maximum number of requests on the device has been reached. // - The underlying transport layer returned an error. // - The underlying transport layer returned an error related to the content-range request or response. // - There is not enough space on the disk. if (ex.Message == "There is not enough space on the disk.") { MessageBox.Show("There is not enough space on the device to start the transfer. Please free up some space and then retry.", "Unable to start transfer", MessageBoxButton.OK); } #if DEBUG // In debug mode show MessageBox with exception details. MessageBox.Show("I'm unable to add the background transfer request (SystemException). " + ex.Message, "Unable to start transfer", MessageBoxButton.OK); #endif } catch (Exception ex) { #if DEBUG // In debug mode show MessageBox with exception details. MessageBox.Show("I'm unable to add the background transfer request (Exception). " + ex.Message, "Unable to start transfer", MessageBoxButton.OK); #endif } return false; }