Example #1
0
        private async void DeleteButton_OnClickedButton_OnClicked(object sender, EventArgs e)
        {
            var    ci             = CrossMultilingual.Current.CurrentCultureInfo;
            string confirmTitle   = resmgr.Value.GetString("DeleteWord", ci);
            string confirmMessage = resmgr.Value.GetString("DeleteWordMessage", ci) + " ? ";
            string yes            = resmgr.Value.GetString("Yes", ci);
            string no             = resmgr.Value.GetString("No", ci);
            bool   confirmDelete  = await DisplayAlert(confirmTitle, confirmMessage, yes, no);

            if (confirmDelete)
            {
                _viewModel.IsBusy   = true;
                _viewModel.EditMode = false;
                VocabularyItem deleteVocabularyItem = await ProgenyService.DeleteVocabularyItem(_viewModel.CurrentVocabularyItem);

                if (deleteVocabularyItem.WordId == 0)
                {
                    _viewModel.EditMode = false;
                    // Todo: Show success message
                }
                else
                {
                    _viewModel.EditMode = true;
                    // Todo: Show failed message
                }
                _viewModel.IsBusy = false;
            }
        }
Example #2
0
        //
        // GET: /Vocabulary/Details/5

        public ViewResult Details(int id)
        {
            var            query          = (from c in db.VocabularyItems where c.Id == id select c).Include("TranslateSuggestions");
            VocabularyItem vocabularyitem = query.FirstOrDefault();

            return(View(vocabularyitem));
        }
Example #3
0
        //
        // GET: /Vocabulary/Edit/5

        public ActionResult Edit(int id)
        {
            VocabularyItem vocabularyitem =
                db.VocabularyItems.Include(m => m.TranslateSuggestions).FirstOrDefault(x => x.Id == id);

            return(View(vocabularyitem));
        }
Example #4
0
        public void TestMethod1()
        {
            Database.SetInitializer(new DropCreateDatabaseAlways <LessonContext>());

            var            db    = new LessonContext();
            VocabularyItem vItem = new VocabularyItem
            {
                Word                 = "mouse",
                Translation          = "mysz",
                TranslateSuggestions = new List <TranslateSuggestion> {
                    new TranslateSuggestion {
                        Suggestion = "kon"
                    },
                    new TranslateSuggestion {
                        Suggestion = "pies"
                    },
                    new TranslateSuggestion {
                        Suggestion = "mysz"
                    }
                }
            };

            db.VocabularyItems.Add(vItem);
            db.SaveChanges();
        }
