Ejemplo n.º 1
0
        private async void btnEdit_Clicked(object sender, EventArgs e)
        {
            RegularDataItem selectedItem = (RegularDataItem)listViewRegularData.SelectedItem;
            RegularData     editItem     = selectedItem.DbRegDataItem;
            string          title        = string.Empty;

            if (editItem.CategoryType == Constants.EXPENSE_STRING)
            {
                title = Panda_Kakei.Resources.AppResource.EditRegularExpenseText;
            }
            else if (editItem.CategoryType == Constants.INCOME_STRING)
            {
                title = Panda_Kakei.Resources.AppResource.EditRegularIncomeText;
            }

            btnEdit.IsEnabled = false;

            string message = Constants.EDITED_REGULAR_DATA_ITEM_MESSAGE;
            Page   newPage = new RegularDataItemPage(title, true, editItem);

            MessagingCenter.Unsubscribe <RegularDataItemPage>(this, message);
            MessagingCenter.Subscribe <RegularDataItemPage>(this, message, (RegularDataItemPage) =>
            {
                loadRegularDataItemsFromDB();
                // Send message back to SettingsPage that will referesh calculations on MainPage
                MessagingCenter.Send <ViewRegularDataItemPage>(this, Constants.ADD_EDIT_REGULAR_DATA_ITEM_MESSAGE);

                MessagingCenter.Unsubscribe <RegularDataItemPage>(this, message);
            });

            await Navigation.PushAsync(newPage);

            btnEdit.IsEnabled = true;
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Does bulk Brunet DHT gets by calling the bulk DHT operation API of its
        /// XML-RPC interface.
        /// </summary>
        /// <returns>Null if not all the pieces are successfully retrieved and parsed.</returns>
        /// <exception cref="Exception">Parsing errors.</exception>
        private MemBlock GetFragsInBulk(byte[] base_key, int piece_num,
                                        out int largest_age, out int smallest_ttl)
        {
            largest_age  = 0;
            smallest_ttl = Int32.MaxValue;
            MemBlock fragments = new MemBlock();

            byte[][] keys = new byte[piece_num][];
            for (int i = 0; i < piece_num; i++)
            {
                byte[] piece_key = BuildFragmentKey(base_key, i);
                keys[i] = piece_key;
            }

            DhtGetResult[] dgrs = _dht.BulkGet(keys);
            for (int i = 0; i < dgrs.Length; i++)
            {
                DhtGetResult dgr = dgrs[i];
                if (dgr == null)
                {
                    Logger.WriteLineIf(LogLevel.Error, _log_props,
                                       string.Format("Piece #{0} is null. Retrying...", i));
                    dgr = GetWithRetries(keys[i], 2);
                    if (dgr == null)
                    {
                        Logger.WriteLineIf(LogLevel.Error, _log_props,
                                           string.Format("Piece #{0} is null after retries. Skipping " +
                                                         "further parsing and returning...", i));
                        return(null);
                    }
                }
                FingerprintedData fpd;
                try {
                    fpd =
                        (FingerprintedData)DictionaryData.CreateDictionaryData(dgr.value);
                } catch (Exception ex) {
                    Logger.WriteLineIf(LogLevel.Error, _log_props,
                                       ex);
                    throw ex;
                }
                Logger.WriteLineIf(LogLevel.Verbose, _log_props,
                                   string.Format("Piece #{0} retrieved and successfully parsed", i));
                RegularData rd = fpd.InnerData as RegularData;
                fragments = MemBlock.Concat(fragments, MemBlock.Reference(rd.PayLoad));
                if (smallest_ttl > dgr.ttl)
                {
                    smallest_ttl = dgr.ttl;
                }
                if (largest_age < dgr.age)
                {
                    largest_age = dgr.age;
                }
                //Now it's safe to say, this attempt succeeded.
            }

            return(fragments);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Gets the first data item of the given name and possibly gets the
        /// indicated pieces from DHT.
        /// </summary>
        /// <param name="getPieces">Whether to get pieces if the data at the
        /// specified DHT name is a FragmentationInfo</param>
        public DhtGetResult GetOneDatum(byte[] key, bool getPieces,
                                        OneDatumMode mode)
        {
            DhtGetResult[] results = _dht.Get(key);
            DhtGetResult   ret;

            if (results.Length == 0)
            {
                ret = null;
            }
            else
            {
                DhtGetResult dgr;
                if (mode == OneDatumMode.FirstOne)
                {
                    dgr = results[0];
                }
                else if (mode == OneDatumMode.LastOne)
                {
                    dgr = results[results.Length - 1];
                }
                else
                {
                    throw new NotImplementedException(
                              "This OneDatumMode not implemented.");
                }
                DictionaryData dd = null;
                try {
                    dd = DictionaryData.CreateDictionaryData(dgr.value);
                } catch (Exception ex) {
                    // Not an error in this case. Log with verbose level.
                    Logger.WriteLineIf(LogLevel.Verbose, _log_props,
                                       ex);
                }
                if (dd != null && dd is FragmentationInfo)
                {
                    FragmentationInfo frag_info = dd as FragmentationInfo;
                    BrunetDhtEntry    bde       = null;
                    try {
                        bde = GetFragments(frag_info) as BrunetDhtEntry;
                        RegularData rd = (RegularData)DictionaryData.CreateDictionaryData(
                            bde.Value);
                        //Only 1 entry (if any) in this array
                        ret = new DhtGetResult(rd.PayLoad, bde.Age, bde.Ttl);
                    } catch (Exception ex) {
                        Logger.WriteLineIf(LogLevel.Error, _log_props, string.Format("Can't get fragments."), ex);
                        ret = null;
                    }
                }
                else
                {
                    ret = dgr;
                }
            }
            return(ret);
        }
Ejemplo n.º 4
0
 public void AddRegularDataItem(RegularData regularData)
 {
     try
     {
         dbConnection.Insert(regularData);
     }
     catch (Exception e)
     {
         ErrorStatusMessage = string.Format("Failed to add regular data item. Error: {0}", e.Message);
     }
 }
Ejemplo n.º 5
0
 public void DeleteRegularDataItem(RegularData regularData)
 {
     try
     {
         dbConnection.Delete(regularData);
     }
     catch (Exception e)
     {
         ErrorStatusMessage = string.Format("Failed to delete regular data item. Error: {0}", e.Message);
     }
 }
Ejemplo n.º 6
0
 public void ModifyRegularDataItem(RegularData regularData)
 {
     try
     {
         dbConnection.Update(regularData);
     }
     catch (Exception e)
     {
         ErrorStatusMessage = string.Format("Failed to modify regular data item. Error: {0}", e.Message);
     }
 }
Ejemplo n.º 7
0
        private void btnAdd_Clicked(object sender, EventArgs e)
        {
            int amount = 0;

            try
            {
                amount = int.Parse(entryAmount.Text);
            }
            catch (FormatException)
            {
                DisplayAlert(Panda_Kakei.Resources.AppResource.InputErrorText,
                             Panda_Kakei.Resources.AppResource.ErrorAmountText, Panda_Kakei.Resources.AppResource.OkText);

                return;
            }

            RegularData regularDataItem;

            if (this.modifyItem)
            {
                regularDataItem = this.regularDataItem;
            }
            else
            {
                regularDataItem = new RegularData();
            }

            regularDataItem.Amount       = amount;
            regularDataItem.Comment      = entryMemo.Text;
            regularDataItem.Category     = pickerCategory.SelectedItem.ToString();
            regularDataItem.CategoryType = this.categoryType;
            regularDataItem.Day          = int.Parse(pickerDay.SelectedItem.ToString());

            if (this.modifyItem)
            {
                SharedObject.dbManager.ModifyRegularDataItem(regularDataItem);
                MessagingCenter.Send <RegularDataItemPage>(this, Constants.EDITED_REGULAR_DATA_ITEM_MESSAGE);
            }
            else
            {
                SharedObject.dbManager.AddRegularDataItem(regularDataItem);
                MessagingCenter.Send <RegularDataItemPage>(this, Constants.ADDED_REGULAR_DATA_ITEM_MESSAGE);
            }
            SharedObject.dbManager.Commit();

            this.Navigation.PopAsync();
        }
Ejemplo n.º 8
0
        public RegularDataItemPage(string title, bool modifyItem, RegularData editItem)
            : this(title)
        {
            this.modifyItem      = modifyItem;
            this.regularDataItem = editItem;
            btnAdd.Text          = Panda_Kakei.Resources.AppResource.SaveText;

            if (editItem.CategoryType == Constants.EXPENSE_STRING)
            {
                pickerCategoryType.SelectedIndex = 0;
            }
            else if (editItem.CategoryType == Constants.INCOME_STRING)
            {
                pickerCategoryType.SelectedIndex = 1;
            }

            loadFromExistingItem(editItem);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Load page with an existing item.
        /// </summary>
        /// <param name="regularDataItem"></param>
        private void loadFromExistingItem(RegularData regularDataItem)
        {
            entryAmount.Text = regularDataItem.Amount.ToString();
            entryMemo.Text   = regularDataItem.Comment;

            foreach (var item in pickerDay.Items)
            {
                int day = int.Parse(item);
                if (day == regularDataItem.Day)
                {
                    pickerDay.SelectedItem = day;
                    break;
                }
            }

            foreach (DataSettings category in this.categoryModel.Categories)
            {
                if (regularDataItem.Category == category.Name)
                {
                    pickerCategory.SelectedItem = category;
                    break;
                }
            }
        }
Ejemplo n.º 10
0
        /// <returns>The memblock assembled from pieces. Null if operation failed.</returns>
        private MemBlock GetFragsSequentially(byte[] base_key, int piece_num,
                                              out int largest_age, out int smallest_ttl)
        {
            largest_age  = 0;
            smallest_ttl = Int32.MaxValue;
            MemBlock fragments = new MemBlock();

            for (int i = 0; i < piece_num; i++)
            {
                byte[] piece_key = BuildFragmentKey(base_key, i);
                bool   succ      = false; //set to false iff bad things happen
                int    retries   = 3;     //After that we fail the operation
                for (; !succ && retries > 0; retries--)
                {
                    if (retries == 3)
                    {
                        Logger.WriteLineIf(LogLevel.Verbose, _log_props,
                                           string.Format("Getting: {0}", piece_key));
                    }
                    else
                    {
                        Logger.WriteLineIf(LogLevel.Verbose, _log_props,
                                           string.Format("Retrying..."));
                    }
                    try {
                        DhtGetResult[] dgrs = _dht.Get(piece_key);
                        //It should have only one entry. If not, just let the the exception caught
                        //and retry.
                        DhtGetResult      dgr = dgrs[0];
                        FingerprintedData fpd =
                            (FingerprintedData)DictionaryData.CreateDictionaryData(dgr.value);
                        Logger.WriteLineIf(LogLevel.Verbose, _log_props,
                                           string.Format("Piece {0} retrieved and successfully parsed", piece_key));
                        RegularData rd = fpd.InnerData as RegularData;
                        fragments = MemBlock.Concat(fragments, MemBlock.Reference(rd.PayLoad));
                        if (smallest_ttl > dgr.ttl)
                        {
                            smallest_ttl = dgr.ttl;
                        }
                        if (largest_age < dgr.age)
                        {
                            largest_age = dgr.age;
                        }
                        //Now it's safe to say, this attempt succeeded.
                        succ = true;
                    } catch (Exception ex) {
                        Logger.WriteLineIf(LogLevel.Error, _log_props,
                                           ex);
                        succ = false;
                    }
                } //if succ then we are good

                if (retries <= 0)
                {
                    //Quit because retries exhausted.
                    throw new Exception(string.Format("Retries exhausted when retrieving "
                                                      + "and deserializing piece : {0}", piece_key));
                }
                else
                {
                    Logger.WriteLineIf(LogLevel.Verbose, _log_props, string.Format(
                                           "Done with piece {0}",
                                           Encoding.UTF8.GetString(piece_key)));
                }
            }
            return(fragments);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Concurrenly gets the fragments from DHT.
        /// </summary>
        /// <returns>The fragments</returns>
        private MemBlock GetFragsConcurrently(byte[] baseKey, int pieceNum,
                                              out int largestAge, out int smallestTtl)
        {
            // First set the int values to be invalid.
            smallestTtl = Int32.MaxValue;
            largestAge  = 0;

            int                      max_enqueues = 1;
            BlockingQueue            bq_result    = new BlockingQueue(max_enqueues);
            AsyncGetFragsGlobalState global_state =
                new AsyncGetFragsGlobalState(pieceNum, baseKey, bq_result);
            int concurrency_degree = Concurrency;

            global_state.Concurrency = concurrency_degree;

            for (int i = 0; i < pieceNum; i++)
            {
                int    index            = i;
                byte[] piece_key        = BuildFragmentKey(baseKey, i);
                string piece_key_string = Encoding.UTF8.GetString(piece_key);
                // piece state
                AsyncOpState      aps  = new AsyncOpState(piece_key);
                AsyncFragsOpState afos = new AsyncFragsOpState(global_state, aps);
                // async get, one instance of IDht per get because thread safty not guaranteed
                IDht proxy = DhtServiceClient.GetXmlRpcDhtClient(_svc_uri.Port);
                BrunetDhtClientOperations brdht_ops = new BrunetDhtClientOperations(
                    proxy);
                lock (global_state.SyncRoot) {
                    brdht_ops.BeginGetWithCallback(piece_key,
                                                   new AsyncCallback(this.OnDhtGetReturns), afos);
                }
                Logger.WriteLineIf(LogLevel.Verbose, _log_props,
                                   string.Format("Get piece {0} from DHT began (asynchronously)",
                                                 piece_key_string));

                if ((concurrency_degree > 1 && (index + 1) % concurrency_degree == 0) ||
                    index == pieceNum - 1)
                {
                    // Stop to wait for batch finish or all finish
                    global_state.BatchFinishedEvent.WaitOne();
                    if (concurrency_degree > 1)
                    {
                        Logger.WriteLineIf(LogLevel.Verbose, _log_props,
                                           string.Format("Batch {0} finished. Moving on",
                                                         (int)((index + 1) / concurrency_degree)));
                    }
                }
            }

            //block here until result comes
            GetFragsStoppedEventArgs stop_args =
                (GetFragsStoppedEventArgs)bq_result.Dequeue();
            //All results have returned.
            MemBlock ret = new MemBlock();

            if (stop_args.IsSuccessful)
            {
                // We successfully got everything but aren't sure whether they are
                // correct. Now parse them.
                for (int i = 0; i < global_state.Fragments.Length; i++)
                {
                    try {
                        DhtGetResult      dgr = global_state.Fragments[i];
                        FingerprintedData fpd =
                            (FingerprintedData)DictionaryData.CreateDictionaryData(dgr.value);
                        RegularData rd = fpd.InnerData as RegularData;
                        // This piece is OK.
                        ret = MemBlock.Concat(ret, MemBlock.Reference(rd.PayLoad));
                        if (smallestTtl > dgr.ttl)
                        {
                            smallestTtl = dgr.ttl;
                        }
                        if (largestAge < dgr.age)
                        {
                            largestAge = dgr.age;
                        }
                        //Now it's safe to say, this attempt succeeded.
                    } catch (Exception) {
                        Logger.WriteLineIf(LogLevel.Error, _log_props,
                                           string.Format("Parsing Piece failed at index {0}", i));
                        throw;
                    }
                }
                return(ret);
            }
            return(null);
        }