Example #5
0
        public ActionResult DeleteConfirmed(int id)
        {
            VocabularyItem vocabularyitem = db.VocabularyItems.Find(id);

            db.VocabularyItems.Remove(vocabularyitem);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Example #6
0
        /// <summary>
        /// Read cell and store it directly in typed list, to avoid boxing
        /// </summary>
        /// <param name="br">Binary reader</param>
        /// <param name="strings">Collection of string values from vocabulary</param>
        /// <param name="decimals">Collection of decimal values from vocabulary</param>
        /// <returns>Vocabulary item with cell type and value index in typed array</returns>
        /// <exception cref="Exception">Unknown symbol type</exception>
        private static VocabularyItem ReadVocabularyItem(BinaryReader br, List <string> strings, List <decimal> decimals)
        {
            SymbolType type = (SymbolType)br.ReadByte();

            VocabularyItem result;

            switch (type)
            {
            case SymbolType.Nothing:
                result = new VocabularyItem(CellType.Nothing, 0);
                break;

            case SymbolType.Int8:
                result = new VocabularyItem(CellType.Number, decimals.Count);
                decimals.Add(br.ReadSByte());
                break;

            case SymbolType.Int16:
                result = new VocabularyItem(CellType.Number, decimals.Count);
                decimals.Add(br.ReadInt16());
                break;

            case SymbolType.Int32:
                result = new VocabularyItem(CellType.Number, decimals.Count);
                decimals.Add(br.ReadInt32());
                break;

            case SymbolType.Decimal:
                result = new VocabularyItem(CellType.Number, decimals.Count);
                decimals.Add(br.ReadDecimal());
                break;

            case SymbolType.Text:
                result = new VocabularyItem(CellType.Text, strings.Count);
                strings.Add(br.ReadString());
                break;

            case SymbolType.BoolTrue:
                result = new VocabularyItem(CellType.Boolean, 1);
                break;

            case SymbolType.BoolFalse:
                result = new VocabularyItem(CellType.Boolean, 0);
                break;

            case SymbolType.Error:
                br.ReadInt32();         //Error code. Not used as of now. Reserved for future versions.

                result = new VocabularyItem(CellType.Error, strings.Count);
                strings.Add(br.ReadString());
                break;

            default:
                throw new Exception($"Unknown symbol type: {type}");
            }

            return(result);
        }
Example #7
0
        /// <summary>
        /// Constructs a CodableValue based on display value and
        /// a <see cref="VocabularyItem"/>.
        /// </summary>
        ///
        /// <param name="text">
        /// The text value of the codable value.
        /// </param>
        ///
        /// <param name="item">
        /// The <see cref="VocabularyItem"/>.
        /// </param>
        ///
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="text"/> parameter is <b>null</b>.
        /// </exception>
        ///
        public CodableValue(string text, VocabularyItem item)
        {
            Text = text;

            if (item != null)
            {
                Add(item);
            }
        }
Example #8
0
        //
        // GET: /Vocabulary/Create

        public ActionResult Create()
        {
            VocabularyItem model = new VocabularyItem();

            model.TranslateSuggestions = new List <TranslateSuggestion>();
            model.TranslateSuggestions.Add(new TranslateSuggestion());
            model.TranslateSuggestions.Add(new TranslateSuggestion());
            model.TranslateSuggestions.Add(new TranslateSuggestion());
            return(View(model));
        }
Example #9
0
        public ActionResult Create(VocabularyItem vocabularyitem)
        {
            if (ModelState.IsValid)
            {
                db.VocabularyItems.Add(vocabularyitem);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(vocabularyitem));
        }
Example #10
0
 public ActionResult Edit(VocabularyItem vocabularyitem)
 {
     if (ModelState.IsValid)
     {
         db.Entry(vocabularyitem).State = EntityState.Modified;
         //db.Entry(vocabularyitem.TranslateSuggestions).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(vocabularyitem));
 }
        public async Task <IActionResult> Delete(int id)
        {
            VocabularyItem vocabularyItem = await _context.VocabularyDb.SingleOrDefaultAsync(w => w.WordId == id);

            if (vocabularyItem != null)
            {
                // Check if child exists.
                Progeny prog = await _context.ProgenyDb.AsNoTracking().SingleOrDefaultAsync(p => p.Id == vocabularyItem.ProgenyId);

                string userEmail = User.GetEmail() ?? Constants.DefaultUserEmail;
                if (prog != null)
                {
                    // Check if user is allowed to delete words for this child.
                    if (!prog.IsInAdminList(userEmail))
                    {
                        return(Unauthorized());
                    }
                }
                else
                {
                    return(NotFound());
                }

                TimeLineItem tItem = await _context.TimeLineDb.SingleOrDefaultAsync(t =>
                                                                                    t.ItemId == vocabularyItem.WordId.ToString() && t.ItemType == (int)KinaUnaTypes.TimeLineType.Vocabulary);

                if (tItem != null)
                {
                    _context.TimeLineDb.Remove(tItem);
                    await _dataService.RemoveTimeLineItem(tItem.TimeLineId, tItem.ItemType, tItem.ProgenyId);

                    await _context.SaveChangesAsync();

                    await _dataService.RemoveTimeLineItem(tItem.TimeLineId, tItem.ItemType, tItem.ProgenyId);
                }

                _context.VocabularyDb.Remove(vocabularyItem);
                await _context.SaveChangesAsync();

                await _dataService.RemoveVocabularyItem(vocabularyItem.WordId, vocabularyItem.ProgenyId);

                UserInfo userinfo = await _dataService.GetUserInfoByEmail(userEmail);

                string title   = "Word deleted for " + prog.NickName;
                string message = userinfo.FirstName + " " + userinfo.MiddleName + " " + userinfo.LastName + " deleted a word for " + prog.NickName + ". Word: " + vocabularyItem.Word;
                tItem.AccessLevel = 0;
                await _azureNotifications.ProgenyUpdateNotification(title, message, tItem, userinfo.ProfilePicture);

                return(NoContent());
            }

            return(NotFound());
        }
Example #12
0
        public async Task <VocabularyItem> SetVocabularyItem(int id)
        {
            VocabularyItem word = await _context.VocabularyDb.AsNoTracking().SingleOrDefaultAsync(w => w.WordId == id);

            await _cache.SetStringAsync(Constants.AppName + "vocabularyitem" + id, JsonConvert.SerializeObject(word), _cacheOptions);

            List <VocabularyItem> wordList = await _context.VocabularyDb.AsNoTracking().Where(w => w.ProgenyId == word.ProgenyId).ToListAsync();

            await _cache.SetStringAsync(Constants.AppName + "vocabularylist" + word.ProgenyId, JsonConvert.SerializeObject(wordList), _cacheOptionsSliding);

            return(word);
        }
Example #13
0
        private void RemoveWordButton_Click(object sender, System.EventArgs e)
        {
            Button         target       = (Button)sender;
            VocabularyItem itemToRemove = (VocabularyItem)target.Tag;

            string title   = Properties.Strings.vocabulary_remove_word_title;
            string message = string.Format(Properties.Strings.vocabulary_remove_word_text, itemToRemove.word);

            if (MessageBox.Show(message, title, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                removeWord(itemToRemove);
            }
        }
        public async Task <IActionResult> GetVocabularyItem(int id)
        {
            VocabularyItem result = await _dataService.GetVocabularyItem(id);

            string     userEmail  = User.GetEmail() ?? Constants.DefaultUserEmail;
            UserAccess userAccess = await _dataService.GetProgenyUserAccessForUser(result.ProgenyId, userEmail);

            if (userAccess != null || id == Constants.DefaultChildId)
            {
                return(Ok(result));
            }

            return(Unauthorized());
        }
Example #15
0
 public VocabularyDetailPage(VocabularyItem vocabularyItem)
 {
     InitializeComponent();
     _viewModel = new VocabularyDetailViewModel
     {
         CurrentVocabularyItemId = vocabularyItem.WordId,
         Word        = vocabularyItem.Word,
         AccessLevel = vocabularyItem.AccessLevel,
         Language    = vocabularyItem.Language,
         SoundsLike  = vocabularyItem.SoundsLike,
         Description = vocabularyItem.Description
     };
     BindingContext = _viewModel;
 }
Example #16
0
        public async Task <IActionResult> GetVocabularyItemMobile(int id)
        {
            VocabularyItem result = await _dataService.GetVocabularyItem(id); // _context.VocabularyDb.AsNoTracking().SingleOrDefaultAsync(w => w.WordId == id);

            if (result.ProgenyId != Constants.DefaultChildId)
            {
                result             = new VocabularyItem();
                result.AccessLevel = 5;
                result.ProgenyId   = Constants.DefaultChildId;
                result.Word        = Constants.AppName;
                result.DateAdded   = DateTime.UtcNow;
                result.Date        = DateTime.UtcNow;
            }
            return(Ok(result));
        }
        protected override void AddItemToVocabulary(VocabularyItem toAdd)
        {
            TrieNode curTrieNode = _root;

            foreach (char wordSymbol in toAdd.Word)
            {
                if (curTrieNode[wordSymbol] == null)
                {
                    curTrieNode[wordSymbol] = new TrieNode();
                }
                curTrieNode = curTrieNode[wordSymbol];
            }

            curTrieNode.VocabularyItem = new VocabularyItem(toAdd.Word, toAdd.WordOccurrence);
        }
        // -------------------------------------------------------------
        public void insert(VocabularyItem item) // Вставка элемента данных
                                                // (Метод предполагает, что таблица не заполнена)
        {
            string key     = item.EngWord;      // Получение ключа
            int    hashVal = hashFunc(key);     // Хеширование ключа

            // Пока не будет найдена
            while (hashArray[hashVal] != null &&     // пустая ячейка или -1,
                   hashArray[hashVal].GetHashCode() != -1)
            {
                ++hashVal;             // Переход к следующей ячейке
                hashVal %= arraySize;  // При достижении конца таблицы
            }                          // происходит возврат к началу
            hashArray[hashVal] = item; // Вставка элемента
        }
Example #19
0
        public VocabularyDetailViewModel()
        {
            _progeny = new Progeny();
            _currentVocabularyItem = new VocabularyItem();

            _currentVocabularyItem.Date        = DateTime.Now;
            _currentVocabularyItem.AccessLevel = 0;

            _dateYear  = _currentVocabularyItem.Date.Value.Year;
            _dateMonth = _currentVocabularyItem.Date.Value.Month;
            _dateDay   = _currentVocabularyItem.Date.Value.Day;

            VocabularyItems = new ObservableRangeCollection <VocabularyItem>();

            _accessLevelList = new List <string>();
            var ci = CrossMultilingual.Current.CurrentCultureInfo.TwoLetterISOLanguageName;

            if (ci == "da")
            {
                _accessLevelList.Add("Administratorer");
                _accessLevelList.Add("Familie");
                _accessLevelList.Add("Omsorgspersoner/Speciel adgang");
                _accessLevelList.Add("Venner");
                _accessLevelList.Add("Registrerede brugere");
                _accessLevelList.Add("Offentlig/alle");
            }
            else
            {
                if (ci == "de")
                {
                    _accessLevelList.Add("Administratoren");
                    _accessLevelList.Add("Familie");
                    _accessLevelList.Add("Betreuer/Spezial");
                    _accessLevelList.Add("Freunde");
                    _accessLevelList.Add("Registrierte Benutzer");
                    _accessLevelList.Add("Allen zugänglich");
                }
                else
                {
                    _accessLevelList.Add("Hidden/Private");
                    _accessLevelList.Add("Family");
                    _accessLevelList.Add("Caretakers/Special Access");
                    _accessLevelList.Add("Friends");
                    _accessLevelList.Add("Registered Users");
                    _accessLevelList.Add("Public/Anyone");
                }
            }
        }
Example #20
0
        /// <summary>
        /// Encodes a <see cref="VocabularyItem"/> as a CodedValue and
        /// adds it to the list of coded values.
        /// </summary>
        ///
        /// <param name="item">
        /// The <see cref="VocabularyItem"/> to use.
        /// </param>
        ///
        public void Add(VocabularyItem item)
        {
            CodedValue codedValue =
                new CodedValue(
                    item.Value,
                    item.VocabularyName,
                    item.Family,
                    item.Version);

            if (_text == null)
            {
                _text = item.DisplayText;
            }

            Codes.Add(codedValue);
        }
Example #21
0
        private void removeWord(VocabularyItem itemToRemove)
        {
            bool          wordIsRemoved = _removeWordFromVocabularyCallback(itemToRemove.id);
            VocabularySet setToRemove   = null;

            if (wordIsRemoved)
            {
                for (int i = 0; i < _vocabularyContents.Count; i++)
                {
                    VocabularySet set = _vocabularyContents[i];
                    if (set.section == itemToRemove.section)
                    {
                        set.words.Remove(itemToRemove);
                        if (set.words.Count == 0)
                        {
                            setToRemove = set;
                        }
                        break;
                    }
                }

                Control controlToRemove = null;
                foreach (Control control in _cellsContainer.Controls)
                {
                    if (control.Tag == itemToRemove)
                    {
                        controlToRemove = control;
                        break;
                    }
                }

                if (controlToRemove != null)
                {
                    _cellsContainer.Controls.Remove(controlToRemove);
                    controlToRemove.Dispose();

                    if (setToRemove != null)
                    {
                        checkRemoveTitle(setToRemove.section);
                        _vocabularyContents.Remove(setToRemove);
                    }

                    recolourCells();
                }
            }
        }
        // -------------------------------------------------------------
        public VocabularyItem delete(string key) // Удаление элемента данных
        {
            int hashVal = hashFunc(key);         // Хеширование ключа

            while (hashArray[hashVal] != null)   // Пока не будет найдена
                                                 // пустая ячейка
            {                                    // Ключ найден?
                if (hashArray[hashVal].EngWord == key)
                {
                    VocabularyItem temp = hashArray[hashVal];        // Временное сохранение
                    hashArray[hashVal] = new VocabularyItem("", ""); // Удаление элемента
                    return(temp);                                    // Метод возвращает элемент
                }
                ++hashVal;                                           // Переход к следующей ячейке
                hashVal %= arraySize;                                // При достижении конца таблицы
            }                                                        // происходит возврат к началу
            return(null);                                            // Элемент не найден
        }
Example #23
0
        /// <summary>
        /// Read compressed column from binary reader
        /// </summary>
        /// <param name="br">Binary reader</param>
        /// <param name="fieldName">name of read column</param>
        /// <param name="token">token to monitor cancellation requests</param>
        /// <returns>Column from binary reader</returns>
        private static async Task <CompressedColumn> ReadCompressedColumn(BinaryReader br, string fieldName, CancellationToken token)
        {
            token.ThrowIfCancellationRequested();

            //Read vocabulary
            int vocabularyLength = br.ReadInt32();

            VocabularyItem[] vocabularyItems = new VocabularyItem[vocabularyLength];
            var strings  = new List <string>();
            var decimals = new List <decimal>();

            for (int i = 0; i < vocabularyLength; i++)
            {
                token.ThrowIfCancellationRequested();
                vocabularyItems[i] = ReadVocabularyItem(br, strings, decimals);
            }

            var vocabulary = new Vocabulary(strings.ToArray(), decimals.ToArray(), vocabularyItems);
            // The max width of bitindex in bits.
            int bitWidth = (int)Math.Floor(Math.Log(vocabularyLength - 1, 2) + 1);      // -1 because we need max index.

            //Read vector as byte array
            int vectorLength = br.ReadInt32();

            var stream        = br.BaseStream;
            var numberOfBytes = (int)Math.Ceiling((double)bitWidth * vectorLength / 8.0);

            byte[]    bytes     = new byte[numberOfBytes];
            int       offset    = 0;
            const int chunkSize = 10240;

            while (offset < bytes.Length)
            {
                var count = Math.Min(bytes.Length - offset, chunkSize);
                offset += await stream.ReadAsync(bytes, offset, count, token);
            }

            return(new CompressedColumn(bytes, vocabulary, bitWidth, vectorLength, fieldName));
        }
Example #24
0
        private Panel makeWordCell(VocabularyItem vocabularyItem)
        {
            Panel panel = new Panel();

            panel.Size = new Size(CELL_WIDTH, CELL_HEIGHT);

            Label wordlabel = new Label();

            wordlabel.Text      = vocabularyItem.word;
            wordlabel.Location  = new Point(0, 0);
            wordlabel.Size      = new Size(LABEL_WIDTH, LABEL_HEIGHT);
            wordlabel.TextAlign = ContentAlignment.MiddleLeft;
            wordlabel.Font      = new Font("Arial", 14.0f, FontStyle.Regular);

            while (wordlabel.Width < TextRenderer.MeasureText(wordlabel.Text, new Font(wordlabel.Font.FontFamily, wordlabel.Font.Size, wordlabel.Font.Style)).Width)
            {
                wordlabel.Font = new Font(wordlabel.Font.FontFamily, wordlabel.Font.Size - 0.5f, wordlabel.Font.Style);
            }

            panel.Controls.Add(wordlabel);

            Button removeWordButton = new Button();

            removeWordButton.Size                  = new Size(X_BUTTON_WIDTH, X_BUTTON_HEIGHT);
            removeWordButton.Location              = new Point(LABEL_WIDTH + X_BUTTON_MARGIN_LEFT, 0);
            removeWordButton.TabStop               = false;
            removeWordButton.Tag                   = vocabularyItem;
            removeWordButton.Click                += RemoveWordButton_Click;
            removeWordButton.BackgroundImage       = removeImage;
            removeWordButton.ImageAlign            = ContentAlignment.MiddleCenter;
            removeWordButton.BackgroundImageLayout = ImageLayout.Center;
            removeWordButton.Dock                  = DockStyle.Right;
            panel.Controls.Add(removeWordButton);
            panel.Name = string.Concat(CELL_NAME_TEMPLATE, vocabularyItem.id);
            panel.Dock = DockStyle.Top;

            return(panel);
        }
Example #25
0
        private async void EditButton_OnClicked(object sender, EventArgs e)
        {
            if (_viewModel.EditMode)
            {
                _viewModel.EditMode = false;
                _viewModel.IsBusy   = true;
                _viewModel.IsSaving = true;

                DateTime wordDate = new DateTime(_viewModel.DateYear, _viewModel.DateMonth, _viewModel.DateDay);
                _viewModel.CurrentVocabularyItem.Date        = wordDate;
                _viewModel.CurrentVocabularyItem.Word        = _viewModel.Word;
                _viewModel.CurrentVocabularyItem.SoundsLike  = _viewModel.SoundsLike;
                _viewModel.CurrentVocabularyItem.Description = _viewModel.Description;
                _viewModel.CurrentVocabularyItem.Language    = _viewModel.Language;
                _viewModel.CurrentVocabularyItem.AccessLevel = _viewModel.AccessLevel;

                // Save changes.
                VocabularyItem resultVocabularyItem = await ProgenyService.UpdateVocabularyItem(_viewModel.CurrentVocabularyItem);

                _viewModel.IsBusy   = false;
                _viewModel.IsSaving = true;
                EditButton.Text     = IconFont.CalendarEdit;
                if (resultVocabularyItem != null)                  // Todo: Error message if update fails.
                {
                    MessageLabel.Text            = "Word Updated"; // Todo: Translate
                    MessageLabel.BackgroundColor = Color.DarkGreen;
                    MessageLabel.IsVisible       = true;
                    await Reload();
                }
            }
            else
            {
                EditButton.Text = IconFont.ContentSave;

                _viewModel.EditMode = true;
            }
        }
Example #26
0
        public static VocabularyItem CreateVocabulary(string name, int languageID)
        {
            VocabularyItem item = new VocabularyItem(-1, name, languageID);
            int res = -1;

            using (OleDbCommand cmd = new OleDbCommand(CREATE_VOCABULARY, connection))
            {
                cmd.Parameters.AddWithValue("@VocabularyName", name);
                cmd.Parameters.AddWithValue("@LanguageID", languageID);
                res = cmd.ExecuteNonQuery();
            }
            if (res > 0)
            {
                using (OleDbCommand cmd = new OleDbCommand(GET_VOCABULARY_ID, connection))
                {
                    cmd.Parameters.AddWithValue("@Name", name);
                    item.ID = int.Parse(cmd.ExecuteScalar().ToString());
                }
            }
            else
                item = null;

            return item;
        }
 protected abstract void AddItemToVocabulary(VocabularyItem item);
Example #28
0
        //
        // GET: /Vocabulary/Delete/5

        public ActionResult Delete(int id)
        {
            VocabularyItem vocabularyitem = db.VocabularyItems.Find(id);

            return(View(vocabularyitem));
        }
        public async Task <IActionResult> Post([FromBody] VocabularyItem value)
        {
            // Check if child exists.
            Progeny prog = await _context.ProgenyDb.AsNoTracking().SingleOrDefaultAsync(p => p.Id == value.ProgenyId);

            string userEmail = User.GetEmail() ?? Constants.DefaultUserEmail;

            if (prog != null)
            {
                // Check if user is allowed to add words for this child.

                if (!prog.IsInAdminList(userEmail))
                {
                    return(Unauthorized());
                }
            }
            else
            {
                return(NotFound());
            }

            VocabularyItem vocabularyItem = new VocabularyItem();

            vocabularyItem.AccessLevel = value.AccessLevel;
            vocabularyItem.Author      = value.Author;
            vocabularyItem.Date        = value.Date;
            vocabularyItem.DateAdded   = DateTime.UtcNow;
            vocabularyItem.ProgenyId   = value.ProgenyId;
            vocabularyItem.Description = value.Description;
            vocabularyItem.Language    = value.Language;
            vocabularyItem.SoundsLike  = value.SoundsLike;
            vocabularyItem.Word        = value.Word;

            _context.VocabularyDb.Add(vocabularyItem);
            await _context.SaveChangesAsync();

            await _dataService.SetVocabularyItem(vocabularyItem.WordId);

            TimeLineItem tItem = new TimeLineItem();

            tItem.ProgenyId   = vocabularyItem.ProgenyId;
            tItem.AccessLevel = vocabularyItem.AccessLevel;
            tItem.ItemType    = (int)KinaUnaTypes.TimeLineType.Vocabulary;
            tItem.ItemId      = vocabularyItem.WordId.ToString();
            UserInfo userinfo = _context.UserInfoDb.SingleOrDefault(u => u.UserEmail.ToUpper() == userEmail.ToUpper());

            if (userinfo != null)
            {
                tItem.CreatedBy = userinfo.UserId;
            }
            tItem.CreatedTime = DateTime.UtcNow;
            if (vocabularyItem.Date != null)
            {
                tItem.ProgenyTime = vocabularyItem.Date.Value;
            }
            else
            {
                tItem.ProgenyTime = DateTime.UtcNow;
            }

            await _context.TimeLineDb.AddAsync(tItem);

            await _context.SaveChangesAsync();

            await _dataService.SetTimeLineItem(tItem.TimeLineId);

            string title   = "Word added for " + prog.NickName;
            string message = userinfo.FirstName + " " + userinfo.MiddleName + " " + userinfo.LastName + " added a new word for " + prog.NickName;
            await _azureNotifications.ProgenyUpdateNotification(title, message, tItem, userinfo.ProfilePicture);

            return(Ok(vocabularyItem));
        }
Example #30
0
        private async void SaveVocabularyButton_OnClicked(object sender, EventArgs e)
        {
            if (ProgenyCollectionView.SelectedItem is Progeny progeny)
            {
                _viewModel.IsBusy   = true;
                _viewModel.IsSaving = true;

                VocabularyItem saveVocabulary = new VocabularyItem();
                saveVocabulary.ProgenyId   = progeny.Id;
                saveVocabulary.AccessLevel = _viewModel.AccessLevel;
                saveVocabulary.Progeny     = progeny;
                saveVocabulary.Date        = WordDatePicker.Date;
                string userEmail = await UserService.GetUserEmail();

                UserInfo userinfo = await UserService.GetUserInfo(userEmail);

                saveVocabulary.Author      = userinfo.UserId;
                saveVocabulary.DateAdded   = DateTime.Now;
                saveVocabulary.Word        = WordEntry.Text;
                saveVocabulary.SoundsLike  = SoundsLikeEntry.Text;
                saveVocabulary.Description = DescriptionEditor.Text;
                saveVocabulary.Language    = LanguageEntry.Text;

                if (ProgenyService.Online())
                {
                    // Todo: Translate messages.
                    saveVocabulary = await ProgenyService.SaveVocabularyItem(saveVocabulary);

                    _viewModel.IsSaving = false;
                    _viewModel.IsBusy   = false;

                    if (saveVocabulary.WordId == 0)
                    {
                        var ci = CrossMultilingual.Current.CurrentCultureInfo;
                        ErrorLabel.Text            = resmgr.Value.GetString("ErrorWordNotSaved", ci);
                        ErrorLabel.BackgroundColor = Color.Red;
                    }
                    else
                    {
                        var ci = CrossMultilingual.Current.CurrentCultureInfo;
                        ErrorLabel.Text                        = resmgr.Value.GetString("WordSaved", ci) + saveVocabulary.WordId;
                        ErrorLabel.BackgroundColor             = Color.Green;
                        SaveVocabularyButton.IsVisible         = false;
                        CancelVocabularyButton.Text            = "Ok";
                        CancelVocabularyButton.BackgroundColor = Color.FromHex("#4caf50");
                        await Shell.Current.Navigation.PopModalAsync();
                    }
                }
                else
                {
                    // Todo: Translate message.
                    ErrorLabel.Text            = $"Error: No internet connection. Measurement for {progeny.NickName} was not saved. Try again later.";
                    ErrorLabel.BackgroundColor = Color.Red;
                }

                ErrorLabel.IsVisible = true;
            }

            _viewModel.IsSaving = false;
            _viewModel.IsBusy   = false;
        }
 // -------------------------------------------------------------
 public EngRusVocabularyHashTable(int size)     // Конструктор
 {
     arraySize = size;
     hashArray = new VocabularyItem[arraySize];
     VocabularyItem nonItem = new VocabularyItem("", "");    // Ключ удаленного элемента
 }
Example #32
0
        public async Task <ActionResult> GetTimeLineItem(TimeLineItemViewModel model)
        {
            string userEmail = HttpContext.User.FindFirst("email")?.Value ?? _defaultUser;

            UserInfo userinfo = await _progenyHttpClient.GetUserInfo(userEmail);

            string id   = model.ItemId.ToString();
            int    type = model.TypeId;
            int    itemId;
            bool   idParse = int.TryParse(id, out itemId);

            if (type == (int)KinaUnaTypes.TimeLineType.Photo)
            {
                if (idParse)
                {
                    PictureViewModel picture = await _mediaHttpClient.GetPictureViewModel(itemId, 0, 1, userinfo.Timezone);

                    if (picture != null)
                    {
                        if (!picture.PictureLink.StartsWith("https://"))
                        {
                            picture.PictureLink = _imageStore.UriFor(picture.PictureLink);
                        }
                        picture.CommentsCount = picture.CommentsList.Count;
                        return(PartialView("TimeLinePhotoPartial", picture));
                    }
                }
            }

            if (type == (int)KinaUnaTypes.TimeLineType.Video)
            {
                if (idParse)
                {
                    VideoViewModel video = await _mediaHttpClient.GetVideoViewModel(itemId, 0, 1, userinfo.Timezone);

                    if (video != null)
                    {
                        video.CommentsCount = video.CommentsList.Count;
                        return(PartialView("TimeLineVideoPartial", video));
                    }
                }
            }

            if (type == (int)KinaUnaTypes.TimeLineType.Calendar)
            {
                if (idParse)
                {
                    CalendarItem evt = await _progenyHttpClient.GetCalendarItem(itemId); // _context.CalendarDb.AsNoTracking().SingleOrDefault(e => e.EventId == itemId);

                    if (evt != null && evt.StartTime.HasValue && evt.EndTime.HasValue)
                    {
                        evt.StartTime = TimeZoneInfo.ConvertTimeFromUtc(evt.StartTime.Value, TimeZoneInfo.FindSystemTimeZoneById(userinfo.Timezone));
                        evt.EndTime   = TimeZoneInfo.ConvertTimeFromUtc(evt.EndTime.Value, TimeZoneInfo.FindSystemTimeZoneById(userinfo.Timezone));
                        return(PartialView("TimeLineEventPartial", evt));
                    }
                }
            }

            if (type == (int)KinaUnaTypes.TimeLineType.Vocabulary)
            {
                if (idParse)
                {
                    VocabularyItem voc = await _progenyHttpClient.GetWord(itemId); // _context.VocabularyDb.AsNoTracking().SingleOrDefault(v => v.WordId == itemId);

                    if (voc != null)
                    {
                        if (voc.Date != null)
                        {
                            voc.Date = TimeZoneInfo.ConvertTimeFromUtc(voc.Date.Value, TimeZoneInfo.FindSystemTimeZoneById(userinfo.Timezone));
                        }
                        return(PartialView("TimeLineVocabularyPartial", voc));
                    }
                }
            }

            if (type == (int)KinaUnaTypes.TimeLineType.Skill)
            {
                if (idParse)
                {
                    Skill skl = await _progenyHttpClient.GetSkill(itemId); // _context.SkillsDb.AsNoTracking().SingleOrDefault(s => s.SkillId == itemId);

                    if (skl != null)
                    {
                        return(PartialView("TimeLineSkillPartial", skl));
                    }
                }
            }

            if (type == (int)KinaUnaTypes.TimeLineType.Friend)
            {
                if (idParse)
                {
                    Friend frn = await _progenyHttpClient.GetFriend(itemId); // _context.FriendsDb.AsNoTracking().SingleOrDefault(f => f.FriendId == itemId);

                    if (frn != null)
                    {
                        if (!frn.PictureLink.StartsWith("https://"))
                        {
                            frn.PictureLink = _imageStore.UriFor(frn.PictureLink, "friends");
                        }
                        return(PartialView("TimeLineFriendPartial", frn));
                    }
                }
            }

            if (type == (int)KinaUnaTypes.TimeLineType.Measurement)
            {
                if (idParse)
                {
                    Measurement mes = await _progenyHttpClient.GetMeasurement(itemId); // _context.MeasurementsDb.AsNoTracking().SingleOrDefault(m => m.MeasurementId == itemId);

                    if (mes != null)
                    {
                        return(PartialView("TimeLineMeasurementPartial", mes));
                    }
                }
            }

            if (type == (int)KinaUnaTypes.TimeLineType.Sleep)
            {
                if (idParse)
                {
                    Sleep slp = await _progenyHttpClient.GetSleepItem(itemId); // _context.SleepDb.AsNoTracking().SingleOrDefault(s => s.SleepId == itemId);

                    if (slp != null)
                    {
                        slp.SleepStart = TimeZoneInfo.ConvertTimeFromUtc(slp.SleepStart, TimeZoneInfo.FindSystemTimeZoneById(userinfo.Timezone));
                        slp.SleepEnd   = TimeZoneInfo.ConvertTimeFromUtc(slp.SleepEnd, TimeZoneInfo.FindSystemTimeZoneById(userinfo.Timezone));
                        DateTimeOffset sOffset = new DateTimeOffset(slp.SleepStart,
                                                                    TimeZoneInfo.FindSystemTimeZoneById(userinfo.Timezone).GetUtcOffset(slp.SleepStart));
                        DateTimeOffset eOffset = new DateTimeOffset(slp.SleepEnd,
                                                                    TimeZoneInfo.FindSystemTimeZoneById(userinfo.Timezone).GetUtcOffset(slp.SleepEnd));
                        slp.SleepDuration = eOffset - sOffset;
                        return(PartialView("TimeLineSleepPartial", slp));
                    }
                }
            }

            if (type == (int)KinaUnaTypes.TimeLineType.Note)
            {
                if (idParse)
                {
                    Note nte = await _progenyHttpClient.GetNote(itemId); // _context.NotesDb.AsNoTracking().SingleOrDefault(n => n.NoteId == itemId);

                    if (nte != null)
                    {
                        nte.CreatedDate = TimeZoneInfo.ConvertTimeFromUtc(nte.CreatedDate, TimeZoneInfo.FindSystemTimeZoneById(userinfo.Timezone));
                        return(PartialView("TimeLineNotePartial", nte));
                    }
                }
            }

            if (type == (int)KinaUnaTypes.TimeLineType.Contact)
            {
                if (idParse)
                {
                    Contact cnt = await _progenyHttpClient.GetContact(itemId); // _context.ContactsDb.AsNoTracking().SingleOrDefault(c => c.ContactId == itemId);

                    if (cnt != null)
                    {
                        if (!cnt.PictureLink.StartsWith("https://"))
                        {
                            cnt.PictureLink = _imageStore.UriFor(cnt.PictureLink, "contacts");
                        }
                        if (cnt.DateAdded == null)
                        {
                            cnt.DateAdded = new DateTime(1900, 1, 1);
                        }
                        return(PartialView("TimeLineContactPartial", cnt));
                    }
                }
            }

            if (type == (int)KinaUnaTypes.TimeLineType.Vaccination)
            {
                if (idParse)
                {
                    Vaccination vac = await _progenyHttpClient.GetVaccination(itemId); // _context.VaccinationsDb.AsNoTracking().SingleOrDefault(v => v.VaccinationId == itemId);

                    if (vac != null)
                    {
                        return(PartialView("TimeLineVaccinationPartial", vac));
                    }
                }
            }

            if (type == (int)KinaUnaTypes.TimeLineType.Location)
            {
                if (idParse)
                {
                    Location loc = await _progenyHttpClient.GetLocation(itemId); // _context.LocationsDb.AsNoTracking().SingleOrDefault(l => l.LocationId == itemId);

                    if (loc != null)
                    {
                        return(PartialView("TimeLineLocationPartial", loc));
                    }
                }
            }

            Note failNote = new Note();

            failNote.CreatedDate = DateTime.UtcNow;
            failNote.Title       = "Error, content not found.";

            return(PartialView("TimeLineNotePartial", failNote));
        }
Example #33
0
 public IActionResult TimeLineVocabularyPartial(VocabularyItem model)
 {
     return(View(model));
 }